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