Beispiel #1
0
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;
    }
}
Beispiel #2
0
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
        );
}
Beispiel #3
0
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);
        }
    };
}
	void ouroboros_server::handle_group_rest(const rest_request& aRequest)
	{
		//get reference to named thing
		group<var_field> *pgroup = mStore.get(normalize_group(aRequest.getGroups()));

		std::string sjson;
		mg_connection *conn = aRequest.getConnection();
		if (pgroup)
		{
			switch (aRequest.getHttpRequestType())
			{
				case GET:
					//Send JSON describing named item
					sjson = pgroup->getJSON();
					break;

				default:
					sjson = detail::bad_JSON(conn);
			}
		}
		else
		{
			sjson = detail::bad_JSON(conn);
		}

		mg_send_data(conn, sjson.c_str(), sjson.length());
	}
Beispiel #5
0
static void send_index_page(struct mg_connection *conn) {
  const char *data;
  int data_len;
  char var_name[100], file_name[100];

  mg_printf_data(conn, "%s",
                 "<html><body>Upload example."
                 "<form method=\"POST\" action=\"/handle_post_request\" "
                 "  enctype=\"multipart/form-data\">"
                 "<input type=\"file\" name=\"file\" /> <br/>"
                 "<input type=\"submit\" value=\"Upload\" />"
                 "</form>");

  if (mg_parse_multipart(conn->content, conn->content_len,
                         var_name, sizeof(var_name),
                         file_name, sizeof(file_name),
                         &data, &data_len) > 0) {

    mg_printf_data(conn, "%s", "Uploaded file:<pre>");
    mg_send_data(conn, data, data_len);
    mg_printf_data(conn, "%s", "/pre>");
  }

  mg_printf_data(conn, "%s", "</body></html>");
}
Beispiel #6
0
static int handle_health(struct mg_connection *conn)
{
    send_headers(conn);
    char health[4] = {(char)0xF0, (char)0x9F, (char)0x91, (char)0xBB};
    mg_send_data(conn, health, 4);
    return MG_TRUE;
}
	void ouroboros_server::handle_callback_rest(const rest_request& aRequest)
	{
		//get reference to named thing
		std::string resource = normalize_group(aRequest.getGroups()) + '/' + aRequest.getFields();
		var_field *named = mStore.get(normalize_group(aRequest.getGroups()), aRequest.getFields());

		std::string response;
		mg_connection *conn = aRequest.getConnection();
		if (named)
		{
			switch (aRequest.getHttpRequestType())
			{
				case POST:
				{
					std::string data(conn->content, conn->content_len);
					JSON json(data);

					std::string response_url = json.get("callback");

					//create callback

					//Due to a limitation of C++03, use a semi-global map
					//to track response URLs
					mResponseUrls[named] = response_url;
					std::string callback_id = register_callback(aRequest.getGroups(), aRequest.getFields(), establish_connection);

					std::stringstream ss;
					ss << "{ \"id\" : \"" << callback_id << "\" }";
					mg_send_status(conn, 201);
					response = ss.str();
				}
					break;

				//TODO DELETE is not supported by the underlying mechanism
				/*case DELETE:
				{
					
					//Send JSON describing named item
					std::string data(conn->content, conn->content_len);
					JSON json(data);

					std::string id = json.get("id");
					unregister_callback(id);
					response = detail::good_JSON();
				}*/
					break;

				default:
					response = detail::bad_JSON(conn);
			}
		}
		else
		{
			response = detail::bad_JSON(conn);
		}

		mg_send_data(conn, response.c_str(), response.length());
	}
