Inital commit

This commit is contained in:
Kiril 2024-04-30 14:31:49 +01:00
commit 8f837ca67b
3 changed files with 61 additions and 0 deletions

1
compile.sh Executable file
View File

@ -0,0 +1 @@
gcc server.c -l ssl

10
index.html Normal file
View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<title>Test Demo Page</title>
</head>
<body>
<h1>Test Page</h1>
<p>If you are seeing this page, you have correctly configured the web server to run under HTTPS!</p>
</body>
</html>

50
server.c Normal file
View File

@ -0,0 +1,50 @@
#include <sys/types.h>
#include <sys/socket.h>
#include <openssl/ssl.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
static const short PORT = 8081;
static const short BACKLOG_SIZE = 10;
static const char * CERTIFICATE_PATH = "cert.pem";
static const char * PRIVATE_KEY_PATH = "key";
static const char * ERROR_404 = "No page found";
int main(int argc, char** argv) {
int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
const struct sockaddr addr = {
AF_INET,
htons(PORT),
0
};
bind(socket_fd, &addr, sizeof(addr));
listen(socket_fd, BACKLOG_SIZE);
int client_fd = accept(socket_fd, NULL, NULL);
SSL_CTX* ctx = SSL_CTX_new(TLS_server_method());
SSL* ssl = SSL_new(ctx);
SSL_set_fd(ssl, client_fd);
SSL_use_certificate_chain_file(ssl, CERTIFICATE_PATH);
SSL_use_PrivateKey_file(ssl, PRIVATE_KEY_PATH, SSL_FILETYPE_PEM);
SSL_accept(ssl);
char buffer[1024] = {0};
SSL_read(ssl, buffer, 1023);
// Assume GET request
char* file_request = buffer + 5;
char response[1024] = {0};
char* headers = "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n";
memcpy(response, headers, strlen(headers));
if (strncmp(file_request, "index.html", strlen("index.html"))) {
FILE* f = fopen("index.html", "r");
fread(response + strlen(headers), 1024 - strlen(headers) - 1, 1, f);
fclose(f);
} else {
memcpy(response + strlen(headers), ERROR_404, strlen(ERROR_404));
}
SSL_write(ssl, response, 1024);
SSL_shutdown(ssl);
}