]> ruderich.org/simon Gitweb - tlsproxy/tlsproxy.git/blob - src/tlsproxy.c
src/tlsproxy.c: Ignore SIGPIPEs.
[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 /* Size of ringbuffer. */
39 #define RINGBUFFER_SIZE 10
40
41
42 /* Server should shut down. Set by SIGINT handler. */
43 static volatile int done;
44
45 /* Number of threads. */
46 static size_t thread_count;
47 /* Synchronized ring buffer storing accept()ed client sockets. */
48 static int ringbuffer[RINGBUFFER_SIZE];
49 static int ringbuffer_read;
50 static int ringbuffer_write;
51 static SEM *ringbuffer_full; /* At least one element in the buffer? */
52 static SEM *ringbuffer_free; /* Space for another element in the buffer? */
53 static SEM *ringbuffer_lock; /* Read lock. */
54
55
56 static void sigint_handler(int signal);
57
58 static void parse_arguments(int argc, char **argv);
59 static void print_usage(const char *argv);
60
61 static void worker_thread(void);
62
63
64 int main(int argc, char **argv) {
65     int port;
66     int client_socket, server_socket;
67     struct sockaddr_in6 server_in;
68
69     size_t i;
70     pthread_t *threads;
71
72     struct sigaction action;
73
74     parse_arguments(argc, argv);
75
76     port = atoi(argv[argc - 1]);
77     if (0 >= port || 0xffff < port) {
78         print_usage(argv[0]);
79         fprintf(stderr, "\ninvalid port\n");
80         return EXIT_FAILURE;
81     }
82
83     /* Setup our SIGINT signal handler which allows a "normal" termination of
84      * the server. */
85     sigemptyset(&action.sa_mask);
86     action.sa_handler = sigint_handler;
87     action.sa_flags   = 0;
88     sigaction(SIGINT, &action, NULL);
89     /* Ignore SIGPIPEs. */
90     action.sa_handler = SIG_IGN;
91     sigaction(SIGPIPE, &action, NULL);
92
93     /* Initialize ring buffer. */
94     ringbuffer_read  = 0;
95     ringbuffer_write = 0;
96     ringbuffer_full  = sem_init(0);
97     ringbuffer_free  = sem_init(RINGBUFFER_SIZE);
98     ringbuffer_lock  = sem_init(1);
99     if (NULL == ringbuffer_full
100             || NULL == ringbuffer_free
101             || NULL == ringbuffer_lock) {
102         perror("sem_init()");
103         return EXIT_FAILURE;
104     }
105
106     /* Spawn worker threads to handle requests. */
107     threads = (pthread_t *)malloc(thread_count * sizeof(pthread_t));
108     if (NULL == threads) {
109         perror("thread malloc failed");
110         return EXIT_FAILURE;
111     }
112     for (i = 0; i < thread_count; i++) {
113         int result;
114         pthread_t thread;
115
116         result = pthread_create(&thread, NULL,
117                                 (void * (*)(void *))&worker_thread,
118                                 NULL);
119         if (0 != result) {
120             printf("failed to create worker thread: %s\n", strerror(result));
121             return EXIT_FAILURE;
122         }
123
124         threads[i] = thread;
125     }
126
127     server_socket = socket(PF_INET6, SOCK_STREAM, 0);
128     if (-1 == server_socket) {
129         perror("socket()");
130         return EXIT_FAILURE;
131     }
132
133 #ifdef DEBUG
134     /* Fast rebinding for debug mode, could cause invalid packets. */
135     {
136         int socket_option = 1;
137         setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR,
138                    &socket_option, sizeof(socket_option));
139     }
140 #endif
141
142     /* Bind to the listen socket. */
143     memset(&server_in, 0, sizeof(server_in));
144     server_in.sin6_family = AF_INET6;              /* IPv6 (and IPv4) */
145     server_in.sin6_addr   = in6addr_any;           /* bind to any address */
146     server_in.sin6_port   = htons((uint16_t)port); /* port to bind to */
147     if (-1 == bind(server_socket, (struct sockaddr *)&server_in,
148                                   sizeof(server_in))) {
149         perror("bind()");
150         return EXIT_FAILURE;
151     }
152     /* And accept connections. */
153     if (-1 == listen(server_socket, 5)) {
154         perror("listen()");
155         return EXIT_FAILURE;
156     }
157
158     if (LOG_DEBUG <= global_log_level) {
159         printf("Listening for connections on port %d.\n", port);
160
161         if (NULL != global_proxy_host && NULL != global_proxy_port) {
162             printf("Using proxy: %s:%s.\n", global_proxy_host,
163                                             global_proxy_port);
164         }
165     }
166
167     while (!done) {
168         /* Accept new connection. */
169         client_socket = accept(server_socket, NULL, NULL);
170         if (-1 == client_socket) {
171             perror("accept()");
172             break;
173         }
174
175         /* No lock, we only have one producer! */
176         P(ringbuffer_free);
177         ringbuffer[ringbuffer_write] = client_socket;
178         ringbuffer_write = (ringbuffer_write + 1) % RINGBUFFER_SIZE;
179         V(ringbuffer_full);
180     }
181
182     close(server_socket);
183
184     /* Poison all threads and shut them down. */
185     for (i = 0; i < thread_count; i++) {
186         P(ringbuffer_free);
187         ringbuffer[ringbuffer_write] = -1; /* poison */
188         ringbuffer_write = (ringbuffer_write + 1) % RINGBUFFER_SIZE;
189         V(ringbuffer_full);
190     }
191     for (i = 0; i < thread_count; i++) {
192         errno = pthread_join(threads[i], NULL);
193         if (0 != errno) {
194             perror("pthread_join()");
195             continue;
196         }
197     }
198
199     free(ringbuffer_full);
200     free(ringbuffer_free);
201     free(ringbuffer_lock);
202
203     free(threads);
204
205     free(global_proxy_host);
206     free(global_proxy_port);
207
208     return EXIT_FAILURE;
209 }
210
211 static void sigint_handler(int signal_number) {
212     (void)signal_number;
213
214     done = 1;
215 }
216
217 static void parse_arguments(int argc, char **argv) {
218     int option;
219
220     /* Default values. */
221     thread_count = 10;
222 #ifdef DEBUG
223     global_log_level = LOG_DEBUG;
224 #else
225     global_log_level = LOG_WARNING;
226 #endif
227
228     while (-1 != (option = getopt(argc, argv, "d:p:t:h?"))) {
229         switch (option) {
230             case 'd': {
231                 if (0 > atoi(optarg)) {
232                     print_usage(argv[0]);
233                     fprintf(stderr, "\n-d positive number required\n");
234                     exit(EXIT_FAILURE);
235                 }
236                 global_log_level = atoi(optarg);
237                 break;
238             }
239             case 'p': {
240                 char *position;
241
242                 /* -p must have the format host:port. */
243                 if (NULL == (position = strchr(optarg, ':'))
244                         || position == optarg
245                         || 0 == strlen(position + 1)
246                         || 0 >= atoi(position + 1)
247                         || 0xffff < atoi(position + 1)) {
248                     print_usage(argv[0]);
249                     fprintf(stderr, "\ninvalid -p, format host:port\n");
250                     exit(EXIT_FAILURE);
251                 }
252
253                 global_proxy_host = malloc((size_t)(position - optarg) + 1);
254                 if (NULL == global_proxy_host) {
255                     perror("malloc()");
256                     exit(EXIT_FAILURE);
257                 }
258                 memcpy(global_proxy_host, optarg, (size_t)(position - optarg));
259                 global_proxy_host[position - optarg] = '\0';
260
261                 global_proxy_port = malloc(strlen(position + 1) + 1);
262                 if (NULL == global_proxy_port) {
263                     perror("malloc()");
264                     exit(EXIT_FAILURE);
265                 }
266                 strcpy(global_proxy_port, position + 1);
267
268                 break;
269             }
270             case 't': {
271                 if (0 >= atoi(optarg)) {
272                     print_usage(argv[0]);
273                     fprintf(stderr, "\n-t positive number required\n");
274                     exit(EXIT_FAILURE);
275                 }
276                 thread_count = (size_t)atoi(optarg);
277                 break;
278             }
279             case 'h':
280             default: /* '?' */
281                 print_usage(argv[0]);
282                 exit(EXIT_FAILURE);
283         }
284     }
285
286     if (optind >= argc) {
287         print_usage(argv[0]);
288         fprintf(stderr, "\nport missing\n");
289         exit(EXIT_FAILURE);
290     }
291 }
292 static void print_usage(const char *argv) {
293     fprintf(stderr, "Usage: %s [-d level] [-p host:port] [-t count] port\n",
294                     argv);
295     fprintf(stderr, "\n");
296     fprintf(stderr, "-d debug level: 0=errors only, 2=debug [default: 1]\n");
297     fprintf(stderr, "-p proxy hostname and port\n");
298     fprintf(stderr, "-t number of threads [default: 10]\n");
299 }
300
301 static void worker_thread(void) {
302     int client_socket;
303
304     for (;;) {
305         /* Get next element from ring buffer. */
306         P(ringbuffer_full);
307         P(ringbuffer_lock);
308         client_socket = ringbuffer[ringbuffer_read];
309         ringbuffer_read = (ringbuffer_read + 1) % RINGBUFFER_SIZE;
310         V(ringbuffer_lock);
311         V(ringbuffer_free);
312
313         /* Negative value indicates we should shut down our thread. */
314         if (0 > client_socket) {
315             break;
316         }
317
318         handle_connection(client_socket);
319     }
320 }