]> ruderich.org/simon Gitweb - tlsproxy/tlsproxy.git/blob - src/tlsproxy.c
src/tlsproxy.c: Add thread support.
[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 <config.h>
21
22 #include <stdlib.h>
23 #include <stdio.h>
24 /* socket(), bind(), accept(), listen() */
25 #include <sys/types.h>
26 #include <sys/socket.h>
27 /* close() */
28 #include <unistd.h>
29 /* htons() */
30 #include <arpa/inet.h>
31 /* getaddrinfo() */
32 #include <netdb.h>
33 /* strncmp() */
34 #include <string.h>
35 /* sigaction() */
36 #include <signal.h>
37 /* poll() */
38 #include <poll.h>
39 /* errno */
40 #include <errno.h>
41 /* pthread_*() */
42 #include <pthread.h>
43
44 #include "sem.h"
45
46 /* Maximum line of the request line. Longer request lines are aborted with an
47  * error. The standard doesn't specify a maximum line length but this should
48  * be a good limit to make processing simpler. */
49 #define MAX_REQUEST_LINE 4096
50
51 /* Size of ringbuffer. */
52 #define RINGBUFFER_SIZE 10
53
54
55 /* Server should shut down. Set by SIGINT handler. */
56 static volatile int done;
57
58 /* Number of threads. */
59 static size_t thread_count;
60 /* Synchronized ring buffer storing accept()ed client sockets. */
61 static int ringbuffer[RINGBUFFER_SIZE];
62 static int ringbuffer_read;
63 static int ringbuffer_write;
64 static SEM *ringbuffer_full; /* At least one element in the buffer? */
65 static SEM *ringbuffer_free; /* Space for another element in the buffer? */
66 static SEM *ringbuffer_lock; /* Read lock. */
67 /* Proxy hostname and port if specified on the command line. */
68 static char *use_proxy_host;
69 static char *use_proxy_port;
70
71
72 static void sigint_handler(int signal);
73
74 static void parse_arguments(int argc, char **argv);
75 static void print_usage(const char *argv);
76
77 static void worker_thread(void);
78 static void handle_connection(int socket);
79 static int read_http_request(FILE *client_fd, char *request, size_t length);
80 static void send_close_bad_request(FILE *client_fd);
81 static void send_close_forwarding_failure(FILE *client_fd);
82
83 static void transfer_data(int client, int server);
84 static int read_from_write_to(int from, int to);
85
86 static int connect_to_host(const char *hostname, const char *port);
87
88 static int parse_request(const char *buffer, char *host, char *port,
89                                              int *version_minor);
90
91
92 int main(int argc, char **argv) {
93     int port;
94     int client_socket, server_socket;
95     struct sockaddr_in6 server_in;
96
97     size_t i;
98     pthread_t *threads;
99
100     struct sigaction action;
101
102     parse_arguments(argc, argv);
103
104     port = atoi(argv[argc - 1]);
105     if (0 >= port || 0xffff < port) {
106         print_usage(argv[0]);
107         fprintf(stderr, "\ninvalid port");
108         return EXIT_FAILURE;
109     }
110
111     /* Setup our SIGINT signal handler which allows a "normal" termination of
112      * the server. */
113     sigemptyset(&action.sa_mask);
114     action.sa_handler = sigint_handler;
115     action.sa_flags   = 0;
116     sigaction(SIGINT, &action, NULL);
117
118     /* Initialize ring buffer. */
119     ringbuffer_read  = 0;
120     ringbuffer_write = 0;
121     ringbuffer_full  = sem_init(0);
122     ringbuffer_free  = sem_init(RINGBUFFER_SIZE);
123     ringbuffer_lock  = sem_init(1);
124     if (NULL == ringbuffer_full
125             || NULL == ringbuffer_free
126             || NULL == ringbuffer_lock) {
127         perror("sem_init()");
128         return EXIT_FAILURE;
129     }
130
131     /* Spawn worker threads to handle requests. */
132     threads = (pthread_t *)malloc(thread_count * sizeof(pthread_t));
133     if (NULL == threads) {
134         perror("thread malloc failed");
135         return EXIT_FAILURE;
136     }
137     for (i = 0; i < thread_count; i++) {
138         int result;
139         pthread_t thread;
140
141         result = pthread_create(&thread, NULL,
142                                 (void * (*)(void *))&worker_thread,
143                                 NULL);
144         if (0 != result) {
145             printf("failed to create worker thread: %s\n", strerror(result));
146             return EXIT_FAILURE;
147         }
148
149         threads[i] = thread;
150     }
151
152     server_socket = socket(PF_INET6, SOCK_STREAM, 0);
153     if (-1 == server_socket) {
154         perror("socket()");
155         return EXIT_FAILURE;
156     }
157
158 #ifdef DEBUG
159     /* Fast rebinding for debug mode, could cause invalid packets. */
160     {
161         int socket_option = 1;
162         setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR,
163                    &socket_option, sizeof(socket_option));
164     }
165 #endif
166
167     /* Bind to the listen socket. */
168     memset(&server_in, 0, sizeof(server_in));
169     server_in.sin6_family = AF_INET6;              /* IPv6 (and IPv4) */
170     server_in.sin6_addr   = in6addr_any;           /* bind to any address */
171     server_in.sin6_port   = htons((uint16_t)port); /* port to bind to */
172     if (-1 == bind(server_socket, (struct sockaddr *)&server_in,
173                                   sizeof(server_in))) {
174         perror("bind()");
175         return EXIT_FAILURE;
176     }
177     /* And accept connections. */
178     if (-1 == listen(server_socket, 5)) {
179         perror("listen()");
180         return EXIT_FAILURE;
181     }
182
183 #ifdef DEBUG
184     printf("Listening for connections on port %d.\n", port);
185
186     if (NULL != use_proxy_host && NULL != use_proxy_port) {
187         printf("Using proxy: %s:%s.\n", use_proxy_host, use_proxy_port);
188     }
189 #endif
190
191     while (!done) {
192         /* Accept new connection. */
193         client_socket = accept(server_socket, NULL, NULL);
194         if (-1 == client_socket) {
195             perror("accept()");
196             break;
197         }
198
199         /* No lock, we only have one producer! */
200         P(ringbuffer_free);
201         ringbuffer[ringbuffer_write] = client_socket;
202         ringbuffer_write = (ringbuffer_write + 1) % RINGBUFFER_SIZE;
203         V(ringbuffer_full);
204     }
205
206     close(server_socket);
207
208     /* Poison all threads and shut them down. */
209     for (i = 0; i < thread_count; i++) {
210         P(ringbuffer_free);
211         ringbuffer[ringbuffer_write] = -1; /* poison */
212         ringbuffer_write = (ringbuffer_write + 1) % RINGBUFFER_SIZE;
213         V(ringbuffer_full);
214     }
215     for (i = 0; i < thread_count; i++) {
216         errno = pthread_join(threads[i], NULL);
217         if (0 != errno) {
218             perror("pthread_join()");
219             continue;
220         }
221     }
222
223     free(ringbuffer_full);
224     free(ringbuffer_free);
225     free(ringbuffer_lock);
226
227     free(threads);
228
229     free(use_proxy_host);
230     free(use_proxy_port);
231
232     return EXIT_FAILURE;
233 }
234
235 static void sigint_handler(int signal_number) {
236     (void)signal_number;
237
238     done = 1;
239 }
240
241 static void parse_arguments(int argc, char **argv) {
242     int option;
243
244     /* Default values. */
245     thread_count = 10;
246
247     while (-1 != (option = getopt(argc, argv, "p:t:h?"))) {
248         switch (option) {
249             case 'p': {
250                 char *position;
251
252                 /* -p must have the format host:port. */
253                 if (NULL == (position = strchr(optarg, ':'))
254                         || position == optarg
255                         || 0 == strlen(position + 1)
256                         || 0 >= atoi(position + 1)
257                         || 0xffff < atoi(position + 1)) {
258                     fprintf(stderr, "-p host:port\n");
259                     exit(EXIT_FAILURE);
260                 }
261
262                 use_proxy_host = malloc((size_t)(position - optarg) + 1);
263                 if (NULL == use_proxy_host) {
264                     perror("malloc()");
265                     exit(EXIT_FAILURE);
266                 }
267                 memcpy(use_proxy_host, optarg, (size_t)(position - optarg));
268                 use_proxy_host[position - optarg] = '\0';
269
270                 use_proxy_port = malloc(strlen(position + 1) + 1);
271                 if (NULL == use_proxy_port) {
272                     perror("malloc()");
273                     exit(EXIT_FAILURE);
274                 }
275                 strcpy(use_proxy_port, position + 1);
276
277                 break;
278             }
279             case 't': {
280                 if (0 >= atoi(optarg)) {
281                     fprintf(stderr, "-t positive number required\n");
282                     exit(EXIT_FAILURE);
283                 }
284                 thread_count = (size_t)atoi(optarg);
285                 break;
286             }
287             case 'h':
288             default: /* '?' */
289                 print_usage(argv[0]);
290                 exit(EXIT_FAILURE);
291         }
292     }
293
294     if (optind >= argc) {
295         print_usage(argv[0]);
296         exit(EXIT_FAILURE);
297     }
298 }
299 static void print_usage(const char *argv) {
300     fprintf(stderr, "Usage: %s [-p host:port] port\n", argv);
301     fprintf(stderr, "\n");
302     fprintf(stderr, "-p proxy hostname and port\n");
303     fprintf(stderr, "-t number of threads [default: 10]\n");
304 }
305
306 static void worker_thread(void) {
307     int client_socket;
308
309     for (;;) {
310         /* Get next element from ring buffer. */
311         P(ringbuffer_full);
312         P(ringbuffer_lock);
313         client_socket = ringbuffer[ringbuffer_read];
314         ringbuffer_read = (ringbuffer_read + 1) % RINGBUFFER_SIZE;
315         V(ringbuffer_lock);
316         V(ringbuffer_free);
317
318         /* Negative value indicates we should shut down our thread. */
319         if (client_socket < 0) {
320             break;
321         }
322
323         handle_connection(client_socket);
324     }
325 }
326
327 static void handle_connection(int client_socket) {
328     int server_socket;
329     FILE *client_fd, *server_fd;
330
331     char buffer[MAX_REQUEST_LINE];
332     char host[MAX_REQUEST_LINE];
333     char port[5 + 1];
334
335     int version_minor;
336     int result;
337
338     client_fd = fdopen(client_socket, "a+");
339     if (NULL == client_fd) {
340         perror("fdopen()");
341         close(client_socket);
342         return;
343     }
344
345 #ifdef DEBUG
346     printf("New connection:\n");
347 #endif
348
349     /* Read request line (CONNECT ..) and headers (they are discarded). */
350     result = read_http_request(client_fd, buffer, sizeof(buffer));
351     if (result == -1) {
352         /* Read error. */
353         return;
354     } else if (result == -2) {
355         /* EOF */
356         send_close_bad_request(client_fd);
357         return;
358     }
359
360 #ifdef DEBUG
361     printf("  request: %s", buffer);
362 #endif
363
364     if (0 != parse_request(buffer, host, port, &version_minor)) {
365         send_close_bad_request(client_fd);
366 #ifdef DEBUG
367         printf("  bad request\n");
368 #endif
369         return;
370     }
371
372 #ifdef DEBUG
373     printf("  %s:%s (HTTP 1.%d)\n", host, port, version_minor);
374 #endif
375
376     /* Connect to proxy server or directly to server. */
377     if (NULL != use_proxy_host && NULL != use_proxy_port) {
378         server_socket = connect_to_host(use_proxy_host, use_proxy_port);
379     } else {
380         server_socket = connect_to_host(host, port);
381     }
382
383     if (-1 == server_socket) {
384         send_close_forwarding_failure(client_fd);
385         return;
386     }
387     server_fd = fdopen(server_socket, "a+");
388     if (NULL == server_fd) {
389         send_close_forwarding_failure(client_fd);
390         return;
391     }
392
393     /* Connect to proxy if requested (command line option). */
394     if (NULL != use_proxy_host && NULL != use_proxy_port) {
395         fprintf(server_fd, "CONNECT %s:%s HTTP/1.0\r\n", host, port);
396         fprintf(server_fd, "\r\n");
397
398         /* Read response line from proxy server. */
399         result = read_http_request(server_fd, buffer, sizeof(buffer));
400         if (result == -1) {
401             /* Read error. */
402             send_close_forwarding_failure(client_fd);
403             return;
404         } else if (result == -2) {
405             /* EOF */
406             fclose(server_fd);
407             send_close_forwarding_failure(client_fd);
408             return;
409         }
410
411         /* Check response of proxy server. */
412         if (0 != strncmp(buffer, "HTTP/1.0 200", 12)) {
413 #ifdef DEBUG
414             printf("  bad proxy response\n");
415 #endif
416             fclose(server_fd);
417             send_close_forwarding_failure(client_fd);
418             return;
419         }
420     }
421
422 #ifdef DEBUG
423     printf("  connection to server established\n");
424 #endif
425
426     /* We've established a connection, tell the client. */
427     fprintf(client_fd, "HTTP/1.0 200 Connection established\r\n");
428     fprintf(client_fd, "\r\n");
429     fflush(client_fd);
430
431     /* And transfer all data between client and server transparently. */
432     transfer_data(client_socket, server_socket);
433
434     fclose(client_fd);
435     fclose(server_fd);
436 }
437
438 /* Read HTTP request line and headers (ignored).
439  *
440  * On success 0 is returned, -1 on client error (we close client descriptor in
441  * this case), -2 on unexpected EOF.
442  */
443 static int read_http_request(FILE *client_fd, char *request, size_t length) {
444     char buffer[MAX_REQUEST_LINE];
445
446     if (NULL == fgets(request, (int)length, client_fd)) {
447         if (ferror(client_fd)) {
448             perror("fgets(), request");
449             fclose(client_fd);
450             return -1;
451         }
452
453         return -2;
454     }
455
456     while (NULL != fgets(buffer, MAX_REQUEST_LINE, client_fd)) {
457         /* End of header. */
458         if (0 == strcmp(buffer, "\n") || 0 == strcmp(buffer, "\r\n")) {
459             break;
460         }
461     }
462     if (ferror(client_fd)) {
463         perror("fgets(), header");
464         fclose(client_fd);
465         return -1;
466     }
467
468     return 0;
469 }
470
471 static void send_close_bad_request(FILE *client_fd) {
472     fprintf(client_fd, "HTTP/1.0 400 Bad Request\r\n");
473     fprintf(client_fd, "\r\n");
474     fclose(client_fd);
475 }
476 static void send_close_forwarding_failure(FILE *client_fd) {
477     fprintf(client_fd, "HTTP/1.0 503 Forwarding failure\r\n");
478     fprintf(client_fd, "\r\n");
479     fclose(client_fd);
480 }
481
482
483 /* Transfer data between client and server sockets until one closes the
484  * connection. */
485 static void transfer_data(int client, int server) {
486     struct pollfd fds[2];
487     fds[0].fd      = client;
488     fds[0].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
489     fds[0].revents = 0;
490     fds[1].fd      = server;
491     fds[1].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
492     fds[1].revents = 0;
493
494     for (;;) {
495         int result = poll(fds, 2, -1 /* no timeout */);
496         if (result < 0) {
497             perror("poll()");
498             return;
499         }
500
501         /* Data available from client. */
502         if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
503             if (0 != read_from_write_to(client, server)) {
504                 /* EOF (or other error) */
505                 break;
506             }
507         }
508         /* Data available from server. */
509         if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
510             if (0 != read_from_write_to(server, client)) {
511                 /* EOF (or other error) */
512                 break;
513             }
514         }
515
516         /* Client closed connection. */
517         if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
518             break;
519         }
520         /* Server closed connection. */
521         if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
522             break;
523         }
524     }
525 }
526
527 /* Read available data from socket from and write it to socket to. At maximum
528  * 4096 bytes are read/written. */
529 static int read_from_write_to(int from, int to) {
530     ssize_t size_read;
531     ssize_t size_written;
532     char buffer[4096];
533
534     size_read = read(from, buffer, sizeof(buffer));
535     if (0 > size_read) {
536         perror("read()");
537         return -1;
538     }
539     /* EOF */
540     if (0 == size_read) {
541         return -1;
542     }
543
544     size_written = write(to, buffer, (size_t)size_read);
545     if (0 > size_written) {
546         perror("write()");
547         return -1;
548     }
549     if (size_read != size_written) {
550         printf("only written %ld of %ld bytes!\n", (long int)size_read,
551                                                    (long int)size_written);
552         return -1;
553     }
554
555     return 0;
556 }
557
558
559 static int connect_to_host(const char *hostname, const char *port) {
560     struct addrinfo gai_hints;
561     struct addrinfo *gai_result;
562     int gai_return;
563
564     int server_socket;
565     struct addrinfo *server;
566
567     if (NULL == hostname || NULL == port) {
568         return -1;
569     }
570
571     /* Get IP of hostname server. */
572     memset(&gai_hints, 0, sizeof(gai_hints));
573     gai_hints.ai_family   = AF_UNSPEC;
574     gai_hints.ai_socktype = SOCK_STREAM;
575     gai_hints.ai_protocol = 0;
576     gai_hints.ai_flags    = AI_NUMERICSERV /* given port is numeric */
577                           | AI_ADDRCONFIG  /* supported by this computer */
578                           | AI_V4MAPPED;   /* support IPv4 through IPv6 */
579     gai_return = getaddrinfo(hostname, port, &gai_hints, &gai_result);
580     if (0 != gai_return) {
581         perror("getaddrinfo()");
582         return -1;
583     }
584
585     /* Now try to connect to each server returned by getaddrinfo(), use the
586      * first successful connect. */
587     for (server = gai_result; NULL != server; server = server->ai_next) {
588         server_socket = socket(server->ai_family,
589                                server->ai_socktype,
590                                server->ai_protocol);
591         if (-1 == server_socket) {
592             perror("socket(), trying next");
593             continue;
594         }
595
596         if (-1 != connect(server_socket, server->ai_addr,
597                                          server->ai_addrlen)) {
598             break;
599         }
600         perror("connect(), trying next");
601
602         close(server_socket);
603     }
604     /* Make sure we free the result from getaddrinfo(). */
605     freeaddrinfo(gai_result);
606
607     if (NULL == server) {
608         fprintf(stderr, "no server found, aborting\n");
609         return -1;
610     }
611
612     return server_socket;
613 }
614
615
616 /* Parse HTTP CONNECT request string and save its parameters.
617  *
618  * The following format is expected: "CONNECT host:port HTTP/1.y".
619  *
620  * request and host must have the same size! port must be at least 6 bytes
621  * long (5 + '\0').
622  */
623 static int parse_request(const char *request, char *host, char *port,
624                                               int *version_minor) {
625     int port_unused; /* just used to verify the port is numeric */
626     char *position;
627
628     /* scanf() doesn't check spaces. */
629     if (0 != strncmp(request, "CONNECT ", 8)) {
630         return -1;
631     }
632     /* Check request and extract data, "host:port" is not yet separated. */
633     if (2 != sscanf(request, "CONNECT %s HTTP/1.%d",
634                              host, version_minor)) {
635         return -1;
636     }
637     /* Make sure ":port" is there. */
638     if (NULL == (position = strchr(host, ':'))) {
639         return -1;
640     }
641     /* Make sure port is numeric. */
642     if (1 != sscanf(position + 1, "%d", &port_unused)) {
643         return -1;
644     }
645     /* Store it in *port. */
646     strncpy(port, position + 1, 5);
647     port[5] = '\0';
648     /* And remove port from host. */
649     *position = '\0';
650
651     return 0;
652 }