Пример #1
0
bool UpdateRequest::response() {
  // http://ebpadmin.renren.com:8080/union/update.html?id=1000004323000300000&k=id&v=1000004323000300000
  if (!Request::response() && false)
    return false;

  Statement sql;

  sql << "UPDATE ad_union_ads SET " << getProperty("k") << "=" << mysqlpp::quote << getProperty("v") << " WHERE id=" << getProperty("id");

  mysqlpp::StoreQueryResult ret;
  try {
    ret = QueryRunner("ad_db", CDbRServer).store(sql);
  } catch (std::exception& e) {
    MCE_WARN("update ad err : " << e.what());
    FCGX_FPrintF(_fcgi_out,"Content-type: text/html\r\n\r\n-1" );
    return false;
  } catch (...) {
    MCE_WARN("update ad unkown exception.");
    FCGX_FPrintF(_fcgi_out,"Content-type: text/html\r\n\r\n-1" );
    return false;
  }

  stringstream ss;
  FCGX_FPrintF(_fcgi_out,"Content-type: text/html\r\n\r\n0" );
  return true;
}
Пример #2
0
/*
static int
tohex(char c)
{
    if (c>='0' && c<='9')
        return c-'0';
    if (c>='a' && c<='f')
        return c-'a'+10;
    if (c>='A' && c<='F')
        return c-'A'+10;
    return c;
}
*/
static int
handle_ctrl(FCGX_Request *request, char *bfr, int sz)
{
    struct netv_lua_widget *w;
    enum lua_cmd cmd;

    cmd = *bfr;
    bfr++;
    sz--;

    w = (struct netv_lua_widget *)bfr;
    bfr += sizeof(*w);
    sz -= sizeof(*w);

    if (sz < 0) {
        FCGX_FPrintF(request->out, "Content-Type: text/html\r\n"
                                   "Status: 500\r\n"
                                   "\r\n"
                                   "Not enough data to handle ctrl interface\r\n");
        return 0;
    }

    FCGX_FPrintF(request->out, "Content-Type: text/html\r\n"
                               "X-Handle: %d\r\n"
                               "X-%s: x=%d&y=%d&w=%d&h=%d&c1=%d&c2=%d&t=%d\r\n"
                               "\r\n",
                               w->id+HANDLE_OFFSET,
                               (cmd==LC_INPUT || cmd==LC_NEWINPUT)?"Input":"Output",
                               w->x, w->y, w->width, w->height,
                               w->color1, w->color2, w->type);
    if (cmd == LC_OUTPUT)
        FCGX_PutStr(bfr, sz, request->out);
    return 0;
}
Пример #3
0
static void PrintEnv(FCGX_Stream *out, char *label, char **envp)
{
    FCGX_FPrintF(out, "%s:<br>\n<pre>\n", label);
    for( ; *envp != NULL; envp++) {
        FCGX_FPrintF(out, "%s\n", *envp);
    }
    FCGX_FPrintF(out, "</pre><p>\n");
}
Пример #4
0
void CgiService::Response(FCGX_Request *req,
                          const std::string &out,
                          const std::string &cookie,
                          const std::string &cookie_track)
{
    FCGX_FPrintF(req->out,"Content-type: text/html\r\n");
    FCGX_FPrintF(req->out,"Set-Cookie: %s\r\n", cookie.c_str());
    FCGX_FPrintF(req->out,"Set-Cookie: %s\r\n", cookie_track.c_str());
    FCGX_FPrintF(req->out,"Status: 200 OK\r\n");
    FCGX_FFlush(req->out);
    FCGX_FPrintF(req->out,"\r\n%s\n", out.c_str());
    FCGX_Finish_r(req);
}
Пример #5
0
static void *doit(void *a)
{
    int rc, thread_id = (int)a;
    int i = 0;
    pid_t pid = getpid();
    FCGX_Request request;
    char *server_name;

    FCGX_InitRequest(&request, 0, 0);

    for (;;)
    {
        static pthread_mutex_t accept_mutex = PTHREAD_MUTEX_INITIALIZER;
        static pthread_mutex_t counts_mutex = PTHREAD_MUTEX_INITIALIZER;

        /* Some platforms require accept() serialization, some don't.. */
        pthread_mutex_lock(&accept_mutex);
        rc = FCGX_Accept_r(&request);
        pthread_mutex_unlock(&accept_mutex);

        if (rc < 0)
            break;

        server_name = FCGX_GetParam("SERVER_NAME", request.envp);

        FCGX_FPrintF( request.out,
            "Content-type: text/html\r\n"
            "\r\n"
            "<title>FastCGI Hello! (multi-threaded C, fcgiapp library)</title>"
            "<h1>FastCGI Hello! (multi-threaded C, fcgiapp library)</h1>"
            "Thread %d, Process %ld<p>"
            "Request counts for %d threads running on host <i>%s</i><p><code>",
            thread_id, pid, THREAD_COUNT, server_name ? server_name : "?" );

        //sleep(2);

        pthread_mutex_lock(&counts_mutex);
            ++counts[thread_id];
            i++;
            FCGX_FPrintF( request.out, "%5d ", i );

            //for (i = 0; i < THREAD_COUNT; i++)
            //    FCGX_FPrintF(request.out, "%5d " , counts[i]);
        pthread_mutex_unlock(&counts_mutex);

        FCGX_Finish_r(&request);
    }

    return NULL;
}
Пример #6
0
int request_post(FCGX_Stream *in, FCGX_Stream *out, FCGX_ParamArray *envp)
{
	// have not test
	char *contentSplit;  
	char *buffer = NULL;
  
    char *content_type = FCGX_GetParam("CONTENT_TYPE", *envp); 
    contentSplit = strchr(content_type,'=')+1; 
    char *content_length = FCGX_GetParam("CONTENT_LENGTH", *envp); 
	int len = 0;

    if(content_length != NULL)  
    {  
        len = strtol(content_length, NULL, 10);  
        if(len == 0)  
        {  
			FCGX_FPrintF(out, "No data posted\n");  
        }else  
        {  
            if(len > MAX_LEN)                     
                len = MAX_LEN;  
            buffer = (char*)malloc(len);  
            if(buffer)  
            {  
                for(int i=0;i<len;i++)  
                {  
                    buffer[i] = FCGX_GetChar(in);  
                }  
                post_data_handle(buffer,len,contentSplit,out);  
                free(buffer);  
            }  
        }  
    }
	return 0;
}
Пример #7
0
/* TODO: Comment */
static void invalid_request(FCGX_Request *rq, char *code, char *msg) {
      FCGX_FPrintF(rq->out,
		   "Status: %s %s\r\n",
		   code, msg);

      return;
}
Пример #8
0
	bool doRequest(FCGX_Request& request){
		map<string, string> mapParam;
		string query_string = FCGX_GetParam("QUERY_STRING", request.envp);
		ParseParam(mapParam, query_string);
		map<string, string>::iterator itU = mapParam.find("uid");
		if(itU == mapParam.end()){
			return false;
		}
		int userId;
		try{
			userId = boost::lexical_cast<int>((*itU).second);
		}catch(...){
			return false;
		}
		TipPtr tp;
		try{
			tp = QuestCacheAdapter::instance().showTip(userId);
			if(tp->id==-1)
				return false;
		}catch(...){
			return false;
		}
		string res = "Content-type: text/html\r\n\r\n" + tp->content;
		FCGX_FPrintF(request.out, res.c_str());
		FCGX_Finish_r(&request);
		return true;

	}	
