int PostResponser(struct mg_connection *conn, void *cbdata) { long long r_total = 0; int r, s; char buf[2048]; const struct mg_request_info *ri = mg_get_request_info(conn); if (strcmp(ri->request_method, "POST")) { char buf[1024]; int ret = mg_get_request_link(conn, buf, sizeof(buf)); mg_printf(conn, "HTTP/1.1 405 Method Not Allowed\r\nConnection: close\r\n"); mg_printf(conn, "Content-Type: text/plain\r\n\r\n"); mg_printf(conn, "%s method not allowed in the POST handler\n", ri->request_method); if (ret >= 0) { mg_printf(conn, "use a web tool to send a POST request to %s\n", buf); } return 1; } if (ri->content_length >= 0) { /* We know the content length in advance */ } else { /* We must read until we find the end (chunked encoding * or connection close), indicated my mg_read returning 0 */ } mg_printf(conn, "HTTP/1.1 200 OK\r\nConnection: " "close\r\nTransfer-Encoding: chunked\r\n"); mg_printf(conn, "Content-Type: text/plain\r\n\r\n"); r = mg_read(conn, buf, sizeof(buf)); while (r > 0) { r_total += r; s = mg_send_chunk(conn, buf, r); if (r != s) { /* Send error */ break; } r = mg_read(conn, buf, sizeof(buf)); } mg_printf(conn, "0\r\n"); return 1; }
int HttpServer::callback(struct mg_connection *conn) { const struct mg_request_info *request_info = mg_get_request_info(conn); char* readBuffer = NULL; int postSize = 0; HttpServer* _this = (HttpServer*) request_info->user_data; if (strcmp(request_info->request_method, "GET") == 0) { if(_this->showSpec) { _this->SendResponse(_this->GetSpecification(), conn); return 1; } //Mark the request as unprocessed. return 0; } else if (strcmp(request_info->request_method, "POST") == 0) { //get size of postData sscanf(mg_get_header(conn, "Content-Length"), "%d", &postSize); readBuffer = (char*) malloc(sizeof(char) * (postSize + 1)); mg_read(conn, readBuffer, postSize); _this->OnRequest(readBuffer, conn); free(readBuffer); //Mark the request as processed by our handler. return 1; } else { return 0; } }
static void test_mg_upload(void) { static const char *boundary = "OOO___MY_BOUNDARY___OOO"; struct mg_context *ctx; struct mg_connection *conn; char ebuf[100], buf[20], *file_data, *post_data = NULL; int file_len, post_data_len; ASSERT((ctx = mg_start(&CALLBACKS, NULL, OPTIONS)) != NULL); ASSERT((file_data = read_file("mongoose.c", &file_len)) != NULL); post_data_len = alloc_printf(&post_data, 0, "--%s\r\n" "Content-Disposition: form-data; " "name=\"file\"; " "filename=\"%s\"\r\n\r\n" "%.*s\r\n" "--%s\r\n", boundary, upload_filename, file_len, file_data, boundary); ASSERT(post_data_len > 0); ASSERT((conn = mg_download("localhost", atoi(HTTPS_PORT), 1, ebuf, sizeof(ebuf), "POST /upload HTTP/1.1\r\n" "Content-Length: %d\r\n" "Content-Type: multipart/form-data; " "boundary=%s\r\n\r\n" "%.*s", post_data_len, boundary, post_data_len, post_data)) != NULL); free(file_data), free(post_data); ASSERT(mg_read(conn, buf, sizeof(buf)) == (int) strlen(upload_ok_message)); ASSERT(memcmp(buf, upload_ok_message, strlen(upload_ok_message)) == 0); mg_close_connection(conn); mg_stop(ctx); }
static int begin_request_handler(struct mg_connection *conn) { const struct mg_request_info *ri = mg_get_request_info(conn); char post_data[1024], input1[sizeof(post_data)], input2[sizeof(post_data)]; int post_data_len; if (!strcmp(ri->uri, "/handle_post_request")) { // User has submitted a form, show submitted data and a variable value post_data_len = mg_read(conn, post_data, sizeof(post_data)); // Parse form data. input1 and input2 are guaranteed to be NUL-terminated mg_get_var(post_data, post_data_len, "input_1", input1, sizeof(input1)); mg_get_var(post_data, post_data_len, "input_2", input2, sizeof(input2)); // Send reply to the client, showing submitted form values. mg_printf(conn, "HTTP/1.0 200 OK\r\n" "Content-Type: text/plain\r\n\r\n" "Submitted data: [%.*s]\n" "Submitted data length: %d bytes\n" "input_1: [%s]\n" "input_2: [%s]\n", post_data_len, post_data, post_data_len, input1, input2); } else { // Show HTML form. mg_printf(conn, "HTTP/1.0 200 OK\r\n" "Content-Length: %d\r\n" "Content-Type: text/html\r\n\r\n%s", (int) strlen(html_form), html_form); } return 1; // Mark request as processed }
// A handler for the /authorize endpoint. // Login page form sends user name and password to this endpoint. static void authorize(struct mg_connection *conn, const struct mg_request_info *request_info) { char user[32], password[32], referer[256]; if(!strcmp(request_info->request_method, "POST")) { char post_data[1024]; int post_data_len = mg_read(conn, post_data, sizeof(post_data)); mg_get_var(post_data, post_data_len, "user", user, sizeof(user)); mg_get_var(post_data, post_data_len, "password", password, sizeof(password)); mg_get_var(post_data, post_data_len, "referer", referer, sizeof(referer)); } else { // Fetch user name and password. get_qsvar(request_info, "user", user, sizeof(user)); get_qsvar(request_info, "password", password, sizeof(password)); get_qsvar(request_info, "ref", referer, sizeof(referer)); } /* Referer url must begin with '/' */ if((referer[0] != '/') || (strcmp(referer, AUTHORIZE_URL) == 0)) strcpy(referer, "/"); if(ntop->checkUserPassword(user, password)) { set_cookie(conn, user, referer); } else { // Authentication failure, redirect to login. redirect_to_login(conn, request_info); } }
int HttpConnection::read(core::data& da) { if (da.length()) return 0; use<mg_connection> cnt = connection; return mg_read(cnt, da.bytes(), da.length()); }
bool RequestHandler::getJSONFromRequest(struct mg_connection *conn, Json::Value& ret) { Json::Reader reader; _log.log(LOG_INFO, "Parsing data from /graph POST request.\n"); int contentLength = atoi(mg_get_header(conn,"Content-Length")); char* contentData = (char*) malloc(sizeof(char)*(contentLength+1)); if (contentData == NULL) { _log.log(LOG_ERROR, "Could not malloc bodyData for received request.\n"); handleError(conn, ERR_MAJOR_SERVER_ERROR, "Could not malloc bodyData for received request."); return false; } int contentLengthRead = mg_read(conn, contentData, contentLength); if (contentLengthRead != contentLength) { _log.log(LOG_ERROR, "Did not receive the same amount of data as content length claimed\n"); handleError(conn, ERR_SERVER_ERROR, "Could not malloc bodyData for received request."); return false; } contentData[contentLengthRead] = 0; _log.log(LOG_INFO, "Received %d bytes successfully.\n", contentLength); return reader.parse(string(contentData),ret); }
std::wstring IEDriverServer::ReadRequestBody(struct mg_connection *conn, const struct mg_request_info *request_info) { std::wstring request_body = L""; int content_length = 0; for (int header_index = 0; header_index < 64; ++header_index) { if (request_info->http_headers[header_index].name == NULL) { break; } if (strcmp(request_info->http_headers[header_index].name, "Content-Length") == 0) { content_length = atoi(request_info->http_headers[header_index].value); break; } } if (content_length == 0) { request_body = L"{}"; } else { std::vector<char> input_buffer(content_length + 1); int bytes_read = 0; while (bytes_read < content_length) { bytes_read += mg_read(conn, &input_buffer[bytes_read], content_length - bytes_read); } input_buffer[content_length] = '\0'; int output_buffer_size = ::MultiByteToWideChar(CP_UTF8, 0, &input_buffer[0], -1, NULL, 0); vector<TCHAR> output_buffer(output_buffer_size); ::MultiByteToWideChar(CP_UTF8, 0, &input_buffer[0], -1, &output_buffer[0], output_buffer_size); request_body.append(&output_buffer[0], bytes_read); } return request_body; }
// A handler for the /authorize endpoint. // Login page form sends user name and password to this endpoint. static void authorize(struct mg_connection *conn, const struct mg_request_info *request_info) { char user[32], password[32], referer[256]; if(!strcmp(request_info->request_method, "POST")) { char post_data[1024]; int post_data_len = mg_read(conn, post_data, sizeof(post_data)); mg_get_var(post_data, post_data_len, "user", user, sizeof(user)); mg_get_var(post_data, post_data_len, "password", password, sizeof(password)); mg_get_var(post_data, post_data_len, "referer", referer, sizeof(referer)); } else { // Fetch user name and password. get_qsvar(request_info, "user", user, sizeof(user)); get_qsvar(request_info, "password", password, sizeof(password)); get_qsvar(request_info, "ref", referer, sizeof(referer)); } /* Referer url must begin with '/' */ if((referer[0] != '/') || (strcmp(referer, AUTHORIZE_URL) == 0)) strcpy(referer, "/"); if(ntop->checkUserPassword(user, password)) { char key[256], session_id[64], random[64]; // Authentication success: // 1. create new session // 2. set session ID token in the cookie // // The most secure way is to stay HTTPS all the time. However, just to // show the technique, we redirect to HTTP after the successful // authentication. The danger of doing this is that session cookie can // be stolen and an attacker may impersonate the user. // Secure application must use HTTPS all the time. snprintf(random, sizeof(random), "%d", rand()); generate_session_id(session_id, random, user); // ntop->getTrace()->traceEvent(TRACE_ERROR, "==> %s\t%s", random, session_id); /* http://en.wikipedia.org/wiki/HTTP_cookie */ mg_printf(conn, "HTTP/1.1 302 Found\r\n" "Set-Cookie: session=%s; path=/; max-age=%u; HttpOnly\r\n" // Session ID "Set-Cookie: user=%s; path=/; max-age=%u; HttpOnly\r\n" // Set user, needed by Javascript code "Location: %s%s\r\n\r\n", session_id, HTTP_SESSION_DURATION, user, HTTP_SESSION_DURATION, ntop->getPrefs()->get_http_prefix(), referer); /* Save session in redis */ snprintf(key, sizeof(key), "sessions.%s", session_id); ntop->getRedis()->set(key, user, HTTP_SESSION_DURATION); ntop->getTrace()->traceEvent(TRACE_INFO, "[HTTP] Set session sessions.%s", session_id); } else { // Authentication failure, redirect to login. redirect_to_login(conn, request_info); } }
bool handlePut(CivetServer *server, struct mg_connection *conn) { /* Handler may access the request info using mg_get_request_info */ const struct mg_request_info *req_info = mg_get_request_info(conn); long long rlen, wlen; long long nlen = 0; long long tlen = req_info->content_length; FILE * f; char buf[1024]; int fail = 0; #ifdef _WIN32 _snprintf(buf, sizeof(buf), "D:\\somewhere\\%s\\%s", req_info->remote_user, req_info->local_uri); buf[sizeof(buf)-1] = 0; /* TODO: check overflow */ f = fopen_recursive(buf, "wb"); #else snprintf(buf, sizeof(buf), "~/somewhere/%s/%s", req_info->remote_user, req_info->local_uri); buf[sizeof(buf)-1] = 0; /* TODO: check overflow */ f = fopen_recursive(buf, "w"); #endif if (!f) { fail = 1; } else { while (nlen < tlen) { rlen = tlen - nlen; if (rlen > sizeof(buf)) { rlen = sizeof(buf); } rlen = mg_read(conn, buf, (size_t)rlen); if (rlen <= 0) { fail = 1; break; } wlen = fwrite(buf, 1, (size_t)rlen, f); if (rlen != rlen) { fail = 1; break; } nlen += wlen; } fclose(f); } if (fail) { mg_printf(conn, "HTTP/1.1 409 Conflict\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n"); } else { mg_printf(conn, "HTTP/1.1 201 Created\r\n" "Content-Type: text/plain\r\n" "Connection: close\r\n\r\n"); } return true; }
static int lsp_read(lua_State *L) { struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1)); char buf[1024]; int len = mg_read(conn, buf, sizeof(buf)); if (len <= 0) return 0; lua_pushlstring(L, buf, len); return 1; }
static char *read_conn(struct mg_connection *conn, int *size) { char buf[100], *data = NULL; int len; *size = 0; while ((len = mg_read(conn, buf, sizeof(buf))) > 0) { *size += len; ASSERT((data = realloc(data, *size)) != NULL); memcpy(data + *size - len, buf, len); } return data; }
static void test_get_var(struct mg_connection *conn) { char *var, *buf; size_t buf_len; const char *cl; int var_len; const struct mg_request_info *ri = mg_get_request_info(conn); int is_form_enc = 0; send_standard_reply_head(conn); buf_len = 0; var = buf = NULL; cl = mg_get_header(conn, "Content-Length"); mg_printf(conn, "cl: %p\n", cl); if ((!strcmp(ri->request_method, "POST") || !strcmp(ri->request_method, "PUT")) && cl != NULL) { buf_len = atoi(cl); buf = malloc(buf_len); /* Read in two pieces, to test continuation */ if (buf_len > 2) { mg_read(conn, buf, 2); mg_read(conn, buf + 2, buf_len - 2); } else { mg_read(conn, buf, buf_len); } is_form_enc = 1; } else { MG_ASSERT(ri->query_string != NULL); // query_string ~ "" when no query string was specified in the request buf_len = strlen(ri->query_string); buf = malloc(buf_len + 1); strcpy(buf, ri->query_string); is_form_enc = 1; } var = malloc(buf_len + 1); var_len = mg_get_var(buf, buf_len, "my_var", var, buf_len + 1, is_form_enc); mg_printf(conn, "Value: [%s]\n", var); mg_printf(conn, "Value size: [%d]\n", var_len); free(buf); free(var); }
RemRep::RemRep(const std::string &lports) : Replyer("self"), mListenPorts(lports) { mRMpool.push_back(this); // add register filter addPostFilter(std::tuple<std::string, std::function<cJSON *(RequestInfo &)>> {"register", [&](RequestInfo &ri) -> cJSON* { cJSON *root = nullptr; char requestBody[32768]; try { RemoteObjectServer *newros = new RemoteObjectServer(ri.getRequestMethodArgument(0)); mg_read(ri.getClientStructure(), requestBody, sizeof(requestBody)); newros->parseJString(requestBody); if(newros->getServerIp().empty()) newros->setServerIp(ri.getClientFormattedIp()); mRMpool.push_back(newros); addStatusMsg(&root, "Registration succeded : Object indexed into service."); } catch(BadJSONFormatException) { addStatusMsg(&root, "Registration canceled : Unable to parse received data!"); } catch(ArgumentIndexOutOfBounds) { addStatusMsg(&root, "Registration canceled : Can not read object name from query string!"); } return root; }}); // add unregister filter addGetFilter(std::tuple<std::string, std::function<cJSON *(RequestInfo &)>> {"unregister", [&](RequestInfo &ri) -> cJSON* { cJSON *root = nullptr; bool objFound = false; auto newListEnd = std::remove_if(mRMpool.begin(), mRMpool.end(), [&](Replyer *rCandidate) { try { if(rCandidate->getName() == ri.getRequestMethodArgument(0)) { addStatusMsg(&root, "Unregistration succeded : Object is no further accounted for."); objFound = true; return true; } } catch(ArgumentIndexOutOfBounds) { } return false; }); mRMpool.erase(newListEnd, mRMpool.end()); if(!objFound) addStatusMsg(&root, "Unregistration not carried out : Object not found."); return root; }}); }
QString MushiRequest::getPost(){ if(this->read){ return this->readBuffer; } char buffer[1000]; while(mg_read(this->conn,&buffer,1000) > 0){ this->readBuffer.append(buffer); } this->read=true; return this->readBuffer; }
static void *callback(enum mg_event event, struct mg_connection *conn) { if (event == MG_WEBSOCKET_READY) { unsigned char buf[40]; buf[0] = 0x81; buf[1] = snprintf((char *) buf + 2, sizeof(buf) - 2, "%s", "server ready"); mg_write(conn, buf, 2 + buf[1]); return ""; // MG_WEBSOCKET_READY return value is ignored } else if (event == MG_WEBSOCKET_MESSAGE) { unsigned char buf[200], reply[200]; int n, i, mask_len, xor, msg_len, len; // Read message from the client. // Accept only small (<126 bytes) messages. len = 0; msg_len = mask_len = 0; for (;;) { if ((n = mg_read(conn, buf + len, sizeof(buf) - len)) <= 0) { return ""; // Read error, close websocket } len += n; if (len >= 2) { msg_len = buf[1] & 127; mask_len = (buf[1] & 128) ? 4 : 0; if (msg_len > 125) { return ""; // Message is too long, close websocket } // If we've buffered the whole message, exit the loop if (len >= 2 + mask_len + msg_len) { break; } } } // Prepare frame reply[0] = 0x81; // text, FIN set reply[1] = msg_len; // Copy message from request to reply, applying the mask if required. for (i = 0; i < msg_len; i++) { xor = mask_len == 0 ? 0 : buf[2 + (i % 4)]; reply[i + 2] = buf[i + 2 + mask_len] ^ xor; } // Echo the message back to the client mg_write(conn, reply, 2 + msg_len); // Return non-NULL means stoping websocket conversation. // Close the conversation if client has sent us "exit" string. return memcmp(reply + 2, "exit", 4) == 0 ? "" : NULL; } else { return NULL; } }
int ServiceInputStream::read(string& str, int max) { int bytes = 0, recv = 0; size_t size = min(10000, max); char * buffer = new char[size]; while (max > 0 && (bytes = mg_read(_conn, buffer, size)) > 0) { str = str.append(buffer, bytes); max -= bytes; recv += bytes; } //LOGDEBUG("received data size="<<recv); return recv; }
static int event_handler(struct mg_event *event) { struct mg_request_info *ri = event->request_info; if (event->type == MG_REQUEST_BEGIN) { if (!strcmp(ri->uri, "/data")) { mg_printf(event->conn, "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n\r\n" "%s", fetch_data); close_connection(event->conn); return 1; } if (!strcmp(ri->uri, "/zerolen")) { char buf[100]; mg_printf(event->conn, "%s", "HTTP/1.0 200 OK\r\nContent-Length: 2\r\n\r\nok"); printf("[%d]\n", mg_read(event->conn, buf, sizeof(buf))); ASSERT(mg_read(event->conn, buf, sizeof(buf)) == 0); return 1; } if (!strcmp(ri->uri, "/upload")) { test_upload(event->conn, "lua_5.2.1.h", "./f1.txt"); test_upload(event->conn, "lsqlite3.c", "./f2.txt"); ASSERT(mg_upload(event->conn, ".", NULL, 0) == NULL); mg_printf(event->conn, "HTTP/1.0 200 OK\r\n" "Content-Type: text/plain\r\n\r\n" "%s", upload_ok_message); close_connection(event->conn); return 1; } } else if (event->type == MG_EVENT_LOG) { printf("%s\n", (const char *) event->event_param); } return 0; }
static void test_get_var(struct mg_connection *conn, const struct mg_request_info *ri) { char *var, *buf; size_t buf_len; const char *cl; int var_len; mg_printf(conn, "%s", standard_reply); buf_len = 0; var = buf = NULL; cl = mg_get_header(conn, "Content-Length"); mg_printf(conn, "cl: %p\n", cl); if ((!strcmp(ri->request_method, "POST") || !strcmp(ri->request_method, "PUT")) && cl != NULL) { buf_len = atoi(cl); buf = malloc(buf_len); /* Read in two pieces, to test continuation */ if (buf_len > 2) { mg_read(conn, buf, 2); mg_read(conn, buf + 2, buf_len - 2); } else { mg_read(conn, buf, buf_len); } } else if (ri->query_string != NULL) { buf_len = strlen(ri->query_string); buf = malloc(buf_len + 1); strcpy(buf, ri->query_string); } var = malloc(buf_len + 1); var_len = mg_get_var(buf, buf_len, "my_var", var, buf_len + 1); mg_printf(conn, "Value: [%s]\n", var); mg_printf(conn, "Value size: [%d]\n", var_len); free(buf); free(var); }
static char* adapt_read_connection(struct mg_connection* connection, int* len_out) { int buf_size = 256; char* buf = (char*)malloc(buf_size + 1); int len = 0; int r; while((r = mg_read(connection, buf + len, buf_size - len)) > 0) { len += r; if (len == buf_size) { buf_size *= 2; buf = (char*)realloc(buf, buf_size + 1); } } buf[len] = '\0'; *len_out = len; return buf; }
static int api_callback(struct mg_connection *conn) { struct mg_request_info *ri = mg_get_request_info(conn); char post_data[100] = ""; ASSERT(ri->user_data == (void *) 123); ASSERT(ri->num_headers == 2); ASSERT(strcmp(mg_get_header(conn, "host"), "blah.com") == 0); ASSERT(mg_read(conn, post_data, sizeof(post_data)) == 3); ASSERT(memcmp(post_data, "b=1", 3) == 0); ASSERT(ri->query_string != NULL); ASSERT(ri->remote_ip > 0); ASSERT(ri->remote_port > 0); ASSERT(strcmp(ri->http_version, "1.0") == 0); mg_printf(conn, "HTTP/1.0 200 OK\r\n\r\n"); return 1; }
bool handlePost(CivetServer *server, struct mg_connection *conn) { /* Handler may access the request info using mg_get_request_info */ const struct mg_request_info *req_info = mg_get_request_info(conn); long long rlen, wlen; long long nlen = 0; long long tlen = req_info->content_length; char buf[1024]; mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: " "text/html\r\nConnection: close\r\n\r\n"); mg_printf(conn, "<html><body>\n"); mg_printf(conn, "<h2>This is the Foo POST handler!!!</h2>\n"); mg_printf(conn, "<p>The request was:<br><pre>%s %s HTTP/%s</pre></p>\n", req_info->request_method, req_info->uri, req_info->http_version); mg_printf(conn, "<p>Content Length: %li</p>\n", (long)tlen); mg_printf(conn, "<pre>\n"); while (nlen < tlen) { rlen = tlen - nlen; if (rlen > sizeof(buf)) { rlen = sizeof(buf); } rlen = mg_read(conn, buf, (size_t)rlen); if (rlen <= 0) { break; } wlen = mg_write(conn, buf, (size_t)rlen); if (rlen != rlen) { break; } nlen += wlen; } mg_printf(conn, "\n</pre>\n"); mg_printf(conn, "</body></html>\n"); return true; }
Request::Request(struct mg_connection *connection_, const struct mg_request_info *request_) : connection(connection_), request(request_) { url = string(request->uri); method = string(request->request_method); // Downloading POST data ostringstream postData; if (mg_get_header(connection, "Content-Type") != NULL) { int n; char post[1024]; while (n = mg_read(connection, post, sizeof(post))) { postData.write(post, n); } } data = postData.str(); }
static PostDataStatus ReadBody(std::string& postData, struct mg_connection *connection, const IHttpHandler::Arguments& headers) { IHttpHandler::Arguments::const_iterator cs = headers.find("content-length"); if (cs == headers.end()) { return PostDataStatus_NoLength; } int length; try { length = boost::lexical_cast<int>(cs->second); } catch (boost::bad_lexical_cast) { return PostDataStatus_NoLength; } if (length < 0) { length = 0; } postData.resize(length); size_t pos = 0; while (length > 0) { int r = mg_read(connection, &postData[pos], length); if (r <= 0) { return PostDataStatus_Failure; } assert(r <= length); length -= r; pos += r; } return PostDataStatus_Success; }
//////////////////////////////////////////////////////////////// ///Function to send a simple text ajax rely void Executive::ajaxReply(struct mg_connection *conn, const struct mg_request_info *request_info) { try{ const char * clength; char h1[] = "Content-Length"; clength = mg_get_header(conn,h1); //get length of post data int clen = atoi(clength); char *pdata = (char *)malloc(clen+clen/8+1); int datalen = mg_read(conn,pdata,clen); //read post data pdata[clen] = '\0'; printf("\nUser data: %s",pdata); mg_printf(conn, "%s\r\n%s", ajax_reply_start,pdata); free(pdata); } catch(std::exception ex) { std::cout << "\n " << ex.what() << "\n\n"; } }
//////////////////////////////////////////////////////////////// ///Function to send sniffed file list to the client void Executive::listReply(struct mg_connection *conn, const struct mg_request_info *request_info) { try{ int is_jsonp; char text[100]; const char * json; std::stringstream ss; std::string msg; mg_printf(conn, "%s\r\n", json_reply_start); //prints the json message starting headers const char * clength; char h1[] = "Content-Length"; clength = mg_get_header(conn,h1); //get the length of post data int clen = atoi(clength); char *pdata = (char *)malloc(clen+clen/8+1); int datalen = mg_read(conn,pdata,clen); //read post data pdata[clen] = '\0'; mg_get_var(pdata, strlen(pdata == NULL ? "" : pdata), "text", text, sizeof(text)); std::string path(text); is_jsonp = handle_jsonp(pdata,conn, request_info); //find the callback function srand((size_t)time(NULL)); ss<<"["; fsniffer2.Clear(); fsniffer2.sniffFiles(path); std::set<std::string> filelist = fsniffer2.getFiles(); //get sniffed files for (std::set<std::string>::iterator it=filelist.begin(); it != filelist.end(); it++) { std::string tempstr = HTMLEncode(*it); //html encode filepaths ss<<"{item: \""<<tempstr<<"\"},"; } ss<<"]"; msg = ss.str(); json = msg.c_str(); mg_printf(conn, "%s", json); //print json array to the connection if (is_jsonp) { mg_printf(conn, "%s", ")"); //print closing bracket for the function } // fsniffer2.saveFiles(); //save sniffed files } catch(std::exception ex){std::cout << "\n " << ex.what() << "\n\n";} }
//////////////////////////////////////////////////////////////// ///Function to send sniffed process list void Executive::procReply(struct mg_connection *conn, const struct mg_request_info *request_info) { try{ int is_jsonp; const char * json; std::stringstream ss; std::string msg; mg_printf(conn, "%s\r\n", json_reply_start); //prints the json message starting headers const char * clength; char h1[] = "Content-Length"; clength = mg_get_header(conn,h1); //get the length of post data int clen = atoi(clength); char *pdata = (char *)malloc(clen+clen/8+1); int datalen = mg_read(conn,pdata,clen); //read post data pdata[clen] = '\0'; /*mg_get_var(pdata, strlen(pdata == NULL ? "" : pdata), "text", text, sizeof(text)); std::string path(text);*/ is_jsonp = handle_jsonp(pdata,conn, request_info); //find the callback function srand((size_t)time(NULL)); ss<<"["; prsniffer.Clear(); prsniffer.sniffProcesses(); std::map<std::string,int> filelist = prsniffer.getProcesses(); //get process list for (std::map<std::string,int>::iterator it=filelist.begin(); it != filelist.end(); it++) { std::string tempstr = HTMLEncode((*it).first); ss<<"{item: \""<<tempstr<<" ("<<(*it).second<<")\"},"; //store process name and count } ss<<"]"; msg = ss.str(); json = msg.c_str(); mg_printf(conn, "%s", json); //print json array to the connection if (is_jsonp) { mg_printf(conn, "%s", ")"); //print closing bracket for the function } //prsniffer.saveProcesses(); }catch(std::exception ex){std::cout << "\n " << ex.what() << "\n\n";} }
static void mg_keep_alive(struct mg_connection* conn, const struct mg_request_info* ri) { const char *cl; char *buf; int len; mg_printf(conn, "%s", standard_reply); if (strcmp(ri->request_method, "POST") == 0 && (cl = mg_get_header(conn, "Content-Length")) != NULL) { len = atoi(cl); if ((buf = MEM_ALLOC(len+1)) != NULL) { mg_read(conn, buf, len); buf[len] = '\0'; uint id; sscanf(buf, "%u", &id); MEM_FREE(buf); // Invoke keep_alive _invoke("keep_alive_cb", id, NULL); } } }
static int api_cb(struct mg_event *event) { struct mg_request_info *ri = event->request_info; char post_data[100] = ""; if (event->type == MG_REQUEST_BEGIN) { ASSERT(event->user_data == (void *) 123); ASSERT(ri->num_headers == 2); ASSERT(strcmp(mg_get_header(event->conn, "host"), "blah.com") == 0); ASSERT(mg_read(event->conn, post_data, sizeof(post_data)) == 3); ASSERT(memcmp(post_data, "b=1", 3) == 0); ASSERT(ri->query_string != NULL); ASSERT(strcmp(ri->query_string, api_uri + 2) == 0); ASSERT(ri->remote_ip > 0); ASSERT(ri->remote_port > 0); ASSERT(strcmp(ri->http_version, "1.0") == 0); mg_printf(event->conn, "HTTP/1.0 200 OK\r\n\r\n"); return 1; } return 0; }
static void test_mg_upload(void) { static const char *boundary = "OOO___MY_BOUNDARY___OOO"; struct mg_context *ctx; struct mg_connection *conn; char ebuf[100], buf[20], *file_data, *file2_data, *post_data; int file_len, file2_len, post_data_len; ASSERT((ctx = mg_start(OPTIONS, event_handler, NULL)) != NULL); // Upload two files ASSERT((file_data = read_file("lua_5.2.1.h", &file_len)) != NULL); ASSERT((file2_data = read_file("lsqlite3.c", &file2_len)) != NULL); post_data = NULL; post_data_len = alloc_printf(&post_data, 0, // First file "--%s\r\n" "Content-Disposition: form-data; " "name=\"file\"; " "filename=\"%s\"\r\n\r\n" "%.*s\r\n" // Second file "--%s\r\n" "Content-Disposition: form-data; " "name=\"file\"; " "filename=\"%s\"\r\n\r\n" "%.*s\r\n" // Final boundary "--%s--\r\n", boundary, "f1.txt", file_len, file_data, boundary, "f2.txt", file2_len, file2_data, boundary); ASSERT(post_data_len > 0); ASSERT((conn = mg_download("localhost", atoi(HTTPS_PORT), 1, ebuf, sizeof(ebuf), "POST /upload HTTP/1.1\r\n" "Content-Length: %d\r\n" "Content-Type: multipart/form-data; " "boundary=%s\r\n\r\n" "%.*s", post_data_len, boundary, post_data_len, post_data)) != NULL); ASSERT(mg_read(conn, buf, sizeof(buf)) == (int) strlen(upload_ok_message)); ASSERT(memcmp(buf, upload_ok_message, strlen(upload_ok_message)) == 0); mg_close_connection(conn); mg_stop(ctx); }