Explorar o código

Set autoformat options and autoformat all source files

bel %!s(int64=10) %!d(string=hai) anos
pai
achega
6ce8b4e92c
Modificáronse 9 ficheiros con 3212 adicións e 3178 borrados
  1. 14 3
      .clang-format
  2. 323 323
      include/CivetServer.h
  3. 149 150
      include/civetweb.h
  4. 206 206
      src/CivetServer.cpp
  5. 399 398
      src/civetweb.c
  6. 522 522
      src/main.c
  7. 245 254
      src/md5.inl
  8. 1250 1215
      src/mod_lua.inl
  9. 104 107
      src/timer.inl

+ 14 - 3
.clang-format

@@ -1,3 +1,14 @@
-BasedOnStyle: LLVM
-IndentWidth: 4
-Language: Cpp
+# http://clang.llvm.org/docs/ClangFormatStyleOptions.html
+
+BasedOnStyle: LLVM
+
+IndentWidth: 4
+TabWidth: 4
+UseTab: ForIndentation
+ColumnLimit: 80
+
+Language: Cpp
+
+AccessModifierOffset: 2
+AlignAfterOpenBracket: true
+AllowShortIfStatementsOnASingleLine: false

+ 323 - 323
include/CivetServer.h

@@ -21,8 +21,8 @@ class CivetServer;
  * Exception class for thrown exceptions within the CivetHandler object.
  */
 class CIVETWEB_API CivetException : public std::runtime_error {
-  public:
-    CivetException(const std::string &msg) : std::runtime_error(msg) {}
+	  public:
+	CivetException(const std::string &msg) : std::runtime_error(msg) {}
 };
 
 /**
@@ -30,56 +30,56 @@ class CIVETWEB_API CivetException : public std::runtime_error {
  * must be reentrant.
  */
 class CIVETWEB_API CivetHandler {
-  public:
-    /**
-     * Destructor
-     */
-    virtual ~CivetHandler() {}
-
-    /**
-     * Callback method for GET request.
-     *
-     * @param server - the calling server
-     * @param conn - the connection information
-     * @returns true if implemented, false otherwise
-     */
-    virtual bool handleGet(CivetServer *server, struct mg_connection *conn);
-
-    /**
-     * Callback method for POST request.
-     *
-     * @param server - the calling server
-     * @param conn - the connection information
-     * @returns true if implemented, false otherwise
-     */
-    virtual bool handlePost(CivetServer *server, struct mg_connection *conn);
-
-    /**
-     * Callback method for PUT request.
-     *
-     * @param server - the calling server
-     * @param conn - the connection information
-     * @returns true if implemented, false otherwise
-     */
-    virtual bool handlePut(CivetServer *server, struct mg_connection *conn);
-
-    /**
-     * Callback method for DELETE request.
-     *
-     * @param server - the calling server
-     * @param conn - the connection information
-     * @returns true if implemented, false otherwise
-     */
-    virtual bool handleDelete(CivetServer *server, struct mg_connection *conn);
-
-    /**
-     * Callback method for OPTIONS request.
-     *
-     * @param server - the calling server
-     * @param conn - the connection information
-     * @returns true if implemented, false otherwise
-     */
-    virtual bool handleOptions(CivetServer *server, struct mg_connection *conn);
+	  public:
+	/**
+	 * Destructor
+	 */
+	virtual ~CivetHandler() {}
+
+	/**
+	 * Callback method for GET request.
+	 *
+	 * @param server - the calling server
+	 * @param conn - the connection information
+	 * @returns true if implemented, false otherwise
+	 */
+	virtual bool handleGet(CivetServer *server, struct mg_connection *conn);
+
+	/**
+	 * Callback method for POST request.
+	 *
+	 * @param server - the calling server
+	 * @param conn - the connection information
+	 * @returns true if implemented, false otherwise
+	 */
+	virtual bool handlePost(CivetServer *server, struct mg_connection *conn);
+
+	/**
+	 * Callback method for PUT request.
+	 *
+	 * @param server - the calling server
+	 * @param conn - the connection information
+	 * @returns true if implemented, false otherwise
+	 */
+	virtual bool handlePut(CivetServer *server, struct mg_connection *conn);
+
+	/**
+	 * Callback method for DELETE request.
+	 *
+	 * @param server - the calling server
+	 * @param conn - the connection information
+	 * @returns true if implemented, false otherwise
+	 */
+	virtual bool handleDelete(CivetServer *server, struct mg_connection *conn);
+
+	/**
+	 * Callback method for OPTIONS request.
+	 *
+	 * @param server - the calling server
+	 * @param conn - the connection information
+	 * @returns true if implemented, false otherwise
+	 */
+	virtual bool handleOptions(CivetServer *server, struct mg_connection *conn);
 };
 
 /**
@@ -88,277 +88,277 @@ class CIVETWEB_API CivetHandler {
  * Basic class for embedded web server.  This has an URL mapping built-in.
  */
 class CIVETWEB_API CivetServer {
-  public:
-    /**
-     * Constructor
-     *
-     * This automatically starts the sever.
-     * It is good practice to call getContext() after this in case there
-     * were errors starting the server.
-     *
-     * @param options - the web server options.
-     * @param callbacks - optional web server callback methods.
-     *
-     * @throws CivetException
-     */
-    CivetServer(const char **options, const struct mg_callbacks *callbacks = 0);
-
-    /**
-     * Destructor
-     */
-    virtual ~CivetServer();
-
-    /**
-     * close()
-     *
-     * Stops server and frees resources.
-     */
-    void close();
-
-    /**
-     * getContext()
-     *
-     * @return the context or 0 if not running.
-     */
-    const struct mg_context *getContext() const { return context; }
-
-    /**
-     * addHandler(const std::string &, CivetHandler *)
-     *
-     * Adds a URI handler.  If there is existing URI handler, it will
-     * be replaced with this one.
-     *
-     * URI's are ordered and prefix (REST) URI's are supported.
-     *
-     *  @param uri - URI to match.
-     *  @param handler - handler instance to use.
-     */
-    void addHandler(const std::string &uri, CivetHandler *handler);
-
-    void addHandler(const std::string &uri, CivetHandler &handler) {
-        addHandler(uri, &handler);
-    }
-
-    /**
-     * removeHandler(const std::string &)
-     *
-     * Removes a handler.
-     *
-     * @param uri - the exact URL used in addHandler().
-     */
-    void removeHandler(const std::string &uri);
-
-    /**
-     * getListeningPorts()
-     *
-     * Returns a list of ports that are listening
-     *
-     * @return A vector of ports
-     */
-
-    std::vector<int> getListeningPorts();
-
-    /**
-     * getCookie(struct mg_connection *conn, const std::string &cookieName,
-     *std::string &cookieValue)
-     *
-     * Puts the cookie value string that matches the cookie name in the
-     *cookieValue destinaton string.
-     *
-     * @param conn - the connection information
-     * @param cookieName - cookie name to get the value from
-     * @param cookieValue - cookie value is returned using thiis reference
-     * @returns the size of the cookie value string read.
-    */
-    static int getCookie(struct mg_connection *conn,
-                         const std::string &cookieName,
-                         std::string &cookieValue);
-
-    /**
-     * getHeader(struct mg_connection *conn, const std::string &headerName)
-     * @param conn - the connection information
-     * @param headerName - header name to get the value from
-     * @returns a char array whcih contains the header value as string
-    */
-    static const char *getHeader(struct mg_connection *conn,
-                                 const std::string &headerName);
-
-    /**
-     * getParam(struct mg_connection *conn, const char *, std::string &, size_t)
-     *
-     * Returns a query paramter contained in the supplied buffer.  The
-     * occurance value is a zero-based index of a particular key name.  This
-     * should not be confused with the index over all of the keys.  Note that
-     *this
-     * function assumes that parameters are sent as text in http query string
-     * format, which is the default for web forms. This function will work for
-     * html forms with method="GET" and method="POST" attributes. In other
-     *cases,
-     * you may use a getParam version that directly takes the data instead of
-     *the
-     * connection as a first argument.
-     *
-     * @param conn - parameters are read from the data sent through this
-     *connection
-     * @param name - the key to search for
-     * @param dst - the destination string
-     * @param occurrence - the occurrence of the selected name in the query (0
-     *based).
-     * @return true if key was found
-     */
-    static bool getParam(struct mg_connection *conn, const char *name,
-                         std::string &dst, size_t occurrence = 0);
-
-    /**
-     * getParam(const std::string &, const char *, std::string &, size_t)
-     *
-     * Returns a query paramter contained in the supplied buffer.  The
-     * occurance value is a zero-based index of a particular key name.  This
-     * should not be confused with the index over all of the keys.
-     *
-     * @param data - the query string (text)
-     * @param name - the key to search for
-     * @param dst - the destination string
-     * @param occurrence - the occurrence of the selected name in the query (0
-     *based).
-     * @return true if key was found
-     */
-    static bool getParam(const std::string &data, const char *name,
-                         std::string &dst, size_t occurrence = 0) {
-        return getParam(data.c_str(), data.length(), name, dst, occurrence);
-    }
-
-    /**
-     * getParam(const char *, size_t, const char *, std::string &, size_t)
-     *
-     * Returns a query paramter contained in the supplied buffer.  The
-     * occurance value is a zero-based index of a particular key name.  This
-     * should not be confused with the index over all of the keys.
-     *
-     * @param data the - query string (text)
-     * @param data_len - length of the query string
-     * @param name - the key to search for
-     * @param dst - the destination string
-     * @param occurrence - the occurrence of the selected name in the query (0
-     *based).
-     * @return true if key was found
-     */
-    static bool getParam(const char *data, size_t data_len, const char *name,
-                         std::string &dst, size_t occurrence = 0);
-
-    /**
-     * urlDecode(const std::string &, std::string &, bool)
-     *
-     * @param src - string to be decoded
-     * @param dst - destination string
-     * @param is_form_url_encoded - true if form url encoded
-     *       form-url-encoded data differs from URI encoding in a way that it
-     *       uses '+' as character for space, see RFC 1866 section 8.2.1
-     *       http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
-     */
-    static void urlDecode(const std::string &src, std::string &dst,
-                          bool is_form_url_encoded = true) {
-        urlDecode(src.c_str(), src.length(), dst, is_form_url_encoded);
-    }
-
-    /**
-     * urlDecode(const char *, size_t, std::string &, bool)
-     *
-     * @param src - buffer to be decoded
-     * @param src_len - length of buffer to be decoded
-     * @param dst - destination string
-     * @param is_form_url_encoded - true if form url encoded
-     *       form-url-encoded data differs from URI encoding in a way that it
-     *       uses '+' as character for space, see RFC 1866 section 8.2.1
-     *       http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
-     */
-    static void urlDecode(const char *src, size_t src_len, std::string &dst,
-                          bool is_form_url_encoded = true);
-
-    /**
-     * urlDecode(const char *, std::string &, bool)
-     *
-     * @param src - buffer to be decoded (0 terminated)
-     * @param dst - destination string
-     * @param is_form_url_encoded true - if form url encoded
-     *       form-url-encoded data differs from URI encoding in a way that it
-     *       uses '+' as character for space, see RFC 1866 section 8.2.1
-     *       http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
-     */
-    static void urlDecode(const char *src, std::string &dst,
-                          bool is_form_url_encoded = true);
-
-    /**
-     * urlEncode(const std::string &, std::string &, bool)
-     *
-     * @param src - buffer to be encoded
-     * @param dst - destination string
-     * @param append - true if string should not be cleared before encoding.
-     */
-    static void urlEncode(const std::string &src, std::string &dst,
-                          bool append = false) {
-        urlEncode(src.c_str(), src.length(), dst, append);
-    }
-
-    /**
-     * urlEncode(const char *, size_t, std::string &, bool)
-     *
-     * @param src - buffer to be encoded (0 terminated)
-     * @param dst - destination string
-     * @param append - true if string should not be cleared before encoding.
-     */
-    static void urlEncode(const char *src, std::string &dst,
-                          bool append = false);
-
-    /**
-     * urlEncode(const char *, size_t, std::string &, bool)
-     *
-     * @param src - buffer to be encoded
-     * @param src_len - length of buffer to be decoded
-     * @param dst - destination string
-     * @param append - true if string should not be cleared before encoding.
-     */
-    static void urlEncode(const char *src, size_t src_len, std::string &dst,
-                          bool append = false);
-
-  protected:
-    class CivetConnection {
-      public:
-        char *postData;
-        unsigned long postDataLen;
-
-        CivetConnection();
-        ~CivetConnection();
-    };
-
-    struct mg_context *context;
-    std::map<struct mg_connection *, class CivetConnection> connections;
-
-  private:
-    /**
-     * requestHandler(struct mg_connection *, void *cbdata)
-     *
-     * Handles the incomming request.
-     *
-     * @param conn - the connection information
-     * @param cbdata - pointer to the CivetHandler instance.
-     * @returns 0 if implemented, false otherwise
-     */
-    static int requestHandler(struct mg_connection *conn, void *cbdata);
-
-    /**
-     * closeHandler(struct mg_connection *)
-     *
-     * Handles closing a request (internal handler)
-     *
-     * @param conn - the connection information
-     */
-    static void closeHandler(const struct mg_connection *conn);
-
-    /**
-     * Stores the user provided close handler
-     */
-    void (*userCloseHandler)(const struct mg_connection *conn);
+	  public:
+	/**
+	 * Constructor
+	 *
+	 * This automatically starts the sever.
+	 * It is good practice to call getContext() after this in case there
+	 * were errors starting the server.
+	 *
+	 * @param options - the web server options.
+	 * @param callbacks - optional web server callback methods.
+	 *
+	 * @throws CivetException
+	 */
+	CivetServer(const char **options, const struct mg_callbacks *callbacks = 0);
+
+	/**
+	 * Destructor
+	 */
+	virtual ~CivetServer();
+
+	/**
+	 * close()
+	 *
+	 * Stops server and frees resources.
+	 */
+	void close();
+
+	/**
+	 * getContext()
+	 *
+	 * @return the context or 0 if not running.
+	 */
+	const struct mg_context *getContext() const { return context; }
+
+	/**
+	 * addHandler(const std::string &, CivetHandler *)
+	 *
+	 * Adds a URI handler.  If there is existing URI handler, it will
+	 * be replaced with this one.
+	 *
+	 * URI's are ordered and prefix (REST) URI's are supported.
+	 *
+	 *  @param uri - URI to match.
+	 *  @param handler - handler instance to use.
+	 */
+	void addHandler(const std::string &uri, CivetHandler *handler);
+
+	void addHandler(const std::string &uri, CivetHandler &handler) {
+		addHandler(uri, &handler);
+	}
+
+	/**
+	 * removeHandler(const std::string &)
+	 *
+	 * Removes a handler.
+	 *
+	 * @param uri - the exact URL used in addHandler().
+	 */
+	void removeHandler(const std::string &uri);
+
+	/**
+	 * getListeningPorts()
+	 *
+	 * Returns a list of ports that are listening
+	 *
+	 * @return A vector of ports
+	 */
+
+	std::vector<int> getListeningPorts();
+
+	/**
+	 * getCookie(struct mg_connection *conn, const std::string &cookieName,
+	 *std::string &cookieValue)
+	 *
+	 * Puts the cookie value string that matches the cookie name in the
+	 *cookieValue destinaton string.
+	 *
+	 * @param conn - the connection information
+	 * @param cookieName - cookie name to get the value from
+	 * @param cookieValue - cookie value is returned using thiis reference
+	 * @returns the size of the cookie value string read.
+	*/
+	static int getCookie(struct mg_connection *conn,
+	                     const std::string &cookieName,
+	                     std::string &cookieValue);
+
+	/**
+	 * getHeader(struct mg_connection *conn, const std::string &headerName)
+	 * @param conn - the connection information
+	 * @param headerName - header name to get the value from
+	 * @returns a char array whcih contains the header value as string
+	*/
+	static const char *getHeader(struct mg_connection *conn,
+	                             const std::string &headerName);
+
+	/**
+	 * getParam(struct mg_connection *conn, const char *, std::string &, size_t)
+	 *
+	 * Returns a query paramter contained in the supplied buffer.  The
+	 * occurance value is a zero-based index of a particular key name.  This
+	 * should not be confused with the index over all of the keys.  Note that
+	 *this
+	 * function assumes that parameters are sent as text in http query string
+	 * format, which is the default for web forms. This function will work for
+	 * html forms with method="GET" and method="POST" attributes. In other
+	 *cases,
+	 * you may use a getParam version that directly takes the data instead of
+	 *the
+	 * connection as a first argument.
+	 *
+	 * @param conn - parameters are read from the data sent through this
+	 *connection
+	 * @param name - the key to search for
+	 * @param dst - the destination string
+	 * @param occurrence - the occurrence of the selected name in the query (0
+	 *based).
+	 * @return true if key was found
+	 */
+	static bool getParam(struct mg_connection *conn, const char *name,
+	                     std::string &dst, size_t occurrence = 0);
+
+	/**
+	 * getParam(const std::string &, const char *, std::string &, size_t)
+	 *
+	 * Returns a query paramter contained in the supplied buffer.  The
+	 * occurance value is a zero-based index of a particular key name.  This
+	 * should not be confused with the index over all of the keys.
+	 *
+	 * @param data - the query string (text)
+	 * @param name - the key to search for
+	 * @param dst - the destination string
+	 * @param occurrence - the occurrence of the selected name in the query (0
+	 *based).
+	 * @return true if key was found
+	 */
+	static bool getParam(const std::string &data, const char *name,
+	                     std::string &dst, size_t occurrence = 0) {
+		return getParam(data.c_str(), data.length(), name, dst, occurrence);
+	}
+
+	/**
+	 * getParam(const char *, size_t, const char *, std::string &, size_t)
+	 *
+	 * Returns a query paramter contained in the supplied buffer.  The
+	 * occurance value is a zero-based index of a particular key name.  This
+	 * should not be confused with the index over all of the keys.
+	 *
+	 * @param data the - query string (text)
+	 * @param data_len - length of the query string
+	 * @param name - the key to search for
+	 * @param dst - the destination string
+	 * @param occurrence - the occurrence of the selected name in the query (0
+	 *based).
+	 * @return true if key was found
+	 */
+	static bool getParam(const char *data, size_t data_len, const char *name,
+	                     std::string &dst, size_t occurrence = 0);
+
+	/**
+	 * urlDecode(const std::string &, std::string &, bool)
+	 *
+	 * @param src - string to be decoded
+	 * @param dst - destination string
+	 * @param is_form_url_encoded - true if form url encoded
+	 *       form-url-encoded data differs from URI encoding in a way that it
+	 *       uses '+' as character for space, see RFC 1866 section 8.2.1
+	 *       http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
+	 */
+	static void urlDecode(const std::string &src, std::string &dst,
+	                      bool is_form_url_encoded = true) {
+		urlDecode(src.c_str(), src.length(), dst, is_form_url_encoded);
+	}
+
+	/**
+	 * urlDecode(const char *, size_t, std::string &, bool)
+	 *
+	 * @param src - buffer to be decoded
+	 * @param src_len - length of buffer to be decoded
+	 * @param dst - destination string
+	 * @param is_form_url_encoded - true if form url encoded
+	 *       form-url-encoded data differs from URI encoding in a way that it
+	 *       uses '+' as character for space, see RFC 1866 section 8.2.1
+	 *       http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
+	 */
+	static void urlDecode(const char *src, size_t src_len, std::string &dst,
+	                      bool is_form_url_encoded = true);
+
+	/**
+	 * urlDecode(const char *, std::string &, bool)
+	 *
+	 * @param src - buffer to be decoded (0 terminated)
+	 * @param dst - destination string
+	 * @param is_form_url_encoded true - if form url encoded
+	 *       form-url-encoded data differs from URI encoding in a way that it
+	 *       uses '+' as character for space, see RFC 1866 section 8.2.1
+	 *       http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
+	 */
+	static void urlDecode(const char *src, std::string &dst,
+	                      bool is_form_url_encoded = true);
+
+	/**
+	 * urlEncode(const std::string &, std::string &, bool)
+	 *
+	 * @param src - buffer to be encoded
+	 * @param dst - destination string
+	 * @param append - true if string should not be cleared before encoding.
+	 */
+	static void urlEncode(const std::string &src, std::string &dst,
+	                      bool append = false) {
+		urlEncode(src.c_str(), src.length(), dst, append);
+	}
+
+	/**
+	 * urlEncode(const char *, size_t, std::string &, bool)
+	 *
+	 * @param src - buffer to be encoded (0 terminated)
+	 * @param dst - destination string
+	 * @param append - true if string should not be cleared before encoding.
+	 */
+	static void urlEncode(const char *src, std::string &dst,
+	                      bool append = false);
+
+	/**
+	 * urlEncode(const char *, size_t, std::string &, bool)
+	 *
+	 * @param src - buffer to be encoded
+	 * @param src_len - length of buffer to be decoded
+	 * @param dst - destination string
+	 * @param append - true if string should not be cleared before encoding.
+	 */
+	static void urlEncode(const char *src, size_t src_len, std::string &dst,
+	                      bool append = false);
+
+	  protected:
+	class CivetConnection {
+		  public:
+		char *postData;
+		unsigned long postDataLen;
+
+		CivetConnection();
+		~CivetConnection();
+	};
+
+	struct mg_context *context;
+	std::map<struct mg_connection *, class CivetConnection> connections;
+
+	  private:
+	/**
+	 * requestHandler(struct mg_connection *, void *cbdata)
+	 *
+	 * Handles the incomming request.
+	 *
+	 * @param conn - the connection information
+	 * @param cbdata - pointer to the CivetHandler instance.
+	 * @returns 0 if implemented, false otherwise
+	 */
+	static int requestHandler(struct mg_connection *conn, void *cbdata);
+
+	/**
+	 * closeHandler(struct mg_connection *)
+	 *
+	 * Handles closing a request (internal handler)
+	 *
+	 * @param conn - the connection information
+	 */
+	static void closeHandler(const struct mg_connection *conn);
+
+	/**
+	 * Stores the user provided close handler
+	 */
+	void (*userCloseHandler)(const struct mg_connection *conn);
 };
 
 #endif /*  __cplusplus */

+ 149 - 150
include/civetweb.h

