s_time.c 26.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
/* apps/s_time.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 */

#define NO_SHUTDOWN
//#define DEBUG 

/*-----------------------------------------
   s_time - SSL client connection timer program
   Written and donated by Larry Streepy <streepy@healthcare.com>
  -----------------------------------------*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>			// to support boolean
#include "common.h"				// common library between client and server
#define USE_SOCKETS
#include "apps.h"
#ifdef OPENSSL_NO_STDIO
#define APPS_WIN16
#endif
#include <openssl/x509.h>
#include <openssl/ssl.h>
#include <openssl/pem.h>
#include "s_apps.h"
#include <openssl/err.h>
#include <time.h>
#ifdef WIN32_STUFF
#include "winmain.h"
#include "wintext.h"
#endif
#if !defined(OPENSSL_SYS_MSDOS)
#include OPENSSL_UNISTD
#endif

#undef PROG
#define PROG s_time_main

#undef ioctl
#define ioctl ioctlsocket

#define SSL_CONNECT_NAME	"localhost:4433"

/*#define TEST_CERT "client.pem" */ /* no default cert. */

#undef BUFSIZZ
#define BUFSIZZ 1024*10

#define MYBUFSIZ 1024*8

#undef min
#undef max
#define min(a,b) (((a) < (b)) ? (a) : (b))
#define max(a,b) (((a) > (b)) ? (a) : (b))

#undef SECONDS
#define SECONDS	10
extern int verify_depth;
extern int verify_error;

static void s_time_usage(void);
static int parseArgs( int argc, char **argv );
static SSL *doConnection( SSL *scon, char *proto );
static void s_time_init(void);
static int read_proxy_list(char *, char ** ); 
static int check_SSL_write_error( SSL *, int, int );
static void slices_management( SSL *, SPP_SLICE **, SPP_PROXY ** ); 
static int send_GET_request( SSL * ); 
int tcp_connect(char *host, int port);


/***********************************************************************
 * Static data declarations
 */

/* static char *port=PORT_STR;*/
static char *host = SSL_CONNECT_NAME;
static char *t_cert_file = NULL;
static char *t_key_file = NULL;
static char *CApath = NULL;
static char *CAfile = NULL;
static char *tm_cipher = NULL;
static int tm_verify = SSL_VERIFY_NONE;
static int maxTime = SECONDS;
static SSL_CTX *tm_ctx = NULL;
static const SSL_METHOD *s_time_meth = NULL;
static char *s_www_path = NULL;
static long bytes_read = 0; 
static int st_bugs = 0;
static int perform = 0;
#ifdef FIONBIO
static int t_nbio = 0;
#endif
#ifdef OPENSSL_SYS_WIN32
static int exitNow = 0;                    // Set when it's time to exit main
#endif
static int slices_len = 0;                 // Number of slices (spp) 
static int r = 0;                          // Number of proxies with read access (spp)
static int w = 0;                          // Number of proxies with write access (spp)
static char *proto = "ssl";                // Protocol of choice (ssl; spp) 
static int N_proxies = 0;                  // number of proxies indicated
static char *filename = "proxyList";       // filename for proxy
static char **proxies_address;             // array of address for proxies
static bool reuse = false;                 // SSL session caching 
static int mySoc = NULL;

static void s_time_init(void)
	{
	host=SSL_CONNECT_NAME;
	t_cert_file=NULL;
	t_key_file=NULL;
	CApath=NULL;
	CAfile=NULL;
	tm_cipher=NULL;
	tm_verify = SSL_VERIFY_NONE;
	maxTime = SECONDS;
	tm_ctx=NULL;
	s_time_meth=NULL;
	s_www_path=NULL;
	bytes_read=0; 
	st_bugs=0;
	perform=0;

#ifdef FIONBIO
	t_nbio=0;
#endif
#ifdef OPENSSL_SYS_WIN32
	exitNow = 0;		/* Set when it's time to exit main */
#endif
	}

/***********************************************************************
 * usage - display usage message
 */
