]> ruderich.org/simon Gitweb - tlsproxy/tlsproxy.git/blob - connection.c
c91eae358e6a3b7cfa44376afba42c928e96ff6b
[tlsproxy/tlsproxy.git] / connection.c
1 /*
2  * Handle connections.
3  *
4  * Copyright (C) 2011-2013  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 "connection.h"
22 #include "verify.h"
23
24 #include <assert.h>
25 #include <errno.h>
26 #include <limits.h>
27 #include <netdb.h>
28 #include <poll.h>
29 #include <unistd.h>
30
31
32 /* Maximum length of a HTTP request line. Longer request lines are aborted
33  * with an error. The standard doesn't specify a maximum line length but this
34  * should be a good limit to make processing simpler. As HTTPS is used this
35  * doesn't limit long GET requests. */
36 #define MAX_REQUEST_LINE 4096
37
38 /* Format string used to send HTTP/1.0 error responses to the client.
39  *
40  * %s is used 5 times, first is the error code, then additional headers, next
41  * two are the error code (no %n$s!), the last is the message. */
42 #define HTTP_RESPONSE_FORMAT "HTTP/1.0 %s\r\n\
43 Content-Type: text/html; charset=US-ASCII\r\n\
44 %s\r\n\
45 <!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n\
46 <html>\n\
47 <head><title>%s</title></head>\n\
48 <body>\n\
49 <h1>%s</h1>\n\
50 <p>%s</p>\n\
51 </body>\n\
52 </html>\n"
53
54
55 static int initialize_tls_session_client(int peer_socket,
56         const char *hostname,
57         gnutls_session_t *session,
58         gnutls_certificate_credentials_t *x509_cred);
59 static int initialize_tls_session_server(int peer_socket,
60         gnutls_session_t *session,
61         gnutls_certificate_credentials_t *x509_cred);
62 static int initialize_tls_session_both(unsigned int flags,
63         int peer_socket,
64         gnutls_session_t *session,
65         gnutls_certificate_credentials_t *x509_cred);
66
67 static int fdopen_read_write(int socket, FILE **read_fd, FILE **write_fd);
68 static int read_http_request(FILE *client_fd, char *request, size_t length);
69 static void send_bad_request(FILE *client_fd);
70 static void send_authentication_required(FILE *client_fd);
71 static void send_forwarding_failure(FILE *client_fd);
72 static void tls_send_invalid_cert_message(gnutls_session_t session);
73
74 static void transfer_data(int client, int server);
75 static int read_from_write_to(int from, int to);
76 static void transfer_data_tls(int client, int server,
77                               gnutls_session_t client_session,
78                               gnutls_session_t server_session);
79 static int read_from_write_to_tls(gnutls_session_t from, gnutls_session_t to,
80                                   size_t buffer_size);
81
82 static int connect_to_host(const char *hostname, const char *port);
83
84 static int parse_request(const char *buffer, char *host, char *port,
85                                              int *version_minor);
86
87
88 void handle_connection(int client_socket) {
89     int server_socket;
90     FILE *client_fd_read, *client_fd_write, *server_fd_read, *server_fd_write;
91
92     char buffer[MAX_REQUEST_LINE];
93     char host[MAX_REQUEST_LINE];
94     char port[5 + 1];
95
96     int version_minor; /* x in HTTP/1.x */
97     int result;
98
99     /* client_x509_cred is used when talking to the client (acting as a TSL
100      * server), server_x509_cred is used when talking to the server (acting as
101      * a TSL client). */
102     gnutls_certificate_credentials_t client_x509_cred, server_x509_cred;
103
104     gnutls_session_t client_session, server_session;
105     /* initialize_tls_session_*() called? - used for goto out */
106     int client_session_init, server_session_init;
107     /* gnutls_handshake() called? - used for goto out */
108     int client_session_started, server_session_started;
109     /* Validation failed? If yes we need to send the special "invalid"
110      * certificate. */
111     int validation_failed;
112
113     LOG(DEBUG1, "new connection");
114
115     server_socket = -1;
116     client_fd_read = NULL;
117     client_fd_write = NULL;
118     server_fd_read = NULL;
119     server_fd_write = NULL;
120     client_session_init = 0;
121     server_session_init = 0;
122     client_session_started = 0;
123     server_session_started = 0;
124     validation_failed = 0;
125
126     if (fdopen_read_write(client_socket, &client_fd_read,
127                                          &client_fd_write) != 0) {
128         goto out;
129     }
130
131     /* Read request line (CONNECT ..) and headers (they are discarded). */
132     result = read_http_request(client_fd_read, buffer, sizeof(buffer));
133     if (result == -1) {
134         LOG(WARNING, "read_http_request(): client read error");
135         goto out;
136     } else if (result == -2) {
137         LOG(WARNING, "read_http_request(): client EOF");
138         send_bad_request(client_fd_write);
139         goto out;
140     } else if (result == -3) {
141         LOG(DEBUG1, "read_http_request(): proxy authentication failed");
142         send_authentication_required(client_fd_write);
143         goto out;
144     }
145
146     if (parse_request(buffer, host, port, &version_minor) != 0) {
147         LOG(WARNING, "bad request: >%s<", buffer);
148         send_bad_request(client_fd_write);
149         goto out;
150     }
151
152     LOG(DEBUG1, "target: %s:%s (HTTP 1.%d)", host, port, version_minor);
153
154     /* Connect to proxy server or directly to server. */
155     if (global_proxy_host != NULL && global_proxy_port != NULL) {
156         LOG(DEBUG1, "connecting to %s:%s", global_proxy_host,
157                                            global_proxy_port);
158         server_socket = connect_to_host(global_proxy_host, global_proxy_port);
159     } else {
160         LOG(DEBUG1, "connecting to %s:%s", host, port);
161         server_socket = connect_to_host(host, port);
162     }
163
164     if (server_socket < 0) {
165         LOG(WARNING, "failed to connect to server");
166         send_forwarding_failure(client_fd_write);
167         goto out;
168     }
169     if (fdopen_read_write(server_socket, &server_fd_read,
170                                          &server_fd_write) != 0) {
171         send_forwarding_failure(client_fd_write);
172         goto out;
173     }
174
175     /* Connect to proxy if requested (command line option). */
176     if (global_proxy_host != NULL && global_proxy_port != NULL) {
177         fprintf(server_fd_write, "CONNECT %s:%s HTTP/1.0\r\n", host, port);
178         fprintf(server_fd_write, "\r\n");
179         fflush(server_fd_write);
180
181         /* Read response line from proxy server. */
182         result = read_http_request(server_fd_read, buffer, sizeof(buffer));
183         if (result == -1) {
184             LOG(WARNING, "read_http_request(): proxy read error");
185             send_forwarding_failure(client_fd_write);
186             goto out;
187         } else if (result == -2) {
188             LOG(WARNING, "read_http_request(): proxy EOF");
189             send_forwarding_failure(client_fd_write);
190             goto out;
191         }
192
193         /* Check response of proxy server. */
194         if (strncmp(buffer, "HTTP/1.0 200", 12)) {
195             LOG(WARNING, "bad proxy response: %s", buffer);
196             send_forwarding_failure(client_fd_write);
197             goto out;
198         }
199     }
200
201     LOG(DEBUG1, "connection to server established");
202
203     /* If the -u option is used and we don't know this hostname's server
204      * certificate then just pass through the connection and let the client
205      * verify the server certificate. */
206     if (global_passthrough_unknown) {
207         char path[TLSPROXY_MAX_PATH_LENGTH];
208         FILE *file = NULL;
209
210         if (server_certificate_file(&file, host, path, sizeof(path)) == -2) {
211             /* We've established a connection, tell the client. */
212             fprintf(client_fd_write, "HTTP/1.0 200 Connection established\r\n");
213             fprintf(client_fd_write, "\r\n");
214             fflush(client_fd_write);
215
216             LOG(DEBUG1, "transferring data");
217
218             /* Proxy data between client and server until one side is done
219              * (EOF or error). */
220             transfer_data(client_socket, server_socket);
221
222             LOG(DEBUG1, "finished transferring data");
223
224             goto out;
225         }
226         /* server_certificate_file() may have opened the file, close it. */
227         if (file != NULL) {
228             fclose(file);
229         }
230     }
231
232     /* Initialize TLS client credentials to talk to the server. */
233     result = initialize_tls_session_server(server_socket, &server_session,
234                                                           &server_x509_cred);
235     if (result != 0) {
236         LOG(WARNING, "initialize_tls_session_server() failed");
237         send_forwarding_failure(client_fd_write);
238         goto out;
239     }
240     server_session_init = 1;
241
242     LOG(DEBUG1, "starting server TLS handshake");
243
244     /* Try to establish TLS handshake between us and server. */
245     result = gnutls_handshake(server_session);
246     if (result != GNUTLS_E_SUCCESS) {
247         LOG(WARNING, "server TLS handshake failed: %s",
248                      gnutls_strerror(result));
249         send_forwarding_failure(client_fd_write);
250         goto out;
251     }
252     server_session_started = 1;
253
254     LOG(DEBUG1, "server TLS handshake finished");
255
256     /* Make sure the server certificate is valid and known. */
257     if (verify_tls_connection(server_session, host) != 0) {
258         LOG(ERROR, "server certificate validation failed!");
259         /* We'll send the error message over our TLS connection to the client,
260          * but with an invalid certificate. No data is transfered from/to the
261          * target server. */
262         validation_failed = 1;
263     }
264
265     /* Initialize TLS server credentials to talk to the client. */
266     result = initialize_tls_session_client(client_socket,
267                                            /* use a special host if the server
268                                             * certificate was invalid */
269                                            (validation_failed) ? "invalid"
270                                                                : host,
271                                            &client_session,
272                                            &client_x509_cred);
273     if (result != 0) {
274         LOG(WARNING, "initialize_tls_session_client() failed");
275         send_forwarding_failure(client_fd_write);
276         goto out;
277     }
278     client_session_init = 1;
279
280     /* We've established a connection, tell the client. */
281     fprintf(client_fd_write, "HTTP/1.0 200 Connection established\r\n");
282     fprintf(client_fd_write, "\r\n");
283     fflush(client_fd_write);
284
285     LOG(DEBUG1, "starting client TLS handshake");
286
287     /* Try to establish TLS handshake between client and us. */
288     result = gnutls_handshake(client_session);
289     if (result != GNUTLS_E_SUCCESS) {
290         LOG(WARNING, "client TLS handshake failed: %s",
291                      gnutls_strerror(result));
292         send_forwarding_failure(client_fd_write);
293         goto out;
294     }
295     client_session_started = 1;
296
297     LOG(DEBUG1, "client TLS handshake finished");
298
299     /* Tell the client that the verification failed. Shouldn't be necessary as
300      * the client should terminate the connection because he received the
301      * invalid certificate but better be sure. */
302     if (validation_failed) {
303         tls_send_invalid_cert_message(client_session);
304         goto out;
305     }
306
307     LOG(DEBUG1, "transferring TLS data");
308
309     /* Proxy data between client and server until one side is done (EOF or
310      * error). */
311     transfer_data_tls(client_socket, server_socket,
312                       client_session, server_session);
313
314     LOG(DEBUG1, "finished transferring TLS data");
315
316 out:
317     /* Close TLS sessions if necessary. Use GNUTLS_SHUT_RDWR so the data is
318      * reliable transmitted. */
319     if (server_session_started) {
320         /* Recent gnutls-serv (used in the test-suite) won't terminate the
321          * connection when gnutls_bye(session, GNUTLS_SHUT_RDWR) is used
322          * before any other data was received. If the validation failed just
323          * close the connection without waiting for data, we won't read it
324          * anyway.
325          *
326          * For verified connections GNUTLS_SHUT_RDWR is important or we might
327          * lose data. */
328         gnutls_bye(server_session, validation_failed ? GNUTLS_SHUT_WR
329                                                      : GNUTLS_SHUT_RDWR);
330     }
331     if (client_session_started) {
332         gnutls_bye(client_session, GNUTLS_SHUT_RDWR);
333     }
334     if (server_session_init) {
335         gnutls_deinit(server_session);
336         gnutls_certificate_free_credentials(server_x509_cred);
337     }
338     if (client_session_init) {
339         gnutls_deinit(client_session);
340         gnutls_certificate_free_cas(client_x509_cred);
341         gnutls_certificate_free_keys(client_x509_cred);
342         gnutls_certificate_free_credentials(client_x509_cred);
343     }
344
345     /* Close connection to server/proxy. */
346     if (server_fd_read != NULL) {
347         if (server_fd_write != NULL) {
348             fclose(server_fd_write);
349         }
350         fclose(server_fd_read);
351     } else if (server_socket != -1) {
352         close(server_socket);
353     }
354     LOG(DEBUG1, "connection to server closed");
355     /* Close connection to client. */
356     if (client_fd_read != NULL) {
357         if (client_fd_write != NULL) {
358             fclose(client_fd_write);
359         }
360         fclose(client_fd_read);
361     } else {
362         close(client_socket);
363     }
364     LOG(DEBUG1, "connection to client closed");
365
366     LOG(DEBUG1, "connection finished");
367 }
368
369
370 static int initialize_tls_session_client(int peer_socket,
371         const char *hostname,
372         gnutls_session_t *session,
373         gnutls_certificate_credentials_t *x509_cred) {
374     int result;
375     int use_invalid_cert;
376     char path[TLSPROXY_MAX_PATH_LENGTH];
377
378     /* The "invalid" hostname is special. If it's used we send an invalid
379      * certificate to let the client know something is wrong. */
380     use_invalid_cert = (!strcmp(hostname, "invalid"));
381
382     if (proxy_certificate_path(hostname, path, sizeof(path)) != 0) {
383         LOG(ERROR,
384             "initialize_tls_session_client(): "
385             "failed to get proxy certificate path");
386         return -1;
387     }
388
389     result = gnutls_certificate_allocate_credentials(x509_cred);
390     if (result != GNUTLS_E_SUCCESS) {
391         LOG(ERROR,
392             "initialize_tls_session_client(): "
393             "gnutls_certificate_allocate_credentials(): %s",
394             gnutls_strerror(result));
395         return -1;
396     }
397
398     /* Load proxy CA file, this CA "list" is send to the client. */
399     if (!use_invalid_cert) {
400         result = gnutls_certificate_set_x509_trust_file(*x509_cred,
401                                                         PROXY_CA_PATH,
402                                                         GNUTLS_X509_FMT_PEM);
403         if (result <= 0) {
404             LOG(ERROR,
405                 "initialize_tls_session_client(): can't read CA file: '%s'",
406                 PROXY_CA_PATH);
407             gnutls_certificate_free_credentials(*x509_cred);
408             return -1;
409         } else if (result != 1) {
410             /* Must contain only one CA, our proxy CA. */
411             LOG(ERROR, "initialize_tls_session_client(): multiple CAs found");
412             gnutls_certificate_free_credentials(*x509_cred);
413             return -1;
414         }
415     }
416     /* If the invalid hostname was specified do nothing, we use a self-signed
417      * certificate in this case. */
418
419     /* And certificate for this website and proxy's private key. */
420     if (!use_invalid_cert) {
421         result = gnutls_certificate_set_x509_key_file(*x509_cred,
422                                                       path,
423                                                       PROXY_KEY_PATH,
424                                                       GNUTLS_X509_FMT_PEM);
425     /* If the invalid hostname was specified load our special "invalid"
426      * certificate. */
427     } else {
428         result = gnutls_certificate_set_x509_key_file(*x509_cred,
429                                                       PROXY_INVALID_CERT_PATH,
430                                                       PROXY_KEY_PATH,
431                                                       GNUTLS_X509_FMT_PEM);
432     }
433     if (result != GNUTLS_E_SUCCESS) {
434         LOG(ERROR,
435             "initialize_tls_session_client(): "
436             "can't read server certificate ('%s') or key file ('%s'): %s",
437             path, PROXY_KEY_PATH, gnutls_strerror(result));
438         gnutls_certificate_free_credentials(*x509_cred);
439         /* Could be a missing certificate. */
440         return -2;
441     }
442
443     gnutls_certificate_set_dh_params(*x509_cred, global_tls_dh_params);
444
445     return initialize_tls_session_both(GNUTLS_SERVER,
446                                        peer_socket, session, x509_cred);
447 }
448 static int initialize_tls_session_server(int peer_socket,
449         gnutls_session_t *session,
450         gnutls_certificate_credentials_t *x509_cred) {
451     int result;
452
453     result = gnutls_certificate_allocate_credentials(x509_cred);
454     if (result != GNUTLS_E_SUCCESS) {
455         LOG(ERROR,
456             "initialize_tls_session_server(): "
457             "gnutls_certificate_allocate_credentials(): %s",
458             gnutls_strerror(result));
459         return -1;
460     }
461
462     return initialize_tls_session_both(GNUTLS_CLIENT,
463                                        peer_socket, session, x509_cred);
464 }
465 static int initialize_tls_session_both(unsigned int flags,
466         int peer_socket,
467         gnutls_session_t *session,
468         gnutls_certificate_credentials_t *x509_cred) {
469     int result;
470
471     *session = NULL;
472
473     result = gnutls_init(session, flags);
474     if (result != GNUTLS_E_SUCCESS) {
475         LOG(ERROR,
476             "initialize_tls_session_both(): gnutls_init(): %s",
477             gnutls_strerror(result));
478         goto err;
479     }
480     result = gnutls_priority_set(*session, global_tls_priority_cache);
481     if (result != GNUTLS_E_SUCCESS) {
482         LOG(ERROR,
483             "initialize_tls_session_both(): gnutls_priority_set(): %s",
484             gnutls_strerror(result));
485         goto err;
486     }
487     result = gnutls_credentials_set(*session,
488                                     GNUTLS_CRD_CERTIFICATE, *x509_cred);
489     if (result != GNUTLS_E_SUCCESS) {
490         LOG(ERROR,
491             "initialize_tls_session_both(): gnutls_credentials_set(): %s",
492             gnutls_strerror(result));
493         goto err;
494     }
495
496 #ifdef HAVE_GNUTLS_TRANSPORT_SET_INT2
497     /* gnutls_transport_set_int() is a macro. */
498     gnutls_transport_set_int(*session, peer_socket);
499 #else
500     gnutls_transport_set_ptr(*session, (gnutls_transport_ptr_t)peer_socket);
501 #endif
502
503     return 0;
504
505 err:
506     if (*session) {
507         gnutls_deinit(*session);
508     }
509     gnutls_certificate_free_credentials(*x509_cred);
510     return -1;
511 }
512
513
514 static int fdopen_read_write(int socket, FILE **read_fd, FILE **write_fd) {
515     *read_fd = fdopen(socket, "r");
516     if (*read_fd == NULL) {
517         LOG_PERROR(WARNING, "fdopen_read_write(): fdopen(\"r\") failed");
518         return -1;
519     }
520
521     *write_fd = fdopen(dup(socket), "w");
522     if (*write_fd == NULL) {
523         LOG_PERROR(WARNING, "fdopen_read_write(): fdopen(\"w\") failed");
524         fclose(*read_fd);
525         *read_fd = NULL; /* "tell" caller read_fd is already closed */
526         return -1;
527     }
528
529     return 0;
530 }
531
532 /* Read HTTP request line and headers (ignored).
533  *
534  * On success 0 is returned, -1 on client error, -2 on unexpected EOF.
535  */
536 static int read_http_request(FILE *client_fd, char *request, size_t length) {
537     char buffer[MAX_REQUEST_LINE];
538     int found_proxy_authorization;
539
540     assert(length <= INT_MAX);
541     if (fgets(request, (int)length, client_fd) == NULL) {
542         if (ferror(client_fd)) {
543             LOG_PERROR(WARNING, "read_http_request(): fgets()");
544             return -1;
545         }
546         /* EOF */
547         return -2;
548     }
549
550     found_proxy_authorization = 0;
551     while (fgets(buffer, sizeof(buffer), client_fd) != NULL) {
552         const char *authentication = "Proxy-Authorization: Basic ";
553
554         if (global_http_digest_authorization != NULL
555                 && !strncmp(buffer, authentication, strlen(authentication))) {
556             found_proxy_authorization = 1;
557
558             /* Check if the passphrase matches. */
559             strtok(buffer, "\r\n");
560             if (strcmp(buffer + strlen(authentication),
561                        global_http_digest_authorization)) {
562                 return -3;
563             }
564         }
565
566         /* End of header. */
567         if (!strcmp(buffer, "\n") || !strcmp(buffer, "\r\n")) {
568             break;
569         }
570     }
571     if (ferror(client_fd)) {
572         LOG_PERROR(WARNING, "read_http_request(): fgets()");
573         return -1;
574     } else if (feof(client_fd)) {
575         return -2;
576     }
577
578     if (global_http_digest_authorization != NULL && !found_proxy_authorization) {
579         return -3;
580     }
581
582     return 0;
583 }
584
585 static void send_bad_request(FILE *client_fd) {
586     const char error[] = "400 Bad Request";
587     const char msg[]   = "Your browser sent an invalid request.";
588     fprintf(client_fd, HTTP_RESPONSE_FORMAT, error, "", error, error, msg);
589     fflush(client_fd);
590 }
591 static void send_authentication_required(FILE *client_fd) {
592     const char error[] = "407 Proxy Authentication Required";
593     const char auth[]  = "Proxy-Authenticate: Basic realm=\"tlsproxy\"\r\n";
594     const char msg[]   = "TODO";
595     fprintf(client_fd, HTTP_RESPONSE_FORMAT, error, auth, error, error, msg);
596     fflush(client_fd);
597 }
598 static void send_forwarding_failure(FILE *client_fd) {
599     const char error[] = "503 Forwarding failure";
600     const char msg[]   = "Failed to connect to server, check logs.";
601     fprintf(client_fd, HTTP_RESPONSE_FORMAT, error, "", error, error, msg);
602     fflush(client_fd);
603 }
604 static void tls_send_invalid_cert_message(gnutls_session_t session) {
605     const char error[] = "500 Internal Server Error";
606     const char msg[]   = "Server certificate validation failed, check logs.";
607
608     int result;
609     char buffer[sizeof(HTTP_RESPONSE_FORMAT)
610                 + 3 * sizeof(error) + sizeof(msg)];
611
612     result = snprintf(buffer, sizeof(buffer), HTTP_RESPONSE_FORMAT,
613                                               error, "", error, error, msg);
614     assert(result > 0 && (size_t)result < sizeof(buffer));
615
616     gnutls_record_send(session, buffer, strlen(buffer));
617 }
618
619
620 /* Transfer data between client and server sockets until one closes the
621  * connection. */
622 static void transfer_data(int client, int server) {
623     struct pollfd fds[2];
624     fds[0].fd      = client;
625     fds[0].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
626     fds[0].revents = 0;
627     fds[1].fd      = server;
628     fds[1].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
629     fds[1].revents = 0;
630
631     LOG(DEBUG1, "transfer_data(): %d -> %d", client, server);
632
633     for (;;) {
634         int result = poll(fds, 2 /* fd count */, -1 /* no timeout */);
635         if (result < 0) {
636             LOG_PERROR(ERROR, "transfer_data(): poll()");
637             return;
638         }
639
640         /* Data available from client. */
641         if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
642             if (read_from_write_to(client, server) != 0) {
643                 /* EOF (or other error) */
644                 break;
645             }
646         }
647         /* Data available from server. */
648         if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
649             if (read_from_write_to(server, client) != 0) {
650                 /* EOF (or other error) */
651                 break;
652             }
653         }
654
655         /* Client closed connection. */
656         if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
657             break;
658         }
659         /* Server closed connection. */
660         if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
661             break;
662         }
663     }
664 }
665
666 /* Read available data from socket from and write it to socket to. At maximum
667  * 4096 bytes are read/written. */
668 static int read_from_write_to(int from, int to) {
669     ssize_t size_read;
670     ssize_t size_written;
671     char buffer[4096];
672
673     size_read = read(from, buffer, sizeof(buffer));
674     if (size_read < 0) {
675         LOG_PERROR(WARNING, "read_from_write_to(): read()");
676         return -1;
677     /* EOF */
678     } else if (size_read == 0) {
679         return -1;
680     }
681
682     size_written = write(to, buffer, (size_t)size_read);
683     if (size_written < 0) {
684         LOG_PERROR(WARNING, "read_from_write_to(): write()");
685         return -1;
686     }
687     if (size_read != size_written) {
688         LOG(ERROR, "read_from_write_to(): only written %ld of %ld bytes!",
689                    (long int)size_written, (long int)size_read);
690         return -1;
691     }
692
693     return 0;
694 }
695
696 /* Transfer data between client and server TLS connection until one closes the
697  * connection. */
698 static void transfer_data_tls(int client, int server,
699                               gnutls_session_t client_session,
700                               gnutls_session_t server_session) {
701     size_t buffer_size;
702
703     struct pollfd fds[2];
704     fds[0].fd      = client;
705     fds[0].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
706     fds[0].revents = 0;
707     fds[1].fd      = server;
708     fds[1].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
709     fds[1].revents = 0;
710
711     /* Get maximum possible buffer size. */
712     buffer_size = gnutls_record_get_max_size(client_session);
713     if (gnutls_record_get_max_size(server_session) < buffer_size) {
714         buffer_size = gnutls_record_get_max_size(server_session);
715     }
716     LOG(DEBUG1, "transfer_data_tls(): suggested buffer size: %ld",
717                 (long int)buffer_size);
718
719     for (;;) {
720         int result = poll(fds, 2 /* fd count */, -1 /* no timeout */);
721         if (result < 0) {
722             LOG_PERROR(ERROR, "transfer_data(): poll()");
723             return;
724         }
725
726         /* Data available from client. */
727         if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
728             if (read_from_write_to_tls(client_session, server_session,
729                                        buffer_size) != 0) {
730                 /* EOF (or other error) */
731                 break;
732             }
733         }
734         /* Data available from server. */
735         if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
736             if (read_from_write_to_tls(server_session, client_session,
737                                        buffer_size) != 0) {
738                 /* EOF (or other error) */
739                 break;
740             }
741         }
742
743         /* Client closed connection. */
744         if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
745             break;
746         }
747         /* Server closed connection. */
748         if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
749             break;
750         }
751     }
752 }
753
754 /* Read available data from session from and write to session to. */
755 static int read_from_write_to_tls(gnutls_session_t from,
756                                   gnutls_session_t to,
757                                   size_t buffer_size) {
758     ssize_t size_read;
759     ssize_t size_written;
760     char buffer[16384];
761
762     if (buffer_size > sizeof(buffer)) {
763         LOG(WARNING, "read_from_write_to_tls(): reduced buffer size to %ld",
764                      (long int)(sizeof(buffer)));
765         buffer_size = sizeof(buffer);
766     }
767
768     size_read = gnutls_record_recv(from, buffer, buffer_size);
769     if (size_read < 0) {
770         LOG(WARNING, "read_from_write_to_tls(): gnutls_record_recv(): %s",
771                      gnutls_strerror((int)size_read));
772         return -1;
773     /* EOF */
774     } else if (size_read == 0) {
775         return -1;
776     }
777
778     size_written = gnutls_record_send(to, buffer, (size_t)size_read);
779     if (size_written < 0) {
780         LOG(WARNING, "read_from_write_to_tls(): gnutls_record_send(): %s",
781                      gnutls_strerror((int)size_written));
782         return -1;
783     }
784     if (size_read != size_written) {
785         LOG(ERROR, "read_from_write_to_tls(): only written %ld of %ld bytes!",
786                    (long int)size_written, (long int)size_read);
787         return -1;
788     }
789
790     return 0;
791 }
792
793
794 static int connect_to_host(const char *hostname, const char *port) {
795     struct addrinfo gai_hints;
796     struct addrinfo *gai_result;
797     int gai_return;
798
799     int server_socket;
800     struct addrinfo *server;
801
802     if (hostname == NULL || port == NULL) {
803         return -1;
804     }
805
806     /* Get IP of hostname server. */
807     memset(&gai_hints, 0, sizeof(gai_hints));
808     gai_hints.ai_family   = AF_UNSPEC;
809     gai_hints.ai_socktype = SOCK_STREAM;
810     gai_hints.ai_protocol = 0;
811     gai_hints.ai_flags    = AI_NUMERICSERV /* given port is numeric */
812                           | AI_ADDRCONFIG  /* supported by this computer */
813                           | AI_V4MAPPED;   /* support IPv4 through IPv6 */
814     gai_return = getaddrinfo(hostname, port, &gai_hints, &gai_result);
815     if (gai_return != 0) {
816         if (gai_return == EAI_SYSTEM) {
817             LOG_PERROR(WARNING, "connect_to_host(): getaddrinfo()");
818         } else {
819             LOG(WARNING, "connect_to_host(): getaddrinfo(): %s",
820                          gai_strerror(gai_return));
821         }
822         return -1;
823     }
824
825     /* Now try to connect to each server returned by getaddrinfo(), use the
826      * first successful connect. */
827     for (server = gai_result; server != NULL; server = server->ai_next) {
828         server_socket = socket(server->ai_family,
829                                server->ai_socktype,
830                                server->ai_protocol);
831         if (server_socket < 0) {
832             LOG_PERROR(DEBUG1, "connect_to_host(): socket(), trying next");
833             continue;
834         }
835
836         if (connect(server_socket, server->ai_addr, server->ai_addrlen) == 0) {
837             break;
838         }
839         LOG_PERROR(DEBUG1, "connect_to_host(): connect(), trying next");
840
841         close(server_socket);
842     }
843     /* Make sure we free the result from getaddrinfo(). */
844     freeaddrinfo(gai_result);
845
846     if (server == NULL) {
847         LOG_PERROR(WARNING, "connect_to_host(): no server found, abort");
848         return -1;
849     }
850
851     return server_socket;
852 }
853
854
855 /* Parse HTTP CONNECT request string and save its parameters.
856  *
857  * The following format is expected: "CONNECT host:port HTTP/1.x".
858  *
859  * request and host must have the same size! port must be at least 6 bytes
860  * long (5 + '\0').
861  */
862 static int parse_request(const char *request, char *host, char *port,
863                                               int *version_minor) {
864     int port_unused; /* just used to verify the port is numeric */
865     char *position;
866
867     /* scanf() doesn't check spaces. */
868     if (strncmp(request, "CONNECT ", 8)) {
869         return -1;
870     }
871     /* Check request and extract data, "host:port" is not yet separated. */
872     if (sscanf(request, "CONNECT %s HTTP/1.%d", host, version_minor) != 2) {
873         return -1;
874     }
875     /* Make sure ":port" is there. */
876     if ((position = strchr(host, ':')) == NULL) {
877         return -1;
878     }
879     /* Make sure port is numeric. */
880     if (sscanf(position + 1, "%d", &port_unused) != 1) {
881         return -1;
882     }
883     /* Store it in *port. */
884     strncpy(port, position + 1, 5);
885     port[5] = '\0';
886     /* And remove port from host. */
887     *position = '\0';
888
889     return 0;
890 }