source: rtems/cpukit/include/mghttpd/mongoose.h @ d13a624

5
Last change on this file since d13a624 was d13a624, checked in by Chris Johns <chrisj@…>, on 04/10/18 at 05:30:23

cpukit/mttpd: Add a callback to generate a per file HTTP etag

Close #3323.

  • Property mode set to 100644
File size: 15.4 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  // Called when mongoose needs to generate an HTTP etag.
129  // Implementing this callback allows a custom etag to be generated. If
130  // not implemented the standard etag generator is used which is the
131  // modification time as a hex value and the file size.
132  // Use this callback if the modification time cannot be controlled.
133  // Parameters:
134  //   path: path to the file being requested
135  //   etag: buffer to write the etag into
136  //   etag_len: the length of the etag buffer
137  // Return value:
138  int  (*http_etag)(const struct mg_connection *,
139                    const char *path, char *etag, size_t etag_len);
140};
141
142// Start web server.
143//
144// Parameters:
145//   callbacks: mg_callbacks structure with user-defined callbacks.
146//   options: NULL terminated list of option_name, option_value pairs that
147//            specify Mongoose configuration parameters.
148//
149// Side-effects: on UNIX, ignores SIGCHLD and SIGPIPE signals. If custom
150//    processing is required for these, signal handlers must be set up
151//    after calling mg_start().
152//
153//
154// Example:
155//   const char *options[] = {
156//     "document_root", "/var/www",
157//     "listening_ports", "80,443s",
158//     NULL
159//   };
160//   struct mg_context *ctx = mg_start(&my_func, NULL, options);
161//
162// Refer to https://github.com/valenok/mongoose/blob/master/UserManual.md
163// for the list of valid option and their possible values.
164//
165// Return:
166//   web server context, or NULL on error.
167struct mg_context *mg_start(const struct mg_callbacks *callbacks,
168                            void *user_data,
169                            const char **configuration_options);
170
171
172// Stop the web server.
173//
174// Must be called last, when an application wants to stop the web server and
175// release all associated resources. This function blocks until all Mongoose
176// threads are stopped. Context pointer becomes invalid.
177void mg_stop(struct mg_context *);
178
179
180// Get the value of particular configuration parameter.
181// The value returned is read-only. Mongoose does not allow changing
182// configuration at run time.
183// If given parameter name is not valid, NULL is returned. For valid
184// names, return value is guaranteed to be non-NULL. If parameter is not
185// set, zero-length string is returned.
186const char *mg_get_option(const struct mg_context *ctx, const char *name);
187
188
189// Return array of strings that represent valid configuration options.
190// For each option, option name and default value is returned, i.e. the
191// number of entries in the array equals to number_of_options x 2.
192// Array is NULL terminated.
193const char **mg_get_valid_option_names(void);
194
195
196// Add, edit or delete the entry in the passwords file.
197//
198// This function allows an application to manipulate .htpasswd files on the
199// fly by adding, deleting and changing user records. This is one of the
200// several ways of implementing authentication on the server side. For another,
201// cookie-based way please refer to the examples/chat.c in the source tree.
202//
203// If password is not NULL, entry is added (or modified if already exists).
204// If password is NULL, entry is deleted.
205//
206// Return:
207//   1 on success, 0 on error.
208int mg_modify_passwords_file(const char *passwords_file_name,
209                             const char *domain,
210                             const char *user,
211                             const char *password);
212
213
214// Return information associated with the request.
215struct mg_request_info *mg_get_request_info(struct mg_connection *);
216
217
218// Send data to the client.
219// Return:
220//  0   when the connection has been closed
221//  -1  on error
222//  >0  number of bytes written on success
223int mg_write(struct mg_connection *, const void *buf, size_t len);
224
225
226// Send data to a websocket client wrapped in a websocket frame.
227// It is unsafe to read/write to this connection from another thread.
228// This function is available when mongoose is compiled with -DUSE_WEBSOCKET
229//
230// Return:
231//  0   when the connection has been closed
232//  -1  on error
233//  >0  number of bytes written on success
234int mg_websocket_write(struct mg_connection* conn, int opcode,
235                       const char *data, size_t data_len);
236
237// Opcodes, from http://tools.ietf.org/html/rfc6455
238enum {
239  WEBSOCKET_OPCODE_CONTINUATION = 0x0,
240  WEBSOCKET_OPCODE_TEXT = 0x1,
241  WEBSOCKET_OPCODE_BINARY = 0x2,
242  WEBSOCKET_OPCODE_CONNECTION_CLOSE = 0x8,
243  WEBSOCKET_OPCODE_PING = 0x9,
244  WEBSOCKET_OPCODE_PONG = 0xa
245};
246
247
248// Macros for enabling compiler-specific checks for printf-like arguments.
249#undef PRINTF_FORMAT_STRING
250#if defined(_MSC_VER) && _MSC_VER >= 1400
251#include <sal.h>
252#if defined(_MSC_VER) && _MSC_VER > 1400
253#define PRINTF_FORMAT_STRING(s) _Printf_format_string_ s
254#else
255#define PRINTF_FORMAT_STRING(s) __format_string s
256#endif
257#else
258#define PRINTF_FORMAT_STRING(s) s
259#endif
260
261#ifdef __GNUC__
262#define PRINTF_ARGS(x, y) __attribute__((format(printf, x, y)))
263#else
264#define PRINTF_ARGS(x, y)
265#endif
266
267// Send data to the client using printf() semantics.
268//
269// Works exactly like mg_write(), but allows to do message formatting.
270int mg_printf(struct mg_connection *,
271              PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3);
272#ifdef __rtems__
273struct rtems_printer;
274void rtems_print_printer_mg_printf(struct rtems_printer *, struct mg_connection *);
275#endif /* __rtems__ */
276
277
278// Send contents of the entire file together with HTTP headers.
279void mg_send_file(struct mg_connection *conn, const char *path);
280
281
282// Read data from the remote end, return number of bytes read.
283// Return:
284//   0     connection has been closed by peer. No more data could be read.
285//   < 0   read error. No more data could be read from the connection.
286//   > 0   number of bytes read into the buffer.
287int mg_read(struct mg_connection *, void *buf, size_t len);
288
289
290// Get the value of particular HTTP header.
291//
292// This is a helper function. It traverses request_info->http_headers array,
293// and if the header is present in the array, returns its value. If it is
294// not present, NULL is returned.
295const char *mg_get_header(const struct mg_connection *, const char *name);
296
297
298// Get a value of particular form variable.
299//
300// Parameters:
301//   data: pointer to form-uri-encoded buffer. This could be either POST data,
302//         or request_info.query_string.
303//   data_len: length of the encoded data.
304//   var_name: variable name to decode from the buffer
305//   dst: destination buffer for the decoded variable
306//   dst_len: length of the destination buffer
307//
308// Return:
309//   On success, length of the decoded variable.
310//   On error:
311//      -1 (variable not found).
312//      -2 (destination buffer is NULL, zero length or too small to hold the
313//          decoded variable).
314//
315// Destination buffer is guaranteed to be '\0' - terminated if it is not
316// NULL or zero length.
317int mg_get_var(const char *data, size_t data_len,
318               const char *var_name, char *dst, size_t dst_len);
319
320// Fetch value of certain cookie variable into the destination buffer.
321//
322// Destination buffer is guaranteed to be '\0' - terminated. In case of
323// failure, dst[0] == '\0'. Note that RFC allows many occurrences of the same
324// parameter. This function returns only first occurrence.
325//
326// Return:
327//   On success, value length.
328//   On error:
329//      -1 (either "Cookie:" header is not present at all or the requested
330//          parameter is not found).
331//      -2 (destination buffer is NULL, zero length or too small to hold the
332//          value).
333int mg_get_cookie(const char *cookie, const char *var_name,
334                  char *buf, size_t buf_len);
335
336
337// Download data from the remote web server.
338//   host: host name to connect to, e.g. "foo.com", or "10.12.40.1".
339//   port: port number, e.g. 80.
340//   use_ssl: wether to use SSL connection.
341//   error_buffer, error_buffer_size: error message placeholder.
342//   request_fmt,...: HTTP request.
343// Return:
344//   On success, valid pointer to the new connection, suitable for mg_read().
345//   On error, NULL. error_buffer contains error message.
346// Example:
347//   char ebuf[100];
348//   struct mg_connection *conn;
349//   conn = mg_download("google.com", 80, 0, ebuf, sizeof(ebuf),
350//                      "%s", "GET / HTTP/1.0\r\nHost: google.com\r\n\r\n");
351struct mg_connection *mg_download(const char *host, int port, int use_ssl,
352                                  char *error_buffer, size_t error_buffer_size,
353                                  PRINTF_FORMAT_STRING(const char *request_fmt),
354                                  ...) PRINTF_ARGS(6, 7);
355
356
357// Close the connection opened by mg_download().
358void mg_close_connection(struct mg_connection *conn);
359
360
361// File upload functionality. Each uploaded file gets saved into a temporary
362// file and MG_UPLOAD event is sent.
363// Return number of uploaded files.
364int mg_upload(struct mg_connection *conn, const char *destination_dir);
365
366
367// Convenience function -- create detached thread.
368// Return: 0 on success, non-0 on error.
369typedef void * (*mg_thread_func_t)(void *);
370int mg_start_thread(mg_thread_func_t f, void *p);
371
372
373// Return builtin mime type for the given file name.
374// For unrecognized extensions, "text/plain" is returned.
375const char *mg_get_builtin_mime_type(const char *file_name);
376
377
378// Return Mongoose version.
379const char *mg_version(void);
380
381// URL-decode input buffer into destination buffer.
382// 0-terminate the destination buffer.
383// form-url-encoded data differs from URI encoding in a way that it
384// uses '+' as character for space, see RFC 1866 section 8.2.1
385// http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
386// Return: length of the decoded data, or -1 if dst buffer is too small.
387int mg_url_decode(const char *src, int src_len, char *dst,
388                  int dst_len, int is_form_url_encoded);
389
390// MD5 hash given strings.
391// Buffer 'buf' must be 33 bytes long. Varargs is a NULL terminated list of
392// ASCIIz strings. When function returns, buf will contain human-readable
393// MD5 hash. Example:
394//   char buf[33];
395//   mg_md5(buf, "aa", "bb", NULL);
396char *mg_md5(char buf[33], ...);
397
398
399#ifdef __cplusplus
400}
401#endif // __cplusplus
402
403#endif // MONGOOSE_HEADER_INCLUDED
Note: See TracBrowser for help on using the repository browser.