Пример #9
0
void *process(void *a)
{
	char **envp;
	const char *data;
	int res;
	FCGX_Request req;
	json_object *json;
	json_object *jarray;
	FCGX_InitRequest(&req, 0, 0);
	while(1)
	{
		res = FCGX_Accept_r(&req);
		if(res < 0)
		{
			break;
		}
		json = json_object_new_object();
		jarray = json_object_new_array();
		return_header(&req, 200, NULL, "application/json");
		for(envp = req.envp; *envp != NULL; envp++)
		{
//FIXME jsonurlencode...
			json_object_array_add(jarray, json_object_new_string(*envp));
		}
		json_object_object_add(json, "env", jarray);
		data = json_object_to_json_string_ext(json, JSON_C_TO_STRING_PRETTY);
		FCGX_FPrintF(req.out, "%s\n", data);
		json_object_put(json);
		FCGX_Finish_r(&req);
	}
	return NULL;
}
Пример #10
0
/*
 *	send response to server
 */
static void sendResponse(HTTPResponse *resp)
{
   String *resphdrs;
#ifndef PROFILE
   FCGX_FPrintF(out,"Status: %d %s" CRLF,resp->status,resp->statusMsg);
#endif

   resphdrs = resp_packageHeaders(resp);
#ifndef PROFILE
   FCGX_PutS(resphdrs->text,out);
#endif
   str_free(resphdrs);
#ifndef PROFILE
   FCGX_PutS(CRLF, out);
#endif

#ifndef PROFILE

   /* resp->content_valid will be 0 for HEAD requests and empty responses */
   if (resp->content_valid) {
      while (resp->content_read < resp->content_length) {
         //fwrite(resp->content,sizeof(char),resp->content_valid,stdout);
	      FCGX_PutStr(resp->content, resp->content_valid, out);
		 if (resp_getResponseContent(resp, 1) == -1)
         {
         	break;
         }
      }
      //fwrite(resp->content,sizeof(char),resp->content_valid,stdout);
      FCGX_PutStr(resp->content, resp->content_valid, out);
   }
   FCGX_FFlush(out);
#endif
   return;		
}
Пример #11
0
bool GetAllRequest::response() {
  if (!Request::response() && false)
    return false;

  Statement sql;
  sql << "SELECT id, type, name, budget, click_price, click_count FROM ad_union_ads";
  stringstream ss;
  try {
    mysqlpp::StoreQueryResult res = QueryRunner("ad_db", CDbRServer).store(sql);
    if (!res) {
      FCGX_FPrintF(_fcgi_out, "Content-type: text/html\r\n\r\n-3");
      return false;
    }
    ss << "Content-type: text/html\r\n\r\n[";
    for (size_t i = 0; i<res.num_rows(); ++i) {
      mysqlpp::Row row = res.at(i);
      if (i) {
        ss << ",";
      }

      string name = row["name"].c_str();
      jsonEscape(name);
      int click_count = (int)row["click_count"];
      int click_price = (int)row["click_price"];
      int budget = (int)row["budget"];

      ss << "{'id':'" << (long)row["id"]
         << "','type':" << (long)row["type"] 
         << ", 'name':'" << name 
         << "', 'remaining':" << budget - click_count * click_price
         << "}";
    }
    ss << "]";
  } catch (std::exception& e) {
    MCE_WARN("db err : " << e.what());
    FCGX_FPrintF(_fcgi_out, "Content-type: text/html\r\n\r\n-1");
    return false;
  } catch (...) {
    MCE_WARN("db unkown exception.");
    FCGX_FPrintF(_fcgi_out, "Content-type: text/html\r\n\r\n-2");
    return false;
  }
  MCE_DEBUG("response : " << ss.str());
  FCGX_PutS(ss.str().c_str(), _fcgi_out);
  return true;
}
Пример #12
0
static void io_fcgi_write_headers(void *context, const char * const *headers, int num_headers)
{
	FCGX_Request *request = (FCGX_Request *)context;
	for(int i = 0; i < num_headers; i++) {
		FCGX_FPrintF(request->out, "%s\r\n", headers[i]);
	}
	FCGX_PutStr("\r\n", 2, request->out);
}
Пример #13
0
int main ()
{
    FCGX_Stream *in, *out, *err;
    FCGX_ParamArray envp;
    int count = 0;

    while (FCGX_Accept(&in, &out, &err, &envp) >= 0) {
        char *contentLength = FCGX_GetParam("CONTENT_LENGTH", envp);
        int len = 0;

        FCGX_FPrintF(out,
           "Content-type: text/html\r\n"
           "\r\n"
           "<title>FastCGI echo (fcgiapp version)</title>"
           "<h1>FastCGI echo (fcgiapp version)</h1>\n"
           "Request number %d,  Process ID: %d<p>\n", ++count, getpid());

        if (contentLength != NULL)
            len = strtol(contentLength, NULL, 10);

        if (len <= 0) {
            FCGX_FPrintF(out, "No data from standard input.<p>\n");
        }
        else {
            int i, ch;

            FCGX_FPrintF(out, "Standard input:<br>\n<pre>\n");
            for (i = 0; i < len; i++) {
                if ((ch = FCGX_GetChar(in)) < 0) {
                    FCGX_FPrintF(out,
                        "Error: Not enough bytes received on standard input<p>\n");
                    break;
                }
                FCGX_PutChar(ch, out);
            }
            FCGX_FPrintF(out, "\n</pre><p>\n");
        }

        PrintEnv(out, "Request environment", envp);
        PrintEnv(out, "Initial environment", environ);
    } /* while */

    return 0;
}
Пример #14
0
static int
make_error(FCGX_Request *request, char *msg, int err)
{
    FCGX_FPrintF(request->out,
            "Content-type: text/html\r\n"
            "Status: 500\r\n"
            "\r\n"
            "%s: %s\r\n", msg, strerror(err));
    return 0;
}
Пример #15
0
		virtual void run(){
			for (;;) {
				int rc = FCGX_Accept_r(&request);
				if (rc < 0) break;
				if(!doRequest(request)){
					FCGX_FPrintF(request.out, "Content-type: text/html\r\n\r\n");
					FCGX_Finish_r(&request);
				}
			}
		};
