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