Utility

mg_call()

void mg_call(struct mg_connection *c, int ev, void *ev_data);

Send ev event to c event handler. This function is useful then implementing your own protocol.

Parameters:

  • c - Connection to send event
  • ev - Event to send
  • ev_data - Additional event parameter

Return value: None

Usage example:

// In a timer callback, send MG_EV_USER event to all connections
static void timer_fn(void *arg) {
  struct mg_mgr *mgr = (struct mg_mgr *) arg;
  for (struct mg_connection *c = mgr->conns; c != NULL; c = c->next) {
    mg_call(c, MG_EV_USER, "hi!");
  }
}

mg_error()

void mg_error(struct mg_connection *c, const char *fmt, ...);

Send MG_EV_ERROR to connection event handler with error message formatted using printf semantics.

Parameters:

  • c - Connection to send event
  • fmt - Format string in printf semantics

Return value: None

Usage example:

mg_error(c, "Operation failed, error code: %d", errno);

mg_md5_init()

void mg_md5_init(mg_md5_ctx *c);

Initialize context for MD5 hashing.

Parameters:

  • c - Pointer to mg_md5_ctx structure to initialize

Return value: None

Usage example:

mg_md5_ctx ctx;
mg_md5_init(&ctx);

mg_md5_update()

void mg_md5_update(mg_md5_ctx *c, const unsigned char *data, size_t len);

Hash len bytes of data pointed by data using MD5 algorithm.

Parameters:

  • c - MD5 context
  • data - Data to hash
  • len - Data length

Return value: None

Usage example:

mg_md5_ctx ctx;
// Context initialization
// ...

mg_md5_update(&ctx, "data", 4);       // hash "data" string
mg_md5_update(&ctx, "more data", 9);  // hash "more data" string

mg_md5_final()

void mg_md5_final(mg_md5_ctx *c, unsigned char buf[16]);

Get current MD5 hash for context.

Parameters:

  • c - MD5 context
  • buf - Pointer to buffer to write MD5 hash value

Return value: None

Usage example:

mg_md5_ctx ctx;
// Context initialization
// ...

unsigned char buf[16];
mg_md5_final(&ctx, buf);  // `buf` is now MD5 hash

mg_sha1_init()

void mg_sha1_init(mg_sha1_ctx *c);

Initialize context for calculating SHA1 hash

Parameters:

  • c - pointer to mg_sha1_ctx structure to initialize

Return value: none

Usage example:

mg_sha1_ctx ctx;
mg_sha1_init(&ctx);

mg_sha1_update()

void mg_sha1_update(mg_sha1_ctx *c, const unsigned char *data, size_t len);

Hash len bytes of data using SHA1 algorithm.

Parameters:

  • c - SHA1 context
  • data - Data to hash
  • len - Data length

Return value: None

Usage example:

mg_sha1_ctx ctx;
// Context initialization
// ...

mg_sha1_update(&ctx, "data", 4);      // hash "data" string
mg_sha1_update(&ctx, "more data", 9); // hash "more data" string

mg_sha1_final()

void mg_sha1_final(unsigned char digest[20], mg_sha1_ctx *c);

Get current SHA1 hash for context.

Parameters:

  • c - SHA1 context
  • digest - Pointer to buffer to receive hash value

Return value: None

Usage example:

mg_sha1_ctx ctx;
// Context initialization
// ...

unsigned char buf[20];
mg_sha1_final(buf, &ctx); // `buf` is now SHA1 hash

mg_base64_update()

size_t mg_base64_update(unsigned char p, char *buf, size_t len);

Encode p byte to base64 and write result into buf buffer

Parameters:

  • p - Byte to encode
  • buf - Pointer to buffer to write result
  • len - Buffer length

Return value: Number of chars written into buffer

Usage example:

char buf[10];
mg_base64_update((unsigned char)"a", buf, 10); // Encode "a" into base64 and write it to buf

mg_base64_final()

size_t mg_base64_final(char *buf, size_t len);

Add base64 finish mark and \0 symbol to buf

Parameters:

  • buf - Pointer to buffer to write finish mark
  • len - Buffer length

Return value: Number of chars written into buffer

char buf[10];
// ...

mg_base64_final(buf, 10);

mg_base64_encode()

size_t mg_base64_encode(const unsigned char *p, size_t n, char *buf, size_t len);

Encode n bytes data pointed to by p using base64 and write result into buf.

