source: rtems-libbsd/rtemsbsd/mghttpd/mongoose.h @ 4f75a78

4.1155-freebsd-126-freebsd-12freebsd-9.3
Last change on this file since 4f75a78 was 4f75a78, checked in by Sebastian Huber <sebastian.huber@…>, on 04/07/15 at 13:31:27

mghttpd: Import from RTEMS

  • Property mode set to 100644
File size: 14.6 KB
Line 
1// Copyright (c) 2004-2012 Sergey Lyubka
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19// THE SOFTWARE.
20
21#ifndef MONGOOSE_HEADER_INCLUDED
22#define  MONGOOSE_HEADER_INCLUDED
23
24#include <stdio.h>
25#include <stddef.h>
26
27#ifdef __cplusplus
28extern "C" {
29#endif // __cplusplus
30
31struct mg_context;     // Handle for the HTTP service itself
32struct mg_connection;  // Handle for the individual connection
33
34
35// This structure contains information about the HTTP request.
36struct mg_request_info {
37  const char *request_method; // "GET", "POST", etc
38  const char *uri;            // URL-decoded URI
39  const char *http_version;   // E.g. "1.0", "1.1"
40  const char *query_string;   // URL part after '?', not including '?', or NULL
41  const char *remote_user;    // Authenticated user, or NULL if no auth used
42  long remote_ip;             // Client's IP address
43  int remote_port;            // Client's port
44  int is_ssl;                 // 1 if SSL-ed, 0 if not
45  void *user_data;            // User data pointer passed to mg_start()
46  void *conn_data;            // Connection-specific user data
47
48  int num_headers;            // Number of HTTP headers
49  struct mg_header {
50    const char *name;         // HTTP header name
51    const char *value;        // HTTP header value
52  } http_headers[64];         // Maximum 64 headers
53};
54
55
56// This structure needs to be passed to mg_start(), to let mongoose know
57// which callbacks to invoke. For detailed description, see
58// https://github.com/valenok/mongoose/blob/master/UserManual.md
59struct mg_callbacks {
60  // Called when mongoose has received new HTTP request.
61  // If callback returns non-zero,
62  // callback must process the request by sending valid HTTP headers and body,
63  // and mongoose will not do any further processing.
64  // If callback returns 0, mongoose processes the request itself. In this case,
65  // callback must not send any data to the client.
66  int  (*begin_request)(struct mg_connection *);
67
68  // Called when mongoose has finished processing request.
69  void (*end_request)(const struct mg_connection *, int reply_status_code);
70
71  // Called when mongoose is about to log a message. If callback returns
72  // non-zero, mongoose does not log anything.
73  int  (*log_message)(const struct mg_connection *, const char *message);
74
75  // Called when mongoose initializes SSL library.
76  int  (*init_ssl)(void *ssl_context, void *user_data);
77
78  // Called when websocket request is received, before websocket handshake.
79  // If callback returns 0, mongoose proceeds with handshake, otherwise
80  // cinnection is closed immediately.
81  int (*websocket_connect)(const struct mg_connection *);
82
83  // Called when websocket handshake is successfully completed, and
84  // connection is ready for data exchange.
85  void (*websocket_ready)(struct mg_connection *);
86
87  // Called when data frame has been received from the client.
88  // Parameters:
89  //    bits: first byte of the websocket frame, see websocket RFC at
90  //          http://tools.ietf.org/html/rfc6455, section 5.2
91  //    data, data_len: payload, with mask (if any) already applied.
92  // Return value:
93  //    non-0: keep this websocket connection opened.
94  //    0:     close this websocket connection.
95  int  (*websocket_data)(struct mg_connection *, int bits,
96                         char *data, size_t data_len);
97
98  // Called when mongoose tries to open a file. Used to intercept file open
99  // calls, and serve file data from memory instead.
100  // Parameters:
101  //    path:     Full path to the file to open.
102  //    data_len: Placeholder for the file size, if file is served from memory.
103  // Return value:
104  //    NULL: do not serve file from memory, proceed with normal file open.
105  //    non-NULL: pointer to the file contents in memory. data_len must be
106  //              initilized with the size of the memory block.
107  const char * (*open_file)(const struct mg_connection *,
108                             const char *path, size_t *data_len);
109
110  // Called when mongoose is about to serve Lua server page (.lp file), if
111  // Lua support is enabled.
112  // Parameters:
113  //   lua_context: "lua_State *" pointer.
114  void (*init_lua)(struct mg_connection *, void *lua_context);
115
116  // Called when mongoose has uploaded a file to a temporary directory as a
117  // result of mg_upload() call.
118  // Parameters:
119  //    file_file: full path name to the uploaded file.
120  void (*upload)(struct mg_connection *, const char *file_name);
121
122  // Called when mongoose is about to send HTTP error to the client.
123  // Implementing this callback allows to create custom error pages.
124  // Parameters:
125  //   status: HTTP error status code.
126  int  (*http_error)(struct mg_connection *, int status);
127};
128
129// Start web server.
130//
131// Parameters:
132//   callbacks: mg_callbacks structure with user-defined callbacks.
133//   options: NULL terminated list of option_name, option_value pairs that
134//            specify Mongoose configuration parameters.
135//
136// Side-effects: on UNIX, ignores SIGCHLD and SIGPIPE signals. If custom
137//    processing is required for these, signal handlers must be set up
138//    after calling mg_start().
139//
140//
141// Example:
142//   const char *options[] = {
143//     "document_root", "/var/www",
144//     "listening_ports", "80,443s",
145//     NULL
146//   };
147//   struct mg_context *ctx = mg_start(&my_func, NULL, options);
148//
149// Refer to https://github.com/valenok/mongoose/blob/master/UserManual.md
150// for the list of valid option and their possible values.
151//
152// Return:
153//   web server context, or NULL on error.
154struct mg_context *mg_start(const struct mg_callbacks *callbacks,
155                            void *user_data,
156                            const char **configuration_options);
157
158
159// Stop the web server.
160//
161// Must be called last, when an application wants to stop the web server and
162// release all associated resources. This function blocks until all Mongoose
163// threads are stopped. Context pointer becomes invalid.
164void mg_stop(struct mg_context *);
165
166
167// Get the value of particular configuration parameter.
168// The value returned is read-only. Mongoose does not allow changing
169// configuration at run time.
170// If given parameter name is not valid, NULL is returned. For valid
171// names, return value is guaranteed to be non-NULL. If parameter is not
172// set, zero-length string is returned.
173const char *mg_get_option(const struct mg_context *ctx, const char *name);
174
175
176// Return array of strings that represent valid configuration options.
177// For each option, option name and default value is returned, i.e. the
178// number of entries in the array equals to number_of_options x 2.
179// Array is NULL terminated.
180const char **mg_get_valid_option_names(void);
181
182
183// Add, edit or delete the entry in the passwords file.
184//
185// This function allows an application to manipulate .htpasswd files on the
186// fly by adding, deleting and changing user records. This is one of the
187// several ways of implementing authentication on the server side. For another,
188// cookie-based way please refer to the examples/chat.c in the source tree.
189//
190// If password is not NULL, entry is added (or modified if already exists).
191// If password is NULL, entry is deleted.
192//
193// Return:
194//   1 on success, 0 on error.
195int mg_modify_passwords_file(const char *passwords_file_name,
196                             const char *domain,
197                             const char *user,
198                             const char *password);
199
200
201// Return information associated with the request.
202struct mg_request_info *mg_get_request_info(struct mg_connection *);
203
204
205// Send data to the client.
206// Return:
207//  0   when the connection has been closed
208//  -1  on error
209//  >0  number of bytes written on success
210int mg_write(struct mg_connection *, const void *buf, size_t len);
211
212
213// Send data to a websocket client wrapped in a websocket frame.
214// It is unsafe to read/write to this connection from another thread.
215// This function is available when mongoose is compiled with -DUSE_WEBSOCKET
216//
217// Return:
218//  0   when the connection has been closed
219//  -1  on error
220//  >0  number of bytes written on success
221int mg_websocket_write(struct mg_connection* conn, int opcode,
222                       const char *data, size_t data_len);
223
224// Opcodes, from http://tools.ietf.org/html/rfc6455
225enum {
226  WEBSOCKET_OPCODE_CONTINUATION = 0x0,
227  WEBSOCKET_OPCODE_TEXT = 0x1,
228  WEBSOCKET_OPCODE_BINARY = 0x2,
229  WEBSOCKET_OPCODE_CONNECTION_CLOSE = 0x8,
230  WEBSOCKET_OPCODE_PING = 0x9,
231  WEBSOCKET_OPCODE_PONG = 0xa
232};
233
234
235// Macros for enabling compiler-specific checks for printf-like arguments.
236#undef PRINTF_FORMAT_STRING
237#if defined(_MSC_VER) && _MSC_VER >= 1400
238#include <sal.h>
239#if defined(_MSC_VER) && _MSC_VER > 1400
240#define PRINTF_FORMAT_STRING(s) _Printf_format_string_ s
241#else
242#define PRINTF_FORMAT_STRING(s) __format_string s
243#endif
244#else
245#define PRINTF_FORMAT_STRING(s) s
246#endif
247
248#ifdef __GNUC__
249#define PRINTF_ARGS(x, y) __attribute__((format(printf, x, y)))
250#else
251#define PRINTF_ARGS(x, y)
252#endif
253
254// Send data to the client using printf() semantics.
255//
256// Works exactly like mg_write(), but allows to do message formatting.
257int mg_printf(struct mg_connection *,
258              PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3);
259
260
261// Send contents of the entire file together with HTTP headers.
262void mg_send_file(struct mg_connection *conn, const char *path);
263
264
265// Read data from the remote end, return number of bytes read.
266// Return:
267//   0     connection has been closed by peer. No more data could be read.
268//   < 0   read error. No more data could be read from the connection.
269//   > 0   number of bytes read into the buffer.
270int mg_read(struct mg_connection *, void *buf, size_t len);
271
272
273// Get the value of particular HTTP header.
274//
275// This is a helper function. It traverses request_info->http_headers array,
276// and if the header is present in the array, returns its value. If it is
277// not present, NULL is returned.
278const char *mg_get_header(const struct mg_connection *, const char *name);
279
280
281// Get a value of particular form variable.
282//
283// Parameters:
284//   data: pointer to form-uri-encoded buffer. This could be either POST data,
285//         or request_info.query_string.
286//   data_len: length of the encoded data.
287//   var_name: variable name to decode from the buffer
288//   dst: destination buffer for the decoded variable
289//   dst_len: length of the destination buffer
290//
291// Return:
292//   On success, length of the decoded variable.
293//   On error:
294//      -1 (variable not found).
295//      -2 (destination buffer is NULL, zero length or too small to hold the
296//          decoded variable).
297//
298// Destination buffer is guaranteed to be '\0' - terminated if it is not
299// NULL or zero length.
300int mg_get_var(const char *data, size_t data_len,
301               const char *var_name, char *dst, size_t dst_len);
302
303// Fetch value of certain cookie variable into the destination buffer.
304//
305// Destination buffer is guaranteed to be '\0' - terminated. In case of
306// failure, dst[0] == '\0'. Note that RFC allows many occurrences of the same
307// parameter. This function returns only first occurrence.
308//
309// Return:
310//   On success, value length.
311//   On error:
312//      -1 (either "Cookie:" header is not present at all or the requested
313//          parameter is not found).
314//      -2 (destination buffer is NULL, zero length or too small to hold the
315//          value).
316int mg_get_cookie(const char *cookie, const char *var_name,
317                  char *buf, size_t buf_len);
318
319
320// Download data from the remote web server.
321//   host: host name to connect to, e.g. "foo.com", or "10.12.40.1".
322//   port: port number, e.g. 80.
323//   use_ssl: wether to use SSL connection.
324//   error_buffer, error_buffer_size: error message placeholder.
325//   request_fmt,...: HTTP request.
326// Return:
327//   On success, valid pointer to the new connection, suitable for mg_read().
328//   On error, NULL. error_buffer contains error message.
329// Example:
330//   char ebuf[100];
331//   struct mg_connection *conn;
332//   conn = mg_download("google.com", 80, 0, ebuf, sizeof(ebuf),
333//                      "%s", "GET / HTTP/1.0\r\nHost: google.com\r\n\r\n");
334struct mg_connection *mg_download(const char *host, int port, int use_ssl,
335                                  char *error_buffer, size_t error_buffer_size,
336                                  PRINTF_FORMAT_STRING(const char *request_fmt),
337                                  ...) PRINTF_ARGS(6, 7);
338
339
340// Close the connection opened by mg_download().
341void mg_close_connection(struct mg_connection *conn);
342
343
344// File upload functionality. Each uploaded file gets saved into a temporary
345// file and MG_UPLOAD event is sent.
346// Return number of uploaded files.
347int mg_upload(struct mg_connection *conn, const char *destination_dir);
348
349
350// Convenience function -- create detached thread.
351// Return: 0 on success, non-0 on error.
352typedef void * (*mg_thread_func_t)(void *);
353int mg_start_thread(mg_thread_func_t f, void *p);
354
355
356// Return builtin mime type for the given file name.
357// For unrecognized extensions, "text/plain" is returned.
358const char *mg_get_builtin_mime_type(const char *file_name);
359
360
361// Return Mongoose version.
362const char *mg_version(void);
363
364// URL-decode input buffer into destination buffer.
365// 0-terminate the destination buffer.
366// form-url-encoded data differs from URI encoding in a way that it
367// uses '+' as character for space, see RFC 1866 section 8.2.1
368// http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
369// Return: length of the decoded data, or -1 if dst buffer is too small.
370int mg_url_decode(const char *src, int src_len, char *dst,
371                  int dst_len, int is_form_url_encoded);
372
373// MD5 hash given strings.
374// Buffer 'buf' must be 33 bytes long. Varargs is a NULL terminated list of
375// ASCIIz strings. When function returns, buf will contain human-readable
376// MD5 hash. Example:
377//   char buf[33];
378//   mg_md5(buf, "aa", "bb", NULL);
379char *mg_md5(char buf[33], ...);
380
381
382#ifdef __cplusplus
383}
384#endif // __cplusplus
385
386#endif // MONGOOSE_HEADER_INCLUDED
Note: See TracBrowser for help on using the repository browser.