client.c 12.2 KB
Newer Older
powelld's avatar
powelld committed
1 2
#define DEBUG

powelld's avatar
powelld committed
3 4 5 6 7 8
#include <pthread.h>
#include <assert.h>
#include <getopt.h>
#include "common.h"
#include <signal.h>
#include <unistd.h>
powelld's avatar
powelld committed
9 10 11 12 13 14 15 16 17
#include <openssl/err.h>
#include <stdbool.h>
#include "cJSON.h"

#ifdef DEBUG
#define DEBUG_PRINT(...) do{ fprintf( stdout, __VA_ARGS__ ); } while( false )
#else
#define DEBUG_PRINT(...) do{ } while ( false )
#endif
powelld's avatar
powelld committed
18 19 20 21 22 23 24 25 26

const char *USAGE="client [-v | -V logfile ] [ -k keylog ] [-c context_list] [-s server] [-m middlebox_list | -M middlebox_list_file]\n"
	"\tcontext list must be comma-separated list of context names, defaults to \"header,body\"\n"
	"\tserver must be url including port, default 127.0.0.1:" xstr(DEFAULT_SERVER_PORT) "\n"
	"\tmiddlebox list must semi-colon delimited urls including port,"
	"\tmiddlebox list_file must be a file with middlebox urls on separate lines,"
	"\t\tdefault \"127.0.0.1:" xstr(DEFAULT_MBOX_PORT) "\n"
	"Input to send to the server is taken from stdin in lines of the form context:command\n";

powelld's avatar
powelld committed
27 28
// TO-DO: Accept input file as command line argument

powelld's avatar
powelld committed
29 30
const char *ARG_TYPES="v:V:k:c:s:m:M";

powelld's avatar
powelld committed
31 32
typedef struct ClientConfigST 
{
powelld's avatar
powelld committed
33 34 35 36 37 38 39 40
	FILE *vlog;
	FILE *fIn;
	FILE *fOut;
	SSL *pSSL;
	int numContexts;
	const char *contextDescs[50];
	int numMiddleboxes;
	const char *MiddleboxURLs[50];
powelld's avatar
powelld committed
41 42
	int middleboxReadRights[50][50];		// This is horrible
	int middleboxWriteRights[50][50];	 	// This is horrible and has a silly name
powelld's avatar
powelld committed
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
	const char *serverURL;
	char myKeyFile[1024];
	char myPassword[1024];
	char caFile[1024];
} ClientConfig;

static int
client_ParseArgs(int iArgC, char *papsArgV[], ClientConfig *ptCConf);

void
client_SetDefaults(ClientConfig *ptC)
{
	memset(ptC,0,sizeof(*ptC));
	ptC->fIn=stdin;
	ptC->fOut=stdout;
	strcpy(ptC->caFile,"ca.pem");
	strcpy(ptC->myKeyFile,"client.pem");
	strcpy(ptC->myPassword,"password");
	ptC->serverURL="127.0.0.1:" xstr(DEFAULT_SERVER_PORT);
}

extern char *optarg;
//the next two are available but currently ununsed,
//commented out to prevent compiler complaining
//extern int optind;
//extern int optopt;
static int
client_ParseArgs(int iArgC, char *papsArgV[], ClientConfig *ptCConf)
{
	int iStatus=0;
	char carg=0;

	while( iStatus==0 && (carg=getopt(iArgC,papsArgV,ARG_TYPES)) != -1) {
		switch(carg) {
		case 'v':
		case 'V':
			if(ptCConf->vlog!=NULL) {
				COMMON_LogErrorAndExit(iStatus=INVALID_COMMAND_LINE_ARGS,stderr,"verbose logging specified multiple times\n%s",USAGE);
			}
			if(carg=='v') {
				ptCConf->vlog=stdout;
			} else { /*carg=='V'*/
				ptCConf->vlog=fopen(optarg,"w");
				if(ptCConf->vlog==NULL) {
					COMMON_LogErrorAndExit(iStatus=FILE_NOT_WRITABLE,stderr,"Unable to open log file %s",optarg);
				}
			}
			break;
		case 's':
			/*todo*/
			assert(0);
			break;
		case 'k':
			/*todo*/
			assert(0);
			break;
		case 'c':
			/*todo*/
			assert(0);
			break;
		case 'm':
			/*todo*/
			assert(0);
			break;
		case 'M':
			/*todo*/
			assert(0);
			break;
		default:
			COMMON_LogErrorAndExit(iStatus=INVALID_COMMAND_LINE_ARGS,stderr,"Unrecognised command line option -%c",carg);
			break; /*never reached - keeps compiler happy*/
		}
	}

	return iStatus;
}

