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