@@ -51,146 +51,145 @@ struct mg_connection; /* Handle for the individual connection */
 
 /* This structure contains information about the HTTP request. */
 struct mg_request_info {
-    const char *request_method; /* "GET", "POST", etc */
-    const char *uri;            /* URL-decoded URI */
-    const char *http_version;   /* E.g. "1.0", "1.1" */
-    const char *query_string;   /* URL part after '?', not including '?', or
-                                   NULL */
-    const char *remote_user;    /* Authenticated user, or NULL if no auth
-                                   used */
-    char remote_addr[48];       /* Client's IP address as a string. */
-    long
-        remote_ip; /* Client's IP address. Deprecated: use remote_addr instead
-                      */
-
-    long long content_length; /* Length (in bytes) of the request body,
-                                 can be -1 if no length was given. */
-    int remote_port;          /* Client's port */
-    int is_ssl;               /* 1 if SSL-ed, 0 if not */
-    void *user_data;          /* User data pointer passed to mg_start() */
-    void *conn_data;          /* Connection-specific user data */
-
-    int num_headers; /* Number of HTTP headers */
-    struct mg_header {
-        const char *name;  /* HTTP header name */
-        const char *value; /* HTTP header value */
-    } http_headers[64];    /* Maximum 64 headers */
+	const char *request_method; /* "GET", "POST", etc */
+	const char *uri;            /* URL-decoded URI */
+	const char *http_version;   /* E.g. "1.0", "1.1" */
+	const char *query_string;   /* URL part after '?', not including '?', or
+	                               NULL */
+	const char *remote_user;    /* Authenticated user, or NULL if no auth
+	                               used */
+	char remote_addr[48];       /* Client's IP address as a string. */
+	long remote_ip; /* Client's IP address. Deprecated: use remote_addr instead
+	                   */
+
+	long long content_length; /* Length (in bytes) of the request body,
+	                             can be -1 if no length was given. */
+	int remote_port;          /* Client's port */
+	int is_ssl;               /* 1 if SSL-ed, 0 if not */
+	void *user_data;          /* User data pointer passed to mg_start() */
+	void *conn_data;          /* Connection-specific user data */
+
+	int num_headers; /* Number of HTTP headers */
+	struct mg_header {
+		const char *name;  /* HTTP header name */
+		const char *value; /* HTTP header value */
+	} http_headers[64];    /* Maximum 64 headers */
 };
 
 /* This structure needs to be passed to mg_start(), to let civetweb know
    which callbacks to invoke. For a detailed description, see
    https://github.com/bel2125/civetweb/blob/master/docs/UserManual.md */
 struct mg_callbacks {
-    /* Called when civetweb has received new HTTP request.
-       If the callback returns one, it must process the request
-       by sending valid HTTP headers and a body. Civetweb will not do
-       any further processing. Otherwise it must return zero.
-       Note that since V1.7 the "begin_request" function is called
-       before an authorization check. If an authorization check is
-       required, use a request_handler instead.
-       Return value:
-         0: civetweb will process the request itself. In this case,
-            the callback must not send any data to the client.
-         1: callback already processed the request. Civetweb will
-            not send any data after the callback returned. */
-    int (*begin_request)(struct mg_connection *);
-
-    /* Called when civetweb has finished processing request. */
-    void (*end_request)(const struct mg_connection *, int reply_status_code);
-
-    /* Called when civetweb is about to log a message. If callback returns
-       non-zero, civetweb does not log anything. */
-    int (*log_message)(const struct mg_connection *, const char *message);
-
-    /* Called when civetweb is about to log access. If callback returns
-       non-zero, civetweb does not log anything. */
-    int (*log_access)(const struct mg_connection *, const char *message);
-
-    /* Called when civetweb initializes SSL library.
-       Parameters:
-         user_data: parameter user_data passed when starting the server.
-       Return value:
-         0: civetweb will set up the SSL certificate.
-         1: civetweb assumes the callback already set up the certificate.
-        -1: initializing ssl fails. */
-    int (*init_ssl)(void *ssl_context, void *user_data);
-
-    /* Called when websocket request is received, before websocket handshake.
-       Return value:
-         0: civetweb proceeds with websocket handshake.
-         1: connection is closed immediately.
-       This callback is deprecated, use mg_set_websocket_handler instead. */
-    int (*websocket_connect)(const struct mg_connection *);
-
-    /* Called when websocket handshake is successfully completed, and
-       connection is ready for data exchange.
-       This callback is deprecated, use mg_set_websocket_handler instead. */
-    void (*websocket_ready)(struct mg_connection *);
-
-    /* Called when data frame has been received from the client.
-       Parameters:
-         bits: first byte of the websocket frame, see websocket RFC at
-               http://tools.ietf.org/html/rfc6455, section 5.2
-         data, data_len: payload, with mask (if any) already applied.
-       Return value:
-         1: keep this websocket connection open.
-         0: close this websocket connection.
-       This callback is deprecated, use mg_set_websocket_handler instead. */
-    int (*websocket_data)(struct mg_connection *, int bits, char *data,
-                          size_t data_len);
-
-    /* Called when civetweb is closing a connection.  The per-context mutex is
-       locked when this is invoked.  This is primarily useful for noting when
-       a websocket is closing and removing it from any application-maintained
-       list of clients.
-       Using this callback for websocket connections is deprecated, use
-       mg_set_websocket_handler instead. */
-    void (*connection_close)(const struct mg_connection *);
-
-    /* Called when civetweb tries to open a file. Used to intercept file open
-       calls, and serve file data from memory instead.
-       Parameters:
-          path:     Full path to the file to open.
-          data_len: Placeholder for the file size, if file is served from
-                    memory.
-       Return value:
-         NULL: do not serve file from memory, proceed with normal file open.
-         non-NULL: pointer to the file contents in memory. data_len must be
-           initilized with the size of the memory block. */
-    const char *(*open_file)(const struct mg_connection *, const char *path,
-                             size_t *data_len);
-
-    /* Called when civetweb is about to serve Lua server page, if
-       Lua support is enabled.
-       Parameters:
-         lua_context: "lua_State *" pointer. */
-    void (*init_lua)(const struct mg_connection *, void *lua_context);
-
-    /* Called when civetweb has uploaded a file to a temporary directory as a
-       result of mg_upload() call.
-       Parameters:
-         file_name: full path name to the uploaded file. */
-    void (*upload)(struct mg_connection *, const char *file_name);
-
-    /* Called when civetweb is about to send HTTP error to the client.
-       Implementing this callback allows to create custom error pages.
-       Parameters:
-         status: HTTP error status code.
-       Return value:
-         1: run civetweb error handler.
-         0: callback already handled the error. */
-    int (*http_error)(struct mg_connection *, int status);
-
-    /* Called after civetweb context has been created, before requests
-       are processed.
-       Parameters:
-         ctx: context handle */
-    void (*init_context)(const struct mg_context *ctx);
-
-    /* Called when civetweb context is deleted.
-       Parameters:
-         ctx: context handle */
-    void (*exit_context)(const struct mg_context *ctx);
+	/* Called when civetweb has received new HTTP request.
+	   If the callback returns one, it must process the request
+	   by sending valid HTTP headers and a body. Civetweb will not do
+	   any further processing. Otherwise it must return zero.
+	   Note that since V1.7 the "begin_request" function is called
+	   before an authorization check. If an authorization check is
+	   required, use a request_handler instead.
+	   Return value:
+	     0: civetweb will process the request itself. In this case,
+	        the callback must not send any data to the client.
+	     1: callback already processed the request. Civetweb will
+	        not send any data after the callback returned. */
+	int (*begin_request)(struct mg_connection *);
+
+	/* Called when civetweb has finished processing request. */
+	void (*end_request)(const struct mg_connection *, int reply_status_code);
+
+	/* Called when civetweb is about to log a message. If callback returns
+	   non-zero, civetweb does not log anything. */
+	int (*log_message)(const struct mg_connection *, const char *message);
+
+	/* Called when civetweb is about to log access. If callback returns
+	   non-zero, civetweb does not log anything. */
+	int (*log_access)(const struct mg_connection *, const char *message);
+
+	/* Called when civetweb initializes SSL library.
+	   Parameters:
+	     user_data: parameter user_data passed when starting the server.
+	   Return value:
+	     0: civetweb will set up the SSL certificate.
+	     1: civetweb assumes the callback already set up the certificate.
+	    -1: initializing ssl fails. */
+	int (*init_ssl)(void *ssl_context, void *user_data);
+
+	/* Called when websocket request is received, before websocket handshake.
+	   Return value:
+	     0: civetweb proceeds with websocket handshake.
+	     1: connection is closed immediately.
+	   This callback is deprecated, use mg_set_websocket_handler instead. */
+	int (*websocket_connect)(const struct mg_connection *);
+
+	/* Called when websocket handshake is successfully completed, and
+	   connection is ready for data exchange.
+	   This callback is deprecated, use mg_set_websocket_handler instead. */
+	void (*websocket_ready)(struct mg_connection *);
+
+	/* Called when data frame has been received from the client.
+	   Parameters:
+	     bits: first byte of the websocket frame, see websocket RFC at
+	           http://tools.ietf.org/html/rfc6455, section 5.2
+	     data, data_len: payload, with mask (if any) already applied.
+	   Return value:
+	     1: keep this websocket connection open.
+	     0: close this websocket connection.
+	   This callback is deprecated, use mg_set_websocket_handler instead. */
+	int (*websocket_data)(struct mg_connection *, int bits, char *data,
+	                      size_t data_len);
+
+	/* Called when civetweb is closing a connection.  The per-context mutex is
+	   locked when this is invoked.  This is primarily useful for noting when
+	   a websocket is closing and removing it from any application-maintained
+	   list of clients.
+	   Using this callback for websocket connections is deprecated, use
+	   mg_set_websocket_handler instead. */
+	void (*connection_close)(const struct mg_connection *);
+
+	/* Called when civetweb tries to open a file. Used to intercept file open
+	   calls, and serve file data from memory instead.
+	   Parameters:
+	      path:     Full path to the file to open.
+	      data_len: Placeholder for the file size, if file is served from
+	                memory.
+	   Return value:
+	     NULL: do not serve file from memory, proceed with normal file open.
+	     non-NULL: pointer to the file contents in memory. data_len must be
+	       initilized with the size of the memory block. */
+	const char *(*open_file)(const struct mg_connection *, const char *path,
+	                         size_t *data_len);
+
+	/* Called when civetweb is about to serve Lua server page, if
+	   Lua support is enabled.
+	   Parameters:
+	     lua_context: "lua_State *" pointer. */
+	void (*init_lua)(const struct mg_connection *, void *lua_context);
+
+	/* Called when civetweb has uploaded a file to a temporary directory as a
+	   result of mg_upload() call.
+	   Parameters:
+	     file_name: full path name to the uploaded file. */
+	void (*upload)(struct mg_connection *, const char *file_name);
+
+	/* Called when civetweb is about to send HTTP error to the client.
+	   Implementing this callback allows to create custom error pages.
+	   Parameters:
+	     status: HTTP error status code.
+	   Return value:
+	     1: run civetweb error handler.
+	     0: callback already handled the error. */
+	int (*http_error)(struct mg_connection *, int status);
+
+	/* Called after civetweb context has been created, before requests
+	   are processed.
+	   Parameters:
+	     ctx: context handle */
+	void (*init_context)(const struct mg_context *ctx);
+
+	/* Called when civetweb context is deleted.
+	   Parameters:
+	     ctx: context handle */
+	void (*exit_context)(const struct mg_context *ctx);
 };
 
 /* Start web server.
@@ -347,19 +346,19 @@ CIVETWEB_API const char **mg_get_valid_option_names(void);
 #endif
 
 struct mg_option {
-    const char *name;
-    int type;
-    const char *default_value;
+	const char *name;
+	int type;
+	const char *default_value;
 };
 
 enum {
-    CONFIG_TYPE_UNKNOWN = 0x0,
-    CONFIG_TYPE_NUMBER = 0x1,
-    CONFIG_TYPE_STRING = 0x2,
-    CONFIG_TYPE_FILE = 0x3,
-    CONFIG_TYPE_DIRECTORY = 0x4,
-    CONFIG_TYPE_BOOLEAN = 0x5,
-    CONFIG_TYPE_EXT_PATTERN = 0x6
+	CONFIG_TYPE_UNKNOWN = 0x0,
+	CONFIG_TYPE_NUMBER = 0x1,
+	CONFIG_TYPE_STRING = 0x2,
+	CONFIG_TYPE_FILE = 0x3,
+	CONFIG_TYPE_DIRECTORY = 0x4,
+	CONFIG_TYPE_BOOLEAN = 0x5,
+	CONFIG_TYPE_EXT_PATTERN = 0x6
 };
 
 /* Return array of struct mg_option, representing all valid configuration
@@ -439,12 +438,12 @@ CIVETWEB_API void mg_unlock_context(struct mg_context *ctx);
 
 /* Opcodes, from http://tools.ietf.org/html/rfc6455 */
 enum {
-    WEBSOCKET_OPCODE_CONTINUATION = 0x0,
-    WEBSOCKET_OPCODE_TEXT = 0x1,
-    WEBSOCKET_OPCODE_BINARY = 0x2,
-    WEBSOCKET_OPCODE_CONNECTION_CLOSE = 0x8,
-    WEBSOCKET_OPCODE_PING = 0x9,
-    WEBSOCKET_OPCODE_PONG = 0xa
+	WEBSOCKET_OPCODE_CONTINUATION = 0x0,
+	WEBSOCKET_OPCODE_TEXT = 0x1,
+	WEBSOCKET_OPCODE_BINARY = 0x2,
+	WEBSOCKET_OPCODE_CONNECTION_CLOSE = 0x8,
+	WEBSOCKET_OPCODE_PING = 0x9,
+	WEBSOCKET_OPCODE_PONG = 0xa
 };
 
 /* Macros for enabling compiler-specific checks for printf-like arguments. */

+ 206 - 206
src/CivetServer.cpp

@@ -16,288 +16,288 @@
 #endif
 
 bool CivetHandler::handleGet(CivetServer *server, struct mg_connection *conn) {
-    UNUSED_PARAMETER(server);
-    UNUSED_PARAMETER(conn);
-    return false;
+	UNUSED_PARAMETER(server);
+	UNUSED_PARAMETER(conn);
+	return false;
 }
 
 bool CivetHandler::handlePost(CivetServer *server, struct mg_connection *conn) {
-    UNUSED_PARAMETER(server);
-    UNUSED_PARAMETER(conn);
-    return false;
+	UNUSED_PARAMETER(server);
+	UNUSED_PARAMETER(conn);
+	return false;
 }
 
 bool CivetHandler::handlePut(CivetServer *server, struct mg_connection *conn) {
-    UNUSED_PARAMETER(server);
-    UNUSED_PARAMETER(conn);
-    return false;
+	UNUSED_PARAMETER(server);
+	UNUSED_PARAMETER(conn);
+	return false;
 }
 
 bool CivetHandler::handleDelete(CivetServer *server,
                                 struct mg_connection *conn) {
-    UNUSED_PARAMETER(server);
-    UNUSED_PARAMETER(conn);
-    return false;
+	UNUSED_PARAMETER(server);
+	UNUSED_PARAMETER(conn);
+	return false;
 }
 
 bool CivetHandler::handleOptions(CivetServer *server,
                                  struct mg_connection *conn) {
-    UNUSED_PARAMETER(server);
-    UNUSED_PARAMETER(conn);
-    return false;
+	UNUSED_PARAMETER(server);
+	UNUSED_PARAMETER(conn);
+	return false;
 }
 
 int CivetServer::requestHandler(struct mg_connection *conn, void *cbdata) {
-    const struct mg_request_info *request_info = mg_get_request_info(conn);
-    assert(request_info != NULL);
-    CivetServer *me = (CivetServer *)(request_info->user_data);
-    assert(me != NULL);
-
-    // Happens when a request hits the server before the context is saved
-    if (me->context == NULL)
-        return 0;
-
-    mg_lock_context(me->context);
-    me->connections[conn] = CivetConnection();
-    mg_unlock_context(me->context);
-
-    CivetHandler *handler = (CivetHandler *)cbdata;
-
-    if (handler) {
-        if (strcmp(request_info->request_method, "GET") == 0) {
-            return handler->handleGet(me, conn) ? 1 : 0;
-        } else if (strcmp(request_info->request_method, "POST") == 0) {
-            return handler->handlePost(me, conn) ? 1 : 0;
-        } else if (strcmp(request_info->request_method, "PUT") == 0) {
-            return handler->handlePut(me, conn) ? 1 : 0;
-        } else if (strcmp(request_info->request_method, "DELETE") == 0) {
-            return handler->handleDelete(me, conn) ? 1 : 0;
-        } else if (strcmp(request_info->request_method, "OPTIONS") == 0) {
-            return handler->handleOptions(me, conn) ? 1 : 0;
-        }
-    }
-
-    return 0; // No handler found
+	const struct mg_request_info *request_info = mg_get_request_info(conn);
+	assert(request_info != NULL);
+	CivetServer *me = (CivetServer *)(request_info->user_data);
+	assert(me != NULL);
+
+	// Happens when a request hits the server before the context is saved
+	if (me->context == NULL)
+		return 0;
+
+	mg_lock_context(me->context);
+	me->connections[conn] = CivetConnection();
+	mg_unlock_context(me->context);
+
+	CivetHandler *handler = (CivetHandler *)cbdata;
+
+	if (handler) {
+		if (strcmp(request_info->request_method, "GET") == 0) {
+			return handler->handleGet(me, conn) ? 1 : 0;
+		} else if (strcmp(request_info->request_method, "POST") == 0) {
+			return handler->handlePost(me, conn) ? 1 : 0;
+		} else if (strcmp(request_info->request_method, "PUT") == 0) {
+			return handler->handlePut(me, conn) ? 1 : 0;
+		} else if (strcmp(request_info->request_method, "DELETE") == 0) {
+			return handler->handleDelete(me, conn) ? 1 : 0;
+		} else if (strcmp(request_info->request_method, "OPTIONS") == 0) {
+			return handler->handleOptions(me, conn) ? 1 : 0;
+		}
+	}
+
+	return 0; // No handler found
 }
 
 CivetServer::CivetServer(const char **options,
                          const struct mg_callbacks *_callbacks)
     : context(0) {
-    struct mg_callbacks callbacks;
-    memset(&callbacks, 0, sizeof(callbacks));
-
-    if (_callbacks) {
-        callbacks = *_callbacks;
-        userCloseHandler = _callbacks->connection_close;
-    } else {
-        userCloseHandler = NULL;
-    }
-    callbacks.connection_close = closeHandler;
-    context = mg_start(&callbacks, this, options);
-    if (context == NULL)
-        throw CivetException("null context when constructing CivetServer. "
-                             "Possible problem binding to port.");
+	struct mg_callbacks callbacks;
+	memset(&callbacks, 0, sizeof(callbacks));
+
+	if (_callbacks) {
+		callbacks = *_callbacks;
+		userCloseHandler = _callbacks->connection_close;
+	} else {
+		userCloseHandler = NULL;
+	}
+	callbacks.connection_close = closeHandler;
+	context = mg_start(&callbacks, this, options);
+	if (context == NULL)
+		throw CivetException("null context when constructing CivetServer. "
+		                     "Possible problem binding to port.");
 }
 
 CivetServer::~CivetServer() { close(); }
 
 void CivetServer::closeHandler(const struct mg_connection *conn) {
-    const struct mg_request_info *request_info = mg_get_request_info(conn);
-    assert(request_info != NULL);
-    CivetServer *me = (CivetServer *)(request_info->user_data);
-    assert(me != NULL);
-
-    // Happens when a request hits the server before the context is saved
-    if (me->context == NULL)
-        return;
-
-    if (me->userCloseHandler)
-        me->userCloseHandler(conn);
-    mg_lock_context(me->context);
-    me->connections.erase(const_cast<struct mg_connection *>(conn));
-    mg_unlock_context(me->context);
+	const struct mg_request_info *request_info = mg_get_request_info(conn);
+	assert(request_info != NULL);
+	CivetServer *me = (CivetServer *)(request_info->user_data);
+	assert(me != NULL);
+
+	// Happens when a request hits the server before the context is saved
+	if (me->context == NULL)
+		return;
+
+	if (me->userCloseHandler)
+		me->userCloseHandler(conn);
+	mg_lock_context(me->context);
+	me->connections.erase(const_cast<struct mg_connection *>(conn));
+	mg_unlock_context(me->context);
 }
 
 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) {
-    mg_set_request_handler(context, uri.c_str(), NULL, NULL);
+	mg_set_request_handler(context, uri.c_str(), NULL, NULL);
 }
 
 void CivetServer::close() {
-    if (context) {
-        mg_stop(context);
-        context = 0;
-    }
+	if (context) {
+		mg_stop(context);
+		context = 0;
+	}
 }
 
 int CivetServer::getCookie(struct mg_connection *conn,
                            const std::string &cookieName,
                            std::string &cookieValue) {
-    // Maximum cookie length as per microsoft is 4096.
-    // http://msdn.microsoft.com/en-us/library/ms178194.aspx
-    char _cookieValue[4096];
-    const char *cookie = mg_get_header(conn, "Cookie");
-    int lRead = mg_get_cookie(cookie, cookieName.c_str(), _cookieValue,
-                              sizeof(_cookieValue));
-    cookieValue.clear();
-    cookieValue.append(_cookieValue);
-    return lRead;
+	// Maximum cookie length as per microsoft is 4096.
+	// http://msdn.microsoft.com/en-us/library/ms178194.aspx
+	char _cookieValue[4096];
+	const char *cookie = mg_get_header(conn, "Cookie");
+	int lRead = mg_get_cookie(cookie, cookieName.c_str(), _cookieValue,
+	                          sizeof(_cookieValue));
+	cookieValue.clear();
+	cookieValue.append(_cookieValue);
+	return lRead;
 }
 
 const char *CivetServer::getHeader(struct mg_connection *conn,
                                    const std::string &headerName) {
-    return mg_get_header(conn, headerName.c_str());
+	return mg_get_header(conn, headerName.c_str());
 }
 
 void 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 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')
 