static void s_time_usage(void){
	static char umsg[] = "\
-time arg     - max number of seconds to collect data, default %d\n\
-verify arg   - turn on peer certificate verification, arg == depth\n\
-cert arg     - certificate file to use, PEM format assumed\n\
-key arg      - RSA file to use, PEM format assumed, key is in cert file\n\
                file if not specified by this option\n\
-CApath arg   - PEM format directory of CA's\n\
-CAfile arg   - PEM format file of CA's\n\
-cipher       - preferred cipher to use, play with 'openssl ciphers'\n\n";

	printf( "usage: s_time <args>\n\n" );

	printf("-connect host:port - host:port to connect to (default is %s)\n",SSL_CONNECT_NAME);
#ifdef FIONBIO
	printf("-nbio         - Run with non-blocking IO\n");
	//printf("-ssl2         - Just use SSLv2\n");
	//printf("-ssl3         - Just use SSLv3\n");
	printf("-bugs         - Turn on SSL bug compatibility\n");
	printf("-new          - Just time new connections\n");
	printf("-reuse        - Just time connection reuse\n");
	printf("-www page     - Retrieve 'page' from the server\n");
	printf("-time         - Test duration\n");
	printf("--------------------------------\n");
    printf("-proto        - Protocol requested [sll ; spp; fwd ; pln]\n");
	printf("-slice        - Number of slices requested\n"); 
	printf("-proxies      - Number of proxies\n"); 
    printf("-read         - Number of proxies with read access (per slice)\n"); 
    printf("-write        - Number of proxies with write access (per slice)\n");
#endif
	printf( umsg,SECONDS );
}

/***********************************************************************
 * parseArgs - Parse command line arguments and initialize data
 *
 * Returns 0 if ok, -1 on bad args
 */
static int parseArgs(int argc, char **argv){

    int badop = 0;
    verify_depth = 0;
    verify_error = X509_V_OK;

    argc--;
    argv++;

    while (argc >= 1) {
	if (strcmp(*argv,"-connect") == 0){

		if (--argc < 1) goto bad;
		host= *(++argv);

	} else if (strcmp(*argv,"-reuse") == 0){

		perform = 2;
		reuse = true; 

	} else if (strcmp(*argv,"-new") == 0){

		perform = 1;

	} else if( strcmp(*argv,"-verify") == 0) {
	    
		tm_verify=SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE;
	    if (--argc < 1) goto bad;
	    verify_depth = atoi(*(++argv));
	    BIO_printf(bio_err,"verify depth is %d\n",verify_depth);

	} else if( strcmp(*argv,"-cert") == 0) {
	    
		if (--argc < 1) goto bad;
	    t_cert_file = *(++argv);

	} else if( strcmp(*argv,"-key") == 0) {

	    if (--argc < 1) goto bad;
	    t_key_file = *(++argv);

	} else if( strcmp(*argv,"-CApath") == 0) {

	    if (--argc < 1) goto bad;
	    CApath = *(++argv);

	} else if( strcmp(*argv,"-CAfile") == 0) {

	    if (--argc < 1) goto bad;
	    CAfile = *(++argv);

	} else if( strcmp(*argv,"-cipher") == 0) {

	    if (--argc < 1) goto bad;
	    tm_cipher= *(++argv);
	}
#ifdef FIONBIO
	else if(strcmp(*argv,"-nbio") == 0) {

	    t_nbio=1;

	}
#endif
	else if(strcmp(*argv,"-www") == 0) {

		if (--argc < 1) goto bad;
		s_www_path = *(++argv);
		if(strlen(s_www_path) > MYBUFSIZ-100){
			BIO_printf(bio_err,"-www option too long\n");
			badop=1;
		}
	} else if(strcmp(*argv,"-bugs") == 0){

	    st_bugs = 1;

	}

/*
#ifndef OPENSSL_NO_SSL2
	else if(strcmp(*argv,"-ssl2") == 0) {
	    s_time_meth = SSLv2_client_method();
	}
#endif
#ifndef OPENSSL_NO_SSL3
	else if(strcmp(*argv,"-ssl3") == 0) {
	    s_time_meth = SSLv3_client_method();
	}
#endif
*/
	// duration 
	else if( strcmp(*argv,"-time") == 0) {
	    if (--argc < 1) goto bad;
	    maxTime = atoi(*(++argv));
	}

	// protocol type
	else if( strcmp(*argv,"-proto") == 0) {
	    if (--argc < 1) goto bad;
		proto = *(++argv);

		// Added support for fwd (client side is regular SSL)
		if ((strcmp(proto, "fwd")) == 0){	
			proto = "ssl";
		}
		if ((strcmp(proto, "ssl")) == 0){	
		    s_time_meth = TLSv1_2_method();
		} else if ((strcmp(proto, "spp")) == 0){
		    s_time_meth = SPP_method(); 
		} else if ((strcmp(proto, "pln")) == 0){
		    s_time_meth = TLSv1_2_method(); 
		}
		 else {
	    	BIO_printf(bio_err, "Protocol %s not supported\n", proto); 
			goto bad; 
		}
	}

	// number of slices 
	else if( strcmp(*argv,"-slice") == 0) {
	    if (--argc < 1) goto bad;
	    slices_len = atoi(*(++argv));
	}

	// number of proxies with read access
	else if( strcmp(*argv,"-read") == 0) {
	    if (--argc < 1) goto bad;
	    r = atoi(*(++argv));
	}

	// number of proxies with write access
	else if( strcmp(*argv,"-write") == 0) {
	    if (--argc < 1) goto bad;
	    w = atoi(*(++argv));
	}

	else {
	    BIO_printf(bio_err,"unknown option %s\n",*argv);
	    badop=1;
	    break;
	}

	argc--;
	argv++;
    }

    // If no input from the user, perform=3 [2=reuse, 1=new]
	if (perform == 0){
		perform = 3;
	}

	// Exit if a bad option was given 
    if(badop) {
bad:
	s_time_usage();
	return -1;
    }

	// All good here
	return 0; 
}

