// 16. Remote command static void proc_command(struct mg_connection* conn, const struct mg_request_info* request_info) { char cmd[20]; char ret[100]; get_qsvar(request_info, "cmd", cmd, sizeof(cmd)); logger_remotem("proc_command=%s", cmd); if (strstr(cmd, "PLANB")) { char size[20]; get_qsvar(request_info, "size", size, sizeof(size)); int sz = atoi(size); set_planb_size(sz); strcpy(ret, size); } else if (strstr(cmd, "TIO")) { struct statvfs stat_buf; unsigned long long_free_blk; unsigned long long_data_size; char message[14]; statvfs(ODI_DATA, &stat_buf); long_free_blk = stat_buf.f_bavail * stat_buf.f_bsize / 1024000; long_data_size = stat_buf.f_blocks * stat_buf.f_bsize / 1024000; // for free size get time 35MB per minute logger_remotem("proc_recording_time: size=%u free=%u", long_data_size, long_free_blk); float fminutes = (float)long_free_blk / (float)35; int hour = fminutes / 60; int minutes = (int)fminutes - (hour * 60); int seconds = (fminutes - (minutes + hour * 60)) * 60.; sprintf(message, "TM%.2d:%.2d:%.2d\r\n", hour, minutes, seconds); strcpy(ret, message); get_command(message); } else { strcat(cmd, "\r\n"); strcpy(ret, get_command(cmd)); } mg_printf(conn, "HTTP/1.0 200 OK\r\n" "Content-Type: text/plain;charset=iso-8859-1\r\n\r\n" "%s\r\n", ret); }
void Server::SendHttpNotFound(struct mg_connection* const connection, const struct mg_request_info* const request_info, const std::wstring& body) { std::string narrow_body = CW2A(body.c_str(), CP_UTF8); std::ostringstream out; out << "HTTP/1.1 404 Not Found\r\n" << "Content-Length: " << strlen(narrow_body.c_str()) << "\r\n" << "Content-Type: application/json; charset=UTF-8\r\n" << "Vary: Accept-Charset, Accept-Encoding, Accept-Language, Accept\r\n" << "Accept-Ranges: bytes\r\n" << "Connection: close\r\n\r\n"; if (strcmp(request_info->request_method, "HEAD") != 0) { out << narrow_body << "\r\n"; } mg_printf(connection, "%s", out.str().c_str()); }
void imcs_offer() { { assert(imcs_connected() == true); } { webserver_broadcast("imcs_buffer", ">>> offer\n"); } { imcs_charBuffer[0] = '\0'; sprintf(imcs_charOperation, "imcs_offer"); imcs_charTermination[0] = '\0'; mg_printf(imcs_mgconnectionHandle, "offer W\n"); } }
static int begin_request_handler_cb(struct mg_connection *conn) { const struct mg_request_info *ri = mg_get_request_info(conn); if (!strcmp(ri->uri, "/data")) { mg_printf(conn, "HTTP/1.1 200 OK\r\n" "Content-Length: %d\r\n" "Content-Type: text/plain\r\n\r\n" "%s", (int) strlen(fetch_data), fetch_data); return 1; } if (!strcmp(ri->uri, "/upload")) { ASSERT(mg_upload(conn, ".") == 1); } return 0; }
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; }
int field_found(const char *key, const char *filename, char *path, size_t pathlen, void *user_data) { struct mg_connection *conn = (struct mg_connection *)user_data; mg_printf(conn, "%s:\r\n", key); if (filename && *filename) { _snprintf(path, pathlen, "C:\\tmp\\%s", filename); return FORM_DISPOSITION_STORE; } return FORM_DISPOSITION_GET; }
int web_engine::json_slider_handler(struct mg_connection *conn) { const slider_state *curslider; astring tempstring; Json::Value array(Json::arrayValue); // add all sliders for (curslider = machine().ui().get_slider_list(); curslider != NULL; curslider = curslider->next) { INT32 curval = (*curslider->update)(machine(), curslider->arg, &tempstring, SLIDER_NOCHANGE); Json::Value data; data["description"] = curslider->description; data["minval"] = curslider->minval; data["maxval"] = curslider->maxval; data["defval"] = curslider->defval; data["incval"] = curslider->incval; data["curval"] = curval; array.append(data); } // add all sliders for (curslider = (slider_state*)machine().osd().get_slider_list(); curslider != NULL; curslider = curslider->next) { INT32 curval = (*curslider->update)(machine(), curslider->arg, &tempstring, SLIDER_NOCHANGE); Json::Value data; data["description"] = curslider->description; data["minval"] = curslider->minval; data["maxval"] = curslider->maxval; data["defval"] = curslider->defval; data["incval"] = curslider->incval; data["curval"] = curval; array.append(data); } Json::FastWriter writer; const char *json = writer.write(array).c_str(); // Send HTTP reply to the client mg_printf(conn, "HTTP/1.1 200 OK\r\n" "Content-Type: application/json\r\n" "Content-Length: %d\r\n" // Always set Content-Length "\r\n" "%s", (int)strlen(json), json); return MG_TRUE; }
void imcs_ratings() { { assert(imcs_connected() == true); } { webserver_broadcast("imcs_buffer", ">>> ratings\n"); } { imcs_charBuffer[0] = '\0'; sprintf(imcs_charOperation, "imcs_ratings"); sprintf(imcs_charTermination, ".\r\n"); mg_printf(imcs_mgconnectionHandle, "ratings\n"); } }
// 6. GET_DRIVE_INFO static void proc_cmd_get_drive_info(struct mg_connection* conn, const struct mg_request_info* request_info) { char str_path[200]; char str_drive[200]; get_qsvar(request_info, "path", str_path, sizeof(str_path)); sprintf(str_drive, "/odi%s", str_path); logger_remotem("GET_DRIVE_INFO: %s", str_drive); unsigned long* drive_info = getDriveInfo(str_drive); mg_printf(conn, "HTTP/1.0 200 OK\r\n\r\n" "filesystem_size=%lu\r\n" "free_blocks=%lu\r\n" "errno=0\r\n", drive_info[0], drive_info[1]); }
static void test_get_request_info(struct mg_connection *conn, const struct mg_request_info *ri) { int i; mg_printf(conn, "%s", standard_reply); mg_printf(conn, "Method: [%s]\n", ri->request_method); mg_printf(conn, "URI: [%s]\n", ri->uri); mg_printf(conn, "HTTP version: [%s]\n", ri->http_version); for (i = 0; i < ri->num_headers; i++) { mg_printf(conn, "HTTP header [%s]: [%s]\n", ri->http_headers[i].name, ri->http_headers[i].value); } mg_printf(conn, "Query string: [%s]\n", ri->query_string ? ri->query_string: ""); mg_printf(conn, "Remote IP: [%lu]\n", ri->remote_ip); mg_printf(conn, "Remote port: [%d]\n", ri->remote_port); mg_printf(conn, "Remote user: [%s]\n", ri->remote_user ? ri->remote_user : ""); }
/* * Logs the user out. * Removes cookie and any associated session state. */ static void logout_handler(struct mg_connection *nc, int ev, void *p) { struct http_message *hm = (struct http_message *) p; mg_printf(nc, "HTTP/1.0 302 Found\r\n" "Set-Cookie: %s=\r\n" "Location: /\r\n" "\r\n" "Logged out", SESSION_COOKIE_NAME); struct session *s = get_session(hm); if (s != NULL) { fprintf(stderr, "%s logged out, session %" INT64_X_FMT " destroyed\n", s->user, s->id); destroy_session(s); } nc->flags |= MG_F_SEND_AND_CLOSE; (void) ev; }
static void *query_phone_stop(struct mg_connection *conn) { const struct mg_request_info *ri = mg_get_request_info(conn); char name[BUFFER_LEN]; char buffer[BUFFER_LEN]; int qlen = strlen(ri->query_string); memset(name, 0, BUFFER_LEN); mg_get_var(ri->query_string, qlen, "name", name, BUFFER_LEN); sprintf(buffer, "stop:%s", name); printf("send:%s\n", buffer); udp_broadcast(buffer); mg_printf(conn, HTTP_HEADER_PLAIN "0"); return ""; }
static int begin_http_error_handler_static(struct mg_connection *conn, int status) { //const struct mg_request_info *request_info = mg_get_request_info(conn); if (status == 404) // 404 -- File Not Found { { mg_printf(conn, "HTTP/1.1 404 Not Found\r\n" "Content-Type: text/plain\r\n" "Content-Length: 14\r\n" // Always set Content-Length "\r\n" "Nothing to do."); } } // Returning non-zero tells mongoose that our function has replied to // the client, and mongoose should not send client any more data. return 1; }
static int begin_request_handler_cb(struct mg_connection *conn) { const struct mg_request_info *ri = mg_get_request_info(conn); if (!strcmp(ri->uri, "/data")) { mg_printf(conn, "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n\r\n" "%s", fetch_data); close_connection(conn); return 1; } if (!strcmp(ri->uri, "/upload")) { ASSERT(ri->query_string != NULL); ASSERT(mg_upload(conn, ".") == atoi(ri->query_string)); } return 0; }
/* Main event handler. */ static void ev_handler(struct mg_connection *nc, int ev, void *p) { switch (ev) { case MG_EV_HTTP_REQUEST: { struct http_message *hm = (struct http_message *) p; struct session *s = get_session(hm); /* Ask the user to log in if they did not present a valid cookie. */ if (s == NULL) { mg_printf(nc, "HTTP/1.0 302 Found\r\n" "Location: /login.html\r\n" "\r\n" "Please log in"); nc->flags |= MG_F_SEND_AND_CLOSE; break; } /* * Serve the page that was requested. * Save session in user_data for use by SSI calls. */ fprintf(stderr, "%s (sid %" INT64_X_FMT ") requested %.*s\n", s->user, s->id, (int) hm->uri.len, hm->uri.p); nc->user_data = s; mg_serve_http(nc, (struct http_message *) p, s_http_server_opts); break; } case MG_EV_SSI_CALL: { /* Expand variables in a page by using session data. */ const char *var = (const char *) p; const struct session *s = (const struct session *) nc->user_data; if (strcmp(var, "user") == 0) { mg_printf_html_escape(nc, "%s", s->user); } else if (strcmp(var, "lucky_number") == 0) { mg_printf_html_escape(nc, "%d", s->lucky_number); } break; } case MG_EV_TIMER: { /* Perform session maintenance. */ check_sessions(); mg_set_timer(nc, mg_time() + SESSION_CHECK_INTERVAL); break; } } }
bool handleAll(const char * method, CivetServer *server, struct mg_connection *conn) { std::string s = ""; mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"); mg_printf(conn, "<html><body>"); mg_printf(conn, "<h2>This is the A handler for \"%s\" !</h2>", method); if (CivetServer::getParam(conn, "param", s)) { mg_printf(conn, "<p>param set to %s</p>", s.c_str()); } else { mg_printf(conn, "<p>param not set</p>"); } mg_printf(conn, "</body></html>\n"); return true; }
static void handle_setled_call(struct mg_connection *nc, struct http_message *hm) { int val; char *http_status; char inverse[BUF_SIZE]; mg_get_http_var(&hm->body, "inverse", inverse, sizeof(inverse)); if ((val = usbfunk_init()) != USBFUNK_SUCCESS) { http_status = HTTP_503_SERVICE_UNAVAILABLE ; } else if ((val = usbfunk_setled(atoi(inverse)) == USBFUNK_SUCCESS)) { http_status = HTTP_200_OK; } else { http_status = HTTP_400_BAD_REQUEST; } mg_printf(nc, "HTTP/1.1 %s\r\nTransfer-Encoding: chunked\r\n\r\n", http_status); mg_printf_http_chunk(nc, "%s", http_status); mg_send_http_chunk(nc, "", 0); }
int FormHandler(struct mg_connection *conn, void *cbdata) { /* Handler may access the request info using mg_get_request_info */ const struct mg_request_info *req_info = mg_get_request_info(conn); int ret; struct mg_form_data_handler fdh = {field_found, field_get, 0}; /* TODO: Checks before calling handle_form_data ? */ (void)req_info; mg_printf(conn, "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\n"); fdh.user_data = (void *)conn; /* TODO: Handle the return value */ ret = mg_handle_form_data(conn, &fdh); return 1; }
/* * Forwards the jpeg frame data to all open mjpeg connections. * * Incoming messages follow a very simple binary frame format: * 4 bytes: timestamp (in network byte order) * n bytes: jpeg payload * * The timestamp is used to compute a lag. * It's done in a quite stupid way as it requires the device clock * to be synchronized with the cloud endpoint. */ static void push_frame_to_clients(struct mg_mgr *mgr, const struct websocket_message *wm) { struct mg_connection *nc; /* * mjpeg connections are tagged with the MG_F_USER_2 flag so we can find them * my scanning the connection list provided by the mongoose manager. */ for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) { if (!(nc->flags & MG_F_USER_2)) continue; // Ignore un-marked requests mg_printf(nc, "--w00t\r\nContent-Type: image/jpeg\r\n" "Content-Length: %lu\r\n\r\n", (unsigned long) wm->size); mg_send(nc, wm->data, wm->size); mg_send(nc, "\r\n", 2); printf("Image pushed to %p\n", nc); } }
//////////////////////////////////////////////////////////////// ///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"; } }
void Server::redirect_to(struct mg_connection *conn, struct http_message *hm, const char *where) { std::string host; mg_str *host_hdr = mg_get_http_header(hm, "Host"); if (host_hdr) { if (!CONFIG_STRING(m_config, "service.cert").empty()) { host += "https://"; } else { host += "http://"; } host += std::string(host_hdr->p, host_hdr->len); } where = where + 1; mg_printf(conn, "HTTP/1.1 302 Found\r\n" "Set-Cookie: original_url=/\r\n" "Location: %s%s%s\r\n\r\n", host.c_str(), CONFIG_STRING(m_config, "service.base_location").c_str(), where); }
static int us1(struct mg_connection *conn) { static const char *file_name = "mongoose.h"; int file_size; if (conn->status_code == MG_CONNECT_SUCCESS) { mg_printf(conn, "GET /%s HTTP/1.0\r\n\r\n", file_name); return 0; } else if (conn->status_code == MG_DOWNLOAD_SUCCESS) { char *file_data = read_file(file_name, &file_size); sprintf((char *) conn->connection_param, "%d", (size_t) file_size == conn->content_len && memcmp(file_data, conn->content, file_size) == 0 ? 1 : 0); free(file_data); } else if (conn->status_code == MG_CONNECT_FAILURE) { sprintf((char *) conn->connection_param, "%s", "cf"); } else { sprintf((char *) conn->connection_param, "%s", "df"); } return 1; }
// Redirect user to the login form. In the cookie, store the original URL // we came from, so that after the authorization we could redirect back. static void redirect_to_login(struct mg_connection *conn, const struct mg_request_info *request_info) { char session_id[33], buf[128]; mg_get_cookie(conn, "session", session_id, sizeof(session_id)); ntop->getTrace()->traceEvent(TRACE_INFO, "[HTTP] %s(%s)", __FUNCTION__, session_id); mg_printf(conn, "HTTP/1.1 302 Found\r\n" // "HTTP/1.1 401 Unauthorized\r\n" // "WWW-Authenticate: Basic\r\n" "Set-Cookie: session=%s; path=/; expires=Thu, 01-Jan-1970 00:00:01 GMT; max-age=0; HttpOnly\r\n" // Session ID "Location: %s%s?referer=%s%s%s\r\n\r\n", session_id, ntop->getPrefs()->get_http_prefix(), Utils::getURL((char*)LOGIN_URL, buf, sizeof(buf)), conn->request_info.uri, conn->request_info.query_string ? "%3F" /* ? */: "", conn->request_info.query_string ? conn->request_info.query_string : ""); }
void handle_read_call(struct mg_connection* nc, struct http_message* hm) { char** result = init_result_array(); char* tmp = init_tmp(); if (result == NULL || tmp == NULL) { free(result); free(tmp); mg_error(nc, ERR_OUT_OF_MEMORY); return; } split(result, tmp, hm->query_string.p, "&=", hm->query_string.len); int resolution = -1; char* pict_id = NULL; parse_uri(result, &resolution, &pict_id); if (resolution != -1 && pict_id != NULL) { char* image_buffer = NULL; uint32_t image_size = 0; int err_check = do_read(pict_id, resolution, &image_buffer, &image_size, db_file); if (err_check != 0) { mg_error(nc, err_check); } else { mg_printf(nc, "HTTP/1.1 200 OK\r\n" "Content-Type: image/jpeg\r\n" "Content-Length: %" PRIu32 "\r\n\r\n", image_size); mg_send(nc, image_buffer, image_size); nc->flags |= MG_F_SEND_AND_CLOSE; } free(image_buffer); } else { mg_error(nc, ERR_INVALID_ARGUMENT); } free(result); free(tmp); }
/* * choose_backend parses incoming HTTP request and routes it to the appropriate * backend. It assumes that clients don't do HTTP pipelining, handling only * one request request for each connection. To give a hint to backend about * this it inserts "Connection: close" header into each forwarded request. */ static int connect_backend(struct conn_data *conn, struct http_message *hm) { struct mg_connection *nc = conn->client.nc; struct http_backend *be = choose_backend(hm); write_log("%ld %.*s %.*s backend=%s\n", (long) time(NULL), (int) hm->method.len, hm->method.p, (int) hm->uri.len, hm->uri.p, be ? be->host_port : "not defined"); if (be == NULL) return 0; if (be->redirect != 0) { mg_printf(nc, "HTTP/1.1 302 Found\r\nLocation: %s\r\n\r\n", be->host_port); return 1; } struct be_conn *bec = get_conn(be); if (bec != NULL) { bec->nc->handler = ev_handler; #ifdef DEBUG write_log("conn=%p to %p (%s) reusing bec=%p\n", conn, be, be->host_port, bec); #endif } else { bec = malloc(sizeof(*conn->be_conn)); memset(bec, 0, sizeof(*bec)); bec->nc = mg_connect(nc->mgr, be->host_port, ev_handler); #ifdef DEBUG write_log("conn=%p new conn to %p (%s) bec=%p\n", conn, be, be->host_port, bec); #endif if (bec->nc == NULL) { free(bec); write_log("Connection to [%s] failed\n", be->host_port); return 0; } } bec->be = be; conn->be_conn = bec; conn->backend.nc = bec->nc; conn->backend.nc->user_data = conn; mg_set_protocol_http_websocket(conn->backend.nc); return 1; }
static int begin_request_handler(struct mg_connection *conn) { const struct mg_request_info *request_info = mg_get_request_info(conn); char content[100]; VRIO_Message message; message.init(); client->getOrientation(HEAD, message); // Prepare the message we're going to send int content_length = sprintf_s(content, sizeof(content), "%f %f %f \n\n", message.pitch, message.yaw, message.roll); // Send HTTP reply to the client mg_printf(conn, "HTTP/1.1 200 OK\r\n" "Content-Type: text/plain\r\n" "Content-Length: %d\r\n" // Always set Content-Length "\r\n" "%s", content_length, content); return 1; }
static void *event_handler(enum mg_event event, struct mg_connection *conn) { const struct mg_request_info *request_info = mg_get_request_info(conn); if (event == MG_NEW_REQUEST && !strcmp(request_info->uri, "/data")) { mg_printf(conn, "HTTP/1.1 200 OK\r\n" "Content-Length: %d\r\n" "Content-Type: text/plain\r\n\r\n" "%s", (int) strlen(fetch_data), fetch_data); return ""; } else if (event == MG_OPEN_FILE) { const char *path = request_info->ev_data; if (strcmp(path, "./blah") == 0) { mg_get_request_info(conn)->ev_data = (void *) (int) strlen(inmemory_file_data); return (void *) inmemory_file_data; } } else if (event == MG_EVENT_LOG) { } return NULL; }
/* gets the directory folder specified by the 'dirtype' parameter */ static char * get_abs_dirtype_path(struct mg_connection *conn) { char *dir_type, *dir; if (!(dir_type = get_var_or_err(conn, "dirtype"))) { return NULL; } if (strcmp(dir_type, "doc") == 0) { dir = doc_root; } else if (strcmp(dir_type, "root") == 0){ dir = web_root; } else { mg_printf(conn, "HTTP/1.1 400 Bad Request\r\n" "Content-Type: text/plain\r\n\r\n" "Parameter '%s' not valid", dir_type); mg_free(dir_type); return NULL; } return dir; }
static void authorize(struct mg_connection *conn, const struct mg_request_info *ri, void *data) { const char *cookie, *domain; cookie = mg_get_header(conn, "Cookie"); if (!strcmp(ri->uri, "/login")) { /* Always authorize accesses to the login page */ mg_authorize(conn); } else if (cookie != NULL && strstr(cookie, "allow=yes") != NULL) { /* Valid cookie is present, authorize */ mg_authorize(conn); } else { /* Not authorized. Redirect to the login page */ mg_printf(conn, "HTTP/1.1 301 Moved Permanently\r\n" "Set-Cookie: uri=%s;\r\n" "Location: /login\r\n\r\n", ri->uri); } }
static void bbs_input_page(struct mg_connection *conn, const struct mg_request_info *ri, void *data) { /* Print login page */ mg_printf(conn, "HTTP/1.1 200 OK\r\n" "content-Type: text/html\r\n\r\n" "<!DOCTYPE HTML>\r\n" "<html>\r\n" "<head>\r\n" "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\r\n" "<title>POST Message to MobileShare!</title>\r\n" "</head>\r\n" "<body>\r\n" "<form action=\"bbs\" method=\"post\" enctype =\"multipart/form-data\" runat=\"server\">\r\n" "<textarea name=\"msg\" rows=\"2\" cols=\"20\" id=\"msg\" style=\"background-color:White;border-color:#C0C0FF;border-width:1px;border-style:Solid;height:93px;width:445px;\"></textarea><br>\r\n" "<input type=\"submit\" name=\"Button\" value=\"Send\" id=\"Button\" />\r\n" "</form>\r\n" "</body>\r\n" "</html>"); }