location-service/0000755000000000000000000000000012701027425011212 5ustar location-service/doc/0000755000000000000000000000000012701027425011757 5ustar location-service/doc/tips_n_tricks.md0000644000000000000000000000145412701027425015160 0ustar # Tips'n'Tricks ## Mark HERE license as accepted from cmdline sudo LC_ALL=C gdbus call --system --dest org.freedesktop.Accounts --object-path /org/freedesktop/Accounts/User32011 --method org.freedesktop.DBus.Properties.Set com.ubuntu.location.providers.here.AccountsService LicenseAccepted '' ## Force startup after ofono and NM are started This is a *workaround* to get connectivity API to collect; mount your system read-write and edit /etc/init/ubuntu-location-provider-here-slpgwd.conf: sudo mount -o remount,rw / sudo vi /etc/init/ubuntu-location-provider-here-slpgwd.conf change: `start on started dbus and (started ofono or started network-manager)` to: `start on started dbus and started ofono and started network-manager` sudo mount -o remount,ro / sync sudo reboot location-service/doc/manual_testing.md0000644000000000000000000002175512701027425015325 0ustar # Manual Testplan [TOC] While the automatic test suite of the location service is comprehensive and covers large parts of the functionality of the service itself, we still provide an additional level of acceptance testing covering the entire location stack/experience as a part of this document. ## Dependents/Clients - qtubuntu-sensors - Qt/QML applications: - Browser - osmTouch ## Test Plan This test plan is not supposed to be complete; use it to guide your manual testing so you don't miss big functional areas that are part of the component; also this should be used as guideline to inspire the exploratory testing which should be adapted smartly based on the real content of a MP. Please note that if you're testing the GPS provider, the location service relies on GPS hardware to obtain a location fix. For that, it might be required that you execute the manual steps listed before close to a window or ideally outside, with good satellite visibility conditions. __Note: It can take up to 15 minutes for the GPS device to get a lock, due to lack of assisted GPS__ - Install latest image on phone - Install freshly built MPs that are needed for landing Depending on the default configuration of location-service on the image, you may skip parts of this test plan. E.g. if GPS hardware is disabled, skip this part. You can see which providers are enabled by looking at the list of providers on the location-serviced command-line (`ps fauxw | grep location-service`, then look at the `--provider` flags). ### Dummy provider This tests forces location-service to use only the dummy provider; this providers a baseline test for the app to trust-store to location-service path. - phablet-shell into the phone: - `sudo service ubuntu-location-service stop && sudo /usr/bin/ubuntu-location-serviced --bus system --provider dummy::Provider --dummy::Provider::ReferenceLocationLat=48.857503 --dummy::Provider::ReferenceLocationLon=2.295072` - As phablet, start the trust store again (it stops when location-service is stopped) with: `start ubuntu-location-service-trust-stored` - Ensure that all AP tests for the webbrowser pass as expected - Point the browser to maps.google.com (alternatively: here.com, maps.bing.fr). - Request centering the map on current position and observe if it works correctly (should show the Eiffel tower) - Install osmTouch from the app store - Launch osmTouch and check if it centers on the Eiffel tower. - Install a maps webapp such as HERE or Google Maps webapp from the app store - Launch maps webapp and check if it centers on the Eiffel tower. ### GPS Test Plan This applies only if GPS provider is enabled. - (If applicable: Remember to add the silo you are testing) - `sudo apt-get install ubuntu-location-service-tests` - If you want to send off crowdsourced information, i.e., information about visible wifis and visible radio cells for the obtained location fixes to Mozilla's location service and our own instance: - `sudo GLOG_v=40 GLOG_logtostderr=1 GPS_TEST_ENABLE_HARVESTING_DURING_TESTS=1 /usr/bin/uls-tests/gps_provider_test --gtest_filter=*.time_to_first_fix_cold_start_without_supl_benchmark_requires_hardware` - If you '''don't''' want to send off crowdsourced information: - `sudo GLOG_v=40 GLOG_logtostderr=1 /usr/bin/uls-tests/gps_provider_test --gtest_filter=*.time_to_first_fix_cold_start_without_supl_benchmark_requires_hardware` - The test will output a lot of diagnostic information to the terminal and will take ~30 minutes. If satellite visibility is limited, it can take even longer. The test will automatically report success or failure. ### Preliminary AGPS Test Plan **Does not apply to Krillin** Please note that the Krillin GPS chipset driver and its integration within Ubuntu does not support vanilla AGPS (i.e., SUPL) right now. For that, this test case is irrelevant for Krillin and is likely to fail. This applied only if GPS provider and some other provider (giving _A_ssistance) are enabled. - Add the silo. - `sudo apt-get install ubuntu-location-service-tests` - Obtain a (rough) location estimate for your current location on Google maps. - Make sure to replace INSERT_ESTIMATE_HERE with the respective values obtained from Google maps. - If you want to send off crowdsourced information, i.e., information about visible wifis and visible radio cells for the obtained location fixes to Mozilla's location service and our own instance: - `sudo GLOG_v=40 GLOG_logtostderr=1 GPS_TEST_ENABLE_HARVESTING_DURING_TESTS=1 GPS_TEST_REF_LAT=INSERT_ESTIMATE_HERE GPS_TEST_REF_LON=INSERT_ESTIMATE_HERE /usr/bin/uls-tests/gps_provider_test --gtest_filter=*.time_to_first_fix_cold_start_with_supl_benchmark_requires_hardware` - If you '''don't''' want to send off crowdsourced information: - `sudo GLOG_v=40 GLOG_logtostderr=1 GPS_TEST_REF_LAT=INSERT_ESTIMATE_HERE GPS_TEST_REF_LON=INSERT_ESTIMATE_HERE /usr/bin/uls-tests/gps_provider_test --gtest_filter=*.time_to_first_fix_cold_start_with_supl_benchmark_requires_hardware` - The test will output a lot of diagnostic information to the terminal and will take ~10 minutes or less. The test will automatically report success or failure. ### Espoo / HERE provider This applies only if the Espoo / HERE remote provider is enabled. This provider should be enabled by default and may either work standalone as the only provider or as an assistance for the GPS hardware to lock. - Add the silo; special exception for lxc-android-config: see https://wiki.ubuntu.com/Touch/Testing/lxc-android-config - If noted, deploy an updated custom tarball: - Download the tarball under /tmp ('''NOT''' under /) - Unpack there: `cd /tmp; sudo tar xvf custom-vendor-here-*.tar.xz` - Remove older bits: `sudo rm -rf /custom/vendor/here/` - Update custom bits: `sudo mv /tmp/system/custom/vendor/here /custom/vendor` - Reboot - After boot, check you have these three processes running on top of location-service: - slpgwd - posclientd - ubuntu-espoo-service - Make sure SIM is unlocked and attached to the network (has some reliable signal) and that WiFi is turned on. - Install OSMTouch app - Run OSMTouch app, hit the position button every other second until you get a blue circle showing your current location; # Connectivity API For integration of network-based positioning providers, the location service offers a connectivity API that provides access to wifi and cell measurements as well as information on the current overall connectivity status of the device. Please execute the following commands on a newly flashed device with a writable image: - `sudo apt-get update && sudo apt-get build-dep location-service && sudo apt-get install libubuntu-location-service-dev ubuntu-location-service-examples` - `mkdir /tmp/build && cd /tmp/build && cmake /usr/share/ubuntu-location-service/examples/standalone/connectivity/ && make` - `GLOG_logtostderr=1 ./connectivity` Verify that the output looks similar to: phablet@ubuntu-phablet:/tmp/build$ ./connectivity Is wifi enabled: true Is wifi hw enabled: true Is wwan enabled: false Is wwan hw enabled: true umts(mcc: 262, mnc: 2, lac: 5313, id: 131948771, asu: 7) (bssid: BC:F2:AF:AF:19:A2, ssid: devolo-bcf2afaf19a2, last seen: 1408955086, mode: Mode::infrastructure, frequency: 2462, strength: 72) (bssid: 00:22:3F:35:43:58, ssid: JustAnotherWLAN, last seen: 1408955086, mode: Mode::infrastructure, frequency: 2412, strength: 24) (bssid: 82:C7:A6:40:8C:4E, ssid: EasyBox-44D054, last seen: 1408955206, mode: Mode::infrastructure, frequency: 2417, strength: 17) (bssid: 00:24:01:B8:32:8D, ssid: gra, last seen: 1408955086, mode: Mode::infrastructure, frequency: 2412, strength: 12) (bssid: C0:25:06:3C:28:22, ssid: FRITZ!Box 6360 Cable, last seen: 1408954966, mode: Mode::infrastructure, frequency: 2412, strength: 17) (bssid: 00:1C:4A:A5:B7:59, ssid: FRITZ!Box Fon WLAN 7170, last seen: 1408954966, mode: Mode::infrastructure, frequency: 2437, strength: 10) Last seen changed for wifi (bssid: BC:F2:AF:AF:19:A2, ssid: devolo-bcf2afaf19a2, last seen: 1408955257, mode: Mode::infrastructure, frequency: 2462, strength: 72) Last seen changed for wifi (bssid: 00:22:3F:35:43:58, ssid: JustAnotherWLAN, last seen: 1408955257, mode: Mode::infrastructure, frequency: 2412, strength: 24) Signal strength changed for wifi: (bssid: BC:F2:AF:AF:19:A2, ssid: devolo-bcf2afaf19a2, last seen: 1408955257, mode: Mode::infrastructure, frequency: 2462, strength: 73) # Trust Store Integration Please note that we are assuming a freshly wiped system for testing here. If you cannot fulfill that pre-condition, please run `rm -rf /home/phablet/.local/share/UbuntuLocationService && sudo shutdown -r` prior to running the tests: ## Unconfined - Open the browser, go to maps.google.com - Observe the in-browser dialog asking for granting access to location. ## Confined Web-App - Open the Nokia Here web app, observe the trust dialog appearing. ## Confined Application - Open osmtouch and observe the osmtouch surface sliding up, presenting you with a trust dialog. location-service/doc/hacking.md0000644000000000000000000001225512701027425013712 0ustar # Hacking ## Building the code By default, the code is built in release mode. To build a debug version, use $ mkdir builddebug $ cd builddebug $ cmake -DCMAKE_BUILD_TYPE=debug .. $ make For a release version, use -DCMAKE_BUILD_TYPE=release ## Running the tests $ make $ make test Note that "make test" alone is dangerous because it does not rebuild any tests if either the library or the test files themselves need rebuilding. It's not possible to fix this with cmake because cmake cannot add build dependencies to built-in targets. To make sure that everything is up-to-date, run "make" before running "make test"! ## Coverage To build with the flags for coverage testing enabled and get coverage: $ mkdir buildcoverage $ cd buildcoverage $ cmake -DCMAKE_BUILD_TYPE=coverage $ make $ make test $ make coverage Unfortunately, it is not possible to get 100% coverage for some files, mainly due to gcc's generation of two destructors for dynamic and non- dynamic instances. For abstract base classes and for classes that prevent stack and static allocation, this causes one of the destructors to be reported as uncovered. There are also issues with some functions in header files that are incorrectly reported as uncovered due to inlining, as well as the impossibility of covering defensive assert(false) statements, such as an assert in the default branch of a switch, where the switch is meant to handle all possible cases explicitly. If you run a binary and get lots of warnings about a "merge mismatch for summaries", this is caused by having made changes to the source that add or remove code that was previously run, so the new coverage output cannot sensibly be merged into the old coverage output. You can get rid of this problem by running $ make clean-coverage This deletes all the .gcda files, allowing the merge to (sometimes) succeed again. If this doesn't work either, the only remedy is to do a clean build. If lcov complains about unrecognized lines involving '=====', you can patch geninfo and gcovr as explained here: https://bugs.launchpad.net/gcovr/+bug/1086695/comments/2 ## Code style We use a format tool that fixes a whole lot of issues regarding code style. The formatting changes made by the tool are generally sensible (even though they may not be your personal preference in all cases). If there is a case where the formatting really messes things up, consider re-arranging the code to avoid the problem. The convenience of running the entire code base through the pretty-printer far outweighs any minor glitches with pretty printing, and it means that we get consistent code style for free, rather than endlessly having to watch out for formatting issues during code reviews. As of clang-format-3.7, you can use // clang-format off void unformatted_code ; // clang-format on to suppress formatting for a section of code. To format specific files: ${CMAKE_BINARY_DIR}/tools/formatcode x.cpp x.h If no arguments are provided, formatcode reads stdin and writes stdout, so you can easily pipe code into the tool from within an editor. For example, to reformat the entire file in vi (assuming ${CMAKE_BINARY_DIR}/tools is in your PATH): 1G!Gformatcode To re-format all source and header files in the tree: $ make formatcode ## Thread and address sanitizer Set SANITIZER to "thread" or "address" to build with the corresponding sanitizer enabled. ## Updating symbols file To easily spot new/removed/changed symbols in the library, the debian package maintains a .symbols file that lists all exported symbols present in the library .so. If you add new public symbols to the library, it's necessary to refresh the symbols file, otherwise the package will fail to build. The easiest way to do that is using bzr-builddeb: $ bzr bd -- -us -uc -j8 # Don't sign source package or changes file, 8 compiles in parallel $ # this will exit with an error if symbols file isn't up-to-date $ cd ../build-area/location-service-[version] $ ./obj-[arch]/tools/symbol_diff This creates a diff of the symbols in /tmp/symbols.diff. (The demangled symbols from the debian build are in ./new_symbols.) Review any changes in /tmp/symbols.diff. If they are OK: $ cd - $ patch -p0 < /tmp/symbols.diff ## ABI compliance test To use this, install abi-compliance-checker package from the archives. You can use abi-compliance-checker to test whether a particular build is ABI compatible with another build. The tool does some source-level analysis in addition to checking library symbols, so it catches things that are potentially dangerous, but won't be picked up by just looking at the symbol table. Assume you have built devel in src/devel, and you have a later build in src/mybranch and want to check that mybranch is still compatible. To run the compliance test: $ cd src $ abi-compliance-checker -lib libunity-scopes.so -old devel/build/test/abi-compliance/abi.xml -new mybranch/build/test/abi-compliance/abi.xml The script will take about two minutes to run. Now point your browser at src/compat_reports/libunity-scopes.so/[version]_to_[version]/compat_report.html The report provides a nicely layed-out page with all the details. location-service/doc/intro.md0000644000000000000000000000546212701027425013443 0ustar # Introduction {#mainpage} Ubuntu's location service is a central hub for multiplexing access to positioning subsystems available via hard- and software. It provides a client API offering positioning capabilities to applications and other system components, abstracting away the details of individual positioning solutions. ## Vocabulary To make the remainder of this documentation as easily understandable as possible, we start over with introducing some vocabulary: - Engine: Responsible for handling input from multiple positioning subsystems and maintaining the state of the overall system. Think about it like the heart of the system. - Provider: A positioning subsystem that feeds into the positioning engine. Common examples are a GPS provider or a network-based positioning provider. - Service: The point of entry for applications and services that would like to receive position data. - Session: In order to receive position information, every application or service has to create a session with the location Service. - Update: An update is a timestamped entity to a certain type of data. - [WGS84, http://en.wikipedia.org/wiki/World_Geodetic_System]: The coordinate system that is used throughout the entire location subsystem. ## Architectural Overview The high-level architecture of the service is shown in the following diagram: ![High-level architectural overview](images/LocationServiceHighLevel.png) In this diagram, the configuration of the engine refers to: * The current state of any satellite-based positioning subsystems. Can either be off or on. * The current state of reporting facilities responsible for harvesting wifi and cell id measurements together with location information and sending them off to remote services. Can either be off or on. * The overall state of the engine. Can either be off, on or active. The Service takes this configuration and exposes it to client applications. In addition, mainly for debugging purposes, the set of currently visible satellites (if any) is maintained and exposed to privileged client applications. ## Privacy & Access Control Location information is highly privacy relevant. For this reason, the location service is deeply integrated with AppArmor and Ubuntu's overall trust infrastructure. Every incoming session request is validated and if in doubt, the user is asked to explicitly grant trust to the application requesting access to positioning information. Please see [@ref com::ubuntu::location::service::PermissionManager] for further details. In addition, the location service allows for selectively adjusting the accuracy and reporting setup of the location Engine to provide further fine-grained control over the exposed data to user. Within this setup, a user is able to entirely disable all positioning. location-service/doc/images/0000755000000000000000000000000012701027425013224 5ustar location-service/doc/images/LocationServiceHighLevel.png0000644000000000000000000002520512701027425020617 0ustar PNG  IHDRQ[p*LIDATxQU׽]R$XAP , 4H()X|*$|!BCH,B ) $EH B B Jr{n"<=x̓,~;c#snkZs9\s7Ƙs-,,,9Θht9l/X^=ctС3< ' uit_x,0g~_sCNjE@~W4ᄆ"H c!NhEP_y, d(x, d@$局( cy, @TWBARW "<2EP_BpX@ȀZTW "c!d )% PI_y, ds_5S.fZ]s^IC[cvb'\2!NY-)\6`Nx9ؤ_.~YR+H,<!p񘛝]+^uiw;k<2b2Q5 K|l~_(^D3j1[x,xfR.ޯŦXR(^,f_+oU܃nm| ^wXM]B.iֳt'%L zBh17K%d@pR /VǻⳣW vDy̮)Bn٫e2=jK5=k88gWmSz&eN7l Ý<BR@ч-˄˄av{mC岏O 3mX(O;hMpTpzxɍ-;WŨiT<  Se4w6d\ǑfѮd^j !sKaTMD7=;]_;h&de~̕5_^xg#f.Bƨ0cnwF '܁j!NQb#pBcsdO7Gxڐ/Cȸx>)ADnBr!ңi3=Ew;~#J@h=nBF8YF.v?+u=0܅zz]M(8]-n+Xvr=< ޱk(KZB]CVOoX:X ! )+ @TW "c!d8HGATW?pO!d`O+SQ"b㏗>o_izիW:D?߷m|{sq+W~_{,;zj o~󛣯~?QѥKm/o !.$d5կH$n{uz{h0$Ӳ|p&zfs6@,/xک 5drZ!?S[.#jLs0kIr|)ՅϿc$ܷo!>d !}衇Nva_ `b1-R!ܹs~?4^/N4|#E5>aIAB  cf=6ٷ^xae)-S}&vʑ#G}f ϴNYGE_u6$S[_cN6sJ'"dpHC<'eNd"! E2'GN9&fIk<ꇲNWCF?FAH&'dd-mGL6Y#{e9P{hlL},~FYx^@\ 3227zEѓBFNџusz3U*=wԥ 9);ƴw!Dw'q}ӂ]!d,2ҋΑu E?eCdlpsmBXM#~K$d z7 uVH ݵ L^ϻ^!c]=M|~.bG;)%'IO?hCӥڋLJ>YGGȘx>pKجcR W3d:OfvbBFnoթ] \v7ohq]GyM22b|2.©߿rrQNz3R?L}M5lL Sݫj5dKꅇŒӄxK|o{ ]ߥݥ ԞS+:Ea#Eqoѝ{_NUeh?d|ڋdF$!cPk8o=-w1gm;ji֤/̪~_i~<6F}3d|3n?&=cRiEn٧w[W \^(227%m|=r| @T1Wd*h)ri/J<3FsX]Z7tx,0g,7I:6JFDD8Զ1;DD8)DDǞADD- i2-#uUe~}DDQ#c.yR*W~_,[c4su̝o.mV{\1 !ti_+Wztl+|x&(d4l]-[{vd\}GͶ>+NGM@{1Gt cn,S 5xNڰt$rѬR-o-2%@tqRD5% Ⱥ0F׍G^l|䳅/^7BR[ݲ''![YWKUQ CqڵMV ytS\wP¾8^/pOy][Lo/&=DF{kҙQNJ'k1_}N[lgyݭ╻2dk7xY\qKݏz9""+νņY' :!  <2~y|zש?,'cţn4^V;I[(Ǔ<ًůMxxY|~,#6?ѐNWz[eQmLDLjg"">FDDD3#""RLDLjHq&">FDDD3#""R)DLjHq&"cDDD3#""R)DLDLjg"">FDDD31"""RLDLjHq&">FDDD3#""RLDLjHq&">Ljg"">FDD81"""RLDLjg"">FDDD31"""RLDLjg"">FDDD31ZG.7\,5ǂcXg9B:6_җ_y,p1:tg }>f~W41/~1_ 9S_x )+ 8A局( J<BWⱀE@B*+2EP_ǂgPI_y, dX@A% !A"H c!NhEP_y, d(x, d@$局( :QO~d̳<2h!#y!ǜr*EuW)@7smROCS:FG%$*O:W>}Y'O:0{#_-6do<걲eN>'8iҙ6BvoZx, '46wx4_-ŭɄ׍⵻M8PQCƑiy|Bx;ź wm._/o;/}h~4ί}32Q^{Yfq9u2[Qfm2;]p)A|eʐ |u7ю;ȃ+]F4p#믏~,Ç~ӟ?]>SJc_$`xsرcK[ߚ6|0O?^B&… /ˣ۷9276c'NG?Rַ&X<N!c}y/}k_9sf]F1Hc{!d?~A=6SOi7=CKac|gө1kmK;r6hѐEF>00m"XE|1NuO(d(+_?u?1Niά8fc!~5=>Ӿ ~xwկ~5t۷o>o, %0_~,5|{ްvs"w1%bN>X[ӟtgJa'?ɒ?52ڎHēe]zL eD8LjyUYW{d@F[s/t$h:)p̬/oӌ O^I;%xU?#=xLHșԆ,.ciy4]U)J[enFZuCmd2fsP& Kd]\srp)5$g,ӧO}$g]Y>&f(LAKO o3Xv'Ph_r7. G W{ LLJk%,;,,ۮ+^ekω:9^ͺ2699BkCQ9A%\M=uJ@]waz^MzړvR#@ 9>i $#q{Y=>Ԣ=s~.'<}ڗ~6\c̵&G,c 44!k$2ddT&7|9l@B'JJ7dDOβR#@Xu7~ sO.8ƇB.1=XfxZ~&d Iw\WV9Z f9w~ 4[ }R8|^=) 5<~Z7.6dme_=zBFg[hy<8PGgvEY6OC2攤ݜ9930'x}csbI sbl_mC9,_o}UA26)LT'/cyШ#_o;[΃\V/)\vL c9iiG=tLx:/;oj>1Ԇm90_}=ٷ>84ڮk-vԎxcz|\2EP_'iiħåQ @TW<dQFBcf:R7 @TWcWEkWڳ[A% !P@~WⱀE@B*+ @TWBARW "<2EP_BARJ<2&局( J<B*A (<2EP_y, dpBC$局'"<2EP_BARJ<2&局( cy, @TWBARW "<2EP_BpBC$局'"<ݐqر:>/J<3FsX]Z7tx,0g,7I:J<DDDDDDDDDDD4 IENDB`location-service/doc/daemon_and_cli.md0000644000000000000000000000406612701027425015223 0ustar # Service Daemon and CLI The location service offers a daemon executable and a corresponding command-line interface for interacting with it. The daemon does not necessarily require root privileges, but might so depending on your configuration. Run the following command to receive an overview of the arguments to the daemon: ubuntu-location-serviced --help An example invocation of the daemon, configuring a GPS provider that relies on the Android HAL to talk to the chipset, exposing the service on the system DBus instance: ubuntu-location-serviced --bus system --provider gps::Provider The cli allows for querying properties of a running service instance, e.g.: ubuntu-location-serviced-cli --bus system --get --property is_online ## Configuring an Out-Of-Process Provider If you want to run a provider out of process, the daemon executable allows you to do so by instantiating a so-called remote provider. The following invocation of the service tries to connect to the provider instance described by the given unique DBus name and path. ubuntu-location-serviced \ --bus system \ --provider remote::Provider \ --remote::Provider::bus=system \ --remote::Provider::name=com.ubuntu.location.provider.Gps \ --remote::Provider::path=/ Please note that the service allows for decorating provider names to uniquely identify per provider configuration options and to allow for loading more than one provider of a certain kind. The following configuration configures two remote providers, one relying on GPS (decorated with @gps) and another one relying on network-based positioning (decorated with @network): ubuntu-location-serviced \ --bus system \ --provider remote::Provider@gps \ --remote::Provider@gps::bus=system \ --remote::Provider@gps::name=com.ubuntu.location.provider.Gps \ --remote::Provider@gps::path=/ \ --provider remote::Provider@network \ --remote::Provider@network::bus=system \ --remote::Provider@network::name=com.ubuntu.location.provider.Network \ --remote::Provider@network::path=/ location-service/doc/debugging.md0000644000000000000000000001057612701027425014245 0ustar # Debugging Location not working? Here's how to debug. ## Layers Test in OSMTouch (QML app using Qt API) before testing in webapps or webbrowser app. Different results? File a bug where it doesn't work. Same result of no location? Next step. ## Check that stack works with dummy provider Edit /etc/init/ubuntu-location-provider.override to start location-serviced with just the dummy provider; this should work. Doesn't work? File a bug against location-service. Works? Reset config to defaults and try the next thing. ## Hardware GPS breaking all of location-service GPS provider is built-in into location-service and might break all of it if it goes south (working on splitting it out); try enabling only the HERE provider on the location-serviced command-line and see if that works. Works? File a bug against location-service. Doesn't work? Move on. ## HERE test To test whether the low-level HERE stack gets a location, put http://people.canonical.com/~lool/espoo-cli on your phone (will be included along HERE bits in the future) and run with: chmod a+x espoo-cli GLOG_logtostderr=1 GLOG_v=100 LD_LIBRARY_PATH=/custom/vendor/here/location-provider/lib/arm-linux-gnueabihf ./espoo-cli 5 NB: 5 is the number of location updates after which the tool exits; updates should come in at approx 15s interval. Output looks like: I1101 21:30:01.285964 4403 cli.cpp:117] Requested number of updates is 2 I1101 21:30:01.299002 4403 cli.cpp:133] Starting location updates I1101 21:30:01.301888 4403 cli.cpp:141] Starting GLib main loop I1101 21:30:11.304612 4403 cli.cpp:158] Location: tstamp=1414891811 lat=xyz long=foo hor. acc.=2569 alt=nan vert. acc.=nan tech=cell I1101 21:30:11.306061 4403 cli.cpp:170] Remaining updates: 1 I1101 21:30:26.736821 4403 cli.cpp:158] Location: tstamp=1414891826 lat=xyz long=foo hor. acc.=2824 alt=nan vert. acc.=nan tech=cell I1101 21:30:26.738348 4403 cli.cpp:148] Stopping location updates Low-level HERE stack works but location-serviced with just HERE provider doesn't work? File a bug against espoo projet (HERE) and/or location-service. Low-level HERE stack doesn't work? Move on ## location-service and espoo-service debug Collect some debug data by editing /etc/init/ubuntu-espoo-service.conf and /etc/init/ubuntu-location-service.override and changing the start sequence to add some env vars: export GLOG_v=200 before the exec. Reboot, and start some app. You should have some log files under /var/log/upstart/ubuntu-espoo-service.log and /var/log/upstart/ubuntu-location-service.log to attach to a bug report; e.g. a working espoo log looks like this: WARNING: Logging before InitGoogleLogging() is written to STDERR I1105 16:30:10.221474 1620 provider.cpp:568] StartPositionUpdates I1105 16:30:10.224901 1620 provider.cpp:122] Successfully started position updates. I1105 16:30:10.228739 1620 provider.cpp:596] StartVelocityUpdates I1105 16:30:13.046851 1621 provider.cpp:83] Received location: Position(lat: Coordinate(12.34 deg), lon: Coordinate(12.34 deg), alt: Coordinate(nan m), hor.acc.: 1430 m, ver.acc.: nan m) No position there? check connectivity API works by running: cd /tmp wget http://people.ubuntu.com/~lool/connectivity GLOG_v=200 GLOG_logtostderr=1 ./connectivity you should see something like: I1105 16:47:26.431466 11140 cached_radio_cell.cpp:160] (mcc: 123, mnc: 2, lac: 1234, id: 123456, asu: 1) I1105 16:47:26.533818 11140 connectivity.cpp:47] Is wifi enabled: true I1105 16:47:26.533963 11140 connectivity.cpp:48] Is wifi hw enabled: true I1105 16:47:26.534010 11140 connectivity.cpp:49] Is wwan enabled: true I1105 16:47:26.534050 11140 connectivity.cpp:50] Is wwan hw enabled: true I1105 16:47:26.534442 11140 connectivity.cpp:122] umts(mcc: 123, mnc: 2, lac: 1234, id: 123456, asu: 1) I1105 16:47:26.534633 11140 connectivity.cpp:155] (bssid: 12:12:12:12:12:12, ssid: xyz, last seen: 1415224046, mode: Mode::infrastructure, frequency: 2442, strength: 63) I1105 16:47:26.534828 11140 connectivity.cpp:155] (bssid: 12:12:12:12:12:12, ssid: boing, last seen: 1415224046, mode: Mode::infrastructure, frequency: 2467, strength: 57) Also, please attach output of /usr/share/ofono/scripts/list-modems > list-modems-output.txt Please note that the command might take ~1 minute to complete. TODO: document dbus-monitor / d-feet capturing of client / system traffic with snooping config. location-service/doc/CMakeLists.txt0000644000000000000000000000217312701027425014522 0ustar # Copyright © 2013 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # Authored by: Thomas Voss find_package(Doxygen) if(DOXYGEN_FOUND) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/Doxyfile.in ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile @ONLY) add_custom_target(doc ALL ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} COMMENT "Generating API documentation with Doxygen" VERBATIM) install( DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/html DESTINATION share/LocationService/doc) endif(DOXYGEN_FOUND) location-service/doc/Doxyfile.in0000644000000000000000000023466012701027425014105 0ustar # Doxyfile 1.8.3.1 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project. # # All text after a hash (#) is considered a comment and will be ignored. # The format is: # TAG = value [value, ...] # For lists items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (" "). #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # This tag specifies the encoding used for all characters in the config file # that follow. The default is UTF-8 which is also the encoding used for all # text before the first occurrence of this tag. Doxygen uses libiconv (or the # iconv built into libc) for the transcoding. See # http://www.gnu.org/software/libiconv for the list of possible encodings. DOXYFILE_ENCODING = UTF-8 # The PROJECT_NAME tag is a single word (or sequence of words) that should # identify the project. Note that if you do not use Doxywizard you need # to put quotes around the project name if it contains spaces. PROJECT_NAME = @CMAKE_PROJECT_NAME@ # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or # if some version control system is used. PROJECT_NUMBER = @LOCATION_SERVICE_VERSION_MAJOR@.@LOCATION_SERVICE_VERSION_MINOR@.@LOCATION_SERVICE_VERSION_PATCH@ # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer # a quick idea about the purpose of the project. Keep the description short. PROJECT_BRIEF = "An aggregating location service providing positioning and geocoding capabilities to applications." # With the PROJECT_LOGO tag one can specify an logo or icon that is # included in the documentation. The maximum height of the logo should not # exceed 55 pixels and the maximum width should not exceed 200 pixels. # Doxygen will copy the logo to the output directory. PROJECT_LOGO = # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) # base path where the generated documentation will be put. # If a relative path is entered, it will be relative to the location # where doxygen was started. If left blank the current directory will be used. OUTPUT_DIRECTORY = # If the CREATE_SUBDIRS tag is set to YES, then doxygen will create # 4096 sub-directories (in 2 levels) under the output directory of each output # format and will distribute the generated files over these directories. # Enabling this option can be useful when feeding doxygen a huge amount of # source files, where putting all generated files in the same directory would # otherwise cause performance problems for the file system. CREATE_SUBDIRS = NO # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # The default language is English, other supported languages are: # Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, # Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, # Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English # messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, # Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, # Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. OUTPUT_LANGUAGE = English # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # include brief member descriptions after the members that are listed in # the file and class documentation (similar to JavaDoc). # Set to NO to disable this. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend # the brief description of a member or function before the detailed description. # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. REPEAT_BRIEF = YES # This tag implements a quasi-intelligent brief description abbreviator # that is used to form the text in various listings. Each string # in this list, if found as the leading text of the brief description, will be # stripped from the text and the result after processing the whole list, is # used as the annotated text. Otherwise, the brief description is used as-is. # If left blank, the following values are used ("$name" is automatically # replaced with the name of the entity): "The $name class" "The $name widget" # "The $name file" "is" "provides" "specifies" "contains" # "represents" "a" "an" "the" ABBREVIATE_BRIEF = # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # Doxygen will generate a detailed section even if there is only a brief # description. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full # path before files name in the file list and in the header files. If set # to NO the shortest path that makes the file name unique will be used. FULL_PATH_NAMES = YES # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag # can be used to strip a user-defined part of the path. Stripping is # only done if one of the specified strings matches the left-hand part of # the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the # path to strip. Note that you specify absolute paths here, but also # relative paths, which will be relative from the directory where doxygen is # started. STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of # the path mentioned in the documentation of a class, which tells # the reader which header file to include in order to use a class. # If left blank only the name of the header file containing the class # definition is used. Otherwise one should specify the include paths that # are normally passed to the compiler using the -I flag. STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter # (but less readable) file names. This can be useful if your file system # doesn't support long names like on DOS, Mac, or CD-ROM. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen # will interpret the first line (until the first dot) of a JavaDoc-style # comment as the brief description. If set to NO, the JavaDoc # comments will behave just like regular Qt-style comments # (thus requiring an explicit @brief command for a brief description.) JAVADOC_AUTOBRIEF = NO # If the QT_AUTOBRIEF tag is set to YES then Doxygen will # interpret the first line (until the first dot) of a Qt-style # comment as the brief description. If set to NO, the comments # will behave just like regular Qt-style comments (thus requiring # an explicit \brief command for a brief description.) QT_AUTOBRIEF = NO # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen # treat a multi-line C++ special comment block (i.e. a block of //! or /// # comments) as a brief description. This used to be the default behaviour. # The new default is to treat a multi-line C++ comment block as a detailed # description. Set this tag to YES if you prefer the old behaviour instead. MULTILINE_CPP_IS_BRIEF = NO # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented # member inherits the documentation from any documented member that it # re-implements. INHERIT_DOCS = YES # If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce # a new page for each member. If set to NO, the documentation of a member will # be part of the file/class/namespace that contains it. SEPARATE_MEMBER_PAGES = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. TAB_SIZE = 4 # This tag can be used to specify a number of aliases that acts # as commands in the documentation. An alias has the form "name=value". # For example adding "sideeffect=\par Side Effects:\n" will allow you to # put the command \sideeffect (or @sideeffect) in the documentation, which # will result in a user-defined paragraph with heading "Side Effects:". # You can put \n's in the value part of an alias to insert newlines. ALIASES = # This tag can be used to specify a number of word-keyword mappings (TCL only). # A mapping has the form "name=value". For example adding # "class=itcl::class" will allow you to use the command class in the # itcl::class meaning. TCL_SUBST = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C # sources only. Doxygen will then generate output that is more tailored for C. # For instance, some of the names that are used will be different. The list # of all members will be omitted, etc. OPTIMIZE_OUTPUT_FOR_C = NO # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java # sources only. Doxygen will then generate output that is more tailored for # Java. For instance, namespaces will be presented as packages, qualified # scopes will look different, etc. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources only. Doxygen will then generate output that is more tailored for # Fortran. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for # VHDL. OPTIMIZE_OUTPUT_VHDL = NO # Doxygen selects the parser to use depending on the extension of the files it # parses. With this tag you can assign which parser to use for a given # extension. Doxygen has a built-in mapping, but you can override or extend it # using this tag. The format is ext=language, where ext is a file extension, # and language is one of the parsers supported by doxygen: IDL, Java, # Javascript, CSharp, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, # C++. For instance to make doxygen treat .inc files as Fortran files (default # is PHP), and .f files as C (default is Fortran), use: inc=Fortran f=C. Note # that for custom extensions you also need to set FILE_PATTERNS otherwise the # files are not read by doxygen. EXTENSION_MAPPING = # If MARKDOWN_SUPPORT is enabled (the default) then doxygen pre-processes all # comments according to the Markdown format, which allows for more readable # documentation. See http://daringfireball.net/projects/markdown/ for details. # The output of markdown processing is further processed by doxygen, so you # can mix doxygen, HTML, and XML commands with Markdown formatting. # Disable only in case of backward compatibilities issues. MARKDOWN_SUPPORT = YES # When enabled doxygen tries to link words that correspond to documented classes, # or namespaces to their corresponding documentation. Such a link can be # prevented in individual cases by by putting a % sign in front of the word or # globally by setting AUTOLINK_SUPPORT to NO. AUTOLINK_SUPPORT = YES # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should # set this tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); v.s. # func(std::string) {}). This also makes the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. BUILTIN_STL_SUPPORT = YES # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. CPP_CLI_SUPPORT = NO # Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. # Doxygen will parse them like normal C++ but will assume all classes use public # instead of private inheritance when no explicit protection keyword is present. SIP_SUPPORT = NO # For Microsoft's IDL there are propget and propput attributes to indicate # getter and setter methods for a property. Setting this option to YES (the # default) will make doxygen replace the get and set methods by a property in # the documentation. This will only work if the methods are indeed getting or # setting a simple type. If this is not the case, or you want to show the # methods anyway, you should set this option to NO. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES, then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. DISTRIBUTE_GROUP_DOC = NO # Set the SUBGROUPING tag to YES (the default) to allow class member groups of # the same type (for instance a group of public functions) to be put as a # subgroup of that type (e.g. under the Public Functions section). Set it to # NO to prevent subgrouping. Alternatively, this can be done per class using # the \nosubgrouping command. SUBGROUPING = YES # When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and # unions are shown inside the group in which they are included (e.g. using # @ingroup) instead of on a separate page (for HTML and Man pages) or # section (for LaTeX and RTF). INLINE_GROUPED_CLASSES = NO # When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and # unions with only public data fields will be shown inline in the documentation # of the scope in which they are defined (i.e. file, namespace, or group # documentation), provided this scope is documented. If set to NO (the default), # structs, classes, and unions are shown on a separate page (for HTML and Man # pages) or section (for LaTeX and RTF). INLINE_SIMPLE_STRUCTS = NO # When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum # is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically # be useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. TYPEDEF_HIDES_STRUCT = NO # The SYMBOL_CACHE_SIZE determines the size of the internal cache use to # determine which symbols to keep in memory and which to flush to disk. # When the cache is full, less often used symbols will be written to disk. # For small to medium size projects (<1000 input files) the default value is # probably good enough. For larger projects a too small cache size can cause # doxygen to be busy swapping symbols to and from disk most of the time # causing a significant performance penalty. # If the system has enough physical memory increasing the cache will improve the # performance by keeping more symbols in memory. Note that the value works on # a logarithmic scale so increasing the size by one will roughly double the # memory usage. The cache size is given by this formula: # 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, # corresponding to a cache size of 2^16 = 65536 symbols. SYMBOL_CACHE_SIZE = 0 # Similar to the SYMBOL_CACHE_SIZE the size of the symbol lookup cache can be # set using LOOKUP_CACHE_SIZE. This cache is used to resolve symbols given # their name and scope. Since this can be an expensive process and often the # same symbol appear multiple times in the code, doxygen keeps a cache of # pre-resolved symbols. If the cache is too small doxygen will become slower. # If the cache is too large, memory is wasted. The cache size is given by this # formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range is 0..9, the default is 0, # corresponding to a cache size of 2^16 = 65536 symbols. LOOKUP_CACHE_SIZE = 0 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in # documentation are documented, even if no documentation was available. # Private class members and static file members will be hidden unless # the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES EXTRACT_ALL = YES # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = NO # If the EXTRACT_PACKAGE tag is set to YES all members with package or internal # scope will be included in the documentation. EXTRACT_PACKAGE = NO # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. EXTRACT_STATIC = YES # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. # If set to NO only classes defined in header files are included. EXTRACT_LOCAL_CLASSES = YES # This flag is only useful for Objective-C code. When set to YES local # methods, which are defined in the implementation section but not in # the interface are included in the documentation. # If set to NO (the default) only methods in the interface are included. EXTRACT_LOCAL_METHODS = NO # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base # name of the file that contains the anonymous namespace. By default # anonymous namespaces are hidden. EXTRACT_ANON_NSPACES = NO # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members of documented classes, files or namespaces. # If set to NO (the default) these members will be included in the # various overviews, but no documentation section is generated. # This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. # If set to NO (the default) these classes will be included in the various # overviews. This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all # friend (class|struct|union) declarations. # If set to NO (the default) these declarations will be included in the # documentation. HIDE_FRIEND_COMPOUNDS = YES # If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any # documentation blocks found inside the body of a function. # If set to NO (the default) these blocks will be appended to the # function's detailed documentation block. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate # file names in lower-case letters. If set to YES upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. CASE_SENSE_NAMES = YES # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen # will show members with their full class and namespace scopes in the # documentation. If set to YES the scope will be hidden. HIDE_SCOPE_NAMES = NO # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put a list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = YES # If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen # will list include files with double quotes in the documentation # rather than with sharp brackets. FORCE_LOCAL_INCLUDES = NO # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the # brief documentation of file, namespace and class members alphabetically # by member name. If set to NO (the default) the members will appear in # declaration order. SORT_BRIEF_DOCS = NO # If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen # will sort the (brief and detailed) documentation of class members so that # constructors and destructors are listed first. If set to NO (the default) # the constructors will appear in the respective orders defined by # SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. # This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO # and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. SORT_MEMBERS_CTORS_1ST = NO # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the # hierarchy of group names into alphabetical order. If set to NO (the default) # the group names will appear in their defined order. SORT_GROUP_NAMES = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be # sorted by fully-qualified names, including namespaces. If set to # NO (the default), the class list will be sorted only by class name, # not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the # alphabetical list. SORT_BY_SCOPE_NAME = NO # If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to # do proper type resolution of all parameters of a function it will reject a # match between the prototype and the implementation of a member function even # if there is only one candidate or it is obvious which candidate to choose # by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen # will still accept a match between prototype and implementation in such cases. STRICT_PROTO_MATCHING = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or # disable (NO) the todo list. This list is created by putting \todo # commands in the documentation. GENERATE_TODOLIST = YES # The GENERATE_TESTLIST tag can be used to enable (YES) or # disable (NO) the test list. This list is created by putting \test # commands in the documentation. GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable (YES) or # disable (NO) the bug list. This list is created by putting \bug # commands in the documentation. GENERATE_BUGLIST = YES # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or # disable (NO) the deprecated list. This list is created by putting # \deprecated commands in the documentation. GENERATE_DEPRECATEDLIST= YES # The ENABLED_SECTIONS tag can be used to enable conditional # documentation sections, marked by \if section-label ... \endif # and \cond section-label ... \endcond blocks. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines # the initial value of a variable or macro consists of for it to appear in # the documentation. If the initializer consists of more lines than specified # here it will be hidden. Use a value of 0 to hide initializers completely. # The appearance of the initializer of individual variables and macros in the # documentation can be controlled using \showinitializer or \hideinitializer # command in the documentation regardless of this setting. MAX_INITIALIZER_LINES = 30 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated # at the bottom of the documentation of classes and structs. If set to YES the # list will mention the files that were used to generate the documentation. SHOW_USED_FILES = YES # Set the SHOW_FILES tag to NO to disable the generation of the Files page. # This will remove the Files entry from the Quick Index and from the # Folder Tree View (if specified). The default is YES. SHOW_FILES = YES # Set the SHOW_NAMESPACES tag to NO to disable the generation of the # Namespaces page. # This will remove the Namespaces entry from the Quick Index # and from the Folder Tree View (if specified). The default is YES. SHOW_NAMESPACES = YES # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command , where is the value of # the FILE_VERSION_FILTER tag, and is the name of an input file # provided by doxygen. Whatever the program writes to standard output # is used as the file version. See the manual for examples. FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed # by doxygen. The layout file controls the global structure of the generated # output files in an output format independent way. To create the layout file # that represents doxygen's defaults, run doxygen with the -l option. # You can optionally specify a file name after the option, if omitted # DoxygenLayout.xml will be used as the name of the layout file. LAYOUT_FILE = # The CITE_BIB_FILES tag can be used to specify one or more bib files # containing the references data. This must be a list of .bib files. The # .bib extension is automatically appended if omitted. Using this command # requires the bibtex tool to be installed. See also # http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style # of the bibliography can be controlled using LATEX_BIB_STYLE. To use this # feature you need bibtex and perl available in the search path. Do not use # file names with spaces, bibtex cannot handle them. CITE_BIB_FILES = #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated # by doxygen. Possible values are YES and NO. If left blank NO is used. QUIET = NO # The WARNINGS tag can be used to turn on/off the warning messages that are # generated by doxygen. Possible values are YES and NO. If left blank # NO is used. WARNINGS = YES # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings # for undocumented members. If EXTRACT_ALL is set to YES then this flag will # automatically be disabled. WARN_IF_UNDOCUMENTED = YES # If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some # parameters in a documented function, or documenting parameters that # don't exist or using markup commands wrongly. WARN_IF_DOC_ERROR = YES # The WARN_NO_PARAMDOC option can be enabled to get warnings for # functions that are documented, but have no documentation for their parameters # or return value. If set to NO (the default) doxygen will only warn about # wrong or incomplete parameter documentation, but not about the absence of # documentation. WARN_NO_PARAMDOC = NO # The WARN_FORMAT tag determines the format of the warning messages that # doxygen can produce. The string should contain the $file, $line, and $text # tags, which will be replaced by the file and line number from which the # warning originated and the warning text. Optionally the format may contain # $version, which will be replaced by the version of the file (if it could # be obtained via FILE_VERSION_FILTER) WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning # and error messages should be written. If left blank the output is written # to stderr. WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag can be used to specify the files and/or directories that contain # documented source files. You may enter file names like "myfile.cpp" or # directories like "/usr/src/myproject". Separate the files or directories # with spaces. INPUT = @CMAKE_CURRENT_SOURCE_DIR@ @CMAKE_CURRENT_SOURCE_DIR@/../include # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is # also the default input encoding. Doxygen uses libiconv (or the iconv built # into libc) for the transcoding. See http://www.gnu.org/software/libiconv for # the list of possible encodings. INPUT_ENCODING = UTF-8 # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank the following patterns are tested: # *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh # *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py # *.f90 *.f *.for *.vhd *.vhdl FILE_PATTERNS = # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. # If left blank NO is used. RECURSIVE = YES # The EXCLUDE tag can be used to specify files and/or directories that should be # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. # Note that relative paths are relative to the directory from which doxygen is # run. EXCLUDE = # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded # from the input. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. Note that the wildcards are matched # against the file with absolute path, so to exclude all test directories # for example use the pattern */test/* EXCLUDE_PATTERNS = # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, # AClass::ANamespace, ANamespace::*Test EXCLUDE_SYMBOLS = # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). EXAMPLE_PATH = @CMAKE_CURRENT_SOURCE_DIR@/../tests # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude # commands irrespective of the value of the RECURSIVE tag. # Possible values are YES and NO. If left blank NO is used. EXAMPLE_RECURSIVE = YES # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). IMAGE_PATH = @CMAKE_CURRENT_SOURCE_DIR@/images # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command , where # is the value of the INPUT_FILTER tag, and is the name of an # input file. Doxygen will then use the output that the filter program writes # to standard output. # If FILTER_PATTERNS is specified, this tag will be # ignored. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. # Doxygen will compare the file name with each pattern and apply the # filter if there is a match. # The filters are a list of the form: # pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further # info on how filters are used. If FILTER_PATTERNS is empty or if # non of the patterns match the file name, INPUT_FILTER is applied. FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will be used to filter the input files when producing source # files to browse (i.e. when SOURCE_BROWSER is set to YES). FILTER_SOURCE_FILES = NO # The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file # pattern. A pattern will override the setting for FILTER_PATTERN (if any) # and it is also possible to disable source filtering for a specific pattern # using *.ext= (so without naming a filter). This option only has effect when # FILTER_SOURCE_FILES is enabled. FILTER_SOURCE_PATTERNS = # If the USE_MD_FILE_AS_MAINPAGE tag refers to the name of a markdown file that # is part of the input, its contents will be placed on the main page (index.html). # This can be useful if you have a project on for instance GitHub and want reuse # the introduction page also for the doxygen output. USE_MDFILE_AS_MAINPAGE = @CMAKE_SOURCE_DIR@/README.md #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. # Note: To get rid of all source code in the generated output, make sure also # VERBATIM_HEADERS is set to NO. SOURCE_BROWSER = YES # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code # fragments. Normal C, C++ and Fortran comments will always remain visible. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES # then for each documented function all documented # functions referencing it will be listed. REFERENCED_BY_RELATION = YES # If the REFERENCES_RELATION tag is set to YES # then for each documented function all documented entities # called/used by that function will be listed. REFERENCES_RELATION = YES # If the REFERENCES_LINK_SOURCE tag is set to YES (the default) # and SOURCE_BROWSER tag is set to YES, then the hyperlinks from # functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will # link to the source code. # Otherwise they will link to the documentation. REFERENCES_LINK_SOURCE = YES # If the USE_HTAGS tag is set to YES then the references to source code # will point to the HTML generated by the htags(1) tool instead of doxygen # built-in source browser. The htags tool is part of GNU's global source # tagging system (see http://www.gnu.org/software/global/global.html). You # will need version 4.8.6 or higher. USE_HTAGS = NO # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. VERBATIM_HEADERS = YES #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index # of all compounds will be generated. Enable this if the project # contains a lot of classes, structs, unions or interfaces. ALPHABETICAL_INDEX = YES # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # in which this list will be split (can be a number in the range [1..20]) COLS_IN_ALPHA_INDEX = 5 # In case all classes in a project start with a common prefix, all # classes will be put under the same header in the alphabetical index. # The IGNORE_PREFIX tag can be used to specify one or more prefixes that # should be ignored while generating the index headers. IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES (the default) Doxygen will # generate HTML output. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `html' will be used as the default path. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for # each generated HTML page (for example: .htm,.php,.asp). If it is left blank # doxygen will generate files with .html extension. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a personal HTML header for # each generated HTML page. If it is left blank doxygen will generate a # standard header. Note that when using a custom header you are responsible # for the proper inclusion of any scripts and style sheets that doxygen # needs, which is dependent on the configuration options used. # It is advised to generate a default header using "doxygen -w html # header.html footer.html stylesheet.css YourConfigFile" and then modify # that header. Note that the header is subject to change so you typically # have to redo this when upgrading to a newer version of doxygen or when # changing the value of configuration settings such as GENERATE_TREEVIEW! HTML_HEADER = # The HTML_FOOTER tag can be used to specify a personal HTML footer for # each generated HTML page. If it is left blank doxygen will generate a # standard footer. HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user-defined cascading # style sheet that is used by each HTML page. It can be used to # fine-tune the look of the HTML output. If left blank doxygen will # generate a default style sheet. Note that it is recommended to use # HTML_EXTRA_STYLESHEET instead of this one, as it is more robust and this # tag will in the future become obsolete. HTML_STYLESHEET = # The HTML_EXTRA_STYLESHEET tag can be used to specify an additional # user-defined cascading style sheet that is included after the standard # style sheets created by doxygen. Using this option one can overrule # certain style aspects. This is preferred over using HTML_STYLESHEET # since it does not replace the standard style sheet and is therefor more # robust against future updates. Doxygen will copy the style sheet file to # the output directory. HTML_EXTRA_STYLESHEET = @CMAKE_CURRENT_SOURCE_DIR@/extra.css # The HTML_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the HTML output directory. Note # that these files will be copied to the base HTML output directory. Use the # $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these # files. In the HTML_STYLESHEET file, use the file name only. Also note that # the files will be copied as-is; there are no commands or markers available. HTML_EXTRA_FILES = # The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. # Doxygen will adjust the colors in the style sheet and background images # according to this color. Hue is specified as an angle on a colorwheel, # see http://en.wikipedia.org/wiki/Hue for more information. # For instance the value 0 represents red, 60 is yellow, 120 is green, # 180 is cyan, 240 is blue, 300 purple, and 360 is red again. # The allowed range is 0 to 359. HTML_COLORSTYLE_HUE = 220 # The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of # the colors in the HTML output. For a value of 0 the output will use # grayscales only. A value of 255 will produce the most vivid colors. HTML_COLORSTYLE_SAT = 100 # The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to # the luminance component of the colors in the HTML output. Values below # 100 gradually make the output lighter, whereas values above 100 make # the output darker. The value divided by 100 is the actual gamma applied, # so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2, # and 100 does not change the gamma. HTML_COLORSTYLE_GAMMA = 80 # If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML # page will contain the date and time when the page was generated. Setting # this to NO can help when comparing the output of multiple runs. HTML_TIMESTAMP = YES # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the # page has loaded. HTML_DYNAMIC_SECTIONS = YES # With HTML_INDEX_NUM_ENTRIES one can control the preferred number of # entries shown in the various tree structured indices initially; the user # can expand and collapse entries dynamically later on. Doxygen will expand # the tree to such a level that at most the specified number of entries are # visible (unless a fully collapsed tree already exceeds this amount). # So setting the number of entries 1 will produce a full collapsed tree by # default. 0 is a special value representing an infinite number of entries # and will result in a full expanded tree by default. HTML_INDEX_NUM_ENTRIES = 100 # If the GENERATE_DOCSET tag is set to YES, additional index files # will be generated that can be used as input for Apple's Xcode 3 # integrated development environment, introduced with OSX 10.5 (Leopard). # To create a documentation set, doxygen will generate a Makefile in the # HTML output directory. Running make will produce the docset in that # directory and running "make install" will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find # it at startup. # See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html # for more information. GENERATE_DOCSET = NO # When GENERATE_DOCSET tag is set to YES, this tag determines the name of the # feed. A documentation feed provides an umbrella under which multiple # documentation sets from a single provider (such as a company or product suite) # can be grouped. DOCSET_FEEDNAME = "Doxygen generated docs" # When GENERATE_DOCSET tag is set to YES, this tag specifies a string that # should uniquely identify the documentation set bundle. This should be a # reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen # will append .docset to the name. DOCSET_BUNDLE_ID = org.doxygen.Project # When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely # identify the documentation publisher. This should be a reverse domain-name # style string, e.g. com.mycompany.MyDocSet.documentation. DOCSET_PUBLISHER_ID = org.doxygen.Publisher # The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher. DOCSET_PUBLISHER_NAME = Publisher # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compiled HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can # be used to specify the file name of the resulting .chm file. You # can add a path in front of the file if the result should not be # written to the html output directory. CHM_FILE = # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can # be used to specify the location (absolute path including file name) of # the HTML help compiler (hhc.exe). If non-empty doxygen will try to run # the HTML help compiler on the generated index.hhp. HHC_LOCATION = # If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag # controls if a separate .chi index file is generated (YES) or that # it should be included in the master .chm file (NO). GENERATE_CHI = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING # is used to encode HtmlHelp index (hhk), content (hhc) and project file # content. CHM_INDEX_ENCODING = # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag # controls whether a binary table of contents is generated (YES) or a # normal table of contents (NO) in the .chm file. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members # to the contents of the HTML help documentation and to the tree view. TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and # QHP_VIRTUAL_FOLDER are set, an additional index file will be generated # that can be used as input for Qt's qhelpgenerator to generate a # Qt Compressed Help (.qch) of the generated HTML documentation. GENERATE_QHP = NO # If the QHG_LOCATION tag is specified, the QCH_FILE tag can # be used to specify the file name of the resulting .qch file. # The path specified is relative to the HTML output folder. QCH_FILE = # The QHP_NAMESPACE tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#namespace QHP_NAMESPACE = org.doxygen.Project # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#virtual-folders QHP_VIRTUAL_FOLDER = doc # If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to # add. For more information please see # http://doc.trolltech.com/qthelpproject.html#custom-filters QHP_CUST_FILTER_NAME = # The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the # custom filter to add. For more information please see # # Qt Help Project / Custom Filters. QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # project's # filter section matches. # # Qt Help Project / Filter Attributes. QHP_SECT_FILTER_ATTRS = # If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can # be used to specify the location of Qt's qhelpgenerator. # If non-empty doxygen will try to run qhelpgenerator on the generated # .qhp file. QHG_LOCATION = # If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files # will be generated, which together with the HTML files, form an Eclipse help # plugin. To install this plugin and make it available under the help contents # menu in Eclipse, the contents of the directory containing the HTML and XML # files needs to be copied into the plugins directory of eclipse. The name of # the directory within the plugins directory should be the same as # the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before # the help appears. GENERATE_ECLIPSEHELP = NO # A unique identifier for the eclipse help plugin. When installing the plugin # the directory name containing the HTML and XML files should also have # this name. ECLIPSE_DOC_ID = org.doxygen.Project # The DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) # at top of each HTML page. The value NO (the default) enables the index and # the value YES disables it. Since the tabs have the same information as the # navigation tree you can set this option to NO if you already set # GENERATE_TREEVIEW to YES. DISABLE_INDEX = YES # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. # If the tag value is set to YES, a side panel will be generated # containing a tree-like index structure (just like the one that # is generated for HTML Help). For this to work a browser that supports # JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). # Windows users are probably better off using the HTML help feature. # Since the tree basically has the same information as the tab index you # could consider to set DISABLE_INDEX to NO when enabling this option. GENERATE_TREEVIEW = YES # The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values # (range [0,1..20]) that doxygen will group on one line in the generated HTML # documentation. Note that a value of 0 will completely suppress the enum # values from appearing in the overview section. ENUM_VALUES_PER_LINE = 1 # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be # used to set the initial width (in pixels) of the frame in which the tree # is shown. TREEVIEW_WIDTH = 250 # When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open # links to external symbols imported via tag files in a separate window. EXT_LINKS_IN_WINDOW = NO # Use this tag to change the font size of Latex formulas included # as images in the HTML documentation. The default is 10. Note that # when you change the font size after a successful doxygen run you need # to manually remove any form_*.png images from the HTML output directory # to force them to be regenerated. FORMULA_FONTSIZE = 10 # Use the FORMULA_TRANPARENT tag to determine whether or not the images # generated for formulas are transparent PNGs. Transparent PNGs are # not supported properly for IE 6.0, but are supported on all modern browsers. # Note that when changing this option you need to delete any form_*.png files # in the HTML output before the changes have effect. FORMULA_TRANSPARENT = YES # Enable the USE_MATHJAX option to render LaTeX formulas using MathJax # (see http://www.mathjax.org) which uses client side Javascript for the # rendering instead of using prerendered bitmaps. Use this if you do not # have LaTeX installed or if you want to formulas look prettier in the HTML # output. When enabled you may also need to install MathJax separately and # configure the path to it using the MATHJAX_RELPATH option. USE_MATHJAX = NO # When MathJax is enabled you can set the default output format to be used for # thA MathJax output. Supported types are HTML-CSS, NativeMML (i.e. MathML) and # SVG. The default value is HTML-CSS, which is slower, but has the best # compatibility. MATHJAX_FORMAT = HTML-CSS # When MathJax is enabled you need to specify the location relative to the # HTML output directory using the MATHJAX_RELPATH option. The destination # directory should contain the MathJax.js script. For instance, if the mathjax # directory is located at the same level as the HTML output directory, then # MATHJAX_RELPATH should be ../mathjax. The default value points to # the MathJax Content Delivery Network so you can quickly see the result without # installing MathJax. # However, it is strongly recommended to install a local # copy of MathJax from http://www.mathjax.org before deployment. MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest # The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension # names that should be enabled during MathJax rendering. MATHJAX_EXTENSIONS = # When the SEARCHENGINE tag is enabled doxygen will generate a search box # for the HTML output. The underlying search engine uses javascript # and DHTML and should work on any modern browser. Note that when using # HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets # (GENERATE_DOCSET) there is already a search function so this one should # typically be disabled. For large projects the javascript based search engine # can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. SEARCHENGINE = NO # When the SERVER_BASED_SEARCH tag is enabled the search engine will be # implemented using a web server instead of a web client using Javascript. # There are two flavours of web server based search depending on the # EXTERNAL_SEARCH setting. When disabled, doxygen will generate a PHP script for # searching and an index file used by the script. When EXTERNAL_SEARCH is # enabled the indexing and searching needs to be provided by external tools. # See the manual for details. SERVER_BASED_SEARCH = NO # When EXTERNAL_SEARCH is enabled doxygen will no longer generate the PHP # script for searching. Instead the search results are written to an XML file # which needs to be processed by an external indexer. Doxygen will invoke an # external search engine pointed to by the SEARCHENGINE_URL option to obtain # the search results. Doxygen ships with an example indexer (doxyindexer) and # search engine (doxysearch.cgi) which are based on the open source search engine # library Xapian. See the manual for configuration details. EXTERNAL_SEARCH = NO # The SEARCHENGINE_URL should point to a search engine hosted by a web server # which will returned the search results when EXTERNAL_SEARCH is enabled. # Doxygen ships with an example search engine (doxysearch) which is based on # the open source search engine library Xapian. See the manual for configuration # details. SEARCHENGINE_URL = # When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed # search data is written to a file for indexing by an external tool. With the # SEARCHDATA_FILE tag the name of this file can be specified. SEARCHDATA_FILE = searchdata.xml # When SERVER_BASED_SEARCH AND EXTERNAL_SEARCH are both enabled the # EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is # useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple # projects and redirect the results back to the right project. EXTERNAL_SEARCH_ID = # The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen # projects other than the one defined by this configuration file, but that are # all added to the same external search index. Each project needs to have a # unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id # of to a relative location where the documentation can be found. # The format is: EXTRA_SEARCH_MAPPINGS = id1=loc1 id2=loc2 ... EXTRA_SEARCH_MAPPINGS = #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # generate Latex output. GENERATE_LATEX = YES # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `latex' will be used as the default path. LATEX_OUTPUT = latex # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be # invoked. If left blank `latex' will be used as the default command name. # Note that when enabling USE_PDFLATEX this option is only used for # generating bitmaps for formulas in the HTML output, but not in the # Makefile that is written to the output directory. LATEX_CMD_NAME = latex # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to # generate index for LaTeX. If left blank `makeindex' will be used as the # default command name. MAKEINDEX_CMD_NAME = makeindex # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_LATEX = YES # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, letter, legal and # executive. If left blank a4wide will be used. PAPER_TYPE = a4 # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. EXTRA_PACKAGES = # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until # the first chapter. If it is left blank doxygen will generate a # standard header. Notice: only use this tag if you know what you are doing! LATEX_HEADER = # The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for # the generated latex document. The footer should contain everything after # the last chapter. If it is left blank doxygen will generate a # standard footer. Notice: only use this tag if you know what you are doing! LATEX_FOOTER = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated # is prepared for conversion to pdf (using ps2pdf). The pdf file will # contain links (just like the HTML output) instead of page references # This makes the output suitable for online browsing using a pdf viewer. PDF_HYPERLINKS = YES # If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of # plain latex in the generated Makefile. Set this option to YES to get a # higher quality PDF documentation. USE_PDFLATEX = YES # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # command to the generated LaTeX files. This will instruct LaTeX to keep # running if errors occur, instead of asking the user for help. # This option is also used when generating formulas in HTML. LATEX_BATCHMODE = NO # If LATEX_HIDE_INDICES is set to YES then doxygen will not # include the index chapters (such as File Index, Compound Index, etc.) # in the output. LATEX_HIDE_INDICES = NO # If LATEX_SOURCE_CODE is set to YES then doxygen will include # source code with syntax highlighting in the LaTeX output. # Note that which sources are shown also depends on other settings # such as SOURCE_BROWSER. LATEX_SOURCE_CODE = NO # The LATEX_BIB_STYLE tag can be used to specify the style to use for the # bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See # http://en.wikipedia.org/wiki/BibTeX for more info. LATEX_BIB_STYLE = plain #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output # The RTF output is optimized for Word 97 and may not look very pretty with # other RTF readers or editors. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `rtf' will be used as the default path. RTF_OUTPUT = rtf # If the COMPACT_RTF tag is set to YES Doxygen generates more compact # RTF documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # will contain hyperlink fields. The RTF file will # contain links (just like the HTML output) instead of page references. # This makes the output suitable for online browsing using WORD or other # programs which support those fields. # Note: wordpad (write) and others do not support links. RTF_HYPERLINKS = NO # Load style sheet definitions from file. Syntax is similar to doxygen's # config file, i.e. a series of assignments. You only have to provide # replacements, missing definitions are set to their default value. RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an rtf document. # Syntax is similar to doxygen's config file. RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES (the default) Doxygen will # generate man pages GENERATE_MAN = YES # The MAN_OUTPUT tag is used to specify where the man pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `man' will be used as the default path. MAN_OUTPUT = man # The MAN_EXTENSION tag determines the extension that is added to # the generated man pages (default is the subroutine's section .3) MAN_EXTENSION = .3 # If the MAN_LINKS tag is set to YES and Doxygen generates man output, # then it will generate one additional man file for each entity # documented in the real man page(s). These additional files # only source the real man page, but without them the man command # would be unable to find the correct page. The default is NO. MAN_LINKS = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- # If the GENERATE_XML tag is set to YES Doxygen will # generate an XML file that captures the structure of # the code including all documentation. GENERATE_XML = YES # The XML_OUTPUT tag is used to specify where the XML pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `xml' will be used as the default path. XML_OUTPUT = xml # The XML_SCHEMA tag can be used to specify an XML schema, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_SCHEMA = # The XML_DTD tag can be used to specify an XML DTD, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_DTD = # If the XML_PROGRAMLISTING tag is set to YES Doxygen will # dump the program listings (including syntax highlighting # and cross-referencing information) to the XML output. Note that # enabling this will significantly increase the size of the XML output. XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- # If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will # generate an AutoGen Definitions (see autogen.sf.net) file # that captures the structure of the code including all # documentation. Note that this feature is still experimental # and incomplete at the moment. GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # configuration options related to the Perl module output #--------------------------------------------------------------------------- # If the GENERATE_PERLMOD tag is set to YES Doxygen will # generate a Perl module file that captures the structure of # the code including all documentation. Note that this # feature is still experimental and incomplete at the # moment. GENERATE_PERLMOD = NO # If the PERLMOD_LATEX tag is set to YES Doxygen will generate # the necessary Makefile rules, Perl scripts and LaTeX code to be able # to generate PDF and DVI output from the Perl module output. PERLMOD_LATEX = NO # If the PERLMOD_PRETTY tag is set to YES the Perl module output will be # nicely formatted so it can be parsed by a human reader. # This is useful # if you want to understand what is going on. # On the other hand, if this # tag is set to NO the size of the Perl module output will be much smaller # and Perl will parse it just the same. PERLMOD_PRETTY = YES # The names of the make variables in the generated doxyrules.make file # are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. # This is useful so different doxyrules.make files included by the same # Makefile don't overwrite each other's variables. PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will # evaluate all C-preprocessor directives found in the sources and include # files. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro # names in the source code. If set to NO (the default) only conditional # compilation will be performed. Macro expansion can be done in a controlled # way by setting EXPAND_ONLY_PREDEF to YES. MACRO_EXPANSION = NO # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED and EXPAND_AS_DEFINED tags. EXPAND_ONLY_PREDEF = NO # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # pointed to by INCLUDE_PATH will be searched when a #include is found. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by # the preprocessor. INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the # directories. If left blank, the patterns specified with FILE_PATTERNS will # be used. INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that # are defined before the preprocessor is started (similar to the -D option of # gcc). The argument of the tag is a list of macros of the form: name # or name=definition (no spaces). If the definition and the = are # omitted =1 is assumed. To prevent a macro definition from being # undefined via #undef or recursively expanded use the := operator # instead of the = operator. PREDEFINED = # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. # The macro definition that is found in the sources will be used. # Use the PREDEFINED tag if you want to use a different macro definition that # overrules the definition found in the source code. EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then # doxygen's preprocessor will remove all references to function-like macros # that are alone on a line, have an all uppercase name, and do not end with a # semicolon, because these will confuse the parser if not removed. SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration::additions related to external references #--------------------------------------------------------------------------- # The TAGFILES option can be used to specify one or more tagfiles. For each # tag file the location of the external documentation should be added. The # format of a tag file without this location is as follows: # # TAGFILES = file1 file2 ... # Adding location for the tag files is done as follows: # # TAGFILES = file1=loc1 "file2 = loc2" ... # where "loc1" and "loc2" can be relative or absolute paths # or URLs. Note that each tag file must have a unique name (where the name does # NOT include the path). If a tag file is not located in the directory in which # doxygen is run, you must also specify the path to the tagfile here. TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create # a tag file that is based on the input files it reads. GENERATE_TAGFILE = # If the ALLEXTERNALS tag is set to YES all external classes will be listed # in the class index. If set to NO only the inherited external classes # will be listed. ALLEXTERNALS = NO # If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed # in the modules index. If set to NO, only the current project's groups will # be listed. EXTERNAL_GROUPS = YES # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of `which perl'). PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will # generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base # or super classes. Setting the tag to NO turns the diagrams off. Note that # this option also works with HAVE_DOT disabled, but it is recommended to # install and use dot, since it yields more powerful graphs. CLASS_DIAGRAMS = YES # You can define message sequence charts within doxygen comments using the \msc # command. Doxygen will then run the mscgen tool (see # http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the # documentation. The MSCGEN_PATH tag allows you to specify the directory where # the mscgen tool resides. If left empty the tool is assumed to be found in the # default search path. MSCGEN_PATH = # If set to YES, the inheritance and collaboration graphs will hide # inheritance and usage relations if the target is undocumented # or is not a class. HIDE_UNDOC_RELATIONS = NO # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz, a graph visualization # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) HAVE_DOT = YES # The DOT_NUM_THREADS specifies the number of dot invocations doxygen is # allowed to run in parallel. When set to 0 (the default) doxygen will # base this on the number of processors available in the system. You can set it # explicitly to a value larger than 0 to get control over the balance # between CPU load and processing speed. DOT_NUM_THREADS = 1 # By default doxygen will use the Helvetica font for all dot files that # doxygen generates. When you want a differently looking font you can specify # the font name using DOT_FONTNAME. You need to make sure dot is able to find # the font, which can be done by putting it in a standard location or by setting # the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the # directory containing the font. DOT_FONTNAME = Helvetica # The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. # The default size is 10pt. DOT_FONTSIZE = 10 # By default doxygen will tell dot to use the Helvetica font. # If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to # set the path where dot can find it. DOT_FONTPATH = # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect inheritance relations. Setting this tag to YES will force the # CLASS_DIAGRAMS tag to NO. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect implementation dependencies (inheritance, containment, and # class references variables) of the class with other documented classes. COLLABORATION_GRAPH = YES # If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen # will generate a graph for groups, showing the direct groups dependencies GROUP_GRAPHS = YES # If the UML_LOOK tag is set to YES doxygen will generate inheritance and # collaboration diagrams in a style similar to the OMG's Unified Modeling # Language. UML_LOOK = YES # If the UML_LOOK tag is enabled, the fields and methods are shown inside # the class node. If there are many fields or methods and many nodes the # graph may become too big to be useful. The UML_LIMIT_NUM_FIELDS # threshold limits the number of items for each type to make the size more # managable. Set this to 0 for no limit. Note that the threshold may be # exceeded by 50% before the limit is enforced. UML_LIMIT_NUM_FIELDS = 10 # If set to YES, the inheritance and collaboration graphs will show the # relations between templates and their instances. TEMPLATE_RELATIONS = NO # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT # tags are set to YES then doxygen will generate a graph for each documented # file showing the direct and indirect include dependencies of the file with # other documented files. INCLUDE_GRAPH = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and # HAVE_DOT tags are set to YES then doxygen will generate a graph for each # documented header file showing the documented files that directly or # indirectly include this file. INCLUDED_BY_GRAPH = YES # If the CALL_GRAPH and HAVE_DOT options are set to YES then # doxygen will generate a call dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable call graphs # for selected functions only using the \callgraph command. CALL_GRAPH = YES # If the CALLER_GRAPH and HAVE_DOT tags are set to YES then # doxygen will generate a caller dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable caller # graphs for selected functions only using the \callergraph command. CALLER_GRAPH = NO # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen # will generate a graphical hierarchy of all classes instead of a textual one. GRAPHICAL_HIERARCHY = YES # If the DIRECTORY_GRAPH and HAVE_DOT tags are set to YES # then doxygen will show the dependencies a directory has on other directories # in a graphical way. The dependency relations are determined by the #include # relations between the files in the directories. DIRECTORY_GRAPH = YES # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. Possible values are svg, png, jpg, or gif. # If left blank png will be used. If you choose svg you need to set # HTML_FILE_EXTENSION to xhtml in order to make the SVG files # visible in IE 9+ (other browsers do not have this requirement). DOT_IMAGE_FORMAT = png # If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to # enable generation of interactive SVG images that allow zooming and panning. # Note that this requires a modern browser other than Internet Explorer. # Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you # need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files # visible. Older versions of IE do not have SVG support. INTERACTIVE_SVG = YES # The tag DOT_PATH can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found in the path. DOT_PATH = # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the # \dotfile command). DOTFILE_DIRS = # The MSCFILE_DIRS tag can be used to specify one or more directories that # contain msc files that are included in the documentation (see the # \mscfile command). MSCFILE_DIRS = # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of # nodes that will be shown in the graph. If the number of nodes in a graph # becomes larger than this value, doxygen will truncate the graph, which is # visualized by representing a node as a red box. Note that doxygen if the # number of direct children of the root node in a graph is already larger than # DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note # that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. DOT_GRAPH_MAX_NODES = 50 # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the # graphs generated by dot. A depth value of 3 means that only nodes reachable # from the root by following a path via at most 3 edges will be shown. Nodes # that lay further from the root node will be omitted. Note that setting this # option to 1 or 2 may greatly reduce the computation time needed for large # code bases. Also note that the size of a graph can be further restricted by # DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. MAX_DOT_GRAPH_DEPTH = 0 # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent # background. This is disabled by default, because dot on Windows does not # seem to support this out of the box. Warning: Depending on the platform used, # enabling this option may lead to badly anti-aliased labels on the edges of # a graph (i.e. they become hard to read). DOT_TRANSPARENT = YES # Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output # files in one run (i.e. multiple -o and -T options on the command line). This # makes dot run faster, but since only newer versions of dot (>1.8.10) # support this, this feature is disabled by default. DOT_MULTI_TARGETS = YES # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will # generate a legend page explaining the meaning of the various boxes and # arrows in the dot generated graphs. GENERATE_LEGEND = YES # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will # remove the intermediate dot files that are used to generate # the various graphs. DOT_CLEANUP = YES location-service/cmake/0000755000000000000000000000000012701027425012272 5ustar location-service/cmake/FindGFlags.cmake0000644000000000000000000000064112701027425015241 0ustar if (GFlags_INCLUDE_DIR) # Already in cache, be silent set(GFlags_FIND_QUIETLY TRUE) endif () find_path(GFlags_INCLUDE_DIR gflags/gflags.h) find_library(GFlags_LIBRARY libgflags.so HINTS /usr/lib/arm-linux-gnueabihf/) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(GFlags DEFAULT_MSG GFlags_LIBRARY GFlags_INCLUDE_DIR) mark_as_advanced(GFlags_LIBRARY GFlags_INCLUDE_DIR) location-service/cmake/EnableCoverageReport.cmake0000644000000000000000000001537512701027425017345 0ustar # - Creates a special coverage build type and target on GCC. # # Defines a function ENABLE_COVERAGE_REPORT which generates the coverage target # for selected targets. Optional arguments to this function are used to filter # unwanted results using globbing expressions. Moreover targets with tests for # the source code can be specified to trigger regenerating the report if the # test has changed # # ENABLE_COVERAGE_REPORT(TARGETS target... [FILTER filter...] [TESTS test targets...]) # # To generate a coverage report first build the project with # CMAKE_BUILD_TYPE=coverage, then call make test and afterwards make coverage. # # The coverage report is based on gcov. Depending on the availability of lcov # a HTML report will be generated and/or an XML report of gcovr is found. # The generated coverage target executes all found solutions. Special targets # exist to create e.g. only the xml report: coverage-xml. # # Copyright (C) 2010 by Johannes Wienke # # This program is free software; you can redistribute it # and/or modify it under the terms of the GNU General # Public License as published by the Free Software Foundation; # either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # INCLUDE(ParseArguments) FIND_PACKAGE(Lcov) FIND_PACKAGE(gcovr) FUNCTION(ENABLE_COVERAGE_REPORT) # argument parsing PARSE_ARGUMENTS(ARG "FILTER;TARGETS;TESTS" "" ${ARGN}) SET(COVERAGE_RAW_FILE "${CMAKE_BINARY_DIR}/coverage.raw.info") SET(COVERAGE_FILTERED_FILE "${CMAKE_BINARY_DIR}/coverage.info") SET(COVERAGE_REPORT_DIR "${CMAKE_BINARY_DIR}/coveragereport") SET(COVERAGE_XML_FILE "${CMAKE_BINARY_DIR}/coverage.xml") SET(COVERAGE_XML_COMMAND_FILE "${CMAKE_BINARY_DIR}/coverage-xml.cmake") # decide if there is any tool to create coverage data SET(TOOL_FOUND FALSE) IF(LCOV_FOUND OR GCOVR_FOUND) SET(TOOL_FOUND TRUE) ENDIF() IF(NOT TOOL_FOUND) MESSAGE(STATUS "Cannot enable coverage targets because neither lcov nor gcovr are found.") ENDIF() STRING(TOLOWER "${CMAKE_BUILD_TYPE}" COVERAGE_BUILD_TYPE) IF(CMAKE_COMPILER_IS_GNUCXX AND TOOL_FOUND AND "${COVERAGE_BUILD_TYPE}" MATCHES "coverage") MESSAGE(STATUS "Coverage support enabled for targets: ${ARG_TARGETS}") # create coverage build type SET(CMAKE_CXX_FLAGS_COVERAGE ${CMAKE_CXX_FLAGS_DEBUG} PARENT_SCOPE) SET(CMAKE_C_FLAGS_COVERAGE ${CMAKE_C_FLAGS_DEBUG} PARENT_SCOPE) SET(CMAKE_CONFIGURATION_TYPES ${CMAKE_CONFIGURATION_TYPES} coverage PARENT_SCOPE) # instrument targets SET_TARGET_PROPERTIES(${ARG_TARGETS} PROPERTIES COMPILE_FLAGS --coverage LINK_FLAGS --coverage) # html report IF (LCOV_FOUND) MESSAGE(STATUS "Enabling HTML coverage report") # set up coverage target ADD_CUSTOM_COMMAND(OUTPUT ${COVERAGE_RAW_FILE} COMMAND ${LCOV_EXECUTABLE} -c -d ${CMAKE_BINARY_DIR} -o ${COVERAGE_RAW_FILE} WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMENT "Collecting coverage data" DEPENDS ${ARG_TARGETS} ${ARG_TESTS} VERBATIM) # filter unwanted stuff LIST(LENGTH ARG_FILTER FILTER_LENGTH) IF(${FILTER_LENGTH} GREATER 0) SET(FILTER COMMAND ${LCOV_EXECUTABLE}) FOREACH(F ${ARG_FILTER}) SET(FILTER ${FILTER} -r ${COVERAGE_FILTERED_FILE} ${F}) ENDFOREACH() SET(FILTER ${FILTER} -o ${COVERAGE_FILTERED_FILE}) ELSE() SET(FILTER "") ENDIF() ADD_CUSTOM_COMMAND(OUTPUT ${COVERAGE_FILTERED_FILE} COMMAND ${LCOV_EXECUTABLE} -e ${COVERAGE_RAW_FILE} "${CMAKE_SOURCE_DIR}*" -o ${COVERAGE_FILTERED_FILE} ${FILTER} DEPENDS ${COVERAGE_RAW_FILE} COMMENT "Filtering recorded coverage data for project-relevant entries" VERBATIM) ADD_CUSTOM_COMMAND(OUTPUT ${COVERAGE_REPORT_DIR} COMMAND ${CMAKE_COMMAND} -E make_directory ${COVERAGE_REPORT_DIR} COMMAND ${GENHTML_EXECUTABLE} --legend --show-details -t "${PROJECT_NAME} test coverage" -o ${COVERAGE_REPORT_DIR} ${COVERAGE_FILTERED_FILE} DEPENDS ${COVERAGE_FILTERED_FILE} COMMENT "Generating HTML coverage report in ${COVERAGE_REPORT_DIR}" VERBATIM) ADD_CUSTOM_TARGET(coverage-html DEPENDS ${COVERAGE_REPORT_DIR}) ENDIF() # xml coverage report IF(GCOVR_FOUND) MESSAGE(STATUS "Enabling XML coverage report") # gcovr cannot write directly to a file so the execution needs to # be wrapped in a cmake file that generates the file output FILE(WRITE ${COVERAGE_XML_COMMAND_FILE} "SET(ENV{LANG} en)\n") FILE(APPEND ${COVERAGE_XML_COMMAND_FILE} "EXECUTE_PROCESS(COMMAND \"${GCOVR_EXECUTABLE}\" --exclude=tests.* --exclude=obj-.* --exclude=cmake.* -x -r \"${CMAKE_SOURCE_DIR}\" OUTPUT_FILE \"${COVERAGE_XML_FILE}\" WORKING_DIRECTORY \"${CMAKE_BINARY_DIR}\")\n") ADD_CUSTOM_COMMAND(OUTPUT ${COVERAGE_XML_FILE} COMMAND ${CMAKE_COMMAND} ARGS -P ${COVERAGE_XML_COMMAND_FILE} COMMENT "Generating coverage XML report" VERBATIM) ADD_CUSTOM_TARGET(coverage-xml DEPENDS ${COVERAGE_XML_FILE}) ENDIF() # provide a global coverage target executing both steps if available SET(GLOBAL_DEPENDS "") IF(LCOV_FOUND) LIST(APPEND GLOBAL_DEPENDS ${COVERAGE_REPORT_DIR}) ENDIF() IF(GCOVR_FOUND) LIST(APPEND GLOBAL_DEPENDS ${COVERAGE_XML_FILE}) ENDIF() IF(LCOV_FOUND OR GCOVR_FOUND) ADD_CUSTOM_TARGET(coverage DEPENDS ${GLOBAL_DEPENDS}) ENDIF() ENDIF() ENDFUNCTION() location-service/cmake/Findgcovr.cmake0000644000000000000000000000170212701027425015215 0ustar # - Find gcovr scrip # Will define: # # GCOVR_EXECUTABLE - the gcovr script # # Uses: # # GCOVR_ROOT - root to search for the script # # Copyright (C) 2011 by Johannes Wienke # # This program is free software; you can redistribute it # and/or modify it under the terms of the GNU General # Public License as published by the Free Software Foundation; # either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # INCLUDE(FindPackageHandleStandardArgs) FIND_PROGRAM(GCOVR_EXECUTABLE gcovr HINTS ${GCOVR_ROOT} "${GCOVR_ROOT}/bin") FIND_PACKAGE_HANDLE_STANDARD_ARGS(gcovr DEFAULT_MSG GCOVR_EXECUTABLE) # only visible in advanced view MARK_AS_ADVANCED(GCOVR_EXECUTABLE) location-service/cmake/FindGLog.cmake0000644000000000000000000000061412701027425014726 0ustar if (GLog_INCLUDE_DIR) # Already in cache, be silent set(GLog_FIND_QUIETLY TRUE) endif () find_path(GLog_INCLUDE_DIR glog/logging.h) find_library(GLog_LIBRARY libglog.so HINTS /usr/lib/arm-linux-gnueabihf/) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(GLog DEFAULT_MSG GLog_LIBRARY GLog_INCLUDE_DIR) mark_as_advanced(GLog_LIBRARY GLog_INCLUDE_DIR) location-service/cmake/PrePush.cmake0000644000000000000000000000677512701027425014701 0ustar ####################################################################### # A convenience target that carries out the following steps: # - Apply astyle to all source files of interest. # - Build & test in a chroot, comparable setup to CI/Autolanding # and ppa builders. Will fail if new files have not been added. # - Build & test for android. # # NOTE: This target is very sensitive to the availability of all # all required dependencies. For that, we prefer to fail the # target if deps are missing to make the problem very visible. # # TODO: # - Wire up the style-check target once we have reached a state # where trunk actually passes the style check. ####################################################################### add_custom_target( pre-push WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} ) ####################################################################### # Add target for running astyle with the correct options # ####################################################################### find_program(ASTYLE_EXECUTABLE astyle) if (ASTYLE_EXECUTABLE) add_custom_target( astyle ${ASTYLE_EXECUTABLE} --style=allman -s4 --indent=spaces=4 --pad-header --align-pointer=type --recursive ${CMAKE_SOURCE_DIR}/include/*.h COMMAND ${ASTYLE_EXECUTABLE} --recursive --style=allman -s4 --indent=spaces=4 --pad-header --align-pointer=type ${CMAKE_SOURCE_DIR}/tests/*.cpp VERBATIM ) endif (ASTYLE_EXECUTABLE) ####################################################################### # Add target for creating a source tarball with bzr export # ####################################################################### add_custom_target( pre-push-source-tarball COMMAND rm -rf pre-push-build-area COMMAND mkdir pre-push-build-area COMMAND bzr export --root pre-push pre-push-build-area/${PROJECT_NAME}_${DBUS_CPP_VERSION_MAJOR}.${DBUS_CPP_VERSION_MAJOR}.${DBUS_CPP_VERSION_MAJOR}.orig.tar.bz2 ${CMAKE_SOURCE_DIR} WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMENT "Preparing source tarball for pre-push build & test" ) ####################################################################### # Add target for extracting source tarball for pdebuild # ####################################################################### add_custom_target( extract-pre-push-tarball COMMAND tar -xf {PROJECT_NAME}_${DBUS_CPP_VERSION_MAJOR}.${DBUS_CPP_VERSION_MAJOR}.${DBUS_CPP_VERSION_MAJOR}.orig.tar.bz2 WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/pre-push-build-area VERBATIM ) ####################################################################### # Builds & tests the last committed revision of the current branch # ####################################################################### find_program(PDEBUILD_EXECUTABLE pdebuild) if(NOT PDEBUILD_EXECUTABLE) message(STATUS "pdebuild NOT found, pre-push is going to FAIL") endif() add_custom_target( pdebuild COMMAND ${PDEBUILD_EXECUTABLE} WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/pre-push-build-area/pre-push COMMENT "Building & testing in chroot'd environment" VERBATIM ) ####################################################################### # pdebuild: make tarball -> extract to build area -> pdebuild # # android-build: invoke cross-compile script # ####################################################################### add_dependencies(extract-pre-push-tarball pre-push-source-tarball) add_dependencies(pdebuild extract-pre-push-tarball) add_dependencies(pre-push pdebuild android-build) location-service/cmake/ParseArguments.cmake0000644000000000000000000000340612701027425016237 0ustar # Parse arguments passed to a function into several lists separated by # upper-case identifiers and options that do not have an associated list e.g.: # # SET(arguments # hello OPTION3 world # LIST3 foo bar # OPTION2 # LIST1 fuz baz # ) # PARSE_ARGUMENTS(ARG "LIST1;LIST2;LIST3" "OPTION1;OPTION2;OPTION3" ${arguments}) # # results in 7 distinct variables: # * ARG_DEFAULT_ARGS: hello;world # * ARG_LIST1: fuz;baz # * ARG_LIST2: # * ARG_LIST3: foo;bar # * ARG_OPTION1: FALSE # * ARG_OPTION2: TRUE # * ARG_OPTION3: TRUE # # taken from http://www.cmake.org/Wiki/CMakeMacroParseArguments MACRO(PARSE_ARGUMENTS prefix arg_names option_names) SET(DEFAULT_ARGS) FOREACH(arg_name ${arg_names}) SET(${prefix}_${arg_name}) ENDFOREACH(arg_name) FOREACH(option ${option_names}) SET(${prefix}_${option} FALSE) ENDFOREACH(option) SET(current_arg_name DEFAULT_ARGS) SET(current_arg_list) FOREACH(arg ${ARGN}) SET(larg_names ${arg_names}) LIST(FIND larg_names "${arg}" is_arg_name) IF (is_arg_name GREATER -1) SET(${prefix}_${current_arg_name} ${current_arg_list}) SET(current_arg_name ${arg}) SET(current_arg_list) ELSE (is_arg_name GREATER -1) SET(loption_names ${option_names}) LIST(FIND loption_names "${arg}" is_option) IF (is_option GREATER -1) SET(${prefix}_${arg} TRUE) ELSE (is_option GREATER -1) SET(current_arg_list ${current_arg_list} ${arg}) ENDIF (is_option GREATER -1) ENDIF (is_arg_name GREATER -1) ENDFOREACH(arg) SET(${prefix}_${current_arg_name} ${current_arg_list}) ENDMACRO(PARSE_ARGUMENTS) location-service/cmake/FindLcov.cmake0000644000000000000000000000172012701027425015000 0ustar # - Find lcov # Will define: # # LCOV_EXECUTABLE - the lcov binary # GENHTML_EXECUTABLE - the genhtml executable # # Copyright (C) 2010 by Johannes Wienke # # This program is free software; you can redistribute it # and/or modify it under the terms of the GNU General # Public License as published by the Free Software Foundation; # either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # INCLUDE(FindPackageHandleStandardArgs) FIND_PROGRAM(LCOV_EXECUTABLE lcov) FIND_PROGRAM(GENHTML_EXECUTABLE genhtml) FIND_PACKAGE_HANDLE_STANDARD_ARGS(Lcov DEFAULT_MSG LCOV_EXECUTABLE GENHTML_EXECUTABLE) # only visible in advanced view MARK_AS_ADVANCED(LCOV_EXECUTABLE GENHTML_EXECUTABLE) location-service/_clang-format0000644000000000000000000000325412701027425013652 0ustar --- Language: Cpp AccessModifierOffset: -4 ConstructorInitializerIndentWidth: 4 AlignEscapedNewlinesLeft: false AlignTrailingComments: true AllowAllParametersOfDeclarationOnNextLine: true AllowShortBlocksOnASingleLine: false AllowShortIfStatementsOnASingleLine: false AllowShortLoopsOnASingleLine: false AllowShortFunctionsOnASingleLine: All AlwaysBreakTemplateDeclarations: false AlwaysBreakBeforeMultilineStrings: false BreakBeforeBinaryOperators: false BreakBeforeTernaryOperators: true BreakConstructorInitializersBeforeComma: false BinPackParameters: true ColumnLimit: 0 ConstructorInitializerAllOnOneLineOrOnePerLine: false DerivePointerAlignment: false ExperimentalAutoDetectBinPacking: false IndentCaseLabels: false IndentWrappedFunctionNames: false IndentFunctionDeclarationAfterType: false MaxEmptyLinesToKeep: 1 KeepEmptyLinesAtTheStartOfBlocks: true NamespaceIndentation: None ObjCSpaceAfterProperty: false ObjCSpaceBeforeProtocolList: true PenaltyBreakBeforeFirstCallParameter: 19 PenaltyBreakComment: 300 PenaltyBreakString: 1000 PenaltyBreakFirstLessLess: 120 PenaltyExcessCharacter: 1000000 PenaltyReturnTypeOnItsOwnLine: 60 PointerAlignment: Left SpacesBeforeTrailingComments: 1 Cpp11BracedListStyle: true Standard: Cpp11 IndentWidth: 4 TabWidth: 8 UseTab: Never BreakBeforeBraces: Allman SpacesInParentheses: false SpacesInAngles: false SpaceInEmptyParentheses: false SpacesInCStyleCastParentheses: false SpacesInContainerLiterals: true SpaceBeforeAssignmentOperators: true ContinuationIndentWidth: 4 CommentPragmas: '^ IWYU pragma:' ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ] SpaceBeforeParens: ControlStatements DisableFormat: false ... location-service/tests/0000755000000000000000000000000012701027440012351 5ustar location-service/tests/delayed_service_test.cpp0000644000000000000000000001601712701027425017253 0ustar /* * Copyright © 2014 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß * Scott Sweeny */ #include #include #include #include #include #include #include #include #include #include #include #include "did_finish_successfully.h" #include "mock_event_receiver.h" #include namespace location = com::ubuntu::location; namespace remote = com::ubuntu::location::providers::remote; namespace { struct DelayedServiceTest : public core::dbus::testing::Fixture, public ::testing::WithParamInterface { }; } TEST_P(DelayedServiceTest, AClientReceivesUpdatesFromADelayedProvider) { auto oopp = core::posix::fork([this]() { auto bus = session_bus(); // Pass the delay value to the provider char delay[50]; sprintf(delay, "--dummy::DelayedProvider::DelayInMs=%d", GetParam()); const char* argv[] = { "--bus", "session", // 2 "--service-name", "com.ubuntu.location.providers.Dummy", // 4 "--service-path", "/com/ubuntu/location/providers/Dummy", // 6 "--provider", "dummy::DelayedProvider", // 8 delay // 9 }; auto dbus_connection_factory = [bus](core::dbus::WellKnownBus) { return bus; }; return static_cast( location::service::ProviderDaemon::main( location::service::ProviderDaemon::Configuration::from_command_line_args( 9, argv, dbus_connection_factory))); }, core::posix::StandardStream::empty); std::this_thread::sleep_for(std::chrono::milliseconds{250}); auto service = core::posix::fork([this]() { core::posix::this_process::env::set_or_throw( "TRUST_STORE_PERMISSION_MANAGER_IS_RUNNING_UNDER_TESTING", "1"); const char* argv[] = { "--bus", "session", // 2 "--provider", "remote::Provider", // 4 "--remote::Provider::bus=session_with_address_from_env", // 5 "--remote::Provider::name=com.ubuntu.location.providers.Dummy", // 6 "--remote::Provider::path=/com/ubuntu/location/providers/Dummy" // 7 }; // The daemon instance requires two bus instances. auto dbus_connection_factory = [this](core::dbus::WellKnownBus) { return session_bus(); }; return static_cast( location::service::Daemon::main( location::service::Daemon::Configuration::from_command_line_args( 7, argv, dbus_connection_factory))); }, core::posix::StandardStream::empty); // Wait to setup the client until the service is up std::this_thread::sleep_for(std::chrono::milliseconds{250 + GetParam()}); auto client = core::posix::fork([this]() { using namespace ::testing; auto trap = core::posix::trap_signals_for_all_subsequent_threads( { core::posix::Signal::sig_term, core::posix::Signal::sig_int }); trap->signal_raised().connect([trap](const core::posix::Signal&) { trap->stop(); }); auto bus = session_bus(); bus->install_executor(core::dbus::asio::make_executor(bus)); std::thread worker { [bus]() { bus->run(); } }; MockEventReceiver receiver; EXPECT_CALL(receiver, position_update_received(_)).Times(AtLeast(1)); EXPECT_CALL(receiver, heading_update_received(_)).Times(AtLeast(1)); EXPECT_CALL(receiver, velocity_update_received(_)).Times(AtLeast(1)); com::ubuntu::location::service::Stub service{bus}; auto session = service.create_session_for_criteria(location::Criteria{}); session->updates().position.changed().connect([&receiver](location::Update pos) { receiver.position_update_received(pos); }); session->updates().heading.changed().connect([&receiver](location::Update heading) { receiver.heading_update_received(heading); }); session->updates().velocity.changed().connect([&receiver](location::Update velocity) { receiver.velocity_update_received(velocity); }); session->updates().position_status = location::service::session::Interface::Updates::Status::enabled; session->updates().velocity_status = location::service::session::Interface::Updates::Status::enabled; session->updates().heading_status = location::service::session::Interface::Updates::Status::enabled; trap->run(); bus->stop(); if (worker.joinable()) worker.join(); return ::testing::Test::HasFailure() ? core::posix::exit::Status::failure : core::posix::exit::Status::success; }, core::posix::StandardStream::empty); std::this_thread::sleep_for(std::chrono::milliseconds{4000}); std::cout << "Shutting down client" << std::endl; client.send_signal_or_throw(core::posix::Signal::sig_term); EXPECT_TRUE(did_finish_successfully(client.wait_for(core::posix::wait::Flags::untraced))); std::cout << "Shutting down service" << std::endl; service.send_signal_or_throw(core::posix::Signal::sig_term); EXPECT_TRUE(did_finish_successfully(service.wait_for(core::posix::wait::Flags::untraced))); std::cout << "Shutting down oopp" << std::endl; oopp.send_signal_or_throw(core::posix::Signal::sig_term); EXPECT_TRUE(did_finish_successfully(oopp.wait_for(core::posix::wait::Flags::untraced))); } INSTANTIATE_TEST_CASE_P(ServiceDelays, DelayedServiceTest, ::testing::Values(0, 250, 500, 1000, 2000, 5000, 10000)); location-service/tests/boost_ptree_settings_test.cpp0000644000000000000000000000456312701027425020374 0ustar /* * Copyright © 2014 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #include #include #include namespace location = com::ubuntu::location; namespace { const char* fn{"/tmp/totally_does_not_exist_file.ini"}; } TEST(BoostPtreeSettings, does_not_throw_for_file_that_cannot_be_read_from) { std::remove(fn); EXPECT_NO_THROW(location::BoostPtreeSettings settings{fn}); } TEST(BoostPtreeSettings, never_throws_on_syncing) { std::remove(fn); location::BoostPtreeSettings settings{fn}; settings.set_string_for_key("test", "test"); EXPECT_NO_THROW(settings.sync()); } TEST(BoostPtreeSettings, values_are_correctly_stored) { std::remove(fn); location::BoostPtreeSettings settings{fn}; settings.set_string_for_key("test", "42"); EXPECT_TRUE(settings.has_value_for_key("test")); EXPECT_EQ("42", settings.get_string_for_key_or_throw("test")); } TEST(BoostPtreeSettings, throws_correct_exception_for_missing_value) { std::remove(fn); location::BoostPtreeSettings settings{fn}; EXPECT_FALSE(settings.has_value_for_key("test")); EXPECT_THROW(settings.get_string_for_key_or_throw("test"), location::Settings::Error::NoValueForKey); EXPECT_EQ("42", settings.get_string_for_key("test", "42")); } TEST(BoostPtreeSettings, correctly_reads_and_writes_values_to_file) { std::remove(fn); // We feed values in and sync them to file. { location::BoostPtreeSettings settings{fn}; settings.set_string_for_key("test.test", "42"); settings.sync(); } // And read them back here. { location::BoostPtreeSettings settings{fn}; EXPECT_EQ("42", settings.get_string_for_key_or_throw("test.test")); } } location-service/tests/daemon_and_cli_tests.cpp0000644000000000000000000002355112701027440017221 0ustar /* * Copyright © 2012-2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #include #include #include #include #include #include #include #include #include #include #include #include "mock_engine.h" #include #include namespace location = com::ubuntu::location; namespace { struct DaemonAndCli : public core::dbus::testing::Fixture { }; std::function testing_daemon(DaemonAndCli& fixture) { return [&fixture]() { static constexpr const char* fn{"/tmp/settings.ini"}; // Clean up prior to running the test case. std::remove(fn); location::service::Daemon::Configuration config; config.incoming = fixture.session_bus(); config.outgoing = fixture.session_bus(); config.is_testing_enabled = true; config.settings = std::make_shared(fn); auto result = location::service::Daemon::main(config); EXPECT_EQ(EXIT_SUCCESS, result); return ::testing::Test::HasFailure() ? core::posix::exit::Status::failure : core::posix::exit::Status::success; }; } std::function querying_cli_for_property( location::service::Daemon::Cli::Property property, DaemonAndCli& fixture) { return [property, &fixture]() { // We need to wait some time to make sure that the service is up and running std::this_thread::sleep_for(std::chrono::seconds{1}); location::service::Daemon::Cli::Configuration config; config.bus = fixture.session_bus(); config.command = location::service::Daemon::Cli::Command::get; config.property = property; auto result = location::service::Daemon::Cli::main(config); EXPECT_EQ(EXIT_SUCCESS, result); return ::testing::Test::HasFailure() ? core::posix::exit::Status::failure : core::posix::exit::Status::success; }; } template std::function adjusting_cli_for_property( location::service::Daemon::Cli::Property property, const T& value, DaemonAndCli& fixture) { return [property, value, &fixture]() { // We need to wait some time to make sure that the service is up and running std::this_thread::sleep_for(std::chrono::seconds{1}); std::stringstream ss; ss << value; location::service::Daemon::Cli::Configuration config; config.bus = fixture.session_bus(); config.command = location::service::Daemon::Cli::Command::set; config.property = property; config.new_value = ss.str(); auto result = location::service::Daemon::Cli::main(config); EXPECT_EQ(EXIT_SUCCESS, result); return ::testing::Test::HasFailure() ? core::posix::exit::Status::failure : core::posix::exit::Status::success; }; } } TEST_F(DaemonAndCli, QueryingIsOnlinePropertyWorks) { EXPECT_EQ(core::testing::ForkAndRunResult::empty, core::testing::fork_and_run( testing_daemon(*this), querying_cli_for_property( location::service::Daemon::Cli::Property::is_online, *this))); } TEST_F(DaemonAndCli, AdjustingIsOnlinePropertyWorks) { EXPECT_EQ(core::testing::ForkAndRunResult::empty, core::testing::fork_and_run( testing_daemon(*this), adjusting_cli_for_property( location::service::Daemon::Cli::Property::is_online, false, *this))); } TEST_F(DaemonAndCli, QueryingDoesSatelliteBasedPositionPropertyWorks) { EXPECT_EQ(core::testing::ForkAndRunResult::empty, core::testing::fork_and_run( testing_daemon(*this), querying_cli_for_property( location::service::Daemon::Cli::Property::does_satellite_based_positioning, *this))); } TEST_F(DaemonAndCli, AdjustingDoesSatelliteBasedPositionPropertyWorks) { EXPECT_EQ(core::testing::ForkAndRunResult::empty, core::testing::fork_and_run( testing_daemon(*this), adjusting_cli_for_property( location::service::Daemon::Cli::Property::does_satellite_based_positioning, false, *this))); } TEST_F(DaemonAndCli, QueryingDoesReportWifiAndCellIdsPropertyWorks) { EXPECT_NO_FATAL_FAILURE( core::testing::fork_and_run( testing_daemon(*this), querying_cli_for_property( location::service::Daemon::Cli::Property::does_report_wifi_and_cell_ids, *this))); } TEST_F(DaemonAndCli, AdjustingDoesReportWifiAndCellIdsPropertyWorks) { EXPECT_NO_FATAL_FAILURE( core::testing::fork_and_run( testing_daemon(*this), adjusting_cli_for_property( location::service::Daemon::Cli::Property::does_report_wifi_and_cell_ids, true, *this))); } TEST_F(DaemonAndCli, QueryingVisibleSpaceVehiclesPropertyWorks) { EXPECT_EQ(core::testing::ForkAndRunResult::empty, core::testing::fork_and_run( testing_daemon(*this), querying_cli_for_property( location::service::Daemon::Cli::Property::visible_space_vehicles, *this))); } namespace { auto null_dbus_connection_factory = [](core::dbus::WellKnownBus) { return core::dbus::Bus::Ptr{}; }; } TEST(DaemonCli, CommandLineArgsParsingWorksForCorrectArguments) { const char* args[] = { "--bus", "session", "--get", "--property", "is_online" }; auto config = location::service::Daemon::Cli::Configuration::from_command_line_args(5, args, null_dbus_connection_factory); EXPECT_EQ(location::service::Daemon::Cli::Command::get, config.command); EXPECT_EQ(location::service::Daemon::Cli::Property::is_online, config.property); } TEST(DaemonCli, CommandLineArgsParsingThrowsForInvalidArguments) { const char* args[] = { "--bus", "session", "--get", "--set", // Both get and set specificed, expected to throw "--property", "is_online" }; EXPECT_ANY_THROW(location::service::Daemon::Cli::Configuration::from_command_line_args(5, args, null_dbus_connection_factory)); } TEST(Daemon, CommandLineParsingThrowsForEmptyProviders) { const char* args[] = { "--bus", "session" }; EXPECT_ANY_THROW(location::service::Daemon::Configuration::from_command_line_args(2, args, null_dbus_connection_factory)); } TEST(Daemon, CommandLineParsingDoesNotThrowForEmptyProvidersInTesting) { const char* args[] = { "--bus", "session", "--testing" }; EXPECT_ANY_THROW(location::service::Daemon::Configuration::from_command_line_args(2, args, null_dbus_connection_factory)); } TEST(Daemon, CommandLineParsingWorksForProvidersAndProviderOptions) { const char* args[] = { "--bus", "session", "--provider", "does::not::exist::Provider", "--does::not::exist::Provider::option1=test1", "--does::not::exist::Provider::option2=test2", "--does::not::exist::Provider::option3=test3" }; auto config = location::service::Daemon::Configuration::from_command_line_args(7, args, null_dbus_connection_factory); EXPECT_EQ(1u, config.providers.size()); EXPECT_EQ("does::not::exist::Provider", config.providers[0]); EXPECT_EQ("test1", config.provider_options.at(config.providers[0]).get("option1")); EXPECT_EQ("test2", config.provider_options.at(config.providers[0]).get("option2")); EXPECT_EQ("test3", config.provider_options.at(config.providers[0]).get("option3")); } TEST(Daemon, ProviderLoadingWorks) { const char* args[] = { "--bus", "session", "--provider", "dummy::Provider", }; auto config = location::service::Daemon::Configuration::from_command_line_args(4, args, null_dbus_connection_factory); location::service::DefaultConfiguration dc; auto engine = std::make_shared(dc.the_provider_selection_policy(), config.settings); EXPECT_CALL(*engine, add_provider(::testing::_)); location::service::Daemon::load_providers(config, engine); } TEST(Daemon, MultipleProviderLoadingWorks) { const char* args[] = { "--bus", "session", "--provider", "dummy::Provider", "--provider", "dummy::DelayedProvider", "--dummy::DelayedProvider::DelayInMs=250" }; auto config = location::service::Daemon::Configuration::from_command_line_args(7, args, null_dbus_connection_factory); location::service::DefaultConfiguration dc; auto engine = std::make_shared(dc.the_provider_selection_policy(), config.settings); EXPECT_CALL(*engine, add_provider(::testing::_)).Times(2); location::service::Daemon::load_providers(config, engine); } location-service/tests/heading_test.cpp0000644000000000000000000000351312701027425015520 0ustar /* * Copyright © 2012-2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #include #include TEST(Heading, constructing_a_heading_with_invalid_value_throws) { EXPECT_ANY_THROW(com::ubuntu::location::Heading h {-std::numeric_limits::min()*com::ubuntu::location::units::Degrees};); EXPECT_ANY_THROW(com::ubuntu::location::Heading h {361.*com::ubuntu::location::units::Degrees};); } TEST(Heading, constructing_a_heading_with_a_valid_value_does_not_throw) { std::default_random_engine rng; std::uniform_real_distribution dist(com::ubuntu::location::Heading::min().value(), com::ubuntu::location::Heading::max().value()); EXPECT_NO_THROW(com::ubuntu::location::Heading h {dist(rng)*com::ubuntu::location::units::Degrees};); } TEST(Heading, a_heading_contains_value_passed_at_construction) { std::default_random_engine rng; std::uniform_real_distribution dist(com::ubuntu::location::Heading::min().value(), com::ubuntu::location::Heading::max().value()); double d = dist(rng); com::ubuntu::location::Heading h {d* com::ubuntu::location::units::Degrees}; EXPECT_DOUBLE_EQ(d, h.value.value()); } location-service/tests/web_server.h0000644000000000000000000000722312701027425014674 0ustar /* * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef TESTING_WEB_SERVER_H_ #define TESTING_WEB_SERVER_H_ #include #include #include #include #include #include #include #include "mongoose.h" namespace testing { namespace web { namespace server { // Configuration options for creating a testing web server. struct Configuration { // The port to expose the web-server on. std::uint16_t port; // Function that is invoked for individual client requests. std::function request_handler; }; } } // Returns an executable web-server for the given configuration. inline std::function a_web_server(const web::server::Configuration& configuration) { return [configuration](core::testing::CrossProcessSync& cps) { bool terminated = false; // Register for SIG_TERM auto trap = core::posix::trap_signals_for_all_subsequent_threads({core::posix::Signal::sig_term}); // On SIG_TERM, we set terminated to false and request a clean shutdown // of the polling loop. trap->signal_raised().connect([trap, &terminated](core::posix::Signal) { trap->stop(); terminated = true; }); struct Context { static int on_request(mg_connection* conn, mg_event ev) { auto thiz = static_cast(conn->server_param); switch (ev) { case MG_REQUEST: return thiz->handle_request(conn); case MG_AUTH: return MG_TRUE; default: return MG_FALSE; } return MG_FALSE; } int handle_request(mg_connection* conn) { return configuration.request_handler(conn); } const testing::web::server::Configuration& configuration; } context{configuration}; std::thread trap_worker { [trap]() { trap->run(); } }; auto server = mg_create_server(&context, Context::on_request); // Setup the port on which the server should be exposed. mg_set_option(server, "listening_port", std::to_string(configuration.port).c_str()); // Notify framework that we are good to go cps.try_signal_ready_for(std::chrono::milliseconds{500}); // Start the polling loop for (;;) { mg_poll_server(server, 200); if (terminated) break; } // Cleanup, and free server instance mg_destroy_server(&server); if (trap_worker.joinable()) trap_worker.join(); return ::testing::Test::HasFailure() ? core::posix::exit::Status::failure : core::posix::exit::Status::success; }; } } #endif // TESTING_WEB_SERVER_H_ location-service/tests/trust_store_permission_manager_test.cpp0000644000000000000000000001616012701027425022462 0ustar /* * Copyright © 2012-2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #include #include #include #include #include #include #include namespace location = com::ubuntu::location; namespace service = com::ubuntu::location::service; namespace { struct MockAgent : public core::trust::Agent { /** * @brief Presents the given request to the user, returning the user-provided answer. * @param request The trust request that a user has to answer. * @param description Extended description of the trust request. */ MOCK_METHOD1(authenticate_request_with_parameters, core::trust::Request::Answer(const core::trust::Agent::RequestParameters&)); }; struct MockAppArmorProfileResolver { MOCK_METHOD1(resolve_pid_to_app_armor_profile, std::string(const core::trust::Pid&)); service::TrustStorePermissionManager::AppArmorProfileResolver to_functional() { return [this](const core::trust::Pid& pid) { return resolve_pid_to_app_armor_profile(pid); }; } }; location::Criteria default_criteria; } TEST(TrustStorePermissionManager, calls_out_to_agent) { using namespace ::testing; auto mock_agent = std::make_shared(); EXPECT_CALL(*mock_agent, authenticate_request_with_parameters(_)) .Times(1) .WillRepeatedly(Return(core::trust::Request::Answer::denied)); service::TrustStorePermissionManager pm { mock_agent, service::TrustStorePermissionManager::libapparmor_profile_resolver() }; EXPECT_EQ(service::PermissionManager::Result::rejected, pm.check_permission_for_credentials( default_criteria, location::service::Credentials{::getpid(), ::getuid()})); } TEST(TrustStorePermissionManager, returns_rejected_for_throwing_agent) { using namespace ::testing; auto mock_agent = std::make_shared(); EXPECT_CALL(*mock_agent, authenticate_request_with_parameters(_)) .Times(1) .WillRepeatedly(Throw(std::runtime_error{"Thrown from mock agent"})); service::TrustStorePermissionManager pm{mock_agent, service::TrustStorePermissionManager::libapparmor_profile_resolver()}; EXPECT_EQ(service::PermissionManager::Result::rejected, pm.check_permission_for_credentials(default_criteria, location::service::Credentials{::getpid(), ::getuid()})); } TEST(TrustStorePermissionManager, resolves_app_id) { using namespace ::testing; const pid_t pid = ::getpid(); const uid_t uid = ::getuid(); auto mock_agent = std::make_shared(); EXPECT_CALL(*mock_agent, authenticate_request_with_parameters(_)) .Times(1) .WillRepeatedly(Return(core::trust::Request::Answer::denied)); MockAppArmorProfileResolver resolver; EXPECT_CALL(resolver, resolve_pid_to_app_armor_profile(core::trust::Pid{pid})) .Times(1) .WillRepeatedly(Return(std::string{"does.not.exist"})); service::TrustStorePermissionManager pm { mock_agent, resolver.to_functional() }; EXPECT_EQ(service::PermissionManager::Result::rejected, pm.check_permission_for_credentials(default_criteria, location::service::Credentials{pid, uid})); } TEST(TrustStorePermissionManager, returns_rejected_for_throwing_app_id_resolver) { using namespace ::testing; const pid_t pid = ::getpid(); const uid_t uid = ::getuid(); auto mock_agent = std::make_shared(); EXPECT_CALL(*mock_agent, authenticate_request_with_parameters(_)) .Times(0); // This should never be called if we cannot resolve an apparmor profile. MockAppArmorProfileResolver resolver; EXPECT_CALL(resolver, resolve_pid_to_app_armor_profile(core::trust::Pid{pid})) .Times(1) .WillRepeatedly(Throw(std::runtime_error{"Thrown from MockAppArmorProfileResolver"})); service::TrustStorePermissionManager pm { mock_agent, resolver.to_functional() }; EXPECT_EQ(service::PermissionManager::Result::rejected, pm.check_permission_for_credentials(default_criteria, location::service::Credentials{pid, uid})); } // We should be provided with this kind of functionality by the trust-store. // The respective request is captured here: // https://bugs.launchpad.net/trust-store/+bug/1350736 TEST(AppArmorProfileResolver, libapparmor_profile_resolver_returns_correct_profile_for_unconfined_process) { auto child = core::posix::fork( []() { while (true); return core::posix::exit::Status::success;}, core::posix::StandardStream::empty); EXPECT_EQ("unconfined", service::TrustStorePermissionManager::libapparmor_profile_resolver()(core::trust::Pid{child.pid()})); } TEST(AppArmorProfileResolver, libapparmor_profile_resolver_throws_for_apparmor_error) { // Passing -1 as the pid value results in the underlying apparmor call failing // and the implementation translating to a std::system_error. EXPECT_THROW(service::TrustStorePermissionManager::libapparmor_profile_resolver()(core::trust::Pid{-1}), std::system_error); } // We disabel this test by default as it requires the developer to take some manual preparations. // Specifically: // sudo apparmor-parser -n for_testing --add tests/app_armor_testing_profile namespace for_testing { static constexpr const char* an_empty_profile_for_testing_purposes { "an_empty_profile_for_testing_purposes" }; } TEST(AppArmorProfileResolver, DISABLED_libapparmor_profile_resolver_returns_correct_profile_for_confined_process) { core::testing::CrossProcessSync cps; // child --| aa_profile_changed |--> parent auto child = core::posix::fork( [&cps]() { aa_change_profile(for_testing::an_empty_profile_for_testing_purposes); cps.try_signal_ready_for(std::chrono::milliseconds{500}); while (true); return core::posix::exit::Status::success; }, core::posix::StandardStream::empty); cps.wait_for_signal_ready_for(std::chrono::milliseconds{500}); EXPECT_EQ(for_testing::an_empty_profile_for_testing_purposes, service::TrustStorePermissionManager::libapparmor_profile_resolver()(core::trust::Pid{child.pid()})); } location-service/tests/app_armor_testing_profile0000644000000000000000000000006112701027425017531 0ustar profile an_empty_profile_for_testing_purposes { }location-service/tests/mock_event_consumer.h0000644000000000000000000000753612701027425016605 0ustar /* * Copyright © 2014 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef MOCK_EVENT_CONSUMER_H_ #define MOCK_EVENT_CONSUMER_H_ #include #include #include class MockEventConsumer { public: MockEventConsumer() { using namespace ::testing; ON_CALL(*this, on_new_position(_)) .WillByDefault( InvokeWithoutArgs( this, &MockEventConsumer::notify_position_update_arrived)); ON_CALL(*this, on_new_heading(_)) .WillByDefault( InvokeWithoutArgs( this, &MockEventConsumer::notify_heading_update_arrived)); ON_CALL(*this, on_new_velocity(_)) .WillByDefault( InvokeWithoutArgs( this, &MockEventConsumer::notify_velocity_update_arrived)); } bool wait_for_position_update_for(const std::chrono::milliseconds& timeout) { std::unique_lock ul{position.guard}; return position.wait_condition.wait_for(ul, timeout, [this] { return position.update_arrived; }); } bool wait_for_heading_update_for(const std::chrono::milliseconds& timeout) { std::unique_lock ul{heading.guard}; return heading.wait_condition.wait_for(ul, timeout, [this] { return heading.update_arrived; }); } bool wait_for_velocity_update_for(const std::chrono::milliseconds& timeout) { std::unique_lock ul{velocity.guard}; return velocity.wait_condition.wait_for(ul, timeout, [this] { return velocity.update_arrived; }); } MOCK_METHOD1(on_new_position, void(const com::ubuntu::location::Update&)); MOCK_METHOD1(on_new_heading, void(const com::ubuntu::location::Update&)); MOCK_METHOD1(on_new_velocity, void(const com::ubuntu::location::Update&)); private: // Notes down the arrival of a position update // and notifies any waiting threads about the event. void notify_position_update_arrived() { position.update_arrived = true; position.wait_condition.notify_all(); } // Notes down the arrival of a heading update // and notifies any waiting threads about the event. void notify_heading_update_arrived() { heading.update_arrived = true; heading.wait_condition.notify_all(); } // Notes down the arrival of a heading update // and notifies any waiting threads about the event. void notify_velocity_update_arrived() { velocity.update_arrived = true; velocity.wait_condition.notify_all(); } struct { std::mutex guard; std::condition_variable wait_condition; bool update_arrived{false}; } position; struct { std::mutex guard; std::condition_variable wait_condition; bool update_arrived{false}; } heading; struct { std::mutex guard; std::condition_variable wait_condition; bool update_arrived{false}; } velocity; }; #endif // MOCK_EVENT_CONSUMER_H_ location-service/tests/mock_network_manager.h0000644000000000000000000002134212701027425016723 0ustar /* * Copyright © 2014 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Thomas Voß */ #ifndef MOCK_NETWORK_MANAGER_H_ #define MOCK_NETWORK_MANAGER_H_ #include #include namespace xdg = org::freedesktop; namespace mock { struct NetworkManager { struct AccessPoint { AccessPoint(const core::dbus::Object::Ptr& object) : object{object}, properties { object->get_property(), object->get_property(), object->get_property(), object->get_property(), object->get_property(), object->get_property() }, signals { object->get_signal() } { properties.frequency->set(2412); properties.last_seen->set(0); properties.mode->set((std::uint32_t)xdg::NetworkManager::AccessPoint::Mode::infra); } core::dbus::Object::Ptr object; struct { std::shared_ptr> frequency; std::shared_ptr> last_seen; std::shared_ptr> mode; std::shared_ptr> hw_address; std::shared_ptr> ssid; std::shared_ptr> strength; } properties; struct { std::shared_ptr> properties_changed; } signals; }; struct Device { Device(const core::dbus::Bus::Ptr& bus, const core::dbus::Object::Ptr& object) : bus{bus}, object{object}, properties { object->get_property() }, signals { object->get_signal(), object->get_signal(), object->get_signal() } { // To save us some typing. using namespace ::testing; properties.device_type->set(static_cast(xdg::NetworkManager::Device::Type::unknown)); ON_CALL(*this, get_access_points()).WillByDefault(Return(std::vector{})); object->install_method_handler([this](const core::dbus::Message::Ptr& msg) { auto reply = core::dbus::Message::make_method_return(msg); reply->writer() << get_access_points(); this->bus->send(reply); }); object->install_method_handler([this](const core::dbus::Message::Ptr& msg) { auto reply = core::dbus::Message::make_method_return(msg); request_scan(); this->bus->send(reply); }); } MOCK_METHOD0(get_access_points, std::vector()); MOCK_METHOD0(request_scan, void()); core::dbus::Bus::Ptr bus; core::dbus::Object::Ptr object; struct { std::shared_ptr> device_type; } properties; struct { core::dbus::Signal::Ptr scan_done; core::dbus::Signal::Ptr ap_added; core::dbus::Signal::Ptr ap_removed; } signals; }; NetworkManager(const core::dbus::Bus::Ptr& bus, const core::dbus::Service::Ptr& service, const core::dbus::Object::Ptr& object) : bus{bus}, service{service}, object{object}, properties { object->get_property(), object->get_property(), object->get_property(), object->get_property(), object->get_property(), object->get_property(), object->get_property() }, signals { object->get_signal(), object->get_signal(), object->get_signal(), object->get_signal() } { // To save us some typing. using namespace ::testing; ON_CALL(*this, get_devices()).WillByDefault(Return(std::vector{})); object->install_method_handler([this](const core::dbus::Message::Ptr& msg) { auto reply = core::dbus::Message::make_method_return(msg); reply->writer() << get_devices(); this->bus->send(reply); }); } MOCK_METHOD0(get_devices, std::vector()); core::dbus::Bus::Ptr bus; core::dbus::Service::Ptr service; core::dbus::Object::Ptr object; struct { std::shared_ptr > connectivity; std::shared_ptr > primary_connection; std::shared_ptr > state; std::shared_ptr > is_wifi_enabled; std::shared_ptr > is_wifi_hardware_enabled; std::shared_ptr > is_wwan_enabled; std::shared_ptr > is_wwan_hardware_enabled; } properties; struct { core::dbus::Signal::Ptr device_added; core::dbus::Signal::Ptr device_removed; core::dbus::Signal::Ptr properties_changed; core::dbus::Signal::Ptr state_changed; } signals; }; } #endif // MOCK_NETWORK_MANAGER_H_ location-service/tests/mock_engine.h0000644000000000000000000000320312701027440014776 0ustar /* * Copyright © 2016 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * * Authored by: Scott Sweeny #include #include struct MockEngine : public com::ubuntu::location::Engine { MockEngine( const com::ubuntu::location::ProviderSelectionPolicy::Ptr& provider_selection_policy, const com::ubuntu::location::Settings::Ptr& settings) : com::ubuntu::location::Engine(provider_selection_policy, settings) { } // has_provider and remove_provider cannot be mocked because they are marked noexcept MOCK_METHOD1(determine_provider_selection_for_criteria, com::ubuntu::location::ProviderSelection(const com::ubuntu::location::Criteria&)); MOCK_METHOD1(add_provider, void(const com::ubuntu::location::Provider::Ptr&)); MOCK_METHOD1(for_each_provider, void(const std::function& enumerator)); }; #endif // MOCK_ENGINE_H location-service/tests/mongoose.c0000644000000000000000000046106312701027425014360 0ustar // Copyright (c) 2004-2013 Sergey Lyubka // Copyright (c) 2013-2014 Cesanta Software Limited // All rights reserved // // This library is dual-licensed: you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. For the terms of this // license, see . // // You are free to use this library under the terms of the GNU General // Public License, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // Alternatively, you can license this library under a commercial // license, as set out in . #ifdef NOEMBED_NET_SKELETON #include "net_skeleton.h" #else // net_skeleton start // Copyright (c) 2014 Cesanta Software Limited // All rights reserved // // This software is dual-licensed: you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. For the terms of this // license, see . // // You are free to use this software under the terms of the GNU General // Public License, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // Alternatively, you can license this software under a commercial // license, as set out in . #ifndef NS_SKELETON_HEADER_INCLUDED #define NS_SKELETON_HEADER_INCLUDED #define NS_SKELETON_VERSION "1.1" #undef UNICODE // Use ANSI WinAPI functions #undef _UNICODE // Use multibyte encoding on Windows #define _MBCS // Use multibyte encoding on Windows #define _INTEGRAL_MAX_BITS 64 // Enable _stati64() on Windows #define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005+ #undef WIN32_LEAN_AND_MEAN // Let windows.h always include winsock2.h #define _XOPEN_SOURCE 600 // For flockfile() on Linux #define __STDC_FORMAT_MACROS // wants this for C++ #define __STDC_LIMIT_MACROS // C++ wants that for INT64_MAX #define _LARGEFILE_SOURCE // Enable fseeko() and ftello() functions #define _FILE_OFFSET_BITS 64 // Enable 64-bit file offsets #ifdef _MSC_VER #pragma warning (disable : 4127) // FD_SET() emits warning, disable it #pragma warning (disable : 4204) // missing c99 support #endif #include #include #include #include #include #include #include #include #include #include #include #include #ifdef _WIN32 #ifdef _MSC_VER #pragma comment(lib, "ws2_32.lib") // Linking with winsock library #endif #include #include #ifndef EINPROGRESS #define EINPROGRESS WSAEINPROGRESS #endif #ifndef EWOULDBLOCK #define EWOULDBLOCK WSAEWOULDBLOCK #endif #ifndef __func__ #define STRX(x) #x #define STR(x) STRX(x) #define __func__ __FILE__ ":" STR(__LINE__) #endif #ifndef va_copy #define va_copy(x,y) x = y #endif // MINGW #defines va_copy #define snprintf _snprintf #define vsnprintf _vsnprintf #define sleep(x) Sleep((x) * 1000) #define to64(x) _atoi64(x) typedef int socklen_t; typedef unsigned char uint8_t; typedef unsigned int uint32_t; typedef unsigned short uint16_t; typedef unsigned __int64 uint64_t; typedef __int64 int64_t; typedef SOCKET sock_t; #else #include #include #include #include #include #include #include // For inet_pton() when NS_ENABLE_IPV6 is defined #include #include #include #define closesocket(x) close(x) #define __cdecl #define INVALID_SOCKET (-1) #define to64(x) strtoll(x, NULL, 10) typedef int sock_t; #endif #ifdef NS_ENABLE_DEBUG #define DBG(x) do { printf("%-20s ", __func__); printf x; putchar('\n'); \ fflush(stdout); } while(0) #else #define DBG(x) #endif #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0])) #ifdef NS_ENABLE_SSL #ifdef __APPLE__ #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif #include #else typedef void *SSL; typedef void *SSL_CTX; #endif #ifdef __cplusplus extern "C" { #endif // __cplusplus union socket_address { struct sockaddr sa; struct sockaddr_in sin; #ifdef NS_ENABLE_IPV6 struct sockaddr_in6 sin6; #endif }; // IO buffers interface struct iobuf { char *buf; size_t len; size_t size; }; void iobuf_init(struct iobuf *, size_t initial_size); void iobuf_free(struct iobuf *); size_t iobuf_append(struct iobuf *, const void *data, size_t data_size); void iobuf_remove(struct iobuf *, size_t data_size); // Net skeleton interface // Events. Meaning of event parameter (evp) is given in the comment. enum ns_event { NS_POLL, // Sent to each connection on each call to ns_server_poll() NS_ACCEPT, // New connection accept()-ed. union socket_address *remote_addr NS_CONNECT, // connect() succeeded or failed. int *success_status NS_RECV, // Data has benn received. int *num_bytes NS_SEND, // Data has been written to a socket. int *num_bytes NS_CLOSE // Connection is closed. NULL }; // Callback function (event handler) prototype, must be defined by user. // Net skeleton will call event handler, passing events defined above. struct ns_connection; typedef void (*ns_callback_t)(struct ns_connection *, enum ns_event, void *evp); struct ns_server { void *server_data; sock_t listening_sock; struct ns_connection *active_connections; ns_callback_t callback; SSL_CTX *ssl_ctx; SSL_CTX *client_ssl_ctx; sock_t ctl[2]; }; struct ns_connection { struct ns_connection *prev, *next; struct ns_server *server; sock_t sock; union socket_address sa; struct iobuf recv_iobuf; struct iobuf send_iobuf; SSL *ssl; void *connection_data; time_t last_io_time; unsigned int flags; #define NSF_FINISHED_SENDING_DATA (1 << 0) #define NSF_BUFFER_BUT_DONT_SEND (1 << 1) #define NSF_SSL_HANDSHAKE_DONE (1 << 2) #define NSF_CONNECTING (1 << 3) #define NSF_CLOSE_IMMEDIATELY (1 << 4) #define NSF_ACCEPTED (1 << 5) #define NSF_WANT_READ (1 << 6) #define NSF_WANT_WRITE (1 << 7) #define NSF_USER_1 (1 << 26) #define NSF_USER_2 (1 << 27) #define NSF_USER_3 (1 << 28) #define NSF_USER_4 (1 << 29) #define NSF_USER_5 (1 << 30) #define NSF_USER_6 (1 << 31) }; void ns_server_init(struct ns_server *, void *server_data, ns_callback_t); void ns_server_free(struct ns_server *); int ns_server_poll(struct ns_server *, int milli); void ns_server_wakeup(struct ns_server *); void ns_server_wakeup_ex(struct ns_server *, ns_callback_t, void *, size_t); void ns_iterate(struct ns_server *, ns_callback_t cb, void *param); struct ns_connection *ns_add_sock(struct ns_server *, sock_t sock, void *p); int ns_bind(struct ns_server *, const char *addr); int ns_set_ssl_cert(struct ns_server *, const char *ssl_cert); int ns_set_ssl_ca_cert(struct ns_server *, const char *ssl_ca_cert); struct ns_connection *ns_connect(struct ns_server *, const char *host, int port, int ssl, void *connection_param); int ns_send(struct ns_connection *, const void *buf, int len); int ns_printf(struct ns_connection *, const char *fmt, ...); int ns_vprintf(struct ns_connection *, const char *fmt, va_list ap); // Utility functions void *ns_start_thread(void *(*f)(void *), void *p); int ns_socketpair(sock_t [2]); int ns_socketpair2(sock_t [2], int sock_type); // SOCK_STREAM or SOCK_DGRAM void ns_set_close_on_exec(sock_t); void ns_sock_to_str(sock_t sock, char *buf, size_t len, int flags); int ns_hexdump(const void *buf, int len, char *dst, int dst_len); #ifdef __cplusplus } #endif // __cplusplus #endif // NS_SKELETON_HEADER_INCLUDED // Copyright (c) 2014 Cesanta Software Limited // All rights reserved // // This software is dual-licensed: you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. For the terms of this // license, see . // // You are free to use this software under the terms of the GNU General // Public License, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // Alternatively, you can license this software under a commercial // license, as set out in . #ifndef NS_MALLOC #define NS_MALLOC malloc #endif #ifndef NS_REALLOC #define NS_REALLOC realloc #endif #ifndef NS_FREE #define NS_FREE free #endif struct ctl_msg { ns_callback_t callback; char message[1024 * 8]; }; void iobuf_init(struct iobuf *iobuf, size_t size) { iobuf->len = iobuf->size = 0; iobuf->buf = NULL; if (size > 0 && (iobuf->buf = (char *) NS_MALLOC(size)) != NULL) { iobuf->size = size; } } void iobuf_free(struct iobuf *iobuf) { if (iobuf != NULL) { if (iobuf->buf != NULL) NS_FREE(iobuf->buf); iobuf_init(iobuf, 0); } } size_t iobuf_append(struct iobuf *io, const void *buf, size_t len) { char *p = NULL; assert(io != NULL); assert(io->len <= io->size); if (len <= 0) { } else if (io->len + len <= io->size) { memcpy(io->buf + io->len, buf, len); io->len += len; } else if ((p = (char *) NS_REALLOC(io->buf, io->len + len)) != NULL) { io->buf = p; memcpy(io->buf + io->len, buf, len); io->len += len; io->size = io->len; } else { len = 0; } return len; } void iobuf_remove(struct iobuf *io, size_t n) { if (n > 0 && n <= io->len) { memmove(io->buf, io->buf + n, io->len - n); io->len -= n; } } #ifndef NS_DISABLE_THREADS void *ns_start_thread(void *(*f)(void *), void *p) { #ifdef _WIN32 return (void *) _beginthread((void (__cdecl *)(void *)) f, 0, p); #else pthread_t thread_id = (pthread_t) 0; pthread_attr_t attr; (void) pthread_attr_init(&attr); (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); #if NS_STACK_SIZE > 1 (void) pthread_attr_setstacksize(&attr, NS_STACK_SIZE); #endif pthread_create(&thread_id, &attr, f, p); pthread_attr_destroy(&attr); return (void *) thread_id; #endif } #endif // NS_DISABLE_THREADS static void ns_add_conn(struct ns_server *server, struct ns_connection *c) { c->next = server->active_connections; server->active_connections = c; c->prev = NULL; if (c->next != NULL) c->next->prev = c; } static void ns_remove_conn(struct ns_connection *conn) { if (conn->prev == NULL) conn->server->active_connections = conn->next; if (conn->prev) conn->prev->next = conn->next; if (conn->next) conn->next->prev = conn->prev; } // Print message to buffer. If buffer is large enough to hold the message, // return buffer. If buffer is to small, allocate large enough buffer on heap, // and return allocated buffer. static int ns_avprintf(char **buf, size_t size, const char *fmt, va_list ap) { va_list ap_copy; int len; va_copy(ap_copy, ap); len = vsnprintf(*buf, size, fmt, ap_copy); va_end(ap_copy); if (len < 0) { // eCos and Windows are not standard-compliant and return -1 when // the buffer is too small. Keep allocating larger buffers until we // succeed or out of memory. *buf = NULL; while (len < 0) { if (*buf) free(*buf); size *= 2; if ((*buf = (char *) NS_MALLOC(size)) == NULL) break; va_copy(ap_copy, ap); len = vsnprintf(*buf, size, fmt, ap_copy); va_end(ap_copy); } } else if (len > (int) size) { // Standard-compliant code path. Allocate a buffer that is large enough. if ((*buf = (char *) NS_MALLOC(len + 1)) == NULL) { len = -1; } else { va_copy(ap_copy, ap); len = vsnprintf(*buf, len + 1, fmt, ap_copy); va_end(ap_copy); } } return len; } int ns_vprintf(struct ns_connection *conn, const char *fmt, va_list ap) { char mem[2000], *buf = mem; int len; if ((len = ns_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) { iobuf_append(&conn->send_iobuf, buf, len); } if (buf != mem && buf != NULL) { free(buf); } return len; } int ns_printf(struct ns_connection *conn, const char *fmt, ...) { int len; va_list ap; va_start(ap, fmt); len = ns_vprintf(conn, fmt, ap); va_end(ap); return len; } static void ns_call(struct ns_connection *conn, enum ns_event ev, void *p) { if (conn->server->callback) conn->server->callback(conn, ev, p); } static void ns_close_conn(struct ns_connection *conn) { DBG(("%p %d", conn, conn->flags)); ns_call(conn, NS_CLOSE, NULL); ns_remove_conn(conn); closesocket(conn->sock); iobuf_free(&conn->recv_iobuf); iobuf_free(&conn->send_iobuf); #ifdef NS_ENABLE_SSL if (conn->ssl != NULL) { SSL_free(conn->ssl); } #endif NS_FREE(conn); } void ns_set_close_on_exec(sock_t sock) { #ifdef _WIN32 (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0); #else fcntl(sock, F_SETFD, FD_CLOEXEC); #endif } static void ns_set_non_blocking_mode(sock_t sock) { #ifdef _WIN32 unsigned long on = 1; ioctlsocket(sock, FIONBIO, &on); #else int flags = fcntl(sock, F_GETFL, 0); fcntl(sock, F_SETFL, flags | O_NONBLOCK); #endif } #ifndef NS_DISABLE_SOCKETPAIR int ns_socketpair2(sock_t sp[2], int sock_type) { union socket_address sa; sock_t sock; socklen_t len = sizeof(sa.sin); int ret = 0; sp[0] = sp[1] = INVALID_SOCKET; (void) memset(&sa, 0, sizeof(sa)); sa.sin.sin_family = AF_INET; sa.sin.sin_port = htons(0); sa.sin.sin_addr.s_addr = htonl(0x7f000001); if ((sock = socket(AF_INET, sock_type, 0)) != INVALID_SOCKET && !bind(sock, &sa.sa, len) && (sock_type == SOCK_DGRAM || !listen(sock, 1)) && !getsockname(sock, &sa.sa, &len) && (sp[0] = socket(AF_INET, sock_type, 0)) != INVALID_SOCKET && !connect(sp[0], &sa.sa, len) && (sock_type == SOCK_STREAM || (!getsockname(sp[0], &sa.sa, &len) && !connect(sock, &sa.sa, len))) && (sp[1] = (sock_type == SOCK_DGRAM ? sock : accept(sock, &sa.sa, &len))) != INVALID_SOCKET) { ns_set_close_on_exec(sp[0]); ns_set_close_on_exec(sp[1]); ret = 1; } else { if (sp[0] != INVALID_SOCKET) closesocket(sp[0]); if (sp[1] != INVALID_SOCKET) closesocket(sp[1]); sp[0] = sp[1] = INVALID_SOCKET; } if (sock_type != SOCK_DGRAM) closesocket(sock); return ret; } int ns_socketpair(sock_t sp[2]) { return ns_socketpair2(sp, SOCK_STREAM); } #endif // NS_DISABLE_SOCKETPAIR // Valid listening port spec is: [ip_address:]port, e.g. "80", "127.0.0.1:3128" static int ns_parse_port_string(const char *str, union socket_address *sa) { unsigned int a, b, c, d, port; int len = 0; #ifdef NS_ENABLE_IPV6 char buf[100]; #endif // MacOS needs that. If we do not zero it, subsequent bind() will fail. // Also, all-zeroes in the socket address means binding to all addresses // for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). memset(sa, 0, sizeof(*sa)); sa->sin.sin_family = AF_INET; if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) { // Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 sa->sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d); sa->sin.sin_port = htons((uint16_t) port); #ifdef NS_ENABLE_IPV6 } else if (sscanf(str, "[%49[^]]]:%u%n", buf, &port, &len) == 2 && inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) { // IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 sa->sin6.sin6_family = AF_INET6; sa->sin6.sin6_port = htons((uint16_t) port); #endif } else if (sscanf(str, "%u%n", &port, &len) == 1) { // If only port is specified, bind to IPv4, INADDR_ANY sa->sin.sin_port = htons((uint16_t) port); } else { port = 0; // Parsing failure. Make port invalid. } return port <= 0xffff && str[len] == '\0'; } // 'sa' must be an initialized address to bind to static sock_t ns_open_listening_socket(union socket_address *sa) { socklen_t len = sizeof(*sa); sock_t sock = INVALID_SOCKET; #ifndef _WIN32 int on = 1; #endif if ((sock = socket(sa->sa.sa_family, SOCK_STREAM, 6)) != INVALID_SOCKET && #ifndef _WIN32 !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) && #endif !bind(sock, &sa->sa, sa->sa.sa_family == AF_INET ? sizeof(sa->sin) : sizeof(sa->sa)) && !listen(sock, SOMAXCONN)) { ns_set_non_blocking_mode(sock); // In case port was set to 0, get the real port number (void) getsockname(sock, &sa->sa, &len); } else if (sock != INVALID_SOCKET) { closesocket(sock); sock = INVALID_SOCKET; } return sock; } // Certificate generation script is at // https://github.com/cesanta/net_skeleton/blob/master/examples/gen_certs.sh int ns_set_ssl_ca_cert(struct ns_server *server, const char *cert) { #ifdef NS_ENABLE_SSL STACK_OF(X509_NAME) *list = SSL_load_client_CA_file(cert); if (cert != NULL && server->ssl_ctx != NULL && list != NULL) { SSL_CTX_set_client_CA_list(server->ssl_ctx, list); SSL_CTX_set_verify(server->ssl_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL); return 0; } #endif return server != NULL && cert == NULL ? 0 : -1; } int ns_set_ssl_cert(struct ns_server *server, const char *cert) { #ifdef NS_ENABLE_SSL if (cert != NULL && (server->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) { return -1; } else if (SSL_CTX_use_certificate_file(server->ssl_ctx, cert, 1) == 0 || SSL_CTX_use_PrivateKey_file(server->ssl_ctx, cert, 1) == 0) { return -2; } else { SSL_CTX_use_certificate_chain_file(server->ssl_ctx, cert); return 0; } #endif return server != NULL && cert == NULL ? 0 : -3; } int ns_bind(struct ns_server *server, const char *str) { union socket_address sa; ns_parse_port_string(str, &sa); if (server->listening_sock != INVALID_SOCKET) { closesocket(server->listening_sock); } server->listening_sock = ns_open_listening_socket(&sa); return server->listening_sock == INVALID_SOCKET ? -1 : (int) ntohs(sa.sin.sin_port); } static struct ns_connection *accept_conn(struct ns_server *server) { struct ns_connection *c = NULL; union socket_address sa; socklen_t len = sizeof(sa); sock_t sock = INVALID_SOCKET; // NOTE(lsm): on Windows, sock is always > FD_SETSIZE if ((sock = accept(server->listening_sock, &sa.sa, &len)) == INVALID_SOCKET) { } else if ((c = (struct ns_connection *) NS_MALLOC(sizeof(*c))) == NULL || memset(c, 0, sizeof(*c)) == NULL) { closesocket(sock); #ifdef NS_ENABLE_SSL } else if (server->ssl_ctx != NULL && ((c->ssl = SSL_new(server->ssl_ctx)) == NULL || SSL_set_fd(c->ssl, sock) != 1)) { DBG(("SSL error")); closesocket(sock); free(c); c = NULL; #endif } else { ns_set_close_on_exec(sock); ns_set_non_blocking_mode(sock); c->server = server; c->sock = sock; c->flags |= NSF_ACCEPTED; ns_add_conn(server, c); ns_call(c, NS_ACCEPT, &sa); DBG(("%p %d %p %p", c, c->sock, c->ssl, server->ssl_ctx)); } return c; } static int ns_is_error(int n) { return n == 0 || (n < 0 && errno != EINTR && errno != EINPROGRESS && errno != EAGAIN && errno != EWOULDBLOCK #ifdef _WIN32 && WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK #endif ); } void ns_sock_to_str(sock_t sock, char *buf, size_t len, int flags) { union socket_address sa; socklen_t slen = sizeof(sa); if (buf != NULL && len > 0) { buf[0] = '\0'; memset(&sa, 0, sizeof(sa)); if (flags & 4) { getpeername(sock, &sa.sa, &slen); } else { getsockname(sock, &sa.sa, &slen); } if (flags & 1) { #if defined(NS_ENABLE_IPV6) inet_ntop(sa.sa.sa_family, sa.sa.sa_family == AF_INET ? (void *) &sa.sin.sin_addr : (void *) &sa.sin6.sin6_addr, buf, len); #elif defined(_WIN32) // Only Windoze Vista (and newer) have inet_ntop() strncpy(buf, inet_ntoa(sa.sin.sin_addr), len); #else inet_ntop(sa.sa.sa_family, (void *) &sa.sin.sin_addr, buf, len); #endif } if (flags & 2) { snprintf(buf + strlen(buf), len - (strlen(buf) + 1), ":%d", (int) ntohs(sa.sin.sin_port)); } } } int ns_hexdump(const void *buf, int len, char *dst, int dst_len) { const unsigned char *p = (const unsigned char *) buf; char ascii[17] = ""; int i, idx, n = 0; for (i = 0; i < len; i++) { idx = i % 16; if (idx == 0) { if (i > 0) n += snprintf(dst + n, dst_len - n, " %s\n", ascii); n += snprintf(dst + n, dst_len - n, "%04x ", i); } n += snprintf(dst + n, dst_len - n, " %02x", p[i]); ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i]; ascii[idx + 1] = '\0'; } while (i++ % 16) n += snprintf(dst + n, dst_len - n, "%s", " "); n += snprintf(dst + n, dst_len - n, " %s\n\n", ascii); return n; } static void ns_read_from_socket(struct ns_connection *conn) { char buf[2048]; int n = 0; if (conn->flags & NSF_CONNECTING) { int ok = 1, ret; socklen_t len = sizeof(ok); ret = getsockopt(conn->sock, SOL_SOCKET, SO_ERROR, (char *) &ok, &len); (void) ret; #ifdef NS_ENABLE_SSL if (ret == 0 && ok == 0 && conn->ssl != NULL) { int res = SSL_connect(conn->ssl); int ssl_err = SSL_get_error(conn->ssl, res); DBG(("%p %d wres %d %d", conn, conn->flags, res, ssl_err)); if (ssl_err == SSL_ERROR_WANT_READ) conn->flags |= NSF_WANT_READ; if (ssl_err == SSL_ERROR_WANT_WRITE) conn->flags |= NSF_WANT_WRITE; if (res == 1) { conn->flags |= NSF_SSL_HANDSHAKE_DONE; } else if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) { return; // Call us again } else { ok = 1; } } #endif conn->flags &= ~NSF_CONNECTING; DBG(("%p ok=%d", conn, ok)); if (ok != 0) { conn->flags |= NSF_CLOSE_IMMEDIATELY; } ns_call(conn, NS_CONNECT, &ok); return; } #ifdef NS_ENABLE_SSL if (conn->ssl != NULL) { if (conn->flags & NSF_SSL_HANDSHAKE_DONE) { n = SSL_read(conn->ssl, buf, sizeof(buf)); } else { int res = SSL_accept(conn->ssl); int ssl_err = SSL_get_error(conn->ssl, res); DBG(("%p %d rres %d %d", conn, conn->flags, res, ssl_err)); if (ssl_err == SSL_ERROR_WANT_READ) conn->flags |= NSF_WANT_READ; if (ssl_err == SSL_ERROR_WANT_WRITE) conn->flags |= NSF_WANT_WRITE; if (res == 1) { conn->flags |= NSF_SSL_HANDSHAKE_DONE; } else if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) { return; // Call us again } else { conn->flags |= NSF_CLOSE_IMMEDIATELY; } return; } } else #endif { n = recv(conn->sock, buf, sizeof(buf), 0); } DBG(("%p %d <- %d bytes", conn, conn->flags, n)); if (ns_is_error(n)) { conn->flags |= NSF_CLOSE_IMMEDIATELY; } else if (n > 0) { iobuf_append(&conn->recv_iobuf, buf, n); ns_call(conn, NS_RECV, &n); } } static void ns_write_to_socket(struct ns_connection *conn) { struct iobuf *io = &conn->send_iobuf; int n = 0; #ifdef NS_ENABLE_SSL if (conn->ssl != NULL) { n = SSL_write(conn->ssl, io->buf, io->len); if (n < 0) { int ssl_err = SSL_get_error(conn->ssl, n); DBG(("%p %d %d", conn, n, ssl_err)); if (ssl_err == 2 || ssl_err == 3) { return; // Call us again } else { conn->flags |= NSF_CLOSE_IMMEDIATELY; } } } else #endif { n = send(conn->sock, io->buf, io->len, 0); } DBG(("%p %d -> %d bytes", conn, conn->flags, n)); ns_call(conn, NS_SEND, &n); if (ns_is_error(n)) { conn->flags |= NSF_CLOSE_IMMEDIATELY; } else if (n > 0) { iobuf_remove(io, n); } if (io->len == 0 && conn->flags & NSF_FINISHED_SENDING_DATA) { conn->flags |= NSF_CLOSE_IMMEDIATELY; } } int ns_send(struct ns_connection *conn, const void *buf, int len) { return iobuf_append(&conn->send_iobuf, buf, len); } static void ns_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) { if (sock != INVALID_SOCKET) { FD_SET(sock, set); if (*max_fd == INVALID_SOCKET || sock > *max_fd) { *max_fd = sock; } } } int ns_server_poll(struct ns_server *server, int milli) { struct ns_connection *conn, *tmp_conn; struct timeval tv; fd_set read_set, write_set; int num_active_connections = 0; sock_t max_fd = INVALID_SOCKET; time_t current_time = time(NULL); if (server->listening_sock == INVALID_SOCKET && server->active_connections == NULL) return 0; FD_ZERO(&read_set); FD_ZERO(&write_set); ns_add_to_set(server->listening_sock, &read_set, &max_fd); ns_add_to_set(server->ctl[1], &read_set, &max_fd); for (conn = server->active_connections; conn != NULL; conn = tmp_conn) { tmp_conn = conn->next; ns_call(conn, NS_POLL, ¤t_time); if (!(conn->flags & NSF_WANT_WRITE)) { //DBG(("%p read_set", conn)); ns_add_to_set(conn->sock, &read_set, &max_fd); } if (((conn->flags & NSF_CONNECTING) && !(conn->flags & NSF_WANT_READ)) || (conn->send_iobuf.len > 0 && !(conn->flags & NSF_CONNECTING) && !(conn->flags & NSF_BUFFER_BUT_DONT_SEND))) { //DBG(("%p write_set", conn)); ns_add_to_set(conn->sock, &write_set, &max_fd); } if (conn->flags & NSF_CLOSE_IMMEDIATELY) { ns_close_conn(conn); } } tv.tv_sec = milli / 1000; tv.tv_usec = (milli % 1000) * 1000; if (select((int) max_fd + 1, &read_set, &write_set, NULL, &tv) > 0) { // Accept new connections if (server->listening_sock != INVALID_SOCKET && FD_ISSET(server->listening_sock, &read_set)) { // We're not looping here, and accepting just one connection at // a time. The reason is that eCos does not respect non-blocking // flag on a listening socket and hangs in a loop. if ((conn = accept_conn(server)) != NULL) { conn->last_io_time = current_time; } } // Read wakeup messages if (server->ctl[1] != INVALID_SOCKET && FD_ISSET(server->ctl[1], &read_set)) { struct ctl_msg ctl_msg; int len = recv(server->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0); send(server->ctl[1], ctl_msg.message, 1, 0); if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) { ns_iterate(server, ctl_msg.callback, ctl_msg.message); } } for (conn = server->active_connections; conn != NULL; conn = tmp_conn) { tmp_conn = conn->next; //DBG(("%p LOOP %p", conn, conn->ssl)); if (FD_ISSET(conn->sock, &read_set)) { conn->last_io_time = current_time; ns_read_from_socket(conn); } if (FD_ISSET(conn->sock, &write_set)) { if (conn->flags & NSF_CONNECTING) { ns_read_from_socket(conn); } else if (!(conn->flags & NSF_BUFFER_BUT_DONT_SEND)) { conn->last_io_time = current_time; ns_write_to_socket(conn); } } } } for (conn = server->active_connections; conn != NULL; conn = tmp_conn) { tmp_conn = conn->next; num_active_connections++; if (conn->flags & NSF_CLOSE_IMMEDIATELY) { ns_close_conn(conn); } } //DBG(("%d active connections", num_active_connections)); return num_active_connections; } struct ns_connection *ns_connect(struct ns_server *server, const char *host, int port, int use_ssl, void *param) { sock_t sock = INVALID_SOCKET; struct sockaddr_in sin; struct hostent *he = NULL; struct ns_connection *conn = NULL; int connect_ret_val; (void) use_ssl; if (host == NULL || (he = gethostbyname(host)) == NULL || (sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) { DBG(("gethostbyname(%s) failed: %s", host, strerror(errno))); return NULL; } sin.sin_family = AF_INET; sin.sin_port = htons((uint16_t) port); sin.sin_addr = * (struct in_addr *) he->h_addr_list[0]; ns_set_non_blocking_mode(sock); connect_ret_val = connect(sock, (struct sockaddr *) &sin, sizeof(sin)); if (ns_is_error(connect_ret_val)) { closesocket(sock); return NULL; } else if ((conn = (struct ns_connection *) NS_MALLOC(sizeof(*conn))) == NULL) { closesocket(sock); return NULL; } memset(conn, 0, sizeof(*conn)); conn->server = server; conn->sock = sock; conn->connection_data = param; conn->flags = NSF_CONNECTING; conn->last_io_time = time(NULL); #ifdef NS_ENABLE_SSL if (use_ssl && (conn->ssl = SSL_new(server->client_ssl_ctx)) != NULL) { SSL_set_fd(conn->ssl, sock); } #endif ns_add_conn(server, conn); DBG(("%p %s:%d %d %p", conn, host, port, conn->sock, conn->ssl)); return conn; } struct ns_connection *ns_add_sock(struct ns_server *s, sock_t sock, void *p) { struct ns_connection *conn; if ((conn = (struct ns_connection *) NS_MALLOC(sizeof(*conn))) != NULL) { memset(conn, 0, sizeof(*conn)); ns_set_non_blocking_mode(sock); conn->sock = sock; conn->connection_data = p; conn->server = s; conn->last_io_time = time(NULL); ns_add_conn(s, conn); DBG(("%p %d", conn, sock)); } return conn; } void ns_iterate(struct ns_server *server, ns_callback_t cb, void *param) { struct ns_connection *conn, *tmp_conn; for (conn = server->active_connections; conn != NULL; conn = tmp_conn) { tmp_conn = conn->next; cb(conn, NS_POLL, param); } } void ns_server_wakeup_ex(struct ns_server *server, ns_callback_t cb, void *data, size_t len) { struct ctl_msg ctl_msg; if (server->ctl[0] != INVALID_SOCKET && data != NULL && len < sizeof(ctl_msg.message)) { ctl_msg.callback = cb; memcpy(ctl_msg.message, data, len); send(server->ctl[0], (char *) &ctl_msg, offsetof(struct ctl_msg, message) + len, 0); recv(server->ctl[0], (char *) &len, 1, 0); } } void ns_server_wakeup(struct ns_server *server) { ns_server_wakeup_ex(server, NULL, (void *) "", 0); } void ns_server_init(struct ns_server *s, void *server_data, ns_callback_t cb) { memset(s, 0, sizeof(*s)); s->listening_sock = s->ctl[0] = s->ctl[1] = INVALID_SOCKET; s->server_data = server_data; s->callback = cb; #ifdef _WIN32 { WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); } #else // Ignore SIGPIPE signal, so if client cancels the request, it // won't kill the whole process. signal(SIGPIPE, SIG_IGN); #endif #ifndef NS_DISABLE_SOCKETPAIR do { ns_socketpair2(s->ctl, SOCK_DGRAM); } while (s->ctl[0] == INVALID_SOCKET); #endif #ifdef NS_ENABLE_SSL SSL_library_init(); s->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()); #endif } void ns_server_free(struct ns_server *s) { struct ns_connection *conn, *tmp_conn; DBG(("%p", s)); if (s == NULL) return; // Do one last poll, see https://github.com/cesanta/mongoose/issues/286 ns_server_poll(s, 0); if (s->listening_sock != INVALID_SOCKET) closesocket(s->listening_sock); if (s->ctl[0] != INVALID_SOCKET) closesocket(s->ctl[0]); if (s->ctl[1] != INVALID_SOCKET) closesocket(s->ctl[1]); s->listening_sock = s->ctl[0] = s->ctl[1] = INVALID_SOCKET; for (conn = s->active_connections; conn != NULL; conn = tmp_conn) { tmp_conn = conn->next; ns_close_conn(conn); } #ifdef NS_ENABLE_SSL if (s->ssl_ctx != NULL) SSL_CTX_free(s->ssl_ctx); if (s->client_ssl_ctx != NULL) SSL_CTX_free(s->client_ssl_ctx); s->ssl_ctx = s->client_ssl_ctx = NULL; #endif } // net_skeleton end #endif // NOEMBED_NET_SKELETON #include #ifdef _WIN32 //////////////// Windows specific defines and includes #include // For _lseeki64 #include // For _mkdir #ifndef S_ISDIR #define S_ISDIR(x) ((x) & _S_IFDIR) #endif #ifdef stat #undef stat #endif #ifdef lseek #undef lseek #endif #ifdef popen #undef popen #endif #ifdef pclose #undef pclose #endif #define stat(x, y) mg_stat((x), (y)) #define fopen(x, y) mg_fopen((x), (y)) #define open(x, y) mg_open((x), (y)) #define lseek(x, y, z) _lseeki64((x), (y), (z)) #define popen(x, y) _popen((x), (y)) #define pclose(x) _pclose(x) #define mkdir(x, y) _mkdir(x) #ifndef __func__ #define STRX(x) #x #define STR(x) STRX(x) #define __func__ __FILE__ ":" STR(__LINE__) #endif #define INT64_FMT "I64d" #define stat(x, y) mg_stat((x), (y)) #define fopen(x, y) mg_fopen((x), (y)) #define open(x, y) mg_open((x), (y)) #define flockfile(x) ((void) (x)) #define funlockfile(x) ((void) (x)) typedef struct _stati64 file_stat_t; typedef HANDLE process_id_t; #else ////////////// UNIX specific defines and includes #include #include #include #include #define O_BINARY 0 #define INT64_FMT PRId64 typedef struct stat file_stat_t; typedef pid_t process_id_t; #endif //////// End of platform-specific defines and includes #include "mongoose.h" #define MAX_REQUEST_SIZE 16384 #define IOBUF_SIZE 8192 #define MAX_PATH_SIZE 8192 #define DEFAULT_CGI_PATTERN "**.cgi$|**.pl$|**.php$" #define CGI_ENVIRONMENT_SIZE 8192 #define MAX_CGI_ENVIR_VARS 64 #define ENV_EXPORT_TO_CGI "MONGOOSE_CGI" #define PASSWORDS_FILE_NAME ".htpasswd" #ifndef MONGOOSE_USE_WEBSOCKET_PING_INTERVAL #define MONGOOSE_USE_WEBSOCKET_PING_INTERVAL 5 #endif // Extra HTTP headers to send in every static file reply #if !defined(MONGOOSE_USE_EXTRA_HTTP_HEADERS) #define MONGOOSE_USE_EXTRA_HTTP_HEADERS "" #endif #ifndef MONGOOSE_POST_SIZE_LIMIT #define MONGOOSE_POST_SIZE_LIMIT 0 #endif #ifndef MONGOOSE_IDLE_TIMEOUT_SECONDS #define MONGOOSE_IDLE_TIMEOUT_SECONDS 30 #endif #ifdef MONGOOSE_NO_SOCKETPAIR #define MONGOOSE_NO_CGI #endif #ifdef MONGOOSE_NO_FILESYSTEM #define MONGOOSE_NO_AUTH #define MONGOOSE_NO_CGI #define MONGOOSE_NO_DAV #define MONGOOSE_NO_DIRECTORY_LISTING #define MONGOOSE_NO_LOGGING #define MONGOOSE_NO_SSI #define MONGOOSE_NO_DL #endif struct vec { const char *ptr; int len; }; // For directory listing and WevDAV support struct dir_entry { struct connection *conn; char *file_name; file_stat_t st; }; // NOTE(lsm): this enum shoulds be in sync with the config_options. enum { ACCESS_CONTROL_LIST, #ifndef MONGOOSE_NO_FILESYSTEM ACCESS_LOG_FILE, #ifndef MONGOOSE_NO_AUTH AUTH_DOMAIN, #endif #ifndef MONGOOSE_NO_CGI CGI_INTERPRETER, CGI_PATTERN, #endif DAV_AUTH_FILE, DOCUMENT_ROOT, #ifndef MONGOOSE_NO_DIRECTORY_LISTING ENABLE_DIRECTORY_LISTING, #endif #endif EXTRA_MIME_TYPES, #if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_AUTH) GLOBAL_AUTH_FILE, #endif #ifndef MONGOOSE_NO_FILESYSTEM HIDE_FILES_PATTERN, HEXDUMP_FILE, INDEX_FILES, #endif LISTENING_PORT, #ifndef _WIN32 RUN_AS_USER, #endif #ifndef MONGOOSE_NO_SSI SSI_PATTERN, #endif #ifdef NS_ENABLE_SSL SSL_CERTIFICATE, SSL_CA_CERTIFICATE, SSL_MITM_CERTS, #endif URL_REWRITES, NUM_OPTIONS }; static const char *static_config_options[] = { "access_control_list", NULL, #ifndef MONGOOSE_NO_FILESYSTEM "access_log_file", NULL, #ifndef MONGOOSE_NO_AUTH "auth_domain", "mydomain.com", #endif #ifndef MONGOOSE_NO_CGI "cgi_interpreter", NULL, "cgi_pattern", DEFAULT_CGI_PATTERN, #endif "dav_auth_file", NULL, "document_root", NULL, #ifndef MONGOOSE_NO_DIRECTORY_LISTING "enable_directory_listing", "yes", #endif #endif "extra_mime_types", NULL, #if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_AUTH) "global_auth_file", NULL, #endif #ifndef MONGOOSE_NO_FILESYSTEM "hide_files_patterns", NULL, "hexdump_file", NULL, "index_files","index.html,index.htm,index.shtml,index.cgi,index.php,index.lp", #endif "listening_port", NULL, #ifndef _WIN32 "run_as_user", NULL, #endif #ifndef MONGOOSE_NO_SSI "ssi_pattern", "**.shtml$|**.shtm$", #endif #ifdef NS_ENABLE_SSL "ssl_certificate", NULL, "ssl_ca_certificate", NULL, "ssl_mitm_certs", NULL, #endif "url_rewrites", NULL, NULL }; struct mg_server { struct ns_server ns_server; union socket_address lsa; // Listening socket address mg_handler_t event_handler; char *config_options[NUM_OPTIONS]; }; // Local endpoint representation union endpoint { int fd; // Opened regular local file struct ns_connection *nc; // CGI or proxy->target connection }; enum endpoint_type { EP_NONE, EP_FILE, EP_CGI, EP_USER, EP_PUT, EP_CLIENT, EP_PROXY }; #define MG_HEADERS_SENT NSF_USER_1 #define MG_LONG_RUNNING NSF_USER_2 #define MG_CGI_CONN NSF_USER_3 #define MG_PROXY_CONN NSF_USER_4 struct connection { struct ns_connection *ns_conn; // NOTE(lsm): main.c depends on this order struct mg_connection mg_conn; struct mg_server *server; union endpoint endpoint; enum endpoint_type endpoint_type; char *path_info; char *request; int64_t num_bytes_sent; // Total number of bytes sent int64_t cl; // Reply content length, for Range support int request_len; // Request length, including last \r\n after last header }; #define MG_CONN_2_CONN(c) ((struct connection *) ((char *) (c) - \ offsetof(struct connection, mg_conn))) static void open_local_endpoint(struct connection *conn, int skip_user); static void close_local_endpoint(struct connection *conn); static const struct { const char *extension; size_t ext_len; const char *mime_type; } static_builtin_mime_types[] = { {".html", 5, "text/html"}, {".htm", 4, "text/html"}, {".shtm", 5, "text/html"}, {".shtml", 6, "text/html"}, {".css", 4, "text/css"}, {".js", 3, "application/x-javascript"}, {".ico", 4, "image/x-icon"}, {".gif", 4, "image/gif"}, {".jpg", 4, "image/jpeg"}, {".jpeg", 5, "image/jpeg"}, {".png", 4, "image/png"}, {".svg", 4, "image/svg+xml"}, {".txt", 4, "text/plain"}, {".torrent", 8, "application/x-bittorrent"}, {".wav", 4, "audio/x-wav"}, {".mp3", 4, "audio/x-mp3"}, {".mid", 4, "audio/mid"}, {".m3u", 4, "audio/x-mpegurl"}, {".ogg", 4, "application/ogg"}, {".ram", 4, "audio/x-pn-realaudio"}, {".xml", 4, "text/xml"}, {".json", 5, "text/json"}, {".xslt", 5, "application/xml"}, {".xsl", 4, "application/xml"}, {".ra", 3, "audio/x-pn-realaudio"}, {".doc", 4, "application/msword"}, {".exe", 4, "application/octet-stream"}, {".zip", 4, "application/x-zip-compressed"}, {".xls", 4, "application/excel"}, {".tgz", 4, "application/x-tar-gz"}, {".tar", 4, "application/x-tar"}, {".gz", 3, "application/x-gunzip"}, {".arj", 4, "application/x-arj-compressed"}, {".rar", 4, "application/x-rar-compressed"}, {".rtf", 4, "application/rtf"}, {".pdf", 4, "application/pdf"}, {".swf", 4, "application/x-shockwave-flash"}, {".mpg", 4, "video/mpeg"}, {".webm", 5, "video/webm"}, {".mpeg", 5, "video/mpeg"}, {".mov", 4, "video/quicktime"}, {".mp4", 4, "video/mp4"}, {".m4v", 4, "video/x-m4v"}, {".asf", 4, "video/x-ms-asf"}, {".avi", 4, "video/x-msvideo"}, {".bmp", 4, "image/bmp"}, {".ttf", 4, "application/x-font-ttf"}, {NULL, 0, NULL} }; #ifndef MONGOOSE_NO_THREADS void *mg_start_thread(void *(*f)(void *), void *p) { return ns_start_thread(f, p); } #endif // MONGOOSE_NO_THREADS #if defined(_WIN32) && !defined(MONGOOSE_NO_FILESYSTEM) // Encode 'path' which is assumed UTF-8 string, into UNICODE string. // wbuf and wbuf_len is a target buffer and its length. static void to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) { char buf[MAX_PATH_SIZE * 2], buf2[MAX_PATH_SIZE * 2], *p; strncpy(buf, path, sizeof(buf)); buf[sizeof(buf) - 1] = '\0'; // Trim trailing slashes. Leave backslash for paths like "X:\" p = buf + strlen(buf) - 1; while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0'; // Convert to Unicode and back. If doubly-converted string does not // match the original, something is fishy, reject. memset(wbuf, 0, wbuf_len * sizeof(wchar_t)); MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len); WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2), NULL, NULL); if (strcmp(buf, buf2) != 0) { wbuf[0] = L'\0'; } } static int mg_stat(const char *path, file_stat_t *st) { wchar_t wpath[MAX_PATH_SIZE]; to_wchar(path, wpath, ARRAY_SIZE(wpath)); DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st))); return _wstati64(wpath, st); } static FILE *mg_fopen(const char *path, const char *mode) { wchar_t wpath[MAX_PATH_SIZE], wmode[10]; to_wchar(path, wpath, ARRAY_SIZE(wpath)); to_wchar(mode, wmode, ARRAY_SIZE(wmode)); return _wfopen(wpath, wmode); } static int mg_open(const char *path, int flag) { wchar_t wpath[MAX_PATH_SIZE]; to_wchar(path, wpath, ARRAY_SIZE(wpath)); return _wopen(wpath, flag); } #endif // _WIN32 && !MONGOOSE_NO_FILESYSTEM // A helper function for traversing a comma separated list of values. // It returns a list pointer shifted to the next value, or NULL if the end // of the list found. // Value is stored in val vector. If value has form "x=y", then eq_val // vector is initialized to point to the "y" part, and val vector length // is adjusted to point only to "x". static const char *next_option(const char *list, struct vec *val, struct vec *eq_val) { if (list == NULL || *list == '\0') { // End of the list list = NULL; } else { val->ptr = list; if ((list = strchr(val->ptr, ',')) != NULL) { // Comma found. Store length and shift the list ptr val->len = list - val->ptr; list++; } else { // This value is the last one list = val->ptr + strlen(val->ptr); val->len = list - val->ptr; } if (eq_val != NULL) { // Value has form "x=y", adjust pointers and lengths // so that val points to "x", and eq_val points to "y". eq_val->len = 0; eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len); if (eq_val->ptr != NULL) { eq_val->ptr++; // Skip over '=' character eq_val->len = val->ptr + val->len - eq_val->ptr; val->len = (eq_val->ptr - val->ptr) - 1; } } } return list; } // Like snprintf(), but never returns negative value, or a value // that is larger than a supplied buffer. static int mg_vsnprintf(char *buf, size_t buflen, const char *fmt, va_list ap) { int n; if (buflen < 1) return 0; n = vsnprintf(buf, buflen, fmt, ap); if (n < 0) { n = 0; } else if (n >= (int) buflen) { n = (int) buflen - 1; } buf[n] = '\0'; return n; } static int mg_snprintf(char *buf, size_t buflen, const char *fmt, ...) { va_list ap; int n; va_start(ap, fmt); n = mg_vsnprintf(buf, buflen, fmt, ap); va_end(ap); return n; } // Check whether full request is buffered. Return: // -1 if request is malformed // 0 if request is not yet fully buffered // >0 actual request length, including last \r\n\r\n static int get_request_len(const char *s, int buf_len) { const unsigned char *buf = (unsigned char *) s; int i; for (i = 0; i < buf_len; i++) { // Control characters are not allowed but >=128 are. // Abort scan as soon as one malformed character is found. if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) { return -1; } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') { return i + 2; } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' && buf[i + 2] == '\n') { return i + 3; } } return 0; } // Skip the characters until one of the delimiters characters found. // 0-terminate resulting word. Skip the rest of the delimiters if any. // Advance pointer to buffer to the next word. Return found 0-terminated word. static char *skip(char **buf, const char *delimiters) { char *p, *begin_word, *end_word, *end_delimiters; begin_word = *buf; end_word = begin_word + strcspn(begin_word, delimiters); end_delimiters = end_word + strspn(end_word, delimiters); for (p = end_word; p < end_delimiters; p++) { *p = '\0'; } *buf = end_delimiters; return begin_word; } // Parse HTTP headers from the given buffer, advance buffer to the point // where parsing stopped. static void parse_http_headers(char **buf, struct mg_connection *ri) { size_t i; for (i = 0; i < ARRAY_SIZE(ri->http_headers); i++) { ri->http_headers[i].name = skip(buf, ": "); ri->http_headers[i].value = skip(buf, "\r\n"); if (ri->http_headers[i].name[0] == '\0') break; ri->num_headers = i + 1; } } static const char *status_code_to_str(int status_code) { switch (status_code) { case 200: return "OK"; case 201: return "Created"; case 204: return "No Content"; case 301: return "Moved Permanently"; case 302: return "Found"; case 304: return "Not Modified"; case 400: return "Bad Request"; case 403: return "Forbidden"; case 404: return "Not Found"; case 405: return "Method Not Allowed"; case 409: return "Conflict"; case 411: return "Length Required"; case 413: return "Request Entity Too Large"; case 415: return "Unsupported Media Type"; case 423: return "Locked"; case 500: return "Server Error"; case 501: return "Not Implemented"; default: return "Server Error"; } } static int call_user(struct connection *conn, enum mg_event ev) { return conn != NULL && conn->server != NULL && conn->server->event_handler != NULL ? conn->server->event_handler(&conn->mg_conn, ev) : MG_FALSE; } static void send_http_error(struct connection *conn, int code, const char *fmt, ...) { const char *message = status_code_to_str(code); const char *rewrites = conn->server->config_options[URL_REWRITES]; char headers[200], body[200]; struct vec a, b; va_list ap; int body_len, headers_len, match_code; conn->mg_conn.status_code = code; // Invoke error handler if it is set if (call_user(conn, MG_HTTP_ERROR) == MG_TRUE) { close_local_endpoint(conn); return; } // Handle error code rewrites while ((rewrites = next_option(rewrites, &a, &b)) != NULL) { if ((match_code = atoi(a.ptr)) > 0 && match_code == code) { struct mg_connection *c = &conn->mg_conn; c->status_code = 302; mg_printf(c, "HTTP/1.1 %d Moved\r\n" "Location: %.*s?code=%d&orig_uri=%s&query_string=%s\r\n\r\n", c->status_code, b.len, b.ptr, code, c->uri, c->query_string == NULL ? "" : c->query_string); close_local_endpoint(conn); return; } } body_len = mg_snprintf(body, sizeof(body), "%d %s\n", code, message); if (fmt != NULL) { va_start(ap, fmt); body_len += mg_vsnprintf(body + body_len, sizeof(body) - body_len, fmt, ap); va_end(ap); } if ((code >= 300 && code <= 399) || code == 204) { // 3xx errors do not have body body_len = 0; } headers_len = mg_snprintf(headers, sizeof(headers), "HTTP/1.1 %d %s\r\nContent-Length: %d\r\n" "Content-Type: text/plain\r\n\r\n", code, message, body_len); ns_send(conn->ns_conn, headers, headers_len); ns_send(conn->ns_conn, body, body_len); close_local_endpoint(conn); // This will write to the log file } static void write_chunk(struct connection *conn, const char *buf, int len) { char chunk_size[50]; int n = mg_snprintf(chunk_size, sizeof(chunk_size), "%X\r\n", len); ns_send(conn->ns_conn, chunk_size, n); ns_send(conn->ns_conn, buf, len); ns_send(conn->ns_conn, "\r\n", 2); } int mg_printf(struct mg_connection *conn, const char *fmt, ...) { struct connection *c = MG_CONN_2_CONN(conn); int len; va_list ap; va_start(ap, fmt); len = ns_vprintf(c->ns_conn, fmt, ap); va_end(ap); return len; } static void ns_forward(struct ns_connection *from, struct ns_connection *to) { DBG(("%p -> %p %zu bytes", from, to, from->recv_iobuf.len)); ns_send(to, from->recv_iobuf.buf, from->recv_iobuf.len); iobuf_remove(&from->recv_iobuf, from->recv_iobuf.len); } #ifndef MONGOOSE_NO_CGI #ifdef _WIN32 struct threadparam { sock_t s; HANDLE hPipe; }; static int wait_until_ready(sock_t sock, int for_read) { fd_set set; FD_ZERO(&set); FD_SET(sock, &set); select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0); return 1; } static void *push_to_stdin(void *arg) { struct threadparam *tp = (struct threadparam *)arg; int n, sent, stop = 0; DWORD k; char buf[IOBUF_SIZE]; while (!stop && wait_until_ready(tp->s, 1) && (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) { if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue; for (sent = 0; !stop && sent < n; sent += k) { if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1; } } DBG(("%s", "FORWARED EVERYTHING TO CGI")); CloseHandle(tp->hPipe); free(tp); _endthread(); return NULL; } static void *pull_from_stdout(void *arg) { struct threadparam *tp = (struct threadparam *)arg; int k, stop = 0; DWORD n, sent; char buf[IOBUF_SIZE]; while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) { for (sent = 0; !stop && sent < n; sent += k) { if (wait_until_ready(tp->s, 0) && (k = send(tp->s, buf + sent, n - sent, 0)) <= 0) stop = 1; } } DBG(("%s", "EOF FROM CGI")); CloseHandle(tp->hPipe); shutdown(tp->s, 2); // Without this, IO thread may get truncated data closesocket(tp->s); free(tp); _endthread(); return NULL; } static void spawn_stdio_thread(sock_t sock, HANDLE hPipe, void *(*func)(void *)) { struct threadparam *tp = (struct threadparam *)malloc(sizeof(*tp)); if (tp != NULL) { tp->s = sock; tp->hPipe = hPipe; mg_start_thread(func, tp); } } static void abs_path(const char *utf8_path, char *abs_path, size_t len) { wchar_t buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE]; to_wchar(utf8_path, buf, ARRAY_SIZE(buf)); GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL); WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0); } static process_id_t start_process(char *interp, const char *cmd, const char *env, const char *envp[], const char *dir, sock_t sock) { STARTUPINFOW si = {0}; PROCESS_INFORMATION pi = {0}; HANDLE a[2], b[2], me = GetCurrentProcess(); wchar_t wcmd[MAX_PATH_SIZE], full_dir[MAX_PATH_SIZE]; char buf[MAX_PATH_SIZE], buf4[MAX_PATH_SIZE], buf5[MAX_PATH_SIZE], cmdline[MAX_PATH_SIZE], *p; DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS; FILE *fp; si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; si.hStdError = GetStdHandle(STD_ERROR_HANDLE); CreatePipe(&a[0], &a[1], NULL, 0); CreatePipe(&b[0], &b[1], NULL, 0); DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags); DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags); if (interp == NULL && (fp = fopen(cmd, "r")) != NULL) { buf[0] = buf[1] = '\0'; fgets(buf, sizeof(buf), fp); buf[sizeof(buf) - 1] = '\0'; if (buf[0] == '#' && buf[1] == '!') { interp = buf + 2; for (p = interp + strlen(interp); isspace(* (uint8_t *) p) && p > interp; p--) *p = '\0'; } fclose(fp); } if (interp != NULL) { abs_path(interp, buf4, ARRAY_SIZE(buf4)); interp = buf4; } abs_path(dir, buf5, ARRAY_SIZE(buf5)); to_wchar(dir, full_dir, ARRAY_SIZE(full_dir)); mg_snprintf(cmdline, sizeof(cmdline), "%s%s\"%s\"", interp ? interp : "", interp ? " " : "", cmd); to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd)); if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP, (void *) env, full_dir, &si, &pi) != 0) { spawn_stdio_thread(sock, a[1], push_to_stdin); spawn_stdio_thread(sock, b[0], pull_from_stdout); } else { CloseHandle(a[1]); CloseHandle(b[0]); closesocket(sock); } DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess)); CloseHandle(si.hStdOutput); CloseHandle(si.hStdInput); CloseHandle(a[0]); CloseHandle(b[1]); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); return pi.hProcess; } #else static process_id_t start_process(const char *interp, const char *cmd, const char *env, const char *envp[], const char *dir, sock_t sock) { char buf[500]; process_id_t pid = fork(); (void) env; if (pid == 0) { (void) chdir(dir); (void) dup2(sock, 0); (void) dup2(sock, 1); closesocket(sock); // After exec, all signal handlers are restored to their default values, // with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's // implementation, SIGCHLD's handler will leave unchanged after exec // if it was set to be ignored. Restore it to default action. signal(SIGCHLD, SIG_DFL); if (interp == NULL) { execle(cmd, cmd, NULL, envp); } else { execle(interp, interp, cmd, NULL, envp); } snprintf(buf, sizeof(buf), "Status: 500\r\n\r\n" "500 Server Error: %s%s%s: %s", interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd, strerror(errno)); send(1, buf, strlen(buf), 0); exit(EXIT_FAILURE); // exec call failed } return pid; } #endif // _WIN32 // This structure helps to create an environment for the spawned CGI program. // Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings, // last element must be NULL. // However, on Windows there is a requirement that all these VARIABLE=VALUE\0 // strings must reside in a contiguous buffer. The end of the buffer is // marked by two '\0' characters. // We satisfy both worlds: we create an envp array (which is vars), all // entries are actually pointers inside buf. struct cgi_env_block { struct mg_connection *conn; char buf[CGI_ENVIRONMENT_SIZE]; // Environment buffer const char *vars[MAX_CGI_ENVIR_VARS]; // char *envp[] int len; // Space taken int nvars; // Number of variables in envp[] }; // Append VARIABLE=VALUE\0 string to the buffer, and add a respective // pointer into the vars array. static char *addenv(struct cgi_env_block *block, const char *fmt, ...) { int n, space; char *added; va_list ap; // Calculate how much space is left in the buffer space = sizeof(block->buf) - block->len - 2; assert(space >= 0); // Make a pointer to the free space int the buffer added = block->buf + block->len; // Copy VARIABLE=VALUE\0 string into the free space va_start(ap, fmt); n = mg_vsnprintf(added, (size_t) space, fmt, ap); va_end(ap); // Make sure we do not overflow buffer and the envp array if (n > 0 && n + 1 < space && block->nvars < (int) ARRAY_SIZE(block->vars) - 2) { // Append a pointer to the added string into the envp array block->vars[block->nvars++] = added; // Bump up used length counter. Include \0 terminator block->len += n + 1; } return added; } static void addenv2(struct cgi_env_block *blk, const char *name) { const char *s; if ((s = getenv(name)) != NULL) addenv(blk, "%s=%s", name, s); } static void prepare_cgi_environment(struct connection *conn, const char *prog, struct cgi_env_block *blk) { struct mg_connection *ri = &conn->mg_conn; const char *s, *slash; char *p, **opts = conn->server->config_options; int i; blk->len = blk->nvars = 0; blk->conn = ri; if ((s = getenv("SERVER_NAME")) != NULL) { addenv(blk, "SERVER_NAME=%s", s); } else { addenv(blk, "SERVER_NAME=%s", ri->local_ip); } addenv(blk, "SERVER_ROOT=%s", opts[DOCUMENT_ROOT]); addenv(blk, "DOCUMENT_ROOT=%s", opts[DOCUMENT_ROOT]); addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MONGOOSE_VERSION); // Prepare the environment block addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1"); addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1"); addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP // TODO(lsm): fix this for IPv6 case //addenv(blk, "SERVER_PORT=%d", ri->remote_port); addenv(blk, "REQUEST_METHOD=%s", ri->request_method); addenv(blk, "REMOTE_ADDR=%s", ri->remote_ip); addenv(blk, "REMOTE_PORT=%d", ri->remote_port); addenv(blk, "REQUEST_URI=%s%s%s", ri->uri, ri->query_string == NULL ? "" : "?", ri->query_string == NULL ? "" : ri->query_string); // SCRIPT_NAME if (conn->path_info != NULL) { addenv(blk, "SCRIPT_NAME=%.*s", (int) (strlen(ri->uri) - strlen(conn->path_info)), ri->uri); addenv(blk, "PATH_INFO=%s", conn->path_info); } else { s = strrchr(prog, '/'); slash = strrchr(ri->uri, '/'); addenv(blk, "SCRIPT_NAME=%.*s%s", slash == NULL ? 0 : (int) (slash - ri->uri), ri->uri, s == NULL ? prog : s); } addenv(blk, "SCRIPT_FILENAME=%s", prog); addenv(blk, "PATH_TRANSLATED=%s", prog); addenv(blk, "HTTPS=%s", conn->ns_conn->ssl != NULL ? "on" : "off"); if ((s = mg_get_header(ri, "Content-Type")) != NULL) addenv(blk, "CONTENT_TYPE=%s", s); if (ri->query_string != NULL) addenv(blk, "QUERY_STRING=%s", ri->query_string); if ((s = mg_get_header(ri, "Content-Length")) != NULL) addenv(blk, "CONTENT_LENGTH=%s", s); addenv2(blk, "PATH"); addenv2(blk, "TMP"); addenv2(blk, "TEMP"); addenv2(blk, "TMPDIR"); addenv2(blk, "PERLLIB"); addenv2(blk, ENV_EXPORT_TO_CGI); #if defined(_WIN32) addenv2(blk, "COMSPEC"); addenv2(blk, "SYSTEMROOT"); addenv2(blk, "SystemDrive"); addenv2(blk, "ProgramFiles"); addenv2(blk, "ProgramFiles(x86)"); addenv2(blk, "CommonProgramFiles(x86)"); #else addenv2(blk, "LD_LIBRARY_PATH"); #endif // _WIN32 // Add all headers as HTTP_* variables for (i = 0; i < ri->num_headers; i++) { p = addenv(blk, "HTTP_%s=%s", ri->http_headers[i].name, ri->http_headers[i].value); // Convert variable name into uppercase, and change - to _ for (; *p != '=' && *p != '\0'; p++) { if (*p == '-') *p = '_'; *p = (char) toupper(* (unsigned char *) p); } } blk->vars[blk->nvars++] = NULL; blk->buf[blk->len++] = '\0'; assert(blk->nvars < (int) ARRAY_SIZE(blk->vars)); assert(blk->len > 0); assert(blk->len < (int) sizeof(blk->buf)); } static const char cgi_status[] = "HTTP/1.1 200 OK\r\n"; static void open_cgi_endpoint(struct connection *conn, const char *prog) { struct cgi_env_block blk; char dir[MAX_PATH_SIZE]; const char *p; sock_t fds[2]; prepare_cgi_environment(conn, prog, &blk); // CGI must be executed in its own directory. 'dir' must point to the // directory containing executable program, 'p' must point to the // executable program name relative to 'dir'. if ((p = strrchr(prog, '/')) == NULL) { mg_snprintf(dir, sizeof(dir), "%s", "."); } else { mg_snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog); } // Try to create socketpair in a loop until success. ns_socketpair() // can be interrupted by a signal and fail. // TODO(lsm): use sigaction to restart interrupted syscall do { ns_socketpair(fds); } while (fds[0] == INVALID_SOCKET); if (start_process(conn->server->config_options[CGI_INTERPRETER], prog, blk.buf, blk.vars, dir, fds[1]) > 0) { conn->endpoint_type = EP_CGI; conn->endpoint.nc = ns_add_sock(&conn->server->ns_server, fds[0], conn); conn->endpoint.nc->flags |= MG_CGI_CONN; ns_send(conn->ns_conn, cgi_status, sizeof(cgi_status) - 1); conn->mg_conn.status_code = 200; conn->ns_conn->flags |= NSF_BUFFER_BUT_DONT_SEND; // Pass POST data to the CGI process conn->endpoint.nc->send_iobuf = conn->ns_conn->recv_iobuf; iobuf_init(&conn->ns_conn->recv_iobuf, 0); } else { closesocket(fds[0]); send_http_error(conn, 500, "start_process(%s) failed", prog); } #ifndef _WIN32 closesocket(fds[1]); // On Windows, CGI stdio thread closes that socket #endif } static void on_cgi_data(struct ns_connection *nc) { struct connection *conn = (struct connection *) nc->connection_data; const char *status = "500"; struct mg_connection c; if (!conn) return; // Copy CGI data from CGI socket to the client send buffer ns_forward(nc, conn->ns_conn); // If reply has not been parsed yet, parse it if (conn->ns_conn->flags & NSF_BUFFER_BUT_DONT_SEND) { struct iobuf *io = &conn->ns_conn->send_iobuf; int s_len = sizeof(cgi_status) - 1; int len = get_request_len(io->buf + s_len, io->len - s_len); char buf[MAX_REQUEST_SIZE], *s = buf; if (len == 0) return; if (len < 0 || len > (int) sizeof(buf)) { len = io->len; iobuf_remove(io, io->len); send_http_error(conn, 500, "CGI program sent malformed headers: [%.*s]", len, io->buf); } else { memset(&c, 0, sizeof(c)); memcpy(buf, io->buf + s_len, len); buf[len - 1] = '\0'; parse_http_headers(&s, &c); if (mg_get_header(&c, "Location") != NULL) { status = "302"; } else if ((status = (char *) mg_get_header(&c, "Status")) == NULL) { status = "200"; } memcpy(io->buf + 9, status, 3); conn->mg_conn.status_code = atoi(status); } conn->ns_conn->flags &= ~NSF_BUFFER_BUT_DONT_SEND; } } #endif // !MONGOOSE_NO_CGI static char *mg_strdup(const char *str) { char *copy = (char *) malloc(strlen(str) + 1); if (copy != NULL) { strcpy(copy, str); } return copy; } static int isbyte(int n) { return n >= 0 && n <= 255; } static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) { int n, a, b, c, d, slash = 32, len = 0; if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 && slash < 33) { len = n; *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d; *mask = slash ? 0xffffffffU << (32 - slash) : 0; } return len; } // Verify given socket address against the ACL. // Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed. static int check_acl(const char *acl, uint32_t remote_ip) { int allowed, flag; uint32_t net, mask; struct vec vec; // If any ACL is set, deny by default allowed = acl == NULL ? '+' : '-'; while ((acl = next_option(acl, &vec, NULL)) != NULL) { flag = vec.ptr[0]; if ((flag != '+' && flag != '-') || parse_net(&vec.ptr[1], &net, &mask) == 0) { return -1; } if (net == (remote_ip & mask)) { allowed = flag; } } return allowed == '+'; } // Protect against directory disclosure attack by removing '..', // excessive '/' and '\' characters static void remove_double_dots_and_double_slashes(char *s) { char *p = s; while (*s != '\0') { *p++ = *s++; if (s[-1] == '/' || s[-1] == '\\') { // Skip all following slashes, backslashes and double-dots while (s[0] != '\0') { if (s[0] == '/' || s[0] == '\\') { s++; } else if (s[0] == '.' && s[1] == '.') { s += 2; } else { break; } } } } *p = '\0'; } int mg_url_decode(const char *src, int src_len, char *dst, int dst_len, int is_form_url_encoded) { int i, j, a, b; #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W') for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) { if (src[i] == '%' && i < src_len - 2 && isxdigit(* (const unsigned char *) (src + i + 1)) && isxdigit(* (const unsigned char *) (src + i + 2))) { a = tolower(* (const unsigned char *) (src + i + 1)); b = tolower(* (const unsigned char *) (src + i + 2)); dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b)); i += 2; } else if (is_form_url_encoded && src[i] == '+') { dst[j] = ' '; } else { dst[j] = src[i]; } } dst[j] = '\0'; // Null-terminate the destination return i >= src_len ? j : -1; } static int is_valid_http_method(const char *s) { return !strcmp(s, "GET") || !strcmp(s, "POST") || !strcmp(s, "HEAD") || !strcmp(s, "CONNECT") || !strcmp(s, "PUT") || !strcmp(s, "DELETE") || !strcmp(s, "OPTIONS") || !strcmp(s, "PROPFIND") || !strcmp(s, "MKCOL"); } // Parse HTTP request, fill in mg_request structure. // This function modifies the buffer by NUL-terminating // HTTP request components, header names and header values. // Note that len must point to the last \n of HTTP headers. static int parse_http_message(char *buf, int len, struct mg_connection *ri) { int is_request, n; // Reset the connection. Make sure that we don't touch fields that are // set elsewhere: remote_ip, remote_port, server_param ri->request_method = ri->uri = ri->http_version = ri->query_string = NULL; ri->num_headers = ri->status_code = ri->is_websocket = ri->content_len = 0; buf[len - 1] = '\0'; // RFC says that all initial whitespaces should be ingored while (*buf != '\0' && isspace(* (unsigned char *) buf)) { buf++; } ri->request_method = skip(&buf, " "); ri->uri = skip(&buf, " "); ri->http_version = skip(&buf, "\r\n"); // HTTP message could be either HTTP request or HTTP response, e.g. // "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." is_request = is_valid_http_method(ri->request_method); if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) { len = -1; } else { if (is_request) { ri->http_version += 5; } parse_http_headers(&buf, ri); if ((ri->query_string = strchr(ri->uri, '?')) != NULL) { *(char *) ri->query_string++ = '\0'; } n = (int) strlen(ri->uri); mg_url_decode(ri->uri, n, (char *) ri->uri, n + 1, 0); if (*ri->uri == '/' || *ri->uri == '.') { remove_double_dots_and_double_slashes((char *) ri->uri); } } return len; } static int lowercase(const char *s) { return tolower(* (const unsigned char *) s); } static int mg_strcasecmp(const char *s1, const char *s2) { int diff; do { diff = lowercase(s1++) - lowercase(s2++); } while (diff == 0 && s1[-1] != '\0'); return diff; } static int mg_strncasecmp(const char *s1, const char *s2, size_t len) { int diff = 0; if (len > 0) do { diff = lowercase(s1++) - lowercase(s2++); } while (diff == 0 && s1[-1] != '\0' && --len > 0); return diff; } // Return HTTP header value, or NULL if not found. const char *mg_get_header(const struct mg_connection *ri, const char *s) { int i; for (i = 0; i < ri->num_headers; i++) if (!mg_strcasecmp(s, ri->http_headers[i].name)) return ri->http_headers[i].value; return NULL; } // Perform case-insensitive match of string against pattern int mg_match_prefix(const char *pattern, int pattern_len, const char *str) { const char *or_str; int len, res, i = 0, j = 0; if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) { res = mg_match_prefix(pattern, or_str - pattern, str); return res > 0 ? res : mg_match_prefix(or_str + 1, (pattern + pattern_len) - (or_str + 1), str); } for (; i < pattern_len; i++, j++) { if (pattern[i] == '?' && str[j] != '\0') { continue; } else if (pattern[i] == '$') { return str[j] == '\0' ? j : -1; } else if (pattern[i] == '*') { i++; if (pattern[i] == '*') { i++; len = (int) strlen(str + j); } else { len = (int) strcspn(str + j, "/"); } if (i == pattern_len) { return j + len; } do { res = mg_match_prefix(pattern + i, pattern_len - i, str + j + len); } while (res == -1 && len-- > 0); return res == -1 ? -1 : j + res + len; } else if (lowercase(&pattern[i]) != lowercase(&str[j])) { return -1; } } return j; } // This function prints HTML pages, and expands "{{something}}" blocks // inside HTML by calling appropriate callback functions. // Note that {{@path/to/file}} construct outputs embedded file's contents, // which provides SSI-like functionality. void mg_template(struct mg_connection *conn, const char *s, struct mg_expansion *expansions) { int i, j, pos = 0, inside_marker = 0; for (i = 0; s[i] != '\0'; i++) { if (inside_marker == 0 && !memcmp(&s[i], "{{", 2)) { if (i > pos) { mg_send_data(conn, &s[pos], i - pos); } pos = i; inside_marker = 1; } if (inside_marker == 1 && !memcmp(&s[i], "}}", 2)) { for (j = 0; expansions[j].keyword != NULL; j++) { const char *kw = expansions[j].keyword; if ((int) strlen(kw) == i - (pos + 2) && memcmp(kw, &s[pos + 2], i - (pos + 2)) == 0) { expansions[j].handler(conn); pos = i + 2; break; } } inside_marker = 0; } } if (i > pos) { mg_send_data(conn, &s[pos], i - pos); } } #ifndef MONGOOSE_NO_FILESYSTEM static int must_hide_file(struct connection *conn, const char *path) { const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$"; const char *pattern = conn->server->config_options[HIDE_FILES_PATTERN]; return mg_match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 || (pattern != NULL && mg_match_prefix(pattern, strlen(pattern), path) > 0); } // Return 1 if real file has been found, 0 otherwise static int convert_uri_to_file_name(struct connection *conn, char *buf, size_t buf_len, file_stat_t *st) { struct vec a, b; const char *rewrites = conn->server->config_options[URL_REWRITES]; const char *root = conn->server->config_options[DOCUMENT_ROOT]; #ifndef MONGOOSE_NO_CGI const char *cgi_pat = conn->server->config_options[CGI_PATTERN]; char *p; #endif const char *uri = conn->mg_conn.uri; const char *domain = mg_get_header(&conn->mg_conn, "Host"); int match_len, root_len = root == NULL ? 0 : strlen(root); // Perform virtual hosting rewrites if (rewrites != NULL && domain != NULL) { const char *colon = strchr(domain, ':'); int domain_len = colon == NULL ? (int) strlen(domain) : colon - domain; while ((rewrites = next_option(rewrites, &a, &b)) != NULL) { if (a.len > 1 && a.ptr[0] == '@' && a.len == domain_len + 1 && mg_strncasecmp(a.ptr + 1, domain, domain_len) == 0) { root = b.ptr; root_len = b.len; break; } } } // No filesystem access if (root == NULL || root_len == 0) return 0; // Handle URL rewrites mg_snprintf(buf, buf_len, "%.*s%s", root_len, root, uri); rewrites = conn->server->config_options[URL_REWRITES]; // Re-initialize! while ((rewrites = next_option(rewrites, &a, &b)) != NULL) { if ((match_len = mg_match_prefix(a.ptr, a.len, uri)) > 0) { mg_snprintf(buf, buf_len, "%.*s%s", (int) b.len, b.ptr, uri + match_len); break; } } if (stat(buf, st) == 0) return 1; #ifndef MONGOOSE_NO_CGI // Support PATH_INFO for CGI scripts. for (p = buf + strlen(root) + 2; *p != '\0'; p++) { if (*p == '/') { *p = '\0'; if (mg_match_prefix(cgi_pat, strlen(cgi_pat), buf) > 0 && !stat(buf, st)) { DBG(("!!!! [%s]", buf)); *p = '/'; conn->path_info = mg_strdup(p); *p = '\0'; return 1; } *p = '/'; } } #endif return 0; } #endif // MONGOOSE_NO_FILESYSTEM static int should_keep_alive(const struct mg_connection *conn) { struct connection *c = MG_CONN_2_CONN(conn); const char *method = conn->request_method; const char *http_version = conn->http_version; const char *header = mg_get_header(conn, "Connection"); return method != NULL && (!strcmp(method, "GET") || c->endpoint_type == EP_USER) && ((header != NULL && !mg_strcasecmp(header, "keep-alive")) || (header == NULL && http_version && !strcmp(http_version, "1.1"))); } int mg_write(struct mg_connection *c, const void *buf, int len) { struct connection *conn = MG_CONN_2_CONN(c); return ns_send(conn->ns_conn, buf, len); } void mg_send_status(struct mg_connection *c, int status) { if (c->status_code == 0) { c->status_code = status; mg_printf(c, "HTTP/1.1 %d %s\r\n", status, status_code_to_str(status)); } } void mg_send_header(struct mg_connection *c, const char *name, const char *v) { if (c->status_code == 0) { c->status_code = 200; mg_printf(c, "HTTP/1.1 %d %s\r\n", 200, status_code_to_str(200)); } mg_printf(c, "%s: %s\r\n", name, v); } static void terminate_headers(struct mg_connection *c) { struct connection *conn = MG_CONN_2_CONN(c); if (!(conn->ns_conn->flags & MG_HEADERS_SENT)) { mg_send_header(c, "Transfer-Encoding", "chunked"); mg_write(c, "\r\n", 2); conn->ns_conn->flags |= MG_HEADERS_SENT; } } void mg_send_data(struct mg_connection *c, const void *data, int data_len) { terminate_headers(c); write_chunk(MG_CONN_2_CONN(c), (const char *) data, data_len); } void mg_printf_data(struct mg_connection *c, const char *fmt, ...) { struct connection *conn = MG_CONN_2_CONN(c); va_list ap; int len; char mem[IOBUF_SIZE], *buf = mem; terminate_headers(c); va_start(ap, fmt); len = ns_avprintf(&buf, sizeof(mem), fmt, ap); va_end(ap); if (len >= 0) { write_chunk((struct connection *) conn, buf, len); } if (buf != mem && buf != NULL) { free(buf); } } #if !defined(MONGOOSE_NO_WEBSOCKET) || !defined(MONGOOSE_NO_AUTH) static int is_big_endian(void) { static const int n = 1; return ((char *) &n)[0] == 0; } #endif #ifndef MONGOOSE_NO_WEBSOCKET // START OF SHA-1 code // Copyright(c) By Steve Reid #define SHA1HANDSOFF #if defined(__sun) #include "solarisfixes.h" #endif union char64long16 { unsigned char c[64]; uint32_t l[16]; }; #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) static uint32_t blk0(union char64long16 *block, int i) { // Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN if (!is_big_endian()) { block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF); } return block->l[i]; } #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \ ^block->l[(i+2)&15]^block->l[i&15],1)) #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30); #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30); #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30); #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); typedef struct { uint32_t state[5]; uint32_t count[2]; unsigned char buffer[64]; } SHA1_CTX; static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) { uint32_t a, b, c, d, e; union char64long16 block[1]; memcpy(block, buffer, 64); a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3); R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7); R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11); R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15); R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19); R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23); R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27); R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31); R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35); R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39); R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43); R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47); R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51); R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55); R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59); R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63); R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67); R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71); R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75); R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79); state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; // Erase working structures. The order of operations is important, // used to ensure that compiler doesn't optimize those out. memset(block, 0, sizeof(block)); a = b = c = d = e = 0; (void) a; (void) b; (void) c; (void) d; (void) e; } static void SHA1Init(SHA1_CTX* context) { context->state[0] = 0x67452301; context->state[1] = 0xEFCDAB89; context->state[2] = 0x98BADCFE; context->state[3] = 0x10325476; context->state[4] = 0xC3D2E1F0; context->count[0] = context->count[1] = 0; } static void SHA1Update(SHA1_CTX* context, const unsigned char* data, uint32_t len) { uint32_t i, j; j = context->count[0]; if ((context->count[0] += len << 3) < j) context->count[1]++; context->count[1] += (len>>29); j = (j >> 3) & 63; if ((j + len) > 63) { memcpy(&context->buffer[j], data, (i = 64-j)); SHA1Transform(context->state, context->buffer); for ( ; i + 63 < len; i += 64) { SHA1Transform(context->state, &data[i]); } j = 0; } else i = 0; memcpy(&context->buffer[j], &data[i], len - i); } static void SHA1Final(unsigned char digest[20], SHA1_CTX* context) { unsigned i; unsigned char finalcount[8], c; for (i = 0; i < 8; i++) { finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)] >> ((3-(i & 3)) * 8) ) & 255); } c = 0200; SHA1Update(context, &c, 1); while ((context->count[0] & 504) != 448) { c = 0000; SHA1Update(context, &c, 1); } SHA1Update(context, finalcount, 8); for (i = 0; i < 20; i++) { digest[i] = (unsigned char) ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255); } memset(context, '\0', sizeof(*context)); memset(&finalcount, '\0', sizeof(finalcount)); } // END OF SHA1 CODE static void base64_encode(const unsigned char *src, int src_len, char *dst) { static const char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; int i, j, a, b, c; for (i = j = 0; i < src_len; i += 3) { a = src[i]; b = i + 1 >= src_len ? 0 : src[i + 1]; c = i + 2 >= src_len ? 0 : src[i + 2]; dst[j++] = b64[a >> 2]; dst[j++] = b64[((a & 3) << 4) | (b >> 4)]; if (i + 1 < src_len) { dst[j++] = b64[(b & 15) << 2 | (c >> 6)]; } if (i + 2 < src_len) { dst[j++] = b64[c & 63]; } } while (j % 4 != 0) { dst[j++] = '='; } dst[j++] = '\0'; } static void send_websocket_handshake(struct mg_connection *conn, const char *key) { static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; char buf[500], sha[20], b64_sha[sizeof(sha) * 2]; SHA1_CTX sha_ctx; mg_snprintf(buf, sizeof(buf), "%s%s", key, magic); SHA1Init(&sha_ctx); SHA1Update(&sha_ctx, (unsigned char *) buf, strlen(buf)); SHA1Final((unsigned char *) sha, &sha_ctx); base64_encode((unsigned char *) sha, sizeof(sha), b64_sha); mg_snprintf(buf, sizeof(buf), "%s%s%s", "HTTP/1.1 101 Switching Protocols\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n"); mg_write(conn, buf, strlen(buf)); } static int deliver_websocket_frame(struct connection *conn) { // Having buf unsigned char * is important, as it is used below in arithmetic unsigned char *buf = (unsigned char *) conn->ns_conn->recv_iobuf.buf; int i, len, buf_len = conn->ns_conn->recv_iobuf.len, frame_len = 0, mask_len = 0, header_len = 0, data_len = 0, buffered = 0; if (buf_len >= 2) { len = buf[1] & 127; mask_len = buf[1] & 128 ? 4 : 0; if (len < 126 && buf_len >= mask_len) { data_len = len; header_len = 2 + mask_len; } else if (len == 126 && buf_len >= 4 + mask_len) { header_len = 4 + mask_len; data_len = ((((int) buf[2]) << 8) + buf[3]); } else if (buf_len >= 10 + mask_len) { header_len = 10 + mask_len; data_len = (int) (((uint64_t) htonl(* (uint32_t *) &buf[2])) << 32) + htonl(* (uint32_t *) &buf[6]); } } frame_len = header_len + data_len; buffered = frame_len > 0 && frame_len <= buf_len; if (buffered) { conn->mg_conn.content_len = data_len; conn->mg_conn.content = (char *) buf + header_len; conn->mg_conn.wsbits = buf[0]; // Apply mask if necessary if (mask_len > 0) { for (i = 0; i < data_len; i++) { buf[i + header_len] ^= (buf + header_len - mask_len)[i % 4]; } } // Call the handler and remove frame from the iobuf if (call_user(conn, MG_REQUEST) == MG_FALSE) { conn->ns_conn->flags |= NSF_FINISHED_SENDING_DATA; } iobuf_remove(&conn->ns_conn->recv_iobuf, frame_len); } return buffered; } int mg_websocket_write(struct mg_connection* conn, int opcode, const char *data, size_t data_len) { unsigned char mem[4192], *copy = mem; size_t copy_len = 0; int retval = -1; if (data_len + 10 > sizeof(mem) && (copy = (unsigned char *) malloc(data_len + 10)) == NULL) { return -1; } copy[0] = 0x80 + (opcode & 0x0f); // Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 if (data_len < 126) { // Inline 7-bit length field copy[1] = data_len; memcpy(copy + 2, data, data_len); copy_len = 2 + data_len; } else if (data_len <= 0xFFFF) { // 16-bit length field copy[1] = 126; * (uint16_t *) (copy + 2) = (uint16_t) htons((uint16_t) data_len); memcpy(copy + 4, data, data_len); copy_len = 4 + data_len; } else { // 64-bit length field copy[1] = 127; * (uint32_t *) (copy + 2) = (uint32_t) htonl((uint32_t) ((uint64_t) data_len >> 32)); * (uint32_t *) (copy + 6) = (uint32_t) htonl(data_len & 0xffffffff); memcpy(copy + 10, data, data_len); copy_len = 10 + data_len; } if (copy_len > 0) { retval = mg_write(conn, copy, copy_len); } if (copy != mem) { free(copy); } return retval; } int mg_websocket_printf(struct mg_connection* conn, int opcode, const char *fmt, ...) { char mem[4192], *buf = mem; va_list ap; int len; va_start(ap, fmt); if ((len = ns_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) { mg_websocket_write(conn, opcode, buf, len); } va_end(ap); if (buf != mem && buf != NULL) { free(buf); } return len; } static void send_websocket_handshake_if_requested(struct mg_connection *conn) { const char *ver = mg_get_header(conn, "Sec-WebSocket-Version"), *key = mg_get_header(conn, "Sec-WebSocket-Key"); if (ver != NULL && key != NULL) { conn->is_websocket = 1; if (call_user(MG_CONN_2_CONN(conn), MG_WS_HANDSHAKE) == MG_FALSE) { send_websocket_handshake(conn, key); } } } static void ping_idle_websocket_connection(struct connection *conn, time_t t) { if (t - conn->ns_conn->last_io_time > MONGOOSE_USE_WEBSOCKET_PING_INTERVAL) { mg_websocket_write(&conn->mg_conn, WEBSOCKET_OPCODE_PING, "", 0); } } #else #define ping_idle_websocket_connection(conn, t) #endif // !MONGOOSE_NO_WEBSOCKET static void write_terminating_chunk(struct connection *conn) { mg_write(&conn->mg_conn, "0\r\n\r\n", 5); } static int call_request_handler(struct connection *conn) { int result; conn->mg_conn.content = conn->ns_conn->recv_iobuf.buf; if ((result = call_user(conn, MG_REQUEST)) == MG_TRUE) { if (conn->ns_conn->flags & MG_HEADERS_SENT) { write_terminating_chunk(conn); } close_local_endpoint(conn); } return result; } const char *mg_get_mime_type(const char *path, const char *default_mime_type) { const char *ext; size_t i, path_len; path_len = strlen(path); for (i = 0; static_builtin_mime_types[i].extension != NULL; i++) { ext = path + (path_len - static_builtin_mime_types[i].ext_len); if (path_len > static_builtin_mime_types[i].ext_len && mg_strcasecmp(ext, static_builtin_mime_types[i].extension) == 0) { return static_builtin_mime_types[i].mime_type; } } return default_mime_type; } #ifndef MONGOOSE_NO_FILESYSTEM // Convert month to the month number. Return -1 on error, or month number static int get_month_index(const char *s) { static const char *month_names[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; int i; for (i = 0; i < (int) ARRAY_SIZE(month_names); i++) if (!strcmp(s, month_names[i])) return i; return -1; } static int num_leap_years(int year) { return year / 4 - year / 100 + year / 400; } // Parse UTC date-time string, and return the corresponding time_t value. static time_t parse_date_string(const char *datetime) { static const unsigned short days_before_month[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; char month_str[32]; int second, minute, hour, day, month, year, leap_days, days; time_t result = (time_t) 0; if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d", &day, month_str, &year, &hour, &minute, &second) == 6) || (sscanf(datetime, "%d %3s %d %d:%d:%d", &day, month_str, &year, &hour, &minute, &second) == 6) || (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", &day, month_str, &year, &hour, &minute, &second) == 6) || (sscanf(datetime, "%d-%3s-%d %d:%d:%d", &day, month_str, &year, &hour, &minute, &second) == 6)) && year > 1970 && (month = get_month_index(month_str)) != -1) { leap_days = num_leap_years(year) - num_leap_years(1970); year -= 1970; days = year * 365 + days_before_month[month] + (day - 1) + leap_days; result = days * 24 * 3600 + hour * 3600 + minute * 60 + second; } return result; } // Look at the "path" extension and figure what mime type it has. // Store mime type in the vector. static void get_mime_type(const struct mg_server *server, const char *path, struct vec *vec) { struct vec ext_vec, mime_vec; const char *list, *ext; size_t path_len; path_len = strlen(path); // Scan user-defined mime types first, in case user wants to // override default mime types. list = server->config_options[EXTRA_MIME_TYPES]; while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) { // ext now points to the path suffix ext = path + path_len - ext_vec.len; if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) { *vec = mime_vec; return; } } vec->ptr = mg_get_mime_type(path, "text/plain"); vec->len = strlen(vec->ptr); } static const char *suggest_connection_header(const struct mg_connection *conn) { return should_keep_alive(conn) ? "keep-alive" : "close"; } static void construct_etag(char *buf, size_t buf_len, const file_stat_t *st) { mg_snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", (unsigned long) st->st_mtime, (int64_t) st->st_size); } // Return True if we should reply 304 Not Modified. static int is_not_modified(const struct connection *conn, const file_stat_t *stp) { char etag[64]; const char *ims = mg_get_header(&conn->mg_conn, "If-Modified-Since"); const char *inm = mg_get_header(&conn->mg_conn, "If-None-Match"); construct_etag(etag, sizeof(etag), stp); return (inm != NULL && !mg_strcasecmp(etag, inm)) || (ims != NULL && stp->st_mtime <= parse_date_string(ims)); } // For given directory path, substitute it to valid index file. // Return 0 if index file has been found, -1 if not found. // If the file is found, it's stats is returned in stp. static int find_index_file(struct connection *conn, char *path, size_t path_len, file_stat_t *stp) { const char *list = conn->server->config_options[INDEX_FILES]; file_stat_t st; struct vec filename_vec; size_t n = strlen(path), found = 0; // The 'path' given to us points to the directory. Remove all trailing // directory separator characters from the end of the path, and // then append single directory separator character. while (n > 0 && path[n - 1] == '/') { n--; } path[n] = '/'; // Traverse index files list. For each entry, append it to the given // path and see if the file exists. If it exists, break the loop while ((list = next_option(list, &filename_vec, NULL)) != NULL) { // Ignore too long entries that may overflow path buffer if (filename_vec.len > (int) (path_len - (n + 2))) continue; // Prepare full path to the index file strncpy(path + n + 1, filename_vec.ptr, filename_vec.len); path[n + 1 + filename_vec.len] = '\0'; //DBG(("[%s]", path)); // Does it exist? if (!stat(path, &st)) { // Yes it does, break the loop *stp = st; found = 1; break; } } // If no index file exists, restore directory path if (!found) { path[n] = '\0'; } return found; } static int parse_range_header(const char *header, int64_t *a, int64_t *b) { return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b); } static void gmt_time_string(char *buf, size_t buf_len, time_t *t) { strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t)); } static void open_file_endpoint(struct connection *conn, const char *path, file_stat_t *st) { char date[64], lm[64], etag[64], range[64], headers[500]; const char *msg = "OK", *hdr; time_t curtime = time(NULL); int64_t r1, r2; struct vec mime_vec; int n; conn->endpoint_type = EP_FILE; ns_set_close_on_exec(conn->endpoint.fd); conn->mg_conn.status_code = 200; get_mime_type(conn->server, path, &mime_vec); conn->cl = st->st_size; range[0] = '\0'; // If Range: header specified, act accordingly r1 = r2 = 0; hdr = mg_get_header(&conn->mg_conn, "Range"); if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0 && r2 >= 0) { conn->mg_conn.status_code = 206; conn->cl = n == 2 ? (r2 > conn->cl ? conn->cl : r2) - r1 + 1: conn->cl - r1; mg_snprintf(range, sizeof(range), "Content-Range: bytes " "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n", r1, r1 + conn->cl - 1, (int64_t) st->st_size); msg = "Partial Content"; lseek(conn->endpoint.fd, r1, SEEK_SET); } // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 gmt_time_string(date, sizeof(date), &curtime); gmt_time_string(lm, sizeof(lm), &st->st_mtime); construct_etag(etag, sizeof(etag), st); n = mg_snprintf(headers, sizeof(headers), "HTTP/1.1 %d %s\r\n" "Date: %s\r\n" "Last-Modified: %s\r\n" "Etag: %s\r\n" "Content-Type: %.*s\r\n" "Content-Length: %" INT64_FMT "\r\n" "Connection: %s\r\n" "Accept-Ranges: bytes\r\n" "%s%s\r\n", conn->mg_conn.status_code, msg, date, lm, etag, (int) mime_vec.len, mime_vec.ptr, conn->cl, suggest_connection_header(&conn->mg_conn), range, MONGOOSE_USE_EXTRA_HTTP_HEADERS); ns_send(conn->ns_conn, headers, n); if (!strcmp(conn->mg_conn.request_method, "HEAD")) { conn->ns_conn->flags |= NSF_FINISHED_SENDING_DATA; close(conn->endpoint.fd); conn->endpoint_type = EP_NONE; } } #endif // MONGOOSE_NO_FILESYSTEM static void call_request_handler_if_data_is_buffered(struct connection *conn) { struct iobuf *loc = &conn->ns_conn->recv_iobuf; struct mg_connection *c = &conn->mg_conn; #ifndef MONGOOSE_NO_WEBSOCKET if (conn->mg_conn.is_websocket) { do { } while (deliver_websocket_frame(conn)); } else #endif if ((size_t) loc->len >= c->content_len && call_request_handler(conn) == MG_FALSE) { open_local_endpoint(conn, 1); } } #if !defined(MONGOOSE_NO_DIRECTORY_LISTING) || !defined(MONGOOSE_NO_DAV) #ifdef _WIN32 struct dirent { char d_name[MAX_PATH_SIZE]; }; typedef struct DIR { HANDLE handle; WIN32_FIND_DATAW info; struct dirent result; } DIR; // Implementation of POSIX opendir/closedir/readdir for Windows. static DIR *opendir(const char *name) { DIR *dir = NULL; wchar_t wpath[MAX_PATH_SIZE]; DWORD attrs; if (name == NULL) { SetLastError(ERROR_BAD_ARGUMENTS); } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) { SetLastError(ERROR_NOT_ENOUGH_MEMORY); } else { to_wchar(name, wpath, ARRAY_SIZE(wpath)); attrs = GetFileAttributesW(wpath); if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) { (void) wcscat(wpath, L"\\*"); dir->handle = FindFirstFileW(wpath, &dir->info); dir->result.d_name[0] = '\0'; } else { free(dir); dir = NULL; } } return dir; } static int closedir(DIR *dir) { int result = 0; if (dir != NULL) { if (dir->handle != INVALID_HANDLE_VALUE) result = FindClose(dir->handle) ? 0 : -1; free(dir); } else { result = -1; SetLastError(ERROR_BAD_ARGUMENTS); } return result; } static struct dirent *readdir(DIR *dir) { struct dirent *result = 0; if (dir) { if (dir->handle != INVALID_HANDLE_VALUE) { result = &dir->result; (void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1, result->d_name, sizeof(result->d_name), NULL, NULL); if (!FindNextFileW(dir->handle, &dir->info)) { (void) FindClose(dir->handle); dir->handle = INVALID_HANDLE_VALUE; } } else { SetLastError(ERROR_FILE_NOT_FOUND); } } else { SetLastError(ERROR_BAD_ARGUMENTS); } return result; } #endif // _WIN32 POSIX opendir/closedir/readdir implementation static int scan_directory(struct connection *conn, const char *dir, struct dir_entry **arr) { char path[MAX_PATH_SIZE]; struct dir_entry *p; struct dirent *dp; int arr_size = 0, arr_ind = 0, inc = 100; DIR *dirp; *arr = NULL; if ((dirp = (opendir(dir))) == NULL) return 0; while ((dp = readdir(dirp)) != NULL) { // Do not show current dir and hidden files if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..") || must_hide_file(conn, dp->d_name)) { continue; } mg_snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name); // Resize the array if nesessary if (arr_ind >= arr_size) { if ((p = (struct dir_entry *) realloc(*arr, (inc + arr_size) * sizeof(**arr))) != NULL) { // Memset new chunk to zero, otherwize st_mtime will have garbage which // can make strftime() segfault, see // http://code.google.com/p/mongoose/issues/detail?id=79 memset(p + arr_size, 0, sizeof(**arr) * inc); *arr = p; arr_size += inc; } } if (arr_ind < arr_size) { (*arr)[arr_ind].conn = conn; (*arr)[arr_ind].file_name = strdup(dp->d_name); stat(path, &(*arr)[arr_ind].st); arr_ind++; } } closedir(dirp); return arr_ind; } int mg_url_encode(const char *src, size_t s_len, char *dst, size_t dst_len) { static const char *dont_escape = "._-$,;~()"; static const char *hex = "0123456789abcdef"; size_t i = 0, j = 0; for (i = j = 0; dst_len > 0 && i < s_len && j < dst_len - 1; i++, j++) { if (isalnum(* (const unsigned char *) (src + i)) || strchr(dont_escape, * (const unsigned char *) (src + i)) != NULL) { dst[j] = src[i]; } else if (j + 3 < dst_len) { dst[j] = '%'; dst[j + 1] = hex[(* (const unsigned char *) (src + i)) >> 4]; dst[j + 2] = hex[(* (const unsigned char *) (src + i)) & 0xf]; j += 2; } } dst[j] = '\0'; return j; } #endif // !NO_DIRECTORY_LISTING || !MONGOOSE_NO_DAV #ifndef MONGOOSE_NO_DIRECTORY_LISTING static void print_dir_entry(const struct dir_entry *de) { char size[64], mod[64], href[MAX_PATH_SIZE * 3]; int64_t fsize = de->st.st_size; int is_dir = S_ISDIR(de->st.st_mode); const char *slash = is_dir ? "/" : ""; if (is_dir) { mg_snprintf(size, sizeof(size), "%s", "[DIRECTORY]"); } else { // We use (signed) cast below because MSVC 6 compiler cannot // convert unsigned __int64 to double. if (fsize < 1024) { mg_snprintf(size, sizeof(size), "%d", (int) fsize); } else if (fsize < 0x100000) { mg_snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0); } else if (fsize < 0x40000000) { mg_snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576); } else { mg_snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824); } } strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&de->st.st_mtime)); mg_url_encode(de->file_name, strlen(de->file_name), href, sizeof(href)); mg_printf_data(&de->conn->mg_conn, "%s%s" " %s  %s\n", href, slash, de->file_name, slash, mod, size); } // Sort directory entries by size, or name, or modification time. // On windows, __cdecl specification is needed in case if project is built // with __stdcall convention. qsort always requires __cdels callback. static int __cdecl compare_dir_entries(const void *p1, const void *p2) { const struct dir_entry *a = (const struct dir_entry *) p1, *b = (const struct dir_entry *) p2; const char *qs = a->conn->mg_conn.query_string ? a->conn->mg_conn.query_string : "na"; int cmp_result = 0; if (S_ISDIR(a->st.st_mode) && !S_ISDIR(b->st.st_mode)) { return -1; // Always put directories on top } else if (!S_ISDIR(a->st.st_mode) && S_ISDIR(b->st.st_mode)) { return 1; // Always put directories on top } else if (*qs == 'n') { cmp_result = strcmp(a->file_name, b->file_name); } else if (*qs == 's') { cmp_result = a->st.st_size == b->st.st_size ? 0 : a->st.st_size > b->st.st_size ? 1 : -1; } else if (*qs == 'd') { cmp_result = a->st.st_mtime == b->st.st_mtime ? 0 : a->st.st_mtime > b->st.st_mtime ? 1 : -1; } return qs[1] == 'd' ? -cmp_result : cmp_result; } static void send_directory_listing(struct connection *conn, const char *dir) { struct dir_entry *arr = NULL; int i, num_entries, sort_direction = conn->mg_conn.query_string != NULL && conn->mg_conn.query_string[1] == 'd' ? 'a' : 'd'; mg_send_header(&conn->mg_conn, "Transfer-Encoding", "chunked"); mg_send_header(&conn->mg_conn, "Content-Type", "text/html; charset=utf-8"); mg_printf_data(&conn->mg_conn, "Index of %s" "" "

