Mongoose6.11官方手册原版

https://cesanta.com/docs/overview/intro.html

搬运自官网-方便搜索

 

源码下载地址:https://github.com/cesanta/mongoose 

 

OverView

Introduction

Mongoose is a networking library written inC. It is a swiss army knife for embedded network programming. It implementsevent-driven non-blocking APIs for TCP, UDP, HTTP, WebSocket, CoAP, MQTT forclient and server mode. Features include:

Cross-platform: works on Linux/UNIX, MacOS, QNX, eCos, Windows, Android, iPhone, FreeRTOS Native support for PicoTCP embedded TCP/IP stack, LWIP embedded TCP/IP stack Works on a variety of embedded boards: TI CC3200, TI MSP430, STM32, ESP8266; on all Linux-based boards like Raspberry PI, BeagleBone, etc Single-threaded, asynchronous, non-blocking core with simple event-based API Built-in protocols: plain TCP, plain UDP, SSL/TLS (one-way or two-way), client and server HTTP client and server WebSocket client and server MQTT client and server CoAP client and server DNS client and server asynchronous DNS resolver Tiny static and run-time footprint Source code is both ISO C and ISO C++ compliant Very easy to integrate: just copy mongoose.c and mongoose.h files to your build tree

Design Concept

Mongoose has three basic data structures:

struct mg_mgr is an event manager that holds all active connections struct mg_connection describes a connection struct mbuf describes data buffer (received or sent data)

Connections could be either listening,outboundor inbound.Outbound connections are created by the mg_connect() call. Listening connections are created bythe mg_bind() call. Inbound connections are those acceptedby a listening connection. Each connection is described by the struct mg_connection structure, which has a number of fieldslike socket, event handler function, send/receive buffer, flags, etc.

An application that uses mongoose shouldfollow a standard pattern of event-driven application:

1.     declare andinitialise event manager:

struct mg_mgr mgr;
 mg_mgr_init(&mgr, NULL);

2.     Createconnections. For example, a server application should create listeningconnections:

struct mg_connection *c = mg_bind(&mgr, "80", ev_handler_function);
mg_set_protocol_http_websocket(c);

3.     create an eventloop by calling mg_mgr_poll() in a loop:

for (;;) {
mg_mgr_poll(&mgr, 1000);
}

mg_mgr_poll() iterates over all sockets, accepts newconnections, sends and receives data, closes connections and calls eventhandler functions for the respective events. For the full example, see Usage Example which implements TCP echo server.

Memory buffers

Each connection has a send and receivebuffer, struct mg_connection::send_mbuf and structmg_connection::recv_mbufrespectively. When data arrives, Mongoose appends received data to the recv_mbuf and triggers an MG_EV_RECVevent. The user may send data back bycalling one of the output functions, like mg_send() or mg_printf(). Output functions append data to the send_mbuf. When Mongoose successfully writes data tothe socket, it discards data from struct mg_connection::send_mbuf and sends an MG_EV_SEND event. When the connection is closed, an MG_EV_CLOSE event is sent.

 

Event handler function

Each connection has an event handlerfunction associated with it. That function must be implemented by the user.Event handler is the key element of the Mongoose application, since it definesthe application's behaviour. This is what an event handler function looks like:

static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
  switch (ev) {
    /* Event handler code that defines behavior of the connection */
    ...
  }
}

struct mg_connection *nc: Connection that has received an event. int ev: Event number, defined in mongoose.h. For example, when data arrives on an inbound connection, ev would be MG_EV_RECVvoid *ev_data: This pointer points to the event-specific data, and it has a different meaning for different events. For example, for an MG_EV_RECV event, ev_data is an int * pointer, pointing to the number of bytes received from the remote peer and saved into the receive IO buffer. The exact meaning of ev_data is described for each event. Protocol-specific events usually have ev_data pointing to structures that hold protocol-specific information.

NOTE: struct mg_connection has void *user_data which is a placeholder forapplication-specific data. Mongoose does not use that pointer. Event handlercan store any kind of information there.

Events

Mongoose accepts incoming connections,reads and writes data and calls specified event handlers for each connectionwhen appropriate. A typical event sequence is this:

For an outbound connection: MG_EV_CONNECT -> (MG_EV_RECVMG_EV_SENDMG_EV_POLL ...) -> MG_EV_CLOSE For an inbound connection: MG_EV_ACCEPT -> (MG_EV_RECVMG_EV_SENDMG_EV_POLL ...) -> MG_EV_CLOSE

Below is a list of core events triggered byMongoose (note that each protocol triggers protocol-specific events in additionto the core ones):

  • MG_EV_ACCEPT: sent when a new server connection isaccepted by a listening connection. void *ev_data is union socket_address of the remote peer.

  • MG_EV_CONNECT: sent when a new outbound connectioncreated by mg_connect() either failed or succeeded. void *ev_data is int *success. If success is 0, then the connection has beenestablished, otherwise it contains an error code. See mg_connect_opt() function for code example.

  • MG_EV_RECV: New data is received and appended to theend of recv_mbufvoid*ev_data is int*num_received_bytes. Typically,event handler should check received data in nc->recv_mbuf, discard processed data by calling mbuf_remove(), set connection flags nc->flags if necessary (see struct

  • mg_connection) and write data the remote peer by outputfunctions like mg_send().

WARNING: Mongoose uses realloc() to expand the receive buffer. It is theuser's responsibility to discard processed data from the beginning of thereceive buffer, note the mbuf_remove() call in the example above.

  • MG_EV_SEND: Mongoose has written data to the remotepeer and discarded written data from the mg_connection::send_mbufvoid*ev_data is int

  • *num_sent_bytes.

NOTE: Mongoose output functions only appenddata to the mg_connection::send_mbuf. They do not do any socket writes. Anactual IO is done by mg_mgr_poll(). An MG_EV_SEND event is just a notification about an IOhas been done.

  • MG_EV_POLL: Sent to all connections on eachinvocation of mg_mgr_poll(). This event could be used to do anyhousekeeping, for example check whether a certain timeout has expired andcloses the connection or send heartbeat message, etc.

  • MG_EV_TIMER: Sent to the connection if mg_set_timer() was called.

Connection flags

Each connection has a flags bit field. Some flags are set by Mongoose,for example if a user creates an outbound UDP connection using a udp://1.2.3.4:5678 address, Mongoose is going to set a MG_F_UDP flag for that connection. Other flags aremeant to be set only by the user event handler to tell Mongoose how to behave.Below is a list of connection flags that are meant to be set by event handlers:

MG_F_FINISHED_SENDING_DATA tells Mongoose that all data has been appended to the send_mbuf. As soon as Mongoose sends it to the socket, the connection will be closed. MG_F_BUFFER_BUT_DONT_SEND tells Mongoose to append data to the send_mbuf but hold on sending it, because the data will be modified later and then will be sent by clearing the MG_F_BUFFER_BUT_DONT_SEND flag. MG_F_CLOSE_IMMEDIATELY tells Mongoose to close the connection immediately, usually after an error. MG_F_USER_1MG_F_USER_2MG_F_USER_3MG_F_USER_4 could be used by a developer to store an application-specific state.

Flags below are set by Mongoose:

MG_F_SSL_HANDSHAKE_DONE SSL only, set when SSL handshake is done. MG_F_CONNECTING set when the connection is in connecting state after mg_connect() call but connect did not finish yet. MG_F_LISTENING set for all listening connections. MG_F_UDP set if the connection is UDP. MG_F_IS_WEBSOCKET set if the connection is a WebSocket connection. MG_F_WEBSOCKET_NO_DEFRAG should be set by a user if the user wants to switch off automatic WebSocket frame defragmentation.

Buildoptions

Mongoose source code ships in a single .cfile that contains functionality for all supported protocols (modules). Modulescan be disabled at compile time which reduces the executable's size. That canbe done by setting preprocessor flags. Also, some preprocessor flags can beused to tune internal Mongoose parameters.

To set a preprocessor flag during compiletime, use the -D  compiler option. For example, to disableboth MQTT and CoAP, compile the application my_app.c like this (assumed UNIX system):

  $ cc my_app.c mongoose.c -D MG_DISABLE_MQTT -D MG_DISABLE_COAP

Enabling flags

