#include "openssl/ssl.h"
#include "openssl/bio.h"
#include "openssl/err.h"

#include "stdio.h"
#include "string.h"

int main()
{
    BIO * bio;
    SSL * ssl;
    SSL_CTX * ctx = NULL;
    SSL_METHOD *meth;

    int p;

    //char * request = "GET / HTTP/1.1\x0D\x0AHost: www.verisign.com\x0D\x0A\x43onnection: Close\x0D\x0A\x0D\x0A";
    char * request = "<?xml version=\"1.0\" encoding=\"utf-8\"?><CloudStorage><Job Type=\"Change\" List=\"ServiceStatus\"><VolumeID>softline2009@totodisk05</VolumeID><StatusCode>SVC_STATUS_ING</StatusCode></Job></CloudStorage>";
    char r[1024];

    /* Set up the library */
    SSL_library_init();
    //ERR_load_BIO_strings();
    SSL_load_error_strings();

    meth=SSLv3_method();

    /* Set up the SSL context */
    ctx = SSL_CTX_new(meth);
    if(ctx == NULL )
    {
	fprintf(stderr, "Error ctx\n");
        ERR_print_errors_fp(stderr);
	return 1;
    }		

	// 2014.07.10 rc_mngd 는 인증서 필요 없이도 SSL 사용한 데이터 통신 가능함
    /* Load the trust store */
	//if(! SSL_CTX_load_verify_locations(ctx, "/user/service/etc/rc_mmngd_CA.pem", "/user/service/etc/"))
	//{
	//    fprintf(stderr, "Error loading trust store\n");
	//    ERR_print_errors_fp(stderr);
	//    SSL_CTX_free(ctx);
	//    return 0;
	//}

    /* Setup the connection */

    bio = BIO_new_ssl_connect(ctx);

    /* Set the SSL_MODE_AUTO_RETRY flag */

    BIO_get_ssl(bio, & ssl);
    SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);

    /* Create and setup the connection */

    //BIO_set_conn_hostname(bio, "www.verisign.com:https");
    BIO_set_conn_hostname(bio, "localhost:13112");

    if(BIO_do_connect(bio) <= 0)
    {
        fprintf(stderr, "Error attempting to connect\n");
        ERR_print_errors_fp(stderr);
        BIO_free_all(bio);
        SSL_CTX_free(ctx);
        return 0;
    }

	// 2014.07.10 rc_mngd 는 인증서 필요 없이도 SSL 사용한 데이터 통신 가능함
    /* Check the certificate */
    //if(SSL_get_verify_result(ssl) != X509_V_OK)
    //{
    //    fprintf(stderr, "Certificate verification error: %i\n", SSL_get_verify_result(ssl));
    //    BIO_free_all(bio);
    //    SSL_CTX_free(ctx);
    //    return 0;
    //}

    /* Send the request */
    int nH = htonl(strlen(request));
    if( BIO_write(bio, &nH, 4) <= 0 )
    {
        printf("Failed write\n");
        ERR_print_errors_fp(stderr);
        return 0;
    }

    if( BIO_write(bio, request, strlen(request)) <= 0 )
    {
		printf("Failed write\n");
        ERR_print_errors_fp(stderr);
		return 0;
     }
    /* Read in the response */

    for(;;)
    {
        p = BIO_read(bio, r, 1023);
		if(p == 0)
		{
			printf("read end\n");
			ERR_print_errors_fp(stderr);
			break;
		}
		else if(p < 0) 
		{
				printf("Failed read \n");
				ERR_print_errors_fp(stderr);
				break;
		}
		else {}

        r[p] = 0;
        printf("%s", r);
    }
    /* Close the connection and free the context */
    BIO_free_all(bio);
    SSL_CTX_free(ctx);
    return 0;
}


