diff --git a/include/CivetServer.h b/include/CivetServer.h index d0be55e8..4e66609f 100644 --- a/include/CivetServer.h +++ b/include/CivetServer.h @@ -20,25 +20,21 @@ class CivetServer; /** * Exception class for thrown exceptions within the CivetHandler object. */ -class CIVETWEB_API CivetException : public std::runtime_error -{ - public: - CivetException(const std::string& msg) : std::runtime_error(msg) {} +class CIVETWEB_API CivetException : public std::runtime_error { + public: + CivetException(const std::string &msg) : std::runtime_error(msg) {} }; /** * Basic interface for a URI request handler. Handlers implementations * must be reentrant. */ -class CIVETWEB_API CivetHandler -{ -public: - +class CIVETWEB_API CivetHandler { + public: /** * Destructor */ - virtual ~CivetHandler() { - } + virtual ~CivetHandler() {} /** * Callback method for GET request. @@ -91,10 +87,8 @@ public: * * Basic class for embedded web server. This has an URL mapping built-in. */ -class CIVETWEB_API CivetServer -{ -public: - +class CIVETWEB_API CivetServer { + public: /** * Constructor * @@ -126,9 +120,7 @@ public: * * @return the context or 0 if not running. */ - const struct mg_context *getContext() const { - return context; - } + const struct mg_context *getContext() const { return context; } /** * addHandler(const std::string &, CivetHandler *) @@ -167,16 +159,20 @@ public: std::vector getListeningPorts(); /** - * getCookie(struct mg_connection *conn, const std::string &cookieName, std::string &cookieValue) + * getCookie(struct mg_connection *conn, const std::string &cookieName, + *std::string &cookieValue) * - * Puts the cookie value string that matches the cookie name in the cookieValue destinaton string. + * Puts the cookie value string that matches the cookie name in the + *cookieValue destinaton string. * * @param conn - the connection information * @param cookieName - cookie name to get the value from * @param cookieValue - cookie value is returned using thiis reference * @returns the size of the cookie value string read. */ - static int getCookie(struct mg_connection *conn, const std::string &cookieName, std::string &cookieValue); + static int getCookie(struct mg_connection *conn, + const std::string &cookieName, + std::string &cookieValue); /** * getHeader(struct mg_connection *conn, const std::string &headerName) @@ -184,28 +180,34 @@ public: * @param headerName - header name to get the value from * @returns a char array whcih contains the header value as string */ - static const char* getHeader(struct mg_connection *conn, const std::string &headerName); + static const char *getHeader(struct mg_connection *conn, + const std::string &headerName); /** * getParam(struct mg_connection *conn, const char *, std::string &, size_t) * * Returns a query paramter contained in the supplied buffer. The * occurance value is a zero-based index of a particular key name. This - * should not be confused with the index over all of the keys. Note that this + * should not be confused with the index over all of the keys. Note that + *this * function assumes that parameters are sent as text in http query string * format, which is the default for web forms. This function will work for - * html forms with method="GET" and method="POST" attributes. In other cases, - * you may use a getParam version that directly takes the data instead of the + * html forms with method="GET" and method="POST" attributes. In other + *cases, + * you may use a getParam version that directly takes the data instead of + *the * connection as a first argument. * - * @param conn - parameters are read from the data sent through this connection + * @param conn - parameters are read from the data sent through this + *connection * @param name - the key to search for * @param dst - the destination string - * @param occurrence - the occurrence of the selected name in the query (0 based). + * @param occurrence - the occurrence of the selected name in the query (0 + *based). * @return true if key was found */ static bool getParam(struct mg_connection *conn, const char *name, - std::string &dst, size_t occurrence=0); + std::string &dst, size_t occurrence = 0); /** * getParam(const std::string &, const char *, std::string &, size_t) @@ -217,11 +219,12 @@ public: * @param data - the query string (text) * @param name - the key to search for * @param dst - the destination string - * @param occurrence - the occurrence of the selected name in the query (0 based). + * @param occurrence - the occurrence of the selected name in the query (0 + *based). * @return true if key was found */ static bool getParam(const std::string &data, const char *name, - std::string &dst, size_t occurrence=0) { + std::string &dst, size_t occurrence = 0) { return getParam(data.c_str(), data.length(), name, dst, occurrence); } @@ -236,12 +239,12 @@ public: * @param data_len - length of the query string * @param name - the key to search for * @param dst - the destination string - * @param occurrence - the occurrence of the selected name in the query (0 based). + * @param occurrence - the occurrence of the selected name in the query (0 + *based). * @return true if key was found */ static bool getParam(const char *data, size_t data_len, const char *name, - std::string &dst, size_t occurrence=0); - + std::string &dst, size_t occurrence = 0); /** * urlDecode(const std::string &, std::string &, bool) @@ -253,7 +256,8 @@ public: * uses '+' as character for space, see RFC 1866 section 8.2.1 * http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt */ - static void urlDecode(const std::string &src, std::string &dst, bool is_form_url_encoded=true) { + static void urlDecode(const std::string &src, std::string &dst, + bool is_form_url_encoded = true) { urlDecode(src.c_str(), src.length(), dst, is_form_url_encoded); } @@ -268,7 +272,8 @@ public: * uses '+' as character for space, see RFC 1866 section 8.2.1 * http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt */ - static void urlDecode(const char *src, size_t src_len, std::string &dst, bool is_form_url_encoded=true); + static void urlDecode(const char *src, size_t src_len, std::string &dst, + bool is_form_url_encoded = true); /** * urlDecode(const char *, std::string &, bool) @@ -280,7 +285,8 @@ public: * uses '+' as character for space, see RFC 1866 section 8.2.1 * http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt */ - static void urlDecode(const char *src, std::string &dst, bool is_form_url_encoded=true); + static void urlDecode(const char *src, std::string &dst, + bool is_form_url_encoded = true); /** * urlEncode(const std::string &, std::string &, bool) @@ -289,7 +295,8 @@ public: * @param dst - destination string * @param append - true if string should not be cleared before encoding. */ - static void urlEncode(const std::string &src, std::string &dst, bool append=false) { + static void urlEncode(const std::string &src, std::string &dst, + bool append = false) { urlEncode(src.c_str(), src.length(), dst, append); } @@ -300,7 +307,8 @@ public: * @param dst - destination string * @param append - true if string should not be cleared before encoding. */ - static void urlEncode(const char *src, std::string &dst, bool append=false); + static void urlEncode(const char *src, std::string &dst, + bool append = false); /** * urlEncode(const char *, size_t, std::string &, bool) @@ -310,12 +318,13 @@ public: * @param dst - destination string * @param append - true if string should not be cleared before encoding. */ - static void urlEncode(const char *src, size_t src_len, std::string &dst, bool append=false); + static void urlEncode(const char *src, size_t src_len, std::string &dst, + bool append = false); -protected: + protected: class CivetConnection { - public: - char * postData; + public: + char *postData; unsigned long postDataLen; CivetConnection(); @@ -325,7 +334,7 @@ protected: struct mg_context *context; std::map connections; -private: + private: /** * requestHandler(struct mg_connection *, void *cbdata) * @@ -350,7 +359,6 @@ private: * Stores the user provided close handler */ void (*userCloseHandler)(const struct mg_connection *conn); - }; #endif /* __cplusplus */ diff --git a/include/civetweb.h b/include/civetweb.h index 2a4aff64..decfed1a 100644 --- a/include/civetweb.h +++ b/include/civetweb.h @@ -26,17 +26,17 @@ #define CIVETWEB_VERSION "1.7" #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 +#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 @@ -46,9 +46,8 @@ extern "C" { #endif /* __cplusplus */ -struct mg_context; /* Handle for the HTTP service itself */ -struct mg_connection; /* Handle for the individual connection */ - +struct mg_context; /* Handle for the HTTP service itself */ +struct mg_connection; /* Handle for the individual connection */ /* This structure contains information about the HTTP request. */ struct mg_request_info { @@ -60,23 +59,24 @@ struct mg_request_info { const char *remote_user; /* Authenticated user, or NULL if no auth used */ char remote_addr[48]; /* Client's IP address as a string. */ - long remote_ip; /* Client's IP address. Deprecated: use remote_addr instead */ + long + remote_ip; /* Client's IP address. Deprecated: use remote_addr instead + */ - long long content_length; /* Length (in bytes) of the request body, - can be -1 if no length was given. */ - int remote_port; /* Client's port */ - int is_ssl; /* 1 if SSL-ed, 0 if not */ - void *user_data; /* User data pointer passed to mg_start() */ - void *conn_data; /* Connection-specific user data */ + long long content_length; /* Length (in bytes) of the request body, + can be -1 if no length was given. */ + int remote_port; /* Client's port */ + int is_ssl; /* 1 if SSL-ed, 0 if not */ + void *user_data; /* User data pointer passed to mg_start() */ + void *conn_data; /* Connection-specific user data */ - int num_headers; /* Number of HTTP headers */ + int num_headers; /* Number of HTTP headers */ struct mg_header { - const char *name; /* HTTP header name */ - const 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[64]; /* Maximum 64 headers */ }; - /* This structure needs to be passed to mg_start(), to let civetweb know which callbacks to invoke. For a detailed description, see https://github.com/bel2125/civetweb/blob/master/docs/UserManual.md */ @@ -93,18 +93,18 @@ struct mg_callbacks { the callback must not send any data to the client. 1: callback already processed the request. Civetweb will not send any data after the callback returned. */ - int (*begin_request)(struct mg_connection *); + int (*begin_request)(struct mg_connection *); /* Called when civetweb has finished processing request. */ void (*end_request)(const struct mg_connection *, int reply_status_code); /* Called when civetweb is about to log a message. If callback returns non-zero, civetweb does not log anything. */ - int (*log_message)(const struct mg_connection *, const char *message); + int (*log_message)(const struct mg_connection *, const char *message); /* Called when civetweb is about to log access. If callback returns non-zero, civetweb does not log anything. */ - int (*log_access)(const struct mg_connection *, const char *message); + int (*log_access)(const struct mg_connection *, const char *message); /* Called when civetweb initializes SSL library. Parameters: @@ -113,7 +113,7 @@ struct mg_callbacks { 0: civetweb will set up the SSL certificate. 1: civetweb assumes the callback already set up the certificate. -1: initializing ssl fails. */ - int (*init_ssl)(void *ssl_context, void *user_data); + int (*init_ssl)(void *ssl_context, void *user_data); /* Called when websocket request is received, before websocket handshake. Return value: @@ -136,8 +136,8 @@ struct mg_callbacks { 1: keep this websocket connection open. 0: close this websocket connection. This callback is deprecated, use mg_set_websocket_handler instead. */ - int (*websocket_data)(struct mg_connection *, int bits, - char *data, size_t data_len); + int (*websocket_data)(struct mg_connection *, int bits, char *data, + size_t data_len); /* Called when civetweb is closing a connection. The per-context mutex is locked when this is invoked. This is primarily useful for noting when @@ -157,8 +157,8 @@ struct mg_callbacks { NULL: do not serve file from memory, proceed with normal file open. non-NULL: pointer to the file contents in memory. data_len must be initilized with the size of the memory block. */ - const char * (*open_file)(const struct mg_connection *, - const char *path, size_t *data_len); + const char *(*open_file)(const struct mg_connection *, const char *path, + size_t *data_len); /* Called when civetweb is about to serve Lua server page, if Lua support is enabled. @@ -179,21 +179,20 @@ struct mg_callbacks { Return value: 1: run civetweb error handler. 0: callback already handled the error. */ - int (*http_error)(struct mg_connection *, int status); + int (*http_error)(struct mg_connection *, int status); /* Called after civetweb context has been created, before requests are processed. Parameters: ctx: context handle */ - void (*init_context)(const struct mg_context * ctx); + void (*init_context)(const struct mg_context *ctx); /* Called when civetweb context is deleted. Parameters: ctx: context handle */ - void (*exit_context)(const struct mg_context * ctx); + void (*exit_context)(const struct mg_context *ctx); }; - /* Start web server. Parameters: @@ -220,9 +219,8 @@ struct mg_callbacks { Return: web server context, or NULL on error. */ CIVETWEB_API struct mg_context *mg_start(const struct mg_callbacks *callbacks, - void *user_data, - const char **configuration_options); - + void *user_data, + const char **configuration_options); /* Stop the web server. @@ -231,7 +229,6 @@ CIVETWEB_API struct mg_context *mg_start(const struct mg_callbacks *callbacks, threads are stopped. Context pointer becomes invalid. */ CIVETWEB_API void mg_stop(struct mg_context *); - /* mg_request_handler Called when a new request comes in. This callback is URI based @@ -243,8 +240,7 @@ CIVETWEB_API void mg_stop(struct mg_context *); Returns: 0: the handler could not handle the request, so fall through. 1: the handler processed the request. */ -typedef int (* mg_request_handler)(struct mg_connection *conn, void *cbdata); - +typedef int (*mg_request_handler)(struct mg_connection *conn, void *cbdata); /* mg_set_request_handler @@ -261,11 +257,16 @@ typedef int (* mg_request_handler)(struct mg_connection *conn, void *cbdata); ctx: server context uri: the URI (exact or pattern) for the handler handler: the callback handler to use when the URI is requested. - If NULL, an already registered handler for this URI will be removed. - The URI used to remove a handler must match exactly the one used to + If NULL, an already registered handler for this URI will be + removed. + The URI used to remove a handler must match exactly the one used + to register it (not only a pattern match). cbdata: the callback data to give to the handler when it is called. */ -CIVETWEB_API 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); /* Callback types for websocket handlers in C/C++. @@ -292,23 +293,25 @@ CIVETWEB_API void mg_set_request_handler(struct mg_context *ctx, const char *uri mg_connection_close_handler Is called, when the connection is closed.*/ -typedef int (*mg_websocket_connect_handler)(const struct mg_connection *, void *); +typedef int (*mg_websocket_connect_handler)(const struct mg_connection *, + void *); typedef void (*mg_websocket_ready_handler)(struct mg_connection *, void *); -typedef int (*mg_websocket_data_handler)(struct mg_connection *, int, char *, size_t, void *); -typedef void (*mg_websocket_close_handler)(const struct mg_connection *, void *); +typedef int (*mg_websocket_data_handler)(struct mg_connection *, int, char *, + size_t, void *); +typedef void (*mg_websocket_close_handler)(const struct mg_connection *, + void *); /* mg_set_websocket_handler Set or remove handler functions for websocket connections. This function works similar to mg_set_request_handler - see there. */ -CIVETWEB_API void mg_set_websocket_handler(struct mg_context *ctx, - const char *uri, - mg_websocket_connect_handler connect_handler, - mg_websocket_ready_handler ready_handler, - mg_websocket_data_handler data_handler, - mg_websocket_close_handler close_handler, - void *cbdata - ); +CIVETWEB_API void +mg_set_websocket_handler(struct mg_context *ctx, const char *uri, + mg_websocket_connect_handler connect_handler, + mg_websocket_ready_handler ready_handler, + mg_websocket_data_handler data_handler, + mg_websocket_close_handler close_handler, + void *cbdata); /* Get the value of particular configuration parameter. The value returned is read-only. Civetweb does not allow changing @@ -316,24 +319,23 @@ CIVETWEB_API void mg_set_websocket_handler(struct mg_context *ctx, 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. */ -CIVETWEB_API 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); /* Get context from connection. */ -CIVETWEB_API struct mg_context *mg_get_context(const struct mg_connection *conn); - +CIVETWEB_API struct mg_context * +mg_get_context(const struct mg_connection *conn); /* Get user data passed to mg_start from context. */ CIVETWEB_API void *mg_get_user_data(const struct mg_context *ctx); - /* Set user data for the current connection. */ -CIVETWEB_API void mg_set_user_connection_data(const struct mg_connection *conn, void *data); - +CIVETWEB_API void mg_set_user_connection_data(const struct mg_connection *conn, + void *data); /* Get user data set for the current connection. */ -CIVETWEB_API void *mg_get_user_connection_data(const struct mg_connection *conn); - +CIVETWEB_API void * +mg_get_user_connection_data(const struct mg_connection *conn); #if defined(MG_LEGACY_INTERFACE) /* Return array of strings that represent valid configuration options. @@ -344,11 +346,10 @@ CIVETWEB_API void *mg_get_user_connection_data(const struct mg_connection *conn) CIVETWEB_API const char **mg_get_valid_option_names(void); #endif - struct mg_option { - const char * name; + const char *name; int type; - const char * default_value; + const char *default_value; }; enum { @@ -361,13 +362,11 @@ enum { 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. It is the caller's responsibility to make sure ports and ssl each @@ -375,8 +374,8 @@ CIVETWEB_API const struct mg_option *mg_get_valid_options(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. */ -CIVETWEB_API 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. @@ -391,14 +390,12 @@ CIVETWEB_API size_t mg_get_ports(const struct mg_context *ctx, size_t size, int* Return: 1 on success, 0 on error. */ CIVETWEB_API int mg_modify_passwords_file(const char *passwords_file_name, - const char *domain, - const char *user, + const char *domain, const char *user, const char *password); - /* Return information associated with the request. */ -CIVETWEB_API const struct mg_request_info *mg_get_request_info(const struct mg_connection *); - +CIVETWEB_API const struct mg_request_info * +mg_get_request_info(const struct mg_connection *); /* Send data to the client. Return: @@ -407,7 +404,6 @@ CIVETWEB_API const struct mg_request_info *mg_get_request_info(const struct mg_c >0 number of bytes written on success */ 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_connection to ensure that the transmission is not interrupted, i.e., when the application is proactively communicating and responding to @@ -420,17 +416,16 @@ CIVETWEB_API 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 */ -CIVETWEB_API int mg_websocket_write(struct mg_connection* conn, int opcode, +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. */ -CIVETWEB_API void mg_lock_connection(struct mg_connection* conn); -CIVETWEB_API void mg_unlock_connection(struct mg_connection* conn); +CIVETWEB_API void mg_lock_connection(struct mg_connection *conn); +CIVETWEB_API void mg_unlock_connection(struct mg_connection *conn); #if defined(MG_LEGACY_INTERFACE) #define mg_lock mg_lock_connection @@ -439,9 +434,8 @@ CIVETWEB_API void mg_unlock_connection(struct mg_connection* conn); /* Lock server context. This lock may be used to protect resources that are shared between different connection/worker threads. */ -CIVETWEB_API void mg_lock_context(struct mg_context* ctx); -CIVETWEB_API void mg_unlock_context(struct mg_context* ctx); - +CIVETWEB_API void mg_lock_context(struct mg_context *ctx); +CIVETWEB_API void mg_unlock_context(struct mg_context *ctx); /* Opcodes, from http://tools.ietf.org/html/rfc6455 */ enum { @@ -453,7 +447,6 @@ enum { WEBSOCKET_OPCODE_PONG = 0xa }; - /* Macros for enabling compiler-specific checks for printf-like arguments. */ #undef PRINTF_FORMAT_STRING #if defined(_MSC_VER) && _MSC_VER >= 1400 @@ -476,13 +469,12 @@ enum { /* Send data to the client using printf() semantics. Works exactly like mg_write(), but allows to do message formatting. */ CIVETWEB_API int mg_printf(struct mg_connection *, - PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3); - + PRINTF_FORMAT_STRING(const char *fmt), ...) + PRINTF_ARGS(2, 3); /* Send contents of the entire file together with HTTP headers. */ CIVETWEB_API void mg_send_file(struct mg_connection *conn, const char *path); - /* Read data from the remote end, return number of bytes read. Return: 0 connection has been closed by peer. No more data could be read. @@ -490,14 +482,13 @@ CIVETWEB_API void mg_send_file(struct mg_connection *conn, const char *path); > 0 number of bytes read into the buffer. */ CIVETWEB_API 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. */ -CIVETWEB_API 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. @@ -521,7 +512,6 @@ CIVETWEB_API const char *mg_get_header(const struct mg_connection *, const char 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. Parameters: @@ -546,8 +536,8 @@ CIVETWEB_API 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. */ 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); - + const char *var_name, char *dst, size_t dst_len, + size_t occurrence); /* Fetch value of certain cookie variable into the destination buffer. @@ -565,7 +555,6 @@ CIVETWEB_API int mg_get_var2(const char *data, size_t data_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. host: host name to connect to, e.g. "foo.com", or "10.12.40.1". port: port number, e.g. 80. @@ -581,37 +570,33 @@ CIVETWEB_API 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"); */ -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); - +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(). */ 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. */ -CIVETWEB_API 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 *); +typedef void *(*mg_thread_func_t)(void *); 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. */ CIVETWEB_API const char *mg_get_builtin_mime_type(const char *file_name); - /* Return Civetweb version. */ CIVETWEB_API const char *mg_version(void); - /* URL-decode input buffer into destination buffer. 0-terminate the destination buffer. form-url-encoded data differs from URI encoding in a way that it @@ -621,13 +606,11 @@ CIVETWEB_API const char *mg_version(void); 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. */ 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 ASCIIz strings. When function returns, buf will contain human-readable @@ -636,7 +619,6 @@ CIVETWEB_API int mg_url_encode(const char *src, char *dst, size_t dst_len); mg_md5(buf, "aa", "bb", NULL); */ CIVETWEB_API char *mg_md5(char buf[33], ...); - /* Print error message to the opened error log stream. This utilizes the provided logging configuration. conn: connection @@ -645,22 +627,24 @@ CIVETWEB_API char *mg_md5(char buf[33], ...); Example: mg_cry(conn,"i like %s", "logging"); */ CIVETWEB_API void mg_cry(const struct mg_connection *conn, - PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3); - + PRINTF_FORMAT_STRING(const char *fmt), ...) + PRINTF_ARGS(2, 3); /* utility method to compare two buffers, case incensitive. */ CIVETWEB_API int mg_strncasecmp(const char *s1, const char *s2, size_t len); - /* Connect to a websocket as a client Parameters: - host: host to connect to, i.e. "echo.websocket.org" or "192.168.1.1" or "localhost" + host: host to connect to, i.e. "echo.websocket.org" or "192.168.1.1" or + "localhost" port: server port use_ssl: make a secure connection to server error_buffer, error_buffer_size: buffer for an error message - path: server path you are trying to connect to, i.e. if connection to localhost/app, path should be "/app" + path: server path you are trying to connect to, i.e. if connection to + localhost/app, path should be "/app" origin: value of the Origin HTTP header - data_func: callback that should be used when data is received from the server + data_func: callback that should be used when data is received from the + server user_data: user supplied argument Return: @@ -668,16 +652,16 @@ CIVETWEB_API int mg_strncasecmp(const char *s1, const char *s2, size_t len); On error, NULL. Se error_buffer for details. */ -CIVETWEB_API struct mg_connection *mg_connect_websocket_client(const char *host, int port, int use_ssl, - char *error_buffer, size_t error_buffer_size, - const char *path, const char *origin, - mg_websocket_data_handler data_func, mg_websocket_close_handler close_func, - void * user_data); - +CIVETWEB_API struct mg_connection *mg_connect_websocket_client( + const char *host, int port, int use_ssl, char *error_buffer, + size_t error_buffer_size, const char *path, const char *origin, + mg_websocket_data_handler data_func, mg_websocket_close_handler close_func, + void *user_data); /* Connect to a TCP server as a client (can be used to connect to a HTTP server) Parameters: - host: host to connect to, i.e. "www.wikipedia.org" or "192.168.1.1" or "localhost" + host: host to connect to, i.e. "www.wikipedia.org" or "192.168.1.1" or + "localhost" port: server port use_ssl: make a secure connection to server error_buffer, error_buffer_size: buffer for an error message @@ -686,27 +670,26 @@ CIVETWEB_API struct mg_connection *mg_connect_websocket_client(const char *host, On success, valid mg_connection object. On error, NULL. Se error_buffer for details. */ -CIVETWEB_API struct mg_connection *mg_connect_client(const char *host, int port, int use_ssl, - char *error_buffer, size_t error_buffer_size); - - -enum { - TIMEOUT_INFINITE = -1 -}; +CIVETWEB_API struct mg_connection *mg_connect_client(const char *host, int port, + int use_ssl, + char *error_buffer, + size_t error_buffer_size); +enum { TIMEOUT_INFINITE = -1 }; /* Wait for a response from the server Parameters: conn: connection ebuf, ebuf_len: error message placeholder. - timeout: time to wait for a response in milliseconds (if < 0 then wait forever) + timeout: time to wait for a response in milliseconds (if < 0 then wait + forever) Return: On success, >= 0 On error/timeout, < 0 */ -CIVETWEB_API int mg_get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int timeout); - +CIVETWEB_API int mg_get_response(struct mg_connection *conn, char *ebuf, + size_t ebuf_len, int timeout); #ifdef __cplusplus } diff --git a/src/CivetServer.cpp b/src/CivetServer.cpp index 39d762aa..a69648c4 100644 --- a/src/CivetServer.cpp +++ b/src/CivetServer.cpp @@ -15,50 +15,47 @@ #define UNUSED_PARAMETER(x) (void)(x) #endif -bool CivetHandler::handleGet(CivetServer *server, struct mg_connection *conn) -{ +bool CivetHandler::handleGet(CivetServer *server, struct mg_connection *conn) { UNUSED_PARAMETER(server); UNUSED_PARAMETER(conn); return false; } -bool CivetHandler::handlePost(CivetServer *server, struct mg_connection *conn) -{ +bool CivetHandler::handlePost(CivetServer *server, struct mg_connection *conn) { UNUSED_PARAMETER(server); UNUSED_PARAMETER(conn); return false; } -bool CivetHandler::handlePut(CivetServer *server, struct mg_connection *conn) -{ +bool CivetHandler::handlePut(CivetServer *server, struct mg_connection *conn) { UNUSED_PARAMETER(server); UNUSED_PARAMETER(conn); return false; } -bool CivetHandler::handleDelete(CivetServer *server, struct mg_connection *conn) -{ +bool CivetHandler::handleDelete(CivetServer *server, + struct mg_connection *conn) { UNUSED_PARAMETER(server); UNUSED_PARAMETER(conn); return false; } -bool CivetHandler::handleOptions(CivetServer *server, struct mg_connection *conn) -{ +bool CivetHandler::handleOptions(CivetServer *server, + struct mg_connection *conn) { UNUSED_PARAMETER(server); UNUSED_PARAMETER(conn); return false; } -int CivetServer::requestHandler(struct mg_connection *conn, void *cbdata) -{ +int CivetServer::requestHandler(struct mg_connection *conn, void *cbdata) { const struct mg_request_info *request_info = mg_get_request_info(conn); assert(request_info != NULL); - CivetServer *me = (CivetServer*) (request_info->user_data); + CivetServer *me = (CivetServer *)(request_info->user_data); assert(me != NULL); // Happens when a request hits the server before the context is saved - if (me->context == NULL) return 0; + if (me->context == NULL) + return 0; mg_lock_context(me->context); me->connections[conn] = CivetConnection(); @@ -84,9 +81,8 @@ int CivetServer::requestHandler(struct mg_connection *conn, void *cbdata) } CivetServer::CivetServer(const char **options, - const struct mg_callbacks *_callbacks) : - context(0) -{ + const struct mg_callbacks *_callbacks) + : context(0) { struct mg_callbacks callbacks; memset(&callbacks, 0, sizeof(callbacks)); @@ -98,84 +94,82 @@ CivetServer::CivetServer(const char **options, } callbacks.connection_close = closeHandler; context = mg_start(&callbacks, this, options); - if (context == NULL) throw CivetException("null context when constructing CivetServer. Possible problem binding to port."); + if (context == NULL) + throw CivetException("null context when constructing CivetServer. " + "Possible problem binding to port."); } -CivetServer::~CivetServer() -{ - close(); -} +CivetServer::~CivetServer() { close(); } -void CivetServer::closeHandler(const struct mg_connection *conn) -{ +void CivetServer::closeHandler(const struct mg_connection *conn) { const struct mg_request_info *request_info = mg_get_request_info(conn); assert(request_info != NULL); - CivetServer *me = (CivetServer*) (request_info->user_data); + CivetServer *me = (CivetServer *)(request_info->user_data); assert(me != NULL); // Happens when a request hits the server before the context is saved - if (me->context == NULL) return; + if (me->context == NULL) + return; - if (me->userCloseHandler) me->userCloseHandler(conn); + if (me->userCloseHandler) + me->userCloseHandler(conn); mg_lock_context(me->context); me->connections.erase(const_cast(conn)); mg_unlock_context(me->context); } -void CivetServer::addHandler(const std::string &uri, CivetHandler *handler) -{ +void CivetServer::addHandler(const std::string &uri, CivetHandler *handler) { mg_set_request_handler(context, uri.c_str(), requestHandler, handler); } -void CivetServer::removeHandler(const std::string &uri) -{ +void CivetServer::removeHandler(const std::string &uri) { mg_set_request_handler(context, uri.c_str(), NULL, NULL); } -void CivetServer::close() -{ +void CivetServer::close() { if (context) { - mg_stop (context); + mg_stop(context); context = 0; } } -int CivetServer::getCookie(struct mg_connection *conn, const std::string &cookieName, std::string &cookieValue) -{ - //Maximum cookie length as per microsoft is 4096. http://msdn.microsoft.com/en-us/library/ms178194.aspx +int CivetServer::getCookie(struct mg_connection *conn, + const std::string &cookieName, + std::string &cookieValue) { + // Maximum cookie length as per microsoft is 4096. + // http://msdn.microsoft.com/en-us/library/ms178194.aspx char _cookieValue[4096]; const char *cookie = mg_get_header(conn, "Cookie"); - int lRead = mg_get_cookie(cookie, cookieName.c_str(), _cookieValue, sizeof(_cookieValue)); + int lRead = mg_get_cookie(cookie, cookieName.c_str(), _cookieValue, + sizeof(_cookieValue)); cookieValue.clear(); cookieValue.append(_cookieValue); return lRead; } -const char* CivetServer::getHeader(struct mg_connection *conn, const std::string &headerName) -{ +const char *CivetServer::getHeader(struct mg_connection *conn, + const std::string &headerName) { return mg_get_header(conn, headerName.c_str()); } -void -CivetServer::urlDecode(const char *src, std::string &dst, bool is_form_url_encoded) -{ +void CivetServer::urlDecode(const char *src, std::string &dst, + bool is_form_url_encoded) { urlDecode(src, strlen(src), dst, is_form_url_encoded); } -void -CivetServer::urlDecode(const char *src, size_t src_len, std::string &dst, bool is_form_url_encoded) -{ +void CivetServer::urlDecode(const char *src, size_t src_len, std::string &dst, + bool is_form_url_encoded) { int i, j, a, b; #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W') dst.clear(); for (i = j = 0; i < (int)src_len; i++, j++) { if (i < (int)src_len - 2 && src[i] == '%' && - isxdigit(* (const unsigned char *) (src + i + 1)) && - isxdigit(* (const unsigned char *) (src + i + 2))) { - a = tolower(* (const unsigned char *) (src + i + 1)); - b = tolower(* (const unsigned char *) (src + i + 2)); - dst.push_back((char) ((HEXTOI(a) << 4) | HEXTOI(b))); + isxdigit(*(const unsigned char *)(src + i + 1)) && + isxdigit(*(const unsigned char *)(src + i + 2))) { + a = tolower(*(const unsigned char *)(src + i + 1)); + b = tolower(*(const unsigned char *)(src + i + 2)); + dst.push_back((char)((HEXTOI(a) << 4) | HEXTOI(b))); i += 2; } else if (is_form_url_encoded && src[i] == '+') { dst.push_back(' '); @@ -185,14 +179,12 @@ CivetServer::urlDecode(const char *src, size_t src_len, std::string &dst, bool i } } -bool -CivetServer::getParam(struct mg_connection *conn, const char *name, - std::string &dst, size_t occurrence) -{ +bool CivetServer::getParam(struct mg_connection *conn, const char *name, + std::string &dst, size_t occurrence) { const char *formParams = NULL; const struct mg_request_info *ri = mg_get_request_info(conn); assert(ri != NULL); - CivetServer *me = (CivetServer*) (ri->user_data); + CivetServer *me = (CivetServer *)(ri->user_data); assert(me != NULL); mg_lock_context(me->context); CivetConnection &conobj = me->connections[conn]; @@ -202,13 +194,15 @@ CivetServer::getParam(struct mg_connection *conn, const char *name, if (conobj.postData != NULL) { formParams = conobj.postData; } else { - const char * con_len_str = mg_get_header(conn, "Content-Length"); + const char *con_len_str = mg_get_header(conn, "Content-Length"); if (con_len_str) { unsigned long con_len = atoi(con_len_str); - if (con_len>0) { - // Add one extra character: in case the post-data is a text, it is required as 0-termination. - // Do not increment con_len, since the 0 terminating is not part of the content (text or binary). - conobj.postData = (char*)malloc(con_len + 1); + if (con_len > 0) { + // Add one extra character: in case the post-data is a text, it + // is required as 0-termination. + // Do not increment con_len, since the 0 terminating is not part + // of the content (text or binary). + conobj.postData = (char *)malloc(con_len + 1); if (conobj.postData != NULL) { // malloc may fail for huge requests mg_read(conn, conobj.postData, con_len); @@ -220,7 +214,8 @@ CivetServer::getParam(struct mg_connection *conn, const char *name, } } if (formParams == NULL) { - // get requests do store html
field values in the http query_string + // get requests do store html field values in the http + // query_string formParams = ri->query_string; } mg_unlock_connection(conn); @@ -232,10 +227,8 @@ CivetServer::getParam(struct mg_connection *conn, const char *name, return false; } -bool -CivetServer::getParam(const char *data, size_t data_len, const char *name, - std::string &dst, size_t occurrence) -{ +bool CivetServer::getParam(const char *data, size_t data_len, const char *name, + std::string &dst, size_t occurrence) { const char *p, *e, *s; size_t name_len; @@ -255,7 +248,7 @@ CivetServer::getParam(const char *data, size_t data_len, const char *name, p += name_len + 1; // Point s to the end of the value - s = (const char *) memchr(p, '&', (size_t)(e - p)); + s = (const char *)memchr(p, '&', (size_t)(e - p)); if (s == NULL) { s = e; } @@ -269,15 +262,12 @@ CivetServer::getParam(const char *data, size_t data_len, const char *name, return false; } -void -CivetServer::urlEncode(const char *src, std::string &dst, bool append) -{ +void CivetServer::urlEncode(const char *src, std::string &dst, bool append) { urlEncode(src, strlen(src), dst, append); } -void -CivetServer::urlEncode(const char *src, size_t src_len, std::string &dst, bool append) -{ +void CivetServer::urlEncode(const char *src, size_t src_len, std::string &dst, + bool append) { static const char *dont_escape = "._-$,;~()"; static const char *hex = "0123456789abcdef"; @@ -285,20 +275,18 @@ CivetServer::urlEncode(const char *src, size_t src_len, std::string &dst, bool a dst.clear(); for (; src_len > 0; src++, src_len--) { - if (isalnum(*(const unsigned char *) src) || - strchr(dont_escape, * (const unsigned char *) src) != NULL) { + if (isalnum(*(const unsigned char *)src) || + strchr(dont_escape, *(const unsigned char *)src) != NULL) { dst.push_back(*src); } else { dst.push_back('%'); - dst.push_back(hex[(* (const unsigned char *) src) >> 4]); - dst.push_back(hex[(* (const unsigned char *) src) & 0xf]); + dst.push_back(hex[(*(const unsigned char *)src) >> 4]); + dst.push_back(hex[(*(const unsigned char *)src) & 0xf]); } } } -std::vector -CivetServer::getListeningPorts() -{ +std::vector CivetServer::getListeningPorts() { std::vector ports(10); std::vector ssl(10); size_t size = mg_get_ports(context, ports.size(), &ports[0], &ssl[0]); @@ -307,12 +295,9 @@ CivetServer::getListeningPorts() return ports; } - CivetServer::CivetConnection::CivetConnection() { postData = NULL; postDataLen = 0; } -CivetServer::CivetConnection::~CivetConnection() { - free(postData); -} +CivetServer::CivetConnection::~CivetConnection() { free(postData); } diff --git a/src/main.c b/src/main.c index 0d1107ea..2f35de86 100644 --- a/src/main.c +++ b/src/main.c @@ -22,13 +22,13 @@ #if defined(_WIN32) #ifndef _CRT_SECURE_NO_WARNINGS -#define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */ +#define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */ #endif #ifndef _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_NO_DEPRECATE #endif #else -#define _XOPEN_SOURCE 600 /* For PATH_MAX on linux */ +#define _XOPEN_SOURCE 600 /* For PATH_MAX on linux */ #endif #ifndef IGNORE_UNUSED_RESULT @@ -59,13 +59,13 @@ #include #include -#define getcwd(a,b) _getcwd(a,b) +#define getcwd(a, b) _getcwd(a, b) #if !defined(__MINGW32__) extern char *_getcwd(char *buf, size_t size); #endif -static int guard = 0; /* test if any dialog is already open */ +static int guard = 0; /* test if any dialog is already open */ -#if defined (_MSC_VER) +#if defined(_MSC_VER) #define strdup _strdup /* or #pragma warning (disable : 4996 ) */ #endif @@ -75,13 +75,13 @@ static int guard = 0; /* test if any dialog is already open */ #endif #ifndef S_ISDIR -#define S_ISDIR(x) ((x) & _S_IFDIR) +#define S_ISDIR(x) ((x)&_S_IFDIR) #endif #define DIRSEP '\\' #define snprintf _snprintf #define vsnprintf _vsnprintf -#define sleep(x) Sleep((x) * 1000) +#define sleep(x) Sleep((x)*1000) #define WINCDECL __cdecl #define abs_path(rel, abs, abs_size) _fullpath((abs), (rel), (abs_size)) #else @@ -96,16 +96,18 @@ static int guard = 0; /* test if any dialog is already open */ #define MAX_CONF_FILE_LINE_SIZE (8 * 1024) struct tuser_data { - char * first_message; + char *first_message; }; -static int g_exit_flag = 0; /* Main loop should exit */ -static char g_server_base_name[40]; /* Set by init_server_name() */ -static char *g_server_name; /* Set by init_server_name() */ -static char *g_icon_name; /* Set by init_server_name() */ -static char g_config_file[PATH_MAX] = ""; /* Set by process_command_line_arguments() */ -static struct mg_context *g_ctx; /* Set by start_civetweb() */ -static struct tuser_data g_user_data; /* Passed to mg_start() by start_civetweb() */ +static int g_exit_flag = 0; /* Main loop should exit */ +static char g_server_base_name[40]; /* Set by init_server_name() */ +static char *g_server_name; /* Set by init_server_name() */ +static char *g_icon_name; /* Set by init_server_name() */ +static char g_config_file[PATH_MAX] = + ""; /* Set by process_command_line_arguments() */ +static struct mg_context *g_ctx; /* Set by start_civetweb() */ +static struct tuser_data + g_user_data; /* Passed to mg_start() by start_civetweb() */ #if !defined(CONFIG_FILE) #define CONFIG_FILE "civetweb.conf" @@ -120,31 +122,22 @@ static struct tuser_data g_user_data; /* Passed to mg_start() by start_civet #define CONFIG_FILE2 "/usr/local/etc/civetweb.conf" #endif -enum { - OPTION_TITLE, - OPTION_ICON, - NUM_MAIN_OPTIONS -}; +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} -}; + {"title", CONFIG_TYPE_STRING, NULL}, + {"icon", CONFIG_TYPE_STRING, NULL}, + {NULL, CONFIG_TYPE_UNKNOWN, NULL}}; -static void WINCDECL signal_handler(int sig_num) -{ - g_exit_flag = sig_num; -} +static void WINCDECL signal_handler(int sig_num) { g_exit_flag = sig_num; } -static void die(const char *fmt, ...) -{ +static void die(const char *fmt, ...) { va_list ap; char msg[200] = ""; va_start(ap, fmt); - (void) vsnprintf(msg, sizeof(msg) -1, fmt, ap); - msg[sizeof(msg)-1] = 0; + (void)vsnprintf(msg, sizeof(msg) - 1, fmt, ap); + msg[sizeof(msg) - 1] = 0; va_end(ap); #if defined(_WIN32) @@ -160,22 +153,19 @@ static void die(const char *fmt, ...) static int MakeConsole(); #endif -static void show_server_name(void) -{ +static void show_server_name(void) { #ifdef WIN32 MakeConsole(); #endif - fprintf(stderr, "CivetWeb v%s, built on %s\n", - mg_version(), __DATE__); + fprintf(stderr, "CivetWeb v%s, built on %s\n", mg_version(), __DATE__); } -static void show_usage_and_exit(const char *exeName) -{ +static void show_usage_and_exit(const char *exeName) { const struct mg_option *options; int i; - if (exeName==0 || *exeName==0) { + if (exeName == 0 || *exeName == 0) { exeName = "civetweb"; } @@ -186,19 +176,26 @@ static void show_usage_and_exit(const char *exeName) fprintf(stderr, " %s [config_file]\n", exeName); fprintf(stderr, " %s [-option value ...]\n", exeName); fprintf(stderr, " Add user/change password:\n"); - fprintf(stderr, " %s -A \n", exeName); + fprintf(stderr, " %s -A \n", + exeName); fprintf(stderr, " Remove user:\n"); fprintf(stderr, " %s -R \n", exeName); fprintf(stderr, "\nOPTIONS:\n"); 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)); + 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)); + fprintf(stderr, " -%s %s\n", options[i].name, + ((options[i].default_value == NULL) + ? "" + : options[i].default_value)); } exit(EXIT_FAILURE); @@ -213,13 +210,13 @@ static const char *config_file_top_comment = "# To make a change, remove leading '#', modify option's value,\n" "# save this file and then restart Civetweb.\n\n"; -static const char *get_url_to_first_open_port(const struct mg_context *ctx) -{ +static const char *get_url_to_first_open_port(const struct mg_context *ctx) { static char url[100]; const char *open_ports = mg_get_option(ctx, "listening_ports"); int a, b, c, d, port, n; - if (sscanf(open_ports, "%d.%d.%d.%d:%d%n", &a, &b, &c, &d, &port, &n) == 5) { + if (sscanf(open_ports, "%d.%d.%d.%d:%d%n", &a, &b, &c, &d, &port, &n) == + 5) { snprintf(url, sizeof(url), "%s://%d.%d.%d.%d:%d", open_ports[n] == 's' ? "https" : "http", a, b, c, d, port); } else if (sscanf(open_ports, "%d%n", &port, &n) == 1) { @@ -232,8 +229,7 @@ static const char *get_url_to_first_open_port(const struct mg_context *ctx) return url; } -static void create_config_file(const struct mg_context *ctx, const char *path) -{ +static void create_config_file(const struct mg_context *ctx, const char *path) { const struct mg_option *options; const char *value; FILE *fp; @@ -247,27 +243,26 @@ static void create_config_file(const struct mg_context *ctx, const char *path) 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 : ""); + fprintf(fp, "# %s %s\n", options[i].name, + value ? value : ""); } fclose(fp); } } #endif -static char *sdup(const char *str) -{ +static char *sdup(const char *str) { size_t len; char *p; len = strlen(str) + 1; - if ((p = (char *) malloc(len)) != NULL) { + if ((p = (char *)malloc(len)) != NULL) { memcpy(p, str, len); } return p; } -static const char *get_option(char **options, const char *option_name) -{ +static const char *get_option(char **options, const char *option_name) { int i = 0; const char *opt_value = NULL; @@ -276,9 +271,9 @@ static const char *get_option(char **options, const char *option_name) but it currently is an array with options[2*i] = key, options[2*i + 1] = value */ - while (options[2*i] != NULL) { - if (strcmp(options[2*i], option_name) == 0) { - opt_value = options[2*i + 1]; + while (options[2 * i] != NULL) { + if (strcmp(options[2 * i], option_name) == 0) { + opt_value = options[2 * i + 1]; break; } i++; @@ -286,14 +281,14 @@ static const char *get_option(char **options, const char *option_name) return opt_value; } -static int set_option(char **options, const char *name, const char *value) -{ +static int set_option(char **options, const char *name, const char *value) { int i, type; const struct mg_option *default_options = mg_get_valid_options(); for (i = 0; main_config_options[i].name != NULL; 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 */ + 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; } } @@ -305,47 +300,48 @@ static int set_option(char **options, const char *name, const char *value) } } switch (type) { - case CONFIG_TYPE_UNKNOWN: - /* unknown option */ + case CONFIG_TYPE_UNKNOWN: + /* unknown option */ + return 0; + case CONFIG_TYPE_NUMBER: + /* integer number > 0, e.g. number of threads */ + if (atol(value) < 1) { + /* invalid number */ return 0; - case CONFIG_TYPE_NUMBER: - /* integer number > 0, e.g. number of threads */ - if (atol(value)<1) { - /* invalid number */ - return 0; - } - break; - case CONFIG_TYPE_STRING: - /* any text */ - break; - case CONFIG_TYPE_BOOLEAN: - /* boolean value, yes or no */ - if ((0!=strcmp(value,"yes")) && (0!=strcmp(value,"no"))) { - /* invalid boolean */ - return 0; - } - break; - case CONFIG_TYPE_FILE: - case CONFIG_TYPE_DIRECTORY: - /* TODO: check this option when it is set, instead of calling verify_existence later */ - break; - case CONFIG_TYPE_EXT_PATTERN: - /* list of file extentions */ - break; - default: - die("Unknown option type - option %s", name); - break; + } + break; + case CONFIG_TYPE_STRING: + /* any text */ + break; + case CONFIG_TYPE_BOOLEAN: + /* boolean value, yes or no */ + if ((0 != strcmp(value, "yes")) && (0 != strcmp(value, "no"))) { + /* invalid boolean */ + return 0; + } + break; + case CONFIG_TYPE_FILE: + case CONFIG_TYPE_DIRECTORY: + /* TODO: check this option when it is set, instead of calling + * verify_existence later */ + break; + case CONFIG_TYPE_EXT_PATTERN: + /* list of file extentions */ + break; + default: + die("Unknown option type - option %s", name); + break; } for (i = 0; i < MAX_OPTIONS; i++) { - if (options[2*i] == NULL) { - options[2*i] = sdup(name); - options[2*i + 1] = sdup(value); - options[2*i + 2] = NULL; + if (options[2 * i] == NULL) { + options[2 * i] = sdup(name); + options[2 * i + 1] = sdup(value); + options[2 * i + 2] = NULL; break; - } else if (!strcmp(options[2*i], name)) { - free(options[2*i + 1]); - options[2*i + 1] = sdup(value); + } else if (!strcmp(options[2 * i], name)) { + free(options[2 * i + 1]); + options[2 * i + 1] = sdup(value); break; } } @@ -354,7 +350,7 @@ static int set_option(char **options, const char *name, const char *value) die("Too many options specified"); } - if (options[2*i] == NULL || options[2*i + 1] == NULL) { + if (options[2 * i] == NULL || options[2 * i + 1] == NULL) { die("Out of memory"); } @@ -362,8 +358,7 @@ static int set_option(char **options, const char *name, const char *value) return 1; } -static void read_config_file(const char *config_file, char **options) -{ +static void read_config_file(const char *config_file, char **options) { char line[MAX_CONF_FILE_LINE_SIZE], *p; FILE *fp = NULL; size_t i, j, cmd_line_opts_start = 1, line_no = 0; @@ -382,46 +377,52 @@ static void read_config_file(const char *config_file, char **options) /* Loop over the lines in config file */ while (fgets(line, sizeof(line), fp) != NULL) { - if (!line_no && !memcmp(line,"\xEF\xBB\xBF",3)) { + if (!line_no && !memcmp(line, "\xEF\xBB\xBF", 3)) { /* strip UTF-8 BOM */ - p = line+3; + p = line + 3; } else { p = line; } line_no++; /* Ignore empty lines and comments */ - for (i = 0; isspace(* (unsigned char *) &line[i]); ) i++; + for (i = 0; isspace(*(unsigned char *)&line[i]);) + i++; if (p[i] == '#' || p[i] == '\0') { continue; } /* 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; + 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++; + 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 */ + /* 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++; + /* 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); + if (!set_option(options, line + i, line + j)) { + printf("%s: line %d is invalid, ignoring it:\n %s", config_file, + (int)line_no, p); } } - (void) fclose(fp); + (void)fclose(fp); } } -static void process_command_line_arguments(char *argv[], char **options) -{ +static void process_command_line_arguments(char *argv[], char **options) { char *p; size_t i, cmd_line_opts_start = 1; #ifdef CONFIG_FILE2 @@ -430,16 +431,16 @@ static void process_command_line_arguments(char *argv[], char **options) /* Should we use a config file ? */ if (argv[1] != NULL && argv[1][0] != '-') { - snprintf(g_config_file, sizeof(g_config_file)-1, "%s", argv[1]); + snprintf(g_config_file, sizeof(g_config_file) - 1, "%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(g_config_file, sizeof(g_config_file)-1, "%s", CONFIG_FILE); + snprintf(g_config_file, sizeof(g_config_file) - 1, "%s", CONFIG_FILE); } else { - snprintf(g_config_file, sizeof(g_config_file)-1, "%.*s%c%s", - (int) (p - argv[0]), argv[0], DIRSEP, CONFIG_FILE); + snprintf(g_config_file, sizeof(g_config_file) - 1, "%.*s%c%s", + (int)(p - argv[0]), argv[0], DIRSEP, CONFIG_FILE); } - g_config_file[sizeof(g_config_file)-1] = 0; + g_config_file[sizeof(g_config_file) - 1] = 0; #ifdef CONFIG_FILE2 fp = fopen(g_config_file, "r"); @@ -477,32 +478,34 @@ static void process_command_line_arguments(char *argv[], char **options) } } -static void init_server_name(int argc, const char *argv[]) -{ +static void init_server_name(int argc, const char *argv[]) { int i; - assert(sizeof(main_config_options)/sizeof(main_config_options[0]) == NUM_MAIN_OPTIONS+1); - assert((strlen(mg_version())+12) 1 && !strcmp(argv[1], "-A")) { if (argc != 6) { show_usage_and_exit(argv[0]); } - exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], argv[5]) ? - EXIT_SUCCESS : EXIT_FAILURE); + exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], argv[5]) + ? EXIT_SUCCESS + : EXIT_FAILURE); } /* Edit passwords file: Remove user, if -R option is specified */ @@ -659,11 +663,13 @@ static void start_civetweb(int argc, char *argv[]) if (argc != 5) { show_usage_and_exit(argv[0]); } - exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], NULL) ? - EXIT_SUCCESS : EXIT_FAILURE); + exit(mg_modify_passwords_file(argv[2], argv[3], argv[4], NULL) + ? EXIT_SUCCESS + : EXIT_FAILURE); } - /* Call Lua with additional Civetweb specific Lua functions, if -L option is specified */ + /* Call Lua with additional Civetweb specific Lua functions, if -L option is + * specified */ if (argc > 1 && !strcmp(argv[1], "-L")) { #ifdef USE_LUA @@ -679,7 +685,8 @@ static void start_civetweb(int argc, char *argv[]) } /* Show usage if -h or --help options are specified */ - if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "-H") || !strcmp(argv[1], "--help"))) { + if (argc == 2 && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "-H") || + !strcmp(argv[1], "--help"))) { show_usage_and_exit(argv[0]); } @@ -719,18 +726,19 @@ static void start_civetweb(int argc, char *argv[]) /* Start Civetweb */ memset(&callbacks, 0, sizeof(callbacks)); callbacks.log_message = &log_message; - g_ctx = mg_start(&callbacks, &g_user_data, (const char **) options); + g_ctx = mg_start(&callbacks, &g_user_data, (const char **)options); for (i = 0; options[i] != NULL; i++) { free(options[i]); } if (g_ctx == NULL) { - die("Failed to start Civetweb:\n%s", (g_user_data.first_message == NULL) ? "unknown reason" : g_user_data.first_message); + die("Failed to start Civetweb:\n%s", (g_user_data.first_message == NULL) + ? "unknown reason" + : g_user_data.first_message); } } -void stop_civetweb(void) -{ +void stop_civetweb(void) { mg_stop(g_ctx); free(g_user_data.first_message); g_user_data.first_message = NULL; @@ -738,10 +746,24 @@ void stop_civetweb(void) #ifdef _WIN32 enum { - ID_ICON = 100, ID_QUIT, ID_SETTINGS, ID_SEPARATOR, ID_INSTALL_SERVICE, - ID_REMOVE_SERVICE, ID_STATIC, ID_GROUP, ID_PASSWORD, - ID_SAVE, ID_RESET_DEFAULTS, ID_RESET_FILE, ID_RESET_ACTIVE, - ID_STATUS, ID_CONNECT, ID_ADD_USER, ID_ADD_USER_NAME, ID_ADD_USER_REALM, + ID_ICON = 100, + ID_QUIT, + ID_SETTINGS, + ID_SEPARATOR, + ID_INSTALL_SERVICE, + ID_REMOVE_SERVICE, + ID_STATIC, + ID_GROUP, + ID_PASSWORD, + ID_SAVE, + ID_RESET_DEFAULTS, + ID_RESET_FILE, + ID_RESET_ACTIVE, + ID_STATUS, + ID_CONNECT, + ID_ADD_USER, + ID_ADD_USER_NAME, + ID_ADD_USER_REALM, ID_INPUT_LINE, /* All dynamically created text boxes for options have IDs starting from @@ -759,8 +781,7 @@ static SERVICE_STATUS_HANDLE hStatus; static const char *service_magic_argument = "--"; static NOTIFYICONDATA TrayIcon; -static void WINAPI ControlHandler(DWORD code) -{ +static void WINAPI ControlHandler(DWORD code) { if (code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN) { ss.dwWin32ExitCode = 0; ss.dwCurrentState = SERVICE_STOPPED; @@ -768,8 +789,7 @@ static void WINAPI ControlHandler(DWORD code) SetServiceStatus(hStatus, &ss); } -static void WINAPI ServiceMain(void) -{ +static void WINAPI ServiceMain(void) { ss.dwServiceType = SERVICE_WIN32; ss.dwCurrentState = SERVICE_RUNNING; ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; @@ -783,30 +803,27 @@ static void WINAPI ServiceMain(void) stop_civetweb(); ss.dwCurrentState = SERVICE_STOPPED; - ss.dwWin32ExitCode = (DWORD) -1; + ss.dwWin32ExitCode = (DWORD)-1; SetServiceStatus(hStatus, &ss); } -static void show_error(void) -{ +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); + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, sizeof(buf), + NULL); MessageBox(NULL, buf, "Error", MB_OK); } -static void *align(void *ptr, DWORD alig) -{ - ULONG ul = (ULONG) ptr; +static void *align(void *ptr, DWORD alig) { + ULONG ul = (ULONG)ptr; ul += alig; ul &= ~alig; - return ((void *) ul); + return ((void *)ul); } -static void save_config(HWND hDlg, FILE *fp) -{ +static void save_config(HWND hDlg, FILE *fp) { char value[2000] = ""; const char *default_value; const struct mg_option *options; @@ -817,13 +834,14 @@ static void save_config(HWND hDlg, FILE *fp) for (i = 0; options[i].name != NULL; i++) { id = ID_CONTROLS + i; if (options[i].type == CONFIG_TYPE_BOOLEAN) { - snprintf(value, sizeof(value)-1, "%s", + snprintf(value, sizeof(value) - 1, "%s", IsDlgButtonChecked(hDlg, id) ? "yes" : "no"); - value[sizeof(value)-1] = 0; + value[sizeof(value) - 1] = 0; } else { GetDlgItemText(hDlg, id, value, sizeof(value)); } - default_value = options[i].default_value == NULL ? "" : options[i].default_value; + default_value = + options[i].default_value == NULL ? "" : options[i].default_value; /* If value is the same as default, skip it */ if (strcmp(value, default_value) != 0) { fprintf(fp, "%s %s\n", options[i].name, value); @@ -831,13 +849,13 @@ static void save_config(HWND hDlg, FILE *fp) } } -static BOOL CALLBACK SettingsDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam) -{ +static BOOL CALLBACK +SettingsDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam) { FILE *fp; int i, j; const char *name, *value; const struct mg_option *default_options = mg_get_valid_options(); - char *file_options[MAX_OPTIONS*2+1] = {0}; + char *file_options[MAX_OPTIONS * 2 + 1] = {0}; char *title; (void)lParam; @@ -863,10 +881,13 @@ static BOOL CALLBACK SettingsDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM case ID_RESET_DEFAULTS: for (i = 0; default_options[i].name != NULL; i++) { name = default_options[i].name; - value = default_options[i].default_value == NULL ? "" : default_options[i].default_value; + value = default_options[i].default_value == NULL + ? "" + : default_options[i].default_value; if (default_options[i].type == CONFIG_TYPE_BOOLEAN) { - CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes") ? - BST_CHECKED : BST_UNCHECKED); + CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes") + ? BST_CHECKED + : BST_UNCHECKED); } else { SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value); } @@ -887,14 +908,16 @@ static BOOL CALLBACK SettingsDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM value = ""; } if (default_options[i].type == CONFIG_TYPE_BOOLEAN) { - CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes") ? BST_CHECKED : BST_UNCHECKED); + CheckDlgButton(hDlg, ID_CONTROLS + i, !strcmp(value, "yes") + ? BST_CHECKED + : BST_UNCHECKED); } else { SetWindowText(GetDlgItem(hDlg, ID_CONTROLS + i), value); } } - for (i = 0; ibuffer, inBuf->buflen); - if (strlen(inBuf->buffer)>0) { + GetWindowText(GetDlgItem(hDlg, ID_INPUT_LINE), inBuf->buffer, + inBuf->buflen); + if (strlen(inBuf->buffer) > 0) { EndDialog(hDlg, IDOK); } } else if (ctrlId == IDCANCEL) { @@ -1000,13 +1028,14 @@ static BOOL CALLBACK InputDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP) break; case WM_INITDIALOG: - inBuf = (struct tstring_input_buf *) lP; + inBuf = (struct tstring_input_buf *)lP; assert(inBuf != NULL); assert((inBuf->buffer != NULL) && (inBuf->buflen != 0)); assert(strlen(inBuf->buffer) < inBuf->buflen); - SendMessage(hDlg, WM_SETICON, (WPARAM) ICON_SMALL, (LPARAM) hIcon); - SendMessage(hDlg, WM_SETICON, (WPARAM) ICON_BIG, (LPARAM) hIcon); - SendDlgItemMessage(hDlg, ID_INPUT_LINE, EM_LIMITTEXT, inBuf->buflen-1, 0); + SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon); + SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon); + SendDlgItemMessage(hDlg, ID_INPUT_LINE, EM_LIMITTEXT, inBuf->buflen - 1, + 0); SetWindowText(GetDlgItem(hDlg, ID_INPUT_LINE), inBuf->buffer); SetWindowText(hDlg, "Modify password"); SetFocus(GetDlgItem(hDlg, ID_INPUT_LINE)); @@ -1019,10 +1048,9 @@ static BOOL CALLBACK InputDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP) return FALSE; } -void suggest_passwd(char *passwd) -{ +void suggest_passwd(char *passwd) { unsigned u; - char * p; + char *p; union { FILETIME ft; LARGE_INTEGER li; @@ -1036,23 +1064,23 @@ void suggest_passwd(char *passwd) u = (unsigned)(num.li.QuadPart % 95); num.li.QuadPart -= u; num.li.QuadPart /= 95; - *p = (char)(u+32); + *p = (char)(u + 32); p++; } } static void add_control(unsigned char **mem, DLGTEMPLATE *dia, WORD type, - DWORD id, DWORD style, WORD x, WORD y, - WORD cx, WORD cy, const char *caption); + DWORD id, DWORD style, WORD x, WORD y, WORD cx, WORD cy, + const char *caption); -static int get_password(const char * user, const char * realm, char * passwd, unsigned passwd_len) -{ +static int get_password(const char *user, const char *realm, char *passwd, + unsigned passwd_len) { #define HEIGHT 15 #define WIDTH 280 #define LABEL_WIDTH 90 unsigned char mem[4096], *p; - DLGTEMPLATE *dia = (DLGTEMPLATE *) mem; + DLGTEMPLATE *dia = (DLGTEMPLATE *)mem; int ok, y; struct tstring_input_buf dlgprms = {passwd_len, passwd}; @@ -1062,14 +1090,16 @@ static int get_password(const char * user, const char * realm, char * passwd, un wchar_t caption[1]; WORD fontsiz; wchar_t fontface[7]; - } dialog_header = {{ - WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE | - DS_SETFONT | WS_DLGFRAME, WS_EX_TOOLWINDOW, 0, 200, 200, WIDTH, 0 - }, - 0, 0, L"", 8, L"Tahoma" - }; + } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE | + DS_SETFONT | WS_DLGFRAME, + WS_EX_TOOLWINDOW, 0, 200, 200, WIDTH, 0}, + 0, + 0, + L"", + 8, + L"Tahoma"}; - assert((user!=NULL) && (realm!=NULL) && (passwd!=NULL)); + assert((user != NULL) && (realm != NULL) && (passwd != NULL)); if (guard < 100) { guard += 100; @@ -1082,44 +1112,47 @@ static int get_password(const char * user, const char * realm, char * passwd, un suggest_passwd(passwd); /* Create the dialog */ - (void) memset(mem, 0, sizeof(mem)); - (void) memcpy(mem, &dialog_header, sizeof(dialog_header)); + (void)memset(mem, 0, sizeof(mem)); + (void)memcpy(mem, &dialog_header, sizeof(dialog_header)); p = mem + sizeof(dialog_header); y = HEIGHT; - add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD, - 10, y, LABEL_WIDTH, HEIGHT, "User:"); + add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD, 10, y, + LABEL_WIDTH, HEIGHT, "User:"); add_control(&p, dia, 0x81, ID_CONTROLS + 1, - WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_DISABLED, - 15+LABEL_WIDTH, y, WIDTH - LABEL_WIDTH - 25, HEIGHT, user); + WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | + WS_DISABLED, + 15 + LABEL_WIDTH, y, WIDTH - LABEL_WIDTH - 25, HEIGHT, user); y += HEIGHT; - add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD, - 10, y, LABEL_WIDTH, HEIGHT, "Realm:"); + add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD, 10, y, + LABEL_WIDTH, HEIGHT, "Realm:"); add_control(&p, dia, 0x81, ID_CONTROLS + 2, - WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_DISABLED, - 15+LABEL_WIDTH, y, WIDTH - LABEL_WIDTH - 25, HEIGHT, realm); + WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | + WS_DISABLED, + 15 + LABEL_WIDTH, y, WIDTH - LABEL_WIDTH - 25, HEIGHT, realm); y += HEIGHT; - add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD, - 10, y, LABEL_WIDTH, HEIGHT, "Password:"); + add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD, 10, y, + LABEL_WIDTH, HEIGHT, "Password:"); add_control(&p, dia, 0x81, ID_INPUT_LINE, - WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_TABSTOP, - 15+LABEL_WIDTH, y, WIDTH - LABEL_WIDTH - 25, HEIGHT, ""); + WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_TABSTOP, + 15 + LABEL_WIDTH, y, WIDTH - LABEL_WIDTH - 25, HEIGHT, ""); y += (WORD)(HEIGHT * 2); add_control(&p, dia, 0x80, IDOK, - WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, - 80, y, 55, 12, "Ok"); + WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, 80, y, 55, + 12, "Ok"); add_control(&p, dia, 0x80, IDCANCEL, - WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, - 140, y, 55, 12, "Cancel"); + WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, 140, y, 55, + 12, "Cancel"); assert((int)p - (int)mem < (int)sizeof(mem)); dia->cy = y + (WORD)(HEIGHT * 1.5); - ok = (IDOK == DialogBoxIndirectParam(NULL, dia, NULL, InputDlgProc, (LPARAM) &dlgprms)); + ok = (IDOK == DialogBoxIndirectParam(NULL, dia, NULL, InputDlgProc, + (LPARAM)&dlgprms)); guard -= 100; @@ -1130,8 +1163,8 @@ static int get_password(const char * user, const char * realm, char * passwd, un #undef LABEL_WIDTH } -static BOOL CALLBACK PasswordDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP) -{ +static BOOL CALLBACK +PasswordDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP) { static const char *passfile = 0; char domain[256], user[256], password[256]; WORD ctrlId; @@ -1146,26 +1179,32 @@ static BOOL CALLBACK PasswordDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM ctrlId = LOWORD(wParam); if (ctrlId == ID_ADD_USER) { /* Add user */ - GetWindowText(GetDlgItem(hDlg, ID_ADD_USER_NAME), user, sizeof(user)); - GetWindowText(GetDlgItem(hDlg, ID_ADD_USER_REALM), domain, sizeof(domain)); + GetWindowText(GetDlgItem(hDlg, ID_ADD_USER_NAME), user, + sizeof(user)); + GetWindowText(GetDlgItem(hDlg, ID_ADD_USER_REALM), domain, + sizeof(domain)); if (get_password(user, domain, password, sizeof(password))) { mg_modify_passwords_file(passfile, domain, user, password); EndDialog(hDlg, IDOK); } - } else if ((ctrlId>=(ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 3)) && - (ctrlId<(ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 4))) { + } else if ((ctrlId >= (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 3)) && + (ctrlId < (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 4))) { /* Modify password */ - GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 3), user, sizeof(user)); - GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 2), domain, sizeof(domain)); + GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 3), + user, sizeof(user)); + GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 2), + domain, sizeof(domain)); if (get_password(user, domain, password, sizeof(password))) { mg_modify_passwords_file(passfile, domain, user, password); EndDialog(hDlg, IDOK); } - } else if ((ctrlId>=(ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 2)) && - (ctrlId<(ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 3))) { + } else if ((ctrlId >= (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 2)) && + (ctrlId < (ID_CONTROLS + ID_FILE_BUTTONS_DELTA * 3))) { /* Remove user */ - GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 2), user, sizeof(user)); - GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA), domain, sizeof(domain)); + GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA * 2), + user, sizeof(user)); + GetWindowText(GetDlgItem(hDlg, ctrlId - ID_FILE_BUTTONS_DELTA), + domain, sizeof(domain)); mg_modify_passwords_file(passfile, domain, user, NULL); EndDialog(hDlg, IDOK); } @@ -1173,8 +1212,8 @@ static BOOL CALLBACK PasswordDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM case WM_INITDIALOG: passfile = (const char *)lP; - SendMessage(hDlg, WM_SETICON, (WPARAM) ICON_SMALL, (LPARAM) hIcon); - SendMessage(hDlg, WM_SETICON, (WPARAM) ICON_BIG, (LPARAM) hIcon); + SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon); + SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)hIcon); SetWindowText(hDlg, passfile); SetFocus(GetDlgItem(hDlg, ID_ADD_USER_NAME)); break; @@ -1187,16 +1226,15 @@ static BOOL CALLBACK PasswordDlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM } static void add_control(unsigned char **mem, DLGTEMPLATE *dia, WORD type, - DWORD id, DWORD style, WORD x, WORD y, - WORD cx, WORD cy, const char *caption) -{ + DWORD id, DWORD style, WORD x, WORD y, WORD cx, WORD cy, + const char *caption) { DLGITEMTEMPLATE *tp; LPWORD p; dia->cdit++; *mem = align(*mem, 3); - tp = (DLGITEMTEMPLATE *) *mem; + tp = (DLGITEMTEMPLATE *)*mem; tp->id = (WORD)id; tp->style = style; @@ -1211,17 +1249,16 @@ static void add_control(unsigned char **mem, DLGTEMPLATE *dia, WORD type, *p++ = type; while (*caption != '\0') { - *p++ = (WCHAR) *caption++; + *p++ = (WCHAR)*caption++; } *p++ = 0; p = align(p, 1); *p++ = 0; - *mem = (unsigned char *) p; + *mem = (unsigned char *)p; } -static void show_settings_dialog() -{ +static void show_settings_dialog() { #define HEIGHT 15 #define WIDTH 460 #define LABEL_WIDTH 90 @@ -1229,7 +1266,7 @@ static void show_settings_dialog() unsigned char mem[4096], *p; const struct mg_option *options; DWORD style; - DLGTEMPLATE *dia = (DLGTEMPLATE *) mem; + DLGTEMPLATE *dia = (DLGTEMPLATE *)mem; WORD i, cl, x, y, width, nelems = 0; static struct { @@ -1238,12 +1275,14 @@ static void show_settings_dialog() wchar_t caption[1]; WORD fontsiz; wchar_t fontface[7]; - } dialog_header = {{ - WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE | - DS_SETFONT | WS_DLGFRAME, WS_EX_TOOLWINDOW, 0, 200, 200, WIDTH, 0 - }, - 0, 0, L"", 8, L"Tahoma" - }; + } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE | + DS_SETFONT | WS_DLGFRAME, + WS_EX_TOOLWINDOW, 0, 200, 200, WIDTH, 0}, + 0, + 0, + L"", + 8, + L"Tahoma"}; if (guard == 0) { guard++; @@ -1251,15 +1290,15 @@ static void show_settings_dialog() return; } - (void) memset(mem, 0, sizeof(mem)); - (void) memcpy(mem, &dialog_header, sizeof(dialog_header)); + (void)memset(mem, 0, sizeof(mem)); + (void)memcpy(mem, &dialog_header, sizeof(dialog_header)); p = mem + sizeof(dialog_header); options = mg_get_valid_options(); for (i = 0; options[i].name != NULL; i++) { style = WS_CHILD | WS_VISIBLE | WS_TABSTOP; x = 10 + (WIDTH / 2) * (nelems % 2); - y = (nelems/2 + 1) * HEIGHT + 5; + y = (nelems / 2 + 1) * HEIGHT + 5; width = WIDTH / 2 - 20 - LABEL_WIDTH; if (options[i].type == CONFIG_TYPE_NUMBER) { style |= ES_NUMBER; @@ -1273,48 +1312,45 @@ static void show_settings_dialog() style |= WS_BORDER | ES_AUTOHSCROLL; width -= 20; cl = 0x81; - add_control(&p, dia, 0x80, - ID_CONTROLS + i + ID_FILE_BUTTONS_DELTA, + add_control(&p, dia, 0x80, ID_CONTROLS + i + ID_FILE_BUTTONS_DELTA, WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON, - (WORD) (x + width + LABEL_WIDTH + 5), - y, 15, 12, "..."); + (WORD)(x + width + LABEL_WIDTH + 5), y, 15, 12, "..."); } else { cl = 0x81; style |= WS_BORDER | ES_AUTOHSCROLL; } - add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD, - x, y, LABEL_WIDTH, HEIGHT, options[i].name); + add_control(&p, dia, 0x82, ID_STATIC, WS_VISIBLE | WS_CHILD, x, y, + LABEL_WIDTH, HEIGHT, options[i].name); add_control(&p, dia, cl, ID_CONTROLS + i, style, - (WORD) (x + LABEL_WIDTH), y, width, 12, ""); + (WORD)(x + LABEL_WIDTH), y, width, 12, ""); nelems++; assert(((int)p - (int)mem) < (int)sizeof(mem)); } - y = (WORD) (((nelems + 1) / 2 + 1) * HEIGHT + 5); - add_control(&p, dia, 0x80, ID_GROUP, WS_CHILD | WS_VISIBLE | - BS_GROUPBOX, 5, 5, WIDTH - 10, y, " Settings "); + y = (WORD)(((nelems + 1) / 2 + 1) * HEIGHT + 5); + add_control(&p, dia, 0x80, ID_GROUP, WS_CHILD | WS_VISIBLE | BS_GROUPBOX, 5, + 5, WIDTH - 10, y, " Settings "); y += 10; add_control(&p, dia, 0x80, ID_SAVE, - WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, - WIDTH - 70, y, 65, 12, "Save Settings"); + WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, WIDTH - 70, + y, 65, 12, "Save Settings"); add_control(&p, dia, 0x80, ID_RESET_DEFAULTS, - WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, - WIDTH - 140, y, 65, 12, "Reset to defaults"); + WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, WIDTH - 140, + y, 65, 12, "Reset to defaults"); add_control(&p, dia, 0x80, ID_RESET_FILE, - WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, - WIDTH - 210, y, 65, 12, "Reload from file"); + WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, WIDTH - 210, + y, 65, 12, "Reload from file"); add_control(&p, dia, 0x80, ID_RESET_ACTIVE, - WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, - WIDTH - 280, y, 65, 12, "Reload active"); - add_control(&p, dia, 0x82, ID_STATIC, - WS_CHILD | WS_VISIBLE | WS_DISABLED, + WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, WIDTH - 280, + y, 65, 12, "Reload active"); + add_control(&p, dia, 0x82, ID_STATIC, WS_CHILD | WS_VISIBLE | WS_DISABLED, 5, y, 100, 12, g_server_base_name); assert(((int)p - (int)mem) < (int)sizeof(mem)); dia->cy = ((nelems + 1) / 2 + 1) * HEIGHT + 30; - DialogBoxIndirectParam(NULL, dia, NULL, SettingsDlgProc, (LPARAM) NULL); + DialogBoxIndirectParam(NULL, dia, NULL, SettingsDlgProc, (LPARAM)NULL); guard--; #undef HEIGHT @@ -1322,8 +1358,7 @@ static void show_settings_dialog() #undef LABEL_WIDTH } -static void change_password_file() -{ +static void change_password_file() { #define HEIGHT 15 #define WIDTH 320 #define LABEL_WIDTH 90 @@ -1332,11 +1367,11 @@ static void change_password_file() char path[PATH_MAX] = PASSWORDS_FILE_NAME; char strbuf[256], u[256], d[256]; HWND hDlg = NULL; - FILE * f; + FILE *f; int y, nelems; unsigned char mem[4096], *p; - DLGTEMPLATE *dia = (DLGTEMPLATE *) mem; - const char * domain = mg_get_option(g_ctx, "authentication_domain"); + DLGTEMPLATE *dia = (DLGTEMPLATE *)mem; + const char *domain = mg_get_option(g_ctx, "authentication_domain"); static struct { DLGTEMPLATE template; /* 18 bytes */ @@ -1344,12 +1379,14 @@ static void change_password_file() wchar_t caption[1]; WORD fontsiz; wchar_t fontface[7]; - } dialog_header = {{ - WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE | - DS_SETFONT | WS_DLGFRAME, WS_EX_TOOLWINDOW, 0, 200, 200, WIDTH, 0 - }, - 0, 0, L"", 8, L"Tahoma" - }; + } dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE | + DS_SETFONT | WS_DLGFRAME, + WS_EX_TOOLWINDOW, 0, 200, 200, WIDTH, 0}, + 0, + 0, + L"", + 8, + L"Tahoma"}; if (guard == 0) { guard++; @@ -1359,7 +1396,7 @@ static void change_password_file() memset(&of, 0, sizeof(of)); of.lStructSize = sizeof(of); - of.hwndOwner = (HWND) hDlg; + of.hwndOwner = (HWND)hDlg; of.lpstrFile = path; of.nMaxFile = sizeof(path); of.lpstrInitialDir = mg_get_option(g_ctx, "document_root"); @@ -1380,8 +1417,8 @@ static void change_password_file() } do { - (void) memset(mem, 0, sizeof(mem)); - (void) memcpy(mem, &dialog_header, sizeof(dialog_header)); + (void)memset(mem, 0, sizeof(mem)); + (void)memcpy(mem, &dialog_header, sizeof(dialog_header)); p = mem + sizeof(dialog_header); f = fopen(path, "r+"); @@ -1396,51 +1433,61 @@ static void change_password_file() if (sscanf(strbuf, "%255[^:]:%255[^:]:%*s", u, d) != 2) { continue; } - u[255]=0; - d[255]=0; + u[255] = 0; + d[255] = 0; y = (nelems + 1) * HEIGHT + 5; - add_control(&p, dia, 0x80, ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA * 3, - WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, - 10, y, 65, 12, "Modify password"); - add_control(&p, dia, 0x80, ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA * 2, - WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, - 80, y, 55, 12, "Remove user"); - add_control(&p, dia, 0x81, ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA, - WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_DISABLED, - 245, y, 60, 12, d); + add_control(&p, dia, 0x80, + ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA * 3, + WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, 10, + y, 65, 12, "Modify password"); + add_control(&p, dia, 0x80, + ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA * 2, + WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, 80, + y, 55, 12, "Remove user"); + add_control(&p, dia, 0x81, + ID_CONTROLS + nelems + ID_FILE_BUTTONS_DELTA, + WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | + WS_DISABLED, + 245, y, 60, 12, d); add_control(&p, dia, 0x81, ID_CONTROLS + nelems, - WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_DISABLED, - 140, y, 100, 12, u); + WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | + WS_DISABLED, + 140, y, 100, 12, u); nelems++; assert(((int)p - (int)mem) < (int)sizeof(mem)); } fclose(f); - y = (WORD) ((nelems + 1) * HEIGHT + 10); + y = (WORD)((nelems + 1) * HEIGHT + 10); add_control(&p, dia, 0x80, ID_ADD_USER, - WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, - 80, y, 55, 12, "Add user"); + WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, 80, y, + 55, 12, "Add user"); add_control(&p, dia, 0x81, ID_ADD_USER_NAME, - WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_TABSTOP, - 140, y, 100, 12, ""); + WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | + WS_TABSTOP, + 140, y, 100, 12, ""); add_control(&p, dia, 0x81, ID_ADD_USER_REALM, - WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | WS_TABSTOP, - 245, y, 60, 12, domain); + WS_CHILD | WS_VISIBLE | WS_BORDER | ES_AUTOHSCROLL | + WS_TABSTOP, + 245, y, 60, 12, domain); - y = (WORD) ((nelems + 2) * HEIGHT + 10); - add_control(&p, dia, 0x80, ID_GROUP, WS_CHILD | WS_VISIBLE | - BS_GROUPBOX, 5, 5, WIDTH - 10, y, " Users "); + y = (WORD)((nelems + 2) * HEIGHT + 10); + add_control(&p, dia, 0x80, ID_GROUP, + WS_CHILD | WS_VISIBLE | BS_GROUPBOX, 5, 5, WIDTH - 10, y, + " Users "); y += HEIGHT; add_control(&p, dia, 0x82, ID_STATIC, - WS_CHILD | WS_VISIBLE | WS_DISABLED, - 5, y, 100, 12, g_server_base_name); + WS_CHILD | WS_VISIBLE | WS_DISABLED, 5, y, 100, 12, + g_server_base_name); assert(((int)p - (int)mem) < (int)sizeof(mem)); dia->cy = y + 20; - } while ((IDOK == DialogBoxIndirectParam(NULL, dia, NULL, PasswordDlgProc, (LPARAM) path)) && (!g_exit_flag)); + } while ((IDOK == DialogBoxIndirectParam(NULL, dia, NULL, PasswordDlgProc, + (LPARAM)path)) && + (!g_exit_flag)); guard--; @@ -1449,27 +1496,28 @@ static void change_password_file() #undef LABEL_WIDTH } -static int manage_service(int action) -{ - static const char *service_name = "Civetweb"; /* TODO: check using server_name instead of service_name */ +static int manage_service(int action) { + static const char *service_name = + "Civetweb"; /* TODO: check using server_name instead of service_name */ SC_HANDLE hSCM = NULL, hService = NULL; SERVICE_DESCRIPTION descr = {g_server_name}; - char path[PATH_MAX + 20] = "";/* Path to executable plus magic argument */ + 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) { + if ((hSCM = OpenSCManager(NULL, NULL, action == ID_INSTALL_SERVICE + ? GENERIC_WRITE + : GENERIC_READ)) == NULL) { success = 0; show_error(); } else if (action == ID_INSTALL_SERVICE) { - path[sizeof(path)-1] = 0; - GetModuleFileName(NULL, path, sizeof(path)-1); - strncat(path, " ", sizeof(path)-1); - strncat(path, service_magic_argument, sizeof(path)-1); + path[sizeof(path) - 1] = 0; + GetModuleFileName(NULL, path, sizeof(path) - 1); + strncat(path, " ", sizeof(path) - 1); + strncat(path, service_magic_argument, sizeof(path) - 1); 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); + SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, path, + NULL, NULL, NULL, NULL, NULL); if (hService) { ChangeServiceConfig2(hService, SERVICE_CONFIG_DESCRIPTION, &descr); } else { @@ -1493,9 +1541,8 @@ static int manage_service(int action) return success; } -static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam, - LPARAM lParam) -{ +static LRESULT CALLBACK +WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { static SERVICE_TABLE_ENTRY service_table[2]; int service_installed; char buf[200], *service_argv[] = {__argv[0], NULL}; @@ -1509,8 +1556,7 @@ static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam, switch (msg) { case WM_CREATE: - if (__argv[1] != NULL && - !strcmp(__argv[1], service_magic_argument)) { + if (__argv[1] != NULL && !strcmp(__argv[1], service_magic_argument)) { start_civetweb(1, service_argv); StartServiceCtrlDispatcher(service_table); exit(EXIT_SUCCESS); @@ -1539,8 +1585,8 @@ static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam, break; case ID_CONNECT: printf("[%s]\n", get_url_to_first_open_port(g_ctx)); - ShellExecute(NULL, "open", get_url_to_first_open_port(g_ctx), - NULL, NULL, SW_SHOW); + ShellExecute(NULL, "open", get_url_to_first_open_port(g_ctx), NULL, + NULL, SW_SHOW); break; } break; @@ -1550,12 +1596,13 @@ static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam, case WM_LBUTTONUP: case WM_LBUTTONDBLCLK: hMenu = CreatePopupMenu(); - AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, g_server_name); + AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, + g_server_name); AppendMenu(hMenu, MF_SEPARATOR, ID_SEPARATOR, ""); service_installed = manage_service(0); - snprintf(buf, sizeof(buf)-1, "NT service: %s installed", + snprintf(buf, sizeof(buf) - 1, "NT service: %s installed", service_installed ? "" : "not"); - buf[sizeof(buf)-1] = 0; + buf[sizeof(buf) - 1] = 0; AppendMenu(hMenu, MF_STRING | MF_GRAYED, ID_SEPARATOR, buf); AppendMenu(hMenu, MF_STRING | (service_installed ? MF_GRAYED : 0), ID_INSTALL_SERVICE, "Install service"); @@ -1580,9 +1627,9 @@ static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam, Shell_NotifyIcon(NIM_DELETE, &TrayIcon); g_exit_flag = 1; PostQuitMessage(0); - return 0;/* We've just sent our own quit message, with proper hwnd. */ + return 0; /* We've just sent our own quit message, with proper hwnd. */ default: - if (msg==s_uTaskbarRestart) + if (msg == s_uTaskbarRestart) Shell_NotifyIcon(NIM_ADD, &TrayIcon); } @@ -1597,8 +1644,10 @@ static int MakeConsole() { FreeConsole(); if (!AllocConsole()) { err = GetLastError(); - if (err==ERROR_ACCESS_DENIED) { - MessageBox(NULL, "Insufficient rights to create a console window", "Error", MB_ICONERROR); + if (err == ERROR_ACCESS_DENIED) { + MessageBox(NULL, + "Insufficient rights to create a console window", + "Error", MB_ICONERROR); } } AttachConsole(GetCurrentProcessId()); @@ -1619,8 +1668,7 @@ static int MakeConsole() { return ok; } -int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show) -{ +int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show) { WNDCLASS cls; HWND hWnd; MSG msg; @@ -1632,7 +1680,7 @@ int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show) init_server_name((int)__argc, (const char **)__argv); memset(&cls, 0, sizeof(cls)); - cls.lpfnWndProc = (WNDPROC) WindowProc; + cls.lpfnWndProc = (WNDPROC)WindowProc; cls.hIcon = LoadIcon(NULL, IDI_APPLICATION); cls.lpszClassName = g_server_base_name; @@ -1642,9 +1690,11 @@ int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show) ShowWindow(hWnd, SW_HIDE); if (g_icon_name) { - hIcon = LoadImage(NULL, g_icon_name, IMAGE_ICON, 16, 16, LR_LOADFROMFILE); + hIcon = + LoadImage(NULL, g_icon_name, IMAGE_ICON, 16, 16, LR_LOADFROMFILE); } else { - hIcon = LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(ID_ICON), IMAGE_ICON, 16, 16, 0); + hIcon = LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(ID_ICON), + IMAGE_ICON, 16, 16, 0); } TrayIcon.cbSize = sizeof(TrayIcon); @@ -1662,44 +1712,40 @@ int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show) } /* Return the WM_QUIT value. */ - return (int) msg.wParam; + return (int)msg.wParam; } #if defined(CONSOLE) -void main(void) -{ - WinMain(0, 0, 0, 0); -} +void main(void) { WinMain(0, 0, 0, 0); } #endif #elif defined(USE_COCOA) #import -@interface Civetweb : -NSObject -- (void) openBrowser; -- (void) shutDown; +@interface Civetweb : NSObject +- (void)openBrowser; +- (void)shutDown; @end @implementation Civetweb -- (void) openBrowser { +- (void)openBrowser { [[NSWorkspace sharedWorkspace] -openURL:[NSURL URLWithString: -[NSString stringWithUTF8String:get_url_to_first_open_port(g_ctx)]]]; + openURL:[NSURL URLWithString:[NSString stringWithUTF8String: + get_url_to_first_open_port( + g_ctx)]]]; } -- (void) editConfig { +- (void)editConfig { create_config_file(g_ctx, g_config_file); [[NSWorkspace sharedWorkspace] -openFile:[NSString stringWithUTF8String:g_config_file] -withApplication:@"TextEdit"]; + openFile:[NSString stringWithUTF8String:g_config_file] + withApplication:@"TextEdit"]; } - (void)shutDown { -[NSApp terminate:nil]; + [NSApp terminate:nil]; } @end -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { init_server_name(argc, (const char **)argv); start_civetweb(argc, argv); @@ -1708,10 +1754,10 @@ int main(int argc, char *argv[]) /* Add delegate to process menu item actions */ Civetweb *myDelegate = [[Civetweb alloc] autorelease]; -[NSApp setDelegate: myDelegate]; + [NSApp setDelegate:myDelegate]; /* Run this app as agent */ - ProcessSerialNumber psn = { 0, kCurrentProcess }; + ProcessSerialNumber psn = {0, kCurrentProcess}; TransformProcessType(&psn, kProcessTransformToBackgroundApplication); SetFrontProcess(&psn); @@ -1719,38 +1765,42 @@ int main(int argc, char *argv[]) id menu = [[NSMenu new] autorelease]; /* Add version menu item */ -[menu addItem:[[[NSMenuItem alloc] - /*initWithTitle:[NSString stringWithFormat:@"%s", server_name]*/ + [menu + addItem: + [[[NSMenuItem alloc] + /*initWithTitle:[NSString stringWithFormat:@"%s", server_name]*/ initWithTitle:[NSString stringWithUTF8String:g_server_name] - action:@selector(noexist) keyEquivalent:@""] autorelease]]; + action:@selector(noexist) + keyEquivalent:@""] autorelease]]; /* Add configuration menu item */ -[menu addItem:[[[NSMenuItem alloc] - initWithTitle:@"Edit configuration" - action:@selector(editConfig) keyEquivalent:@""] autorelease]]; + [menu addItem:[[[NSMenuItem alloc] initWithTitle:@"Edit configuration" + action:@selector(editConfig) + keyEquivalent:@""] autorelease]]; /* Add connect menu item */ -[menu addItem:[[[NSMenuItem alloc] - initWithTitle:@"Open web root in a browser" - action:@selector(openBrowser) keyEquivalent:@""] autorelease]]; + [menu + addItem:[[[NSMenuItem alloc] initWithTitle:@"Open web root in a browser" + action:@selector(openBrowser) + keyEquivalent:@""] autorelease]]; /* Separator */ -[menu addItem:[NSMenuItem separatorItem]]; + [menu addItem:[NSMenuItem separatorItem]]; /* Add quit menu item */ -[menu addItem:[[[NSMenuItem alloc] - initWithTitle:@"Quit" - action:@selector(shutDown) keyEquivalent:@"q"] autorelease]]; + [menu addItem:[[[NSMenuItem alloc] initWithTitle:@"Quit" + action:@selector(shutDown) + keyEquivalent:@"q"] autorelease]]; /* Attach menu to the status bar */ id item = [[[NSStatusBar systemStatusBar] - statusItemWithLength:NSVariableStatusItemLength] retain]; -[item setHighlightMode:YES]; -[item setImage:[NSImage imageNamed:@"civetweb_22x22.png"]]; -[item setMenu:menu]; + statusItemWithLength:NSVariableStatusItemLength] retain]; + [item setHighlightMode:YES]; + [item setImage:[NSImage imageNamed:@"civetweb_22x22.png"]]; + [item setMenu:menu]; /* Run the app */ -[NSApp activateIgnoringOtherApps:YES]; + [NSApp activateIgnoringOtherApps:YES]; [NSApp run]; stop_civetweb(g_ctx); @@ -1758,12 +1808,11 @@ int main(int argc, char *argv[]) return EXIT_SUCCESS; } #else -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { init_server_name(argc, (const char **)argv); start_civetweb(argc, argv); - printf("%s started on port(s) %s with web root [%s]\n", - g_server_name, mg_get_option(g_ctx, "listening_ports"), + printf("%s started on port(s) %s with web root [%s]\n", g_server_name, + mg_get_option(g_ctx, "listening_ports"), mg_get_option(g_ctx, "document_root")); while (g_exit_flag == 0) { sleep(1);