view playground/main.c @ 22:947b81010aba

[Dowa & Seobeo] Updated so that Dowa hashmaps can use arena and not be broken. Split up web so taht it can handle different paths. Also fixes issues with hash collisions which was pain in the ass.
author June Park <parkjune1995@gmail.com>
date Tue, 07 Oct 2025 07:11:02 -0700
parents fa2b8af609d9
children 342726584be2
line wrap: on
line source

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

#define INITIAL_BUFFER_CAPACITY 8192

void init_openssl()
{
    SSL_load_error_strings();
    OpenSSL_add_ssl_algorithms();
}

int main(void)
{
    const char *host = "www.google.com";
    const char *port = "443";

    struct addrinfo hints = {0}, *res;
    hints.ai_family   = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;

    if (getaddrinfo(host, port, &hints, &res) != 0)
    {
        perror("getaddrinfo");
        return 1;
    }

    int sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    if (sockfd < 0)
    {
        perror("socket");
        return 1;
    }

    if (connect(sockfd, res->ai_addr, res->ai_addrlen) != 0)
    {
        perror("connect");
        return 1;
    }

    freeaddrinfo(res);

    init_openssl();
    SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
    SSL_CTX_set_default_verify_paths(ctx);

    SSL *ssl = SSL_new(ctx);
    SSL_set_fd(ssl, sockfd);

    // ✅ use real hostname for SNI
    SSL_set_tlsext_host_name(ssl, host);

    // ✅ perform blocking handshake for simplicity
    fcntl(sockfd, F_SETFL, 0);

    if (SSL_connect(ssl) != 1)
    {
      fprintf(stderr, "SSL_connect failed\n");
      ERR_print_errors_fp(stderr);
      return 1;
    }

    printf("✅ SSL handshake successful!\n");

    // send a basic HTTP request
    const char *req =
        "GET / HTTP/1.1\r\n"
        "Host: www.google.com\r\n"
        "Connection: close\r\n\r\n";
    SSL_write(ssl, req, strlen(req));

    char buf[INITIAL_BUFFER_CAPACITY];
    int bytes;

    while ((bytes = SSL_read(ssl, buf, sizeof(buf) - 1)) > 0)
    {
        buf[bytes] = '\0';
        printf("%s", buf);
    }

    SSL_shutdown(ssl);
    SSL_free(ssl);
    SSL_CTX_free(ctx);
    close(sockfd);
    EVP_cleanup();
    return 0;
}