MG_ENABLE_SSL Enable SSL/TLS support (OpenSSL API) MG_ENABLE_IPV6 Enable IPv6 support MG_ENABLE_MQTT enable MQTT client(on by default, set to 0 to disable) MG_ENABLE_MQTT_BROKER enable MQTT broker MG_ENABLE_DNS_SERVER enable DNS server MG_ENABLE_COAP enable CoAP protocol MG_ENABLE_HTTP Enable HTTP protocol support (on by default, set to 0 to disable) MG_ENABLE_HTTP_CGI Enable CGI support MG_ENABLE_HTTP_SSI Enable Server Side Includes support MG_ENABLE_HTTP_SSI_EXEC Enable SSI exec operator MG_ENABLE_HTTP_WEBDAV enable WebDAV extensions to HTTP MG_ENABLE_HTTP_WEBSOCKET enable WebSocket extension to HTTP (on by default, =0 to disable) MG_ENABLE_BROADCAST enable mg_broadcast() API MG_ENABLE_GETADDRINFO enablegetaddrinfo() in mg_resolve2() MG_ENABLE_THREADS enable mg_start_thread() API

Disabling flags

MG_DISABLE_HTTP_DIGEST_AUTH disable HTTP Digest (MD5) authorisation support CS_DISABLE_SHA1 disable SHA1 support (used by WebSocket) CS_DISABLE_MD5 disable MD5 support (used by HTTP auth) MG_DISABLE_HTTP_KEEP_ALIVE useful for embedded systems to save resources

Platform specific

Mongoose tries to detect the targetplatform whenever possible, but in some cases you have to explicitly declaresome peculiarities of your target, such as:

MG_CC3200: enable workarounds for the TI CC3200 target. MG_ESP8266: enable workarounds for the ESP8266 target, add RTOS_SDK to specify the RTOS SDK flavour.

Tunables

MG_MALLOCMG_CALLOCMG_REALLOCMG_FREE allow you to a use custom memory allocator, e.g. -DMG_MALLOC=my_malloc MG_USE_READ_WRITE when set replaces calls to recv with read and send with write, thus enabling to add any kind of file descriptor (files, serial devices) to an event manager. MG_SSL_CRYPTO_MODERNMG_SSL_CRYPTO_OLD - choose either "Modern" or "Old" ciphers instead of the default "Intermediate" setting. See this article for details. MG_USER_FILE_FUNCTIONS allow you to use custom file operation, by defining you own mg_statmg_fopenmg_openmg_fread and mg_fwrite functions

Example - TCP echo server

Copy mongoose.c and mongoose.h to your build tree Write code that uses the Mongoose API, e.g. in my_app.c Compile application: $ cc my_app.c mongoose.c

#include "mongoose.h"  // Include Mongoose API definitions
 
// Define an event handler function
static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
  struct mbuf *io = &nc->recv_mbuf;
 
  switch (ev) {
    case MG_EV_RECV:
      // This event handler implements simple TCP echo server
      mg_send(nc, io->buf, io->len);  // Echo received data back
      mbuf_remove(io, io->len);      // Discard data from recv buffer
      break;
    default:
      break;
  }
}
 
int main(void) {
  struct mg_mgr mgr;
 
  mg_mgr_init(&mgr, NULL);  // Initialize event manager object
 
  // Note that many connections can be added to a single event manager
  // Connections can be created at any point, e.g. in event handler function
  mg_bind(&mgr, "1234", ev_handler);  // Create listening connection and add it to the event manager
 
  for (;;) {  // Start infinite event loop
    mg_mgr_poll(&mgr, 1000);
  }
 
  mg_mgr_free(&mgr);
  return 0;
}

HTTP

HTTP server example

To create an HTTP server, follow thispattern:

Create a listening connection by calling mg_bind() or mg_bind_opt() Call mg_set_protocol_http_websocket() for that listening connection. That attaches a built-in HTTP event handler which parses incoming data and triggers HTTP-specific events. For example, when an HTTP request is fully buffered, a built-in HTTP handler parses the request and calls user-defined event handler with MG_EV_HTTP_REQUEST event and parsed HTTP request as an event data. Create event handler function. Note that event handler receives all events - low level TCP events like MG_EV_RECV and high-level HTTP events like MG_EV_HTTP_REQUEST. Normally, an event handler function should only handle MG_EV_HTTP_REQUEST event.

Here's an example of the simplest HTTPserver. Error checking is omitted for the sake of clarity:

#include "mongoose.h"
 
static const char *s_http_port = "8000";
 
static void ev_handler(struct mg_connection *c, int ev, void *p) {
  if (ev == MG_EV_HTTP_REQUEST) {
    struct http_message *hm = (struct http_message *) p;
 
    // We have received an HTTP request. Parsed request is contained in `hm`.
    // Send HTTP reply to the client which shows full original request.
    mg_send_head(c, 200, hm->message.len, "Content-Type: text/plain");
    mg_printf(c, "%.*s", (int)hm->message.len, hm->message.p);
  }
}
 
int main(void) {
  struct mg_mgr mgr;
  struct mg_connection *c;
 
  mg_mgr_init(&mgr, NULL);
  c = mg_bind(&mgr, s_http_port, ev_handler);
  mg_set_protocol_http_websocket(c);
 
  for (;;) {
    mg_mgr_poll(&mgr, 1000);
  }
  mg_mgr_free(&mgr);
 
  return 0;
}
C

See full HTTP server example.

HTTP client example

To create an HTTP client, follow thispattern:

Create an outbound connection by calling mg_connect_http() Create an event handler function that handles MG_EV_HTTP_REPLY event

Here's an example of the simplest HTTPclient. Error checking is omitted for the sake of clarity:

#include "mongoose.h"
 
static const char *url = "http://www.google.com";
static int exit_flag = 0;
 
static void ev_handler(struct mg_connection *c, int ev, void *p) {
  if (ev == MG_EV_HTTP_REPLY) {
    struct http_message *hm = (struct http_message *)p;
    c->flags |= MG_F_CLOSE_IMMEDIATELY;
    fwrite(hm->message.p, 1, (int)hm->message.len, stdout);
    putchar('\n');
    exit_flag = 1;
  } else if (ev == MG_EV_CLOSE) {
    exit_flag = 1;
  };
}
 
int main(void) {
  struct mg_mgr mgr;
 
  mg_mgr_init(&mgr, NULL);
  mg_connect_http(&mgr, ev_handler, url, NULL, NULL);
 
 
  while (exit_flag == 0) {
    mg_mgr_poll(&mgr, 1000);
  }
  mg_mgr_free(&mgr);
 
  return 0;
}
C

See full source code at HTTP client example.

HTTP events

As discussed inthe overview, mg_set_protocol_http_websocket() function parses incoming data, treats it as HTTP or WebSocket, andtriggers high-level HTTP or WebSocket events. Here is a list of events specificto HTTP.

MG_EV_HTTP_REQUEST: An HTTP request has arrived. Parsed request is passed as struct http_message through the handler's void *ev_data pointer. MG_EV_HTTP_REPLY: An HTTP reply has arrived. Parsed reply is passed as struct http_message through the handler's void *ev_data pointer. MG_EV_HTTP_MULTIPART_REQUEST: A multipart POST request has arrived. This event is sent before body is parsed. After this, the user should expect a sequence of MG_EV_HTTP_PART_BEGIN/DATA/END requests. This is also the last time when headers and other request fields are accessible. MG_EV_HTTP_CHUNK: An HTTP chunked-encoding chunk has arrived. The parsed HTTP reply is passed as struct http_message through the handler's void *ev_data pointer. http_message::body would contain incomplete, reassembled HTTP body. It will grow with every new chunk that arrives, and it can potentially consume a lot of memory. The event handler may process the body as chunks are coming, and signal Mongoose to delete processed body by setting MG_F_DELETE_CHUNK in mg_connection::flags. When the last zero chunk is received, Mongoose sends MG_EV_HTTP_REPLY event with full reassembled body (if handler did not signal to delete chunks) or with empty body (if handler did signal to delete chunks). MG_EV_HTTP_PART_BEGIN: a new part of multipart message is started, extra parameters are passed in mg_http_multipart_part MG_EV_HTTP_PART_DATA: a new portion of data from the multiparted message no additional headers are available, only data and data size MG_EV_HTTP_PART_END: a final boundary received, analogue to maybe used to find the end of packet Note: Mongoose should be compiled with MG_ENABLE_HTTP_STREAMING_MULTIPART to enable multipart events.

Serving files

