forked from cholojuanito/http-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.c
509 lines (424 loc) · 15.5 KB
/
proxy.c
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
/**
* Tanner Davis - BYU CS 324 Winter 2019
*
*/
#include <stdio.h>
#include "cache.c"
#include "csapp.h"
#include "sbuf.c"
/* Recommended max cache and object contentLengths */
// #define MAX_CACHE_SIZE 1049000
// #define MAX_OBJECT_SIZE 102400
#define NUM_THREADS 20
#define QUEUE_SIZE 24
#define MIN_PORT_NUMBER 1024
#define MAX_PORT_NUMBER 65536
#define CACHE_OFF "off"
#define FORWARD_SLASH "/"
#define HTTP_DELIM "://"
#define END_STR '\0'
#define DEFAULT_HTTP_PORT "80"
#define GET "GET"
#define END_HTTP "\r\n"
#define HOST_KEY "Host:"
#define USER_AGENT_KEY "User-Agent:"
#define ACCEPT_KEY "Accept:"
#define ACCEPT_ENCODE_KEY "Accept-Encoding:"
#define CONNECTION_KEY "Connection:"
#define PROXY_KEY "Proxy Connection:"
#define COOKIE_KEY "Cookie:"
#define CONTENT_LEN_STR_1 "Content-Length"
//#define CONTENT_LEN_KEY_1 "Content-Length:"
#define CONTENT_LEN_STR_2 "Content-length"
//#define CONTENT_LEN_KEY_2 "Content-length:"
// Headers
static const char* userAgentHeadr = "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:10.0.3) Gecko/20120305 Firefox/10.0.3\r\n";
static const char* connectionHeadr = "Connection: close\r\n";
static const char* proxyConnectionHeadr = "Proxy-Connection: close\r\n";
static const char* httpVersionHeadr = "HTTP/1.0\r\n";
static const char* acceptStr = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n";
static const char* acceptEncoding = "Accept-Encoding: gzip, deflate\r\n";
static const char* dnsFailStr = "HTTP/1.0 400 \
Bad Request\r\nServer: CS324-Proxy\r\nContent-Length: 0\r\nConnection: \
close\r\nContent-Type: text/html\r\n\r\n";
/* <html><head></head><body><p>\
Couldn't connect with this server because of DNS issues.</p></body></html> */
static const char* connectionFailStr = "HTTP/1.0 400 \
Bad Request\r\nServer: CS324-Proxy\r\nContent-Length: 0\r\nConnection: \
close\r\nContent-Type: text/html\r\n\r\n";
/* <html><head></head><body><p>\
Couldn't connect with this server.</p></body></html> */
// Function declarations
void usage();
void loggerThread(void* arg);
void proxyThread(void* arg);
int readRequest(char* str, int clientFd, char* host, char* port, char* cacheKey, char* query);
int forwardToServer(char* host, char* port, int* serverFd, char* requestStr);
int forwardToClient(int clientFd, char* response, unsigned int len);
int readAndForwardToClient(int serverFd, int clientFd, char* cacheKey, char* response);
int append(char* response, char* str, unsigned int addSize, unsigned int* prevSize);
int parseRequest(char* buf, char* method, char* protocol, char* version, char* hostAndPort, char* query);
void getHostAndPort(char* hostAndPort, char* host, char* port);
void closeFds(int* clientFd, int* serverFd);
// END function declarations
sbuf_t connQueue; // Global queue for connections
sbuflog_t logQueue; // Global queue for logs
cacheList* cache; // Here be the cache
volatile sig_atomic_t exitRequested = 0; // SIGINT flag
int main(int argc, char** argv) {
char* port;
int useCache = 1;
struct sockaddr_in clientAddr;
socklen_t clientLength = sizeof(struct sockaddr_in);
pthread_t tid[NUM_THREADS], tidLogger;
int listenFd;
int connFd;
// Incorrect number of arguments
if (argc < 2) {
usage(argv[0]);
}
// Decide if the cache should be used
if (argc >= 3) {
useCache = (strcmp(argv[2], CACHE_OFF));
}
// Make sure the port is valid
port = argv[1];
int portNum = atoi(port);
if (portNum <= MIN_PORT_NUMBER || portNum >= MAX_PORT_NUMBER) {
printf("Invalid port number: %d. Should be between 1025 and 65535\n", portNum);
exit(1);
}
// Initialize cache
cache = NULL;
if (useCache) {
printf("Using cache\n");
cache = initCache();
}
else {
printf("Not using cache\n");
}
// Ignore SIGPIPE
Signal(SIGPIPE, SIG_IGN);
// Spawn the logger thread
sbuflog_init(&logQueue, QUEUE_SIZE);
Pthread_create(&tidLogger, NULL, (void*)loggerThread, NULL);
listenFd = Open_listenfd(port);
sbuf_init(&connQueue, QUEUE_SIZE);
// Spawn the client threads
for (int i = 0; i < NUM_THREADS; i++) {
Pthread_create(&tid[i], NULL, (void*) proxyThread, NULL);
}
// Add new connections to the queue
while (1) {
connFd = Accept(listenFd, (SA *) &clientAddr, (socklen_t *) &clientLength);
sbuf_insert(&connQueue, connFd);
}
// Reap threads
for (int i = 0; i < NUM_THREADS; i++) {
Pthread_join(tid[i], NULL);
}
return 0;
}
void usage(char *str) {
printf("\tusage: %s <port> [use cache]\n", str);
printf("\t\tport: the port this program will connect to\n");
printf("\t\tport: must be a number between 1025 and 65535\n");
printf("\t\tcache: 'off' to turn off caching\n");
printf("\t\tcache: 'on' to turn on caching\n");
printf("\t\tcache is 'on' by default\n");
exit(1);
}
void loggerThread(void* arg) {
while (exitRequested == 0) {
FILE* logFile = fopen("requests.txt", "a+");
if (logFile == NULL) {
fprintf(stderr, "error opening log file");
continue;
}
char* buf = sbuflog_remove(&logQueue);
if (fwrite(buf, strlen(buf), 1, logFile) <= 0) {
fprintf(stderr, "error writing to log file!\n");
}
fclose(logFile);
}
}
void proxyThread(void* arg) {
//printf("pid: %u\n", (unsigned int) pthread_self());
while (exitRequested == 0) {
int clientFd = sbuf_remove(&connQueue); // Take care of the next connection
int serverFd = -1;
char buf[MAXBUF], requestStr[MAXBUF], host[MAXBUF], port[MAXBUF], query[MAXBUF];
char cacheKey[MAXBUF], response[MAX_OBJECT_SIZE];
unsigned int length;
// Read the client request
int readVal = readRequest(requestStr, clientFd, host, port, cacheKey, query);
//printf("Read data from %s:%s\n",host,port);
fflush(stdout);
if (!readVal) {
if (readNodeContent(cache, cacheKey, response, &length) == 0) {
printf("Found in cache!\n");
int forwardVal = forwardToClient(clientFd, response, length);
if (forwardVal == -1) {
fprintf(stderr, "Forward CACHE response to client error\n");
}
//Close(clientFd);
}
else {
// Forward request to remote sever
int bytesWritten = forwardToServer(host, port, &serverFd, requestStr);
if (bytesWritten == -1) {
fprintf(stderr, "forward response to server error.\n");
strcpy(buf, connectionFailStr);
Rio_writen(clientFd, buf, strlen(connectionFailStr));
}
else if (bytesWritten == -2) {
fprintf(stderr, "forward response to server error (dns look up fail).\n");
strcpy(buf, dnsFailStr);
Rio_writen(clientFd, buf, strlen(dnsFailStr));
}
else {
int forwardVal = readAndForwardToClient(serverFd, clientFd, cacheKey, response);
if (forwardVal == -1)
fprintf(stderr, "forward response to client error\n");
else if (forwardVal == -2)
fprintf(stderr, "save response to cache error\n");
}
}
}
closeFds(&clientFd, &serverFd);
// Break out only on SIGINT
}
return;
}
int readRequest(char* request, int clientFd, char* host, char* port, char* cacheKey, char* query) {
char buf[MAXBUF], method[MAXBUF], protocol[MAXBUF], hostAndPort[MAXBUF], version[MAXBUF];
rio_t rioClient;
Rio_readinitb(&rioClient, clientFd);
if (Rio_readlineb(&rioClient, buf, MAXBUF) == -1) {
return -1;
}
if (parseRequest(buf, method, protocol, version, hostAndPort, query) == -1) {
return -1;
}
getHostAndPort(hostAndPort, host, port);
// Begin copying the request
// GET requests
if (strstr(method, GET)) {
strcpy(request, method);
strcat(request, " ");
strcat(request, query);
strcat(request, " ");
strcat(request, httpVersionHeadr);
// Add Host information if present
if (strlen(host)) {
strcpy(buf, HOST_KEY);
strcat(buf, host);
strcat(buf, ":");
strcat(buf, port);
strcat(buf, END_HTTP);
strcat(request, buf);
}
// Add necessary headers
strcat(request, userAgentHeadr);
strcat(request, acceptStr);
strcat(request, acceptEncoding);
strcat(request, connectionHeadr);
strcat(request, proxyConnectionHeadr);
// Copy any other relavant headers
while(Rio_readlineb(&rioClient, buf, MAXBUF) > 0) {
// End when you see '\r\n'
if (!strcmp(buf, END_HTTP)) {
strcat(request, END_HTTP);
break;
}
// Ignore these headers, we overwrote them
else if (strstr(buf, USER_AGENT_KEY) || strstr(buf, ACCEPT_KEY) || strstr(buf, ACCEPT_ENCODE_KEY)
|| strstr(buf, PROXY_KEY) || strstr(buf, CONNECTION_KEY) || strstr(buf, COOKIE_KEY)
|| strstr(buf, HOST_KEY)) {
continue;
}
else {
strcat(request, buf);
}
}
// Add caching information here
strcpy(cacheKey, host);
strcat(cacheKey, ":");
strcat(cacheKey, port);
strcat(cacheKey, query);
// Log it as well
char* httpPrefix = "http://";
char* logBuf = Malloc(sizeof(char) * (strlen(cacheKey) + strlen(httpPrefix) + strlen("\n")));
strcpy(logBuf, httpPrefix);
strcat(logBuf, host);
strcat(logBuf, ":");
strcat(logBuf, port);
strcat(logBuf, query);
strcat(logBuf, "\n");
sbuflog_insert(&logQueue, logBuf);
//fprintf(stderr, "NEW REQUEST:\n %s", request);
return 0;
}
return -1;
}
int parseRequest(char* buf, char* method, char* protocol, char* version, char* hostAndPort, char* query) {
char url[MAXBUF];
// Make sure it is a valid request
if((!strstr(buf, FORWARD_SLASH)) || !strlen(buf)) {
return -1;
}
// Extract the method, url and http version
sscanf(buf,"%s %s %s", method, url, version);
// Prepend the '/' to the query
strcpy(query, FORWARD_SLASH);
if (strstr(url, HTTP_DELIM)) {
// Extract the http protocol, host:port and query
sscanf(url, "%[^:]://%[^/]%s", protocol, hostAndPort, query);
}
else {
// No protocol mentioned
sscanf(url, "%[^/]%s", hostAndPort, query);
}
return 0;
}
int forwardToServer(char* host, char* port, int* serverFd, char* requestStr) {
*serverFd = Open_clientfd(host, port);
if (*serverFd < 0) {
// Something went wrong with connecting to server
if (*serverFd == -1) {
return -1;
}
// DNS lookup failed
else {
return -2;
}
}
int numBytes = Rio_writen(*serverFd, requestStr, strlen(requestStr));
if (numBytes == -1) {
return -1;
}
return numBytes;
}
int forwardToClient(int clientFd, char* response, unsigned int len) {
if (Rio_writen(clientFd, response, len) == -1) {
return -1;
}
return 0;
}
int readAndForwardToClient(int serverFd, int clientFd, char* cacheKey, char* response) {
rio_t rioServer;
char buf[MAXBUF];
unsigned int contentLength = 0, cacheSize = 0;
int validReponseLength = 1;
response[0] = END_STR;
Rio_readinitb(&rioServer, serverFd);
do {
int numBytesRead = Rio_readlineb(&rioServer, buf, MAXBUF);
// Read the response from the server line by line
if (numBytesRead == -1) {
return -1;
}
// Append the read bytes to the proxy's response
if (validReponseLength) {
validReponseLength = append(response, buf, strlen(buf), &cacheSize);
}
// Standardize the content length header
if (strstr(buf, CONTENT_LEN_STR_1) || strstr(buf, CONTENT_LEN_STR_2)) {
sscanf(buf, "Content-length: %d", &contentLength);
}
// Write the read bytes to the client
if (Rio_writen(clientFd, buf, strlen(buf)) == -1) {
return -1;
}
} while (strcmp(buf, END_HTTP) != 0 && strlen(buf));
// Write the response body (if any) to the client
unsigned int lengthToWrite = 0;
if (contentLength) {
// If the content length is more than MAXBUF keep writing until it is not
while (contentLength > MAXBUF) {
if ((lengthToWrite = Rio_readnb(&rioServer, buf, MAXBUF)) == -1) {
return -1;
}
// Append to response
if (validReponseLength) {
validReponseLength = append(response, buf, MAXBUF, &cacheSize);
}
// Write to client
if (Rio_writen(clientFd, buf, lengthToWrite) == -1) {
return -1;
}
// Decrease the length of the content left to write
contentLength -= MAXBUF;
}
// Finish writing anything that is leftover from the loop above
// Bascially anything less than MAXBUF
if (contentLength) {
if ((lengthToWrite = Rio_readnb(&rioServer, buf, contentLength)) == -1) {
return -1;
}
if (validReponseLength) {
validReponseLength = append(response, buf, contentLength, &cacheSize);
}
if (Rio_writen(clientFd, buf, lengthToWrite) == -1) {
return -1;
}
}
}
else {
while ((lengthToWrite = Rio_readnb(&rioServer, buf, MAXBUF)) > 0) {
if (validReponseLength) {
validReponseLength = append(response, buf, lengthToWrite, &cacheSize);
}
if (Rio_writen(clientFd, buf, lengthToWrite) == -1) {
return -1;
}
}
}
if (validReponseLength) {
// Add to cache
int addToCacheVal = insertNodeContent(cache, cacheKey, response, cacheSize);
if (addToCacheVal == -1) {
printf("Cache error!\n");
return -2;
}
else if (addToCacheVal == -2) {
printf("Not enough space in cache!\n");
return -2;
}
else {
printf("Added response to cache!\n");
}
}
return 0;
}
void getHostAndPort(char* hostAndPort, char* host, char* port) {
// Split the host and port into "seperate" strings
char* buf = strstr(hostAndPort,":");
if (buf) {
*buf = END_STR;
// Copy the port
strcpy(port, buf + 1);
}
else {
// Give the default port of '80'
strcpy(port, DEFAULT_HTTP_PORT);
}
// Copy the host
strcpy(host, hostAndPort);
}
int append(char* response, char* str, unsigned int addSize, unsigned int* prevSize) {
if(addSize + (*prevSize) > MAX_OBJECT_SIZE) {
return 0;
}
memcpy(response + (*prevSize), str, addSize);
*prevSize += addSize;
return 1;
}
void closeFds(int* clientFd, int* serverFd) {
if(clientFd && *clientFd >= 0) {
Close(*clientFd);
}
if(serverFd && *serverFd >= 0) {
Close(*serverFd);
}
}