#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <openssl/lhash.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/crypto.h>

#define SESSION_TIMEOUT 300
#define HTTPS_PORT 443

#define GET_REQUEST "GET / HTTP/1.1\n\rConnection: close\n\r\n\r"

static unsigned char *sid_ctx = (unsigned char *)"quickssl SID";

SSL_CTX *ctx;

static void info_callback(SSL *s, int where, int ret)
{
	printf ("%s\n", SSL_state_string_long(s));
}

static void sslerror (char *txt)
{
char string[120];

	ERR_error_string(ERR_get_error(), string);
	printf ("%s: %s", txt, string);
}



int main (int argc, char *argv[])
{
struct sockaddr_in addr;
int s;
SSL *ssl;
char read_buf[2048];
int read_bytes;
int i;

	if (argc < 2) {
		printf ("Usage: %s <ip-address>\n", argv[0]);
		return 0;
	}

	/* Init OpenSSL and setup Context (do once for entire program) */

	SSLeay_add_ssl_algorithms();
	SSL_load_error_strings();
	ctx = SSL_CTX_new(SSLv3_client_method());
	SSL_CTX_set_session_cache_mode (ctx, SSL_SESS_CACHE_BOTH);
	SSL_CTX_set_timeout (ctx, SESSION_TIMEOUT);
	SSL_CTX_set_info_callback(ctx, info_callback);

	/* make TCP connection to server */

	s = socket(AF_INET, SOCK_STREAM, 0);
	memset (&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(HTTPS_PORT);
	addr.sin_addr.s_addr = inet_addr(argv[1]);
	connect(s, (struct sockaddr *) &addr, sizeof(addr));

	/* start ssl negotiation */

	if (!(ssl = SSL_new (ctx))) {
		sslerror("SSL_new");
		goto done;
	}

	SSL_set_session_id_context(ssl, sid_ctx, strlen(sid_ctx));
	SSL_set_fd(ssl, s);
	SSL_set_connect_state(ssl);

	/* do the connect */

	if (SSL_connect(ssl) <= 0) {
		sslerror("SSL_connect");
		goto ssl_shutdown;
	}

	/* Sent HTTP request, get only 2048 bytes of response */

	SSL_write(ssl, GET_REQUEST, strlen(GET_REQUEST));
	read_bytes = SSL_read(ssl, read_buf, 2048);

	/* dump the HTTP response */
	
	for (i=0;i < read_bytes; i++) {
		printf ("%c", read_buf[i]);
	}
	
	/* close SSL connection */

ssl_shutdown:
	SSL_set_shutdown(ssl, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN);
	SSL_free(ssl);
	ERR_remove_state(0);
done:
	close (s);

	return 0;
}
	


	




