common.c 10.5 KB
Newer Older
powelld's avatar
powelld committed
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
#include "common.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <signal.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <sys/select.h>
#include <errno.h>

#define MAXSTRLEN (1024)

static void
common_Log(FILE *pLog, const char *csFmtStr, va_list va_args);
static void
common_DoExit(int iExitCode);
static void
common_SigpipeHandle(int x);

/*function to wait for a specific FILE to be ready for reading*/
ERROR_STATUS
COMMON_ReadWaitFile(FILE *phF)
{
	int iFDNum=fileno(phF);
	return COMMON_ReadWaitFD(iFDNum);
}
/*function to wait for a specific File Descriptor (file, socket, pipe) to be ready for reading*/
ERROR_STATUS
COMMON_ReadWaitFD(int iFD)
{
	int iStatus;
	fd_set fds_r,fds_w,fds_ex;

	FD_ZERO(&fds_r);
	FD_ZERO(&fds_w);
	FD_ZERO(&fds_ex);
	FD_SET(iFD,&fds_r);

	iStatus=select(iFD+1,&fds_r,&fds_w,&fds_ex,NULL);

	if(iStatus>0) {
		/*more one file ready (i.e. should only be one)*/
		iStatus=SUCCESS;
	} else {
		/*something gone wrond or we are interrupted*/
		iStatus=ERROR_INTERRUPT;
	}
	return iStatus;
}


// Function to read a proxy list from file and populate array of proxies
// Each proxy should be a separate line containing the url only
// e.g.:
//127.0.0.1:8423
//127.0.0.1:8424
//127.0.0.1:4433
ERROR_STATUS
COMMON_ReadProxyListFile(SSL *ptSSL,
		const char *sFilename){
	FILE *phF;					// pointer to file
	unsigned int uiCount = 0;	// simple counters
	char acLine [128];			// maximum size of line to read from
	SPP_PROXY *patNewProxiesList=NULL;

	if(ptSSL==NULL || sFilename==NULL) {
		return INVALID_POINTER;
	}

	// Open file for reading
	phF = fopen(sFilename,"r");

	// Check for errors while opening file
	if( phF == NULL ){
		return FILE_NOT_READABLE;
	}

	uiCount=0;
	// Read file line-by-line
	while ( fgets ( acLine, sizeof(acLine), phF ) != NULL ) {

		// Remove trailing newline (NOTE: strtoK is not thread safe)
		strtok(acLine, "\n");
		if(strlen(acLine)<=2) continue; //ignore blank lines

		COMMON_AppendProxy(ptSSL,acLine);

		/*TODO - log the proxy creation properly*/
		COMMON_Log(stdout,"Proxy(%2u): %s\n",uiCount,acLine);
	}

	// Close file
	fclose(phF);
	return SUCCESS;
}

ERROR_STATUS
COMMON_InitProxySet(SSL *ptSSL)
{
	while(ptSSL->proxies_len>0) {
		ptSSL->proxies_len--;
		OPENSSL_free(ptSSL->proxies[ptSSL->proxies_len]);
	}
	ptSSL->proxies_len=0;
	memset(ptSSL->proxies,0,sizeof(ptSSL->proxies));
	return SUCCESS;
}
ERROR_STATUS
COMMON_InitMulticontextSet(SSL *ptSSL)
{
	while(ptSSL->slices_len>0) {
		ptSSL->slices_len--;
		OPENSSL_free(ptSSL->slices[ptSSL->slices_len]);
	}
	ptSSL->slices_len=0;
	memset(ptSSL->slices,0,sizeof(ptSSL->slices));
	return SUCCESS;
}

ERROR_STATUS
COMMON_AppendProxy(SSL *ptSSL,
		const char *psProxyURL)
{
	char *psProxyUrlCpy=NULL;

	if(ptSSL->proxies_len>=(sizeof(ptSSL->proxies)/sizeof(ptSSL->proxies[0])))
		return ARRAY_OVERFLOW;

	/*SPP_generate_proxy will generate something with the string provide
	 * but there is no guarantee that it will be sensible if
	 * invalid data is passed in*/
	psProxyUrlCpy=strdup(psProxyURL);
	ptSSL->proxies[ptSSL->proxies_len] = SPP_generate_proxy(ptSSL, psProxyUrlCpy);
	(ptSSL->proxies_len)++;
	return SUCCESS;
}
ERROR_STATUS
COMMON_AppendClientServer(SSL *ptSSL,
		const char *psURL, int isServer)
{
	char *psUrlCpy=NULL;

	if(ptSSL->proxies_len>=(sizeof(ptSSL->proxies)/sizeof(ptSSL->proxies[0])))
		return ARRAY_OVERFLOW;

	/*SPP_generate_proxy will generate something with the string provide
	 * but there is no guarantee that it will be sensible if
	 * invalid data is passed in*/
	psUrlCpy=strdup(psURL);
	/* TODO - SPP_generate_proxy probably won't assign the correct ID's
	 * to denote server and client
	 */
	if(isServer) {
		ptSSL->proxies[ptSSL->proxies_len] = SPP_generate_proxy(ptSSL, psUrlCpy);
		(ptSSL->proxies_len)++;
	} else { /*isClient*/
		memmove(&ptSSL->proxies[1],&ptSSL->proxies[0],ptSSL->proxies_len * sizeof(*ptSSL->proxies));
		ptSSL->proxies[0] = SPP_generate_proxy(ptSSL, psUrlCpy);
	}
	return SUCCESS;
}
ERROR_STATUS
COMMON_AppendContext(SSL *ptSSL,
		const char *psContextDesc)
{
	char *psContextDescCpy=NULL;

	if(ptSSL->slices_len>=(sizeof(ptSSL->slices)/sizeof(ptSSL->slices[0])))
		return ARRAY_OVERFLOW;
	psContextDescCpy=strdup(psContextDesc);
	ptSSL->slices[ptSSL->slices_len] = SPP_generate_slice(ptSSL, psContextDescCpy);
	ptSSL->slices_len++;
	return SUCCESS;

}

