示例#1
0
文件: http.c 项目: GrayHatter/tox-dns
void http_thread(void *args)
{
    if(!init()) {
        print("http_init() failed\n");
        return;
    }

    while(FCGI_Accept() >= 0)
    {
        FCGI_printf("Content-type: text/html\r\nStatus: 200 OK\r\n\r\n");

        char *name = getenv("SCRIPT_NAME");
        _Bool q = 0;

        if(name[0] == '/' && name[1] == 'q') {
            if(name[2] == 0) {
                q = 1;
            } else if(strcmp(name + 2, "key") == 0) {
                uint8_t k[64];
                key_to_string(k, key.public);
                FCGI_fwrite(k, sizeof(k), 1, FCGI_stdout);
                continue;
            } else if(strcmp(name + 2, "stat") == 0) {
                FCGI_printf("Number of registered names: %u<br/>Number of successful Tox DNS requests: %u\n", stat.registered, stat.requests);
                continue;
            }
        }
示例#2
0
文件: demo.c 项目: rocflyhi/glow
int main(int argc, char *argv)
{
	int count = 0;
	while (FCGI_Accept() >= 0) {
		FCGI_printf("Content-type: text/*\r\n\r\n");
		printf("Hi, I am Zhangpengpeng.\t %d %s \n", count++, getenv("SERVER_NAME"));
	}
	return 0;
}
示例#3
0
static void fcgi_finish(struct fcgi_context *fc, const char* msg)
{
	if (fc->reply_state == REPLY_STATE_INIT) {
		FCGI_puts("Status: 502 Bad Gateway\nContent-type: text/plain\n");
		FCGI_printf("An error occurred while %s\n", msg);
	}

	if (fc->fd_stdin >= 0) close(fc->fd_stdin);
	if (fc->fd_stdout >= 0) close(fc->fd_stdout);
	if (fc->fd_stderr >= 0) close(fc->fd_stderr);

	if (fc->cgi_pid)
		kill(SIGTERM, fc->cgi_pid);
}
示例#4
0
文件: main.c 项目: Zhanyin/taomee
int main(int argc, char **argv)
{

	if (initiate(argv[0]) == -1)
		return -1;

	if (connect_2_analyze_server(&analyze_fd) == -1)
		analyze_broken = 1;
	else
		analyze_broken = 0;
	connect_2_backup_server(&backup_fd);

	store_result_t result;
	while( FCGI_Accept() >= 0) {
		//用cgic初始化获取post数据
		cgic_initiate(0, 0);
		FCGI_printf("Content-type:image/gif\r\n\r\n");
		//判断数据合法性,如合法则放入result中
		if( prepare_data(&result) == -1)
			goto continue_tag;

		//先发到缓存
		if (backup_fd == -1)
			connect_2_backup_server(&backup_fd);//重新连接
		if (backup_fd != -1)
			send_2_server(&result, &backup_fd, "backup", analyze_broken);


		//将数据发送出去
		if (analyze_fd == -1) {
			if (connect_2_analyze_server(&analyze_fd) == -1)//重新连接
				analyze_broken = 1;
			else
				analyze_broken = 0;
		}
		if(analyze_fd != -1)
			send_2_server(&result, &analyze_fd, "analyze", 0);

continue_tag:
		//释放cgic中取数据所分配的内存
		cgiFreeResources();
		FCGI_Finish();
	}
	close(analyze_fd);
	close(backup_fd);
	destroy();
	return 1;
}
示例#5
0
int main() {
	Database *db = Database::getInstance();
	Session *session = Session::getInstance();	
	
	while (FCGI_Accept() >= 0) {
		
		session->sessionInit();
		string result("fail");
		string detail("");
		Json::FastWriter fw;
		Json::Value root;
		vector<unordered_map<string,string>  >   query_result;
		if(session->checkSession() == false) {
			detail = detail + "unlogin";
		} else {
			unordered_map<string,string> ans;
			char * method = getenv("REQUEST_METHOD");
			if ( strcmp(method,"POST") == 0) {
				char *contentLength = getenv("CONTENT_LENGTH");
				int len;
				if (contentLength != NULL) {
					len = strtol(contentLength, NULL, 10);
				} else {
					len = 0;
				}
				int i, ch;
				string post_val="";
				for (i = 0; i < len; i++) {
					if ((ch = getchar()) < 0) {
						break;
					}
					post_val = post_val + (char) ch ;
				}
				ParseParam(post_val,ans);

			} else if(strcmp(method,"GET")==0){
				char* str = getenv("QUERY_STRING");
				string Param(str);
				ParseParam(Param,ans);
			}
			int argu_count = 0;
			if(ans.find("username") != ans.end())
				argu_count++;
			if(argu_count < 1) {
				detail = "参数错误!";

			} else {
				char query_buf[1024] = {0};
				string username,user_id;
				unordered_map<string,string>::iterator it;

				it = ans.find("username");
				username = it->second;
				
				user_id = session->getValue("user_id");
				snprintf(query_buf,sizeof(query_buf),"select user_id,username,nickname from users where username like '%s%%' and user_id != %d ",username.c_str(),atoi(user_id.c_str()));

				string query(query_buf);

				bool flag = db->dbQuery(query, query_result);
				
				for (size_t i = 0 ; i != query_result.size(); i++)
				{
					string uid = query_result[i]["user_id"];
					char buffer[1024]={0};
					snprintf(buffer,sizeof(buffer),"select * from friendship where user_id = %d and friend_id = %d ", atoi(user_id.c_str()),atoi(uid.c_str()) );
					string query_rows(buffer);
					int num = db->dbQuery(query_rows);
					string is_friend = num>0? "1": "0" ;
					query_result[i].insert(make_pair("is_friend",is_friend ));
				}
				if(flag ){
					result = "success" ;

				}else{
					detail = "用户名密码错误!";
				}
			} 
			
		}
		root["result"] = Json::Value(result);
		if(strcmp(result.c_str(),"success") == 0){
			Json::Value user_list;
			for(size_t i = 0 ; i != query_result.size(); i++ ){
				Json::Value user;
				user["user_id"]= Json::Value(query_result[i]["user_id"]);
				user["username"] = Json::Value(query_result[i]["username"]);
				user["nickname"] = Json::Value(query_result[i]["nickname"]);	
				user["is_friend"] = Json::Value(query_result[i]["is_friend"]);
				root["user_list"].append(user);
			}

		}else{
			root["detail"] = Json::Value(detail);
		}
		string str = fw.write(root);
		FCGI_printf("Content-type: application/json\r\n"
			"\r\n");
		FCGI_printf("%s",str.c_str());
	}
	return 0;
}
示例#6
0
int main() {
	Database *db = Database::getInstance();
	Session *session = Session::getInstance();

	while (FCGI_Accept() >= 0) {
		Json::FastWriter fw; 
		Json::Value root;
		string result("fail");
		string detail("");
		session->sessionInit();
		vector<unordered_map<string,string> >   query_result;
		if(session->checkSession() == false){
			detail = detail + "unlogin";

		}else{
			unordered_map<string,string> ans;
			char * method = getenv("REQUEST_METHOD");
			if ( strcmp(method,"POST") == 0) {
				char *contentLength = getenv("CONTENT_LENGTH");
				int len;
				if (contentLength != NULL) {
					len = strtol(contentLength, NULL, 10);
				} else {
					len = 0;
				}
				int i, ch;
				string post_val="";
				for (i = 0; i < len; i++) {
					if ((ch = getchar()) < 0) {
						break;
					}
					post_val = post_val + (char) ch ;
				}
				ParseParam(post_val,ans);

			} else if(strcmp(method,"GET")==0){
				char* str = getenv("QUERY_STRING");
				string Param(str);
				ParseParam(Param,ans);
			}
			int argu_count = 0;

			if(ans.find("team_id") != ans.end())
				argu_count++;
			if(argu_count < 1) {
				detail = "参数错误!";
			}
			else
			{
				char query_buf[1024] = {0};
				string user_id,team_id;
				unordered_map<string,string>::iterator it;
				it = ans.find("team_id");
				team_id = it->second;

				user_id = session->getValue("user_id");
				snprintf(query_buf,sizeof(query_buf),"select friend_id,username,nickname,sex from friendship inner join users on friend_id = users.user_id where friendship.user_id = %d and team_id = %d",atoi(user_id.c_str()),atoi(team_id.c_str()));
				string query(query_buf);
				int flag = db->dbQuery(query,query_result);
				if(flag ){
					result = "success" ;

				}else{
					detail = "用户名密码错误!";
				}
			}
		}
		root["result"] = Json::Value(result);
		if(strcmp(result.c_str(),"success") == 0){
			Json::Value friend_list;
			for(size_t i = 0 ; i != query_result.size(); i++ ){
				Json::Value friend_info;
				friend_info["friend_id"] = Json::Value(query_result[i]["friend_id"]);
				friend_info["friend_name"] = Json::Value(query_result[i]["username"]);
				friend_info["friend_nickname"] = Json::Value(query_result[i]["nickname"]);
				friend_info["friend_sex"] = Json::Value(query_result[i]["sex"]);
				friend_info["online"] = Json::Value(session->getOnline(atoi(query_result[i]["friend_id"].c_str()))?"1":"0");
				root["friend_list"].append(friend_info);
			}

		}else{
			root["detail"] = Json::Value(detail);
		}
		string str = fw.write(root);
		FCGI_printf("Content-type: application/json\r\n"
			"\r\n"
			"%s",str.c_str());
		
		
	}
	return 0;
}
示例#7
0
int main() {
	Database *db = Database::getInstance();
	Session *session = Session::getInstance();

	while (FCGI_Accept() >= 0) {
		session->sessionInit();
		string result("fail");
		string detail("");
		Json::FastWriter fw;
		Json::Value root;
		vector<unordered_map<string,string> >   query_result;
		if(session->checkSession() == false){
			detail = detail + "unlogin";

		}else{
			unordered_map<string,string> ans;
			char * method = getenv("REQUEST_METHOD");
			if ( strcmp(method,"POST") == 0) {
				char *contentLength = getenv("CONTENT_LENGTH");
				int len;
				if (contentLength != NULL) {
					len = strtol(contentLength, NULL, 10);
				} else {
					len = 0;
				}
				int i, ch;
				string post_val="";
				for (i = 0; i < len; i++) {
					if ((ch = getchar()) < 0) {
						break;
					}
					post_val = post_val + (char) ch ;
				}
				ParseParam(post_val,ans);

			} else if(strcmp(method,"GET")==0){
				char* str = getenv("QUERY_STRING");
				string Param(str);
				ParseParam(Param,ans);
			}
			int argu_count = 0;
			
			
			if(ans.find("team_name") != ans.end())
				argu_count++;
			if(argu_count < 1) {
				detail = "参数错误!";
			}
			else
			{
				char query_buf[1024] = {0};
				string user_id,team_name;
				unordered_map<string,string>::iterator it;
				it = ans.find("team_name");
				team_name = it->second;

				user_id = session->getValue("user_id");

				//查询是否有重名
				snprintf(query_buf,sizeof(query_buf),"select team_id from teams where user_id=%d and team_name=%s",atoi(user_id.c_str()),team_name.c_str());
				string query_exist(query_buf);
				int num = db->dbQuery(query_exist);
				if (num == 0) {
					//插入
					memset(query_buf,0,sizeof(query_buf));
					snprintf(query_buf,sizeof(query_buf),"insert  teams (user_id,team_name,team_type,remark) values(%d,'%s',0,'无')",atoi(user_id.c_str()),team_name.c_str());
					string query(query_buf);
					int rows = db->dbQuery(query);
					if(rows){
						result = "success" ;

					}else{
						detail = "网络链接错误!";
					}
				} else {
					detail = "已有同名组,请换名";
				}
			} 

		}
		root["result"] = Json::Value(result);
		if(strcmp(result.c_str(),"fail") == 0){
			root["detail"] = Json::Value(detail);
		}	
		string str = fw.write(root);
		FCGI_printf("Content-type: application/json\r\n"
			"\r\n"
			"%s",str.c_str());

	}
	return 0;
}
示例#8
0
int main (void) {
	char 		*ptr;
	json_t		*responseJSON, *jsonFinal;
	RESTdispatchClass*	root;
	logREST*	log = logREST::instance();
	
	// initialize the dispatch hierarchy
	root = initRESTDispatch();
	
	while (FCGI_Accept() >= 0) {
		RESTdispatchClass::httpMethod method;
		std::string	uri, query, body;
		std::vector<std::string> tokens;
		size_t 		bodyLen;
		size_t		tokenPos;
		// read in the critical environment variables and go to next iteration if any fail

		ptr = getenv("PATH_INFO");
		if (ptr) {
			uri.assign(ptr);
		} else continue;

		method = RESTdispatchClass::methodFromString(getenv("REQUEST_METHOD"));

		ptr = getenv("QUERY_STRING");
		if (ptr) {
			query.assign(ptr);
		} else continue;

		ptr = getenv("CONTENT_LENGTH");
		if (ptr) {
			bodyLen = ::atoi(ptr);
		} else {
	                 // For GET requests, etc., we don't get a CONTENT_LENGTH, which is OK.
		         bodyLen = 0;
		}
		
		// if there is post data, read it in
		if (bodyLen > 0) {
			char *bodyBuf = (char *)calloc(bodyLen, sizeof(char));
			if (bodyBuf == NULL) continue;
			FCGI_fread(bodyBuf, 1, bodyLen, FCGI_stdin);
			body.assign(bodyBuf, bodyLen);
			free(bodyBuf);
		}

		// chop up the URI and move the elements into a vector of strings
		tokens.clear();
		tokenPos = 0;
		while (tokenPos < uri.length() && uri.at(tokenPos) == '/')
			tokenPos ++;
		while (tokenPos != std::string::npos) {
			size_t nextTokenPos = uri.find_first_of("/\\", tokenPos+1);
			size_t tokenLen;
			if (nextTokenPos == std::string::npos) {
				tokenLen = uri.length() - tokenPos;
			} else {
				tokenLen = (nextTokenPos - tokenPos);
				nextTokenPos ++;
			}
			tokens.push_back(uri.substr(tokenPos, tokenLen));
			tokenPos = nextTokenPos;
		}
		
		// dispatch on the URI
		try {
			responseJSON = root->dispatch(tokens, 0, query, method, body);
		} catch (const std::exception& exc) {
			const char *mangled = typeid(exc).name();
			int status = -1;
			char *demangled = abi::__cxa_demangle(mangled, NULL, NULL, &status);
			FCGI_printf("Status: 500\r\nContent-type: text/plain\r\n\r\n"
						"Uncaught exception while processing request:\n"
						"Exception: %s\n"
						"What: %s\n\n",
						(status == 0 && demangled != 0)? demangled : mangled,
						exc.what());
			if (demangled != 0)
				free(demangled);
			continue;
		}

		if (responseJSON == NULL) {
			FCGI_printf("Status: 404\r\nContent-Type: text/plain\r\n\r\n"
						"Dispatch method returned NULL.\r\n");
			continue;
		}
		
		// add some things to the JSON response...
		jsonFinal = json_pack("{sOsissss}", "response", responseJSON, 
								"id", REST_ID, 
								"name", REST_NAME,
								"connected", "true");
		
		// print the result back to the client
		writeJSONResponse(jsonFinal, JSON_COMPACT);

		// log everything
		log->open(REST_LOGFILE);
		char *response = jsonFinal? json_dumps(jsonFinal, JSON_COMPACT) : NULL;
		log->write(tokens, query, body, to_string(method), response);
		if (response)
			::free(response);
		log->close();
		
		// clean up
		tokens.clear();
		json_decref(jsonFinal);
		tokenPos = 0;
	}
}