示例#1
0
inline bool handle_write(mg_connection* connection,const bool authenticated,const std::string& request,
	const std::string& query,const std::string& post_data)
{
	std::string comma_list=get_query(connection,"write");

	if(comma_list.size()>0)
	{
		auto& database=get_database(connection);
		std::cout<<"\tWriting \""<<comma_list<<"\"..."<<std::flush;

		if((database.permissions&P_WRITE)!=0||(authenticated&&database.allow_authentication()))
		{
			if(!database.write(comma_list,post_data))
			{
				mg_send_status(connection,"400 BAD REQUEST");
				std::cout<<"malformed."<<std::endl;
			}
			else
			{
				std::cout<<"done."<<std::endl;
			}
		}
		else
		{
			mg_send_status(connection,"401 UNAUTHORIZED");
			std::cout<<"denied."<<std::endl;
		}

		return true;
	}

	return false;
}
示例#2
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;
    }
}
示例#3
0
文件: web.c 项目: hmflash/tikitank
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);
}
示例#4
0
文件: checkip.c 项目: Papafox/checkip
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);
}
示例#5
0
文件: checkip.c 项目: Papafox/checkip
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);
    }
}
示例#6
0
文件: router.cpp 项目: jamesg/atlas
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);
        }
    };
}
示例#7
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
        );
}
示例#8
0
inline bool handle_read(mg_connection* connection,const bool authenticated,const std::string& request,
	const std::string& query)
{
	std::string comma_list=get_query(connection,"read");

	if(comma_list.size()>0)
	{
		auto& database=get_database(connection);
		std::cout<<"\tReading \""<<comma_list<<"\"..."<<std::flush;

		if((database.permissions&P_READ)!=0||(authenticated&&database.allow_authentication()))
		{
			mg_send(connection,database.read(comma_list),"application/json");
			std::cout<<"done."<<std::endl;
		}
		else
		{
			mg_send_status(connection,"401 UNAUTHORIZED");
			std::cout<<"denied."<<std::endl;
		}

		return true;
	}

	return false;
}
示例#9
0
	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());
	}
示例#10
0
文件: web.c 项目: hmflash/tikitank
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);
}
示例#11
0
文件: web.c 项目: hmflash/tikitank
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);
}
示例#12
0
void webserver_runajax(struct mg_connection* conn, const char* cmd, const char* param1,
		const char* param2)
{
	pfn_ajax_cmd cmd_fn = prf_find_cmd(cmd);
	if (cmd_fn != NULL)	{
		json_t j = cmd_fn(param1, param2);
		if (j != NULL)	{
			size_t json_size;
			char* json_data = json_savetobuffer(j, &json_size, TRUE);
			if (json_data != NULL)	{
				mg_write(conn, json_data, (uint)json_size);
				json_deletebuffer(json_data);
			}
			json_destroy(j);
		}	else	{
			mg_send_status(conn, 400);
		}
	}	else	{
		mg_send_status(conn, 404);
	}
}
示例#13
0
文件: web.c 项目: hmflash/tikitank
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);
}
示例#14
0
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;
}
示例#15
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;
}
示例#16
0
文件: router.cpp 项目: jamesg/atlas
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();
    };
}
示例#17
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();
}
示例#18
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());
    }
}
示例#19
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;
}
示例#20
0
static int ev_handler(struct mg_connection *conn, enum mg_event ev) {
  switch (ev) {
    case MG_AUTH:
      return MG_TRUE;

    case MG_REQUEST:
      printf("==> [%s] [%s]\n", conn->request_method, conn->uri);
      if (strcmp(conn->request_method, "CONNECT") == 0) {
        char host[1025] = "";
        int i, is_ssl, port = 0;
        
        sscanf(conn->uri, "%1024[^:]:%d", host, &port);
        is_ssl = (port == 443 ? 1 : 0);

        // Iterate over existing wrapper, see if we can use one of them
        for (i = 0; i < (int) ARRAY_SIZE(s_wrappers); i++) {
          if (strcmp(host, s_wrappers[i].requested_host) == 0 &&
              is_ssl == (s_wrappers[i].c.ssl_cert == NULL ? 0 : 1)) {
            // Found usable wrapper, tunnel to it.
            mg_forward(conn, "127.0.0.1",
              atoi(s_wrappers[i].c.listening_port), 0);
            return MG_MORE;
          }
        }

        // No suitable wrappers found. Disallow that CONNECT request.
        mg_send_status(conn, 405);
        return MG_TRUE;
      }

      // Not a CONNECT request, serve HTML file.
      mg_send_file(conn, "ws_ssl.html");
      return MG_MORE;

    default:
      return MG_FALSE;
  }
}
示例#21
0
		std::string bad_JSON(mg_connection* aConn)
		{
			mg_send_status(aConn, 400);
			return std::string("{ \"status\" : \"Bad JSON request.\"}");
		}
