Example #1
0
DWORD WINAPI http_do_request(void *lPtr)
{
	socket_conn* conn = (socket_conn*)lPtr;
	if(conn == 0)
		return 0;

	printf("[%08x]new connection\n", GetCurrentThreadId());
	while(1)
	{
		int keepalive = 0;
		dynamic_object * req = dynamic_create();
		if(http_read_request(conn, req) == 0)
		{
			dynamic_delete(req);
			break;
		}
		char* path = dynamic_get_string(dynamic_map_find(req, "PATH"));
		char* method = dynamic_get_string(dynamic_map_find(req, "METHOD"));
		char* connection = dynamic_get_string(dynamic_map_find(req, HTTP_HEADER_CONNECTION));
		if(connection && strcmp(connection, "keep-alive")==0)
			keepalive = 1;
		printf("[%08x]%s %s\n", GetCurrentThreadId(), method, path);

		if(strcmp(path, "/hello") == 0)
		{
			char* html = "<html><body>Hello World!</body></html>";
			int htmllen = strlen(html);
			dynamic_object * res = dynamic_create();
			dynamic_string_printf(dynamic_map_insert(res, HTTP_HEADER_CONTENT_LENGTH), "%d", htmllen);
			dynamic_set_string(dynamic_map_insert(res, HTTP_HEADER_CONTENT_TYPE), "text/html");

			http_send_response(conn, 200, res);
			write_socket(conn, html, htmllen, -1);
			dynamic_delete(res);
		}else
		{
			http_send_file(conn, req);
		}
		dynamic_delete(req);
		if(keepalive == 0)
			break;
	}

	close_socket(conn);
	printf("[%08x]close connection\n", GetCurrentThreadId());
	return 0;
}
Example #2
0
int main() 
{
	int port = 80;
	int sockfd;
	char* buffer = malloc(sizeof(char*) * 1024);
	char* filename = malloc(sizeof(char*) * 255);
	struct http_request* request = malloc(sizeof(*request));
	struct http_response* response = malloc(sizeof(*response));

	printf("Creating socket\n");
	sockfd = create_socket(port);

	while(1) {
		int clientfd;
		clientfd = accept_client(sockfd);

		http_read_request(clientfd, &buffer);
		http_parse_request(request, &buffer);

		// If / is requested, substitute it for index
		if(strlen(request->path) == 1) {
			sprintf(request->path, "index");
		}
		// Make sure path not containing . ends with .html
		if(strstr(request->path, ".") == NULL) {
			strcat(request->path, ".html");
		}

		printf("[REQUEST] Method: %s\n", request->method);
		printf("[REQUEST] Path: %s\n", request->path);

		// Make sure that requested file exists
		sprintf(filename, "static/%s", request->path);
		if(file_exists(filename) == false) {
			sprintf(filename, "static/404.html");
		}

		memset(buffer, '\0', sizeof(char*) * 255);
		read_file(filename, &buffer);

		char* content_type = malloc(sizeof(char*) * 255);
		http_resolve_content_type(&content_type, filename);
		
		printf("[RESPONSE] Content-Type: %s\n", content_type);
		http_set_response(response, &buffer, content_type,  strlen(buffer));
		http_respond(clientfd, response);

		close(clientfd);

		printf("--------------\n");
	}

	free(response->data);
	free(response->content_type);
	free(response);

	free(request->method);
	free(request->path);
	free(request);
	free(filename);
	
	close(sockfd);

	return 0;
}