예제 #1
0
int send_redirect_temp(struct MHD_Connection *connection, const char *url)
{
	struct MHD_Response *response;
	int ret;
	char *redirect = NULL;

	const char *redirect_body = "<html><head></head><body><a href='%s'>Click here to continue to<br>%s</a></body></html>";
	safe_asprintf(&redirect, redirect_body, url, url);

	response = MHD_create_response_from_buffer(strlen(redirect), redirect, MHD_RESPMEM_MUST_FREE);
	if (!response)
		return send_error(connection, 503);

	// MHD_set_response_options(response, MHD_RF_HTTP_VERSION_1_0_ONLY, MHD_RO_END);
	MHD_add_response_header(response, "Location", url);
	MHD_add_response_header(response, "Connection", "close");
	ret = MHD_queue_response(connection, MHD_HTTP_TEMPORARY_REDIRECT, response);
	MHD_destroy_response(response);

	return ret;
}
예제 #2
0
/**
* Handle incoming HTTP requests
**/
int CmdManager::AccessHandlerCallback(
    struct MHD_Connection* connection,
    const char* url, const char* method,
    const char* upload_data, size_t* upload_data_size,
    void** ptr
) {
    static int dummy;
    struct MHD_Response* response;
    int ret;

    if (0 != strcmp(method, "GET")) {
        return MHD_NO; /* unexpected method */
    }

    // The first time only the headers are valid, so store data but don't respond
    if (&dummy != *ptr) {
        *ptr = &dummy;
        return MHD_YES;
    }

    if (0 != *upload_data_size) {
        return MHD_NO; /* upload data in a GET!? */
    }

    // clear context pointer
    *ptr = NULL;

    Cmd* c = this->dispatch(connection, url, method);
    if (c == NULL) {
        return MHD_NO;
    }
    work.push(c);
    std::string resp = c->waitDone();
    delete c;

    response = MHD_create_response_from_buffer(
        resp.length(),
        (void*) resp.c_str(),
        MHD_RESPMEM_MUST_COPY
    );

    // Allows other origins to access data via AJAX
    MHD_add_response_header(response, "Access-Control-Allow-Origin", "*");

    ret = MHD_queue_response(
        connection,
        MHD_HTTP_OK,
        response
    );
    MHD_destroy_response(response);

    return ret;
}
예제 #3
0
파일: skiaserve.cpp 프로젝트: mokacao/skia
static int SendTemplate(MHD_Connection* connection, bool redirect = false,
                        const char* redirectUrl = nullptr) {
    SkString debuggerTemplate = generateTemplate(SkString(FLAGS_source[0]));

    MHD_Response* response = MHD_create_response_from_buffer(
                                 debuggerTemplate.size(),
                                 (void*) const_cast<char*>(debuggerTemplate.c_str()),
                                 MHD_RESPMEM_MUST_COPY);
    MHD_add_response_header (response, "Access-Control-Allow-Origin", "*");

    int status = MHD_HTTP_OK;

    if (redirect) {
        MHD_add_response_header (response, "Location", redirectUrl);
        status = MHD_HTTP_SEE_OTHER;
    }

    int ret = MHD_queue_response(connection, status, response);
    MHD_destroy_response(response);
    return ret;
}
예제 #4
0
int webu_stream_static(struct webui_ctx *webui) {
    /* Create the response for the static image request*/
    int retcd;
    struct MHD_Response *response;
    char resp_used[20];

    if (webu_stream_checks(webui) == -1) return MHD_NO;

    webu_stream_cnct_count(webui);

    webu_stream_mjpeg_checkbuffers(webui);

    webu_stream_static_getimg(webui);

    if (webui->resp_used == 0) {
        MOTION_LOG(ERR, TYPE_STREAM, NO_ERRNO, _("Could not get image to stream."));
        return MHD_NO;
    }

    response = MHD_create_response_from_buffer (webui->resp_size
        ,(void *)webui->resp_page, MHD_RESPMEM_MUST_COPY);
    if (!response){
        MOTION_LOG(ERR, TYPE_STREAM, NO_ERRNO, _("Invalid response"));
        return MHD_NO;
    }

    if (webui->cnt->conf.stream_cors_header != NULL){
        MHD_add_response_header (response, MHD_HTTP_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN
            , webui->cnt->conf.stream_cors_header);
    }

    MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_TYPE, "image/jpeg;");
    snprintf(resp_used, 20, "%9ld\r\n\r\n",(long)webui->resp_used);
    MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_LENGTH, resp_used);

    retcd = MHD_queue_response (webui->connection, MHD_HTTP_OK, response);
    MHD_destroy_response (response);

    return retcd;
}
예제 #5
0
inline int sendMethodNotAllowedResponse(struct MHD_Connection* connection, bool allowGet) {
    struct MHD_Response* response;
    int ret;

#ifdef MICROHTTPD_DEPRECATED
    response = MHD_create_response_from_data(
        strlen(XML_MWS_METHOD_NOT_ALLOWED), (void*)XML_MWS_METHOD_NOT_ALLOWED, false, false);
#else  // MICROHTTPD_DEPRECATED
    response = MHD_create_response_from_buffer(
        strlen(XML_MWS_METHOD_NOT_ALLOWED), (void*)XML_MWS_METHOD_NOT_ALLOWED, MHD_RESPMEM_PERSISTENT);
#endif  // MICROHTTPD_DEPRECATED
    MHD_add_response_header(response, "Content-Type", "text/xml");
    MHD_add_response_header(response, "Allow",
                            allowGet ? "GET, POST, OPTIONS" : "POST, OPTIONS");
    MHD_add_response_header(response, "Access-Control-Allow-Origin", "*");
    MHD_add_response_header(response, "Allow",
                            allowGet ? "GET, POST, OPTIONS" : "POST, OPTIONS");
    MHD_add_response_header(response, "Access-Control-Allow-Headers",
                            "CONTENT-TYPE");
    MHD_add_response_header(response, "Access-Control-Max-Age", "1728000");
    ret = MHD_queue_response(connection, MHD_HTTP_METHOD_NOT_ALLOWED, response);
    MHD_destroy_response(response);

    return ret;
}
// This function sends some answer string back to the Client.
static int send_page(struct MHD_Connection *connection, unsigned int status_code, const char *page)
{
    int ret;
    struct MHD_Response *response;
    response = MHD_create_response_from_buffer(strlen(page), (void *) page, MHD_RESPMEM_MUST_COPY);
    MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_ENCODING, "text/plain");
    if (!response) {
        return MHD_NO;
    }
    ret = MHD_queue_response(connection, status_code, response);
    MHD_destroy_response(response);
    return ret;
}
예제 #7
0
//---- Creating response page with right header syntaxe
int Server::send_page(MHD_Connection *connection, const char *page, int length, int status_code, const char * type){
    
    struct MHD_Response *response;
    
    response = MHD_create_response_from_buffer(length, (void*)page,
                                               MHD_RESPMEM_PERSISTENT);
    if (!response) {
        return MHD_NO;
    }
    
    MHD_add_response_header(response, "Content-Type", type ? type : "text/plain");

    return MHD_queue_response(connection, status_code, response);
}
예제 #8
0
inline int sendOptionsResponse(struct MHD_Connection* connection, bool allowGet) {
    struct MHD_Response* response;
    int ret;

#ifdef MICROHTTPD_DEPRECATED
    response = MHD_create_response_from_data(
        strlen(EMPTY_RESPONSE), (void*)EMPTY_RESPONSE, false, false);
#else  // MICROHTTPD_DEPRECATED
    response = MHD_create_response_from_buffer(
        strlen(EMPTY_RESPONSE), (void*)EMPTY_RESPONSE, MHD_RESPMEM_PERSISTENT);
#endif  // MICROHTTPD_DEPRECATED
    MHD_add_response_header(response, "Content-Type", "text/plain");
    MHD_add_response_header(response, "Access-Control-Allow-Origin", "*");
    MHD_add_response_header(response, "Access-Control-Allow-Methods",
                            allowGet ? "GET, POST, OPTIONS" : "POST, OPTIONS");
    MHD_add_response_header(response, "Access-Control-Allow-Headers",
                            "CONTENT-TYPE");
    MHD_add_response_header(response, "Access-Control-Max-Age", "1728000");
    ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
    MHD_destroy_response(response);

    return ret;
}
예제 #9
0
static int send_error(struct MHD_Connection *connection, int error)
{
	struct MHD_Response *response = NULL;
	// cannot automate since cannot translate automagically between error number and MHD's status codes -- and cannot rely on MHD_HTTP_ values to provide an upper bound for an array
	const char *page_400 = "<html><head><title>Error 400</title></head><body><h1>Error 400 - Bad Request</h1></body></html>";
	const char *page_403 = "<html><head><title>Error 403</title></head><body><h1>Error 403 - Forbidden</h1></body></html>";
	const char *page_404 = "<html><head><title>Error 404</title></head><body><h1>Error 404 - Not Found</h1></body></html>";
	const char *page_500 = "<html><head><title>Error 500</title></head><body><h1>Error 500 - Internal Server Error. Oh no!</body></html>";
	const char *page_501 = "<html><head><title>Error 501</title></head><body><h1>Error 501 - Not Implemented</h1></body></html>";
	const char *page_503 = "<html><head><title>Error 503</title></head><body><h1>Error 503 - Internal Server Error</h1></body></html>";

	const char *mimetype = lookup_mimetype("foo.html");

	int ret = MHD_NO;

	switch (error) {
	case 400:
		response = MHD_create_response_from_buffer(strlen(page_400), (char *)page_400, MHD_RESPMEM_PERSISTENT);
		MHD_add_response_header(response, "Content-Type", mimetype);
		ret = MHD_queue_response(connection, MHD_HTTP_BAD_REQUEST, response);
		break;

	case 403:
		response = MHD_create_response_from_buffer(strlen(page_403), (char *)page_403, MHD_RESPMEM_PERSISTENT);
		MHD_add_response_header(response, "Content-Type", mimetype);
		ret = MHD_queue_response(connection, MHD_HTTP_FORBIDDEN, response);
		break;

	case 404:
		response = MHD_create_response_from_buffer(strlen(page_404), (char *)page_404, MHD_RESPMEM_PERSISTENT);
		MHD_add_response_header(response, "Content-Type", mimetype);
		ret = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, response);
		break;

	case 500:
		response = MHD_create_response_from_buffer(strlen(page_500), (char *)page_500, MHD_RESPMEM_PERSISTENT);
		MHD_add_response_header(response, "Content-Type", mimetype);
		ret = MHD_queue_response(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, response);
		break;

	case 501:
		response = MHD_create_response_from_buffer(strlen(page_501), (char *)page_501, MHD_RESPMEM_PERSISTENT);
		MHD_add_response_header(response, "Content-Type", mimetype);
		ret = MHD_queue_response(connection, MHD_HTTP_NOT_IMPLEMENTED, response);
		break;
	case 503:
		response = MHD_create_response_from_buffer(strlen(page_503), (char *)page_503, MHD_RESPMEM_PERSISTENT);
		MHD_add_response_header(response, "Content-Type", mimetype);
		ret = MHD_queue_response(connection, MHD_HTTP_INTERNAL_SERVER_ERROR, response);
		break;
	}

	if (response)
		MHD_destroy_response(response);
	return ret;
}
예제 #10
0
/**
 * MHD content reader callback that returns
 * data in chunks.
 */
