]> ruderich.org/simon Gitweb - tlsproxy/tlsproxy.git/blob - src/tlsproxy.c
src/: Move log related functions/defines to log.[hc].
[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 "tlsproxy.h"
21 #include "sem.h"
22 #include "connection.h"
23
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 /* sigaction() */
32 #include <signal.h>
33 /* errno */
34 #include <errno.h>
35 /* pthread_*() */
36 #include <pthread.h>
37
38 /* For GnuTLS. */
39 #include <gcrypt.h>
40
41 GCRY_THREAD_OPTION_PTHREAD_IMPL;
42
43
44 /* Size of ringbuffer. */
45 #define RINGBUFFER_SIZE 10
46
47 /* Bit size of Diffie-Hellman key exchange parameters. */
48 #define DH_SIZE 1024
49
50
51 /* For gnutls_*() functions. */
52 #define GNUTLS_ERROR_EXIT(error, message) \
53     if (GNUTLS_E_SUCCESS != error) { \
54         fprintf(stderr, "%s: %s\n", message, gnutls_strerror(error)); \
55         exit(EXIT_FAILURE); \
56     }
57
58
59 /* Server should shut down. Set by SIGINT handler. */
60 static volatile int done;
61
62 /* Number of threads. */
63 static size_t thread_count;
64
65 /* Synchronized ring buffer storing accept()ed client sockets. */
66 static int ringbuffer[RINGBUFFER_SIZE];
67 static int ringbuffer_read;
68 static int ringbuffer_write;
69 static SEM *ringbuffer_full; /* At least one element in the buffer? */
70 static SEM *ringbuffer_free; /* Space for another element in the buffer? */
71 static SEM *ringbuffer_lock; /* Read lock. */
72
73
74 static void sigint_handler(int signal);
75
76 static void parse_arguments(int argc, char **argv);
77 static void print_usage(const char *argv);
78
79 static void initialize_gnutls(void);
80 static void deinitialize_gnutls(void);
81
82 static void worker_thread(void);
83
84
85 int main(int argc, char **argv) {
86     int port;
87     int client_socket, server_socket;
88     struct sockaddr_in6 server_in;
89
90     size_t i;
91     pthread_t *threads;
92
93     struct sigaction action;
94
95     parse_arguments(argc, argv);
96
97     port = atoi(argv[argc - 1]);
98     if (0 >= port || 0xffff < port) {
99         print_usage(argv[0]);
100         fprintf(stderr, "\ninvalid port\n");
101         return EXIT_FAILURE;
102     }
103
104     /* Setup our SIGINT signal handler which allows a "normal" termination of
105      * the server. */
106     sigemptyset(&action.sa_mask);
107     action.sa_handler = sigint_handler;
108     action.sa_flags   = 0;
109     sigaction(SIGINT, &action, NULL);
110     /* Ignore SIGPIPEs. */
111     action.sa_handler = SIG_IGN;
112     sigaction(SIGPIPE, &action, NULL);
113
114     /* Initialize ring buffer. */
115     ringbuffer_read  = 0;
116     ringbuffer_write = 0;
117     ringbuffer_full  = sem_init(0);
118     ringbuffer_free  = sem_init(RINGBUFFER_SIZE);
119     ringbuffer_lock  = sem_init(1);
120     if (NULL == ringbuffer_full
121             || NULL == ringbuffer_free
122             || NULL == ringbuffer_lock) {
123         perror("sem_init()");
124         return EXIT_FAILURE;
125     }
126
127     initialize_gnutls();
128
129     /* Spawn worker threads to handle requests. */
130     threads = (pthread_t *)malloc(thread_count * sizeof(pthread_t));
131     if (NULL == threads) {
132         perror("thread malloc failed");
133         return EXIT_FAILURE;
134     }
135     for (i = 0; i < thread_count; i++) {
136         int result;
137         pthread_t thread;
138
139         result = pthread_create(&thread, NULL,
140                                 (void * (*)(void *))&worker_thread,
141                                 NULL);
142         if (0 != result) {
143             printf("failed to create worker thread: %s\n", strerror(result));
144             return EXIT_FAILURE;
145         }
146
147         threads[i] = thread;
148     }
149
150     server_socket = socket(PF_INET6, SOCK_STREAM, 0);
151     if (-1 == server_socket) {
152         perror("socket()");
153         return EXIT_FAILURE;
154     }
155
156 #ifdef DEBUG
157     /* Fast rebinding for debug mode, could cause invalid packets. */
158     {
159         int socket_option = 1;
160         setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR,
161                    &socket_option, sizeof(socket_option));
162     }
163 #endif
164
165     /* Bind to the listen socket. */
166     memset(&server_in, 0, sizeof(server_in));
167     server_in.sin6_family = AF_INET6;              /* IPv6 (and IPv4) */
168     server_in.sin6_addr   = in6addr_any;           /* bind to any address */
169     server_in.sin6_port   = htons((uint16_t)port); /* port to bind to */
170     if (-1 == bind(server_socket, (struct sockaddr *)&server_in,
171                                   sizeof(server_in))) {
172         perror("bind()");
173         return EXIT_FAILURE;
174     }
175     /* And accept connections. */
176     if (-1 == listen(server_socket, 5)) {
177         perror("listen()");
178         return EXIT_FAILURE;
179     }
180
181     if (LOG_DEBUG <= global_log_level) {
182         printf("Listening for connections on port %d.\n", port);
183
184         if (NULL != global_proxy_host && NULL != global_proxy_port) {
185             printf("Using proxy: %s:%s.\n", global_proxy_host,
186                                             global_proxy_port);
187         }
188     }
189
190     while (!done) {
191         /* Accept new connection. */
192         client_socket = accept(server_socket, NULL, NULL);
193         if (-1 == client_socket) {
194             perror("accept()");
195             break;
196         }
197
198         /* No lock, we only have one producer! */
199         P(ringbuffer_free);
200         ringbuffer[ringbuffer_write] = client_socket;
201         ringbuffer_write = (ringbuffer_write + 1) % RINGBUFFER_SIZE;
202         V(ringbuffer_full);
203     }
204
205     close(server_socket);
206
207     /* Poison all threads and shut them down. */
208     for (i = 0; i < thread_count; i++) {
209         P(ringbuffer_free);
210         ringbuffer[ringbuffer_write] = -1; /* poison */
211         ringbuffer_write = (ringbuffer_write + 1) % RINGBUFFER_SIZE;
212         V(ringbuffer_full);
213     }
214     for (i = 0; i < thread_count; i++) {
215         errno = pthread_join(threads[i], NULL);
216         if (0 != errno) {
217             perror("pthread_join()");
218             continue;
219         }
220     }
221
222     free(ringbuffer_full);
223     free(ringbuffer_free);
224     free(ringbuffer_lock);
225
226     free(threads);
227
228     deinitialize_gnutls();
229
230     free(global_proxy_host);
231     free(global_proxy_port);
232
233     return EXIT_FAILURE;
234 }
235
236 static void sigint_handler(int signal_number) {
237     (void)signal_number;
238
239     done = 1;
240 }
241
242 static void parse_arguments(int argc, char **argv) {
243     int option;
244
245     /* Default values. */
246     thread_count = 10;
247 #ifdef DEBUG
248     global_log_level = LOG_DEBUG;
249 #else
250     global_log_level = LOG_WARNING;
251 #endif
252
253     while (-1 != (option = getopt(argc, argv, "d:p:t:h?"))) {
254         switch (option) {
255             case 'd': {
256                 if (0 > atoi(optarg)) {
257                     print_usage(argv[0]);
258                     fprintf(stderr, "\n-d positive number required\n");
259                     exit(EXIT_FAILURE);
260                 }
261                 global_log_level = atoi(optarg);
262                 break;
263             }
264             case 'p': {
265                 char *position;
266
267                 /* -p must have the format host:port. */
268                 if (NULL == (position = strchr(optarg, ':'))
269                         || position == optarg
270                         || 0 == strlen(position + 1)
271                         || 0 >= atoi(position + 1)
272                         || 0xffff < atoi(position + 1)) {
273                     print_usage(argv[0]);
274                     fprintf(stderr, "\ninvalid -p, format host:port\n");
275                     exit(EXIT_FAILURE);
276                 }
277
278                 global_proxy_host = malloc((size_t)(position - optarg) + 1);
279                 if (NULL == global_proxy_host) {
280                     perror("malloc()");
281                     exit(EXIT_FAILURE);
282                 }
283                 memcpy(global_proxy_host, optarg, (size_t)(position - optarg));
284                 global_proxy_host[position - optarg] = '\0';
285
286                 global_proxy_port = malloc(strlen(position + 1) + 1);
287                 if (NULL == global_proxy_port) {
288                     perror("malloc()");
289                     exit(EXIT_FAILURE);
290                 }
291                 strcpy(global_proxy_port, position + 1);
292
293                 break;
294             }
295             case 't': {
296                 if (0 >= atoi(optarg)) {
297                     print_usage(argv[0]);
298                     fprintf(stderr, "\n-t positive number required\n");
299                     exit(EXIT_FAILURE);
300                 }
301                 thread_count = (size_t)atoi(optarg);
302                 break;
303             }
304             case 'h':
305             default: /* '?' */
306                 print_usage(argv[0]);
307                 exit(EXIT_FAILURE);
308         }
309     }
310
311     if (optind >= argc) {
312         print_usage(argv[0]);
313         fprintf(stderr, "\nport missing\n");
314         exit(EXIT_FAILURE);
315     }
316 }
317 static void print_usage(const char *argv) {
318     fprintf(stderr, "Usage: %s [-d level] [-p host:port] [-t count] port\n",
319                     argv);
320     fprintf(stderr, "\n");
321     fprintf(stderr, "-d debug level: 0=errors only, 2=debug [default: 1]\n");
322     fprintf(stderr, "-p proxy hostname and port\n");
323     fprintf(stderr, "-t number of threads [default: 10]\n");
324 }
325
326 static void initialize_gnutls(void) {
327     int result;
328     gcry_error_t error = 0;
329
330     /* Thread safe setup. Must be called before gnutls_global_init(). */
331     error = gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
332     if (error) {
333         fprintf(stderr, "gcry_control(): %s/%s\n", gcry_strsource(error),
334                                                    gcry_strerror(error));
335         exit(EXIT_FAILURE);
336     }
337     /* Prevent usage of blocking /dev/random. */
338     error = gcry_control(GCRYCTL_ENABLE_QUICK_RANDOM, 0);
339     if (error) {
340         fprintf(stderr, "gcry_control(): %s/%s\n", gcry_strsource(error),
341                                                    gcry_strerror(error));
342         exit(EXIT_FAILURE);
343     }
344
345     /* Initialize GnuTLS. */
346     result = gnutls_global_init();
347     GNUTLS_ERROR_EXIT(result, "gnutls_global_init()");
348
349     /* Setup GnuTLS cipher suites. */
350     result = gnutls_priority_init(&tls_priority_cache, "NORMAL", NULL);
351     GNUTLS_ERROR_EXIT(result, "gnutls_priority_init()");
352
353     /* Generate Diffie-Hellman parameters. */
354     result = gnutls_dh_params_init(&tls_dh_params);
355     GNUTLS_ERROR_EXIT(result, "gnutls_dh_params_init()");
356     result = gnutls_dh_params_generate2(tls_dh_params, DH_SIZE);
357     GNUTLS_ERROR_EXIT(result, "gnutls_dh_params_generate2()");
358 }
359 static void deinitialize_gnutls(void) {
360     gnutls_dh_params_deinit(tls_dh_params);
361     gnutls_priority_deinit(tls_priority_cache);
362
363     gnutls_global_deinit();
364 }
365
366 static void worker_thread(void) {
367     int client_socket;
368
369     for (;;) {
370         /* Get next element from ring buffer. */
371         P(ringbuffer_full);
372         P(ringbuffer_lock);
373         client_socket = ringbuffer[ringbuffer_read];
374         ringbuffer_read = (ringbuffer_read + 1) % RINGBUFFER_SIZE;
375         V(ringbuffer_lock);
376         V(ringbuffer_free);
377
378         /* Negative value indicates we should shut down our thread. */
379         if (0 > client_socket) {
380             break;
381         }
382
383         handle_connection(client_socket);
384     }
385 }