Parameters:

  • p - Pointer to data to encode
  • n - Data length
  • buf - Pointer to buffer to write result
  • len - Buffer length

Return value: Number of chars written into buffer

Usage example:

char buf[128];
mg_base64_encode((uint8_t *) "abcde", 5, buf, 128); // buf is now YWJjZGU=

mg_base64_decode()

size_t mg_base64_decode(const char *src, size_t n, char *dst, size_t len);

Decode n bytes of base64-ed src and write it to dst.

Parameters:

  • src - Data to decode
  • n - Data length
  • dst - Pointer to output buffer
  • len - Buffer length

Return value: Number of chars written into buffer

Usage example:

char buf[128];
mg_base64_decode("Q2VzYW50YQ==", 12, buf, 128); // buf is now "Cesanta"

mg_random()

bool mg_random(void *buf, size_t len);

Fill in buffer buf, len with random data. Note: Mongoose uses this function for TLS and some other routines that require RNG (random number generator). It is possible to override a built-in mg_random() by specifying a MG_ENABLE_CUSTOM_RANDOM=1 build preprocessor constant.

Parameters:

  • buf - Pointer to buffer to receive random data
  • len - Buffer size

Return value: This function returns false when the system rand() has to be used, because a stronger PRNG for the configured MG_ARCH could not be found.

Usage example:

char buf[10];
mg_random(buf, sizeof(buf)); // `buf` is now random bytes

mg_random_str()

char *mg_random_str(char *buf, size_t len);

Fill in buffer buf, len with random alphanumeric characters: a-zA-Z0-9. A buffer is zero-terminated.

Parameters:

  • buf - a pointer to a buffer
  • len - a buffer size

Return value: buf value.

Usage example:

char buf[10];
printf("Random: %s\n", mg_random_str(buf, sizeof(buf)));

mg_ntohs()

uint16_t mg_ntohs(uint16_t net);

Convert uint16_t value to host order.

Parameters:

  • net - 16-bit value in network order

Return value: 16-bit value in host order

Usage example:

uint16_t val = mg_ntohs(0x1234);

mg_ntohl()

uint32_t mg_ntohl(uint32_t net);

Convert uint32_t value to host order.

Parameters:

  • net - 32-bit value in network order

Return value: 32-bit value in host order

Usage example:

uint32_t val = mg_ntohl(0x12345678);

mg_htons()

uint16_t mg_htons(uint16_t h);

Convert uint16_t value to network order.

Parameters:

  • h - 16-bit value in host order

Return value: 16-bit value in network order

Usage example:

uint16_t val = mg_htons(0x1234);

mg_htonl()

uint32_t mg_ntohl(uint32_t h);

Convert uint32_t value to network order.

Parameters:

  • h - 32-bit value in host order

Return value: 32-bit value in network order

Usage example:

uint32_t val = mg_htonl(0x12345678);

mg_crc32()

uint32_t mg_crc32(uint32_t crc, const char *buf, size_t len);

Calculate CRC32 checksum for a given buffer. An initial crc value should be 0.

Parameters:

  • crc - Initial CRC value
  • buf - Data to calculate CRC32
  • len - Data size

Return value: Calculated CRC32 checksum

Usage example:

char data[] = "hello";
uint32_t crc = mg_crc32(0, data, sizeof(data));

mg_check_ip_acl()

int mg_check_ip_acl(struct mg_str acl, struct mg_addr *remote_ip);

Check IP address remote_ip against the IP ACL acl.

Currently, only the IPv4 address format is supported for the ACL string.

Parameters:

  • acl - an ACL string, e.g. -0.0.0.0/0,+1.2.3.4
  • remote_ip - an IP address

Return value: 1 if remote_ip is allowed, 0 if not, and <0 if acl is invalid

Usage example:

if (mg_check_ip_acl(mg_str("-0.0.0.0/0,+1.2.3.4"), c->rem) != 1) {
  LOG(LL_INFO, ("NOT ALLOWED!"));
}

mg_url_decode()

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

Decode URL-encoded string s and write it into to buffer.

Parameters:

  • src - String to decode
  • src_len - Length of the string to decode
  • dst - Pointer to output buffer
  • dst_len - Output buffer size
  • form - If non-zero, then + is decoded as whitespace.

Return value: Decoded bytes count or negative value on error

Usage example:

