diff --git a/Makefile b/Makefile index 133a1efe..392fa505 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -# +# # Copyright (c) 2013 No Face Press, LLC # License http://opensource.org/licenses/mit-license.php MIT License # @@ -24,6 +24,8 @@ DOCDIR = $(DATAROOTDIR)/doc/$(CPROG) SYSCONFDIR = $(PREFIX)/etc HTMLDIR = $(DOCDIR) +UNAME := $(shell uname) + # desired configuration of the document root # never assume that the document_root actually # exists on the build machine. When building @@ -92,7 +94,7 @@ LIB_OBJECTS = $(filter-out $(MAIN_OBJECTS), $(BUILD_OBJECTS)) LIBS = -lpthread -lm -ifeq ($(TARGET_OS),LINUX) +ifeq ($(TARGET_OS),LINUX) LIBS += -ldl endif @@ -100,6 +102,13 @@ ifeq ($(TARGET_OS),LINUX) CAN_INSTALL = 1 endif +ifneq (, $(findstring MINGW32, $(UNAME))) + LIBS += -lws2_32 -lcomdlg32 + SHARED_LIB=dll +else + SHARED_LIB=so +endif + all: build help: @@ -174,7 +183,7 @@ endif lib: lib$(CPROG).a -slib: lib$(CPROG).so +slib: lib$(CPROG).$(SHARED_LIB) clean: rm -rf $(BUILD_DIR) @@ -182,16 +191,20 @@ clean: distclean: clean @rm -rf VS2012/Debug VS2012/*/Debug VS2012/*/*/Debug @rm -rf VS2012/Release VS2012/*/Release VS2012/*/*/Release - rm -f $(CPROG) lib$(CPROG).so lib$(CPROG).a *.dmg *.msi *.exe + rm -f $(CPROG) lib$(CPROG).so lib$(CPROG).a *.dmg *.msi *.exe lib$(CPROG).dll lib$(CPROG).dll.a lib$(CPROG).a: $(LIB_OBJECTS) - @rm -f $@ + @rm -f $@ ar cq $@ $(LIB_OBJECTS) lib$(CPROG).so: CFLAGS += -fPIC lib$(CPROG).so: $(LIB_OBJECTS) $(LCC) -shared -o $@ $(CFLAGS) $(LDFLAGS) $(LIB_OBJECTS) +lib$(CPROG).dll: CFLAGS += -fPIC +lib$(CPROG).dll: $(LIB_OBJECTS) + $(LCC) -shared -o $@ $(CFLAGS) $(LDFLAGS) $(LIB_OBJECTS) $(LIBS) -Wl,--out-implib,lib$(CPROG).dll.a + $(CPROG): $(BUILD_OBJECTS) $(LCC) -o $@ $(CFLAGS) $(LDFLAGS) $(BUILD_OBJECTS) $(LIBS) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 97bb9cd9..51a03720 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -1,14 +1,24 @@ Release Notes v1.6 (Under Development) === -### Objectives: *???* +### Objectives: *Enhance Lua support, bug fixes and updates" Changes ------- +- Allow to specify title and tray icon for the Windows standalone server (bel) +- Fix minor memory leaks (bel) +- Redirect all memory allocation/deallocation through mg functions which may be overwritten (bel) +- Support Cross-Origin Resource Sharing (CORS) for static files and scripts (bel) +- Win32: Replace dll.def file by export macros in civetweb.h (CSTAJ) +- Base64 encode and decode functions for Lua (bel) +- Support pre-loaded files for the Lua environment (bel) +- Server should check the nonce for http digest access authentication (bel) +- Hide read-only flag in file dialogs opened by the Edit Settings dialog for the Windows executable (bel) +- Add all functions to dll.def, that are in the header (bel) - Added Lua extensions: send_file, get_var, get_mime_type, get_cookie, url_decode, url_encode (bel) - mg_set_request_handler() mod to use pattern (bel, Patch from Toni Wilk) - Solved, tested and documented SSL support for Windows (bel) -- Fixed: select for Linux needs the nfds parameter set correctly (bel) +- Fixed: select for Linux needs the nfds parameter set correctly (bel) - Add methods for returning the ports civetweb is listening on (keithel) - Fixes for Lua Server Pages, as described within the google groups thread. (bel) - Added support for plain Lua Scripts, and an example script. (bel) @@ -30,7 +40,7 @@ Changes - Corrected bad mask flag/opcode passing to websocket callback (William Greathouse) - Moved CEVITWEB_VERSION define into civetweb.h -- Added new simple zip deployment build for Windows. +- Added new simple zip deployment build for Windows. - Removed windows install package build. - Fixes page violation in mod_lua.inl (apkbox) - Use C style comments to enable compiling most of civetweb with -ansi. (F-Secure Corporation) @@ -79,7 +89,7 @@ Changes - Conformed source files to UNIX line endings for consistency. - Unified the coding style to improve reability. -Release Notes v1.3 +Release Notes v1.3 === ### Objectives: *Buildroot Integration* @@ -91,7 +101,7 @@ Changes - Updated documentation - Updated Buildroot config example -Release Notes v1.2 +Release Notes v1.2 === ### Objectives: *Installation Improvements, buildroot, cross compile support* The objective of this release is to make installation seamless. @@ -115,7 +125,7 @@ Known Issues - The prebuilt Window's version requires [Visual C++ Redistributable for Visual Studio 2012](http://www.microsoft.com/en-us/download/details.aspx?id=30679) -Release Notes v1.1 +Release Notes v1.1 === ### Objectives: *Build, Documentation, License Improvements* The objective of this release is to establish a maintable code base, ensure MIT license rights and improve usability and documentation. @@ -144,7 +154,7 @@ Changes + Removed yaSSL from the OSX build, not needed. - Added new Visual Studio projects for Windows builds. + Removed Windows support from Makefiles - + Provided additional, examples with Lua, and another with yaSSL. + + Provided additional, examples with Lua, and another with yaSSL. - Changed Zombie Reaping policy to not ignore SIGCHLD. + The previous method caused trouble in applciations that spawn children. @@ -154,7 +164,7 @@ Known Issues - Build support for VS6 and some other has been deprecated. + This does not impact embedded programs, just the stand-alone build. + The old Makefile was renamed to Makefile.deprecated. - + This is partcially do to lack fo testing. + + This is partcially do to lack fo testing. + Need to find out what is actually in demand. - Build changes may impact current users. + As with any change of this type, changes may impact some users. diff --git a/VS2012/civetweb_lua/civetweb_lua.vcxproj b/VS2012/civetweb_lua/civetweb_lua.vcxproj index 35b0e22a..c8a1f6b4 100644 --- a/VS2012/civetweb_lua/civetweb_lua.vcxproj +++ b/VS2012/civetweb_lua/civetweb_lua.vcxproj @@ -88,7 +88,7 @@ Level3 Disabled - LUA_COMPAT_ALL;USE_LUA;USE_LUA_SQLITE3;USE_LUA_FILE_SYSTEM;WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + LUA_COMPAT_ALL;USE_LUA;USE_LUA_SQLITE3;USE_LUA_FILE_SYSTEM;USE_WEBSOCKET;WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) $(ProjectDir)..\..\include;$(ProjectDir)..\..\src\third_party\lua-5.2.2\src;%(AdditionalIncludeDirectories) @@ -102,7 +102,7 @@ Level3 Disabled - LUA_COMPAT_ALL;USE_LUA;USE_LUA_SQLITE3;USE_LUA_FILE_SYSTEM;WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) + LUA_COMPAT_ALL;USE_LUA;USE_LUA_SQLITE3;USE_LUA_FILE_SYSTEM;USE_WEBSOCKET;WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) $(ProjectDir)..\..\include;$(ProjectDir)..\..\src\third_party\lua-5.2.2\src;%(AdditionalIncludeDirectories) @@ -118,7 +118,7 @@ MaxSpeed true true - LUA_COMPAT_ALL;USE_LUA;USE_LUA_SQLITE3;USE_LUA_FILE_SYSTEM;WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + LUA_COMPAT_ALL;USE_LUA;USE_LUA_SQLITE3;USE_LUA_FILE_SYSTEM;USE_WEBSOCKET;WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) $(ProjectDir)..\..\include;$(ProjectDir)..\..\src\third_party\lua-5.2.2\src;%(AdditionalIncludeDirectories) @@ -136,7 +136,7 @@ MaxSpeed true true - LUA_COMPAT_ALL;USE_LUA;USE_LUA_SQLITE3;USE_LUA_FILE_SYSTEM;WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) + LUA_COMPAT_ALL;USE_LUA;USE_LUA_SQLITE3;USE_LUA_FILE_SYSTEM;USE_WEBSOCKET;WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions) $(ProjectDir)..\..\include;$(ProjectDir)..\..\src\third_party\lua-5.2.2\src;%(AdditionalIncludeDirectories) diff --git a/docs/UserManual.md b/docs/UserManual.md index 56543ecb..3e188e41 100644 --- a/docs/UserManual.md +++ b/docs/UserManual.md @@ -316,6 +316,13 @@ Timeout for network read and network write operations, in milliseconds. If client intends to keep long-running connection, either increase this value or use keep-alive messages. +### lua_preload_file +This configuration option can be used to specify a Lua script file, which +is executed before the actual web page script (Lua script, Lua server page +or Lua websocket). It can be used to modify the Lua environment of all web +page scripts, e.g., by loading additional libraries required by all scripts +or to achieve backward compatibility by defining obsolete functions. + ### lua_script_pattern `"**.lua$` A pattern for files that are interpreted as Lua scripts by the server. In contrast to Lua server pages, Lua scripts use plain Lua syntax. @@ -402,11 +409,13 @@ mg (table): mg.document_root -- a string that holds the document root directory mg.auth_domain -- a string that holds the HTTP authentication domain mg.get_var(str, varname) -- extract variable from (query) string - mg.get_cookie(str, cookie) -- extract cookie from a string + mg.get_cookie(str, cookie) -- extract cookie from a string mg.get_mime_type(filename) -- get MIME type of a file mg.send_file(filename) -- send a file, including MIME type mg.url_encode(str) -- URL encode a string mg.url_decode(str) -- URL decode a string + mg.base64_encode(str) -- BASE64 encode a string + mg.base64_decode(str) -- BASE64 decode a string mg.md5(str) -- return the MD5 hash of a string mg.keep_alive(bool) -- allow/forbid to use http keep-alive for this request mg.request_info -- a table with the following request information @@ -419,7 +428,7 @@ mg (table): .query_string -- query string if present, nil otherwise .script_name -- name of the Lua script .https -- true if accessed by https://, false otherwise - .remote_user -- user name if authenticated, nil otherwise + .remote_user -- user name if authenticated, nil otherwise connect (function): -- Connect to the remote TCP server. This function is an implementation diff --git a/examples/websocket/WebSockCallbacks.c b/examples/websocket/WebSockCallbacks.c index 36cf68f4..df547e43 100644 --- a/examples/websocket/WebSockCallbacks.c +++ b/examples/websocket/WebSockCallbacks.c @@ -3,6 +3,10 @@ #include #include "WebSockCallbacks.h" +#ifdef __APPLE__ +#include +#endif + #ifdef _WIN32 #include typedef HANDLE pthread_mutex_t; @@ -73,7 +77,7 @@ void websocket_ready_handler(struct mg_connection *conn) { break; } } - printf("\nNew websocket attached: %08x:%u\n", rq->remote_ip, rq->remote_port); + printf("\nNew websocket attached: %08lx:%u\n", rq->remote_ip, rq->remote_port); pthread_mutex_unlock(&sMutex); } @@ -88,7 +92,7 @@ static void websocket_done(tWebSockInfo * wsock) { break; } } - printf("\nClose websocket attached: %08x:%u\n", mg_get_request_info(wsock->conn)->remote_ip, mg_get_request_info(wsock->conn)->remote_port); + printf("\nClose websocket attached: %08lx:%u\n", mg_get_request_info(wsock->conn)->remote_ip, mg_get_request_info(wsock->conn)->remote_port); free(wsock); } } @@ -107,7 +111,7 @@ int websocket_data_handler(struct mg_connection *conn, int flags, char *data, si pthread_mutex_unlock(&sMutex); return 1; } - if ((data_len>=5) && (data_len<100) && (flags==129) || (flags==130)) { + if (((data_len>=5) && (data_len<100) && (flags==129)) || (flags==130)) { // init command if ((wsock->webSockState==1) && (!memcmp(data,"init ",5))) { diff --git a/include/civetweb.h b/include/civetweb.h index b8be9c41..a6ca3e72 100644 --- a/include/civetweb.h +++ b/include/civetweb.h @@ -1,4 +1,5 @@ -/* Copyright (c) 2004-2013 Sergey Lyubka +/* Copyright (c) 2013-2014 the Civetweb developers + * Copyright (c) 2004-2013 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 @@ -26,6 +27,20 @@ #define CIVETWEB_VERSION "1.6" #endif +#ifndef CIVETWEB_API + #if defined(_WIN32) + #if defined(CIVETWEB_DLL_EXPORTS) + #define CIVETWEB_API __declspec(dllexport) + #elif defined(CIVETWEB_DLL_IMPORTS) + #define CIVETWEB_API __declspec(dllimport) + #else + #define CIVETWEB_API + #endif + #else + #define CIVETWEB_API + #endif +#endif + #include #include @@ -140,6 +155,7 @@ struct mg_callbacks { int (*http_error)(struct mg_connection *, int status); }; + /* Start web server. Parameters: @@ -165,7 +181,7 @@ struct mg_callbacks { Return: web server context, or NULL on error. */ -struct mg_context *mg_start(const struct mg_callbacks *callbacks, +CIVETWEB_API struct mg_context *mg_start(const struct mg_callbacks *callbacks, void *user_data, const char **configuration_options); @@ -175,7 +191,8 @@ struct mg_context *mg_start(const struct mg_callbacks *callbacks, Must be called last, when an application wants to stop the web server and release all associated resources. This function blocks until all Civetweb threads are stopped. Context pointer becomes invalid. */ -void mg_stop(struct mg_context *); +CIVETWEB_API void mg_stop(struct mg_context *); + /* mg_request_handler @@ -190,6 +207,7 @@ void mg_stop(struct mg_context *); 1: the handler processed the request. */ typedef int (* mg_request_handler)(struct mg_connection *conn, void *cbdata); + /* mg_set_request_handler Sets or removes a URI mapping for a request handler. @@ -206,7 +224,7 @@ typedef int (* mg_request_handler)(struct mg_connection *conn, void *cbdata); handler: the callback handler to use when the URI is requested. If NULL, the URI will be removed. cbdata: the callback data to give to the handler when it s requested. */ -void mg_set_request_handler(struct mg_context *ctx, const char *uri, mg_request_handler handler, void *cbdata); +CIVETWEB_API void mg_set_request_handler(struct mg_context *ctx, const char *uri, mg_request_handler handler, void *cbdata); /* Get the value of particular configuration parameter. @@ -215,14 +233,41 @@ void mg_set_request_handler(struct mg_context *ctx, const char *uri, mg_request_ 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); +CIVETWEB_API const char *mg_get_option(const struct mg_context *ctx, const char *name); +#if defined(MG_LEGACY_INTERFACE) /* Return array of strings that represent valid configuration options. For each option, option name and default value is returned, i.e. the number of entries in the array equals to number_of_options x 2. Array is NULL terminated. */ -const char **mg_get_valid_option_names(void); +/* Deprecated: Use mg_get_valid_options instead. */ +CIVETWEB_API const char **mg_get_valid_option_names(void); +#endif + + +struct mg_option { + const char * name; + int type; + const char * default_value; +}; + +enum { + CONFIG_TYPE_UNKNOWN = 0x0, + CONFIG_TYPE_NUMBER = 0x1, + CONFIG_TYPE_STRING = 0x2, + CONFIG_TYPE_FILE = 0x3, + CONFIG_TYPE_DIRECTORY = 0x4, + CONFIG_TYPE_BOOLEAN = 0x5, + CONFIG_TYPE_EXT_PATTERN = 0x6 +}; + + +/* Return array of struct mg_option, representing all valid configuration + options of civetweb.c. + The array is terminated by a NULL name option. */ +CIVETWEB_API const struct mg_option *mg_get_valid_options(void); + /* Get the list of ports that civetweb is listening on. size is the size of the ports int array and ssl int array to fill. @@ -231,7 +276,8 @@ const char **mg_get_valid_option_names(void); Return value is the number of ports and ssl information filled in. The value returned is read-only. Civetweb does not allow changing configuration at run time. */ -size_t mg_get_ports(const struct mg_context *ctx, size_t size, int* ports, int* ssl); +CIVETWEB_API size_t mg_get_ports(const struct mg_context *ctx, size_t size, int* ports, int* ssl); + /* Add, edit or delete the entry in the passwords file. @@ -245,14 +291,14 @@ size_t mg_get_ports(const struct mg_context *ctx, size_t size, int* ports, int* 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); +CIVETWEB_API int mg_modify_passwords_file(const char *passwords_file_name, + const char *domain, + const char *user, + const char *password); /* Return information associated with the request. */ -struct mg_request_info *mg_get_request_info(struct mg_connection *); +CIVETWEB_API struct mg_request_info *mg_get_request_info(struct mg_connection *); /* Send data to the client. @@ -260,7 +306,7 @@ struct mg_request_info *mg_get_request_info(struct mg_connection *); 0 when the connection has been closed -1 on error >0 number of bytes written on success */ -int mg_write(struct mg_connection *, const void *buf, size_t len); +CIVETWEB_API int mg_write(struct mg_connection *, const void *buf, size_t len); /* Send data to a websocket client wrapped in a websocket frame. Uses mg_lock @@ -275,16 +321,18 @@ int mg_write(struct mg_connection *, const void *buf, size_t len); 0 when the connection has been closed -1 on error >0 number of bytes written on success */ -int mg_websocket_write(struct mg_connection* conn, int opcode, - const char *data, size_t data_len); +CIVETWEB_API int mg_websocket_write(struct mg_connection* conn, int opcode, + const char *data, size_t data_len); + /* Blocks until unique access is obtained to this connection. Intended for use with websockets only. Invoke this before mg_write or mg_printf when communicating with a websocket if your code has server-initiated communication as well as communication in direct response to a message. */ -void mg_lock(struct mg_connection* conn); -void mg_unlock(struct mg_connection* conn); +CIVETWEB_API void mg_lock(struct mg_connection* conn); +CIVETWEB_API void mg_unlock(struct mg_connection* conn); + /* Opcodes, from http://tools.ietf.org/html/rfc6455 */ enum { @@ -317,14 +365,13 @@ enum { #endif /* Send data to the client using printf() semantics. - Works exactly like mg_write(), but allows to do message formatting. */ -int mg_printf(struct mg_connection *, - PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3); +CIVETWEB_API 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); +CIVETWEB_API void mg_send_file(struct mg_connection *conn, const char *path); /* Read data from the remote end, return number of bytes read. @@ -332,7 +379,7 @@ void mg_send_file(struct mg_connection *conn, const char *path); 0 connection has been closed by peer. No more data could be read. < 0 read error. No more data could be read from the connection. > 0 number of bytes read into the buffer. */ -int mg_read(struct mg_connection *, void *buf, size_t len); +CIVETWEB_API int mg_read(struct mg_connection *, void *buf, size_t len); /* Get the value of particular HTTP header. @@ -340,7 +387,7 @@ int mg_read(struct mg_connection *, void *buf, size_t len); 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); +CIVETWEB_API const char *mg_get_header(const struct mg_connection *, const char *name); /* Get a value of particular form variable. @@ -362,8 +409,9 @@ const char *mg_get_header(const struct mg_connection *, const char *name); Destination buffer is guaranteed to be '\0' - terminated if it is not NULL or zero length. */ -int mg_get_var(const char *data, size_t data_len, - const char *var_name, char *dst, size_t dst_len); +CIVETWEB_API int mg_get_var(const char *data, size_t data_len, + const char *var_name, char *dst, size_t dst_len); + /* Get a value of particular form variable. @@ -388,8 +436,9 @@ int mg_get_var(const char *data, size_t data_len, Destination buffer is guaranteed to be '\0' - terminated if it is not NULL or zero length. */ -int mg_get_var2(const char *data, size_t data_len, - const char *var_name, char *dst, size_t dst_len, size_t occurrence); +CIVETWEB_API int mg_get_var2(const char *data, size_t data_len, + const char *var_name, char *dst, size_t dst_len, size_t occurrence); + /* Fetch value of certain cookie variable into the destination buffer. @@ -404,8 +453,8 @@ int mg_get_var2(const char *data, size_t data_len, parameter is not found). -2 (destination buffer is NULL, zero length or too small to hold the value). */ -int mg_get_cookie(const char *cookie, const char *var_name, - char *buf, size_t buf_len); +CIVETWEB_API int mg_get_cookie(const char *cookie, const char *var_name, + char *buf, size_t buf_len); /* Download data from the remote web server. @@ -423,35 +472,36 @@ int mg_get_cookie(const char *cookie, const char *var_name, conn = mg_download("google.com", 80, 0, ebuf, sizeof(ebuf), "%s", "GET / HTTP/1.0\r\nHost: google.com\r\n\r\n"); */ -struct mg_connection *mg_download(const char *host, int port, int use_ssl, - char *error_buffer, size_t error_buffer_size, - PRINTF_FORMAT_STRING(const char *request_fmt), - ...) PRINTF_ARGS(6, 7); +CIVETWEB_API struct mg_connection *mg_download(const char *host, int port, int use_ssl, + char *error_buffer, size_t error_buffer_size, + PRINTF_FORMAT_STRING(const char *request_fmt), + ...) PRINTF_ARGS(6, 7); /* Close the connection opened by mg_download(). */ -void mg_close_connection(struct mg_connection *conn); +CIVETWEB_API void mg_close_connection(struct mg_connection *conn); /* File upload functionality. Each uploaded file gets saved into a temporary file and MG_UPLOAD event is sent. Return number of uploaded files. */ -int mg_upload(struct mg_connection *conn, const char *destination_dir); +CIVETWEB_API int mg_upload(struct mg_connection *conn, const char *destination_dir); /* 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); +CIVETWEB_API 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); +CIVETWEB_API const char *mg_get_builtin_mime_type(const char *file_name); /* Return Civetweb version. */ -const char *mg_version(void); +CIVETWEB_API const char *mg_version(void); + /* URL-decode input buffer into destination buffer. 0-terminate the destination buffer. @@ -459,13 +509,15 @@ const char *mg_version(void); uses '+' as character for space, see RFC 1866 section 8.2.1 http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt Return: length of the decoded data, or -1 if dst buffer is too small. */ -int mg_url_decode(const char *src, int src_len, char *dst, - int dst_len, int is_form_url_encoded); +CIVETWEB_API int mg_url_decode(const char *src, int src_len, char *dst, + int dst_len, int is_form_url_encoded); + /* URL-encode input buffer into destination buffer. returns the length of the resulting buffer or -1 is the buffer is too small. */ -int mg_url_encode(const char *src, char *dst, size_t dst_len); +CIVETWEB_API int mg_url_encode(const char *src, char *dst, size_t dst_len); + /* MD5 hash given strings. Buffer 'buf' must be 33 bytes long. Varargs is a NULL terminated list of @@ -473,7 +525,7 @@ int mg_url_encode(const char *src, char *dst, size_t dst_len); MD5 hash. Example: char buf[33]; mg_md5(buf, "aa", "bb", NULL); */ -char *mg_md5(char buf[33], ...); +CIVETWEB_API char *mg_md5(char buf[33], ...); /* Print error message to the opened error log stream. @@ -483,11 +535,13 @@ char *mg_md5(char buf[33], ...); ...: variable argument list Example: mg_cry(conn,"i like %s", "logging"); */ -void mg_cry(struct mg_connection *conn, - PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3); +CIVETWEB_API void mg_cry(struct mg_connection *conn, + PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3); + /* utility method to compare two buffers, case incensitive. */ -int mg_strncasecmp(const char *s1, const char *s2, size_t len); +CIVETWEB_API int mg_strncasecmp(const char *s1, const char *s2, size_t len); + #ifdef __cplusplus } diff --git a/resources/dll.def b/resources/dll.def deleted file mode 100644 index afd53118..00000000 --- a/resources/dll.def +++ /dev/null @@ -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 diff --git a/src/CivetServer.cpp b/src/CivetServer.cpp index fc5a5700..70a414da 100644 --- a/src/CivetServer.cpp +++ b/src/CivetServer.cpp @@ -150,8 +150,19 @@ bool CivetServer::getParam(struct mg_connection *conn, const char *name, std::string &dst, size_t occurrence) { - const char *query = mg_get_request_info(conn)->query_string; - return getParam(query, strlen(query), name, dst, occurrence); + const char *formParams = NULL; + mg_request_info * ri = mg_get_request_info(conn); + + if (ri) { + // get requests do store html
field values in the http query_string + formParams = ri->query_string; + } + + if (formParams) { + return getParam(formParams, strlen(formParams), name, dst, occurrence); + } + + return false; } bool diff --git a/src/civetweb.c b/src/civetweb.c index 49b184fa..b681f460 100644 --- a/src/civetweb.c +++ b/src/civetweb.c @@ -1,4 +1,5 @@ -/* Copyright (c) 2004-2013 Sergey Lyubka +/* Copyright (c) 2013-2014 the Civetweb developers + * Copyright (c) 2004-2013 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 @@ -27,10 +28,19 @@ #ifdef __linux__ #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */ #endif -#define _LARGEFILE_SOURCE /* Enable 64-bit file offsets */ +#ifndef _LARGEFILE_SOURCE +#define _LARGEFILE_SOURCE /* For fseeko(), ftello() */ +#endif +#ifndef _FILE_OFFSET_BITS +#define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */ +#endif +#ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS /* wants this for C++ */ +#endif +#ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */ #endif +#endif #if defined (_MSC_VER) /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */ @@ -43,7 +53,7 @@ /* Disable WIN32_LEAN_AND_MEAN. This makes windows.h always include winsock2.h */ -#if defined(WIN32_LEAN_AND_MEAN) && (_MSC_VER <= 1400) +#if defined(WIN32_LEAN_AND_MEAN) #undef WIN32_LEAN_AND_MEAN #endif @@ -79,7 +89,9 @@ #include #include +#ifndef MAX_WORKER_THREADS #define MAX_WORKER_THREADS 1024 +#endif #if defined(_WIN32) && !defined(__SYMBIAN32__) /* Windows specific */ #if defined(_MSC_VER) && _MSC_VER <= 1400 @@ -186,14 +198,22 @@ typedef struct { pthread_t *waitingthreadhdls; /* The thread handles. */ } pthread_cond_t; +#ifndef __clockid_t_defined typedef DWORD clockid_t; +#endif +#ifndef CLOCK_MONOTONIC #define CLOCK_MONOTONIC (1) +#endif +#ifndef CLOCK_REALTIME #define CLOCK_REALTIME (2) +#endif +#ifndef _TIMESPEC_DEFINED struct timespec { time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; +#endif #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */ @@ -247,10 +267,15 @@ struct pollfd { #include #include #include +#include #include #include #include +#if defined(ANDROID) +typedef unsigned short int in_port_t; +#endif + #include #include #include @@ -295,6 +320,145 @@ typedef int SOCKET; #endif #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0])) +#ifdef DEBUG_TRACE +#undef DEBUG_TRACE +#define DEBUG_TRACE(x) +#else +#if defined(DEBUG) +#define DEBUG_TRACE(x) do { \ + flockfile(stdout); \ + printf("*** %lu.%p.%s.%d: ", \ + (unsigned long) time(NULL), (void *) pthread_self(), \ + __func__, __LINE__); \ + printf x; \ + putchar('\n'); \ + fflush(stdout); \ + funlockfile(stdout); \ +} while (0) +#else +#define DEBUG_TRACE(x) +#endif /* DEBUG */ +#endif /* DEBUG_TRACE */ + +#if defined(MEMORY_DEBUGGING) +static unsigned long blockCount = 0; +static unsigned long totalMemUsed = 0; + +static void * mg_malloc_ex(size_t size, const char * file, unsigned line) { + + void * data = malloc(size + sizeof(size_t)); + void * memory = 0; + char mallocStr[256]; + + if (data) { + *(size_t*)data = size; + totalMemUsed += size; + blockCount++; + memory = (void *)(((char*)data)+sizeof(size_t)); + } + + sprintf(mallocStr, "MEM: %p %5u alloc %7u %4u --- %s:%u\n", memory, size, totalMemUsed, blockCount, file, line); +#if defined(_WIN32) + OutputDebugStringA(mallocStr); +#else + DEBUG_TRACE("%s", mallocStr); +#endif + + return memory; +} + +static void * mg_calloc_ex(size_t count, size_t size, const char * file, unsigned line) { + + void * data = mg_malloc_ex(size*count, file, line); + if (data) memset(data, 0, size); + + return data; +} + +static void mg_free_ex(void * memory, const char * file, unsigned line) { + + char mallocStr[256]; + void * data = (void *)(((char*)memory)-sizeof(size_t)); + size_t size; + + if (memory) { + size = *(size_t*)data; + totalMemUsed -= size; + blockCount--; + sprintf(mallocStr, "MEM: %p %5u free %7u %4u --- %s:%u\n", memory, size, totalMemUsed, blockCount, file, line); +#if defined(_WIN32) + OutputDebugStringA(mallocStr); +#else + DEBUG_TRACE("%s", mallocStr); +#endif + + free(data); + } +} + +static void * mg_realloc_ex(void * memory, size_t newsize, const char * file, unsigned line) { + + char mallocStr[256]; + void * data; + size_t oldsize; + + if (newsize) { + if (memory) { + data = (void *)(((char*)memory)-sizeof(size_t)); + oldsize = *(size_t*)data; + data = realloc(data, newsize+sizeof(size_t)); + if (data) { + totalMemUsed -= oldsize; + sprintf(mallocStr, "MEM: %p %5u r-free %7u %4u --- %s:%u\n", memory, oldsize, totalMemUsed, blockCount, file, line); +#if defined(_WIN32) + OutputDebugStringA(mallocStr); +#else + DEBUG_TRACE("%s", mallocStr); +#endif + totalMemUsed += newsize; + sprintf(mallocStr, "MEM: %p %5u r-alloc %7u %4u --- %s:%u\n", memory, newsize, totalMemUsed, blockCount, file, line); +#if defined(_WIN32) + OutputDebugStringA(mallocStr); +#else + DEBUG_TRACE("%s", mallocStr); +#endif + *(size_t*)data = newsize; + data = (void *)(((char*)data)+sizeof(size_t)); + } else { +#if defined(_WIN32) + OutputDebugStringA("MEM: realloc failed\n"); +#else + DEBUG_TRACE("MEM: realloc failed\n"); +#endif + } + } else { + data = mg_malloc_ex(newsize, file, line); + } + } else { + data = 0; + mg_free_ex(memory, file, line); + } + + return data; +} + +#define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__) +#define mg_calloc(a,b) mg_calloc_ex(a, b, __FILE__, __LINE__) +#define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__) +#define mg_free(a) mg_free_ex(a, __FILE__, __LINE__) + +#else +static __inline void * mg_malloc(size_t a) {return malloc(a);} +static __inline void * mg_calloc(size_t a, size_t b) {return calloc(a, b);} +static __inline void * mg_realloc(void * a, size_t b) {return realloc(a, b);} +static __inline void mg_free(void * a) {free(a);} +#endif + +#define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc +#define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc +#define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc +#define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free + #ifdef _WIN32 static CRITICAL_SECTION global_log_file_lock; static DWORD pthread_self(void) @@ -331,26 +495,6 @@ void *pthread_getspecific(pthread_key_t key) #define MD5_STATIC static #include "md5.inl" -#ifdef DEBUG_TRACE -#undef DEBUG_TRACE -#define DEBUG_TRACE(x) -#else -#if defined(DEBUG) -#define DEBUG_TRACE(x) do { \ - flockfile(stdout); \ - printf("*** %lu.%p.%s.%d: ", \ - (unsigned long) time(NULL), (void *) pthread_self(), \ - __func__, __LINE__); \ - printf x; \ - putchar('\n'); \ - fflush(stdout); \ - funlockfile(stdout); \ -} while (0) -#else -#define DEBUG_TRACE(x) -#endif /* DEBUG */ -#endif /* DEBUG_TRACE */ - /* Darwin prior to 7.0 and Win32 do not have socklen_t */ #ifdef NO_SOCKLEN_T typedef int socklen_t; @@ -526,7 +670,7 @@ enum { NUM_THREADS, RUN_AS_USER, REWRITE, HIDE_FILES, REQUEST_TIMEOUT, #if defined(USE_LUA) - LUA_SCRIPT_EXTENSIONS, LUA_SERVER_PAGE_EXTENSIONS, + LUA_PRELOAD_FILE, LUA_SCRIPT_EXTENSIONS, LUA_SERVER_PAGE_EXTENSIONS, #endif #if defined(USE_WEBSOCKET) WEBSOCKET_ROOT, @@ -534,53 +678,57 @@ enum { #if defined(USE_LUA) && defined(USE_WEBSOCKET) LUA_WEBSOCKET_EXTENSIONS, #endif + ACCESS_CONTROL_ALLOW_ORIGIN, NUM_OPTIONS }; -static const char *config_options[] = { - "cgi_pattern", "**.cgi$|**.pl$|**.php$", - "cgi_environment", NULL, - "put_delete_auth_file", NULL, - "cgi_interpreter", NULL, - "protect_uri", NULL, - "authentication_domain", "mydomain.com", - "ssi_pattern", "**.shtml$|**.shtm$", - "throttle", NULL, - "access_log_file", NULL, - "enable_directory_listing", "yes", - "error_log_file", NULL, - "global_auth_file", NULL, - "index_files", +/* TODO: replace 12345 by proper config types */ +static struct mg_option config_options[] = { + {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"}, + {"cgi_environment", CONFIG_TYPE_STRING, NULL}, + {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL}, + {"cgi_interpreter", CONFIG_TYPE_FILE, NULL}, + {"protect_uri", 12345, NULL}, + {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"}, + {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"}, + {"throttle", 12345, NULL}, + {"access_log_file", CONFIG_TYPE_FILE, NULL}, + {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"}, + {"error_log_file", CONFIG_TYPE_FILE, NULL}, + {"global_auth_file", CONFIG_TYPE_FILE, NULL}, + {"index_files", 12345, #ifdef USE_LUA - "index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,index.shtml,index.php", + "index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,index.shtml,index.php"}, #else - "index.html,index.htm,index.cgi,index.shtml,index.php", + "index.html,index.htm,index.cgi,index.shtml,index.php"}, #endif - "enable_keep_alive", "no", - "access_control_list", NULL, - "extra_mime_types", NULL, - "listening_ports", "8080", - "document_root", NULL, - "ssl_certificate", NULL, - "num_threads", "50", - "run_as_user", NULL, - "url_rewrite_patterns", NULL, - "hide_files_patterns", NULL, - "request_timeout_ms", "30000", + {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"}, + {"access_control_list", 12345, NULL}, + {"extra_mime_types", 12345, NULL}, + {"listening_ports", 12345, "8080"}, + {"document_root", CONFIG_TYPE_DIRECTORY, NULL}, + {"ssl_certificate", CONFIG_TYPE_FILE, NULL}, + {"num_threads", CONFIG_TYPE_NUMBER, "50"}, + {"run_as_user", CONFIG_TYPE_STRING, NULL}, + {"url_rewrite_patterns", 12345, NULL}, + {"hide_files_patterns", 12345, NULL}, + {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"}, #if defined(USE_LUA) - "lua_script_pattern", "**.lua$", - "lua_server_page_pattern", "**.lp$|**.lsp$", + {"lua_preload_file", CONFIG_TYPE_FILE, NULL}, + {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"}, + {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"}, #endif #if defined(USE_WEBSOCKET) - "websocket_root", NULL, + {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL}, #endif #if defined(USE_LUA) && defined(USE_WEBSOCKET) - "lua_websocket_pattern", "**.lua$", + {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"}, #endif + {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"}, - NULL + {NULL, CONFIG_TYPE_UNKNOWN, NULL} }; struct mg_request_handler_info { @@ -617,8 +765,18 @@ struct mg_context { int workerthreadcount; /* The amount of worker threads. */ pthread_t *workerthreadids;/* The worker thread IDs. */ + unsigned long start_time; /* Server start time, used for authentication */ + unsigned long nonce_count; /* Used nonces, used for authentication */ + + char *systemName; /* What operating system is running */ + /* linked list of uri handlers */ struct mg_request_handler_info *request_handlers; + +#if defined(USE_LUA) && defined(USE_WEBSOCKET) + /* linked list of shared lua websockets */ + struct mg_shared_lua_websocket *shared_lua_websockets; +#endif }; struct mg_connection { @@ -670,11 +828,27 @@ struct de { static int is_websocket_request(const struct mg_connection *conn); #endif +#if defined(MG_LEGACY_INTERFACE) const char **mg_get_valid_option_names(void) +{ + static const char * data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0}; + int i; + + for (i=0; config_options[i].name != NULL; i++) { + data[i * 2] = config_options[i].name; + data[i * 2 + 1] = config_options[i].default_value; + } + + return data; +} +#endif + +const struct mg_option *mg_get_valid_options(void) { return config_options; } + static int is_file_in_memory(struct mg_connection *conn, const char *path, struct file *filep) { @@ -721,8 +895,8 @@ static int get_option_index(const char *name) { int i; - for (i = 0; config_options[i * 2] != NULL; i++) { - if (strcmp(config_options[i * 2], name) == 0) { + for (i = 0; config_options[i].name != NULL; i++) { + if (strcmp(config_options[i].name, name) == 0) { return i; } } @@ -882,7 +1056,7 @@ static char * mg_strndup(const char *ptr, size_t len) { char *p; - if ((p = (char *) malloc(len + 1)) != NULL) { + if ((p = (char *) mg_malloc(len + 1)) != NULL) { mg_strlcpy(p, ptr, len + 1); } @@ -1192,6 +1366,7 @@ static int pthread_mutex_unlock(pthread_mutex_t *mutex) return ReleaseMutex(*mutex) == 0 ? -1 : 0; } +#ifndef WIN_PTHREADS_TIME_H static int clock_gettime(clockid_t clk_id, struct timespec *tp) { FILETIME ft; @@ -1227,13 +1402,14 @@ static int clock_gettime(clockid_t clk_id, struct timespec *tp) return ok ? 0 : -1; } +#endif static int pthread_cond_init(pthread_cond_t *cv, const void *unused) { (void) unused; InitializeCriticalSection(&cv->threadIdSec); cv->waitingthreadcount = 0; - cv->waitingthreadhdls = calloc(MAX_WORKER_THREADS, sizeof(pthread_t)); + cv->waitingthreadhdls = mg_calloc(MAX_WORKER_THREADS, sizeof(pthread_t)); return (cv->waitingthreadhdls!=NULL) ? 0 : -1; } @@ -1312,8 +1488,8 @@ static int pthread_cond_destroy(pthread_cond_t *cv) { EnterCriticalSection(&cv->threadIdSec); assert(cv->waitingthreadcount==0); + mg_free(cv->waitingthreadhdls); cv->waitingthreadhdls = 0; - free(cv->waitingthreadhdls); LeaveCriticalSection(&cv->threadIdSec); DeleteCriticalSection(&cv->threadIdSec); @@ -1484,7 +1660,7 @@ static DIR * opendir(const char *name) if (name == NULL) { SetLastError(ERROR_BAD_ARGUMENTS); - } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) { + } else if ((dir = (DIR *) mg_malloc(sizeof(*dir))) == NULL) { SetLastError(ERROR_NOT_ENOUGH_MEMORY); } else { to_unicode(name, wpath, ARRAY_SIZE(wpath)); @@ -1495,7 +1671,7 @@ static DIR * opendir(const char *name) dir->handle = FindFirstFileW(wpath, &dir->info); dir->result.d_name[0] = '\0'; } else { - free(dir); + mg_free(dir); dir = NULL; } } @@ -1511,7 +1687,7 @@ static int closedir(DIR *dir) if (dir->handle != INVALID_HANDLE_VALUE) result = FindClose(dir->handle) ? 0 : -1; - free(dir); + mg_free(dir); } else { result = -1; SetLastError(ERROR_BAD_ARGUMENTS); @@ -1589,9 +1765,9 @@ int mg_start_thread(mg_thread_func_t f, void *p) { #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384 */ - return (long)_beginthread((void (__cdecl *)(void *)) f, USE_STACK_SIZE, p) == -1L ? -1 : 0; + return ((_beginthread((void (__cdecl *)(void *)) f, USE_STACK_SIZE, p) == ((uintptr_t)(-1L))) ? -1 : 0); #else - return (long)_beginthread((void (__cdecl *)(void *)) f, 0, p) == -1L ? -1 : 0; + return ((_beginthread((void (__cdecl *)(void *)) f, 0, p) == ((uintptr_t)(-1L))) ? -1 : 0); #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */ } @@ -1602,15 +1778,15 @@ static int mg_start_thread_with_id(unsigned (__stdcall *f)(void *), void *p, { uintptr_t uip; HANDLE threadhandle; - int result; + int result = 0; uip = _beginthreadex(NULL, 0, (unsigned (__stdcall *)(void *)) f, p, 0, NULL); threadhandle = (HANDLE) uip; - if (threadidptr != NULL) { + if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) { *threadidptr = threadhandle; + result = 1; } - result = (threadhandle == NULL) ? -1 : 0; return result; } @@ -2071,8 +2247,8 @@ static int alloc_vprintf2(char **buf, const char *fmt, va_list ap) *buf = NULL; while (len == -1) { - if (*buf) free(*buf); - *buf = (char *)malloc(size *= 4); + if (*buf) mg_free(*buf); + *buf = (char *)mg_malloc(size *= 4); if (!*buf) break; va_copy(ap_copy, ap); len = vsnprintf(*buf, size, fmt, ap_copy); @@ -2109,7 +2285,7 @@ static int alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap) va_end(ap_copy); } else if (len > (int) size && (size = len + 1) > 0 && - (*buf = (char *) malloc(size)) == NULL) { + (*buf = (char *) mg_malloc(size)) == NULL) { len = -1; /* Allocation failed, mark failure */ } else { va_copy(ap_copy, ap); @@ -2131,7 +2307,7 @@ int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap) len = mg_write(conn, buf, (size_t) len); } if (buf != mem && buf != NULL) { - free(buf); + mg_free(buf); } return len; @@ -2270,6 +2446,75 @@ int mg_get_cookie(const char *cookie_header, const char *var_name, return len; } +#if defined(USE_WEBSOCKET) || defined(USE_LUA) +static void base64_encode(const unsigned char *src, int src_len, char *dst) +{ + static const char *b64 = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + int i, j, a, b, c; + + for (i = j = 0; i < src_len; i += 3) { + a = src[i]; + b = i + 1 >= src_len ? 0 : src[i + 1]; + c = i + 2 >= src_len ? 0 : src[i + 2]; + + dst[j++] = b64[a >> 2]; + dst[j++] = b64[((a & 3) << 4) | (b >> 4)]; + if (i + 1 < src_len) { + dst[j++] = b64[(b & 15) << 2 | (c >> 6)]; + } + if (i + 2 < src_len) { + dst[j++] = b64[c & 63]; + } + } + while (j % 4 != 0) { + dst[j++] = '='; + } + dst[j++] = '\0'; +} + +static unsigned char b64reverse(char letter) { + if (letter>='A' && letter<='Z') return letter-'A'; + if (letter>='a' && letter<='z') return letter-'a'+26; + if (letter>='0' && letter<='9') return letter-'0'+52; + if (letter=='+') return 62; + if (letter=='/') return 63; + if (letter=='=') return 255; /* normal end */ + return 254; /* error */ +} + +static int base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len) +{ + int i; + unsigned char a, b, c, d; + + *dst_len = 0; + + for (i = 0; i < src_len; i += 4) { + a = b64reverse(src[i]); + if (a>=254) return i; + + b = b64reverse(i + 1 >= src_len ? 0 : src[i + 1]); + if (b>=254) return i+1; + + c = b64reverse(i + 2 >= src_len ? 0 : src[i + 2]); + if (c==254) return i+2; + + d = b64reverse(i + 3 >= src_len ? 0 : src[i + 3]); + if (c==254) return i+3; + + dst[(*dst_len)++] = (a << 2) + (b >> 4); + if (c!=255) { + dst[(*dst_len)++] = (b << 4) + (c >> 2); + if (d!=255) { + dst[(*dst_len)++] = (c << 6) + d; + } + } + } + return -1; +} +#endif + static void convert_uri_to_file_name(struct mg_connection *conn, char *buf, size_t buf_len, struct file *filep, int * is_script_ressource) @@ -2704,6 +2949,7 @@ static int parse_auth_header(struct mg_connection *conn, char *buf, { char *name, *value, *s; const char *auth_header; + unsigned long nonce; (void) memset(ah, 0, sizeof(*ah)); if ((auth_header = mg_get_header(conn, "Authorization")) == NULL || @@ -2754,6 +3000,24 @@ static int parse_auth_header(struct mg_connection *conn, char *buf, } } +#ifndef NO_NONCE_CHECK + /* Convert the nonce from the client to a number and check it. */ + /* Server side nonce check is valuable in all situations but one: if the server restarts frequently, + but the client should not see that, so the server should accept nonces from previous starts. */ + nonce = strtoul(ah->nonce, &s, 10); + if ((s == NULL) || (*s != 0)) { + return 0; + } + nonce ^= (unsigned long)(conn->ctx); + if (noncectx->start_time) { + /* nonce is from a previous start of the server and no longer valid (replay attack?) */ + return 0; + } + if (nonce>=conn->ctx->start_time+conn->ctx->nonce_count) { + return 0; + } +#endif + /* CGI needs it as REMOTE_USER */ if (ah->user != NULL) { conn->request_info.remote_user = mg_strdup(ah->user); @@ -2855,7 +3119,14 @@ static void send_authorization_request(struct mg_connection *conn) { char date[64]; time_t curtime = time(NULL); + unsigned long nonce = (unsigned long)(conn->ctx->start_time); + (void)pthread_mutex_lock(&conn->ctx->mutex); + nonce += conn->ctx->nonce_count; + ++conn->ctx->nonce_count; + (void)pthread_mutex_unlock(&conn->ctx->mutex); + + nonce ^= (unsigned long)(conn->ctx); conn->status_code = 401; conn->must_close = 1; @@ -2869,7 +3140,7 @@ static void send_authorization_request(struct mg_connection *conn) "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", nonce=\"%lu\"\r\n\r\n", date, suggest_connection_header(conn), conn->ctx->config[AUTHENTICATION_DOMAIN], - (unsigned long) time(NULL)); + nonce); } static int is_authorized_for_put(struct mg_connection *conn) @@ -3185,9 +3456,9 @@ struct dir_scan_data { /* Behaves like realloc(), but frees original pointer on failure */ static void *realloc2(void *ptr, size_t size) { - void *new_ptr = realloc(ptr, size); + void *new_ptr = mg_realloc(ptr, size); if (new_ptr == NULL) { - free(ptr); + mg_free(ptr); } return new_ptr; } @@ -3261,9 +3532,9 @@ static void handle_directory_request(struct mg_connection *conn, sizeof(data.entries[0]), compare_dir_entries); for (i = 0; i < data.num_entries; i++) { print_dir_entry(&data.entries[i]); - free(data.entries[i].file_name); + mg_free(data.entries[i].file_name); } - free(data.entries); + mg_free(data.entries); } conn->num_bytes_sent += mg_printf(conn, "%s", ""); @@ -3350,7 +3621,8 @@ static void handle_file_request(struct mg_connection *conn, const char *path, struct vec mime_vec; int n; char gz_path[PATH_MAX]; - char const* encoding = ""; + const char *encoding = ""; + const char *cors1, *cors2, *cors3; get_mime_type(conn->ctx, path, &mime_vec); cl = filep->size; @@ -3387,7 +3659,7 @@ static void handle_file_request(struct mg_connection *conn, const char *path, return; } conn->status_code = 206; -cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1: cl - r1; + cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1: cl - r1; mg_snprintf(conn, range, sizeof(range), "Content-Range: bytes " "%" INT64_FMT "-%" @@ -3396,6 +3668,17 @@ cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1: cl - r1; msg = "Partial Content"; } + hdr = mg_get_header(conn, "Origin"); + if (hdr) { + /* Cross-origin resource sharing (CORS), see http://www.html5rocks.com/en/tutorials/cors/, + http://www.html5rocks.com/static/images/cors_server_flowchart.png - preflight is not supported for files. */ + cors1 = "Access-Control-Allow-Origin: "; + cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN]; + cors3 = "\r\n"; + } else { + cors1 = cors2 = cors3 = ""; + } + /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */ gmt_time_string(date, sizeof(date), &curtime); @@ -3404,6 +3687,7 @@ cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1: cl - r1; (void) mg_printf(conn, "HTTP/1.1 %d %s\r\n" + "%s%s%s" "Date: %s\r\n" "Last-Modified: %s\r\n" "Etag: %s\r\n" @@ -3412,7 +3696,9 @@ cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1: cl - r1; "Connection: %s\r\n" "Accept-Ranges: bytes\r\n" "%s%s\r\n", - conn->status_code, msg, date, lm, etag, (int) mime_vec.len, + conn->status_code, msg, + cors1, cors2, cors3, + date, lm, etag, (int) mime_vec.len, mime_vec.ptr, cl, suggest_connection_header(conn), range, encoding); if (strcmp(conn->request_info.request_method, "HEAD") != 0) { @@ -3888,7 +4174,7 @@ static void handle_cgi_request(struct mg_connection *conn, const char *prog) Do not send anything back to client, until we buffer in all HTTP headers. */ data_len = 0; - buf = malloc(buflen); + buf = mg_malloc(buflen); if (buf == NULL) { send_http_error(conn, 500, http_500_error, "Not enough memory for buffer (%u bytes)", @@ -3971,7 +4257,7 @@ done: close(fdout[0]); } if (buf != NULL) { - free(buf); + mg_free(buf); } } #endif /* !NO_CGI */ @@ -4247,6 +4533,16 @@ static void handle_ssi_file_request(struct mg_connection *conn, struct file file = STRUCT_FILE_INITIALIZER; char date[64]; time_t curtime = time(NULL); + const char *cors1, *cors2, *cors3; + + if (mg_get_header(conn, "Origin")) { + /* Cross-origin resource sharing (CORS). */ + cors1 = "Access-Control-Allow-Origin: "; + cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN]; + cors3 = "\r\n"; + } else { + cors1 = cors2 = cors3 = ""; + } if (!mg_fopen(conn, path, "rb", &file)) { send_http_error(conn, 500, http_500_error, "fopen(%s): %s", path, @@ -4256,10 +4552,12 @@ static void handle_ssi_file_request(struct mg_connection *conn, gmt_time_string(date, sizeof(date), &curtime); fclose_on_exec(&file, conn); mg_printf(conn, "HTTP/1.1 200 OK\r\n" + "%s%s%s" "Date: %s\r\n" "Content-Type: text/html\r\n" "Connection: %s\r\n\r\n", - date, suggest_connection_header(conn)); + cors1, cors2, cors3, + date, suggest_connection_header(conn)); send_ssi_file(conn, path, &file, 0); mg_fclose(&file); } @@ -4567,32 +4865,6 @@ static void SHA1Final(unsigned char digest[20], SHA1_CTX* context) } /* END OF SHA1 CODE */ -static void base64_encode(const unsigned char *src, int src_len, char *dst) -{ - static const char *b64 = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - int i, j, a, b, c; - - for (i = j = 0; i < src_len; i += 3) { - a = src[i]; - b = i + 1 >= src_len ? 0 : src[i + 1]; - c = i + 2 >= src_len ? 0 : src[i + 2]; - - dst[j++] = b64[a >> 2]; - dst[j++] = b64[((a & 3) << 4) | (b >> 4)]; - if (i + 1 < src_len) { - dst[j++] = b64[(b & 15) << 2 | (c >> 6)]; - } - if (i + 2 < src_len) { - dst[j++] = b64[c & 63]; - } - } - while (j % 4 != 0) { - dst[j++] = '='; - } - dst[j++] = '\0'; -} - static void send_websocket_handshake(struct mg_connection *conn) { static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; @@ -4664,11 +4936,11 @@ static void read_websocket(struct mg_connection *conn) /* Allocate space to hold websocket payload */ data = mem; if (data_len > sizeof(mem)) { - data = (char *)malloc(data_len); + data = (char *)mg_malloc(data_len); if (data == NULL) { /* Allocation failed, exit the loop and then close the connection */ - mg_cry(conn, "websocket malloc() failed; closing connection"); + mg_cry(conn, "websocket out of memory; closing connection"); break; } } @@ -4691,7 +4963,7 @@ static void read_websocket(struct mg_connection *conn) error = 0; while (len < data_len) { int n = pull(NULL, conn, data + len, (int)(data_len - len)); - if (n < 0) { + if (n <= 0) { error = 1; break; } @@ -4742,7 +5014,7 @@ static void read_websocket(struct mg_connection *conn) } if (data != mem) { - free(data); + mg_free(data); } /* Not breaking the loop, process next websocket frame. */ } else { @@ -4821,6 +5093,7 @@ static void handle_websocket_request(struct mg_connection *conn, const char *pat path) : 0; if (lua_websock || shared_lua_websock) { + /* TODO */ shared_lua_websock = 0; conn->lua_websocket_state = lua_websocket_new(path, conn, !!shared_lua_websock); if (conn->lua_websocket_state) { send_websocket_handshake(conn); @@ -5100,8 +5373,8 @@ void mg_set_request_handler(struct mg_context *ctx, const char *uri, mg_request_ lastref->next = tmp_rh->next; else ctx->request_handlers = tmp_rh->next; - free(tmp_rh->uri); - free(tmp_rh); + mg_free(tmp_rh->uri); + mg_free(tmp_rh); } return; } @@ -5122,7 +5395,7 @@ void mg_set_request_handler(struct mg_context *ctx, const char *uri, mg_request_ return; } - tmp_rh = (struct mg_request_handler_info *)malloc(sizeof(struct mg_request_handler_info)); + tmp_rh = (struct mg_request_handler_info *)mg_malloc(sizeof(struct mg_request_handler_info)); if (tmp_rh == NULL) { mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM"); return; @@ -5220,6 +5493,8 @@ static void handle_request(struct mg_connection *conn) use_request_handler(conn)) { /* Do nothing, callback has served the request */ } else if (!is_script_resource && !strcmp(ri->request_method, "OPTIONS")) { + /* Scripts should support the OPTIONS method themselves, to allow a maximum flexibility. + Lua and CGI scripts may fully support CORS this way (including preflights). */ send_options(conn); } else if (conn->ctx->config[DOCUMENT_ROOT] == NULL) { send_http_error(conn, 404, "Not Found", "Not Found"); @@ -5288,15 +5563,7 @@ static void handle_request(struct mg_connection *conn) } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS], (int)strlen(conn->ctx->config[CGI_EXTENSIONS]), path) > 0) { - /* TODO: check unsupported methods -> 501 - if (strcmp(ri->request_method, "POST") && - strcmp(ri->request_method, "HEAD") && - strcmp(ri->request_method, "GET")) { - send_http_error(conn, 501, "Not Implemented", - "Method %s is not implemented", ri->request_method); - } else { - handle_cgi_request(conn, path); - } */ + /* CGI scripts may support all HTTP methods */ handle_cgi_request(conn, path); #endif /* !NO_CGI */ } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS], @@ -5316,7 +5583,10 @@ static void close_all_listening_sockets(struct mg_context *ctx) for (i = 0; i < ctx->num_listening_sockets; i++) { closesocket(ctx->listening_sockets[i].sock); } - free(ctx->listening_sockets); + mg_free(ctx->listening_sockets); + ctx->listening_sockets=0; + mg_free(ctx->listening_ports); + ctx->listening_ports=0; } static int is_valid_port(unsigned int port) @@ -5379,11 +5649,11 @@ static int set_ports_option(struct mg_context *ctx) struct socket so, *ptr; in_port_t *portPtr; - struct sockaddr_in sin; + union usa usa; socklen_t len; - memset(&sin, 0, sizeof(sin)); - len = sizeof(sin); + memset(&usa, 0, sizeof(usa)); + len = sizeof(usa); while (success && (list = next_option(list, &vec, NULL)) != NULL) { if (!parse_port_string(&vec, &so)) { @@ -5407,19 +5677,19 @@ static int set_ports_option(struct mg_context *ctx) bind(so.sock, &so.lsa.sa, so.lsa.sa.sa_family == AF_INET ? sizeof(so.lsa.sin) : sizeof(so.lsa)) != 0 || listen(so.sock, SOMAXCONN) != 0 || - getsockname(so.sock, (struct sockaddr *)&sin, &len) != 0) { + getsockname(so.sock, &(usa.sa), &len) != 0) { mg_cry(fc(ctx), "%s: cannot bind to %.*s: %d (%s)", __func__, (int) vec.len, vec.ptr, ERRNO, strerror(errno)); if (so.sock != INVALID_SOCKET) { closesocket(so.sock); } success = 0; - } else if ((ptr = (struct socket *) realloc(ctx->listening_sockets, + } else if ((ptr = (struct socket *) mg_realloc(ctx->listening_sockets, (ctx->num_listening_sockets + 1) * sizeof(ctx->listening_sockets[0]))) == NULL) { closesocket(so.sock); success = 0; - } else if ((portPtr = (in_port_t*) realloc(ctx->listening_ports, + } else if ((portPtr = (in_port_t*) mg_realloc(ctx->listening_ports, (ctx->num_listening_sockets + 1) * sizeof(ctx->listening_ports[0]))) == NULL) { closesocket(so.sock); @@ -5430,7 +5700,7 @@ static int set_ports_option(struct mg_context *ctx) ctx->listening_sockets = ptr; ctx->listening_sockets[ctx->num_listening_sockets] = so; ctx->listening_ports = portPtr; - ctx->listening_ports[ctx->num_listening_sockets] = ntohs(sin.sin_port); + ctx->listening_ports[ctx->num_listening_sockets] = ntohs(usa.sin.sin_port); ctx->num_listening_sockets++; } } @@ -5668,7 +5938,7 @@ static int set_ssl_option(struct mg_context *ctx) /* Initialize locking callbacks, needed for thread safety. http://www.openssl.org/support/faq.html#PROG1 */ size = sizeof(pthread_mutex_t) * CRYPTO_num_locks(); - if ((ssl_mutexes = (pthread_mutex_t *) malloc((size_t)size)) == NULL) { + if ((ssl_mutexes = (pthread_mutex_t *) mg_malloc((size_t)size)) == NULL) { mg_cry(fc(ctx), "%s: cannot allocate mutexes: %s", __func__, ssl_error()); return 0; } @@ -5799,12 +6069,9 @@ void mg_close_connection(struct mg_connection *conn) #endif close_connection(conn); (void) pthread_mutex_destroy(&conn->mutex); - free(conn); + mg_free(conn); } -struct mg_connection *mg_connect(const char *host, int port, int use_ssl, - char *ebuf, size_t ebuf_len); - struct mg_connection *mg_connect(const char *host, int port, int use_ssl, char *ebuf, size_t ebuf_len) { @@ -5815,7 +6082,7 @@ struct mg_connection *mg_connect(const char *host, int port, int use_ssl, if ((sock = conn2(&fake_ctx, host, port, use_ssl, ebuf, ebuf_len)) == INVALID_SOCKET) { } else if ((conn = (struct mg_connection *) - calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) { + mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) { snprintf(ebuf, ebuf_len, "calloc(): %s", strerror(ERRNO)); closesocket(sock); #ifndef NO_SSL @@ -5823,7 +6090,7 @@ struct mg_connection *mg_connect(const char *host, int port, int use_ssl, SSL_CTX_new(SSLv23_client_method())) == NULL) { snprintf(ebuf, ebuf_len, "SSL_CTX_new error"); closesocket(sock); - free(conn); + mg_free(conn); conn = NULL; #endif /* NO_SSL */ } else { @@ -5949,7 +6216,7 @@ static void process_new_connection(struct mg_connection *conn) log_access(conn); } if (ri->remote_user != NULL) { - free((void *) ri->remote_user); + mg_free((void *) ri->remote_user); /* Important! When having connections with and without auth would cause double free and then crash */ ri->remote_user = NULL; @@ -6016,7 +6283,7 @@ static void *worker_thread_run(void *thread_func_param) tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL); #endif - conn = (struct mg_connection *) calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE); + conn = (struct mg_connection *) mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE); if (conn == NULL) { mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM"); } else { @@ -6068,7 +6335,7 @@ static void *worker_thread_run(void *thread_func_param) #if defined(_WIN32) && !defined(__SYMBIAN32__) CloseHandle(tls.pthread_cond_helper_mutex); #endif - free(conn); + mg_free(conn); DEBUG_TRACE(("exiting")); return NULL; @@ -6189,13 +6456,18 @@ static void master_thread_run(void *thread_func_param) } #endif + /* Initialize thread local storage */ #if defined(_WIN32) && !defined(__SYMBIAN32__) tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL); #endif tls.is_master = 1; pthread_setspecific(sTlsKey, &tls); - pfd = (struct pollfd *) calloc(ctx->num_listening_sockets, sizeof(pfd[0])); + /* Server starts *now* */ + ctx->start_time = (unsigned long)time(NULL); + + /* Allocate memory for the listening sockets, and start the server */ + pfd = (struct pollfd *) mg_calloc(ctx->num_listening_sockets, sizeof(pfd[0])); while (pfd != NULL && ctx->stop_flag == 0) { for (i = 0; i < ctx->num_listening_sockets; i++) { pfd[i].fd = ctx->listening_sockets[i].sock; @@ -6215,7 +6487,7 @@ static void master_thread_run(void *thread_func_param) } } } - free(pfd); + mg_free(pfd); DEBUG_TRACE(("stopping workers")); /* Stop signal received: somebody called mg_stop. Quit. */ @@ -6289,15 +6561,15 @@ static void free_context(struct mg_context *ctx) #ifdef WIN32 #pragma warning(suppress: 6001) #endif - free(ctx->config[i]); + mg_free(ctx->config[i]); } /* Deallocate request handlers */ while (ctx->request_handlers) { tmp_rh = ctx->request_handlers; ctx->request_handlers = tmp_rh->next; - free(tmp_rh->uri); - free(tmp_rh); + mg_free(tmp_rh->uri); + mg_free(tmp_rh); } #ifndef NO_SSL @@ -6306,14 +6578,14 @@ static void free_context(struct mg_context *ctx) SSL_CTX_free(ctx->ssl_ctx); } if (ssl_mutexes != NULL) { - free(ssl_mutexes); + mg_free(ssl_mutexes); ssl_mutexes = NULL; } #endif /* !NO_SSL */ /* Deallocate worker thread ID array */ if (ctx->workerthreadids != NULL) { - free(ctx->workerthreadids); + mg_free(ctx->workerthreadids); } /* Deallocate the tls variable */ @@ -6322,8 +6594,11 @@ static void free_context(struct mg_context *ctx) pthread_key_delete(sTlsKey); } + /* deallocate system name string */ + mg_free(ctx->systemName); + /* Deallocate context itself */ - free(ctx); + mg_free(ctx); } void mg_stop(struct mg_context *ctx) @@ -6342,6 +6617,35 @@ void mg_stop(struct mg_context *ctx) #endif /* _WIN32 && !__SYMBIAN32__ */ } +void get_system_name(char **sysName) +{ +#if defined(_WIN32) +#if !defined(__SYMBIAN32__) + char name[128]; + DWORD dwVersion = 0; + DWORD dwMajorVersion = 0; + DWORD dwMinorVersion = 0; + DWORD dwBuild = 0; + + dwVersion = GetVersion(); + + dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion))); + dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion))); + dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0); + + sprintf(name, "Windows %d.%d", dwMajorVersion, dwMinorVersion); + *sysName = mg_strdup(name); +#else + *sysName = mg_strdup("Symbian"); +#endif +#else + struct utsname name; + memset(&name, 0, sizeof(name)); + uname(&name); + *sysName = mg_strdup(name.sysname); +#endif +} + struct mg_context *mg_start(const struct mg_callbacks *callbacks, void *user_data, const char **options) @@ -6360,18 +6664,18 @@ struct mg_context *mg_start(const struct mg_callbacks *callbacks, /* Check if the config_options and the corresponding enum have compatible sizes. */ /* Could use static_assert, once it is verified that all compilers support this. */ - assert(sizeof(config_options)/sizeof(config_options[0]) == NUM_OPTIONS*2+1); + assert(sizeof(config_options)/sizeof(config_options[0]) == NUM_OPTIONS+1); /* Allocate context and initialize reasonable general case defaults. TODO(lsm): do proper error handling here. */ - if ((ctx = (struct mg_context *) calloc(1, sizeof(*ctx))) == NULL) { + if ((ctx = (struct mg_context *) mg_calloc(1, sizeof(*ctx))) == NULL) { return NULL; } if (sTlsInit==0) { if (0 != pthread_key_create(&sTlsKey, NULL)) { mg_cry(fc(ctx), "Cannot initialize thread local storage"); - free(ctx); + mg_free(ctx); return NULL; } sTlsInit++; @@ -6381,6 +6685,10 @@ struct mg_context *mg_start(const struct mg_callbacks *callbacks, ctx->user_data = user_data; ctx->request_handlers = 0; +#if defined(USE_LUA) && defined(USE_WEBSOCKET) + ctx->shared_lua_websockets = 0; +#endif + while (options && (name = *options++) != NULL) { if ((i = get_option_index(name)) == -1) { mg_cry(fc(ctx), "Invalid option: %s", name); @@ -6393,20 +6701,22 @@ struct mg_context *mg_start(const struct mg_callbacks *callbacks, } if (ctx->config[i] != NULL) { mg_cry(fc(ctx), "warning: %s: duplicate option", name); - free(ctx->config[i]); + mg_free(ctx->config[i]); } ctx->config[i] = mg_strdup(value); DEBUG_TRACE(("[%s] -> [%s]", name, value)); } /* Set default value if needed */ - for (i = 0; config_options[i * 2] != NULL; i++) { - default_value = config_options[i * 2 + 1]; + for (i = 0; config_options[i].name != NULL; i++) { + default_value = config_options[i].default_value; if (ctx->config[i] == NULL && default_value != NULL) { ctx->config[i] = mg_strdup(default_value); } } + get_system_name(&ctx->systemName); + /* NOTE(lsm): order is important here. SSL certificates must be initialized before listening ports. UID must be set last. */ if (!set_gpass_option(ctx) || @@ -6443,7 +6753,7 @@ struct mg_context *mg_start(const struct mg_callbacks *callbacks, if (workerthreadcount > 0) { ctx->workerthreadcount = workerthreadcount; - ctx->workerthreadids = calloc(workerthreadcount, sizeof(pthread_t)); + ctx->workerthreadids = mg_calloc(workerthreadcount, sizeof(pthread_t)); if (ctx->workerthreadids == NULL) { mg_cry(fc(ctx), "Not enough memory for worker thread ID array"); free_context(ctx); diff --git a/src/main.c b/src/main.c index 2763d810..061cb8e7 100644 --- a/src/main.c +++ b/src/main.c @@ -1,4 +1,5 @@ -/* Copyright (c) 2004-2013 Sergey Lyubka +/* Copyright (c) 2013-2014 the Civetweb developers + * Copyright (c) 2004-2013 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 @@ -39,6 +40,7 @@ #include #include #include +#include #include "civetweb.h" @@ -76,10 +78,11 @@ extern char *_getcwd(char *buf, size_t size); #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_civetweb() */ +static char server_base_name[40]; /* Set by init_server_name() */ +static char *server_name; /* Set by init_server_name() */ +static char *icon_name; /* 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_civetweb() */ #if !defined(CONFIG_FILE) #define CONFIG_FILE "civetweb.conf" @@ -90,6 +93,18 @@ static struct mg_context *ctx; /* Set by start_civetweb() */ #define CONFIG_FILE2 "/usr/local/etc/civetweb.conf" #endif +enum { + OPTION_TITLE, + OPTION_ICON, + NUM_MAIN_OPTIONS +}; + +static struct mg_option main_config_options[] = { + {"title", CONFIG_TYPE_STRING, NULL}, + {"icon", CONFIG_TYPE_STRING, NULL}, + {NULL, CONFIG_TYPE_UNKNOWN, NULL} +}; + static void WINCDECL signal_handler(int sig_num) { exit_flag = sig_num; @@ -116,9 +131,18 @@ static void die(const char *fmt, ...) static void show_usage_and_exit(void) { - const char **names; + const struct mg_option *options; int i; +#ifdef WIN32 + if (!AttachConsole(ATTACH_PARENT_PROCESS)) { + AllocConsole(); + AttachConsole(GetCurrentProcessId()); + } + freopen("CON", "a", stdout); + freopen("CON", "a", stderr); +#endif + fprintf(stderr, "Civetweb v%s, built on %s\n", mg_version(), __DATE__); fprintf(stderr, "Usage:\n"); @@ -127,11 +151,16 @@ static void show_usage_and_exit(void) fprintf(stderr, " civetweb [-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 ? "" : names[i + 1]); + options = mg_get_valid_options(); + for (i = 0; options[i].name != NULL; i++) { + fprintf(stderr, " -%s %s\n", options[i].name, ((options[i].default_value == NULL) ? "" : options[i].default_value)); } + + options = main_config_options; + for (i = 0; options[i].name != NULL; i++) { + fprintf(stderr, " -%s %s\n", options[i].name, ((options[i].default_value == NULL) ? "" : options[i].default_value)); + } + exit(EXIT_FAILURE); } @@ -165,7 +194,8 @@ static const char *get_url_to_first_open_port(const struct mg_context *ctx) static void create_config_file(const char *path) { - const char **names, *value; + const struct mg_option *options; + const char *value; FILE *fp; int i; @@ -174,10 +204,10 @@ static void create_config_file(const char *path) fclose(fp); } else if ((fp = fopen(path, "a+")) != NULL) { fprintf(fp, "%s", config_file_top_comment); - names = mg_get_valid_option_names(); - for (i = 0; names[i * 2] != NULL; i++) { - value = mg_get_option(ctx, names[i * 2]); - fprintf(fp, "# %s %s\n", names[i * 2], value ? value : ""); + options = mg_get_valid_options(); + for (i = 0; options[i].name != NULL; i++) { + value = mg_get_option(ctx, options[i].name); + fprintf(fp, "# %s %s\n", options[i].name, value ? value : ""); } fclose(fp); } @@ -196,9 +226,41 @@ static char *sdup(const char *str) return p; } -static void set_option(char **options, const char *name, const char *value) +static int set_option(char **options, const char *name, const char *value) { - int i; + int i, type; + const struct mg_option *default_options = mg_get_valid_options(); + + for (i = 0; main_config_options[i].name != 0; i++) { + if (0==strcmp(name, main_config_options[i].name)) { + /* This option is evaluated by main.c, not civetweb.c - just skip it and return OK */ + return 1; + } + } + + type = CONFIG_TYPE_UNKNOWN; + for (i = 0; default_options[i].name != 0; i++) { + if (!strcmp(default_options[i].name, name)) { + type = default_options[i].type; + } + } + switch (type) { + case CONFIG_TYPE_UNKNOWN: + /* unknown option */ + return 0; + case CONFIG_TYPE_NUMBER: + if (atol(value)<1) { + /* invalid number */ + return 0; + } + break; + case CONFIG_TYPE_BOOLEAN: + if ((0!=strcmp(value,"yes")) && (0!=strcmp(value,"no"))) { + /* invalid boolean */ + return 0; + } + break; + } for (i = 0; i < MAX_OPTIONS - 3; i++) { if (options[i] == NULL) { @@ -216,14 +278,16 @@ static void set_option(char **options, const char *name, const char *value) if (i == MAX_OPTIONS - 3) { die("%s", "Too many options specified"); } -} + /* TODO: check if this option is defined and the correct data type, return 1 (OK) or 0 (false) */ + return 1; +} static void read_config_file(const char *config_file, char **options) { - char line[MAX_CONF_FILE_LINE_SIZE], opt[sizeof(line)], val[sizeof(line)], *p; + char line[MAX_CONF_FILE_LINE_SIZE], *p; FILE *fp = NULL; - size_t i, cmd_line_opts_start = 1, line_no = 0; + size_t i, j, cmd_line_opts_start = 1, line_no = 0; fp = fopen(config_file, "r"); @@ -253,11 +317,23 @@ static void read_config_file(const char *config_file, char **options) continue; } - if (sscanf(p, "%s %[^\r\n#]", opt, val) != 2) { + /* Skip spaces, \r and \n at the end of the line */ + for (j = strlen(line)-1; isspace(* (unsigned char *) &line[j]) || iscntrl(* (unsigned char *) &line[j]); ) line[j--]=0; + + /* Find the space character between option name and value */ + for (j=i; !isspace(* (unsigned char *) &line[j]) && (line[j]!=0); ) j++; + + /* Terminate the string - then the string at (line+i) contains the option name */ + line[j] = 0; + j++; + + /* Trim additional spaces between option name and value - then (line+j) contains the option value */ + while (isspace(line[j])) j++; + + /* Set option */ + if (!set_option(options, line+i, line+j)) { printf("%s: line %d is invalid, ignoring it:\n %s", config_file, (int) line_no, p); - } else { - set_option(options, opt, val); } } @@ -265,7 +341,6 @@ static void read_config_file(const char *config_file, char **options) } } - static void process_command_line_arguments(char *argv[], char **options) { char *p; @@ -314,15 +389,34 @@ static void process_command_line_arguments(char *argv[], char **options) if (argv[i][0] != '-' || argv[i + 1] == NULL) { show_usage_and_exit(); } - set_option(options, &argv[i][1], argv[i + 1]); + if (!set_option(options, &argv[i][1], argv[i + 1])) { + printf("command line option is invalid, ignoring it:\n %s %s\n", + argv[i], argv[i + 1]); + } } } } -static void init_server_name(void) +static void init_server_name(int argc, const char *argv[]) { - snprintf(server_name, sizeof(server_name), "Civetweb v%s", + int i; + assert(sizeof(main_config_options)/sizeof(main_config_options[0]) == NUM_MAIN_OPTIONS+1); + assert((strlen(mg_version())+12)cy = ((nelems + 1) / 2 + 1) * HEIGHT + 30; DialogBoxIndirectParam(NULL, dia, NULL, DlgProc, (LPARAM) NULL); @@ -857,7 +945,7 @@ static void show_settings_dialog() static int manage_service(int action) { - static const char *service_name = "Civetweb"; + static const char *service_name = "Civetweb"; /* TODO: check using server_name instead of service_name */ SC_HANDLE hSCM = NULL, hService = NULL; SERVICE_DESCRIPTION descr = {server_name}; char path[PATH_MAX + 20] = "";/* Path to executable plus magic argument */ @@ -902,16 +990,16 @@ static int manage_service(int action) 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} - }; + static SERVICE_TABLE_ENTRY service_table[2] = {0}; int service_installed; char buf[200], *service_argv[] = {__argv[0], NULL}; POINT pt; HMENU hMenu; static UINT s_uTaskbarRestart; /* for taskbar creation */ + service_table[0].lpServiceName = server_name; + service_table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain; + switch (msg) { case WM_CREATE: if (__argv[1] != NULL && @@ -964,7 +1052,7 @@ static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam, ID_REMOVE_SERVICE, "Deinstall service"); AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, ""); AppendMenu(hMenu, MF_STRING, ID_CONNECT, "Start browser"); - AppendMenu(hMenu, MF_STRING, ID_SETTINGS, "Edit Settings"); + AppendMenu(hMenu, MF_STRING, ID_SETTINGS, "Edit settings"); AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, ""); AppendMenu(hMenu, MF_STRING, ID_QUIT, "Exit"); GetCursorPos(&pt); @@ -994,23 +1082,27 @@ int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show) HWND hWnd; MSG msg; - init_server_name(); + init_server_name(__argc, __argv); memset(&cls, 0, sizeof(cls)); cls.lpfnWndProc = (WNDPROC) WindowProc; cls.hIcon = LoadIcon(NULL, IDI_APPLICATION); - cls.lpszClassName = server_name; + cls.lpszClassName = server_base_name; RegisterClass(&cls); hWnd = CreateWindow(cls.lpszClassName, server_name, WS_OVERLAPPEDWINDOW, 0, 0, 0, 0, NULL, NULL, NULL, NULL); ShowWindow(hWnd, SW_HIDE); + if (icon_name) { + hIcon = LoadImage(NULL, icon_name, IMAGE_ICON, 16, 16, LR_LOADFROMFILE); + } else { + hIcon = LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(ID_ICON), IMAGE_ICON, 16, 16, 0); + } + TrayIcon.cbSize = sizeof(TrayIcon); TrayIcon.uID = ID_ICON; TrayIcon.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP; - TrayIcon.hIcon = hIcon = LoadImage(GetModuleHandle(NULL), - MAKEINTRESOURCE(ID_ICON), - IMAGE_ICON, 16, 16, 0); + TrayIcon.hIcon = hIcon; TrayIcon.hWnd = hWnd; snprintf(TrayIcon.szTip, sizeof(TrayIcon.szTip), "%s", server_name); TrayIcon.uCallbackMessage = WM_USER; @@ -1052,7 +1144,7 @@ withApplication:@"TextEdit"]; int main(int argc, char *argv[]) { - init_server_name(); + init_server_name(argc, argv); start_civetweb(argc, argv); [NSAutoreleasePool new]; @@ -1112,7 +1204,7 @@ int main(int argc, char *argv[]) #else int main(int argc, char *argv[]) { - init_server_name(); + init_server_name(argc, argv); start_civetweb(argc, argv); printf("%s started on port(s) %s with web root [%s]\n", server_name, mg_get_option(ctx, "listening_ports"), diff --git a/src/mod_lua.inl b/src/mod_lua.inl index 8f6dba34..189aabcf 100644 --- a/src/mod_lua.inl +++ b/src/mod_lua.inl @@ -559,6 +559,70 @@ static int lsp_url_decode(lua_State *L) return 1; } +/* mg.base64_encode */ +static int lsp_base64_encode(lua_State *L) +{ + int num_args = lua_gettop(L); + const char *text; + size_t text_len; + char *dst; + + if (num_args==1) { + text = lua_tolstring(L, 1, &text_len); + if (text) { + dst = mg_malloc(text_len*8/6+4); + if (dst) { + base64_encode(text, text_len, dst); + lua_pushstring(L, dst); + mg_free(dst); + } else { + return luaL_error(L, "out of memory in base64_encode() call"); + } + } else { + lua_pushnil(L); + } + } else { + /* Syntax error */ + return luaL_error(L, "invalid base64_encode() call"); + } + return 1; +} + +/* mg.base64_encode */ +static int lsp_base64_decode(lua_State *L) +{ + int num_args = lua_gettop(L); + const char *text; + size_t text_len, dst_len; + int ret; + char *dst; + + if (num_args==1) { + text = lua_tolstring(L, 1, &text_len); + if (text) { + dst = mg_malloc(text_len); + if (dst) { + ret = base64_decode(text, text_len, dst, &dst_len); + if (ret != -1) { + mg_free(dst); + return luaL_error(L, "illegal character in lsp_base64_decode() call"); + } else { + lua_pushlstring(L, dst, dst_len); + mg_free(dst); + } + } else { + return luaL_error(L, "out of memory in lsp_base64_decode() call"); + } + } else { + lua_pushnil(L); + } + } else { + /* Syntax error */ + return luaL_error(L, "invalid lsp_base64_decode() call"); + } + return 1; +} + /* mg.write for websockets */ static int lwebsock_write(lua_State *L) { @@ -605,6 +669,7 @@ static void prepare_lua_environment(struct mg_connection *conn, lua_State *L, co { const struct mg_request_info *ri = mg_get_request_info(conn); char src_addr[IP_ADDR_STR_LEN]; + const char * preload_file = conn->ctx->config[LUA_PRELOAD_FILE]; int i; extern void luaL_openlibs(lua_State *); @@ -676,6 +741,8 @@ static void prepare_lua_environment(struct mg_connection *conn, lua_State *L, co reg_function(L, "md5", lsp_md5, conn); reg_function(L, "url_encode", lsp_url_encode, conn); reg_function(L, "url_decode", lsp_url_decode, conn); + reg_function(L, "base64_encode", lsp_base64_encode, conn); + reg_function(L, "base64_decode", lsp_base64_decode, conn); reg_string(L, "version", CIVETWEB_VERSION); reg_string(L, "document_root", conn->ctx->config[DOCUMENT_ROOT]); @@ -684,6 +751,10 @@ static void prepare_lua_environment(struct mg_connection *conn, lua_State *L, co reg_string(L, "websocket_root", conn->ctx->config[WEBSOCKET_ROOT]); #endif + if (conn->ctx->systemName) { + reg_string(L, "system", conn->ctx->systemName); + } + /* Export request_info */ lua_pushstring(L, "request_info"); lua_newtable(L); @@ -719,6 +790,11 @@ static void prepare_lua_environment(struct mg_connection *conn, lua_State *L, co /* Register default mg.onerror function */ IGNORE_UNUSED_RESULT(luaL_dostring(L, "mg.onerror = function(e) mg.write('\\nLua error:\\n', " "debug.traceback(e, 1)) end")); + + /* Preload */ + if ((preload_file != NULL) && (*preload_file != 0)) { + IGNORE_UNUSED_RESULT(luaL_dofile(L, preload_file)); + } } static int lua_error_handler(lua_State *L) @@ -741,6 +817,17 @@ static int lua_error_handler(lua_State *L) return 0; } +static void * lua_allocator(void *ud, void *ptr, size_t osize, size_t nsize) { + + (void)ud; (void)osize; /* not used */ + + if (nsize == 0) { + mg_free(ptr); + return NULL; + } + return mg_realloc(ptr, nsize); +} + void mg_exec_lua_script(struct mg_connection *conn, const char *path, const void **exports) { @@ -751,7 +838,7 @@ void mg_exec_lua_script(struct mg_connection *conn, const char *path, conn->must_close=1; /* Execute a plain Lua script. */ - if (path != NULL && (L = luaL_newstate()) != NULL) { + if (path != NULL && (L = lua_newstate(lua_allocator, NULL)) != NULL) { prepare_lua_environment(conn, L, path, LUA_ENV_TYPE_PLAIN_LUA_PAGE); lua_pushcclosure(L, &lua_error_handler, 0); @@ -809,7 +896,7 @@ struct file *filep, struct lua_State *ls) fileno(filep->fp), 0)) == MAP_FAILED) { lsp_send_err(conn, ls, "mmap(%s, %zu, %d): %s", path, (size_t) filep->size, fileno(filep->fp), strerror(errno)); - } else if ((L = ls != NULL ? ls : luaL_newstate()) == NULL) { + } else if ((L = ls != NULL ? ls : lua_newstate(lua_allocator, NULL)) == NULL) { send_http_error(conn, 500, http_500_error, "%s", "luaL_newstate failed"); } else { /* We're not sending HTTP headers here, Lua page must do it. */ @@ -833,7 +920,15 @@ struct file *filep, struct lua_State *ls) struct lua_websock_data { lua_State *main; lua_State *thread; + char * script; + unsigned shared; struct mg_connection *conn; + pthread_mutex_t mutex; +}; + +struct mg_shared_lua_websocket { + struct lua_websock_data *sock; + struct mg_shared_lua_websocket *next; }; static void websock_cry(struct mg_connection *conn, int err, lua_State * L, const char * ws_operation, const char * lua_operation) @@ -866,22 +961,62 @@ static void websock_cry(struct mg_connection *conn, int err, lua_State * L, cons static void * lua_websocket_new(const char * script, struct mg_connection *conn, int is_shared) { struct lua_websock_data *lws_data; + struct mg_shared_lua_websocket **shared_websock_list = &(conn->ctx->shared_lua_websockets); int ok = 0; + int found = 0; int err, nargs; assert(conn->lua_websocket_state == NULL); - lws_data = (struct lua_websock_data *) malloc(sizeof(*lws_data)); + + /* + lock list (mg_context global) + check if in list + yes: inc rec counter + no: create state, add to list + lock list element + unlock list (mg_context global) + call add + unlock list element + */ + + if (is_shared) { + (void)pthread_mutex_lock(&conn->ctx->mutex); + while (*shared_websock_list) { + if (!strcmp((*shared_websock_list)->sock->script, script)) { + lws_data = (*shared_websock_list)->sock; + lws_data->shared++; + found = 1; + } + shared_websock_list = &((*shared_websock_list)->next); + } + (void)pthread_mutex_unlock(&conn->ctx->mutex); + } + + if (!found) { + lws_data = (struct lua_websock_data *) mg_malloc(sizeof(*lws_data)); + } if (lws_data) { - lws_data->conn = conn; - - if (is_shared) { - (void)pthread_mutex_lock(&conn->ctx->mutex); - // TODO: add_to_websocket_list(lws_data); - (void)pthread_mutex_unlock(&conn->ctx->mutex); + if (!found) { + lws_data->shared = is_shared; + lws_data->conn = conn; + lws_data->script = mg_strdup(script); + lws_data->main = lua_newstate(lua_allocator, NULL); + if (is_shared) { + (void)pthread_mutex_lock(&conn->ctx->mutex); + shared_websock_list = &(conn->ctx->shared_lua_websockets); + while (*shared_websock_list) { + shared_websock_list = &((*shared_websock_list)->next); + } + *shared_websock_list = (struct mg_shared_lua_websocket *)mg_malloc(sizeof(struct mg_shared_lua_websocket)); + if (*shared_websock_list) { + (*shared_websock_list)->sock = lws_data; + (*shared_websock_list)->next = 0; + } + (void)pthread_mutex_unlock(&conn->ctx->mutex); + } } - lws_data->main = luaL_newstate(); if (lws_data->main) { prepare_lua_environment(conn, lws_data->main, script, LUA_ENV_TYPE_LUA_WEBSOCKET); if (conn->ctx->callbacks.init_lua != NULL) { @@ -908,7 +1043,8 @@ static void * lua_websocket_new(const char * script, struct mg_connection *conn, if (!ok) { if (lws_data->main) lua_close(lws_data->main); - free(lws_data); + mg_free(lws_data->script); + mg_free(lws_data); lws_data=0; } } else { @@ -928,6 +1064,12 @@ static int lua_websocket_data(struct mg_connection *conn, int bits, char *data, assert(lws_data->main != NULL); assert(lws_data->thread != NULL); + /* + lock list element + call data + unlock list element + */ + do { retry=0; @@ -978,17 +1120,53 @@ static int lua_websocket_ready(struct mg_connection *conn) static void lua_websocket_close(struct mg_connection *conn) { struct lua_websock_data *lws_data = (struct lua_websock_data *)(conn->lua_websocket_state); + struct mg_shared_lua_websocket **shared_websock_list; int err; assert(lws_data != NULL); assert(lws_data->main != NULL); assert(lws_data->thread != NULL); + /* + lock list element + lock list (mg_context global) + call remove + dec ref counter + if ref counter == 0 close state and remove from list + unlock list element + unlock list (mg_context global) + */ + + lua_pushboolean(lws_data->thread, 0); err = lua_resume(lws_data->thread, NULL, 1); - lua_close(lws_data->main); - free(lws_data); + if (lws_data->shared) { + (void)pthread_mutex_lock(&conn->ctx->mutex); + lws_data->shared--; + if (lws_data->shared==0) { + /* + shared_websock_list = &(conn->ctx->shared_lua_websockets); + while (*shared_websock_list) { + if ((*shared_websock_list)->sock == lws_data) { + *shared_websock_list = (*shared_websock_list)->next; + } else { + shared_websock_list = &((*shared_websock_list)->next); + } + } + + lua_close(lws_data->main); + mg_free(lws_data->script); + lws_data->script=0; + mg_free(lws_data); + */ + } + (void)pthread_mutex_unlock(&conn->ctx->mutex); + } else { + lua_close(lws_data->main); + mg_free(lws_data->script); + mg_free(lws_data); + } conn->lua_websocket_state = NULL; } #endif diff --git a/test/ajax/echo.lp b/test/ajax/echo.lp index f524ab86..7276f813 100644 --- a/test/ajax/echo.lp +++ b/test/ajax/echo.lp @@ -1,6 +1,9 @@ \ No newline at end of file diff --git a/test/ajax/echo.lua b/test/ajax/echo.lua index 1834a465..13175162 100644 --- a/test/ajax/echo.lua +++ b/test/ajax/echo.lua @@ -24,12 +24,12 @@ resp = resp .. "}"; -mg.write("HTTP/1.1 200 OK\n") -mg.write("Connection: close\n") -mg.write("Content-Type: text/html\n") -mg.write("Cache-Control: no-cache\n") +mg.write("HTTP/1.1 200 OK\r\n") +mg.write("Connection: close\r\n") +mg.write("Content-Type: text/html\r\n") +mg.write("Cache-Control: no-cache\r\n") --mg.write("Content-Length: " .. resp:len() .. "\n") -mg.write("\n") +mg.write("\r\n") mg.write(resp) diff --git a/test/cors.html b/test/cors.html new file mode 100644 index 00000000..5ab53606 --- /dev/null +++ b/test/cors.html @@ -0,0 +1,75 @@ + + + +CORS test + + + + + + +