API function mg_serve_http() makes it easy to serve files from afilesystem. Generally speaking, that function is an implementation of the HTTPserver that serves static files, CGI and SSI. It's behavior is driven by a listof options that are consolidated into the struct mg_serve_http_opts structure. See struct mg_serve_http_opts definition for the full list ofcapabilities of mg_serve_http().

For example, in order to create a webserver that serves static files from the current directory, implement eventhandler function as follows:

static void ev_handler(struct mg_connection *c, int ev, void *ev_data) {
  if (ev == MG_EV_HTTP_REQUEST) {
    struct mg_serve_http_opts opts;
 
    memset(&opts, 0, sizeof(opts);  // Reset all options to defaults
    opts.document_root = ".";       // Serve files from the current directory
 
    mg_serve_http(c, (struct http_message *) ev_data, s_http_server_opts);
  }
}
C

See working example at simplest web server.

Sometimes there is no need to implement afull static web server, for example if one works on a RESTful server. Ifcertain endpoints must return the contents of a static file, a simpler mg_http_serve_file() function can be used:

  static void ev_handler(struct mg_connection *c, int ev, void *ev_data) {
   switch (ev) {
     case MG_EV_HTTP_REQUEST: {
       struct http_message *hm = (struct http_message *) ev_data;
       mg_http_serve_file(c, hm, "file.txt",
                          mg_mk_str("text/plain"), mg_mk_str(""));
       break;
     }
     ...
   }
  }

CGI

CGI is a simple mechanism to generate dynamic content. In order to use CGI,call mg_serve_http() function and use .cgi file extension for the CGI files. To bemore precise, all files that match cgi_file_pattern setting in the struct mg_serve_http_opts are treated as CGI. If cgi_file_pattern is NULL, **.cgi$|**.php$ is used.

If Mongoose recognises a file as CGI, itexecutes it, and sends the output back to the client. Therefore, CGI file mustbe executable. Mongoose honours the shebang line - see http://en.wikipedia.org/wiki/Shebang_(Unix).

For example, if both PHP and Perl CGIs areused, then #!/path/to/php-cgi.exe and #!/path/to/perl.exe must be the first lines of the respectiveCGI scripts.

It is possible to hardcode the path to theCGI interpreter for all CGI scripts and disregard the shebang line. To do that,set the cgi_interpreter setting in the struct mg_serve_http_opts.

NOTE: PHP scripts must use php-cgi.exe as CGI interpreter, not php.exe. Example:

  opts.cgi_interpreter = "C:\\ruby\\ruby.exe";

NOTE: In the CGI handler we don't useexplicitly a system call waitpid() for reaping zombie processes. Instead, weset the SIGCHLD handler to SIG_IGN. It will cause zombie processes to be reapedautomatically. CAUTION: not all OSes (e.g. QNX) reap zombies if SIGCHLD isignored.

SSI

Server Side Includes (SSI) is a simpleinterpreted server-side scripting language which is most commonly used toinclude the contents of a file into a web page. It can be useful when it isdesirable to include a common piece of code throughout a website, for example,headers and footers.

In order to use SSI, call mg_serve_http() function and use .shtml file extension for the SSI files. To bemore precise, all files that match ssi_pattern setting in the struct mg_serve_http_opts are treated as SSI. If ssi_pattern is NULL, **.shtml$|**.shtm$ is used.

Unknown SSI directives are silently ignoredby Mongoose. Currently, the following SSI directives are supported:

 - inject the content of some other file  - runs a command and inject the output  - triggers MG_EV_SSI_CALL event

Note that  directivesupports three path specifications:

 Path is relative to web server root  Path is absolute or relative to the web server working dir  Path is relative to current document

The include directive may be used toinclude the contents of a file or the result of running a CGI script.

The exec directive is used to execute acommand on a server, and show command's output. Example: 

The call directive is a way to invoke a Chandler from the HTML page. On each occurrence of  directive,Mongoose calls a registered event handler with MG_EV_SSI_CALL event. Event parameter will point to the PARAMS string. An event handler can output anytext, for example by calling mg_printf(). This is a flexible way of generating aweb page on server side by calling a C event handler. Example:

  

In the event handler:

   case MG_EV_SSI_CALL: {
     const char *param = (const char *) ev_data;
     if (strcmp(param, "foo") == 0) {
       mg_printf(c, "hello from foo");
     } else if (strcmp(param, "bar") == 0) {
       mg_printf(c, "hello from bar");
     }
     break;
   }

Handling file uploads

In order to handle file uploads, use thefollowing HTML snippet:

  
  
HTML

Uploaded files will be sent to the /upload endpoint via the POST request. HTTP body will containmultipart-encoded buffer with the file contents.

To save the uploaded file, use this codesnippet:

struct mg_str cb(struct mg_connection *c, struct mg_str file_name) {
  // Return the same filename. Do not actually do this except in test!
  // fname is user-controlled and needs to be sanitized.
  return file_name;
}
 
void ev_handler(struct mg_connection *c, int ev, void *ev_data) {
  switch (ev) {
    ...
    case MG_EV_HTTP_PART_BEGIN:
    case MG_EV_HTTP_PART_DATA:
    case MG_EV_HTTP_PART_END:
      mg_file_upload_handler(c, ev, ev_data, cb);
      break;
  }
}

Enabling SSL (HTTPS)

To enable SSL on the server side, pleasefollow these steps:

Obtain SSL certificate file and private key file Declare struct mg_bind_opts, initialize ssl_cert and ssl_key Use mg_bind_opt() to create listening socket

Example:

int main(void) {
  struct mg_mgr mgr;
  struct mg_connection *c;
  struct mg_bind_opts bind_opts;
 
  mg_mgr_init(&mgr, NULL);
 
  memset(&bind_opts, 0, sizeof(bind_opts));
  bind_opts.ssl_cert = "server.pem";
  bind_opts.ssl_key = "key.pem";
 
  // Use bind_opts to specify SSL certificate & key file
  c = mg_bind_opt(&mgr, "443", ev_handler, bind_opts);
  mg_set_protocol_http_websocket(c);
 
  ...
}

For the full example, please see the Simplest HTTPS server example.

Digest Authentication

Mongoose has a built-in Digest (MD5)authentication support. In order to enable Digest authentication, create a file.htpasswd in the directory you would like toprotect. That file should be in the format that Apache's htdigest utility.

You can use either Apache htdigest utility, or Mongoose pre-build binary at https://www.cesanta.com/binary.html to add new users into that file:

mongoose -A /path/to/.htdigest mydomain.com joe joes_password

#include "http.h"

=== Common API reference

struct http_message {
  struct mg_str message; /* Whole message: request line + headers + body */
  struct mg_str body;    /* Message body. 0-length for requests with no body */
 
  /* HTTP Request line (or HTTP response line) */
  struct mg_str method; /* "GET" */
  struct mg_str uri;    /* "/my_file.html" */
  struct mg_str proto;  /* "HTTP/1.1" -- for both request and response */
 
  /* For responses, code and response status message are set */
  int resp_code;
  struct mg_str resp_status_msg;
 
  /*
   * Query-string part of the URI. For example, for HTTP request
   *    GET /foo/bar?param1=val1¶m2=val2
   *    |    uri    |     query_string     |
   *
   * Note that question mark character doesn't belong neither to the uri,
   * nor to the query_string
   */
  struct mg_str query_string;
 
  /* Headers */
  struct mg_str header_names[MG_MAX_HTTP_HEADERS];
  struct mg_str header_values[MG_MAX_HTTP_HEADERS];
};

HTTP message

struct websocket_message {
  unsigned char *data;
  size_t size;
  unsigned char flags;
};

WebSocket message

struct mg_http_multipart_part {
  const char *file_name;
  const char *var_name;
  struct mg_str data;
  int status; /* <0 on error */
  void *user_data;
};

HTTP multipart part

struct mg_ssi_call_ctx {
  struct http_message *req; /* The request being processed. */
  struct mg_str file;       /* Filesystem path of the file being processed. */
  struct mg_str arg; /* The argument passed to the tag: . */
};

SSI call context

void mg_set_protocol_http_websocket(struct mg_connection *nc);

Attaches a built-in HTTP event handler tothe given connection. The user-defined event handler will receive followingextra events:

MG_EV_HTTP_REQUEST: HTTP request has arrived. Parsed HTTP request is passed as struct http_message through the handler'svoid ev_data pointer. MG_EV_HTTP_REPLY: The HTTP reply has arrived. The parsed HTTP reply is passed as struct http_message through the handler's void ev_data pointer. MG_EV_HTTP_CHUNK: The HTTP chunked-encoding chunk has arrived. The parsed HTTP reply is passed as struct http_message through the handler's void ev_data pointer. http_message::body would contain incomplete, reassembled HTTP body. It will grow with every new chunk that arrives, and it can potentially consume a lot of memory. An event handler may process the body as chunks are coming, and signal Mongoose to delete processed body by setting MG_F_DELETE_CHUNK in mg_connection::flags. When the last zero chunk is received, Mongoose sends MG_EV_HTTP_REPLYevent with full reassembled body (if handler did not signal to delete chunks) or with empty body (if handler did signal to delete chunks). MG_EV_WEBSOCKET_HANDSHAKE_REQUEST: server has received the WebSocket handshake request. ev_data contains parsed HTTP request. MG_EV_WEBSOCKET_HANDSHAKE_DONE: server has completed the WebSocket handshake. ev_data is NULL. MG_EV_WEBSOCKET_FRAME: new WebSocket frame has arrived. ev_data is struct websocket_message

When compiled withMG_ENABLE_HTTP_STREAMING_MULTIPART, Mongoose parses multipart requests andsplits them into separate events:

MG_EV_HTTP_MULTIPART_REQUEST: Start of the request. This event is sent before body is parsed. After this, the user should expect a sequence of PART_BEGIN/DATA/END requests. This is also the last time when headers and other request fields are accessible. MG_EV_HTTP_PART_BEGIN: Start of a part of a multipart message. Argument: mg_http_multipart_part with var_name and file_name set (if present). No data is passed in this message. MG_EV_HTTP_PART_DATA: new portion of data from the multipart message. Argument: mg_http_multipart_part. var_name and file_name are preserved, data is available in mg_http_multipart_part.data. MG_EV_HTTP_PART_END: End of the current part. var_name, file_name are the same, no data in the message. If status is 0, then the part is properly terminated with a boundary, status < 0 means that connection was terminated. MG_EV_HTTP_MULTIPART_REQUEST_END: End of the multipart request. Argument: mg_http_multipart_part, var_name and file_name are NULL, status = 0 means request was properly closed, < 0 means connection was terminated (note: in this case both PART_END and REQUEST_END are delivered).

void mg_send_websocket_handshake(struct mg_connection *nc, const char *uri,
                                 const char *extra_headers);

Send websocket handshake to the server.

nc must be a valid connection, connected to aserver. uri is an URI to fetch, extra_headersis extra HTTP headers tosend orNULL`.

This function is intended to be used bywebsocket client.

Note that the Host header is mandatory inHTTP/1.1 and must be included in extra_headersmg_send_websocket_handshake2 offers a better API for that.

Deprecated in favour of mg_send_websocket_handshake2

void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path,
                                  const char *host, const char *protocol,
                                  const char *extra_headers);

Send websocket handshake to the server.

nc must be a valid connection, connected to aserver. uri is an URI to fetch, host goes into the Host header, protocol goes into the Sec-WebSocket-Proto header (NULL to omit), extra_headersis extraHTTP

headers to send orNULL`.

This function is intended to be used bywebsocket client.

void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path,
                                  const char *host, const char *protocol,
                                  const char *extra_headers, const char *user,
                                  const char *pass);