Beispiel #8
0
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 httpserver_ev_handler(struct mg_connection *conn, enum mg_event ev) {
	if (ev == MG_REQUEST) {
		//mg_send_header(conn, "Content-Type", "text/plain");
		//mg_printf_data(conn, "This is a reply from server instance # %s", (char *)conn->server_param);
		if (PaymentVerifyModule.OnChargeFromSWServer(conn)) {
			mg_send_data(conn, "0", 1);
		}
		else {
			mg_send_data(conn, "1", 1);
		}

		return MG_TRUE;
	}
	else if (ev == MG_AUTH) {
		return MG_TRUE;
	}
	else {
		return MG_FALSE;
	}
}
Beispiel #10
0
static void lsp(struct mg_connection *conn, const char *p, int len, lua_State *L) {
	int i, j, pos = 0;
	for (i = 0; i < len; i++) {
	if (p[i] == '<' && p[i + 1] == '?') {
		for (j = i + 1; j < len ; j++) {
		if (p[j] == '?' && p[j + 1] == '>') {
			if (i-pos!=0) mg_send_data(conn, p + pos, i - pos);
			if (luaL_loadbuffer(L, p + (i + 2), j - (i + 2), "") == 0) {
			lua_pcall(L, 0, LUA_MULTRET, 0);
			}
			pos = j + 2;
			i = pos - 1;
			break;
		}
		}
	}
	}
	if (i > pos) {
	mg_send_data(conn, p + pos, i - pos);
	}
}
Beispiel #11
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);
}
Beispiel #12
0
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);
}
Beispiel #13
0
static int event_handler(struct mg_connection *conn) {

	mg_send_data(conn, "test success", strlen("test success"));
	std::cout << conn->uri << std::endl;

	std::string strUri = conn->uri;
	strUri.erase(0, strUri.find("/callPython/") + sizeof("/callPython/") - 1);
	std::cout << strUri.c_str() << std::endl;

	std::string strCmd = "python ";
	strCmd += strUri;
	system(strCmd.c_str());
	return 0;
}
Beispiel #14
0
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;
  }
}
Beispiel #15
0
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();
    };
}
Beispiel #16
0
int webserver_request_handler(struct mg_connection* conn, enum mg_event ev)
{
	if (ev == MG_REQUEST)	{
		/* check ajax json requests
		 * else just send the file to the client */
		if (strstr(conn->uri, AJAX_HEADER) == conn->uri)	{
			char param1[64];
			char param2[64];

			const char* cmd = conn->uri + strlen(AJAX_HEADER);

			/* read POST data for parameters */
			mg_get_var(conn, "p1", param1, sizeof(param1));
			mg_get_var(conn, "p2", param2, sizeof(param2));

			webserver_runajax(conn, cmd, param1, param2);
		}	else	{
			/* set default 'index.html' for urls with no file references */
			char path[DH_PATH_MAX];
            strcpy(path, WEB_ROOTDIR);
            strcat(path, conn->uri);
			if (util_pathisdir(path))	{
				if (path[strlen(path)-1] != '/')
					strcat(path, "/index.html");
				else
					strcat(path, "index.html");
			}

			/* send back the file to the client */
            file_t f = fio_openmem(mem_heap(), path, FALSE, MID_PRF);
            if (f != NULL)  {
                size_t size;
                void* data = fio_detachmem(f, &size, NULL);
                mg_send_data(conn, data, (uint)size);
                fio_close(f);
            }   else {
                mg_send_status(conn, 404);
            }

		}

        return MG_TRUE;
	}

    return MG_FALSE;
}
Beispiel #17
0
static int lua_write(lua_State *L) {
	int i, num_args;
	const char *str;
	size_t size;
	struct mg_connection *conn = (struct mg_connection *)
	lua_touserdata(L, lua_upvalueindex(1));

	num_args = lua_gettop(L);
	for (i = 1; i <= num_args; i++) {
	if (lua_isstring(L, i)) {
		str = lua_tolstring(L, i, &size);
		mg_send_data(conn, str, size);
	}
	}

	return 0;
}
Beispiel #18
0
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();
}
Beispiel #19
0
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 ouroboros_server::handle_name_rest(const rest_request& aRequest)
	{
		//get reference to named thing
		var_field *named = mStore.get(normalize_group(aRequest.getGroups()), aRequest.getFields());

		std::string sjson;
		mg_connection *conn = aRequest.getConnection();
		if (named)
		{
			switch (aRequest.getHttpRequestType())
			{
				case PUT:
				{
					std::string data(conn->content, conn->content_len);
					JSON json(data);

					if (named->setJSON(json))
					{
						handle_notification(aRequest.getGroups(), aRequest.getFields());
						sjson = detail::good_JSON();
					}
					else
					{
						sjson = detail::bad_JSON(conn);
					}
				}
					break;

				case GET:
					//Send JSON describing named item
					sjson = named->getJSON();
					break;

				default:
					sjson = detail::bad_JSON(conn);
			}
		}
		else
		{
			sjson = detail::bad_JSON(conn);
		}

		mg_send_data(conn, sjson.c_str(), sjson.length());
	}