static int
crc (void *cls, size_t pos, char *buf, int max)
{
  struct MHD_Response **responseptr = cls;

  if (pos == 128 * 10)
    {
      MHD_add_response_header (*responseptr, "Footer", "working");
      return -1;                /* end of stream */
    }
  if (max < 128)
    abort ();                   /* should not happen in this testcase... */
  memset (buf, 'A' + (pos / 128), 128);
  return 128;
}
예제 #11
0
void http_response::decorate_response_str(MHD_Response* response)
{
    map<string, string, header_comparator>::iterator it;

    for (it=headers.begin() ; it != headers.end(); ++it)
        MHD_add_response_header(
                response,
                (*it).first.c_str(),
                (*it).second.c_str()
        );

    for (it=footers.begin() ; it != footers.end(); ++it)
        MHD_add_response_footer(response,
                (*it).first.c_str(),
                (*it).second.c_str()
        );

    for (it=cookies.begin(); it != cookies.end(); ++it)
        MHD_add_response_header(
                response,
                "Set-Cookie",
                ((*it).first + "=" + (*it).second).c_str()
        );
}
예제 #12
0
/*
 * web_send_data
 * Send internal HTML string
 */
static int web_send_data (struct MHD_Connection *connection, const char *data,
		const int code, bool free, bool copy, const char *ct)
{
	struct MHD_Response *response;
	int ret;

	response = MHD_create_response_from_data(strlen(data), (void *)data, free ? MHD_YES : MHD_NO, copy ? MHD_YES : MHD_NO);
	if (response == NULL)
		return MHD_NO;
	if (ct != NULL)
		MHD_add_response_header(response, "Content-type", ct);
	ret = MHD_queue_response(connection, code, response);
	MHD_destroy_response(response);
	return ret;
}
예제 #13
0
/**
 * MHD content reader callback that returns
 * data in chunks.
 */