ERROR_STATUS
client_CreateContext(SSL_CTX **pptSSLctx,const ClientConfig *ptConf)
{
	ERROR_STATUS iStatus;
	iStatus=COMMON_InitializeSSLCtx(pptSSLctx,
			ptConf->myKeyFile, ptConf->myPassword,
			ptConf->caFile,
			ID_CLIENT);
	return iStatus;

}

ERROR_STATUS
client_Connect(SSL_CTX *ptSSLctx, ClientConfig *ptConf)
{
	ERROR_STATUS iStatus=SUCCESS;
	int i,j,p;
	BIO *ptSBio;

	/*step 0 - create SSL structure*/
	/*the SSL_CTX already has out keys set up*/
	ptConf->pSSL=SSL_new(ptSSLctx);
	/*todo - check for NULL return*/
	assert(ptConf->pSSL!=NULL);

	/*step 1 - create the contexts*/
	iStatus=COMMON_InitMulticontextSet(ptConf->pSSL);
	assert(iStatus==SUCCESS);
powelld's avatar
powelld committed
148 149 150 151
	
	if(ptConf->numContexts==0) 
	{
		DEBUG_PRINT("[CLIENT DEBUG] No contexts specified, adding default\n");
powelld's avatar
powelld committed
152
		iStatus=COMMON_AppendContext(ptConf->pSSL,"default");
powelld's avatar
powelld committed
153 154 155 156 157
		assert(iStatus==SUCCESS);
	} 
	else 
	{
		DEBUG_PRINT("[CLIENT DEBUG] Appending %d context\n", ptConf->numContexts);
powelld's avatar
powelld committed
158
		/*Iterate through the context descriptions and create each one*/
powelld's avatar
powelld committed
159 160 161
		for(i=0;i!=ptConf->numContexts && iStatus==SUCCESS;i++) 
		{
			DEBUG_PRINT("    [CLIENT DEBUG] Appending context %s\n", ptConf->contextDescs[i]);
powelld's avatar
powelld committed
162
			iStatus=COMMON_AppendContext(ptConf->pSSL,ptConf->contextDescs[i]);
powelld's avatar
powelld committed
163
			assert(iStatus==SUCCESS);
powelld's avatar
powelld committed
164 165 166
		}

	}
powelld's avatar
powelld committed
167 168
	if(iStatus!=SUCCESS) 
	{
powelld's avatar
powelld committed
169 170 171 172 173 174 175 176 177
		/*TODO*/
		assert(0);
	}

	/*step 2 - create the middlebox list*/
	iStatus=COMMON_InitProxySet(ptConf->pSSL);
	assert(iStatus==SUCCESS);
	/*step 2.0? - do we need to insert client as middlebox 0? - TODO confirm*/
	/*step 2.1 - iterate through middlebox list */
powelld's avatar
powelld committed
178 179 180 181
	DEBUG_PRINT("[CLIENT DEBUG] Appending %d middleboxes\n", ptConf->numMiddleboxes );
	for(i=0;i!=ptConf->numMiddleboxes;i++) 
	{
		DEBUG_PRINT("    [CLIENT DEBUG] Appending middlbox %d (%s)\n", i, ptConf->MiddleboxURLs[i]);
powelld's avatar
powelld committed
182 183 184
		iStatus=COMMON_AppendProxy(ptConf->pSSL,ptConf->MiddleboxURLs[i]);
	}
	/*step 2.2 - add server url*/
powelld's avatar
powelld committed
185 186

	DEBUG_PRINT("[CLIENT DEBUG] Setting server URL { %s }\n", ptConf->serverURL);
powelld's avatar
powelld committed
187
	iStatus=COMMON_SetServer(ptConf->pSSL,ptConf->serverURL);
powelld's avatar
powelld committed
188

powelld's avatar
powelld committed
189 190 191
	DEBUG_PRINT("[CLIENT DEBUG] Setting middlebox access permissions\n");
	for(j=0;j!=ptConf->numContexts;j++) 
	{
powelld's avatar
powelld committed
192 193
		/*grant client if included*/
		/*grant server*/
powelld's avatar
powelld committed
194 195 196 197 198 199
		DEBUG_PRINT("    [CLIENT DEBUG] Setting permissions for slice %d (%s)\n", ptConf->pSSL->slices[j]->slice_id,ptConf->pSSL->slices[j]->purpose);
		//DEBUG_PRINT("        [CLIENT DEBUG] Setting full permissions for server (%d)\n", ptConf->numMiddleboxes-1);
		//iStatus=COMMON_SetProxyAccessPermissionByID(ptConf->pSSL,ptConf->pSSL->slices[j]->slice_id, ptConf->numMiddleboxes-1,
		//		1,1);
		for(i=0;i!=ptConf->numMiddleboxes/*-1*/;i++) 
		{ /*change to i=1 if client included*/
powelld's avatar
powelld committed
200 201
			char *sMBoxUrl=ptConf->pSSL->proxies[i]->address;
			char *sPort=strchr(sMBoxUrl,':');
powelld's avatar
powelld committed
202 203
			int writePermission = ptConf->middleboxWriteRights[i][j];
			int readPermission = ptConf->middleboxReadRights[i][j];
powelld's avatar
powelld committed
204 205 206
			assert(sPort);
			sPort++;
			int iPort=atoi(sPort);
powelld's avatar
powelld committed
207
			DEBUG_PRINT("        [CLIENT DEBUG] Setting permissions for middlebox %d (%s) R = %d W = %d\n", i, sMBoxUrl, readPermission, writePermission);
powelld's avatar
powelld committed
208
			iStatus=COMMON_SetProxyAccessPermissionByID(ptConf->pSSL,ptConf->pSSL->slices[j]->slice_id, i,
powelld's avatar
powelld committed
209
					readPermission, writePermission);
powelld's avatar
powelld committed
210 211 212
		}
	}

powelld's avatar
powelld committed
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
	#ifdef DEBUG
	printf ("----------------------------\n");
	for (int q = 0; q < ptConf->pSSL->proxies_len; q++)
	{
		printf ("Proxy %d: \n", q);
		printf ("  WriteSliceIDs: \n");
		for (int p = 0; p < ptConf->pSSL->proxies[0]->write_slice_ids_len; p++)
		{
			printf ("     [%d]: %d\n", p, ptConf->pSSL->proxies[0]->write_slice_ids[p]);
		}
		printf ("  ReadSliceISs: \n");
		for (int p = 0; p < ptConf->pSSL->proxies[0]->read_slice_ids_len; p++)
		{
			printf ("     [%d]: %d\n", p, ptConf->pSSL->proxies[0]->read_slice_ids[p]);
		}
	}
	printf ("----------------------------\n");
	#endif

powelld's avatar
powelld committed
232 233 234 235 236 237 238
	/*step 4? - do we need to create a socket to first middlebox?*/
	// TCP Connect
	char* sAddress = (char*)malloc(strlen(ptConf->pSSL->proxies[0]->address) + 1); // Large enough for string+\0
	memcpy(sAddress, ptConf->pSSL->proxies[0]->address, strlen(ptConf->pSSL->proxies[0]->address) + 1);
	char *sHost = strtok(sAddress, ":");
	int iPort = atoi(strtok(NULL, ":"));
	int iSock;
powelld's avatar
powelld committed
239
	DEBUG_PRINT ("[CLIENT DEBUG] Connecting to %s\n", sHost);
powelld's avatar
powelld committed
240 241 242 243 244 245 246 247 248 249 250 251 252 253
	COMMON_TcpConnect(&iSock, sHost, iPort);
	// Connect TCP socket to SSL socket
	ptSBio = BIO_new_socket(iSock, BIO_NOCLOSE);
    SSL_set_bio(ptConf->pSSL, ptSBio, ptSBio);

	/*step 5 - call the connect method*/
	/*SPP connect calls this method but also adds some checks,
	 * in particular it checks that there is at least one context (fine)
	 * but also checks that there is at least one proxy (which seems
	 * unnecassary but the server is included so there must be one)
	 */
	if (SSL_connect(ptConf->pSSL) <= 0) {
		iStatus=NETWORK_CONNECT_FAIL;
	}
powelld's avatar
powelld committed
254 255 256 257 258 259 260 261 262 263 264

	X509* client_cert = SSL_get_certificate(ptConf->pSSL);
        printf ("[CLIENT] Client certificate:\n");
        COMMON_PrintCertificateDetails(client_cert);
        X509_free(client_cert);

        X509* server_cert = SSL_get_peer_certificate(ptConf->pSSL);
        printf ("[CLIENT] Server certificate:\n");
        COMMON_PrintCertificateDetails(server_cert);
        X509_free(server_cert);
	
powelld's avatar
powelld committed
265
	return SUCCESS;
powelld's avatar
powelld committed
266
	// MC: Do we really want to return SUCCESS regardless of the value of iStatus?
powelld's avatar
powelld committed
267 268
}

