/*
 * WSSSH Library - SSL functions implementation
 *
 * Copyright (C) 2024 Stefy Lanza <stefy@nexlab.net> and SexHack.me
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include "wssh_ssl.h"
#include <openssl/err.h>
#include <stdio.h>

SSL_CTX *create_ssl_context(void) {
    SSL_CTX *ssl_ctx;

    // Initialize SSL
    SSL_library_init();
    OpenSSL_add_all_algorithms();
    SSL_load_error_strings();

    ssl_ctx = SSL_CTX_new(TLS_client_method());
    if (!ssl_ctx) {
        ERR_print_errors_fp(stderr);
        return NULL;
    }

    // Allow self-signed certificates
    SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_NONE, NULL);

    return ssl_ctx;
}

SSL *create_ssl_connection(SSL_CTX *ssl_ctx, int sock, int debug) {
    SSL *ssl = SSL_new(ssl_ctx);
    SSL_set_fd(ssl, sock);

    if (debug) {
        fprintf(stderr, "[DEBUG] Establishing SSL connection...\n");
    }
    if (SSL_connect(ssl) <= 0) {
        ERR_print_errors_fp(stderr);
        fprintf(stderr, "SSL connection failed\n");
        SSL_free(ssl);
        return NULL;
    }
    if (debug) {
        fprintf(stderr, "[DEBUG] SSL connection established\n");
    }

    return ssl;
}