static ssize_t
crc (void *cls, uint64_t pos, char *buf, size_t max)
{
  struct MHD_Response **responseptr = cls;

  if (pos == 128 * 10)
    {
      MHD_add_response_header (*responseptr, "Footer", "working");
      return MHD_CONTENT_READER_END_OF_STREAM;
    }
  if (max < 128)
    abort ();                   /* should not happen in this testcase... */
  memset (buf, 'A' + (pos / 128), 128);
  return 128;
}
예제 #14
0
/**
 * @brief serve_file try to serve a request via filesystem. Using webroot as root.
 * @param connection
 * @param client
 * @return
 */
static int serve_file(struct MHD_Connection *connection, t_client *client, const char *url)
{
	struct stat stat_buf;
	s_config *config = config_get_config();
	struct MHD_Response *response;
	char filename[PATH_MAX];
	int ret = MHD_NO;
	const char *mimetype = NULL;
	off_t size;

	snprintf(filename, PATH_MAX, "%s/%s", config->webroot, url);

	/* check if file exists and is not a directory */
	ret = stat(filename, &stat_buf);
	if (ret) {
		/* stat failed */
		return send_error(connection, 404);
	}

	if (!S_ISREG(stat_buf.st_mode)) {
#ifdef S_ISLNK
		/* ignore links */
		if (!S_ISLNK(stat_buf.st_mode))
#endif /* S_ISLNK */
		return send_error(connection, 404);
	}

	int fd = open(filename, O_RDONLY);
	if (fd < 0)
		return send_error(connection, 404);

	mimetype = lookup_mimetype(filename);

	/* serving file and creating response */
	size = lseek(fd, 0, SEEK_END);
	if (size < 0)
		return send_error(connection, 404);

	response = MHD_create_response_from_fd(size, fd);
	if (!response)
		return send_error(connection, 503);

	MHD_add_response_header(response, "Content-Type", mimetype);
	ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
	MHD_destroy_response(response);

	return ret;
}
예제 #15
0
파일: 02.cpp 프로젝트: Jerryang/cdec
int ahc_echo(void* servctx, MHD_Connection* connection, const char* url, const char* method, const char* version, const char* upload_data, size_t* upload_data_size, void** reqctx)
{
	static int dummy;
	if (reqctx == NULL)
	{
		// The first time only the headers are valid, do not respond in the first round.
		*reqctx = &dummy;
		return MHD_YES;
	}

	ServerContext* pServCtx = (ServerContext*)servctx;	// Not used yet
	printf("%s %s %s\n", method, url, version);

	if (strcmp(method, "GET") == 0)
	{
		if (*upload_data_size != 0)
			return MHD_NO;	// No upload data expected in HTTP GET method
 
		// Parse headers
		puts("[HEADERS]");
		MHD_get_connection_values(connection, MHD_HEADER_KIND, &print_out_key, NULL);

		// Parse GET parameters
		puts("[GET PARAMS]");
		StringPairList spl;
		MHD_get_connection_values(connection, MHD_GET_ARGUMENT_KIND, &print_out_key, &spl);

		std::string text = "<html><body>\n";
		text += "<p>URL="; text += url; 
		text += "</p>\n<p>Parameters</p>\n<ul>\n";
		for (StringPairList::iterator it = spl.begin(); it != spl.end(); ++it)
		{
			text += "<li>"; text += it->first; text += '='; text += it->second; text += "</li>\n";
		}
		text += "</body></html>\n";

		MHD_Response* response = MHD_create_response_from_buffer(text.size(), (void*)text.c_str(), MHD_RESPMEM_MUST_COPY);
		MHD_add_response_header(response, "Content-Type", "text/html");
		int ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
		MHD_destroy_response(response);

		*reqctx = NULL; // clear context pointer
		return ret;
	}
	else
		return MHD_NO;	// Not supported yet
}
예제 #16
0
static int
answer_to_connection (void *cls, struct MHD_Connection *connection,
                      const char *url, const char *method,
                      const char *version, const char *upload_data,
                      size_t *upload_data_size, void **con_cls)
{
  struct MHD_Response *response;
  int fd;
  int ret;
  struct stat sbuf;

  if (0 != strcmp (method, "GET"))
    return MHD_NO;

  if ( (-1 == (fd = open (FILENAME, O_RDONLY))) ||
       (0 != fstat (fd, &sbuf)) )
    {
      const char *errorstr =
        "<html><body>An internal server error has occured!\
                              </body></html>";
      /* error accessing file */
      if (fd != -1)
	(void) close (fd);
      response =
	MHD_create_response_from_buffer (strlen (errorstr),
					 (void *) errorstr,
					 MHD_RESPMEM_PERSISTENT);
      if (NULL != response)
        {
          ret =
            MHD_queue_response (connection, MHD_HTTP_INTERNAL_SERVER_ERROR,
                                response);
          MHD_destroy_response (response);

          return ret;
        }
      else
        return MHD_NO;
    }
  response =
    MHD_create_response_from_fd_at_offset64 (sbuf.st_size, fd, 0);
  MHD_add_response_header (response, "Content-Type", MIMETYPE);
  ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
  MHD_destroy_response (response);

  return ret;
}
예제 #17
0
/**
 * Handler that adds the 'v1' value to the given HTML code.
 *
 * @param cls unused
 * @param mime mime type to use
 * @param session session handle
 * @param connection connection to use
 */