Index of %s

"
              ""
              ""
              ""
              "",
              conn->mg_conn.uri, conn->mg_conn.uri,
              sort_direction, sort_direction, sort_direction);

  num_entries = scan_directory(conn, dir, &arr);
  qsort(arr, num_entries, sizeof(arr[0]), compare_dir_entries);
  for (i = 0; i < num_entries; i++) {
    print_dir_entry(&arr[i]);
    free(arr[i].file_name);
  }
  free(arr);

  write_terminating_chunk(conn);
  close_local_endpoint(conn);
}
#endif  // MONGOOSE_NO_DIRECTORY_LISTING

#ifndef MONGOOSE_NO_DAV
static void print_props(struct connection *conn, const char *uri,
                        file_stat_t *stp) {
  char mtime[64];

  gmt_time_string(mtime, sizeof(mtime), &stp->st_mtime);
  mg_printf(&conn->mg_conn,
      ""
       "%s"
       ""
        ""
         "%s"
         "%" INT64_FMT ""
         "%s"
        ""
        "HTTP/1.1 200 OK"
       ""
      "\n",
      uri, S_ISDIR(stp->st_mode) ? "" : "",
      (int64_t) stp->st_size, mtime);
}

static void handle_propfind(struct connection *conn, const char *path,
                            file_stat_t *stp, int exists) {
  static const char header[] = "HTTP/1.1 207 Multi-Status\r\n"
    "Connection: close\r\n"
    "Content-Type: text/xml; charset=utf-8\r\n\r\n"
    ""
    "\n";
  static const char footer[] = "";
  const char *depth = mg_get_header(&conn->mg_conn, "Depth"),
        *list_dir = conn->server->config_options[ENABLE_DIRECTORY_LISTING];

  conn->mg_conn.status_code = 207;

  // Print properties for the requested resource itself
  if (!exists) {
    conn->mg_conn.status_code = 404;
    mg_printf(&conn->mg_conn, "%s", "HTTP/1.1 404 Not Found\r\n\r\n");
  } else if (S_ISDIR(stp->st_mode) && mg_strcasecmp(list_dir, "yes") != 0) {
    conn->mg_conn.status_code = 403;
    mg_printf(&conn->mg_conn, "%s",
              "HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
  } else {
    ns_send(conn->ns_conn, header, sizeof(header) - 1);
    print_props(conn, conn->mg_conn.uri, stp);

    if (S_ISDIR(stp->st_mode) &&
             (depth == NULL || strcmp(depth, "0") != 0)) {
      struct dir_entry *arr = NULL;
      int i, num_entries = scan_directory(conn, path, &arr);

      for (i = 0; i < num_entries; i++) {
        char buf[MAX_PATH_SIZE * 3];
        struct dir_entry *de = &arr[i];
        mg_url_encode(de->file_name, strlen(de->file_name), buf, sizeof(buf));
        print_props(conn, buf, &de->st);
      }
    }
    ns_send(conn->ns_conn, footer, sizeof(footer) - 1);
  }

  close_local_endpoint(conn);
}

static void handle_mkcol(struct connection *conn, const char *path) {
  int status_code = 500;

  if (conn->mg_conn.content_len > 0) {
    status_code = 415;
  } else if (!mkdir(path, 0755)) {
    status_code = 201;
  } else if (errno == EEXIST) {
    status_code = 405;
  } else if (errno == EACCES) {
    status_code = 403;
  } else if (errno == ENOENT) {
    status_code = 409;
  }
  send_http_error(conn, status_code, NULL);
}

static int remove_directory(const char *dir) {
  char path[MAX_PATH_SIZE];
  struct dirent *dp;
  file_stat_t st;
  DIR *dirp;

  if ((dirp = opendir(dir)) == NULL) return 0;

  while ((dp = readdir(dirp)) != NULL) {
    if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue;
    mg_snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
    stat(path, &st);
    if (S_ISDIR(st.st_mode)) {
      remove_directory(path);
    } else {
      remove(path);
    }
  }
  closedir(dirp);
  rmdir(dir);

  return 1;
}

static void handle_delete(struct connection *conn, const char *path) {
  file_stat_t st;

  if (stat(path, &st) != 0) {
    send_http_error(conn, 404, NULL);
  } else if (S_ISDIR(st.st_mode)) {
    remove_directory(path);
    send_http_error(conn, 204, NULL);
  } else if (remove(path) == 0) {
    send_http_error(conn, 204, NULL);
  } else {
    send_http_error(conn, 423, NULL);
  }
}

// For a given PUT path, create all intermediate subdirectories
// for given path. Return 0 if the path itself is a directory,
// or -1 on error, 1 if OK.
static int put_dir(const char *path) {
  char buf[MAX_PATH_SIZE];
  const char *s, *p;
  file_stat_t st;

  // Create intermediate directories if they do not exist
  for (s = p = path + 1; (p = strchr(s, '/')) != NULL; s = ++p) {
    if (p - path >= (int) sizeof(buf)) return -1; // Buffer overflow
    memcpy(buf, path, p - path);
    buf[p - path] = '\0';
    if (stat(buf, &st) != 0 && mkdir(buf, 0755) != 0) return -1;
    if (p[1] == '\0') return 0;  // Path is a directory itself
  }

  return 1;
}

static void handle_put(struct connection *conn, const char *path) {
  file_stat_t st;
  const char *range, *cl_hdr = mg_get_header(&conn->mg_conn, "Content-Length");
  int64_t r1, r2;
  int rc;

  conn->mg_conn.status_code = !stat(path, &st) ? 200 : 201;
  if ((rc = put_dir(path)) == 0) {
    mg_printf(&conn->mg_conn, "HTTP/1.1 %d OK\r\n\r\n",
              conn->mg_conn.status_code);
    close_local_endpoint(conn);
  } else if (rc == -1) {
    send_http_error(conn, 500, "put_dir: %s", strerror(errno));
  } else if (cl_hdr == NULL) {
    send_http_error(conn, 411, NULL);
#ifdef _WIN32
    //On Windows, open() is a macro with 2 params
  } else if ((conn->endpoint.fd =
              open(path, O_RDWR | O_CREAT | O_TRUNC)) < 0) {
#else
  } else if ((conn->endpoint.fd =
              open(path, O_RDWR | O_CREAT | O_TRUNC, 0644)) < 0) {
#endif
    send_http_error(conn, 500, "open(%s): %s", path, strerror(errno));
  } else {
    DBG(("PUT [%s] %zu", path, conn->ns_conn->recv_iobuf.len));
    conn->endpoint_type = EP_PUT;
    ns_set_close_on_exec(conn->endpoint.fd);
    range = mg_get_header(&conn->mg_conn, "Content-Range");
    conn->cl = to64(cl_hdr);
    r1 = r2 = 0;
    if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
      conn->mg_conn.status_code = 206;
      lseek(conn->endpoint.fd, r1, SEEK_SET);
      conn->cl = r2 > r1 ? r2 - r1 + 1: conn->cl - r1;
    }
    mg_printf(&conn->mg_conn, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n",
              conn->mg_conn.status_code);
  }
}

