-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.c
More file actions
468 lines (425 loc) · 13.8 KB
/
Copy pathproxy.c
File metadata and controls
468 lines (425 loc) · 13.8 KB
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
/**
* proxy.c
*
* Acts as a server proxy
* Handles multiple requests by creating threads. All processes are concurrently
* handled. Server constantly searches for requests, and does not shut down
* after processing requests. Proxy follows the HTTP/1.0 protocol, and
* translates all HTTP/1.1 requests to HTTP/1.0 requests. All additional headers
* given to the proxy are forwarded to the server. Connection based errors will
* cause the proxy to end the connection. Function based errors notify the
* server and attempt to continue. Any errors provided by the server are
* forwarded back to the client.
*
*/
#include "csapp.h"
#include "http_parser.h"
#include <assert.h>
#include <ctype.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#include <pthread.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/types.h>
/*
* Debug macros, which can be enabled by adding -DDEBUG in the Makefile
* Use these if you find them useful, or delete them if not
*/
#ifdef DEBUG
#define dbg_assert(...) assert(__VA_ARGS__)
#define dbg_printf(...) fprintf(stderr, __VA_ARGS__)
#else
#define dbg_assert(...)
#define dbg_printf(...)
#endif
/** @brief bool for verbose mode */
volatile bool verbose = false;
/** @brief the size of the http portion of a request */
#define HTTPSIZE 8;
/*
* String to use for the User-Agent header.
* Don't forget to terminate with \r\n
*/
static const char *header_user_agent = "Mozilla/5.0"
" (X11; Linux x86_64; rv:3.10.0)"
" Gecko/20250408 Firefox/63.0.1";
/*
* clienterror - returns an error message to the client
*/
void clienterror(int fd, const char *errnum, const char *shortmsg,
const char *longmsg) {
char buf[MAXLINE];
char body[MAXBUF];
size_t buflen;
size_t bodylen;
/* Build the HTTP response body */
bodylen = snprintf(body, MAXBUF,
"<!DOCTYPE html>\r\n"
"<html>\r\n"
"<head><title>Tiny Error</title></head>\r\n"
"<body bgcolor=\"ffffff\">\r\n"
"<h1>%s: %s</h1>\r\n"
"<p>%s</p>\r\n"
"<hr /><em>The Tiny Web server</em>\r\n"
"</body></html>\r\n",
errnum, shortmsg, longmsg);
if (bodylen >= MAXBUF) {
return; // Overflow!
}
/* Build the HTTP response headers */
buflen = snprintf(buf, MAXLINE,
"HTTP/1.0 %s %s\r\n"
"Content-Type: text/html\r\n"
"Content-Length: %zu\r\n\r\n",
errnum, shortmsg, bodylen);
if (buflen >= MAXLINE) {
return; // Overflow!
}
/* Write the headers */
if (rio_writen(fd, buf, buflen) < 0) {
fprintf(stderr, "Error writing error response headers to client\n");
return;
}
/* Write the body */
if (rio_writen(fd, body, bodylen) < 0) {
fprintf(stderr, "Error writing error response body to client\n");
return;
}
}
void sigpipe_handler(int sig) {
if (verbose) {
sio_printf("SIGPIPE: %d caught by Handler\n", sig);
}
}
/**
* @brief Prints out the request parsed by parser
*
* Mostly used for debug purposes
*
* @param[in] parser The parser object
*/
void displayParseLine(parser_t *parser) {
const char *parseVal;
for (int i = 0; i < 7; i++) {
if (parser_retrieve(parser, i, &parseVal) < 0) {
sio_printf("Error parsing request\n");
}
if (verbose) {
sio_printf("Got request: %s\n", parseVal);
}
}
}
/**
* @brief connects to the server using the latest line parsed by parser
*
* @param[in] parser The parser that parsed the commnand
* @param[out] hostHeader Pointer to location where a host header can be stored
* @return file descriptor of connection
*/
int connectServer(parser_t *parser, char *hostHeader) {
const char *host, *port, buf[MAXLINE];
parser_retrieve(parser, HOST, &host);
parser_retrieve(parser, PORT, &port);
// Attempt connection
int serverfd = open_clientfd(host, port);
if (serverfd == -1) {
if (verbose) {
sio_printf("Server connection %s:%s not established\n", host, port);
}
return -1;
} else if (serverfd == -2) {
if (verbose) {
sio_printf("%s:%s: %s\n", host, port, strerror(errno));
}
return -1;
}
if (verbose) {
sio_printf("Successfully connected to %s at port %s\n", host, port);
}
sprintf(hostHeader, "Host: %s:%s\r\n", host, port);
return serverfd;
}
/**
* @brief gets the http version.
* This should always return the same HTTP version
*
* @return the http request version that the proxy handles
*/
char *gethttp(void) {
// Buffer is large enough to cover the string
char buf[8];
char *http;
http = "HTTP/1.0";
return http;
}
/**
* @brief reads and parses the command line
*
* Handles any errors that might occur
*
* @param[out] line Mainly for debug purposes, stores the request line
* @param[out] parseState Stores the parse state after parsing
* @param[in] parser An initialized parser to be used for parsing
* @param[in] fd The file descriptor to be parsed
* @return number of request characters parsed on success, -1 on file reading
* error, -2 on parsing error
*/
int readParse(char *line, parser_state *parseState, parser_t *parser, int fd) {
// Initialize rio
rio_t rio;
rio_readinitb(&rio, fd);
// Parse the request line
ssize_t read = rio_readlineb(&rio, line, MAXLINE);
if (read == 0) {
return 0;
} else if (read == -1) {
if (verbose) {
sio_printf("Error reading request\n");
}
return -1;
} else {
*parseState = parser_parse_line(parser, line);
if (*parseState == ERROR) {
if (verbose) {
sio_printf("Error while parsing\n");
}
return -2;
}
}
// Parse the other headers
char tmpline[PARSER_MAXLINE] = "";
if (rio_readlineb(&rio, &tmpline, PARSER_MAXLINE) < 0) {
fprintf(stderr, "Failed to read client headers\n");
}
while (strcmp(tmpline, "\r\n")) {
if (parser_parse_line(parser, tmpline) == ERROR) {
fprintf(stderr, "Failed to parse client headers\n");
}
if (rio_readlineb(&rio, &tmpline, PARSER_MAXLINE) < 0) {
fprintf(stderr, "Failed to read client headers\n");
}
}
return read;
}
/**
* @brief Given a request, forwards it to the host server
*
* @param[in] parser The parser that parsed the request
* @param[in] count The number of words parsed, used for smaller buffer sizes
* @param[in] clientfd The file descriptor of the client
* @return 0 on success, -1 on failure
*/
int forward(parser_t *parser, ssize_t count, int clientfd) {
// Create the connection to the server
int serverfd;
char hostHeader[PARSER_MAXLINE];
if ((serverfd = connectServer(parser, hostHeader)) < 0) {
return -1;
}
// Declare variables for request string
const char *cmd, *pathname, *httpval;
httpval = gethttp();
parser_retrieve(parser, METHOD, &cmd);
parser_retrieve(parser, PATH, &pathname);
// Req is a string containing the request line
// Add 5 for spaces, \n, \r
size_t reqsize = strlen(cmd) + strlen(pathname) + strlen(httpval) + 4;
char req[reqsize];
snprintf(req, MAXLINE, "%s %s %s\r\n", cmd, pathname, httpval);
// User-Agent header
// Add 16 for additional characters
size_t userAgentSize = strlen(header_user_agent) + 16;
char userAgent[userAgentSize];
sprintf(userAgent, "User-Agent: %s\r\n", header_user_agent);
// Connection header
char *connection = "Connection: close\r\n";
// Proxy connection header
char *proxyConnection = "Proxy-Connection: close\r\n";
// Forwarding messages
char fwd[PARSER_MAXLINE] = "";
header_t *header = parser_lookup_header(parser, "Request-ID");
while (header != NULL) {
char join[PARSER_MAXLINE];
sprintf(join, "%s: %s\r\n", header->name, header->value);
strcat(fwd, join);
header = parser_retrieve_next_header(parser);
}
// Construct the full message
// Plus 2 for \r\n
size_t msglen = strlen(req) + strlen(hostHeader) + strlen(userAgent) +
strlen(connection) + strlen(proxyConnection) + strlen(fwd) +
2;
char msg[msglen];
sprintf(msg, "%s%s%s%s%s%s\r\n", req, hostHeader, userAgent, connection,
proxyConnection, fwd);
if (verbose) {
sio_printf("msg:\n%s\n", msg);
}
// Send the message
if (rio_writen(serverfd, (void *)msg, strlen(msg)) < 0) {
fprintf(stderr, "Failed to write message for client\n");
}
if (verbose) {
sio_printf("Message sent\n");
}
// Read the response
bool continueRead = true;
while (continueRead) {
size_t readlen;
char response[MAXLINE];
ssize_t read = rio_readn(serverfd, response, MAXLINE);
if (read < 0) {
fprintf(stderr, "Failed to read server response\n");
}
// Check if the entire response has been parsed
if (read < MAXLINE) {
continueRead = false;
readlen = read;
if (verbose) {
sio_printf("Sending response to client\n");
}
} else {
readlen = MAXLINE;
}
// Write the parsed data
if (rio_writen(clientfd, response, readlen) < 0) {
fprintf(stderr, "Failed to write message for client\n");
}
}
if (verbose) {
sio_printf("Response Sent, closing connection\n");
}
// Close the connection with the server
close(serverfd);
return 0;
}
/**
* @brief handles a single request
*
* Creates a new thread to handle the request
* @param[in] vargp pointer storing the fd of the client making the request
* @return NULL when process terminates
*/
void *thread(void *vargp) {
int clientfd = *((int *)vargp);
bool connected = true;
// Setup parser
parser_t *parser = parser_new();
// Hold the connection
do {
// Create the value to store parser data
// Create the buffer
char line[MAXLINE];
parser_state parseState;
int count = readParse(line, &parseState, parser, clientfd);
if (count == 0) {
connected = false;
} else if (count == -1 || count == -2) {
clienterror(clientfd, "400", "Bad Request",
"Did not recieve a proper request");
// Reset parse
parser_free(parser);
parser = parser_new();
// Wait for another request when there is an error
} else {
if (parseState == REQUEST) {
const char *cmd;
if (parser_retrieve(parser, METHOD, &cmd) < 0) {
fprintf(stderr, "Failed to read cmd\n");
}
if (strcmp(cmd, "POST") == 0) {
clienterror(clientfd, "501", "Not Implemented",
"Proxy does not accept POST requests");
}
if (verbose) {
displayParseLine(parser);
}
// Forward the messsage to the server
int status = forward(parser, count, clientfd);
// Reset parser (on error or success either way)
parser_free(parser);
parser = parser_new();
if (status == -1) {
connected = false;
}
connected = false;
} else {
// Did not get a request
clienterror(clientfd, "400", "Bad Request",
"Did not recieve a proper request");
parser_free(parser);
parser = parser_new();
}
}
} while (connected);
// Cleanup pointers
parser_free(parser);
close(clientfd);
pthread_detach(pthread_self());
return NULL;
}
int main(int argc, char **argv) {
// Install the handler
Signal(SIGPIPE, &sigpipe_handler);
if (verbose) {
sio_printf("Signal handler installed\n");
}
// Parse the command line
char *port;
if (argv[1] == NULL) {
argv[1] = "8000";
}
port = argv[1];
// Begin listening for connections
int listenfd = open_listenfd(port);
if (listenfd < 0) {
sio_printf("Failed to connect to port %s\n", argv[1]);
exit(0);
}
if (verbose) {
sio_printf("Created port at %s\n", port);
}
// Initialize variables
struct sockaddr clientaddr;
socklen_t clientaddr_len;
pthread_t tid;
int *clientfd;
// Keep the server on
do {
clientaddr_len = sizeof(clientaddr);
clientfd = malloc(sizeof(int));
if (clientfd == NULL) {
// Try malloc again
} else {
// Wait for connection
*clientfd = accept(listenfd, &clientaddr, &clientaddr_len);
if (*clientfd < 0) {
sio_printf("Failed to accept connection: %s\n",
strerror(errno));
} else {
if (verbose) {
sio_printf("Accepted client\n");
}
}
// Create thread to handle the request
int err;
if ((err = pthread_create(&tid, NULL, thread, clientfd)) != 0) {
sio_printf("Failed to create thread: %d\n", err);
close(listenfd);
return 0;
}
}
} while (true);
// Cleanup fd
close(listenfd);
return 0;
}