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