]> ruderich.org/simon Gitweb - tlsproxy/tlsproxy.git/blob - src/connection.c
Rename DEBUG log level to DEBUG1.
[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         gnutls_bye(server_session, GNUTLS_SHUT_RDWR);
317     }
318     if (client_session_started) {
319         gnutls_bye(client_session, GNUTLS_SHUT_RDWR);
320     }
321     if (server_session_init) {
322         gnutls_deinit(server_session);
323         gnutls_certificate_free_credentials(server_x509_cred);
324     }
325     if (client_session_init) {
326         gnutls_deinit(client_session);
327         gnutls_certificate_free_cas(client_x509_cred);
328         gnutls_certificate_free_keys(client_x509_cred);
329         gnutls_certificate_free_credentials(client_x509_cred);
330     }
331
332     /* Close connection to server/proxy. */
333     if (server_fd_read != NULL) {
334         if (server_fd_write != NULL) {
335             fclose(server_fd_write);
336         }
337         fclose(server_fd_read);
338     } else if (server_socket != -1) {
339         close(server_socket);
340     }
341     LOG(DEBUG1, "connection to server closed");
342     /* Close connection to client. */
343     if (client_fd_read != NULL) {
344         if (client_fd_write != NULL) {
345             fclose(client_fd_write);
346         }
347         fclose(client_fd_read);
348     } else {
349         close(client_socket);
350     }
351     LOG(DEBUG1, "connection to client closed");
352
353     LOG(DEBUG1, "connection finished");
354 }
355
356
357 static int initialize_tls_session_client(int peer_socket,
358         const char *hostname,
359         gnutls_session_t *session,
360         gnutls_certificate_credentials_t *x509_cred) {
361     int result;
362     int use_invalid_cert;
363     char path[TLSPROXY_MAX_PATH_LENGTH];
364
365     /* The "invalid" hostname is special. If it's used we send an invalid
366      * certificate to let the client know something is wrong. */
367     use_invalid_cert = (!strcmp(hostname, "invalid"));
368
369     if (proxy_certificate_path(hostname, path, sizeof(path)) != 0) {
370         LOG(ERROR,
371             "initialize_tls_session_client(): "
372             "failed to get proxy certificate path");
373         return -1;
374     }
375
376     result = gnutls_certificate_allocate_credentials(x509_cred);
377     if (result != GNUTLS_E_SUCCESS) {
378         LOG(ERROR,
379             "initialize_tls_session_client(): "
380             "gnutls_certificate_allocate_credentials(): %s",
381             gnutls_strerror(result));
382         return -1;
383     }
384
385     /* Load proxy CA file, this CA "list" is send to the client. */
386     if (!use_invalid_cert) {
387         result = gnutls_certificate_set_x509_trust_file(*x509_cred,
388                                                         PROXY_CA_FILE,
389                                                         GNUTLS_X509_FMT_PEM);
390         if (result <= 0) {
391             LOG(ERROR,
392                 "initialize_tls_session_client(): can't read CA file: '%s'",
393                 PROXY_CA_FILE);
394             gnutls_certificate_free_credentials(*x509_cred);
395             return -1;
396         }
397     }
398     /* If the invalid hostname was specified do nothing, we use a self-signed
399      * certificate in this case. */
400
401     /* And certificate for this website and proxy's private key. */
402     if (!use_invalid_cert) {
403         result = gnutls_certificate_set_x509_key_file(*x509_cred,
404                                                       path, PROXY_KEY_FILE,
405                                                       GNUTLS_X509_FMT_PEM);
406     /* If the invalid hostname was specified load our special "invalid"
407      * certificate. */
408     } else {
409         result = gnutls_certificate_set_x509_key_file(*x509_cred,
410                                                       PROXY_INVALID_CERT_FILE,
411                                                       PROXY_KEY_FILE,
412                                                       GNUTLS_X509_FMT_PEM);
413     }
414     if (result != GNUTLS_E_SUCCESS) {
415         LOG(ERROR,
416             "initialize_tls_session_client(): "
417             "can't read server certificate ('%s') or key file ('%s'): %s",
418             path, PROXY_KEY_FILE, gnutls_strerror(result));
419         gnutls_certificate_free_credentials(*x509_cred);
420         /* Could be a missing certificate. */
421         return -2;
422     }
423
424     gnutls_certificate_set_dh_params(*x509_cred, global_tls_dh_params);
425
426     result = gnutls_init(session, GNUTLS_SERVER);
427     if (result != GNUTLS_E_SUCCESS) {
428         LOG(ERROR,
429             "initialize_tls_session_client(): gnutls_init(): %s",
430             gnutls_strerror(result));
431         gnutls_certificate_free_credentials(*x509_cred);
432         return -1;
433     }
434     result = gnutls_priority_set(*session, global_tls_priority_cache);
435     if (result != GNUTLS_E_SUCCESS) {
436         LOG(ERROR,
437             "initialize_tls_session_client(): gnutls_priority_set(): %s",
438             gnutls_strerror(result));
439         gnutls_deinit(*session);
440         gnutls_certificate_free_credentials(*x509_cred);
441         return -1;
442     }
443     result = gnutls_credentials_set(*session,
444                                     GNUTLS_CRD_CERTIFICATE, *x509_cred);
445     if (result != GNUTLS_E_SUCCESS) {
446         LOG(ERROR,
447             "initialize_tls_session_client(): gnutls_credentials_set(): %s",
448             gnutls_strerror(result));
449         gnutls_deinit(*session);
450         gnutls_certificate_free_credentials(*x509_cred);
451         return -1;
452     }
453
454     gnutls_transport_set_ptr(*session, (gnutls_transport_ptr_t)peer_socket);
455
456     return 0;
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     result = gnutls_init(session, GNUTLS_CLIENT);
473     if (result != GNUTLS_E_SUCCESS) {
474         LOG(ERROR,
475             "initialize_tls_session_server(): gnutls_init(): %s",
476             gnutls_strerror(result));
477         gnutls_certificate_free_credentials(*x509_cred);
478         return -1;
479     }
480     result = gnutls_priority_set(*session, global_tls_priority_cache);
481     if (result != GNUTLS_E_SUCCESS) {
482         LOG(ERROR,
483             "initialize_tls_session_server(): gnutls_priority_set(): %s",
484             gnutls_strerror(result));
485         gnutls_deinit(*session);
486         gnutls_certificate_free_credentials(*x509_cred);
487         return -1;
488     }
489     result = gnutls_credentials_set(*session,
490                                     GNUTLS_CRD_CERTIFICATE, *x509_cred);
491     if (result != GNUTLS_E_SUCCESS) {
492         LOG(ERROR,
493             "initialize_tls_session_server(): gnutls_credentials_set(): %s",
494             gnutls_strerror(result));
495         gnutls_deinit(*session);
496         gnutls_certificate_free_credentials(*x509_cred);
497         return -1;
498     }
499
500     gnutls_transport_set_ptr(*session, (gnutls_transport_ptr_t)peer_socket);
501
502     return 0;
503 }
504
505
506 static int fdopen_read_write(int socket, FILE **read_fd, FILE **write_fd) {
507     *read_fd = fdopen(socket, "r");
508     if (*read_fd == NULL) {
509         LOG_PERROR(WARNING, "fdopen_read_write(): fdopen(\"r\") failed");
510         return -1;
511     }
512
513     *write_fd = fdopen(dup(socket), "w");
514     if (*write_fd == NULL) {
515         LOG_PERROR(WARNING, "fdopen_read_write(): fdopen(\"w\") failed");
516         fclose(*read_fd);
517         *read_fd = NULL; /* "tell" caller read_fd is already closed */
518         return -1;
519     }
520
521     return 0;
522 }
523
524 /* Read HTTP request line and headers (ignored).
525  *
526  * On success 0 is returned, -1 on client error, -2 on unexpected EOF.
527  */
528 static int read_http_request(FILE *client_fd, char *request, size_t length) {
529     char buffer[MAX_REQUEST_LINE];
530     int found_proxy_authorization;
531
532     assert(length <= INT_MAX);
533     if (fgets(request, (int)length, client_fd) == NULL) {
534         if (ferror(client_fd)) {
535             LOG_PERROR(WARNING, "read_http_request(): fgets()");
536             return -1;
537         }
538         /* EOF */
539         return -2;
540     }
541
542     found_proxy_authorization = 0;
543     while (fgets(buffer, sizeof(buffer), client_fd) != NULL) {
544         const char *authentication = "Proxy-Authorization: Basic ";
545
546         if (http_digest_authorization != NULL
547                 && !strncmp(buffer, authentication, strlen(authentication))) {
548             found_proxy_authorization = 1;
549
550             /* Check if the passphrase matches. */
551             strtok(buffer, "\r\n");
552             if (strcmp(buffer + strlen(authentication),
553                        http_digest_authorization)) {
554                 return -3;
555             }
556         }
557
558         /* End of header. */
559         if (!strcmp(buffer, "\n") || !strcmp(buffer, "\r\n")) {
560             break;
561         }
562     }
563     if (ferror(client_fd)) {
564         LOG_PERROR(WARNING, "read_http_request(): fgets()");
565         return -1;
566     }
567
568     if (http_digest_authorization != NULL && !found_proxy_authorization) {
569         return -3;
570     }
571
572     return 0;
573 }
574
575 static void send_bad_request(FILE *client_fd) {
576     const char error[] = "400 Bad Request";
577     const char msg[]   = "Your browser sent an invalid request.";
578     fprintf(client_fd, HTTP_RESPONSE_FORMAT, error, "", error, error, msg);
579     fflush(client_fd);
580 }
581 static void send_authentication_required(FILE *client_fd) {
582     const char error[] = "407 Proxy Authentication Required";
583     const char auth[]  = "Proxy-Authenticate: Basic realm=\"tlsproxy\"\r\n";
584     const char msg[]   = "TODO";
585     fprintf(client_fd, HTTP_RESPONSE_FORMAT, error, auth, error, error, msg);
586     fflush(client_fd);
587 }
588 static void send_forwarding_failure(FILE *client_fd) {
589     const char error[] = "503 Forwarding failure";
590     const char msg[]   = "Failed to connect to server, check logs.";
591     fprintf(client_fd, HTTP_RESPONSE_FORMAT, error, "", error, error, msg);
592     fflush(client_fd);
593 }
594 static void tls_send_invalid_cert_message(gnutls_session_t session) {
595     const char error[] = "500 Internal Server Error";
596     const char msg[]   = "Server certificate validation failed, check logs.";
597
598     int result;
599     char buffer[sizeof(HTTP_RESPONSE_FORMAT)
600                 + 3 * sizeof(error) + sizeof(msg)];
601
602     result = snprintf(buffer, sizeof(buffer), HTTP_RESPONSE_FORMAT,
603                                               error, "", error, error, msg);
604     assert(result > 0 && (size_t)result < sizeof(buffer));
605
606     gnutls_record_send(session, buffer, strlen(buffer));
607 }
608
609
610 /* Transfer data between client and server sockets until one closes the
611  * connection. */
612 static void transfer_data(int client, int server) {
613     struct pollfd fds[2];
614     fds[0].fd      = client;
615     fds[0].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
616     fds[0].revents = 0;
617     fds[1].fd      = server;
618     fds[1].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
619     fds[1].revents = 0;
620
621     LOG(DEBUG1, "transfer_data(): %d -> %d", client, server);
622
623     for (;;) {
624         int result = poll(fds, 2 /* fd count */, -1 /* no timeout */);
625         if (result < 0) {
626             LOG_PERROR(ERROR, "transfer_data(): poll()");
627             return;
628         }
629
630         /* Data available from client. */
631         if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
632             if (read_from_write_to(client, server) != 0) {
633                 /* EOF (or other error) */
634                 break;
635             }
636         }
637         /* Data available from server. */
638         if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
639             if (read_from_write_to(server, client) != 0) {
640                 /* EOF (or other error) */
641                 break;
642             }
643         }
644
645         /* Client closed connection. */
646         if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
647             break;
648         }
649         /* Server closed connection. */
650         if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
651             break;
652         }
653     }
654 }
655
656 /* Read available data from socket from and write it to socket to. At maximum
657  * 4096 bytes are read/written. */
658 static int read_from_write_to(int from, int to) {
659     ssize_t size_read;
660     ssize_t size_written;
661     char buffer[4096];
662
663     size_read = read(from, buffer, sizeof(buffer));
664     if (size_read < 0) {
665         LOG_PERROR(WARNING, "read_from_write_to(): read()");
666         return -1;
667     /* EOF */
668     } else if (size_read == 0) {
669         return -1;
670     }
671
672     size_written = write(to, buffer, (size_t)size_read);
673     if (size_written < 0) {
674         LOG_PERROR(WARNING, "read_from_write_to(): write()");
675         return -1;
676     }
677     if (size_read != size_written) {
678         LOG(ERROR, "read_from_write_to(): only written %ld of %ld bytes!",
679                    (long int)size_written, (long int)size_read);
680         return -1;
681     }
682
683     return 0;
684 }
685
686 /* Transfer data between client and server TLS connection until one closes the
687  * connection. */
688 static void transfer_data_tls(int client, int server,
689                               gnutls_session_t client_session,
690                               gnutls_session_t server_session) {
691     size_t buffer_size;
692
693     struct pollfd fds[2];
694     fds[0].fd      = client;
695     fds[0].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
696     fds[0].revents = 0;
697     fds[1].fd      = server;
698     fds[1].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
699     fds[1].revents = 0;
700
701     /* Get maximum possible buffer size. */
702     buffer_size = gnutls_record_get_max_size(client_session);
703     if (gnutls_record_get_max_size(server_session) < buffer_size) {
704         buffer_size = gnutls_record_get_max_size(server_session);
705     }
706     LOG(DEBUG1, "transfer_data_tls(): suggested buffer size: %ld",
707                 (long int)buffer_size);
708
709     for (;;) {
710         int result = poll(fds, 2 /* fd count */, -1 /* no timeout */);
711         if (result < 0) {
712             LOG_PERROR(ERROR, "transfer_data(): poll()");
713             return;
714         }
715
716         /* Data available from client. */
717         if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
718             if (read_from_write_to_tls(client_session, server_session,
719                                        buffer_size) != 0) {
720                 /* EOF (or other error) */
721                 break;
722             }
723         }
724         /* Data available from server. */
725         if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
726             if (read_from_write_to_tls(server_session, client_session,
727                                        buffer_size) != 0) {
728                 /* EOF (or other error) */
729                 break;
730             }
731         }
732
733         /* Client closed connection. */
734         if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
735             break;
736         }
737         /* Server closed connection. */
738         if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
739             break;
740         }
741     }
742 }
743
744 /* Read available data from session from and write to session to. */
745 static int read_from_write_to_tls(gnutls_session_t from,
746                                   gnutls_session_t to,
747                                   size_t buffer_size) {
748     ssize_t size_read;
749     ssize_t size_written;
750     char buffer[16384];
751
752     if (buffer_size > sizeof(buffer)) {
753         LOG(WARNING, "read_from_write_to_tls(): reduced buffer size to %ld",
754                      (long int)(sizeof(buffer)));
755         buffer_size = sizeof(buffer);
756     }
757
758     size_read = gnutls_record_recv(from, buffer, buffer_size);
759     if (size_read < 0) {
760         LOG(WARNING, "read_from_write_to_tls(): gnutls_record_recv(): %s",
761                      gnutls_strerror((int)size_read));
762         return -1;
763     /* EOF */
764     } else if (size_read == 0) {
765         return -1;
766     }
767
768     size_written = gnutls_record_send(to, buffer, (size_t)size_read);
769     if (size_written < 0) {
770         LOG(WARNING, "read_from_write_to_tls(): gnutls_record_send(): %s",
771                      gnutls_strerror((int)size_written));
772         return -1;
773     }
774     if (size_read != size_written) {
775         LOG(ERROR, "read_from_write_to_tls(): only written %ld of %ld bytes!",
776                    (long int)size_written, (long int)size_read);
777         return -1;
778     }
779
780     return 0;
781 }
782
783
784 static int connect_to_host(const char *hostname, const char *port) {
785     struct addrinfo gai_hints;
786     struct addrinfo *gai_result;
787     int gai_return;
788
789     int server_socket;
790     struct addrinfo *server;
791
792     if (hostname == NULL || port == NULL) {
793         return -1;
794     }
795
796     /* Get IP of hostname server. */
797     memset(&gai_hints, 0, sizeof(gai_hints));
798     gai_hints.ai_family   = AF_UNSPEC;
799     gai_hints.ai_socktype = SOCK_STREAM;
800     gai_hints.ai_protocol = 0;
801     gai_hints.ai_flags    = AI_NUMERICSERV /* given port is numeric */
802                           | AI_ADDRCONFIG  /* supported by this computer */
803                           | AI_V4MAPPED;   /* support IPv4 through IPv6 */
804     gai_return = getaddrinfo(hostname, port, &gai_hints, &gai_result);
805     if (gai_return != 0) {
806         if (gai_return == EAI_SYSTEM) {
807             LOG_PERROR(WARNING, "connect_to_host(): getaddrinfo()");
808         } else {
809             LOG(WARNING, "connect_to_host(): getaddrinfo(): %s",
810                          gai_strerror(gai_return));
811         }
812         return -1;
813     }
814
815     /* Now try to connect to each server returned by getaddrinfo(), use the
816      * first successful connect. */
817     for (server = gai_result; server != NULL; server = server->ai_next) {
818         server_socket = socket(server->ai_family,
819                                server->ai_socktype,
820                                server->ai_protocol);
821         if (server_socket < 0) {
822             LOG_PERROR(DEBUG1, "connect_to_host(): socket(), trying next");
823             continue;
824         }
825
826         if (connect(server_socket, server->ai_addr, server->ai_addrlen) == 0) {
827             break;
828         }
829         LOG_PERROR(DEBUG1, "connect_to_host(): connect(), trying next");
830
831         close(server_socket);
832     }
833     /* Make sure we free the result from getaddrinfo(). */
834     freeaddrinfo(gai_result);
835
836     if (server == NULL) {
837         LOG_PERROR(WARNING, "connect_to_host(): no server found, abort");
838         return -1;
839     }
840
841     return server_socket;
842 }
843
844
845 /* Parse HTTP CONNECT request string and save its parameters.
846  *
847  * The following format is expected: "CONNECT host:port HTTP/1.x".
848  *
849  * request and host must have the same size! port must be at least 6 bytes
850  * long (5 + '\0').
851  */
852 static int parse_request(const char *request, char *host, char *port,
853                                               int *version_minor) {
854     int port_unused; /* just used to verify the port is numeric */
855     char *position;
856
857     /* scanf() doesn't check spaces. */
858     if (strncmp(request, "CONNECT ", 8)) {
859         return -1;
860     }
861     /* Check request and extract data, "host:port" is not yet separated. */
862     if (sscanf(request, "CONNECT %s HTTP/1.%d", host, version_minor) != 2) {
863         return -1;
864     }
865     /* Make sure ":port" is there. */
866     if ((position = strchr(host, ':')) == NULL) {
867         return -1;
868     }
869     /* Make sure port is numeric. */
870     if (sscanf(position + 1, "%d", &port_unused) != 1) {
871         return -1;
872     }
873     /* Store it in *port. */
874     strncpy(port, position + 1, 5);
875     port[5] = '\0';
876     /* And remove port from host. */
877     *position = '\0';
878
879     return 0;
880 }