示例#22
0
static void send_headers(struct mg_connection *conn)
{
	mg_send_status(conn, 200);
	mg_send_header(conn, "Connection", "close");
	mg_send_header(conn, "Content-Type", "application/json");
}
示例#23
0
/* Serve a Cortex object */
static int web_serveObject(struct mg_connection *conn) {
    cx_object o = NULL;

    /* Resolve object based on URI */
    o = cx_resolve(NULL, (cx_string)conn->uri + 2);

    if (!o) {
        mg_send_status(conn, 404);
        mg_printf_data(conn, "404: resource '%s' not found\n", conn->uri);
    } else {
        char option[6];
        cx_bool value = 0;
        cx_bool meta = 0;
        cx_bool scope = 0;

        /* Set correct content type */
        mg_send_header(conn, "Content-Type", "application/json; charset=utf-8");

        /* Determine what to show */
        mg_get_var(conn, "value", option, sizeof(option));
        if (!strcmp(option, "true")) { value = TRUE; }

        mg_get_var(conn, "meta", option, sizeof(option));
        if (!strcmp(option, "true")) { meta = TRUE; }

        mg_get_var(conn, "scope", option, sizeof(option));
        if (!strcmp(option, "true")) { scope = TRUE; }

        if (!(value || meta || scope)) {
            value = TRUE;
        }

        {
            /* Serialize object-value to JSON */
            struct cx_serializer_s serializer = cx_json_ser(CX_PRIVATE, CX_NOT, CX_SERIALIZER_TRACE_NEVER);

            if ((cx_typeof(o)->kind == CX_VOID) && (!meta && !scope)) {
                mg_printf_data(conn, "\n");
            } else {
                mg_printf_data(conn, "[");

                /* Serialize metadata of parents */
                if (meta) {
                    if (web_printParents(conn, cx_parentof(o))) {
                        mg_printf_data(conn, ",");
                    }
                }

                /* Serialize value */              
                {
                    cx_json_ser_t jsonData = {NULL, NULL, 0, 0, 0, meta, value, scope, TRUE};
                    cx_serialize(&serializer, o, &jsonData);
                    mg_printf_data(conn, "%s", jsonData.buffer);
                    cx_dealloc(jsonData.buffer);
                }
                mg_printf_data(conn, "]\n");
            }
        }

        cx_free(o);
    }

    return MG_TRUE;
}
示例#24
0
int request_handler(struct mg_connection *conn){
  char tmpBuf[1024];

  sprintf(tmpBuf, "%s %s from %s", conn->request_method, conn->uri, conn->remote_ip);

  log_line(tmpBuf, LOG_INFO);

  if(strcmp(STATS_JSON_URI, conn->uri) == 0){
    return stats_json(conn);
  }

#ifndef DEBUG
  // serve assets from resources.c
  size_t asset_size;
  int is_modified = 0;
  const char *asset_content = NULL, *if_modifier_since_header = NULL;
  char date_str[48], cache_control[58], expires[48], last_modified[48];
  time_t current_time, expires_time, if_modified_time, modified_time;
  struct tm *current_time_tm, *expires_tm, if_modifier_since, *last_modified_tm;

  last_modified_tm = gmtime(&globalOptions.start_time);
  strftime(last_modified, sizeof(last_modified), CONST_RFC1945_TIME_FORMAT, last_modified_tm);

  if_modifier_since_header = mg_get_header(conn, "If-Modified-Since");

  if(if_modifier_since_header){
    strptime(if_modifier_since_header, CONST_RFC1945_TIME_FORMAT, &if_modifier_since);
    if_modified_time = mktime(&if_modifier_since);
    modified_time = mktime(last_modified_tm);

    if(modified_time <= if_modified_time){
      mg_send_status(conn, 304);
      is_modified = 1;
    }
  }

  if(strcmp("/", conn->uri) == 0){
    asset_content = find_embedded_file("public/index.html", &asset_size);
    mg_send_header(conn, "Content-Type", "text/html; charset=utf-8");
  }else if(strcmp("/assets/app.js", conn->uri) == 0){
    asset_content = find_embedded_file("public/assets/app.js", &asset_size);
    mg_send_header(conn, "Content-Type", "application/x-javascript; charset=utf-8");
  }else if(strcmp("/assets/app.css", conn->uri) == 0){
    asset_content = find_embedded_file("public/assets/app.css", &asset_size);
    mg_send_header(conn, "Content-Type", "text/css; charset=utf-8");
  }

  if(asset_content != NULL){
    current_time = time(NULL);
    current_time_tm = gmtime(&current_time);
    strftime(date_str, sizeof(date_str), CONST_RFC1945_TIME_FORMAT, current_time_tm);

    sprintf(cache_control, "max-age=%d, public", CACHE_LIMIT);

    expires_time = time(NULL) + CACHE_LIMIT;
    expires_tm = gmtime(&expires_time);
    strftime(expires, sizeof(expires), CONST_RFC1945_TIME_FORMAT, expires_tm);

    mg_send_header(conn, "Date", date_str);
    mg_send_header(conn, "Cache-Control", cache_control);
    mg_send_header(conn, "Vary", "Accept-Encoding");
    mg_send_header(conn, "Expires", expires);

    if(is_modified == 0){
      mg_send_header(conn, "Last-Modified", last_modified);
      mg_send_data(conn, asset_content, asset_size);
    }else{
      // close connection
      mg_send_data(conn, "\r\n", 2);
    }

    return MG_REQUEST_PROCESSED;
  }
#endif

  return MG_REQUEST_NOT_PROCESSED;
}
示例#25
0
文件: common.c 项目: toha/DCAF
int http_send_error(struct mg_connection *conn, int status_code, char *msg) {
    mg_send_status(conn, status_code);
    mg_printf_data(conn, msg);
    return MG_TRUE;
}
示例#26
0
/**
 * Callback function which handles all HTTP requests.
 */