Пример #16
0
int default_message(FCGX_Stream *out, FCGX_ParamArray *envp, int *count) {
	int i;
	i = FCGX_FPrintF(out,
			 "Content-type: text/html\r\n"
			 "\r\n"
			 "<title>FastCGI echo (fcgiapp version)</title>\n"
			 "<h1>FastCGI echo (fcgiapp version)</h1>\n"
			 "Request number %d,	Process ID: %d<p>\n"
			 "Requested url '%s'\n",
			 ++(*count), getpid(),
			 FCGX_GetParam("REQUEST_URI", *envp));
	return i;
}
Пример #17
0
static int fy_fcgi_layout_task_submit(fy_task *task, void *request)
{
    size_t       output_n;
    jc_json_t   *err_js;
    fy_request  *r;
    const char  *output;

    r = (fy_request *)request;
    assert(r != NULL);
    assert(r->info != NULL);

    if (r->info->json_rc != NULL) {
        output = jc_json_str_n(r->info->json_rc, &output_n);
        FCGX_FPrintF(r->fcgi_request->out, "Status: 200 OK\r\n"
                "Content-type: text/html\r\n"
                "Content-Length: %lu\r\n\r\n%s\r",
                output_n, output);
        fy_request_next_module(r);
        return 0;
    }

error:
    err_js = jc_json_create();
    assert(err_js != NULL);

    jc_json_add_num(err_js, "errorno", 1);
    jc_json_add_str(err_js, "errormsg", "no suitable ads");
    jc_json_add_num(err_js, "expiredtime", fy_cur_sec());
    jc_json_add_json(err_js, "data", jc_json_create());
    output = jc_json_str_n(err_js, &output_n);
    FCGX_FPrintF(r->fcgi_request->out, "Status: 200 OK\r\n"
            "Content-type: text/html\r\n"
            "Content-Length: %lu\r\n\r\n%s\r",
            output_n, output);
    r->info->json_rc = err_js;
    fy_request_next_module(r);
    return 0;
}
Пример #18
0
int bridge_request_json_params(bridge_request_t *self, DBusMessageIter *it,
			       struct json_object **result, int is_array)
{
	struct json_object *tmp;
	const char *key;
	char *signature;