static int
ServeMainPage (const void *cls,
	      const char *mime,
	      struct Session *session,
	      struct MHD_Connection *connection)
{
  int ret;
  char *reply;
  struct MHD_Response *response;
  
  reply = malloc(MAXTEXTFILELENGTH);
  if (NULL == reply)
    return MHD_NO;  
  if ( !ReadTextFileIntoString(reply, "data/MainPage.html") )
    return MHD_NO;  

/*    
  // Open the MainPage html file
  FILE *fp = fopen("data/MainPage.html", "rb");
  if (NULL == fp)
	  return MHD_NO;
  fseek(fp, 0L, SEEK_END);
  long sz = ftell(fp);
  fseek(fp, 0L, SEEK_SET);
  reply = malloc (sz+1);
  if (NULL == reply)
    return MHD_NO;
  fread (reply, 1, sz, fp);
  fclose (fp);
 */

  /* return static form */
  response = MHD_create_response_from_buffer (strlen (reply),
					      (void *) reply,
					      MHD_RESPMEM_MUST_FREE);
  if (NULL == response)
    return MHD_NO;
  add_session_cookie (session, response);
  MHD_add_response_header (response,
			   MHD_HTTP_HEADER_CONTENT_ENCODING,
			   mime);
  ret = MHD_queue_response (connection,
			    MHD_HTTP_OK,
			    response);
  MHD_destroy_response (response);
  return ret;
}
예제 #18
0
void
http_create_response(struct Proxy* proxy,
                     char **nv)
{
  size_t i;
  
  if(!proxy->http_active)
    return;
  
  for(i = 0; nv[i]; i += 2) {
    if(0 == strcmp(":status", nv[i]))
    {
      char tmp[4];
      memcpy(&tmp,nv[i+1],3);
      tmp[3]=0;
      proxy->status = atoi(tmp);
      continue;
    }
    else if(0 == strcmp(":version", nv[i]))
    {
      proxy->version = nv[i+1];
      continue;
    }
    else if(0 == strcmp("content-length", nv[i]))
    {
      continue;
    }

    char *header = *(nv+i);
    if(MHD_NO == MHD_add_response_header (proxy->http_response,
                   header, nv[i+1]))
    {
      PRINT_INFO2("SPDY_name_value_add failed: '%s' '%s'", header, nv[i+1]);
    }
    PRINT_INFO2("adding '%s: %s'",header, nv[i+1]);
  }
  
  if(MHD_NO == MHD_queue_response (proxy->http_connection, proxy->status, proxy->http_response)){
    PRINT_INFO("No queue");
    //TODO
    //abort();
    proxy->http_error = true;
  }
  
  MHD_destroy_response (proxy->http_response);
  proxy->http_response = NULL;
}
예제 #19
0
/**
 * Add header to response to set a session cookie.
 *
 * @param session session to use
 * @param response response to modify
 */