static void forward_put_data(struct connection *conn) {
  struct iobuf *io = &conn->ns_conn->recv_iobuf;
  size_t k = conn->cl < (int64_t) io->len ? conn->cl : io->len;   // To write
  int n = write(conn->endpoint.fd, io->buf, k);   // Write them!
  if (n > 0) {
    iobuf_remove(io, n);
    conn->cl -= n;
  }
  if (conn->cl <= 0) {
    close_local_endpoint(conn);
  }
}
#endif //  MONGOOSE_NO_DAV

static void send_options(struct connection *conn) {
  conn->mg_conn.status_code = 200;
  mg_printf(&conn->mg_conn, "%s",
            "HTTP/1.1 200 OK\r\nAllow: GET, POST, HEAD, CONNECT, PUT, "
            "DELETE, OPTIONS, PROPFIND, MKCOL\r\nDAV: 1\r\n\r\n");
  close_local_endpoint(conn);
}

#ifndef MONGOOSE_NO_AUTH
void mg_send_digest_auth_request(struct mg_connection *c) {
  struct connection *conn = MG_CONN_2_CONN(c);
  c->status_code = 401;
  mg_printf(c,
            "HTTP/1.1 401 Unauthorized\r\n"
            "WWW-Authenticate: Digest qop=\"auth\", "
            "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
            conn->server->config_options[AUTH_DOMAIN],
            (unsigned long) time(NULL));
  close_local_endpoint(conn);
}

