



#include <string.h>


#ifdef _WIN32 
# include <winsock2.h>
#else 
# include <sys/socket.h>
#endif

#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>


static BIO *create_socket_bio(const char *hostname, const char *port,
                              int family, BIO_ADDR **peer_addr)
{
    int sock = -1;
    BIO_ADDRINFO *res;
    const BIO_ADDRINFO *ai = NULL;
    BIO *bio;

    
    if (!BIO_lookup_ex(hostname, port, BIO_LOOKUP_CLIENT, family, SOCK_DGRAM, 0,
                       &res))
        return NULL;

    
    for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {
        
        sock = BIO_socket(BIO_ADDRINFO_family(ai), SOCK_DGRAM, 0, 0);
        if (sock == -1)
            continue;

        
        if (!BIO_connect(sock, BIO_ADDRINFO_address(ai), 0)) {
            BIO_closesocket(sock);
            sock = -1;
            continue;
        }

        
        if (!BIO_socket_nbio(sock, 1)) {
            BIO_closesocket(sock);
            sock = -1;
            continue;
        }

        break;
    }

    if (sock != -1) {
        *peer_addr = BIO_ADDR_dup(BIO_ADDRINFO_address(ai));
        if (*peer_addr == NULL) {
            BIO_closesocket(sock);
            return NULL;
        }
    }

    
    BIO_ADDRINFO_free(res);

    
    if (sock == -1)
        return NULL;

    
    bio = BIO_new(BIO_s_datagram());
    if (bio == NULL) {
        BIO_closesocket(sock);
        return NULL;
    }

    
    BIO_set_fd(bio, sock, BIO_CLOSE);

    return bio;
}

int write_a_request(SSL *stream, const char *request_start,
                    const char *hostname)
{
    const char *request_end = "\r\n\r\n";
    size_t written;

    if (!SSL_write_ex(stream, request_start, strlen(request_start),
                      &written))
        return 0;
    if (!SSL_write_ex(stream, hostname, strlen(hostname), &written))
        return 0;
    if (!SSL_write_ex(stream, request_end, strlen(request_end), &written))
        return 0;

    return 1;
}