void WebServer::addSessionCookie (WebSession *session, struct MHD_Response *response)
{
    char cstr[256];
    snprintf (cstr,
              sizeof (cstr),
              "%s=%s",
              COOKIE_NAME,
              session->getSID().c_str());
    if (MHD_NO ==
        MHD_add_response_header (response,
                                 MHD_HTTP_HEADER_SET_COOKIE,
                                 cstr))
    {
        fprintf (stderr,
                 "Failed to set session cookie header!\n");
    }
}
예제 #20
0
inline void set_auth_cookie(struct MHD_Connection *connection)
{
	char response[64] = { 0 };
	char cookie[256] = { 0 };

	sprintf(response, "{\"login\": \"YES\"}");
	last_cookie = get_random_cookie();
	sprintf(cookie, AUTHENTICATE_COOKIE_FORAMT, AUTHENTICATE_COOKIE_NAME,
	        last_cookie, AUTHENTICATE_COOKIE_TIME);

	response = MHD_create_response_from_buffer (strlen(login),
	           (void *)(login), MHD_RESPMEM_PERSISTENT);
	MHD_add_response_header (response, MHD_HTTP_HEADER_SET_COOKIE,
	                         set_coockie);
	MHD_queue_response (connection, MHD_HTTP_OK, response);
	MHD_destroy_response (response);
}
예제 #21
0
    // return MHD_NO or MHD_YES
    virtual int handleRequest(  struct MHD_Connection *connection,
                                const char */*url*/, const char *method, const char */*version*/,
                                const char *upload_data, size_t *upload_data_size)
    {
        // new request
        if(mState == BEGIN)
        {
            if(strcmp(method, "POST") == 0)
            {
                mState = WAITING_DATA;
                // first time there is no data, do nothing and return
                return MHD_YES;
            }
        }
        if(mState == WAITING_DATA)
        {
            if(upload_data && *upload_data_size)
            {
                mRequesString += std::string(upload_data, *upload_data_size);
                *upload_data_size = 0;
                return MHD_YES;
            }
        }

        std::vector<uint8_t> bytes(mRequesString.begin(), mRequesString.end());

        int id = mApiServer->getTmpBlobStore()->storeBlob(bytes);

        resource_api::JsonStream responseStream;
        if(id)
            responseStream << makeKeyValue("ok", true);
        else
            responseStream << makeKeyValue("ok", false);

        responseStream << makeKeyValueReference("id", id);

        std::string result = responseStream.getJsonString();

        struct MHD_Response* resp = MHD_create_response_from_data(result.size(), (void*)result.data(), 0, 1);

        MHD_add_response_header(resp, "Content-Type", "application/json");

        secure_queue_response(connection, MHD_HTTP_OK, resp);
        MHD_destroy_response(resp);
        return MHD_YES;
    }
