https-server/server.c

51 lines
1.6 KiB
C
Raw Normal View History

2024-04-30 13:31:49 +00:00
#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);
}