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