예제 #22
0
int handle_request(void *cls, struct MHD_Connection *connection, const char *url, const char *method,
			const char *version, const char *upload_data, size_t *upload_data_size, void **con_cls) {
	const char * json_str;
	int ret;
	int num_chans = *(int *) cls;
	print(2, "Local request received: %s %s %s", NULL, version, method, url);
	
	struct MHD_Response *response;
	
	struct json_object *json_obj = json_object_new_object();
	struct json_object *json_data = json_object_new_object();

	for (int i = 0; i < num_chans; i++) {
		channel_t *ch = &chans[i];
		reading_t rd;
		
		if (strcmp(url, "/") == 0 || strcmp(ch->uuid, url + 1) == 0) {
			pthread_mutex_lock(&ch->mutex);
				/* wait for new data comet-like blocking of HTTP response */
				pthread_cond_wait(&ch->condition, &ch->mutex); // TODO use pthread_cond_timedwait()
			pthread_mutex_unlock(&ch->mutex);
		
			struct json_object *json_tuples = api_json_tuples(ch, TRUE);

			json_object_object_add(json_data, "uuid", json_object_new_string(ch->uuid));
			json_object_object_add(json_data, "interval", json_object_new_int(ch->interval));
			json_object_object_add(json_data, "tuples", json_tuples);
		}
	}
	
	json_object_object_add(json_obj, "version", json_object_new_string(VZ_VERSION));
	json_object_object_add(json_obj, "generator", json_object_new_string("vzlogger"));
	json_object_object_add(json_obj, "data", json_data);
	json_str = json_object_to_json_string(json_obj);
	
	response = MHD_create_response_from_data(strlen(json_str), (void *) json_str, FALSE, TRUE);
	
	MHD_add_response_header(response, "Content-type", "application/json");
	
	ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
	
	MHD_destroy_response (response);

	return ret;
}
예제 #23
0
파일: deployapp.cpp 프로젝트: dokoto/hwt
		FUNCTION PRIVATE DEFINITION static int send_page 
			(
				struct MHD_Connection* connection, 
				const Str_t& page, 
				const Str_t& mimetype
			)
		{
			int ret = 0;
			struct MHD_Response* response = NULL;
			
			response = MHD_create_response_from_data(page.size(), (void*) page.c_str(), MHD_NO, MHD_YES);
			if (!response) return MHD_NO;
			MHD_add_response_header (response, "Content-Type", mimetype.c_str());
			ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
			MHD_destroy_response (response);

			return ret;    
		}    