-    dst.clear();
-    for (i = j = 0; i < (int)src_len; i++, j++) {
-        if (i < (int)src_len - 2 && src[i] == '%' &&
-            isxdigit(*(const unsigned char *)(src + i + 1)) &&
-            isxdigit(*(const unsigned char *)(src + i + 2))) {
-            a = tolower(*(const unsigned char *)(src + i + 1));
-            b = tolower(*(const unsigned char *)(src + i + 2));
-            dst.push_back((char)((HEXTOI(a) << 4) | HEXTOI(b)));
-            i += 2;
-        } else if (is_form_url_encoded && src[i] == '+') {
-            dst.push_back(' ');
-        } else {
-            dst.push_back(src[i]);
-        }
-    }
+	dst.clear();
+	for (i = j = 0; i < (int)src_len; i++, j++) {
+		if (i < (int)src_len - 2 && src[i] == '%' &&
+		    isxdigit(*(const unsigned char *)(src + i + 1)) &&
+		    isxdigit(*(const unsigned char *)(src + i + 2))) {
+			a = tolower(*(const unsigned char *)(src + i + 1));
+			b = tolower(*(const unsigned char *)(src + i + 2));
+			dst.push_back((char)((HEXTOI(a) << 4) | HEXTOI(b)));
+			i += 2;
+		} else if (is_form_url_encoded && src[i] == '+') {
+			dst.push_back(' ');
+		} else {
+			dst.push_back(src[i]);
+		}
+	}
 }
 
 bool CivetServer::getParam(struct mg_connection *conn, const char *name,
                            std::string &dst, size_t occurrence) {
-    const char *formParams = NULL;
-    const struct mg_request_info *ri = mg_get_request_info(conn);
-    assert(ri != NULL);
-    CivetServer *me = (CivetServer *)(ri->user_data);
-    assert(me != NULL);
-    mg_lock_context(me->context);
-    CivetConnection &conobj = me->connections[conn];
-    mg_lock_connection(conn);
-    mg_unlock_context(me->context);
-
-    if (conobj.postData != NULL) {
-        formParams = conobj.postData;
-    } else {
-        const char *con_len_str = mg_get_header(conn, "Content-Length");
-        if (con_len_str) {
-            unsigned long con_len = atoi(con_len_str);
-            if (con_len > 0) {
-                // Add one extra character: in case the post-data is a text, it
-                // is required as 0-termination.
-                // Do not increment con_len, since the 0 terminating is not part
-                // of the content (text or binary).
-                conobj.postData = (char *)malloc(con_len + 1);
-                if (conobj.postData != NULL) {
-                    // malloc may fail for huge requests
-                    mg_read(conn, conobj.postData, con_len);
-                    conobj.postData[con_len] = 0;
-                    formParams = conobj.postData;
-                    conobj.postDataLen = con_len;
-                }
-            }
-        }
-    }
-    if (formParams == NULL) {
-        // get requests do store html <form> field values in the http
-        // query_string
-        formParams = ri->query_string;
-    }
-    mg_unlock_connection(conn);
-
-    if (formParams != NULL) {
-        return getParam(formParams, strlen(formParams), name, dst, occurrence);
-    }
-
-    return false;
+	const char *formParams = NULL;
+	const struct mg_request_info *ri = mg_get_request_info(conn);
+	assert(ri != NULL);
+	CivetServer *me = (CivetServer *)(ri->user_data);
+	assert(me != NULL);
+	mg_lock_context(me->context);
+	CivetConnection &conobj = me->connections[conn];
+	mg_lock_connection(conn);
+	mg_unlock_context(me->context);
+
+	if (conobj.postData != NULL) {
+		formParams = conobj.postData;
+	} else {
+		const char *con_len_str = mg_get_header(conn, "Content-Length");
+		if (con_len_str) {
+			unsigned long con_len = atoi(con_len_str);
+			if (con_len > 0) {
+				// Add one extra character: in case the post-data is a text, it
+				// is required as 0-termination.
+				// Do not increment con_len, since the 0 terminating is not part
+				// of the content (text or binary).
+				conobj.postData = (char *)malloc(con_len + 1);
+				if (conobj.postData != NULL) {
+					// malloc may fail for huge requests
+					mg_read(conn, conobj.postData, con_len);
+					conobj.postData[con_len] = 0;
+					formParams = conobj.postData;
+					conobj.postDataLen = con_len;
+				}
+			}
+		}
+	}
+	if (formParams == NULL) {
+		// get requests do store html <form> field values in the http
+		// query_string
+		formParams = ri->query_string;
+	}
+	mg_unlock_connection(conn);
+
+	if (formParams != NULL) {
+		return getParam(formParams, strlen(formParams), name, dst, occurrence);
+	}
+
+	return false;
 }
 
 bool CivetServer::getParam(const char *data, size_t data_len, const char *name,
                            std::string &dst, size_t occurrence) {
-    const char *p, *e, *s;
-    size_t name_len;
-
-    dst.clear();
-    if (data == NULL || name == NULL || data_len == 0) {
-        return false;
-    }
-    name_len = strlen(name);
-    e = data + data_len;
-
-    // data is "var1=val1&var2=val2...". Find variable first
-    for (p = data; p + name_len < e; p++) {
-        if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
-            !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
-
-            // Point p to variable value
-            p += name_len + 1;
-
-            // Point s to the end of the value
-            s = (const char *)memchr(p, '&', (size_t)(e - p));
-            if (s == NULL) {
-                s = e;
-            }
-            assert(s >= p);
-
-            // Decode variable into destination buffer
-            urlDecode(p, (int)(s - p), dst, true);
-            return true;
-        }
-    }
-    return false;
+	const char *p, *e, *s;
+	size_t name_len;
+
+	dst.clear();
+	if (data == NULL || name == NULL || data_len == 0) {
+		return false;
+	}
+	name_len = strlen(name);
+	e = data + data_len;
+
+	// data is "var1=val1&var2=val2...". Find variable first
+	for (p = data; p + name_len < e; p++) {
+		if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
+		    !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
+
+			// Point p to variable value
+			p += name_len + 1;
+
+			// Point s to the end of the value
+			s = (const char *)memchr(p, '&', (size_t)(e - p));
+			if (s == NULL) {
+				s = e;
+			}
+			assert(s >= p);
+
+			// Decode variable into destination buffer
+			urlDecode(p, (int)(s - p), dst, true);
+			return true;
+		}
+	}
+	return false;
 }
 
 void CivetServer::urlEncode(const char *src, std::string &dst, bool append) {
-    urlEncode(src, strlen(src), dst, append);
+	urlEncode(src, strlen(src), dst, append);
 }
 
 void CivetServer::urlEncode(const char *src, size_t src_len, std::string &dst,
                             bool append) {
-    static const char *dont_escape = "._-$,;~()";
-    static const char *hex = "0123456789abcdef";
-
-    if (!append)
-        dst.clear();
-
-    for (; src_len > 0; src++, src_len--) {
-        if (isalnum(*(const unsigned char *)src) ||
-            strchr(dont_escape, *(const unsigned char *)src) != NULL) {
-            dst.push_back(*src);
-        } else {
-            dst.push_back('%');
-            dst.push_back(hex[(*(const unsigned char *)src) >> 4]);
-            dst.push_back(hex[(*(const unsigned char *)src) & 0xf]);
-        }
-    }
+	static const char *dont_escape = "._-$,;~()";
+	static const char *hex = "0123456789abcdef";
+
+	if (!append)
+		dst.clear();
+
+	for (; src_len > 0; src++, src_len--) {
+		if (isalnum(*(const unsigned char *)src) ||
+		    strchr(dont_escape, *(const unsigned char *)src) != NULL) {
+			dst.push_back(*src);
+		} else {
+			dst.push_back('%');
+			dst.push_back(hex[(*(const unsigned char *)src) >> 4]);
+			dst.push_back(hex[(*(const unsigned char *)src) & 0xf]);
+		}
+	}
 }
 
 std::vector<int> CivetServer::getListeningPorts() {
-    std::vector<int> ports(10);
-    std::vector<int> ssl(10);
-    size_t size = mg_get_ports(context, ports.size(), &ports[0], &ssl[0]);
-    ports.resize(size);
-    ssl.resize(size);
-    return ports;
+	std::vector<int> ports(10);
+	std::vector<int> ssl(10);
+	size_t size = mg_get_ports(context, ports.size(), &ports[0], &ssl[0]);
+	ports.resize(size);
+	ssl.resize(size);
+	return ports;
 }
 
 CivetServer::CivetConnection::CivetConnection() {
-    postData = NULL;
-    postDataLen = 0;
+	postData = NULL;
+	postDataLen = 0;
 }
 
 CivetServer::CivetConnection::~CivetConnection() { free(postData); }

A diferenza do arquivo foi suprimida porque é demasiado grande
+ 399 - 398
src/civetweb.c


A diferenza do arquivo foi suprimida porque é demasiado grande
+ 522 - 522
src/main.c


+ 245 - 254
src/md5.inl

@@ -35,7 +35,7 @@
  */
 
 #ifndef md5_INCLUDED
-#  define md5_INCLUDED
+#define md5_INCLUDED
 
 /*
  * This package supports both compile-time and run-time determination of CPU
@@ -48,31 +48,31 @@
  */
 
 typedef unsigned char md5_byte_t; /* 8-bit byte */
-typedef unsigned int md5_word_t; /* 32-bit word */
+typedef unsigned int md5_word_t;  /* 32-bit word */
 
 /* Define the state of the MD5 Algorithm. */
 typedef struct md5_state_s {
-    md5_word_t count[2];    /* message length in bits, lsw first */
-    md5_word_t abcd[4];        /* digest buffer */
-    md5_byte_t buf[64];        /* accumulate block */
+	md5_word_t count[2]; /* message length in bits, lsw first */
+	md5_word_t abcd[4];  /* digest buffer */
+	md5_byte_t buf[64];  /* accumulate block */
 } md5_state_t;
 
 #ifdef __cplusplus
-extern "C"
-{
+extern "C" {
 #endif
 
 /* Initialize the algorithm. */
 MD5_STATIC void md5_init(md5_state_t *pms);
 
 /* Append a string to the message. */
-MD5_STATIC void md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes);
+MD5_STATIC void md5_append(md5_state_t *pms, const md5_byte_t *data,
+                           int nbytes);
 
 /* Finish the message and return the digest. */
 MD5_STATIC void md5_finish(md5_state_t *pms, md5_byte_t digest[16]);
 
 #ifdef __cplusplus
-}  /* end extern "C" */
+} /* end extern "C" */
 #endif
 
 #endif /* md5_INCLUDED */
@@ -134,330 +134,321 @@ MD5_STATIC void md5_finish(md5_state_t *pms, md5_byte_t digest[16]);
 #include <string.h>
 #endif
 
-#undef BYTE_ORDER    /* 1 = big-endian, -1 = little-endian, 0 = unknown */
+#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */
 #ifdef ARCH_IS_BIG_ENDIAN
-#  define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1)
+#define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1)
 #else
-#  define BYTE_ORDER 0
+#define BYTE_ORDER 0
 #endif
 
 #define T_MASK ((md5_word_t)~0)
 #define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87)
 #define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9)
-#define T3    0x242070db
+#define T3 0x242070db
 #define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111)
 #define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050)
-#define T6    0x4787c62a
+#define T6 0x4787c62a
 #define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec)
 #define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe)
-#define T9    0x698098d8
+#define T9 0x698098d8
 #define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850)
 #define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e)
 #define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841)
-#define T13    0x6b901122
+#define T13 0x6b901122
 #define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c)
 #define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71)
-#define T16    0x49b40821
+#define T16 0x49b40821
 #define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d)
 #define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf)
-#define T19    0x265e5a51
+#define T19 0x265e5a51
 #define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855)
 #define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2)
-#define T22    0x02441453
+#define T22 0x02441453
 #define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e)
 #define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437)
-#define T25    0x21e1cde6
+#define T25 0x21e1cde6
 #define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829)
 #define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278)
-#define T28    0x455a14ed
+#define T28 0x455a14ed
 #define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa)
 #define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07)
-#define T31    0x676f02d9
+#define T31 0x676f02d9
 #define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375)
 #define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd)
 #define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e)
-#define T35    0x6d9d6122
+#define T35 0x6d9d6122
 #define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3)
 #define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb)
-#define T38    0x4bdecfa9
+#define T38 0x4bdecfa9
 #define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f)
 #define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f)
-#define T41    0x289b7ec6
+#define T41 0x289b7ec6
 #define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805)
 #define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a)
-#define T44    0x04881d05
+#define T44 0x04881d05
 #define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6)
 #define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a)
-#define T47    0x1fa27cf8
+#define T47 0x1fa27cf8
 #define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a)
 #define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb)
-#define T50    0x432aff97
+#define T50 0x432aff97
 #define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58)
 #define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6)
-#define T53    0x655b59c3
+#define T53 0x655b59c3
 #define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d)
 #define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82)
 #define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e)
-#define T57    0x6fa87e4f
+#define T57 0x6fa87e4f
 #define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f)
 #define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb)
-#define T60    0x4e0811a1
+#define T60 0x4e0811a1
 #define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d)
 #define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca)
-#define T63    0x2ad7d2bb
+#define T63 0x2ad7d2bb
 #define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e)
 
-
-static void
-md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/)
-{
-    md5_word_t
-    a = pms->abcd[0], b = pms->abcd[1],
-    c = pms->abcd[2], d = pms->abcd[3];
-    md5_word_t t;
+static void md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/) {
+	md5_word_t a = pms->abcd[0], b = pms->abcd[1], c = pms->abcd[2],
+	           d = pms->abcd[3];
+	md5_word_t t;
 #if BYTE_ORDER > 0
-    /* Define storage only for big-endian CPUs. */
-    md5_word_t X[16];
+	/* Define storage only for big-endian CPUs. */
+	md5_word_t X[16];
 #else
-    /* Define storage for little-endian or both types of CPUs. */
-    md5_word_t xbuf[16];
-    const md5_word_t *X;
+	/* Define storage for little-endian or both types of CPUs. */
+	md5_word_t xbuf[16];
+	const md5_word_t *X;
 #endif
 
-    {
+	{
 #if BYTE_ORDER == 0
-        /*
-         * Determine dynamically whether this is a big-endian or
-         * little-endian machine, since we can use a more efficient
-         * algorithm on the latter.
-         */
-        static const int w = 1;
-
-        if (*((const md5_byte_t *)&w)) /* dynamic little-endian */
+		/*
+		 * Determine dynamically whether this is a big-endian or
+		 * little-endian machine, since we can use a more efficient
+		 * algorithm on the latter.
+		 */
+		static const int w = 1;
+
+		if (*((const md5_byte_t *)&w)) /* dynamic little-endian */
 #endif
-#if BYTE_ORDER <= 0        /* little-endian */
-        {
-            /*
-             * On little-endian machines, we can process properly aligned
-             * data without copying it.
-             */
-            if (!((data - (const md5_byte_t *)0) & 3)) {
-                /* data are properly aligned, a direct assignment is possible */
-                /* cast through a (void *) should avoid a compiler warning,
-                   see https://github.com/bel2125/civetweb/issues/94#issuecomment-98112861 */
-                X = (const md5_word_t *)(void *)data;
-            } else {
-                /* not aligned */
-                memcpy(xbuf, data, 64);
-                X = xbuf;
-            }
-        }
+#if BYTE_ORDER <= 0 /* little-endian */
+		{
+			/*
+			 * On little-endian machines, we can process properly aligned
+			 * data without copying it.
+			 */
+			if (!((data - (const md5_byte_t *)0) & 3)) {
+				/* data are properly aligned, a direct assignment is possible */
+				/* cast through a (void *) should avoid a compiler warning,
+				   see
+				   https://github.com/bel2125/civetweb/issues/94#issuecomment-98112861
+				   */
+				X = (const md5_word_t *)(void *)data;
+			} else {
+				/* not aligned */
+				memcpy(xbuf, data, 64);
+				X = xbuf;
+			}
+		}
 #endif
 #if BYTE_ORDER == 0
-        else            /* dynamic big-endian */
+		else /* dynamic big-endian */
+#endif
+#if BYTE_ORDER >= 0 /* big-endian */
+		{
+			/*
+			 * On big-endian machines, we must arrange the bytes in the
+			 * right order.
+			 */
+			const md5_byte_t *xp = data;
+			int i;
+
+#if BYTE_ORDER == 0
+			X = xbuf; /* (dynamic only) */
+#else
+#define xbuf X /* (static only) */
 #endif
-#if BYTE_ORDER >= 0        /* big-endian */
-        {
-            /*
-             * On big-endian machines, we must arrange the bytes in the
-             * right order.
-             */
-            const md5_byte_t *xp = data;
-            int i;
-
-#  if BYTE_ORDER == 0
-            X = xbuf;        /* (dynamic only) */
-#  else
-#    define xbuf X        /* (static only) */
-#  endif
-            for (i = 0; i < 16; ++i, xp += 4)
-                xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24);
-        }
+			for (i = 0; i < 16; ++i, xp += 4)
+				xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24);
+		}
 #endif
-    }
+	}
 
 #define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
 
-    /* Round 1. */
-    /* Let [abcd k s i] denote the operation
-       a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
+/* Round 1. */
+/* Let [abcd k s i] denote the operation
+   a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
 #define F(x, y, z) (((x) & (y)) | (~(x) & (z)))
-#define SET(a, b, c, d, k, s, Ti)\
-  t = a + F(b,c,d) + X[k] + Ti;\
-  a = ROTATE_LEFT(t, s) + b
-    /* Do the following 16 operations. */
-    SET(a, b, c, d,  0,  7,  T1);
-    SET(d, a, b, c,  1, 12,  T2);
-    SET(c, d, a, b,  2, 17,  T3);
-    SET(b, c, d, a,  3, 22,  T4);
-    SET(a, b, c, d,  4,  7,  T5);
-    SET(d, a, b, c,  5, 12,  T6);
-    SET(c, d, a, b,  6, 17,  T7);
-    SET(b, c, d, a,  7, 22,  T8);
-    SET(a, b, c, d,  8,  7,  T9);
-    SET(d, a, b, c,  9, 12, T10);
-    SET(c, d, a, b, 10, 17, T11);
-    SET(b, c, d, a, 11, 22, T12);
-    SET(a, b, c, d, 12,  7, T13);
-    SET(d, a, b, c, 13, 12, T14);
-    SET(c, d, a, b, 14, 17, T15);
-    SET(b, c, d, a, 15, 22, T16);
+#define SET(a, b, c, d, k, s, Ti)                                              \
+	t = a + F(b, c, d) + X[k] + Ti;                                            \
+	a = ROTATE_LEFT(t, s) + b
+	/* Do the following 16 operations. */
+	SET(a, b, c, d, 0, 7, T1);
+	SET(d, a, b, c, 1, 12, T2);
+	SET(c, d, a, b, 2, 17, T3);
+	SET(b, c, d, a, 3, 22, T4);
+	SET(a, b, c, d, 4, 7, T5);
+	SET(d, a, b, c, 5, 12, T6);
+	SET(c, d, a, b, 6, 17, T7);
+	SET(b, c, d, a, 7, 22, T8);
+	SET(a, b, c, d, 8, 7, T9);
+	SET(d, a, b, c, 9, 12, T10);
+	SET(c, d, a, b, 10, 17, T11);
+	SET(b, c, d, a, 11, 22, T12);
+	SET(a, b, c, d, 12, 7, T13);
+	SET(d, a, b, c, 13, 12, T14);
+	SET(c, d, a, b, 14, 17, T15);
+	SET(b, c, d, a, 15, 22, T16);
 #undef SET
 
-    /* Round 2. */
-    /* Let [abcd k s i] denote the operation
-         a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
+/* Round 2. */
+/* Let [abcd k s i] denote the operation
+     a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
 #define G(x, y, z) (((x) & (z)) | ((y) & ~(z)))
-#define SET(a, b, c, d, k, s, Ti)\
-  t = a + G(b,c,d) + X[k] + Ti;\
-  a = ROTATE_LEFT(t, s) + b
-    /* Do the following 16 operations. */
-    SET(a, b, c, d,  1,  5, T17);
-    SET(d, a, b, c,  6,  9, T18);
-    SET(c, d, a, b, 11, 14, T19);
-    SET(b, c, d, a,  0, 20, T20);
-    SET(a, b, c, d,  5,  5, T21);
-    SET(d, a, b, c, 10,  9, T22);
-    SET(c, d, a, b, 15, 14, T23);
-    SET(b, c, d, a,  4, 20, T24);
-    SET(a, b, c, d,  9,  5, T25);
-    SET(d, a, b, c, 14,  9, T26);
-    SET(c, d, a, b,  3, 14, T27);
-    SET(b, c, d, a,  8, 20, T28);
-    SET(a, b, c, d, 13,  5, T29);
-    SET(d, a, b, c,  2,  9, T30);
-    SET(c, d, a, b,  7, 14, T31);
-    SET(b, c, d, a, 12, 20, T32);
+#define SET(a, b, c, d, k, s, Ti)                                              \
+	t = a + G(b, c, d) + X[k] + Ti;                                            \
+	a = ROTATE_LEFT(t, s) + b
+	/* Do the following 16 operations. */
+	SET(a, b, c, d, 1, 5, T17);
+	SET(d, a, b, c, 6, 9, T18);
+	SET(c, d, a, b, 11, 14, T19);
+	SET(b, c, d, a, 0, 20, T20);
+	SET(a, b, c, d, 5, 5, T21);
+	SET(d, a, b, c, 10, 9, T22);
+	SET(c, d, a, b, 15, 14, T23);
+	SET(b, c, d, a, 4, 20, T24);
+	SET(a, b, c, d, 9, 5, T25);
+	SET(d, a, b, c, 14, 9, T26);
+	SET(c, d, a, b, 3, 14, T27);
+	SET(b, c, d, a, 8, 20, T28);
+	SET(a, b, c, d, 13, 5, T29);
+	SET(d, a, b, c, 2, 9, T30);
+	SET(c, d, a, b, 7, 14, T31);
+	SET(b, c, d, a, 12, 20, T32);
 #undef SET
 
-    /* Round 3. */
-    /* Let [abcd k s t] denote the operation
-         a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
+/* Round 3. */
+/* Let [abcd k s t] denote the operation
+     a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
 #define H(x, y, z) ((x) ^ (y) ^ (z))
-#define SET(a, b, c, d, k, s, Ti)\
-  t = a + H(b,c,d) + X[k] + Ti;\
-  a = ROTATE_LEFT(t, s) + b
-    /* Do the following 16 operations. */
-    SET(a, b, c, d,  5,  4, T33);
-    SET(d, a, b, c,  8, 11, T34);
-    SET(c, d, a, b, 11, 16, T35);
-    SET(b, c, d, a, 14, 23, T36);
-    SET(a, b, c, d,  1,  4, T37);
-    SET(d, a, b, c,  4, 11, T38);
-    SET(c, d, a, b,  7, 16, T39);
-    SET(b, c, d, a, 10, 23, T40);
-    SET(a, b, c, d, 13,  4, T41);
-    SET(d, a, b, c,  0, 11, T42);
-    SET(c, d, a, b,  3, 16, T43);
-    SET(b, c, d, a,  6, 23, T44);
-    SET(a, b, c, d,  9,  4, T45);
-    SET(d, a, b, c, 12, 11, T46);
-    SET(c, d, a, b, 15, 16, T47);
-    SET(b, c, d, a,  2, 23, T48);
+#define SET(a, b, c, d, k, s, Ti)                                              \
+	t = a + H(b, c, d) + X[k] + Ti;                                            \
+	a = ROTATE_LEFT(t, s) + b
+	/* Do the following 16 operations. */
+	SET(a, b, c, d, 5, 4, T33);
+	SET(d, a, b, c, 8, 11, T34);
+	SET(c, d, a, b, 11, 16, T35);
+	SET(b, c, d, a, 14, 23, T36);
+	SET(a, b, c, d, 1, 4, T37);
+	SET(d, a, b, c, 4, 11, T38);
+	SET(c, d, a, b, 7, 16, T39);
+	SET(b, c, d, a, 10, 23, T40);
+	SET(a, b, c, d, 13, 4, T41);
+	SET(d, a, b, c, 0, 11, T42);
+	SET(c, d, a, b, 3, 16, T43);
+	SET(b, c, d, a, 6, 23, T44);
+	SET(a, b, c, d, 9, 4, T45);
+	SET(d, a, b, c, 12, 11, T46);
+	SET(c, d, a, b, 15, 16, T47);
+	SET(b, c, d, a, 2, 23, T48);
 #undef SET
 