/***********************************************************************
 * TIME - time functions
 */
#define START	0
#define STOP	1

// Function used to compute CPU (or process) time 
static double tm_Time_F(int s){
	return app_tminterval(s, 1);   //defined in [2833, /apps/appsc]
}

/***********************************************************************
 * Read counter of number of proxies in the provided list 
 */	
int read_proxy_count(char *file_name){
	FILE *fp;					// pointer to file
	int N; 						// number of proxies 
	char line [128];			// maximum size of line to read from 

	// Open file for reading
	fp = fopen(file_name,"r");	
   
	// CHheck for errors while opening file
	if( fp == NULL ){
		printf("Error while opening file %s.\r\n", file_name);
		exit(-1);
    }

	// Read first line of file
	fgets ( line, sizeof line, fp ); 
	
	// Convert char into integer 
	N = line[0] - '0';
	
	// Close file
	fclose(fp);

	return N; 
}


/***********************************************************************
 * Read a proxy list from file and populate array of proxies
 */		
//void read_proxy_list(char *, SPP_PROXY **, SSL *); 
int read_proxy_list(char *file_name, char **proxies_address){
   	FILE *fp;					// pointer to file
	int count = 0;				// simple counters
	char line [128];			// maximum size of line to read from 
	bool firstLine = 1; 		// flag for first line in file
	int N; 						// local variable for number of proxies

	// Open file for reading
	fp = fopen(file_name,"r");	
   
	// Check for errors while opening file
	if( fp == NULL ){
		printf("Error while opening file %s.\r\n", file_name);
		exit(-1);
	}

	// Read file line-by-line
	while ( fgets ( line, sizeof line, fp ) != NULL ) {
	
		// Remove trailing newline (NOTE: strtoK is not thread safe)
		strtok(line, "\n");

		// Handle first line as a special case
		if (firstLine){
			firstLine = 0; 
			continue; 
		}

		// Generate a proxy from IP address just read 
		char *newLine;  
		newLine = (char *)malloc(strlen(line));    
		strcpy(newLine, line);
		proxies_address[count] = newLine;
		
		// Move array index
		count++; 
	}
	
	// Close file
	fclose(fp);

	// all good; 
	return N; 
}


/***********************************************************************
 * Print proxy list 
 */	
