1
0
mirror of https://github.com/lammertb/libhttp.git synced 2025-08-06 05:02:40 +03:00

Renamed mg_ to httplib_

This commit is contained in:
Lammert Bies
2016-12-13 17:32:31 +01:00
parent 647139558b
commit d317ce3e82
178 changed files with 2173 additions and 2513 deletions

View File

@@ -55,11 +55,11 @@ By default, the server will automatically serve up files like a normal HTTP serv
### C ### C
- Include the C interface ```libhttp.h```. - Include the C interface ```libhttp.h```.
- Use `mg_start()` to start the server. - Use `httplib_start()` to start the server.
- Use *options* to select the port and document root among other things. - Use *options* to select the port and document root among other things.
- Use *callbacks* to add your own hooks. - Use *callbacks* to add your own hooks.
- Use `mg_set_request_handler()` to easily add your own request handlers. - Use `httplib_set_request_handler()` to easily add your own request handlers.
- Use `mg_stop()` to stop the server. - Use `httplib_stop()` to stop the server.
### C++ ### C++
- Note that LibHTTP is Clean C, and C++ interface ```LibHTTPServer.h``` is only a wrapper layer around the C interface. - Note that LibHTTP is Clean C, and C++ interface ```LibHTTPServer.h``` is only a wrapper layer around the C interface.
@@ -136,8 +136,8 @@ LibHTTP can be built with server side JavaScript support by including the Duktap
LibHTTP internals LibHTTP internals
------ ------
LibHTTP is multithreaded web server. `mg_start()` function allocates LibHTTP is multithreaded web server. `httplib_start()` function allocates
web server context (`struct mg_context`), which holds all information web server context (`struct httplib_context`), which holds all information
about web server instance: about web server instance:
- configuration options. Note that LibHTTP makes internal copies of - configuration options. Note that LibHTTP makes internal copies of
@@ -148,14 +148,14 @@ about web server instance:
- a queue for accepted sockets - a queue for accepted sockets
- mutexes and condition variables for inter-thread synchronization - mutexes and condition variables for inter-thread synchronization
When `mg_start()` returns, all initialization is guaranteed to be complete When `httplib_start()` returns, all initialization is guaranteed to be complete
(e.g. listening ports are opened, SSL is initialized, etc). `mg_start()` starts (e.g. listening ports are opened, SSL is initialized, etc). `httplib_start()` starts
some threads: a master thread, that accepts new connections, and several some threads: a master thread, that accepts new connections, and several
worker threads, that process accepted connections. The number of worker threads worker threads, that process accepted connections. The number of worker threads
is configurable via `num_threads` configuration option. That number puts a is configurable via `num_threads` configuration option. That number puts a
limit on number of simultaneous requests that can be handled by LibHTTP. limit on number of simultaneous requests that can be handled by LibHTTP.
If you embed LibHTTP into a program that uses SSL outside LibHTTP as well, If you embed LibHTTP into a program that uses SSL outside LibHTTP as well,
you may need to initialize SSL before calling `mg_start()`, and set the pre- you may need to initialize SSL before calling `httplib_start()`, and set the pre-
processor define SSL_ALREADY_INITIALIZED. This is not required if SSL is used processor define SSL_ALREADY_INITIALIZED. This is not required if SSL is used
only within LibHTTP. only within LibHTTP.

View File