ERROR_STATUS
COMMON_SetProxyAccessPermissionByID(SSL *ptSSL, int iSliceID, int iMiddleboxNum,
							int bGrantRead, int bGrantWrite)
{
	int *read_slices; size_t *read_slice_len;
	int *write_slices; size_t *write_slice_len;
	int reads_insert_index, write_insert_index;
	int x,y,z;

	if(ptSSL->proxies_len<iMiddleboxNum || ptSSL->slices_len<iSliceID)
		return ARRAY_OVERFLOW;
	read_slices=ptSSL->proxies[iMiddleboxNum]->read_slice_ids;
	read_slice_len=&(ptSSL->proxies[iMiddleboxNum]->read_slice_ids_len);
	write_slices=ptSSL->proxies[iMiddleboxNum]->write_slice_ids;
	write_slice_len=&(ptSSL->proxies[iMiddleboxNum]->write_slice_ids_len);

	/*handle empty case specially*/
	if(*read_slice_len==0 && bGrantRead) {
		read_slices[0]=iSliceID;
		(*read_slice_len)++;
	}
	if(*write_slice_len==0 && bGrantWrite) {
		write_slices[0]=iSliceID;
		(*write_slice_len)++;
	}

	/*if we have just inserted the first record, this loop will
	 * terminate on first iteration*/
	x=0;y=*read_slice_len;
	while(y>x+1) {
		z=(x+y)/2;
		if(read_slices[z]>iSliceID) y=z;
		else x=z;
	}
	if(bGrantRead) {
		if(read_slices[x]!=iSliceID) {
			if(*read_slice_len>y) { /*we have higher number slices to move up*/
				memmove(&read_slices[x+1],&read_slices[x],(*read_slice_len-y)*sizeof(*read_slices));
			}
			read_slices[x]=iSliceID;
			(*read_slice_len)++;
		} /*else we are re-granted an already granted access - NOP*/
	} else { /*we are removing the permission if it is granted*/
		if(read_slices[x]==iSliceID) {
			if(*read_slice_len>y) { /*we have higher number slices to move up*/
				memmove(&read_slices[x],&read_slices[x+1],(*read_slice_len-y)*sizeof(*read_slices));
			}
			(*read_slice_len)--;
		} /*else we removing a non-existent permission - NOP*/
	}


	x=0;y=*write_slice_len;
	while(y>x+1) {
		z=(x+y)/2;
		if(write_slices[z]>iSliceID) y=z;
		else x=z;
	}
	if(bGrantWrite) {
		if(write_slices[x]!=iSliceID) {
			if(*write_slice_len>y) { /*we have higher number slices to move up*/
				memmove(&write_slices[x+1],&write_slices[x],(*write_slice_len-y)*sizeof(*write_slices));
			}
			write_slices[x]=iSliceID;
			(*write_slice_len)++;
		} /*else we are re-granted an already granted access - NOP*/
	} else { /*we are removing the permission if it is granted*/
		if(write_slices[x]==iSliceID) {
			if(*write_slice_len>y) { /*we have higher number slices to move up*/
				memmove(&write_slices[x],&write_slices[x+1],(*write_slice_len-y)*sizeof(*write_slices));
			}
			(*write_slice_len)--;
		} /*else we removing a non-existent permission - NOP*/
	}
	return SUCCESS;
}