void print_proxy_list(SPP_PROXY **proxies, int N){
	int i; 
	
	#ifdef DEBUG	
	printf("Print proxy list. There are %d available proxies.\r\n", N);	
	#endif 
	for (i = 0; i < N; i++){
		printf("Proxy %d -- %s\r\n", i, proxies[i]->address);
	}
}


/***********************************************************************
 * Check for SSL_write error (just write at this point)  
 */	
int check_SSL_write_error(SSL *ssl, int r, int request_len){
	
	switch(SSL_get_error(ssl, r)){
		case SSL_ERROR_NONE:
			if(request_len != r){
				printf("Incomplete write!");
				return -1; 
			}
			break;

		default:
			printf("SSL write problem");
			return -1; 
	}
	return 0; 
}

/***********************************************************************
 * Create slices and assign read and write rights to proxies 
 */	

void slices_management(SSL *ssl, SPP_SLICE **slice_set, SPP_PROXY ** proxies){

	// Create slices_n slices with incremental purpose 
	int i; 
	#ifdef DEBUG
	printf("[DEBUG] Generating %d slices\n", slices_len); 
	#endif
	for (i = 0;  i < slices_len; i++){
		char *newPurpose;  
		char str[30]; 
		sprintf (str, "slices_%d", i); 
		newPurpose = (char *)malloc(strlen(str));    
		strcpy(newPurpose, str);
		slice_set[i] = SPP_generate_slice(ssl, newPurpose); 
		#ifdef DEBUG
		printf("[DEBUG] Generated slices %d with purpose %s\n", slice_set[i]->slice_id, slice_set[i]->purpose); 
		#endif
	}

	// Assign write access to proxies for all slices 
	// Find MAX between r and w
	int MAX = max(w, r);
	
	// Iterate among proxies
	for (i = 0; i < MAX ; i++){
		// assign read access if requested
		if (i < r){
			if (SPP_assign_proxy_read_slices(ssl, proxies[i], slice_set, slices_len) == 1 ) {
				#ifdef DEBUG
				printf ("[DEBUG] Proxy %s assigned read access to slice-set (READ_COUNT=%d)\n", proxies[i]->address, (i + 1)); 
				#endif
			}
		}

		// assign write access if requested
		if (i < w){
			if (SPP_assign_proxy_write_slices(ssl, proxies[i], slice_set, slices_len) == 1 ) {
				#ifdef DEBUG
				printf ("[DEBUG] Proxy %s assigned write access to slice-set (WRITE COUNT=%d)\n", proxies[i]->address, (i + 1)); 
				#endif
			}
		}
	}	
}

/***********************************************************************
 * Send a GET request (ssl and spp)
 */
int send_GET_request(SSL *scon){

		MS_STATIC char buf[1024*8];   //Buffer allocation 
		int i; 
		
		// Logging 
		#ifdef DEBUG
		printf("[DEBUG]  GET %s\n", s_www_path); 
		#endif 

		// Form HTTP GET request 
		BIO_snprintf(buf, sizeof buf, "GET %s HTTP/1.0\r\n\r\n", s_www_path);
		int request_len = strlen(buf); 
			
		// Send HTTP GET request (SPP) 
		if (strcmp(proto, "spp") == 0){	
			for (i = 0; i < scon->slices_len; i++){
				// currently writing same record -- differentiate per record in the future 
				int r = SPP_write_record(scon, buf, request_len, scon->slices[i]);
				if (check_SSL_write_error(scon, r, request_len) < 0){
					return -1;  
				}
			}	 
		}
			
		// Send HTTP GET request (SSL) 
		if (strcmp(proto, "ssl") == 0){
			#ifdef DEBUG
			printf("[DEBUG] Sending GET request %s\n", buf); 
			#endif 
			int r = SSL_write(scon, buf, request_len);
			if (check_SSL_write_error(scon, r, request_len) < 0){
				return -1; 
			}
		}
				// Send HTTP GET request (SSL) 
		if (strcmp(proto, "pln") == 0){
			#ifdef DEBUG
			printf("[DEBUG] Sending GET request (plain) %s\n", buf); 
			#endif 
			int r = write(scon, buf, request_len);
			if (r < 0){
				return -1; 
			}
		}

		// All good
		return 0; 
}