Like mg_send_websocket_handshake2 but alsopasses basic auth header

void mg_send_websocket_handshake3v(struct mg_connection *nc,
                                   const struct mg_str path,
                                   const struct mg_str host,
                                   const struct mg_str protocol,
                                   const struct mg_str extra_headers,
                                   const struct mg_str user,
                                   const struct mg_str pass);

Same as mg_send_websocket_handshake3 butwith strings not necessarily NUL-temrinated

struct mg_connection *mg_connect_ws(struct mg_mgr *mgr,
                                    MG_CB(mg_event_handler_t event_handler,
                                          void *user_data),
                                    const char *url, const char *protocol,
                                    const char *extra_headers);

Helper function that creates an outboundWebSocket connection.

url is a URL to connect to. It must beproperly URL-encoded, e.g. have no spaces, etc. By default, mg_connect_ws() sends Connection and Host headers. extra_headers is an extra HTTP header to send, e.g. "User-Agent:my-app\r\n". If protocol is not NULL, then a Sec-WebSocket-Protocol header is sent.

Examples:

  nc1 = mg_connect_ws(mgr, ev_handler_1, "ws://echo.websocket.org", NULL,
                      NULL);
  nc2 = mg_connect_ws(mgr, ev_handler_1, "wss://echo.websocket.org", NULL,
                      NULL);
  nc3 = mg_connect_ws(mgr, ev_handler_1, "ws://api.cesanta.com",
                      "clubby.cesanta.com", NULL);
struct mg_connection *mg_connect_ws_opt(
    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
    struct mg_connect_opts opts, const char *url, const char *protocol,
    const char *extra_headers);

Helper function that creates an outboundWebSocket connection

Mostly identical to mg_connect_ws, but allows to provide extra parameters(for example, SSL parameters)

void mg_send_websocket_frame(struct mg_connection *nc, int op_and_flags,
                             const void *data, size_t data_len);

Send WebSocket frame to the remote end.

op_and_flags specifies the frame's type. It's one of:

WEBSOCKET_OP_CONTINUE WEBSOCKET_OP_TEXT WEBSOCKET_OP_BINARY WEBSOCKET_OP_CLOSE WEBSOCKET_OP_PING WEBSOCKET_OP_PONG

Orred with one of the flags:

WEBSOCKET_DONT_FIN: Don't set the FIN flag on the frame to be sent.

data and data_len contain frame data.

void mg_send_websocket_framev(struct mg_connection *nc, int op_and_flags,
                              const struct mg_str *strings, int num_strings);

Sends multiple websocket frames.

Like mg_send_websocket_frame(), but composes a frame from multiplebuffers.

void mg_printf_websocket_frame(struct mg_connection *nc, int op_and_flags,
                               const char *fmt, ...);

Sends WebSocket frame to the remote end.

Like mg_send_websocket_frame(), but allows to create formatted messageswith printf()-like semantics.

int mg_url_decode(const char *src, int src_len, char *dst, int dst_len,
                  int is_form_url_encoded);

Decodes a URL-encoded string.

Source string is specified by (srcsrc_len), and destination is (dstdst_len). If is_form_url_encoded is non-zero, then + character is decoded as a blank spacecharacter. This function guarantees to NUL-terminate the destination. Ifdestination is too small, then the source string is partially decoded and -1 is returned. Otherwise, a length of thedecoded string is returned, not counting final NUL.

extern void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[],
                          const size_t *msg_lens, uint8_t *digest);
extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
                           const size_t *msg_lens, uint8_t *digest);

 

#include "http_server.h"

int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req);

Parses a HTTP message.

is_req should be set to 1 if parsing a request, 0if reply.

Returns the number of bytes parsed. If HTTPmessage is incomplete 0 is returned. On parse error, a negative number is returned.

struct mg_str *mg_get_http_header(struct http_message *hm, const char *name);

Searches and returns the header name in parsed HTTP message hm. If header is not found, NULL is returned.Example:

struct mg_str *host_hdr = mg_get_http_header(hm, "Host");
int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf,
                         size_t buf_size);

Parses the HTTP header hdr. Finds variable var_name and stores its value in the buffer bufbuf_size. Returns 0 if variable not found, non-zerootherwise.

This function is supposed to parse cookies,authentication headers, etc. Example (error handling omitted):

char user[20];
struct mg_str *hdr = mg_get_http_header(hm, "Authorization");
mg_http_parse_header(hdr, "username", user, sizeof(user));

Returns the length of the variable's value.If buffer is not large enough, or variable not found, 0 is returned.

int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len, char *pass, size_t pass_len);

Gets and parses the Authorization: Basicheader Returns -1 if no Authorization header is found, or ifmg_parse_http_basic_auth fails parsing the resulting header.

int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len,
                             char *pass, size_t pass_len);

Parses the Authorization: Basic headerReturns -1 iif the authorization type is not "Basic" or any othererror such as incorrectly encoded base64 user password pair.

size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name,
                          size_t var_name_len, char *file_name,
                          size_t file_name_len, const char **chunk,
                          size_t *chunk_len);