static int handle_http(struct mg_connection *conn) {
	char *url = (char *) &conn->uri[1];	// exclude the starting '/'
	Item *item;
	ACSIServer *acsiServer = (ACSIServer *) conn->server_param;

#ifdef USE_SSL
#if USE_HTTP_AUTH == 1
	static const char *passwords_file = "htpasswd.txt";
	FILE *fp = fopen(passwords_file, "r");

	if (fp == NULL || !mg_authorize_digest(conn, fp)) {
		mg_send_digest_auth_request(conn);
		return 1;
	}

	if (fp != NULL) {
		fclose(fp);
	}
#endif
#endif

	// check for method names in url
	if (strcmp(conn->request_method, "GET") == 0) {
		int len = 0;
		char printBuf[ACSI_RESPONSE_MAX_SIZE];

		if (strncmp(url, ACSI_GET_DEFINITION, strlen(ACSI_GET_DEFINITION)) == 0) {
			item = getItemFromPath(acsiServer->iedName, (char *) &url[strlen(ACSI_GET_DEFINITION) + 1]);
			len = itemDescriptionTreeToJSON(printBuf, item, FALSE);
		}
		else if (strncmp(url, ACSI_GET_DIRECTORY, strlen(ACSI_GET_DIRECTORY)) == 0) {
			item = getItemFromPath(acsiServer->iedName, (char *) &url[strlen(ACSI_GET_DIRECTORY) + 1]);
			len = itemDescriptionTreeToJSON(printBuf, item, TRUE);
		}
//		else if (strncmp(url, "scd", strlen("scd")) == 0) {
//		    mg_send_header(conn, "Content-Type", "application/xml");
//			mg_send_data(conn, scd_file, strlen(scd_file));
//		}
		else if (strncmp(url, ACSI_ASSOCIATE, strlen(ACSI_ASSOCIATE)) == 0) {
			acsiServer->clients = addClient(acsiServer->clients, conn->remote_ip, conn->remote_port);
			mg_send_data(conn, ACSI_OK, strlen(ACSI_OK));
			return 1;
		}
		else if (strncmp(url, ACSI_RELEASE, strlen(ACSI_RELEASE)) == 0) {
			// TODO raise flag here, rather than remove?
			acsiServer->clients = removeClientByConnection(acsiServer->clients, conn->remote_ip, conn->remote_port);
			mg_send_data(conn, ACSI_OK, strlen(ACSI_OK));
			return 1;
		}
		else if (strncmp(url, ACSI_ABORT, strlen(ACSI_ABORT)) == 0) {
			acsiServer->clients = removeClientByConnection(acsiServer->clients, conn->remote_ip, conn->remote_port);
			mg_send_data(conn, ACSI_OK, strlen(ACSI_OK));
			return 1;
		}
		else {
			item = getItemFromPath(acsiServer->iedName, (char *) url);
			len = itemTreeToJSON(printBuf, item);
		}

		if (item != NULL && len == -1) {
			mg_send_status(conn, 500);
			mg_send_data(conn, ACSI_BUFFER_OVERRUN, strlen(ACSI_BUFFER_OVERRUN));
			return 1;
		}
		else if (item != NULL && len > 0) {
#if ACSI_AUTO_ASSOCIATE == 1
			acsiServer->clients = addClient(acsiServer->clients, conn->remote_ip, conn->remote_port);
#endif
		    mg_send_header(conn, "Content-Type", "application/json");
		    mg_send_header(conn, "Cache-Control", "no-cache");
		    mg_send_header(conn, "Access-Control-Allow-Origin", "*");
			mg_send_data(conn, printBuf, len);
//			printf("len: %d\n", len);
//			fflush(stdout);
			return 1;
		}
	}
	else if (strcmp(conn->request_method, "POST") == 0) {
		item = getItemFromPath(acsiServer->iedName, (char *) url);
		int setReturn = setItem(item, conn->content, conn->content_len);

//		printf("content: %.*s\n", conn->content_len, conn->content);
//		fflush(stdout);

		if (setReturn > 0) {
		    mg_send_header(conn, "Cache-Control", "no-cache");
		    mg_send_header(conn, "Access-Control-Allow-Origin", "*");
			mg_send_data(conn, ACSI_OK, strlen(ACSI_OK));
		}
		else {
			mg_send_data(conn, ACSI_NOT_POSSIBLE, strlen(ACSI_NOT_POSSIBLE));
		}
		return 1;
	}

	// by default, return 404
	mg_send_status(conn, 404);
	mg_send_data(conn, ACSI_NOT_FOUND, strlen(ACSI_NOT_FOUND));
	return 1;
}
示例#27
0
文件: web.c 项目: hmflash/tikitank
static
void effects_post(struct mg_connection* conn) {
	int len1;
	int len2;
	char kind[256];
	char arg1[256];
	char arg2[256];
	struct channel* channel;

	settings_load();

	len1 = mg_get_var(conn, KIND, kind, sizeof(kind));
	if (len1 < 0) {
		mg_printf_data(conn, "Missing field: " KIND);
		mg_send_status(conn, 400);
		return;
	}

	if(!strncmp(kind, "treads", sizeof(kind))) {
		channel = &channel_treads;
	} else if(!strncmp(kind, "barrel", sizeof(kind))) {
		channel = &channel_barrel;
	} else if(!strncmp(kind, "panels", sizeof(kind))) {
		channel = &channel_panels;
	} else {
		mg_printf_data(conn, "Invalid kind");
		mg_send_status(conn, 400);
		return;
	}
	
	len1 = mg_get_var(conn, ACTIVE, arg1, sizeof(arg1));
	if (len1 > 0) {
		long idx;

		LOG(("selectEffect: kind=%s active=%s\n", kind, arg1));

		idx = strntol(arg1, len1, 10);
		if (idx >= 0 && idx < channel->num_effects) {
			channel->active = idx;
			effects_post_reply(conn);
			return;
		}

		mg_printf_data(conn, "Invalid effect");
		mg_send_status(conn, 400);
		return;
	}

	len1 = mg_get_var(conn, IS_SSAVER, arg1, sizeof(arg1));
	if (len1 > 0) {
		LOG(("setEffectScreenSaver: %s\n", arg1));
		if (!strncmp(arg1, "true", sizeof(arg1))) {
			channel->effects[channel->active]->screen_saver = 1;
		} else {
			channel->effects[channel->active]->screen_saver = 0;
		}
		effects_post_reply(conn);
		return;
	}

	len1 = mg_get_var(conn, COLOR, arg1, sizeof(arg1));
	len2 = mg_get_var(conn, ARGUMENT, arg2, sizeof(arg2));

	if (len1 > 0 && len2 > 0) {
		long idx = strntol(arg2, len2, 10);
		long color = strntol(arg1+1, len1-1, 16);
		LOG(("setEffectParameters: %ld, %lx\n", idx, color));
		if (idx < NUM_PANELS/3) {
			channel->effects[channel->active]->color_arg.colors[idx].value = color;
		}
		effects_post_reply(conn);
		return;
	} else if (len1 > 0) {
		long color = strntol(arg1+1, len1-1, 16);
		LOG(("setEffectColor: %lx\n", color));
		channel->effects[channel->active]->color_arg.color.value = color;
		effects_post_reply(conn);
		return;
	} else if (len2 > 0) {
		long value = strntol(arg2, len2, 10);
		LOG(("setEffectArgument: %ld\n", value));
		channel->effects[channel->active]->argument = value;
		effects_post_reply(conn);
		return;
	}

	mg_printf_data(conn, "Invalid data");
	mg_send_status(conn, 400);
}