/***********************************************************************
 * Wait GET response (ssl and spp)
 */
int wait_GET_response(SSL* scon){

	MS_STATIC char buf[1024*8];   //Buffer allocation 
	int i = 0; 

	// Wait for HTTP response (SPP)
	if (strcmp(proto, "spp") == 0){				
		SPP_SLICE *slice;    // slice for SPP_read
		SPP_CTX *ctx;        // context pointer for SPP_read
		
		// check error for SSP_read_record
		while ((i = SPP_read_record(scon, buf, sizeof(buf), &slice, &ctx)) > 0){
			bytes_read += i;
			#ifdef DEBUG
			//printf("%s", buf); 
			printf("[DEBUG] GET response received (size=%lu)\n", bytes_read); 
			#endif 
		}
	}
	
	// Wait for HTTP response (SSL)
	if (strcmp(proto, "ssl") == 0){
		// check error for SSP_read_record
		while ((i = SSL_read(scon, buf, sizeof(buf))) > 0){
			bytes_read += i;
			#ifdef DEBUG
			//printf("%s", buf); 
			printf("[DEBUG] GET response received (size=%lu)\n", bytes_read); 
			#endif 
		}
	}
		// Wait for HTTP response (pln)
	if (strcmp(proto, "pln") == 0){
		// check error for SSP_read_record
		while ((i = read(scon, buf, sizeof(buf))) > 0){
			bytes_read += i;
			#ifdef DEBUG
			//printf("%s", buf); 
			printf("[DEBUG] GET response received (size=%lu)\n", bytes_read); 
			#endif 
		}
	}

	// All good 
	return 0; 
}


/***********************************************************************
 * MAIN - main processing area for client
 *			real name depends on MONOLITH
 */
int MAIN(int, char **);

