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