Example #1
0
static void *doit(int id, Config &conf)
{
    
    FCGX_Request request;
	
    if(FCGX_InitRequest(&request, socketId.load(), 0) != 0)
    {
        //ошибка при инициализации структуры запроса
        printf("Can not init request\n");
        return NULL;
    }

	Router router(&request, &conf);
	
	router.addHandler("OPTIONS",	"/users/login", 		&OptUsersLogin);
	router.addHandler("GET",		"/users/login", 		&UsersInfo);
	router.addHandler("POST",		"/users/login", 		&PostUsersLogin);
	
	router.addHandler("OPTIONS",	"/users/add", 			&OptUsersAdd);
	router.addHandler("POST",		"/users/add", 			&PostUsersAdd);
	
	router.addHandler("OPTIONS",	".*", 					&OptDirs);
	router.addHandler("OPTIONS",	"/dirs/(?<id>\\d+)",	&OptDirs);
	
	router.addHandler("POST",		"/dirs", 				&PostCreateDir);
	router.addHandler("GET",		"/dirs/(\\d+)",			&GetDir);
	router.addHandler("DELETE",		"/dirs/(\\d+)",			&DelDir);
	
	router.addHandler("POST",		"/files/(\\d+)/(.+)",	&PutFile);
	router.addHandler("GET",		"/files/(\\d+)",		&GetFile);
	router.addHandler("DELETE",		"/files/(\\d+)",		&DelFile);


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

        pthread_mutex_lock(&accept_mutex);
        int rc = FCGX_Accept_r(&request);
		
		pthread_mutex_unlock(&accept_mutex);
        
        if(rc < 0)
        {
            //ошибка при получении запроса
            printf("Can not accept new request\n");
            break;
        }

	   	std::streambuf * cin_streambuf  = std::cin.rdbuf();
	    std::streambuf * cout_streambuf = std::cout.rdbuf();
	    std::streambuf * cerr_streambuf = std::cerr.rdbuf();    


        fcgi_streambuf cin_fcgi_streambuf(request.in);
        fcgi_streambuf cout_fcgi_streambuf(request.out);
        fcgi_streambuf cerr_fcgi_streambuf(request.err);

        std::cin.rdbuf(&cin_fcgi_streambuf);
        std::cout.rdbuf(&cout_fcgi_streambuf);
        std::cerr.rdbuf(&cerr_fcgi_streambuf);
		try
		{	
			router.Run();
		}
		catch (Error &e)
		{
			router.SetStatus(e.http_code());
			router.AddHeader("Content-Type", "application/json; charset=utf-8");
			router.AddContent(e.what());
			router.AcceptContent();
		}
		catch (std::exception &e)
		{
			std::cerr << e.what();
			router.SetStatus(Httpstatus::InternalServerError);
			router.AddHeader("Content-Type", "text/plain; charset=utf-8");
			router.AddContent(e.what());
			router.AcceptContent();
		}
		
		FCGX_Finish_r(&request);
		
        //завершающие действия - запись статистики, логгирование ошибок и т.п.

		router.Cleanup();


	    std::cin.rdbuf(cin_streambuf);
	    std::cout.rdbuf(cout_streambuf);
	    std::cerr.rdbuf(cerr_streambuf);

    }


    return NULL;
}
Example #2
0
void WebInterface::worker() {
	/* Backup the stdio streambufs */
	std::streambuf * cin_streambuf  = std::cin.rdbuf();
	std::streambuf * cout_streambuf = std::cout.rdbuf();
	std::streambuf * cerr_streambuf = std::cerr.rdbuf();

	const std::string kw_title(KW_TITLE);
	const std::string kw_head(KW_HEAD);
	const std::string kw_menu(KW_MENU);
	const std::string kw_content(KW_CONTENT);

	FCGX_Request request;

	/* Initialize FastCGI library and request */
	FCGX_Init();
	FCGX_InitRequest(&request, 0, FCGI_FAIL_ACCEPT_ON_INTR);

	LOG_DBG("FastCGI initialization success!");

	while (!stop_flag_) {
		if(FCGX_Accept_r(&request) >= 0) {

			fcgi_streambuf cin_fcgi_streambuf(request.in);
			fcgi_streambuf cout_fcgi_streambuf(request.out);
			fcgi_streambuf cerr_fcgi_streambuf(request.err);

			std::cin.rdbuf(&cin_fcgi_streambuf);
			std::cout.rdbuf(&cout_fcgi_streambuf);
			std::cerr.rdbuf(&cerr_fcgi_streambuf);

			/* getting the uri from the request */
			std::string uri;
			const char *uri_param = FCGX_GetParam("REQUEST_URI", request.envp);
			if(!uri_param) {
				LOG_ERR("Failed to retrieve the request URI environment value!");
				uri = URI_PAGE_ERROR;
			} else {
				uri = uri_param;
			}

			LOG_DBG("Request received: %s", uri.c_str());

			/* Check if URI is a file in the home folder and get the mime of
			 * that file (by extension) */
			std::string path;
			std::string mime = if_file_get_mime(uri, &path);

			if (!mime.empty()) {
				/* This is a file we need to serve */
				StringPtr file_data = Utils::read_file(path);
				std::cout << "Content-type: " << mime << "\r\n\r\n";
				std::cout << *(file_data);

				file_data.reset();
			} else {
				/* Parse the URI */
				std::map<std::string, std::string> uri_data = parseURI(uri);

				LOG_DBG("URI Parsed, page requested: %s",
						uri_data[URI_PAGE].c_str());

				/* Generate and serve the page depending on the URI */
				StringPtr page;
				std::string content_type = "text/html";

				/* Main page requested */
				if (uri_data[URI_PAGE].compare(URI_PAGE_MAIN) == 0) {
					bool success = false;

					/* Check if a command was sent from the client. */
					if (uri_data.find(URI_PAGE_COMMAND) != uri_data.end()) {
						success = add_command(uri_data[URI_PAGE_COMMAND]);
					}

					std::string s;
					/* Check if the request was sent from javascript or pure HTML */
					if(uri_data.find(URI_PAGE_SOURCE) != uri_data.end()) {
						LOG_DBG("This query's source IS javascript: %s, Source: %s",
								uri.c_str(), (uri_data[URI_PAGE_SOURCE]).c_str());
						content_type = "application/json";
						page = generate_command_json(success);
					} else {
						LOG_DBG("This query's source IS NOT javascript: %s", uri.c_str());
						/* Just generate a standard main page */
						page = generate_main_page();
					}
				/* Log page requested */
				} else if (uri_data[URI_PAGE].compare(URI_PAGE_LOG) == 0) {
					page = generate_log_page();

				/* Status page requested */
				} else if (uri_data[URI_PAGE].compare(URI_PAGE_STATUS) == 0) {
					page = generate_status_page();

				/* Console lines JSON page requested */
				} else if (uri_data[URI_PAGE].compare(URI_PAGE_CL) == 0) {
					if (uri_data.find(URI_PAGE_BEFORE) != uri_data.end()) {
						content_type = "application/json";
						page = generate_cljson_before(
								uri_data[URI_PAGE_BEFORE]);
					} else if (uri_data.find(URI_PAGE_AFTER)
							!= uri_data.end()) {
						content_type = "application/json";
						page = generate_cljson_after(uri_data[URI_PAGE_AFTER]);
					} else {
						page = generate_error_page();
					}

				/* Log lines JSON page requested */
				} else if (uri_data[URI_PAGE].compare(URI_PAGE_LL) == 0) {
					if (uri_data.find(URI_PAGE_BEFORE) != uri_data.end()) {
						content_type = "application/json";
						page = generate_lljson_before(
								uri_data[URI_PAGE_BEFORE]);
					} else if (uri_data.find(URI_PAGE_AFTER)
							!= uri_data.end()) {
						content_type = "application/json";
						page = generate_lljson_after(uri_data[URI_PAGE_AFTER]);
					} else {
						page = generate_error_page();
					}
				} else {
					page = generate_error_page();
				}

				/* Output the generated page with the correct content type */
				std::cout << "Content-type: " << content_type << "\r\n\r\n";
				std::cout << *(page.get());
			}

		}
		else {
			LOG_TRC("FCGX_Aceept_r returned less than 0!");
		}
	}

	LOG_TRC("Out of accept request loop!");

	// Free request strucure
	FCGX_Finish_r(&request);

	// Flag the thread as not running anymore.
	running_ = false;

	// restore stdio streambufs
	std::cin.rdbuf(cin_streambuf);
	std::cout.rdbuf(cout_streambuf);
	std::cerr.rdbuf(cerr_streambuf);
}