int MAIN(int argc, char **argv){

	double totalTime = 0.0;
	int nConn = 0;
	SSL *scon = NULL;
	long finishtime = 0;
	int ret = 1, i;
	MS_STATIC char buf[1024*8];
	int ver;
	clock_t start, end;
	double cpu_time_used;

	apps_startup();
	s_time_init();

	// Outpur for errors
	if (bio_err == NULL){
		bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
	}

/*	
#if !defined(OPENSSL_NO_SSL2) && !defined(OPENSSL_NO_SSL3)
	s_time_meth = SSLv23_client_method();
#elif !defined(OPENSSL_NO_SSL3)
	s_time_meth = SSLv3_client_method();
#elif !defined(OPENSSL_NO_SSL2)
	s_time_meth = SSLv2_client_method();
#endif
*/

	// Parse command line arguments
	if( parseArgs( argc, argv ) < 0 ){
		goto end;
	}

	// Read proxy list 
	N_proxies = read_proxy_count(filename); 
	
	// Quick check on input parameters	
	if (r > N_proxies || w > N_proxies){
		printf ("The values for r and w need to be <= than the number of proxies\n"); 
		goto end; 
	}

	// Logging input parameters
	#ifdef DEBUG
	BIO_printf(bio_err, "[DEBUG] No. slices=%d No. proxies=%d read=%d write=%d proto=%s\n", slices_len, N_proxies, r, w, proto);
	#endif

	// Allocate memory for proxies address
	proxies_address  = malloc( N_proxies * sizeof (char*));
	read_proxy_list(filename, proxies_address); 

	#ifdef DEBUG
	int ii; 
	for (ii = 0; ii < N_proxies; ii++){
		printf("\t[DEBUG] Proxy %d: %s\n", ii, proxies_address[ii]); 
	}
	#endif

	
	OpenSSL_add_ssl_algorithms();
	if ((tm_ctx = SSL_CTX_new(s_time_meth)) == NULL){
		return(1);
	}

	// Quiet shutdown ...
	SSL_CTX_set_quiet_shutdown(tm_ctx, 1);

	// Set bug options
	if (st_bugs){
		SSL_CTX_set_options(tm_ctx,SSL_OP_ALL);
	}



	SSL_CTX_set_cipher_list(tm_ctx, tm_cipher);

	// Set certificate 
	if(!set_cert_stuff(tm_ctx,t_cert_file,t_key_file)){
		goto end;
	}

	SSL_load_error_strings();

	if ((!SSL_CTX_load_verify_locations(tm_ctx,CAfile,CApath)) || (!SSL_CTX_set_default_verify_paths(tm_ctx))){
		/* BIO_printf(bio_err,"error setting default verify locations\n"); */
		ERR_print_errors(bio_err);
		/* goto end; */
	}

	// If no cipher in input, use default one
	if (tm_cipher == NULL){
		tm_cipher = getenv("SSL_CIPHER");
	}

	// If no cipher at this point, throw an error 
	if (tm_cipher == NULL ) {
		fprintf( stderr, "No CIPHER specified\n" );
	}

    /* [Perform = {2=reuse, 1=new, 3=undefined}]
	if (!(perform & 1)){
		goto next;
	}
	*/
	
	// We are here if -new was used or nothing was specified 
	#ifdef DEBUG
	printf( "[DEBUG] Option=-new Collecting connection statistics for %d seconds\n", maxTime );
	#endif

	// Loop and time how long it takes to make connections
	bytes_read = 0;
	finishtime = (long) time (NULL) + maxTime;
	tm_Time_F(START);

	// Successively open and use connections until time expires
	start = clock();
	for (;;){
		// If time is done just break 
		if (finishtime < (long) time (NULL)){
			#ifdef DEBUG
			printf("[DEBUG] Time is up %lu\n", finishtime); 
			#endif 
			break;
		}
		/*
		// WIN32 specific stuff
#ifdef WIN32_STUFF
		if( flushWinMsgs(0) == -1 ){
			goto end;
		}

		if( waitingToDie || exitNow ){		
			goto end;
		}
#endif */
		// new connection (no re-use) 

		#ifdef DEBUG
		printf("[DEBUG] Connection %d ", nConn); 
		#endif 
		// Handshake
		if (! reuse){
			#ifdef DEBUG
			printf("(new)\n"); 
			#endif 
			scon = NULL; 
		}else{
			#ifdef DEBUG
			printf("(reuse)\n"); 
			#endif 
		}



		if( (scon = doConnection( scon, proto )) == NULL ){
			printf("Error: Could not establish connection\n");
			goto end;
		}

		// Ask for a file if indicated in input 
		if (s_www_path != NULL) {
			
			// Send GET request 
			if (send_GET_request(scon) < 0){
				printf("Error in sending GET request\n");
				goto end; 
			}
			
			// Wait for GET response 
			if (wait_GET_response(scon) < 0){
				printf("Error in receivign GET response\n");
				goto end; 
			}
		}

		nConn += 1;

		if (strcmp(proto, "pln") == 0){	
			#ifdef DEBUG
			printf("[DEBUG] Closing %d\n", scon);
			#endif 
			close((int)scon);
			#ifdef DEBUG
			printf("[DEBUG] Done %d\n", scon);
			#endif 
			scon = NULL;
			continue; //avoid all the tls closing...
		}

#ifdef NO_SHUTDOWN
		#ifdef DEBUG
		printf("[DEBUG] NO SSL shutdown\n"); 
		#endif 
		SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
#else
		#ifdef DEBUG
		printf("[DEBUG] SSL shutdown\n"); 
		#endif 
		SSL_shutdown(scon);
#endif
		
		#ifdef DEBUG
		printf("[DEBUG] SSL shutdown2 -- ?\n"); 
		#endif 
		SHUTDOWN2(SSL_get_fd(scon));


		if (SSL_session_reused(scon)){
			ver = 'r';
		} else{
			ver = SSL_version(scon);
			if (ver == TLS1_VERSION)
				ver = 't';
			else if (ver == SSL3_VERSION)
				ver = '3';
			else if (ver == SSL2_VERSION)
				ver = '2';
			else
				ver = '*';
		}
		#ifdef DEBUG
		printf("[DEBUG] SSL version=%d\n", ver); 
		#endif 
		fflush(stdout);

		// Free session 
		SSL_free(scon);
		scon = NULL;
	}
	end = clock();
	cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;	
	totalTime += tm_Time_F(STOP); /* Add the time for this iteration */

	i = (int)((long)time(NULL) - finishtime + maxTime);
	//printf( "\n\n%d connections. CPU time=%.2fs; %.2f connections/user sec, bytes read %ld\n", nConn, totalTime, ((double)nConn/totalTime),bytes_read);
	printf( "\n\n%d connections. CPU time=%.5fs; %.2f connections/user sec, bytes read %ld\n", nConn, totalTime, ((double)nConn/cpu_time_used),bytes_read);
	printf( "%d connections in %ld real seconds, %ld bytes read per connection\n",nConn, (long)time(NULL) - finishtime + maxTime, bytes_read/nConn);
	//printf( "\n CPU time=%.5fs; %.5f connections/user sec [NEW]", cpu_time_used, ((double)nConn/cpu_time_used));


/* Now loop and time connections using the same session id over and over
next:
    // [Perform = {2=reuse, 1=new, 3=undefined}]
	if (!(perform & 2)){
		goto end;
	}
	#ifdef DEBUG 
	printf( "[DEBUG] Now timing with session id reuse.\n" );
	#endif 

	nConn = 0;
	totalTime = 0.0;

	finishtime=(long)time(NULL)+maxTime;

	printf( "starting\n" );
	bytes_read=0;
	tm_Time_F(START);
	scon = NULL; 

	for (;;){
		if (finishtime < (long)time(NULL)){
			break;
		}

#ifdef WIN32_STUFF
		if( flushWinMsgs(0) == -1 )
			goto end;

		if( waitingToDie || exitNow )	// we're dead 
			goto end;
#endif

	 	if( (doConnection( scon, proto )) == NULL )
			goto end;
		
		if (s_www_path) {
			// Send GET request 
			if (send_GET_request(scon) < 0){
				printf("Error in sending GET request\n");
				goto end; 
			}
		
			// Receive GET response
			if (wait_GET_response(scon) < 0){
				printf("Error in receiving GET response\n");
				goto end; 
			}

		}

#ifdef NO_SHUTDOWN
		SSL_set_shutdown(scon,SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN);
#else
		SSL_shutdown(scon);
#endif
		SHUTDOWN2(SSL_get_fd(scon));
	
		nConn += 1;
		if (SSL_session_reused(scon))
			ver='r';
		else
			{
			ver = SSL_version(scon);
			if (ver == TLS1_VERSION)
				ver = 't';
			else if (ver == SSL3_VERSION)
				ver = '3';
			else if (ver == SSL2_VERSION)
				ver = '2';
			else
				ver = '*';
			}
		fflush(stdout);
		}
	totalTime += tm_Time_F(STOP); // Add the time for this iteration

	// Logging 
	printf( "\n\n%d connections in %.2fs; %.2f connections/user sec, bytes read %ld\n", nConn, totalTime, ((double)nConn/totalTime),bytes_read);
	printf( "%d connections in %ld real seconds, %ld bytes read per connection\n",nConn,(long)time(NULL)-finishtime+maxTime,bytes_read/nConn);
	//

	ret=0;
*/

end:
	if (scon != NULL){
		SSL_free(scon);
	}

	if (tm_ctx != NULL){
		SSL_CTX_free(tm_ctx);
		tm_ctx=NULL;
	}

	apps_shutdown();
	OPENSSL_EXIT(ret);
}

/* A simple error and exit routine*/
int err_exit(string)
  char *string;
  {
  	#ifdef DEBUG
    printf("[ERROR] %s\n",string);
	#endif

    fprintf(stderr,"%s\n",string);
    exit(0);
  }

/* Print SSL errors and exit*/
int berr_exit(string)
  char *string;
  {
    #ifdef DEBUG
	BIO_printf(bio_err,"%s\n",string);
    ERR_print_errors(bio_err);
	#endif
    exit(0);
  }



// TCP connect function 
int tcp_connect(char *host, int port){

	struct hostent *hp;
	struct sockaddr_in addr;
	int sock;



	// Resolve host 
	if(!(hp = gethostbyname(host))){
		berr_exit("Couldn't resolve host");
	}