static void test_parse_http_request() {
  struct mg_request_info ri;
  char req1[] = "GET / HTTP/1.1\r\n\r\n";
  char req2[] = "BLAH / HTTP/1.1\r\n\r\n";
  char req3[] = "GET / HTTP/1.1\r\nBah\r\n";
  char req4[] = "GET / HTTP/1.1\r\nA: foo bar\r\nB: bar\r\nbaz\r\n\r\n";

  ASSERT(parse_http_request(req1, sizeof(req1), &ri) == sizeof(req1) - 1);
  ASSERT(strcmp(ri.http_version, "1.1") == 0);
  ASSERT(ri.num_headers == 0);

  ASSERT(parse_http_request(req2, sizeof(req2), &ri) == -1);
  ASSERT(parse_http_request(req3, sizeof(req3), &ri) == -1);

  // TODO(lsm): Fix this. Header value may span multiple lines.
  ASSERT(parse_http_request(req4, sizeof(req4), &ri) == sizeof(req4) - 1);
  ASSERT(ri.num_headers == 3);
  ASSERT(strcmp(ri.http_headers[0].name, "A") == 0);
  ASSERT(strcmp(ri.http_headers[0].value, "foo bar") == 0);
  ASSERT(strcmp(ri.http_headers[1].name, "B") == 0);
  ASSERT(strcmp(ri.http_headers[1].value, "bar") == 0);
  ASSERT(strcmp(ri.http_headers[2].name, "baz\r\n\r") == 0);
  ASSERT(strcmp(ri.http_headers[2].value, "") == 0);

  // TODO(lsm): add more tests.
}
Exemple #2
0
void handle_request(char* client_message, int sock) {
  struct slre_cap caps[4], params[2];
  parse_http_request(client_message, caps);

  char *path = malloc(caps[1].len + 1);
  memcpy(path, caps[1].ptr, caps[1].len);
  path[caps[1].len] = '\0';

  if (!slre_match("^/([a-z]+)/([a-z]+)", path, strlen(path), params, 2, 0) > 0) {
    printf("Error parsing [%s]\n", path);
    exit(1);
  } else {
    char *service = malloc(params[0].len + 1);
    memcpy(service, params[0].ptr, params[0].len);
    service[params[0].len] = '\0';

    char *username = malloc(params[1].len + 1);
    memcpy(username, params[1].ptr, params[1].len);
    username[params[1].len] = '\0';
    char *image_url;


    if (strcmp(service, "instagram") == 0) {
      image_url = get_instagram_url_for(username);
    } else if (strcmp(service, "facebook") == 0) {
      image_url = get_facebook_url_for(username);
    } else if (strcmp(service, "twitter") == 0) {
      image_url = get_twitter_url_for(username);
    } else if (strcmp(service, "gravatar") == 0) {
      image_url = get_gravatar_url_for(username);
    }

    download_jpeg(image_url, sock);
  }
}
Exemple #3
0
int check_client_header(FILE *file) {
  char buffer[1024];
  http_request request;

  fgets_or_exit(buffer, 1024, file);

  if (parse_http_request(buffer, &request) == 1) {
    char *url = rewrite_url(request.url);
    if (request.method != HTTP_GET) {
      skip_headers(file);
      send_response(file, 400, "Bad request", "Bad request\r\n");
      free(url);
      return 400;
    } else if (strcmp(url, "/")) {
      skip_headers(file);
      send_response(file, 404, "Not Found", "Not Found\r\n");
      free(url);
      return 404;
    } else {
      skip_headers(file);
      free(url);
      return 200;
    }
  } else {
    skip_headers(file);
    send_response(file, 400, "Bad Request", "Bad request\r\n");
    return 400;
  }
}
// Receive a HTTP request
void httpd_recv(chanend tcp_svr, xtcp_connection_t *conn)
{
  struct httpd_state_t *hs = (struct httpd_state_t *) conn->appstate;
  char data[XTCP_CLIENT_BUF_SIZE];
  int len;

  // Receive the data from the TCP stack
  len = xtcp_recv(tcp_svr, data);

  // If we already have data to send, return
  if ( hs == NULL || hs->dptr != NULL)
    {
      return;
    }

  // Otherwise we have data, so parse it
  parse_http_request(hs, &data[0], len);

  // If we are required to send data
  if (hs->dptr != NULL)
    {
      // Initate a send request with the TCP stack.
      // It will then reply with event XTCP_REQUEST_DATA
      // when it's ready to send
      xtcp_init_send(tcp_svr, conn);
    }
  ////
}
Exemple #5
0
void client_handler(client_t* client) {
	int ret;

	assert(client->fired_event != NULL);

	// Two stages
	// First, read HTTP request, interested in readable event
	if (client->stage == CS_READ_REQUEST) {
		if (client->fired_event->filter == EVFILT_READ) {
			ret = parse_http_request(client);
			if (ret) goto close;

			ret = generate_http_response(client);
			if (ret) goto close;

			client->stage = CS_WRITE_RESPONSE;
		}
	}
	// Then, write HTTP response, interested in writable event
	else if (client->stage == CS_WRITE_RESPONSE) {
		if (client->fired_event->filter == EVFILT_WRITE) {
			ret = write_http_response(client,
					client->fired_event->data);
			// When it went wrong or just finished correctly,
			// close the client
			if (ret) goto close;
		}
	}

	// Clear the event since it has been handled
	client->fired_event = NULL;
	return;
close:
	close_client(client);
}
static void test_lua(void) {
  static struct mg_connection conn;
  static struct mg_context ctx;

  char http_request[] = "POST /foo/bar HTTP/1.1\r\n"
      "Content-Length: 12\r\n"
      "Connection: close\r\n\r\nhello world!";
  const char *page = "<? print('hi') ?>";
  lua_State *L = luaL_newstate();

  conn.ctx = &ctx;
  conn.buf = http_request;
  conn.buf_size = conn.data_len = strlen(http_request);
  conn.request_len = parse_http_request(conn.buf, conn.data_len,
                                        &conn.request_info);
  conn.content_len = conn.data_len - conn.request_len;

  prepare_lua_environment(&conn, L);
  ASSERT(lua_gettop(L) == 0);

  check_lua_expr(L, "'hi'", "hi");
  check_lua_expr(L, "request_info.request_method", "POST");
  check_lua_expr(L, "request_info.uri", "/foo/bar");
  check_lua_expr(L, "request_info.num_headers", "2");
  check_lua_expr(L, "request_info.remote_ip", "0");
  check_lua_expr(L, "request_info.http_headers['Content-Length']", "12");
  check_lua_expr(L, "request_info.http_headers['Connection']", "close");
  luaL_dostring(L, "post = read()");
  check_lua_expr(L, "# post", "12");
  check_lua_expr(L, "post", "hello world!");
  lua_close(L);
}
Exemple #7
0
int main(int argc, char *argv[])
{
    int socket_fd, client_socket, addr_size;
    int yes = 1;
    struct sockaddr_in server, client;
    char buffer[10000];
    ssize_t msglen;
    int http_port = 8000;

    socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_fd == -1)
    {
        puts("Error creating socket");
        return -1;
    }

    if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
    {
        puts("Set reuse addr on socket failed");
    }

    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(http_port);

    if (bind(socket_fd, (struct sockaddr *) &server, sizeof(server)) < 0)
    {
        puts("Error bind port");
        return -2;
    }
    printf("Bind port %d done\n", http_port);

    listen(socket_fd, 3);
    puts("Waiting client connection");

    addr_size = sizeof(struct sockaddr_in);

    while ((client_socket = accept(socket_fd, (struct sockaddr *) &client, (socklen_t *) &addr_size)))
    {
        http_request request;
        puts("Connection accepted");

        msglen = recv(client_socket, (void *) buffer, sizeof(buffer), 0);
        if (msglen < 0) {
            puts("Error recv");
        }else{
            request = parse_http_request(msglen, buffer);
            puts(request.method);
            puts(request.path);
            puts(request.http_version);
        }

        send(client_socket, response, strlen(response), 0);
        close(client_socket);
    }

    return 0;
}
int main(int argc, char **argv, char **envp)
{
	int fd;
	char *p;

	background_process(NAME, UID, GID);	
	fd = serve_forever(PORT);
	set_io(fd);

	parse_http_request();	
}
Exemple #9
0
int main() 
{   
    char buf[BUF_SIZE];
    int socket_serveur, socket_client;
    if((socket_serveur = creer_serveur(8080)) == EXIT_FAILURE) {
        return EXIT_FAILURE;
    }

    initialiser_signaux();
    const char * message_bienvenue = "Bonjour, bienvenue sur le serveur\nle plus parfait du monde.\nSur votre droite, vous pourrez voir\nrien qui n\'est plus parfait que\nle serveur qui defie la perfection.\nSur votre gauche, pareil.\nNenufar.\nOgnon.\r\n";

    while (1) {
        socket_client = accept(socket_serveur, NULL, NULL);
        if (socket_client == -1) {
            perror("accept");
            return EXIT_FAILURE;
        }
        FILE *fsocket = fdopen(socket_client, "w+");
        switch (fork()) {
	case -1:
	    perror("fork");
	    return EXIT_FAILURE;
	case 0:
	    /* On peut maintenant dialoguer avec le client */
                
	    fgets_or_exit(buf, BUF_SIZE, fsocket);
	    http_request request;

	    int bad_request = parse_http_request(buf, &request);
	    skip_header(fsocket);
                
	    if (bad_request == 0) {
		send_response(fsocket, 400, "Bad Request", "Bad Request\r\n");
	    }
	    else if (request.method == HTTP_UNSUPPORTED) {
		send_response(fsocket, 405, "Method not allowed", "Method not allowed\r\n");
	    }
	    else if (strcmp(request.url, "/") == 0) {
		send_response(fsocket, 200, "OK", message_bienvenue);
	    }
	    else {
		send_response(fsocket, 404, "Not Found", "Not Found\r\n");
	    }
	    fclose(fsocket);
	    return EXIT_SUCCESS;
	default:
	    fclose(fsocket);
	    close(socket_client);
        }
    }

    return EXIT_SUCCESS;
}
Exemple #10
0
static void test_should_keep_alive(void) {
  struct mg_connection conn;
  struct mg_context ctx;
  char req1[] = "GET / HTTP/1.1\r\n\r\n";
  char req2[] = "GET / HTTP/1.0\r\n\r\n";
  char req3[] = "GET / HTTP/1.1\r\nConnection: close\r\n\r\n";
  char req4[] = "GET / HTTP/1.1\r\nConnection: keep-alive\r\n\r\n";

  memset(&conn, 0, sizeof(conn));
  conn.ctx = &ctx;
  parse_http_request(req1, sizeof(req1), &conn.request_info);

  ctx.config[ENABLE_KEEP_ALIVE] = "no";
  ASSERT(should_keep_alive(&conn) == 0);

  ctx.config[ENABLE_KEEP_ALIVE] = "yes";
  ASSERT(should_keep_alive(&conn) == 1);

  conn.must_close = 1;
  ASSERT(should_keep_alive(&conn) == 0);

  conn.must_close = 0;
  parse_http_request(req2, sizeof(req2), &conn.request_info);
  ASSERT(should_keep_alive(&conn) == 0);

  parse_http_request(req3, sizeof(req3), &conn.request_info);
  ASSERT(should_keep_alive(&conn) == 0);

  parse_http_request(req4, sizeof(req4), &conn.request_info);
  ASSERT(should_keep_alive(&conn) == 1);

  conn.status_code = 401;
  ASSERT(should_keep_alive(&conn) == 0);

  conn.status_code = 200;
  conn.must_close = 1;
  ASSERT(should_keep_alive(&conn) == 0);
}
int handle_connection(int new_sock_conn, char *buf,
		      struct sockaddr_in cli_addr,
		      int cli_len, FILE *debg_ofp)
{
    int                   status = 0;
    http_packet_info_t    req_info;

 
    parse_http_request(buf, &req_info, debg_ofp);

    status = respond_to_http(new_sock_conn, req_info,
			     cli_addr, cli_len, debg_ofp);
    fprintf(debg_ofp, "DEBUG: Error in replying back to UDP\n");
    fflush(debg_ofp);
    return status;
}
Exemple #12
0
void HTTPProcessor(uint8 s, char * buf)
{
	uint8* http_response;
	st_http_request *http_request;

	http_response = (uint8*)rx_buf;
	http_request = (st_http_request*)tx_buf;

	memset(tx_buf,0x00,MAX_URI_SIZE);
	parse_http_request(http_request, buf);		// After analyze request, convert into http_request
	memset(rx_buf,0x00,MAX_URI_SIZE);

	//method Analyze
	switch (http_request->METHOD)				
	{
		case METHOD_ERR :	
			memcpy(http_response, ERROR_REQUEST_PAGE, sizeof(ERROR_REQUEST_PAGE));
			TCPSend(s, (int8 *)http_response, strlen((char*)http_response));
			break;
		case METHOD_HEAD:
		case METHOD_GET:
		case METHOD_POST:
			if (!strcmp((char*)http_request->URI, "/")) strcpy(http_request->URI, (char const*)homepage_default);	// If URI is "/", respond by index.htm 

			RESTProcessor(http_request);

			//get http type from type
			find_http_uri_type(&http_request->TYPE, http_request->URI);	//Check file type (HTML, TEXT, GIF, JPEG are included)

			if(http_request->TYPE == PTYPE_PL || http_request->TYPE == PTYPE_CGI)
			{
				CGIProcessor(http_request, (char*)http_response);
			}

			FILESend(s, http_request, (char*)http_response);

			break;

		default:
			break;
	}
}
Exemple #13
0
void httpd_recv(chanend tcp_svr,
                xtcp_connection_t *conn,
                chanend page_svr,
                chanend led_svr)
{
  struct httpd_state_t *hs = (struct httpd_state_t *) conn->appstate;
  char data[XTCP_CLIENT_BUF_SIZE];
  int len; 

  len = xtcp_recv(tcp_svr, data);
  // this assumes that a request fits in one read!!
  if (hs == NULL || hs->pss.cmdptr != 0) 
    return;

  parse_http_request(hs, &data[0], len, page_svr, led_svr);
  if (hs->pss.cmdptr != 0)
    xtcp_init_send(tcp_svr, conn);
  else
    xtcp_close(tcp_svr, conn);
}
Exemple #14
0
void fgets_or_exit(char * buf , int size , FILE * stream ){
//VARIABLE 
	/*char* e400="HTTP/1.1 400 Bad Request\r\nConnection: close\r\nContent-Length: 17\r\n\r\n400 Bad request\r\n";
	char* w200="HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Length: 17\r\n\r\nSalut poto ! :)\r\n";
	char* e404="HTTP/1.1 404 Not Found\r\nConnection: close\r\nContent-Length: 15\r\n\r\n404 Not Found\r\n";*/
	http_request request;
	fgets(buf, size,stream);

	char * request_line = malloc(size);
	strcpy(request_line, buf);
	skip_headers (stream , size);
	int bad_request = parse_http_request(request_line,&request);

	if ( bad_request )
		send_response ( stream , 400 , "Bad Request" , "Bad request\r\n" );
	else if (request.method == HTTP_UNSUPPORTED )
		send_response ( stream , 405 , "Method Not Allowed" , "Method Not Allowed\r\n" );
	else if (strcmp(request.url , "/" ) == 0)
		send_response ( stream , 200 , "OK" , "Salut poto ! :)\r\n" );
	else
		send_response ( stream , 404 , "Not Found" , "Not Found\r\n" );
}
Exemple #15
0
void dispatch_request(int socket_fd) {

	static char buffer[BUFSIZE + 1];
	static struct http_request request;

	request.socket_fd = socket_fd;

	long ret = read(socket_fd,buffer,BUFSIZE); 	// read Web request in one go
	if(ret > 0 && ret < BUFSIZE)			// return code is valid chars 
		buffer[ret]=0;				// terminate the buffer
	else buffer[0]=0;

	if(parse_http_request(buffer, &request) == 0) {
		printf("Warning: Could not parse incomming request dumping headers!\n");
		printf("%s", buffer);
		http_response_send("400 Bad Request", "text/plain", &request, "Could not parse HTTP headers");
	}

	struct route *active_route;
	if(routes_match(&request, &active_route) == 0) {
		printf("Warning: 404 on %s\n", request.path);
		http_response_send("404 Not Found", "text/plain", &request, "Resource not found");
	}
	else {
		if(active_route->type == RT_STATIC) {
			printf("Log: Found static route %s\n", active_route->static_content_source);
			http_response_send("200 OK", active_route->content_type, &request, active_route->static_content);
		}
		else if(active_route->type == RT_DYNAMIC) {
			printf("Log: Found dynamic route %s\n", active_route->request_string);
			(*active_route->callback)(&request);
		}
		else {
			printf("Warning: Request method not implemented dumping request\n");
			http_response_send("503 Not Implemented", "text/plain", &request, "Method not implemented");
		}
	}
	destroy_request(&request);
} 
static void process_new_connection(struct mg_connection *conn) {
  struct mg_request_info *ri = &conn->request_info;
  const char *cl;

  reset_per_request_attributes(conn);

  // If next request is not pipelined, read it in
  if ((conn->request_len = get_request_len(conn->buf, conn->data_len)) == 0) {
    conn->request_len = read_request(conn->client.sock,
        conn->buf, conn->buf_size, &conn->data_len);
  }
  assert(conn->data_len >= conn->request_len);
  if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
    mg_send_http_error(conn, 413, "Request Too Large", "");
    return;
  } if (conn->request_len <= 0) {
    return;  // Remote end closed the connection
  }

  // Nul-terminate the request cause parse_http_request() uses sscanf
  conn->buf[conn->request_len - 1] = '\0';
  if (!parse_http_request(conn->buf, ri)) {
    // Do not put garbage in the access log, just send it back to the client
    mg_send_http_error(conn, 400, "Bad Request",
        "Cannot parse HTTP request: [%.*s]", conn->data_len, conn->buf);
  } else if (strcmp(ri->http_version, "1.0") && strcmp(ri->http_version, "1.1")) {
    // Request seems valid, but HTTP version is strange
    mg_send_http_error(conn, 505, "HTTP version not supported", "");
  } else {
    // Request is valid, handle it
    cl = get_header(ri, "Content-Length");
    conn->content_len = cl == NULL ? -1 : strtoll(cl, NULL, 10);
    conn->birth_time = time(NULL);
    handle_request(conn);
    discard_current_request_from_buffer(conn);
  }
}
Exemple #17
0
test_parse_http_request(void)
{
	struct mg_request_info	ri;
	struct usa		usa;

	char	empty[] = "";
	char	bad1[] = "BOO / HTTP/1.0\n\n";
	char	bad2[] = "GET / TTP/1.0\n\n";
	char	bad3[] = "GET TTP/1.0\n\n";
	char	bad4[] = "GET \n/ HTTP/1.0\n\n";
	char	good[] = "GET / HTTP/1.0\n\n";
	char	good2[] = "GET / HTTP/1.1\r\nA: b c\nB: c d\r\nC:  \r\n\n";

	if (parse_http_request(empty, &ri, &usa) != FALSE)
		fail("%s: empty request", __func__);

	if (parse_http_request(bad1, &ri, &usa) != FALSE ||
	    parse_http_request(bad2, &ri, &usa) != FALSE ||
	    parse_http_request(bad3, &ri, &usa) != FALSE ||
	    parse_http_request(bad4, &ri, &usa) != FALSE)
		fail("%s: bad request parsed successfully", __func__);

	if (parse_http_request(good, &ri, &usa) != TRUE)
		fail("%s: good request", __func__);

	if (parse_http_request(good2, &ri, &usa) != TRUE ||
	    ri.num_headers != 3 ||
	    strcmp(ri.http_headers[0].name, "A") != 0 ||
	    strcmp(ri.http_headers[0].value, "b c") != 0 ||
	    strcmp(ri.http_headers[1].name, "B") != 0 ||
	    strcmp(ri.http_headers[1].value, "c d") != 0 ||
	    strcmp(ri.http_headers[2].name, "C") != 0 ||
	    strcmp(ri.http_headers[2].value, "") != 0)
		fail("%s: good2 request", __func__);

}
Exemple #18
0
/**
 * Establish a connection from proxenet -> server.
 * If proxy forwarding configured, then this function performs the negociation with the other proxy.
 * If the host applies for SSL intercept rules, this function also handles the SSL handshake.
 *
 * @return 0 if successful, -1 otherwise
 */
