2 * tlsproxy is a transparent TLS proxy for HTTPS connections.
4 * Copyright (C) 2011 Simon Ruderich
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.
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.
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/>.
24 /* socket(), bind(), accept(), listen() */
25 #include <sys/types.h>
26 #include <sys/socket.h>
30 #include <arpa/inet.h>
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
51 /* Size of ringbuffer. */
52 #define RINGBUFFER_SIZE 10
55 /* Server should shut down. Set by SIGINT handler. */
56 static volatile int done;
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;
72 static void sigint_handler(int signal);
74 static void parse_arguments(int argc, char **argv);
75 static void print_usage(const char *argv);
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);
83 static void transfer_data(int client, int server);
84 static int read_from_write_to(int from, int to);
86 static int connect_to_host(const char *hostname, const char *port);
88 static int parse_request(const char *buffer, char *host, char *port,
92 int main(int argc, char **argv) {
94 int client_socket, server_socket;
95 struct sockaddr_in6 server_in;
100 struct sigaction action;
102 parse_arguments(argc, argv);
104 port = atoi(argv[argc - 1]);
105 if (0 >= port || 0xffff < port) {
106 print_usage(argv[0]);
107 fprintf(stderr, "\ninvalid port");
111 /* Setup our SIGINT signal handler which allows a "normal" termination of
113 sigemptyset(&action.sa_mask);
114 action.sa_handler = sigint_handler;
116 sigaction(SIGINT, &action, NULL);
118 /* Initialize ring buffer. */
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()");
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");
137 for (i = 0; i < thread_count; i++) {
141 result = pthread_create(&thread, NULL,
142 (void * (*)(void *))&worker_thread,
145 printf("failed to create worker thread: %s\n", strerror(result));
152 server_socket = socket(PF_INET6, SOCK_STREAM, 0);
153 if (-1 == server_socket) {
159 /* Fast rebinding for debug mode, could cause invalid packets. */
161 int socket_option = 1;
162 setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR,
163 &socket_option, sizeof(socket_option));
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))) {
177 /* And accept connections. */
178 if (-1 == listen(server_socket, 5)) {
184 printf("Listening for connections on port %d.\n", port);
186 if (NULL != use_proxy_host && NULL != use_proxy_port) {
187 printf("Using proxy: %s:%s.\n", use_proxy_host, use_proxy_port);
192 /* Accept new connection. */
193 client_socket = accept(server_socket, NULL, NULL);
194 if (-1 == client_socket) {
199 /* No lock, we only have one producer! */
201 ringbuffer[ringbuffer_write] = client_socket;
202 ringbuffer_write = (ringbuffer_write + 1) % RINGBUFFER_SIZE;
206 close(server_socket);
208 /* Poison all threads and shut them down. */
209 for (i = 0; i < thread_count; i++) {
211 ringbuffer[ringbuffer_write] = -1; /* poison */
212 ringbuffer_write = (ringbuffer_write + 1) % RINGBUFFER_SIZE;
215 for (i = 0; i < thread_count; i++) {
216 errno = pthread_join(threads[i], NULL);
218 perror("pthread_join()");
223 free(ringbuffer_full);
224 free(ringbuffer_free);
225 free(ringbuffer_lock);
229 free(use_proxy_host);
230 free(use_proxy_port);
235 static void sigint_handler(int signal_number) {
241 static void parse_arguments(int argc, char **argv) {
244 /* Default values. */
247 while (-1 != (option = getopt(argc, argv, "p:t:h?"))) {
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");
262 use_proxy_host = malloc((size_t)(position - optarg) + 1);
263 if (NULL == use_proxy_host) {
267 memcpy(use_proxy_host, optarg, (size_t)(position - optarg));
268 use_proxy_host[position - optarg] = '\0';
270 use_proxy_port = malloc(strlen(position + 1) + 1);
271 if (NULL == use_proxy_port) {
275 strcpy(use_proxy_port, position + 1);
280 if (0 >= atoi(optarg)) {
281 fprintf(stderr, "-t positive number required\n");
284 thread_count = (size_t)atoi(optarg);
289 print_usage(argv[0]);
294 if (optind >= argc) {
295 print_usage(argv[0]);
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");
306 static void worker_thread(void) {
310 /* Get next element from ring buffer. */
313 client_socket = ringbuffer[ringbuffer_read];
314 ringbuffer_read = (ringbuffer_read + 1) % RINGBUFFER_SIZE;
318 /* Negative value indicates we should shut down our thread. */
319 if (client_socket < 0) {
323 handle_connection(client_socket);
327 static void handle_connection(int client_socket) {
329 FILE *client_fd, *server_fd;
331 char buffer[MAX_REQUEST_LINE];
332 char host[MAX_REQUEST_LINE];
338 client_fd = fdopen(client_socket, "a+");
339 if (NULL == client_fd) {
341 close(client_socket);
346 printf("New connection:\n");
349 /* Read request line (CONNECT ..) and headers (they are discarded). */
350 result = read_http_request(client_fd, buffer, sizeof(buffer));
354 } else if (result == -2) {
356 send_close_bad_request(client_fd);
361 printf(" request: %s", buffer);
364 if (0 != parse_request(buffer, host, port, &version_minor)) {
365 send_close_bad_request(client_fd);
367 printf(" bad request\n");
373 printf(" %s:%s (HTTP 1.%d)\n", host, port, version_minor);
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);
380 server_socket = connect_to_host(host, port);
383 if (-1 == server_socket) {
384 send_close_forwarding_failure(client_fd);
387 server_fd = fdopen(server_socket, "a+");
388 if (NULL == server_fd) {
389 send_close_forwarding_failure(client_fd);
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");
398 /* Read response line from proxy server. */
399 result = read_http_request(server_fd, buffer, sizeof(buffer));
402 send_close_forwarding_failure(client_fd);
404 } else if (result == -2) {
407 send_close_forwarding_failure(client_fd);
411 /* Check response of proxy server. */
412 if (0 != strncmp(buffer, "HTTP/1.0 200", 12)) {
414 printf(" bad proxy response\n");
417 send_close_forwarding_failure(client_fd);
423 printf(" connection to server established\n");
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");
431 /* And transfer all data between client and server transparently. */
432 transfer_data(client_socket, server_socket);
438 /* Read HTTP request line and headers (ignored).
440 * On success 0 is returned, -1 on client error (we close client descriptor in
441 * this case), -2 on unexpected EOF.
443 static int read_http_request(FILE *client_fd, char *request, size_t length) {
444 char buffer[MAX_REQUEST_LINE];
446 if (NULL == fgets(request, (int)length, client_fd)) {
447 if (ferror(client_fd)) {
448 perror("fgets(), request");
456 while (NULL != fgets(buffer, MAX_REQUEST_LINE, client_fd)) {
458 if (0 == strcmp(buffer, "\n") || 0 == strcmp(buffer, "\r\n")) {
462 if (ferror(client_fd)) {
463 perror("fgets(), header");
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");
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");
483 /* Transfer data between client and server sockets until one closes the
485 static void transfer_data(int client, int server) {
486 struct pollfd fds[2];
488 fds[0].events = POLLIN | POLLPRI | POLLHUP | POLLERR;
491 fds[1].events = POLLIN | POLLPRI | POLLHUP | POLLERR;
495 int result = poll(fds, 2, -1 /* no timeout */);
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) */
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) */
516 /* Client closed connection. */
517 if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
520 /* Server closed connection. */
521 if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
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) {
531 ssize_t size_written;
534 size_read = read(from, buffer, sizeof(buffer));
540 if (0 == size_read) {
544 size_written = write(to, buffer, (size_t)size_read);
545 if (0 > size_written) {
549 if (size_read != size_written) {
550 printf("only written %ld of %ld bytes!\n", (long int)size_read,
551 (long int)size_written);
559 static int connect_to_host(const char *hostname, const char *port) {
560 struct addrinfo gai_hints;
561 struct addrinfo *gai_result;
565 struct addrinfo *server;
567 if (NULL == hostname || NULL == port) {
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()");
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,
590 server->ai_protocol);
591 if (-1 == server_socket) {
592 perror("socket(), trying next");
596 if (-1 != connect(server_socket, server->ai_addr,
597 server->ai_addrlen)) {
600 perror("connect(), trying next");
602 close(server_socket);
604 /* Make sure we free the result from getaddrinfo(). */
605 freeaddrinfo(gai_result);
607 if (NULL == server) {
608 fprintf(stderr, "no server found, aborting\n");
612 return server_socket;
616 /* Parse HTTP CONNECT request string and save its parameters.
618 * The following format is expected: "CONNECT host:port HTTP/1.y".
620 * request and host must have the same size! port must be at least 6 bytes
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 */
628 /* scanf() doesn't check spaces. */
629 if (0 != strncmp(request, "CONNECT ", 8)) {
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)) {
637 /* Make sure ":port" is there. */
638 if (NULL == (position = strchr(host, ':'))) {
641 /* Make sure port is numeric. */
642 if (1 != sscanf(position + 1, "%d", &port_unused)) {
645 /* Store it in *port. */
646 strncpy(port, position + 1, 5);
648 /* And remove port from host. */