Parses the buffer bufbuf_len that contains multipart form data chunks.Stores the chunk name in a var_name,var_name_len buffer. If a chunk is an uploaded file,then file_namefile_name_len is filled with an uploaded file name. chunkchunk_len points to the chunk data.

Return: number of bytes to skip to the nextchunk or 0 if there are no more chunks.

Usage example:

   static void ev_handler(struct mg_connection nc, int ev, void ev_data) {
     switch(ev) {
       case MG_EV_HTTP_REQUEST: {
         struct http_message hm = (struct http_message ) ev_data;
         char var_name[100], file_name[100];
         const char chunk;
         size_t chunk_len, n1, n2;
 
         n1 = n2 = 0;
         while ((n2 = mg_parse_multipart(hm->body.p + n1,
                                         hm->body.len - n1,
                                         var_name, sizeof(var_name),
                                         file_name, sizeof(file_name),
                                         &chunk, &chunk_len)) > 0) {
           printf("var: %s, file_name: %s, size: %d, chunk: [%.s]\n",
                  var_name, file_name, (int) chunk_len,
                  (int) chunk_len, chunk);
           n1 += n2;
         }
       }
       break;
int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst,
                    size_t dst_len);

Fetches a HTTP form variable.

Fetches a variable name from a buf into a buffer specified by dstdst_len. The destination is alwayszero-terminated. Returns the length of a fetched variable. If not found, 0 isreturned. buf must be valid url-encoded buffer. If destination is too small or an erroroccured, negative number is returned.

struct mg_serve_http_opts {
  /* Path to web root directory */
  const char *document_root;
 
  /* List of index files. Default is "" */
  const char *index_files;
 
  /*
   * Leave as NULL to disable authentication.
   * To enable directory protection with authentication, set this to ".htpasswd"
   * Then, creating ".htpasswd" file in any directory automatically protects
   * it with digest authentication.
   * Use `mongoose` web server binary, or `htdigest` Apache utility to
   * create/manipulate passwords file.
   * Make sure `auth_domain` is set to a valid domain name.
   */
  const char *per_directory_auth_file;
 
  /* Authorization domain (domain name of this web server) */
  const char *auth_domain;
 
  /*
   * Leave as NULL to disable authentication.
   * Normally, only selected directories in the document root are protected.
   * If absolutely every access to the web server needs to be authenticated,
   * regardless of the URI, set this option to the path to the passwords file.
   * Format of that file is the same as ".htpasswd" file. Make sure that file
   * is located outside document root to prevent people fetching it.
   */
  const char *global_auth_file;
 
  /* Set to "no" to disable directory listing. Enabled by default. */
  const char *enable_directory_listing;
 
  /*
   * SSI files pattern. If not set, "**.shtml$|**.shtmDOC_CONTENTquot; is used.
   *
   * All files that match ssi_pattern are treated as SSI.
   *
   * Server Side Includes (SSI) is a simple interpreted server-side scripting
   * language which is most commonly used to include the contents of a file
   * into a web page. It can be useful when it is desirable to include a common
   * piece of code throughout a website, for example, headers and footers.
   *
   * In order for a webpage to recognize an SSI-enabled HTML file, the
   * filename should end with a special extension, by default the extension
   * should be either .shtml or .shtm
   *
   * Unknown SSI directives are silently ignored by Mongoose. Currently,
   * the following SSI directives are supported:
   *    <!--#include FILE_TO_INCLUDE -->
   *    <!--#exec "COMMAND_TO_EXECUTE" -->
   *    <!--#call COMMAND -->
   *
   * Note that <!--#include ...> directive supports three path
   *specifications:
   *
   * <!--#include virtual="path" -->  Path is relative to web server root
   * <!--#include abspath="path" -->  Path is absolute or relative to the
   *                                  web server working dir
   * <!--#include file="path" -->,    Path is relative to current document
   * <!--#include "path" -->
   *
   * The include directive may be used to include the contents of a file or
   * the result of running a CGI script.
   *
   * The exec directive is used to execute
   * a command on a server, and show command's output. Example:
   *
   * <!--#exec "ls -l" -->
   *
   * The call directive is a way to invoke a C handler from the HTML page.
   * On each occurence of <!--#call COMMAND OPTIONAL_PARAMS> directive,
   * Mongoose calls a registered event handler with MG_EV_SSI_CALL event,
   * and event parameter will point to the COMMAND OPTIONAL_PARAMS string.
   * An event handler can output any text, for example by calling
   * `mg_printf()`. This is a flexible way of generating a web page on
   * server side by calling a C event handler. Example:
   *
   * <!--#call foo --> ... <!--#call bar -->
   *
   * In the event handler:
   *    case MG_EV_SSI_CALL: {
   *      const char *param = (const char *) ev_data;
   *      if (strcmp(param, "foo") == 0) {
   *        mg_printf(c, "hello from foo");

This structure defines how mg_serve_http() works. Best practice is to set onlyrequired settings, and leave the rest as NULL.

void mg_serve_http(struct mg_connection *nc, struct http_message *hm,
                   struct mg_serve_http_opts opts);

Serves given HTTP request according to the options.

Example code snippet:

static void ev_handler(struct mg_connection nc, int ev, void ev_data) {
  struct http_message hm = (struct http_message ) ev_data;
  struct mg_serve_http_opts opts = { .document_root = "/var/www" };  // C99
 
  switch (ev) {
    case MG_EV_HTTP_REQUEST:
      mg_serve_http(nc, hm, opts);
      break;
    default:
      break;
  }
}
void mg_http_serve_file(struct mg_connection *nc, struct http_message *hm,
                        const char *path, const struct mg_str mime_type,
                        const struct mg_str extra_headers);

Serves a specific file with a given MIMEtype and optional extra headers.

Example code snippet:

static void ev_handler(struct mg_connection nc, int ev, void ev_data) {
  switch (ev) {
    case MG_EV_HTTP_REQUEST: {
      struct http_message hm = (struct http_message ) ev_data;
      mg_http_serve_file(nc, hm, "file.txt",
                         mg_mk_str("text/plain"), mg_mk_str(""));
      break;
    }
    ...
  }
}
typedef struct mg_str (*mg_fu_fname_fn)(struct mg_connection *nc,
                                        struct mg_str fname);

Callback prototype for mg_file_upload_handler().

void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data,
                            mg_fu_fname_fn local_name_fn
                                MG_UD_ARG(void *user_data));

File upload handler. This handler can beused to implement file uploads with minimum code. This handler will processMG_EV_HTTPPART events and store file data into a local file. local_name_fn will be invoked with whatever name wasprovided by the client and will expect the name of the local file to open. Areturn value of NULL will abort file upload (client will get a "403Forbidden" response). If non-null, the returned string must beheap-allocated and will be freed by the caller. Exception: it is ok to returnthe same string verbatim.

Example:

struct mg_str upload_fname(struct mg_connection nc, struct mg_str fname) {
  // Just return the same filename. Do not actually do this except in test!
  // fname is user-controlled and needs to be sanitized.
  return fname;
}
void ev_handler(struct mg_connection nc, int ev, void ev_data) {
  switch (ev) {
    ...
    case MG_EV_HTTP_PART_BEGIN:
    case MG_EV_HTTP_PART_DATA:
    case MG_EV_HTTP_PART_END:
      mg_file_upload_handler(nc, ev, ev_data, upload_fname);
      break;
  }
}
void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path,
                               MG_CB(mg_event_handler_t handler,
                                     void *user_data));

Registers a callback for a specified httpendpoint Note: if callback is registered it is called instead of the callbackprovided in mg_bind

Example code snippet:

static void handle_hello1(struct mg_connection nc, int ev, void ev_data) {
  (void) ev; (void) ev_data;
  mg_printf(nc, "HTTP/1.0 200 OK\r\n\r\n[I am Hello1]");
 nc->flags |= MG_F_SEND_AND_CLOSE;
}
 
static void handle_hello2(struct mg_connection nc, int ev, void ev_data) {
 (void) ev; (void) ev_data;
  mg_printf(nc, "HTTP/1.0 200 OK\r\n\r\n[I am Hello2]");
 nc->flags |= MG_F_SEND_AND_CLOSE;
}
 
void init() {
  nc = mg_bind(&mgr, local_addr, cb1);
  mg_register_http_endpoint(nc, "/hello1", handle_hello1);
  mg_register_http_endpoint(nc, "/hello1/hello2", handle_hello2);
}
 
struct mg_http_endpoint_opts {
  void *user_data;
  /* Authorization domain (realm) */
  const char *auth_domain;
  const char *auth_file;
};
void mg_register_http_endpoint_opt(struct mg_connection *nc,
                                   const char *uri_path,
                                   mg_event_handler_t handler,
                                   struct mg_http_endpoint_opts opts);
int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain, FILE *fp);