// Use the global passwords file, if specified by auth_gpass option,
// or search for .htpasswd in the requested directory.
static FILE *open_auth_file(struct connection *conn, const char *path) {
  char name[MAX_PATH_SIZE];
  const char *p, *gpass = conn->server->config_options[GLOBAL_AUTH_FILE];
  file_stat_t st;
  FILE *fp = NULL;

  if (gpass != NULL) {
    // Use global passwords file
    fp = fopen(gpass, "r");
  } else if (!stat(path, &st) && S_ISDIR(st.st_mode)) {
    mg_snprintf(name, sizeof(name), "%s%c%s", path, '/', PASSWORDS_FILE_NAME);
    fp = fopen(name, "r");
  } else {
    // Try to find .htpasswd in requested directory.
    if ((p = strrchr(path, '/')) == NULL) p = path;
    mg_snprintf(name, sizeof(name), "%.*s%c%s",
                (int) (p - path), path, '/', PASSWORDS_FILE_NAME);
    fp = fopen(name, "r");
  }

  return fp;
}

#if !defined(HAVE_MD5) && !defined(MONGOOSE_NO_AUTH)
typedef struct MD5Context {
  uint32_t buf[4];
  uint32_t bits[2];
  unsigned char in[64];
} MD5_CTX;

static void byteReverse(unsigned char *buf, unsigned longs) {
  uint32_t t;

  // Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN
  if (is_big_endian()) {
    do {
      t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
        ((unsigned) buf[1] << 8 | buf[0]);
      * (uint32_t *) buf = t;
      buf += 4;
    } while (--longs);
  }
}