ERROR_STATUS
COMMON_TcpConnect(int *piSocket, const char *sHost, int iPort){

	struct hostent *hp;
	struct sockaddr_in addr;
	int iOne=1;

	// Resolve host
	if(!(hp = gethostbyname(sHost)))
		return NETWORK_CONNECT_FAIL;

	memset(&addr, 0, sizeof(addr));
	addr.sin_addr = *(struct in_addr*)
	hp->h_addr_list[0];
	addr.sin_family = AF_INET;
	addr.sin_port = htons(iPort);

	if((*piSocket=socket(AF_INET,SOCK_STREAM, IPPROTO_TCP))<0){
		return NETWORK_CONNECT_FAIL;
	}
	/*I'm copying this option below*/
	//set_nagle(*piSocket, 1);
	setsockopt(*piSocket, IPPROTO_TCP, TCP_NODELAY, (char*)&iOne, sizeof(int));

	if(connect(*piSocket,(struct sockaddr *)&addr, sizeof(addr))<0){
		return NETWORK_CONNECT_FAIL;
	}

	return SUCCESS;
}


void
COMMON_LogErrorAndExit(int iExitCode, FILE *pLog, const char *csFmtStr, ...)
{
	va_list va_args;
	va_start(va_args,csFmtStr);
	common_Log(pLog, csFmtStr,va_args);
	va_end(va_args);
	common_DoExit(iExitCode);

}
void
COMMON_CheckLogErrorAndExit(int iExitCode, FILE *pLog, const char *csFmtStr, ...)
{
	va_list va_args;
	if(iExitCode!=0) {
		va_start(va_args,csFmtStr);
		common_Log(pLog, csFmtStr,va_args);
		va_end(va_args);
		common_DoExit(iExitCode);
	}
}
void
COMMON_Log(FILE *pLog, const char *csFmtStr, ...)
{
	va_list va_args;
	va_start(va_args,csFmtStr);
	common_Log(pLog, csFmtStr,va_args);
	va_end(va_args);

}
void
COMMON_CheckLog(int iExitCode, FILE *pLog, const char *csFmtStr, ...)
{
	va_list va_args;
	if(iExitCode!=0) {
		va_start(va_args,csFmtStr);
		common_Log(pLog, csFmtStr,va_args);
		va_end(va_args);
	}
}

char *gsPassword=NULL;

static int
password_cb(char *buf,int num, int rwflag,void *userdata)
{
	if(gsPassword==NULL)
		return 0;

	if(num<strlen(gsPassword)+1)
		return(0);

	strcpy(buf,gsPassword);
	return(strlen(gsPassword));

}

ERROR_STATUS
COMMON_InitializeSSLCtx(SSL_CTX **pptCtx,
		const char *sMyKeyfile, const char *sMyPassword,
		const char *sCAKeysFile,
		unsigned int iID) /*todo - check the name of this in spec - the byte that identifies the middlebox number, client or server*/
{
	const SSL_METHOD *meth;
	SSL_CTX *ctx;

	/* Global system initialization*/
	SSL_library_init();
	SSL_load_error_strings();


	/* Set up a SIGPIPE handler */
	signal(SIGPIPE,common_SigpipeHandle);

	if(iID==ID_CLIENT || iID==ID_SERVER) {
		meth = SPP_method();
	} else if(iID >=ID_MIDDLEBOX_MIN && iID<=ID_MIDDLEBOX_MAX) {
		meth = SPP_proxy_method();
	} else {
		return INTEGER_OUT_OF_RANGE;
	}

	ctx = SSL_CTX_new(meth);

	/* Specify the cipher suites that may be used. */
	if (!SSL_CTX_set_cipher_list(ctx, "DHE-RSA-AES128-SHA256")) {
		return ERROR_IN_LIBRARY_CALL;
	}


	/* Load the CAs*/
	if(!(SSL_CTX_load_verify_locations(ctx,
			sCAKeysFile,NULL)))
		return FILE_NOT_READABLE;

	/* Load our certificate*/
	if(!(SSL_CTX_use_certificate_chain_file(ctx,
			sMyKeyfile)))
		return FILE_NOT_READABLE;

	/*set the routine to handle passing in the passowrd for our private key*/
	if(gsPassword!=NULL) {
		free(gsPassword); gsPassword=NULL;
	}
	if(sMyPassword!=NULL){
		gsPassword=strdup(sMyPassword);
	}

	SSL_CTX_set_default_passwd_cb(ctx,
			password_cb);

	/*load our private key*/
	if(!(SSL_CTX_use_PrivateKey_file(ctx,
			sMyKeyfile,SSL_FILETYPE_PEM)))
		return FILE_NOT_READABLE;

	*pptCtx=ctx;
	return SUCCESS;
}

void
COMMON_DestroyCtx(SSL_CTX *ptCtx)
{
	if(gsPassword!=NULL) {
		free(gsPassword); gsPassword=NULL;
		SSL_CTX_free(ptCtx);
	}
}



static void
common_Log(FILE *pLog, const char *csFmtStr, va_list va_args)
{
	assert(pLog!=NULL);
	assert(csFmtStr!=NULL);
	assert(strnlen(csFmtStr,MAXSTRLEN)<MAXSTRLEN);
	vfprintf(pLog,csFmtStr,va_args);
	fflush(pLog);
}

static void
common_DoExit(int iExitCode)
{
	exit(iExitCode);
}

static void
common_SigpipeHandle(int x)
{
	UNUSED(x);
}