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