Authenticates a HTTP request against anopened password file. Returns 1 if authenticated, 0 otherwise.

int mg_check_digest_auth(struct mg_str method, struct mg_str uri,
                         struct mg_str username, struct mg_str cnonce,
                         struct mg_str response, struct mg_str qop,
                         struct mg_str nc, struct mg_str nonce,
                         struct mg_str auth_domain, FILE *fp);

Authenticates given response params againstan opened password file. Returns 1 if authenticated, 0 otherwise.

It's used by mg_http_check_digest_auth().

void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len);

Sends buffer buf of size len to the client using chunked HTTP encoding.This function sends the buffer size as hex number + newline first, then thebuffer itself, then the newline. For example, mg_send_http_chunk(nc,"foo", 3) will append the3\r\nfoo\r\n string to the nc->send_mbuf output IO buffer.

NOTE: The HTTP header"Transfer-Encoding: chunked" should be sent prior to using thisfunction.

NOTE: do not forget to send an empty chunkat the end of the response, to tell the client that everything was sent.Example:

  mg_printf_http_chunk(nc, "%s", "my response!");
  mg_send_http_chunk(nc, "", 0); // Tell the client we're finished
void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...);

Sends a printf-formatted HTTP chunk.Functionality is similar to mg_send_http_chunk().

void mg_send_response_line(struct mg_connection *nc, int status_code,
                           const char *extra_headers);

Sends the response status line. If extra_headers is not NULL, then extra_headers are also sent after the response line. extra_headers must NOT end end with new line. Example:

 mg_send_response_line(nc, 200, "Access-Control-Allow-Origin: ");

Will result in:

 HTTP/1.1 200 OK\r\n
 Access-Control-Allow-Origin: \r\n
void mg_http_send_error(struct mg_connection *nc, int code, const char *reason);

Sends an error response. If reason is NULL,the message will be inferred from the error code (if supported).

void mg_http_send_redirect(struct mg_connection *nc, int status_code,
                           const struct mg_str location,
                           const struct mg_str extra_headers);

Sends a redirect response. status_code should be either 301 or 302 and location point to the new location. If extra_headers is not empty, then extra_headers are also sent after the response line. extra_headers must NOT end end with new line.

Example:

 mg_http_send_redirect(nc, 302, mg_mk_str("/login"), mg_mk_str(NULL));
void mg_send_head(struct mg_connection *n, int status_code,
                  int64_t content_length, const char *extra_headers);

Sends the response line and headers. Thisfunction sends the response line with the status_code, and automatically sends one header:either "Content-Length" or "Transfer-Encoding". If content_length is negative, then "Transfer-Encoding:chunked" header is sent, otherwise, "Content-Length" header issent.

NOTE: If Transfer-Encoding is chunked, then message body must be sent using mg_send_http_chunk() or mg_printf_http_chunk() functions. Otherwise, mg_send() or mg_printf() must be used. Extra headers could be setthrough extra_headers. Note extra_headers must NOT be terminated by a new line.

void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...);

Sends a printf-formatted HTTP chunk,escaping HTML tags.

void mg_http_reverse_proxy(struct mg_connection *nc,
                           const struct http_message *hm, struct mg_str mount,
                           struct mg_str upstream);

Proxies a given request to a given upstreamhttp server. The path prefix in mount will be stripped of the path requested tothe upstream server, e.g. if mount is /api and upstream is http://localhost:8001/foo then an incoming request to /api/bar willcause a request to http://localhost:8001/foo/bar

EXPERIMENTAL API. Please usehttp_serve_http + url_rewrites if a static mapping is good enough.

 

#include "http_client.h"

struct mg_connection *mg_connect_http(
    struct mg_mgr *mgr,
    MG_CB(mg_event_handler_t event_handler, void *user_data), const char *url,
    const char *extra_headers, const char *post_data);

Helper function that creates an outboundHTTP connection.

url is the URL to fetch. It must be properlyURL-encoded, e.g. have no spaces, etc. By default, mg_connect_http() sends the Connection and Host headers. extra_headers is an extra HTTP header to send, e.g. "User-Agent:my-app\r\n". If post_data is NULL, then a GET request is created.Otherwise, a POST request is created with the specified POST data. Note that ifthe data being posted is a form submission, the Content-Type header should be set accordingly (seeexample below).

Examples:

  nc1 = mg_connect_http(mgr, ev_handler_1, "http://www.google.com", NULL,
                        NULL);
  nc2 = mg_connect_http(mgr, ev_handler_1, "https://github.com", NULL, NULL);
  nc3 = mg_connect_http(
      mgr, ev_handler_1, "my_server:8000/form_submit/",
      "Content-Type: application/x-www-form-urlencoded\r\n",
      "var_1=value_1&var_2=value_2");
struct mg_connection *mg_connect_http_opt(
    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
    struct mg_connect_opts opts, const char *url, const char *extra_headers,
    const char *post_data);

Helper function that creates an outboundHTTP connection.

Mostly identical to mg_connect_http, butallows you to provide extra parameters (for example, SSL parameters)

int mg_http_create_digest_auth_header(char *buf, size_t buf_len,
                                      const char *method, const char *uri,
                                      const char *auth_domain, const char *user,
                                      const char *passwd);

Creates digest authenticationheader for a client request.

MQTT

#include "mqtt.h"

=== MQTT API reference

struct mg_mqtt_message {
  int cmd;
  int qos;
  int len; /* message length in the IO buffer */
  struct mg_str topic;
  struct mg_str payload;
 
  uint8_t connack_ret_code; /* connack */
  uint16_t message_id;      /* puback */
 
  /* connect */
  uint8_t protocol_version;
  uint8_t connect_flags;
  uint16_t keep_alive_timer;
  struct mg_str protocol_name;
  struct mg_str client_id;
  struct mg_str will_topic;
  struct mg_str will_message;
  struct mg_str user_name;
  struct mg_str password;
};
 
struct mg_mqtt_topic_expression {
  const char *topic;
  uint8_t qos;
};
 
struct mg_send_mqtt_handshake_opts {
  unsigned char flags; /* connection flags */
  uint16_t keep_alive;
  const char *will_topic;
  const char *will_message;
  const char *user_name;
  const char *password;
};
 
struct mg_mqtt_proto_data {
  uint16_t keep_alive;
  double last_control_time;
};
 

mg_mqtt_proto_data should be in header toallow external access to it

void mg_set_protocol_mqtt(struct mg_connection *nc);

Attaches a built-in MQTT event handler tothe given connection.

The user-defined event handler will receivefollowing extra events:

MG_EV_MQTT_CONNACK MG_EV_MQTT_PUBLISH MG_EV_MQTT_PUBACK MG_EV_MQTT_PUBREC MG_EV_MQTT_PUBREL MG_EV_MQTT_PUBCOMP MG_EV_MQTT_SUBACK

void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id);

Sends an MQTT handshake.

void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id,
                                struct mg_send_mqtt_handshake_opts);

Sends an MQTT handshake with optionalparameters.

void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
                     uint16_t message_id, int flags, const void *data,
                     size_t len);

Publishes a message to a given topic.

void mg_mqtt_subscribe(struct mg_connection *nc,
                       const struct mg_mqtt_topic_expression *topics,
                       size_t topics_len, uint16_t message_id);

Subscribes to a bunch of topics.

void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,
                         size_t topics_len, uint16_t message_id);

Unsubscribes from a bunch of topics.

void mg_mqtt_disconnect(struct mg_connection *nc);

Sends a DISCONNECT command.

void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code);

Sends a CONNACK command with a given return_code.

void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id);

Sends a PUBACK command with a given message_id.

void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id);

Sends a PUBREC command with a given message_id.

void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id);

Sends a PUBREL command with a given message_id.

void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id);

Sends a PUBCOMP command with a given message_id.

void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len,
                    uint16_t message_id);

Sends a SUBACK command with a given message_id and a sequence of granted QoSs.

void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id);

Sends a UNSUBACK command with a given message_id.