-    /* Round 4. */
-    /* Let [abcd k s t] denote the operation
-         a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
+/* Round 4. */
+/* Let [abcd k s t] denote the operation
+     a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
 #define I(x, y, z) ((y) ^ ((x) | ~(z)))
-#define SET(a, b, c, d, k, s, Ti)\
-  t = a + I(b,c,d) + X[k] + Ti;\
-  a = ROTATE_LEFT(t, s) + b
-    /* Do the following 16 operations. */
-    SET(a, b, c, d,  0,  6, T49);
-    SET(d, a, b, c,  7, 10, T50);
-    SET(c, d, a, b, 14, 15, T51);
-    SET(b, c, d, a,  5, 21, T52);
-    SET(a, b, c, d, 12,  6, T53);
-    SET(d, a, b, c,  3, 10, T54);
-    SET(c, d, a, b, 10, 15, T55);
-    SET(b, c, d, a,  1, 21, T56);
-    SET(a, b, c, d,  8,  6, T57);
-    SET(d, a, b, c, 15, 10, T58);
-    SET(c, d, a, b,  6, 15, T59);
-    SET(b, c, d, a, 13, 21, T60);
-    SET(a, b, c, d,  4,  6, T61);
-    SET(d, a, b, c, 11, 10, T62);
-    SET(c, d, a, b,  2, 15, T63);
-    SET(b, c, d, a,  9, 21, T64);
+#define SET(a, b, c, d, k, s, Ti)                                              \
+	t = a + I(b, c, d) + X[k] + Ti;                                            \
+	a = ROTATE_LEFT(t, s) + b
+	/* Do the following 16 operations. */
+	SET(a, b, c, d, 0, 6, T49);
+	SET(d, a, b, c, 7, 10, T50);
+	SET(c, d, a, b, 14, 15, T51);
+	SET(b, c, d, a, 5, 21, T52);
+	SET(a, b, c, d, 12, 6, T53);
+	SET(d, a, b, c, 3, 10, T54);
+	SET(c, d, a, b, 10, 15, T55);
+	SET(b, c, d, a, 1, 21, T56);
+	SET(a, b, c, d, 8, 6, T57);
+	SET(d, a, b, c, 15, 10, T58);
+	SET(c, d, a, b, 6, 15, T59);
+	SET(b, c, d, a, 13, 21, T60);
+	SET(a, b, c, d, 4, 6, T61);
+	SET(d, a, b, c, 11, 10, T62);
+	SET(c, d, a, b, 2, 15, T63);
+	SET(b, c, d, a, 9, 21, T64);
 #undef SET
 
-    /* Then perform the following additions. (That is increment each
-       of the four registers by the value it had before this block
-       was started.) */
-    pms->abcd[0] += a;
-    pms->abcd[1] += b;
-    pms->abcd[2] += c;
-    pms->abcd[3] += d;
+	/* Then perform the following additions. (That is increment each
+	   of the four registers by the value it had before this block
+	   was started.) */
+	pms->abcd[0] += a;
+	pms->abcd[1] += b;
+	pms->abcd[2] += c;
+	pms->abcd[3] += d;
 }
 
-MD5_STATIC void
-md5_init(md5_state_t *pms)
-{
-    pms->count[0] = pms->count[1] = 0;
-    pms->abcd[0] = 0x67452301;
-    pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476;
-    pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301;
-    pms->abcd[3] = 0x10325476;
+MD5_STATIC void md5_init(md5_state_t *pms) {
+	pms->count[0] = pms->count[1] = 0;
+	pms->abcd[0] = 0x67452301;
+	pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476;
+	pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301;
+	pms->abcd[3] = 0x10325476;
 }
 
-MD5_STATIC void
-md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes)
-{
-    const md5_byte_t *p = data;
-    int left = nbytes;
-    int offset = (pms->count[0] >> 3) & 63;
-    md5_word_t nbits = (md5_word_t)(nbytes << 3);
-
-    if (nbytes <= 0)
-        return;
-
-    /* Update the message length. */
-    pms->count[1] += nbytes >> 29;
-    pms->count[0] += nbits;
-    if (pms->count[0] < nbits)
-        pms->count[1]++;
-
-    /* Process an initial partial block. */
-    if (offset) {
-        int copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
-
-        memcpy(pms->buf + offset, p, copy);
-        if (offset + copy < 64)
-            return;
-        p += copy;
-        left -= copy;
-        md5_process(pms, pms->buf);
-    }
-
-    /* Process full blocks. */
-    for (; left >= 64; p += 64, left -= 64)
-        md5_process(pms, p);
-
-    /* Process a final partial block. */
-    if (left)
-        memcpy(pms->buf, p, left);
+MD5_STATIC void md5_append(md5_state_t *pms, const md5_byte_t *data,
+                           int nbytes) {
+	const md5_byte_t *p = data;
+	int left = nbytes;
+	int offset = (pms->count[0] >> 3) & 63;
+	md5_word_t nbits = (md5_word_t)(nbytes << 3);
+
+	if (nbytes <= 0)
+		return;
+
+	/* Update the message length. */
+	pms->count[1] += nbytes >> 29;
+	pms->count[0] += nbits;
+	if (pms->count[0] < nbits)
+		pms->count[1]++;
+
+	/* Process an initial partial block. */
+	if (offset) {
+		int copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
+
+		memcpy(pms->buf + offset, p, copy);
+		if (offset + copy < 64)
+			return;
+		p += copy;
+		left -= copy;
+		md5_process(pms, pms->buf);
+	}
+
+	/* Process full blocks. */
+	for (; left >= 64; p += 64, left -= 64)
+		md5_process(pms, p);
+
+	/* Process a final partial block. */
+	if (left)
+		memcpy(pms->buf, p, left);
 }
 
-MD5_STATIC void
-md5_finish(md5_state_t *pms, md5_byte_t digest[16])
-{
-    static const md5_byte_t pad[64] = {
-        0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
-    };
-    md5_byte_t data[8];
-    int i;
-
-    /* Save the length before padding. */
-    for (i = 0; i < 8; ++i)
-        data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
-    /* Pad to 56 bytes mod 64. */
-    md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1);
-    /* Append the length. */
-    md5_append(pms, data, 8);
-    for (i = 0; i < 16; ++i)
-        digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
+MD5_STATIC void md5_finish(md5_state_t *pms, md5_byte_t digest[16]) {
+	static const md5_byte_t pad[64] = {
+	    0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+	    0,    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+	    0,    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
+	md5_byte_t data[8];
+	int i;
+
+	/* Save the length before padding. */
+	for (i = 0; i < 8; ++i)
+		data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
+	/* Pad to 56 bytes mod 64. */
+	md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1);
+	/* Append the length. */
+	md5_append(pms, data, 8);
+	for (i = 0; i < 16; ++i)
+		digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
 }

+ 1250 - 1215
src/mod_lua.inl

@@ -3,19 +3,15 @@
 
 #ifdef _WIN32
 static void *mmap(void *addr, int64_t len, int prot, int flags, int fd,
-    int offset)
-{
-    HANDLE fh = (HANDLE) _get_osfhandle(fd);
-    HANDLE mh = CreateFileMapping(fh, 0, PAGE_READONLY, 0, 0, 0);
-    void *p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, (size_t) len);
-    CloseHandle(mh);
-    return p;
+                  int offset) {
+	HANDLE fh = (HANDLE)_get_osfhandle(fd);
+	HANDLE mh = CreateFileMapping(fh, 0, PAGE_READONLY, 0, 0, 0);
+	void *p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, (size_t)len);
+	CloseHandle(mh);
+	return p;
 }
 
-static void munmap(void *addr, int64_t length)
-{
-    UnmapViewOfFile(addr);
-}
+static void munmap(void *addr, int64_t length) { UnmapViewOfFile(addr); }
 
 #define MAP_FAILED NULL
 #define MAP_PRIVATE 0
@@ -31,1380 +27,1419 @@ static const char lua_regkey_connlist = 2;
 /* Forward declarations */
 static void handle_request(struct mg_connection *);
 static int handle_lsp_request(struct mg_connection *, const char *,
-struct file *, struct lua_State *);
-
-static void reg_string(struct lua_State *L, const char *name, const char *val)
-{
-    if (name!=NULL && val!=NULL) {
-        lua_pushstring(L, name);
-        lua_pushstring(L, val);
-        lua_rawset(L, -3);
-    }
+                              struct file *, struct lua_State *);
+
+static void reg_string(struct lua_State *L, const char *name, const char *val) {
+	if (name != NULL && val != NULL) {
+		lua_pushstring(L, name);
+		lua_pushstring(L, val);
+		lua_rawset(L, -3);
+	}
 }
 
