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