Moonbridge reference ==================== Global function listen{...} --------------------------- This function initializes the Moonbridge Network Server. It may be called multiple times. However, it is not allowed to register additional listeners by calling listen(...) from a "prepare", "connect", or "finish" handler. See file "example.lua" for parametrization of the listen(...) function. Warning: Moonbridge will fork the Lua environment to handle parallel requests. Functions provided as "prepare", "connect", and "finish" handlers may access global variables, but for every child process these global variables will not be shared! If you require a global state, a DBMS, cache server, or similar is necessary. Global function timeout(...) ---------------------------- Calling this function with a positive number (time in seconds) sets a timer that kills the current process after the selected time runs out. The remaining time can be queried by calling this function without arguments. Calling this function with a single argument that is the number zero will disable the timeout. Another mode of operation is selected by passing two arguments: a time (in seconds) as first argument and a function as second argument. In this case, a sub-timer will be used to limit the execution time of the function. In case of timeout, the process will be killed (and the timeout function does not return). If the time for the sub-timer is longer than a previously set timeout (using the timeout(...) function with one argument), the shorter timeout (of the previous call of timeout(...)) will have precedence. Timers are also automatically reset (disabled) when a handler (prepare handler or connect handler) returns. To shutdown processes after a certain time waiting for a new request, use the idle_time parameter of the listen function. Socket object passed to "connect" handler ----------------------------------------- For every incoming connection, the registered "connect" handler is called with a single socket object as argument, which is described below: ### socket:close() Closes the socket connection (input and output stream) by flushing all data and sending a TCP FIN packet. Returns true on success, or nil plus error message in case of an I/O error. Using this method on sockets that have already been closed (or reset) will throw an error. Warning: Pending data on the input stream may cause connection aborts (TCP RST) when network connections are used. All pending input data should have been read (or drained) before calling socket:close(). Use socket:finish() to send a TCP FIN packet to the peer before waiting for EOF from the peer. ### socket:drain(maxlen, terminator) Same as socket:read(maxlen, terminator), but discards the input and returns the number of discarded bytes. If no bytes could be read but EOF was encountered, then true is returned. In case of an I/O error, nil (as first return value) plus an error message (as second result value) are returned. ### socket:drain_nb(maxlen, terminator) Same as socket:read_nb(maxlen, terminator), but discards the input and returns the number of discarded bytes. If no bytes could be read but EOF was encountered, then true is returned. In case of an I/O error, nil (as first return value) plus an error message (as second result value) are returned. ### socket:finish() Sends a TCP FIN packet to indicate EOF on write stream. Subsequent reads are still possible. When there is no more input data to be read, the connection should finally be closed with socket:close(). In case of local sockets (Unix Domain Sockets), socket:finish() simply closes the underlying socket and emulates EOF on subsequent reads. Also in this case, the connection should be finally closed with socket:close(). ### socket:flush(...) Same as socket:write(...) but additionally flushes the socket (i.e. all pending data is passed to the operating system). In case of an I/O error, nil (as first return value) plus an error message (as second result value) are returned. On success, the socket userdata object is returned. ### socket:flush_nb(...) Same as socket:write_nb(...) but additionally flushes the socket (i.e. all pending data is passed to the operating system). The total number of bytes that could not be passed yet to the operating system is returned. Zero is returned if all data could be flushed out. In case of an I/O error, nil (as first return value) plus an error message (as second result value) are returned. ### socket.interval Set to the name of an interval timer if the "connect" handler was called due to an elapsed interval timer. Otherwise nil. ### socket.local_ip4 Local IPv4 address used for the connection. Encoded as 4 raw bytes in form of a string. ### socket.local_ip6 Local IPv6 address used for the connection. Encoded as 16 raw bytes in form of a string. ### socket.local_tcpport Local TCP port used for the connection. ### socket:read(maxlen, terminator) Read up to maxlen bytes or until an optional termination character is encountered (which is included in the result). The maxlen value may be nil, in which case there is no limit on the number of bytes read. If EOF is encountered before any data could be read, then false (as first return value) plus a notice string (as second return value) are returned. In case of an I/O error, nil (as first return value) plus an error message (as second result value) are returned. ### socket:read_nb(maxlen, terminator) Read up to maxlen bytes, until an optional termination character is encountered (which is included in the result), or until no more data is available for reading. The maxlen value may be nil, in which case there is no limit on the number of bytes read. If EOF is encountered before any data could be read, then false (as first return value) plus a notice string (as second return value) are returned. If no data was available for reading, but no EOF was encountered, then an empty string is returned. In case of an I/O error, nil (as first return value) plus an error message (as second result value) are returned. ### socket.remote_ip4 Remote IPv4 address used for the connection. Encoded as 4 raw bytes in form of a string. ### socket.remote_ip6 Remote IPv6 address used for the connection. Encoded as 16 raw bytes in form of a string. ### socket.remote_tcpport Remote TCP port used for the connection. ### socket:reset() Alias for socket:close(0). Closes the socket connection by sending a TCP RST packet if possible to indicate error condition. Returns true on success, or nil (as first result value) plus error message (as second result value) in case of an I/O error. Using this method on sockets that have already been closed (or reset) will throw an error. Warning: Previously sent (and flushed) data may be lost during transmission. ### socket:write(...) Takes a variable number of strings and sends them to the peer. The operation is buffered, so to actually send out the data, it is necessary to eventually call socket:flush(), socket:finish(), or socket:close(). In case of an I/O error, nil (as first return value) plus an error message (as second result value) are returned. On success, the socket userdata object is returned. ### socket:write_nb(...) Takes a variable number of strings and sends them to the peer. The operation is buffered, so to actually send out the data, it is necessary to eventually call socket:flush_nb(), socket:flush(), socket:finish(), or socket:close(). This function always returns immediately (i.e. it does not block). If all data (but a small buffered portion) could be sent out, then zero is returned. Otherwise, all arguments that could not be sent are stored in a buffer of unlimited size (up to memory capabilities) and an integer is returned that indicates the number of bytes currently in the buffer. In case of an I/O error, nil (as first return value) plus an error message (as second result value) are returned. HTTP module ----------- The http module exports the function http.generate_handler(callback) that converts an HTTP handler to a "connect" handler. See file "example.lua" for an example of invocation. A table with options may be passed either as a second argument, or as a first argument preceeding the callback function (whichever is more convenient). The following options are supported: - request_body_size_limit: maximum size of payload of HTTP request body (transfer encoding is allowed to add a limited amount of extra data) - chunk_size: optional default value for maximum_input_chunk_size and minimum_output_chunk_size - request_header_size_limit: maximum size of HTTP request headers - maximum_input_chunk_size: maximum chunk size when streaming a request body or certain POST fields (bigger chunks will be fragmented automatically) - minimum_output_chunk_size: minimum size for a chunk when sending a response body (smaller chunks will be buffered and concatenated with future data; ignored when request:flush() is called) - static_headers: a set of headers to be included in every HTTP response (may be a string, a table or strings, or a table of key-value pairs) The callback function receives a single request object as argument, which is described below. ### request.body The request body (without headers) as a string. Accessing this value makes further access to request.post_params and request.post_params_list, or invocation of request:stream_request_body(...) impossible. ### request:close_after_finish() Closes the connection after answering the request. This method can only be called before the HTTP response header section has been finished (i.e. before request:finish_headers(), request:send_data(...), or request:finish() were called), but it may be called before a status code has been sent using request:send_status(...). A corresponding "Connection: close" header is automatically sent. ### request.cookies A table with all cookies sent by the client. ### request.defer_reading() Disables automatic request body processing on write. Can be called before sending a HTTP status code to send a response before the request has been fully received. CAUTION: Responding to a request before the request body has been processed may lead to a deadlock if the browser does not process the response while trying to send the request. Therefore, this function should only be used if: - the TCP stack has enough buffer space for the response (i.e. if the response is small enough), and if - a timer is used to cancel the response in case of a deadlock. It is recommended to not use this function unless certain performance tweaks are desired. ### request.faulty Normally set to false. In case of a read or write error on the client connection, this value is set to true before a Lua error is raised. A faulty request handle must not be used, or another Lua error will be raised. ### request:finish() Finishes and flushes a HTTP response. May be called multiple times. An HTTP status, all headers, and the response body (if applicable) must have been previously sent. After calling this method, no further data may be written. ### request:finish_headers() Finishes and flushes the HTTP response header section. May be called multiple times, as long as the request is not finished completely. This method is automatically invoked if the application is beginning to send a response body. After calling this method, no further headers may be sent. ### request:flush() Flushes any pending output data. Note: In order to mark the end of a response body, it is required to call request:finish(). ### request.get_params A table that maps field names to their corresponding GET value. If there are several GET values with the given field name, then the first value is used. Note: May be implemented through metamethods, but does support iteration through pairs(...). ### request.get_params_list A table that maps field names to a sequence of their corresponding GET values. Note: May be implemented through metamethods, but does support iteration through pairs(...). ### request.headers A table that maps (case-insensitively) a HTTP header field name to a sequence of values. One entry is created for every occurrence of a header line with the given field name). ### request.headers_csv_string A table that maps (case-insensitively) a HTTP header field name to a comma separated string. Multiple occurrences of the header with the given field name are automatically merged into the comma separated string. ### request.headers_csv_table A table that maps (case-insensitively) a HTTP header field name to a sequence of values. One entry is created for every comma separated value of each header with the given field name. ### request.headers_flags A table that maps (case-insensitively) a HTTP header field name to another table which (again case-insensitively) maps a string to a boolean, depending on whether this string occurred in the list of comma separated values of one header line with the given field name that was the key in the first table. ### request.headers_value A table that maps (case-insensitively) a HTTP header field name to a value. If multiple header lines with the given field name have been received, false is used as value. ### request.method The HTTP request method, e.g. "HEAD", "GET", or "POST". ### request.path The requested path without a leading slash and without the query part (e.g. "index.html" if "/index.html?a=b&c=d" has been requested). For the query part, see request.query. This value will be nil if (and only if) the request method is "OPTIONS" with a request target equal to "*" (see also asterisk-form of request-target in section 5.3.4 in RFC 7230). ### request.post_metadata Only set for multipart/form-data POST requests. A table that maps field names to their corresponding POST metadata table which contains two entries: "file_name" and "content_type". If there are several POST values with the given field name, then the first value/file is used. ### request.post_metadata_list Only set for multipart/form-data POST requests. A table that maps field names to a sequence with their corresponding POST metadata tables. Needed if multiple files are uploaded with the same field name. ### request.post_params A table that maps field names to their corresponding POST value. If there are several POST values with the given field name, then the first value is used. Note: May be implemented through metamethods, but does support iteration through pairs(...). ### request.post_params_list A table that maps field names to a sequence of their corresponding POST values. Note: May be implemented through metamethods, but does support iteration through pairs(...). ### request.query Query part of the request target including the leading question mark, e.g. "?a=b&c=d" if the requested target is "/index.html?a=b&c=d". The data is automatically parsed and made available through request.get_params and request.get_params_list. If there is no query part given in the request target, then this string is the empty string. This value will be nil if (and only if) the request method is "OPTIONS" with a request target equal to "*" (see also asterisk-form of request-target in section 5.3.4 in RFC 7230). ### request:process_request_body() Starts processing the request body (if existent) to set the values request.post_params, request.post_params_list, request.post_metadata, and and request.post_metadata_list and/or to call POST field stream handlers that have been previously registered with request:stream_post_param(...) or request:stream_post_params(...). This method gets invoked automatically when the POST param tables (request.post_params, etc.) are accessed, or if a response is sent (to avoid deadlocks with the webbrowser). (Note: Automatic request body processing on write may be disabled by calling request:defer_reading().) After this method returned, all registered POST field stream handlers have received all data. Registration of other POST field stream handlers is not possible after this method has been called (or after request.post_params_list or request.post_params have been accessed). ### request:send_data(...) Sends data as response body. All arguments are converted via tostring(...) and concatenated. May be called multiple times until the request has been finished by calling request:finish(). If the request method (see request.method) is "HEAD", then calls to request:send_data(...) are automatically ignored. ### request:send_header(key, value) Sends a HTTP response header that consists of the given key and the given value. Note: Key and value must be provided as separate arguments. Before any headers can be sent, a HTTP status must have been set with request:send_status(status_string). ### request:send_status(status_string) Sends a HTTP response status that is given as a string consisting of a 3-digit number and an explanatory string, e.g. "200 OK" or "404 Not Found". This function must be called once before any headers or response body data may be sent. ### request.socket The underlaying socket. Can be used to force a TCP RST, etc. ### request:stream_post_param(field_name, callback) Registers a stream handler for the given POST parameter. The callback function will be called in the following manner: - For the initial chunk, the first chunk gets passed as first argument while a table with metadata ("field_name" and "content_type") gets passed as second argument. In case of an immediate EOF (i.e. an empty file), the passed chunk is the empty string. In all other cases the chunk has a length greater than zero. - For any remaining chunks, the respective chunk gets passed as first and only argument (no metadata). Here, the chunk has always a length greater than zero. - To indicate the end of the stream, the callback function is called without arguments. This also happens in case of an immediate EOF (see above). In case of an immediate EOF (i.e. an empty file), the callback function is thus called as follows: - The first time with an empty string as first argument, and with the metadata as second argument. - The second time without any arguments. ### request:stream_post_params(pattern, callback) Same as request:stream_post_param(...) but providing a string pattern to match multiple field names (e.g. "^file_[0-9]+$"). ### request:stream_request_body(callback) Start streaming of request body. For each chunk of the request body, the callback function is called with the corresponding chunk. End of data is indicated through return of request:stream_request_body(...) (not by calling the callback without arguments). The function may be called with nil instead of a callback function. In this case, the request body is read and discarded. Only if nil is passed instead of a callback, then the function may also be invoked when the request body has already been read and/or processed. In the latter case, the function performs no operation.