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 eventev- Event to sendev_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 eventfmt- Format string inprintfsemantics
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 tomg_md5_ctxstructure 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 contextdata- Data to hashlen- 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 contextbuf- 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 tomg_sha1_ctxstructure 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 contextdata- Data to hashlen- 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 contextdigest- 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 encodebuf- Pointer to buffer to write resultlen- 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 marklen- 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 encoden- Data lengthbuf- Pointer to buffer to write resultlen- 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 decoden- Data lengthdst- Pointer to output bufferlen- 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 datalen- 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 bufferlen- 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 valuebuf- Data to calculate CRC32len- 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.4remote_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 decodesrc_len- Length of the string to decodedst- Pointer to output bufferdst_len- Output buffer sizeform- 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 encoden- String to encode lengthbuf- Output bufferlen- 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 charsparam- argument to be passed toout
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 charsparam- argument to be passed toout
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 charsparam- argument to be passed toout
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 charsparam- argument to be passed toout
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 charsparam- argument to be passed toout
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 charsparam- argument to be passed toout
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 charsparam- argument to be passed toout
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 charsparam- argument to be passed toout
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.
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 tomg_iobufstructure to initializesize- Amount of bytes to allocatealign- Alignsizeto thealignmem boundary.0means 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 resizesize- 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 dataoffset- Offset to add databuf- Data to addlen- 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
mg_iobuf_add(&io, io.len, "hello", 5); // Append "hello"
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 dataoffset- Start offsetlen- 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