#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define F2(x, y, z) F1(z, x, y)
#define F3(x, y, z) (x ^ y ^ z)
#define F4(x, y, z) (y ^ (x | ~z))

#define MD5STEP(f, w, x, y, z, data, s) \
  ( w += f(x, y, z) + data,  w = w<>(32-s),  w += x )

// Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
// initialization constants.
static void MD5Init(MD5_CTX *ctx) {
  ctx->buf[0] = 0x67452301;
  ctx->buf[1] = 0xefcdab89;
  ctx->buf[2] = 0x98badcfe;
  ctx->buf[3] = 0x10325476;

  ctx->bits[0] = 0;
  ctx->bits[1] = 0;
}

static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
  register uint32_t a, b, c, d;

  a = buf[0];
  b = buf[1];
  c = buf[2];
  d = buf[3];

  MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);

  MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);

  MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);

  MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);

  buf[0] += a;
  buf[1] += b;
  buf[2] += c;
  buf[3] += d;
}

static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) {
  uint32_t t;

  t = ctx->bits[0];
  if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
    ctx->bits[1]++;
  ctx->bits[1] += len >> 29;

  t = (t >> 3) & 0x3f;

  if (t) {
    unsigned char *p = (unsigned char *) ctx->in + t;

    t = 64 - t;
    if (len < t) {
      memcpy(p, buf, len);
      return;
    }
    memcpy(p, buf, t);
    byteReverse(ctx->in, 16);
    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
    buf += t;
    len -= t;
  }

  while (len >= 64) {
    memcpy(ctx->in, buf, 64);
    byteReverse(ctx->in, 16);
    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
    buf += 64;
    len -= 64;
  }

  memcpy(ctx->in, buf, len);
}