int main(int argc, char *argv[])
{
    SSL_CTX *ctx = NULL;
    SSL *ssl = NULL;
    SSL *stream1 = NULL, *stream2 = NULL, *stream3 = NULL;
    BIO *bio = NULL;
    int res = EXIT_FAILURE;
    int ret;
    unsigned char alpn[] = { 8, 'h', 't', 't', 'p', '/', '1', '.', '0' };
    const char *request1_start =
        "GET /request1.html HTTP/1.0\r\nConnection: close\r\nHost: ";
    const char *request2_start =
        "GET /request2.html HTTP/1.0\r\nConnection: close\r\nHost: ";
    size_t readbytes;
    char buf[160];
    BIO_ADDR *peer_addr = NULL;
    char *hostname, *port;
    int argnext = 1;
    int ipv6 = 0;

    if (argc < 3) {
        printf("Usage: quic-client-non-block [-6] hostname port\n");
        goto end;
    }

    if (!strcmp(argv[argnext], "-6")) {
        if (argc < 4) {
            printf("Usage: quic-client-non-block [-6] hostname port\n");
            goto end;
        }
        ipv6 = 1;
        argnext++;
    }
    hostname = argv[argnext++];
    port = argv[argnext];

    
    ctx = SSL_CTX_new(OSSL_QUIC_client_method());
    if (ctx == NULL) {
        printf("Failed to create the SSL_CTX\n");
        goto end;
    }

    
    SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);

    
    if (!SSL_CTX_set_default_verify_paths(ctx)) {
        printf("Failed to set the default trusted certificate store\n");
        goto end;
    }

    
    ssl = SSL_new(ctx);
    if (ssl == NULL) {
        printf("Failed to create the SSL object\n");
        goto end;
    }

    
    if (!SSL_set_default_stream_mode(ssl, SSL_DEFAULT_STREAM_MODE_NONE)) {
        printf("Failed to disable the default stream mode\n");
        goto end;
    }

    
    bio = create_socket_bio(hostname, port, ipv6 ? AF_INET6 : AF_INET, &peer_addr);
    if (bio == NULL) {
        printf("Failed to crete the BIO\n");
        goto end;
    }
    SSL_set_bio(ssl, bio, bio);

    
    if (!SSL_set_tlsext_host_name(ssl, hostname)) {
        printf("Failed to set the SNI hostname\n");
        goto end;
    }

    
    if (!SSL_set1_host(ssl, hostname)) {
        printf("Failed to set the certificate verification hostname");
        goto end;
    }

    
    if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn)) != 0) {
        printf("Failed to set the ALPN for the connection\n");
        goto end;
    }

    
    if (!SSL_set1_initial_peer_addr(ssl, peer_addr)) {
        printf("Failed to set the initial peer address\n");
        goto end;
    }

    
    if (SSL_connect(ssl) < 1) {
        printf("Failed to connect to the server\n");
        
        if (SSL_get_verify_result(ssl) != X509_V_OK)
            printf("Verify error: %s\n",
                X509_verify_cert_error_string(SSL_get_verify_result(ssl)));
        goto end;
    }

    
    stream1 = SSL_new_stream(ssl, 0);
    stream2 = SSL_new_stream(ssl, SSL_STREAM_FLAG_UNI);
    if (stream1 == NULL || stream2 == NULL) {
        printf("Failed to create streams\n");
        goto end;
    }

    
    if (!write_a_request(stream1, request1_start, hostname)) {
        printf("Failed to write HTTP request on stream 1\n");
        goto end;
    }

    if (!write_a_request(stream2, request2_start, hostname)) {
        printf("Failed to write HTTP request on stream 2\n");
        goto end;
    }

    

    printf("Stream 1 data:\n");
    
    while (SSL_read_ex(stream1, buf, sizeof(buf), &readbytes)) {
        
        fwrite(buf, 1, readbytes, stdout);
    }
    
    printf("\n");

    
    switch (SSL_get_error(stream1, 0)) {
    case SSL_ERROR_ZERO_RETURN:
        
        break;

    case SSL_ERROR_SSL:
        
        switch (SSL_get_stream_read_state(stream1)) {
        case SSL_STREAM_STATE_RESET_REMOTE:
            printf("Stream reset occurred\n");
            
            break;

        case SSL_STREAM_STATE_CONN_CLOSED:
            printf("Connection closed\n");
            
            goto end;

        default:
            printf("Unknown stream failure\n");
            break;
        }
        break;

    default:
        
        printf ("Failed reading remaining data\n");
        break;
    }

    
    stream3 = SSL_accept_stream(ssl, 0);
    if (stream3 == NULL) {
        printf("Failed to accept a new stream\n");
        goto end;
    }

    printf("Stream 3 data:\n");
    
    while (SSL_read_ex(stream3, buf, sizeof(buf), &readbytes))
        fwrite(buf, 1, readbytes, stdout);
    printf("\n");

    
    switch (SSL_get_error(stream3, 0)) {
    case SSL_ERROR_ZERO_RETURN:
        
        break;

    case SSL_ERROR_SSL:
        switch (SSL_get_stream_read_state(stream3)) {
        case SSL_STREAM_STATE_RESET_REMOTE:
            printf("Stream reset occurred\n");
            break;

        case SSL_STREAM_STATE_CONN_CLOSED:
            printf("Connection closed\n");
            goto end;

        default:
            printf("Unknown stream failure\n");
            break;
        }
        break;

    default:
        printf ("Failed reading remaining data\n");
        break;
    }

    
    do {
        ret = SSL_shutdown(ssl);
        if (ret < 0) {
            printf("Error shutting down: %d\n", ret);
            goto end;
        }
    } while (ret != 1);

    
    res = EXIT_SUCCESS;
 end:
    
    if (res == EXIT_FAILURE)
        ERR_print_errors_fp(stderr);

    
    SSL_free(ssl);
    SSL_free(stream1);
    SSL_free(stream2);
    SSL_free(stream3);
    SSL_CTX_free(ctx);
    BIO_ADDR_free(peer_addr);
    return res;
}