@@ -531,7 +531,7 @@ is an example for a plain Lua script.
is an example for a Lua Server Page. is an example for a Lua Server Page.
Both examples show the content of the `mg.request_info` object as the page Both examples show the content of the `mg.request_info` object as the page
content. Please refer to `struct mg_request_info` definition in content. Please refer to `struct httplib_request_info` definition in
[libhttp.h](https://github.com/lammertb/libhttp/blob/master/include/libhttp.h) [libhttp.h](https://github.com/lammertb/libhttp/blob/master/include/libhttp.h)
to see additional information on the elements of the `mg.request_info` object. to see additional information on the elements of the `mg.request_info` object.

View File

@@ -54,13 +54,13 @@ static long last_message_id;
static pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER; static pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
// Get session object for the connection. Caller must hold the lock. // Get session object for the connection. Caller must hold the lock.
static struct session *get_session(const struct mg_connection *conn) static struct session *get_session(const struct httplib_connection *conn)
{ {
int i; int i;
const char *cookie = mg_get_header(conn, "Cookie"); const char *cookie = httplib_get_header(conn, "Cookie");
char session_id[33]; char session_id[33];
time_t now = time(NULL); time_t now = time(NULL);
mg_get_cookie(cookie, "session", session_id, sizeof(session_id)); httplib_get_cookie(cookie, "session", session_id, sizeof(session_id));
for (i = 0; i < MAX_SESSIONS; i++) { for (i = 0; i < MAX_SESSIONS; i++) {
if (sessions[i].expire != 0 && if (sessions[i].expire != 0 &&
sessions[i].expire > now && sessions[i].expire > now &&
@@ -71,11 +71,10 @@ static struct session *get_session(const struct mg_connection *conn)
return i == MAX_SESSIONS ? NULL : &sessions[i]; return i == MAX_SESSIONS ? NULL : &sessions[i];
} }
static void get_qsvar(const struct mg_request_info *request_info, static void get_qsvar(const struct httplib_request_info *request_info, const char *name, char *dst, size_t dst_len)
const char *name, char *dst, size_t dst_len)
{ {
const char *qs = request_info->query_string; const char *qs = request_info->query_string;
mg_get_var(qs, strlen(qs == NULL ? "" : qs), name, dst, dst_len); httplib_get_var(qs, strlen(qs == NULL ? "" : qs), name, dst, dst_len);
} }
// Get a get of messages with IDs greater than last_id and transform them // Get a get of messages with IDs greater than last_id and transform them
@@ -118,14 +117,14 @@ static char *messages_to_json(long last_id)
// If "callback" param is present in query string, this is JSONP call. // If "callback" param is present in query string, this is JSONP call.
// Return 1 in this case, or 0 if "callback" is not specified. // Return 1 in this case, or 0 if "callback" is not specified.
// Wrap an output in Javascript function call. // Wrap an output in Javascript function call.
static int handle_jsonp(struct mg_connection *conn, static int handle_jsonp(struct httplib_connection *conn,
const struct mg_request_info *request_info) const struct httplib_request_info *request_info)
{ {
char cb[64]; char cb[64];
get_qsvar(request_info, "callback", cb, sizeof(cb)); get_qsvar(request_info, "callback", cb, sizeof(cb));
if (cb[0] != '\0') { if (cb[0] != '\0') {
mg_printf(conn, "%s(", cb); httplib_printf(conn, "%s(", cb);
} }
return cb[0] == '\0' ? 0 : 1; return cb[0] == '\0' ? 0 : 1;
@@ -133,23 +132,23 @@ static int handle_jsonp(struct mg_connection *conn,
// A handler for the /ajax/get_messages endpoint. // A handler for the /ajax/get_messages endpoint.
// Return a list of messages with ID greater than requested. // Return a list of messages with ID greater than requested.
static void ajax_get_messages(struct mg_connection *conn, static void ajax_get_messages(struct httplib_connection *conn,
const struct mg_request_info *request_info) const struct httplib_request_info *request_info)
{ {
char last_id[32], *json; char last_id[32], *json;
int is_jsonp; int is_jsonp;
mg_printf(conn, "%s", ajax_reply_start); httplib_printf(conn, "%s", ajax_reply_start);
is_jsonp = handle_jsonp(conn, request_info); is_jsonp = handle_jsonp(conn, request_info);
get_qsvar(request_info, "last_id", last_id, sizeof(last_id)); get_qsvar(request_info, "last_id", last_id, sizeof(last_id));
if ((json = messages_to_json(strtoul(last_id, NULL, 10))) != NULL) { if ((json = messages_to_json(strtoul(last_id, NULL, 10))) != NULL) {
mg_printf(conn, "[%s]", json); httplib_printf(conn, "[%s]", json);
free(json); free(json);
} }
if (is_jsonp) { if (is_jsonp) {
mg_printf(conn, "%s", ")"); httplib_printf(conn, "%s", ")");
} }
} }
@@ -170,15 +169,15 @@ static void my_strlcpy(char *dst, const char *src, size_t len)
} }
// A handler for the /ajax/send_message endpoint. // A handler for the /ajax/send_message endpoint.
static void ajax_send_message(struct mg_connection *conn, static void ajax_send_message(struct httplib_connection *conn,
const struct mg_request_info *request_info) const struct httplib_request_info *request_info)
{ {
struct message *message; struct message *message;
struct session *session; struct session *session;
char text[sizeof(message->text) - 1]; char text[sizeof(message->text) - 1];
int is_jsonp; int is_jsonp;
mg_printf(conn, "%s", ajax_reply_start); httplib_printf(conn, "%s", ajax_reply_start);
is_jsonp = handle_jsonp(conn, request_info); is_jsonp = handle_jsonp(conn, request_info);
get_qsvar(request_info, "text", text, sizeof(text)); get_qsvar(request_info, "text", text, sizeof(text));
@@ -195,19 +194,19 @@ static void ajax_send_message(struct mg_connection *conn,
pthread_rwlock_unlock(&rwlock); pthread_rwlock_unlock(&rwlock);
} }
mg_printf(conn, "%s", text[0] == '\0' ? "false" : "true"); httplib_printf(conn, "%s", text[0] == '\0' ? "false" : "true");
if (is_jsonp) { if (is_jsonp) {
mg_printf(conn, "%s", ")"); httplib_printf(conn, "%s", ")");
} }
} }
// Redirect user to the login form. In the cookie, store the original URL // Redirect user to the login form. In the cookie, store the original URL
// we came from, so that after the authorization we could redirect back. // we came from, so that after the authorization we could redirect back.
static void redirect_to_login(struct mg_connection *conn, static void redirect_to_login(struct httplib_connection *conn,
const struct mg_request_info *request_info) const struct httplib_request_info *request_info)
{ {
mg_printf(conn, "HTTP/1.1 302 Found\r\n" httplib_printf(conn, "HTTP/1.1 302 Found\r\n"
"Set-Cookie: original_url=%s\r\n" "Set-Cookie: original_url=%s\r\n"
"Location: %s\r\n\r\n", "Location: %s\r\n\r\n",
request_info->uri, login_url); request_info->uri, login_url);
@@ -244,7 +243,7 @@ static struct session *new_session(void)
static void generate_session_id(char *buf, const char *random, static void generate_session_id(char *buf, const char *random,
const char *user) const char *user)
{ {
mg_md5(buf, random, user, NULL); httplib_md5(buf, random, user, NULL);
} }
static void send_server_message(const char *fmt, ...) static void send_server_message(const char *fmt, ...)
@@ -264,8 +263,8 @@ static void send_server_message(const char *fmt, ...)
// A handler for the /authorize endpoint. // A handler for the /authorize endpoint.
// Login page form sends user name and password to this endpoint. // Login page form sends user name and password to this endpoint.
static void authorize(struct mg_connection *conn, static void authorize(struct httplib_connection *conn,
const struct mg_request_info *request_info) const struct httplib_request_info *request_info)
{ {
char user[MAX_USER_LEN], password[MAX_USER_LEN]; char user[MAX_USER_LEN], password[MAX_USER_LEN];
struct session *session; struct session *session;
@@ -290,7 +289,7 @@ static void authorize(struct mg_connection *conn,
snprintf(session->random, sizeof(session->random), "%d", rand()); snprintf(session->random, sizeof(session->random), "%d", rand());
generate_session_id(session->session_id, session->random, session->user); generate_session_id(session->session_id, session->random, session->user);
send_server_message("<%s> joined", session->user); send_server_message("<%s> joined", session->user);
mg_printf(conn, "HTTP/1.1 302 Found\r\n" httplib_printf(conn, "HTTP/1.1 302 Found\r\n"
"Set-Cookie: session=%s; max-age=3600; http-only\r\n" // Session ID "Set-Cookie: session=%s; max-age=3600; http-only\r\n" // Session ID
"Set-Cookie: user=%s\r\n" // Set user, needed by Javascript code "Set-Cookie: user=%s\r\n" // Set user, needed by Javascript code
"Set-Cookie: original_url=/; max-age=0\r\n" // Delete original_url "Set-Cookie: original_url=/; max-age=0\r\n" // Delete original_url
@@ -303,8 +302,8 @@ static void authorize(struct mg_connection *conn,
} }
// Return 1 if request is authorized, 0 otherwise. // Return 1 if request is authorized, 0 otherwise.
static int is_authorized(const struct mg_connection *conn, static int is_authorized(const struct httplib_connection *conn,
const struct mg_request_info *request_info) const struct httplib_request_info *request_info)
{ {
struct session *session; struct session *session;
char valid_id[33]; char valid_id[33];
@@ -329,22 +328,22 @@ static int is_authorized(const struct mg_connection *conn,
return authorized; return authorized;
} }
static void redirect_to_ssl(struct mg_connection *conn, static void redirect_to_ssl(struct httplib_connection *conn,
const struct mg_request_info *request_info) const struct httplib_request_info *request_info)
{ {
const char *p, *host = mg_get_header(conn, "Host"); const char *p, *host = httplib_get_header(conn, "Host");
if (host != NULL && (p = strchr(host, ':')) != NULL) { if (host != NULL && (p = strchr(host, ':')) != NULL) {
mg_printf(conn, "HTTP/1.1 302 Found\r\n" httplib_printf(conn, "HTTP/1.1 302 Found\r\n"
"Location: https://%.*s:8082/%s:8082\r\n\r\n", "Location: https://%.*s:8082/%s:8082\r\n\r\n",
(int) (p - host), host, request_info->uri); (int) (p - host), host, request_info->uri);
} else { } else {
mg_printf(conn, "%s", "HTTP/1.1 500 Error\r\n\r\nHost: header is not set"); httplib_printf(conn, "%s", "HTTP/1.1 500 Error\r\n\r\nHost: header is not set");
} }
} }
static int begin_request_handler(struct mg_connection *conn) static int begin_request_handler(struct httplib_connection *conn)
{ {
const struct mg_request_info *request_info = mg_get_request_info(conn); const struct httplib_request_info *request_info = httplib_get_request_info(conn);
int processed = 1; int processed = 1;
if (!request_info->is_ssl) { if (!request_info->is_ssl) {
@@ -375,8 +374,8 @@ static const char *options[] = {
int main(void) int main(void)
{ {
struct mg_callbacks callbacks; struct httplib_callbacks callbacks;
struct mg_context *ctx; struct httplib_context *ctx;
// Initialize random number generator. It will be used later on for // Initialize random number generator. It will be used later on for
// the session identifier creation. // the session identifier creation.
@@ -385,16 +384,16 @@ int main(void)
// Setup and start Civetweb // Setup and start Civetweb
memset(&callbacks, 0, sizeof(callbacks)); memset(&callbacks, 0, sizeof(callbacks));
callbacks.begin_request = begin_request_handler; callbacks.begin_request = begin_request_handler;
if ((ctx = mg_start(&callbacks, NULL, options)) == NULL) { if ((ctx = httplib_start(&callbacks, NULL, options)) == NULL) {
printf("%s\n", "Cannot start chat server, fatal exit"); printf("%s\n", "Cannot start chat server, fatal exit");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
// Wait until enter is pressed, then exit // Wait until enter is pressed, then exit
printf("Chat server started on ports %s, press enter to quit.\n", printf("Chat server started on ports %s, press enter to quit.\n",
mg_get_option(ctx, "listening_ports")); httplib_get_option(ctx, "listening_ports"));
getchar(); getchar();
mg_stop(ctx); httplib_stop(ctx);
printf("%s\n", "Chat server stopped."); printf("%s\n", "Chat server stopped.");
return EXIT_SUCCESS; return EXIT_SUCCESS;

View File

@@ -38,157 +38,157 @@ int exitNow = 0;
int int
ExampleHandler(struct mg_connection *conn, void *cbdata) ExampleHandler(struct httplib_connection *conn, void *cbdata)
{ {
mg_printf(conn, httplib_printf(conn,
"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: " "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: "
"close\r\n\r\n"); "close\r\n\r\n");
mg_printf(conn, "<html><body>"); httplib_printf(conn, "<html><body>");
mg_printf(conn, "<h2>This is an example text from a C handler</h2>"); httplib_printf(conn, "<h2>This is an example text from a C handler</h2>");
mg_printf( httplib_printf(
conn, conn,
"<p>To see a page from the A handler <a href=\"A\">click A</a></p>"); "<p>To see a page from the A handler <a href=\"A\">click A</a></p>");
mg_printf(conn, httplib_printf(conn,
"<p>To see a page from the A handler <a href=\"A/A\">click " "<p>To see a page from the A handler <a href=\"A/A\">click "
"A/A</a></p>"); "A/A</a></p>");
mg_printf(conn, httplib_printf(conn,
"<p>To see a page from the A/B handler <a " "<p>To see a page from the A/B handler <a "
"href=\"A/B\">click A/B</a></p>"); "href=\"A/B\">click A/B</a></p>");
mg_printf(conn, httplib_printf(conn,
"<p>To see a page from the B handler (0) <a " "<p>To see a page from the B handler (0) <a "
"href=\"B\">click B</a></p>"); "href=\"B\">click B</a></p>");
mg_printf(conn, httplib_printf(conn,
"<p>To see a page from the B handler (1) <a " "<p>To see a page from the B handler (1) <a "
"href=\"B/A\">click B/A</a></p>"); "href=\"B/A\">click B/A</a></p>");
mg_printf(conn, httplib_printf(conn,
"<p>To see a page from the B handler (2) <a " "<p>To see a page from the B handler (2) <a "
"href=\"B/B\">click B/B</a></p>"); "href=\"B/B\">click B/B</a></p>");
mg_printf(conn, httplib_printf(conn,
"<p>To see a page from the *.foo handler <a " "<p>To see a page from the *.foo handler <a "
"href=\"xy.foo\">click xy.foo</a></p>"); "href=\"xy.foo\">click xy.foo</a></p>");
mg_printf(conn, httplib_printf(conn,
"<p>To see a page from the close handler <a " "<p>To see a page from the close handler <a "
"href=\"close\">click close</a></p>"); "href=\"close\">click close</a></p>");
mg_printf(conn, httplib_printf(conn,
"<p>To see a page from the FileHandler handler <a " "<p>To see a page from the FileHandler handler <a "
"href=\"form\">click form</a> (the starting point of the " "href=\"form\">click form</a> (the starting point of the "
"<b>form</b> test)</p>"); "<b>form</b> test)</p>");
mg_printf(conn, httplib_printf(conn,
"<p>To see a page from the CookieHandler handler <a " "<p>To see a page from the CookieHandler handler <a "
"href=\"cookie\">click cookie</a></p>"); "href=\"cookie\">click cookie</a></p>");
mg_printf(conn, httplib_printf(conn,
"<p>To see an example for parsing files on the fly <a " "<p>To see an example for parsing files on the fly <a "
"href=\"on_the_fly_form\">click form</a> (form for " "href=\"on_the_fly_form\">click form</a> (form for "
"uploading files)</p>"); "uploading files)</p>");
#ifdef USE_WEBSOCKET #ifdef USE_WEBSOCKET
mg_printf(conn, httplib_printf(conn,
"<p>To test websocket handler <a href=\"/websocket\">click " "<p>To test websocket handler <a href=\"/websocket\">click "
"websocket</a></p>"); "websocket</a></p>");
#endif #endif
mg_printf(conn, "<p>To exit <a href=\"%s\">click exit</a></p>", EXIT_URI); httplib_printf(conn, "<p>To exit <a href=\"%s\">click exit</a></p>", EXIT_URI);
mg_printf(conn, "</body></html>\n"); httplib_printf(conn, "</body></html>\n");
return 1; return 1;
} }
int int
ExitHandler(struct mg_connection *conn, void *cbdata) ExitHandler(struct httplib_connection *conn, void *cbdata)
{ {
mg_printf(conn, httplib_printf(conn,
"HTTP/1.1 200 OK\r\nContent-Type: " "HTTP/1.1 200 OK\r\nContent-Type: "
"text/plain\r\nConnection: close\r\n\r\n"); "text/plain\r\nConnection: close\r\n\r\n");
mg_printf(conn, "Server will shut down.\n"); httplib_printf(conn, "Server will shut down.\n");
mg_printf(conn, "Bye!\n"); httplib_printf(conn, "Bye!\n");
exitNow = 1; exitNow = 1;
return 1; return 1;
} }
int int
AHandler(struct mg_connection *conn, void *cbdata) AHandler(struct httplib_connection *conn, void *cbdata)
{ {
mg_printf(conn, httplib_printf(conn,
"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: " "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: "
"close\r\n\r\n"); "close\r\n\r\n");
mg_printf(conn, "<html><body>"); httplib_printf(conn, "<html><body>");
mg_printf(conn, "<h2>This is the A handler!!!</h2>"); httplib_printf(conn, "<h2>This is the A handler!!!</h2>");
mg_printf(conn, "</body></html>\n"); httplib_printf(conn, "</body></html>\n");
return 1; return 1;
} }
int int
ABHandler(struct mg_connection *conn, void *cbdata) ABHandler(struct httplib_connection *conn, void *cbdata)
{ {
mg_printf(conn, httplib_printf(conn,
"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: " "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: "
"close\r\n\r\n"); "close\r\n\r\n");
mg_printf(conn, "<html><body>"); httplib_printf(conn, "<html><body>");
mg_printf(conn, "<h2>This is the AB handler!!!</h2>"); httplib_printf(conn, "<h2>This is the AB handler!!!</h2>");
mg_printf(conn, "</body></html>\n"); httplib_printf(conn, "</body></html>\n");
return 1; return 1;
} }
int int
BXHandler(struct mg_connection *conn, void *cbdata) BXHandler(struct httplib_connection *conn, void *cbdata)
{ {
/* Handler may access the request info using mg_get_request_info */ /* Handler may access the request info using httplib_get_request_info */
const struct mg_request_info *req_info = mg_get_request_info(conn); const struct httplib_request_info *req_info = httplib_get_request_info(conn);
mg_printf(conn, httplib_printf(conn,
"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: " "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: "
"close\r\n\r\n"); "close\r\n\r\n");
mg_printf(conn, "<html><body>"); httplib_printf(conn, "<html><body>");
mg_printf(conn, "<h2>This is the BX handler %p!!!</h2>", cbdata); httplib_printf(conn, "<h2>This is the BX handler %p!!!</h2>", cbdata);
mg_printf(conn, "<p>The actual uri is %s</p>", req_info->uri); httplib_printf(conn, "<p>The actual uri is %s</p>", req_info->uri);
mg_printf(conn, "</body></html>\n"); httplib_printf(conn, "</body></html>\n");
return 1; return 1;
} }
int int
FooHandler(struct mg_connection *conn, void *cbdata) FooHandler(struct httplib_connection *conn, void *cbdata)
{ {
/* Handler may access the request info using mg_get_request_info */ /* Handler may access the request info using httplib_get_request_info */
const struct mg_request_info *req_info = mg_get_request_info(conn); const struct httplib_request_info *req_info = httplib_get_request_info(conn);
mg_printf(conn, httplib_printf(conn,
"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: " "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: "
"close\r\n\r\n"); "close\r\n\r\n");
mg_printf(conn, "<html><body>"); httplib_printf(conn, "<html><body>");
mg_printf(conn, "<h2>This is the Foo handler!!!</h2>"); httplib_printf(conn, "<h2>This is the Foo handler!!!</h2>");
mg_printf(conn, httplib_printf(conn,
"<p>The request was:<br><pre>%s %s HTTP/%s</pre></p>", "<p>The request was:<br><pre>%s %s HTTP/%s</pre></p>",
req_info->request_method, req_info->request_method,
req_info->uri, req_info->uri,
req_info->http_version); req_info->http_version);
mg_printf(conn, "</body></html>\n"); httplib_printf(conn, "</body></html>\n");
return 1; return 1;
} }
int int
CloseHandler(struct mg_connection *conn, void *cbdata) CloseHandler(struct httplib_connection *conn, void *cbdata)
{ {
/* Handler may access the request info using mg_get_request_info */ /* Handler may access the request info using httplib_get_request_info */
const struct mg_request_info *req_info = mg_get_request_info(conn); const struct httplib_request_info *req_info = httplib_get_request_info(conn);
mg_printf(conn, httplib_printf(conn,
"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: " "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: "
"close\r\n\r\n"); "close\r\n\r\n");
mg_printf(conn, "<html><body>"); httplib_printf(conn, "<html><body>");
mg_printf(conn, httplib_printf(conn,
"<h2>This handler will close the connection in a second</h2>"); "<h2>This handler will close the connection in a second</h2>");
#ifdef _WIN32 #ifdef _WIN32
Sleep(1000); Sleep(1000);
#else #else
sleep(1); sleep(1);
#endif #endif
mg_printf(conn, "bye"); httplib_printf(conn, "bye");
printf("CloseHandler: close connection\n"); printf("CloseHandler: close connection\n");
mg_close_connection(conn); httplib_close_connection(conn);
printf("CloseHandler: wait 10 sec\n"); printf("CloseHandler: wait 10 sec\n");
#ifdef _WIN32 #ifdef _WIN32
Sleep(10000); Sleep(10000);
@@ -201,12 +201,12 @@ CloseHandler(struct mg_connection *conn, void *cbdata)
int int
FileHandler(struct mg_connection *conn, void *cbdata) FileHandler(struct httplib_connection *conn, void *cbdata)
{ {
/* In this handler, we ignore the req_info and send the file "fileName". */ /* In this handler, we ignore the req_info and send the file "fileName". */
const char *fileName = (const char *)cbdata; const char *fileName = (const char *)cbdata;
mg_send_file(conn, fileName); httplib_send_file(conn, fileName);
return 1; return 1;
} }
@@ -218,9 +218,9 @@ field_found(const char *key,
size_t pathlen, size_t pathlen,
void *user_data) void *user_data)
{ {
struct mg_connection *conn = (struct mg_connection *)user_data; struct httplib_connection *conn = (struct httplib_connection *)user_data;
mg_printf(conn, "\r\n\r\n%s:\r\n", key); httplib_printf(conn, "\r\n\r\n%s:\r\n", key);
if (filename && *filename) { if (filename && *filename) {
#ifdef _WIN32 #ifdef _WIN32
@@ -237,12 +237,12 @@ field_found(const char *key,
int int
field_get(const char *key, const char *value, size_t valuelen, void *user_data) field_get(const char *key, const char *value, size_t valuelen, void *user_data)
{ {
struct mg_connection *conn = (struct mg_connection *)user_data; struct httplib_connection *conn = (struct httplib_connection *)user_data;
if (key[0]) { if (key[0]) {
mg_printf(conn, "%s = ", key); httplib_printf(conn, "%s = ", key);
} }
mg_write(conn, value, valuelen); httplib_write(conn, value, valuelen);
return 0; return 0;
} }
@@ -251,62 +251,59 @@ field_get(const char *key, const char *value, size_t valuelen, void *user_data)
int int
field_stored(const char *path, long long file_size, void *user_data) field_stored(const char *path, long long file_size, void *user_data)
{ {
struct mg_connection *conn = (struct mg_connection *)user_data; struct httplib_connection *conn = (struct httplib_connection *)user_data;
mg_printf(conn, httplib_printf(conn, "stored as %s (%lu bytes)\r\n\r\n", path, (unsigned long)file_size);
"stored as %s (%lu bytes)\r\n\r\n",
path,
(unsigned long)file_size);
return 0; return 0;
} }
int int
FormHandler(struct mg_connection *conn, void *cbdata) FormHandler(struct httplib_connection *conn, void *cbdata)
{ {
/* Handler may access the request info using mg_get_request_info */ /* Handler may access the request info using httplib_get_request_info */
const struct mg_request_info *req_info = mg_get_request_info(conn); const struct httplib_request_info *req_info = httplib_get_request_info(conn);
int ret; int ret;
struct mg_form_data_handler fdh = {field_found, field_get, field_stored, 0}; struct httplib_form_data_handler fdh = {field_found, field_get, field_stored, 0};
/* It would be possible to check the request info here before calling /* It would be possible to check the request info here before calling
* mg_handle_form_request. */ * httplib_handle_form_request. */
(void)req_info; (void)req_info;
mg_printf(conn, httplib_printf(conn,
"HTTP/1.1 200 OK\r\nContent-Type: " "HTTP/1.1 200 OK\r\nContent-Type: "
"text/plain\r\nConnection: close\r\n\r\n"); "text/plain\r\nConnection: close\r\n\r\n");
fdh.user_data = (void *)conn; fdh.user_data = (void *)conn;
/* Call the form handler */ /* Call the form handler */
mg_printf(conn, "Form data:"); httplib_printf(conn, "Form data:");
ret = mg_handle_form_request(conn, &fdh); ret = httplib_handle_form_request(conn, &fdh);
mg_printf(conn, "\r\n%i fields found", ret); httplib_printf(conn, "\r\n%i fields found", ret);
return 1; return 1;
} }
int int
FileUploadForm(struct mg_connection *conn, void *cbdata) FileUploadForm(struct httplib_connection *conn, void *cbdata)
{ {
mg_printf(conn, httplib_printf(conn,
"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: " "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: "
"close\r\n\r\n"); "close\r\n\r\n");
mg_printf(conn, "<!DOCTYPE html>\n"); httplib_printf(conn, "<!DOCTYPE html>\n");
mg_printf(conn, "<html>\n<head>\n"); httplib_printf(conn, "<html>\n<head>\n");
mg_printf(conn, "<meta charset=\"UTF-8\">\n"); httplib_printf(conn, "<meta charset=\"UTF-8\">\n");
mg_printf(conn, "<title>File upload</title>\n"); httplib_printf(conn, "<title>File upload</title>\n");
mg_printf(conn, "</head>\n<body>\n"); httplib_printf(conn, "</head>\n<body>\n");
mg_printf(conn, httplib_printf(conn,
"<form action=\"%s\" method=\"POST\" " "<form action=\"%s\" method=\"POST\" "
"enctype=\"multipart/form-data\">\n", "enctype=\"multipart/form-data\">\n",
(const char *)cbdata); (const char *)cbdata);
mg_printf(conn, "<input type=\"file\" name=\"filesin\" multiple>\n"); httplib_printf(conn, "<input type=\"file\" name=\"filesin\" multiple>\n");
mg_printf(conn, "<input type=\"submit\" value=\"Submit\">\n"); httplib_printf(conn, "<input type=\"submit\" value=\"Submit\">\n");
mg_printf(conn, "</form>\n</body>\n</html>\n"); httplib_printf(conn, "</form>\n</body>\n</html>\n");
return 1; return 1;
} }
@@ -371,66 +368,63 @@ field_get_checksum(const char *key,
int int
CheckSumHandler(struct mg_connection *conn, void *cbdata) CheckSumHandler(struct httplib_connection *conn, void *cbdata)
{ {
/* Handler may access the request info using mg_get_request_info */ /* Handler may access the request info using httplib_get_request_info */
const struct mg_request_info *req_info = mg_get_request_info(conn); const struct httplib_request_info *req_info = httplib_get_request_info(conn);
int i, j, ret; int i, j, ret;
struct tfiles_checksums chksums; struct tfiles_checksums chksums;
md5_byte_t digest[16]; md5_byte_t digest[16];
struct mg_form_data_handler fdh = {field_disp_read_on_the_fly, struct httplib_form_data_handler fdh = {field_disp_read_on_the_fly, field_get_checksum, 0,(void *)&chksums};
field_get_checksum,
0,
(void *)&chksums};
/* It would be possible to check the request info here before calling /* It would be possible to check the request info here before calling
* mg_handle_form_request. */ * httplib_handle_form_request. */
(void)req_info; (void)req_info;
memset(&chksums, 0, sizeof(chksums)); memset(&chksums, 0, sizeof(chksums));
mg_printf(conn, httplib_printf(conn,
"HTTP/1.1 200 OK\r\n" "HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n" "Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n"); "Connection: close\r\n\r\n");
/* Call the form handler */ /* Call the form handler */
mg_printf(conn, "File checksums:"); httplib_printf(conn, "File checksums:");
ret = mg_handle_form_request(conn, &fdh); ret = httplib_handle_form_request(conn, &fdh);
for (i = 0; i < chksums.index; i++) { for (i = 0; i < chksums.index; i++) {
md5_finish(&(chksums.file[i].chksum), digest); md5_finish(&(chksums.file[i].chksum), digest);
/* Visual Studio 2010+ support llu */ /* Visual Studio 2010+ support llu */
mg_printf(conn, httplib_printf(conn,
"\r\n%s %llu ", "\r\n%s %llu ",
chksums.file[i].name, chksums.file[i].name,
chksums.file[i].length); chksums.file[i].length);
for (j = 0; j < 16; j++) { for (j = 0; j < 16; j++) {
mg_printf(conn, "%02x", (unsigned int)digest[j]); httplib_printf(conn, "%02x", (unsigned int)digest[j]);
} }
} }
mg_printf(conn, "\r\n%i files\r\n", ret); httplib_printf(conn, "\r\n%i files\r\n", ret);
return 1; return 1;
} }
int int
CookieHandler(struct mg_connection *conn, void *cbdata) CookieHandler(struct httplib_connection *conn, void *cbdata)
{ {
/* Handler may access the request info using mg_get_request_info */ /* Handler may access the request info using httplib_get_request_info */
const struct mg_request_info *req_info = mg_get_request_info(conn); const struct httplib_request_info *req_info = httplib_get_request_info(conn);
const char *cookie = mg_get_header(conn, "Cookie"); const char *cookie = httplib_get_header(conn, "Cookie");
char first_str[64], count_str[64]; char first_str[64], count_str[64];
int count; int count;
(void)mg_get_cookie(cookie, "first", first_str, sizeof(first_str)); httplib_get_cookie(cookie, "first", first_str, sizeof(first_str));
(void)mg_get_cookie(cookie, "count", count_str, sizeof(count_str)); httplib_get_cookie(cookie, "count", count_str, sizeof(count_str));
mg_printf(conn, "HTTP/1.1 200 OK\r\nConnection: close\r\n"); httplib_printf(conn, "HTTP/1.1 200 OK\r\nConnection: close\r\n");
if (first_str[0] == 0) { if (first_str[0] == 0) {
time_t t = time(0); time_t t = time(0);
struct tm *ptm = localtime(&t); struct tm *ptm = localtime(&t);
mg_printf(conn, httplib_printf(conn,
"Set-Cookie: first=%04i-%02i-%02iT%02i:%02i:%02i\r\n", "Set-Cookie: first=%04i-%02i-%02iT%02i:%02i:%02i\r\n",
ptm->tm_year + 1900, ptm->tm_year + 1900,
ptm->tm_mon + 1, ptm->tm_mon + 1,
@@ -440,42 +434,42 @@ CookieHandler(struct mg_connection *conn, void *cbdata)
ptm->tm_sec); ptm->tm_sec);
} }
count = (count_str[0] == 0) ? 0 : atoi(count_str); count = (count_str[0] == 0) ? 0 : atoi(count_str);
mg_printf(conn, "Set-Cookie: count=%i\r\n", count + 1); httplib_printf(conn, "Set-Cookie: count=%i\r\n", count + 1);
mg_printf(conn, "Content-Type: text/html\r\n\r\n"); httplib_printf(conn, "Content-Type: text/html\r\n\r\n");
mg_printf(conn, "<html><body>"); httplib_printf(conn, "<html><body>");
mg_printf(conn, "<h2>This is the CookieHandler.</h2>"); httplib_printf(conn, "<h2>This is the CookieHandler.</h2>");
mg_printf(conn, "<p>The actual uri is %s</p>", req_info->uri); httplib_printf(conn, "<p>The actual uri is %s</p>", req_info->uri);
if (first_str[0] == 0) { if (first_str[0] == 0) {
mg_printf(conn, "<p>This is the first time, you opened this page</p>"); httplib_printf(conn, "<p>This is the first time, you opened this page</p>");
} else { } else {
mg_printf(conn, "<p>You opened this page %i times before.</p>", count); httplib_printf(conn, "<p>You opened this page %i times before.</p>", count);
mg_printf(conn, "<p>You first opened this page on %s.</p>", first_str); httplib_printf(conn, "<p>You first opened this page on %s.</p>", first_str);
} }
mg_printf(conn, "</body></html>\n"); httplib_printf(conn, "</body></html>\n");
return 1; return 1;
} }
int int
WebSocketStartHandler(struct mg_connection *conn, void *cbdata) WebSocketStartHandler(struct httplib_connection *conn, void *cbdata)
{ {
mg_printf(conn, httplib_printf(conn,
"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: " "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: "
"close\r\n\r\n"); "close\r\n\r\n");
mg_printf(conn, "<!DOCTYPE html>\n"); httplib_printf(conn, "<!DOCTYPE html>\n");
mg_printf(conn, "<html>\n<head>\n"); httplib_printf(conn, "<html>\n<head>\n");
mg_printf(conn, "<meta charset=\"UTF-8\">\n"); httplib_printf(conn, "<meta charset=\"UTF-8\">\n");
mg_printf(conn, "<title>Embedded websocket example</title>\n"); httplib_printf(conn, "<title>Embedded websocket example</title>\n");
#ifdef USE_WEBSOCKET #ifdef USE_WEBSOCKET
/* mg_printf(conn, "<script type=\"text/javascript\"><![CDATA[\n"); ... /* httplib_printf(conn, "<script type=\"text/javascript\"><![CDATA[\n"); ...
* xhtml style */ * xhtml style */
mg_printf(conn, "<script>\n"); httplib_printf(conn, "<script>\n");
mg_printf( httplib_printf(
conn, conn,
"function load() {\n" "function load() {\n"
" var wsproto = (location.protocol === 'https:') ? 'wss:' : 'ws:';\n" " var wsproto = (location.protocol === 'https:') ? 'wss:' : 'ws:';\n"
@@ -491,17 +485,17 @@ WebSocketStartHandler(struct mg_connection *conn, void *cbdata)
" connection.close();\n" " connection.close();\n"
" }\n" " }\n"
"}\n"); "}\n");
/* mg_printf(conn, "]]></script>\n"); ... xhtml style */ /* httplib_printf(conn, "]]></script>\n"); ... xhtml style */
mg_printf(conn, "</script>\n"); httplib_printf(conn, "</script>\n");
mg_printf(conn, "</head>\n<body onload=\"load()\">\n"); httplib_printf(conn, "</head>\n<body onload=\"load()\">\n");
mg_printf( httplib_printf(
conn, conn,
"<div id='websock_text_field'>No websocket connection yet</div>\n"); "<div id='websock_text_field'>No websocket connection yet</div>\n");
#else #else
mg_printf(conn, "</head>\n<body>\n"); httplib_printf(conn, "</head>\n<body>\n");
mg_printf(conn, "Example not compiled with USE_WEBSOCKET\n"); httplib_printf(conn, "Example not compiled with USE_WEBSOCKET\n");
#endif #endif
mg_printf(conn, "</body>\n</html>\n"); httplib_printf(conn, "</body>\n</html>\n");
return 1; return 1;
} }
@@ -517,7 +511,7 @@ WebSocketStartHandler(struct mg_connection *conn, void *cbdata)
#define MAX_WS_CLIENTS (5) #define MAX_WS_CLIENTS (5)
struct t_ws_client { struct t_ws_client {
struct mg_connection *conn; struct httplib_connection *conn;
int state; int state;
} static ws_clients[MAX_WS_CLIENTS]; } static ws_clients[MAX_WS_CLIENTS];
@@ -533,39 +527,36 @@ struct t_ws_client {
int int
WebSocketConnectHandler(const struct mg_connection *conn, void *cbdata) WebSocketConnectHandler(const struct httplib_connection *conn, void *cbdata)
{ {
struct mg_context *ctx = mg_get_context(conn); struct httplib_context *ctx = httplib_get_context(conn);
int reject = 1; int reject = 1;
int i; int i;
mg_lock_context(ctx); httplib_lock_context(ctx);
for (i = 0; i < MAX_WS_CLIENTS; i++) { for (i = 0; i < MAX_WS_CLIENTS; i++) {
if (ws_clients[i].conn == NULL) { if (ws_clients[i].conn == NULL) {
ws_clients[i].conn = (struct mg_connection *)conn; ws_clients[i].conn = (struct httplib_connection *)conn;
ws_clients[i].state = 1; ws_clients[i].state = 1;
mg_set_user_connection_data(ws_clients[i].conn, httplib_set_user_connection_data(ws_clients[i].conn, (void *)(ws_clients + i));
(void *)(ws_clients + i));
reject = 0; reject = 0;
break; break;
} }
} }
mg_unlock_context(ctx); httplib_unlock_context(ctx);
fprintf(stdout, fprintf(stdout, "Websocket client %s\r\n\r\n", (reject ? "rejected" : "accepted"));
"Websocket client %s\r\n\r\n",
(reject ? "rejected" : "accepted"));
return reject; return reject;
} }
void void
WebSocketReadyHandler(struct mg_connection *conn, void *cbdata) WebSocketReadyHandler(struct httplib_connection *conn, void *cbdata)
{ {
const char *text = "Hello from the websocket ready handler"; const char *text = "Hello from the websocket ready handler";
struct t_ws_client *client = mg_get_user_connection_data(conn); struct t_ws_client *client = httplib_get_user_connection_data(conn);
mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, text, strlen(text)); httplib_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, text, strlen(text));
fprintf(stdout, "Greeting message sent to websocket client\r\n\r\n"); fprintf(stdout, "Greeting message sent to websocket client\r\n\r\n");
ASSERT(client->conn == conn); ASSERT(client->conn == conn);
ASSERT(client->state == 1); ASSERT(client->state == 1);
@@ -575,13 +566,9 @@ WebSocketReadyHandler(struct mg_connection *conn, void *cbdata)
int int
WebsocketDataHandler(struct mg_connection *conn, WebsocketDataHandler(struct httplib_connection *conn, int bits, char *data, size_t len, void *cbdata)
int bits,
char *data,
size_t len,
void *cbdata)
{ {
struct t_ws_client *client = mg_get_user_connection_data(conn); struct t_ws_client *client = httplib_get_user_connection_data(conn);
ASSERT(client->conn == conn); ASSERT(client->conn == conn);
ASSERT(client->state >= 1); ASSERT(client->state >= 1);
@@ -594,25 +581,24 @@ WebsocketDataHandler(struct mg_connection *conn,
void void
WebSocketCloseHandler(const struct mg_connection *conn, void *cbdata) WebSocketCloseHandler(const struct httplib_connection *conn, void *cbdata)
{ {
struct mg_context *ctx = mg_get_context(conn); struct httplib_context *ctx = httplib_get_context(conn);
struct t_ws_client *client = mg_get_user_connection_data(conn); struct t_ws_client *client = httplib_get_user_connection_data(conn);
ASSERT(client->conn == conn); ASSERT(client->conn == conn);
ASSERT(client->state >= 1); ASSERT(client->state >= 1);
mg_lock_context(ctx); httplib_lock_context(ctx);
client->state = 0; client->state = 0;
client->conn = NULL; client->conn = NULL;
mg_unlock_context(ctx); httplib_unlock_context(ctx);
fprintf(stdout, fprintf(stdout, "Client droped from the set of webserver connections\r\n\r\n");
"Client droped from the set of webserver connections\r\n\r\n");
} }
void void
InformWebsockets(struct mg_context *ctx) InformWebsockets(struct httplib_context *ctx)
{ {
static unsigned long cnt = 0; static unsigned long cnt = 0;
char text[32]; char text[32];
@@ -620,16 +606,13 @@ InformWebsockets(struct mg_context *ctx)
sprintf(text, "%lu", ++cnt); sprintf(text, "%lu", ++cnt);
mg_lock_context(ctx); httplib_lock_context(ctx);
for (i = 0; i < MAX_WS_CLIENTS; i++) { for (i = 0; i < MAX_WS_CLIENTS; i++) {
if (ws_clients[i].state == 2) { if (ws_clients[i].state == 2) {
mg_websocket_write(ws_clients[i].conn, httplib_websocket_write(ws_clients[i].conn, WEBSOCKET_OPCODE_TEXT, text, strlen(text));
WEBSOCKET_OPCODE_TEXT,
text,
strlen(text));
} }
} }
mg_unlock_context(ctx); httplib_unlock_context(ctx);
} }
#endif #endif
@@ -747,15 +730,15 @@ main(int argc, char *argv[])
#endif #endif
#endif #endif
0}; 0};
struct mg_callbacks callbacks; struct httplib_callbacks callbacks;
struct mg_context *ctx; struct httplib_context *ctx;
struct mg_server_ports ports[32]; struct httplib_server_ports ports[32];
int port_cnt, n; int port_cnt, n;
int err = 0; int err = 0;
/* Check if libcivetweb has been built with all required features. */ /* Check if libcivetweb has been built with all required features. */
#ifdef USE_IPV6 #ifdef USE_IPV6
if (!mg_check_feature(8)) { if (!httplib_check_feature(8)) {
fprintf(stderr, fprintf(stderr,
"Error: Embedded example built with IPv6 support, " "Error: Embedded example built with IPv6 support, "
"but civetweb library build without.\n"); "but civetweb library build without.\n");
@@ -763,7 +746,7 @@ main(int argc, char *argv[])
} }
#endif #endif
#ifdef USE_WEBSOCKET #ifdef USE_WEBSOCKET
if (!mg_check_feature(16)) { if (!httplib_check_feature(16)) {
fprintf(stderr, fprintf(stderr,
"Error: Embedded example built with websocket support, " "Error: Embedded example built with websocket support, "
"but civetweb library build without.\n"); "but civetweb library build without.\n");
@@ -771,7 +754,7 @@ main(int argc, char *argv[])
} }
#endif #endif
#ifndef NO_SSL #ifndef NO_SSL
if (!mg_check_feature(2)) { if (!httplib_check_feature(2)) {
fprintf(stderr, fprintf(stderr,
"Error: Embedded example built with SSL support, " "Error: Embedded example built with SSL support, "
"but civetweb library build without.\n"); "but civetweb library build without.\n");
@@ -788,58 +771,49 @@ main(int argc, char *argv[])
#ifndef NO_SSL #ifndef NO_SSL
callbacks.init_ssl = init_ssl; callbacks.init_ssl = init_ssl;
#endif #endif
ctx = mg_start(&callbacks, 0, options); ctx = httplib_start(&callbacks, 0, options);
/* Add handler EXAMPLE_URI, to explain the example */ /* Add handler EXAMPLE_URI, to explain the example */
mg_set_request_handler(ctx, EXAMPLE_URI, ExampleHandler, 0); httplib_set_request_handler(ctx, EXAMPLE_URI, ExampleHandler, 0);
mg_set_request_handler(ctx, EXIT_URI, ExitHandler, 0); httplib_set_request_handler(ctx, EXIT_URI, ExitHandler, 0);
/* Add handler for /A* and special handler for /A/B */ /* Add handler for /A* and special handler for /A/B */
mg_set_request_handler(ctx, "/A", AHandler, 0); httplib_set_request_handler(ctx, "/A", AHandler, 0);
mg_set_request_handler(ctx, "/A/B", ABHandler, 0); httplib_set_request_handler(ctx, "/A/B", ABHandler, 0);
/* Add handler for /B, /B/A, /B/B but not for /B* */ /* Add handler for /B, /B/A, /B/B but not for /B* */
mg_set_request_handler(ctx, "/B$", BXHandler, (void *)0); httplib_set_request_handler(ctx, "/B$", BXHandler, (void *)0);
mg_set_request_handler(ctx, "/B/A$", BXHandler, (void *)1); httplib_set_request_handler(ctx, "/B/A$", BXHandler, (void *)1);
mg_set_request_handler(ctx, "/B/B$", BXHandler, (void *)2); httplib_set_request_handler(ctx, "/B/B$", BXHandler, (void *)2);
/* Add handler for all files with .foo extention */ /* Add handler for all files with .foo extention */
mg_set_request_handler(ctx, "**.foo$", FooHandler, 0); httplib_set_request_handler(ctx, "**.foo$", FooHandler, 0);
/* Add handler for /close extention */ /* Add handler for /close extention */
mg_set_request_handler(ctx, "/close", CloseHandler, 0); httplib_set_request_handler(ctx, "/close", CloseHandler, 0);
/* Add handler for /form (serve a file outside the document root) */ /* Add handler for /form (serve a file outside the document root) */
mg_set_request_handler(ctx, httplib_set_request_handler(ctx, "/form", FileHandler, (void *)"../../test/form.html");
"/form",
FileHandler,
(void *)"../../test/form.html");
/* Add handler for form data */ /* Add handler for form data */
mg_set_request_handler(ctx, httplib_set_request_handler(ctx,
"/handle_form.embedded_c.example.callback", "/handle_form.embedded_c.example.callback",
FormHandler, FormHandler,
(void *)0); (void *)0);
/* Add a file upload handler for parsing files on the fly */ /* Add a file upload handler for parsing files on the fly */
mg_set_request_handler(ctx, httplib_set_request_handler(ctx, "/on_the_fly_form", FileUploadForm, (void *)"/on_the_fly_form.md5.callback");
"/on_the_fly_form", httplib_set_request_handler(ctx, "/on_the_fly_form.md5.callback", CheckSumHandler, (void *)0);
FileUploadForm,
(void *)"/on_the_fly_form.md5.callback");
mg_set_request_handler(ctx,
"/on_the_fly_form.md5.callback",
CheckSumHandler,
(void *)0);
/* Add handler for /cookie example */ /* Add handler for /cookie example */
mg_set_request_handler(ctx, "/cookie", CookieHandler, 0); httplib_set_request_handler(ctx, "/cookie", CookieHandler, 0);
/* Add HTTP site to open a websocket connection */ /* Add HTTP site to open a websocket connection */
mg_set_request_handler(ctx, "/websocket", WebSocketStartHandler, 0); httplib_set_request_handler(ctx, "/websocket", WebSocketStartHandler, 0);
#ifdef USE_WEBSOCKET #ifdef USE_WEBSOCKET
/* WS site for the websocket connection */ /* WS site for the websocket connection */
mg_set_websocket_handler(ctx, httplib_set_websocket_handler(ctx,
"/websocket", "/websocket",
WebSocketConnectHandler, WebSocketConnectHandler,
WebSocketReadyHandler, WebSocketReadyHandler,
@@ -850,7 +824,7 @@ main(int argc, char *argv[])
/* List all listening ports */ /* List all listening ports */
memset(ports, 0, sizeof(ports)); memset(ports, 0, sizeof(ports));
port_cnt = mg_get_server_ports(ctx, 32, ports); port_cnt = httplib_get_server_ports(ctx, 32, ports);
printf("\n%i listening ports:\n\n", port_cnt); printf("\n%i listening ports:\n\n", port_cnt);
for (n = 0; n < port_cnt && n < 32; n++) { for (n = 0; n < port_cnt && n < 32; n++) {
@@ -899,7 +873,7 @@ main(int argc, char *argv[])
} }
/* Stop the server */ /* Stop the server */
mg_stop(ctx); httplib_stop(ctx);
printf("Server stopped.\n"); printf("Server stopped.\n");
printf("Bye!\n"); printf("Bye!\n");

View File

@@ -23,30 +23,30 @@ class ExampleHandler : public CivetHandler
{ {
public: public:
bool bool
handleGet(CivetServer *server, struct mg_connection *conn) handleGet(CivetServer *server, struct httplib_connection *conn)
{ {
mg_printf(conn, httplib_printf(conn,
"HTTP/1.1 200 OK\r\nContent-Type: " "HTTP/1.1 200 OK\r\nContent-Type: "
"text/html\r\nConnection: close\r\n\r\n"); "text/html\r\nConnection: close\r\n\r\n");
mg_printf(conn, "<html><body>\r\n"); httplib_printf(conn, "<html><body>\r\n");
mg_printf(conn, httplib_printf(conn,
"<h2>This is an example text from a C++ handler</h2>\r\n"); "<h2>This is an example text from a C++ handler</h2>\r\n");
mg_printf(conn, httplib_printf(conn,
"<p>To see a page from the A handler <a " "<p>To see a page from the A handler <a "
"href=\"a\">click here</a></p>\r\n"); "href=\"a\">click here</a></p>\r\n");
mg_printf(conn, httplib_printf(conn,
"<p>To see a page from the A handler with a parameter " "<p>To see a page from the A handler with a parameter "
"<a href=\"a?param=1\">click here</a></p>\r\n"); "<a href=\"a?param=1\">click here</a></p>\r\n");
mg_printf(conn, httplib_printf(conn,
"<p>To see a page from the A/B handler <a " "<p>To see a page from the A/B handler <a "
"href=\"a/b\">click here</a></p>\r\n"); "href=\"a/b\">click here</a></p>\r\n");
mg_printf(conn, httplib_printf(conn,
"<p>To see a page from the *.foo handler <a " "<p>To see a page from the *.foo handler <a "
"href=\"xy.foo\">click here</a></p>\r\n"); "href=\"xy.foo\">click here</a></p>\r\n");
mg_printf(conn, httplib_printf(conn,
"<p>To exit <a href=\"%s\">click here</a></p>\r\n", "<p>To exit <a href=\"%s\">click here</a></p>\r\n",
EXIT_URI); EXIT_URI);
mg_printf(conn, "</body></html>\r\n"); httplib_printf(conn, "</body></html>\r\n");
return true; return true;
} }
}; };
@@ -55,12 +55,12 @@ class ExitHandler : public CivetHandler
{ {
public: public:
bool bool
handleGet(CivetServer *server, struct mg_connection *conn) handleGet(CivetServer *server, struct httplib_connection *conn)
{ {
mg_printf(conn, httplib_printf(conn,
"HTTP/1.1 200 OK\r\nContent-Type: " "HTTP/1.1 200 OK\r\nContent-Type: "
"text/plain\r\nConnection: close\r\n\r\n"); "text/plain\r\nConnection: close\r\n\r\n");
mg_printf(conn, "Bye!\n"); httplib_printf(conn, "Bye!\n");
exitNow = true; exitNow = true;
return true; return true;
} }
@@ -72,31 +72,31 @@ class AHandler : public CivetHandler
bool bool
handleAll(const char *method, handleAll(const char *method,
CivetServer *server, CivetServer *server,
struct mg_connection *conn) struct httplib_connection *conn)
{ {
std::string s = ""; std::string s = "";
mg_printf(conn, httplib_printf(conn,
"HTTP/1.1 200 OK\r\nContent-Type: " "HTTP/1.1 200 OK\r\nContent-Type: "
"text/html\r\nConnection: close\r\n\r\n"); "text/html\r\nConnection: close\r\n\r\n");
mg_printf(conn, "<html><body>"); httplib_printf(conn, "<html><body>");
mg_printf(conn, "<h2>This is the A handler for \"%s\" !</h2>", method); httplib_printf(conn, "<h2>This is the A handler for \"%s\" !</h2>", method);
if (CivetServer::getParam(conn, "param", s)) { if (CivetServer::getParam(conn, "param", s)) {
mg_printf(conn, "<p>param set to %s</p>", s.c_str()); httplib_printf(conn, "<p>param set to %s</p>", s.c_str());
} else { } else {
mg_printf(conn, "<p>param not set</p>"); httplib_printf(conn, "<p>param not set</p>");
} }
mg_printf(conn, "</body></html>\n"); httplib_printf(conn, "</body></html>\n");
return true; return true;
} }
public: public:
bool bool
handleGet(CivetServer *server, struct mg_connection *conn) handleGet(CivetServer *server, struct httplib_connection *conn)
{ {
return handleAll("GET", server, conn); return handleAll("GET", server, conn);
} }
bool bool
handlePost(CivetServer *server, struct mg_connection *conn) handlePost(CivetServer *server, struct httplib_connection *conn)
{ {
return handleAll("POST", server, conn); return handleAll("POST", server, conn);
} }
@@ -106,14 +106,14 @@ class ABHandler : public CivetHandler
{ {
public: public:
bool bool
handleGet(CivetServer *server, struct mg_connection *conn) handleGet(CivetServer *server, struct httplib_connection *conn)
{ {
mg_printf(conn, httplib_printf(conn,
"HTTP/1.1 200 OK\r\nContent-Type: " "HTTP/1.1 200 OK\r\nContent-Type: "
"text/html\r\nConnection: close\r\n\r\n"); "text/html\r\nConnection: close\r\n\r\n");
mg_printf(conn, "<html><body>"); httplib_printf(conn, "<html><body>");
mg_printf(conn, "<h2>This is the AB handler!!!</h2>"); httplib_printf(conn, "<h2>This is the AB handler!!!</h2>");
mg_printf(conn, "</body></html>\n"); httplib_printf(conn, "</body></html>\n");
return true; return true;
} }
}; };
@@ -122,68 +122,64 @@ class FooHandler : public CivetHandler
{ {
public: public:
bool bool
handleGet(CivetServer *server, struct mg_connection *conn) handleGet(CivetServer *server, struct httplib_connection *conn)
{ {
/* Handler may access the request info using mg_get_request_info */ /* Handler may access the request info using httplib_get_request_info */
const struct mg_request_info *req_info = mg_get_request_info(conn); const struct httplib_request_info *req_info = httplib_get_request_info(conn);
mg_printf(conn, httplib_printf(conn,
"HTTP/1.1 200 OK\r\nContent-Type: " "HTTP/1.1 200 OK\r\nContent-Type: "
"text/html\r\nConnection: close\r\n\r\n"); "text/html\r\nConnection: close\r\n\r\n");
mg_printf(conn, "<html><body>\n"); httplib_printf(conn, "<html><body>\n");
mg_printf(conn, "<h2>This is the Foo GET handler!!!</h2>\n"); httplib_printf(conn, "<h2>This is the Foo GET handler!!!</h2>\n");
mg_printf(conn, httplib_printf(conn,
"<p>The request was:<br><pre>%s %s HTTP/%s</pre></p>\n", "<p>The request was:<br><pre>%s %s HTTP/%s</pre></p>\n",
req_info->request_method, req_info->request_method,
req_info->uri, req_info->uri,
req_info->http_version); req_info->http_version);
mg_printf(conn, "</body></html>\n"); httplib_printf(conn, "</body></html>\n");
return true; return true;
} }
bool bool
handlePost(CivetServer *server, struct mg_connection *conn) handlePost(CivetServer *server, struct httplib_connection *conn)
{ {
/* Handler may access the request info using mg_get_request_info */ /* Handler may access the request info using httplib_get_request_info */
const struct mg_request_info *req_info = mg_get_request_info(conn); const struct httplib_request_info *req_info = httplib_get_request_info(conn);
long long rlen, wlen; long long rlen, wlen;
long long nlen = 0; long long nlen = 0;
long long tlen = req_info->content_length; long long tlen = req_info->content_length;
char buf[1024]; char buf[1024];
mg_printf(conn, httplib_printf(conn,
"HTTP/1.1 200 OK\r\nContent-Type: " "HTTP/1.1 200 OK\r\nContent-Type: "
"text/html\r\nConnection: close\r\n\r\n"); "text/html\r\nConnection: close\r\n\r\n");
mg_printf(conn, "<html><body>\n"); httplib_printf(conn, "<html><body>\n");
mg_printf(conn, "<h2>This is the Foo POST handler!!!</h2>\n"); httplib_printf(conn, "<h2>This is the Foo POST handler!!!</h2>\n");
mg_printf(conn, httplib_printf(conn,
"<p>The request was:<br><pre>%s %s HTTP/%s</pre></p>\n", "<p>The request was:<br><pre>%s %s HTTP/%s</pre></p>\n",
req_info->request_method, req_info->request_method,
req_info->uri, req_info->uri,
req_info->http_version); req_info->http_version);
mg_printf(conn, "<p>Content Length: %li</p>\n", (long)tlen); httplib_printf(conn, "<p>Content Length: %li</p>\n", (long)tlen);
mg_printf(conn, "<pre>\n"); httplib_printf(conn, "<pre>\n");
while (nlen < tlen) { while (nlen < tlen) {
rlen = tlen - nlen; rlen = tlen - nlen;
if (rlen > sizeof(buf)) { if (rlen > sizeof(buf)) {
rlen = sizeof(buf); rlen = sizeof(buf);
} }
rlen = mg_read(conn, buf, (size_t)rlen); rlen = httplib_read(conn, buf, (size_t)rlen);
if (rlen <= 0) { if (rlen <= 0) break;
break; wlen = httplib_write(conn, buf, (size_t)rlen);
} if (rlen != rlen) break;
wlen = mg_write(conn, buf, (size_t)rlen);
if (rlen != rlen) {
break;
}
nlen += wlen; nlen += wlen;
} }
mg_printf(conn, "\n</pre>\n"); httplib_printf(conn, "\n</pre>\n");
mg_printf(conn, "</body></html>\n"); httplib_printf(conn, "</body></html>\n");
return true; return true;
} }
@@ -191,10 +187,10 @@ class FooHandler : public CivetHandler
#define fopen_recursive fopen #define fopen_recursive fopen
bool bool
handlePut(CivetServer *server, struct mg_connection *conn) handlePut(CivetServer *server, struct httplib_connection *conn)
{ {
/* Handler may access the request info using mg_get_request_info */ /* Handler may access the request info using httplib_get_request_info */
const struct mg_request_info *req_info = mg_get_request_info(conn); const struct httplib_request_info *req_info = httplib_get_request_info(conn);
long long rlen, wlen; long long rlen, wlen;
long long nlen = 0; long long nlen = 0;
long long tlen = req_info->content_length; long long tlen = req_info->content_length;
@@ -220,7 +216,7 @@ class FooHandler : public CivetHandler
if (rlen > sizeof(buf)) { if (rlen > sizeof(buf)) {
rlen = sizeof(buf); rlen = sizeof(buf);
} }
rlen = mg_read(conn, buf, (size_t)rlen); rlen = httplib_read(conn, buf, (size_t)rlen);
if (rlen <= 0) { if (rlen <= 0) {
fail = 1; fail = 1;
break; break;
@@ -236,12 +232,12 @@ class FooHandler : public CivetHandler
} }
if (fail) { if (fail) {
mg_printf(conn, httplib_printf(conn,
"HTTP/1.1 409 Conflict\r\n" "HTTP/1.1 409 Conflict\r\n"
"Content-Type: text/plain\r\n" "Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n"); "Connection: close\r\n\r\n");
} else { } else {
mg_printf(conn, httplib_printf(conn,
"HTTP/1.1 201 Created\r\n" "HTTP/1.1 201 Created\r\n"
"Content-Type: text/plain\r\n" "Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n"); "Connection: close\r\n\r\n");

View File

@@ -3,9 +3,9 @@
#include "civetweb.h" #include "civetweb.h"
// This function will be called by civetweb on every new request. // This function will be called by civetweb on every new request.
static int begin_request_handler(struct mg_connection *conn) static int begin_request_handler(struct httplib_connection *conn)
{ {
const struct mg_request_info *request_info = mg_get_request_info(conn); const struct httplib_request_info *request_info = httplib_get_request_info(conn);
char content[100]; char content[100];
// Prepare the message we're going to send // Prepare the message we're going to send
@@ -14,7 +14,7 @@ static int begin_request_handler(struct mg_connection *conn)
request_info->remote_port); request_info->remote_port);
// Send HTTP reply to the client // Send HTTP reply to the client
mg_printf(conn, httplib_printf(conn,
"HTTP/1.1 200 OK\r\n" "HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n" "Content-Type: text/plain\r\n"
"Content-Length: %d\r\n" // Always set Content-Length "Content-Length: %d\r\n" // Always set Content-Length
@@ -29,8 +29,8 @@ static int begin_request_handler(struct mg_connection *conn)
int main(void) int main(void)
{ {
struct mg_context *ctx; struct httplib_context *ctx;
struct mg_callbacks callbacks; struct httplib_callbacks callbacks;
// List of options. Last element must be NULL. // List of options. Last element must be NULL.
const char *options[] = {"listening_ports", "8080", NULL}; const char *options[] = {"listening_ports", "8080", NULL};
@@ -40,14 +40,14 @@ int main(void)
callbacks.begin_request = begin_request_handler; callbacks.begin_request = begin_request_handler;
// Start the web server. // Start the web server.
ctx = mg_start(&callbacks, NULL, options); ctx = httplib_start(&callbacks, NULL, options);
// Wait until user hits "enter". Server is running in separate thread. // Wait until user hits "enter". Server is running in separate thread.
// Navigating to http://localhost:8080 will invoke begin_request_handler(). // Navigating to http://localhost:8080 will invoke begin_request_handler().
getchar(); getchar();
// Stop the server. // Stop the server.
mg_stop(ctx); httplib_stop(ctx);
return 0; return 0;
} }

View File

@@ -10,22 +10,22 @@ static const char *html_form =
"<input type=\"submit\" />" "<input type=\"submit\" />"
"</form></body></html>"; "</form></body></html>";
static int begin_request_handler(struct mg_connection *conn) static int begin_request_handler(struct httplib_connection *conn)
{ {
const struct mg_request_info *ri = mg_get_request_info(conn); const struct httplib_request_info *ri = httplib_get_request_info(conn);
char post_data[1024], input1[sizeof(post_data)], input2[sizeof(post_data)]; char post_data[1024], input1[sizeof(post_data)], input2[sizeof(post_data)];
int post_data_len; int post_data_len;
if (!strcmp(ri->uri, "/handle_post_request")) { if (!strcmp(ri->uri, "/handle_post_request")) {
// User has submitted a form, show submitted data and a variable value // User has submitted a form, show submitted data and a variable value
post_data_len = mg_read(conn, post_data, sizeof(post_data)); post_data_len = httplib_read(conn, post_data, sizeof(post_data));
// Parse form data. input1 and input2 are guaranteed to be NUL-terminated // Parse form data. input1 and input2 are guaranteed to be NUL-terminated
mg_get_var(post_data, post_data_len, "input_1", input1, sizeof(input1)); httplib_get_var(post_data, post_data_len, "input_1", input1, sizeof(input1));
mg_get_var(post_data, post_data_len, "input_2", input2, sizeof(input2)); httplib_get_var(post_data, post_data_len, "input_2", input2, sizeof(input2));
// Send reply to the client, showing submitted form values. // Send reply to the client, showing submitted form values.
mg_printf(conn, "HTTP/1.0 200 OK\r\n" httplib_printf(conn, "HTTP/1.0 200 OK\r\n"
"Content-Type: text/plain\r\n\r\n" "Content-Type: text/plain\r\n\r\n"
"Submitted data: [%.*s]\n" "Submitted data: [%.*s]\n"
"Submitted data length: %d bytes\n" "Submitted data length: %d bytes\n"
@@ -34,7 +34,7 @@ static int begin_request_handler(struct mg_connection *conn)
post_data_len, post_data, post_data_len, input1, input2); post_data_len, post_data, post_data_len, input1, input2);
} else { } else {
// Show HTML form. // Show HTML form.
mg_printf(conn, "HTTP/1.0 200 OK\r\n" httplib_printf(conn, "HTTP/1.0 200 OK\r\n"
"Content-Length: %d\r\n" "Content-Length: %d\r\n"
"Content-Type: text/html\r\n\r\n%s", "Content-Type: text/html\r\n\r\n%s",
(int) strlen(html_form), html_form); (int) strlen(html_form), html_form);
@@ -44,15 +44,15 @@ static int begin_request_handler(struct mg_connection *conn)
int main(void) int main(void)
{ {
struct mg_context *ctx; struct httplib_context *ctx;
const char *options[] = {"listening_ports", "8080", NULL}; const char *options[] = {"listening_ports", "8080", NULL};
struct mg_callbacks callbacks; struct httplib_callbacks callbacks;
memset(&callbacks, 0, sizeof(callbacks)); memset(&callbacks, 0, sizeof(callbacks));
callbacks.begin_request = begin_request_handler; callbacks.begin_request = begin_request_handler;
ctx = mg_start(&callbacks, NULL, options); ctx = httplib_start(&callbacks, NULL, options);
getchar(); // Wait until user hits "enter" getchar(); // Wait until user hits "enter"
mg_stop(ctx); httplib_stop(ctx);
return 0; return 0;
} }

View File

@@ -29,7 +29,7 @@ typedef __int64 int64_t;
/* callback: used to generate all content */ /* callback: used to generate all content */
static int begin_request_handler(struct mg_connection *conn) static int begin_request_handler(struct httplib_connection *conn)
{ {
const char * tempPath = "."; const char * tempPath = ".";
#ifdef _WIN32 #ifdef _WIN32
@@ -40,10 +40,10 @@ static int begin_request_handler(struct mg_connection *conn)
tempPath = "/tmp"; tempPath = "/tmp";
#endif #endif
if (!strcmp(mg_get_request_info(conn)->uri, "/handle_post_request")) { if (!strcmp(httplib_get_request_info(conn)->uri, "/handle_post_request")) {
mg_printf(conn, "%s", "HTTP/1.0 200 OK\r\n\r\n"); httplib_printf(conn, "%s", "HTTP/1.0 200 OK\r\n\r\n");
mg_upload(conn, tempPath); httplib_upload(conn, tempPath);
} else { } else {
/* Show HTML form. */ /* Show HTML form. */
/* See http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1 */ /* See http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1 */
@@ -60,7 +60,7 @@ static int begin_request_handler(struct mg_connection *conn)
"" ""
"</body></html>"; "</body></html>";
mg_printf(conn, "HTTP/1.0 200 OK\r\n" httplib_printf(conn, "HTTP/1.0 200 OK\r\n"
"Content-Length: %d\r\n" "Content-Length: %d\r\n"
"Content-Type: text/html\r\n\r\n%s", "Content-Type: text/html\r\n\r\n%s",
(int) strlen(html_form), html_form); (int) strlen(html_form), html_form);
@@ -72,9 +72,9 @@ static int begin_request_handler(struct mg_connection *conn)
/* callback: called after uploading a file is completed */ /* callback: called after uploading a file is completed */
static void upload_handler(struct mg_connection *conn, const char *path) static void upload_handler(struct httplib_connection *conn, const char *path)
{ {
mg_printf(conn, "Saved [%s]", path); httplib_printf(conn, "Saved [%s]", path);
} }
@@ -85,11 +85,11 @@ int main(void)
const char * PORT = "8080"; const char * PORT = "8080";
/* Startup options for the server */ /* Startup options for the server */
struct mg_context *ctx; struct httplib_context *ctx;
const char *options[] = { const char *options[] = {
"listening_ports", PORT, "listening_ports", PORT,
NULL}; NULL};
struct mg_callbacks callbacks; struct httplib_callbacks callbacks;
memset(&callbacks, 0, sizeof(callbacks)); memset(&callbacks, 0, sizeof(callbacks));
callbacks.begin_request = begin_request_handler; callbacks.begin_request = begin_request_handler;
@@ -100,11 +100,11 @@ int main(void)
printf("Open http://localhost:%s/ in your browser.\n\n", PORT); printf("Open http://localhost:%s/ in your browser.\n\n", PORT);
/* Start the server */ /* Start the server */
ctx = mg_start(&callbacks, NULL, options); ctx = httplib_start(&callbacks, NULL, options);
/* Wait until thr user hits "enter", then stop the server */ /* Wait until thr user hits "enter", then stop the server */
getchar(); getchar();
mg_stop(ctx); httplib_stop(ctx);
return 0; return 0;
} }

View File

@@ -11,49 +11,49 @@
#ifdef _WIN32 #ifdef _WIN32
#include <Windows.h> #include <Windows.h>
#define mg_sleep(x) Sleep(x) #define httplib_sleep(x) Sleep(x)
#else #else
#include <unistd.h> #include <unistd.h>
#include <pthread.h> #include <pthread.h>
#define mg_sleep(x) usleep((x)*1000) #define httplib_sleep(x) usleep((x)*1000)
#endif #endif
static void static void
send_to_all_websockets(struct mg_context *ctx, const char *data, int data_len) send_to_all_websockets(struct httplib_context *ctx, const char *data, int data_len)
{ {
int i; int i;
tWebSockContext *ws_ctx = (tWebSockContext *)mg_get_user_data(ctx); tWebSockContext *ws_ctx = (tWebSockContext *)httplib_get_user_data(ctx);
mg_lock_context(ctx); httplib_lock_context(ctx);
for (i = 0; i < MAX_NUM_OF_WEBSOCKS; i++) { for (i = 0; i < MAX_NUM_OF_WEBSOCKS; i++) {
if (ws_ctx->socketList[i] if (ws_ctx->socketList[i]
&& (ws_ctx->socketList[i]->webSockState == 2)) { && (ws_ctx->socketList[i]->webSockState == 2)) {
mg_websocket_write(ws_ctx->socketList[i]->conn, httplib_websocket_write(ws_ctx->socketList[i]->conn,
WEBSOCKET_OPCODE_TEXT, WEBSOCKET_OPCODE_TEXT,
data, data,
data_len); data_len);
} }
} }
mg_unlock_context(ctx); httplib_unlock_context(ctx);
} }
void void
websocket_ready_handler(struct mg_connection *conn, void *_ignored) websocket_ready_handler(struct httplib_connection *conn, void *_ignored)
{ {
int i; int i;
const struct mg_request_info *rq = mg_get_request_info(conn); const struct httplib_request_info *rq = httplib_get_request_info(conn);
struct mg_context *ctx = mg_get_context(conn); struct httplib_context *ctx = httplib_get_context(conn);
tWebSockContext *ws_ctx = (tWebSockContext *)mg_get_user_data(ctx); tWebSockContext *ws_ctx = (tWebSockContext *)httplib_get_user_data(ctx);
tWebSockInfo *wsock = malloc(sizeof(tWebSockInfo)); tWebSockInfo *wsock = malloc(sizeof(tWebSockInfo));
assert(wsock); assert(wsock);
wsock->webSockState = 0; wsock->webSockState = 0;
mg_set_user_connection_data(conn, wsock); httplib_set_user_connection_data(conn, wsock);
mg_lock_context(ctx); httplib_lock_context(ctx);
for (i = 0; i < MAX_NUM_OF_WEBSOCKS; i++) { for (i = 0; i < MAX_NUM_OF_WEBSOCKS; i++) {
if (0 == ws_ctx->socketList[i]) { if (0 == ws_ctx->socketList[i]) {
ws_ctx->socketList[i] = wsock; ws_ctx->socketList[i] = wsock;
@@ -65,7 +65,7 @@ websocket_ready_handler(struct mg_connection *conn, void *_ignored)
printf("\nNew websocket attached: %s:%u\n", printf("\nNew websocket attached: %s:%u\n",
rq->remote_addr, rq->remote_addr,
rq->remote_port); rq->remote_port);
mg_unlock_context(ctx); httplib_unlock_context(ctx);
} }
@@ -84,33 +84,33 @@ websocket_done(tWebSockContext *ws_ctx, tWebSockInfo *wsock)
} }
} }
printf("\nClose websocket attached: %s:%u\n", printf("\nClose websocket attached: %s:%u\n",
mg_get_request_info(wsock->conn)->remote_addr, httplib_get_request_info(wsock->conn)->remote_addr,
mg_get_request_info(wsock->conn)->remote_port); httplib_get_request_info(wsock->conn)->remote_port);
free(wsock); free(wsock);
} }
} }
int int
websocket_data_handler(struct mg_connection *conn, websocket_data_handler(struct httplib_connection *conn,
int flags, int flags,
char *data, char *data,
size_t data_len, size_t data_len,
void *_ignored) void *_ignored)
{ {
const struct mg_request_info *rq = mg_get_request_info(conn); const struct httplib_request_info *rq = httplib_get_request_info(conn);
tWebSockInfo *wsock = (tWebSockInfo *)rq->conn_data; tWebSockInfo *wsock = (tWebSockInfo *)rq->conn_data;
struct mg_context *ctx = mg_get_context(conn); struct httplib_context *ctx = httplib_get_context(conn);
tWebSockContext *ws_ctx = (tWebSockContext *)mg_get_user_data(ctx); tWebSockContext *ws_ctx = (tWebSockContext *)httplib_get_user_data(ctx);
char msg[128]; char msg[128];
mg_lock_context(ctx); httplib_lock_context(ctx);
if (flags == 136) { if (flags == 136) {
// close websock // close websock
websocket_done(ws_ctx, wsock); websocket_done(ws_ctx, wsock);
mg_set_user_connection_data(conn, NULL); httplib_set_user_connection_data(conn, NULL);
mg_unlock_context(ctx); httplib_unlock_context(ctx);
return 1; return 1;
} }
if (((data_len >= 5) && (data_len < 100) && (flags == 129)) if (((data_len >= 5) && (data_len < 100) && (flags == 129))
@@ -127,42 +127,42 @@ websocket_data_handler(struct mg_connection *conn,
if (gid > 0 && chk != NULL && *chk == 0) { if (gid > 0 && chk != NULL && *chk == 0) {
wsock->webSockState = 2; wsock->webSockState = 2;
} }
mg_unlock_context(ctx); httplib_unlock_context(ctx);
return 1; return 1;
} }
// chat message // chat message
if ((wsock->webSockState == 2) && (!memcmp(data, "msg ", 4))) { if ((wsock->webSockState == 2) && (!memcmp(data, "msg ", 4))) {
send_to_all_websockets(ctx, data, data_len); send_to_all_websockets(ctx, data, data_len);
mg_unlock_context(ctx); httplib_unlock_context(ctx);
return 1; return 1;
} }
} }
// keep alive // keep alive
if ((data_len == 4) && !memcmp(data, "ping", 4)) { if ((data_len == 4) && !memcmp(data, "ping", 4)) {
mg_unlock_context(ctx); httplib_unlock_context(ctx);
return 1; return 1;
} }
mg_unlock_context(ctx); httplib_unlock_context(ctx);
return 0; return 0;
} }
void void
connection_close_handler(const struct mg_connection *conn, void *_ignored) connection_close_handler(const struct httplib_connection *conn, void *_ignored)
{ {
const struct mg_request_info *rq = mg_get_request_info(conn); const struct httplib_request_info *rq = httplib_get_request_info(conn);
tWebSockInfo *wsock = (tWebSockInfo *)rq->conn_data; tWebSockInfo *wsock = (tWebSockInfo *)rq->conn_data;
struct mg_context *ctx = mg_get_context(conn); struct httplib_context *ctx = httplib_get_context(conn);
tWebSockContext *ws_ctx = (tWebSockContext *)mg_get_user_data(ctx); tWebSockContext *ws_ctx = (tWebSockContext *)httplib_get_user_data(ctx);
mg_lock_context(ctx); httplib_lock_context(ctx);
websocket_done(ws_ctx, wsock); websocket_done(ws_ctx, wsock);
mg_set_user_connection_data(conn, NULL); httplib_set_user_connection_data(conn, NULL);
mg_unlock_context(ctx); httplib_unlock_context(ctx);
} }
@@ -171,8 +171,8 @@ eventMain(void *arg)
{ {
char msg[256]; char msg[256];
struct mg_context *ctx = (struct mg_context *)arg; struct httplib_context *ctx = (struct httplib_context *)arg;
tWebSockContext *ws_ctx = (tWebSockContext *)mg_get_user_data(ctx); tWebSockContext *ws_ctx = (tWebSockContext *)httplib_get_user_data(ctx);
ws_ctx->runLoop = 1; ws_ctx->runLoop = 1;
while (ws_ctx->runLoop) { while (ws_ctx->runLoop) {
@@ -181,7 +181,7 @@ eventMain(void *arg)
strftime(msg, sizeof(msg), "title %c", timestr); strftime(msg, sizeof(msg), "title %c", timestr);
send_to_all_websockets(ctx, msg, strlen(msg)); send_to_all_websockets(ctx, msg, strlen(msg));
mg_sleep(1000); httplib_sleep(1000);
} }
return NULL; return NULL;
@@ -189,7 +189,7 @@ eventMain(void *arg)
void void
websock_send_broadcast(struct mg_context *ctx, const char *data, int data_len) websock_send_broadcast(struct httplib_context *ctx, const char *data, int data_len)
{ {
char buffer[260]; char buffer[260];
@@ -204,22 +204,22 @@ websock_send_broadcast(struct mg_context *ctx, const char *data, int data_len)
void void
websock_init_lib(const struct mg_context *ctx) websock_init_lib(const struct httplib_context *ctx)
{ {
tWebSockContext *ws_ctx = (tWebSockContext *)mg_get_user_data(ctx); tWebSockContext *ws_ctx = (tWebSockContext *)httplib_get_user_data(ctx);
memset(ws_ctx, 0, sizeof(*ws_ctx)); memset(ws_ctx, 0, sizeof(*ws_ctx));
/* todo: use mg_start_thread_id instead of mg_start_thread */ /* todo: use httplib_start_thread_id instead of httplib_start_thread */
mg_start_thread(eventMain, (void *)ctx); httplib_start_thread(eventMain, (void *)ctx);
} }
void void
websock_exit_lib(const struct mg_context *ctx) websock_exit_lib(const struct httplib_context *ctx)
{ {
tWebSockContext *ws_ctx = (tWebSockContext *)mg_get_user_data(ctx); tWebSockContext *ws_ctx = (tWebSockContext *)httplib_get_user_data(ctx);
ws_ctx->runLoop = 0; ws_ctx->runLoop = 0;
/* todo: wait for the thread instead of a timeout */ /* todo: wait for the thread instead of a timeout */
mg_sleep(2000); httplib_sleep(2000);
} }

View File

@@ -11,7 +11,7 @@ extern "C" {
typedef struct tWebSockInfo { typedef struct tWebSockInfo {
int webSockState; int webSockState;
unsigned long initId; unsigned long initId;
struct mg_connection *conn; struct httplib_connection *conn;
} tWebSockInfo; } tWebSockInfo;
#define MAX_NUM_OF_WEBSOCKS (256) #define MAX_NUM_OF_WEBSOCKS (256)
@@ -22,23 +22,19 @@ typedef struct tWebSockContext {
} tWebSockContext; } tWebSockContext;
void websock_init_lib(const struct mg_context *ctx); void websock_init_lib(const struct httplib_context *ctx);
void websock_exit_lib(const struct mg_context *ctx); void websock_exit_lib(const struct httplib_context *ctx);
void void
websock_send_broadcast(struct mg_context *ctx, const char *data, int data_len); websock_send_broadcast(struct httplib_context *ctx, const char *data, int data_len);
void websocket_ready_handler(struct mg_connection *conn, void *_ignored); void websocket_ready_handler(struct httplib_connection *conn, void *_ignored);
int websocket_data_handler(struct mg_connection *conn, int websocket_data_handler(struct httplib_connection *conn, int flags, char *data, size_t data_len, void *_ignored);
int flags, void connection_close_handler(const struct httplib_connection *conn, void *_ignored);
char *data,
size_t data_len,
void *_ignored);
void connection_close_handler(const struct mg_connection *conn, void *_ignored);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif
#endif #endif

View File

@@ -13,8 +13,8 @@
int int
main(void) main(void)
{ {
struct mg_context *ctx = 0; struct httplib_context *ctx = 0;
struct mg_callbacks callback_funcs = {0}; struct httplib_callbacks callback_funcs = {0};
tWebSockContext ws_ctx; tWebSockContext ws_ctx;
char inbuf[4]; char inbuf[4];
@@ -35,9 +35,9 @@ main(void)
callback_funcs.init_context = websock_init_lib; callback_funcs.init_context = websock_init_lib;
callback_funcs.exit_context = websock_exit_lib; callback_funcs.exit_context = websock_exit_lib;
ctx = mg_start(&callback_funcs, &ws_ctx, server_options); ctx = httplib_start(&callback_funcs, &ws_ctx, server_options);
mg_set_websocket_handler(ctx, httplib_set_websocket_handler(ctx,
"/MyWebSock", "/MyWebSock",
NULL, NULL,
websocket_ready_handler, websocket_ready_handler,
@@ -46,7 +46,7 @@ main(void)
NULL); NULL);
printf("Connect to localhost:%s/websock.htm\n", printf("Connect to localhost:%s/websock.htm\n",
mg_get_option(ctx, "listening_ports")); httplib_get_option(ctx, "listening_ports"));
puts("Enter an (ASCII) character or * to exit:"); puts("Enter an (ASCII) character or * to exit:");
for (;;) { for (;;) {
@@ -59,7 +59,7 @@ main(void)
websock_send_broadcast(ctx, inbuf, 1); websock_send_broadcast(ctx, inbuf, 1);
} }
mg_stop(ctx); httplib_stop(ctx);
return 0; return 0;
} }

View File

@@ -40,10 +40,10 @@ const size_t websocket_goodbye_msg_len = 14 /* strlen(websocket_goodbye_msg) */;
/*************************************************************************************/ /*************************************************************************************/
#if defined(MG_LEGACY_INTERFACE) #if defined(MG_LEGACY_INTERFACE)
int int
websock_server_connect(const struct mg_connection *conn) websock_server_connect(const struct httplib_connection *conn)
#else #else
int int
websocket_server_connect(const struct mg_connection *conn, void *_ignored) websocket_server_connect(const struct httplib_connection *conn, void *_ignored)
#endif #endif
{ {
printf("Server: Websocket connected\n"); printf("Server: Websocket connected\n");
@@ -53,33 +53,33 @@ websocket_server_connect(const struct mg_connection *conn, void *_ignored)
#if defined(MG_LEGACY_INTERFACE) #if defined(MG_LEGACY_INTERFACE)
void void
websocket_server_ready(struct mg_connection *conn) websocket_server_ready(struct httplib_connection *conn)
#else #else
void void
websocket_server_ready(struct mg_connection *conn, void *_ignored) websocket_server_ready(struct httplib_connection *conn, void *_ignored)
#endif #endif
{ {
printf("Server: Websocket ready\n"); printf("Server: Websocket ready\n");
/* Send websocket welcome message */ /* Send websocket welcome message */
mg_lock_connection(conn); httplib_lock_connection(conn);
mg_websocket_write(conn, httplib_websocket_write(conn,
WEBSOCKET_OPCODE_TEXT, WEBSOCKET_OPCODE_TEXT,
websocket_welcome_msg, websocket_welcome_msg,
websocket_welcome_msg_len); websocket_welcome_msg_len);
mg_unlock_connection(conn); httplib_unlock_connection(conn);
} }
#if defined(MG_LEGACY_INTERFACE) #if defined(MG_LEGACY_INTERFACE)
int int
websocket_server_data(struct mg_connection *conn, websocket_server_data(struct httplib_connection *conn,
int bits, int bits,
char *data, char *data,
size_t data_len) size_t data_len)
#else #else
int int
websocket_server_data(struct mg_connection *conn, websocket_server_data(struct httplib_connection *conn,
int bits, int bits,
char *data, char *data,
size_t data_len, size_t data_len,
@@ -93,20 +93,20 @@ websocket_server_data(struct mg_connection *conn,
if (data_len < 3 || 0 != memcmp(data, "bye", 3)) { if (data_len < 3 || 0 != memcmp(data, "bye", 3)) {
/* Send websocket acknowledge message */ /* Send websocket acknowledge message */
mg_lock_connection(conn); httplib_lock_connection(conn);
mg_websocket_write(conn, httplib_websocket_write(conn,
WEBSOCKET_OPCODE_TEXT, WEBSOCKET_OPCODE_TEXT,
websocket_acknowledge_msg, websocket_acknowledge_msg,
websocket_acknowledge_msg_len); websocket_acknowledge_msg_len);
mg_unlock_connection(conn); httplib_unlock_connection(conn);
} else { } else {
/* Send websocket acknowledge message */ /* Send websocket acknowledge message */
mg_lock_connection(conn); httplib_lock_connection(conn);
mg_websocket_write(conn, httplib_websocket_write(conn,
WEBSOCKET_OPCODE_TEXT, WEBSOCKET_OPCODE_TEXT,
websocket_goodbye_msg, websocket_goodbye_msg,
websocket_goodbye_msg_len); websocket_goodbye_msg_len);
mg_unlock_connection(conn); httplib_unlock_connection(conn);
} }
return 1; /* return 1 to keep the connetion open */ return 1; /* return 1 to keep the connetion open */
@@ -115,10 +115,10 @@ websocket_server_data(struct mg_connection *conn,
#if defined(MG_LEGACY_INTERFACE) #if defined(MG_LEGACY_INTERFACE)
void void
websocket_server_connection_close(const struct mg_connection *conn) websocket_server_connection_close(const struct httplib_connection *conn)
#else #else
void void
websocket_server_connection_close(const struct mg_connection *conn, websocket_server_connection_close(const struct httplib_connection *conn,
void *_ignored) void *_ignored)
#endif #endif
{ {
@@ -129,7 +129,7 @@ websocket_server_connection_close(const struct mg_connection *conn,
} }
struct mg_context * struct httplib_context *
start_websocket_server() start_websocket_server()
{ {
const char *options[] = {"document_root", const char *options[] = {"document_root",
@@ -141,8 +141,8 @@ start_websocket_server()
"request_timeout_ms", "request_timeout_ms",
"5000", "5000",
0}; 0};
struct mg_callbacks callbacks; struct httplib_callbacks callbacks;
struct mg_context *ctx; struct httplib_context *ctx;
memset(&callbacks, 0, sizeof(callbacks)); memset(&callbacks, 0, sizeof(callbacks));
@@ -153,12 +153,12 @@ start_websocket_server()
callbacks.websocket_data = websocket_server_data; callbacks.websocket_data = websocket_server_data;
callbacks.connection_close = websocket_server_connection_close; callbacks.connection_close = websocket_server_connection_close;
ctx = mg_start(&callbacks, 0, options); ctx = httplib_start(&callbacks, 0, options);
#else #else
/* New interface: */ /* New interface: */
ctx = mg_start(&callbacks, 0, options); ctx = httplib_start(&callbacks, 0, options);
mg_set_websocket_handler(ctx, httplib_set_websocket_handler(ctx,
"/websocket", "/websocket",
websocket_server_connect, websocket_server_connect,
websocket_server_ready, websocket_server_ready,
@@ -181,15 +181,11 @@ struct tclient_data {
}; };
static int static int
websocket_client_data_handler(struct mg_connection *conn, websocket_client_data_handler(struct httplib_connection *conn, int flags, char *data, size_t data_len, void *user_data) {
int flags,
char *data, struct httplib_context *ctx = httplib_get_context(conn);
size_t data_len,
void *user_data)
{
struct mg_context *ctx = mg_get_context(conn);
struct tclient_data *pclient_data = struct tclient_data *pclient_data =
(struct tclient_data *)mg_get_user_data(ctx); (struct tclient_data *)httplib_get_user_data(ctx);
printf("Client received data from server: "); printf("Client received data from server: ");
fwrite(data, 1, data_len, stdout); fwrite(data, 1, data_len, stdout);
@@ -204,12 +200,12 @@ websocket_client_data_handler(struct mg_connection *conn,
} }
static void static void
websocket_client_close_handler(const struct mg_connection *conn, websocket_client_close_handler(const struct httplib_connection *conn,
void *user_data) void *user_data)
{ {
struct mg_context *ctx = mg_get_context(conn); struct httplib_context *ctx = httplib_get_context(conn);
struct tclient_data *pclient_data = struct tclient_data *pclient_data =
(struct tclient_data *)mg_get_user_data(ctx); (struct tclient_data *)httplib_get_user_data(ctx);
printf("Client: Close handler\n"); printf("Client: Close handler\n");
pclient_data->closed++; pclient_data->closed++;
@@ -219,13 +215,13 @@ websocket_client_close_handler(const struct mg_connection *conn,
int int
main(int argc, char *argv[]) main(int argc, char *argv[])
{ {
struct mg_context *ctx = NULL; struct httplib_context *ctx = NULL;
struct tclient_data client1_data = {NULL, 0, 0}; struct tclient_data client1_data = {NULL, 0, 0};
struct tclient_data client2_data = {NULL, 0, 0}; struct tclient_data client2_data = {NULL, 0, 0};
struct tclient_data client3_data = {NULL, 0, 0}; struct tclient_data client3_data = {NULL, 0, 0};
struct mg_connection *newconn1 = NULL; struct httplib_connection *newconn1 = NULL;
struct mg_connection *newconn2 = NULL; struct httplib_connection *newconn2 = NULL;
struct mg_connection *newconn3 = NULL; struct httplib_connection *newconn3 = NULL;
char ebuf[100] = {0}; char ebuf[100] = {0};
assert(websocket_welcome_msg_len == strlen(websocket_welcome_msg)); assert(websocket_welcome_msg_len == strlen(websocket_welcome_msg));
@@ -236,7 +232,7 @@ main(int argc, char *argv[])
printf("Server init\n\n"); printf("Server init\n\n");
/* Then connect a first client */ /* Then connect a first client */
newconn1 = mg_connect_websocket_client("localhost", newconn1 = httplib_connect_websocket_client("localhost",
atoi(PORT), atoi(PORT),
0, 0,
ebuf, ebuf,
@@ -266,7 +262,7 @@ main(int argc, char *argv[])
client1_data.data = NULL; client1_data.data = NULL;
client1_data.len = 0; client1_data.len = 0;
mg_websocket_client_write(newconn1, WEBSOCKET_OPCODE_TEXT, "data1", 5); httplib_websocket_client_write(newconn1, WEBSOCKET_OPCODE_TEXT, "data1", 5);
sleep(1); /* Should get the acknowledge message */ sleep(1); /* Should get the acknowledge message */
assert(client1_data.closed == 0); assert(client1_data.closed == 0);
@@ -283,7 +279,7 @@ main(int argc, char *argv[])
client1_data.len = 0; client1_data.len = 0;
/* Now connect a second client */ /* Now connect a second client */
newconn2 = mg_connect_websocket_client("localhost", newconn2 = httplib_connect_websocket_client("localhost",
atoi(PORT), atoi(PORT),
0, 0,
ebuf, ebuf,
@@ -313,7 +309,7 @@ main(int argc, char *argv[])
client2_data.data = NULL; client2_data.data = NULL;
client2_data.len = 0; client2_data.len = 0;
mg_websocket_client_write(newconn1, WEBSOCKET_OPCODE_TEXT, "data2", 5); httplib_websocket_client_write(newconn1, WEBSOCKET_OPCODE_TEXT, "data2", 5);
sleep(1); /* Should get the acknowledge message */ sleep(1); /* Should get the acknowledge message */
assert(client1_data.closed == 0); assert(client1_data.closed == 0);
@@ -329,7 +325,7 @@ main(int argc, char *argv[])
client1_data.data = NULL; client1_data.data = NULL;
client1_data.len = 0; client1_data.len = 0;
mg_websocket_client_write(newconn1, WEBSOCKET_OPCODE_TEXT, "bye", 3); httplib_websocket_client_write(newconn1, WEBSOCKET_OPCODE_TEXT, "bye", 3);
sleep(1); /* Should get the goodbye message */ sleep(1); /* Should get the goodbye message */
assert(client1_data.closed == 0); assert(client1_data.closed == 0);
@@ -345,7 +341,7 @@ main(int argc, char *argv[])
client1_data.data = NULL; client1_data.data = NULL;
client1_data.len = 0; client1_data.len = 0;
mg_close_connection(newconn1); httplib_close_connection(newconn1);
sleep(1); /* Won't get any message */ sleep(1); /* Won't get any message */
assert(client1_data.closed == 1); assert(client1_data.closed == 1);
@@ -355,7 +351,7 @@ main(int argc, char *argv[])
assert(client2_data.data == NULL); assert(client2_data.data == NULL);
assert(client2_data.len == 0); assert(client2_data.len == 0);
mg_websocket_client_write(newconn2, WEBSOCKET_OPCODE_TEXT, "bye", 3); httplib_websocket_client_write(newconn2, WEBSOCKET_OPCODE_TEXT, "bye", 3);
sleep(1); /* Should get the goodbye message */ sleep(1); /* Should get the goodbye message */
assert(client1_data.closed == 1); assert(client1_data.closed == 1);
@@ -371,7 +367,7 @@ main(int argc, char *argv[])
client2_data.data = NULL; client2_data.data = NULL;
client2_data.len = 0; client2_data.len = 0;
mg_close_connection(newconn2); httplib_close_connection(newconn2);
sleep(1); /* Won't get any message */ sleep(1); /* Won't get any message */
assert(client1_data.closed == 1); assert(client1_data.closed == 1);
@@ -382,7 +378,7 @@ main(int argc, char *argv[])
assert(client2_data.len == 0); assert(client2_data.len == 0);
/* Connect client 3 */ /* Connect client 3 */
newconn3 = mg_connect_websocket_client("localhost", newconn3 = httplib_connect_websocket_client("localhost",
atoi(PORT), atoi(PORT),
0, 0,
ebuf, ebuf,
@@ -410,7 +406,7 @@ main(int argc, char *argv[])
client3_data.data = NULL; client3_data.data = NULL;
client3_data.len = 0; client3_data.len = 0;
mg_stop(ctx); httplib_stop(ctx);
printf("Server shutdown\n"); printf("Server shutdown\n");
sleep(10); sleep(10);

View File

@@ -12,7 +12,7 @@
// simple structure for keeping track of websocket connection // simple structure for keeping track of websocket connection
struct ws_connection { struct ws_connection {
struct mg_connection *conn; struct httplib_connection *conn;
int update; int update;
int closing; int closing;
}; };
@@ -36,7 +36,7 @@ static struct ws_connection ws_conn[CONNECTIONS];
static void *ws_server_thread(void *parm) static void *ws_server_thread(void *parm)
{ {
int wsd = (long)parm; int wsd = (long)parm;
struct mg_connection *conn = ws_conn[wsd].conn; struct httplib_connection *conn = ws_conn[wsd].conn;
int timer = 0; int timer = 0;
char tstr[32]; char tstr[32];
int i; int i;
@@ -61,7 +61,7 @@ static void *ws_server_thread(void *parm)
meter[i].value = meter[i].limit; meter[i].value = meter[i].limit;
sprintf(tstr, "meter%d:%d,%d", i+1, sprintf(tstr, "meter%d:%d,%d", i+1,
meter[i].value, meter[i].limit); meter[i].value, meter[i].limit);
mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, tstr, strlen(tstr)); httplib_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, tstr, strlen(tstr));
} }
/* While the connection is open, send periodic updates */ /* While the connection is open, send periodic updates */
@@ -83,7 +83,7 @@ static void *ws_server_thread(void *parm)
if (!ws_conn[wsd].closing) { if (!ws_conn[wsd].closing) {
sprintf(tstr, "meter%d:%d,%d", i+1, sprintf(tstr, "meter%d:%d,%d", i+1,
meter[i].value, meter[i].limit); meter[i].value, meter[i].limit);
mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, tstr, strlen(tstr)); httplib_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, tstr, strlen(tstr));
} }
} }
} }
@@ -91,7 +91,7 @@ static void *ws_server_thread(void *parm)
/* Send periodic PING to assure websocket remains connected, except if we are closing */ /* Send periodic PING to assure websocket remains connected, except if we are closing */
if (timer%100 == 0 && !ws_conn[wsd].closing) if (timer%100 == 0 && !ws_conn[wsd].closing)
mg_websocket_write(conn, WEBSOCKET_OPCODE_PING, NULL, 0); httplib_websocket_write(conn, WEBSOCKET_OPCODE_PING, NULL, 0);
} }
fprintf(stderr, "ws_server_thread %d exiting\n", wsd); fprintf(stderr, "ws_server_thread %d exiting\n", wsd);
@@ -108,7 +108,7 @@ static void *ws_server_thread(void *parm)
// On new client connection, find next available server connection and store // On new client connection, find next available server connection and store
// new connection information. If no more server connections are available // new connection information. If no more server connections are available
// tell civetweb to not accept the client request. // tell civetweb to not accept the client request.
static int websocket_connect_handler(const struct mg_connection *conn) static int websocket_connect_handler(const struct httplib_connection *conn)
{ {
int i; int i;
@@ -117,7 +117,7 @@ static int websocket_connect_handler(const struct mg_connection *conn)
for(i=0; i < CONNECTIONS; ++i) { for(i=0; i < CONNECTIONS; ++i) {
if (ws_conn[i].conn == NULL) { if (ws_conn[i].conn == NULL) {
fprintf(stderr, "...prep for server %d\n", i); fprintf(stderr, "...prep for server %d\n", i);
ws_conn[i].conn = (struct mg_connection *)conn; ws_conn[i].conn = (struct httplib_connection *)conn;
ws_conn[i].closing = 0; ws_conn[i].closing = 0;
ws_conn[i].update = 0; ws_conn[i].update = 0;
break; break;
@@ -133,7 +133,7 @@ static int websocket_connect_handler(const struct mg_connection *conn)
// websocket_ready_handler() // websocket_ready_handler()
// Once websocket negotiation is complete, start a server for the connection // Once websocket negotiation is complete, start a server for the connection
static void websocket_ready_handler(struct mg_connection *conn) static void websocket_ready_handler(struct httplib_connection *conn)
{ {
int i; int i;
@@ -142,7 +142,7 @@ static void websocket_ready_handler(struct mg_connection *conn)
for(i=0; i < CONNECTIONS; ++i) { for(i=0; i < CONNECTIONS; ++i) {
if (ws_conn[i].conn == conn) { if (ws_conn[i].conn == conn) {
fprintf(stderr, "...start server %d\n", i); fprintf(stderr, "...start server %d\n", i);
mg_start_thread(ws_server_thread, (void *)(long)i); httplib_start_thread(ws_server_thread, (void *)(long)i);
break; break;
} }
} }
@@ -150,7 +150,7 @@ static void websocket_ready_handler(struct mg_connection *conn)
// websocket_close_handler() // websocket_close_handler()
// When websocket is closed, tell the associated server to shut down // When websocket is closed, tell the associated server to shut down
static void websocket_close_handler(struct mg_connection *conn) static void websocket_close_handler(struct httplib_connection *conn)
{ {
int i; int i;
@@ -168,8 +168,7 @@ static void websocket_close_handler(struct mg_connection *conn)
// flags: first byte of websocket frame, see websocket RFC, // flags: first byte of websocket frame, see websocket RFC,
// http://tools.ietf.org/html/rfc6455, section 5.2 // http://tools.ietf.org/html/rfc6455, section 5.2
// data, data_len: payload data. Mask, if any, is already applied. // data, data_len: payload data. Mask, if any, is already applied.
static int websocket_data_handler(struct mg_connection *conn, int flags, static int websocket_data_handler(struct httplib_connection *conn, int flags, char *data, size_t data_len)
char *data, size_t data_len)
{ {
int i; int i;
int wsd; int wsd;
@@ -198,12 +197,12 @@ static int websocket_data_handler(struct mg_connection *conn, int flags,
/* turn on updates */ /* turn on updates */
ws_conn[wsd].update = 1; ws_conn[wsd].update = 1;
/* echo back */ /* echo back */
mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, data, data_len); httplib_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, data, data_len);
} else if (strncmp("update off", data, data_len)== 0) { } else if (strncmp("update off", data, data_len)== 0) {
/* turn off updates */ /* turn off updates */
ws_conn[wsd].update = 0; ws_conn[wsd].update = 0;
/* echo back */ /* echo back */
mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, data, data_len); httplib_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, data, data_len);
} }
break; break;
case WEBSOCKET_OPCODE_BINARY: case WEBSOCKET_OPCODE_BINARY:
@@ -213,14 +212,14 @@ static int websocket_data_handler(struct mg_connection *conn, int flags,
fprintf(stderr, "CLOSE...\n"); fprintf(stderr, "CLOSE...\n");
/* If client initiated close, respond with close message in acknowlegement */ /* If client initiated close, respond with close message in acknowlegement */
if (!ws_conn[wsd].closing) { if (!ws_conn[wsd].closing) {
mg_websocket_write(conn, WEBSOCKET_OPCODE_CONNECTION_CLOSE, data, data_len); httplib_websocket_write(conn, WEBSOCKET_OPCODE_CONNECTION_CLOSE, data, data_len);
ws_conn[wsd].closing = 1; /* we should not send addional messages when close requested/acknowledged */ ws_conn[wsd].closing = 1; /* we should not send addional messages when close requested/acknowledged */
} }
return 0; /* time to close the connection */ return 0; /* time to close the connection */
break; break;
case WEBSOCKET_OPCODE_PING: case WEBSOCKET_OPCODE_PING:
/* client sent PING, respond with PONG */ /* client sent PING, respond with PONG */
mg_websocket_write(conn, WEBSOCKET_OPCODE_PONG, data, data_len); httplib_websocket_write(conn, WEBSOCKET_OPCODE_PONG, data, data_len);
break; break;
case WEBSOCKET_OPCODE_PONG: case WEBSOCKET_OPCODE_PONG:
/* received PONG to our PING, no action */ /* received PONG to our PING, no action */
@@ -238,8 +237,8 @@ static int websocket_data_handler(struct mg_connection *conn, int flags,
int main(void) int main(void)
{ {
char server_name[40]; char server_name[40];
struct mg_context *ctx; struct httplib_context *ctx;
struct mg_callbacks callbacks; struct httplib_callbacks callbacks;
const char *options[] = { const char *options[] = {
"listening_ports", "8080", "listening_ports", "8080",
"document_root", "docroot", "document_root", "docroot",
@@ -247,9 +246,7 @@ int main(void)
}; };
/* get simple greeting for the web server */ /* get simple greeting for the web server */
snprintf(server_name, sizeof(server_name), snprintf(server_name, sizeof(server_name), "Civetweb websocket server v. %s", httplib_version());
"Civetweb websocket server v. %s",
mg_version());
memset(&callbacks, 0, sizeof(callbacks)); memset(&callbacks, 0, sizeof(callbacks));
callbacks.websocket_connect = websocket_connect_handler; callbacks.websocket_connect = websocket_connect_handler;
@@ -257,15 +254,15 @@ int main(void)
callbacks.websocket_data = websocket_data_handler; callbacks.websocket_data = websocket_data_handler;
callbacks.connection_close = websocket_close_handler; callbacks.connection_close = websocket_close_handler;
ctx = mg_start(&callbacks, NULL, options); ctx = httplib_start(&callbacks, NULL, options);
/* show the greeting and some basic information */ /* show the greeting and some basic information */
printf("%s started on port(s) %s with web root [%s]\n", printf("%s started on port(s) %s with web root [%s]\n",
server_name, mg_get_option(ctx, "listening_ports"), server_name, httplib_get_option(ctx, "listening_ports"),
mg_get_option(ctx, "document_root")); httplib_get_option(ctx, "document_root"));
getchar(); // Wait until user hits "enter" getchar(); // Wait until user hits "enter"
mg_stop(ctx); httplib_stop(ctx);
return 0; return 0;
} }

View File

@@ -16,7 +16,7 @@
#endif #endif
bool bool
CivetHandler::handleGet(CivetServer *server, struct mg_connection *conn) CivetHandler::handleGet(CivetServer *server, struct httplib_connection *conn)
{ {
UNUSED_PARAMETER(server); UNUSED_PARAMETER(server);
UNUSED_PARAMETER(conn); UNUSED_PARAMETER(conn);
@@ -24,7 +24,7 @@ CivetHandler::handleGet(CivetServer *server, struct mg_connection *conn)
} }
bool bool
CivetHandler::handlePost(CivetServer *server, struct mg_connection *conn) CivetHandler::handlePost(CivetServer *server, struct httplib_connection *conn)
{ {
UNUSED_PARAMETER(server); UNUSED_PARAMETER(server);
UNUSED_PARAMETER(conn); UNUSED_PARAMETER(conn);
@@ -32,7 +32,7 @@ CivetHandler::handlePost(CivetServer *server, struct mg_connection *conn)
} }
bool bool
CivetHandler::handleHead(CivetServer *server, struct mg_connection *conn) CivetHandler::handleHead(CivetServer *server, struct httplib_connection *conn)
{ {
UNUSED_PARAMETER(server); UNUSED_PARAMETER(server);
UNUSED_PARAMETER(conn); UNUSED_PARAMETER(conn);
@@ -40,7 +40,7 @@ CivetHandler::handleHead(CivetServer *server, struct mg_connection *conn)
} }
bool bool
CivetHandler::handlePut(CivetServer *server, struct mg_connection *conn) CivetHandler::handlePut(CivetServer *server, struct httplib_connection *conn)
{ {
UNUSED_PARAMETER(server); UNUSED_PARAMETER(server);
UNUSED_PARAMETER(conn); UNUSED_PARAMETER(conn);
@@ -48,7 +48,7 @@ CivetHandler::handlePut(CivetServer *server, struct mg_connection *conn)
} }
bool bool
CivetHandler::handlePatch(CivetServer *server, struct mg_connection *conn) CivetHandler::handlePatch(CivetServer *server, struct httplib_connection *conn)
{ {
UNUSED_PARAMETER(server); UNUSED_PARAMETER(server);
UNUSED_PARAMETER(conn); UNUSED_PARAMETER(conn);
@@ -56,7 +56,7 @@ CivetHandler::handlePatch(CivetServer *server, struct mg_connection *conn)
} }
bool bool
CivetHandler::handleDelete(CivetServer *server, struct mg_connection *conn) CivetHandler::handleDelete(CivetServer *server, struct httplib_connection *conn)
{ {
UNUSED_PARAMETER(server); UNUSED_PARAMETER(server);
UNUSED_PARAMETER(conn); UNUSED_PARAMETER(conn);
@@ -64,7 +64,7 @@ CivetHandler::handleDelete(CivetServer *server, struct mg_connection *conn)
} }
bool bool
CivetHandler::handleOptions(CivetServer *server, struct mg_connection *conn) CivetHandler::handleOptions(CivetServer *server, struct httplib_connection *conn)
{ {
UNUSED_PARAMETER(server); UNUSED_PARAMETER(server);
UNUSED_PARAMETER(conn); UNUSED_PARAMETER(conn);
@@ -72,8 +72,7 @@ CivetHandler::handleOptions(CivetServer *server, struct mg_connection *conn)
} }
bool bool
CivetWebSocketHandler::handleConnection(CivetServer *server, CivetWebSocketHandler::handleConnection(CivetServer *server, const struct httplib_connection *conn)
const struct mg_connection *conn)
{ {
UNUSED_PARAMETER(server); UNUSED_PARAMETER(server);
UNUSED_PARAMETER(conn); UNUSED_PARAMETER(conn);
@@ -81,8 +80,7 @@ CivetWebSocketHandler::handleConnection(CivetServer *server,
} }
void void
CivetWebSocketHandler::handleReadyState(CivetServer *server, CivetWebSocketHandler::handleReadyState(CivetServer *server, struct httplib_connection *conn)
struct mg_connection *conn)
{ {
UNUSED_PARAMETER(server); UNUSED_PARAMETER(server);
UNUSED_PARAMETER(conn); UNUSED_PARAMETER(conn);
@@ -90,11 +88,7 @@ CivetWebSocketHandler::handleReadyState(CivetServer *server,
} }
bool bool
CivetWebSocketHandler::handleData(CivetServer *server, CivetWebSocketHandler::handleData(CivetServer *server, struct httplib_connection *conn, int bits, char *data, size_t data_len)
struct mg_connection *conn,
int bits,
char *data,
size_t data_len)
{ {
UNUSED_PARAMETER(server); UNUSED_PARAMETER(server);
UNUSED_PARAMETER(conn); UNUSED_PARAMETER(conn);
@@ -105,8 +99,7 @@ CivetWebSocketHandler::handleData(CivetServer *server,
} }
void void
CivetWebSocketHandler::handleClose(CivetServer *server, CivetWebSocketHandler::handleClose(CivetServer *server, const struct httplib_connection *conn)
const struct mg_connection *conn)
{ {
UNUSED_PARAMETER(server); UNUSED_PARAMETER(server);
UNUSED_PARAMETER(conn); UNUSED_PARAMETER(conn);
@@ -114,9 +107,9 @@ CivetWebSocketHandler::handleClose(CivetServer *server,
} }
int int
CivetServer::requestHandler(struct mg_connection *conn, void *cbdata) CivetServer::requestHandler(struct httplib_connection *conn, void *cbdata)
{ {
const struct mg_request_info *request_info = mg_get_request_info(conn); const struct httplib_request_info *request_info = httplib_get_request_info(conn);
assert(request_info != NULL); assert(request_info != NULL);
CivetServer *me = (CivetServer *)(request_info->user_data); CivetServer *me = (CivetServer *)(request_info->user_data);
assert(me != NULL); assert(me != NULL);
@@ -125,9 +118,9 @@ CivetServer::requestHandler(struct mg_connection *conn, void *cbdata)
if (me->context == NULL) if (me->context == NULL)
return 0; return 0;
mg_lock_context(me->context); httplib_lock_context(me->context);
me->connections[conn] = CivetConnection(); me->connections[conn] = CivetConnection();
mg_unlock_context(me->context); httplib_unlock_context(me->context);
CivetHandler *handler = (CivetHandler *)cbdata; CivetHandler *handler = (CivetHandler *)cbdata;
@@ -153,9 +146,9 @@ CivetServer::requestHandler(struct mg_connection *conn, void *cbdata)
} }
int int
CivetServer::authHandler(struct mg_connection *conn, void *cbdata) CivetServer::authHandler(struct httplib_connection *conn, void *cbdata)
{ {
const struct mg_request_info *request_info = mg_get_request_info(conn); const struct httplib_request_info *request_info = httplib_get_request_info(conn);
assert(request_info != NULL); assert(request_info != NULL);
CivetServer *me = (CivetServer *)(request_info->user_data); CivetServer *me = (CivetServer *)(request_info->user_data);
assert(me != NULL); assert(me != NULL);
@@ -164,9 +157,9 @@ CivetServer::authHandler(struct mg_connection *conn, void *cbdata)
if (me->context == NULL) if (me->context == NULL)
return 0; return 0;
mg_lock_context(me->context); httplib_lock_context(me->context);
me->connections[conn] = CivetConnection(); me->connections[conn] = CivetConnection();
mg_unlock_context(me->context); httplib_unlock_context(me->context);
CivetAuthHandler *handler = (CivetAuthHandler *)cbdata; CivetAuthHandler *handler = (CivetAuthHandler *)cbdata;
@@ -178,10 +171,9 @@ CivetServer::authHandler(struct mg_connection *conn, void *cbdata)
} }
int int
CivetServer::webSocketConnectionHandler(const struct mg_connection *conn, CivetServer::webSocketConnectionHandler(const struct httplib_connection *conn, void *cbdata)
void *cbdata)
{ {
const struct mg_request_info *request_info = mg_get_request_info(conn); const struct httplib_request_info *request_info = httplib_get_request_info(conn);
assert(request_info != NULL); assert(request_info != NULL);
CivetServer *me = (CivetServer *)(request_info->user_data); CivetServer *me = (CivetServer *)(request_info->user_data);
assert(me != NULL); assert(me != NULL);
@@ -200,9 +192,9 @@ CivetServer::webSocketConnectionHandler(const struct mg_connection *conn,
} }
void void
CivetServer::webSocketReadyHandler(struct mg_connection *conn, void *cbdata) CivetServer::webSocketReadyHandler(struct httplib_connection *conn, void *cbdata)
{ {
const struct mg_request_info *request_info = mg_get_request_info(conn); const struct httplib_request_info *request_info = httplib_get_request_info(conn);
assert(request_info != NULL); assert(request_info != NULL);
CivetServer *me = (CivetServer *)(request_info->user_data); CivetServer *me = (CivetServer *)(request_info->user_data);
assert(me != NULL); assert(me != NULL);
@@ -219,13 +211,9 @@ CivetServer::webSocketReadyHandler(struct mg_connection *conn, void *cbdata)
} }
int int
CivetServer::webSocketDataHandler(struct mg_connection *conn, CivetServer::webSocketDataHandler(struct httplib_connection *conn, int bits, char *data, size_t data_len, void *cbdata)
int bits,
char *data,
size_t data_len,
void *cbdata)
{ {
const struct mg_request_info *request_info = mg_get_request_info(conn); const struct httplib_request_info *request_info = httplib_get_request_info(conn);
assert(request_info != NULL); assert(request_info != NULL);
CivetServer *me = (CivetServer *)(request_info->user_data); CivetServer *me = (CivetServer *)(request_info->user_data);
assert(me != NULL); assert(me != NULL);
@@ -244,10 +232,9 @@ CivetServer::webSocketDataHandler(struct mg_connection *conn,
} }
void void
CivetServer::webSocketCloseHandler(const struct mg_connection *conn, CivetServer::webSocketCloseHandler(const struct httplib_connection *conn, void *cbdata)
void *cbdata)
{ {
const struct mg_request_info *request_info = mg_get_request_info(conn); const struct httplib_request_info *request_info = httplib_get_request_info(conn);
assert(request_info != NULL); assert(request_info != NULL);
CivetServer *me = (CivetServer *)(request_info->user_data); CivetServer *me = (CivetServer *)(request_info->user_data);
assert(me != NULL); assert(me != NULL);
@@ -281,7 +268,7 @@ CivetServer::CivetServer(const char **options,
userCloseHandler = NULL; userCloseHandler = NULL;
} }
callbacks.connection_close = closeHandler; callbacks.connection_close = closeHandler;
context = mg_start(&callbacks, this, options); context = httplib_start(&callbacks, this, options);
if (context == NULL) if (context == NULL)
throw CivetException("null context when constructing CivetServer. " throw CivetException("null context when constructing CivetServer. "
"Possible problem binding to port."); "Possible problem binding to port.");
@@ -307,7 +294,7 @@ CivetServer::CivetServer(std::vector<std::string> options,
} }
pointers.push_back(0); pointers.push_back(0);
context = mg_start(&callbacks, this, &pointers[0]); context = httplib_start(&callbacks, this, &pointers[0]);
if (context == NULL) if (context == NULL)
throw CivetException("null context when constructing CivetServer. " throw CivetException("null context when constructing CivetServer. "
"Possible problem binding to port."); "Possible problem binding to port.");
@@ -319,9 +306,9 @@ CivetServer::~CivetServer()
} }
void void
CivetServer::closeHandler(const struct mg_connection *conn) CivetServer::closeHandler(const struct httplib_connection *conn)
{ {
const struct mg_request_info *request_info = mg_get_request_info(conn); const struct httplib_request_info *request_info = httplib_get_request_info(conn);
assert(request_info != NULL); assert(request_info != NULL);
CivetServer *me = (CivetServer *)(request_info->user_data); CivetServer *me = (CivetServer *)(request_info->user_data);
assert(me != NULL); assert(me != NULL);
@@ -332,22 +319,22 @@ CivetServer::closeHandler(const struct mg_connection *conn)
if (me->userCloseHandler) if (me->userCloseHandler)
me->userCloseHandler(conn); me->userCloseHandler(conn);
mg_lock_context(me->context); httplib_lock_context(me->context);
me->connections.erase(const_cast<struct mg_connection *>(conn)); me->connections.erase(const_cast<struct httplib_connection *>(conn));
mg_unlock_context(me->context); httplib_unlock_context(me->context);
} }
void void
CivetServer::addHandler(const std::string &uri, CivetHandler *handler) CivetServer::addHandler(const std::string &uri, CivetHandler *handler)
{ {
mg_set_request_handler(context, uri.c_str(), requestHandler, handler); httplib_set_request_handler(context, uri.c_str(), requestHandler, handler);
} }
void void
CivetServer::addWebSocketHandler(const std::string &uri, CivetServer::addWebSocketHandler(const std::string &uri,
CivetWebSocketHandler *handler) CivetWebSocketHandler *handler)
{ {
mg_set_websocket_handler(context, httplib_set_websocket_handler(context,
uri.c_str(), uri.c_str(),
webSocketConnectionHandler, webSocketConnectionHandler,
webSocketReadyHandler, webSocketReadyHandler,
@@ -359,60 +346,55 @@ CivetServer::addWebSocketHandler(const std::string &uri,
void void
CivetServer::addAuthHandler(const std::string &uri, CivetAuthHandler *handler) CivetServer::addAuthHandler(const std::string &uri, CivetAuthHandler *handler)
{ {
mg_set_auth_handler(context, uri.c_str(), authHandler, handler); httplib_set_auth_handler(context, uri.c_str(), authHandler, handler);
} }
void void
CivetServer::removeHandler(const std::string &uri) CivetServer::removeHandler(const std::string &uri)
{ {
mg_set_request_handler(context, uri.c_str(), NULL, NULL); httplib_set_request_handler(context, uri.c_str(), NULL, NULL);
} }
void void
CivetServer::removeWebSocketHandler(const std::string &uri) CivetServer::removeWebSocketHandler(const std::string &uri)
{ {
mg_set_websocket_handler( httplib_set_websocket_handler( context, uri.c_str(), NULL, NULL, NULL, NULL, NULL);
context, uri.c_str(), NULL, NULL, NULL, NULL, NULL);
} }
void void
CivetServer::removeAuthHandler(const std::string &uri) CivetServer::removeAuthHandler(const std::string &uri)
{ {
mg_set_auth_handler(context, uri.c_str(), NULL, NULL); httplib_set_auth_handler(context, uri.c_str(), NULL, NULL);
} }
void void
CivetServer::close() CivetServer::close()
{ {
if (context) { if (context) {
mg_stop(context); httplib_stop(context);
context = 0; context = 0;
} }
} }
int int
CivetServer::getCookie(struct mg_connection *conn, CivetServer::getCookie(struct httplib_connection *conn,
const std::string &cookieName, const std::string &cookieName,
std::string &cookieValue) std::string &cookieValue)
{ {
// Maximum cookie length as per microsoft is 4096. // Maximum cookie length as per microsoft is 4096.
// http://msdn.microsoft.com/en-us/library/ms178194.aspx // http://msdn.microsoft.com/en-us/library/ms178194.aspx
char _cookieValue[4096]; char _cookieValue[4096];
const char *cookie = mg_get_header(conn, "Cookie"); const char *cookie = httplib_get_header(conn, "Cookie");
int lRead = mg_get_cookie(cookie, int lRead = httplib_get_cookie(cookie, cookieName.c_str(), _cookieValue, sizeof(_cookieValue));
cookieName.c_str(),
_cookieValue,
sizeof(_cookieValue));
cookieValue.clear(); cookieValue.clear();
cookieValue.append(_cookieValue); cookieValue.append(_cookieValue);
return lRead; return lRead;
} }
const char * const char *
CivetServer::getHeader(struct mg_connection *conn, CivetServer::getHeader(struct httplib_connection *conn, const std::string &headerName) {
const std::string &headerName)
{ return httplib_get_header(conn, headerName.c_str());
return mg_get_header(conn, headerName.c_str());
} }
void void
@@ -450,25 +432,22 @@ CivetServer::urlDecode(const char *src,
} }
bool bool
CivetServer::getParam(struct mg_connection *conn, CivetServer::getParam(struct httplib_connection *conn, const char *name, std::string &dst, size_t occurrence)
const char *name,
std::string &dst,
size_t occurrence)
{ {
const char *formParams = NULL; const char *formParams = NULL;
const struct mg_request_info *ri = mg_get_request_info(conn); const struct httplib_request_info *ri = httplib_get_request_info(conn);
assert(ri != NULL); assert(ri != NULL);
CivetServer *me = (CivetServer *)(ri->user_data); CivetServer *me = (CivetServer *)(ri->user_data);
assert(me != NULL); assert(me != NULL);
mg_lock_context(me->context); httplib_lock_context(me->context);
CivetConnection &conobj = me->connections[conn]; CivetConnection &conobj = me->connections[conn];
mg_lock_connection(conn); httplib_lock_connection(conn);
mg_unlock_context(me->context); httplib_unlock_context(me->context);
if (conobj.postData != NULL) { if (conobj.postData != NULL) {
formParams = conobj.postData; formParams = conobj.postData;
} else { } else {
const char *con_len_str = mg_get_header(conn, "Content-Length"); const char *con_len_str = httplib_get_header(conn, "Content-Length");
if (con_len_str) { if (con_len_str) {
unsigned long con_len = atoi(con_len_str); unsigned long con_len = atoi(con_len_str);
if (con_len > 0) { if (con_len > 0) {
@@ -479,7 +458,7 @@ CivetServer::getParam(struct mg_connection *conn,
conobj.postData = (char *)malloc(con_len + 1); conobj.postData = (char *)malloc(con_len + 1);
if (conobj.postData != NULL) { if (conobj.postData != NULL) {
// malloc may fail for huge requests // malloc may fail for huge requests
mg_read(conn, conobj.postData, con_len); httplib_read(conn, conobj.postData, con_len);
conobj.postData[con_len] = 0; conobj.postData[con_len] = 0;
formParams = conobj.postData; formParams = conobj.postData;
conobj.postDataLen = con_len; conobj.postDataLen = con_len;
@@ -492,7 +471,7 @@ CivetServer::getParam(struct mg_connection *conn,
// query_string // query_string
formParams = ri->query_string; formParams = ri->query_string;
} }
mg_unlock_connection(conn); httplib_unlock_connection(conn);
if (formParams != NULL) { if (formParams != NULL) {
return getParam(formParams, strlen(formParams), name, dst, occurrence); return getParam(formParams, strlen(formParams), name, dst, occurrence);
@@ -521,7 +500,7 @@ CivetServer::getParam(const char *data,
// data is "var1=val1&var2=val2...". Find variable first // data is "var1=val1&var2=val2...". Find variable first
for (p = data; p + name_len < e; p++) { for (p = data; p + name_len < e; p++) {
if ((p == data || p[-1] == '&') && p[name_len] == '=' if ((p == data || p[-1] == '&') && p[name_len] == '='
&& !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) { && !httplib_strncasecmp(name, p, name_len) && 0 == occurrence--) {
// Point p to variable value // Point p to variable value
p += name_len + 1; p += name_len + 1;
@@ -576,7 +555,7 @@ CivetServer::getListeningPorts()
{ {
std::vector<int> ports(10); std::vector<int> ports(10);
std::vector<int> ssl(10); std::vector<int> ssl(10);
size_t size = mg_get_ports(context, ports.size(), &ports[0], &ssl[0]); size_t size = httplib_get_ports(context, ports.size(), &ports[0], &ssl[0]);
ports.resize(size); ports.resize(size);
ssl.resize(size); ssl.resize(size);
return ports; return ports;

View File

@@ -26,13 +26,13 @@
#include "httplib_ssl.h" #include "httplib_ssl.h"
/* /*
* void XX_httplib_accept_new_connection( const struct socket *lostener, struct mg_context *ctx ); * void XX_httplib_accept_new_connection( const struct socket *lostener, struct httplib_context *ctx );
* *
* The function XX_httplib_accept_new_connection() is used to process new * The function XX_httplib_accept_new_connection() is used to process new
* incoming connections to the server. * incoming connections to the server.
*/ */
void XX_httplib_accept_new_connection( const struct socket *listener, struct mg_context *ctx ) { void XX_httplib_accept_new_connection( const struct socket *listener, struct httplib_context *ctx ) {
struct socket so; struct socket so;
char src_addr[IP_ADDR_STR_LEN]; char src_addr[IP_ADDR_STR_LEN];
@@ -46,7 +46,7 @@ void XX_httplib_accept_new_connection( const struct socket *listener, struct mg_
== INVALID_SOCKET) { == INVALID_SOCKET) {
} else if (!XX_httplib_check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) { } else if (!XX_httplib_check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
XX_httplib_sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa); XX_httplib_sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
mg_cry( XX_httplib_fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr); httplib_cry( XX_httplib_fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
closesocket(so.sock); closesocket(so.sock);
so.sock = INVALID_SOCKET; so.sock = INVALID_SOCKET;
} else { } else {
@@ -55,7 +55,7 @@ void XX_httplib_accept_new_connection( const struct socket *listener, struct mg_
so.is_ssl = listener->is_ssl; so.is_ssl = listener->is_ssl;
so.ssl_redir = listener->ssl_redir; so.ssl_redir = listener->ssl_redir;
if (getsockname(so.sock, &so.lsa.sa, &len) != 0) { if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
mg_cry( XX_httplib_fc(ctx), "%s: getsockname() failed: %s", __func__, strerror(ERRNO)); httplib_cry( XX_httplib_fc(ctx), "%s: getsockname() failed: %s", __func__, strerror(ERRNO));
} }
/* Set TCP keep-alive. This is needed because if HTTP-level /* Set TCP keep-alive. This is needed because if HTTP-level
@@ -67,7 +67,7 @@ void XX_httplib_accept_new_connection( const struct socket *listener, struct mg_
* Thanks to Igor Klopov who suggested the patch. */ * Thanks to Igor Klopov who suggested the patch. */
if (setsockopt(so.sock, SOL_SOCKET, SO_KEEPALIVE, (SOCK_OPT_TYPE)&on, sizeof(on)) != 0) { if (setsockopt(so.sock, SOL_SOCKET, SO_KEEPALIVE, (SOCK_OPT_TYPE)&on, sizeof(on)) != 0) {
mg_cry( XX_httplib_fc(ctx), "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s", __func__, strerror(ERRNO)); httplib_cry( XX_httplib_fc(ctx), "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s", __func__, strerror(ERRNO));
} }
/* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
@@ -80,7 +80,7 @@ void XX_httplib_accept_new_connection( const struct socket *listener, struct mg_
if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL) if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
&& (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) { && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
if (XX_httplib_set_tcp_nodelay(so.sock, 1) != 0) { if (XX_httplib_set_tcp_nodelay(so.sock, 1) != 0) {
mg_cry( XX_httplib_fc(ctx), "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s", __func__, strerror(ERRNO)); httplib_cry( XX_httplib_fc(ctx), "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s", __func__, strerror(ERRNO));
} }
} }

View File

@@ -59,7 +59,7 @@ void XX_httplib_addenv( struct cgi_environment *env, const char *fmt, ... ) {
added = (char *)XX_httplib_realloc(env->buf, n); added = (char *)XX_httplib_realloc(env->buf, n);
if (!added) { if (!added) {
/* Out of memory */ /* Out of memory */
mg_cry(env->conn, "%s: Cannot allocate memory for CGI variable [%s]", __func__, fmt); httplib_cry(env->conn, "%s: Cannot allocate memory for CGI variable [%s]", __func__, fmt);
return; return;
} }
env->buf = added; env->buf = added;
@@ -90,7 +90,7 @@ void XX_httplib_addenv( struct cgi_environment *env, const char *fmt, ... ) {
/* Now update the variable index */ /* Now update the variable index */
space = (env->varlen - env->varused); space = (env->varlen - env->varused);
if (space < 2) { if (space < 2) {
mg_cry(env->conn, "%s: Cannot register CGI variable [%s]", __func__, fmt); httplib_cry(env->conn, "%s: Cannot register CGI variable [%s]", __func__, fmt);
return; return;
} }

View File

@@ -25,7 +25,7 @@
#include "httplib_main.h" #include "httplib_main.h"
/* Authorize against the opened passwords file. Return 1 if authorized. */ /* Authorize against the opened passwords file. Return 1 if authorized. */
int XX_httplib_authorize( struct mg_connection *conn, struct file *filep ) { int XX_httplib_authorize( struct httplib_connection *conn, struct file *filep ) {
struct read_auth_file_struct workdata; struct read_auth_file_struct workdata;
char buf[MG_BUF_LEN]; char buf[MG_BUF_LEN];

View File

@@ -25,7 +25,7 @@
#include "httplib_main.h" #include "httplib_main.h"
/* /*
* int XX_httplib_check_acl( struct mg_context *ctx, uint32_t remote_ip ); * int XX_httplib_check_acl( struct httplib_context *ctx, uint32_t remote_ip );
* *
* The function XX_httplib_check_acl() is used to check of the socket address * The function XX_httplib_check_acl() is used to check of the socket address
* of a connection is allowed according to the access control list. The * of a connection is allowed according to the access control list. The
@@ -33,7 +33,7 @@
* allowed and 1 if the address is allowed. * allowed and 1 if the address is allowed.
*/ */
int XX_httplib_check_acl( struct mg_context *ctx, uint32_t remote_ip ) { int XX_httplib_check_acl( struct httplib_context *ctx, uint32_t remote_ip ) {
int allowed; int allowed;
int flag; int flag;
@@ -50,7 +50,7 @@ int XX_httplib_check_acl( struct mg_context *ctx, uint32_t remote_ip ) {
while ((list = XX_httplib_next_option(list, &vec, NULL)) != NULL) { while ((list = XX_httplib_next_option(list, &vec, NULL)) != NULL) {
flag = vec.ptr[0]; flag = vec.ptr[0];
if ((flag != '+' && flag != '-') || XX_httplib_parse_net(&vec.ptr[1], &net, &mask) == 0) { if ((flag != '+' && flag != '-') || XX_httplib_parse_net(&vec.ptr[1], &net, &mask) == 0) {
mg_cry( XX_httplib_fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__); httplib_cry( XX_httplib_fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__);
return -1; return -1;
} }

View File

@@ -26,7 +26,7 @@
#include "httplib_string.h" #include "httplib_string.h"
/* Return 1 if request is authorised, 0 otherwise. */ /* Return 1 if request is authorised, 0 otherwise. */
int XX_httplib_check_authorization( struct mg_connection *conn, const char *path ) { int XX_httplib_check_authorization( struct httplib_connection *conn, const char *path ) {
char fname[PATH_MAX]; char fname[PATH_MAX];
struct vec uri_vec; struct vec uri_vec;
@@ -44,7 +44,7 @@ int XX_httplib_check_authorization( struct mg_connection *conn, const char *path
XX_httplib_snprintf(conn, &truncated, fname, sizeof(fname), "%.*s", (int)filename_vec.len, filename_vec.ptr); XX_httplib_snprintf(conn, &truncated, fname, sizeof(fname), "%.*s", (int)filename_vec.len, filename_vec.ptr);
if (truncated || !XX_httplib_fopen(conn, fname, "r", &file)) { if (truncated || !XX_httplib_fopen(conn, fname, "r", &file)) {
mg_cry(conn, "%s: cannot open %s: %s", __func__, fname, strerror(errno)); httplib_cry(conn, "%s: cannot open %s: %s", __func__, fname, strerror(errno));
} }
break; break;
} }

View File

@@ -25,13 +25,13 @@
#include "httplib_main.h" #include "httplib_main.h"
/* /*
* unsigned mg_check_feature( unsigned feature ); * unsigned httplib_check_feature( unsigned feature );
* *
* The function mg_check_feature returns an integer indicating if a specific * The function httplib_check_feature returns an integer indicating if a specific
* functionality has been compiled in at compile time. * functionality has been compiled in at compile time.
*/ */
unsigned mg_check_feature( unsigned feature ) { unsigned httplib_check_feature( unsigned feature ) {
static const unsigned feature_set = 0 static const unsigned feature_set = 0
/* Set bits for available features according to API documentation. /* Set bits for available features according to API documentation.
@@ -71,4 +71,4 @@ unsigned mg_check_feature( unsigned feature ) {
; ;
return (feature & feature_set); return (feature & feature_set);
} /* mg_check_feature */ } /* httplib_check_feature */

View File

@@ -36,9 +36,9 @@ int XX_httplib_check_password( const char *method, const char *ha1, const char *
/* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */ /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
if (strlen(response) != 32) return 0; if (strlen(response) != 32) return 0;
mg_md5(ha2, method, ":", uri, NULL); httplib_md5(ha2, method, ":", uri, NULL);
mg_md5(expected_response, ha1, ":", nonce, ":", nc, ":", cnonce, ":", qop, ":", ha2, NULL); httplib_md5(expected_response, ha1, ":", nonce, ":", nc, ":", cnonce, ":", qop, ":", ha2, NULL);
return mg_strcasecmp(response, expected_response) == 0; return httplib_strcasecmp(response, expected_response) == 0;
} /* XX_httplib_check_password */ } /* XX_httplib_check_password */

View File

@@ -26,13 +26,13 @@
#include "httplib_memory.h" #include "httplib_memory.h"
/* /*
* void XX_httplib_close_all_listening_sockets( struct mg_context *ctx ); * void XX_httplib_close_all_listening_sockets( struct httplib_context *ctx );
* *
* The function XX_httplib_close_all_listening_sockets() closes all listening * The function XX_httplib_close_all_listening_sockets() closes all listening
* sockets of a given context. * sockets of a given context.
*/ */
void XX_httplib_close_all_listening_sockets( struct mg_context *ctx ) { void XX_httplib_close_all_listening_sockets( struct httplib_context *ctx ) {
unsigned int i; unsigned int i;

View File

@@ -28,13 +28,13 @@
#include "httplib_ssl.h" #include "httplib_ssl.h"
/* /*
* void XX_httplib_close_connection( struct mg_connection *conn ); * void XX_httplib_close_connection( struct httplib_connection *conn );
* *
* The function XX_httplib_close_connection() is the internal function which * The function XX_httplib_close_connection() is the internal function which
* does the heavy lifting to close a connection. * does the heavy lifting to close a connection.
*/ */
void XX_httplib_close_connection( struct mg_connection *conn ) { void XX_httplib_close_connection( struct httplib_connection *conn ) {
if ( conn == NULL || conn->ctx == NULL ) return; if ( conn == NULL || conn->ctx == NULL ) return;
@@ -43,7 +43,7 @@ void XX_httplib_close_connection( struct mg_connection *conn ) {
conn->ctx->callbacks.connection_close(conn); conn->ctx->callbacks.connection_close(conn);
} }
mg_lock_connection( conn ); httplib_lock_connection( conn );
conn->must_close = 1; conn->must_close = 1;
@@ -65,23 +65,23 @@ void XX_httplib_close_connection( struct mg_connection *conn ) {
conn->client.sock = INVALID_SOCKET; conn->client.sock = INVALID_SOCKET;
} }
mg_unlock_connection( conn ); httplib_unlock_connection( conn );
} /* XX_httplib_close_connection */ } /* XX_httplib_close_connection */
/* /*
* void mg_close_connection( struct mg_connection *conn ); * void httplib_close_connection( struct httplib_connection *conn );
* *
* The function mg_close_connection() closes the connection passed as a * The function httplib_close_connection() closes the connection passed as a
* parameter to this function. The function does not return a success or * parameter to this function. The function does not return a success or
* failure value. * failure value.
*/ */
void mg_close_connection( struct mg_connection *conn ) { void httplib_close_connection( struct httplib_connection *conn ) {
struct mg_context *client_ctx = NULL; struct httplib_context *client_ctx = NULL;
unsigned int i; unsigned int i;
if ( conn == NULL ) return; if ( conn == NULL ) return;
@@ -109,4 +109,4 @@ void mg_close_connection( struct mg_connection *conn ) {
XX_httplib_free(conn); XX_httplib_free(conn);
} }
} /* mg_close_connection */ } /* httplib_close_connection */

View File

@@ -25,13 +25,13 @@
#include "httplib_main.h" #include "httplib_main.h"
/* /*
* void XX_httplib_close_socket_gracefully( struct mg_connection *conn ); * void XX_httplib_close_socket_gracefully( struct httplib_connection *conn );
* *
* The function XX_httplib_close_socket_gracefully() closes a socket in a * The function XX_httplib_close_socket_gracefully() closes a socket in a
* graceful way. * graceful way.
*/ */
void XX_httplib_close_socket_gracefully( struct mg_connection *conn ) { void XX_httplib_close_socket_gracefully( struct httplib_connection *conn ) {
#if defined(_WIN32) #if defined(_WIN32)
char buf[MG_BUF_LEN]; char buf[MG_BUF_LEN];
@@ -54,7 +54,7 @@ void XX_httplib_close_socket_gracefully( struct mg_connection *conn ) {
/* Socket already closed by client/peer, close socket without linger */ /* Socket already closed by client/peer, close socket without linger */
} else { } else {
if (setsockopt(conn->client.sock, SOL_SOCKET, SO_LINGER, (char *)&linger, sizeof(linger)) != 0) { if (setsockopt(conn->client.sock, SOL_SOCKET, SO_LINGER, (char *)&linger, sizeof(linger)) != 0) {
mg_cry(conn, "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s", __func__, strerror(ERRNO)); httplib_cry(conn, "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s", __func__, strerror(ERRNO));
} }
} }

View File

@@ -25,7 +25,7 @@
#include "httplib_main.h" #include "httplib_main.h"
/* Config option name, config types, default value */ /* Config option name, config types, default value */
struct mg_option XX_httplib_config_options[] = { struct httplib_option XX_httplib_config_options[] = {
{ "cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$" }, { "cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$" },
{ "cgi_environment", CONFIG_TYPE_STRING, NULL }, { "cgi_environment", CONFIG_TYPE_STRING, NULL },
{ "put_delete_auth_file", CONFIG_TYPE_FILE, NULL }, { "put_delete_auth_file", CONFIG_TYPE_FILE, NULL },
@@ -81,4 +81,4 @@ struct mg_option XX_httplib_config_options[] = {
* Check if the XX_httplib_config_options and the corresponding enum have * Check if the XX_httplib_config_options and the corresponding enum have
* compatible sizes * compatible sizes
*/ */
mg_static_assert((sizeof(XX_httplib_config_options) / sizeof(XX_httplib_config_options[0])) == (NUM_OPTIONS + 1), "XX_httplib_config_options and enum not sync"); httplib_static_assert((sizeof(XX_httplib_config_options) / sizeof(XX_httplib_config_options[0])) == (NUM_OPTIONS + 1), "XX_httplib_config_options and enum not sync");

View File

@@ -28,65 +28,64 @@
#include "httplib_ssl.h" #include "httplib_ssl.h"
#include "httplib_string.h" #include "httplib_string.h"
static struct mg_connection * mg_connect_client_impl( const struct mg_client_options *client_options, int use_ssl, char *ebuf, size_t ebuf_len ); static struct httplib_connection * httplib_connect_client_impl( const struct httplib_client_options *client_options, int use_ssl, char *ebuf, size_t ebuf_len );
/* /*
* struct mg_connection *mg_connect_client_secure( const struct mg_client_options *client options, char *error buffer, size_t error_buffer_size ); * struct httplib_connection *httplib_connect_client_secure( const struct httplib_client_options *client options, char *error buffer, size_t error_buffer_size );
* *
* The function mg_connect_client_secure() creates a secure connection as a * The function httplib_connect_client_secure() creates a secure connection as a
* client to a remote server and returns a pointer to the connection * client to a remote server and returns a pointer to the connection
* information, or NULL if an error occured. * information, or NULL if an error occured.
*/ */
CIVETWEB_API struct mg_connection *mg_connect_client_secure( const struct mg_client_options *client_options, char *error_buffer, size_t error_buffer_size ) { CIVETWEB_API struct httplib_connection *httplib_connect_client_secure( const struct httplib_client_options *client_options, char *error_buffer, size_t error_buffer_size ) {
return mg_connect_client_impl( client_options, 1, error_buffer, error_buffer_size ); return httplib_connect_client_impl( client_options, 1, error_buffer, error_buffer_size );
} /* mg_connect_client_secure */ } /* httplib_connect_client_secure */
/* /*
* struct mg_connection *mg_connect_client( const char *host, int port, int use_ssl, char *error_buffer, size_t error_buffer_size ); * struct httplib_connection *httplib_connect_client( const char *host, int port, int use_ssl, char *error_buffer, size_t error_buffer_size );
* *
* The function mg_connect_client() connects to a remote server as a client * The function httplib_connect_client() connects to a remote server as a client
* with the options of the connection provided as parameters. * with the options of the connection provided as parameters.
*/ */
struct mg_connection * mg_connect_client( const char *host, int port, int use_ssl, char *error_buffer, size_t error_buffer_size ) { struct httplib_connection * httplib_connect_client( const char *host, int port, int use_ssl, char *error_buffer, size_t error_buffer_size ) {
struct mg_client_options opts; struct httplib_client_options opts;
memset( &opts, 0, sizeof(opts) ); memset( &opts, 0, sizeof(opts) );
opts.host = host; opts.host = host;
opts.port = port; opts.port = port;
return mg_connect_client_impl( &opts, use_ssl, error_buffer, error_buffer_size ); return httplib_connect_client_impl( &opts, use_ssl, error_buffer, error_buffer_size );
} /* mg_connect_client */ } /* httplib_connect_client */
/* /*
* static struct mg_connection *mg_connect_client_impl( const struct mg_client_options *client_options, int use_ssl, char *ebuf, size_t ebuf_len ); * static struct httplib_connection *httplib_connect_client_impl( const struct httplib_client_options *client_options, int use_ssl, char *ebuf, size_t ebuf_len );
* *
* The function mg_connect_client_impl() is the background function doing the * The function httplib_connect_client_impl() is the background function doing the
* heavy lifting to make connections as a client to remote servers. * heavy lifting to make connections as a client to remote servers.
*/ */
static struct mg_connection *mg_connect_client_impl( const struct mg_client_options *client_options, int use_ssl, char *ebuf, size_t ebuf_len ) { static struct httplib_connection *httplib_connect_client_impl( const struct httplib_client_options *client_options, int use_ssl, char *ebuf, size_t ebuf_len ) {
static struct mg_context fake_ctx; static struct httplib_context fake_ctx;
struct mg_connection *conn = NULL; struct httplib_connection *conn = NULL;
SOCKET sock; SOCKET sock;
union usa sa; union usa sa;
if (!XX_httplib_connect_socket(&fake_ctx, client_options->host, client_options->port, use_ssl, ebuf, ebuf_len, &sock, &sa)) { if (!XX_httplib_connect_socket(&fake_ctx, client_options->host, client_options->port, use_ssl, ebuf, ebuf_len, &sock, &sa)) {
; ;
} else if ((conn = (struct mg_connection *) } else if ((conn = (struct httplib_connection *) XX_httplib_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
XX_httplib_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
XX_httplib_snprintf(NULL, NULL, ebuf, ebuf_len, "calloc(): %s", strerror(ERRNO)); XX_httplib_snprintf(NULL, NULL, ebuf, ebuf_len, "calloc(): %s", strerror(ERRNO));
closesocket(sock); closesocket(sock);
#ifndef NO_SSL #ifndef NO_SSL
@@ -114,7 +113,7 @@ static struct mg_connection *mg_connect_client_impl( const struct mg_client_opti
conn->client.sock = sock; conn->client.sock = sock;
conn->client.lsa = sa; conn->client.lsa = sa;
if (getsockname(sock, psa, &len) != 0) mg_cry(conn, "%s: getsockname() failed: %s", __func__, strerror(ERRNO)); if (getsockname(sock, psa, &len) != 0) httplib_cry(conn, "%s: getsockname() failed: %s", __func__, strerror(ERRNO));
conn->client.is_ssl = use_ssl ? 1 : 0; conn->client.is_ssl = use_ssl ? 1 : 0;
pthread_mutex_init(&conn->mutex, &XX_httplib_pthread_mutex_attr); pthread_mutex_init(&conn->mutex, &XX_httplib_pthread_mutex_attr);
@@ -161,4 +160,4 @@ static struct mg_connection *mg_connect_client_impl( const struct mg_client_opti
return conn; return conn;
} /* mg_connect_client_impl */ } /* httplib_connect_client_impl */

View File

@@ -36,7 +36,7 @@
* may not be null for this function to succeed. * may not be null for this function to succeed.
*/ */
int XX_httplib_connect_socket( struct mg_context *ctx, const char *host, int port, int use_ssl, char *ebuf, size_t ebuf_len, SOCKET *sock, union usa *sa ) { int XX_httplib_connect_socket( struct httplib_context *ctx, const char *host, int port, int use_ssl, char *ebuf, size_t ebuf_len, SOCKET *sock, union usa *sa ) {
int ip_ver = 0; int ip_ver = 0;

View File

@@ -27,28 +27,28 @@
#include "httplib_string.h" #include "httplib_string.h"
/* /*
* struct mg_connection *mg_connect_websocket_client(); * struct httplib_connection *httplib_connect_websocket_client();
* *
* The function mg_connect_websocket_client() connects as a client to a * The function httplib_connect_websocket_client() connects as a client to a
* websocket on another server. If this succeeds a connection pointer is * websocket on another server. If this succeeds a connection pointer is
* returned, otherwise NULL. * returned, otherwise NULL.
*/ */
struct mg_connection *mg_connect_websocket_client(const char *host, struct httplib_connection *httplib_connect_websocket_client(const char *host,
int port, int port,
int use_ssl, int use_ssl,
char *error_buffer, char *error_buffer,
size_t error_buffer_size, size_t error_buffer_size,
const char *path, const char *path,
const char *origin, const char *origin,
mg_websocket_data_handler data_func, httplib_websocket_data_handler data_func,
mg_websocket_close_handler close_func, httplib_websocket_close_handler close_func,
void *user_data) void *user_data)
{ {
struct mg_connection *conn = NULL; struct httplib_connection *conn = NULL;
#if defined(USE_WEBSOCKET) #if defined(USE_WEBSOCKET)
struct mg_context *newctx = NULL; struct httplib_context *newctx = NULL;
struct websocket_client_thread_data *thread_data; struct websocket_client_thread_data *thread_data;
static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw=="; static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
static const char *handshake_req; static const char *handshake_req;
@@ -73,7 +73,7 @@ struct mg_connection *mg_connect_websocket_client(const char *host,
} }
/* Establish the client connection and request upgrade */ /* Establish the client connection and request upgrade */
conn = mg_download(host, port, use_ssl, error_buffer, error_buffer_size, handshake_req, path, host, magic, origin); conn = httplib_download(host, port, use_ssl, error_buffer, error_buffer_size, handshake_req, path, host, magic, origin);
/* Connection object will be null if something goes wrong */ /* Connection object will be null if something goes wrong */
if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) { if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
@@ -89,10 +89,10 @@ struct mg_connection *mg_connect_websocket_client(const char *host,
return conn; return conn;
} }
/* For client connections, mg_context is fake. Since we need to set a /* For client connections, httplib_context is fake. Since we need to set a
* callback function, we need to create a copy and modify it. */ * callback function, we need to create a copy and modify it. */
newctx = (struct mg_context *)XX_httplib_malloc(sizeof(struct mg_context)); newctx = (struct httplib_context *)XX_httplib_malloc(sizeof(struct httplib_context));
memcpy(newctx, conn->ctx, sizeof(struct mg_context)); memcpy(newctx, conn->ctx, sizeof(struct httplib_context));
newctx->user_data = user_data; newctx->user_data = user_data;
newctx->context_type = 2; /* client context type */ newctx->context_type = 2; /* client context type */
newctx->cfg_worker_threads = 1; /* one worker thread will be created */ newctx->cfg_worker_threads = 1; /* one worker thread will be created */
@@ -105,7 +105,7 @@ struct mg_connection *mg_connect_websocket_client(const char *host,
thread_data->callback_data = NULL; thread_data->callback_data = NULL;
/* Start a thread to read the websocket client connection /* Start a thread to read the websocket client connection
* This thread will automatically stop when mg_disconnect is * This thread will automatically stop when httplib_disconnect is
* called on the client connection */ * called on the client connection */
if (XX_httplib_start_thread_with_id( XX_httplib_websocket_client_thread, (void *)thread_data, newctx->workerthreadids) != 0) { if (XX_httplib_start_thread_with_id( XX_httplib_websocket_client_thread, (void *)thread_data, newctx->workerthreadids) != 0) {
@@ -131,4 +131,4 @@ struct mg_connection *mg_connect_websocket_client(const char *host,
return conn; return conn;
} /* mg_connect_websocket_client */ } /* httplib_connect_websocket_client */

View File

@@ -26,7 +26,7 @@
#include "httplib_pthread.h" #include "httplib_pthread.h"
/* /*
* int XX_httplib_consume_socket( struct mg_context *ctx, struct socket *sp, int thread_index ); * int XX_httplib_consume_socket( struct httplib_context *ctx, struct socket *sp, int thread_index );
* *
* The function XX_httplib_consume_socket() takes an accepted socket from the * The function XX_httplib_consume_socket() takes an accepted socket from the
* queue for further processing. * queue for further processing.
@@ -34,7 +34,7 @@
#if defined(ALTERNATIVE_QUEUE) #if defined(ALTERNATIVE_QUEUE)
int XX_httplib_consume_socket( struct mg_context *ctx, struct socket *sp, int thread_index ) { int XX_httplib_consume_socket( struct httplib_context *ctx, struct socket *sp, int thread_index ) {
ctx->client_socks[thread_index].in_use = 0; ctx->client_socks[thread_index].in_use = 0;
event_wait(ctx->client_wait_events[thread_index]); event_wait(ctx->client_wait_events[thread_index]);
@@ -47,7 +47,7 @@ int XX_httplib_consume_socket( struct mg_context *ctx, struct socket *sp, int th
#else /* ALTERNATIVE_QUEUE */ #else /* ALTERNATIVE_QUEUE */
/* Worker threads take accepted socket from the queue */ /* Worker threads take accepted socket from the queue */
int XX_httplib_consume_socket( struct mg_context *ctx, struct socket *sp, int thread_index ) { int XX_httplib_consume_socket( struct httplib_context *ctx, struct socket *sp, int thread_index ) {
#define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue))) #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))

View File

@@ -26,7 +26,7 @@
#include "httplib_ssl.h" #include "httplib_ssl.h"
/* Print error message to the opened error log stream. */ /* Print error message to the opened error log stream. */
void mg_cry(const struct mg_connection *conn, const char *fmt, ...) { void httplib_cry(const struct httplib_connection *conn, const char *fmt, ...) {
char buf[MG_BUF_LEN]; char buf[MG_BUF_LEN];
char src_addr[IP_ADDR_STR_LEN]; char src_addr[IP_ADDR_STR_LEN];
@@ -82,4 +82,4 @@ void mg_cry(const struct mg_connection *conn, const char *fmt, ...) {
} }
} }
} /* mg_cry */ } /* httplib_cry */

View File

@@ -25,7 +25,7 @@
#include "httplib_main.h" #include "httplib_main.h"
/* /*
* void XX_httplib_delete_file( struct mg_connection *conn, const char *path ); * void XX_httplib_delete_file( struct httplib_connection *conn, const char *path );
* *
* The function XX_httplib_delete_file() deletes a file after a request over a * The function XX_httplib_delete_file() deletes a file after a request over a
* connection. * connection.
@@ -33,7 +33,7 @@
#if !defined(NO_FILES) #if !defined(NO_FILES)
void XX_httplib_delete_file( struct mg_connection *conn, const char *path ) { void XX_httplib_delete_file( struct httplib_connection *conn, const char *path ) {
struct de de; struct de de;

View File

@@ -24,7 +24,7 @@
#include "httplib_main.h" #include "httplib_main.h"
void XX_httplib_discard_unread_request_data( struct mg_connection *conn ) { void XX_httplib_discard_unread_request_data( struct httplib_connection *conn ) {
char buf[MG_BUF_LEN]; char buf[MG_BUF_LEN];
size_t to_read; size_t to_read;
@@ -40,10 +40,8 @@ void XX_httplib_discard_unread_request_data( struct mg_connection *conn ) {
/* Chunked encoding: 1=chunk not read completely, 2=chunk read /* Chunked encoding: 1=chunk not read completely, 2=chunk read
* completely */ * completely */
while (conn->is_chunked == 1) { while (conn->is_chunked == 1) {
nread = mg_read(conn, buf, to_read); nread = httplib_read(conn, buf, to_read);
if (nread <= 0) { if (nread <= 0) break;
break;
}
} }
} else { } else {
@@ -54,7 +52,7 @@ void XX_httplib_discard_unread_request_data( struct mg_connection *conn ) {
to_read = (size_t)(conn->content_len - conn->consumed_content); to_read = (size_t)(conn->content_len - conn->consumed_content);
} }
nread = mg_read(conn, buf, to_read); nread = httplib_read(conn, buf, to_read);
if (nread <= 0) break; if (nread <= 0) break;
} }
} }

View File

@@ -26,15 +26,15 @@
#include "httplib_string.h" #include "httplib_string.h"
/* /*
* struct mg_connection *mg_download(); * struct httplib_connection *httplib_download();
* *
* The function mg_download() is used to download a file from a remote location * The function httplib_download() is used to download a file from a remote location
* and returns a pointer to the connection on success, or NULL on error. * and returns a pointer to the connection on success, or NULL on error.
*/ */
struct mg_connection * mg_download( const char *host, int port, int use_ssl, char *ebuf, size_t ebuf_len, const char *fmt, ... ) { struct httplib_connection * httplib_download( const char *host, int port, int use_ssl, char *ebuf, size_t ebuf_len, const char *fmt, ... ) {
struct mg_connection *conn; struct httplib_connection *conn;
va_list ap; va_list ap;
int i; int i;
int reqerr; int reqerr;
@@ -43,7 +43,7 @@ struct mg_connection * mg_download( const char *host, int port, int use_ssl, cha
ebuf[0] = '\0'; ebuf[0] = '\0';
/* open a connection */ /* open a connection */
conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len); conn = httplib_connect_client(host, port, use_ssl, ebuf, ebuf_len);
if (conn != NULL) { if (conn != NULL) {
i = XX_httplib_vprintf(conn, fmt, ap); i = XX_httplib_vprintf(conn, fmt, ap);
@@ -60,11 +60,11 @@ struct mg_connection * mg_download( const char *host, int port, int use_ssl, cha
/* if an error occured, close the connection */ /* if an error occured, close the connection */
if (ebuf[0] != '\0' && conn != NULL) { if (ebuf[0] != '\0' && conn != NULL) {
mg_close_connection(conn); httplib_close_connection(conn);
conn = NULL; conn = NULL;
} }
va_end(ap); va_end(ap);
return conn; return conn;
} /* mg_download */ } /* httplib_download */

View File

@@ -26,9 +26,9 @@
/* Return fake connection structure. Used for logging, if connection /* Return fake connection structure. Used for logging, if connection
* is not applicable at the moment of logging. */ * is not applicable at the moment of logging. */
struct mg_connection *XX_httplib_fc( struct mg_context *ctx ) { struct httplib_connection *XX_httplib_fc( struct httplib_context *ctx ) {
static struct mg_connection fake_connection; static struct httplib_connection fake_connection;
fake_connection.ctx = ctx; fake_connection.ctx = ctx;
return &fake_connection; return &fake_connection;

View File

@@ -24,14 +24,14 @@
#include "httplib_main.h" #include "httplib_main.h"
void XX_httplib_fclose_on_exec( struct file *filep, struct mg_connection *conn ) { void XX_httplib_fclose_on_exec( struct file *filep, struct httplib_connection *conn ) {
if (filep != NULL && filep->fp != NULL) { if (filep != NULL && filep->fp != NULL) {
#ifdef _WIN32 #ifdef _WIN32
(void)conn; /* Unused. */ (void)conn; /* Unused. */
#else #else
if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) { if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
mg_cry(conn, "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s", __func__, strerror(ERRNO)); httplib_cry(conn, "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s", __func__, strerror(ERRNO));
} }
#endif #endif
} }

View File

@@ -29,7 +29,7 @@
* The input parameter mode is the same as for fopen. * The input parameter mode is the same as for fopen.
* Either fp or membuf will be set in the output struct filep. * Either fp or membuf will be set in the output struct filep.
* The function returns 1 on success, 0 on error. */ * The function returns 1 on success, 0 on error. */
int XX_httplib_fopen( const struct mg_connection *conn, const char *path, const char *mode, struct file *filep ) { int XX_httplib_fopen( const struct httplib_connection *conn, const char *path, const char *mode, struct file *filep ) {
struct stat st; struct stat st;

View File

@@ -25,14 +25,14 @@
#include "httplib_main.h" #include "httplib_main.h"
/* /*
* int XX_httplib_forward_body_data( struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl ); * int XX_httplib_forward_body_data( struct httplib_connection *conn, FILE *fp, SOCKET sock, SSL *ssl );
* *
* The function XX_httplib_forward_body_data() forwards body data to the * The function XX_httplib_forward_body_data() forwards body data to the
* client. * client.
*/ */
#if !defined(NO_CGI) || !defined(NO_FILES) #if !defined(NO_CGI) || !defined(NO_FILES)
int XX_httplib_forward_body_data( struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl ) { int XX_httplib_forward_body_data( struct httplib_connection *conn, FILE *fp, SOCKET sock, SSL *ssl ) {
const char *expect; const char *expect;
const char *body; const char *body;
@@ -43,12 +43,12 @@ int XX_httplib_forward_body_data( struct mg_connection *conn, FILE *fp, SOCKET s
int64_t buffered_len; int64_t buffered_len;
double timeout = -1.0; double timeout = -1.0;
if (!conn) { return 0; } if ( conn == NULL ) return 0;
if (conn->ctx->config[REQUEST_TIMEOUT]) { if (conn->ctx->config[REQUEST_TIMEOUT]) {
timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0; timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
} }
expect = mg_get_header(conn, "Expect"); expect = httplib_get_header(conn, "Expect");
/* assert(fp != NULL); */ /* assert(fp != NULL); */
if (!fp) { if (!fp) {
XX_httplib_send_http_error(conn, 500, "%s", "Error: NULL File"); XX_httplib_send_http_error(conn, 500, "%s", "Error: NULL File");
@@ -59,12 +59,12 @@ int XX_httplib_forward_body_data( struct mg_connection *conn, FILE *fp, SOCKET s
/* Content length is not specified by the client. */ /* Content length is not specified by the client. */
XX_httplib_send_http_error(conn, 411, "%s", "Error: Client did not specify content length"); XX_httplib_send_http_error(conn, 411, "%s", "Error: Client did not specify content length");
} else if ((expect != NULL) } else if ((expect != NULL)
&& (mg_strcasecmp(expect, "100-continue") != 0)) { && (httplib_strcasecmp(expect, "100-continue") != 0)) {
/* Client sent an "Expect: xyz" header and xyz is not 100-continue. */ /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
XX_httplib_send_http_error(conn, 417, "Error: Can not fulfill expectation %s", expect); XX_httplib_send_http_error(conn, 417, "Error: Can not fulfill expectation %s", expect);
} else { } else {
if (expect != NULL) { if (expect != NULL) {
(void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n"); (void)httplib_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
conn->status_code = 100; conn->status_code = 100;
} else conn->status_code = 200; } else conn->status_code = 200;

View File

@@ -29,16 +29,16 @@
#include "httplib_utils.h" #include "httplib_utils.h"
/* /*
* void XX_httplib_free_context( struct mg_context *ctx ); * void XX_httplib_free_context( struct httplib_context *ctx );
* *
* The function XX_httplib_free_context() is used to free the resources * The function XX_httplib_free_context() is used to free the resources
* associated with a context. * associated with a context.
*/ */
void XX_httplib_free_context( struct mg_context *ctx ) { void XX_httplib_free_context( struct httplib_context *ctx ) {
int i; int i;
struct mg_handler_info *tmp_rh; struct httplib_handler_info *tmp_rh;
if ( ctx == NULL ) return; if ( ctx == NULL ) return;

View File

@@ -570,14 +570,14 @@ const char *httplib_get_builtin_mime_type( const char *path ) {
while ( eind-start > 1 ) { while ( eind-start > 1 ) {
midden = (start+eind) >> 1; midden = (start+eind) >> 1;
retval = mg_strcasecmp( ext, builtin_mime_types[midden].extension ); retval = httplib_strcasecmp( ext, builtin_mime_types[midden].extension );
if ( retval == 0 ) return builtin_mime_types[midden].mime_type; if ( retval == 0 ) return builtin_mime_types[midden].mime_type;
else if ( retval < 0 ) eind = midden; else if ( retval < 0 ) eind = midden;
else start = midden; else start = midden;
} }
if ( ! mg_strcasecmp( ext, builtin_mime_types[start].extension ) ) return builtin_mime_types[start].mime_type; if ( ! httplib_strcasecmp( ext, builtin_mime_types[start].extension ) ) return builtin_mime_types[start].mime_type;
return "text/plain"; return "text/plain";

View File

@@ -24,8 +24,8 @@
#include "httplib_main.h" #include "httplib_main.h"
struct mg_context * mg_get_context(const struct mg_connection *conn) { struct httplib_context * httplib_get_context(const struct httplib_connection *conn) {
return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx); return (conn == NULL) ? (struct httplib_context *)NULL : (conn->ctx);
} /* mg_get_context */ } /* httplib_get_context */

View File

@@ -26,7 +26,7 @@
#include "httplib_string.h" #include "httplib_string.h"
/* HCP24: some changes to compare hole var_name */ /* HCP24: some changes to compare hole var_name */
int mg_get_cookie(const char *cookie_header, const char *var_name, char *dst, size_t dst_size) { int httplib_get_cookie(const char *cookie_header, const char *var_name, char *dst, size_t dst_size) {
const char *s; const char *s;
const char *p; const char *p;
@@ -64,4 +64,4 @@ int mg_get_cookie(const char *cookie_header, const char *var_name, char *dst, si
} }
return len; return len;
} /* mg_get_cookie */ } /* httplib_get_cookie */

View File

@@ -26,13 +26,13 @@
#include "httplib_ssl.h" #include "httplib_ssl.h"
/* /*
* int XX_httplib_get_first_ssl_listener_index( const struct mg_context *ctx ); * int XX_httplib_get_first_ssl_listener_index( const struct httplib_context *ctx );
* *
* The function XX_httplib_get_first_ssl_listener_index() returns the first * The function XX_httplib_get_first_ssl_listener_index() returns the first
* index of a listening socket where SSL encryption is active. * index of a listening socket where SSL encryption is active.
*/ */
int XX_httplib_get_first_ssl_listener_index( const struct mg_context *ctx ) { int XX_httplib_get_first_ssl_listener_index( const struct httplib_context *ctx ) {
unsigned int i; unsigned int i;
int idx; int idx;

View File

@@ -25,12 +25,12 @@
#include "httplib_main.h" #include "httplib_main.h"
/* Return HTTP header value, or NULL if not found. */ /* Return HTTP header value, or NULL if not found. */
const char *XX_httplib_get_header( const struct mg_request_info *ri, const char *name ) { const char *XX_httplib_get_header( const struct httplib_request_info *ri, const char *name ) {
int i; int i;
if (ri) { if (ri) {
for (i = 0; i < ri->num_headers; i++) { for (i = 0; i < ri->num_headers; i++) {
if (!mg_strcasecmp(name, ri->http_headers[i].name)) return ri->http_headers[i].value; if (!httplib_strcasecmp(name, ri->http_headers[i].name)) return ri->http_headers[i].value;
} }
} }
@@ -39,10 +39,10 @@ const char *XX_httplib_get_header( const struct mg_request_info *ri, const char
} /* XX_httplib_get_header */ } /* XX_httplib_get_header */
const char *mg_get_header( const struct mg_connection *conn, const char *name ) { const char *httplib_get_header( const struct httplib_connection *conn, const char *name ) {
if ( conn == NULL ) return NULL; if ( conn == NULL ) return NULL;
return XX_httplib_get_header( & conn->request_info, name ); return XX_httplib_get_header( & conn->request_info, name );
} /* mg_get_header */ } /* httplib_get_header */

View File

@@ -26,7 +26,7 @@
/* Look at the "path" extension and figure what mime type it has. /* Look at the "path" extension and figure what mime type it has.
* Store mime type in the vector. */ * Store mime type in the vector. */
void XX_httplib_get_mime_type( struct mg_context *ctx, const char *path, struct vec *vec ) { void XX_httplib_get_mime_type( struct httplib_context *ctx, const char *path, struct vec *vec ) {
struct vec ext_vec; struct vec ext_vec;
struct vec mime_vec; struct vec mime_vec;
@@ -44,7 +44,7 @@ void XX_httplib_get_mime_type( struct mg_context *ctx, const char *path, struct
while ((list = XX_httplib_next_option(list, &ext_vec, &mime_vec)) != NULL) { while ((list = XX_httplib_next_option(list, &ext_vec, &mime_vec)) != NULL) {
/* ext now points to the path suffix */ /* ext now points to the path suffix */
ext = path + path_len - ext_vec.len; ext = path + path_len - ext_vec.len;
if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) { if (httplib_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
*vec = mime_vec; *vec = mime_vec;
return; return;
} }

View File

@@ -24,7 +24,7 @@
#include "httplib_main.h" #include "httplib_main.h"
const char *mg_get_option(const struct mg_context *ctx, const char *name) { const char *httplib_get_option(const struct httplib_context *ctx, const char *name) {
int i; int i;
@@ -32,4 +32,4 @@ const char *mg_get_option(const struct mg_context *ctx, const char *name) {
else if ( ctx == NULL || ctx->config[i] == NULL ) return ""; else if ( ctx == NULL || ctx->config[i] == NULL ) return "";
else return ctx->config[i]; else return ctx->config[i];
} /* mg_get_option */ } /* httplib_get_option */

View File

@@ -25,13 +25,13 @@
#include "httplib_main.h" #include "httplib_main.h"
/* /*
* const char *XX_httplib_get_rel_url_at_current_server( const char *uri, const struct mg_connection *conn ); * const char *XX_httplib_get_rel_url_at_current_server( const char *uri, const struct httplib_connection *conn );
* *
* The function XX_httplib_get_rel_url_at_current_server() returns the relative * The function XX_httplib_get_rel_url_at_current_server() returns the relative
* uri at the current server. * uri at the current server.
*/ */
const char * XX_httplib_get_rel_url_at_current_server( const char *uri, const struct mg_connection *conn ) { const char * XX_httplib_get_rel_url_at_current_server( const char *uri, const struct httplib_connection *conn ) {
const char *server_domain; const char *server_domain;
size_t server_domain_len; size_t server_domain_len;
@@ -55,7 +55,7 @@ const char * XX_httplib_get_rel_url_at_current_server( const char *uri, const st
} }
for (i = 0; XX_httplib_abs_uri_protocols[i].proto != NULL; i++) { for (i = 0; XX_httplib_abs_uri_protocols[i].proto != NULL; i++) {
if (mg_strncasecmp(uri, if (httplib_strncasecmp(uri,
XX_httplib_abs_uri_protocols[i].proto, XX_httplib_abs_uri_protocols[i].proto,
XX_httplib_abs_uri_protocols[i].proto_len) == 0) { XX_httplib_abs_uri_protocols[i].proto_len) == 0) {

View File

@@ -25,13 +25,13 @@
#include "httplib_main.h" #include "httplib_main.h"
/* /*
* uint32_t XX_httplib_get_remote_ip( const struct mg_connection *conn ); * uint32_t XX_httplib_get_remote_ip( const struct httplib_connection *conn );
* *
* The function XX_httplib_get_remote_ip() returns the IPv4 address of the * The function XX_httplib_get_remote_ip() returns the IPv4 address of the
* remote peer. * remote peer.
*/ */
uint32_t XX_httplib_get_remote_ip( const struct mg_connection *conn ) { uint32_t XX_httplib_get_remote_ip( const struct httplib_connection *conn ) {
if ( conn == NULL ) return 0; if ( conn == NULL ) return 0;

View File

@@ -31,18 +31,18 @@
* for a connection. * for a connection.
*/ */
int XX_httplib_get_request_handler( struct mg_connection *conn, int handler_type, mg_request_handler *handler, mg_websocket_connect_handler *connect_handler, mg_websocket_ready_handler *ready_handler, mg_websocket_data_handler *data_handler, mg_websocket_close_handler *close_handler, mg_authorization_handler *auth_handler, void **cbdata ) { int XX_httplib_get_request_handler( struct httplib_connection *conn, int handler_type, httplib_request_handler *handler, httplib_websocket_connect_handler *connect_handler, httplib_websocket_ready_handler *ready_handler, httplib_websocket_data_handler *data_handler, httplib_websocket_close_handler *close_handler, httplib_authorization_handler *auth_handler, void **cbdata ) {
const struct mg_request_info *request_info = mg_get_request_info(conn); const struct httplib_request_info *request_info = httplib_get_request_info(conn);
if ( request_info == NULL ) return 0; if ( request_info == NULL ) return 0;
const char *uri = request_info->local_uri; const char *uri = request_info->local_uri;
size_t urilen = strlen(uri); size_t urilen = strlen(uri);
struct mg_handler_info *tmp_rh; struct httplib_handler_info *tmp_rh;
if ( conn == NULL || conn->ctx == NULL ) return 0; if ( conn == NULL || conn->ctx == NULL ) return 0;
mg_lock_context(conn->ctx); httplib_lock_context(conn->ctx);
/* first try for an exact match */ /* first try for an exact match */
for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL; for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
@@ -60,7 +60,7 @@ int XX_httplib_get_request_handler( struct mg_connection *conn, int handler_type
*auth_handler = tmp_rh->auth_handler; *auth_handler = tmp_rh->auth_handler;
} }
*cbdata = tmp_rh->cbdata; *cbdata = tmp_rh->cbdata;
mg_unlock_context(conn->ctx); httplib_unlock_context(conn->ctx);
return 1; return 1;
} }
} }
@@ -83,7 +83,7 @@ int XX_httplib_get_request_handler( struct mg_connection *conn, int handler_type
*auth_handler = tmp_rh->auth_handler; *auth_handler = tmp_rh->auth_handler;
} }
*cbdata = tmp_rh->cbdata; *cbdata = tmp_rh->cbdata;
mg_unlock_context(conn->ctx); httplib_unlock_context(conn->ctx);
return 1; return 1;
} }
} }
@@ -105,13 +105,13 @@ int XX_httplib_get_request_handler( struct mg_connection *conn, int handler_type
*auth_handler = tmp_rh->auth_handler; *auth_handler = tmp_rh->auth_handler;
} }
*cbdata = tmp_rh->cbdata; *cbdata = tmp_rh->cbdata;
mg_unlock_context(conn->ctx); httplib_unlock_context(conn->ctx);
return 1; return 1;
} }
} }
} }
mg_unlock_context(conn->ctx); httplib_unlock_context(conn->ctx);
return 0; /* none found */ return 0; /* none found */

View File

@@ -24,10 +24,10 @@
#include "httplib_main.h" #include "httplib_main.h"
const struct mg_request_info *mg_get_request_info( const struct mg_connection *conn ) { const struct httplib_request_info *httplib_get_request_info( const struct httplib_connection *conn ) {
if ( conn == NULL ) return NULL; if ( conn == NULL ) return NULL;
return & conn->request_info; return & conn->request_info;
} /* mg_get_request_info */ } /* httplib_get_request_info */

View File

@@ -26,19 +26,19 @@
#include "httplib_string.h" #include "httplib_string.h"
/* /*
* int mg_get_response( struct mg_connection *conn, char *ebuf, size_t ebuf_len, int timeout ); * int httplib_get_response( struct httplib_connection *conn, char *ebuf, size_t ebuf_len, int timeout );
* *
* The function mg_get_response tries to get a response from a remote peer. * The function httplib_get_response tries to get a response from a remote peer.
*/ */
int mg_get_response( struct mg_connection *conn, char *ebuf, size_t ebuf_len, int timeout ) { int httplib_get_response( struct httplib_connection *conn, char *ebuf, size_t ebuf_len, int timeout ) {
if ( conn == NULL ) return -1; if ( conn == NULL ) return -1;
/* Implementation of API function for HTTP clients */ /* Implementation of API function for HTTP clients */
int err, ret; int err, ret;
struct mg_context *octx = conn->ctx; struct httplib_context *octx = conn->ctx;
struct mg_context rctx = *(conn->ctx); struct httplib_context rctx = *(conn->ctx);
char txt[32]; /* will not overflow */ char txt[32]; /* will not overflow */
if (timeout >= 0) { if (timeout >= 0) {
@@ -61,4 +61,4 @@ int mg_get_response( struct mg_connection *conn, char *ebuf, size_t ebuf_len, in
* For the first test use <0 for error and >0 for OK */ * For the first test use <0 for error and >0 for OK */
return (ret == 0) ? -1 : +1; return (ret == 0) ? -1 : +1;
} /* mg_get_response */ } /* httplib_get_response */

View File

@@ -25,13 +25,13 @@
#include "httplib_main.h" #include "httplib_main.h"
/* /*
* const char *mg_get_response_code_text( struct mg_connection *conn, int response_code ); * const char *httplib_get_response_code_text( struct httplib_connection *conn, int response_code );
* *
* The function mg_get_response_code_text() returns a text associated with an * The function httplib_get_response_code_text() returns a text associated with an
* HTTP response code. * HTTP response code.
*/ */
const char *mg_get_response_code_text( struct mg_connection *conn, int response_code ) { const char *httplib_get_response_code_text( struct httplib_connection *conn, int response_code ) {
/* See IANA HTTP status code assignment: /* See IANA HTTP status code assignment:
* http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
@@ -111,7 +111,7 @@ const char *mg_get_response_code_text( struct mg_connection *conn, int response_
default: default:
/* This error code is unknown. This should not happen. */ /* This error code is unknown. This should not happen. */
if ( conn != NULL) mg_cry( conn, "Unknown HTTP response code: %u", response_code ); if ( conn != NULL) httplib_cry( conn, "Unknown HTTP response code: %u", response_code );
/* Return at least a category according to RFC 2616 Section 10. */ /* Return at least a category according to RFC 2616 Section 10. */
if (response_code >= 100 && response_code < 200) return "Information"; if (response_code >= 100 && response_code < 200) return "Information";
@@ -123,4 +123,4 @@ const char *mg_get_response_code_text( struct mg_connection *conn, int response_
return ""; return "";
} }
} /* mg_get_response_code_text */ } /* httplib_get_response_code_text */

View File

@@ -24,7 +24,7 @@
#include "httplib_main.h" #include "httplib_main.h"
int mg_get_server_ports(const struct mg_context *ctx, int size, struct mg_server_ports *ports) { int httplib_get_server_ports(const struct httplib_context *ctx, int size, struct httplib_server_ports *ports) {
int i; int i;
int cnt = 0; int cnt = 0;
@@ -59,4 +59,4 @@ int mg_get_server_ports(const struct mg_context *ctx, int size, struct mg_server
return cnt; return cnt;
} /* mg_get_server_ports */ } /* httplib_get_server_ports */

View File

@@ -95,7 +95,7 @@ int XX_httplib_get_uri_type( const char *uri ) {
* addressing the current server. So LibHTTP can also be used * addressing the current server. So LibHTTP can also be used
* as a proxy server. */ * as a proxy server. */
for (i = 0; XX_httplib_abs_uri_protocols[i].proto != NULL; i++) { for (i = 0; XX_httplib_abs_uri_protocols[i].proto != NULL; i++) {
if (mg_strncasecmp(uri, XX_httplib_abs_uri_protocols[i].proto, XX_httplib_abs_uri_protocols[i].proto_len) == 0) { if (httplib_strncasecmp(uri, XX_httplib_abs_uri_protocols[i].proto, XX_httplib_abs_uri_protocols[i].proto_len) == 0) {
hostend = strchr(uri + XX_httplib_abs_uri_protocols[i].proto_len, '/'); hostend = strchr(uri + XX_httplib_abs_uri_protocols[i].proto_len, '/');
if (!hostend) return 0; if (!hostend) return 0;

View File

@@ -24,10 +24,10 @@
#include "httplib_main.h" #include "httplib_main.h"
void * mg_get_user_connection_data(const struct mg_connection *conn) { void * httplib_get_user_connection_data(const struct httplib_connection *conn) {
if (conn != NULL) return conn->request_info.conn_data; if (conn != NULL) return conn->request_info.conn_data;
return NULL; return NULL;
} /* mg_get_user_connection_data */ } /* httplib_get_user_connection_data */

View File

@@ -24,8 +24,8 @@
#include "httplib_main.h" #include "httplib_main.h"
void * mg_get_user_data(const struct mg_context *ctx) { void * httplib_get_user_data(const struct httplib_context *ctx) {
return (ctx == NULL) ? NULL : ctx->user_data; return (ctx == NULL) ? NULL : ctx->user_data;
} /* mg_get_user_data */ } /* httplib_get_user_data */

View File

@@ -24,8 +24,8 @@
#include "httplib_main.h" #include "httplib_main.h"
const struct mg_option *mg_get_valid_options(void) { const struct httplib_option *httplib_get_valid_options(void) {
return XX_httplib_config_options; return XX_httplib_config_options;
} /* mg_get_valid_options */ } /* httplib_get_valid_options */

View File

@@ -24,14 +24,14 @@
#include "httplib_main.h" #include "httplib_main.h"
int mg_get_var( const char *data, size_t data_len, const char *name, char *dst, size_t dst_len ) { int httplib_get_var( const char *data, size_t data_len, const char *name, char *dst, size_t dst_len ) {
return mg_get_var2( data, data_len, name, dst, dst_len, 0 ); return httplib_get_var2( data, data_len, name, dst, dst_len, 0 );
} /* mg_get_var */ } /* httplib_get_var */
int mg_get_var2( const char *data, size_t data_len, const char *name, char *dst, size_t dst_len, size_t occurrence ) { int httplib_get_var2( const char *data, size_t data_len, const char *name, char *dst, size_t dst_len, size_t occurrence ) {
const char *p; const char *p;
const char *e; const char *e;
@@ -53,7 +53,7 @@ int mg_get_var2( const char *data, size_t data_len, const char *name, char *dst,
/* data is "var1=val1&var2=val2...". Find variable first */ /* data is "var1=val1&var2=val2...". Find variable first */
for (p = data; p + name_len < e; p++) { for (p = data; p + name_len < e; p++) {
if ((p == data || p[-1] == '&') && p[name_len] == '=' if ((p == data || p[-1] == '&') && p[name_len] == '='
&& !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) { && !httplib_strncasecmp(name, p, name_len) && 0 == occurrence--) {
/* Point p to variable value */ /* Point p to variable value */
p += name_len + 1; p += name_len + 1;
@@ -64,7 +64,7 @@ int mg_get_var2( const char *data, size_t data_len, const char *name, char *dst,
if (s < p) return -3; if (s < p) return -3;
/* Decode variable into destination buffer */ /* Decode variable into destination buffer */
len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1); len = httplib_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
/* Redirect error code from -1 to -2 (destination buffer too /* Redirect error code from -1 to -2 (destination buffer too
* small). */ * small). */
@@ -76,4 +76,4 @@ int mg_get_var2( const char *data, size_t data_len, const char *name, char *dst,
return len; return len;
} /* mg_get_var2 */ } /* httplib_get_var2 */

View File

@@ -26,12 +26,12 @@
#include "httplib_string.h" #include "httplib_string.h"
/* /*
* int XX_httplib_getreq( struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err ); * int XX_httplib_getreq( struct httplib_connection *conn, char *ebuf, size_t ebuf_len, int *err );
* *
* The function XX_httplib_getreq() processes a request from a remote client. * The function XX_httplib_getreq() processes a request from a remote client.
*/ */
int XX_httplib_getreq( struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err ) { int XX_httplib_getreq( struct httplib_connection *conn, char *ebuf, size_t ebuf_len, int *err ) {
const char *cl; const char *cl;
@@ -93,16 +93,13 @@ int XX_httplib_getreq( struct mg_connection *conn, char *ebuf, size_t ebuf_len,
conn->request_info.content_length = conn->content_len; conn->request_info.content_length = conn->content_len;
} else if ((cl = XX_httplib_get_header(&conn->request_info, "Transfer-Encoding")) } else if ((cl = XX_httplib_get_header(&conn->request_info, "Transfer-Encoding"))
!= NULL != NULL
&& !mg_strcasecmp(cl, "chunked")) { && !httplib_strcasecmp(cl, "chunked")) {
conn->is_chunked = 1; conn->is_chunked = 1;
} else if (!mg_strcasecmp(conn->request_info.request_method, "POST") } else if (!httplib_strcasecmp(conn->request_info.request_method, "POST")
|| !mg_strcasecmp(conn->request_info.request_method, || !httplib_strcasecmp(conn->request_info.request_method, "PUT")) {
"PUT")) {
/* POST or PUT request without content length set */ /* POST or PUT request without content length set */
conn->content_len = -1; conn->content_len = -1;
} else if (!mg_strncasecmp(conn->request_info.request_method, } else if (!httplib_strncasecmp(conn->request_info.request_method, "HTTP/", 5)) {
"HTTP/",
5)) {
/* Response without content length set */ /* Response without content length set */
conn->content_len = -1; conn->content_len = -1;
} else { } else {

View File

@@ -27,7 +27,7 @@
#include "httplib_string.h" #include "httplib_string.h"
/* /*
* void XX_httplib_handle_cgi_request( struct mg_connection *conn, const char *prog ); * void XX_httplib_handle_cgi_request( struct httplib_connection *conn, const char *prog );
* *
* The function XX_httplib_handle_cgi_request() handles a request for a CGI * The function XX_httplib_handle_cgi_request() handles a request for a CGI
* resource. * resource.
@@ -35,7 +35,7 @@
#if !defined(NO_CGI) #if !defined(NO_CGI)
void XX_httplib_handle_cgi_request( struct mg_connection *conn, const char *prog ) { void XX_httplib_handle_cgi_request( struct httplib_connection *conn, const char *prog ) {
char *buf; char *buf;
size_t buflen; size_t buflen;
@@ -52,7 +52,7 @@ void XX_httplib_handle_cgi_request( struct mg_connection *conn, const char *prog
char *pbuf; char *pbuf;
char dir[PATH_MAX]; char dir[PATH_MAX];
char *p; char *p;
struct mg_request_info ri; struct httplib_request_info ri;
struct cgi_environment blk; struct cgi_environment blk;
FILE *in; FILE *in;
FILE *out; FILE *out;
@@ -76,7 +76,7 @@ void XX_httplib_handle_cgi_request( struct mg_connection *conn, const char *prog
XX_httplib_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog); XX_httplib_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
if (truncated) { if (truncated) {
mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog); httplib_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
XX_httplib_send_http_error(conn, 500, "Error: %s", "CGI path too long"); XX_httplib_send_http_error(conn, 500, "Error: %s", "CGI path too long");
goto done; goto done;
} }
@@ -90,7 +90,7 @@ void XX_httplib_handle_cgi_request( struct mg_connection *conn, const char *prog
if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) { if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
status = strerror(ERRNO); status = strerror(ERRNO);
mg_cry(conn, "Error: CGI program \"%s\": Can not create CGI pipes: %s", prog, status); httplib_cry(conn, "Error: CGI program \"%s\": Can not create CGI pipes: %s", prog, status);
XX_httplib_send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status); XX_httplib_send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
goto done; goto done;
} }
@@ -99,7 +99,7 @@ void XX_httplib_handle_cgi_request( struct mg_connection *conn, const char *prog
if (pid == (pid_t)-1) { if (pid == (pid_t)-1) {
status = strerror(ERRNO); status = strerror(ERRNO);
mg_cry(conn, "Error: CGI program \"%s\": Can not spawn CGI process: %s", prog, status); httplib_cry(conn, "Error: CGI program \"%s\": Can not spawn CGI process: %s", prog, status);
XX_httplib_send_http_error(conn, 500, "Error: Cannot spawn CGI process [%s]: %s", prog, status); XX_httplib_send_http_error(conn, 500, "Error: Cannot spawn CGI process [%s]: %s", prog, status);
goto done; goto done;
} }
@@ -126,21 +126,21 @@ void XX_httplib_handle_cgi_request( struct mg_connection *conn, const char *prog
if ((in = fdopen(fdin[1], "wb")) == NULL) { if ((in = fdopen(fdin[1], "wb")) == NULL) {
status = strerror(ERRNO); status = strerror(ERRNO);
mg_cry(conn, "Error: CGI program \"%s\": Can not open stdin: %s", prog, status); httplib_cry(conn, "Error: CGI program \"%s\": Can not open stdin: %s", prog, status);
XX_httplib_send_http_error(conn, 500, "Error: CGI can not open fdin\nfopen: %s", status); XX_httplib_send_http_error(conn, 500, "Error: CGI can not open fdin\nfopen: %s", status);
goto done; goto done;
} }
if ((out = fdopen(fdout[0], "rb")) == NULL) { if ((out = fdopen(fdout[0], "rb")) == NULL) {
status = strerror(ERRNO); status = strerror(ERRNO);
mg_cry(conn, "Error: CGI program \"%s\": Can not open stdout: %s", prog, status); httplib_cry(conn, "Error: CGI program \"%s\": Can not open stdout: %s", prog, status);
XX_httplib_send_http_error(conn, 500, "Error: CGI can not open fdout\nfopen: %s", status); XX_httplib_send_http_error(conn, 500, "Error: CGI can not open fdout\nfopen: %s", status);
goto done; goto done;
} }
if ((err = fdopen(fderr[0], "rb")) == NULL) { if ((err = fdopen(fderr[0], "rb")) == NULL) {
status = strerror(ERRNO); status = strerror(ERRNO);
mg_cry(conn, "Error: CGI program \"%s\": Can not open stderr: %s", prog, status); httplib_cry(conn, "Error: CGI program \"%s\": Can not open stderr: %s", prog, status);
XX_httplib_send_http_error(conn, 500, "Error: CGI can not open fdout\nfopen: %s", status); XX_httplib_send_http_error(conn, 500, "Error: CGI can not open fdout\nfopen: %s", status);
goto done; goto done;
} }
@@ -154,7 +154,7 @@ void XX_httplib_handle_cgi_request( struct mg_connection *conn, const char *prog
/* This is a POST/PUT request, or another request with body data. */ /* This is a POST/PUT request, or another request with body data. */
if (!XX_httplib_forward_body_data(conn, in, INVALID_SOCKET, NULL)) { if (!XX_httplib_forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
/* Error sending the body data */ /* Error sending the body data */
mg_cry(conn, "Error: CGI program \"%s\": Forward body data failed", prog); httplib_cry(conn, "Error: CGI program \"%s\": Forward body data failed", prog);
goto done; goto done;
} }
} }
@@ -172,7 +172,7 @@ void XX_httplib_handle_cgi_request( struct mg_connection *conn, const char *prog
buf = (char *)XX_httplib_malloc(buflen); buf = (char *)XX_httplib_malloc(buflen);
if (buf == NULL) { if (buf == NULL) {
XX_httplib_send_http_error(conn, 500, "Error: Not enough memory for CGI buffer (%u bytes)", (unsigned int)buflen); XX_httplib_send_http_error(conn, 500, "Error: Not enough memory for CGI buffer (%u bytes)", (unsigned int)buflen);
mg_cry(conn, "Error: CGI program \"%s\": Not enough memory for buffer (%u " "bytes)", prog, (unsigned int)buflen); httplib_cry(conn, "Error: CGI program \"%s\": Not enough memory for buffer (%u " "bytes)", prog, (unsigned int)buflen);
goto done; goto done;
} }
headers_len = XX_httplib_read_request(out, conn, buf, (int)buflen, &data_len); headers_len = XX_httplib_read_request(out, conn, buf, (int)buflen, &data_len);
@@ -182,10 +182,10 @@ void XX_httplib_handle_cgi_request( struct mg_connection *conn, const char *prog
* stderr. */ * stderr. */
i = XX_httplib_pull_all(err, conn, buf, (int)buflen); i = XX_httplib_pull_all(err, conn, buf, (int)buflen);
if (i > 0) { if (i > 0) {
mg_cry(conn, "Error: CGI program \"%s\" sent error " "message: [%.*s]", prog, i, buf); httplib_cry(conn, "Error: CGI program \"%s\" sent error " "message: [%.*s]", prog, i, buf);
XX_httplib_send_http_error(conn, 500, "Error: CGI program \"%s\" sent error " "message: [%.*s]", prog, i, buf); XX_httplib_send_http_error(conn, 500, "Error: CGI program \"%s\" sent error " "message: [%.*s]", prog, i, buf);
} else { } else {
mg_cry(conn, "Error: CGI program sent malformed or too big " "(>%u bytes) HTTP headers: [%.*s]", (unsigned)buflen, data_len, buf); httplib_cry(conn, "Error: CGI program sent malformed or too big " "(>%u bytes) HTTP headers: [%.*s]", (unsigned)buflen, data_len, buf);
XX_httplib_send_http_error(conn, XX_httplib_send_http_error(conn,
500, 500,
@@ -220,17 +220,16 @@ void XX_httplib_handle_cgi_request( struct mg_connection *conn, const char *prog
if (!XX_httplib_header_has_option(connection_state, "keep-alive")) { if (!XX_httplib_header_has_option(connection_state, "keep-alive")) {
conn->must_close = 1; conn->must_close = 1;
} }
mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text); httplib_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
/* Send headers */ /* Send headers */
for (i = 0; i < ri.num_headers; i++) { for (i = 0; i < ri.num_headers; i++) {
mg_printf(conn, "%s: %s\r\n", ri.http_headers[i].name, ri.http_headers[i].value); httplib_printf(conn, "%s: %s\r\n", ri.http_headers[i].name, ri.http_headers[i].value);
} }
mg_write(conn, "\r\n", 2); httplib_write(conn, "\r\n", 2);
/* Send chunk of data that may have been read after the headers */ /* Send chunk of data that may have been read after the headers */
conn->num_bytes_sent += conn->num_bytes_sent += httplib_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
/* Read the rest of CGI output and send to the client */ /* Read the rest of CGI output and send to the client */
XX_httplib_send_file_data(conn, &fout, 0, INT64_MAX); XX_httplib_send_file_data(conn, &fout, 0, INT64_MAX);

View File

@@ -26,7 +26,7 @@
#include "httplib_memory.h" #include "httplib_memory.h"
#include "httplib_utils.h" #include "httplib_utils.h"
void XX_httplib_handle_directory_request( struct mg_connection *conn, const char *dir ) { void XX_httplib_handle_directory_request( struct httplib_connection *conn, const char *dir ) {
unsigned int i; unsigned int i;
int sort_direction; int sort_direction;
@@ -46,12 +46,12 @@ void XX_httplib_handle_directory_request( struct mg_connection *conn, const char
sort_direction = ((conn->request_info.query_string != NULL) && (conn->request_info.query_string[1] == 'd')) ? 'a' : 'd'; sort_direction = ((conn->request_info.query_string != NULL) && (conn->request_info.query_string[1] == 'd')) ? 'a' : 'd';
conn->must_close = 1; conn->must_close = 1;
mg_printf(conn, "HTTP/1.1 200 OK\r\n"); httplib_printf(conn, "HTTP/1.1 200 OK\r\n");
XX_httplib_send_static_cache_header(conn); XX_httplib_send_static_cache_header(conn);
mg_printf(conn, "Date: %s\r\n" "Connection: close\r\n" "Content-Type: text/html; charset=utf-8\r\n\r\n", date); httplib_printf(conn, "Date: %s\r\n" "Connection: close\r\n" "Content-Type: text/html; charset=utf-8\r\n\r\n", date);
conn->num_bytes_sent += conn->num_bytes_sent +=
mg_printf(conn, httplib_printf(conn,
"<html><head><title>Index of %s</title>" "<html><head><title>Index of %s</title>"
"<style>th {text-align: left;}</style></head>" "<style>th {text-align: left;}</style></head>"
"<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">" "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
@@ -67,7 +67,7 @@ void XX_httplib_handle_directory_request( struct mg_connection *conn, const char
/* Print first entry - link to a parent directory */ /* Print first entry - link to a parent directory */
conn->num_bytes_sent += conn->num_bytes_sent +=
mg_printf(conn, httplib_printf(conn,
"<tr><td><a href=\"%s%s\">%s</a></td>" "<tr><td><a href=\"%s%s\">%s</a></td>"
"<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n", "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
conn->request_info.local_uri, conn->request_info.local_uri,
@@ -89,7 +89,7 @@ void XX_httplib_handle_directory_request( struct mg_connection *conn, const char
XX_httplib_free(data.entries); XX_httplib_free(data.entries);
} }
conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>"); conn->num_bytes_sent += httplib_printf(conn, "%s", "</table></body></html>");
conn->status_code = 200; conn->status_code = 200;
} /* XX_httplib_handle_directory_request */ } /* XX_httplib_handle_directory_request */

View File

@@ -25,14 +25,14 @@
#include "httplib_main.h" #include "httplib_main.h"
/* /*
* void XX_httplib_handle_file_based_request( struct mg_connection *conn, const char *path, struct file *file ); * void XX_httplib_handle_file_based_request( struct httplib_connection *conn, const char *path, struct file *file );
* *
* The function XX_httplib_handle_file_based_request() handles a request which * The function XX_httplib_handle_file_based_request() handles a request which
* involves a file. This can either be a CGI request, an SSI request of a * involves a file. This can either be a CGI request, an SSI request of a
* request for a static file. * request for a static file.
*/ */
void XX_httplib_handle_file_based_request( struct mg_connection *conn, const char *path, struct file *file ) { void XX_httplib_handle_file_based_request( struct httplib_connection *conn, const char *path, struct file *file ) {
if ( conn == NULL || conn->ctx == NULL ) return; if ( conn == NULL || conn->ctx == NULL ) return;

View File

@@ -24,14 +24,14 @@
#include "httplib_main.h" #include "httplib_main.h"
#include "httplib_memory.h" #include "httplib_memory.h"
static int url_encoded_field_found(const struct mg_connection *conn, static int url_encoded_field_found(const struct httplib_connection *conn,
const char *key, const char *key,
size_t key_len, size_t key_len,
const char *filename, const char *filename,
size_t filename_len, size_t filename_len,
char *path, char *path,
size_t path_len, size_t path_len,
struct mg_form_data_handler *fdh) { struct httplib_form_data_handler *fdh) {
char key_dec[1024]; char key_dec[1024];
char filename_dec[1024]; char filename_dec[1024];
@@ -39,17 +39,17 @@ static int url_encoded_field_found(const struct mg_connection *conn,
int filename_dec_len; int filename_dec_len;
int ret; int ret;
key_dec_len = mg_url_decode(key, (int)key_len, key_dec, (int)sizeof(key_dec), 1); key_dec_len = httplib_url_decode(key, (int)key_len, key_dec, (int)sizeof(key_dec), 1);
if (((size_t)key_dec_len >= (size_t)sizeof(key_dec)) || (key_dec_len < 0)) return FORM_FIELD_STORAGE_SKIP; if (((size_t)key_dec_len >= (size_t)sizeof(key_dec)) || (key_dec_len < 0)) return FORM_FIELD_STORAGE_SKIP;
if (filename) { if (filename) {
filename_dec_len = mg_url_decode(filename, (int)filename_len, filename_dec, (int)sizeof(filename_dec), 1); filename_dec_len = httplib_url_decode(filename, (int)filename_len, filename_dec, (int)sizeof(filename_dec), 1);
if (((size_t)filename_dec_len >= (size_t)sizeof(filename_dec)) if (((size_t)filename_dec_len >= (size_t)sizeof(filename_dec))
|| (filename_dec_len < 0)) { || (filename_dec_len < 0)) {
/* Log error message and skip this field. */ /* Log error message and skip this field. */
mg_cry(conn, "%s: Cannot decode filename", __func__); httplib_cry(conn, "%s: Cannot decode filename", __func__);
return FORM_FIELD_STORAGE_SKIP; return FORM_FIELD_STORAGE_SKIP;
} }
@@ -60,13 +60,13 @@ static int url_encoded_field_found(const struct mg_connection *conn,
if ((ret & 0xF) == FORM_FIELD_STORAGE_GET) { if ((ret & 0xF) == FORM_FIELD_STORAGE_GET) {
if (fdh->field_get == NULL) { if (fdh->field_get == NULL) {
mg_cry(conn, "%s: Function \"Get\" not available", __func__); httplib_cry(conn, "%s: Function \"Get\" not available", __func__);
return FORM_FIELD_STORAGE_SKIP; return FORM_FIELD_STORAGE_SKIP;
} }
} }
if ((ret & 0xF) == FORM_FIELD_STORAGE_STORE) { if ((ret & 0xF) == FORM_FIELD_STORAGE_STORE) {
if (fdh->field_store == NULL) { if (fdh->field_store == NULL) {
mg_cry(conn, "%s: Function \"Store\" not available", __func__); httplib_cry(conn, "%s: Function \"Store\" not available", __func__);
return FORM_FIELD_STORAGE_SKIP; return FORM_FIELD_STORAGE_SKIP;
} }
} }
@@ -75,12 +75,12 @@ static int url_encoded_field_found(const struct mg_connection *conn,
} }
static int url_encoded_field_get(const struct mg_connection *conn, static int url_encoded_field_get(const struct httplib_connection *conn,
const char *key, const char *key,
size_t key_len, size_t key_len,
const char *value, const char *value,
size_t value_len, size_t value_len,
struct mg_form_data_handler *fdh) { struct httplib_form_data_handler *fdh) {
char key_dec[1024]; char key_dec[1024];
@@ -89,13 +89,13 @@ static int url_encoded_field_get(const struct mg_connection *conn,
if (!value_dec) { if (!value_dec) {
/* Log error message and stop parsing the form data. */ /* Log error message and stop parsing the form data. */
mg_cry(conn, "%s: Not enough memory (required: %lu)", __func__, (unsigned long)(value_len + 1)); httplib_cry(conn, "%s: Not enough memory (required: %lu)", __func__, (unsigned long)(value_len + 1));
return FORM_FIELD_STORAGE_ABORT; return FORM_FIELD_STORAGE_ABORT;
} }
mg_url_decode(key, (int)key_len, key_dec, (int)sizeof(key_dec), 1); httplib_url_decode(key, (int)key_len, key_dec, (int)sizeof(key_dec), 1);
value_dec_len = mg_url_decode(value, (int)value_len, value_dec, (int)value_len + 1, 1); value_dec_len = httplib_url_decode(value, (int)value_len, value_dec, (int)value_len + 1, 1);
ret = fdh->field_get(key_dec, value_dec, (size_t)value_dec_len, fdh->user_data); ret = fdh->field_get(key_dec, value_dec, (size_t)value_dec_len, fdh->user_data);
XX_httplib_free(value_dec); XX_httplib_free(value_dec);
@@ -104,28 +104,27 @@ static int url_encoded_field_get(const struct mg_connection *conn,
} }
static int static int unencoded_field_get(const struct httplib_connection *conn,
unencoded_field_get(const struct mg_connection *conn,
const char *key, const char *key,
size_t key_len, size_t key_len,
const char *value, const char *value,
size_t value_len, size_t value_len,
struct mg_form_data_handler *fdh) { struct httplib_form_data_handler *fdh) {
char key_dec[1024]; char key_dec[1024];
(void)conn; (void)conn;
mg_url_decode(key, (int)key_len, key_dec, (int)sizeof(key_dec), 1); httplib_url_decode(key, (int)key_len, key_dec, (int)sizeof(key_dec), 1);
return fdh->field_get(key_dec, value, value_len, fdh->user_data); return fdh->field_get(key_dec, value, value_len, fdh->user_data);
} }
static int field_stored(const struct mg_connection *conn, const char *path, long long file_size, struct mg_form_data_handler *fdh) { static int field_stored(const struct httplib_connection *conn, const char *path, long long file_size, struct httplib_form_data_handler *fdh) {
/* Equivalent to "upload" callback of "mg_upload". */ /* Equivalent to "upload" callback of "httplib_upload". */
(void)conn; /* we do not need mg_cry here, so conn is currently unused */ (void)conn; /* we do not need httplib_cry here, so conn is currently unused */
return fdh->field_store(path, file_size, fdh->user_data); return fdh->field_store(path, file_size, fdh->user_data);
} }
@@ -149,7 +148,7 @@ static const char * search_boundary(const char *buf, size_t buf_len, const char
} }
int mg_handle_form_request(struct mg_connection *conn, struct mg_form_data_handler *fdh) { int httplib_handle_form_request(struct httplib_connection *conn, struct httplib_form_data_handler *fdh) {
const char *content_type; const char *content_type;
char path[512]; char path[512];
@@ -186,7 +185,7 @@ int mg_handle_form_request(struct mg_connection *conn, struct mg_form_data_handl
/* GET request: form data is in the query string. */ /* GET request: form data is in the query string. */
/* The entire data has already been loaded, so there is no nead to /* The entire data has already been loaded, so there is no nead to
* call mg_read. We just need to split the query string into key-value * call httplib_read. We just need to split the query string into key-value
* pairs. */ * pairs. */
data = conn->request_info.query_string; data = conn->request_info.query_string;
if (!data) { if (!data) {
@@ -243,7 +242,7 @@ int mg_handle_form_request(struct mg_connection *conn, struct mg_form_data_handl
size_t n = size_t n =
(size_t)fwrite(val, 1, (size_t)vallen, fstore.fp); (size_t)fwrite(val, 1, (size_t)vallen, fstore.fp);
if ((n != (size_t)vallen) || (ferror(fstore.fp))) { if ((n != (size_t)vallen) || (ferror(fstore.fp))) {
mg_cry(conn, "%s: Cannot write file %s", __func__, path); httplib_cry(conn, "%s: Cannot write file %s", __func__, path);
fclose(fstore.fp); fclose(fstore.fp);
fstore.fp = NULL; fstore.fp = NULL;
XX_httplib_remove_bad_file(conn, path); XX_httplib_remove_bad_file(conn, path);
@@ -256,13 +255,13 @@ int mg_handle_form_request(struct mg_connection *conn, struct mg_form_data_handl
/* stored successfully */ /* stored successfully */
field_stored(conn, path, file_size, fdh); field_stored(conn, path, file_size, fdh);
} else { } else {
mg_cry(conn, "%s: Error saving file %s", __func__, path); httplib_cry(conn, "%s: Error saving file %s", __func__, path);
XX_httplib_remove_bad_file(conn, path); XX_httplib_remove_bad_file(conn, path);
} }
fstore.fp = NULL; fstore.fp = NULL;
} }
} else mg_cry(conn, "%s: Cannot create file %s", __func__, path); } else httplib_cry(conn, "%s: Cannot create file %s", __func__, path);
} }
/* if (field_storage == FORM_FIELD_STORAGE_READ) { */ /* if (field_storage == FORM_FIELD_STORAGE_READ) { */
@@ -290,11 +289,11 @@ int mg_handle_form_request(struct mg_connection *conn, struct mg_form_data_handl
return field_count; return field_count;
} }
content_type = mg_get_header(conn, "Content-Type"); content_type = httplib_get_header(conn, "Content-Type");
if (!content_type if (!content_type
|| !mg_strcasecmp(content_type, "APPLICATION/X-WWW-FORM-URLENCODED") || !httplib_strcasecmp(content_type, "APPLICATION/X-WWW-FORM-URLENCODED")
|| !mg_strcasecmp(content_type, "APPLICATION/WWW-FORM-URLENCODED")) { || !httplib_strcasecmp(content_type, "APPLICATION/WWW-FORM-URLENCODED")) {
/* The form data is in the request body data, encoded in key/value /* The form data is in the request body data, encoded in key/value
* pairs. */ * pairs. */
int all_data_read = 0; int all_data_read = 0;
@@ -315,7 +314,7 @@ int mg_handle_form_request(struct mg_connection *conn, struct mg_form_data_handl
if ((size_t)buf_fill < (sizeof(buf) - 1)) { if ((size_t)buf_fill < (sizeof(buf) - 1)) {
size_t to_read = sizeof(buf) - 1 - (size_t)buf_fill; size_t to_read = sizeof(buf) - 1 - (size_t)buf_fill;
r = mg_read(conn, buf + (size_t)buf_fill, to_read); r = httplib_read(conn, buf + (size_t)buf_fill, to_read);
if (r < 0) { if (r < 0) {
/* read error */ /* read error */
return -1; return -1;
@@ -355,7 +354,7 @@ int mg_handle_form_request(struct mg_connection *conn, struct mg_form_data_handl
if (field_storage == FORM_FIELD_STORAGE_STORE) { if (field_storage == FORM_FIELD_STORAGE_STORE) {
if (XX_httplib_fopen(conn, path, "wb", &fstore) == 0) fstore.fp = NULL; if (XX_httplib_fopen(conn, path, "wb", &fstore) == 0) fstore.fp = NULL;
file_size = 0; file_size = 0;
if (!fstore.fp) mg_cry(conn, "%s: Cannot create file %s", __func__, path); if (!fstore.fp) httplib_cry(conn, "%s: Cannot create file %s", __func__, path);
} }
get_block = 0; get_block = 0;
@@ -393,7 +392,7 @@ int mg_handle_form_request(struct mg_connection *conn, struct mg_form_data_handl
if (fstore.fp) { if (fstore.fp) {
size_t n = (size_t)fwrite(val, 1, (size_t)vallen, fstore.fp); size_t n = (size_t)fwrite(val, 1, (size_t)vallen, fstore.fp);
if ((n != (size_t)vallen) || (ferror(fstore.fp))) { if ((n != (size_t)vallen) || (ferror(fstore.fp))) {
mg_cry(conn, "%s: Cannot write file %s", __func__, path); httplib_cry(conn, "%s: Cannot write file %s", __func__, path);
fclose(fstore.fp); fclose(fstore.fp);
fstore.fp = NULL; fstore.fp = NULL;
XX_httplib_remove_bad_file(conn, path); XX_httplib_remove_bad_file(conn, path);
@@ -408,7 +407,7 @@ int mg_handle_form_request(struct mg_connection *conn, struct mg_form_data_handl
if ((size_t)buf_fill < (sizeof(buf) - 1)) { if ((size_t)buf_fill < (sizeof(buf) - 1)) {
size_t to_read = sizeof(buf) - 1 - (size_t)buf_fill; size_t to_read = sizeof(buf) - 1 - (size_t)buf_fill;
r = mg_read(conn, buf + (size_t)buf_fill, to_read); r = httplib_read(conn, buf + (size_t)buf_fill, to_read);
if (r < 0) { if (r < 0) {
/* read error */ /* read error */
return -1; return -1;
@@ -436,7 +435,7 @@ int mg_handle_form_request(struct mg_connection *conn, struct mg_form_data_handl
/* stored successfully */ /* stored successfully */
field_stored(conn, path, file_size, fdh); field_stored(conn, path, file_size, fdh);
} else { } else {
mg_cry(conn, "%s: Error saving file %s", __func__, path); httplib_cry(conn, "%s: Error saving file %s", __func__, path);
XX_httplib_remove_bad_file(conn, path); XX_httplib_remove_bad_file(conn, path);
} }
fstore.fp = NULL; fstore.fp = NULL;
@@ -451,14 +450,14 @@ int mg_handle_form_request(struct mg_connection *conn, struct mg_form_data_handl
return field_count; return field_count;
} }
if (!mg_strncasecmp(content_type, "MULTIPART/FORM-DATA;", 20)) { if (!httplib_strncasecmp(content_type, "MULTIPART/FORM-DATA;", 20)) {
/* The form data is in the request body data, encoded as multipart /* The form data is in the request body data, encoded as multipart
* content (see https://www.ietf.org/rfc/rfc1867.txt, * content (see https://www.ietf.org/rfc/rfc1867.txt,
* https://www.ietf.org/rfc/rfc2388.txt). */ * https://www.ietf.org/rfc/rfc2388.txt). */
const char *boundary; const char *boundary;
size_t bl; size_t bl;
ptrdiff_t used; ptrdiff_t used;
struct mg_request_info part_header; struct httplib_request_info part_header;
char *hbuf; char *hbuf;
char *hend; char *hend;
char *fbeg; char *fbeg;
@@ -475,7 +474,7 @@ int mg_handle_form_request(struct mg_connection *conn, struct mg_form_data_handl
while (content_type[bl] == ' ') bl++; while (content_type[bl] == ' ') bl++;
/* There has to be a BOUNDARY definition in the Content-Type header */ /* There has to be a BOUNDARY definition in the Content-Type header */
if (mg_strncasecmp(content_type + bl, "BOUNDARY=", 9)) { if (httplib_strncasecmp(content_type + bl, "BOUNDARY=", 9)) {
/* Malformed request */ /* Malformed request */
return -1; return -1;
} }
@@ -499,7 +498,7 @@ int mg_handle_form_request(struct mg_connection *conn, struct mg_form_data_handl
size_t towrite, n; size_t towrite, n;
int get_block; int get_block;
r = mg_read(conn, buf + (size_t)buf_fill, sizeof(buf) - 1 - (size_t)buf_fill); r = httplib_read(conn, buf + (size_t)buf_fill, sizeof(buf) - 1 - (size_t)buf_fill);
if (r < 0) { if (r < 0) {
/* read error */ /* read error */
return -1; return -1;
@@ -600,7 +599,7 @@ int mg_handle_form_request(struct mg_connection *conn, struct mg_form_data_handl
if (XX_httplib_fopen(conn, path, "wb", &fstore) == 0) fstore.fp = NULL; if (XX_httplib_fopen(conn, path, "wb", &fstore) == 0) fstore.fp = NULL;
file_size = 0; file_size = 0;
if (!fstore.fp) mg_cry(conn, "%s: Cannot create file %s", __func__, path); if (!fstore.fp) httplib_cry(conn, "%s: Cannot create file %s", __func__, path);
} }
get_block = 0; get_block = 0;
@@ -631,7 +630,7 @@ int mg_handle_form_request(struct mg_connection *conn, struct mg_form_data_handl
/* Store the content of the buffer. */ /* Store the content of the buffer. */
n = (size_t)fwrite(hend, 1, towrite, fstore.fp); n = (size_t)fwrite(hend, 1, towrite, fstore.fp);
if ((n != towrite) || (ferror(fstore.fp))) { if ((n != towrite) || (ferror(fstore.fp))) {
mg_cry(conn, "%s: Cannot write file %s", __func__, path); httplib_cry(conn, "%s: Cannot write file %s", __func__, path);
fclose(fstore.fp); fclose(fstore.fp);
fstore.fp = NULL; fstore.fp = NULL;
XX_httplib_remove_bad_file(conn, path); XX_httplib_remove_bad_file(conn, path);
@@ -645,7 +644,7 @@ int mg_handle_form_request(struct mg_connection *conn, struct mg_form_data_handl
hend = buf; hend = buf;
/* Read new data */ /* Read new data */
r = mg_read(conn, buf + (size_t)buf_fill, sizeof(buf) - 1 - (size_t)buf_fill); r = httplib_read(conn, buf + (size_t)buf_fill, sizeof(buf) - 1 - (size_t)buf_fill);
if (r < 0) { if (r < 0) {
/* read error */ /* read error */
return -1; return -1;
@@ -679,7 +678,7 @@ int mg_handle_form_request(struct mg_connection *conn, struct mg_form_data_handl
if (fstore.fp) { if (fstore.fp) {
n = (size_t)fwrite(hend, 1, towrite, fstore.fp); n = (size_t)fwrite(hend, 1, towrite, fstore.fp);
if ((n != towrite) || (ferror(fstore.fp))) { if ((n != towrite) || (ferror(fstore.fp))) {
mg_cry(conn, "%s: Cannot write file %s", __func__, path); httplib_cry(conn, "%s: Cannot write file %s", __func__, path);
fclose(fstore.fp); fclose(fstore.fp);
fstore.fp = NULL; fstore.fp = NULL;
XX_httplib_remove_bad_file(conn, path); XX_httplib_remove_bad_file(conn, path);
@@ -696,7 +695,7 @@ int mg_handle_form_request(struct mg_connection *conn, struct mg_form_data_handl
/* stored successfully */ /* stored successfully */
field_stored(conn, path, file_size, fdh); field_stored(conn, path, file_size, fdh);
} else { } else {
mg_cry(conn, "%s: Error saving file %s", __func__, path); httplib_cry(conn, "%s: Error saving file %s", __func__, path);
XX_httplib_remove_bad_file(conn, path); XX_httplib_remove_bad_file(conn, path);
} }
fstore.fp = NULL; fstore.fp = NULL;

View File

@@ -26,7 +26,7 @@
#include "httplib_utils.h" #include "httplib_utils.h"
/* /*
* void XX_httplib_handle_not_modified_static_file_request( struct mg_connection *conn, struct file *filep ); * void XX_httplib_handle_not_modified_static_file_request( struct httplib_connection *conn, struct file *filep );
* *
* The function XX_httplib_handle_not_modified_static_file_request() is used to * The function XX_httplib_handle_not_modified_static_file_request() is used to
* send a 304 response to a client to indicate that the requested resource has * send a 304 response to a client to indicate that the requested resource has
@@ -34,7 +34,7 @@
*/ */
#if !defined(NO_CACHING) #if !defined(NO_CACHING)
void XX_httplib_handle_not_modified_static_file_request( struct mg_connection *conn, struct file *filep ) { void XX_httplib_handle_not_modified_static_file_request( struct httplib_connection *conn, struct file *filep ) {
char date[64]; char date[64];
char lm[64]; char lm[64];
@@ -50,9 +50,9 @@ void XX_httplib_handle_not_modified_static_file_request( struct mg_connection *c
XX_httplib_gmt_time_string(lm, sizeof(lm), &filep->last_modified); XX_httplib_gmt_time_string(lm, sizeof(lm), &filep->last_modified);
XX_httplib_construct_etag(etag, sizeof(etag), filep); XX_httplib_construct_etag(etag, sizeof(etag), filep);
mg_printf(conn, "HTTP/1.1 %d %s\r\n" "Date: %s\r\n", conn->status_code, mg_get_response_code_text(conn, conn->status_code), date); httplib_printf(conn, "HTTP/1.1 %d %s\r\n" "Date: %s\r\n", conn->status_code, httplib_get_response_code_text(conn, conn->status_code), date);
XX_httplib_send_static_cache_header(conn); XX_httplib_send_static_cache_header(conn);
mg_printf(conn, "Last-Modified: %s\r\n" "Etag: %s\r\n" "Connection: %s\r\n" "\r\n", lm, etag, XX_httplib_suggest_connection_header(conn)); httplib_printf(conn, "Last-Modified: %s\r\n" "Etag: %s\r\n" "Connection: %s\r\n" "\r\n", lm, etag, XX_httplib_suggest_connection_header(conn));
} /* XX_httplib_handle_not_modified_static_file_request */ } /* XX_httplib_handle_not_modified_static_file_request */

View File

@@ -29,13 +29,13 @@
#if !defined(NO_FILES) #if !defined(NO_FILES)
/* /*
* static void print_props( struct mg_connection *conn, const char *uri, struct file *filep ); * static void print_props( struct httplib_connection *conn, const char *uri, struct file *filep );
* *
* The function print_props() writes the PROPFIND properties for a collection * The function print_props() writes the PROPFIND properties for a collection
* event. * event.
*/ */
static void print_props( struct mg_connection *conn, const char *uri, struct file *filep ) { static void print_props( struct httplib_connection *conn, const char *uri, struct file *filep ) {
char mtime[64]; char mtime[64];
@@ -43,7 +43,7 @@ static void print_props( struct mg_connection *conn, const char *uri, struct fil
XX_httplib_gmt_time_string(mtime, sizeof(mtime), &filep->last_modified); XX_httplib_gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
conn->num_bytes_sent += conn->num_bytes_sent +=
mg_printf(conn, httplib_printf(conn,
"<d:response>" "<d:response>"
"<d:href>%s</d:href>" "<d:href>%s</d:href>"
"<d:propstat>" "<d:propstat>"
@@ -77,13 +77,13 @@ static void print_dav_dir_entry( struct de *de, void *data ) {
char href_encoded[PATH_MAX * 3 /* worst case */]; char href_encoded[PATH_MAX * 3 /* worst case */];
int truncated; int truncated;
struct mg_connection *conn = (struct mg_connection *)data; struct httplib_connection *conn = (struct httplib_connection *)data;
if (!de || !conn) return; if (!de || !conn) return;
XX_httplib_snprintf(conn, &truncated, href, sizeof(href), "%s%s", conn->request_info.local_uri, de->file_name); XX_httplib_snprintf(conn, &truncated, href, sizeof(href), "%s%s", conn->request_info.local_uri, de->file_name);
if (!truncated) { if (!truncated) {
mg_url_encode(href, href_encoded, PATH_MAX * 3); httplib_url_encode(href, href_encoded, PATH_MAX * 3);
print_props(conn, href_encoded, &de->file); print_props(conn, href_encoded, &de->file);
} }
@@ -92,14 +92,14 @@ static void print_dav_dir_entry( struct de *de, void *data ) {
/* /*
* void XX_httplib_handle_propfind( struct mg_connection *conn, const char *path, struct file *filep ); * void XX_httplib_handle_propfind( struct httplib_connection *conn, const char *path, struct file *filep );
* *
* The function XX_httlib_handle_propfind() handles a propfind request. * The function XX_httlib_handle_propfind() handles a propfind request.
*/ */
void XX_httplib_handle_propfind( struct mg_connection *conn, const char *path, struct file *filep ) { void XX_httplib_handle_propfind( struct httplib_connection *conn, const char *path, struct file *filep ) {
const char *depth = mg_get_header(conn, "Depth"); const char *depth = httplib_get_header(conn, "Depth");
char date[64]; char date[64];
time_t curtime = time(NULL); time_t curtime = time(NULL);
@@ -109,23 +109,23 @@ void XX_httplib_handle_propfind( struct mg_connection *conn, const char *path, s
conn->must_close = 1; conn->must_close = 1;
conn->status_code = 207; conn->status_code = 207;
mg_printf(conn, "HTTP/1.1 207 Multi-Status\r\n" "Date: %s\r\n", date); httplib_printf(conn, "HTTP/1.1 207 Multi-Status\r\n" "Date: %s\r\n", date);
XX_httplib_send_static_cache_header(conn); XX_httplib_send_static_cache_header(conn);
mg_printf(conn, "Connection: %s\r\n" "Content-Type: text/xml; charset=utf-8\r\n\r\n", XX_httplib_suggest_connection_header(conn)); httplib_printf(conn, "Connection: %s\r\n" "Content-Type: text/xml; charset=utf-8\r\n\r\n", XX_httplib_suggest_connection_header(conn));
conn->num_bytes_sent += mg_printf(conn, "<?xml version=\"1.0\" encoding=\"utf-8\"?>" "<d:multistatus xmlns:d='DAV:'>\n"); conn->num_bytes_sent += httplib_printf(conn, "<?xml version=\"1.0\" encoding=\"utf-8\"?>" "<d:multistatus xmlns:d='DAV:'>\n");
/* Print properties for the requested resource itself */ /* Print properties for the requested resource itself */
print_props(conn, conn->request_info.local_uri, filep); print_props(conn, conn->request_info.local_uri, filep);
/* If it is a directory, print directory entries too if Depth is not 0 */ /* If it is a directory, print directory entries too if Depth is not 0 */
if (filep && filep->is_directory if (filep && filep->is_directory
&& !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") && !httplib_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
&& (depth == NULL || strcmp(depth, "0") != 0)) { && (depth == NULL || strcmp(depth, "0") != 0)) {
XX_httplib_scan_directory(conn, path, conn, &print_dav_dir_entry); XX_httplib_scan_directory(conn, path, conn, &print_dav_dir_entry);
} }
conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>"); conn->num_bytes_sent += httplib_printf(conn, "%s\n", "</d:multistatus>");
} /* XX_httplib_handle_propfind */ } /* XX_httplib_handle_propfind */

View File

@@ -27,7 +27,7 @@
#include "httplib_utils.h" #include "httplib_utils.h"
/* /*
* void XX_httplib_handle_request( struct mg_connection *conn ); * void XX_httplib_handle_request( struct httplib_connection *conn );
* *
* The function XX_httplib_handle_request() handles an incoming request. This * The function XX_httplib_handle_request() handles an incoming request. This
* is the heart of the LibHTTP's logic. This function is called when the * is the heart of the LibHTTP's logic. This function is called when the
@@ -35,11 +35,11 @@
* to take: serve a file, or a directory, or call embedded function, etcetera. * to take: serve a file, or a directory, or call embedded function, etcetera.
*/ */
void XX_httplib_handle_request( struct mg_connection *conn ) { void XX_httplib_handle_request( struct httplib_connection *conn ) {
if ( conn == NULL ) return; if ( conn == NULL ) return;
struct mg_request_info *ri = &conn->request_info; struct httplib_request_info *ri = &conn->request_info;
char path[PATH_MAX]; char path[PATH_MAX];
int uri_len; int uri_len;
int ssl_index; int ssl_index;
@@ -50,13 +50,13 @@ void XX_httplib_handle_request( struct mg_connection *conn ) {
int is_callback_resource = 0; int is_callback_resource = 0;
int i; int i;
struct file file = STRUCT_FILE_INITIALIZER; struct file file = STRUCT_FILE_INITIALIZER;
mg_request_handler callback_handler = NULL; httplib_request_handler callback_handler = NULL;
mg_websocket_connect_handler ws_connect_handler = NULL; httplib_websocket_connect_handler ws_connect_handler = NULL;
mg_websocket_ready_handler ws_ready_handler = NULL; httplib_websocket_ready_handler ws_ready_handler = NULL;
mg_websocket_data_handler ws_data_handler = NULL; httplib_websocket_data_handler ws_data_handler = NULL;
mg_websocket_close_handler ws_close_handler = NULL; httplib_websocket_close_handler ws_close_handler = NULL;
void *callback_data = NULL; void *callback_data = NULL;
mg_authorization_handler auth_handler = NULL; httplib_authorization_handler auth_handler = NULL;
void *auth_callback_data = NULL; void *auth_callback_data = NULL;
#if !defined(NO_FILES) #if !defined(NO_FILES)
time_t curtime = time(NULL); time_t curtime = time(NULL);
@@ -83,14 +83,14 @@ void XX_httplib_handle_request( struct mg_connection *conn ) {
/* A http to https forward port has been specified, /* A http to https forward port has been specified,
* but no https port to forward to. */ * but no https port to forward to. */
XX_httplib_send_http_error(conn, 503, "%s", "Error: SSL forward not configured properly"); XX_httplib_send_http_error(conn, 503, "%s", "Error: SSL forward not configured properly");
mg_cry(conn, "Can not redirect to SSL, no SSL port available"); httplib_cry(conn, "Can not redirect to SSL, no SSL port available");
} }
return; return;
} }
uri_len = (int)strlen(ri->local_uri); uri_len = (int)strlen(ri->local_uri);
/* 1.3. decode url (if config says so) */ /* 1.3. decode url (if config says so) */
if (XX_httplib_should_decode_url(conn)) mg_url_decode( ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0); if (XX_httplib_should_decode_url(conn)) httplib_url_decode( ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
/* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
* not possible */ * not possible */
@@ -324,7 +324,7 @@ void XX_httplib_handle_request( struct mg_connection *conn ) {
if (file.is_directory && (uri_len > 0) if (file.is_directory && (uri_len > 0)
&& (ri->local_uri[uri_len - 1] != '/')) { && (ri->local_uri[uri_len - 1] != '/')) {
XX_httplib_gmt_time_string(date, sizeof(date), &curtime); XX_httplib_gmt_time_string(date, sizeof(date), &curtime);
mg_printf(conn, httplib_printf(conn,
"HTTP/1.1 301 Moved Permanently\r\n" "HTTP/1.1 301 Moved Permanently\r\n"
"Location: %s/\r\n" "Location: %s/\r\n"
"Date: %s\r\n" "Date: %s\r\n"
@@ -368,7 +368,7 @@ void XX_httplib_handle_request( struct mg_connection *conn ) {
* define what should be possible in this case. */ * define what should be possible in this case. */
} else { } else {
/* 14.2. no substitute file */ /* 14.2. no substitute file */
if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")) XX_httplib_handle_directory_request(conn, path); if (!httplib_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")) XX_httplib_handle_directory_request(conn, path);
else XX_httplib_send_http_error(conn, 403, "%s", "Error: Directory listing denied"); else XX_httplib_send_http_error(conn, 403, "%s", "Error: Directory listing denied");
return; return;
} }

View File

@@ -33,7 +33,7 @@
* request for a static file. * request for a static file.
*/ */
void XX_httplib_handle_static_file_request( struct mg_connection *conn, const char *path, struct file *filep, const char *mime_type, const char *additional_headers ) { void XX_httplib_handle_static_file_request( struct httplib_connection *conn, const char *path, struct file *filep, const char *mime_type, const char *additional_headers ) {
char date[64]; char date[64];
char lm[64]; char lm[64];
@@ -92,7 +92,7 @@ void XX_httplib_handle_static_file_request( struct mg_connection *conn, const ch
/* If Range: header specified, act accordingly */ /* If Range: header specified, act accordingly */
r1 = r2 = 0; r1 = r2 = 0;
hdr = mg_get_header(conn, "Range"); hdr = httplib_get_header(conn, "Range");
if (hdr != NULL && (n = XX_httplib_parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0 if (hdr != NULL && (n = XX_httplib_parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
&& r2 >= 0) { && r2 >= 0) {
/* actually, range requests don't play well with a pre-gzipped /* actually, range requests don't play well with a pre-gzipped
@@ -115,7 +115,7 @@ void XX_httplib_handle_static_file_request( struct mg_connection *conn, const ch
msg = "Partial Content"; msg = "Partial Content";
} }
hdr = mg_get_header(conn, "Origin"); hdr = httplib_get_header(conn, "Origin");
if (hdr) { if (hdr) {
/* Cross-origin resource sharing (CORS), see /* Cross-origin resource sharing (CORS), see
* http://www.html5rocks.com/en/tutorials/cors/, * http://www.html5rocks.com/en/tutorials/cors/,
@@ -134,9 +134,9 @@ void XX_httplib_handle_static_file_request( struct mg_connection *conn, const ch
XX_httplib_gmt_time_string(lm, sizeof(lm), &filep->last_modified); XX_httplib_gmt_time_string(lm, sizeof(lm), &filep->last_modified);
XX_httplib_construct_etag(etag, sizeof(etag), filep); XX_httplib_construct_etag(etag, sizeof(etag), filep);
mg_printf(conn, "HTTP/1.1 %d %s\r\n" "%s%s%s" "Date: %s\r\n", conn->status_code, msg, cors1, cors2, cors3, date); httplib_printf(conn, "HTTP/1.1 %d %s\r\n" "%s%s%s" "Date: %s\r\n", conn->status_code, msg, cors1, cors2, cors3, date);
XX_httplib_send_static_cache_header(conn); XX_httplib_send_static_cache_header(conn);
mg_printf(conn, httplib_printf(conn,
"Last-Modified: %s\r\n" "Last-Modified: %s\r\n"
"Etag: %s\r\n" "Etag: %s\r\n"
"Content-Type: %.*s\r\n" "Content-Type: %.*s\r\n"
@@ -157,8 +157,8 @@ void XX_httplib_handle_static_file_request( struct mg_connection *conn, const ch
* sure no one of the additional_headers is included twice */ * sure no one of the additional_headers is included twice */
if (additional_headers != NULL) { if (additional_headers != NULL) {
mg_printf(conn, "%.*s\r\n\r\n", (int)strlen(additional_headers), additional_headers); httplib_printf(conn, "%.*s\r\n\r\n", (int)strlen(additional_headers), additional_headers);
} else mg_printf(conn, "\r\n"); } else httplib_printf(conn, "\r\n");
if (strcmp(conn->request_info.request_method, "HEAD") != 0) XX_httplib_send_file_data(conn, filep, r1, cl); if (strcmp(conn->request_info.request_method, "HEAD") != 0) XX_httplib_send_file_data(conn, filep, r1, cl);
XX_httplib_fclose(filep); XX_httplib_fclose(filep);

View File

@@ -33,10 +33,10 @@
#if defined(USE_WEBSOCKET) #if defined(USE_WEBSOCKET)
void XX_httplib_handle_websocket_request( struct mg_connection *conn, const char *path, int is_callback_resource, mg_websocket_connect_handler ws_connect_handler, mg_websocket_ready_handler ws_ready_handler, mg_websocket_data_handler ws_data_handler, mg_websocket_close_handler ws_close_handler, void *cbData ) { void XX_httplib_handle_websocket_request( struct httplib_connection *conn, const char *path, int is_callback_resource, httplib_websocket_connect_handler ws_connect_handler, httplib_websocket_ready_handler ws_ready_handler, httplib_websocket_data_handler ws_data_handler, httplib_websocket_close_handler ws_close_handler, void *cbData ) {
const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key"); const char *websock_key = httplib_get_header(conn, "Sec-WebSocket-Key");
const char *version = mg_get_header(conn, "Sec-WebSocket-Version"); const char *version = httplib_get_header(conn, "Sec-WebSocket-Version");
int lua_websock = 0; int lua_websock = 0;
(void)path; (void)path;
@@ -50,14 +50,14 @@ void XX_httplib_handle_websocket_request( struct mg_connection *conn, const char
/* It could be the hixie draft version /* It could be the hixie draft version
* (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76). * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
*/ */
const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1"); const char *key1 = httplib_get_header(conn, "Sec-WebSocket-Key1");
const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2"); const char *key2 = httplib_get_header(conn, "Sec-WebSocket-Key2");
char key3[8]; char key3[8];
if ((key1 != NULL) && (key2 != NULL)) { if ((key1 != NULL) && (key2 != NULL)) {
/* This version uses 8 byte body data in a GET request */ /* This version uses 8 byte body data in a GET request */
conn->content_len = 8; conn->content_len = 8;
if (8 == mg_read(conn, key3, 8)) { if (8 == httplib_read(conn, key3, 8)) {
/* This is the hixie version */ /* This is the hixie version */
XX_httplib_send_http_error(conn, 426, "%s", "Protocol upgrade to RFC 6455 required"); XX_httplib_send_http_error(conn, 426, "%s", "Protocol upgrade to RFC 6455 required");
return; return;

View File

@@ -36,7 +36,7 @@ int XX_httplib_header_has_option( const char *header, const char *option ) {
assert(option[0] != '\0'); assert(option[0] != '\0');
while ((header = XX_httplib_next_option(header, &opt_vec, &eq_vec)) != NULL) { while ((header = XX_httplib_next_option(header, &opt_vec, &eq_vec)) != NULL) {
if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0) return 1; if (httplib_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0) return 1;
} }
return 0; return 0;

View File

@@ -43,13 +43,13 @@ static void *cryptolib_dll_handle; /* Store the crypto library handle. */
/* /*
* int XX_httplib_initialize_ssl( struct mg_context *ctx ); * int XX_httplib_initialize_ssl( struct httplib_context *ctx );
* *
* The function XX_httplib_initialize_ssl() initializes the use of SSL * The function XX_httplib_initialize_ssl() initializes the use of SSL
* encrypted communication on the given context. * encrypted communication on the given context.
*/ */
int XX_httplib_initialize_ssl( struct mg_context *ctx ) { int XX_httplib_initialize_ssl( struct httplib_context *ctx ) {
int i; int i;
size_t size; size_t size;
@@ -70,7 +70,7 @@ int XX_httplib_initialize_ssl( struct mg_context *ctx ) {
if (i < 0) i = 0; if (i < 0) i = 0;
size = sizeof(pthread_mutex_t) * ((size_t)(i)); size = sizeof(pthread_mutex_t) * ((size_t)(i));
if ((XX_httplib_ssl_mutexes = (pthread_mutex_t *)XX_httplib_malloc(size)) == NULL) { if ((XX_httplib_ssl_mutexes = (pthread_mutex_t *)XX_httplib_malloc(size)) == NULL) {
mg_cry( XX_httplib_fc(ctx), "%s: cannot allocate mutexes: %s", __func__, XX_httplib_ssl_error()); httplib_cry( XX_httplib_fc(ctx), "%s: cannot allocate mutexes: %s", __func__, XX_httplib_ssl_error());
return 0; return 0;
} }

View File

@@ -41,7 +41,7 @@
* is_put_or_delete_request: out: put/delete file? * is_put_or_delete_request: out: put/delete file?
*/ */
void XX_httplib_interpret_uri( struct mg_connection *conn, char *filename, size_t filename_buf_len, struct file *filep, int *is_found, int *is_script_resource, int *is_websocket_request, int *is_put_or_delete_request ) { void XX_httplib_interpret_uri( struct httplib_connection *conn, char *filename, size_t filename_buf_len, struct file *filep, int *is_found, int *is_script_resource, int *is_websocket_request, int *is_put_or_delete_request ) {
/* TODO (high): Restructure this function */ /* TODO (high): Restructure this function */
@@ -141,7 +141,7 @@ void XX_httplib_interpret_uri( struct mg_connection *conn, char *filename, size_
* to indicate that the response need to have the content- * to indicate that the response need to have the content-
* encoding: gzip header. * encoding: gzip header.
* We can only do this if the browser declares support. */ * We can only do this if the browser declares support. */
if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) { if ((accept_encoding = httplib_get_header(conn, "Accept-Encoding")) != NULL) {
if (strstr(accept_encoding, "gzip") != NULL) { if (strstr(accept_encoding, "gzip") != NULL) {
XX_httplib_snprintf( conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename); XX_httplib_snprintf( conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);

View File

@@ -25,7 +25,7 @@
#include "httplib_main.h" #include "httplib_main.h"
#if !defined(NO_FILES) #if !defined(NO_FILES)
int XX_httplib_is_authorized_for_put( struct mg_connection *conn ) { int XX_httplib_is_authorized_for_put( struct httplib_connection *conn ) {
if ( conn == NULL ) return 0; if ( conn == NULL ) return 0;

View File

@@ -24,7 +24,7 @@
#include "httplib_main.h" #include "httplib_main.h"
int XX_httplib_is_file_in_memory( const struct mg_connection *conn, const char *path, struct file *filep ) { int XX_httplib_is_file_in_memory( const struct httplib_connection *conn, const char *path, struct file *filep ) {
size_t size = 0; size_t size = 0;

View File

@@ -25,7 +25,7 @@
#include "httplib_main.h" #include "httplib_main.h"
/* /*
* int XX_httplib_is_not_modified( const struct mg_connection *conn, const struct file *filep ); * int XX_httplib_is_not_modified( const struct httplib_connection *conn, const struct file *filep );
* *
* The function XX_httplib_is_not_modified() returns true, if a resource has * The function XX_httplib_is_not_modified() returns true, if a resource has
* not been modified sinze a given datetime and a 304 response should therefore * not been modified sinze a given datetime and a 304 response should therefore
@@ -34,15 +34,15 @@
#if !defined(NO_CACHING) #if !defined(NO_CACHING)
int XX_httplib_is_not_modified( const struct mg_connection *conn, const struct file *filep ) { int XX_httplib_is_not_modified( const struct httplib_connection *conn, const struct file *filep ) {
char etag[64]; char etag[64];
const char *ims = mg_get_header( conn, "If-Modified-Since" ); const char *ims = httplib_get_header( conn, "If-Modified-Since" );
const char *inm = mg_get_header( conn, "If-None-Match" ); const char *inm = httplib_get_header( conn, "If-None-Match" );
XX_httplib_construct_etag( etag, sizeof(etag), filep ); XX_httplib_construct_etag( etag, sizeof(etag), filep );
if ( filep == NULL ) return 0; if ( filep == NULL ) return 0;
return (inm != NULL && !mg_strcasecmp(etag, inm)) || (ims != NULL && (filep->last_modified <= XX_httplib_parse_date_string(ims))); return (inm != NULL && !httplib_strcasecmp(etag, inm)) || (ims != NULL && (filep->last_modified <= XX_httplib_parse_date_string(ims)));
} /* XX_httplib_is_not_modified */ } /* XX_httplib_is_not_modified */

View File

@@ -24,7 +24,7 @@
#include "httplib_main.h" #include "httplib_main.h"
int XX_httplib_is_put_or_delete_method( const struct mg_connection *conn ) { int XX_httplib_is_put_or_delete_method( const struct httplib_connection *conn ) {
if ( conn == NULL ) return 0; if ( conn == NULL ) return 0;

View File

@@ -26,13 +26,13 @@
#include "httplib_string.h" #include "httplib_string.h"
/* /*
* int XX_httplib_is_websocket_protocol( const struct mg_connection *conn ); * int XX_httplib_is_websocket_protocol( const struct httplib_connection *conn );
* *
* The function XX_httplib_is_websocket_protocol() checks the request headers * The function XX_httplib_is_websocket_protocol() checks the request headers
* to see if the connection is a valid websocket protocol. * to see if the connection is a valid websocket protocol.
*/ */
int XX_httplib_is_websocket_protocol( const struct mg_connection *conn ) { int XX_httplib_is_websocket_protocol( const struct httplib_connection *conn ) {
#if defined(USE_WEBSOCKET) #if defined(USE_WEBSOCKET)
const char *upgrade; const char *upgrade;
@@ -44,12 +44,12 @@ int XX_httplib_is_websocket_protocol( const struct mg_connection *conn ) {
* Upgrade: Websocket * Upgrade: Websocket
*/ */
upgrade = mg_get_header(conn, "Upgrade"); upgrade = httplib_get_header(conn, "Upgrade");
if (upgrade == NULL) return 0; /* fail early, don't waste time checking other header * fields */ if (upgrade == NULL) return 0; /* fail early, don't waste time checking other header * fields */
if (!XX_httplib_strcasestr(upgrade, "websocket")) return 0; if (!XX_httplib_strcasestr(upgrade, "websocket")) return 0;
connection = mg_get_header(conn, "Connection"); connection = httplib_get_header(conn, "Connection");
if (connection == NULL) return 0; if (connection == NULL) return 0;
if (!XX_httplib_strcasestr(connection, "upgrade")) return 0; if (!XX_httplib_strcasestr(connection, "upgrade")) return 0;

View File

@@ -61,7 +61,7 @@ static int dlclose( void *handle ) {
/* /*
* XX_httplib_load_dll( struct mg_context *ctx, const char *dll_name, struct ssl_func *sw ); * XX_httplib_load_dll( struct httplib_context *ctx, const char *dll_name, struct ssl_func *sw );
* *
* The function XX_httplib_load_dll() is used to load the SSL library in a * The function XX_httplib_load_dll() is used to load the SSL library in a
* dynamic way. The function returns either a handle to the dll, or NULL if an * dynamic way. The function returns either a handle to the dll, or NULL if an
@@ -71,7 +71,7 @@ static int dlclose( void *handle ) {
#if !defined(NO_SSL) #if !defined(NO_SSL)
#if !defined(NO_SSL_DL) #if !defined(NO_SSL_DL)
void *XX_httplib_load_dll( struct mg_context *ctx, const char *dll_name, struct ssl_func *sw ) { void *XX_httplib_load_dll( struct httplib_context *ctx, const char *dll_name, struct ssl_func *sw ) {
union { union {
void *p; void *p;
@@ -81,7 +81,7 @@ void *XX_httplib_load_dll( struct mg_context *ctx, const char *dll_name, struct
struct ssl_func *fp; struct ssl_func *fp;
if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) { if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
mg_cry( XX_httplib_fc(ctx), "%s: cannot load %s", __func__, dll_name); httplib_cry( XX_httplib_fc(ctx), "%s: cannot load %s", __func__, dll_name);
return NULL; return NULL;
} }
@@ -96,7 +96,7 @@ void *XX_httplib_load_dll( struct mg_context *ctx, const char *dll_name, struct
u.p = dlsym(dll_handle, fp->name); u.p = dlsym(dll_handle, fp->name);
#endif /* _WIN32 */ #endif /* _WIN32 */
if (u.fp == NULL) { if (u.fp == NULL) {
mg_cry( XX_httplib_fc(ctx), "%s: %s: cannot find %s", __func__, dll_name, fp->name); httplib_cry( XX_httplib_fc(ctx), "%s: %s: cannot find %s", __func__, dll_name, fp->name);
dlclose(dll_handle); dlclose(dll_handle);
return NULL; return NULL;
} else fp->ptr = u.fp; } else fp->ptr = u.fp;

View File

@@ -26,28 +26,28 @@
#include "httplib_pthread.h" #include "httplib_pthread.h"
/* /*
* void mg_lock_connection( struct mg_connection *conn ); * void httplib_lock_connection( struct httplib_connection *conn );
* *
* The function mg_lock_connection() puts a lock on a connection. * The function httplib_lock_connection() puts a lock on a connection.
*/ */
void mg_lock_connection( struct mg_connection *conn ) { void httplib_lock_connection( struct httplib_connection *conn ) {
if ( conn != NULL ) pthread_mutex_lock( & conn->mutex ); if ( conn != NULL ) pthread_mutex_lock( & conn->mutex );
} /* mg_lock_connection */ } /* httplib_lock_connection */
/* /*
* void mg_unlock_connection( struct mg_connection *conn ); * void httplib_unlock_connection( struct httplib_connection *conn );
* *
* The function mg_unlock_connection() removes the current lock from a * The function httplib_unlock_connection() removes the current lock from a
* connection. * connection.
*/ */
void mg_unlock_connection( struct mg_connection *conn ) { void httplib_unlock_connection( struct httplib_connection *conn ) {
if ( conn != NULL ) pthread_mutex_unlock( & conn->mutex ); if ( conn != NULL ) pthread_mutex_unlock( & conn->mutex );
} /* mg_unlock_connection */ } /* httplib_unlock_connection */

View File

@@ -26,27 +26,27 @@
#include "httplib_pthread.h" #include "httplib_pthread.h"
/* /*
* void mg_lock_context( struct mg_context *ctx ); * void httplib_lock_context( struct httplib_context *ctx );
* *
* The function mg_lock_context() puts a lock on the context. * The function httplib_lock_context() puts a lock on the context.
*/ */
void mg_lock_context( struct mg_context *ctx ) { void httplib_lock_context( struct httplib_context *ctx ) {
if ( ctx != NULL ) pthread_mutex_lock( & ctx->nonce_mutex ); if ( ctx != NULL ) pthread_mutex_lock( & ctx->nonce_mutex );
} /* mg_lock_context */ } /* httplib_lock_context */
/* /*
* void mg_unlock_context( struct mg_context *ctx ); * void httplib_unlock_context( struct httplib_context *ctx );
* *
* The function mg_unlock_context() removes the current lock from the context. * The function httplib_unlock_context() removes the current lock from the context.
*/ */
void mg_unlock_context( struct mg_context *ctx ) { void httplib_unlock_context( struct httplib_context *ctx ) {
if ( ctx != NULL ) pthread_mutex_unlock( & ctx->nonce_mutex ); if ( ctx != NULL ) pthread_mutex_unlock( & ctx->nonce_mutex );
} /* mg_unlock_context */ } /* httplib_unlock_context */

View File

@@ -26,17 +26,17 @@
#include "httplib_ssl.h" #include "httplib_ssl.h"
#include "httplib_string.h" #include "httplib_string.h"
static const char *header_val( const struct mg_connection *conn, const char *header ); static const char *header_val( const struct httplib_connection *conn, const char *header );
/* /*
* void XX_httplib_log_access( const struct mg_connection *conn ); * void XX_httplib_log_access( const struct httplib_connection *conn );
* *
* The function XX_httplib_log_access() logs an access of a client. * The function XX_httplib_log_access() logs an access of a client.
*/ */
void XX_httplib_log_access( const struct mg_connection *conn ) { void XX_httplib_log_access( const struct httplib_connection *conn ) {
const struct mg_request_info *ri; const struct httplib_request_info *ri;
struct file fi; struct file fi;
char date[64]; char date[64];
char src_addr[IP_ADDR_STR_LEN]; char src_addr[IP_ADDR_STR_LEN];
@@ -104,17 +104,17 @@ void XX_httplib_log_access( const struct mg_connection *conn ) {
/* /*
* static const char *header_val( const struct mg_connection *conn, const char *header ); * static const char *header_val( const struct httplib_connection *conn, const char *header );
* *
* The function header_val() returns the value of a specific header of a * The function header_val() returns the value of a specific header of a
* connection. * connection.
*/ */
static const char *header_val( const struct mg_connection *conn, const char *header ) { static const char *header_val( const struct httplib_connection *conn, const char *header ) {
const char *header_value; const char *header_value;
if ((header_value = mg_get_header(conn, header)) == NULL) return "-"; if ((header_value = httplib_get_header(conn, header)) == NULL) return "-";
else return header_value; else return header_value;
} /* header_val */ } /* header_val */

View File

@@ -73,20 +73,20 @@
* Unfortunately some compilers still do not support it, so we have a * Unfortunately some compilers still do not support it, so we have a
* replacement function here. */ * replacement function here. */
#if defined(_MSC_VER) && (_MSC_VER >= 1600) #if defined(_MSC_VER) && (_MSC_VER >= 1600)
#define mg_static_assert static_assert #define httplib_static_assert static_assert
#elif defined(__cplusplus) && (__cplusplus >= 201103L) #elif defined(__cplusplus) && (__cplusplus >= 201103L)
#define mg_static_assert static_assert #define httplib_static_assert static_assert
#elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
#define mg_static_assert _Static_assert #define httplib_static_assert _Static_assert
#else #else
char static_assert_replacement[1]; char static_assert_replacement[1];
#define mg_static_assert(cond, txt) \ #define httplib_static_assert(cond, txt) \
extern char static_assert_replacement[(cond) ? 1 : -1] extern char static_assert_replacement[(cond) ? 1 : -1]
#endif #endif
mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8, "int data type size check"); httplib_static_assert(sizeof(int) == 4 || sizeof(int) == 8, "int data type size check");
mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8, "pointer data type size check"); httplib_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8, "pointer data type size check");
mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check"); httplib_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
/* DTL -- including winsock2.h works better if lean and mean */ /* DTL -- including winsock2.h works better if lean and mean */
@@ -163,7 +163,7 @@ typedef const char *SOCK_OPT_TYPE;
#define PATH_MAX (4096) #define PATH_MAX (4096)
#endif /* PATH_MAX */ #endif /* PATH_MAX */
mg_static_assert(PATH_MAX >= 1, "path length must be a positive number"); httplib_static_assert(PATH_MAX >= 1, "path length must be a positive number");
#ifndef _IN_PORT_T #ifndef _IN_PORT_T
#ifndef in_port_t #ifndef in_port_t
@@ -234,7 +234,7 @@ typedef long off_t;
#define WINCDECL __cdecl #define WINCDECL __cdecl
#define vsnprintf_impl _vsnprintf #define vsnprintf_impl _vsnprintf
#define access _access #define access _access
#define mg_sleep(x) (Sleep(x)) #define httplib_sleep(x) (Sleep(x))
#define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY) #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
#ifndef popen #ifndef popen
@@ -265,7 +265,7 @@ typedef DWORD pthread_key_t;
typedef HANDLE pthread_t; typedef HANDLE pthread_t;
typedef struct { typedef struct {
CRITICAL_SECTION threadIdSec; CRITICAL_SECTION threadIdSec;
struct mg_workerTLS * waiting_thread; /* The chain of threads */ struct httplib_workerTLS * waiting_thread; /* The chain of threads */
} pthread_cond_t; } pthread_cond_t;
#ifndef __clockid_t_defined #ifndef __clockid_t_defined
@@ -361,11 +361,11 @@ typedef unsigned short int in_port_t;
#define O_BINARY (0) #define O_BINARY (0)
#endif /* O_BINARY */ #endif /* O_BINARY */
#define closesocket(a) (close(a)) #define closesocket(a) (close(a))
#define mg_mkdir(conn, path, mode) (mkdir(path, mode)) #define httplib_mkdir(conn, path, mode) (mkdir(path, mode))
#define mg_sleep(x) (usleep((x)*1000)) #define httplib_sleep(x) (usleep((x)*1000))
#define mg_opendir(conn, x) (opendir(x)) #define httplib_opendir(conn, x) (opendir(x))
#define mg_closedir(x) (closedir(x)) #define httplib_closedir(x) (closedir(x))
#define mg_readdir(x) (readdir(x)) #define httplib_readdir(x) (readdir(x))
#define ERRNO (errno) #define ERRNO (errno)
#define INVALID_SOCKET (-1) #define INVALID_SOCKET (-1)
#define INT64_FMT PRId64 #define INT64_FMT PRId64
@@ -516,12 +516,12 @@ typedef struct x509 X509;
#endif /* NO_SSL_DL */ #endif /* NO_SSL_DL */
#endif /* NO_SSL */ #endif /* NO_SSL */
struct mg_workerTLS { struct httplib_workerTLS {
int is_master; int is_master;
unsigned long thread_idx; unsigned long thread_idx;
#if defined(_WIN32) #if defined(_WIN32)
HANDLE pthread_cond_helper_mutex; HANDLE pthread_cond_helper_mutex;
struct mg_workerTLS *next_waiting_thread; struct httplib_workerTLS *next_waiting_thread;
#endif #endif
}; };
@@ -534,7 +534,7 @@ extern CRITICAL_SECTION global_log_file_lock;
#define MAX_CGI_ENVIR_VARS (256) #define MAX_CGI_ENVIR_VARS (256)
#define MG_BUF_LEN (8192) #define MG_BUF_LEN (8192)
mg_static_assert(MAX_REQUEST_SIZE >= 256, "request size length must be a positive number"); httplib_static_assert(MAX_REQUEST_SIZE >= 256, "request size length must be a positive number");
/* Describes listening socket, or socket which was accept()-ed by the master /* Describes listening socket, or socket which was accept()-ed by the master
@@ -551,10 +551,10 @@ struct socket {
/* /*
* struct mg_handler_info; * struct httplib_handler_info;
*/ */
struct mg_handler_info { struct httplib_handler_info {
/* Name/Pattern of the URI. */ /* Name/Pattern of the URI. */
char *uri; char *uri;
size_t uri_len; size_t uri_len;
@@ -563,34 +563,34 @@ struct mg_handler_info {
int handler_type; int handler_type;
/* Handler for http/https or authorization requests. */ /* Handler for http/https or authorization requests. */
mg_request_handler handler; httplib_request_handler handler;
/* Handler for ws/wss (websocket) requests. */ /* Handler for ws/wss (websocket) requests. */
mg_websocket_connect_handler connect_handler; httplib_websocket_connect_handler connect_handler;
mg_websocket_ready_handler ready_handler; httplib_websocket_ready_handler ready_handler;
mg_websocket_data_handler data_handler; httplib_websocket_data_handler data_handler;
mg_websocket_close_handler close_handler; httplib_websocket_close_handler close_handler;
/* Handler for authorization requests */ /* Handler for authorization requests */
mg_authorization_handler auth_handler; httplib_authorization_handler auth_handler;
/* User supplied argument for the handler function. */ /* User supplied argument for the handler function. */
void *cbdata; void *cbdata;
/* next handler in a linked list */ /* next handler in a linked list */
struct mg_handler_info *next; struct httplib_handler_info *next;
}; };
/* /*
* struct mg_context; * struct httplib_context;
*/ */
struct mg_context { struct httplib_context {
volatile int stop_flag; /* Should we stop event loop */ volatile int stop_flag; /* Should we stop event loop */
SSL_CTX *ssl_ctx; /* SSL context */ SSL_CTX *ssl_ctx; /* SSL context */
char *config[NUM_OPTIONS]; /* LibHTTP configuration parameters */ char *config[NUM_OPTIONS]; /* LibHTTP configuration parameters */
struct mg_callbacks callbacks; /* User-defined callback function */ struct httplib_callbacks callbacks; /* User-defined callback function */
void *user_data; /* User-defined data */ void *user_data; /* User-defined data */
int context_type; /* 1 = server context, 2 = client context */ int context_type; /* 1 = server context, 2 = client context */
@@ -624,7 +624,7 @@ struct mg_context {
char *systemName; /* What operating system is running */ char *systemName; /* What operating system is running */
/* linked list of uri handlers */ /* linked list of uri handlers */
struct mg_handler_info *handlers; struct httplib_handler_info *handlers;
#ifdef USE_TIMERS #ifdef USE_TIMERS
struct ttimers *timers; struct ttimers *timers;
@@ -632,12 +632,12 @@ struct mg_context {
}; };
/* /*
* struct mg_connection; * struct httplib_connection;
*/ */
struct mg_connection { struct httplib_connection {
struct mg_request_info request_info; struct httplib_request_info request_info;
struct mg_context *ctx; struct httplib_context *ctx;
SSL *ssl; /* SSL descriptor */ SSL *ssl; /* SSL descriptor */
SSL_CTX *client_ssl_ctx; /* SSL context for client connections */ SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
struct socket client; /* Connected client */ struct socket client; /* Connected client */
@@ -662,21 +662,21 @@ struct mg_connection {
int throttle; /* Throttling, bytes/sec. <= 0 means no throttle */ int throttle; /* Throttling, bytes/sec. <= 0 means no throttle */
time_t last_throttle_time; /* Last time throttled data was sent */ time_t last_throttle_time; /* Last time throttled data was sent */
int64_t last_throttle_bytes; /* Bytes sent this second */ int64_t last_throttle_bytes; /* Bytes sent this second */
pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure atomic transmissions for websockets */ pthread_mutex_t mutex; /* Used by httplib_(un)lock_connection to ensure atomic transmissions for websockets */
int thread_index; /* Thread index within ctx */ int thread_index; /* Thread index within ctx */
}; };
struct worker_thread_args { struct worker_thread_args {
struct mg_context *ctx; struct httplib_context *ctx;
int index; int index;
}; };
struct websocket_client_thread_data { struct websocket_client_thread_data {
struct mg_connection *conn; struct httplib_connection *conn;
mg_websocket_data_handler data_handler; httplib_websocket_data_handler data_handler;
mg_websocket_close_handler close_handler; httplib_websocket_close_handler close_handler;
void *callback_data; void *callback_data;
}; };
@@ -707,7 +707,7 @@ enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
/* Directory entry */ /* Directory entry */
struct de { struct de {
struct mg_connection *conn; struct httplib_connection *conn;
char *file_name; char *file_name;
struct file file; struct file file;
}; };
@@ -728,7 +728,7 @@ struct dir_scan_data {
* We satisfy both worlds: we create an envp array (which is vars), all * We satisfy both worlds: we create an envp array (which is vars), all
* entries are actually pointers inside buf. */ * entries are actually pointers inside buf. */
struct cgi_environment { struct cgi_environment {
struct mg_connection *conn; struct httplib_connection *conn;
/* Data block */ /* Data block */
char *buf; /* Environment buffer */ char *buf; /* Environment buffer */
size_t buflen; /* Space available in buf */ size_t buflen; /* Space available in buf */
@@ -751,7 +751,7 @@ struct ah {
}; };
struct read_auth_file_struct { struct read_auth_file_struct {
struct mg_connection *conn; struct httplib_connection *conn;
struct ah ah; struct ah ah;
char *domain; char *domain;
char buf[256 + 256 + 40]; char buf[256 + 256 + 40];
@@ -773,8 +773,8 @@ typedef struct {
mg_static_assert(MAX_WORKER_THREADS >= 1, "worker threads must be a positive number"); httplib_static_assert(MAX_WORKER_THREADS >= 1, "worker threads must be a positive number");
mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8, "size_t data type size check"); httplib_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8, "size_t data type size check");
/* va_copy should always be a macro, C99 and C++11 - DTL */ /* va_copy should always be a macro, C99 and C++11 - DTL */
#ifndef va_copy #ifndef va_copy
@@ -809,127 +809,127 @@ void SHA1Final( unsigned char digest[20], SHA1_CTX *context );
void SHA1Init( SHA1_CTX *context ); void SHA1Init( SHA1_CTX *context );
void SHA1Update( SHA1_CTX *context, const unsigned char *data, uint32_t len ); void SHA1Update( SHA1_CTX *context, const unsigned char *data, uint32_t len );
void XX_httplib_accept_new_connection( const struct socket *listener, struct mg_context *ctx ); void XX_httplib_accept_new_connection( const struct socket *listener, struct httplib_context *ctx );
int XX_httplib_authorize( struct mg_connection *conn, struct file *filep ); int XX_httplib_authorize( struct httplib_connection *conn, struct file *filep );
const char * XX_httplib_builtin_mime_ext( int index ); const char * XX_httplib_builtin_mime_ext( int index );
const char * XX_httplib_builtin_mime_type( int index ); const char * XX_httplib_builtin_mime_type( int index );
int XX_httplib_check_acl( struct mg_context *ctx, uint32_t remote_ip ); int XX_httplib_check_acl( struct httplib_context *ctx, uint32_t remote_ip );
int XX_httplib_check_authorization( struct mg_connection *conn, const char *path ); int XX_httplib_check_authorization( struct httplib_connection *conn, const char *path );
int XX_httplib_check_password( const char *method, const char *ha1, const char *uri, const char *nonce, const char *nc, const char *cnonce, const char *qop, const char *response ); int XX_httplib_check_password( const char *method, const char *ha1, const char *uri, const char *nonce, const char *nc, const char *cnonce, const char *qop, const char *response );
void XX_httplib_close_all_listening_sockets( struct mg_context *ctx ); void XX_httplib_close_all_listening_sockets( struct httplib_context *ctx );
void XX_httplib_close_connection( struct mg_connection *conn ); void XX_httplib_close_connection( struct httplib_connection *conn );
int XX_httplib_closedir( DIR *dir ); int XX_httplib_closedir( DIR *dir );
void XX_httplib_close_socket_gracefully( struct mg_connection *conn ); void XX_httplib_close_socket_gracefully( struct httplib_connection *conn );
int WINCDECL XX_httplib_compare_dir_entries( const void *p1, const void *p2 ); int WINCDECL XX_httplib_compare_dir_entries( const void *p1, const void *p2 );
int XX_httplib_connect_socket( struct mg_context *ctx, const char *host, int port, int use_ssl, char *ebuf, size_t ebuf_len, SOCKET *sock, union usa *sa ); int XX_httplib_connect_socket( struct httplib_context *ctx, const char *host, int port, int use_ssl, char *ebuf, size_t ebuf_len, SOCKET *sock, union usa *sa );
void XX_httplib_construct_etag( char *buf, size_t buf_len, const struct file *filep ); void XX_httplib_construct_etag( char *buf, size_t buf_len, const struct file *filep );
int XX_httplib_consume_socket( struct mg_context *ctx, struct socket *sp, int thread_index ); int XX_httplib_consume_socket( struct httplib_context *ctx, struct socket *sp, int thread_index );
void XX_httplib_delete_file( struct mg_connection *conn, const char *path ); void XX_httplib_delete_file( struct httplib_connection *conn, const char *path );
void XX_httplib_dir_scan_callback( struct de *de, void *data ); void XX_httplib_dir_scan_callback( struct de *de, void *data );
void XX_httplib_discard_unread_request_data( struct mg_connection *conn ); void XX_httplib_discard_unread_request_data( struct httplib_connection *conn );
struct mg_connection * XX_httplib_fc( struct mg_context *ctx ); struct httplib_connection * XX_httplib_fc( struct httplib_context *ctx );
void XX_httplib_fclose( struct file *filep ); void XX_httplib_fclose( struct file *filep );
void XX_httplib_fclose_on_exec( struct file *filep, struct mg_connection *conn ); void XX_httplib_fclose_on_exec( struct file *filep, struct httplib_connection *conn );
const char * XX_httplib_fgets( char *buf, size_t size, struct file *filep, char **p ); const char * XX_httplib_fgets( char *buf, size_t size, struct file *filep, char **p );
int XX_httplib_fopen( const struct mg_connection *conn, const char *path, const char *mode, struct file *filep ); int XX_httplib_fopen( const struct httplib_connection *conn, const char *path, const char *mode, struct file *filep );
int XX_httplib_forward_body_data( struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl ); int XX_httplib_forward_body_data( struct httplib_connection *conn, FILE *fp, SOCKET sock, SSL *ssl );
void XX_httplib_free_context( struct mg_context *ctx ); void XX_httplib_free_context( struct httplib_context *ctx );
const char * XX_httplib_get_header( const struct mg_request_info *ri, const char *name ); const char * XX_httplib_get_header( const struct httplib_request_info *ri, const char *name );
void XX_httplib_get_mime_type( struct mg_context *ctx, const char *path, struct vec *vec ); void XX_httplib_get_mime_type( struct httplib_context *ctx, const char *path, struct vec *vec );
int XX_httplib_get_option_index( const char *name ); int XX_httplib_get_option_index( const char *name );
const char * XX_httplib_get_rel_url_at_current_server( const char *uri, const struct mg_connection *conn ); const char * XX_httplib_get_rel_url_at_current_server( const char *uri, const struct httplib_connection *conn );
uint32_t XX_httplib_get_remote_ip( const struct mg_connection *conn ); uint32_t XX_httplib_get_remote_ip( const struct httplib_connection *conn );
int XX_httplib_get_request_handler( struct mg_connection *conn, int handler_type, mg_request_handler *handler, mg_websocket_connect_handler *connect_handler, mg_websocket_ready_handler *ready_handler, mg_websocket_data_handler *data_handler, mg_websocket_close_handler *close_handler, mg_authorization_handler *auth_handler, void **cbdata ); int XX_httplib_get_request_handler( struct httplib_connection *conn, int handler_type, httplib_request_handler *handler, httplib_websocket_connect_handler *connect_handler, httplib_websocket_ready_handler *ready_handler, httplib_websocket_data_handler *data_handler, httplib_websocket_close_handler *close_handler, httplib_authorization_handler *auth_handler, void **cbdata );
int XX_httplib_get_request_len( const char *buf, int buflen ); int XX_httplib_get_request_len( const char *buf, int buflen );
void XX_httplib_get_system_name( char **sysName ); void XX_httplib_get_system_name( char **sysName );
int XX_httplib_get_uri_type( const char *uri ); int XX_httplib_get_uri_type( const char *uri );
int XX_httplib_getreq( struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err ); int XX_httplib_getreq( struct httplib_connection *conn, char *ebuf, size_t ebuf_len, int *err );
void XX_httplib_handle_cgi_request( struct mg_connection *conn, const char *prog ); void XX_httplib_handle_cgi_request( struct httplib_connection *conn, const char *prog );
void XX_httplib_handle_directory_request( struct mg_connection *conn, const char *dir ); void XX_httplib_handle_directory_request( struct httplib_connection *conn, const char *dir );
void XX_httplib_handle_file_based_request( struct mg_connection *conn, const char *path, struct file *filep ); void XX_httplib_handle_file_based_request( struct httplib_connection *conn, const char *path, struct file *filep );
void XX_httplib_handle_not_modified_static_file_request( struct mg_connection *conn, struct file *filep ); void XX_httplib_handle_not_modified_static_file_request( struct httplib_connection *conn, struct file *filep );
void XX_httplib_handle_propfind( struct mg_connection *conn, const char *path, struct file *filep ); void XX_httplib_handle_propfind( struct httplib_connection *conn, const char *path, struct file *filep );
void XX_httplib_handle_request( struct mg_connection *conn ); void XX_httplib_handle_request( struct httplib_connection *conn );
void XX_httplib_handle_ssi_file_request( struct mg_connection *conn, const char *path, struct file *filep ); void XX_httplib_handle_ssi_file_request( struct httplib_connection *conn, const char *path, struct file *filep );
void XX_httplib_handle_static_file_request( struct mg_connection *conn, const char *path, struct file *filep, const char *mime_type, const char *additional_headers ); void XX_httplib_handle_static_file_request( struct httplib_connection *conn, const char *path, struct file *filep, const char *mime_type, const char *additional_headers );
void XX_httplib_handle_websocket_request( struct mg_connection *conn, const char *path, int is_callback_resource, mg_websocket_connect_handler ws_connect_handler, mg_websocket_ready_handler ws_ready_handler, mg_websocket_data_handler ws_data_handler, mg_websocket_close_handler ws_close_handler, void *cbData ); void XX_httplib_handle_websocket_request( struct httplib_connection *conn, const char *path, int is_callback_resource, httplib_websocket_connect_handler ws_connect_handler, httplib_websocket_ready_handler ws_ready_handler, httplib_websocket_data_handler ws_data_handler, httplib_websocket_close_handler ws_close_handler, void *cbData );
int XX_httplib_header_has_option( const char *header, const char *option ); int XX_httplib_header_has_option( const char *header, const char *option );
void XX_httplib_interpret_uri( struct mg_connection *conn, char *filename, size_t filename_buf_len, struct file *filep, int *is_found, int *is_script_resource, int *is_websocket_request, int *is_put_or_delete_request ); void XX_httplib_interpret_uri( struct httplib_connection *conn, char *filename, size_t filename_buf_len, struct file *filep, int *is_found, int *is_script_resource, int *is_websocket_request, int *is_put_or_delete_request );
int XX_httplib_is_authorized_for_put( struct mg_connection *conn ); int XX_httplib_is_authorized_for_put( struct httplib_connection *conn );
int XX_httplib_is_file_in_memory( const struct mg_connection *conn, const char *path, struct file *filep ); int XX_httplib_is_file_in_memory( const struct httplib_connection *conn, const char *path, struct file *filep );
bool XX_httplib_is_file_opened( const struct file *filep ); bool XX_httplib_is_file_opened( const struct file *filep );
int XX_httplib_is_not_modified( const struct mg_connection *conn, const struct file *filep ); int XX_httplib_is_not_modified( const struct httplib_connection *conn, const struct file *filep );
int XX_httplib_is_put_or_delete_method( const struct mg_connection *conn ); int XX_httplib_is_put_or_delete_method( const struct httplib_connection *conn );
bool XX_httplib_is_valid_http_method( const char *method ); bool XX_httplib_is_valid_http_method( const char *method );
int XX_httplib_is_valid_port( unsigned long port ); int XX_httplib_is_valid_port( unsigned long port );
int XX_httplib_is_websocket_protocol( const struct mg_connection *conn ); int XX_httplib_is_websocket_protocol( const struct httplib_connection *conn );
int XX_httplib_join_thread( pthread_t threadid ); int XX_httplib_join_thread( pthread_t threadid );
int XX_httplib_kill( pid_t pid, int sig_num ); int XX_httplib_kill( pid_t pid, int sig_num );
void * XX_httplib_load_dll( struct mg_context *ctx, const char *dll_name, struct ssl_func *sw ); void * XX_httplib_load_dll( struct httplib_context *ctx, const char *dll_name, struct ssl_func *sw );
void XX_httplib_log_access( const struct mg_connection *conn ); void XX_httplib_log_access( const struct httplib_connection *conn );
int XX_httplib_match_prefix(const char *pattern, size_t pattern_len, const char *str); int XX_httplib_match_prefix(const char *pattern, size_t pattern_len, const char *str);
void XX_httplib_mkcol( struct mg_connection *conn, const char *path ); void XX_httplib_mkcol( struct httplib_connection *conn, const char *path );
int XX_httplib_mkdir( const struct mg_connection *conn, const char *path, int mode ); int XX_httplib_mkdir( const struct httplib_connection *conn, const char *path, int mode );
int XX_httplib_must_hide_file( struct mg_connection *conn, const char *path ); int XX_httplib_must_hide_file( struct httplib_connection *conn, const char *path );
const char * XX_httplib_next_option( const char *list, struct vec *val, struct vec *eq_val ); const char * XX_httplib_next_option( const char *list, struct vec *val, struct vec *eq_val );
void XX_httplib_open_auth_file( struct mg_connection *conn, const char *path, struct file *filep ); void XX_httplib_open_auth_file( struct httplib_connection *conn, const char *path, struct file *filep );
DIR * XX_httplib_opendir( const struct mg_connection *conn, const char *name ); DIR * XX_httplib_opendir( const struct httplib_connection *conn, const char *name );
int XX_httplib_parse_auth_header( struct mg_connection *conn, char *buf, size_t buf_size, struct ah *ah ); int XX_httplib_parse_auth_header( struct httplib_connection *conn, char *buf, size_t buf_size, struct ah *ah );
time_t XX_httplib_parse_date_string( const char *datetime ); time_t XX_httplib_parse_date_string( const char *datetime );
int XX_httplib_parse_http_headers( char **buf, struct mg_request_info *ri ); int XX_httplib_parse_http_headers( char **buf, struct httplib_request_info *ri );
int XX_httplib_parse_http_message( char *buf, int len, struct mg_request_info *ri ); int XX_httplib_parse_http_message( char *buf, int len, struct httplib_request_info *ri );
int XX_httplib_parse_net( const char *spec, uint32_t *net, uint32_t *mask ); int XX_httplib_parse_net( const char *spec, uint32_t *net, uint32_t *mask );
int XX_httplib_parse_range_header( const char *header, int64_t *a, int64_t *b ); int XX_httplib_parse_range_header( const char *header, int64_t *a, int64_t *b );
void XX_httplib_path_to_unicode( const struct mg_connection *conn, const char *path, wchar_t *wbuf, size_t wbuf_len ); void XX_httplib_path_to_unicode( const struct httplib_connection *conn, const char *path, wchar_t *wbuf, size_t wbuf_len );
void XX_httplib_prepare_cgi_environment( struct mg_connection *conn, const char *prog, struct cgi_environment *env ); void XX_httplib_prepare_cgi_environment( struct httplib_connection *conn, const char *prog, struct cgi_environment *env );
void XX_httplib_print_dir_entry( struct de *de ); void XX_httplib_print_dir_entry( struct de *de );
void XX_httplib_process_new_connection( struct mg_connection *conn ); void XX_httplib_process_new_connection( struct httplib_connection *conn );
void XX_httplib_produce_socket( struct mg_context *ctx, const struct socket *sp ); void XX_httplib_produce_socket( struct httplib_context *ctx, const struct socket *sp );
int XX_httplib_pull( FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout ); int XX_httplib_pull( FILE *fp, struct httplib_connection *conn, char *buf, int len, double timeout );
int XX_httplib_pull_all( FILE *fp, struct mg_connection *conn, char *buf, int len ); int XX_httplib_pull_all( FILE *fp, struct httplib_connection *conn, char *buf, int len );
int64_t XX_httplib_push_all( struct mg_context *ctx, FILE *fp, SOCKET sock, SSL *ssl, const char *buf, int64_t len ); int64_t XX_httplib_push_all( struct httplib_context *ctx, FILE *fp, SOCKET sock, SSL *ssl, const char *buf, int64_t len );
int XX_httplib_put_dir( struct mg_connection *conn, const char *path ); int XX_httplib_put_dir( struct httplib_connection *conn, const char *path );
void XX_httplib_put_file( struct mg_connection *conn, const char *path ); void XX_httplib_put_file( struct httplib_connection *conn, const char *path );
int XX_httplib_read_auth_file( struct file *filep, struct read_auth_file_struct *workdata ); int XX_httplib_read_auth_file( struct file *filep, struct read_auth_file_struct *workdata );
int XX_httplib_read_request( FILE *fp, struct mg_connection *conn, char *buf, int bufsiz, int *nread ); int XX_httplib_read_request( FILE *fp, struct httplib_connection *conn, char *buf, int bufsiz, int *nread );
void XX_httplib_read_websocket( struct mg_connection *conn, mg_websocket_data_handler ws_data_handler, void *callback_data ); void XX_httplib_read_websocket( struct httplib_connection *conn, httplib_websocket_data_handler ws_data_handler, void *callback_data );
struct dirent * XX_httplib_readdir( DIR *dir ); struct dirent * XX_httplib_readdir( DIR *dir );
void XX_httplib_redirect_to_https_port( struct mg_connection *conn, int ssl_index ); void XX_httplib_redirect_to_https_port( struct httplib_connection *conn, int ssl_index );
int XX_httplib_refresh_trust( struct mg_connection *conn ); int XX_httplib_refresh_trust( struct httplib_connection *conn );
int XX_httplib_remove( const struct mg_connection *conn, const char *path ); int XX_httplib_remove( const struct httplib_connection *conn, const char *path );
void XX_httplib_remove_bad_file( const struct mg_connection *conn, const char *path ); void XX_httplib_remove_bad_file( const struct httplib_connection *conn, const char *path );
int XX_httplib_remove_directory( struct mg_connection *conn, const char *dir ); int XX_httplib_remove_directory( struct httplib_connection *conn, const char *dir );
void XX_httplib_remove_double_dots_and_double_slashes( char *s ); void XX_httplib_remove_double_dots_and_double_slashes( char *s );
void XX_httplib_reset_per_request_attributes( struct mg_connection *conn ); void XX_httplib_reset_per_request_attributes( struct httplib_connection *conn );
int XX_httplib_scan_directory( struct mg_connection *conn, const char *dir, void *data, void (*cb)(struct de *, void *) ); int XX_httplib_scan_directory( struct httplib_connection *conn, const char *dir, void *data, void (*cb)(struct de *, void *) );
void XX_httplib_send_authorization_request( struct mg_connection *conn ); void XX_httplib_send_authorization_request( struct httplib_connection *conn );
void XX_httplib_send_file_data( struct mg_connection *conn, struct file *filep, int64_t offset, int64_t len ); void XX_httplib_send_file_data( struct httplib_connection *conn, struct file *filep, int64_t offset, int64_t len );
void XX_httplib_send_http_error( struct mg_connection *, int, PRINTF_FORMAT_STRING(const char *fmt), ... ) PRINTF_ARGS(3, 4); void XX_httplib_send_http_error( struct httplib_connection *, int, PRINTF_FORMAT_STRING(const char *fmt), ... ) PRINTF_ARGS(3, 4);
int XX_httplib_send_no_cache_header( struct mg_connection *conn ); int XX_httplib_send_no_cache_header( struct httplib_connection *conn );
void XX_httplib_send_options( struct mg_connection *conn ); void XX_httplib_send_options( struct httplib_connection *conn );
int XX_httplib_send_static_cache_header( struct mg_connection *conn ); int XX_httplib_send_static_cache_header( struct httplib_connection *conn );
int XX_httplib_send_websocket_handshake( struct mg_connection *conn, const char *websock_key ); int XX_httplib_send_websocket_handshake( struct httplib_connection *conn, const char *websock_key );
int XX_httplib_set_acl_option( struct mg_context *ctx ); int XX_httplib_set_acl_option( struct httplib_context *ctx );
void XX_httplib_set_close_on_exec( SOCKET sock, struct mg_connection *conn ); void XX_httplib_set_close_on_exec( SOCKET sock, struct httplib_connection *conn );
int XX_httplib_set_gpass_option( struct mg_context *ctx ); int XX_httplib_set_gpass_option( struct httplib_context *ctx );
void XX_httplib_set_handler_type( struct mg_context *ctx, const char *uri, int handler_type, int is_delete_request, mg_request_handler handler, mg_websocket_connect_handler connect_handler, mg_websocket_ready_handler ready_handler, mg_websocket_data_handler data_handler, mg_websocket_close_handler close_handler, mg_authorization_handler auth_handler, void *cbdata ); void XX_httplib_set_handler_type( struct httplib_context *ctx, const char *uri, int handler_type, int is_delete_request, httplib_request_handler handler, httplib_websocket_connect_handler connect_handler, httplib_websocket_ready_handler ready_handler, httplib_websocket_data_handler data_handler, httplib_websocket_close_handler close_handler, httplib_authorization_handler auth_handler, void *cbdata );
int XX_httplib_set_non_blocking_mode( SOCKET sock ); int XX_httplib_set_non_blocking_mode( SOCKET sock );
int XX_httplib_set_ports_option( struct mg_context *ctx ); int XX_httplib_set_ports_option( struct httplib_context *ctx );
int XX_httplib_set_sock_timeout( SOCKET sock, int milliseconds ); int XX_httplib_set_sock_timeout( SOCKET sock, int milliseconds );
int XX_httplib_set_tcp_nodelay( SOCKET sock, int nodelay_on ); int XX_httplib_set_tcp_nodelay( SOCKET sock, int nodelay_on );
void XX_httplib_set_thread_name( const char *name ); void XX_httplib_set_thread_name( const char *name );
int XX_httplib_set_throttle( const char *spec, uint32_t remote_ip, const char *uri ); int XX_httplib_set_throttle( const char *spec, uint32_t remote_ip, const char *uri );
int XX_httplib_set_uid_option( struct mg_context *ctx ); int XX_httplib_set_uid_option( struct httplib_context *ctx );
int XX_httplib_should_decode_url( const struct mg_connection *conn ); int XX_httplib_should_decode_url( const struct httplib_connection *conn );
int XX_httplib_should_keep_alive( const struct mg_connection *conn ); int XX_httplib_should_keep_alive( const struct httplib_connection *conn );
char * XX_httplib_skip( char **buf, const char *delimiters ); char * XX_httplib_skip( char **buf, const char *delimiters );
char * XX_httplib_skip_quoted( char **buf, const char *delimiters, const char *whitespace, char quotechar ); char * XX_httplib_skip_quoted( char **buf, const char *delimiters, const char *whitespace, char quotechar );
void XX_httplib_sockaddr_to_string(char *buf, size_t len, const union usa *usa ); void XX_httplib_sockaddr_to_string(char *buf, size_t len, const union usa *usa );
pid_t XX_httplib_spawn_process( struct mg_connection *conn, const char *prog, char *envblk, char *envp[], int fdin[2], int fdout[2], int fderr[2], const char *dir ); pid_t XX_httplib_spawn_process( struct httplib_connection *conn, const char *prog, char *envblk, char *envp[], int fdin[2], int fdout[2], int fderr[2], const char *dir );
int XX_httplib_stat( struct mg_connection *conn, const char *path, struct file *filep ); int XX_httplib_stat( struct httplib_connection *conn, const char *path, struct file *filep );
int XX_httplib_substitute_index_file( struct mg_connection *conn, char *path, size_t path_len, struct file *filep ); int XX_httplib_substitute_index_file( struct httplib_connection *conn, char *path, size_t path_len, struct file *filep );
const char * XX_httplib_suggest_connection_header( const struct mg_connection *conn ); const char * XX_httplib_suggest_connection_header( const struct httplib_connection *conn );
int XX_httplib_websocket_write_exec( struct mg_connection *conn, int opcode, const char *data, size_t dataLen, uint32_t masking_key ); int XX_httplib_websocket_write_exec( struct httplib_connection *conn, int opcode, const char *data, size_t dataLen, uint32_t masking_key );
@@ -957,7 +957,7 @@ unsigned __stdcall XX_httplib_worker_thread( void *thread_func_param );
extern struct pthread_mutex_undefined_struct * XX_httplib_pthread_mutex_attr; extern struct pthread_mutex_undefined_struct * XX_httplib_pthread_mutex_attr;
#else /* _WIN32 */ #else /* _WIN32 */
void * XX_httplib_master_thread( void *thread_func_param ); void * XX_httplib_master_thread( void *thread_func_param );
int XX_httplib_start_thread_with_id( mg_thread_func_t func, void *param, pthread_t *threadidptr ); int XX_httplib_start_thread_with_id( httplib_thread_func_t func, void *param, pthread_t *threadidptr );
void * XX_httplib_websocket_client_thread( void *data ); void * XX_httplib_websocket_client_thread( void *data );
void * XX_httplib_worker_thread( void *thread_func_param ); void * XX_httplib_worker_thread( void *thread_func_param );
@@ -965,4 +965,4 @@ extern pthread_mutexattr_t XX_httplib_pthread_mutex_attr;
#endif /* _WIN32 */ #endif /* _WIN32 */
extern const struct uriprot_tp XX_httplib_abs_uri_protocols[]; extern const struct uriprot_tp XX_httplib_abs_uri_protocols[];
extern struct mg_option XX_httplib_config_options[]; extern struct httplib_option XX_httplib_config_options[];

View File

@@ -27,8 +27,8 @@
#if defined(MEMORY_DEBUGGING) #if defined(MEMORY_DEBUGGING)
unsigned long mg_memory_debug_blockCount = 0; unsigned long httplib_memory_debug_blockCount = 0;
unsigned long mg_memory_debug_totalMemUsed = 0; unsigned long httplib_memory_debug_totalMemUsed = 0;
void *XX_httplib_malloc_ex( size_t size, const char *file, unsigned line ) { void *XX_httplib_malloc_ex( size_t size, const char *file, unsigned line ) {
@@ -39,8 +39,8 @@ void *XX_httplib_malloc_ex( size_t size, const char *file, unsigned line ) {
if (data) { if (data) {
*(size_t *)data = size; *(size_t *)data = size;
mg_memory_debug_totalMemUsed += size; httplib_memory_debug_totalMemUsed += size;
mg_memory_debug_blockCount++; httplib_memory_debug_blockCount++;
memory = (void *)(((char *)data) + sizeof(size_t)); memory = (void *)(((char *)data) + sizeof(size_t));
} }
@@ -67,8 +67,8 @@ void XX_httplib_free_ex( void *memory, const char *file, unsigned line ) {
if (memory) { if (memory) {
size = *(size_t *)data; size = *(size_t *)data;
mg_memory_debug_totalMemUsed -= size; httplib_memory_debug_totalMemUsed -= size;
mg_memory_debug_blockCount--; httplib_memory_debug_blockCount--;
free(data); free(data);
} }
@@ -90,8 +90,8 @@ void *XX_httplib_realloc_ex( void *memory, size_t newsize, const char *file, uns
_realloc = realloc(data, newsize + sizeof(size_t)); _realloc = realloc(data, newsize + sizeof(size_t));
if (_realloc) { if (_realloc) {
data = _realloc; data = _realloc;
mg_memory_debug_totalMemUsed -= oldsize; httplib_memory_debug_totalMemUsed -= oldsize;
mg_memory_debug_totalMemUsed += newsize; httplib_memory_debug_totalMemUsed += newsize;
*(size_t *)data = newsize; *(size_t *)data = newsize;
data = (void *)(((char *)data) + sizeof(size_t)); data = (void *)(((char *)data) + sizeof(size_t));
} else { } else {

View File

@@ -58,8 +58,8 @@ void *XX_httplib_master_thread( void *thread_func_param ) {
static void master_thread_run(void *thread_func_param) { static void master_thread_run(void *thread_func_param) {
struct mg_context *ctx = (struct mg_context *)thread_func_param; struct httplib_context *ctx = (struct httplib_context *)thread_func_param;
struct mg_workerTLS tls; struct httplib_workerTLS tls;
struct pollfd *pfd; struct pollfd *pfd;
unsigned int i; unsigned int i;
unsigned int workerthreadcount; unsigned int workerthreadcount;
@@ -122,7 +122,7 @@ static void master_thread_run(void *thread_func_param) {
/* Here stop_flag is 1 - Initiate shutdown. */ /* Here stop_flag is 1 - Initiate shutdown. */
/* Stop signal received: somebody called mg_stop. Quit. */ /* Stop signal received: somebody called httplib_stop. Quit. */
XX_httplib_close_all_listening_sockets(ctx); XX_httplib_close_all_listening_sockets(ctx);
/* Wakeup workers that are waiting for connections to handle. */ /* Wakeup workers that are waiting for connections to handle. */
@@ -158,7 +158,7 @@ static void master_thread_run(void *thread_func_param) {
#endif #endif
pthread_setspecific(XX_httplib_sTlsKey, NULL); pthread_setspecific(XX_httplib_sTlsKey, NULL);
/* Signal mg_stop() that we're done. /* Signal httplib_stop() that we're done.
* WARNING: This must be the very last thing this * WARNING: This must be the very last thing this
* thread does, as ctx becomes invalid after this line. */ * thread does, as ctx becomes invalid after this line. */
ctx->stop_flag = 2; ctx->stop_flag = 2;

View File

@@ -40,7 +40,7 @@ static void bin2str(char *to, const unsigned char *p, size_t len) {
/* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */ /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
char * mg_md5(char buf[33], ...) { char * httplib_md5(char buf[33], ...) {
md5_byte_t hash[16]; md5_byte_t hash[16];
const char *p; const char *p;
@@ -57,4 +57,4 @@ char * mg_md5(char buf[33], ...) {
bin2str(buf, hash, sizeof(hash)); bin2str(buf, hash, sizeof(hash));
return buf; return buf;
} /* mg_md5 */ } /* httplib_md5 */

View File

@@ -26,14 +26,14 @@
#include "httplib_utils.h" #include "httplib_utils.h"
/* /*
* void XX_httplib_mkcol( struct mg_connection *conn, const char *path ); * void XX_httplib_mkcol( struct httplib_connection *conn, const char *path );
* *
* The function XX_httplib_mkcol() handles a MKCOL command from a remote * The function XX_httplib_mkcol() handles a MKCOL command from a remote
* client. * client.
*/ */
#if !defined(NO_FILES) #if !defined(NO_FILES)
void XX_httplib_mkcol( struct mg_connection *conn, const char *path ) { void XX_httplib_mkcol( struct httplib_connection *conn, const char *path ) {
int rc; int rc;
int body_len; int body_len;
@@ -49,7 +49,7 @@ void XX_httplib_mkcol( struct mg_connection *conn, const char *path ) {
memset(&de.file, 0, sizeof(de.file)); memset(&de.file, 0, sizeof(de.file));
if (!XX_httplib_stat(conn, path, &de.file)) { if (!XX_httplib_stat(conn, path, &de.file)) {
mg_cry(conn, "%s: XX_httplib_stat(%s) failed: %s", __func__, path, strerror(ERRNO)); httplib_cry(conn, "%s: XX_httplib_stat(%s) failed: %s", __func__, path, strerror(ERRNO));
} }
if (de.file.last_modified) { if (de.file.last_modified) {
@@ -70,9 +70,9 @@ void XX_httplib_mkcol( struct mg_connection *conn, const char *path ) {
conn->status_code = 201; conn->status_code = 201;
XX_httplib_gmt_time_string(date, sizeof(date), &curtime); XX_httplib_gmt_time_string(date, sizeof(date), &curtime);
mg_printf(conn, "HTTP/1.1 %d Created\r\n" "Date: %s\r\n", conn->status_code, date); httplib_printf(conn, "HTTP/1.1 %d Created\r\n" "Date: %s\r\n", conn->status_code, date);
XX_httplib_send_static_cache_header(conn); XX_httplib_send_static_cache_header(conn);
mg_printf(conn, "Content-Length: 0\r\n" "Connection: %s\r\n\r\n", XX_httplib_suggest_connection_header(conn)); httplib_printf(conn, "Content-Length: 0\r\n" "Connection: %s\r\n\r\n", XX_httplib_suggest_connection_header(conn));
} }
else if (rc == -1) { else if (rc == -1) {

View File

@@ -26,7 +26,7 @@
#if defined(_WIN32) #if defined(_WIN32)
int XX_httplib_mkdir( const struct mg_connection *conn, const char *path, int mode ) { int XX_httplib_mkdir( const struct httplib_connection *conn, const char *path, int mode ) {
wchar_t wbuf[PATH_MAX]; wchar_t wbuf[PATH_MAX];

View File

@@ -24,7 +24,7 @@
#include "httplib_main.h" #include "httplib_main.h"
int mg_modify_passwords_file( const char *fname, const char *domain, const char *user, const char *pass ) { int httplib_modify_passwords_file( const char *fname, const char *domain, const char *user, const char *pass ) {
int found, i; int found, i;
char line[512]; char line[512];
@@ -90,7 +90,7 @@ int mg_modify_passwords_file( const char *fname, const char *domain, const char
if (!strcmp(u, user) && !strcmp(d, domain)) { if (!strcmp(u, user) && !strcmp(d, domain)) {
found++; found++;
if (pass != NULL) { if (pass != NULL) {
mg_md5(ha1, user, ":", domain, ":", pass, NULL); httplib_md5(ha1, user, ":", domain, ":", pass, NULL);
fprintf(fp2, "%s:%s:%s\n", user, domain, ha1); fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
} }
} else { } else {
@@ -100,7 +100,7 @@ int mg_modify_passwords_file( const char *fname, const char *domain, const char
/* If new user, just add it */ /* If new user, just add it */
if (!found && pass != NULL) { if (!found && pass != NULL) {
mg_md5(ha1, user, ":", domain, ":", pass, NULL); httplib_md5(ha1, user, ":", domain, ":", pass, NULL);
fprintf(fp2, "%s:%s:%s\n", user, domain, ha1); fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
} }
@@ -114,4 +114,4 @@ int mg_modify_passwords_file( const char *fname, const char *domain, const char
return 1; return 1;
} /* mg_modify_passwords_file */ } /* httplib_modify_passwords_file */

View File

@@ -24,7 +24,7 @@
#include "httplib_main.h" #include "httplib_main.h"
int XX_httplib_must_hide_file( struct mg_connection *conn, const char *path ) { int XX_httplib_must_hide_file( struct httplib_connection *conn, const char *path ) {
if (conn && conn->ctx) { if (conn && conn->ctx) {
const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$"; const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";

View File

@@ -27,7 +27,7 @@
/* Use the global passwords file, if specified by auth_gpass option, /* Use the global passwords file, if specified by auth_gpass option,
* or search for .htpasswd in the requested directory. */ * or search for .htpasswd in the requested directory. */
void XX_httplib_open_auth_file( struct mg_connection *conn, const char *path, struct file *filep ) { void XX_httplib_open_auth_file( struct httplib_connection *conn, const char *path, struct file *filep ) {
if ( conn == NULL || conn->ctx == NULL ) return; if ( conn == NULL || conn->ctx == NULL ) return;
@@ -42,7 +42,7 @@ void XX_httplib_open_auth_file( struct mg_connection *conn, const char *path, st
/* Use global passwords file */ /* Use global passwords file */
if (!XX_httplib_fopen(conn, gpass, "r", filep)) { if (!XX_httplib_fopen(conn, gpass, "r", filep)) {
#ifdef DEBUG #ifdef DEBUG
mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO)); httplib_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
#endif #endif
} }
/* Important: using local struct file to test path for is_directory /* Important: using local struct file to test path for is_directory
@@ -53,7 +53,7 @@ void XX_httplib_open_auth_file( struct mg_connection *conn, const char *path, st
if (truncated || !XX_httplib_fopen(conn, name, "r", filep)) { if (truncated || !XX_httplib_fopen(conn, name, "r", filep)) {
#ifdef DEBUG #ifdef DEBUG
mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO)); httplib_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
#endif #endif
} }
} else { } else {
@@ -65,7 +65,7 @@ void XX_httplib_open_auth_file( struct mg_connection *conn, const char *path, st
if (truncated || !XX_httplib_fopen(conn, name, "r", filep)) { if (truncated || !XX_httplib_fopen(conn, name, "r", filep)) {
#ifdef DEBUG #ifdef DEBUG
mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO)); httplib_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
#endif #endif
} }
} }

View File

@@ -28,7 +28,7 @@
#if defined(_WIN32) #if defined(_WIN32)
/* Implementation of POSIX opendir/closedir/readdir for Windows. */ /* Implementation of POSIX opendir/closedir/readdir for Windows. */
DIR *XX_httplib_opendir( const struct mg_connection *conn, const char *name ) { DIR *XX_httplib_opendir( const struct httplib_connection *conn, const char *name ) {
DIR *dir = NULL; DIR *dir = NULL;
wchar_t wpath[PATH_MAX]; wchar_t wpath[PATH_MAX];

View File

@@ -26,7 +26,7 @@
#include "httplib_string.h" #include "httplib_string.h"
/* Return 1 on success. Always initializes the ah structure. */ /* Return 1 on success. Always initializes the ah structure. */
int XX_httplib_parse_auth_header(struct mg_connection *conn, char *buf, size_t buf_size, struct ah *ah) { int XX_httplib_parse_auth_header(struct httplib_connection *conn, char *buf, size_t buf_size, struct ah *ah) {
char *name; char *name;
char *value; char *value;
@@ -37,7 +37,7 @@ int XX_httplib_parse_auth_header(struct mg_connection *conn, char *buf, size_t b
if (!ah || !conn) return 0; if (!ah || !conn) return 0;
memset(ah, 0, sizeof(*ah)); memset(ah, 0, sizeof(*ah));
if ((auth_header = mg_get_header(conn, "Authorization")) == NULL || mg_strncasecmp(auth_header, "Digest ", 7) != 0) return 0; if ((auth_header = httplib_get_header(conn, "Authorization")) == NULL || httplib_strncasecmp(auth_header, "Digest ", 7) != 0) return 0;
/* Make modifiable copy of the auth header */ /* Make modifiable copy of the auth header */
XX_httplib_strlcpy(buf, auth_header + 7, buf_size); XX_httplib_strlcpy(buf, auth_header + 7, buf_size);

View File

@@ -25,7 +25,7 @@
#include "httplib_main.h" #include "httplib_main.h"
/* /*
* int XX_httplib_parse_http_headers( char **buf, struct mg_request_info *ri ); * int XX_httplib_parse_http_headers( char **buf, struct httplib_request_info *ri );
* *
* The function XX_httplib_parse_http_headers() parses the HTTP headers from * The function XX_httplib_parse_http_headers() parses the HTTP headers from
* the given buffer. The buf pointer is advanced to the point where parsing * the given buffer. The buf pointer is advanced to the point where parsing
@@ -33,7 +33,7 @@
* headers read is returned, or a negative value if an error occured. * headers read is returned, or a negative value if an error occured.
*/ */
int XX_httplib_parse_http_headers( char **buf, struct mg_request_info *ri ) { int XX_httplib_parse_http_headers( char **buf, struct httplib_request_info *ri ) {
int i; int i;

View File

@@ -25,21 +25,21 @@
#include "httplib_main.h" #include "httplib_main.h"
/* /*
* int XX_httplib_parse_http_message( char *buf, int len, struct mg_request_info *ri ); * int XX_httplib_parse_http_message( char *buf, int len, struct httplib_request_info *ri );
* *
* The function XX_httplib_parse_http_message() parses an HTTP request and * The function XX_httplib_parse_http_message() parses an HTTP request and
* fills in the mg_request_info structure. This function modifies the buffer by * fills in the httplib_request_info structure. This function modifies the buffer by
* NUL terminating HTTP request components, header names and header values. * NUL terminating HTTP request components, header names and header values.
* Parameters: * Parameters:
* buf (in/out) pointer to the HTTP header to parse and split * buf (in/out) pointer to the HTTP header to parse and split
* len (in) length of the HTTP header buffer * len (in) length of the HTTP header buffer
* ri (out) parsed header as a mg_request_info structure * ri (out) parsed header as a httplib_request_info structure
* The parameters buf and ri must be valid pointers (not NULL) with a length * The parameters buf and ri must be valid pointers (not NULL) with a length
* larger than zero. On error the function return a negative value, otherwise * larger than zero. On error the function return a negative value, otherwise
* the length of the request is returned. * the length of the request is returned.
*/ */
int XX_httplib_parse_http_message( char *buf, int len, struct mg_request_info *ri ) { int XX_httplib_parse_http_message( char *buf, int len, struct httplib_request_info *ri ) {
int is_request; int is_request;
int request_length; int request_length;

View File

@@ -50,7 +50,7 @@ static void change_slashes_to_backslashes( char *path ) {
static int mg_wcscasecmp( const wchar_t *s1, const wchar_t *s2 ) { static int httplib_wcscasecmp( const wchar_t *s1, const wchar_t *s2 ) {
int diff; int diff;
@@ -62,19 +62,19 @@ static int mg_wcscasecmp( const wchar_t *s1, const wchar_t *s2 ) {
return diff; return diff;
} /* mg_wcscasecmp */ } /* httplib_wcscasecmp */
/* Encode 'path' which is assumed UTF-8 string, into UNICODE string. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
* wbuf and wbuf_len is a target buffer and its length. */ * wbuf and wbuf_len is a target buffer and its length. */
void XX_httplib_path_to_unicode( const struct mg_connection *conn, const char *path, wchar_t *wbuf, size_t wbuf_len ) { void XX_httplib_path_to_unicode( const struct httplib_connection *conn, const char *path, wchar_t *wbuf, size_t wbuf_len ) {
char buf[PATH_MAX]; char buf[PATH_MAX];
char buf2[PATH_MAX]; char buf2[PATH_MAX];
wchar_t wbuf2[MAX_PATH + 1]; wchar_t wbuf2[MAX_PATH + 1];
DWORD long_len; DWORD long_len;
DWORD err; DWORD err;
int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp; int (*fcompare)(const wchar_t *, const wchar_t *) = httplib_wcscasecmp;
XX_httplib_strlcpy(buf, path, sizeof(buf)); XX_httplib_strlcpy(buf, path, sizeof(buf));
change_slashes_to_backslashes(buf); change_slashes_to_backslashes(buf);

View File

@@ -29,7 +29,7 @@
#include "httplib_utils.h" #include "httplib_utils.h"
/* /*
* void XX_httplib_prepare_cgi_environment( struct mg_connection *conn, const char *prog, struct cgi_environment *env ); * void XX_httplib_prepare_cgi_environment( struct httplib_connection *conn, const char *prog, struct cgi_environment *env );
* *
* The function XX_httplib_prepare_cgi_environment() is used to prepare all * The function XX_httplib_prepare_cgi_environment() is used to prepare all
* environment variables before a CGI script is called. * environment variables before a CGI script is called.
@@ -37,7 +37,7 @@
#if !defined(NO_CGI) #if !defined(NO_CGI)
void XX_httplib_prepare_cgi_environment( struct mg_connection *conn, const char *prog, struct cgi_environment *env ) { void XX_httplib_prepare_cgi_environment( struct httplib_connection *conn, const char *prog, struct cgi_environment *env ) {
const char *s; const char *s;
struct vec var_vec; struct vec var_vec;
@@ -60,7 +60,7 @@ void XX_httplib_prepare_cgi_environment( struct mg_connection *conn, const char
XX_httplib_addenv( env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN] ); XX_httplib_addenv( env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN] );
XX_httplib_addenv( env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT] ); XX_httplib_addenv( env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT] );
XX_httplib_addenv( env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT] ); XX_httplib_addenv( env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT] );
XX_httplib_addenv( env, "SERVER_SOFTWARE=%s/%s", "LibHTTP", mg_version() ); XX_httplib_addenv( env, "SERVER_SOFTWARE=%s/%s", "LibHTTP", httplib_version() );
/* Prepare the environment block */ /* Prepare the environment block */
XX_httplib_addenv( env, "%s", "GATEWAY_INTERFACE=CGI/1.1" ); XX_httplib_addenv( env, "%s", "GATEWAY_INTERFACE=CGI/1.1" );
@@ -98,9 +98,9 @@ void XX_httplib_prepare_cgi_environment( struct mg_connection *conn, const char
XX_httplib_addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on"); XX_httplib_addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
if ( (s = mg_get_header( conn, "Content-Type" ) ) != NULL ) XX_httplib_addenv( env, "CONTENT_TYPE=%s", s ); if ( (s = httplib_get_header( conn, "Content-Type" ) ) != NULL ) XX_httplib_addenv( env, "CONTENT_TYPE=%s", s );
if ( conn->request_info.query_string != NULL ) XX_httplib_addenv( env, "QUERY_STRING=%s", conn->request_info.query_string ); if ( conn->request_info.query_string != NULL ) XX_httplib_addenv( env, "QUERY_STRING=%s", conn->request_info.query_string );
if ( (s = mg_get_header( conn, "Content-Length" ) ) != NULL ) XX_httplib_addenv( env, "CONTENT_LENGTH=%s", s ); if ( (s = httplib_get_header( conn, "Content-Length" ) ) != NULL ) XX_httplib_addenv( env, "CONTENT_LENGTH=%s", s );
if ( (s = getenv( "PATH" )) != NULL ) XX_httplib_addenv( env, "PATH=%s", s ); if ( (s = getenv( "PATH" )) != NULL ) XX_httplib_addenv( env, "PATH=%s", s );
if ( conn->path_info != NULL ) XX_httplib_addenv( env, "PATH_INFO=%s", conn->path_info ); if ( conn->path_info != NULL ) XX_httplib_addenv( env, "PATH_INFO=%s", conn->path_info );
@@ -132,7 +132,7 @@ void XX_httplib_prepare_cgi_environment( struct mg_connection *conn, const char
XX_httplib_snprintf(conn, &truncated, http_var_name, sizeof(http_var_name), "HTTP_%s", conn->request_info.http_headers[i].name); XX_httplib_snprintf(conn, &truncated, http_var_name, sizeof(http_var_name), "HTTP_%s", conn->request_info.http_headers[i].name);
if (truncated) { if (truncated) {
mg_cry(conn, "%s: HTTP header variable too long [%s]", __func__, conn->request_info.http_headers[i].name); httplib_cry(conn, "%s: HTTP header variable too long [%s]", __func__, conn->request_info.http_headers[i].name);
continue; continue;
} }

View File

@@ -52,9 +52,9 @@ void XX_httplib_print_dir_entry( struct de *de ) {
XX_httplib_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod)); XX_httplib_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
mod[sizeof(mod) - 1] = '\0'; mod[sizeof(mod) - 1] = '\0';
} }
mg_url_encode(de->file_name, href, sizeof(href)); httplib_url_encode(de->file_name, href, sizeof(href));
de->conn->num_bytes_sent += de->conn->num_bytes_sent +=
mg_printf(de->conn, httplib_printf(de->conn,
"<tr><td><a href=\"%s%s%s\">%s%s</a></td>" "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
"<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n", "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
de->conn->request_info.local_uri, de->conn->request_info.local_uri,

View File

@@ -25,7 +25,7 @@
#include "httplib_main.h" #include "httplib_main.h"
#include "httplib_string.h" #include "httplib_string.h"
int mg_printf( struct mg_connection *conn, const char *fmt, ... ) { int httplib_printf( struct httplib_connection *conn, const char *fmt, ... ) {
va_list ap; va_list ap;
int result; int result;
@@ -36,4 +36,4 @@ int mg_printf( struct mg_connection *conn, const char *fmt, ... ) {
return result; return result;
} /* mg_printf */ } /* httplib_printf */

View File

@@ -27,17 +27,17 @@
#include "httplib_string.h" #include "httplib_string.h"
/* /*
* void XX_httplib_process_new_connection( struct mg_connection *conn ); * void XX_httplib_process_new_connection( struct httplib_connection *conn );
* *
* The function XX_httplib_process_new_connection() is used to process a new * The function XX_httplib_process_new_connection() is used to process a new
* incoming connection on a socket. * incoming connection on a socket.
*/ */
void XX_httplib_process_new_connection( struct mg_connection *conn ) { void XX_httplib_process_new_connection( struct httplib_connection *conn ) {
if ( conn == NULL || conn->ctx == NULL ) return; if ( conn == NULL || conn->ctx == NULL ) return;
struct mg_request_info *ri = &conn->request_info; struct httplib_request_info *ri = &conn->request_info;
int keep_alive_enabled; int keep_alive_enabled;
int keep_alive; int keep_alive;
int discard_len; int discard_len;

View File

@@ -26,14 +26,14 @@
#include "httplib_pthread.h" #include "httplib_pthread.h"
/* /*
* void XX_httplib_produce_socket( struct mg_context *ctx, const struct socket *sp ); * void XX_httplib_produce_socket( struct httplib_context *ctx, const struct socket *sp );
* *
* The function XX_httplib_produce_socket() is used to produce a socket. * The function XX_httplib_produce_socket() is used to produce a socket.
*/ */
#if defined(ALTERNATIVE_QUEUE) #if defined(ALTERNATIVE_QUEUE)
void XX_httplib_produce_socket( struct mg_context *ctx, const struct socket *sp ) { void XX_httplib_produce_socket( struct httplib_context *ctx, const struct socket *sp ) {
unsigned int i; unsigned int i;
@@ -48,7 +48,7 @@ void XX_httplib_produce_socket( struct mg_context *ctx, const struct socket *sp
} }
} }
/* queue is full */ /* queue is full */
mg_sleep(1); httplib_sleep(1);
} }
} /* XX_httplib_produce_socket */ } /* XX_httplib_produce_socket */
@@ -56,7 +56,7 @@ void XX_httplib_produce_socket( struct mg_context *ctx, const struct socket *sp
#else /* ALTERNATIVE_QUEUE */ #else /* ALTERNATIVE_QUEUE */
/* Master thread adds accepted socket to a queue */ /* Master thread adds accepted socket to a queue */
void XX_httplib_produce_socket(struct mg_context *ctx, const struct socket *sp) { void XX_httplib_produce_socket(struct httplib_context *ctx, const struct socket *sp) {
#define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue))) #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
if (!ctx) return; if (!ctx) return;

View File

@@ -28,7 +28,7 @@
/* Read from IO channel - opened file descriptor, socket, or SSL descriptor. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
* Return negative value on error, or number of bytes read on success. */ * Return negative value on error, or number of bytes read on success. */
int XX_httplib_pull( FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout ) { int XX_httplib_pull( FILE *fp, struct httplib_connection *conn, char *buf, int len, double timeout ) {
int nread; int nread;
int err; int err;

View File

@@ -24,7 +24,7 @@
#include "httplib_main.h" #include "httplib_main.h"
int XX_httplib_pull_all( FILE *fp, struct mg_connection *conn, char *buf, int len ) { int XX_httplib_pull_all( FILE *fp, struct httplib_connection *conn, char *buf, int len ) {
int n; int n;
int nread = 0; int nread = 0;

Some files were not shown because too many files have changed in this diff Show More