/* Collection of code snippets by Arne Vajhøj */
/* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <sys/socket.h>
#include <netdb.h>
#endif

#include <errno.h>

#include <openssl/ssl.h>

void recv_line(SSL *ssl, char *buf, int buflen)
{
    int ix;
    ix = 0;
    buf[ix] = '\0';
    while(ix < buflen && strstr(buf, "\r\n") == NULL)
    {
        ix = ix + SSL_read(ssl, buf + ix, buflen - ix);
        buf[ix] = '\0';
    }
}

int get_password(char *buf, int size, int rwflag, void *userdata)
{
    strcpy(buf, "topsecret");
    return strlen(buf);
}

void client_to_ssl(int sd2)
{
    int status, buflen;
    long int a, b, c;
    char *buf, *v, *v2;
    SSL_CTX *sslctx;
    SSL *ssl;
    /* setup SSL */
    SSL_library_init();
    sslctx = SSL_CTX_new(TLSv1_2_server_method());
    if(sslctx == NULL)
    {
        printf("Error creating SSL context\n");
        exit(0);
    }
    status = SSL_CTX_use_certificate_file(sslctx, "/work/sslserver.pem", SSL_FILETYPE_PEM);
    if(status <= 0)
    {
        printf("Error reading certificate file\n");
        exit(0);
    }
    SSL_CTX_set_default_passwd_cb(sslctx, get_password);
    status = SSL_CTX_use_PrivateKey_file(sslctx, "/work/sslserver.pem", SSL_FILETYPE_PEM);
    if(status <= 0)
    {
        printf("Error reading private key file\n");
        exit(0);
    }
    SSL_CTX_set_options(sslctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1);
    /* SSL handshake */
    ssl = SSL_new(sslctx);
    if(ssl == NULL)
    {
        printf("Error initalizing SSL\n");
        exit(0);
    }
    SSL_set_fd(ssl, sd2); 
    status = SSL_accept(ssl);
    if(status <= 0)
    {
        printf("Error accepting SSL handshake\n");
        exit(0);
    }
    /* read a and b */
    buflen = 24;
    buf = malloc(buflen);
    recv_line(ssl, buf, buflen);
    sscanf(buf, "%ld %ld\r\n", &a, &b);
    free(buf);
    /* calculate c and send */
    c = a + b;
    buflen = 13;
    buf = malloc(buflen);
    sprintf(buf, "%ld\r\n", c);
    status = SSL_write(ssl, buf, strlen(buf));
    if(status < 0)
    {
        printf("Error sending c\n");
        exit(0);
    }
    free(buf);
    /* read v */
    buflen = 258;
    buf = malloc(buflen);
    recv_line(ssl, buf, buflen);
    v = malloc(strlen(buf) + 1);
    sscanf(buf, "%s\r\n", v);
    free(buf);
    /* calculate v2 and send */
    v2 = malloc(2 * strlen(v) + 1);
    strcpy(v2, v);
    strcat(v2, v);
    buflen = strlen(v2) + 3;
    buf = malloc(buflen);
    sprintf(buf, "%s\r\n", v2);
    status = SSL_write(ssl, buf, strlen(buf));
    if(status < 0)
    {
        printf("Error sending v2: %s\n", strerror(errno));
        exit(0);
    }
    free(buf);
    free(v);
    free(v2);
    /* close socket */
    SSL_free(ssl);
    SSL_CTX_free(sslctx);
#ifdef WIN32
    closesocket(sd2);
#else
    close(sd2);
#endif
}

#define PORT "12345"
#define BACKLOG 100

int main()
{
    int sd, sd2, status, slen;
    char addr[47];
    struct sockaddr remote;
    struct addrinfo hints, *res;
#ifdef WIN32
    WSADATA WSAData;
    if(WSAStartup(0x0101, &WSAData) != 0)
    {
        printf("Error initializing\n");
        exit(0);
    }
#endif
    /* find port */
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET; //AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE; 
    status = getaddrinfo(NULL, PORT, &hints, &res);
    if(status != 0)
    {
        printf("Error finding port: %s\n", PORT);
        exit(0);
    }
    /* create socket */
    sd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    if(sd < 0)
    {
        printf("Error creating socket: %s\n", strerror(errno));
        exit(0);
    }
    /* bind */
    status = bind(sd, res->ai_addr, res->ai_addrlen);
    if(status < 0)
    {
        printf("Error binding socket: %s\n", strerror(errno));
        exit(0);
    }
    freeaddrinfo(res);
    /* listen */
    status = listen(sd, BACKLOG);
    if(status < 0)                            
    {
        printf("Error listening socket: %s\n", strerror(errno));
        exit(0);
    }
    for(;;)
    {
        /* accept */
        sd2 = accept(sd, 0, 0);
        if(sd2 < 0)
        {
            printf("Error accepting socket: %s\n", strerror(errno));
            exit(0);
        }
        slen = sizeof(remote);
        getpeername(sd2, &remote, &slen);
        if(remote.sa_family == AF_INET)
            printf("(connection from %s)\n", inet_ntop(AF_INET, &((struct sockaddr_in *)&remote)->sin_addr, addr, sizeof(addr)));
        if(remote.sa_family == AF_INET6)
            printf("(connection from %s)\n", inet_ntop(AF_INET6, &((struct sockaddr_in6 *)&remote)->sin6_addr, addr, sizeof(addr)));
        /* switch client to SSL */
        client_to_ssl(sd2);
    }
    return 0;
}