char url[] = "eexample.org%2Ftest";
char buf[1024];
mg_url_encode(url, sizeof(url) - 1, buf, sizeof(buf), 0); // buf is now "example.org/test"

mg_url_encode

size_t mg_url_encode(const char *s, size_t n, char *buf, size_t len);

Encode s string to URL-encoding and write encoded string into buf.

Parameters:

  • s - String to encode
  • n - String to encode length
  • buf - Output buffer
  • len - Output buffer size

Return value: Number of characters written to buf

Usage example:

char url[] = "example.org/test";
char buf[1024];
mg_url_encode(url, sizeof(url) - 1, buf, sizeof(buf)); // buf is now "example.org%2Ftest"

mg_print_base64

size_t mg_print_base64(void (*out)(char, void *), void *param, va_list *ap);

Print a buffer as a base64-encoded string. Expects data length and a pointer to the data as next arguments in the va_list ap

Parameters:

  • out - function to be used for printing chars
  • param - argument to be passed to out

Return value: Number of bytes printed

Usage example:

mg_snprintf(buf, sizeof(buf), "hi, %m", mg_print_base64, 1, "a");  // hi, "YWJj"

mg_print_esc

size_t mg_print_esc(void (*out)(char, void *), void *param, va_list *ap);

Print a JSON-escaped string. Expects string length and a pointer to the string in the va_list ap. For null-terminated strings use 0 for string length, or the macro MG_ESC()

Parameters:

  • out - function to be used for printing chars
  • param - argument to be passed to out

Return value: Number of bytes printed

Usage example:

mg_snprintf(buf, sizeof(buf), "{%m: %u}", MG_ESC("value"), 123);           // {"value": 123}
mg_snprintf(buf, sizeof(buf), "{%m: %u}", mg_print_esc, 0, "value", 123);  // {"value": 123}

mg_print_hex

size_t mg_print_hex(void (*out)(char, void *), void *param, va_list *ap);

Print a buffer as a hex-encoded string. Expects data length and a pointer to the data as next arguments in the va_list ap

Parameters:

  • out - function to be used for printing chars
  • param - argument to be passed to out

Return value: Number of bytes printed

Usage example:

mg_snprintf(buf, sizeof(buf), "hi, %M", mg_print_hex, 1, 255);  // hi, ff

mg_print_ip

size_t mg_print_ip(void (*out)(char, void *), void *param, va_list *ap);

Print an IP address using a specified character output function. Expects a pointer to a struct mg_addr as the next argument in the va_list ap

Parameters:

  • out - function to be used for printing chars
  • param - argument to be passed to out

Return value: Number of bytes printed

Usage example:

struct mg_addr addr;
addr.ip = MG_U32('a', 'b', 'c', 'd');
mg_snprintf(buf, sizeof(buf), "%M", mg_print_ip, &addr);         // 97.98.99.100

mg_print_ip_port

size_t mg_print_ip_port(void (*out)(char, void *), void *param, va_list *ap);

Print an IP address and port, using a specified character output function. Expects a pointer to a struct mg_addr as the next argument in the va_list ap

Parameters:

  • out - function to be used for printing chars
  • param - argument to be passed to out

Return value: Number of bytes printed

Usage example:

struct mg_addr addr;
addr.ip = MG_U32('a', 'b', 'c', 'd');
addr.port = mg_htons(1234);
mg_snprintf(buf, sizeof(buf), "%M", mg_print_ip_port, &addr);         // 97.98.99.100:1234

mg_print_ip4

size_t mg_print_ip4(void (*out)(char, void *), void *param, va_list *ap);

Print an IP address using a specified character output function. Expects a pointer to a buffer containing the IPv4 address in network order as the next argument in the va_list ap

Parameters:

  • out - function to be used for printing chars
  • param - argument to be passed to out

Return value: Number of bytes printed

Usage example:

mg_snprintf(buf, sizeof(buf), "%M", mg_print_ip4, "abcd");         // 97.98.99.100

mg_print_ip6

size_t mg_print_ip6(void (*out)(char, void *), void *param, va_list *ap);

Print an IPv6 address using a specified character output function. Expects a pointer to a buffer containing the IPv6 address in network order as the next argument in the va_list ap

Parameters:

  • out - function to be used for printing chars
  • param - argument to be passed to out

Return value: Number of bytes printed

Usage example:

mg_snprintf(buf, sizeof(buf), "%M", mg_print_ip6, "abcdefghijklmnop");         // [4142:4344:4546:4748:494a:4b4c:4d4e:4f50]

mg_print_mac

size_t mg_print_mac(void (*out)(char, void *), void *param, va_list *ap);

Print a MAC address using a specified character output function. Expects a pointer to a buffer containing the hardware address as the next argument in the va_list ap

Parameters:

  • out - function to be used for printing chars
  • param - argument to be passed to out

Return value: Number of bytes printed

Usage example:

mg_snprintf(buf, sizeof(buf), "%M", mg_print_mac, "abcdef");          // 61:62:63:64:65:66

struct mg_iobuf

struct mg_iobuf {
  unsigned char *buf;  // Pointer to stored data
  size_t size;         // Total size available
  size_t len;          // Current number of bytes
  size_t align;        // Alignment during allocation
};

IO buffer, described by the struct mg_iobuf, is a simple data structure that inserts or deletes chunks of data at arbitrary offsets and grows/shrinks automatically.

Generic IO buffer. The size specifies an allocation size of the data pointed by buf, and len specifies number of bytes currently stored.

struct mg_iobuf diagram

mg_iobuf_init()

int mg_iobuf_init(struct mg_iobuf *io, size_t size, size_t align);

Initialize IO buffer, allocate size bytes.

Parameters:

  • io - Pointer to mg_iobuf structure to initialize
  • size - Amount of bytes to allocate
  • align - Align size to the align mem boundary. 0 means no alignment

Return value: 1 on success, 0 on allocation failure

Usage example:

struct mg_iobuf io;
if (mg_iobuf_init(&io, 0, 64)) {
  // io successfully initialized
}

mg_iobuf_resize()

int mg_iobuf_resize(struct mg_iobuf *io, size_t size);

Resize IO buffer, set the new size to size. The io->buf pointer could change after this, for example if the buffer grows. If size is 0, then the io->buf is freed and set to NULL, and both size and len are set to 0. The resulting io->size is always aligned to the io->align byte boundary; therefore, to avoid memory fragmentation and frequent reallocations, set io->align to a higher value.

Parameters:

  • io - iobuf to resize
  • size - New size

Return value: 1 on success, 0 on allocation failure

Usage example:

struct mg_iobuf io;
mg_iobuf_init(&io, 0, 10);  // An empty buffer with 10-byte alignment

if (mg_iobuf_resize(&io, 1)) {
  // New io size is 10
}

mg_iobuf_free()

void mg_iobuf_free(struct mg_iobuf *io);

Free memory pointed by io->buf and set to NULL. Both size and len are set to 0.

Parameters:

  • io - iobuf to free

Return value: None

Usage example:

struct mg_iobuf io;
// IO buffer initialization
// ...

// Time to cleanup
mg_iobuf_free(&io);

mg_iobuf_add()

size_t mg_iobuf_add(struct mg_iobuf *io, size_t offset, const void *buf, size_t len);

Insert data buffer buf, len at offset offset. The iobuf is expanded if required. The resulting io->size is always aligned to the io->align byte boundary; therefore, to avoid memory fragmentation and frequent reallocations, set align to a higher value.

Parameters:

  • io - iobuf to add data
  • offset - Offset to add data
  • buf - Data to add
  • len - Data length

Return value: new io length

Usage example:

struct mg_iobuf io;         // Declare buffer
mg_iobuf_init(&io, 0, 16);  // Initialise empty buffer with 16 byte alignment
Function mg_iobuf_init()
mg_iobuf_add(&io, io.len, "hello", 5);  // Append "hello"
Function mg_iobuf_add()

mg_iobuf_del()

size_t mg_iobuf_del(struct mg_iobuf *io, size_t offset, size_t len);

Delete up to len bytes starting from offset, shifting the remaining bytes, as detailed in the graph below. There is no further action on the iobuf, offset and len are capped to operate within current iobuf size.

Parameters:

  • io - iobuf to delete data
  • offset - Start offset
  • len - Number of bytes to delete

Return value: Number of bytes actually deleted

Usage example:

struct mg_iobuf io;
mg_iobuf_init(&io, 0, 16);          // Empty buffer, 16-bytes aligned
mg_iobuf_add(&io, 0, "hello", 5);   // io->len is 5, io->size is 16
mg_iobuf_del(&io, 1, 3);            // io->len is 2, io->size is still 16
Function mg_iobuf_del()