void mg_mqtt_ping(struct mg_connection *nc);

Sends a PINGREQ command.

void mg_mqtt_pong(struct mg_connection *nc);

Sends a PINGRESP command.

int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg,
                                 struct mg_str *topic, uint8_t *qos, int pos);

Extracts the next topic expression from aSUBSCRIBE command payload.

The topic expression name will point to astring in the payload buffer. Returns the pos of the next topic expression or-1 when the list of topics is exhausted.

int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic);

Matches a topic against a topic expression

Returns 1 if it matches; 0 otherwise.

int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic);

Same as mg_mqtt_match_topic_expression(), but takes exp as a NULL-terminated string.

DNS

DNSserver example

To create a DNS server, follow thispattern:

Create a listening UDP connection by calling mg_bind() or mg_bind_opt() Call mg_set_protocol_dns() for that listening connection. That attaches a built-in DNS event handler which parses incoming data and triggers DNS-specific events. Create an event handler function.

Here is an example of a simpe DNS server.It is a captive DNS server, meaning that it replies with the same IP address onall queries, regardless of what exactly host name is being resolved. Errorchecking is omitted for the sake of clarity:

#include "mongoose.h"
#include 
 
static const char *s_listening_addr = "udp://:5353";
 
static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
  struct mg_dns_message *msg;
  struct mg_dns_resource_record *rr;
  struct mg_dns_reply reply;
  int i;
 
  switch (ev) {
    case MG_DNS_MESSAGE: {
      struct mbuf reply_buf;
      mbuf_init(&reply_buf, 512);
      msg = (struct mg_dns_message *) ev_data;
      reply = mg_dns_create_reply(&reply_buf, msg);
 
      for (i = 0; i < msg->num_questions; i++) {
        char rname[256];
        rr = &msg->questions[i];
        mg_dns_uncompress_name(msg, &rr->name, rname, sizeof(rname) - 1);
        fprintf(stdout, "Q type %d name %s\n", rr->rtype, rname);
        if (rr->rtype == MG_DNS_A_RECORD) {
          in_addr_t addr = inet_addr("127.0.0.1");
          mg_dns_reply_record(&reply, rr, NULL, rr->rtype, 10, &addr, 4);
        }
      }
 
      mg_dns_send_reply(nc, &reply);
      nc->flags |= MG_F_SEND_AND_CLOSE;
      mbuf_free(&reply_buf);
      break;
    }
  }
}
 
int main(int argc, char *argv[]) {
  struct mg_mgr mgr;
  struct mg_connection *c;
 
  mg_mgr_init(&mgr, NULL);
  c = mg_bind(&mgr, s_listening_addr, ev_handler);
  mg_set_protocol_dns(c);
 
  for (;;) {
    mg_mgr_poll(&mgr, 1000);
  }
  mg_mgr_free(&mgr);
 
  return 0;
}

See full Captive DNS server example.

DNSclient example

See https://github.com/cesanta/mongoose/blob/master/mongoose.c and search for the mg_resolve_async_eh() function - that is the core of built-inMongoose async DNS resolver.

#include "dns.h"

=== DNS API reference

enum mg_dns_resource_record_kind {
  MG_DNS_INVALID_RECORD = 0,
  MG_DNS_QUESTION,
  MG_DNS_ANSWER
};

High-level DNS message event

struct mg_dns_resource_record {
  struct mg_str name; /* buffer with compressed name */
  int rtype;
  int rclass;
  int ttl;
  enum mg_dns_resource_record_kind kind;
  struct mg_str rdata; /* protocol data (can be a compressed name) */
};

DNS resource record.

struct mg_dns_message {
  struct mg_str pkt; /* packet body */
  uint16_t flags;
  uint16_t transaction_id;
  int num_questions;
  int num_answers;
  struct mg_dns_resource_record questions[MG_MAX_DNS_QUESTIONS];
  struct mg_dns_resource_record answers[MG_MAX_DNS_ANSWERS];
};

DNS message (request and response).

struct mg_dns_resource_record *mg_dns_next_record(
    struct mg_dns_message *msg, int query, struct mg_dns_resource_record *prev);
int mg_dns_parse_record_data(struct mg_dns_message *msg,
                             struct mg_dns_resource_record *rr, void *data,
                             size_t data_len);

Parses the record data from a DNS resourcerecord.

A: struct in_addr ina AAAA: struct in6_addr ina CNAME: char buffer

Returns -1 on error.

TODO(mkm): MX

void mg_send_dns_query(struct mg_connection *nc, const char *name,
                       int query_type);

Sends a DNS query to the remote end.

int mg_dns_insert_header(struct mbuf *io, size_t pos,
                         struct mg_dns_message *msg);

Inserts a DNS header to an IO buffer.

Returns the number of bytes inserted.

int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg);

Appends already encoded questions from anexisting message.

This is useful when generating a DNS replymessage which includes all question records.

Returns the number of appended bytes.

int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr,
                         const char *name, size_t nlen, const void *rdata,
                         size_t rlen);

Encodes and appends a DNS resource recordto an IO buffer.

The record metadata is taken from the rr parameter, while the name and data are takenfrom the parameters, encoded in the appropriate format depending on record typeand stored in the IO buffer. The encoded values might contain offsets withinthe IO buffer. It's thus important that the IO buffer doesn't get trimmed whilea sequence of records are encoded while preparing a DNS reply.

This function doesn't update the name and rdata pointers in the rr struct because they might be invalidatedas soon as the IO buffer grows again.

Returns the number of bytes appended or -1in case of error.

int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len);

Encodes a DNS name.

int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg);

Low-level: parses a DNS response.

size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name,
                              char *dst, int dst_len);

Uncompresses a DNS compressed name.

The containing DNS message is requiredbecause of the compressed encoding and reference suffixes present elsewhere inthe packet.

If the name is less than dst_len characters long, the remainder of dst is terminated with \0 characters. Otherwise, dst is not terminated.

If dst_len is 0 dst can be NULL. Returns the uncompressed namelength.

void mg_set_protocol_dns(struct mg_connection *nc);

Attaches a built-in DNS event handler tothe given listening connection.

The DNS event handler parses the incomingUDP packets, treating them as DNS requests. If an incoming packet getssuccessfully parsed by the DNS event handler, a user event handler will receivean MG_DNS_REQUEST event, with ev_data pointing to the parsed struct mg_dns_message.

See captive_dns_server example on how to handle DNS request andsend DNS reply.

#include "dns_server.h"

=== DNS server API reference

Disabled by default; enable with -DMG_ENABLE_DNS_SERVER.

struct mg_dns_reply {
  struct mg_dns_message *msg;
  struct mbuf *io;
  size_t start;
};
struct mg_dns_reply mg_dns_create_reply(struct mbuf *io,
                                        struct mg_dns_message *msg);

Creates a DNS reply.

The reply will be based on an existingquery message msg. The query body will be appended to the output buffer. "reply +recursion allowed" will be added to the message flags and the message'snum_answers will be set to 0.

Answer records can be appended with mg_dns_send_reply or by lower level function defined in theDNS API.

In order to send a reply use mg_dns_send_reply. It's possible to use a connection's sendbuffer as reply buffer, and it will work for both UDP and TCP connections.

Example:

reply = mg_dns_create_reply(&nc->send_mbuf, msg);
for (i = 0; i < msg->num_questions; i++) {
  rr = &msg->questions[i];
  if (rr->rtype == MG_DNS_A_RECORD) {
    mg_dns_reply_record(&reply, rr, 3600, &dummy_ip_addr, 4);
  }
}
mg_dns_send_reply(nc, &reply);
int mg_dns_reply_record(struct mg_dns_reply *reply,
                        struct mg_dns_resource_record *question,
                        const char *name, int rtype, int ttl, const void *rdata,
                        size_t rdata_len);

Appends a DNS reply record to the IO bufferand to the DNS message.

The message's num_answers field will beincremented. It's the caller's duty to ensure num_answers is properlyinitialised.

Returns -1 on error.

void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r);

Sends a DNS reply through a connection.

The DNS data is stored in an IO bufferpointed by reply structure in r. This function mutates the content of thatbuffer in order to ensure that the DNS header reflects the size and flags ofthe message, that might have been updated either with mg_dns_reply_record or by direct manipulation of r->message.

Once sent, the IO buffer will be trimmedunless the reply IO buffer is the connection's send buffer and the connectionis not in UDP mode.