-static void reg_int(struct lua_State *L, const char *name, int val)
-{
-    if (name!=NULL) {
-        lua_pushstring(L, name);
-        lua_pushinteger(L, val);
-        lua_rawset(L, -3);
-    }
+static void reg_int(struct lua_State *L, const char *name, int val) {
+	if (name != NULL) {
+		lua_pushstring(L, name);
+		lua_pushinteger(L, val);
+		lua_rawset(L, -3);
+	}
 }
 
-static void reg_boolean(struct lua_State *L, const char *name, int val)
-{
-    if (name!=NULL) {
-        lua_pushstring(L, name);
-        lua_pushboolean(L, val != 0);
-        lua_rawset(L, -3);
-    }
+static void reg_boolean(struct lua_State *L, const char *name, int val) {
+	if (name != NULL) {
+		lua_pushstring(L, name);
+		lua_pushboolean(L, val != 0);
+		lua_rawset(L, -3);
+	}
 }
 
 static void reg_conn_function(struct lua_State *L, const char *name,
-    lua_CFunction func, struct mg_connection *conn)
-{
-    if (name!=NULL && func!=NULL && conn!=NULL) {
-        lua_pushstring(L, name);
-        lua_pushlightuserdata(L, conn);
-        lua_pushcclosure(L, func, 1);
-        lua_rawset(L, -3);
-    }
+                              lua_CFunction func, struct mg_connection *conn) {
+	if (name != NULL && func != NULL && conn != NULL) {
+		lua_pushstring(L, name);
+		lua_pushlightuserdata(L, conn);
+		lua_pushcclosure(L, func, 1);
+		lua_rawset(L, -3);
+	}
 }
 
-static void reg_function(struct lua_State *L, const char *name, lua_CFunction func)
-{
-    if (name!=NULL && func!=NULL) {
-        lua_pushstring(L, name);
-        lua_pushcclosure(L, func, 0);
-        lua_rawset(L, -3);
-    }
+static void reg_function(struct lua_State *L, const char *name,
+                         lua_CFunction func) {
+	if (name != NULL && func != NULL) {
+		lua_pushstring(L, name);
+		lua_pushcclosure(L, func, 0);
+		lua_rawset(L, -3);
+	}
 }
 
-static void lua_cry(struct mg_connection *conn, int err, lua_State * L, const char * lua_title, const char * lua_operation)
-{
-    switch (err) {
-    case LUA_OK:
-    case LUA_YIELD:
-        break;
-    case LUA_ERRRUN:
-        mg_cry(conn, "%s: %s failed: runtime error: %s", lua_title, lua_operation, lua_tostring(L, -1));
-        break;
-    case LUA_ERRSYNTAX:
-        mg_cry(conn, "%s: %s failed: syntax error: %s", lua_title, lua_operation, lua_tostring(L, -1));
-        break;
-    case LUA_ERRMEM:
-        mg_cry(conn, "%s: %s failed: out of memory", lua_title, lua_operation);
-        break;
-    case LUA_ERRGCMM:
-        mg_cry(conn, "%s: %s failed: error during garbage collection", lua_title, lua_operation);
-        break;
-    case LUA_ERRERR:
-        mg_cry(conn, "%s: %s failed: error in error handling: %s", lua_title, lua_operation, lua_tostring(L, -1));
-        break;
-    default:
-        mg_cry(conn, "%s: %s failed: error %i", lua_title, lua_operation, err);
-        break;
-    }
+static void lua_cry(struct mg_connection *conn, int err, lua_State *L,
+                    const char *lua_title, const char *lua_operation) {
+	switch (err) {
+	case LUA_OK:
+	case LUA_YIELD:
+		break;
+	case LUA_ERRRUN:
+		mg_cry(conn, "%s: %s failed: runtime error: %s", lua_title,
+		       lua_operation, lua_tostring(L, -1));
+		break;
+	case LUA_ERRSYNTAX:
+		mg_cry(conn, "%s: %s failed: syntax error: %s", lua_title,
+		       lua_operation, lua_tostring(L, -1));
+		break;
+	case LUA_ERRMEM:
+		mg_cry(conn, "%s: %s failed: out of memory", lua_title, lua_operation);
+		break;
+	case LUA_ERRGCMM:
+		mg_cry(conn, "%s: %s failed: error during garbage collection",
+		       lua_title, lua_operation);
+		break;
+	case LUA_ERRERR:
+		mg_cry(conn, "%s: %s failed: error in error handling: %s", lua_title,
+		       lua_operation, lua_tostring(L, -1));
+		break;
+	default:
+		mg_cry(conn, "%s: %s failed: error %i", lua_title, lua_operation, err);
+		break;
+	}
 }
 
-static int lsp_sock_close(lua_State *L)
-{
-    int num_args = lua_gettop(L);
-    if ((num_args == 1) && lua_istable(L, -1)) {
-        lua_getfield(L, -1, "sock");
-        closesocket((SOCKET) lua_tonumber(L, -1));
-    } else {
-        return luaL_error(L, "invalid :close() call");
-    }
-    return 1;
+static int lsp_sock_close(lua_State *L) {
+	int num_args = lua_gettop(L);
+	if ((num_args == 1) && lua_istable(L, -1)) {
+		lua_getfield(L, -1, "sock");
+		closesocket((SOCKET)lua_tonumber(L, -1));
+	} else {
+		return luaL_error(L, "invalid :close() call");
+	}
+	return 1;
 }
 
-static int lsp_sock_recv(lua_State *L)
-{
-    int num_args = lua_gettop(L);
-    char buf[2000];
-    int n;
-
-    if ((num_args == 1) && lua_istable(L, -1)) {
-        lua_getfield(L, -1, "sock");
-        n = recv((SOCKET) lua_tonumber(L, -1), buf, sizeof(buf), 0);
-        if (n <= 0) {
-            lua_pushnil(L);
-        } else {
-            lua_pushlstring(L, buf, n);
-        }
-    } else {
-        return luaL_error(L, "invalid :close() call");
-    }
-    return 1;
+static int lsp_sock_recv(lua_State *L) {
+	int num_args = lua_gettop(L);
+	char buf[2000];
+	int n;
+
+	if ((num_args == 1) && lua_istable(L, -1)) {
+		lua_getfield(L, -1, "sock");
+		n = recv((SOCKET)lua_tonumber(L, -1), buf, sizeof(buf), 0);
+		if (n <= 0) {
+			lua_pushnil(L);
+		} else {
+			lua_pushlstring(L, buf, n);
+		}
+	} else {
+		return luaL_error(L, "invalid :close() call");
+	}
+	return 1;
 }
 
-static int lsp_sock_send(lua_State *L)
-{
-    int num_args = lua_gettop(L);
-    const char *buf;
-    size_t len, sent = 0;
-    int n = 0, sock;
-
-    if ((num_args == 2) && lua_istable(L, -2) && lua_isstring(L, -1)) {
-        buf = lua_tolstring(L, -1, &len);
-        lua_getfield(L, -2, "sock");
-        sock = (int) lua_tonumber(L, -1);
-        while (sent < len) {
-            if ((n = send(sock, buf + sent, (int)(len - sent), 0)) <= 0) {
-                break;
-            }
-            sent += n;
-        }
-        lua_pushnumber(L, n);
-    } else {
-        return luaL_error(L, "invalid :close() call");
-    }
-    return 1;
+static int lsp_sock_send(lua_State *L) {
+	int num_args = lua_gettop(L);
+	const char *buf;
+	size_t len, sent = 0;
+	int n = 0, sock;
+
+	if ((num_args == 2) && lua_istable(L, -2) && lua_isstring(L, -1)) {
+		buf = lua_tolstring(L, -1, &len);
+		lua_getfield(L, -2, "sock");
+		sock = (int)lua_tonumber(L, -1);
+		while (sent < len) {
+			if ((n = send(sock, buf + sent, (int)(len - sent), 0)) <= 0) {
+				break;
+			}
+			sent += n;
+		}
+		lua_pushnumber(L, n);
+	} else {
+		return luaL_error(L, "invalid :close() call");
+	}
+	return 1;
 }
 
-static const struct luaL_Reg luasocket_methods[] = {
-    {"close", lsp_sock_close},
-    {"send", lsp_sock_send},
-    {"recv", lsp_sock_recv},
-    {NULL, NULL}
-};
-
-static int lsp_connect(lua_State *L)
-{
-    int num_args = lua_gettop(L);
-    char ebuf[100];
-    SOCKET sock;
-
-    if ((num_args == 3) && lua_isstring(L, -3) && lua_isnumber(L, -2) && lua_isnumber(L, -1)) {
-        sock = conn2(NULL, lua_tostring(L, -3), (int) lua_tonumber(L, -2),
-            (int) lua_tonumber(L, -1), ebuf, sizeof(ebuf));
-        if (sock == INVALID_SOCKET) {
-            return luaL_error(L, ebuf);
-        } else {
-            lua_newtable(L);
-            reg_int(L, "sock", (int) sock);
-            reg_string(L, "host", lua_tostring(L, -4));
-            luaL_getmetatable(L, LUASOCKET);
-            lua_setmetatable(L, -2);
-        }
-    } else {
-        return luaL_error(L, "connect(host,port,is_ssl): invalid parameter given.");
-    }
-    return 1;
+static const struct luaL_Reg luasocket_methods[] = {{"close", lsp_sock_close},
+                                                    {"send", lsp_sock_send},
+                                                    {"recv", lsp_sock_recv},
+                                                    {NULL, NULL}};
+
+static int lsp_connect(lua_State *L) {
+	int num_args = lua_gettop(L);
+	char ebuf[100];
+	SOCKET sock;
+
+	if ((num_args == 3) && lua_isstring(L, -3) && lua_isnumber(L, -2) &&
+	    lua_isnumber(L, -1)) {
+		sock = conn2(NULL, lua_tostring(L, -3), (int)lua_tonumber(L, -2),
+		             (int)lua_tonumber(L, -1), ebuf, sizeof(ebuf));
+		if (sock == INVALID_SOCKET) {
+			return luaL_error(L, ebuf);
+		} else {
+			lua_newtable(L);
+			reg_int(L, "sock", (int)sock);
+			reg_string(L, "host", lua_tostring(L, -4));
+			luaL_getmetatable(L, LUASOCKET);
+			lua_setmetatable(L, -2);
+		}
+	} else {
+		return luaL_error(
+		    L, "connect(host,port,is_ssl): invalid parameter given.");
+	}
+	return 1;
 }
 
-static int lsp_error(lua_State *L)
-{
-    lua_getglobal(L, "mg");
-    lua_getfield(L, -1, "onerror");
-    lua_pushvalue(L, -3);
-    lua_pcall(L, 1, 0, 0);
-    return 0;
+static int lsp_error(lua_State *L) {
+	lua_getglobal(L, "mg");
+	lua_getfield(L, -1, "onerror");
+	lua_pushvalue(L, -3);
+	lua_pcall(L, 1, 0, 0);
+	return 0;
 }
 
 /* Silently stop processing chunks. */
-static void lsp_abort(lua_State *L)
-{
-    int top = lua_gettop(L);
-    lua_getglobal(L, "mg");
-    lua_pushnil(L);
-    lua_setfield(L, -2, "onerror");
-    lua_settop(L, top);
-    lua_pushstring(L, "aborting");
-    lua_error(L);
+static void lsp_abort(lua_State *L) {
+	int top = lua_gettop(L);
+	lua_getglobal(L, "mg");
+	lua_pushnil(L);
+	lua_setfield(L, -2, "onerror");
+	lua_settop(L, top);
+	lua_pushstring(L, "aborting");
+	lua_error(L);
 }
 
-struct lsp_var_reader_data
-{
-    const char * begin;
-    unsigned len;
-    unsigned state;
+struct lsp_var_reader_data {
+	const char *begin;
+	unsigned len;
+	unsigned state;
 };
 
-static const char * lsp_var_reader(lua_State *L, void *ud, size_t *sz)
-{
-    struct lsp_var_reader_data * reader = (struct lsp_var_reader_data *)ud;
-    const char * ret;
-    (void)(L); /* unused */
-
-    switch (reader->state) {
-    case 0:
-        ret = "mg.write(";
-        *sz = strlen(ret);
-        break;
-    case 1:
-        ret = reader->begin;
-        *sz = reader->len;
-        break;
-    case 2:
-        ret = ")";
-        *sz = strlen(ret);
-        break;
-    default:
-        ret = 0;
-        *sz = 0;
-    }
-
-    reader->state++;
-    return ret;
+static const char *lsp_var_reader(lua_State *L, void *ud, size_t *sz) {
+	struct lsp_var_reader_data *reader = (struct lsp_var_reader_data *)ud;
+	const char *ret;
+	(void)(L); /* unused */
+
+	switch (reader->state) {
+	case 0:
+		ret = "mg.write(";
+		*sz = strlen(ret);
+		break;
+	case 1:
+		ret = reader->begin;
+		*sz = reader->len;
+		break;
+	case 2:
+		ret = ")";
+		*sz = strlen(ret);
+		break;
+	default:
+		ret = 0;
+		*sz = 0;
+	}
+
+	reader->state++;
+	return ret;
 }
 
-static int lsp(struct mg_connection *conn, const char *path,
-    const char *p, int64_t len, lua_State *L)
-{
-    int i, j, pos = 0, lines = 1, lualines = 0, is_var, lua_ok;
-    char chunkname[MG_BUF_LEN];
-    struct lsp_var_reader_data data;
-
-    for (i = 0; i < len; i++) {
-        if (p[i] == '\n') lines++;
-        if ((i + 1) < len && p[i] == '<' && p[i + 1] == '?') {
-
-            /* <?= ?> means a variable is enclosed and its value should be printed */
-            is_var = ((i + 2) < len && p[i + 2] == '=');
-
-            if (is_var) j = i + 2;
-            else j = i + 1;
-
-            while (j < len) {
-                if (p[j] == '\n') lualines++;
-                if ((j + 1) < len && p[j] == '?' && p[j + 1] == '>') {
-                    mg_write(conn, p + pos, i - pos);
-
-                    snprintf(chunkname, sizeof(chunkname), "@%s+%i", path, lines);
-                    lua_pushlightuserdata(L, conn);
-                    lua_pushcclosure(L, lsp_error, 1);
-
-                    if (is_var) {
-                        data.begin = p + (i + 3);
-                        data.len = j - (i + 3);
-                        data.state = 0;
-                        lua_ok = lua_load(L, lsp_var_reader, &data, chunkname, NULL);
-                    } else {
-                        lua_ok = luaL_loadbuffer(L, p + (i + 2), j - (i + 2), chunkname);
-                    }
-
-                    if (lua_ok) {
-                        /* Syntax error or OOM. Error message is pushed on stack. */
-                        lua_pcall(L, 1, 0, 0);
-                    } else {
-                        /* Success loading chunk. Call it. */
-                        lua_pcall(L, 0, 0, 1);
-                    }
-
-                    pos = j + 2;
-                    i = pos - 1;
-                    break;
-                }
-                j++;
-            }
-
-            if (lualines > 0) {
-                lines += lualines;
-                lualines = 0;
-            }
-        }
-    }
-
-    if (i > pos) {
-        mg_write(conn, p + pos, i - pos);
-    }
-
-    return 0;
+static int lsp(struct mg_connection *conn, const char *path, const char *p,
+               int64_t len, lua_State *L) {
+	int i, j, pos = 0, lines = 1, lualines = 0, is_var, lua_ok;
+	char chunkname[MG_BUF_LEN];
+	struct lsp_var_reader_data data;
+
+	for (i = 0; i < len; i++) {
+		if (p[i] == '\n')
+			lines++;
+		if ((i + 1) < len && p[i] == '<' && p[i + 1] == '?') {
+
+			/* <?= ?> means a variable is enclosed and its value should be
+			 * printed */
+			is_var = ((i + 2) < len && p[i + 2] == '=');
+
+			if (is_var)
+				j = i + 2;
+			else
+				j = i + 1;
+
+			while (j < len) {
+				if (p[j] == '\n')
+					lualines++;
+				if ((j + 1) < len && p[j] == '?' && p[j + 1] == '>') {
+					mg_write(conn, p + pos, i - pos);
+
+					snprintf(chunkname, sizeof(chunkname), "@%s+%i", path,
+					         lines);
+					lua_pushlightuserdata(L, conn);
+					lua_pushcclosure(L, lsp_error, 1);
+
+					if (is_var) {
+						data.begin = p + (i + 3);
+						data.len = j - (i + 3);
+						data.state = 0;
+						lua_ok =
+						    lua_load(L, lsp_var_reader, &data, chunkname, NULL);
+					} else {
+						lua_ok = luaL_loadbuffer(L, p + (i + 2), j - (i + 2),
+						                         chunkname);
+					}
+
+					if (lua_ok) {
+						/* Syntax error or OOM. Error message is pushed on
+						 * stack. */
+						lua_pcall(L, 1, 0, 0);
+					} else {
+						/* Success loading chunk. Call it. */
+						lua_pcall(L, 0, 0, 1);
+					}
+
+					pos = j + 2;
+					i = pos - 1;
+					break;
+				}
+				j++;
+			}
+
+			if (lualines > 0) {
+				lines += lualines;
+				lualines = 0;
+			}
+		}
+	}
+
+	if (i > pos) {
+		mg_write(conn, p + pos, i - pos);
+	}
+
+	return 0;
 }
 
 /* mg.write: Send data to the client */
-static int lsp_write(lua_State *L)
-{
-    struct mg_connection *conn = (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
-    int num_args = lua_gettop(L);
-    const char *str;
-    size_t size;
-    int i;
-
-    for (i = 1; i <= num_args; i++) {
-        if (lua_isstring(L, i)) {
-            str = lua_tolstring(L, i, &size);
-            mg_write(conn, str, size);
-        }
-    }
-
-    return 0;
+static int lsp_write(lua_State *L) {
+	struct mg_connection *conn =
+	    (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
+	int num_args = lua_gettop(L);
+	const char *str;
+	size_t size;
+	int i;
+
+	for (i = 1; i <= num_args; i++) {
+		if (lua_isstring(L, i)) {
+			str = lua_tolstring(L, i, &size);
+			mg_write(conn, str, size);
+		}
+	}
+
+	return 0;
 }
 
 /* mg.read: Read data from the client (e.g., from a POST request) */
-static int lsp_read(lua_State *L)
-{
-    struct mg_connection *conn = (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
-    char buf[1024];
-    int len = mg_read(conn, buf, sizeof(buf));
+static int lsp_read(lua_State *L) {
+	struct mg_connection *conn =
+	    (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
+	char buf[1024];
+	int len = mg_read(conn, buf, sizeof(buf));
 
-    if (len <= 0) return 0;
-    lua_pushlstring(L, buf, len);
+	if (len <= 0)
+		return 0;
+	lua_pushlstring(L, buf, len);
 
-    return 1;
+	return 1;
 }
 
 /* mg.keep_alive: Allow Lua pages to use the http keep-alive mechanism */
-static int lsp_keep_alive(lua_State *L)
-{
-    struct mg_connection *conn = (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
-    int num_args = lua_gettop(L);
-
-    /* This function may be called with one parameter (boolean) to set the keep_alive state.
-    Or without a parameter to just query the current keep_alive state. */
-    if ((num_args==1) && lua_isboolean(L, 1)) {
-        conn->must_close = !lua_toboolean(L, 1);
-    } else if (num_args != 0) {
-        /* Syntax error */
-        return luaL_error(L, "invalid keep_alive() call");
-    }
-
-    /* Return the current "keep_alive" state. This may be false, even it keep_alive(true) has been called. */
-    lua_pushboolean(L, should_keep_alive(conn));
-    return 1;
+static int lsp_keep_alive(lua_State *L) {
+	struct mg_connection *conn =
+	    (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
+	int num_args = lua_gettop(L);
+
+	/* This function may be called with one parameter (boolean) to set the
+	keep_alive state.
+	Or without a parameter to just query the current keep_alive state. */
+	if ((num_args == 1) && lua_isboolean(L, 1)) {
+		conn->must_close = !lua_toboolean(L, 1);
+	} else if (num_args != 0) {
+		/* Syntax error */
+		return luaL_error(L, "invalid keep_alive() call");
+	}
+
+	/* Return the current "keep_alive" state. This may be false, even it
+	 * keep_alive(true) has been called. */
+	lua_pushboolean(L, should_keep_alive(conn));
+	return 1;
 }
 
 /* mg.include: Include another .lp file */
-static int lsp_include(lua_State *L)
-{
-    struct mg_connection *conn = (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
-    int num_args = lua_gettop(L);
-    struct file file = STRUCT_FILE_INITIALIZER;
-    const char * filename = (num_args == 1) ? lua_tostring(L, 1) : NULL;
-
-    if (filename) {
-        if (handle_lsp_request(conn, filename, &file, L)) {
-            /* handle_lsp_request returned an error code, meaning an error occured in
-            the included page and mg.onerror returned non-zero. Stop processing. */
-            lsp_abort(L);
-        }
-    } else {
-        /* Syntax error */
-        return luaL_error(L, "invalid include() call");
-    }
-    return 0;
+static int lsp_include(lua_State *L) {
+	struct mg_connection *conn =
+	    (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
+	int num_args = lua_gettop(L);
+	struct file file = STRUCT_FILE_INITIALIZER;
+	const char *filename = (num_args == 1) ? lua_tostring(L, 1) : NULL;
+
+	if (filename) {
+		if (handle_lsp_request(conn, filename, &file, L)) {
+			/* handle_lsp_request returned an error code, meaning an error
+			occured in
+			the included page and mg.onerror returned non-zero. Stop processing.
+			*/
+			lsp_abort(L);
+		}
+	} else {
+		/* Syntax error */
+		return luaL_error(L, "invalid include() call");
+	}
+	return 0;
 }
 
 /* mg.cry: Log an error. Default value for mg.onerror. */
-static int lsp_cry(lua_State *L)
-{
-    struct mg_connection *conn = (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
-    int num_args = lua_gettop(L);
-    const char * text = (num_args == 1) ? lua_tostring(L, 1) : NULL;
-
-    if (text) {
-        mg_cry(conn, "%s", lua_tostring(L, -1));
-    } else {
-        /* Syntax error */
-        return luaL_error(L, "invalid cry() call");
-    }
-    return 0;
+static int lsp_cry(lua_State *L) {
+	struct mg_connection *conn =
+	    (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
+	int num_args = lua_gettop(L);
+	const char *text = (num_args == 1) ? lua_tostring(L, 1) : NULL;
+
+	if (text) {
+		mg_cry(conn, "%s", lua_tostring(L, -1));
+	} else {
+		/* Syntax error */
+		return luaL_error(L, "invalid cry() call");
+	}
+	return 0;
 }
 
 /* mg.redirect: Redirect the request (internally). */
-static int lsp_redirect(lua_State *L)
-{
-    struct mg_connection *conn = (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
-    int num_args = lua_gettop(L);
-    const char * target = (num_args == 1) ? lua_tostring(L, 1) : NULL;
-
-    if (target) {
-        conn->request_info.uri = target;
-        handle_request(conn);
-        lsp_abort(L);
-    } else {
-        /* Syntax error */
-        return luaL_error(L, "invalid redirect() call");
-    }
-    return 0;
+static int lsp_redirect(lua_State *L) {
+	struct mg_connection *conn =
+	    (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
+	int num_args = lua_gettop(L);
+	const char *target = (num_args == 1) ? lua_tostring(L, 1) : NULL;
+
+	if (target) {
+		conn->request_info.uri = target;
+		handle_request(conn);
+		lsp_abort(L);
+	} else {
+		/* Syntax error */
+		return luaL_error(L, "invalid redirect() call");
+	}
+	return 0;
 }
 
 /* mg.send_file */
-static int lsp_send_file(lua_State *L)
-{
-    struct mg_connection *conn = (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
-    int num_args = lua_gettop(L);
-    const char * filename = (num_args == 1) ? lua_tostring(L, 1) : NULL;
-
-    if (filename) {
-        mg_send_file(conn, filename);
-    } else {
-        /* Syntax error */
-        return luaL_error(L, "invalid send_file() call");
-    }
-    return 0;
+static int lsp_send_file(lua_State *L) {
+	struct mg_connection *conn =
+	    (struct mg_connection *)lua_touserdata(L, lua_upvalueindex(1));
+	int num_args = lua_gettop(L);
+	const char *filename = (num_args == 1) ? lua_tostring(L, 1) : NULL;
+
+	if (filename) {
+		mg_send_file(conn, filename);
+	} else {
+		/* Syntax error */
+		return luaL_error(L, "invalid send_file() call");
+	}
+	return 0;
 }
 
 /* mg.get_time */
-static int lsp_get_time(lua_State *L)
-{
-    int num_args = lua_gettop(L);
-    int monotonic = (num_args > 0) ? lua_toboolean(L, 1) : 0;
-    struct timespec ts;
-    double d;
-
-    clock_gettime(monotonic ? CLOCK_MONOTONIC : CLOCK_REALTIME, &ts);
-    d = (double)ts.tv_sec + ((double)ts.tv_nsec * 1.0E-9);
-    lua_pushnumber(L, d);
-    return 1;
+static int lsp_get_time(lua_State *L) {
+	int num_args = lua_gettop(L);
+	int monotonic = (num_args > 0) ? lua_toboolean(L, 1) : 0;
+	struct timespec ts;
+	double d;
+
+	clock_gettime(monotonic ? CLOCK_MONOTONIC : CLOCK_REALTIME, &ts);
+	d = (double)ts.tv_sec + ((double)ts.tv_nsec * 1.0E-9);
+	lua_pushnumber(L, d);
+	return 1;
 }
 
 /* mg.get_var */
-static int lsp_get_var(lua_State *L)
-{
-    int num_args = lua_gettop(L);
-    const char *data, *var_name;
-    size_t data_len, occurrence;
-    int ret;
-    char dst[512];
-
-    if (num_args>=2 && num_args<=3) {
-        data = lua_tolstring(L, 1, &data_len);
-        var_name = lua_tostring(L, 2);
-        occurrence = (num_args>2) ? (long)lua_tonumber(L, 3) : 0;
-
-        ret = mg_get_var2(data, data_len, var_name, dst, sizeof(dst), occurrence);
-        if (ret>=0) {
-            /* Variable found: return value to Lua */
-            lua_pushstring(L, dst);
-        } else {
-            /* Variable not found (TODO: may be string too long) */
-            lua_pushnil(L);
-        }
-    } else {
-        /* Syntax error */
-        return luaL_error(L, "invalid get_var() call");
-    }
-    return 1;
+static int lsp_get_var(lua_State *L) {
+	int num_args = lua_gettop(L);
+	const char *data, *var_name;
+	size_t data_len, occurrence;
+	int ret;
+	char dst[512];
+
+	if (num_args >= 2 && num_args <= 3) {
+		data = lua_tolstring(L, 1, &data_len);
+		var_name = lua_tostring(L, 2);
+		occurrence = (num_args > 2) ? (long)lua_tonumber(L, 3) : 0;
+
+		ret =
+		    mg_get_var2(data, data_len, var_name, dst, sizeof(dst), occurrence);
+		if (ret >= 0) {
+			/* Variable found: return value to Lua */
+			lua_pushstring(L, dst);
+		} else {
+			/* Variable not found (TODO: may be string too long) */
+			lua_pushnil(L);
+		}
+	} else {
+		/* Syntax error */
+		return luaL_error(L, "invalid get_var() call");
+	}
+	return 1;
 }
 
 /* mg.get_mime_type */
-static int lsp_get_mime_type(lua_State *L)
-{
-    int num_args = lua_gettop(L);
-    struct vec mime_type = {0, 0};
-    struct mg_context *ctx;
-    const char *text;
-
-    lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
-    lua_gettable(L, LUA_REGISTRYINDEX);
-    ctx = (struct mg_context *)lua_touserdata(L, -1);
-
-    if (num_args==1) {
-        text = lua_tostring(L, 1);
-        if (text) {
-            if (ctx) {
-                get_mime_type(ctx, text, &mime_type);
-                lua_pushlstring(L, mime_type.ptr, mime_type.len);
-            } else {
-                text = mg_get_builtin_mime_type(text);
-                lua_pushstring(L, text);
-            }
-        } else {
-            /* Syntax error */
-            return luaL_error(L, "invalid argument for get_mime_type() call");
-        }
-    } else {
-        /* Syntax error */
-        return luaL_error(L, "invalid get_mime_type() call");
-    }
-    return 1;
+static int lsp_get_mime_type(lua_State *L) {
+	int num_args = lua_gettop(L);
+	struct vec mime_type = {0, 0};
+	struct mg_context *ctx;
+	const char *text;
+
+	lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
+	lua_gettable(L, LUA_REGISTRYINDEX);
+	ctx = (struct mg_context *)lua_touserdata(L, -1);
+
+	if (num_args == 1) {
+		text = lua_tostring(L, 1);
+		if (text) {
+			if (ctx) {
+				get_mime_type(ctx, text, &mime_type);
+				lua_pushlstring(L, mime_type.ptr, mime_type.len);
+			} else {
+				text = mg_get_builtin_mime_type(text);
+				lua_pushstring(L, text);
+			}
+		} else {
+			/* Syntax error */
+			return luaL_error(L, "invalid argument for get_mime_type() call");
+		}
+	} else {
+		/* Syntax error */
+		return luaL_error(L, "invalid get_mime_type() call");
+	}
+	return 1;
 }
 
 /* mg.get_cookie */
-static int lsp_get_cookie(lua_State *L)
-{
-    int num_args = lua_gettop(L);
-    const char *cookie;
-    const char *var_name;
-    int ret;
-    char dst[512];
-
-    if (num_args==2) {
-        cookie = lua_tostring(L, 1);
-        var_name = lua_tostring(L, 2);
-        if (cookie!=NULL && var_name!=NULL) {
-            ret = mg_get_cookie(cookie, var_name, dst, sizeof(dst));
-        } else {
-            ret = -1;
-        }
-
-        if (ret>=0) {
-            lua_pushlstring(L, dst, ret);
-        } else {
-            lua_pushnil(L);
-        }
-    } else {
-        /* Syntax error */
-        return luaL_error(L, "invalid get_cookie() call");
-    }
-    return 1;
+static int lsp_get_cookie(lua_State *L) {
+	int num_args = lua_gettop(L);
+	const char *cookie;
+	const char *var_name;
+	int ret;
+	char dst[512];
+
+	if (num_args == 2) {
+		cookie = lua_tostring(L, 1);
+		var_name = lua_tostring(L, 2);
+		if (cookie != NULL && var_name != NULL) {
+			ret = mg_get_cookie(cookie, var_name, dst, sizeof(dst));
+		} else {
+			ret = -1;
+		}
+
+		if (ret >= 0) {
+			lua_pushlstring(L, dst, ret);
+		} else {
+			lua_pushnil(L);
+		}
+	} else {
+		/* Syntax error */
+		return luaL_error(L, "invalid get_cookie() call");
+	}
+	return 1;
 }
 
 /* mg.md5 */
-static int lsp_md5(lua_State *L)
-{
-    int num_args = lua_gettop(L);
-    const char *text;
-    md5_byte_t hash[16];
-    md5_state_t ctx;
-    size_t text_len;
-    char buf[40];
-
-    if (num_args==1) {
-        text = lua_tolstring(L, 1, &text_len);
-        if (text) {
-            md5_init(&ctx);
-            md5_append(&ctx, (const md5_byte_t *) text, text_len);
-            md5_finish(&ctx, hash);
-            bin2str(buf, hash, sizeof(hash));
-            lua_pushstring(L, buf);
-        } else {
-            lua_pushnil(L);
-        }
-    } else {
-        /* Syntax error */
-        return luaL_error(L, "invalid md5() call");
-    }
-    return 1;
+static int lsp_md5(lua_State *L) {
+	int num_args = lua_gettop(L);
+	const char *text;
+	md5_byte_t hash[16];
+	md5_state_t ctx;
+	size_t text_len;
+	char buf[40];
+
+	if (num_args == 1) {
+		text = lua_tolstring(L, 1, &text_len);
+		if (text) {
+			md5_init(&ctx);
+			md5_append(&ctx, (const md5_byte_t *)text, text_len);
+			md5_finish(&ctx, hash);
+			bin2str(buf, hash, sizeof(hash));
+			lua_pushstring(L, buf);
+		} else {
+			lua_pushnil(L);
+		}
+	} else {
+		/* Syntax error */
+		return luaL_error(L, "invalid md5() call");
+	}
+	return 1;
 }
 
 /* mg.url_encode */
-static int lsp_url_encode(lua_State *L)
-{
-    int num_args = lua_gettop(L);
-    const char *text;
-    size_t text_len;
-    char dst[512];
-
-    if (num_args==1) {
-        text = lua_tolstring(L, 1, &text_len);
-        if (text) {
-            mg_url_encode(text, dst, sizeof(dst));
-            lua_pushstring(L, dst);
-        } else {
-            lua_pushnil(L);
-        }
-    } else {
-        /* Syntax error */
-        return luaL_error(L, "invalid url_encode() call");
-    }
-    return 1;
+static int lsp_url_encode(lua_State *L) {
+	int num_args = lua_gettop(L);
+	const char *text;
+	size_t text_len;
+	char dst[512];
+
+	if (num_args == 1) {
+		text = lua_tolstring(L, 1, &text_len);
+		if (text) {
+			mg_url_encode(text, dst, sizeof(dst));
+			lua_pushstring(L, dst);
+		} else {
+			lua_pushnil(L);
+		}
+	} else {
+		/* Syntax error */
+		return luaL_error(L, "invalid url_encode() call");
+	}
+	return 1;
 }
 
 /* mg.url_decode */
-static int lsp_url_decode(lua_State *L)
-{
-    int num_args = lua_gettop(L);
-    const char *text;
-    size_t text_len;
-    int is_form;
-    char dst[512];
-
-    if (num_args==1 || (num_args==2 && lua_isboolean(L, 2))) {
-        text = lua_tolstring(L, 1, &text_len);
-        is_form = (num_args==2) ? lua_isboolean(L, 2) : 0;
-        if (text) {
-            mg_url_decode(text, text_len, dst, sizeof(dst), is_form);
-            lua_pushstring(L, dst);
-        } else {
-            lua_pushnil(L);
-        }
-    } else {
-        /* Syntax error */
-        return luaL_error(L, "invalid url_decode() call");
-    }
-    return 1;
+static int lsp_url_decode(lua_State *L) {
+	int num_args = lua_gettop(L);
+	const char *text;
+	size_t text_len;
+	int is_form;
+	char dst[512];
+
+	if (num_args == 1 || (num_args == 2 && lua_isboolean(L, 2))) {
+		text = lua_tolstring(L, 1, &text_len);
+		is_form = (num_args == 2) ? lua_isboolean(L, 2) : 0;
+		if (text) {
+			mg_url_decode(text, text_len, dst, sizeof(dst), is_form);
+			lua_pushstring(L, dst);
+		} else {
+			lua_pushnil(L);
+		}
+	} else {
+		/* Syntax error */
+		return luaL_error(L, "invalid url_decode() call");
+	}
+	return 1;
 }
 
 /* mg.base64_encode */
-static int lsp_base64_encode(lua_State *L)
-{
-    int num_args = lua_gettop(L);
-    const char *text;
-    size_t text_len;
-    char *dst;
-
-    if (num_args==1) {
-        text = lua_tolstring(L, 1, &text_len);
-        if (text) {
-            dst = (char *)mg_malloc(text_len*8/6+4);
-            if (dst) {
-                base64_encode((const unsigned char *)text, text_len, dst);
-                lua_pushstring(L, dst);
-                mg_free(dst);
-            } else {
-                return luaL_error(L, "out of memory in base64_encode() call");
-            }
-        } else {
-            lua_pushnil(L);
-        }
-    } else {
-        /* Syntax error */
-        return luaL_error(L, "invalid base64_encode() call");
-    }
-    return 1;
+static int lsp_base64_encode(lua_State *L) {
+	int num_args = lua_gettop(L);
+	const char *text;
+	size_t text_len;
+	char *dst;
+
+	if (num_args == 1) {
+		text = lua_tolstring(L, 1, &text_len);
+		if (text) {
+			dst = (char *)mg_malloc(text_len * 8 / 6 + 4);
+			if (dst) {
+				base64_encode((const unsigned char *)text, text_len, dst);
+				lua_pushstring(L, dst);
+				mg_free(dst);
+			} else {
+				return luaL_error(L, "out of memory in base64_encode() call");
+			}
+		} else {
+			lua_pushnil(L);
+		}
+	} else {
+		/* Syntax error */
+		return luaL_error(L, "invalid base64_encode() call");
+	}
+	return 1;
 }
 
 /* mg.base64_encode */
-static int lsp_base64_decode(lua_State *L)
-{
-    int num_args = lua_gettop(L);
-    const char *text;
-    size_t text_len, dst_len;
-    int ret;
-    char *dst;
-
-    if (num_args==1) {
-        text = lua_tolstring(L, 1, &text_len);
-        if (text) {
-            dst = (char *)mg_malloc(text_len);
-            if (dst) {
-                ret = base64_decode((const unsigned char *)text, text_len, dst, &dst_len);
-                if (ret != -1) {
-                    mg_free(dst);
-                    return luaL_error(L, "illegal character in lsp_base64_decode() call");
-                } else {
-                    lua_pushlstring(L, dst, dst_len);
-                    mg_free(dst);
-                }
-            } else {
-                return luaL_error(L, "out of memory in lsp_base64_decode() call");
-            }
-        } else {
-            lua_pushnil(L);
-        }
-    } else {
-        /* Syntax error */
-        return luaL_error(L, "invalid lsp_base64_decode() call");
-    }
-    return 1;
+static int lsp_base64_decode(lua_State *L) {
+	int num_args = lua_gettop(L);
+	const char *text;
+	size_t text_len, dst_len;
+	int ret;
+	char *dst;
+
+	if (num_args == 1) {
+		text = lua_tolstring(L, 1, &text_len);
+		if (text) {
+			dst = (char *)mg_malloc(text_len);
+			if (dst) {
+				ret = base64_decode((const unsigned char *)text, text_len, dst,
+				                    &dst_len);
+				if (ret != -1) {
+					mg_free(dst);
+					return luaL_error(
+					    L, "illegal character in lsp_base64_decode() call");
+				} else {
+					lua_pushlstring(L, dst, dst_len);
+					mg_free(dst);
+				}
+			} else {
+				return luaL_error(L,
+				                  "out of memory in lsp_base64_decode() call");
+			}
+		} else {
+			lua_pushnil(L);
+		}
+	} else {
+		/* Syntax error */
+		return luaL_error(L, "invalid lsp_base64_decode() call");
+	}
+	return 1;
 }
 
 /* mg.get_response_code_text */
 static int lsp_get_response_code_text(lua_State *L) {
-    int num_args = lua_gettop(L);
-    int type1;
-    double code;
-    const char *text;
-
-    if (num_args==1) {
-        type1 = lua_type(L, 1);
-        if (type1 == LUA_TNUMBER) {
-            /* If the first argument is a number,
-               convert it to the corresponding text. */
-            code = lua_tonumber(L, 1);
-            text = mg_get_response_code_text((int)code, NULL);
-            if (text) lua_pushstring(L, text);
-            return text ? 1 : 0;
-        }
-    }
-
-    /* Syntax error */
-    return luaL_error(L, "invalid get_response_code_text() call");
+	int num_args = lua_gettop(L);
+	int type1;
+	double code;
+	const char *text;
+
+	if (num_args == 1) {
+		type1 = lua_type(L, 1);
+		if (type1 == LUA_TNUMBER) {
+			/* If the first argument is a number,
+			   convert it to the corresponding text. */
+			code = lua_tonumber(L, 1);
+			text = mg_get_response_code_text((int)code, NULL);
+			if (text)
+				lua_pushstring(L, text);
+			return text ? 1 : 0;
+		}
+	}
+
+	/* Syntax error */
+	return luaL_error(L, "invalid get_response_code_text() call");
 }
 
 #ifdef USE_WEBSOCKET
 struct lua_websock_data {
-    lua_State *state;
-    char * script;
-    unsigned references;
-    struct mg_connection *conn[MAX_WORKER_THREADS];
-    pthread_mutex_t ws_mutex;
+	lua_State *state;
+	char *script;
+	unsigned references;
+	struct mg_connection *conn[MAX_WORKER_THREADS];
+	pthread_mutex_t ws_mutex;
 };
 #endif
 
 /* mg.write for websockets */
-static int lwebsock_write(lua_State *L)
-{
+static int lwebsock_write(lua_State *L) {
 #ifdef USE_WEBSOCKET
-    int num_args = lua_gettop(L);
-    struct lua_websock_data *ws;
-    const char *str;
-    size_t size;
-    int opcode = -1;
-    unsigned i;
-    struct mg_connection * client = NULL;
-
-    lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
-    lua_gettable(L, LUA_REGISTRYINDEX);
-    ws = (struct lua_websock_data *)lua_touserdata(L, -1);
-
-    if (num_args == 1) {
-        /* just one text: send it to all client */
-        if (lua_isstring(L, 1)) {
-            opcode = WEBSOCKET_OPCODE_TEXT;
-        }
-    } else if (num_args == 2) {
-        if (lua_isnumber(L, 1)) {
-            /* opcode number and message text */
-            opcode = (int)lua_tointeger(L, 1);
-        } else if (lua_isstring(L,1)) {
-            /* opcode string and message text */
-            str = lua_tostring(L, 1);
-            if (!mg_strncasecmp(str, "text", 4)) opcode = WEBSOCKET_OPCODE_TEXT;
-            else if (!mg_strncasecmp(str, "bin", 3)) opcode = WEBSOCKET_OPCODE_BINARY;
-            else if (!mg_strncasecmp(str, "close", 5)) opcode = WEBSOCKET_OPCODE_CONNECTION_CLOSE;
-            else if (!mg_strncasecmp(str, "ping", 4)) opcode = WEBSOCKET_OPCODE_PING;
-            else if (!mg_strncasecmp(str, "pong", 4)) opcode = WEBSOCKET_OPCODE_PONG;
-            else if (!mg_strncasecmp(str, "cont", 4)) opcode = WEBSOCKET_OPCODE_CONTINUATION;
-        } else if (lua_isuserdata(L, 1)) {
-            /* client id and message text */
-            client = (struct mg_connection *) lua_touserdata(L, 1);
-            opcode = WEBSOCKET_OPCODE_TEXT;
-        }
-    } else if (num_args == 3) {
-        if (lua_isuserdata(L, 1)) {
-            client = (struct mg_connection *) lua_touserdata(L, 1);
-            if (lua_isnumber(L, 2)) {
-                /* client id, opcode number and message text */
-                opcode = (int)lua_tointeger(L, 2);
-            } else if (lua_isstring(L,2)) {
-                /* client id, opcode string and message text */
-                str = lua_tostring(L, 2);
-                if (!mg_strncasecmp(str, "text", 4)) opcode = WEBSOCKET_OPCODE_TEXT;
-                else if (!mg_strncasecmp(str, "bin", 3)) opcode = WEBSOCKET_OPCODE_BINARY;
-                else if (!mg_strncasecmp(str, "close", 5)) opcode = WEBSOCKET_OPCODE_CONNECTION_CLOSE;
-                else if (!mg_strncasecmp(str, "ping", 4)) opcode = WEBSOCKET_OPCODE_PING;
-                else if (!mg_strncasecmp(str, "pong", 4)) opcode = WEBSOCKET_OPCODE_PONG;
-                else if (!mg_strncasecmp(str, "cont", 4)) opcode = WEBSOCKET_OPCODE_CONTINUATION;
-            }
-        }
-    }
-
-    if (opcode>=0 && opcode<16 && lua_isstring(L, num_args)) {
-        str = lua_tolstring(L, num_args, &size);
-        if (client) {
-            for (i=0; i<ws->references; i++) {
-                if (client == ws->conn[i]) {
-                    mg_websocket_write(ws->conn[i], opcode, str, size);
-                }
-            }
-        } else {
-            for (i=0; i<ws->references; i++) {
-                mg_websocket_write(ws->conn[i], opcode, str, size);
-            }
-        }
-    } else {
-        return luaL_error(L, "invalid websocket write() call");
-    }
+	int num_args = lua_gettop(L);
+	struct lua_websock_data *ws;
+	const char *str;
+	size_t size;
+	int opcode = -1;
+	unsigned i;
+	struct mg_connection *client = NULL;
+
+	lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
+	lua_gettable(L, LUA_REGISTRYINDEX);
+	ws = (struct lua_websock_data *)lua_touserdata(L, -1);
+
+	if (num_args == 1) {
+		/* just one text: send it to all client */
+		if (lua_isstring(L, 1)) {
+			opcode = WEBSOCKET_OPCODE_TEXT;
+		}
+	} else if (num_args == 2) {
+		if (lua_isnumber(L, 1)) {
+			/* opcode number and message text */
+			opcode = (int)lua_tointeger(L, 1);
+		} else if (lua_isstring(L, 1)) {
+			/* opcode string and message text */
+			str = lua_tostring(L, 1);
+			if (!mg_strncasecmp(str, "text", 4))
+				opcode = WEBSOCKET_OPCODE_TEXT;
+			else if (!mg_strncasecmp(str, "bin", 3))
+				opcode = WEBSOCKET_OPCODE_BINARY;
+			else if (!mg_strncasecmp(str, "close", 5))
+				opcode = WEBSOCKET_OPCODE_CONNECTION_CLOSE;
+			else if (!mg_strncasecmp(str, "ping", 4))
+				opcode = WEBSOCKET_OPCODE_PING;
+			else if (!mg_strncasecmp(str, "pong", 4))
+				opcode = WEBSOCKET_OPCODE_PONG;
+			else if (!mg_strncasecmp(str, "cont", 4))
+				opcode = WEBSOCKET_OPCODE_CONTINUATION;
+		} else if (lua_isuserdata(L, 1)) {
+			/* client id and message text */
+			client = (struct mg_connection *)lua_touserdata(L, 1);
+			opcode = WEBSOCKET_OPCODE_TEXT;
+		}
+	} else if (num_args == 3) {
+		if (lua_isuserdata(L, 1)) {
+			client = (struct mg_connection *)lua_touserdata(L, 1);
+			if (lua_isnumber(L, 2)) {
+				/* client id, opcode number and message text */
+				opcode = (int)lua_tointeger(L, 2);
+			} else if (lua_isstring(L, 2)) {
+				/* client id, opcode string and message text */
+				str = lua_tostring(L, 2);
+				if (!mg_strncasecmp(str, "text", 4))
+					opcode = WEBSOCKET_OPCODE_TEXT;
+				else if (!mg_strncasecmp(str, "bin", 3))
+					opcode = WEBSOCKET_OPCODE_BINARY;
+				else if (!mg_strncasecmp(str, "close", 5))
+					opcode = WEBSOCKET_OPCODE_CONNECTION_CLOSE;
+				else if (!mg_strncasecmp(str, "ping", 4))
+					opcode = WEBSOCKET_OPCODE_PING;
+				else if (!mg_strncasecmp(str, "pong", 4))
+					opcode = WEBSOCKET_OPCODE_PONG;
+				else if (!mg_strncasecmp(str, "cont", 4))
+					opcode = WEBSOCKET_OPCODE_CONTINUATION;
+			}
+		}
+	}
+
+	if (opcode >= 0 && opcode < 16 && lua_isstring(L, num_args)) {
+		str = lua_tolstring(L, num_args, &size);
+		if (client) {
+			for (i = 0; i < ws->references; i++) {
+				if (client == ws->conn[i]) {
+					mg_websocket_write(ws->conn[i], opcode, str, size);
+				}
+			}
+		} else {
+			for (i = 0; i < ws->references; i++) {
+				mg_websocket_write(ws->conn[i], opcode, str, size);
+			}
+		}
+	} else {
+		return luaL_error(L, "invalid websocket write() call");
+	}
 #else
-    (void)(L); /* unused */
+	(void)(L);           /* unused */
 #endif
-    return 0;
+	return 0;
 }
 
 struct laction_arg {
-    lua_State *state;
-    const char *script;
-    pthread_mutex_t *pmutex;
-    char txt[1];
+	lua_State *state;
+	const char *script;
+	pthread_mutex_t *pmutex;
+	char txt[1];
 };
 
-static int lua_action(struct laction_arg *arg)
-{
-    int err, ok;
-    struct mg_context *ctx;
-
-    (void)pthread_mutex_lock(arg->pmutex);
-
-    lua_pushlightuserdata(arg->state, (void *)&lua_regkey_ctx);
-    lua_gettable(arg->state, LUA_REGISTRYINDEX);
-    ctx = (struct mg_context *)lua_touserdata(arg->state, -1);
-
-    err = luaL_loadstring(arg->state, arg->txt);
-    if (err != 0) {
-        lua_cry(fc(ctx), err, arg->state, arg->script, "timer");
-        (void)pthread_mutex_unlock(arg->pmutex);
-        mg_free(arg);
-        return 0;
-    }
-    err = lua_pcall(arg->state, 0, 1, 0);
-    if (err != 0) {
-        lua_cry(fc(ctx), err, arg->state, arg->script, "timer");
-        (void)pthread_mutex_unlock(arg->pmutex);
-        mg_free(arg);
-        return 0;
-    }
-
-    ok = lua_type(arg->state, -1);
-    if (lua_isboolean(arg->state, -1)) {
-       ok = lua_toboolean(arg->state, -1);
-    } else {
-       ok = 0;
-    }
-    lua_pop(arg->state, 1);
-
-    (void)pthread_mutex_unlock(arg->pmutex);
-
-    if (!ok) {
-        mg_free(arg);
-    }
-    return ok;
+static int lua_action(struct laction_arg *arg) {
+	int err, ok;
+	struct mg_context *ctx;
+
+	(void)pthread_mutex_lock(arg->pmutex);
+
+	lua_pushlightuserdata(arg->state, (void *)&lua_regkey_ctx);
+	lua_gettable(arg->state, LUA_REGISTRYINDEX);
+	ctx = (struct mg_context *)lua_touserdata(arg->state, -1);
+
+	err = luaL_loadstring(arg->state, arg->txt);
+	if (err != 0) {
+		lua_cry(fc(ctx), err, arg->state, arg->script, "timer");
+		(void)pthread_mutex_unlock(arg->pmutex);
+		mg_free(arg);
+		return 0;
+	}
+	err = lua_pcall(arg->state, 0, 1, 0);
+	if (err != 0) {
+		lua_cry(fc(ctx), err, arg->state, arg->script, "timer");
+		(void)pthread_mutex_unlock(arg->pmutex);
+		mg_free(arg);
+		return 0;
+	}
+
+	ok = lua_type(arg->state, -1);
+	if (lua_isboolean(arg->state, -1)) {
+		ok = lua_toboolean(arg->state, -1);
+	} else {
+		ok = 0;
+	}
+	lua_pop(arg->state, 1);
+
+	(void)pthread_mutex_unlock(arg->pmutex);
+
+	if (!ok) {
+		mg_free(arg);
+	}
+	return ok;
 }
 
-static int lua_action_free(struct laction_arg *arg)
-{
-    if (lua_action(arg)) {
-        mg_free(arg);
-    }
-    return 0;
+static int lua_action_free(struct laction_arg *arg) {
+	if (lua_action(arg)) {
+		mg_free(arg);
+	}
+	return 0;
 }
 
-static int lwebsocket_set_timer(lua_State *L, int is_periodic)
-{
+static int lwebsocket_set_timer(lua_State *L, int is_periodic) {
 #if defined(USE_TIMERS) && defined(USE_WEBSOCKET)
-    int num_args = lua_gettop(L);
-    struct lua_websock_data *ws;
-    int type1,type2, ok = 0;
-    double timediff;
-    struct mg_context *ctx;
-    struct laction_arg *arg;
-    const char *txt;
-    size_t txt_len;
-
-    lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
-    lua_gettable(L, LUA_REGISTRYINDEX);
-    ctx = (struct mg_context *)lua_touserdata(L, -1);
-
-    lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
-    lua_gettable(L, LUA_REGISTRYINDEX);
-    ws = (struct lua_websock_data *)lua_touserdata(L, -1);
-
-    if (num_args < 2) {
-        return luaL_error(L, "not enough arguments for set_timer/interval() call");
-    }
-
-    type1 = lua_type(L, 1);
-    type2 = lua_type(L, 2);
-
-    if (type1==LUA_TSTRING && type2==LUA_TNUMBER && num_args==2) {
-        timediff = (double)lua_tonumber(L, 2);
-        txt = lua_tostring(L, 1);
-        txt_len = strlen(txt);
-        arg = (struct laction_arg *) mg_malloc(sizeof(struct laction_arg) + txt_len + 10);
-        arg->state = L;
-        arg->script = ws->script;
-        arg->pmutex = &(ws->ws_mutex);
-        memcpy(arg->txt, "return(", 7);
-        memcpy(arg->txt+7, txt, txt_len);
-        arg->txt[txt_len+7] = ')';
-        arg->txt[txt_len+8] = 0;
-        ok = (0==timer_add(ctx, timediff, is_periodic, 1, (taction)(is_periodic ? lua_action : lua_action_free), (void*)arg));
-    } else if (type1==LUA_TFUNCTION && type2==LUA_TNUMBER)  {
-        /* TODO: not implemented yet */
-        return luaL_error(L, "invalid arguments for set_timer/interval() call");
-    } else {
-        return luaL_error(L, "invalid arguments for set_timer/interval() call");
-    }
-
-    lua_pushboolean(L, ok);
-    return 1;
+	int num_args = lua_gettop(L);
+	struct lua_websock_data *ws;
+	int type1, type2, ok = 0;
+	double timediff;
+	struct mg_context *ctx;
+	struct laction_arg *arg;
+	const char *txt;
+	size_t txt_len;
+
+	lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
+	lua_gettable(L, LUA_REGISTRYINDEX);
+	ctx = (struct mg_context *)lua_touserdata(L, -1);
+
+	lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
+	lua_gettable(L, LUA_REGISTRYINDEX);
+	ws = (struct lua_websock_data *)lua_touserdata(L, -1);
+
+	if (num_args < 2) {
+		return luaL_error(L,
+		                  "not enough arguments for set_timer/interval() call");
+	}
+
+	type1 = lua_type(L, 1);
+	type2 = lua_type(L, 2);
+
+	if (type1 == LUA_TSTRING && type2 == LUA_TNUMBER && num_args == 2) {
+		timediff = (double)lua_tonumber(L, 2);
+		txt = lua_tostring(L, 1);
+		txt_len = strlen(txt);
+		arg = (struct laction_arg *)mg_malloc(sizeof(struct laction_arg) +
+		                                      txt_len + 10);
+		arg->state = L;
+		arg->script = ws->script;
+		arg->pmutex = &(ws->ws_mutex);
+		memcpy(arg->txt, "return(", 7);
+		memcpy(arg->txt + 7, txt, txt_len);
+		arg->txt[txt_len + 7] = ')';
+		arg->txt[txt_len + 8] = 0;
+		ok = (0 ==
+		      timer_add(ctx, timediff, is_periodic, 1,
+		                (taction)(is_periodic ? lua_action : lua_action_free),
+		                (void *)arg));
+	} else if (type1 == LUA_TFUNCTION && type2 == LUA_TNUMBER) {
+		/* TODO: not implemented yet */
+		return luaL_error(L, "invalid arguments for set_timer/interval() call");
+	} else {
+		return luaL_error(L, "invalid arguments for set_timer/interval() call");
+	}
+
+	lua_pushboolean(L, ok);
+	return 1;
 
 #else
-    (void)(L);           /* unused */
-    (void)(is_periodic); /* unused */
-    return 0;
+	(void)(L);           /* unused */
+	(void)(is_periodic); /* unused */
+	return 0;
 #endif
 }
 
 /* mg.set_timeout for websockets */
-static int lwebsocket_set_timeout(lua_State *L)
-{
-    return lwebsocket_set_timer(L, 0);
+static int lwebsocket_set_timeout(lua_State *L) {
+	return lwebsocket_set_timer(L, 0);
 }
 
 /* mg.set_interval for websockets */
-static int lwebsocket_set_interval(lua_State *L)
-{
-    return lwebsocket_set_timer(L, 1);
+static int lwebsocket_set_interval(lua_State *L) {
+	return lwebsocket_set_timer(L, 1);
 }
 
 enum {
-    LUA_ENV_TYPE_LUA_SERVER_PAGE = 0,
-    LUA_ENV_TYPE_PLAIN_LUA_PAGE = 1,
-    LUA_ENV_TYPE_LUA_WEBSOCKET = 2,
+	LUA_ENV_TYPE_LUA_SERVER_PAGE = 0,
+	LUA_ENV_TYPE_PLAIN_LUA_PAGE = 1,
+	LUA_ENV_TYPE_LUA_WEBSOCKET = 2,
 };
 
-static void prepare_lua_request_info(struct mg_connection *conn, lua_State *L)
-{
-    const char *s;
-    int i;
-
-    /* Export mg.request_info */
-    lua_pushstring(L, "request_info");
-    lua_newtable(L);
-    reg_string(L, "request_method", conn->request_info.request_method);
-    reg_string(L, "uri", conn->request_info.uri);
-    reg_string(L, "http_version", conn->request_info.http_version);
-    reg_string(L, "query_string", conn->request_info.query_string);
+static void prepare_lua_request_info(struct mg_connection *conn, lua_State *L) {
+	const char *s;
+	int i;
+
+	/* Export mg.request_info */
+	lua_pushstring(L, "request_info");
+	lua_newtable(L);
+	reg_string(L, "request_method", conn->request_info.request_method);
+	reg_string(L, "uri", conn->request_info.uri);
+	reg_string(L, "http_version", conn->request_info.http_version);
+	reg_string(L, "query_string", conn->request_info.query_string);
 #if defined(MG_LEGACY_INTERFACE)
-    reg_int(L, "remote_ip", conn->request_info.remote_ip); /* remote_ip is deprecated, use remote_addr instead */
+	reg_int(
+	    L, "remote_ip",
+	    conn->request_info
+	        .remote_ip); /* remote_ip is deprecated, use remote_addr instead */
 #endif
-    reg_string(L, "remote_addr", conn->request_info.remote_addr);
-    /* TODO: ip version */
-    reg_int(L, "remote_port", conn->request_info.remote_port);
-    reg_int(L, "num_headers", conn->request_info.num_headers);
-    reg_int(L, "server_port", ntohs(conn->client.lsa.sin.sin_port));
-
-    if (conn->request_info.content_length >= 0) {
-        /* reg_int64: content_length */
-        lua_pushstring(L, "content_length");
-        lua_pushnumber(L, (lua_Number)conn->request_info.content_length); /* lua_Number may be used as 52 bit integer */
-        lua_rawset(L, -3);
-    }
-    if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
-        reg_string(L, "content_type", s);
-    }
-
-    if (conn->request_info.remote_user != NULL) {
-        reg_string(L, "remote_user", conn->request_info.remote_user);
-        reg_string(L, "auth_type", "Digest");
-    }
-
-    reg_boolean(L, "https", conn->ssl != NULL);
-
-    if (conn->status_code > 0) {
-        /* Lua error handler should show the status code */
-        reg_int(L, "status", conn->status_code);
-    }
-
-    lua_pushstring(L, "http_headers");
-    lua_newtable(L);
-    for (i = 0; i < conn->request_info.num_headers; i++) {
-        reg_string(L, conn->request_info.http_headers[i].name, conn->request_info.http_headers[i].value);
-    }
-    lua_rawset(L, -3);
-
-    lua_rawset(L, -3);
+	reg_string(L, "remote_addr", conn->request_info.remote_addr);
+	/* TODO: ip version */
+	reg_int(L, "remote_port", conn->request_info.remote_port);
+	reg_int(L, "num_headers", conn->request_info.num_headers);
+	reg_int(L, "server_port", ntohs(conn->client.lsa.sin.sin_port));
+
+	if (conn->request_info.content_length >= 0) {
+		/* reg_int64: content_length */
+		lua_pushstring(L, "content_length");
+		lua_pushnumber(
+		    L,
+		    (lua_Number)conn->request_info
+		        .content_length); /* lua_Number may be used as 52 bit integer */
+		lua_rawset(L, -3);
+	}
+	if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
+		reg_string(L, "content_type", s);
+	}
+
+	if (conn->request_info.remote_user != NULL) {
+		reg_string(L, "remote_user", conn->request_info.remote_user);
+		reg_string(L, "auth_type", "Digest");
+	}
+
+	reg_boolean(L, "https", conn->ssl != NULL);
+
+	if (conn->status_code > 0) {
+		/* Lua error handler should show the status code */
+		reg_int(L, "status", conn->status_code);
+	}
+
+	lua_pushstring(L, "http_headers");
+	lua_newtable(L);
+	for (i = 0; i < conn->request_info.num_headers; i++) {
+		reg_string(L, conn->request_info.http_headers[i].name,
+		           conn->request_info.http_headers[i].value);
+	}
+	lua_rawset(L, -3);
+
+	lua_rawset(L, -3);
 }
 
-void lua_civet_open_all_libs(lua_State *L)
-{
-    {
-        extern void luaL_openlibs(lua_State *);
-        luaL_openlibs(L);
-    }
+void lua_civet_open_all_libs(lua_State *L) {
+	{
+		extern void luaL_openlibs(lua_State *);
+		luaL_openlibs(L);
+	}
 
 #ifdef USE_LUA_SQLITE3
-    {
-        extern int luaopen_lsqlite3(lua_State *);
-        luaopen_lsqlite3(L);
-    }
+	{
+		extern int luaopen_lsqlite3(lua_State *);
+		luaopen_lsqlite3(L);
+	}
 #endif
 #ifdef USE_LUA_LUAXML
-    {
-        extern int luaopen_LuaXML_lib(lua_State *);
-        luaopen_LuaXML_lib(L);
-    }
+	{
+		extern int luaopen_LuaXML_lib(lua_State *);
+		luaopen_LuaXML_lib(L);
+	}
 #endif
 #ifdef USE_LUA_FILE_SYSTEM
-    {
-        extern int luaopen_lfs(lua_State *);
-        luaopen_lfs(L);
-    }
+	{
+		extern int luaopen_lfs(lua_State *);
+		luaopen_lfs(L);
+	}
 #endif
 }
 
-static void prepare_lua_environment(struct mg_context * ctx, struct mg_connection *conn, struct lua_websock_data *conn_list, lua_State *L, const char *script_name, int lua_env_type)
-{
-    lua_civet_open_all_libs(L);
-
-    luaL_newmetatable(L, LUASOCKET);
-    lua_pushliteral(L, "__index");
-    luaL_newlib(L, luasocket_methods);
-    lua_rawset(L, -3);
-    lua_pop(L, 1);
-    lua_register(L, "connect", lsp_connect);
-
-    /* Store context in the registry */
-    if (ctx) {
-        lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
-        lua_pushlightuserdata(L, (void *)ctx);
-        lua_settable(L, LUA_REGISTRYINDEX);
-    }
-    if (conn_list) {
-        lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
-        lua_pushlightuserdata(L, (void *)conn_list);
-        lua_settable(L, LUA_REGISTRYINDEX);
-    }
-
-    /* Register mg module */
-    lua_newtable(L);
-
-    switch (lua_env_type) {
-    case LUA_ENV_TYPE_LUA_SERVER_PAGE:
-        reg_string(L, "lua_type", "page");
-        break;
-    case LUA_ENV_TYPE_PLAIN_LUA_PAGE:
-        reg_string(L, "lua_type", "script");
-        break;
-    case LUA_ENV_TYPE_LUA_WEBSOCKET:
-        reg_string(L, "lua_type", "websocket");
-        break;
-    }
-
-    if (lua_env_type==LUA_ENV_TYPE_LUA_SERVER_PAGE || lua_env_type==LUA_ENV_TYPE_PLAIN_LUA_PAGE) {
-        reg_conn_function(L, "cry", lsp_cry, conn);
-        reg_conn_function(L, "read", lsp_read, conn);
-        reg_conn_function(L, "write", lsp_write, conn);
-        reg_conn_function(L, "keep_alive", lsp_keep_alive, conn);
-        reg_conn_function(L, "send_file", lsp_send_file, conn);
-    }
-
-    if (lua_env_type==LUA_ENV_TYPE_LUA_SERVER_PAGE) {
-        reg_conn_function(L, "include", lsp_include, conn);
-        reg_conn_function(L, "redirect", lsp_redirect, conn);
-    }
-
-    if (lua_env_type==LUA_ENV_TYPE_LUA_WEBSOCKET) {
-        reg_function(L, "write", lwebsock_write);
+static void prepare_lua_environment(struct mg_context *ctx,
+                                    struct mg_connection *conn,
+                                    struct lua_websock_data *conn_list,
+                                    lua_State *L, const char *script_name,
+                                    int lua_env_type) {
+	lua_civet_open_all_libs(L);
+
+	luaL_newmetatable(L, LUASOCKET);
+	lua_pushliteral(L, "__index");
+	luaL_newlib(L, luasocket_methods);
+	lua_rawset(L, -3);
+	lua_pop(L, 1);
+	lua_register(L, "connect", lsp_connect);
+
+	/* Store context in the registry */
+	if (ctx) {
+		lua_pushlightuserdata(L, (void *)&lua_regkey_ctx);
+		lua_pushlightuserdata(L, (void *)ctx);
+		lua_settable(L, LUA_REGISTRYINDEX);
+	}
+	if (conn_list) {
+		lua_pushlightuserdata(L, (void *)&lua_regkey_connlist);
+		lua_pushlightuserdata(L, (void *)conn_list);
+		lua_settable(L, LUA_REGISTRYINDEX);
+	}
+
+	/* Register mg module */
+	lua_newtable(L);
+
+	switch (lua_env_type) {
+	case LUA_ENV_TYPE_LUA_SERVER_PAGE:
+		reg_string(L, "lua_type", "page");
+		break;
+	case LUA_ENV_TYPE_PLAIN_LUA_PAGE:
+		reg_string(L, "lua_type", "script");
+		break;
+	case LUA_ENV_TYPE_LUA_WEBSOCKET:
+		reg_string(L, "lua_type", "websocket");
+		break;
+	}
+
+	if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE ||
+	    lua_env_type == LUA_ENV_TYPE_PLAIN_LUA_PAGE) {
+		reg_conn_function(L, "cry", lsp_cry, conn);
+		reg_conn_function(L, "read", lsp_read, conn);
+		reg_conn_function(L, "write", lsp_write, conn);
+		reg_conn_function(L, "keep_alive", lsp_keep_alive, conn);
+		reg_conn_function(L, "send_file", lsp_send_file, conn);
+	}
+
+	if (lua_env_type == LUA_ENV_TYPE_LUA_SERVER_PAGE) {
+		reg_conn_function(L, "include", lsp_include, conn);
+		reg_conn_function(L, "redirect", lsp_redirect, conn);
+	}
+
+	if (lua_env_type == LUA_ENV_TYPE_LUA_WEBSOCKET) {
+		reg_function(L, "write", lwebsock_write);
 #ifdef USE_TIMERS
-        reg_function(L, "set_timeout", lwebsocket_set_timeout);
-        reg_function(L, "set_interval", lwebsocket_set_interval);
+		reg_function(L, "set_timeout", lwebsocket_set_timeout);
+		reg_function(L, "set_interval", lwebsocket_set_interval);
 #endif
-        /* reg_conn_function(L, "send_file", lsp_send_file, conn); */
-    }
-
-    reg_function(L, "time", lsp_get_time);
-    reg_function(L, "get_var", lsp_get_var);
-    reg_function(L, "get_mime_type", lsp_get_mime_type);
-    reg_function(L, "get_cookie", lsp_get_cookie);
-    reg_function(L, "md5", lsp_md5);
-    reg_function(L, "url_encode", lsp_url_encode);
-    reg_function(L, "url_decode", lsp_url_decode);
-    reg_function(L, "base64_encode", lsp_base64_encode);
-    reg_function(L, "base64_decode", lsp_base64_decode);
-    reg_function(L, "get_response_code_text", lsp_get_response_code_text);
-
-    reg_string(L, "version", CIVETWEB_VERSION);
-    reg_string(L, "document_root", ctx->config[DOCUMENT_ROOT]);
-    reg_string(L, "auth_domain", ctx->config[AUTHENTICATION_DOMAIN]);
+		/* reg_conn_function(L, "send_file", lsp_send_file, conn); */
+	}
+
+	reg_function(L, "time", lsp_get_time);
+	reg_function(L, "get_var", lsp_get_var);
+	reg_function(L, "get_mime_type", lsp_get_mime_type);
+	reg_function(L, "get_cookie", lsp_get_cookie);
+	reg_function(L, "md5", lsp_md5);
+	reg_function(L, "url_encode", lsp_url_encode);
+	reg_function(L, "url_decode", lsp_url_decode);
+	reg_function(L, "base64_encode", lsp_base64_encode);
+	reg_function(L, "base64_decode", lsp_base64_decode);
+	reg_function(L, "get_response_code_text", lsp_get_response_code_text);
+
+	reg_string(L, "version", CIVETWEB_VERSION);
+	reg_string(L, "document_root", ctx->config[DOCUMENT_ROOT]);
+	reg_string(L, "auth_domain", ctx->config[AUTHENTICATION_DOMAIN]);
 #if defined(USE_WEBSOCKET)
-    reg_string(L, "websocket_root", ctx->config[WEBSOCKET_ROOT]);
+	reg_string(L, "websocket_root", ctx->config[WEBSOCKET_ROOT]);
 #endif
-    reg_string(L, "script_name", script_name);
+	reg_string(L, "script_name", script_name);
 
-    if (ctx->systemName != NULL) {
-        reg_string(L, "system", ctx->systemName);
-    }
+	if (ctx->systemName != NULL) {
+		reg_string(L, "system", ctx->systemName);
+	}
 
-    /* Export connection specific info */
-    if (conn!=NULL) {
-        prepare_lua_request_info(conn, L);
-    }
+	/* Export connection specific info */
+	if (conn != NULL) {
+		prepare_lua_request_info(conn, L);
+	}
 
-    lua_setglobal(L, "mg");
+	lua_setglobal(L, "mg");
 
-    /* Register default mg.onerror function */
-    IGNORE_UNUSED_RESULT(luaL_dostring(L, "mg.onerror = function(e) mg.write('\\nLua error:\\n', "
-        "debug.traceback(e, 1)) end"));
+	/* Register default mg.onerror function */
+	IGNORE_UNUSED_RESULT(luaL_dostring(
+	    L, "mg.onerror = function(e) mg.write('\\nLua error:\\n', "
+	       "debug.traceback(e, 1)) end"));
 
-    /* Preload */
-    if (ctx->config[LUA_PRELOAD_FILE] != NULL) {
-        IGNORE_UNUSED_RESULT(luaL_dofile(L, ctx->config[LUA_PRELOAD_FILE]));
-    }
+	/* Preload */
+	if (ctx->config[LUA_PRELOAD_FILE] != NULL) {
+		IGNORE_UNUSED_RESULT(luaL_dofile(L, ctx->config[LUA_PRELOAD_FILE]));
+	}
 
-    if (ctx->callbacks.init_lua != NULL) {
-        ctx->callbacks.init_lua(conn, L);
-    }
+	if (ctx->callbacks.init_lua != NULL) {
+		ctx->callbacks.init_lua(conn, L);
+	}
 }
 
-static int lua_error_handler(lua_State *L)
-{
-    const char *error_msg =  lua_isstring(L, -1) ?  lua_tostring(L, -1) : "?\n";
-
-    lua_getglobal(L, "mg");
-    if (!lua_isnil(L, -1)) {
-        lua_getfield(L, -1, "write");   /* call mg.write() */
-        lua_pushstring(L, error_msg);
-        lua_pushliteral(L, "\n");
-        lua_call(L, 2, 0);
-        IGNORE_UNUSED_RESULT(luaL_dostring(L, "mg.write(debug.traceback(), '\\n')"));
-    } else {
-        printf("Lua error: [%s]\n", error_msg);
-        IGNORE_UNUSED_RESULT(luaL_dostring(L, "print(debug.traceback(), '\\n')"));
-    }
-    /* TODO(lsm): leave the stack balanced */
-
-    return 0;
+static int lua_error_handler(lua_State *L) {
+	const char *error_msg = lua_isstring(L, -1) ? lua_tostring(L, -1) : "?\n";
+
+	lua_getglobal(L, "mg");
+	if (!lua_isnil(L, -1)) {
+		lua_getfield(L, -1, "write"); /* call mg.write() */
+		lua_pushstring(L, error_msg);
+		lua_pushliteral(L, "\n");
+		lua_call(L, 2, 0);
+		IGNORE_UNUSED_RESULT(
+		    luaL_dostring(L, "mg.write(debug.traceback(), '\\n')"));
+	} else {
+		printf("Lua error: [%s]\n", error_msg);
+		IGNORE_UNUSED_RESULT(
+		    luaL_dostring(L, "print(debug.traceback(), '\\n')"));
+	}
+	/* TODO(lsm): leave the stack balanced */
+
+	return 0;
 }
 
-static void * lua_allocator(void *ud, void *ptr, size_t osize, size_t nsize) {
+static void *lua_allocator(void *ud, void *ptr, size_t osize, size_t nsize) {
 
-    (void)ud; (void)osize; /* not used */
+	(void)ud;
+	(void)osize; /* not used */
 
-    if (nsize == 0) {
-        mg_free(ptr);
-        return NULL;
-    }
-    return mg_realloc(ptr, nsize);
+	if (nsize == 0) {
+		mg_free(ptr);
+		return NULL;
+	}
+	return mg_realloc(ptr, nsize);
 }
 
 void mg_exec_lua_script(struct mg_connection *conn, const char *path,
-    const void **exports)
-{
-    int i;
-    lua_State *L;
-
-    /* Assume the script does not support keep_alive. The script may change this by calling mg.keep_alive(true). */
-    conn->must_close=1;
-
-    /* Execute a plain Lua script. */
-    if (path != NULL && (L = lua_newstate(lua_allocator, NULL)) != NULL) {
-        prepare_lua_environment(conn->ctx, conn, NULL, L, path, LUA_ENV_TYPE_PLAIN_LUA_PAGE);
-        lua_pushcclosure(L, &lua_error_handler, 0);
-
-        if (exports != NULL) {
-            lua_pushglobaltable(L);
-            for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
-                lua_CFunction func;
-                lua_pushstring(L, (const char *)(exports[i]));
-                *(const void**)(&func) = exports[i + 1];
-                lua_pushcclosure(L, func, 0);
-                lua_rawset(L, -3);
-            }
-        }
-
-        if (luaL_loadfile(L, path) != 0) {
-            lua_error_handler(L);
-        }
-        lua_pcall(L, 0, 0, -2);
-        lua_close(L);
-    }
+                        const void **exports) {
+	int i;
+	lua_State *L;
+
+	/* Assume the script does not support keep_alive. The script may change this
+	 * by calling mg.keep_alive(true). */
+	conn->must_close = 1;
+
+	/* Execute a plain Lua script. */
+	if (path != NULL && (L = lua_newstate(lua_allocator, NULL)) != NULL) {
+		prepare_lua_environment(conn->ctx, conn, NULL, L, path,
+		                        LUA_ENV_TYPE_PLAIN_LUA_PAGE);
+		lua_pushcclosure(L, &lua_error_handler, 0);
+
+		if (exports != NULL) {
+			lua_pushglobaltable(L);
+			for (i = 0; exports[i] != NULL && exports[i + 1] != NULL; i += 2) {
+				lua_CFunction func;
+				lua_pushstring(L, (const char *)(exports[i]));
+				*(const void **)(&func) = exports[i + 1];
+				lua_pushcclosure(L, func, 0);
+				lua_rawset(L, -3);
+			}
+		}
+
+		if (luaL_loadfile(L, path) != 0) {
+			lua_error_handler(L);
+		}
+		lua_pcall(L, 0, 0, -2);
+		lua_close(L);
+	}
 }
 
-static int handle_lsp_request(struct mg_connection *conn, const char *path, struct file *filep, struct lua_State *ls)
-{
-    void *p = NULL;
-    lua_State *L = NULL;
-    int error = 1;
-
-    /* Assume the script does not support keep_alive. The script may change this by calling mg.keep_alive(true). */
-    conn->must_close=1;
-
-    /* We need both mg_stat to get file size, and mg_fopen to get fd */
-    if (!mg_stat(conn, path, filep) || !mg_fopen(conn, path, "r", filep)) {
-        /* File not found or not accessible */
-        if (ls == NULL) {
-            send_http_error(conn, 500,
-                "Error: Cannot open script\nFile %s can not be read", path);
-        } else {
-            luaL_error(ls, "File [%s] not found", path);
-        }
-    } else if (filep->membuf == NULL &&
-        (p = mmap(NULL, (size_t) filep->size, PROT_READ, MAP_PRIVATE,
-        fileno(filep->fp), 0)) == MAP_FAILED) {
-        /* mmap failed */
-        if (ls == NULL) {
-            send_http_error(conn, 500,
-                "Error: Cannot open script\nFile %s can not be mapped", path);
-        } else {
-            luaL_error(ls, "mmap(%s, %zu, %d): %s", path, (size_t) filep->size,
-                fileno(filep->fp), strerror(errno));
-        }
-    } else if ((L = (ls != NULL ? ls : lua_newstate(lua_allocator, NULL))) == NULL) {
-        send_http_error(conn, 500, "%s",
-            "Error: Cannot execute script\nlua_newstate failed");
-    } else {
-        /* We're not sending HTTP headers here, Lua page must do it. */
-        if (ls == NULL) {
-            prepare_lua_environment(conn->ctx, conn, NULL, L, path, LUA_ENV_TYPE_LUA_SERVER_PAGE);
-        }
-        error = lsp(conn, path, (filep->membuf == NULL) ? (const char *)p : (const char *)filep->membuf,
-            filep->size, L);
-    }
-
-    if (L != NULL && ls == NULL) lua_close(L);
-    if (p != NULL) munmap(p, filep->size);
-    mg_fclose(filep);
-    return error;
+static int handle_lsp_request(struct mg_connection *conn, const char *path,
+                              struct file *filep, struct lua_State *ls) {
+	void *p = NULL;
+	lua_State *L = NULL;
+	int error = 1;
+
+	/* Assume the script does not support keep_alive. The script may change this
+	 * by calling mg.keep_alive(true). */
+	conn->must_close = 1;
+
+	/* We need both mg_stat to get file size, and mg_fopen to get fd */
+	if (!mg_stat(conn, path, filep) || !mg_fopen(conn, path, "r", filep)) {
+		/* File not found or not accessible */
+		if (ls == NULL) {
+			send_http_error(
+			    conn, 500, "Error: Cannot open script\nFile %s can not be read",
+			    path);
+		} else {
+			luaL_error(ls, "File [%s] not found", path);
+		}
+	} else if (filep->membuf == NULL &&
+	           (p = mmap(NULL, (size_t)filep->size, PROT_READ, MAP_PRIVATE,
+	                     fileno(filep->fp), 0)) == MAP_FAILED) {
+		/* mmap failed */
+		if (ls == NULL) {
+			send_http_error(
+			    conn, 500,
+			    "Error: Cannot open script\nFile %s can not be mapped", path);
+		} else {
+			luaL_error(ls, "mmap(%s, %zu, %d): %s", path, (size_t)filep->size,
+			           fileno(filep->fp), strerror(errno));
+		}
+	} else if ((L = (ls != NULL ? ls : lua_newstate(lua_allocator, NULL))) ==
+	           NULL) {
+		send_http_error(conn, 500, "%s",
+		                "Error: Cannot execute script\nlua_newstate failed");
+	} else {
+		/* We're not sending HTTP headers here, Lua page must do it. */
+		if (ls == NULL) {
+			prepare_lua_environment(conn->ctx, conn, NULL, L, path,
+			                        LUA_ENV_TYPE_LUA_SERVER_PAGE);
+		}
+		error = lsp(conn, path,
+		            (filep->membuf == NULL) ? (const char *)p
+		                                    : (const char *)filep->membuf,
+		            filep->size, L);
+	}
+
+	if (L != NULL && ls == NULL)
+		lua_close(L);
+	if (p != NULL)
+		munmap(p, filep->size);
+	mg_fclose(filep);
+	return error;
 }
 
 #ifdef USE_WEBSOCKET
 struct mg_shared_lua_websocket_list {
-    struct lua_websock_data ws;
-    struct mg_shared_lua_websocket_list *next;
+	struct lua_websock_data ws;
+	struct mg_shared_lua_websocket_list *next;
 };
 
-static void * lua_websocket_new(const char * script, struct mg_connection *conn)
-{
-    struct mg_shared_lua_websocket_list **shared_websock_list = &(conn->ctx->shared_lua_websockets);
-    struct lua_websock_data *ws;
-    int err, ok = 0;
-
-    assert(conn->lua_websocket_state == NULL);
-
-    /* lock list (mg_context global) */
-    mg_lock_context(conn->ctx);
-    while (*shared_websock_list) {
-        /* check if ws already in list */
-        if (0==strcmp(script,(*shared_websock_list)->ws.script)) {
-            break;
-        }
-        shared_websock_list = &((*shared_websock_list)->next);
-    }
-    if (*shared_websock_list == NULL) {
-        /* add ws to list */
-        *shared_websock_list = (struct mg_shared_lua_websocket_list *) mg_calloc(sizeof(struct mg_shared_lua_websocket_list), 1);
-        if (*shared_websock_list == NULL) {
-            mg_unlock_context(conn->ctx);
-            mg_cry(conn, "Cannot create shared websocket struct, OOM");
-            return NULL;
-        }
-        /* init ws list element */
-        ws = &(*shared_websock_list)->ws;
-        ws->script = mg_strdup(script); /* TODO: handle OOM */
-        pthread_mutex_init(&(ws->ws_mutex), NULL);
-        ws->state = lua_newstate(lua_allocator, NULL);
-        ws->conn[0] = conn;
-        ws->references = 1;
-        (void)pthread_mutex_lock(&(ws->ws_mutex));
-        prepare_lua_environment(conn->ctx, NULL, ws, ws->state, script, LUA_ENV_TYPE_LUA_WEBSOCKET);
-        err = luaL_loadfile(ws->state, script);
-        if (err != 0) {
-            lua_cry(conn, err, ws->state, script, "load");
-        }
-        err = lua_pcall(ws->state, 0, 0, 0);
-        if (err != 0) {
-            lua_cry(conn, err, ws->state, script, "init");
-        }
-    } else {
-        /* inc ref count */
-        ws = &(*shared_websock_list)->ws;
-        (void)pthread_mutex_lock(&(ws->ws_mutex));
-        (*shared_websock_list)->ws.conn[(ws->references)++] = conn;
-    }
-    mg_unlock_context(conn->ctx);
-
-    /* call add */
-    lua_getglobal(ws->state, "open");
-    lua_newtable(ws->state);
-    prepare_lua_request_info(conn, ws->state);
-    lua_pushstring(ws->state, "client");
-    lua_pushlightuserdata(ws->state, (void *)conn);
-    lua_rawset(ws->state, -3);
-
-    err = lua_pcall(ws->state, 1, 1, 0);
-    if (err != 0) {
-        lua_cry(conn, err, ws->state, script, "open handler");
-    } else {
-        if (lua_isboolean(ws->state, -1)) {
-            ok = lua_toboolean(ws->state, -1);
-        }
-        lua_pop(ws->state, 1);
-    }
-    if (!ok) {
-        /* Remove from ws connection list. */
-        /* TODO: Check if list entry and Lua state needs to be deleted (see websocket_close). */
-        (*shared_websock_list)->ws.conn[--(ws->references)] = 0;
-    }
-
-    (void)pthread_mutex_unlock(&(ws->ws_mutex));
-
-    return ok ? (void*)ws : NULL;
+static void *lua_websocket_new(const char *script, struct mg_connection *conn) {
+	struct mg_shared_lua_websocket_list **shared_websock_list =
+	    &(conn->ctx->shared_lua_websockets);
+	struct lua_websock_data *ws;
+	int err, ok = 0;
+
+	assert(conn->lua_websocket_state == NULL);
+
+	/* lock list (mg_context global) */
+	mg_lock_context(conn->ctx);
+	while (*shared_websock_list) {
+		/* check if ws already in list */
+		if (0 == strcmp(script, (*shared_websock_list)->ws.script)) {
+			break;
+		}
+		shared_websock_list = &((*shared_websock_list)->next);
+	}
+	if (*shared_websock_list == NULL) {
+		/* add ws to list */
+		*shared_websock_list = (struct mg_shared_lua_websocket_list *)mg_calloc(
+		    sizeof(struct mg_shared_lua_websocket_list), 1);
+		if (*shared_websock_list == NULL) {
+			mg_unlock_context(conn->ctx);
+			mg_cry(conn, "Cannot create shared websocket struct, OOM");
+			return NULL;
+		}
+		/* init ws list element */
+		ws = &(*shared_websock_list)->ws;
+		ws->script = mg_strdup(script); /* TODO: handle OOM */
+		pthread_mutex_init(&(ws->ws_mutex), NULL);
+		ws->state = lua_newstate(lua_allocator, NULL);
+		ws->conn[0] = conn;
+		ws->references = 1;
+		(void)pthread_mutex_lock(&(ws->ws_mutex));
+		prepare_lua_environment(conn->ctx, NULL, ws, ws->state, script,
+		                        LUA_ENV_TYPE_LUA_WEBSOCKET);
+		err = luaL_loadfile(ws->state, script);
+		if (err != 0) {
+			lua_cry(conn, err, ws->state, script, "load");
+		}
+		err = lua_pcall(ws->state, 0, 0, 0);
+		if (err != 0) {
+			lua_cry(conn, err, ws->state, script, "init");
+		}
+	} else {
+		/* inc ref count */
+		ws = &(*shared_websock_list)->ws;
+		(void)pthread_mutex_lock(&(ws->ws_mutex));
+		(*shared_websock_list)->ws.conn[(ws->references)++] = conn;
+	}
+	mg_unlock_context(conn->ctx);
+
+	/* call add */
+	lua_getglobal(ws->state, "open");
+	lua_newtable(ws->state);
+	prepare_lua_request_info(conn, ws->state);
+	lua_pushstring(ws->state, "client");
+	lua_pushlightuserdata(ws->state, (void *)conn);
+	lua_rawset(ws->state, -3);
+
+	err = lua_pcall(ws->state, 1, 1, 0);
+	if (err != 0) {
+		lua_cry(conn, err, ws->state, script, "open handler");
+	} else {
+		if (lua_isboolean(ws->state, -1)) {
+			ok = lua_toboolean(ws->state, -1);
+		}
+		lua_pop(ws->state, 1);
+	}
+	if (!ok) {
+		/* Remove from ws connection list. */
+		/* TODO: Check if list entry and Lua state needs to be deleted (see
+		 * websocket_close). */
+		(*shared_websock_list)->ws.conn[--(ws->references)] = 0;
+	}
+
+	(void)pthread_mutex_unlock(&(ws->ws_mutex));
+
+	return ok ? (void *)ws : NULL;
 }
 
-static int lua_websocket_data(struct mg_connection * conn, int bits, char *data, size_t data_len, void *ws_arg)
-{
-    struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
-    int err, ok = 0;
-
-    assert(ws != NULL);
-    assert(ws->state != NULL);
-
-    (void)pthread_mutex_lock(&ws->ws_mutex);
-
-    lua_getglobal(ws->state, "data");
-    lua_newtable(ws->state);
-    lua_pushstring(ws->state, "client");
-    lua_pushlightuserdata(ws->state, (void *)conn);
-    lua_rawset(ws->state, -3);
-    lua_pushstring(ws->state, "bits"); /* TODO: dont use "bits" but fields with a meaning according to http://tools.ietf.org/html/rfc6455, section 5.2 */
-    lua_pushnumber(ws->state, bits);
-    lua_rawset(ws->state, -3);
-    lua_pushstring(ws->state, "data");
-    lua_pushlstring(ws->state, data, data_len);
-    lua_rawset(ws->state, -3);
-
-    err = lua_pcall(ws->state, 1, 1, 0);
-    if (err != 0) {
-        lua_cry(conn, err, ws->state, ws->script, "data handler");
-    } else {
-        if (lua_isboolean(ws->state, -1)) {
-            ok = lua_toboolean(ws->state, -1);
-        }
-        lua_pop(ws->state, 1);
-    }
-    (void)pthread_mutex_unlock(&ws->ws_mutex);
-
-    return ok;
+static int lua_websocket_data(struct mg_connection *conn, int bits, char *data,
+                              size_t data_len, void *ws_arg) {
+	struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
+	int err, ok = 0;
+
+	assert(ws != NULL);
+	assert(ws->state != NULL);
+
+	(void)pthread_mutex_lock(&ws->ws_mutex);
+
+	lua_getglobal(ws->state, "data");
+	lua_newtable(ws->state);
+	lua_pushstring(ws->state, "client");
+	lua_pushlightuserdata(ws->state, (void *)conn);
+	lua_rawset(ws->state, -3);
+	lua_pushstring(ws->state, "bits"); /* TODO: dont use "bits" but fields with
+	                                      a meaning according to
+	                                      http://tools.ietf.org/html/rfc6455,
+	                                      section 5.2 */
+	lua_pushnumber(ws->state, bits);
+	lua_rawset(ws->state, -3);
+	lua_pushstring(ws->state, "data");
+	lua_pushlstring(ws->state, data, data_len);
+	lua_rawset(ws->state, -3);
+
+	err = lua_pcall(ws->state, 1, 1, 0);
+	if (err != 0) {
+		lua_cry(conn, err, ws->state, ws->script, "data handler");
+	} else {
+		if (lua_isboolean(ws->state, -1)) {
+			ok = lua_toboolean(ws->state, -1);
+		}
+		lua_pop(ws->state, 1);
+	}
+	(void)pthread_mutex_unlock(&ws->ws_mutex);
+
+	return ok;
 }
 
-static int lua_websocket_ready(struct mg_connection * conn, void * ws_arg)
-{
-    struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
-    int err, ok = 0;
+static int lua_websocket_ready(struct mg_connection *conn, void *ws_arg) {
+	struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
+	int err, ok = 0;
 
-    assert(ws != NULL);
-    assert(ws->state != NULL);
+	assert(ws != NULL);
+	assert(ws->state != NULL);
 
-    (void)pthread_mutex_lock(&ws->ws_mutex);
+	(void)pthread_mutex_lock(&ws->ws_mutex);
 
-    lua_getglobal(ws->state, "ready");
-    lua_newtable(ws->state);
-    lua_pushstring(ws->state, "client");
-    lua_pushlightuserdata(ws->state, (void *)conn);
-    lua_rawset(ws->state, -3);
+	lua_getglobal(ws->state, "ready");
+	lua_newtable(ws->state);
+	lua_pushstring(ws->state, "client");
+	lua_pushlightuserdata(ws->state, (void *)conn);
+	lua_rawset(ws->state, -3);
 
-    err = lua_pcall(ws->state, 1, 1, 0);
-    if (err != 0) {
-        lua_cry(conn, err, ws->state, ws->script, "ready handler");
-    } else {
-        if (lua_isboolean(ws->state, -1)) {
-            ok = lua_toboolean(ws->state, -1);
-        }
-        lua_pop(ws->state, 1);
-    }
+	err = lua_pcall(ws->state, 1, 1, 0);
+	if (err != 0) {
+		lua_cry(conn, err, ws->state, ws->script, "ready handler");
+	} else {
+		if (lua_isboolean(ws->state, -1)) {
+			ok = lua_toboolean(ws->state, -1);
+		}
+		lua_pop(ws->state, 1);
+	}
 
-    (void)pthread_mutex_unlock(&ws->ws_mutex);
+	(void)pthread_mutex_unlock(&ws->ws_mutex);
 
-    return ok;
+	return ok;
 }
 
-static void lua_websocket_close(struct mg_connection * conn, void * ws_arg)
-{
-    struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
-    struct mg_shared_lua_websocket_list **shared_websock_list = &(conn->ctx->shared_lua_websockets);
-    int err = 0;
-    unsigned i;
-
-    assert(ws != NULL);
-    assert(ws->state != NULL);
-
-    (void)pthread_mutex_lock(&ws->ws_mutex);
-
-    lua_getglobal(ws->state, "close");
-    lua_newtable(ws->state);
-    lua_pushstring(ws->state, "client");
-    lua_pushlightuserdata(ws->state, (void *)conn);
-    lua_rawset(ws->state, -3);
-
-    err = lua_pcall(ws->state, 1, 0, 0);
-    if (err != 0) {
-        lua_cry(conn, err, ws->state, ws->script, "close handler");
-    }
-    for (i=0;i<ws->references;i++) {
-        if (ws->conn[i]==conn) {
-            ws->references--;
-            ws->conn[i] = ws->conn[ws->references];
-        }
-    }
-    /* TODO: Delete lua_websock_data and remove it from the websocket list.
-       This must only be done, when all connections are closed, and all
-       asynchronous operations and timers are completed/expired. */
-    (void)pthread_mutex_unlock(&ws->ws_mutex);
+static void lua_websocket_close(struct mg_connection *conn, void *ws_arg) {
+	struct lua_websock_data *ws = (struct lua_websock_data *)(ws_arg);
+	struct mg_shared_lua_websocket_list **shared_websock_list =
+	    &(conn->ctx->shared_lua_websockets);
+	int err = 0;
+	unsigned i;
+
+	assert(ws != NULL);
+	assert(ws->state != NULL);
+
+	(void)pthread_mutex_lock(&ws->ws_mutex);
+
+	lua_getglobal(ws->state, "close");
+	lua_newtable(ws->state);
+	lua_pushstring(ws->state, "client");
+	lua_pushlightuserdata(ws->state, (void *)conn);
+	lua_rawset(ws->state, -3);
+
+	err = lua_pcall(ws->state, 1, 0, 0);
+	if (err != 0) {
+		lua_cry(conn, err, ws->state, ws->script, "close handler");
+	}
+	for (i = 0; i < ws->references; i++) {
+		if (ws->conn[i] == conn) {
+			ws->references--;
+			ws->conn[i] = ws->conn[ws->references];
+		}
+	}
+	/* TODO: Delete lua_websock_data and remove it from the websocket list.
+	   This must only be done, when all connections are closed, and all
+	   asynchronous operations and timers are completed/expired. */
+	(void)pthread_mutex_unlock(&ws->ws_mutex);
 }
 #endif

+ 104 - 107
src/timer.inl

@@ -1,131 +1,128 @@
-
-#if !defined(MAX_TIMERS)
-#define MAX_TIMERS MAX_WORKER_THREADS
-#endif
-
-typedef int (*taction)(void *arg);
-
-struct ttimer {
-    double time;
-    double period;
-    taction action;
-    void * arg;
-};
-
-struct ttimers {
-    pthread_t threadid;               /* Timer thread ID */
-    pthread_mutex_t mutex;            /* Protects timer lists */
-    struct ttimer timers[MAX_TIMERS];  /* List of timers */
-    unsigned timer_count;             /* Current size of timer list */
+
+#if !defined(MAX_TIMERS)
+#define MAX_TIMERS MAX_WORKER_THREADS
+#endif
+
+typedef int (*taction)(void *arg);
+
+struct ttimer {
+	double time;
+	double period;
+	taction action;
+	void *arg;
 };
 
-static int timer_add(struct mg_context * ctx, double next_time, double period, int is_relative, taction action, void * arg)
-{
-    unsigned u, v;
-    int error = 0;
-    struct timespec now;
+struct ttimers {
+	pthread_t threadid;               /* Timer thread ID */
+	pthread_mutex_t mutex;            /* Protects timer lists */
+	struct ttimer timers[MAX_TIMERS]; /* List of timers */
+	unsigned timer_count;             /* Current size of timer list */
+};
+
+static int timer_add(struct mg_context *ctx, double next_time, double period,
+                     int is_relative, taction action, void *arg) {
+	unsigned u, v;
+	int error = 0;
+	struct timespec now;
 
-    if (ctx->stop_flag) {
-        return 0;
-    }
+	if (ctx->stop_flag) {
+		return 0;
+	}
 
-    if (is_relative) {
-        clock_gettime(CLOCK_MONOTONIC, &now);
-        next_time += now.tv_sec;
-        next_time += now.tv_nsec * 1.0E-9;
-    }
+	if (is_relative) {
+		clock_gettime(CLOCK_MONOTONIC, &now);
+		next_time += now.tv_sec;
+		next_time += now.tv_nsec * 1.0E-9;
+	}
 
-    pthread_mutex_lock(&ctx->timers->mutex);
-    if (ctx->timers->timer_count == MAX_TIMERS) {
-        error = 1;
-    } else {
-        for (u=0; u<ctx->timers->timer_count; u++) {
-            if (ctx->timers->timers[u].time < next_time) {
-                for (v=ctx->timers->timer_count; v>u; v--) {
-                    ctx->timers->timers[v] = ctx->timers->timers[v-1];
-                }
-                break;
-            }
-        }
-        ctx->timers->timers[u].time = next_time;
-        ctx->timers->timers[u].period = period;
-        ctx->timers->timers[u].action = action;
-        ctx->timers->timers[u].arg = arg;
-        ctx->timers->timer_count++;
-    }
-    pthread_mutex_unlock(&ctx->timers->mutex);
-    return error;
+	pthread_mutex_lock(&ctx->timers->mutex);
+	if (ctx->timers->timer_count == MAX_TIMERS) {
+		error = 1;
+	} else {
+		for (u = 0; u < ctx->timers->timer_count; u++) {
+			if (ctx->timers->timers[u].time < next_time) {
+				for (v = ctx->timers->timer_count; v > u; v--) {
+					ctx->timers->timers[v] = ctx->timers->timers[v - 1];
+				}
+				break;
+			}
+		}
+		ctx->timers->timers[u].time = next_time;
+		ctx->timers->timers[u].period = period;
+		ctx->timers->timers[u].action = action;
+		ctx->timers->timers[u].arg = arg;
+		ctx->timers->timer_count++;
+	}
+	pthread_mutex_unlock(&ctx->timers->mutex);
+	return error;
 }
 
-static void timer_thread_run(void *thread_func_param)
-{
-    struct mg_context *ctx = (struct mg_context *) thread_func_param;
-    struct timespec now;
-    double d;
-    unsigned u;
-    int re_schedule;
-    struct ttimer t;
+static void timer_thread_run(void *thread_func_param) {
+	struct mg_context *ctx = (struct mg_context *)thread_func_param;
+	struct timespec now;
+	double d;
+	unsigned u;
+	int re_schedule;
+	struct ttimer t;
 
 #if defined(HAVE_CLOCK_NANOSLEEP) /* Linux with librt */
-    /* TODO */
-    while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &request, &request)==EINTR) {/*nop*/;}
+	/* TODO */
+	while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &request,
+	                       &request) == EINTR) { /*nop*/
+		;
+	}
 #else
-    clock_gettime(CLOCK_MONOTONIC, &now);
-    d = (double)now.tv_sec + (double)now.tv_nsec * 1.0E-9;
-    while (ctx->stop_flag == 0) {
-        pthread_mutex_lock(&ctx->timers->mutex);
-        if (ctx->timers->timer_count > 0 && d >= ctx->timers->timers[0].time) {
-            t = ctx->timers->timers[0];
-            for (u=1; u<ctx->timers->timer_count; u++) {
-                ctx->timers->timers[u-1] = ctx->timers->timers[u];
-            }
-            ctx->timers->timer_count--;
-            pthread_mutex_unlock(&ctx->timers->mutex);
-            re_schedule = t.action(t.arg);
-            if (re_schedule && (t.period>0)) {
-                timer_add(ctx, t.time+t.period, t.period, 0, t.action, t.arg);
-            }
-            continue;
-        } else {
-            pthread_mutex_unlock(&ctx->timers->mutex);
-        }
-        mg_sleep(1);
-        clock_gettime(CLOCK_MONOTONIC, &now);
-        d = (double)now.tv_sec + (double)now.tv_nsec * 1.0E-9;
-    }
+	clock_gettime(CLOCK_MONOTONIC, &now);
+	d = (double)now.tv_sec + (double)now.tv_nsec * 1.0E-9;
+	while (ctx->stop_flag == 0) {
+		pthread_mutex_lock(&ctx->timers->mutex);
+		if (ctx->timers->timer_count > 0 && d >= ctx->timers->timers[0].time) {
+			t = ctx->timers->timers[0];
+			for (u = 1; u < ctx->timers->timer_count; u++) {
+				ctx->timers->timers[u - 1] = ctx->timers->timers[u];
+			}
+			ctx->timers->timer_count--;
+			pthread_mutex_unlock(&ctx->timers->mutex);
+			re_schedule = t.action(t.arg);
+			if (re_schedule && (t.period > 0)) {
+				timer_add(ctx, t.time + t.period, t.period, 0, t.action, t.arg);
+			}
+			continue;
+		} else {
+			pthread_mutex_unlock(&ctx->timers->mutex);
+		}
+		mg_sleep(1);
+		clock_gettime(CLOCK_MONOTONIC, &now);
+		d = (double)now.tv_sec + (double)now.tv_nsec * 1.0E-9;
+	}
 #endif
-
 }
 
 #ifdef _WIN32
-static unsigned __stdcall timer_thread(void *thread_func_param)
-{
-    timer_thread_run(thread_func_param);
-    return 0;
+static unsigned __stdcall timer_thread(void *thread_func_param) {
+	timer_thread_run(thread_func_param);
+	return 0;
 }
 #else
-static void *timer_thread(void *thread_func_param)
-{
-    timer_thread_run(thread_func_param);
-    return NULL;
+static void *timer_thread(void *thread_func_param) {
+	timer_thread_run(thread_func_param);
+	return NULL;
 }
 #endif /* _WIN32 */
 
-static int timers_init(struct mg_context * ctx)
-{
-    ctx->timers = (struct ttimers*) mg_calloc(sizeof(struct ttimers), 1);
-    (void) pthread_mutex_init(&ctx->timers->mutex, NULL);
+static int timers_init(struct mg_context *ctx) {
+	ctx->timers = (struct ttimers *)mg_calloc(sizeof(struct ttimers), 1);
+	(void)pthread_mutex_init(&ctx->timers->mutex, NULL);
 
-    /* Start timer thread */
-    mg_start_thread_with_id(timer_thread, ctx, &ctx->timers->threadid);
+	/* Start timer thread */
+	mg_start_thread_with_id(timer_thread, ctx, &ctx->timers->threadid);
 
-    return 0;
+	return 0;
 }
 
-static void timers_exit(struct mg_context * ctx)
-{
-    if (ctx->timers) {
-        (void) pthread_mutex_destroy(&ctx->timers->mutex);
-        mg_free(ctx->timers);
-    }
+static void timers_exit(struct mg_context *ctx) {
+	if (ctx->timers) {
+		(void)pthread_mutex_destroy(&ctx->timers->mutex);
+		mg_free(ctx->timers);
+	}
 }

Algúns arquivos non se mostraron porque demasiados arquivos cambiaron neste cambio