예제 #24
0
MHD_Response *execute(struct MHD_Connection *connection, const char *bas) {
  const char *width =
    MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "width");
  const char *height =
    MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "height");
  const char *command =
    MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "command");
  const char *graphicText =
    MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND, "graphic-text");
  const char *accept =
    MHD_lookup_connection_value(connection, MHD_HEADER_KIND, MHD_HTTP_HEADER_ACCEPT);

  if (width != NULL) {
    os_graf_mx = atoi(width);
  }
  if (height != NULL) {
    os_graf_my = atoi(height);
  }
  if (graphicText != NULL) {
    g_graphicText = atoi(graphicText) > 0;
  }
  if (command != NULL) {
    strcpy(opt_command, command);
  }

  log("%s dim:%dX%d", bas, os_graf_mx, os_graf_my);
  g_connection = connection;
  g_canvas.reset();
  g_start = dev_get_millisecond_count();
  g_canvas.setGraphicText(g_graphicText);
  g_canvas.setJSON((strncmp(accept, "application/json", 16) == 0));
  g_cookies.removeAll();
  sbasic_main(bas);
  g_connection = NULL;
  String page = g_canvas.getPage();
  MHD_Response *response =
    MHD_create_response_from_buffer(page.length(), (void *)page.c_str(),
                                    MHD_RESPMEM_MUST_COPY);
  List_each(String *, it, g_cookies) {
    String *next = (*it);
    MHD_add_response_header(response,
                            MHD_HTTP_HEADER_SET_COOKIE,
                            next->c_str());
  }
예제 #25
0
/**
 * Queues a response to request basic authentication from the client.
 * The given response object is expected to include the payload for
 * the response; the "WWW-Authenticate" header will be added and the
 * response queued with the 'UNAUTHORIZED' status code.
 *
 * @param connection The MHD connection structure
 * @param realm the realm presented to the client
 * @param response response object to modify and queue
 * @return #MHD_YES on success, #MHD_NO otherwise
 * @ingroup authentication
 */
int
MHD_queue_basic_auth_fail_response (struct MHD_Connection *connection,
				    const char *realm,
				    struct MHD_Response *response)
{
  int ret;
  int res;
  size_t hlen = strlen(realm) + strlen("Basic realm=\"\"") + 1;
  char *header;

  header = (char *) malloc(hlen);
  if (NULL == header)
  {
#ifdef HAVE_MESSAGES
    MHD_DLOG(connection->daemon,
		   "Failed to allocate memory for auth header\n");
#endif /* HAVE_MESSAGES */
    return MHD_NO;
  }
  res = MHD_snprintf_ (header,
                       hlen,
                       "Basic realm=\"%s\"",
                       realm);
  if (res > 0 && (size_t)res < hlen)
    ret = MHD_add_response_header (response,
                                   MHD_HTTP_HEADER_WWW_AUTHENTICATE,
                                   header);
  else
    ret = MHD_NO;

  free(header);
  if (MHD_YES == ret)
    ret = MHD_queue_response (connection,
			      MHD_HTTP_UNAUTHORIZED,
			      response);
  else
    {
#ifdef HAVE_MESSAGES
      MHD_DLOG (connection->daemon,
                _("Failed to add Basic auth header\n"));
#endif /* HAVE_MESSAGES */
    }
  return ret;
}
예제 #26
0
/*
 * web_send_file
 * Read files and send them out
 */
int web_send_file (struct MHD_Connection *conn, const char *filename, const int code, const bool unl)
{
	struct stat buf;
	FILE *fp;
	struct MHD_Response *response;
	const char *p;
	const char *ct = NULL;
	int ret;

	if ((p = strchr(filename, '.')) != NULL) {
		p++;
		if (strcmp(p, "xml") == 0)
			ct = "text/xml";
		else if (strcmp(p, "js") == 0)
			ct = "text/javascript";
	}
	if (stat(filename, &buf) == -1 ||
			((fp = fopen(filename, "r")) == NULL)) {
		if (strcmp(p, "xml") == 0)
			response = MHD_create_response_from_data(0, (void *)"", MHD_NO, MHD_NO);
		else {
			int len = strlen(FNF) + strlen(filename) - 1; // len(%s) + 1 for \0
			char *s = (char *)malloc(len);
			if (s == NULL) {
				fprintf(stderr, "Out of memory FNF\n");
				exit(1);
			}
			snprintf(s, len, FNF, filename);
			response = MHD_create_response_from_data(len, (void *)s, MHD_YES, MHD_NO); // free
		}
	} else
		response = MHD_create_response_from_callback(buf.st_size, 32 * 1024, &web_read_file, fp,
				&web_close_file);
	if (response == NULL)
		return MHD_YES;
	if (ct != NULL)
		MHD_add_response_header(response, "Content-type", ct);
	ret = MHD_queue_response(conn, code, response);
	MHD_destroy_response(response);
	if (unl)
		unlink(filename);
	return ret;
}
예제 #27
0
/**
 * Add header to response to set a session cookie.
 *
 * @param session session to use
 * @param response response to modify
 */ 