static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) {
  unsigned count;
  unsigned char *p;
  uint32_t *a;

  count = (ctx->bits[0] >> 3) & 0x3F;

  p = ctx->in + count;
  *p++ = 0x80;
  count = 64 - 1 - count;
  if (count < 8) {
    memset(p, 0, count);
    byteReverse(ctx->in, 16);
    MD5Transform(ctx->buf, (uint32_t *) ctx->in);
    memset(ctx->in, 0, 56);
  } else {
    memset(p, 0, count - 8);
  }
  byteReverse(ctx->in, 14);

  a = (uint32_t *)ctx->in;
  a[14] = ctx->bits[0];
  a[15] = ctx->bits[1];

  MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  byteReverse((unsigned char *) ctx->buf, 4);
  memcpy(digest, ctx->buf, 16);
  memset((char *) ctx, 0, sizeof(*ctx));
}
#endif // !HAVE_MD5



// Stringify binary data. Output buffer must be twice as big as input,
// because each byte takes 2 bytes in string representation
static void bin2str(char *to, const unsigned char *p, size_t len) {
  static const char *hex = "0123456789abcdef";

  for (; len--; p++) {
    *to++ = hex[p[0] >> 4];
    *to++ = hex[p[0] & 0x0f];
  }
  *to = '\0';
}

// Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
char *mg_md5(char buf[33], ...) {
  unsigned char hash[16];
  const char *p;
  va_list ap;
  MD5_CTX ctx;

  MD5Init(&ctx);

  va_start(ap, buf);
  while ((p = va_arg(ap, const char *)) != NULL) {
    MD5Update(&ctx, (const unsigned char *) p, (unsigned) strlen(p));
  }
  va_end(ap);

  MD5Final(hash, &ctx);
  bin2str(buf, hash, sizeof(hash));
  return buf;
}

// Check the user's password, return 1 if OK
static int check_password(const char *method, const char *ha1, const char *uri,
                          const char *nonce, const char *nc, const char *cnonce,
                          const char *qop, const char *response) {
  char ha2[32 + 1], expected_response[32 + 1];

#if 0
  // Check for authentication timeout
  if ((unsigned long) time(NULL) - (unsigned long) to64(nonce) > 3600 * 2) {
    return 0;
  }
#endif

  mg_md5(ha2, method, ":", uri, NULL);
  mg_md5(expected_response, ha1, ":", nonce, ":", nc,
      ":", cnonce, ":", qop, ":", ha2, NULL);

  return mg_strcasecmp(response, expected_response) == 0 ? MG_TRUE : MG_FALSE;
}


// Authorize against the opened passwords file. Return 1 if authorized.
int mg_authorize_digest(struct mg_connection *c, FILE *fp) {
  struct connection *conn = MG_CONN_2_CONN(c);
  const char *hdr;
  char line[256], f_user[256], ha1[256], f_domain[256], user[100], nonce[100],
       uri[MAX_REQUEST_SIZE], cnonce[100], resp[100], qop[100], nc[100];

  if (c == NULL || fp == NULL) return 0;
  if ((hdr = mg_get_header(c, "Authorization")) == NULL ||
      mg_strncasecmp(hdr, "Digest ", 7) != 0) return 0;
  if (!mg_parse_header(hdr, "username", user, sizeof(user))) return 0;
  if (!mg_parse_header(hdr, "cnonce", cnonce, sizeof(cnonce))) return 0;
  if (!mg_parse_header(hdr, "response", resp, sizeof(resp))) return 0;
  if (!mg_parse_header(hdr, "uri", uri, sizeof(uri))) return 0;
  if (!mg_parse_header(hdr, "qop", qop, sizeof(qop))) return 0;
  if (!mg_parse_header(hdr, "nc", nc, sizeof(nc))) return 0;
  if (!mg_parse_header(hdr, "nonce", nonce, sizeof(nonce))) return 0;

  while (fgets(line, sizeof(line), fp) != NULL) {
    if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) == 3 &&
        !strcmp(user, f_user) &&
        // NOTE(lsm): due to a bug in MSIE, we do not compare URIs
        !strcmp(conn->server->config_options[AUTH_DOMAIN], f_domain))
      return check_password(c->request_method, ha1, uri,
                            nonce, nc, cnonce, qop, resp);
  }
  return MG_FALSE;
}