	*result = 0;

	/* empty array */
	if (is_array && dbus_message_iter_get_arg_type(it) == DBUS_TYPE_INVALID) {
		// empty array of dict entries => empty json object
		// empty array of other types => empty json array
		signature = dbus_message_iter_get_signature(it);
		if(signature && signature[0] == '{') {
			*result = json_object_new_object();
			dbus_free(signature);
		}
		else
			*result = json_object_new_array();
		return 0;
	}

	do {
		bridge_request_json_params_parse(self, it, &tmp, &key);
		if (!tmp) {
			bridge_request_error(self ,
				"unsupported dbus argument type.");
			FCGX_FPrintF(self->request.err, "type: %c\n", dbus_message_iter_get_arg_type(it));
			return EINVAL;
		}

		if (key != 0) {
			if (!*result)
				*result = json_object_new_object();
			json_object_object_add(*result, key, tmp);
		}
		else if (is_array) {
			if (!*result)
				*result = json_object_new_array();
			json_object_array_add(*result, tmp);
		}
		else {
			*result = tmp;
			break;
		}
	} while (dbus_message_iter_next(it));

	return 0;
}
Пример #19
0
static void
flush_headers(slash_context_t* ctx)
{
    sl_response_key_value_t* headers;
    size_t header_count, i;
    int sent_content_type = 0;
    if(ctx->sent_headers) {
        return;
    }
    ctx->sent_headers = 1;
    headers = sl_response_get_headers(ctx->vm, &header_count);
    FCGX_FPrintF(ctx->request.out, "Status: %d\r\n", sl_response_get_status(ctx->vm));
    for(i = 0; i < header_count; i++) {
        /* @TODO: do something not non-standard */
        if(strcasecmp(headers[i].name, "Content-Type") == 0) {
            sent_content_type = 1;
        }
        FCGX_FPrintF(ctx->request.out, "%s: %s\r\n", headers[i].name, headers[i].value);
    }
    if(!sent_content_type) {
        FCGX_PutS("Content-Type: text/html; charset=utf-8\r\n", ctx->request.out);
    }
    FCGX_PutS("\r\n", ctx->request.out);
}
Пример #20
0
void return_header(FCGX_Request *req, int status, char *status_str, char *content_type)
{
	if(status == 200 && status_str == NULL)
	{
		status_str = "OK";
	}
	FCGX_FPrintF(req->out,
	             "Status: %d %s\r\n"
	             "Content-type: %s\r\n"
	             "\r\n",
	             status,
	             status_str,
	             content_type
	);
}
Пример #21
0
int request_get(FCGX_Stream *in, FCGX_Stream *out, FCGX_ParamArray *envp)
{
	vector<key_value_t> kvs;
	char *query_string = FCGX_GetParam("QUERY_STRING", *envp);
	char *ip = FCGX_GetParam("REMOTE_ADDR", *envp);
	char query[1024] = {0}, remote_ip[20] = {0};
	memcpy(query, query_string, strlen(query_string));
	memcpy(remote_ip, ip, strlen(ip));
	parse_get_query(query, kvs);
	char *result = http_query_proc(kvs, remote_ip);
	//const char *result = "ok";
    FCGX_FPrintF(out, "Content-type: text/plain; charset=utf-8\r\n"
    	"\r\n"
    	""
		"%s", result);
	return 0;
}
Пример #22
0
JSBool
Output_content_set (JSContext *cx, JSObject *obj, jsval idval, jsval *vp)
{
    JS_BeginRequest(cx);
    JS_EnterLocalRootScope(cx);

    jsval     property;
    int       limit;
    JSBool    buffered;
    JSString* string;

    JS_GetProperty(cx, obj, "limit", &property);
    JS_ValueToInt32(cx, property, &limit);
    JS_GetProperty(cx, obj, "buffered", &property);
    JS_ValueToBoolean(cx, property, &buffered);
    string = JS_ValueToString(cx, *vp);

    if (!buffered && JS_GetStringLength(string) > limit) {
        if (!JSVAL_TO_BOOLEAN(JS_EVAL(cx, "Headers.sent"))) {
            JS_EVAL(cx, "Headers.send()");
        }

        FCGX_Stream* out       = ((LCGIData*) JS_GetContextPrivate(cx))->cgi->out;
        char*        cString   = JS_GetStringBytes(string);
        char         size[300] = {NULL};
        sprintf(size, "%x", strlen(cString));

        FCGX_FPrintF(out, "%s\r\n%s\r\n", size, cString);

        property = JS_GetEmptyStringValue(cx);
        JS_SetProperty(cx, obj, "content", &property);
    }

    JS_LeaveLocalRootScope(cx);
    JS_EndRequest(cx);

    return JS_TRUE;
}
Пример #23
0
bool ReloadRequest::response() {
  if (!Request::response() && false)
    return false;

  string out = "Content-type: text/html\r\n\r\n";

  bool ret = false;
  try{
    ret = AdUnionGateAdapter::instance().Reload();
  } catch (Ice::Exception& e){
    MCE_WARN("AdUnionGateAdapter Reload() exception : " << e.what());
    ret = false;
  }

  MCE_INFO("AdUnionGateAdapter Reload() : " << ret);
  if (ret) {
    out += "0";
  } else {
    out += "-1";
  }

  FCGX_FPrintF(_fcgi_out, out.c_str());
  return ret;
}
Пример #24
0
bool SaveRequest::response(){
  //
  // /union/save.html?id=1&n=test&t=1&o=2&g=3&cam=4&b=5&p=1&t=t&ct=test%20content&img=image%20url&dst=dest%20url
  //
  if (!Request::response() && false)
    return false;

  Statement sql;
  string id = getProperty("id");

  sql << "INSERT INTO ad_union_ads (id, type, name, owner_id, group_id, campaign_id, budget, daily_budget, "\
         "click_price, click_count, title, content, img_url, dest_url, update_time)"
      << " VALUES (" << getProperty("id") << ',' << getProperty("tp") << ',' << mysqlpp::quote << getProperty("n") << ','
      << getProperty("o") << ',' << getProperty("g") << ',' << getProperty("cam") << ','
      << getProperty("b") << ',' << getProperty("b") << ',' << mysqlpp::quote << getProperty("p") << ",0,"
      << mysqlpp::quote << getProperty("tt") << ',' << mysqlpp::quote << getProperty("ct") << ',' << mysqlpp::quote << getProperty("img") << ','
      << mysqlpp::quote << getProperty("dst") << ", NOW())";

  int ret_code = -1;
  try {
    mysqlpp::SimpleResult res = QueryRunner("ad_db", CDbWServer).execute(sql);
    if (res) {
      ret_code = res.insert_id();
    }
  } catch (std::exception& e) {
    MCE_WARN("Store ad exception : " << e.what());
  } catch (...) {
    MCE_WARN("Store ad unkown exception.");
  }

  stringstream ss;
  ss << "Content-type: text/html\r\n\r\n" << ret_code;
  FCGX_FPrintF(_fcgi_out, ss.str().c_str());

  return ret_code > 0;
}
Пример #25
0
static void io_fcgi_write_http_status(void *context, int code, const char *message)
{
	FCGX_Request *request = (FCGX_Request *)context;
	FCGX_FPrintF(request->out, "Status: %d %s\r\n", code, message);
}
Пример #26
0
/* TODO: Comment */
static void *doit(void *a){
  int rc, thread_id = (pthread_t) a;
  FCGX_Request request;
  apr_pool_t* pool;
  struct range_request* rr;
  struct libcrange *lr;
  char *config_file = NULL;
  char * r_query;		/* range query */
  int r_status = 0;

  apr_initialize();
  atexit(apr_terminate);
  apr_pool_create(&pool, NULL);

  config_file = LIBCRANGE_CONF;

  lr = libcrange_new(pool, config_file);

  /* malloc for query */
  r_query = (char *)malloc(QUERY_STR_SIZE);

  FCGX_InitRequest(&request, 0, 0);

  for (;;)
    {
      static pthread_mutex_t accept_mutex = PTHREAD_MUTEX_INITIALIZER;

      apr_pool_t* sub_pool;

      apr_pool_create(&sub_pool, pool);

      /* zero it out */
      bzero(r_query, QUERY_STR_SIZE);
      r_status = 0;
	

      /* Some platforms require accept() serialization, some don't.. */
      pthread_mutex_lock(&accept_mutex);
      rc = FCGX_Accept_r(&request);
      pthread_mutex_unlock(&accept_mutex);

      if (rc < 0)
	break;

      
      r_status = get_range_query(&request, r_query);
      rr = range_expand(lr, sub_pool, r_query);

      FCGX_FPrintF(request.out, "Content-type: text/plain\r\n");
      
      /* set headers */
      if (range_request_has_warnings(rr)) {
      	const char *warnings = range_request_warnings(rr);
      	FCGX_FPrintF(request.out,
      		     "RangeException: %s\r\nRange_FCGI_Thread_Id: %d\r\n",
      		     warnings, thread_id);
      }

      /* End Delimiter */
      FCGX_FPrintF(request.out, "\r\n");

      /* r_status == 1, then wants list */
      if (r_status == 1) {
      	const char **nodes = range_request_nodes(rr);
      	while(*nodes) {
      	  FCGX_FPrintF(request.out, "%s\n", *nodes++);
      	}
      } else if (r_status == 0) {
      	FCGX_FPrintF(request.out, "%s\n", range_request_compressed(rr));
      }
      
      apr_pool_destroy(sub_pool);

      FCGX_Finish_r(&request);

    } /* for (;;) */

  /* free, what I hogged :-) */
  free(r_query);

  apr_pool_destroy(pool);

  return NULL;
}
Пример #27
0
void bridge_request_error(bridge_request_t *self, const char *message)
{
	FCGX_FPrintF(self->request.err, "error: %s\n", message);
	bridge_request_json_error(self, error_origin_server,
				  error_code_illegal_service, message);
}
Пример #28
0
int bridge_request_json_params_parse(bridge_request_t *self, DBusMessageIter *it,
				     struct json_object **result, const char **key)
{
	int ret;
	const char *unused;
	int type = dbus_message_iter_get_arg_type(it);

