static void reject_req(struct mg_connection *conn, int result) { char resp[500]; send_headers(conn); // Return a please go away message snprintf(resp, sizeof(resp), ((strstr(conn->uri, "://") == NULL)? "<html><head><meta name='google-site-verification' content='sdVLgoSVNvwkjzJEwKUVFlbBuQY-n2HBoUzlHPBWGN8' /><title>Page not found</title></head><body><p>This page you requested '%s' does not exist</p></body></html>" : "<html><head><meta name='google-site-verification' content='sdVLgoSVNvwkjzJEwKUVFlbBuQY-n2HBoUzlHPBWGN8' /><title>This is not a proxy</title></head><body><p>This is not an open proxy. Your IP address %s has been banned</p></body></html>"), conn->remote_ip); // Handle invalid method if (result == 501) snprintf(resp, sizeof(resp), "<html><head><title>No Supported</title></head><body><h1>501 Not Supported</h1><p>Method '%s' is not supported by this server</p></body></html>", conn->request_method); // Send result mg_send_status(conn, result); // Compute a message len and return a Content-Length header char lenStr[10]; mg_send_header(conn, "Content-Language", "en"); int len = strlen(resp); snprintf(lenStr, 10, "%d", len); mg_send_header(conn, "Content-Length", lenStr); // Return the rejection message mg_printf_data(conn, resp, conn->uri); }
static void checkip_letsencrypt(struct mg_connection *conn) { const char* remote_ip = conn->remote_ip; mg_send_header(conn, "Host", HOSTNAME); mg_send_header(conn, "Server", "wsadmin-CheckIP/" VERSION); mg_send_header(conn, "Content-Type", "text/plain; charset=ascii"); if (strcmp(conn->uri, letsencrypt_req) == 0) { char lenStr[10]; snprintf(lenStr, 10, "%d", strlen(letsencrypt_resp)); mg_send_header(conn, "Content-Length", lenStr); mg_printf_data(conn, letsencrypt_resp); log_msg(daemon_mode, "letsencrypt challenge received from %s response '%s'", remote_ip, letsencrypt_resp); } else { char *resp = "** Invalid LetsEncrypt Challenge **\r\nExpected: '%s'\r\nReceived: '%s'\r\n"; char buff[500]; char lenStr[10]; snprintf(buff, 500, resp, letsencrypt_req, conn->uri); mg_send_status(conn, 404); snprintf(lenStr, 10, "%d", strlen(buff)); mg_send_header(conn, "Content-Length", lenStr); mg_printf_data(conn, buff); log_msg(daemon_mode, "incorrect letsencrypt challenge received from %s", remote_ip); log_msg(daemon_mode, "received '%s', expected '%s'", conn->uri, letsencrypt_req); } }
static void send_headers(struct mg_connection* conn) { mg_send_header(conn, "Content-Type", "application/json"); static const char kszFormat[] = "ddd, dd MMM yyyy HH:mm:ss 'GMT'"; QDateTime now = QDateTime::currentDateTime(); mg_send_header(conn, "Date", now.toString(kszFormat).toLocal8Bit().constData()); mg_send_header(conn, "Server", QString("%1 %2").arg(ICHABOD_NAME).arg(ICHABOD_VERSION).toLocal8Bit().constData()); }
static int ev_handler(struct mg_connection *conn, enum mg_event ev) { char buffer[Tbuffer]; buffer[0] = '\x0'; FILE *arq; char ch; int x; switch (ev) { case MG_AUTH: return MG_MORE; case MG_REQUEST: mg_send_header(conn, "Content-Type", "text/html"); char index[] ="web/index.html"; arq = fopen(index, "r"); if (arq == NULL) { printf("Error 404 - Página não encontrada\n"); } else { for (x = 0; (ch = fgetc(arq)) != EOF && x < Tbuffer; x++) { buffer[x] = ch; } fclose(arq); } mg_printf_data(conn, buffer); return MG_TRUE; default: return MG_FALSE; } }
int WebController::HandleApiRequest(struct mg_connection *conn) { if (conn->content == NULL) { //Content is NULL if request method is GET debug("GET is not supported."); return MG_FALSE; } int result; char **ap, *argv[3], *input, *tofree; tofree = input = strdup(conn->uri); // should check for NULL for (ap = argv; (*ap = strsep(&input, "/")) != NULL;) if (**ap != '\0') if (++ap >= &argv[3]) break; if (!strcmp("api", argv[0])) { debug("%s/%s/%s\n", argv[0],argv[1],argv[2]); result = HandleJsonRequest(conn,argv[1],argv[2]); } else { mg_send_header(conn, "Content-Type", "text/plain"); mg_printf_data(conn, "KMotionCNC API # query_string %s\n", (char *) conn->query_string); mg_printf_data(conn, "KMotionCNC API # uri %s\n", (char *) tofree); result = MG_TRUE; } free(tofree); return result; }
void apollo::upload_item_image( hades::connection& conn, mg_connection *mg_conn, const int item_id, atlas::http::uri_callback_type callback_success, atlas::http::uri_callback_type callback_failure ) { upload_file( conn, mg_conn, "attachment_title", "attachment_data", [&conn, mg_conn, callback_success, item_id](attachment a) { insert_attachment(a, conn); image_of iof; iof.get_int<attr::attachment_id>() = a.info.get_int<attr::attachment_id>(); iof.get_int<attr::item_id>() = item_id; iof.insert(conn); // Send details of the attachment. auto r = atlas::http::json_response(a.info); mg_send_status(mg_conn, 200); mg_send_header(mg_conn, "Content-type", "text/json"); mg_send_data(mg_conn, r.data.c_str(), r.data.length()); callback_success(); }, callback_failure ); }
atlas::http::uri_type atlas::http::detail::make_async(uri_function_type f) { return [f]( mg_connection *conn, uri_parameters_type match, uri_callback_type success, uri_callback_type failure ) { try { response r = f(match); mg_send_status(conn, r.status_code); for(std::pair<std::string, std::string> header : r.headers) mg_send_header(conn, header.first.c_str(), header.second.c_str()); mg_send_data(conn, r.data.c_str(), r.data.length()); success(); } catch(const http::exception& e) { log::error("atlas::http::detail::make_async") << "exception returned to client: " << e.what(); error(e.code(), e.what(), conn, success, failure); } catch(const std::exception& e) { log::error("atlas::http::detail::make_async") << "exception not returned to client: " << e.what(); // There was an exception while processing the request; we don't // want to provide further information to the client. error(500, "unknown error", conn, success, failure); } }; }
static int ev_handler(struct mg_connection *conn, enum mg_event ev) { const char **file_names = (const char **) conn->server_param; struct conn_state *state; time_t now = time(NULL); switch (ev) { case MG_AUTH: return MG_TRUE; case MG_REQUEST: if (strcmp(conn->uri, "/stream") != 0) { printf("stream\n"); mg_send_header(conn, "Content-Type", "text/html"); mg_printf_data(conn, "%s", "Go to <a href=/stream>/stream</a> for MJPG stream"); return MG_TRUE; } printf("%s\n", conn->uri ); mg_printf(conn, "%s", "HTTP/1.0 200 OK\r\n" "Cache-Control: no-cache\r\n" "Pragma: no-cache\r\nExpires: Thu, 01 Dec 1994 16:00:00 GMT\r\n" "Connection: close\r\nContent-Type: multipart/x-mixed-replace; " "boundary=--w00t\r\n\r\n"); send_file(conn, file_names[0]); state = (struct conn_state *) malloc(sizeof(*state)); conn->connection_param = state; state->file_index = 1; // First file is already sent state->last_poll = time(NULL); return MG_MORE; case MG_POLL: state = (struct conn_state *) conn->connection_param; if (state != NULL && now > state->last_poll) { printf("Polling\n"); printf("%s\n", conn->uri ); if (file_names[state->file_index] != NULL) { send_file(conn, file_names[state->file_index]); state->file_index++; if (file_names[state->file_index] == NULL) { return MG_TRUE; // No more images, close connection } } state->last_poll = now; } return MG_FALSE; case MG_CLOSE: free(conn->connection_param); conn->connection_param = NULL; return MG_FALSE; default: return MG_FALSE; } }
void atlas::http::static_text( const std::string& mimetype, const std::string& content, mg_connection *conn, uri_parameters_type, http::uri_callback_type success, http::uri_callback_type error ) { mg_send_status(conn, 200); mg_send_header(conn, "Connection", "close"); mg_send_header(conn, "Content-Type", mimetype.c_str()); mg_send_data(conn, content.c_str(), content.length()); success(); }
int lcTemplateSend(struct mg_connection *conn,struct lcTemplate *tpl){ //mg_send_status(conn, 200); mg_send_header(conn, "Content-type", "text/html;charset=utf-8"); _lcTemplateProcess(tpl); mg_printf_data(conn,tpl->sText); return 1; }
void render(mg_connection* conn, string cookie, int id){ // string url(conn->uri); // vector<string> tmp = cc_split(url, "/"); // if(tmp.size() != 3){ // views::info::render(conn, "Error"); // return; // } // cclong id = atol(tmp[tmp.size() - 1].c_str()); cck_send_ssid(conn, cookie); mg_send_header(conn, "charset", "utf-8"); mg_send_header(conn, "Content-Type", "text/html"); mg_send_header(conn, "cache-control", "private, max-age=0"); templates.invoke("site_header").toggle("success_post_page").pipe_to(conn).destory(); templates.invoke("info_page").var("THREAD_NO", id).toggle("return_page").pipe_to(conn).destory(); templates.invoke("site_footer").var("TIME", 0).pipe_to(conn).destory(); }
int ev_handler(struct mg_connection *conn, enum mg_event ev) { switch (ev) { case MG_AUTH: return MG_TRUE; case MG_REQUEST: { //mg_printf_data(conn, "Hello! Requested URI is [%s]", conn->uri); info("Requested URI:REQ is [%s]:[%s]", conn->uri, conn->request_method); mg_send_header(conn, "Content-Type", "application/json"); json_t* jobj_req = NULL; json_error_t jerror; if (cmpuri(conn->request_method,"POST")){ jobj_req = json_loadb(conn->content, conn->content_len, 0, &jerror); if (!jobj_req){ mg_printf_data(conn,"json error on line %d: %s\n", jerror.line, jerror.text); mg_send_status(conn, 400); info("error parsing json POST, json error on line %d: %s\n", jerror.line, jerror.text); return MG_TRUE; } } json_t* jobj_resp = json_object(); int status = 404; //allow handler to choose response status status = root_handler(conn, jobj_req, jobj_resp); //free request if (jobj_req){ json_decref(jobj_req); jobj_req = NULL; } //dump response char * jstr = json_dumps(jobj_resp, 0); json_decref(jobj_resp); jobj_resp = NULL; if (status == 404){ char* errmsg = "{\"error\":\"No handler for URI found.\"}"; mg_send_data(conn, errmsg, strlen(errmsg)); mg_send_status(conn, 404); } else { mg_send_data(conn, jstr, strlen(jstr)); mg_send_status(conn, status); } free(jstr); return MG_TRUE; } default: return MG_FALSE; } }
static int lua_header(lua_State *L) { struct mg_connection *conn = (struct mg_connection *) lua_touserdata(L, lua_upvalueindex(1)); const char *header = luaL_checkstring(L,1); const char *value = luaL_checkstring(L,2); mg_send_header(conn, header, value); return 0; }
static void effects_get(struct mg_connection* conn) { int len; settings_load(); len = effects_json(work_buf, sizeof(work_buf)); mg_send_header(conn, CONTENT_TYPE, CONTENT_TYPE_JSON); mg_send_status(conn, 200); mg_send_data(conn, work_buf, len); }
static int ev_handler(struct mg_connection *conn, enum mg_event ev) { switch (ev) { case MG_AUTH: return MG_TRUE; case MG_REQUEST: mg_send_header(conn, "Content-Type", "text/html; charset=utf-8"); mg_printf_data(conn, "👊 I know kung fu 👊\n"); return MG_TRUE; default: return MG_FALSE; } }
int stats_json(struct mg_connection *conn){ json_object *stats_json = NULL; char *stats_string = NULL; stats_json = get_stats_json(); stats_string = (char *) json_object_to_json_string(stats_json); mg_send_header(conn, "Content-Type", "application/json; charset=utf-8"); mg_send_header(conn, "Cache-Control", "no-cache"); mg_send_data( conn, stats_string, strlen(stats_string) ); json_object_put(stats_json); return MG_REQUEST_PROCESSED; }
static void settings_post(struct mg_connection* conn) { int rc; int len; char buf[256]; settings_load(); len = mg_get_var(conn, BRIGHTNESS, buf, sizeof(buf)); if (len > 0) { settings.brightness = strtol(buf, NULL, 10); } len = mg_get_var(conn, MANUAL_TICK, buf, sizeof(buf)); if (len > 0) { settings.manual_tick = strtol(buf, NULL, 10); } len = mg_get_var(conn, IDLE_INTERVAL, buf, sizeof(buf)); if (len > 0) { settings.idle_interval = strtol(buf, NULL, 10); } len = mg_get_var(conn, MANUAL_TOGGLE, buf, sizeof(buf)); if (len > 0) { settings.manual_toggle = strtol(buf, NULL, 10); } len = mg_get_var(conn, SCREEN_SAVER_TOGGLE, buf, sizeof(buf)); if (len > 0) { settings.screen_saver_toggle = strtol(buf, NULL, 10); } len = mg_get_var(conn, ALPHA, buf, sizeof(buf)); if (len > 0) { settings.alpha = strtol(buf, NULL, 10); } rc = settings_save(); if (rc) { mg_printf_data(conn, "Could not save " SETTINGS_FILE); mg_send_status(conn, 500); return; } len = settings_json(work_buf, sizeof(work_buf)); mg_send_header(conn, CONTENT_TYPE, CONTENT_TYPE_JSON); mg_send_status(conn, 200); mg_send_data(conn, work_buf, len); }
static int expire_metric(struct mg_connection *conn) { struct brubeck_server *server = conn->server_param; struct brubeck_metric *metric = safe_lookup_metric( server, conn->uri + strlen("/expire/")); if (metric) { metric->expire = BRUBECK_EXPIRE_DISABLED; mg_send_status(conn, 200); mg_send_header(conn, "Connection", "close"); return MG_TRUE; } return MG_FALSE; }
static void send_headers(struct mg_connection *conn) { // Prevent proxies and browsers from caching response, also include some security headers mg_send_header(conn, "Cache-Control", "max-age=0, post-check=0, pre-check=0, no-store, no-cache, must-revalidate"); mg_send_header(conn, "Pragma", "no-cache"); mg_send_header(conn, "Host", HOSTNAME); mg_send_header(conn, "Content-Type", "text/html; charset=utf8"); mg_send_header(conn, "X-Frame-Options", "DENY"); mg_send_header(conn, "Server", "wsadmin-CheckIP/" VERSION); }
atlas::http::uri_type atlas::http::detail::make_async_with_conn(conn_uri_function_type f) { return [f]( mg_connection *conn, uri_parameters_type match, uri_callback_type success, uri_callback_type failure ) { response r = f(conn, match); mg_send_status(conn, r.status_code); for(std::pair<std::string, std::string> header : r.headers) mg_send_header(conn, header.first.c_str(), header.second.c_str()); mg_send_data(conn, r.data.c_str(), r.data.length()); success(); }; }
static int index_html(struct mg_connection *conn) { size_t index_size; const char *index_html = find_embedded_file("websocket.html", &index_size); if (conn->is_websocket) { // This handler is called for each incoming websocket frame, one or more // times for connection lifetime. // Echo websocket data back to the client. mg_websocket_write(conn, 1, conn->content, conn->content_len); return conn->content_len == 4 && !memcmp(conn->content, "exit", 4) ? MG_CLIENT_CLOSE : MG_CLIENT_CONTINUE; } else { mg_send_header(conn, "Content-Type", "text/html"); mg_send_data(conn, index_html, index_size); return MG_REQUEST_PROCESSED; } }
static void effects_post_reply(struct mg_connection* conn) { int rc; int len; rc = settings_save(); if (rc) { mg_printf_data(conn, "Could not save " SETTINGS_FILE); mg_send_status(conn, 500); return; } len = effects_json(work_buf, sizeof(work_buf)); mg_send_header(conn, CONTENT_TYPE, CONTENT_TYPE_JSON); mg_send_status(conn, 200); mg_send_data(conn, work_buf, len); }
void Response::Send(struct mg_connection* conn) const { mg_send_status(conn, status_code_); if (!headers_.empty()) { HeaderMap::const_iterator itr = headers_.begin(); HeaderMap::const_iterator end = headers_.end(); for (; itr != end; ++itr) { mg_send_header(conn, (itr->first).c_str(), (itr->second).c_str()); } } if (data_.empty()) { mg_send_data(conn, 0, 0); } else { mg_send_data(conn, data_.c_str(), data_.length()); } }
static int web_SockJsServer_request(struct mg_connection *conn, enum mg_event ev) { int result = MG_TRUE; web_SockJsServer _this = web_SockJsServer(conn->server_param); switch (ev) { case MG_AUTH: break; case MG_WS_CONNECT: /* Send open message fast since SockJS uses this to determine latency */ mg_websocket_printf(conn, WEBSOCKET_OPCODE_TEXT, "o"); web_SockJsServer_open(_this, conn); break; case MG_CLOSE: web_SockJsServer_close(_this, conn); break; case MG_REQUEST: if (conn->is_websocket) { web_SockJsServer_message(_this, conn); } else { if (!strcmp(conn->uri, "/sockjs/info")) { mg_send_header(conn, "Access-Control-Allow-Origin", "*"); mg_printf_data( conn, "{\"websocket\":true,\"origins\":[\"*:*\"],\"cookie_needed\":false,\"entropy\":%u}", 10000000000 * rand()); } } break; case MG_HTTP_ERROR: result = MG_FALSE; break; case MG_POLL: result = MG_FALSE; break; case MG_CONNECT: case MG_WS_HANDSHAKE: case MG_REPLY: case MG_RECV: result = MG_FALSE; break; } return result; }
static void checkip_req(struct mg_connection *conn) { send_headers(conn); // Return the remote ipaddr char resp[500]; char* location; location = (char*)malloc(500); lookupCountry(conn->remote_ip, &location, sizeof(location)); //log_msg(daemon_mode, "IP addr = %s Location = %s", conn->remote_ip, location); //strcpy(location, "unknown"); snprintf(resp, sizeof(resp), "<html><head><meta name=\"google-site-verification\" content=\"sdVLgoSVNvwkjzJEwKUVFlbBuQY-n2HBoUzlHPBWGN8\" /><title>Current IP Check</title></head><body>Current IP Address: %s<br/>Geography: %s<br/><br/>This product includes GeoLite2 data created by MaxMind, available from <a href=\"http://www.maxmind.com\">http://www.maxmind.com</a></body></html>", conn->remote_ip, location); int len = strlen(resp); char lenStr[10]; snprintf(lenStr, 10, "%d", len); mg_send_header(conn, "Content-Length", lenStr); mg_printf_data(conn, resp); }
int CommManager::HttpMsgHandler( struct mg_connection *conn, enum mg_event ev ) { BOOL bValidData = FALSE; BOOL bNeedReply = FALSE; BOOL bHasRecv = FALSE; ByteBuffer buffer; int nOutSize = 0; LPBYTE pOutBuf = NULL; ByteBuffer toSendBuffer; SOCKADDR_IN addr = {0}; char szLength[255] = {0}; switch (ev) { case MG_AUTH: return MG_TRUE; case MG_REQUEST: if (strcmp(conn->request_method,"GET") == 0) { mg_printf_data(conn,"<h1>Website Buiding!</h1>"); return MG_TRUE; } addr.sin_addr.S_un.S_addr = inet_addr(conn->remote_ip); bNeedReply = CommManager::GetInstanceRef().HandleMessageAndReply(addr,(LPBYTE)conn->content , conn->content_len, COMMNAME_HTTP, bValidData, HTTP_COMM_REPLY_MAXSIZE, toSendBuffer); sprintf_s(szLength,"%d",toSendBuffer.Size()); mg_send_header(conn,"Content-Length",szLength); if (bNeedReply) mg_send_data(conn,toSendBuffer,toSendBuffer.Size()); return MG_TRUE; default: return MG_FALSE; } }
// output error and send error back to client static int send_error(struct mg_connection* conn, const char* err) { log(conn, err); mg_send_status(conn, 500); mg_send_header(conn, "X-Error-Message", err); Json::Value root; root["path"] = Json::Value(); root["elapsed"] = Json::Value(); root["conversion"] = false; root["output"] = Json::Value(); root["result"] = Json::Value(); root["warnings"] = Json::Value(); Json::Value js_errors; js_errors.append( err ); root["errors"] = js_errors; Json::StyledWriter writer; std::string json = writer.write(root); mg_send_data(conn, json.c_str(), json.length()); return MG_TRUE; }
static void on_reset(struct mg_connection* conn) { int rc; int len; LOG(("reset: %s\n", conn->uri)); settings_reset(); rc = settings_save(); if (rc) { mg_printf_data(conn, "Could not save " SETTINGS_FILE); mg_send_status(conn, 500); return; } len = settings_json(work_buf, sizeof(work_buf)); mg_send_header(conn, CONTENT_TYPE, CONTENT_TYPE_JSON); mg_send_status(conn, 200); mg_send_data(conn, work_buf, len); }
static int ev_handler(struct mg_connection *conn, enum mg_event ev) { char buffer[Tbuffer]; buffer[0] = '\x0'; switch (ev) { case MG_AUTH: return MG_MORE; case MG_REQUEST: mg_send_header(conn, "Content-Type", "text/html"); if(home(buffer, sizeof(buffer)) == 0){ return MG_FALSE; } mg_printf_data(conn, buffer); return MG_TRUE; default: return MG_FALSE; } }
static void send_reply(struct mg_connection *conn) { char var1[500], var2[500]; if (strcmp(conn->uri, "/handle_post_request") == 0) { // User has submitted a form, show submitted data and a variable value // Parse form data. var1 and var2 are guaranteed to be NUL-terminated mg_get_var(conn, "input_1", var1, sizeof(var1)); mg_get_var(conn, "input_2", var2, sizeof(var2)); // Send reply to the client, showing submitted form values. // POST data is in conn->content, data length is in conn->content_len mg_send_header(conn, "Content-Type", "text/plain"); mg_printf_data(conn, "Submitted data: [%.*s]\n" "Submitted data length: %d bytes\n" "input_1: [%s]\n" "input_2: [%s]\n", conn->content_len, conn->content, conn->content_len, var1, var2); } else { // Show HTML form. mg_send_data(conn, html_form, strlen(html_form)); } }