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