1
0
mirror of https://github.com/lammertb/libhttp.git synced 2025-07-31 08:24:23 +03:00

Normallized coding style in a predictable way.

Uses astyle program which is freely avaiable on all platforms.
This commit is contained in:
Thomas Davis
2013-09-01 12:55:53 -04:00
parent 3f9ded0d6d
commit b745f22107
17 changed files with 5871 additions and 5482 deletions

View File

@ -207,4 +207,10 @@ $(BUILD_DIR)/%.o : %.cpp
$(BUILD_DIR)/%.o : %.c $(BUILD_DIR)/%.o : %.c
$(CC) -c $(CFLAGS) $< -o $@ $(CC) -c $(CFLAGS) $< -o $@
# This rules is used to keep the code formatted in a reasonable manor
# For this to work astyle must be installed and in the path
# http://sourceforge.net/projects/astyle
indent:
astyle --suffix=none --style=linux --indent=spaces=4 --lineend=linux include/*.h src/*.c src/*.cpp src/*.inl examples/*/*.c examples/*/*.cpp
.PHONY: all help build install clean lib so .PHONY: all help build install clean lib so

View File

@ -21,6 +21,7 @@ Changes
- Added CivetServer::getHeader method (Hariprasad Kamath) - Added CivetServer::getHeader method (Hariprasad Kamath)
- Added new basic C embedding example - Added new basic C embedding example
- Conformed source files to UNIX line endings for consistency. - Conformed source files to UNIX line endings for consistency.
- Unified the coding style to improve reability.
Release Notes v1.3 Release Notes v1.3
=== ===

View File

@ -54,7 +54,8 @@ 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 mg_connection *conn)
{
int i; int i;
const char *cookie = mg_get_header(conn, "Cookie"); const char *cookie = mg_get_header(conn, "Cookie");
char session_id[33]; char session_id[33];
@ -71,7 +72,8 @@ static struct session *get_session(const struct mg_connection *conn) {
} }
static void get_qsvar(const struct mg_request_info *request_info, static void get_qsvar(const struct mg_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); mg_get_var(qs, strlen(qs == NULL ? "" : qs), name, dst, dst_len);
} }
@ -80,7 +82,8 @@ static void get_qsvar(const struct mg_request_info *request_info,
// into a JSON string. Return that string to the caller. The string is // into a JSON string. Return that string to the caller. The string is
// dynamically allocated, caller must free it. If there are no messages, // dynamically allocated, caller must free it. If there are no messages,
// NULL is returned. // NULL is returned.
static char *messages_to_json(long last_id) { static char *messages_to_json(long last_id)
{
const struct message *message; const struct message *message;
int max_msgs, len; int max_msgs, len;
char buf[sizeof(messages)]; // Large enough to hold all messages char buf[sizeof(messages)]; // Large enough to hold all messages
@ -116,7 +119,8 @@ static char *messages_to_json(long last_id) {
// 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 mg_connection *conn,
const struct mg_request_info *request_info) { const struct mg_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));
@ -130,7 +134,8 @@ 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 mg_connection *conn,
const struct mg_request_info *request_info) { const struct mg_request_info *request_info)
{
char last_id[32], *json; char last_id[32], *json;
int is_jsonp; int is_jsonp;
@ -149,7 +154,8 @@ static void ajax_get_messages(struct mg_connection *conn,
} }
// Allocate new message. Caller must hold the lock. // Allocate new message. Caller must hold the lock.
static struct message *new_message(void) { static struct message *new_message(void)
{
static int size = sizeof(messages) / sizeof(messages[0]); static int size = sizeof(messages) / sizeof(messages[0]);
struct message *message = &messages[last_message_id % size]; struct message *message = &messages[last_message_id % size];
message->id = last_message_id++; message->id = last_message_id++;
@ -157,14 +163,16 @@ static struct message *new_message(void) {
return message; return message;
} }
static void my_strlcpy(char *dst, const char *src, size_t len) { static void my_strlcpy(char *dst, const char *src, size_t len)
{
strncpy(dst, src, len); strncpy(dst, src, len);
dst[len - 1] = '\0'; dst[len - 1] = '\0';
} }
// 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 mg_connection *conn,
const struct mg_request_info *request_info) { const struct mg_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];
@ -197,7 +205,8 @@ static void ajax_send_message(struct mg_connection *conn,
// 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 mg_connection *conn,
const struct mg_request_info *request_info) { const struct mg_request_info *request_info)
{
mg_printf(conn, "HTTP/1.1 302 Found\r\n" mg_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",
@ -205,7 +214,8 @@ static void redirect_to_login(struct mg_connection *conn,
} }
// Return 1 if username/password is allowed, 0 otherwise. // Return 1 if username/password is allowed, 0 otherwise.
static int check_password(const char *user, const char *password) { static int check_password(const char *user, const char *password)
{
// In production environment we should ask an authentication system // In production environment we should ask an authentication system
// to authenticate the user. // to authenticate the user.
// Here however we do trivial check that user and password are not empty // Here however we do trivial check that user and password are not empty
@ -213,7 +223,8 @@ static int check_password(const char *user, const char *password) {
} }
// Allocate new session object // Allocate new session object
static struct session *new_session(void) { static struct session *new_session(void)
{
int i; int i;
time_t now = time(NULL); time_t now = time(NULL);
pthread_rwlock_wrlock(&rwlock); pthread_rwlock_wrlock(&rwlock);
@ -231,11 +242,13 @@ static struct session *new_session(void) {
// Note that it is easy to steal session cookies by sniffing traffic. // Note that it is easy to steal session cookies by sniffing traffic.
// This is why all communication must be SSL-ed. // This is why all communication must be SSL-ed.
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); mg_md5(buf, random, user, NULL);
} }
static void send_server_message(const char *fmt, ...) { static void send_server_message(const char *fmt, ...)
{
va_list ap; va_list ap;
struct message *message; struct message *message;
@ -252,7 +265,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 mg_connection *conn,
const struct mg_request_info *request_info) { const struct mg_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 +304,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 mg_connection *conn,
const struct mg_request_info *request_info) { const struct mg_request_info *request_info)
{
struct session *session; struct session *session;
char valid_id[33]; char valid_id[33];
int authorized = 0; int authorized = 0;
@ -315,7 +330,8 @@ static int is_authorized(const struct mg_connection *conn,
} }
static void redirect_to_ssl(struct mg_connection *conn, static void redirect_to_ssl(struct mg_connection *conn,
const struct mg_request_info *request_info) { const struct mg_request_info *request_info)
{
const char *p, *host = mg_get_header(conn, "Host"); const char *p, *host = mg_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" mg_printf(conn, "HTTP/1.1 302 Found\r\n"
@ -326,7 +342,8 @@ static void redirect_to_ssl(struct mg_connection *conn,
} }
} }
static int begin_request_handler(struct mg_connection *conn) { static int begin_request_handler(struct mg_connection *conn)
{
const struct mg_request_info *request_info = mg_get_request_info(conn); const struct mg_request_info *request_info = mg_get_request_info(conn);
int processed = 1; int processed = 1;
@ -356,7 +373,8 @@ static const char *options[] = {
NULL NULL
}; };
int main(void) { int main(void)
{
struct mg_callbacks callbacks; struct mg_callbacks callbacks;
struct mg_context *ctx; struct mg_context *ctx;

View File

@ -21,7 +21,8 @@
#define EXIT_URI "/exit" #define EXIT_URI "/exit"
int exitNow = 0; int exitNow = 0;
int ExampleHandler(struct mg_connection *conn, void *cbdata) { int ExampleHandler(struct mg_connection *conn, void *cbdata)
{
mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"); mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
mg_printf(conn, "<html><body>"); mg_printf(conn, "<html><body>");
mg_printf(conn, "<h2>This is example text!!!</h2>"); mg_printf(conn, "<h2>This is example text!!!</h2>");
@ -31,14 +32,16 @@ int ExampleHandler(struct mg_connection *conn, void *cbdata) {
return 1; return 1;
} }
int ExitHandler(struct mg_connection *conn, void *cbdata) { int ExitHandler(struct mg_connection *conn, void *cbdata)
{
mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n"); mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n");
mg_printf(conn, "Bye!\n"); mg_printf(conn, "Bye!\n");
exitNow = 1; exitNow = 1;
return 1; return 1;
} }
int AHandler(struct mg_connection *conn, void *cbdata) { int AHandler(struct mg_connection *conn, void *cbdata)
{
mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"); mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
mg_printf(conn, "<html><body>"); mg_printf(conn, "<html><body>");
mg_printf(conn, "<h2>This is the A handler!!!</h2>"); mg_printf(conn, "<h2>This is the A handler!!!</h2>");
@ -46,7 +49,8 @@ int AHandler(struct mg_connection *conn, void *cbdata) {
return 1; return 1;
} }
int ABHandler(struct mg_connection *conn, void *cbdata) { int ABHandler(struct mg_connection *conn, void *cbdata)
{
mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"); mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
mg_printf(conn, "<html><body>"); mg_printf(conn, "<html><body>");
mg_printf(conn, "<h2>This is the AB handler!!!</h2>"); mg_printf(conn, "<h2>This is the AB handler!!!</h2>");
@ -55,10 +59,12 @@ int ABHandler(struct mg_connection *conn, void *cbdata) {
} }
int main(int argc, char *argv[]) { int main(int argc, char *argv[])
{
const char * options[] = { "document_root", DOCUMENT_ROOT, const char * options[] = { "document_root", DOCUMENT_ROOT,
"listening_ports", PORT, 0 }; "listening_ports", PORT, 0
};
struct mg_callbacks callbacks; struct mg_callbacks callbacks;
struct mg_context *ctx; struct mg_context *ctx;

View File

@ -17,7 +17,8 @@
#define EXIT_URI "/exit" #define EXIT_URI "/exit"
bool exitNow = false; bool exitNow = false;
class ExampleHandler: public CivetHandler { class ExampleHandler: public CivetHandler
{
public: public:
bool handleGet(CivetServer *server, struct mg_connection *conn) { bool handleGet(CivetServer *server, struct mg_connection *conn) {
mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"); mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
@ -30,7 +31,8 @@ public:
} }
}; };
class ExitHandler: public CivetHandler { class ExitHandler: public CivetHandler
{
public: public:
bool handleGet(CivetServer *server, struct mg_connection *conn) { bool handleGet(CivetServer *server, struct mg_connection *conn) {
mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n"); mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n");
@ -40,7 +42,8 @@ public:
} }
}; };
class AHandler: public CivetHandler { class AHandler: public CivetHandler
{
public: public:
bool handleGet(CivetServer *server, struct mg_connection *conn) { bool handleGet(CivetServer *server, struct mg_connection *conn) {
mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"); mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
@ -51,7 +54,8 @@ public:
} }
}; };
class ABHandler: public CivetHandler { class ABHandler: public CivetHandler
{
public: public:
bool handleGet(CivetServer *server, struct mg_connection *conn) { bool handleGet(CivetServer *server, struct mg_connection *conn) {
mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"); mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n");
@ -62,10 +66,12 @@ public:
} }
}; };
int main(int argc, char *argv[]) { int main(int argc, char *argv[])
{
const char * options[] = { "document_root", DOCUMENT_ROOT, const char * options[] = { "document_root", DOCUMENT_ROOT,
"listening_ports", PORT, 0 }; "listening_ports", PORT, 0
};
CivetServer server(options); CivetServer server(options);

View File

@ -3,7 +3,8 @@
#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 mg_connection *conn)
{
const struct mg_request_info *request_info = mg_get_request_info(conn); const struct mg_request_info *request_info = mg_get_request_info(conn);
char content[100]; char content[100];
@ -26,7 +27,8 @@ static int begin_request_handler(struct mg_connection *conn) {
return 1; return 1;
} }
int main(void) { int main(void)
{
struct mg_context *ctx; struct mg_context *ctx;
struct mg_callbacks callbacks; struct mg_callbacks callbacks;

View File

@ -3,13 +3,15 @@
#include "lua.h" #include "lua.h"
#include "lauxlib.h" #include "lauxlib.h"
static int smile(lua_State *L) { static int smile(lua_State *L)
{
(void) L; // Unused (void) L; // Unused
printf("%s\n", ":-)"); printf("%s\n", ":-)");
return 0; return 0;
} }
int LUA_API luaopen_lua_dll(lua_State *L) { int LUA_API luaopen_lua_dll(lua_State *L)
{
static const struct luaL_Reg api[] = { static const struct luaL_Reg api[] = {
{"smile", smile}, {"smile", smile},
{NULL, NULL}, {NULL, NULL},

View File

@ -10,7 +10,8 @@ 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 mg_connection *conn)
{
const struct mg_request_info *ri = mg_get_request_info(conn); const struct mg_request_info *ri = mg_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;
@ -41,7 +42,8 @@ static int begin_request_handler(struct mg_connection *conn) {
return 1; // Mark request as processed return 1; // Mark request as processed
} }
int main(void) { int main(void)
{
struct mg_context *ctx; struct mg_context *ctx;
const char *options[] = {"listening_ports", "8080", NULL}; const char *options[] = {"listening_ports", "8080", NULL};
struct mg_callbacks callbacks; struct mg_callbacks callbacks;

View File

@ -17,7 +17,8 @@ typedef __int64 int64_t;
#include "civetweb.h" #include "civetweb.h"
static int begin_request_handler(struct mg_connection *conn) { static int begin_request_handler(struct mg_connection *conn)
{
if (!strcmp(mg_get_request_info(conn)->uri, "/handle_post_request")) { if (!strcmp(mg_get_request_info(conn)->uri, "/handle_post_request")) {
mg_printf(conn, "%s", "HTTP/1.0 200 OK\r\n\r\n"); mg_printf(conn, "%s", "HTTP/1.0 200 OK\r\n\r\n");
mg_upload(conn, "/tmp"); mg_upload(conn, "/tmp");
@ -41,11 +42,13 @@ static int begin_request_handler(struct mg_connection *conn) {
return 1; return 1;
} }
static void upload_handler(struct mg_connection *conn, const char *path) { static void upload_handler(struct mg_connection *conn, const char *path)
{
mg_printf(conn, "Saved [%s]", path); mg_printf(conn, "Saved [%s]", path);
} }
int main(void) { int main(void)
{
struct mg_context *ctx; struct mg_context *ctx;
const char *options[] = {"listening_ports", "8080", NULL}; const char *options[] = {"listening_ports", "8080", NULL};
struct mg_callbacks callbacks; struct mg_callbacks callbacks;

View File

@ -5,7 +5,8 @@
#include <string.h> #include <string.h>
#include "civetweb.h" #include "civetweb.h"
static void websocket_ready_handler(struct mg_connection *conn) { static void websocket_ready_handler(struct mg_connection *conn)
{
static const char *message = "server ready"; static const char *message = "server ready";
mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, message, strlen(message)); mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, message, strlen(message));
} }
@ -15,7 +16,8 @@ static void websocket_ready_handler(struct mg_connection *conn) {
// 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 mg_connection *conn, int flags,
char *data, size_t data_len) { char *data, size_t data_len)
{
(void) flags; // Unused (void) flags; // Unused
mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, data, data_len); mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, data, data_len);
@ -24,7 +26,8 @@ static int websocket_data_handler(struct mg_connection *conn, int flags,
return memcmp(data, "exit", 4); return memcmp(data, "exit", 4);
} }
int main(void) { int main(void)
{
struct mg_context *ctx; struct mg_context *ctx;
struct mg_callbacks callbacks; struct mg_callbacks callbacks;
const char *options[] = { const char *options[] = {

View File

@ -17,7 +17,8 @@ class CivetServer; // forward declaration
* Basic interface for a URI request handler. Handlers implementations * Basic interface for a URI request handler. Handlers implementations
* must be reentrant. * must be reentrant.
*/ */
class CivetHandler { class CivetHandler
{
public: public:
/** /**
@ -69,7 +70,8 @@ public:
* *
* Basic class for embedded web server. This has a URL mapping built-in. * Basic class for embedded web server. This has a URL mapping built-in.
*/ */
class CivetServer { class CivetServer
{
public: public:
/** /**

View File

@ -10,34 +10,39 @@
#include <assert.h> #include <assert.h>
#ifndef UNUSED_PARAMETER #ifndef UNUSED_PARAMETER
#define UNUSED_PARAMETER(x) (void)(x) #define UNUSED_PARAMETER(x) (void)(x)
#endif #endif
bool CivetHandler::handleGet(CivetServer *server, struct mg_connection *conn) { bool CivetHandler::handleGet(CivetServer *server, struct mg_connection *conn)
{
UNUSED_PARAMETER(server); UNUSED_PARAMETER(server);
UNUSED_PARAMETER(conn); UNUSED_PARAMETER(conn);
return false; return false;
} }
bool CivetHandler::handlePost(CivetServer *server, struct mg_connection *conn) { bool CivetHandler::handlePost(CivetServer *server, struct mg_connection *conn)
{
UNUSED_PARAMETER(server); UNUSED_PARAMETER(server);
UNUSED_PARAMETER(conn); UNUSED_PARAMETER(conn);
return false; return false;
} }
bool CivetHandler::handlePut(CivetServer *server, struct mg_connection *conn) { bool CivetHandler::handlePut(CivetServer *server, struct mg_connection *conn)
{
UNUSED_PARAMETER(server); UNUSED_PARAMETER(server);
UNUSED_PARAMETER(conn); UNUSED_PARAMETER(conn);
return false; return false;
} }
bool CivetHandler::handleDelete(CivetServer *server, struct mg_connection *conn) { bool CivetHandler::handleDelete(CivetServer *server, struct mg_connection *conn)
{
UNUSED_PARAMETER(server); UNUSED_PARAMETER(server);
UNUSED_PARAMETER(conn); UNUSED_PARAMETER(conn);
return false; return false;
} }
int CivetServer::requestHandler(struct mg_connection *conn, void *cbdata) { int CivetServer::requestHandler(struct mg_connection *conn, void *cbdata)
{
struct mg_request_info *request_info = mg_get_request_info(conn); struct mg_request_info *request_info = mg_get_request_info(conn);
CivetServer *me = (CivetServer*) (request_info->user_data); CivetServer *me = (CivetServer*) (request_info->user_data);
CivetHandler *handler = (CivetHandler *)cbdata; CivetHandler *handler = (CivetHandler *)cbdata;
@ -60,7 +65,8 @@ int CivetServer::requestHandler(struct mg_connection *conn, void *cbdata) {
CivetServer::CivetServer(const char **options, CivetServer::CivetServer(const char **options,
const struct mg_callbacks *_callbacks) : const struct mg_callbacks *_callbacks) :
context(0) { context(0)
{
if (_callbacks) { if (_callbacks) {
@ -72,19 +78,23 @@ CivetServer::CivetServer(const char **options,
} }
} }
CivetServer::~CivetServer() { CivetServer::~CivetServer()
{
close(); close();
} }
void CivetServer::addHandler(const std::string &uri, CivetHandler *handler) { void CivetServer::addHandler(const std::string &uri, CivetHandler *handler)
{
mg_set_request_handler(context, uri.c_str(), requestHandler, handler); mg_set_request_handler(context, uri.c_str(), requestHandler, handler);
} }
void CivetServer::removeHandler(const std::string &uri) { void CivetServer::removeHandler(const std::string &uri)
{
mg_set_request_handler(context, uri.c_str(), NULL, NULL); mg_set_request_handler(context, uri.c_str(), NULL, NULL);
} }
void CivetServer::close() { void CivetServer::close()
{
if (context) { if (context) {
mg_stop (context); mg_stop (context);
context = 0; context = 0;
@ -108,12 +118,14 @@ const char* CivetServer::getHeader(struct mg_connection *conn, const std::string
} }
void void
CivetServer::urlDecode(const char *src, std::string &dst, bool is_form_url_encoded) { CivetServer::urlDecode(const char *src, std::string &dst, bool is_form_url_encoded)
{
urlDecode(src, strlen(src), dst, is_form_url_encoded); urlDecode(src, strlen(src), dst, is_form_url_encoded);
} }
void void
CivetServer::urlDecode(const char *src, size_t src_len, std::string &dst, bool is_form_url_encoded) { CivetServer::urlDecode(const char *src, size_t src_len, std::string &dst, bool is_form_url_encoded)
{
int i, j, a, b; int i, j, a, b;
#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W') #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
@ -136,14 +148,16 @@ CivetServer::urlDecode(const char *src, size_t src_len, std::string &dst, bool i
bool bool
CivetServer::getParam(struct mg_connection *conn, const char *name, CivetServer::getParam(struct mg_connection *conn, const char *name,
std::string &dst, size_t occurrence) { std::string &dst, size_t occurrence)
{
const char *query = mg_get_request_info(conn)->query_string; const char *query = mg_get_request_info(conn)->query_string;
return getParam(query, strlen(query), name, dst, occurrence); return getParam(query, strlen(query), name, dst, occurrence);
} }
bool bool
CivetServer::getParam(const char *data, size_t data_len, const char *name, CivetServer::getParam(const char *data, size_t data_len, const char *name,
std::string &dst, size_t occurrence) { std::string &dst, size_t occurrence)
{
const char *p, *e, *s; const char *p, *e, *s;
size_t name_len; size_t name_len;
@ -178,12 +192,14 @@ CivetServer::getParam(const char *data, size_t data_len, const char *name,
} }
void void
CivetServer::urlEncode(const char *src, std::string &dst, bool append) { CivetServer::urlEncode(const char *src, std::string &dst, bool append)
{
urlEncode(src, strlen(src), dst, append); urlEncode(src, strlen(src), dst, append);
} }
void void
CivetServer::urlEncode(const char *src, size_t src_len, std::string &dst, bool append) { CivetServer::urlEncode(const char *src, size_t src_len, std::string &dst, bool append)
{
static const char *dont_escape = "._-$,;~()"; static const char *dont_escape = "._-$,;~()";
static const char *hex = "0123456789abcdef"; static const char *hex = "0123456789abcdef";

File diff suppressed because it is too large Load Diff

View File

@ -81,11 +81,13 @@ static struct mg_context *ctx; // Set by start_civetweb()
#define CONFIG_FILE2 "/usr/local/etc/civetweb.conf" #define CONFIG_FILE2 "/usr/local/etc/civetweb.conf"
#endif #endif
static void WINCDECL signal_handler(int sig_num) { static void WINCDECL signal_handler(int sig_num)
{
exit_flag = sig_num; exit_flag = sig_num;
} }
static void die(const char *fmt, ...) { static void die(const char *fmt, ...)
{
va_list ap; va_list ap;
char msg[200]; char msg[200];
@ -102,7 +104,8 @@ static void die(const char *fmt, ...) {
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
static void show_usage_and_exit(void) { static void show_usage_and_exit(void)
{
const char **names; const char **names;
int i; int i;
@ -124,14 +127,15 @@ static void show_usage_and_exit(void) {
#if defined(_WIN32) || defined(USE_COCOA) #if defined(_WIN32) || defined(USE_COCOA)
static const char *config_file_top_comment = static const char *config_file_top_comment =
"# Civetweb web server configuration file.\n" "# Civetweb web server configuration file.\n"
"# For detailed description of every option, visit\n" "# For detailed description of every option, visit\n"
"# https://github.com/sunsetbrew/civetweb/blob/master/docs/UserManual.md\n" "# https://github.com/sunsetbrew/civetweb/blob/master/docs/UserManual.md\n"
"# Lines starting with '#' and empty lines are ignored.\n" "# Lines starting with '#' and empty lines are ignored.\n"
"# To make a change, remove leading '#', modify option's value,\n" "# To make a change, remove leading '#', modify option's value,\n"
"# save this file and then restart Civetweb.\n\n"; "# save this file and then restart Civetweb.\n\n";
static const char *get_url_to_first_open_port(const struct mg_context *ctx) { static const char *get_url_to_first_open_port(const struct mg_context *ctx)
{
static char url[100]; static char url[100];
const char *open_ports = mg_get_option(ctx, "listening_ports"); const char *open_ports = mg_get_option(ctx, "listening_ports");
int a, b, c, d, port, n; int a, b, c, d, port, n;
@ -149,7 +153,8 @@ static const char *get_url_to_first_open_port(const struct mg_context *ctx) {
return url; return url;
} }
static void create_config_file(const char *path) { static void create_config_file(const char *path)
{
const char **names, *value; const char **names, *value;
FILE *fp; FILE *fp;
int i; int i;
@ -169,7 +174,8 @@ static void create_config_file(const char *path) {
} }
#endif #endif
static char *sdup(const char *str) { static char *sdup(const char *str)
{
char *p; char *p;
if ((p = (char *) malloc(strlen(str) + 1)) != NULL) { if ((p = (char *) malloc(strlen(str) + 1)) != NULL) {
strcpy(p, str); strcpy(p, str);
@ -177,7 +183,8 @@ static char *sdup(const char *str) {
return p; return p;
} }
static void set_option(char **options, const char *name, const char *value) { static void set_option(char **options, const char *name, const char *value)
{
int i; int i;
for (i = 0; i < MAX_OPTIONS - 3; i++) { for (i = 0; i < MAX_OPTIONS - 3; i++) {
@ -198,7 +205,8 @@ static void set_option(char **options, const char *name, const char *value) {
} }
} }
static void process_command_line_arguments(char *argv[], char **options) { static void process_command_line_arguments(char *argv[], char **options)
{
char line[MAX_CONF_FILE_LINE_SIZE], opt[sizeof(line)], val[sizeof(line)], *p; char line[MAX_CONF_FILE_LINE_SIZE], opt[sizeof(line)], val[sizeof(line)], *p;
FILE *fp = NULL; FILE *fp = NULL;
size_t i, cmd_line_opts_start = 1, line_no = 0; size_t i, cmd_line_opts_start = 1, line_no = 0;
@ -272,18 +280,21 @@ static void process_command_line_arguments(char *argv[], char **options) {
} }
} }
static void init_server_name(void) { static void init_server_name(void)
{
snprintf(server_name, sizeof(server_name), "Civetweb v%s", snprintf(server_name, sizeof(server_name), "Civetweb v%s",
mg_version()); mg_version());
} }
static int log_message(const struct mg_connection *conn, const char *message) { static int log_message(const struct mg_connection *conn, const char *message)
{
(void) conn; (void) conn;
printf("%s\n", message); printf("%s\n", message);
return 0; return 0;
} }
static int is_path_absolute(const char *path) { static int is_path_absolute(const char *path)
{
#ifdef _WIN32 #ifdef _WIN32
return path != NULL && return path != NULL &&
((path[0] == '\\' && path[1] == '\\') || // UNC path, e.g. \\server\dir ((path[0] == '\\' && path[1] == '\\') || // UNC path, e.g. \\server\dir
@ -293,7 +304,8 @@ static int is_path_absolute(const char *path) {
#endif #endif
} }
static char *get_option(char **options, const char *option_name) { static char *get_option(char **options, const char *option_name)
{
int i; int i;
for (i = 0; options[i] != NULL; i++) for (i = 0; options[i] != NULL; i++)
@ -304,7 +316,8 @@ static char *get_option(char **options, const char *option_name) {
} }
static void verify_existence(char **options, const char *option_name, static void verify_existence(char **options, const char *option_name,
int must_be_dir) { int must_be_dir)
{
struct stat st; struct stat st;
const char *path = get_option(options, option_name); const char *path = get_option(options, option_name);
@ -317,7 +330,8 @@ static void verify_existence(char **options, const char *option_name,
} }
static void set_absolute_path(char *options[], const char *option_name, static void set_absolute_path(char *options[], const char *option_name,
const char *path_to_civetweb_exe) { const char *path_to_civetweb_exe)
{
char path[PATH_MAX], abs[PATH_MAX], *option_value; char path[PATH_MAX], abs[PATH_MAX], *option_value;
const char *p; const char *p;
@ -346,7 +360,8 @@ static void set_absolute_path(char *options[], const char *option_name,
} }
} }
static void start_civetweb(int argc, char *argv[]) { static void start_civetweb(int argc, char *argv[])
{
struct mg_callbacks callbacks; struct mg_callbacks callbacks;
char *options[MAX_OPTIONS]; char *options[MAX_OPTIONS];
int i; int i;
@ -423,7 +438,8 @@ static SERVICE_STATUS_HANDLE hStatus;
static const char *service_magic_argument = "--"; static const char *service_magic_argument = "--";
static NOTIFYICONDATA TrayIcon; static NOTIFYICONDATA TrayIcon;
static void WINAPI ControlHandler(DWORD code) { static void WINAPI ControlHandler(DWORD code)
{
if (code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN) { if (code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN) {
ss.dwWin32ExitCode = 0; ss.dwWin32ExitCode = 0;
ss.dwCurrentState = SERVICE_STOPPED; ss.dwCurrentState = SERVICE_STOPPED;
@ -431,7 +447,8 @@ static void WINAPI ControlHandler(DWORD code) {
SetServiceStatus(hStatus, &ss); SetServiceStatus(hStatus, &ss);
} }
static void WINAPI ServiceMain(void) { static void WINAPI ServiceMain(void)
{
ss.dwServiceType = SERVICE_WIN32; ss.dwServiceType = SERVICE_WIN32;
ss.dwCurrentState = SERVICE_RUNNING; ss.dwCurrentState = SERVICE_RUNNING;
ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
@ -450,7 +467,8 @@ static void WINAPI ServiceMain(void) {
} }
static void show_error(void) { static void show_error(void)
{
char buf[256]; char buf[256];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, GetLastError(), NULL, GetLastError(),
@ -459,19 +477,22 @@ static void show_error(void) {
MessageBox(NULL, buf, "Error", MB_OK); MessageBox(NULL, buf, "Error", MB_OK);
} }
static void *align(void *ptr, DWORD alig) { static void *align(void *ptr, DWORD alig)
{
ULONG ul = (ULONG) ptr; ULONG ul = (ULONG) ptr;
ul += alig; ul += alig;
ul &= ~alig; ul &= ~alig;
return ((void *) ul); return ((void *) ul);
} }
static int is_boolean_option(const char *option_name) { static int is_boolean_option(const char *option_name)
{
return !strcmp(option_name, "enable_directory_listing") || return !strcmp(option_name, "enable_directory_listing") ||
!strcmp(option_name, "enable_keep_alive"); !strcmp(option_name, "enable_keep_alive");
} }
static int is_filename_option(const char *option_name) { static int is_filename_option(const char *option_name)
{
return !strcmp(option_name, "cgi_interpreter") || return !strcmp(option_name, "cgi_interpreter") ||
!strcmp(option_name, "global_auth_file") || !strcmp(option_name, "global_auth_file") ||
!strcmp(option_name, "put_delete_auth_file") || !strcmp(option_name, "put_delete_auth_file") ||
@ -480,15 +501,18 @@ static int is_filename_option(const char *option_name) {
!strcmp(option_name, "ssl_certificate"); !strcmp(option_name, "ssl_certificate");
} }
static int is_directory_option(const char *option_name) { static int is_directory_option(const char *option_name)
{
return !strcmp(option_name, "document_root"); return !strcmp(option_name, "document_root");
} }
static int is_numeric_options(const char *option_name) { static int is_numeric_options(const char *option_name)
{
return !strcmp(option_name, "num_threads"); return !strcmp(option_name, "num_threads");
} }
static void save_config(HWND hDlg, FILE *fp) { static void save_config(HWND hDlg, FILE *fp)
{
char value[2000]; char value[2000];
const char **options, *name, *default_value; const char **options, *name, *default_value;
int i, id; int i, id;
@ -512,7 +536,8 @@ static void save_config(HWND hDlg, FILE *fp) {
} }
} }
static BOOL CALLBACK DlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP) { static BOOL CALLBACK DlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP)
{
FILE *fp; FILE *fp;
int i; int i;
const char *name, *value, **options = mg_get_valid_option_names(); const char *name, *value, **options = mg_get_valid_option_names();
@ -608,7 +633,8 @@ static BOOL CALLBACK DlgProc(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lP) {
static void add_control(unsigned char **mem, DLGTEMPLATE *dia, WORD type, static void add_control(unsigned char **mem, DLGTEMPLATE *dia, WORD type,
DWORD id, DWORD style, WORD x, WORD y, DWORD id, DWORD style, WORD x, WORD y,
WORD cx, WORD cy, const char *caption) { WORD cx, WORD cy, const char *caption)
{
DLGITEMTEMPLATE *tp; DLGITEMTEMPLATE *tp;
LPWORD p; LPWORD p;
@ -639,7 +665,8 @@ static void add_control(unsigned char **mem, DLGTEMPLATE *dia, WORD type,
*mem = (unsigned char *) p; *mem = (unsigned char *) p;
} }
static void show_settings_dialog() { static void show_settings_dialog()
{
#define HEIGHT 15 #define HEIGHT 15
#define WIDTH 400 #define WIDTH 400
#define LABEL_WIDTH 80 #define LABEL_WIDTH 80
@ -657,9 +684,12 @@ static void show_settings_dialog() {
wchar_t caption[1]; wchar_t caption[1];
WORD fontsiz; WORD fontsiz;
wchar_t fontface[7]; wchar_t fontface[7];
} dialog_header = {{WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE | } dialog_header = {{
DS_SETFONT | WS_DLGFRAME, WS_EX_TOOLWINDOW, 0, 200, 200, WIDTH, 0}, WS_CAPTION | WS_POPUP | WS_SYSMENU | WS_VISIBLE |
0, 0, L"", 8, L"Tahoma"}; DS_SETFONT | WS_DLGFRAME, WS_EX_TOOLWINDOW, 0, 200, 200, WIDTH, 0
},
0, 0, L"", 8, L"Tahoma"
};
if (guard == 0) { if (guard == 0) {
guard++; guard++;
@ -725,7 +755,8 @@ static void show_settings_dialog() {
guard--; guard--;
} }
static int manage_service(int action) { static int manage_service(int action)
{
static const char *service_name = "Civetweb"; static const char *service_name = "Civetweb";
SC_HANDLE hSCM = NULL, hService = NULL; SC_HANDLE hSCM = NULL, hService = NULL;
SERVICE_DESCRIPTION descr = {server_name}; SERVICE_DESCRIPTION descr = {server_name};
@ -766,7 +797,8 @@ static int manage_service(int action) {
} }
static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam, static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam,
LPARAM lParam) { LPARAM lParam)
{
static SERVICE_TABLE_ENTRY service_table[] = { static SERVICE_TABLE_ENTRY service_table[] = {
{server_name, (LPSERVICE_MAIN_FUNCTION) ServiceMain}, {server_name, (LPSERVICE_MAIN_FUNCTION) ServiceMain},
{NULL, NULL} {NULL, NULL}
@ -852,7 +884,8 @@ static LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam,
return DefWindowProc(hWnd, msg, wParam, lParam); return DefWindowProc(hWnd, msg, wParam, lParam);
} }
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show) { int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show)
{
WNDCLASS cls; WNDCLASS cls;
HWND hWnd; HWND hWnd;
MSG msg; MSG msg;
@ -890,7 +923,8 @@ int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show) {
#elif defined(USE_COCOA) #elif defined(USE_COCOA)
#import <Cocoa/Cocoa.h> #import <Cocoa/Cocoa.h>
@interface Civetweb : NSObject<NSApplicationDelegate> @interface Civetweb :
NSObject<NSApplicationDelegate>
- (void) openBrowser; - (void) openBrowser;
- (void) shutDown; - (void) shutDown;
@end @end
@ -898,21 +932,22 @@ int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmdline, int show) {
@implementation Civetweb @implementation Civetweb
- (void) openBrowser { - (void) openBrowser {
[[NSWorkspace sharedWorkspace] [[NSWorkspace sharedWorkspace]
openURL:[NSURL URLWithString: openURL:[NSURL URLWithString:
[NSString stringWithUTF8String:get_url_to_first_open_port(ctx)]]]; [NSString stringWithUTF8String:get_url_to_first_open_port(ctx)]]];
} }
- (void) editConfig { - (void) editConfig {
create_config_file(config_file); create_config_file(config_file);
[[NSWorkspace sharedWorkspace] [[NSWorkspace sharedWorkspace]
openFile:[NSString stringWithUTF8String:config_file] openFile:[NSString stringWithUTF8String:config_file]
withApplication:@"TextEdit"]; withApplication:@"TextEdit"];
} }
- (void)shutDown{ - (void)shutDown {
[NSApp terminate:nil]; [NSApp terminate:nil];
} }
@end @end
int main(int argc, char *argv[]) { int main(int argc, char *argv[])
{
init_server_name(); init_server_name();
start_civetweb(argc, argv); start_civetweb(argc, argv);
@ -921,7 +956,7 @@ int main(int argc, char *argv[]) {
// Add delegate to process menu item actions // Add delegate to process menu item actions
Civetweb *myDelegate = [[Civetweb alloc] autorelease]; Civetweb *myDelegate = [[Civetweb alloc] autorelease];
[NSApp setDelegate: myDelegate]; [NSApp setDelegate: myDelegate];
// Run this app as agent // Run this app as agent
ProcessSerialNumber psn = { 0, kCurrentProcess }; ProcessSerialNumber psn = { 0, kCurrentProcess };
@ -932,38 +967,38 @@ int main(int argc, char *argv[]) {
id menu = [[NSMenu new] autorelease]; id menu = [[NSMenu new] autorelease];
// Add version menu item // Add version menu item
[menu addItem:[[[NSMenuItem alloc] [menu addItem:[[[NSMenuItem alloc]
//initWithTitle:[NSString stringWithFormat:@"%s", server_name] //initWithTitle:[NSString stringWithFormat:@"%s", server_name]
initWithTitle:[NSString stringWithUTF8String:server_name] initWithTitle:[NSString stringWithUTF8String:server_name]
action:@selector(noexist) keyEquivalent:@""] autorelease]]; action:@selector(noexist) keyEquivalent:@""] autorelease]];
// Add configuration menu item // Add configuration menu item
[menu addItem:[[[NSMenuItem alloc] [menu addItem:[[[NSMenuItem alloc]
initWithTitle:@"Edit configuration" initWithTitle:@"Edit configuration"
action:@selector(editConfig) keyEquivalent:@""] autorelease]]; action:@selector(editConfig) keyEquivalent:@""] autorelease]];
// Add connect menu item // Add connect menu item
[menu addItem:[[[NSMenuItem alloc] [menu addItem:[[[NSMenuItem alloc]
initWithTitle:@"Open web root in a browser" initWithTitle:@"Open web root in a browser"
action:@selector(openBrowser) keyEquivalent:@""] autorelease]]; action:@selector(openBrowser) keyEquivalent:@""] autorelease]];
// Separator // Separator
[menu addItem:[NSMenuItem separatorItem]]; [menu addItem:[NSMenuItem separatorItem]];
// Add quit menu item // Add quit menu item
[menu addItem:[[[NSMenuItem alloc] [menu addItem:[[[NSMenuItem alloc]
initWithTitle:@"Quit" initWithTitle:@"Quit"
action:@selector(shutDown) keyEquivalent:@"q"] autorelease]]; action:@selector(shutDown) keyEquivalent:@"q"] autorelease]];
// Attach menu to the status bar // Attach menu to the status bar
id item = [[[NSStatusBar systemStatusBar] id item = [[[NSStatusBar systemStatusBar]
statusItemWithLength:NSVariableStatusItemLength] retain]; statusItemWithLength:NSVariableStatusItemLength] retain];
[item setHighlightMode:YES]; [item setHighlightMode:YES];
[item setImage:[NSImage imageNamed:@"civetweb_22x22.png"]]; [item setImage:[NSImage imageNamed:@"civetweb_22x22.png"]];
[item setMenu:menu]; [item setMenu:menu];
// Run the app // Run the app
[NSApp activateIgnoringOtherApps:YES]; [NSApp activateIgnoringOtherApps:YES];
[NSApp run]; [NSApp run];
mg_stop(ctx); mg_stop(ctx);
@ -971,7 +1006,8 @@ int main(int argc, char *argv[]) {
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }
#else #else
int main(int argc, char *argv[]) { int main(int argc, char *argv[])
{
init_server_name(); init_server_name();
start_civetweb(argc, argv); start_civetweb(argc, argv);
printf("%s started on port(s) %s with web root [%s]\n", printf("%s started on port(s) %s with web root [%s]\n",

View File

@ -3,7 +3,8 @@
#ifdef _WIN32 #ifdef _WIN32
static void *mmap(void *addr, int64_t len, int prot, int flags, int fd, static void *mmap(void *addr, int64_t len, int prot, int flags, int fd,
int offset) { int offset)
{
HANDLE fh = (HANDLE) _get_osfhandle(fd); HANDLE fh = (HANDLE) _get_osfhandle(fd);
HANDLE mh = CreateFileMapping(fh, 0, PAGE_READONLY, 0, 0, 0); HANDLE mh = CreateFileMapping(fh, 0, PAGE_READONLY, 0, 0, 0);
void *p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, (size_t) len); void *p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, (size_t) len);
@ -25,27 +26,31 @@ static void handle_request(struct mg_connection *);
static int handle_lsp_request(struct mg_connection *, const char *, static int handle_lsp_request(struct mg_connection *, const char *,
struct file *, struct lua_State *); struct file *, struct lua_State *);
static void reg_string(struct lua_State *L, const char *name, const char *val) { static void reg_string(struct lua_State *L, const char *name, const char *val)
{
lua_pushstring(L, name); lua_pushstring(L, name);
lua_pushstring(L, val); lua_pushstring(L, val);
lua_rawset(L, -3); lua_rawset(L, -3);
} }
static void reg_int(struct lua_State *L, const char *name, int val) { static void reg_int(struct lua_State *L, const char *name, int val)
{
lua_pushstring(L, name); lua_pushstring(L, name);
lua_pushinteger(L, val); lua_pushinteger(L, val);
lua_rawset(L, -3); lua_rawset(L, -3);
} }
static void reg_function(struct lua_State *L, const char *name, static void reg_function(struct lua_State *L, const char *name,
lua_CFunction func, struct mg_connection *conn) { lua_CFunction func, struct mg_connection *conn)
{
lua_pushstring(L, name); lua_pushstring(L, name);
lua_pushlightuserdata(L, conn); lua_pushlightuserdata(L, conn);
lua_pushcclosure(L, func, 1); lua_pushcclosure(L, func, 1);
lua_rawset(L, -3); lua_rawset(L, -3);
} }
static int lsp_sock_close(lua_State *L) { static int lsp_sock_close(lua_State *L)
{
if (lua_gettop(L) > 0 && lua_istable(L, -1)) { if (lua_gettop(L) > 0 && lua_istable(L, -1)) {
lua_getfield(L, -1, "sock"); lua_getfield(L, -1, "sock");
closesocket((SOCKET) lua_tonumber(L, -1)); closesocket((SOCKET) lua_tonumber(L, -1));
@ -55,7 +60,8 @@ static int lsp_sock_close(lua_State *L) {
return 1; return 1;
} }
static int lsp_sock_recv(lua_State *L) { static int lsp_sock_recv(lua_State *L)
{
char buf[2000]; char buf[2000];
int n; int n;
@ -73,7 +79,8 @@ static int lsp_sock_recv(lua_State *L) {
return 1; return 1;
} }
static int lsp_sock_send(lua_State *L) { static int lsp_sock_send(lua_State *L)
{
const char *buf; const char *buf;
size_t len, sent = 0; size_t len, sent = 0;
int n, sock; int n, sock;
@ -102,7 +109,8 @@ static const struct luaL_Reg luasocket_methods[] = {
{NULL, NULL} {NULL, NULL}
}; };
static int lsp_connect(lua_State *L) { static int lsp_connect(lua_State *L)
{
char ebuf[100]; char ebuf[100];
SOCKET sock; SOCKET sock;
@ -124,7 +132,8 @@ static int lsp_connect(lua_State *L) {
return 1; return 1;
} }
static int lsp_error(lua_State *L) { static int lsp_error(lua_State *L)
{
lua_getglobal(L, "mg"); lua_getglobal(L, "mg");
lua_getfield(L, -1, "onerror"); lua_getfield(L, -1, "onerror");
lua_pushvalue(L, -3); lua_pushvalue(L, -3);
@ -133,7 +142,8 @@ static int lsp_error(lua_State *L) {
} }
// Silently stop processing chunks. // Silently stop processing chunks.
static void lsp_abort(lua_State *L) { static void lsp_abort(lua_State *L)
{
int top = lua_gettop(L); int top = lua_gettop(L);
lua_getglobal(L, "mg"); lua_getglobal(L, "mg");
lua_pushnil(L); lua_pushnil(L);
@ -144,7 +154,8 @@ static void lsp_abort(lua_State *L) {
} }
static int lsp(struct mg_connection *conn, const char *path, static int lsp(struct mg_connection *conn, const char *path,
const char *p, int64_t len, lua_State *L) { const char *p, int64_t len, lua_State *L)
{
int i, j, pos = 0, lines = 1, lualines = 0; int i, j, pos = 0, lines = 1, lualines = 0;
char chunkname[MG_BUF_LEN]; char chunkname[MG_BUF_LEN];
@ -186,7 +197,8 @@ static int lsp(struct mg_connection *conn, const char *path,
return 0; return 0;
} }
static int lsp_write(lua_State *L) { static int lsp_write(lua_State *L)
{
int i, num_args; int i, num_args;
const char *str; const char *str;
size_t size; size_t size;
@ -203,7 +215,8 @@ static int lsp_write(lua_State *L) {
return 0; return 0;
} }
static int lsp_read(lua_State *L) { static int lsp_read(lua_State *L)
{
struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1)); struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
char buf[1024]; char buf[1024];
int len = mg_read(conn, buf, sizeof(buf)); int len = mg_read(conn, buf, sizeof(buf));
@ -215,7 +228,8 @@ static int lsp_read(lua_State *L) {
} }
// mg.include: Include another .lp file // mg.include: Include another .lp file
static int lsp_include(lua_State *L) { static int lsp_include(lua_State *L)
{
struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1)); struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
struct file file = STRUCT_FILE_INITIALIZER; struct file file = STRUCT_FILE_INITIALIZER;
if (handle_lsp_request(conn, lua_tostring(L, -1), &file, L)) { if (handle_lsp_request(conn, lua_tostring(L, -1), &file, L)) {
@ -227,14 +241,16 @@ static int lsp_include(lua_State *L) {
} }
// mg.cry: Log an error. Default value for mg.onerror. // mg.cry: Log an error. Default value for mg.onerror.
static int lsp_cry(lua_State *L){ static int lsp_cry(lua_State *L)
{
struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1)); struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
cry(conn, "%s", lua_tostring(L, -1)); cry(conn, "%s", lua_tostring(L, -1));
return 0; return 0;
} }
// mg.redirect: Redirect the request (internally). // mg.redirect: Redirect the request (internally).
static int lsp_redirect(lua_State *L) { static int lsp_redirect(lua_State *L)
{
struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1)); struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
conn->request_info.uri = lua_tostring(L, -1); conn->request_info.uri = lua_tostring(L, -1);
handle_request(conn); handle_request(conn);
@ -242,14 +258,18 @@ static int lsp_redirect(lua_State *L) {
return 0; return 0;
} }
static void prepare_lua_environment(struct mg_connection *conn, lua_State *L) { static void prepare_lua_environment(struct mg_connection *conn, lua_State *L)
{
const struct mg_request_info *ri = mg_get_request_info(conn); const struct mg_request_info *ri = mg_get_request_info(conn);
extern void luaL_openlibs(lua_State *); extern void luaL_openlibs(lua_State *);
int i; int i;
luaL_openlibs(L); luaL_openlibs(L);
#ifdef USE_LUA_SQLITE3 #ifdef USE_LUA_SQLITE3
{ extern int luaopen_lsqlite3(lua_State *); luaopen_lsqlite3(L); } {
extern int luaopen_lsqlite3(lua_State *);
luaopen_lsqlite3(L);
}
#endif #endif
luaL_newmetatable(L, LUASOCKET); luaL_newmetatable(L, LUASOCKET);
@ -296,7 +316,8 @@ static void prepare_lua_environment(struct mg_connection *conn, lua_State *L) {
"debug.traceback(e, 1)) end"); "debug.traceback(e, 1)) end");
} }
static int lua_error_handler(lua_State *L) { static int lua_error_handler(lua_State *L)
{
const char *error_msg = lua_isstring(L, -1) ? lua_tostring(L, -1) : "?\n"; const char *error_msg = lua_isstring(L, -1) ? lua_tostring(L, -1) : "?\n";
lua_getglobal(L, "mg"); lua_getglobal(L, "mg");
@ -316,7 +337,8 @@ static int lua_error_handler(lua_State *L) {
} }
void mg_exec_lua_script(struct mg_connection *conn, const char *path, void mg_exec_lua_script(struct mg_connection *conn, const char *path,
const void **exports) { const void **exports)
{
int i; int i;
lua_State *L; lua_State *L;
@ -342,7 +364,8 @@ void mg_exec_lua_script(struct mg_connection *conn, const char *path,
} }
static void lsp_send_err(struct mg_connection *conn, struct lua_State *L, static void lsp_send_err(struct mg_connection *conn, struct lua_State *L,
const char *fmt, ...) { const char *fmt, ...)
{
char buf[MG_BUF_LEN]; char buf[MG_BUF_LEN];
va_list ap; va_list ap;
int len; int len;
@ -360,7 +383,8 @@ static void lsp_send_err(struct mg_connection *conn, struct lua_State *L,
} }
static int handle_lsp_request(struct mg_connection *conn, const char *path, static int handle_lsp_request(struct mg_connection *conn, const char *path,
struct file *filep, struct lua_State *ls) { struct file *filep, struct lua_State *ls)
{
void *p = NULL; void *p = NULL;
lua_State *L = NULL; lua_State *L = NULL;
int error = 1; int error = 1;