// Return 1 if request is authorised, 0 otherwise.
static int is_authorized(struct connection *conn, const char *path) {
  FILE *fp;
  int authorized = MG_TRUE;

  if ((fp = open_auth_file(conn, path)) != NULL) {
    authorized = mg_authorize_digest(&conn->mg_conn, fp);
    fclose(fp);
  }

  return authorized;
}

static int is_authorized_for_dav(struct connection *conn) {
  const char *auth_file = conn->server->config_options[DAV_AUTH_FILE];
  const char *method = conn->mg_conn.request_method;
  FILE *fp;
  int authorized = MG_FALSE;

  // If dav_auth_file is not set, allow non-authorized PROPFIND
  if (method != NULL && !strcmp(method, "PROPFIND") && auth_file == NULL) {
    authorized = MG_TRUE;
  } else if (auth_file != NULL && (fp = fopen(auth_file, "r")) != NULL) {
    authorized = mg_authorize_digest(&conn->mg_conn, fp);
    fclose(fp);
  }

  return authorized;
}

static int is_dav_request(const struct connection *conn) {
  const char *s = conn->mg_conn.request_method;
  return !strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
    !strcmp(s, "MKCOL") || !strcmp(s, "PROPFIND");
}
#endif // MONGOOSE_NO_AUTH

static int parse_header(const char *str, int str_len, const char *var_name,
                        char *buf, size_t buf_size) {
  int ch = ' ', len = 0, n = strlen(var_name);
  const char *p, *end = str + str_len, *s = NULL;

  if (buf != NULL && buf_size > 0) buf[0] = '\0';

  // Find where variable starts
  for (s = str; s != NULL && s + n < end; s++) {
    if ((s == str || s[-1] == ' ' || s[-1] == ',') && s[n] == '=' &&
        !memcmp(s, var_name, n)) break;
  }

  if (s != NULL && &s[n + 1] < end) {
    s += n + 1;
    if (*s == '"' || *s == '\'') ch = *s++;
    p = s;
    while (p < end && p[0] != ch && p[0] != ',' && len < (int) buf_size) {
      if (p[0] == '\\' && p[1] == ch) p++;
      buf[len++] = *p++;
    }
    if (len >= (int) buf_size || (ch != ' ' && *p != ch)) {
      len = 0;
    } else {
      if (len > 0 && s[len - 1] == ',') len--;
      if (len > 0 && s[len - 1] == ';') len--;
      buf[len] = '\0';
    }
  }

  return len;
}

int mg_parse_header(const char *s, const char *var_name, char *buf,
                    size_t buf_size) {
  return parse_header(s, s == NULL ? 0 : strlen(s), var_name, buf, buf_size);
}

#ifndef MONGOOSE_NO_SSI
static void send_ssi_file(struct mg_connection *, const char *, FILE *, int);

static void send_file_data(struct mg_connection *conn, FILE *fp) {
  char buf[IOBUF_SIZE];
  int n;
  while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
    mg_write(conn, buf, n);
  }
}

static void do_ssi_include(struct mg_connection *conn, const char *ssi,
                           char *tag, int include_level) {
  char file_name[IOBUF_SIZE], path[MAX_PATH_SIZE], *p;
  char **opts = (MG_CONN_2_CONN(conn))->server->config_options;
  FILE *fp;

  // sscanf() is safe here, since send_ssi_file() also uses buffer
  // of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
  if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
    // File name is relative to the webserver root
    mg_snprintf(path, sizeof(path), "%s%c%s",
                opts[DOCUMENT_ROOT], '/', file_name);
  } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
    // File name is relative to the webserver working directory
    // or it is absolute system path
    mg_snprintf(path, sizeof(path), "%s", file_name);
  } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
             sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
    // File name is relative to the currect document
    mg_snprintf(path, sizeof(path), "%s", ssi);
    if ((p = strrchr(path, '/')) != NULL) {
      p[1] = '\0';
    }
    mg_snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s",
                file_name);
  } else {
    mg_printf(conn, "Bad SSI #include: [%s]", tag);
    return;
  }

  if ((fp = fopen(path, "rb")) == NULL) {
    mg_printf(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",
              tag, path, strerror(errno));
  } else {
    ns_set_close_on_exec(fileno(fp));
    if (mg_match_prefix(opts[SSI_PATTERN], strlen(opts[SSI_PATTERN]),
        path) > 0) {
      send_ssi_file(conn, path, fp, include_level + 1);
    } else {
      send_file_data(conn, fp);
    }
    fclose(fp);
  }
}

#ifndef MONGOOSE_NO_POPEN
static void do_ssi_exec(struct mg_connection *conn, char *tag) {
  char cmd[IOBUF_SIZE];
  FILE *fp;

  if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
    mg_printf(conn, "Bad SSI #exec: [%s]", tag);
  } else if ((fp = popen(cmd, "r")) == NULL) {
    mg_printf(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(errno));
  } else {
    send_file_data(conn, fp);
    pclose(fp);
  }
}
#endif // !MONGOOSE_NO_POPEN

static void send_ssi_file(struct mg_connection *conn, const char *path,
                          FILE *fp, int include_level) {
  char buf[IOBUF_SIZE];
  int ch, offset, len, in_ssi_tag;

  if (include_level > 10) {
    mg_printf(conn, "SSI #include level is too deep (%s)", path);
    return;
  }

  in_ssi_tag = len = offset = 0;
  while ((ch = fgetc(fp)) != EOF) {
    if (in_ssi_tag && ch == '>') {
      in_ssi_tag = 0;
      buf[len++] = (char) ch;
      buf[len] = '\0';
      assert(len <= (int) sizeof(buf));
      if (len < 6 || memcmp(buf, "
NameModifiedSize