Beispiel #21
0
static int web_handler(struct mg_connection *conn)
{
    struct mg_context *ctx = conn->server_param;
    lua_State *L = ctx->vm;

    lua_rawgeti(L, LUA_REGISTRYINDEX , ctx->callbackweb);
    web_param(L, conn);

    lua_pcall(L, 1, 1, 0);
    if(lua_isnoneornil(L, -1))
    {
        return -1;
    }

    size_t len;
    const char* ret = luaL_tolstring(L, -1, &len);
    mg_send_data(conn,ret,len);
    return 0;
}
Beispiel #22
0
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;
	}
}
Beispiel #23
0
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;
}
Beispiel #24
0
// 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;
}
Beispiel #25
0
static int index_html(struct mg_connection *conn) {
  FILE *fp = (FILE *) conn->connection_param;
  char buf[200];
  size_t n = 0;

  if (fp == NULL) {
    fp = fopen("../mongoose.c", "r");
    conn->connection_param = (void *) fp;
  }

  if (fp != NULL) {
    n = fread(buf, 1, sizeof(buf), fp);
    mg_send_data(conn, buf, n);

    if (n < sizeof(buf) || conn->wsbits != 0) {
      fclose(fp);
      conn->connection_param = NULL;
    }
  }

  return n < sizeof(buf) ? 1 : 0;
}
Beispiel #26
0
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);
}
Beispiel #27
0
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));
  }
}
Beispiel #28
0
int UHTTPAdmin::MGHandler(mg_connection* conn, enum mg_event ev)
{
	if (ev == MG_AUTH)
	{
		return MG_TRUE;   // Authorize any requests
	}
	else if (ev == MG_REQUEST) // Something was requested
	{
		// Determin if this is a Lobby or Dedi server
		// Create a new object of given type
		// Call ProcessRequest
		// Call JSON return
		// Send return back to client

		// Get a reference of any object using the UTBaseGameMode
		AUTBaseGameMode* BaseGameMode;
		BaseGameMode = Cast<AUTBaseGameMode>(GWorld->GetAuthGameMode());

		// Are we a Lobby server?
		if (BaseGameMode->IsLobbyServer())
		{
			// Yes, get a reference to the lobby 
			AUTLobbyGameMode* LobbyGameMode = GWorld->GetAuthGameMode<AUTLobbyGameMode>();
			if (LobbyGameMode)
			{
				// Create a new object
				HTTPAdminLobby* HTTPLobby = new HTTPAdminLobby;
				// set GameMode
				HTTPLobby->SetGameMode(LobbyGameMode);
				// set Connection
				HTTPLobby->SetConnection(conn);
				// set World

				// IF object->ProcessRequest()
				// Call JSON return
				// else
				// return MG_FALSE; // Nothing for us to process here, hand back to Mongoose to surve page/image

				if (HTTPLobby->ProcessRequest())
				{
					FString ReturnData = HTTPLobby->GetJSONReturn();

					//FString ReturnData = FString::Printf(TEXT("%.*s"), (int)conn->content_len, conn->content);
					//FString ReturnData2 = FString::Format("%.*s", (int)conn->content_len, (char*)conn->content);
					//FString ReturnData2 = FString::ChrN((int)conn->content_len, (char*)conn->content);
					//strncpy(ReturnData, ANSI_TO_TCHAR(conn->content), (int)conn->content_len);
					//mg_printf_data(conn, "%.*s", (int)conn->content_len, (char*)conn->content);
					//Wokring
					//FString HelloWorld = TEXT("Hello World: ") + FString::FromInt(sizeof((char*)conn->content)) + TEXT(" -");
					//mg_send_header(conn, "Content-Type", "application/json");
					//mg_send_data(conn, conn->content, conn->content_len);
					//mg_send_data(conn, "", 0);


					mg_send_header(conn, "Content-Type", "application/json");
					mg_send_data(conn, TCHAR_TO_ANSI(*ReturnData), ReturnData.Len());
					mg_send_data(conn, "", 0);

					return MG_TRUE;
				}
				else
				{
					return MG_FALSE; // Nothing for us to process here, hand back to Mongoose to surve page/image
				} // Process request

			} // game lobby
			else
			{
				// Umm error, we're not a lobby server
			} // game lobby
		}
		else
		{
			// Nope, we must be a dedi server

			AUTGameMode* GameMode = GWorld->GetAuthGameMode<AUTGameMode>();
			if (GameMode)
			{
				// Create a new object passing the connection
				HTTPAdminDedi* HTTPDedi = new HTTPAdminDedi(conn);

				// Call ProcessRequest
				if (HTTPDedi->ProcessRequest())
				{
					FString ReturnData = HTTPDedi->GetJSONReturn();

					mg_send_header(conn, "Content-Type", "application/json");
					mg_send_data(conn, TCHAR_TO_ANSI(*ReturnData), ReturnData.Len());
					mg_send_data(conn, "", 0);

					return MG_TRUE;
				}
				else
				{
					return MG_FALSE; // Nothing for us to process here, hand back to Mongoose to surve page/image

				} // Process request
			
			}
			else
			{
				// Umm error, we are not a dedi server
			}

		}



		// Send return back to client

		return MG_TRUE;

		
	}// request

	return MG_FALSE; // Nothing for us to process here, hand back to Mongoose to surve page/image
}
Beispiel #29
0
bool send_jpg(const mg_connection& connection,const std::string& jpg)
{
	return mg_send_data((mg_connection*)&connection,jpg.data(),jpg.size())>=0;
}
Beispiel #30
0
static int request(struct mg_connection *mc) {
	size_t edata_size=0;
	const char *edata_data;
	char *free_buf = NULL;

	if (mc->is_websocket) {
		// This handler is called for each incoming websocket frame, one or more
		// times for connection lifetime.
		char *s = mc->content;
		int sl = mc->content_len;
		//printf("WEBSOCKET: len %d uri <%s>\n", sl, mc->uri);
		if (sl == 0) {
			//printf("----KA %d\n", mc->remote_port);
			return MG_TRUE;	// keepalive?
		}
		
		conn_t *c = rx_server_websocket(mc);
		if (c == NULL) return MG_FALSE;
		if (c->stop_data) return MG_FALSE;
		
		s[sl]=0;
		//printf("WEBSOCKET: %d <%s> ", sl, s);
		nbuf_allocq(&c->w2a, s, sl);
		
		if (mc->content_len == 4 && !memcmp(mc->content, "exit", 4)) {
			//printf("----EXIT %d\n", mc->remote_port);
			return MG_FALSE;
		} else {
			return MG_TRUE;
		}
	} else {
		if (strcmp(mc->uri, "/") == 0) mc->uri = "index.html"; else
		if (mc->uri[0] == '/') mc->uri++;
		
		char *ouri = (char *) mc->uri;
		char *uri = ouri;
		bool free_uri = FALSE;
		
		if (strncmp(ouri, "wrx/", 4) == 0) {
			uri = (char *) &mc->uri[4];
		} else {
			user_iface_t *ui = find_ui(mc->local_port);
			// should never not find match since we only listen to ports in ui table
			assert(ui);
			asprintf(&uri, "%s/%s", ui->name, ouri);
			free_uri = TRUE;
		}
		//printf("---- HTTP: uri %s (%s)\n", ouri, uri);

		// try as file from in-memory embedded data
		edata_data = edata(uri, &edata_size, &free_buf);
		
		// try as request from browser
		if (!edata_data) {
			free_buf = (char*) wrx_malloc("req", NREQ_BUF);
			edata_data = rx_server_request(mc, free_buf, &edata_size);	// mc->uri is ouri without ui->name prefix
			if (!edata_data) { wrx_free("req", free_buf); free_buf = NULL; }
		}

		if (!edata_data) {
			printf("unknown URL: %s (%s) %s\n", ouri, uri, mc->query_string);
			return MG_FALSE;
		}
		
		// for index.html process %[substitution]
		if (strcmp(ouri, "index.html") == 0) {
			static bool index_init;
			static char *index_html, *index_buf;
			static size_t index_size;

#ifdef EDATA_EMBED
			if (!index_init) {		// only have to do once
#else
			if (true) {		// file might change anytime during development
#endif
				if (!index_buf) index_buf = (char*) wrx_malloc("index_buf", edata_size*3/2);
				char *cp = (char*) edata_data, *np = index_buf, *pp;
				int i, cl, sl, nl=0, pl;

				for (cl=0; cl < edata_size;) {
					if (*cp == '%' && *(cp+1) == '[') {
						cp += 2; cl += 2; pp = cp; pl = 0;
						while (*cp != ']' && cl < edata_size) { cp++; cl++; pl++; }
						cp++; cl++;
						for (i=0; i < ARRAY_LEN(index_html_params); i++) {
							index_html_params_t *ip = &index_html_params[i];
							if (strncmp(pp, ip->param, pl) == 0) {
								sl = strlen(ip->value);
								strcpy(np, ip->value); np += sl;
								break;
							}
						}
						if (i == ARRAY_LEN(index_html_params)) {
							// not found, put back original
							strcpy(np, "%["); np += 2;
							strncpy(np, pp, pl); np += pl;
							*np++ = ']';
						}
					} else {
						*np++ = *cp++; cl++;
					}
				}
				
				index_html = index_buf;
				index_size = np - index_buf;
				index_init = true;
			}
			edata_data = index_html;
			edata_size = index_size;
		}

		//printf("DATA: %s %d ", mc->uri, (int) edata_size);
		mg_send_header(mc, "Content-Type", mg_get_mime_type(mc->uri, "text/plain"));
		mg_send_data(mc, edata_data, edata_size);
		
		if (free_uri) free(uri);
		if (free_buf) wrx_free("req", free_buf);
		
		http_bytes += edata_size;
		return MG_TRUE;
	}
}

static int ev_handler(struct mg_connection *mc, enum mg_event ev) {
  int r;
  
  //printf("ev_handler %d:%d len %d ", mc->local_port, mc->remote_port, (int) mc->content_len);
  if (ev == MG_REQUEST) {
  	//printf("MG_REQUEST: URI:%s query:%s\n", mc->uri, mc->query_string);
    r = request(mc);
    //printf("\n");
    return r;
  } else
  if (ev == MG_AUTH) {
  	//printf("MG_AUTH\n");
    return MG_TRUE;
  } else {
  	//printf("MG_OTHER\n");
    return MG_FALSE;
  }
}