static void
add_session_cookie (struct Session *session,
		    struct MHD_Response *response)
{
  char cstr[256];
  snprintf (cstr,
	    sizeof (cstr),
	    "%s=%s",
	    COOKIE_NAME,
	    session->sid);
  if (MHD_NO == 
      MHD_add_response_header (response,
			       MHD_HTTP_HEADER_SET_COOKIE,
			       cstr))
    {
      fprintf (stderr, 
	       "Failed to set session cookie header!\n");
    }
}
예제 #28
0
/**
 * Handler that returns a simple static HTTP page.
 *
 * @param connection connection to use
 * @return MHD_YES on success
 */
static int
serve_main_page (struct MHD_Connection *connection)
{
  int ret;
  struct MHD_Response *response;

  /* return static form */
  response = MHD_create_response_from_buffer (strlen (MAIN_PAGE),
					      (void *) MAIN_PAGE,
					      MHD_RESPMEM_PERSISTENT);
  MHD_add_response_header (response,
			   MHD_HTTP_HEADER_CONTENT_TYPE,
			   MIME_HTML);
  ret = MHD_queue_response (connection,
			    MHD_HTTP_OK,
			    response);
  MHD_destroy_response (response);
  return ret;
}
예제 #29
0
파일: http.c 프로젝트: Dridi/vagent2
int send_response2(struct http_response *resp)
{
	int ret;
	struct MHD_Response *MHDresponse;
	void *data_copy;
	struct http_header *hdr;
	data_copy = malloc(resp->ndata);
	memcpy(data_copy, resp->data, resp->ndata);
	MHDresponse = MHD_create_response_from_data(resp->ndata,
			data_copy, MHD_YES, MHD_NO);
	assert(MHDresponse);
	for (hdr = resp->headers; hdr; hdr = hdr->next)
		MHD_add_response_header(MHDresponse, hdr->key, hdr->value);

	ret = MHD_queue_response (resp->connection, resp->status, MHDresponse);
	assert(ret == 1);
	MHD_destroy_response (MHDresponse);
	return ret;
}
예제 #30
0
int
main (int argc, char *const *argv)
{
  struct MHD_Daemon *d;
  unsigned int i;

  if (argc != 2)
    {
      printf ("%s PORT\n", argv[0]);
      return 1;
    }
  response = MHD_create_response_from_buffer (strlen (PAGE),
					      (void *) PAGE,
					      MHD_RESPMEM_PERSISTENT);
#if 0
  (void) MHD_add_response_header (response,
				  MHD_HTTP_HEADER_CONNECTION,
				  "close");
#endif
  d = MHD_start_daemon (MHD_USE_SELECT_INTERNALLY | MHD_SUPPRESS_DATE_NO_CLOCK
#ifdef EPOLL_SUPPORT
			| MHD_USE_EPOLL | MHD_USE_EPOLL_TURBO
#endif
			,
                        atoi (argv[1]),
                        NULL, NULL, &ahc_echo, NULL,
			MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120,
			MHD_OPTION_THREAD_POOL_SIZE, (unsigned int) NUMBER_OF_THREADS,
			MHD_OPTION_URI_LOG_CALLBACK, &uri_logger_cb, NULL,
			MHD_OPTION_NOTIFY_COMPLETED, &completed_callback, NULL,
			MHD_OPTION_CONNECTION_LIMIT, (unsigned int) 1000,
			MHD_OPTION_END);
  if (d == NULL)
    return 1;
  (void) getc (stdin);
  MHD_stop_daemon (d);
  MHD_destroy_response (response);
  for (i=0;i<SMALL;i++)
    if (0 != small_deltas[i])
      fprintf (stdout, "D: %d %u\n", i, small_deltas[i]);
  return 0;
}