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