powelld's avatar
powelld committed
269
int intCount = 0;
powelld's avatar
powelld committed
270 271 272 273 274 275 276 277 278 279

struct iobuffer {
	int iUsed;
	union {
		unsigned char aucBuffer[1024];
		char stext[1024];
	};
	char z;/*force null termination of string*/
};

powelld's avatar
powelld committed
280
int main(const int iArgC, char *papsArgV[])
powelld's avatar
powelld committed
281
{
powelld's avatar
powelld committed
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
	DEBUG_PRINT ("[CLIENT DEBUG] Client starting\n");

	ClientConfig tConfig;
	SSL_CTX *ptSSLctx=NULL;
	int iStatus;

	client_SetDefaults(&tConfig);

	char* inputFile = "inputData.json";
	DEBUG_PRINT ("[CLIENT DEBUG] Reading input data from %s\n", inputFile);
	cJSON* json = COMMON_ReadJSONFile(inputFile);
	cJSON* item = NULL;

	char* configStr = cJSON_Print(json);
	DEBUG_PRINT("%s\n", configStr);
	free(configStr);

	// TO DO bounds, null or error checking of any kind at all
	cJSON* contextNames = cJSON_GetObjectItem(json, "contexts");
	int contextCount = 0;
	cJSON_ArrayForEach(item, contextNames)
	{
		tConfig.contextDescs[contextCount] = strdup(item->valuestring);
		contextCount++;
	}
	tConfig.numContexts = contextCount;
	
	
	cJSON* middleboxes = cJSON_GetObjectItem(json, "middleboxes");
	int mboxCount = 0;
	cJSON_ArrayForEach(item, middleboxes)
	{
		tConfig.MiddleboxURLs[mboxCount] = strdup(cJSON_GetObjectItem(item, "url")->valuestring);
		cJSON* readAccessItem = NULL;
		cJSON_ArrayForEach(readAccessItem, cJSON_GetObjectItem(item, "readAccess"))
		{
			tConfig.middleboxReadRights[mboxCount][readAccessItem->valueint] = 1;
		}
		cJSON* writeAccessItem = NULL;
		cJSON_ArrayForEach(writeAccessItem, cJSON_GetObjectItem(item, "writeAccess"))
		{
			tConfig.middleboxWriteRights[mboxCount][writeAccessItem->valueint] = 1;
powelld's avatar
powelld committed
324
		}
powelld's avatar
powelld committed
325
		mboxCount++;
powelld's avatar
powelld committed
326
	}
powelld's avatar
powelld committed
327 328 329 330
	tConfig.numMiddleboxes = mboxCount;
	
	iStatus=client_ParseArgs(iArgC,papsArgV, &tConfig);
	COMMON_CheckLogErrorAndExit(iStatus,stderr,"%s\n",USAGE);
powelld's avatar
powelld committed
331

powelld's avatar
powelld committed
332 333 334 335
	iStatus=client_CreateContext(&ptSSLctx,&tConfig);
	iStatus=client_Connect(ptSSLctx,&tConfig);

	DEBUG_PRINT("[CLIENT DEBUG] Connected\n");
powelld's avatar
powelld committed
336 337 338

	struct iobuffer tInBuff;

powelld's avatar
powelld committed
339 340 341 342 343 344 345 346 347 348
	cJSON* slicedData = cJSON_GetObjectItem(json, "slicedData");
	cJSON_ArrayForEach(item, slicedData)
    {
        cJSON *slice = cJSON_GetObjectItem(item, "slice");
        cJSON *text = cJSON_GetObjectItem(item, "data");
		if (slice->valueint >= tConfig.numContexts)
		{
			printf("[CLIENT ERROR] Data specified for slice id %d, which is out of bounds\n", slice->valueint);
			exit(-1);
		}
powelld's avatar
powelld committed
349

powelld's avatar
powelld committed
350 351 352 353 354 355 356 357 358 359
		tConfig.pSSL->write_slice=SPP_get_slice_by_id(tConfig.pSSL,tConfig.pSSL->slices[slice->valueint]->slice_id);
		if (tConfig.pSSL->write_slice == NULL)
		{
			printf("[CLIENT ERROR] Data specified for slice id %d which is not found\n", slice->valueint);
			exit(-1);
		}
		int iBytesSent=SSL_write(tConfig.pSSL, text->valuestring, strlen(text->valuestring));
		printf ("[CLIENT DEBUG] Sent %d bytes { %s }\n", iBytesSent, text->valuestring);				
	}
	cJSON_Delete(json);
powelld's avatar
powelld committed
360 361


powelld's avatar
powelld committed
362
	int iBytesRead = 1;
powelld's avatar
powelld committed
363

powelld's avatar
powelld committed
364 365
	cJSON* recvData = cJSON_CreateObject();
	cJSON* sliceDataArray = cJSON_AddArrayToObject(recvData, "slices");
powelld's avatar
powelld committed
366

powelld's avatar
powelld committed
367 368 369
	SPP_SLICE* slice;
	SPP_CTX* ctx;
	int slicesSeen = 0;
powelld's avatar
powelld committed
370

powelld's avatar
powelld committed
371 372 373 374 375
	while ((iBytesRead > 0) && (slicesSeen < tConfig.numContexts))
	{
		DEBUG_PRINT ("[CLIENT DEBUG] Waiting for response\n");
		//iBytesRead = SSL_read(tConfig.pSSL,tInBuff.aucBuffer,sizeof(tInBuff.aucBuffer));
		iBytesRead = SPP_read_record(tConfig.pSSL, tInBuff.aucBuffer, sizeof(tInBuff.aucBuffer), &slice, &ctx);
powelld's avatar
powelld committed
376

powelld's avatar
powelld committed
377 378 379 380 381 382 383 384 385 386 387 388 389
		if (iBytesRead > 0)
		{
			cJSON* jslice = cJSON_CreateObject();
			cJSON_AddNumberToObject(jslice, "slice", slice->slice_id );
			cJSON_AddStringToObject(jslice, "data", COMMON_MakeNullTerminatedCopy(tInBuff.aucBuffer, iBytesRead));
			cJSON_AddItemToArray(sliceDataArray, jslice);
			DEBUG_PRINT ("[CLIENT DEBUG] Recv %d bytes [(%s)]\n", iBytesRead, tInBuff.aucBuffer);
		}
		else
		{
			DEBUG_PRINT ("[CLIENT DEBUG] SPP_read_record return zero bytes\n");
			break;
		}
powelld's avatar
powelld committed
390

powelld's avatar
powelld committed
391 392
		slicesSeen++;
	}
powelld's avatar
powelld committed
393

powelld's avatar
powelld committed
394 395 396
	char* filename = COMMON_WriteJSONFile(recvData, "Client");
	DEBUG_PRINT("[CLIENT DEBUG] Data written to %s\n", filename);
	free(filename);
powelld's avatar
powelld committed
397

powelld's avatar
powelld committed
398 399 400
	char* recvDataString = cJSON_Print(recvData);
	printf("[CLIENT] Received\n%s\n", recvDataString);
	free(recvDataString);
powelld's avatar
powelld committed
401

powelld's avatar
powelld committed
402
	cJSON_Delete(recvData);
powelld's avatar
powelld committed
403

powelld's avatar
powelld committed
404
	DEBUG_PRINT ("[CLIENT DEBUG] Exiting\n");
powelld's avatar
powelld committed
405 406
	return iStatus;
}