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