MCPcopy Create free account
hub / github.com/cesanta/mongoose / cb

Function cb

tutorials/http/http-server/main.c:29–79  ·  view source on GitHub ↗

Event handler for the listening connection. Simply serve static files from `s_root_dir`

Source from the content-addressed store, hash-verified

27// Event handler for the listening connection.
28// Simply serve static files from `s_root_dir`
29static void cb(struct mg_connection *c, int ev, void *ev_data) {
30 if (ev == MG_EV_ACCEPT && c->is_tls) {
31 struct mg_tls_opts opts;
32 memset(&opts, 0, sizeof(opts));
33 opts.cert = s_crt;
34 opts.key = s_key;
35 opts.ca = s_ca;
36 mg_tls_init(c, &opts);
37 }
38 if (ev == MG_EV_HTTP_MSG) {
39 struct mg_http_message *hm = ev_data;
40
41 if (mg_match(hm->uri, mg_str("/upload"), NULL)) {
42 // Serve file upload
43 if (s_upload_dir == NULL) {
44 mg_http_reply(c, 403, "", "Denied: file upload directory not set\n");
45 } else {
46 struct mg_http_part part;
47 size_t pos = 0, total_bytes = 0, num_files = 0;
48 while ((pos = mg_http_next_multipart(hm->body, pos, &part)) > 0) {
49 char path[MG_PATH_MAX];
50 MG_INFO(("Chunk name: [%.*s] filename: [%.*s] length: %lu bytes",
51 part.name.len, part.name.buf, part.filename.len,
52 part.filename.buf, part.body.len));
53 mg_snprintf(path, sizeof(path), "%s/%.*s", s_upload_dir,
54 part.filename.len, part.filename.buf);
55 if (mg_path_is_sane(mg_str(path))) {
56 mg_file_write(&mg_fs_posix, path, part.body.buf, part.body.len);
57 total_bytes += part.body.len;
58 num_files++;
59 } else {
60 MG_ERROR(("Rejecting dangerous path %s", path));
61 }
62 }
63 mg_http_reply(c, 200, "", "Uploaded %lu files, %lu bytes\n", num_files,
64 total_bytes);
65 }
66 } else {
67 // Serve web root directory
68 struct mg_http_serve_opts opts = {0};
69 opts.root_dir = s_root_dir;
70 opts.ssi_pattern = s_ssi_pattern;
71 mg_http_serve_dir(c, hm, &opts);
72 }
73
74 // Log request
75 MG_INFO(("%.*s %.*s %lu -> %.*s %lu", hm->method.len, hm->method.buf,
76 hm->uri.len, hm->uri.buf, hm->body.len, 3, c->send.buf + 9,
77 c->send.len));
78 }
79}
80
81static void usage(const char *prog) {
82 fprintf(stderr,

Callers

nothing calls this directly

Calls 9

mg_strClass · 0.70
mg_tls_initFunction · 0.50
mg_matchFunction · 0.50
mg_http_replyFunction · 0.50
mg_http_next_multipartFunction · 0.50
mg_snprintfFunction · 0.50
mg_path_is_saneFunction · 0.50
mg_file_writeFunction · 0.50
mg_http_serve_dirFunction · 0.50

Tested by

no test coverage detected