	*key = 0;
	*result = 0;
	switch (type) {
		case DBUS_TYPE_STRING:
		case DBUS_TYPE_SIGNATURE:
		case DBUS_TYPE_OBJECT_PATH: {
			char *value;
			dbus_message_iter_get_basic(it, &value);
			*result = json_object_new_string(value);
			break;
		}
		case DBUS_TYPE_UINT16:
		case DBUS_TYPE_UINT32:
		case DBUS_TYPE_UINT64: {
			uint64_t value = 0;
			dbus_message_iter_get_basic(it, &value);
			*result = json_object_new_int64(value);
			break;
		}
		case DBUS_TYPE_INT16:
		case DBUS_TYPE_INT32:
		case DBUS_TYPE_INT64:
		case DBUS_TYPE_BYTE: {
			int64_t value = 0;
			dbus_message_iter_get_basic(it, &value);
			*result = json_object_new_int64(value);
			break;
		}
		case DBUS_TYPE_DOUBLE: {
			double value;
			dbus_message_iter_get_basic(it, &value);
			*result = json_object_new_double(value);
			break;
		}
		case DBUS_TYPE_BOOLEAN: {
			int value;
			dbus_message_iter_get_basic(it, &value);
			*result = json_object_new_boolean(value);
			break;
		}
		case DBUS_TYPE_ARRAY:
		case DBUS_TYPE_STRUCT:
		case DBUS_TYPE_VARIANT: {
			DBusMessageIter args;
			dbus_message_iter_recurse(it, &args);
			ret = bridge_request_json_params(self,
				&args, result, ((type == DBUS_TYPE_ARRAY) || (type == DBUS_TYPE_STRUCT)));
			if (ret != 0)
				return ret;
			break;
		}
		case DBUS_TYPE_DICT_ENTRY: {
			DBusMessageIter args;
			dbus_message_iter_recurse(it, &args);
			if (dbus_message_iter_get_arg_type(&args) != DBUS_TYPE_STRING) {
				bridge_request_error(self,
					"dictionary with non-string keys not supported.");
				return EINVAL;
			}
			dbus_message_iter_get_basic(&args, key);
			if (!dbus_message_iter_has_next(&args))
				break;
			dbus_message_iter_next(&args);
			ret = bridge_request_json_params_parse(self, &args, result, &unused);
			if (ret != 0)
				return ret;
			break;
		}
		default:
			break;
	}
	if (!*result) {
		bridge_request_error(self,
			"Unexpected error while parsing D-Bus arguments.");
		FCGX_FPrintF(self->request.err, "arg: %i\n", dbus_message_iter_get_arg_type(it));
		return EINVAL;
	}
	return 0;
}
Пример #29
0
bool GetOneRequest::response() {
  if (!Request::response() && false)
    return false;
  long aid = getPropertyLong("id");

  Statement sql;
  sql << "SELECT id, type, name, owner_id, group_id, campaign_id, budget, daily_budget, "\
      "click_price, click_count, title, content, img_url, dest_url, update_time FROM ad_union_ads WHERE id=" << aid;
  stringstream ss;
  try {
    mysqlpp::StoreQueryResult res = QueryRunner("ad_db", CDbRServer).store(sql);
    if (!res) {
      FCGX_FPrintF(_fcgi_out, "Content-type: text/html\r\n\r\n-3");
      return false;
    }
    ss << "Content-type: text/html\r\n\r\n[";
    for (size_t i = 0; i<res.num_rows(); ++i) {
      mysqlpp::Row row = res.at(i);
      if (i) {
        ss << ",";
      }

      string name = row["name"].c_str();
      jsonEscape(name);
      int click_count = (int)row["click_count"];
      int click_price = (int)row["click_price"];
      int budget = (int)row["budget"];

      string title = row["title"].c_str();
      jsonEscape(title);
      string content = row["content"].c_str();
      jsonEscape(content);
      for(size_t i = 0; i < content.size(); ++i) {
        if (content[i] == '\r' || content[i] == '\n') {
          content[i] = ' ';
        }
      }

      ss << "{'id':'" << (long)row["id"] << '\''
         << ",'type':" << (long)row["type"] 
         << ", 'name':'" << name  << '\''
         << ", 'owner_id':'" << row["owner_id"] << '\''
         << ", 'group_id':'" << row["group_id"] << '\''
         << ", 'campaign_id':'" << row["campaign_id"] << '\''
         << ", 'budget':'" << budget << '\''
         << ", 'click_price':'" << click_price << '\''
         << ", 'click_count':'" << click_count << '\''
         << ", 'daily_budget':'" << row["daily_budget"] << '\''
         << ", 'title':'" << title << '\''
         << ", 'content':'" << content << '\''
         << ", 'img_url':'" << row["img_url"] << '\''
         << ", 'dest_url':'" << row["dest_url"] << '\''
         << ", 'update_time':'" << row["update_time"] << '\''
         << "}";
    }
    ss << "]";
  } catch (std::exception& e) {
    MCE_WARN("db err : " << e.what());
    FCGX_FPrintF(_fcgi_out, "Content-type: text/html\r\n\r\n-1");
    return false;
  } catch (...) {
    MCE_WARN("db unkown exception.");
    FCGX_FPrintF(_fcgi_out, "Content-type: text/html\r\n\r\n-2");
    return false;
  }
  MCE_DEBUG("response : " << ss.str());
  FCGX_PutS(ss.str().c_str(), _fcgi_out);
  return true;
}
Пример #30
0
void CgiService::Response(FCGX_Request *req, int status)
{
    FCGX_FPrintF(req->out,"Content-type: text/html\r\n");

    FCGX_FPrintF(req->out,"Status: ");
    switch (status)
    {
    case 200:
        FCGX_FPrintF(req->out,"200 OK");
        break;
    case 301:
        FCGX_FPrintF(req->out,"301 Moved Permanently");
        break;
    case 302:
        FCGX_FPrintF(req->out,"302 Found");
        break;
    case 307:
        FCGX_FPrintF(req->out,"307 Temporary Redirect");
        break;
    case 400:
        FCGX_FPrintF(req->out,"400 Bad Request");
        break;
    case 403:
        FCGX_FPrintF(req->out,"403 Forbidden");
        break;
    case 500:
        FCGX_FPrintF(req->out,"500 Internal Server Error");
        break;
    case 503:
        FCGX_FPrintF(req->out,"503 Service Unavailable");
        break;
    default:
        FCGX_FPrintF(req->out,"200 OK");
        break;
    }
    FCGX_FPrintF(req->out,"\r\n");
    FCGX_FFlush(req->out);
    FCGX_Finish_r(req);
}