#include "resolv.h"

=== API reference

enum mg_resolve_err {
  MG_RESOLVE_OK = 0,
  MG_RESOLVE_NO_ANSWERS = 1,
  MG_RESOLVE_EXCEEDED_RETRY_COUNT = 2,
  MG_RESOLVE_TIMEOUT = 3
};
typedef void (*mg_resolve_callback_t)(struct mg_dns_message *dns_message,
                                      void *user_data, enum mg_resolve_err);
struct mg_resolve_async_opts {
  const char *nameserver;
  int max_retries;    /* defaults to 2 if zero */
  int timeout;        /* in seconds; defaults to 5 if zero */
  int accept_literal; /* pseudo-resolve literal ipv4 and ipv6 addrs */
  int only_literal;   /* only resolves literal addrs; sync cb invocation */
  struct mg_connection **dns_conn; /* return DNS connection */
};

Options for mg_resolve_async_opt.

int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query,
                     mg_resolve_callback_t cb, void *data);

See mg_resolve_async_opt()

void mg_set_nameserver(struct mg_mgr *mgr, const char *nameserver);

Set default DNS server

int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query,
                         mg_resolve_callback_t cb, void *data,
                         struct mg_resolve_async_opts opts);

Resolved a DNS name asynchronously.

Upon successful resolution, the usercallback will be invoked with the full DNS response message and a pointer tothe user's context data.

In case of timeout while performing theresolution the callback will receive a NULL msg.

The DNS answers can be extracted with mg_next_record and mg_dns_parse_record_data:

[source,c]

struct in_addr ina; structmg_dns_resource_record *rr = mg_next_record(msg, MG_DNS_A_RECORD, NULL);

mg_dns_parse_record_data(msg, rr, &ina, sizeof(ina));
int mg_resolve_from_hosts_file(const char *host, union socket_address *usa);

Resolve a name from /etc/hosts.

Returns 0 on success, -1 on failure.

COAP

title:CoAP server example

To create a CoAP server, follow thispattern:

Create a listening connection by calling mg_bind() or mg_bind_opt()   Call mg_set_protocol_coap() for that listening connection. Create an event handler function that handles the following events: MG_EV_COAP_CON MG_EV_COAP_NOC MG_EV_COAP_ACK MG_EV_COAP_RST

Here's an example of the simplest CoAPserver. Error checking is omitted for the sake of clarity:

#include "mongoose.h"
 
static char *s_default_address = "udp://:5683";
 
static void coap_handler(struct mg_connection *nc, int ev, void *p) {
  switch (ev) {
    case MG_EV_COAP_CON: {
      uint32_t res;
      struct mg_coap_message *cm = (struct mg_coap_message *) p;
      printf("CON with msg_id = %d received\n", cm->msg_id);
      res = mg_coap_send_ack(nc, cm->msg_id);
      if (res == 0) {
        printf("Successfully sent ACK for message with msg_id = %d\n",
               cm->msg_id);
      } else {
        printf("Error: %d\n", res);
      }
      break;
    }
    case MG_EV_COAP_NOC:
    case MG_EV_COAP_ACK:
    case MG_EV_COAP_RST: {
      struct mg_coap_message *cm = (struct mg_coap_message *) p;
      printf("ACK/RST/NOC with msg_id = %d received\n", cm->msg_id);
      break;
    }
  }
}
 
int main(void) {
  struct mg_mgr mgr;
  struct mg_connection *nc;
 
  mg_mgr_init(&mgr, 0);
 
  nc = mg_bind(&mgr, s_default_address, coap_handler);
  mg_set_protocol_coap(nc);
 
  while (1) {
    mg_mgr_poll(&mgr, 1000);
  }
 
  mg_mgr_free(&mgr);
  return 0;
}

See full source code at CoAP server example.

title:CoAP client example

To create a CoAP client, follow thispattern:

Create an outbound connection by calling mg_connect Call mg_set_protocol_coap for created connection Create an event handler function that handles the following events: MG_EV_COAP_CON MG_EV_COAP_NOC MG_EV_COAP_ACK MG_EV_COAP_RST

Here's an example of the simplest CoAPclient. Error checking is omitted for the sake of clarity:

#include "mongoose.h"
 
static int s_time_to_exit = 0;
static char *s_default_address = "udp://coap.me:5683";
 
static void coap_handler(struct mg_connection *nc, int ev, void *p) {
  switch (ev) {
    case MG_EV_CONNECT: {
      struct mg_coap_message cm;
 
      memset(&cm, 0, sizeof(cm));
      cm.msg_id = 1;
      cm.msg_type = MG_COAP_MSG_CON;
      mg_coap_send_message(nc, &cm);
      break;
    }
    case MG_EV_COAP_ACK:
    case MG_EV_COAP_RST: {
      struct mg_coap_message *cm = (struct mg_coap_message *) p;
      printf("ACK/RST for message with msg_id = %d received\n", cm->msg_id);
      s_time_to_exit = 1;
      break;
    }
    case MG_EV_CLOSE: {
      if (s_time_to_exit == 0) {
        printf("Server closed connection\n");
        s_time_to_exit = 1;
      }
      break;
    }
  }
}
 
int main(int argc, char *argv[]) {
  struct mg_mgr mgr;
  struct mg_connection *nc;
 
  mg_mgr_init(&mgr, 0);
 
  nc = mg_connect(&mgr, s_default_address, coap_handler);
 
  mg_set_protocol_coap(nc);
 
  while (!s_time_to_exit) {
    mg_mgr_poll(&mgr, 1000000);
  }
 
  mg_mgr_free(&mgr);
 
  return 0;
}

See full source code at CoAP client example.

#include "coap.h"

=== CoAP API reference

CoAP message format:

+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
|Ver| T | TKL | Code | Message ID | Token (if any, TKL bytes) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
| Options (if any) ...            |1 1 1 1 1 1 1 1| Payload (if any) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
struct mg_coap_option {
  struct mg_coap_option *next;
  uint32_t number;
  struct mg_str value;
};

CoAP options. Use mg_coap_add_option andmg_coap_free_options for creation and destruction.

struct mg_coap_message {
  uint32_t flags;
  uint8_t msg_type;
  uint8_t code_class;
  uint8_t code_detail;
  uint16_t msg_id;
  struct mg_str token;
  struct mg_coap_option *options;
  struct mg_str payload;
  struct mg_coap_option *optiomg_tail;
};

CoAP message. See RFC 7252 for details.

int mg_set_protocol_coap(struct mg_connection *nc);

Sets CoAP protocol handler - triggers CoAPspecific events.

struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm,
                                          uint32_t number, char *value,
                                          size_t len);

Adds a new option to mg_coap_messagestructure. Returns pointer to the newly created option. Note: options must befreed by using mg_coap_free_options

void mg_coap_free_options(struct mg_coap_message *cm);

Frees the memory allocated for options. Ifthe cm parameter doesn't contain any option it does nothing.

uint32_t mg_coap_send_message(struct mg_connection *nc,
                              struct mg_coap_message *cm);

Composes a CoAP message from mg_coap_message and sends it into nc connection. Returns 0 on success. Onerror, it is a bitmask:

#define MG_COAP_ERROR 0x10000 #define MG_COAP_FORMAT_ERROR (MG_COAP_ERROR | 0x20000) #define MG_COAP_IGNORE (MG_COAP_ERROR | 0x40000) #define MG_COAP_NOT_ENOUGH_DATA (MG_COAP_ERROR | 0x80000) #define MG_COAP_NETWORK_ERROR (MG_COAP_ERROR | 0x100000)

uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id);

Composes CoAP acknowledgement from mg_coap_message and sends it into nc connection. Return value: see mg_coap_send_message()

uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm);

Parses CoAP message and fillsmg_coap_message and returns cm->flags. This is a helper function.

NOTE: usually CoAP works over UDP, so lackof data means format error. But, in theory, it is possible to use CoAP over TCP(according to RFC)

The caller has to check results and treat COAP_NOT_ENOUGH_DATAaccording to underlying protocol:

in case of UDP COAP_NOT_ENOUGH_DATA means COAP_FORMAT_ERROR, in case of TCP client can try to receive more data

Return value: see mg_coap_send_message()

uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io);

Composes CoAP message from mg_coap_messagestructure. This is a helper function. Return value: see mg_coap_send_message()

你可能感兴趣的:(Mongoose)