]> ruderich.org/simon Gitweb - tlsproxy/tlsproxy.git/blob - src/tlsproxy.c
src/tlsproxy.c: Fix wrong timeout for poll(), -1 is infinity.
[tlsproxy/tlsproxy.git] / src / tlsproxy.c
1 /*
2  * tlsproxy is a transparent TLS proxy for HTTPS connections.
3  *
4  * Copyright (C) 2011  Simon Ruderich
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <stdlib.h>
21 #include <stdio.h>
22 /* socket(), bind(), accept(), listen() */
23 #include <sys/types.h>
24 #include <sys/socket.h>
25 /* close() */
26 #include <unistd.h>
27 /* htons() */
28 #include <arpa/inet.h>
29 /* getaddrinfo() */
30 #include <netdb.h>
31 /* strncmp() */
32 #include <string.h>
33 /* sigaction() */
34 #include <signal.h>
35 /* poll() */
36 #include <poll.h>
37
38 #include <config.h>
39
40
41 /* Maximum line of the request line. Longer request lines are aborted with an
42  * error. The standard doesn't specify a maximum line length but this should
43  * be a good limit to make processing simpler. */
44 #define MAX_REQUEST_LINE 4096
45
46
47 /* Server should shut down. Set by SIGINT handler. */
48 static volatile int done;
49
50 /* Proxy hostname and port if specified on the command line. */
51 static char *use_proxy_host;
52 static char *use_proxy_port;
53
54
55 static void sigint_handler(int signal);
56
57 static void parse_arguments(int argc, char **argv);
58 static void print_usage(const char *argv);
59
60 static void handle_connection(int socket);
61 static int read_http_request(FILE *client_fd, char *request, size_t length);
62 static void send_close_bad_request(FILE *client_fd);
63 static void send_close_forwarding_failure(FILE *client_fd);
64
65 static void transfer_data(int client, int server);
66 static int read_from_write_to(int from, int to);
67
68 static int connect_to_host(const char *hostname, const char *port);
69
70 static int parse_request(const char *buffer, char *host, char *port,
71                                              int *version_minor);
72
73
74 int main(int argc, char **argv) {
75     int port;
76     int client_socket, server_socket;
77     struct sockaddr_in6 server_in;
78
79     struct sigaction action;
80
81     parse_arguments(argc, argv);
82
83     port = atoi(argv[argc - 1]);
84     if (0 >= port || 0xffff < port) {
85         print_usage(argv[0]);
86         fprintf(stderr, "\ninvalid port");
87         return EXIT_FAILURE;
88     }
89
90     /* Setup our SIGINT signal handler which allows a "normal" termination of
91      * the server. */
92     sigemptyset(&action.sa_mask);
93     action.sa_handler = sigint_handler;
94     action.sa_flags   = 0;
95     sigaction(SIGINT, &action, NULL);
96
97     server_socket = socket(PF_INET6, SOCK_STREAM, 0);
98     if (-1 == server_socket) {
99         perror("socket()");
100         return EXIT_FAILURE;
101     }
102
103 #ifdef DEBUG
104     /* Fast rebinding for debug mode, could cause invalid packets. */
105     {
106         int socket_option = 1;
107         setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR,
108                    &socket_option, sizeof(socket_option));
109     }
110 #endif
111
112     /* Bind to the listen socket. */
113     memset(&server_in, 0, sizeof(server_in));
114     server_in.sin6_family = AF_INET6;              /* IPv6 (and IPv4) */
115     server_in.sin6_addr   = in6addr_any;           /* bind to any address */
116     server_in.sin6_port   = htons((uint16_t)port); /* port to bind to */
117     if (-1 == bind(server_socket, (struct sockaddr *)&server_in,
118                                   sizeof(server_in))) {
119         perror("bind()");
120         return EXIT_FAILURE;
121     }
122     /* And accept connections. */
123     if (-1 == listen(server_socket, 5)) {
124         perror("listen()");
125         return EXIT_FAILURE;
126     }
127
128 #ifdef DEBUG
129     printf("Listening for connections on port %d.\n", port);
130
131     if (NULL != use_proxy_host && NULL != use_proxy_port) {
132         printf("Using proxy: %s:%s.\n", use_proxy_host, use_proxy_port);
133     }
134 #endif
135
136     while (!done) {
137         /* Accept new connection. */
138         client_socket = accept(server_socket, NULL, NULL);
139         if (-1 == client_socket) {
140             perror("accept()");
141             break;
142         }
143
144         handle_connection(client_socket);
145     }
146
147     close(server_socket);
148
149     free(use_proxy_host);
150     free(use_proxy_port);
151
152     return EXIT_FAILURE;
153 }
154
155 static void sigint_handler(int signal_number) {
156     (void)signal_number;
157
158     done = 1;
159 }
160
161 static void parse_arguments(int argc, char **argv) {
162     int option;
163
164     while (-1 != (option = getopt(argc, argv, "p:h?"))) {
165         switch (option) {
166             case 'p': {
167                 char *position;
168
169                 /* -p must have the format host:port. */
170                 if (NULL == (position = strchr(optarg, ':'))
171                         || position == optarg
172                         || 0 == strlen(position + 1)
173                         || 0 >= atoi(position + 1)
174                         || 0xffff < atoi(position + 1)) {
175                     fprintf(stderr, "-p host:port\n");
176                     exit(EXIT_FAILURE);
177                 }
178
179                 use_proxy_host = malloc((size_t)(position - optarg) + 1);
180                 if (NULL == use_proxy_host) {
181                     perror("malloc()");
182                     exit(EXIT_FAILURE);
183                 }
184                 memcpy(use_proxy_host, optarg, (size_t)(position - optarg));
185                 use_proxy_host[position - optarg] = '\0';
186
187                 use_proxy_port = malloc(strlen(position + 1) + 1);
188                 if (NULL == use_proxy_port) {
189                     perror("malloc()");
190                     exit(EXIT_FAILURE);
191                 }
192                 strcpy(use_proxy_port, position + 1);
193
194                 break;
195             }
196             case 'h':
197             default: /* '?' */
198                 print_usage(argv[0]);
199                 exit(EXIT_FAILURE);
200         }
201     }
202
203     if (optind >= argc) {
204         print_usage(argv[0]);
205         exit(EXIT_FAILURE);
206     }
207 }
208 static void print_usage(const char *argv) {
209     fprintf(stderr, "Usage: %s [-p host:port] port\n", argv);
210     fprintf(stderr, "\n");
211     fprintf(stderr, "-p proxy hostname and port\n");
212 }
213
214 static void handle_connection(int client_socket) {
215     int server_socket;
216     FILE *client_fd, *server_fd;
217
218     char buffer[MAX_REQUEST_LINE];
219     char host[MAX_REQUEST_LINE];
220     char port[5 + 1];
221
222     int version_minor;
223     int result;
224
225     client_fd = fdopen(client_socket, "a+");
226     if (NULL == client_fd) {
227         perror("fdopen()");
228         close(client_socket);
229         return;
230     }
231
232 #ifdef DEBUG
233     printf("New connection:\n");
234 #endif
235
236     /* Read request line (CONNECT ..) and headers (they are discarded). */
237     result = read_http_request(client_fd, buffer, sizeof(buffer));
238     if (result == -1) {
239         /* Read error. */
240         return;
241     } else if (result == -2) {
242         /* EOF */
243         send_close_bad_request(client_fd);
244         return;
245     }
246
247 #ifdef DEBUG
248     printf("  request: %s", buffer);
249 #endif
250
251     if (0 != parse_request(buffer, host, port, &version_minor)) {
252         send_close_bad_request(client_fd);
253 #ifdef DEBUG
254         printf("  bad request\n");
255 #endif
256         return;
257     }
258
259 #ifdef DEBUG
260     printf("  %s:%s (HTTP 1.%d)\n", host, port, version_minor);
261 #endif
262
263     /* Connect to proxy server or directly to server. */
264     if (NULL != use_proxy_host && NULL != use_proxy_port) {
265         server_socket = connect_to_host(use_proxy_host, use_proxy_port);
266     } else {
267         server_socket = connect_to_host(host, port);
268     }
269
270     if (-1 == server_socket) {
271         send_close_forwarding_failure(client_fd);
272         return;
273     }
274     server_fd = fdopen(server_socket, "a+");
275     if (NULL == server_fd) {
276         send_close_forwarding_failure(client_fd);
277         return;
278     }
279
280     /* Connect to proxy if requested (command line option). */
281     if (NULL != use_proxy_host && NULL != use_proxy_port) {
282         fprintf(server_fd, "CONNECT %s:%s HTTP/1.0\r\n", host, port);
283         fprintf(server_fd, "\r\n");
284
285         /* Read response line from proxy server. */
286         result = read_http_request(server_fd, buffer, sizeof(buffer));
287         if (result == -1) {
288             /* Read error. */
289             send_close_forwarding_failure(client_fd);
290             return;
291         } else if (result == -2) {
292             /* EOF */
293             fclose(server_fd);
294             send_close_forwarding_failure(client_fd);
295             return;
296         }
297
298         /* Check response of proxy server. */
299         if (0 != strncmp(buffer, "HTTP/1.0 200", 12)) {
300 #ifdef DEBUG
301             printf("  bad proxy response\n");
302 #endif
303             fclose(server_fd);
304             send_close_forwarding_failure(client_fd);
305             return;
306         }
307     }
308
309 #ifdef DEBUG
310     printf("  connection to server established\n");
311 #endif
312
313     /* We've established a connection, tell the client. */
314     fprintf(client_fd, "HTTP/1.0 200 Connection established\r\n");
315     fprintf(client_fd, "\r\n");
316     fflush(client_fd);
317
318     /* And transfer all data between client and server transparently. */
319     transfer_data(client_socket, server_socket);
320
321     fclose(client_fd);
322     fclose(server_fd);
323 }
324
325 /* Read HTTP request line and headers (ignored).
326  *
327  * On success 0 is returned, -1 on client error (we close client descriptor in
328  * this case), -2 on unexpected EOF.
329  */
330 static int read_http_request(FILE *client_fd, char *request, size_t length) {
331     char buffer[MAX_REQUEST_LINE];
332
333     if (NULL == fgets(request, (int)length, client_fd)) {
334         if (ferror(client_fd)) {
335             perror("fgets(), request");
336             fclose(client_fd);
337             return -1;
338         }
339
340         return -2;
341     }
342
343     while (NULL != fgets(buffer, MAX_REQUEST_LINE, client_fd)) {
344         /* End of header. */
345         if (0 == strcmp(buffer, "\n") || 0 == strcmp(buffer, "\r\n")) {
346             break;
347         }
348     }
349     if (ferror(client_fd)) {
350         perror("fgets(), header");
351         fclose(client_fd);
352         return -1;
353     }
354
355     return 0;
356 }
357
358 static void send_close_bad_request(FILE *client_fd) {
359     fprintf(client_fd, "HTTP/1.0 400 Bad Request\r\n");
360     fprintf(client_fd, "\r\n");
361     fclose(client_fd);
362 }
363 static void send_close_forwarding_failure(FILE *client_fd) {
364     fprintf(client_fd, "HTTP/1.0 503 Forwarding failure\r\n");
365     fprintf(client_fd, "\r\n");
366     fclose(client_fd);
367 }
368
369
370 /* Transfer data between client and server sockets until one closes the
371  * connection. */
372 static void transfer_data(int client, int server) {
373     struct pollfd fds[2];
374     fds[0].fd      = client;
375     fds[0].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
376     fds[0].revents = 0;
377     fds[1].fd      = server;
378     fds[1].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
379     fds[1].revents = 0;
380
381     for (;;) {
382         int result = poll(fds, 2, -1 /* no timeout */);
383         if (result < 0) {
384             perror("poll()");
385             return;
386         }
387
388         /* Data available from client. */
389         if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
390             if (0 != read_from_write_to(client, server)) {
391                 /* EOF (or other error) */
392                 break;
393             }
394         }
395         /* Data available from server. */
396         if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
397             if (0 != read_from_write_to(server, client)) {
398                 /* EOF (or other error) */
399                 break;
400             }
401         }
402
403         /* Client closed connection. */
404         if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
405             break;
406         }
407         /* Server closed connection. */
408         if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
409             break;
410         }
411     }
412 }
413
414 /* Read available data from socket from and write it to socket to. At maximum
415  * 4096 bytes are read/written. */
416 static int read_from_write_to(int from, int to) {
417     ssize_t size_read;
418     ssize_t size_written;
419     char buffer[4096];
420
421     size_read = read(from, buffer, sizeof(buffer));
422     if (0 > size_read) {
423         perror("read()");
424         return -1;
425     }
426     /* EOF */
427     if (0 == size_read) {
428         return -1;
429     }
430
431     size_written = write(to, buffer, (size_t)size_read);
432     if (0 > size_written) {
433         perror("write()");
434         return -1;
435     }
436     if (size_read != size_written) {
437         printf("only written %ld of %ld bytes!\n", (long int)size_read,
438                                                    (long int)size_written);
439         return -1;
440     }
441
442     return 0;
443 }
444
445
446 static int connect_to_host(const char *hostname, const char *port) {
447     struct addrinfo gai_hints;
448     struct addrinfo *gai_result;
449     int gai_return;
450
451     int server_socket;
452     struct addrinfo *server;
453
454     if (NULL == hostname || NULL == port) {
455         return -1;
456     }
457
458     /* Get IP of hostname server. */
459     memset(&gai_hints, 0, sizeof(gai_hints));
460     gai_hints.ai_family   = AF_UNSPEC;
461     gai_hints.ai_socktype = SOCK_STREAM;
462     gai_hints.ai_protocol = 0;
463     gai_hints.ai_flags    = AI_NUMERICSERV /* given port is numeric */
464                           | AI_ADDRCONFIG  /* supported by this computer */
465                           | AI_V4MAPPED;   /* support IPv4 through IPv6 */
466     gai_return = getaddrinfo(hostname, port, &gai_hints, &gai_result);
467     if (0 != gai_return) {
468         perror("getaddrinfo()");
469         return -1;
470     }
471
472     /* Now try to connect to each server returned by getaddrinfo(), use the
473      * first successful connect. */
474     for (server = gai_result; NULL != server; server = server->ai_next) {
475         server_socket = socket(server->ai_family,
476                                server->ai_socktype,
477                                server->ai_protocol);
478         if (-1 == server_socket) {
479             perror("socket(), trying next");
480             continue;
481         }
482
483         if (-1 != connect(server_socket, server->ai_addr,
484                                          server->ai_addrlen)) {
485             break;
486         }
487         perror("connect(), trying next");
488
489         close(server_socket);
490     }
491     /* Make sure we free the result from getaddrinfo(). */
492     freeaddrinfo(gai_result);
493
494     if (NULL == server) {
495         fprintf(stderr, "no server found, aborting\n");
496         return -1;
497     }
498
499     return server_socket;
500 }
501
502
503 /* Parse HTTP CONNECT request string and save its parameters.
504  *
505  * The following format is expected: "CONNECT host:port HTTP/1.y".
506  *
507  * request and host must have the same size! port must be at least 6 bytes
508  * long (5 + '\0').
509  */
510 static int parse_request(const char *request, char *host, char *port,
511                                               int *version_minor) {
512     int port_unused; /* just used to verify the port is numeric */
513     char *position;
514
515     /* scanf() doesn't check spaces. */
516     if (0 != strncmp(request, "CONNECT ", 8)) {
517         return -1;
518     }
519     /* Check request and extract data, "host:port" is not yet separated. */
520     if (2 != sscanf(request, "CONNECT %s HTTP/1.%d",
521                              host, version_minor)) {
522         return -1;
523     }
524     /* Make sure ":port" is there. */
525     if (NULL == (position = strchr(host, ':'))) {
526         return -1;
527     }
528     /* Make sure port is numeric. */
529     if (1 != sscanf(position + 1, "%d", &port_unused)) {
530         return -1;
531     }
532     /* Store it in *port. */
533     strncpy(port, position + 1, 5);
534     port[5] = '\0';
535     /* And remove port from host. */
536     *position = '\0';
537
538     return 0;
539 }