Cross-origin resource sharing test

+

*** Error: Javascript is not activated. This test will not work. ***

+ + + + +

More information on CORS: See enable-cors.org and html5rocks.com.

+ + diff --git a/test/cors.reply.html b/test/cors.reply.html new file mode 100644 index 00000000..26d88dfc --- /dev/null +++ b/test/cors.reply.html @@ -0,0 +1,7 @@ + + +CORS test reply - test OK + +Do not load this page directly - use cors.html instead! + + diff --git a/test/cors.reply.lua b/test/cors.reply.lua new file mode 100644 index 00000000..9a659a95 --- /dev/null +++ b/test/cors.reply.lua @@ -0,0 +1,73 @@ +-- http://www.html5rocks.com/static/images/cors_server_flowchart.png + +if not mg.request_info.http_headers.Origin then + mg.write("HTTP/1.0 200 OK\r\n") + mg.write("Connection: close\r\n") + mg.write("Content-Type: text/html; charset=utf-8\r\n") + mg.write("\r\n") + mg.write("This test page should not be used directly. Open cors.html instead.") + return +end + +if mg.request_info.request_method == "OPTIONS" then + + local acrm = mg.request_info.http_headers['Access-Control-Request-Method']; + if (acrm) then + local acrh = nil -- mg.request_info.http_headers['Access-Control-Request-Header']; + if (acrm~='PUT') then + -- invalid request + mg.write("HTTP/1.0 403 Forbidden\r\n") + mg.write("Connection: close\r\n") + mg.write("\r\n") + return + else + -- preflight request + mg.write("HTTP/1.0 200 OK\r\n") + mg.write("Access-Control-Allow-Methods: PUT\r\n") + if (acrh) then + mg.write("Access-Control-Allow-Headers: " .. acrh .. "\r\n") + end + mg.write("Access-Control-Allow-Origin: *\r\n") + mg.write("Connection: close\r\n") + mg.write("Content-Type: text/html; charset=utf-8\r\n") + mg.write("\r\n") + return + end + end +end + +-- actual request +if mg.request_info.request_method == "GET" then + mg.write("HTTP/1.0 200 OK\r\n") + mg.write("Access-Control-Allow-Origin: *\r\n") + mg.write("Connection: close\r\n") + mg.write("Content-Type: text/html; charset=utf-8\r\n") + mg.write("\r\n") + mg.write([[ + + CORS dynamic GET test reply - test OK + This should never be shown + + ]]) + return +end + + +if mg.request_info.request_method == "PUT" then + mg.write("HTTP/1.0 200 OK\r\n") + mg.write("Access-Control-Allow-Origin: *\r\n") + mg.write("Connection: close\r\n") + mg.write("Content-Type: text/html; charset=utf-8\r\n") + mg.write("\r\n") + mg.write([[ + + CORS dynamic PUT test reply - test OK + This should never be shown + + ]]) + return +end + +mg.write("HTTP/1.0 403 Forbidden\r\n") +mg.write("Connection: close\r\n") +mg.write("\r\n") diff --git a/test/cors.reply.shtml b/test/cors.reply.shtml new file mode 100644 index 00000000..26d88dfc --- /dev/null +++ b/test/cors.reply.shtml @@ -0,0 +1,7 @@ + + +CORS test reply - test OK + +Do not load this page directly - use cors.html instead! + + diff --git a/test/lua_preload_file.lua b/test/lua_preload_file.lua new file mode 100644 index 00000000..7761f473 --- /dev/null +++ b/test/lua_preload_file.lua @@ -0,0 +1,7 @@ +--[[ +Load this test file by adding + lua_preload_file ./lua_preload_file.lua +to the civetweb.conf file +]] + +mg.preload = "lua_preload_file successfully loaded" diff --git a/test/page4.lua b/test/page4.lua index ac5ff2a0..cd73990c 100644 --- a/test/page4.lua +++ b/test/page4.lua @@ -11,6 +11,7 @@ end mg.write("HTTP/1.0 200 OK\r\n") mg.write("Connection: close\r\n") mg.write("Content-Type: text/html; charset=utf-8\r\n") +mg.write("Cache-Control: max-age=0, must-revalidate\r\n") if not cookie_value then mg.write("Set-Cookie: " .. cookie_name .. "=" .. tostring(now) .. "\r\n") end @@ -106,23 +107,47 @@ else end raw_string = [[ !"#$%&'()*+,-./0123456789:;<=>?@]] mg.write(" original string: " .. htmlEscape(raw_string) .. "\r\n") -url_string = mg.url_encode(raw_string):upper() +mg_string = mg.url_encode(raw_string):upper() ref_string = "%20!%22%23%24%25%26'()*%2B%2C-.%2F0123456789%3A%3B%3C%3D%3E%3F%40" -- from http://www.w3schools.com/tags/ref_urlencode.asp -mg.write(" mg-url: " .. htmlEscape(url_string) .. "\r\n") +mg.write(" mg-url: " .. htmlEscape(mg_string) .. "\r\n") mg.write(" reference url: " .. htmlEscape(ref_string) .. "\r\n") -dec_url_string = mg.url_decode(url_string) +dec_mg_string = mg.url_decode(mg_string) dec_ref_string = mg.url_decode(ref_string) -mg.write(" decoded mg-url: " .. htmlEscape(dec_url_string) .. "\r\n") +mg.write(" decoded mg-url: " .. htmlEscape(dec_mg_string) .. "\r\n") mg.write(" decoded reference url: " .. htmlEscape(dec_ref_string) .. "\r\n") -dec_url_string = mg.url_decode(url_string, false) +dec_mg_string = mg.url_decode(mg_string, false) dec_ref_string = mg.url_decode(ref_string, false) -mg.write(" decoded mg-url: " .. htmlEscape(dec_url_string) .. "\r\n") +mg.write(" decoded mg-url: " .. htmlEscape(dec_mg_string) .. "\r\n") mg.write(" decoded reference url: " .. htmlEscape(dec_ref_string) .. "\r\n") -dec_url_string = mg.url_decode(url_string, true) +dec_mg_string = mg.url_decode(mg_string, true) dec_ref_string = mg.url_decode(ref_string, true) -mg.write(" decoded mg-url: " .. htmlEscape(dec_url_string) .. "\r\n") +mg.write(" decoded mg-url: " .. htmlEscape(dec_mg_string) .. "\r\n") mg.write(" decoded reference url: " .. htmlEscape(dec_ref_string) .. "\r\n") mg.write("\r\n") +-- base64_encode +mg.write("BASE64 encode/decode test:\r\n") +raw_string = [[ !"#$%&'()*+,-./0123456789:;<=>?@]] +mg.write(" original string: " .. htmlEscape(raw_string) .. "\r\n") +mg_string = mg.base64_encode(raw_string) +ref_string = "ICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9A" -- from http://www.base64encode.org/ +mg.write(" mg-base64: " .. htmlEscape(mg_string) .. "\r\n") +mg.write(" reference base64: " .. htmlEscape(ref_string) .. "\r\n") +dec_mg_string = mg.base64_decode(mg_string) +dec_ref_string = mg.base64_decode(ref_string) +mg.write(" decoded mg-base64: " .. htmlEscape(dec_mg_string) .. "\r\n") +mg.write(" decoded reference base64: " .. htmlEscape(dec_ref_string) .. "\r\n") +mg.write("\r\n") +raw_string = [[ -?-]] +mg.write(" original string: " .. htmlEscape(raw_string) .. "\r\n") +mg_string = mg.base64_encode(raw_string) +ref_string = "PD8+IC0/LQ==" -- from http://www.base64encode.org/ +mg.write(" mg-base64: " .. htmlEscape(mg_string) .. "\r\n") +mg.write(" reference base64: " .. htmlEscape(ref_string) .. "\r\n") +dec_mg_string = mg.base64_decode(mg_string) +dec_ref_string = mg.base64_decode(ref_string) +mg.write(" decoded mg-base64: " .. htmlEscape(dec_mg_string) .. "\r\n") +mg.write(" decoded reference base64: " .. htmlEscape(dec_ref_string) .. "\r\n") + -- end of page mg.write("\r\n\r\n\r\n") diff --git a/test/test.ico b/test/test.ico new file mode 100644 index 00000000..70ab89d0 Binary files /dev/null and b/test/test.ico differ