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