110 lines
3.0 KiB
C
110 lines
3.0 KiB
C
#include <stdbool.h>
|
|
#include <stdint.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
#include "native.h"
|
|
|
|
typedef enum {
|
|
HttpMethodGet,
|
|
HttpMethodPost,
|
|
} HttpMethod;
|
|
|
|
typedef struct {
|
|
HttpMethod method;
|
|
size_t path_index, path_length;
|
|
size_t content_length;
|
|
} HttpRequestHeader;
|
|
|
|
HttpRequestHeader parse_http_request_header(const char* message, size_t message_size)
|
|
{
|
|
size_t i = 0;
|
|
|
|
// parse method
|
|
HttpMethod method;
|
|
if (i + 3 < message_size && strncmp(&message[0], "GET", 3)) {
|
|
method = HttpMethodGet;
|
|
i += 3;
|
|
} else if (i + 4 < message_size && strncmp(&message[0], "POST", 4)) {
|
|
method = HttpMethodPost;
|
|
i += 4;
|
|
} else {
|
|
printf("error: header parse fail #1\n");
|
|
exit(1);
|
|
}
|
|
|
|
// skip space
|
|
i += 1;
|
|
if (i >= message_size) { }
|
|
|
|
return (HttpRequestHeader) { 0 };
|
|
}
|
|
|
|
const uint16_t port = 8000;
|
|
|
|
int main(void)
|
|
{
|
|
init_sockets();
|
|
|
|
printf("starting server...\n");
|
|
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
|
|
if (server_socket < 0) {
|
|
printf("error: could not open socket\n");
|
|
return 1;
|
|
}
|
|
struct sockaddr_in server;
|
|
server.sin_addr.s_addr = inet_addr("127.0.0.1");
|
|
server.sin_family = AF_INET;
|
|
server.sin_port = htons(port);
|
|
if (bind(server_socket, (struct sockaddr*)&server, sizeof(server)) > 0) {
|
|
printf("error: could not bind socket\n");
|
|
return 1;
|
|
}
|
|
if (listen(server_socket, SOMAXCONN) < 0) {
|
|
printf("error: could not listen on server");
|
|
return 1;
|
|
}
|
|
printf("listening on port %d\n", port);
|
|
|
|
while (true) {
|
|
struct sockaddr_in client;
|
|
socklen_t client_size;
|
|
printf("waiting for client...\n");
|
|
int client_socket = accept(server_socket, (struct sockaddr*)&client, &client_size);
|
|
if (client_socket < 0) {
|
|
printf("error: could not accept connection\n");
|
|
continue;
|
|
}
|
|
printf("client connected\n");
|
|
while (true) {
|
|
uint8_t buffer[8192] = { 0 };
|
|
ssize_t read_size = recv(client_socket, buffer, 8192, 0);
|
|
if (read_size < 0) {
|
|
printf("error: could not recieve\n");
|
|
break;
|
|
} else if (read_size == 0) {
|
|
printf("client disconnected\n");
|
|
break;
|
|
}
|
|
printf("recieved:\n%s\n", buffer);
|
|
uint8_t send_buffer[]
|
|
= "HTTP/1.1 200 OK\r\n"
|
|
"Content-Type: text/html\r\n"
|
|
"\r\n"
|
|
"<!DOCTYPE><html><head><meta charset=\"utf-8\"><title>hej med "
|
|
"dig</title></head><body><h1>fuck c hashtag</h1></body></html>\r\n"
|
|
"\r\n";
|
|
ssize_t written = send(client_socket, send_buffer, sizeof(send_buffer), 0);
|
|
if (written < 0) {
|
|
printf("error: could not write\n");
|
|
continue;
|
|
}
|
|
printf("disconnecting client\n");
|
|
close_socket(client_socket);
|
|
}
|
|
}
|
|
|
|
return 0;
|
|
}
|