int create_http_socket(request_t* req, sock_t* server_sock, sock_t* client_sock, ssl_context_t* ssl_ctx)
{
        int retcode;
        char *host, *port;
        char sport[7] = {0, };
        http_infos_t* http_infos = &req->http_infos;
        bool use_proxy = (cfg->proxy.host != NULL);
        bool use_socks_proxy = use_proxy && (cfg->is_socks_proxy==true);
        bool use_http_proxy = use_proxy && (cfg->is_socks_proxy==false);
        char errmsg[512]={0,};

        if (parse_http_request(req) < 0){
                xlog(LOG_ERROR, "%s\n", "Failed to extract valid parameters from URL.");
                return -1;
        }

        ssl_ctx->use_ssl = req->is_ssl;
        proxenet_xsnprintf(sport, sizeof(sport), "%hu", http_infos->port);

        /* do we forward to another proxy ? */
        if (use_proxy) {
                host = cfg->proxy.host;
                port = cfg->proxy.port;
        } else {
                host = http_infos->hostname;
                port = sport;
        }


#ifdef DEBUG
        xlog(LOG_DEBUG, "Relay request %s to '%s:%s (type=%d)'\n",
             use_http_proxy ? "via HTTP proxy" : "direct",
             host, port, http_infos->proto_type);
#endif

        retcode = proxenet_open_socket(host, port);
        if (retcode < 0) {
                proxenet_xsnprintf(errmsg, sizeof(errmsg), "Cannot connect to %s:%s<br><br>Reason: %s",
                                   host, port, errno?strerror(errno):"<i>proxenet_open_socket()</i> failed");

                generic_http_error_page(*server_sock, errmsg);
                return -1;
        }

        if (cfg->verbose > 2)
                xlog(LOG_INFO, "Socket to %s '%s:%s': fd=%d\n",
                     use_http_proxy?"HTTP proxy":(use_socks_proxy?"SOCKS4 proxy":"server"),
                     host, port, retcode);

        *client_sock = retcode;

        req->do_intercept = apply_intercept_rules(http_infos);

        if (cfg->verbose > 1) {
                xlog(LOG_INFO, "Server '%s' %s match filter '%s' with pattern '%s'\n",
                     http_infos->hostname,
                     req->do_intercept ? "do" : "do not",
                     cfg->intercept_mode==INTERCEPT_ONLY?"INTERCEPT_ONLY":"INTERCEPT_EXCEPT",
                     cfg->intercept_pattern);
        }


        if(use_socks_proxy){
                char*rhost = http_infos->hostname;
                int  rport = http_infos->port;
                retcode = proxenet_socks_connect(*client_sock, rhost, rport, true);
                if( retcode<0 ){
                        proxenet_xsnprintf(errmsg, sizeof(errmsg), "Failed to open SOCKS4 tunnel to %s:%s.\n",
                                 host, port);
                        generic_http_error_page(*server_sock, errmsg);
                        xlog(LOG_ERROR, "%s", errmsg);
                        return -1;
                }
        }

        /* set up specific sockets */
        switch (http_infos->proto_type){
                case HTTPS:
                        if(cfg->verbose > 2)
                                xlog(LOG_INFO, "Creating a new HTTPS socket: %d/%d proxy=%s\n", client_sock, server_sock, use_socks_proxy?"true":"false");
                        return create_https_socket(req, client_sock, server_sock, ssl_ctx, use_socks_proxy);

                default:
                        break;
        }

        return 0;
}
/* HTTP Server Run */
void httpServer_run(uint16_t server_port)
{
	int8_t sock; 			// HW socket number
	uint8_t sock_status;	// HW socket status
	int8_t seqnum; 			// Sequence number
	int16_t len;
	
#ifdef _HTTPSERVER_DEBUG_
	uint8_t destip[4] = {0, };	// Destination IP address
	uint16_t destport = 0;		// Destination Port number
#endif
	
	sock = getAvailableHTTPSocketNum(); // Get the H/W socket number
	if(sock < 0) return; // HW socket allocation failed
	
	seqnum = getHTTPSequenceNum(sock);
	
	http_request = (st_http_request *)httpserver.recvbuf;		// HTTP Request Structure
	parsed_http_request = (st_http_request *)http_req;
	//parsed_http_request = (st_http_request *)httpserver.sendbuf; // old
	
	/* Web Service Start */
	sock_status = getSn_SR(sock);
	switch(sock_status)
	{
		case SOCK_ESTABLISHED:
			// Interrupt clear
			if(getSn_IR(sock) & Sn_IR_CON)
			{
				setSn_IR(sock, Sn_IR_CON);
			}

			// HTTP Process states
			switch(HTTPSock[seqnum].status)
			{
				case STATE_HTTP_IDLE :
					if ((len = getSn_RX_RSR(sock)) > 0)
					{
						if (len > DATA_BUF_SIZE) len = DATA_BUF_SIZE;
						if ((len = recv(sock, (uint8_t *)http_request, len)) < 0) break;	// Exception handler
						
						*(((uint8_t *)http_request) + len) = '\0';	// End of string (EOS) marker
						
						parse_http_request(parsed_http_request, (uint8_t *)http_request);

#ifdef _HTTPSERVER_DEBUG_
						printf("> HTTP Request START ==========\r\n");
						printf("%s", (uint8_t *)http_request);
						printf("> HTTP Request END ============\r\n");
#endif
						
#ifdef _HTTPSERVER_DEBUG_
						getSn_DIPR(sock, destip);
						destport = getSn_DPORT(sock);
						printf("\r\n");
						printf("> HTTPSocket[%d] : HTTP Request received ", sock);
						printf("from %d.%d.%d.%d : %d\r\n", destip[0], destip[1], destip[2], destip[3], destport);
#endif

#ifdef _HTTPSERVER_DEBUG_
						printf("> HTTPSocket[%d] : [State] STATE_HTTP_REQ_DONE\r\n", sock);
#endif
						// HTTP 'response' handler; includes send_http_response_header / body function
						http_process_handler(sock, parsed_http_request);

						if(HTTPSock[seqnum].file_len > 0) HTTPSock[seqnum].status = STATE_HTTP_RES_INPROC;
						else HTTPSock[seqnum].status = STATE_HTTP_RES_DONE; // Send the 'HTTP response' end
						
					}
					break;


				case STATE_HTTP_RES_INPROC :
					/* Repeat: Send the remain parts of HTTP responses */
#ifdef _HTTPSERVER_DEBUG_
					printf("> HTTPSocket[%d] : [State] STATE_HTTP_RES_INPROC\r\n", sock);
#endif
					// Repeatedly send remaining data to client
					send_http_response_body(sock, http_response, 0);

					if(HTTPSock[seqnum].file_len == 0) HTTPSock[seqnum].status = STATE_HTTP_RES_DONE;
					break;

				case STATE_HTTP_RES_DONE :
#ifdef _HTTPSERVER_DEBUG_
					printf("> HTTPSocket[%d] : [State] STATE_HTTP_RES_DONE\r\n", sock);
#endif
					// Socket file info structure re-initialize
					HTTPSock[seqnum].file_len = 0;
					HTTPSock[seqnum].file_offset = 0;
					HTTPSock[seqnum].file_start = 0;
					HTTPSock[seqnum].status = STATE_HTTP_IDLE;
					
#ifdef _USE_WATCHDOG_
					HTTPServer_WDT_Reset();
#endif
					http_disconnect(sock);
					break;

				default :
					break;
			}
			break;

		case SOCK_CLOSE_WAIT:
#ifdef _HTTPSERVER_DEBUG_
			printf("> HTTPSocket[%d] : ClOSE_WAIT\r\n", sock);	// if a peer requests to close the current connection
#endif
			// Socket file info structure re-initialize: HTTP connection 'close'
			HTTPSock[seqnum].file_len = 0;
			HTTPSock[seqnum].file_offset = 0;
			HTTPSock[seqnum].file_start = 0;
			HTTPSock[seqnum].status = STATE_HTTP_IDLE;
			
			http_disconnect(sock);
			break;

		case SOCK_INIT:
			listen(sock);
			break;

		case SOCK_LISTEN:
			break;

		case SOCK_SYNSENT:
		//case SOCK_SYNSENT_M:
		case SOCK_SYNRECV:
		//case SOCK_SYNRECV_M:
			break;

		case SOCK_CLOSED:
#ifdef _HTTPSERVER_DEBUG_
			//printf("> HTTPSocket[%d] : CLOSED\r\n", sock);
#endif
			if(server_port == 0) server_port = HTTP_SERVER_PORT;
			if(socket(sock, Sn_MR_TCP, server_port, 0x00) == sock) // Init / Reinitialize the socket
			{
#ifdef _HTTPSERVER_DEBUG_
				printf("> HTTPSocket[%d] : SERVER OPEN, Port: %d\r\n", sock, server_port);
#endif
				;
			}
			break;

		default :
			break;
	} // end of switch

#ifdef _USE_WATCHDOG_
	HTTPServer_WDT_Reset();
#endif
}
int init_socket_tcp(int port){
  //IpV4 - TCP Socket
  int server_socket = socket(AF_INET, SOCK_STREAM, 0);
  int server_init_state = -1;
  if (server_socket == (-1)){
    //Error while creating tcp socket
    perror("init_socket_tcp");
    //Cancelling next operations
    return server_socket;
  }
  //Binding socket
  if ((server_init_state = bind_socket_tcp(server_socket, port)) == -1)
    //Cancelling next operations
    return server_init_state;
  //Listening
  if ((server_init_state = listen_socket_tcp(server_socket)) == -1)
    //Cancelling next operations
    return server_init_state;
  //LOG
  struct tm * timeinfo;
  timeinfo = time_get_time();
  printf("[%d:%d:%d] Server started on port %d\n", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, port);
  //Accepting connections (Server loop process)
  if (!fork()){
    //Init signals
    init_signals();
    //Clients accept() loop
    while(1){
      //Client information
      struct sockaddr_in client_addr;
      //Accepting client
      int client_socket = accept_socket_tcp(server_socket, &client_addr);
      if (client_socket != (-1)){
	//LOG
	_client_idata client_information;
	  get_client_information(&client_addr, &client_information);
	printf("Request from [%s:%d] !\n", client_information.client_ip, client_information.client_port);
	//New instance for client 
	if(!fork()){
	  //Client pipe
	  FILE * clnt_sd = fdopen(client_socket, "w+");
	  //Receive buffer
	  char rcv_buff[SERVER_RECEIVE_BUFFER_SIZE];
	  //HTTP header 
	  http_request http_req;
	  //Header check vars
	  int  header_valid = 0, url_valid = 0;
	  //Reading client request
	  fgets_or_exit(rcv_buff, sizeof(rcv_buff), clnt_sd);
	  //Parsing http
	  header_valid = parse_http_request(rcv_buff, &http_req);
	  //Checking header
	  header_valid = (((http_req.method == HTTP_GET) && (http_req.major_version == 1) && ((http_req.minor_version == 1) || (http_req.minor_version = 0))) ? 1 : 0);
	  //Valid URL
	  url_valid = ((strcmp(http_req.url,"/") == 0) ? 1 : 0); 
	  //Skipping headers
	  skip_headers(clnt_sd);
	  //Header validation
	  if (http_req.method == HTTP_UNSUPPORTED)
	    //Method not supported
	    send_response (clnt_sd, 405, "Method Not Allowed", "Method Not Allowed\r\n");
	  else if ((header_valid == 1) && (url_valid == 1))
	    //Welcome message
	    send_response(clnt_sd, 200 , "OK" , SERVER_WELCOME_MSG );
	  else if ((header_valid == 1) && (url_valid == 0))
	    //404
	    send_response(clnt_sd, 404,"Not Found", "Not Found\r\n");
	  else
	    //Bad request
	    send_response(clnt_sd, 400, "Bad Request" , "Bad request\r\n");
	    
	  //Disconnected
	  fclose(clnt_sd);
	  //Client child-process ending
	  exit(0);
	}
	//Closing client socket
	close(client_socket);
      }
    }
  }
  //Success
  return server_socket;
}
Exemple #21
0
void * handle_client_request(void * workerId)
{
	int id = *((int *) workerId); 

	char * request = NULL;
	int clientSocket, parseSuccess;
	struct http_request_s * request_obj;
	struct http_response_s * response_obj;
	char *response = NULL;
	printf("Hullo in %d\n", id);
	while(1)
	{
		clientSocket = -1;
		printf("Go to loop in %d\n", id);
		pthread_mutex_lock(&queue_mutex);
		{
			if(is_empty_queue(clientQueue))
			{
				pthread_cond_wait(&queue_has_client, &queue_mutex);
			}
			else 
				/* Take 1 client out of the queue */
				dequeue(clientQueue, &clientSocket);
		}
		pthread_mutex_unlock(&queue_mutex);
		printf("Worker with id = %d handles socketId = %d\n", id, clientSocket);
		if(clientSocket >= 0)
		{
			/* Initalize for new request handling */
			request_obj = create_request_struct();
			response_obj = create_response_struct();
			response = NULL;
			
			/* Handle the request of the client */
			request = read_request(clientSocket);
/*			ssize_t numByte = recv(clientSocket, m_request, 1000, 0);
			m_request[numByte] = '\0'; */
			printf("OK reading request\n"); 
			/* Parse request */
			parseSuccess = parse_http_request(request_obj, request, response_obj);

			response_obj->version = copy_str_dynamic(SUPPORT_HTTP);

			if(parseSuccess)
			{
				/* Check HTTP version */
				if(strcasecmp(request_obj->version, SUPPORT_HTTP) != 0)
				{
					set_status_code_error(response_obj, 505, "505 HTTP Version Not Supported", "This server supports only HTTP/1.1");
				}
				else
				{
					/* Check file access security */
					if(count_occurence(request_obj->path, '/') > MAX_NUM_SLASH)
						set_status_code_error(response_obj, 401, "401 Unauthorized", "You are not authorized to access the requested file on this server");
					else
					{
						exec_http_request(request_obj, response_obj);
					}
				}
			} 
			/* Execute command and return output 
			sprintf(response, "Server worker thread with id = %d handles request: %s", id, request); */
			
			response = get_response_text(response_obj);
			send(clientSocket, response, strlen(response), 0);

			//recv(clientSocket, response, 100, 0);
			/* Close socket, free memory */
			close(clientSocket);
			free(request);
			free(response);
			delete_request(&request_obj);
			delete_response(&response_obj); 
		}
	}
}
Exemple #22
0
int main(){
	int taille=0;
	int socket_client, pid, erreur = 0;
	
	char str[1024];
	http_request req;
	FILE *f = NULL;
	const char *message_bienvenue = "Bonjour, c'est un grand honneur de vous avoir sur notre serveur. Bienvenue à bord !\n";
	int socket_serveur = creer_serveur(8080);
	message_bienvenue +=0;
	taille+=0;
	
	initialiser_signaux();
	while((socket_client = accept(socket_serveur , NULL , NULL)) != -1){
		
		if((pid = fork()) == -1){
			perror("Erreur fork");
		/* traitement d’erreur */
		}
		if(pid == 0){
			sleep(1);
			f = fdopen(socket_client, "w+");
			/* if(write(socket_client, message_bienvenue, strlen(message_bienvenue)) == -1){
				perror("Erreur write bienvenu");
				traitement d’erreur 
			}*/
			fgets_or_exit(str, sizeof(str), f);
			skip_headers(f);
			erreur=parse_http_request(str,&req);
				
				//erreur = 1;
				/*strcpy(s, str);
				char* token = strtok(s, " ");
				while (token) {
					tokenCounter++;
					if(tokenCounter == 1 && !strcmp(token,"GET") == 0){
						erreur = 0;
					}
					if(tokenCounter ==2 && !strcmp(token, "/") ==0){
						erreur=0;
					}
					if(tokenCounter == 3 && (strncmp(token, "HTTP/1.1",8) != 0 && strncmp(token, "HTTP/1.0",8) !=0)){
						
						erreur = 0;
					}
					if(tokenCounter >=4){
						printf("%s\n", token);
					}			
					token = strtok(NULL, " ");

				}*/
			if(erreur == 404){
				send_response(f,404,"Page not found","Page not found\r\n");
			}else if(erreur == 400){
				send_response(f,400,"Bad Request","Bad Request\r\n");
			}else{
				fprintf(f, "HTTP/1.1 200 OK\r\nContent-Length: %d\r\n\r\n%s\r\n", (int)strlen(message_bienvenue)+2, message_bienvenue);
			}

			fflush(f);
			fclose(f);
			
			
			/*while((taille = read(socket_client, buffer, 256)) != 0){
				if(write(socket_client, buffer, taille)== -1){
					perror("Erreur write retour de message");
				}
			}*/
			exit(EXIT_SUCCESS);
		}else{
			close(socket_client);
		}

	}
	return 1;
}
Exemple #23
0
void httpServer_run(uint8_t seqnum)
{
	uint8_t s;	// socket number
	uint16_t len;
	uint32_t gettime = 0;

#ifdef _HTTPSERVER_DEBUG_
	uint8_t destip[4] = {0, };
	uint16_t destport = 0;
#endif

	http_request = (st_http_request *)pHTTP_RX;		// Structure of HTTP Request
	parsed_http_request = (st_http_request *)pHTTP_TX;

	// Get the H/W socket number
	s = getHTTPSocketNum(seqnum);

	/* HTTP Service Start */
	switch(getSn_SR(s))
	{
		case SOCK_ESTABLISHED:
			// Interrupt clear
			if(getSn_IR(s) & Sn_IR_CON)
			{
				setSn_IR(s, Sn_IR_CON);
			}

			// HTTP Process states
			switch(HTTPSock_Status[seqnum].sock_status)
			{

				case STATE_HTTP_IDLE :
					if ((len = getSn_RX_RSR(s)) > 0)
					{
						if (len > DATA_BUF_SIZE) len = DATA_BUF_SIZE;
						len = recv(s, (uint8_t *)http_request, len);

						*(((uint8_t *)http_request) + len) = '\0';

						parse_http_request(parsed_http_request, (uint8_t *)http_request);
#ifdef _HTTPSERVER_DEBUG_
						getSn_DIPR(s, destip);
						destport = getSn_DPORT(s);
						printf("\r\n");
						printf("> HTTPSocket[%d] : HTTP Request received ", s);
						printf("from %d.%d.%d.%d : %d\r\n", destip[0], destip[1], destip[2], destip[3], destport);
#endif
#ifdef _HTTPSERVER_DEBUG_
						printf("> HTTPSocket[%d] : [State] STATE_HTTP_REQ_DONE\r\n", s);
#endif
						// HTTP 'response' handler; includes send_http_response_header / body function
						http_process_handler(s, parsed_http_request);

						gettime = get_httpServer_timecount();
						// Check the TX socket buffer for End of HTTP response sends
						while(getSn_TX_FSR(s) != (getSn_TXBUF_SIZE(s)*1024))
						{
							if((get_httpServer_timecount() - gettime) > 3)
							{
#ifdef _HTTPSERVER_DEBUG_
								printf("> HTTPSocket[%d] : [State] STATE_HTTP_REQ_DONE: TX Buffer clear timeout\r\n", s);
#endif
								break;
							}
						}

						if(HTTPSock_Status[seqnum].file_len > 0) HTTPSock_Status[seqnum].sock_status = STATE_HTTP_RES_INPROC;
						else HTTPSock_Status[seqnum].sock_status = STATE_HTTP_RES_DONE; // Send the 'HTTP response' end
					}
					break;

				case STATE_HTTP_RES_INPROC :
					/* Repeat: Send the remain parts of HTTP responses */
#ifdef _HTTPSERVER_DEBUG_
					printf("> HTTPSocket[%d] : [State] STATE_HTTP_RES_INPROC\r\n", s);
#endif
					// Repeatedly send remaining data to client
					send_http_response_body(s, 0, http_response, 0, 0);

					if(HTTPSock_Status[seqnum].file_len == 0) HTTPSock_Status[seqnum].sock_status = STATE_HTTP_RES_DONE;
					break;

				case STATE_HTTP_RES_DONE :
#ifdef _HTTPSERVER_DEBUG_
					printf("> HTTPSocket[%d] : [State] STATE_HTTP_RES_DONE\r\n", s);
#endif
					// Socket file info structure re-initialize
					HTTPSock_Status[seqnum].file_len = 0;
					HTTPSock_Status[seqnum].file_offset = 0;
					HTTPSock_Status[seqnum].file_start = 0;
					HTTPSock_Status[seqnum].sock_status = STATE_HTTP_IDLE;

//#ifdef _USE_SDCARD_
//					f_close(&fs);
//#endif
#ifdef _USE_WATCHDOG_
					HTTPServer_WDT_Reset();
#endif
					http_disconnect(s);
					break;

				default :
					break;
			}
			break;

		case SOCK_CLOSE_WAIT:
#ifdef _HTTPSERVER_DEBUG_
		printf("> HTTPSocket[%d] : ClOSE_WAIT\r\n", s);	// if a peer requests to close the current connection
#endif
			disconnect(s);
			break;

		case SOCK_CLOSED:
#ifdef _HTTPSERVER_DEBUG_
			printf("> HTTPSocket[%d] : CLOSED\r\n", s);
#endif
			if(socket(s, Sn_MR_TCP, HTTP_SERVER_PORT, 0x00) == s)    /* Reinitialize the socket */
			{
#ifdef _HTTPSERVER_DEBUG_
				printf("> HTTPSocket[%d] : OPEN\r\n", s);
#endif
			}
			break;

		case SOCK_INIT:
			listen(s);
			break;

		case SOCK_LISTEN:
			break;

		default :
			break;

	} // end of switch

#ifdef _USE_WATCHDOG_
	HTTPServer_WDT_Reset();
#endif
}
Exemple #24
0
void httpServer_run(uint8_t seqnum)
{
    uint8_t s;	// socket number
    int16_t len;
    //uint32_t gettime = 0;	// 20150828 ## Eric removed

    uint8_t ret = 0;

#ifdef _HTTPSERVER_DEBUG_
    uint8_t destip[4] = {0, };
    uint16_t destport = 0;
#endif

    http_request = (st_http_request *)pHTTP_RX;		// Structure of HTTP Request
    parsed_http_request = (st_http_request *)pHTTP_TX;

    // Get the H/W socket number
    s = getHTTPSocketNum(seqnum);

    /* HTTP Service Start */
    switch(getSn_SR(s))
    {
    case SOCK_ESTABLISHED:
        // Interrupt clear
        if(getSn_IR(s) & Sn_IR_CON)
        {
            setSn_IR(s, Sn_IR_CON);
        }

        // HTTP Process states
        switch(HTTPSock_Status[seqnum].sock_status)
        {

        case STATE_HTTP_IDLE :
            if ((len = getSn_RX_RSR(s)) > 0)
            {
                if (len > DATA_BUF_SIZE) len = DATA_BUF_SIZE;

                // ## 20150828, Eric / Bongjun Hur added
                if ((len = recv(s, (uint8_t *)http_request, len)) < 0) break;	// Exception handler

                ////////////////////////////////////////////////////////////////////////////////
                // Todo; User defined custom command handler (userHandler.c)
                ret = custom_command_handler((uint8_t *)http_request);
                ////////////////////////////////////////////////////////////////////////////////

                if(ret > 0) // Custom command handler
                {
                    // Todo: Users can change this parts for custom function added
                    //if(ret == COMMAND_SUCCESS)		send(s, (uint8_t *)"CMDOK", 5);
                    //else if(ret == COMMAND_ERROR)	send(s, (uint8_t *)"CMDERROR", 8);

                    HTTPSock_Status[seqnum].sock_status = STATE_HTTP_RES_DONE;
                }
                else // HTTP process handler
                {
                    *(((uint8_t *)http_request) + len) = '\0';	// End of string (EOS) marker
                    parse_http_request(parsed_http_request, (uint8_t *)http_request);
#ifdef _HTTPSERVER_DEBUG_
                    getSn_DIPR(s, destip);
                    destport = getSn_DPORT(s);
                    printf("\r\n");
                    printf("> HTTPSocket[%d] : HTTP Request received ", s);
                    printf("from %d.%d.%d.%d : %d\r\n", destip[0], destip[1], destip[2], destip[3], destport);
#endif

#ifdef _HTTPSERVER_DEBUG_
                    printf("> HTTPSocket[%d] : [State] STATE_HTTP_REQ_DONE\r\n", s);
#endif
                    // HTTP 'response' handler; includes send_http_response_header / body function
                    http_process_handler(s, parsed_http_request);

                    /*
                    							// ## 20150828 Eric removed
                    							gettime = get_httpServer_timecount();
                    							// Check the TX socket buffer for End of HTTP response sends
                    							while(getSn_TX_FSR(s) != (getSn_TXBUF_SIZE(s)*1024))
                    							{
                    								if((get_httpServer_timecount() - gettime) > 3)
                    								{
                    #ifdef _HTTPSERVER_DEBUG_
                    									printf("> HTTPSocket[%d] : [State] STATE_HTTP_REQ_DONE: TX Buffer clear timeout\r\n", s);
                    #endif
                    									break;
                    								}
                    							}
                    */

                    if(HTTPSock_Status[seqnum].file_len > 0) HTTPSock_Status[seqnum].sock_status = STATE_HTTP_RES_INPROC;
                    else HTTPSock_Status[seqnum].sock_status = STATE_HTTP_RES_DONE; // Send the 'HTTP response' end
                }
            }
            break;


        case STATE_HTTP_RES_INPROC :
            /* Repeat: Send the remain parts of HTTP responses */
#ifdef _HTTPSERVER_DEBUG_
            printf("> HTTPSocket[%d] : [State] STATE_HTTP_RES_INPROC\r\n", s);
#endif
            // Repeatedly send remaining data to client
            send_http_response_body(s, 0, http_response, 0, 0);

            if(HTTPSock_Status[seqnum].file_len == 0) HTTPSock_Status[seqnum].sock_status = STATE_HTTP_RES_DONE;
            break;

        case STATE_HTTP_RES_DONE :
#ifdef _HTTPSERVER_DEBUG_
            printf("> HTTPSocket[%d] : [State] STATE_HTTP_RES_DONE\r\n", s);
#endif
            // Socket file info structure re-initialize
            HTTPSock_Status[seqnum].file_len = 0;
            HTTPSock_Status[seqnum].file_offset = 0;
            HTTPSock_Status[seqnum].file_start = 0;
            HTTPSock_Status[seqnum].sock_status = STATE_HTTP_IDLE;

//#ifdef _USE_SDCARD_
//					f_close(&fs);
//#endif
#ifdef _USE_WATCHDOG_
            HTTPServer_WDT_Reset();
#endif
            http_disconnect(s);
            break;

        default :
            break;
        }
        break;

    case SOCK_CLOSE_WAIT:
#ifdef _HTTPSERVER_DEBUG_
        printf("> HTTPSocket[%d] : ClOSE_WAIT\r\n", s);	// if a peer requests to close the current connection
#endif
        //disconnect(s);
        http_disconnect(s);
        break;

    case SOCK_INIT:
        listen(s);
        break;

    case SOCK_LISTEN:
        break;

    case SOCK_SYNSENT:
    //case SOCK_SYNSENT_M:
    case SOCK_SYNRECV:
        //case SOCK_SYNRECV_M:
        break;

    case SOCK_CLOSED:
    default :
#ifdef _HTTPSERVER_DEBUG_
        printf("> HTTPSocket[%d] : CLOSED\r\n", s);
#endif
        if(socket(s, Sn_MR_TCP, HTTP_SERVER_PORT, 0x00) == s)    /* Reinitialize the socket */
        {
#ifdef _HTTPSERVER_DEBUG_
            printf("> HTTPSocket[%d] : OPEN\r\n", s);
#endif
        }
        break;
    } // end of switch

#ifdef _USE_WATCHDOG_
    HTTPServer_WDT_Reset();
#endif
}
char *
trust_url(struct http_request *http, struct client_state *csp)
{
	struct file_list *fl;
	struct block_spec *b;
	struct url_spec url[1], **tl, *t;
	char *p, *h;
	char *hostport, *path, *referrer;
	struct http_request rhttp[1];
	int n;

	if(((fl = csp->tlist) == NULL) || ((b  = fl->f) == NULL)) {
		return(NULL);
	}

	*url = dsplit(http->host);

	/* if splitting the domain fails, punt */
	if(url->dbuf == NULL) return(NULL);

	memset(rhttp, '\0', sizeof(*rhttp));

	for(b = b->next; b ; b = b->next) {

		if((b->url->port == 0) || (b->url->port == http->port)) {
			if((b->url->domain[0] == '\0') || (domaincmp(b->url, url) == 0)) {
				if((b->url->path == NULL) ||
#ifdef REGEX
				   (regexec(b->url->preg, http->path, 0, NULL, 0) == 0)
#else
				   (strncmp(b->url->path, http->path, b->url->pathlen) == 0)
#endif
				) {
					freez(url->dbuf);
					freez(url->dvec);

					if(b->reject == 0) return(NULL);

					hostport = URL(http->hostport);
					path     = URL(http->path);

					if(csp->referrer) {
						referrer = URL(csp->referrer);
					} else {
						referrer = URL("undefined");
					}

					n  = strlen(CTRUST);
					n += strlen(hostport);
					n += strlen(path);
					n += strlen(referrer);

					p = malloc(n);

					sprintf(p, CTRUST,
						hostport, path, referrer);

					freez(hostport);
					freez(path);
					freez(referrer);

					return(p);
				}
			}
		}
	}

	freez(url->dbuf);
	freez(url->dvec);

	if((csp->referrer == NULL)|| (strlen(csp->referrer) <= 9)) {
		/* no referrer was supplied */
		goto trust_url_not_trusted;
	}

	/* forge a URL from the referrer so we can use
	 * convert_url() to parse it into its components.
	 */

	p = NULL;
	p = strsav(p, "GET ");
	p = strsav(p, csp->referrer + 9);	/* skip over "Referer: " */
	p = strsav(p, " HTTP/1.0");

	parse_http_request(p, rhttp, csp);

	if(rhttp->cmd == NULL) {
		freez(p);
		goto trust_url_not_trusted;
	}

	freez(p);

	*url = dsplit(rhttp->host);

	/* if splitting the domain fails, punt */
	if(url->dbuf == NULL) goto trust_url_not_trusted;

	for(tl = trust_list; (t = *tl) ; tl++) {
		if((t->port == 0) || (t->port == rhttp->port)) {
			if((t->domain[0] == '\0') || domaincmp(t, url) == 0) {
				if((t->path == NULL) ||
#ifdef REGEX
				   (regexec(t->preg, rhttp->path, 0, NULL, 0) == 0)
#else
				   (strncmp(t->path, rhttp->path, t->pathlen) == 0)
#endif
				) {
					/* if the URL's referrer is from a trusted referrer, then
					 * add the target spec to the trustfile as an unblocked
					 * domain and return NULL (which means it's OK).
					 */

					FILE *fp;
					
					freez(url->dbuf);
					freez(url->dvec);

					if((fp = fopen(trustfile, "a"))) {
						h = NULL;

						h = strsav(h, "~");
						h = strsav(h, http->hostport);

						p = http->path;
						if((*p++ == '/')
						&& (*p++ == '~')) {
						/* since this path points into a user's home space
						 * be sure to include this spec in the trustfile.
						 */
							if((p = strchr(p, '/'))) {
								*p = '\0';
								h = strsav(h, http->path);
								h = strsav(h, "/");
							}
						}

						free_http_request(rhttp);

						fprintf(fp, "%s\n", h);
						freez(h);
						fclose(fp);
					}
					return(NULL);
				}
			}
		}
	}

trust_url_not_trusted:
	free_http_request(rhttp);

	hostport = URL(http->hostport);
	path     = URL(http->path);

	if(csp->referrer) {
		referrer = URL(csp->referrer);
	} else {
		referrer = URL("undefined");
	}

	n  = strlen(CTRUST);
	n += strlen(hostport);
	n += strlen(path);
	n += strlen(referrer);

	p = malloc(n);
	sprintf(p, CTRUST, hostport, path, referrer);

	freez(hostport);
	freez(path);
	freez(referrer);

	return(p);
}
Exemple #26
0
int wait_packets(int sd)
{
	int flags;
	int ret;
	int recv_len;
	int len;
	int err;
	fd_set rfds;
	struct nlmsgerr *nl_err;
	struct timeval tv;
	struct nlattr *na;
	struct msgtemplate msg;
	char *http_data;
	struct sample_http_info *http_info;
	long xxxx = 0;
	long errcnt = 0;

	unsigned int query_id = 0;
	char url[MAX_URL_LEN] = {0};
	int sec_flag = 0x0f0f;

#ifdef FIRST_SEND
	printf("%s, first send for test !!!\n", __FUNCTION__);
	err = send_cmd(sd, nl_family_id, SAMPLE_NETLINK_CMD_SECURITY_QUERY,
			SAMPLE_NETLINK_ATTR_SECURITY_FLAG, (void*)&sec_flag,
			sizeof(int), NLM_F_REQUEST);
	if (err < 0) {
		printf("Error sending result (%d:%s)\n",
				errno, strerror(errno));
		return -1;
	}
#endif

	flags = fcntl(sd, F_GETFL);
	fcntl(sd, F_SETFL, flags | O_NONBLOCK);

	err = 0;
	do {
		FD_ZERO(&rfds);
		FD_SET(sd, &rfds);

		/* Monitoring, no timeout */
		ret = select(sd+1, &rfds, NULL, NULL, NULL);

		if (ret < 0) {
			if (errno == EINTR)
				continue;
			perror("select()");
			err = ret;
			break;
		} else if (ret == 0) {
			printf("No answer within %lu seconds.\n", tv.tv_sec);
			err = -ETIMEDOUT;
			break;
		}
		if (!FD_ISSET(sd, &rfds))
			continue;

		printf("\n\n========================================\n\n");
		recv_len = recv(nl_sd, &msg, sizeof(msg), 0);
		if (recv_len < 0) {
			printf("nonfatal reply error: errno %d\n", recv_len);
			err = errno;
			errcnt++;
			printf("fail cnt %d\n", errcnt);
			/* TODO check why failed with high pressure. overwrite on rcv buffer? */
			// break;
		}
#ifdef __DEBUG_MSG__
		if (msg.n.nlmsg_type == NLMSG_ERROR ||
				!NLMSG_OK((&msg.n), recv_len)) {
			nl_err = NLMSG_DATA(&msg);
			printf("fatal reply error,  errno %d\n", nl_err->error);
			err = nl_err->error;
			break;
		}
#endif
		recv_len = GENLMSG_PAYLOAD(&msg.n);
		na = (struct nlattr *) GENLMSG_DATA(&msg);

		printf("%s, recv genl msg, cmd=%d\n", __FUNCTION__, msg.g.cmd);
		print_timestamp();
		len = 0;
		while (len < recv_len) {
			len += NLA_ALIGN(na->nla_len);
			switch (na->nla_type) {
				case SAMPLE_NETLINK_TYPE_SEC_QID:
					{
						query_id = *(unsigned int *)NLA_DATA(na);
						printf("HTTP query id:%d\n", query_id);
					}
					break;
				case SAMPLE_NETLINK_TYPE_HTTP_INFO:
					http_info = (struct http_info *)NLA_DATA(na);
#ifdef __DEBUG_MSG__
					printf("%08x(%u) --> %08x(%u)\n",
							ntohl(http_info->sip), ntohs(http_info->sport),
							ntohl(http_info->dip), ntohs(http_info->dport));
#endif
					break;
				case SAMPLE_NETLINK_TYPE_HTTP_DATA:
					http_data = NLA_DATA(na);
#ifdef __DEBUG_MSG__
					printf("Http data len:%d\n", len);
					printf("Http data[%d]:%s\n", len, http_data);
#endif
					if (SAMPLE_NETLINK_CMD_SECURITY_QUERY == msg.g.cmd) {
						/* parse REQUEST */
						memset((void*)url, 0, sizeof(url));
						if (parse_http_request(http_data, len, url)) {
							printf("%s, parse http request error, skip this query!!!\n", __FUNCTION__);
							break;
						}

						/* query security center */
						char *mac="78:1D:BA:32:11:06";
						char *ip = "201.201.201.201";
						//sec_flag = send_pkg_by_udp(url, url, mac, ip);
						// 2 means evil url
						if (2 == sec_flag) {
							sec_flag = 1;
						} else {
							sec_flag = 0;
						}

						/* send response */
						err = send_security_response(sd, nl_family_id, SAMPLE_NETLINK_CMD_SECURITY_QUERY,
								NLM_F_REQUEST, (void*)&sec_flag, (void*)&query_id);
						if (err < 0) {
							printf("Error sending result (%d:%s)\n",
									errno, strerror(errno));
							return -1;
						}
						printf("%s, send query flag=%d, query_id=%d\n", __FUNCTION__, sec_flag, query_id);
						print_timestamp();
					}
					break;
				default:
					printf("Unknown nla_type %d\n", na->nla_type);
					break;
			}
			na = (struct nlattr *) (GENLMSG_DATA(&msg) + len);
		}
		xxxx++;
		if (xxxx % 100 == 0)
			printf("Get message %d\n", xxxx);


	} while (1);

	/* restore previous attributes */
	fcntl(sd, F_SETFL, flags);
	return err;
}