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/>.
22 /* socket(), bind(), accept(), listen() */
23 #include <sys/types.h>
24 #include <sys/socket.h>
28 #include <arpa/inet.h>
41 /* Maximum line of the request line. Longer request lines are aborted with an
42 * error. The standard doesn't specify a maximum line length but this should
43 * be a good limit to make processing simpler. */
44 #define MAX_REQUEST_LINE 4096
47 /* Server should shut down. Set by SIGINT handler. */
48 static volatile int done;
50 /* Proxy hostname and port if specified on the command line. */
51 static char *use_proxy_host;
52 static char *use_proxy_port;
55 static void sigint_handler(int signal);
57 static void parse_arguments(int argc, char **argv);
58 static void print_usage(const char *argv);
60 static void handle_connection(int socket);
61 static int read_http_request(FILE *client_fd, char *request, size_t length);
62 static void send_close_bad_request(FILE *client_fd);
63 static void send_close_forwarding_failure(FILE *client_fd);
65 static void transfer_data(int client, int server);
66 static int read_from_write_to(int from, int to);
68 static int connect_to_host(const char *hostname, const char *port);
70 static int parse_request(const char *buffer, char *host, char *port,
74 int main(int argc, char **argv) {
76 int client_socket, server_socket;
77 struct sockaddr_in6 server_in;
79 struct sigaction action;
81 parse_arguments(argc, argv);
83 port = atoi(argv[argc - 1]);
84 if (0 >= port || 0xffff < port) {
86 fprintf(stderr, "\ninvalid port");
90 /* Setup our SIGINT signal handler which allows a "normal" termination of
92 sigemptyset(&action.sa_mask);
93 action.sa_handler = sigint_handler;
95 sigaction(SIGINT, &action, NULL);
97 server_socket = socket(PF_INET6, SOCK_STREAM, 0);
98 if (-1 == server_socket) {
104 /* Fast rebinding for debug mode, could cause invalid packets. */
106 int socket_option = 1;
107 setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR,
108 &socket_option, sizeof(socket_option));
112 /* Bind to the listen socket. */
113 memset(&server_in, 0, sizeof(server_in));
114 server_in.sin6_family = AF_INET6; /* IPv6 (and IPv4) */
115 server_in.sin6_addr = in6addr_any; /* bind to any address */
116 server_in.sin6_port = htons((uint16_t)port); /* port to bind to */
117 if (-1 == bind(server_socket, (struct sockaddr *)&server_in,
118 sizeof(server_in))) {
122 /* And accept connections. */
123 if (-1 == listen(server_socket, 5)) {
129 printf("Listening for connections on port %d.\n", port);
131 if (NULL != use_proxy_host && NULL != use_proxy_port) {
132 printf("Using proxy: %s:%s.\n", use_proxy_host, use_proxy_port);
137 /* Accept new connection. */
138 client_socket = accept(server_socket, NULL, NULL);
139 if (-1 == client_socket) {
144 handle_connection(client_socket);
147 close(server_socket);
149 free(use_proxy_host);
150 free(use_proxy_port);
155 static void sigint_handler(int signal_number) {
161 static void parse_arguments(int argc, char **argv) {
164 while (-1 != (option = getopt(argc, argv, "p:h?"))) {
169 /* -p must have the format host:port. */
170 if (NULL == (position = strchr(optarg, ':'))
171 || position == optarg
172 || 0 == strlen(position + 1)
173 || 0 >= atoi(position + 1)
174 || 0xffff < atoi(position + 1)) {
175 fprintf(stderr, "-p host:port\n");
179 use_proxy_host = malloc((size_t)(position - optarg) + 1);
180 if (NULL == use_proxy_host) {
184 memcpy(use_proxy_host, optarg, (size_t)(position - optarg));
185 use_proxy_host[position - optarg] = '\0';
187 use_proxy_port = malloc(strlen(position + 1) + 1);
188 if (NULL == use_proxy_port) {
192 strcpy(use_proxy_port, position + 1);
198 print_usage(argv[0]);
203 if (optind >= argc) {
204 print_usage(argv[0]);
208 static void print_usage(const char *argv) {
209 fprintf(stderr, "Usage: %s [-p host:port] port\n", argv);
210 fprintf(stderr, "\n");
211 fprintf(stderr, "-p proxy hostname and port\n");
214 static void handle_connection(int client_socket) {
216 FILE *client_fd, *server_fd;
218 char buffer[MAX_REQUEST_LINE];
219 char host[MAX_REQUEST_LINE];
225 client_fd = fdopen(client_socket, "a+");
226 if (NULL == client_fd) {
228 close(client_socket);
233 printf("New connection:\n");
236 /* Read request line (CONNECT ..) and headers (they are discarded). */
237 result = read_http_request(client_fd, buffer, sizeof(buffer));
241 } else if (result == -2) {
243 send_close_bad_request(client_fd);
248 printf(" request: %s", buffer);
251 if (0 != parse_request(buffer, host, port, &version_minor)) {
252 send_close_bad_request(client_fd);
254 printf(" bad request\n");
260 printf(" %s:%s (HTTP 1.%d)\n", host, port, version_minor);
263 /* Connect to proxy server or directly to server. */
264 if (NULL != use_proxy_host && NULL != use_proxy_port) {
265 server_socket = connect_to_host(use_proxy_host, use_proxy_port);
267 server_socket = connect_to_host(host, port);
270 if (-1 == server_socket) {
271 send_close_forwarding_failure(client_fd);
274 server_fd = fdopen(server_socket, "a+");
275 if (NULL == server_fd) {
276 send_close_forwarding_failure(client_fd);
280 /* Connect to proxy if requested (command line option). */
281 if (NULL != use_proxy_host && NULL != use_proxy_port) {
282 fprintf(server_fd, "CONNECT %s:%s HTTP/1.0\r\n", host, port);
283 fprintf(server_fd, "\r\n");
285 /* Read response line from proxy server. */
286 result = read_http_request(server_fd, buffer, sizeof(buffer));
289 send_close_forwarding_failure(client_fd);
291 } else if (result == -2) {
294 send_close_forwarding_failure(client_fd);
298 /* Check response of proxy server. */
299 if (0 != strncmp(buffer, "HTTP/1.0 200", 12)) {
301 printf(" bad proxy response\n");
304 send_close_forwarding_failure(client_fd);
310 printf(" connection to server established\n");
313 /* We've established a connection, tell the client. */
314 fprintf(client_fd, "HTTP/1.0 200 Connection established\r\n");
315 fprintf(client_fd, "\r\n");
318 /* And transfer all data between client and server transparently. */
319 transfer_data(client_socket, server_socket);
325 /* Read HTTP request line and headers (ignored).
327 * On success 0 is returned, -1 on client error (we close client descriptor in
328 * this case), -2 on unexpected EOF.
330 static int read_http_request(FILE *client_fd, char *request, size_t length) {
331 char buffer[MAX_REQUEST_LINE];
333 if (NULL == fgets(request, (int)length, client_fd)) {
334 if (ferror(client_fd)) {
335 perror("fgets(), request");
343 while (NULL != fgets(buffer, MAX_REQUEST_LINE, client_fd)) {
345 if (0 == strcmp(buffer, "\n") || 0 == strcmp(buffer, "\r\n")) {
349 if (ferror(client_fd)) {
350 perror("fgets(), header");
358 static void send_close_bad_request(FILE *client_fd) {
359 fprintf(client_fd, "HTTP/1.0 400 Bad Request\r\n");
360 fprintf(client_fd, "\r\n");
363 static void send_close_forwarding_failure(FILE *client_fd) {
364 fprintf(client_fd, "HTTP/1.0 503 Forwarding failure\r\n");
365 fprintf(client_fd, "\r\n");
370 /* Transfer data between client and server sockets until one closes the
372 static void transfer_data(int client, int server) {
373 struct pollfd fds[2];
375 fds[0].events = POLLIN | POLLPRI | POLLHUP | POLLERR;
378 fds[1].events = POLLIN | POLLPRI | POLLHUP | POLLERR;
382 int result = poll(fds, 2, 0);
388 /* Data available from client. */
389 if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
390 if (0 != read_from_write_to(client, server)) {
391 /* EOF (or other error) */
395 /* Data available from server. */
396 if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
397 if (0 != read_from_write_to(server, client)) {
398 /* EOF (or other error) */
403 /* Client closed connection. */
404 if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
407 /* Server closed connection. */
408 if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
414 /* Read available data from socket from and write it to socket to. At maximum
415 * 4096 bytes are read/written. */
416 static int read_from_write_to(int from, int to) {
418 ssize_t size_written;
421 size_read = read(from, buffer, sizeof(buffer));
427 if (0 == size_read) {
431 size_written = write(to, buffer, (size_t)size_read);
432 if (0 > size_written) {
436 if (size_read != size_written) {
437 printf("only written %ld of %ld bytes!\n", (long int)size_read,
438 (long int)size_written);
446 static int connect_to_host(const char *hostname, const char *port) {
447 struct addrinfo gai_hints;
448 struct addrinfo *gai_result;
452 struct addrinfo *server;
454 if (NULL == hostname || NULL == port) {
458 /* Get IP of hostname server. */
459 memset(&gai_hints, 0, sizeof(gai_hints));
460 gai_hints.ai_family = AF_UNSPEC;
461 gai_hints.ai_socktype = SOCK_STREAM;
462 gai_hints.ai_protocol = 0;
463 gai_hints.ai_flags = AI_NUMERICSERV /* given port is numeric */
464 | AI_ADDRCONFIG /* supported by this computer */
465 | AI_V4MAPPED; /* support IPv4 through IPv6 */
466 gai_return = getaddrinfo(hostname, port, &gai_hints, &gai_result);
467 if (0 != gai_return) {
468 perror("getaddrinfo()");
472 /* Now try to connect to each server returned by getaddrinfo(), use the
473 * first successful connect. */
474 for (server = gai_result; NULL != server; server = server->ai_next) {
475 server_socket = socket(server->ai_family,
477 server->ai_protocol);
478 if (-1 == server_socket) {
479 perror("socket(), trying next");
483 if (-1 != connect(server_socket, server->ai_addr,
484 server->ai_addrlen)) {
487 perror("connect(), trying next");
489 close(server_socket);
491 /* Make sure we free the result from getaddrinfo(). */
492 freeaddrinfo(gai_result);
494 if (NULL == server) {
495 fprintf(stderr, "no server found, aborting\n");
499 return server_socket;
503 /* Parse HTTP CONNECT request string and save its parameters.
505 * The following format is expected: "CONNECT host:port HTTP/1.y".
507 * request and host must have the same size! port must be at least 6 bytes
510 static int parse_request(const char *request, char *host, char *port,
511 int *version_minor) {
512 int port_unused; /* just used to verify the port is numeric */
515 /* scanf() doesn't check spaces. */
516 if (0 != strncmp(request, "CONNECT ", 8)) {
519 /* Check request and extract data, "host:port" is not yet separated. */
520 if (2 != sscanf(request, "CONNECT %s HTTP/1.%d",
521 host, version_minor)) {
524 /* Make sure ":port" is there. */
525 if (NULL == (position = strchr(host, ':'))) {
528 /* Make sure port is numeric. */
529 if (1 != sscanf(position + 1, "%d", &port_unused)) {
532 /* Store it in *port. */
533 strncpy(port, position + 1, 5);
535 /* And remove port from host. */