]> ruderich.org/simon Gitweb - tlsproxy/tlsproxy.git/blob - src/connection.c
Simplify a few if conditions.
[tlsproxy/tlsproxy.git] / src / connection.c
1 /*
2  * Handle connections.
3  *
4  * Copyright (C) 2011-2013  Simon Ruderich
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include "tlsproxy.h"
21 #include "connection.h"
22 #include "verify.h"
23
24 /* 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 (client_fd == NULL) {
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 (result == -1) {
129         /* Read error. */
130         LOG(LOG_WARNING, "read_http_request(): client read error");
131         goto out;
132     } else if (result == -2) {
133         /* EOF */
134         LOG(LOG_WARNING, "read_http_request(): client EOF");
135         send_bad_request(client_fd);
136         goto out;
137     }
138
139     if (parse_request(buffer, host, port, &version_minor) != 0) {
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 (global_proxy_host != NULL && global_proxy_port != NULL) {
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 (server_socket == -1) {
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 (server_fd == NULL) {
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 (global_proxy_host != NULL && global_proxy_port != NULL) {
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 (result == -1) {
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 (result == -2) {
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 (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[TLSPROXY_MAX_PATH_LENGTH];
203         FILE *file = NULL;
204
205         if (server_certificate_file(&file, host, path, sizeof(path)) == -2) {
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_file() may have opened the file, close it. */
222         if (file != NULL) {
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 (result != 0) {
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 (result != GNUTLS_E_SUCCESS) {
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 (verify_tls_connection(server_session, host) != 0) {
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 (result != 0) {
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 (result != GNUTLS_E_SUCCESS) {
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 (server_session_started) {
315         gnutls_bye(server_session, GNUTLS_SHUT_RDWR);
316     }
317     if (client_session_started) {
318         gnutls_bye(client_session, GNUTLS_SHUT_RDWR);
319     }
320     if (server_session_init) {
321         gnutls_deinit(server_session);
322         gnutls_certificate_free_credentials(server_x509_cred);
323     }
324     if (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 (server_fd != NULL) {
333         fclose(server_fd);
334     } else if (server_socket != -1) {
335         close(server_socket);
336     }
337     LOG(LOG_DEBUG, "connection to server closed");
338     /* Close connection to client. */
339     if (client_fd != NULL) {
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[TLSPROXY_MAX_PATH_LENGTH];
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 = (!strcmp(hostname, "invalid"));
361
362     if (proxy_certificate_path(hostname, path, sizeof(path)) != 0) {
363         LOG(LOG_ERROR,
364             "initialize_tls_session_client(): \
365 failed to get proxy certificate path");
366         return -1;
367     }
368
369     result = gnutls_certificate_allocate_credentials(x509_cred);
370     if (result != GNUTLS_E_SUCCESS) {
371         LOG(LOG_ERROR,
372             "initialize_tls_session_client(): \
373 gnutls_certificate_allocate_credentials(): %s",
374             gnutls_strerror(result));
375         return -1;
376     }
377
378     /* Load proxy CA file, this CA "list" is send to the client. */
379     if (!use_invalid_cert) {
380         result = gnutls_certificate_set_x509_trust_file(*x509_cred,
381                                                         PROXY_CA_FILE,
382                                                         GNUTLS_X509_FMT_PEM);
383         if (result <= 0) {
384             LOG(LOG_ERROR,
385                 "initialize_tls_session_client(): can't read CA file: '%s'",
386                 PROXY_CA_FILE);
387             gnutls_certificate_free_credentials(*x509_cred);
388             return -1;
389         }
390     }
391     /* If the invalid hostname was specified do nothing, we use a self-signed
392      * certificate in this case. */
393
394     /* And certificate for this website and proxy's private key. */
395     if (!use_invalid_cert) {
396         result = gnutls_certificate_set_x509_key_file(*x509_cred,
397                                                       path, PROXY_KEY_FILE,
398                                                       GNUTLS_X509_FMT_PEM);
399     /* If the invalid hostname was specified load our special "invalid"
400      * certificate. */
401     } else {
402         result = gnutls_certificate_set_x509_key_file(*x509_cred,
403                                                       PROXY_INVALID_CERT_FILE,
404                                                       PROXY_KEY_FILE,
405                                                       GNUTLS_X509_FMT_PEM);
406     }
407     if (result != GNUTLS_E_SUCCESS) {
408         LOG(LOG_ERROR,
409             "initialize_tls_session_client(): \
410 can't read server certificate ('%s') or key file ('%s'): %s",
411             path, PROXY_KEY_FILE, gnutls_strerror(result));
412         gnutls_certificate_free_credentials(*x509_cred);
413         /* Could be a missing certificate. */
414         return -2;
415     }
416
417     gnutls_certificate_set_dh_params(*x509_cred, global_tls_dh_params);
418
419     result = gnutls_init(session, GNUTLS_SERVER);
420     if (result != GNUTLS_E_SUCCESS) {
421         LOG(LOG_ERROR,
422             "initialize_tls_session_client(): gnutls_init(): %s",
423             gnutls_strerror(result));
424         gnutls_certificate_free_credentials(*x509_cred);
425         return -1;
426     }
427     result = gnutls_priority_set(*session, global_tls_priority_cache);
428     if (result != GNUTLS_E_SUCCESS) {
429         LOG(LOG_ERROR,
430             "initialize_tls_session_client(): gnutls_priority_set(): %s",
431             gnutls_strerror(result));
432         gnutls_deinit(*session);
433         gnutls_certificate_free_credentials(*x509_cred);
434         return -1;
435     }
436     result = gnutls_credentials_set(*session,
437                                     GNUTLS_CRD_CERTIFICATE, *x509_cred);
438     if (result != GNUTLS_E_SUCCESS) {
439         LOG(LOG_ERROR,
440             "initialize_tls_session_client(): gnutls_credentials_set(): %s",
441             gnutls_strerror(result));
442         gnutls_deinit(*session);
443         gnutls_certificate_free_credentials(*x509_cred);
444         return -1;
445     }
446
447     gnutls_transport_set_ptr(*session, (gnutls_transport_ptr_t)peer_socket);
448
449     return 0;
450 }
451 static int initialize_tls_session_server(int peer_socket,
452         gnutls_session_t *session,
453         gnutls_certificate_credentials_t *x509_cred) {
454     int result;
455
456     result = gnutls_certificate_allocate_credentials(x509_cred);
457     if (result != GNUTLS_E_SUCCESS) {
458         LOG(LOG_ERROR,
459             "initialize_tls_session_server(): \
460 gnutls_certificate_allocate_credentials(): %s",
461             gnutls_strerror(result));
462         return -1;
463     }
464
465     result = gnutls_init(session, GNUTLS_CLIENT);
466     if (result != GNUTLS_E_SUCCESS) {
467         LOG(LOG_ERROR,
468             "initialize_tls_session_server(): gnutls_init(): %s",
469             gnutls_strerror(result));
470         gnutls_certificate_free_credentials(*x509_cred);
471         return -1;
472     }
473     result = gnutls_priority_set(*session, global_tls_priority_cache);
474     if (result != GNUTLS_E_SUCCESS) {
475         LOG(LOG_ERROR,
476             "initialize_tls_session_server(): gnutls_priority_set(): %s",
477             gnutls_strerror(result));
478         gnutls_deinit(*session);
479         gnutls_certificate_free_credentials(*x509_cred);
480         return -1;
481     }
482     result = gnutls_credentials_set(*session,
483                                     GNUTLS_CRD_CERTIFICATE, *x509_cred);
484     if (result != GNUTLS_E_SUCCESS) {
485         LOG(LOG_ERROR,
486             "initialize_tls_session_server(): gnutls_credentials_set(): %s",
487             gnutls_strerror(result));
488         gnutls_deinit(*session);
489         gnutls_certificate_free_credentials(*x509_cred);
490         return -1;
491     }
492
493     gnutls_transport_set_ptr(*session, (gnutls_transport_ptr_t)peer_socket);
494
495     return 0;
496 }
497
498
499 /* Read HTTP request line and headers (ignored).
500  *
501  * On success 0 is returned, -1 on client error, -2 on unexpected EOF.
502  */
503 static int read_http_request(FILE *client_fd, char *request, size_t length) {
504     char buffer[MAX_REQUEST_LINE];
505
506     if (fgets(request, (int)length, client_fd) == NULL) {
507         if (ferror(client_fd)) {
508             LOG_PERROR(LOG_WARNING, "read_http_request(): fgets()");
509             return -1;
510         }
511
512         return -2;
513     }
514
515     while (fgets(buffer, sizeof(buffer), client_fd) != NULL) {
516         /* End of header. */
517         if (!strcmp(buffer, "\n") || !strcmp(buffer, "\r\n")) {
518             break;
519         }
520     }
521     if (ferror(client_fd)) {
522         LOG_PERROR(LOG_WARNING, "read_http_request(): fgets()");
523         return -1;
524     }
525
526     return 0;
527 }
528
529 static void send_bad_request(FILE *client_fd) {
530 #define RESPONSE_ERROR "400 Bad Request"
531 #define RESPONSE_MSG   "Your browser sent an invalid request."
532     fprintf(client_fd, HTTP_RESPONSE_FORMAT,
533                        RESPONSE_ERROR, RESPONSE_ERROR, RESPONSE_ERROR,
534                        RESPONSE_MSG);
535 #undef RESPONSE_ERROR
536 #undef RESPONSE_MSG
537 }
538 static void send_forwarding_failure(FILE *client_fd) {
539 #define RESPONSE_ERROR "503 Forwarding failure"
540 #define RESPONSE_MSG   "Failed to connect to server, check logs."
541     fprintf(client_fd, HTTP_RESPONSE_FORMAT,
542                        RESPONSE_ERROR, RESPONSE_ERROR, RESPONSE_ERROR,
543                        RESPONSE_MSG);
544 #undef RESPONSE_ERROR
545 #undef RESPONSE_MSG
546 }
547 static void tls_send_invalid_cert_message(gnutls_session_t session) {
548 #define RESPONSE_ERROR "500 Internal Server Error"
549 #define RESPONSE_MSG   "Server certificate validation failed, check logs."
550
551     int result;
552     char buffer[sizeof(HTTP_RESPONSE_FORMAT) - 1 /* '\0' */
553                                              - 4 * 2 /* four %s */
554                 + (sizeof(RESPONSE_ERROR) - 1 /* '\0' */) * 3
555                 + sizeof(RESPONSE_MSG)    - 1 /* '\0' */
556                 + 1 /* '\0' */];
557
558     result = snprintf(buffer, sizeof(buffer),
559                       HTTP_RESPONSE_FORMAT,
560                       RESPONSE_ERROR, RESPONSE_ERROR, RESPONSE_ERROR,
561                       RESPONSE_MSG);
562     if (result < 0) {
563         LOG_PERROR(LOG_ERROR,
564                    "tls_send_invalid_cert_message(): snprintf failed");
565         return;
566     } else if ((size_t)result >= sizeof(buffer)) {
567         LOG(LOG_ERROR,
568             "tls_send_invalid_cert_message(): snprintf buffer too short");
569         return;
570     }
571
572     gnutls_record_send(session, buffer, sizeof(buffer) - 1);
573                                         /* don't send trailing '\0' */
574 #undef RESPONSE_ERROR
575 #undef RESPONSE_MSG
576 }
577
578
579 /* Transfer data between client and server sockets until one closes the
580  * connection. */
581 static void transfer_data(int client, int server) {
582     struct pollfd fds[2];
583     fds[0].fd      = client;
584     fds[0].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
585     fds[0].revents = 0;
586     fds[1].fd      = server;
587     fds[1].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
588     fds[1].revents = 0;
589
590     for (;;) {
591         int result = poll(fds, 2, -1 /* no timeout */);
592         if (result < 0) {
593             LOG_PERROR(LOG_ERROR, "transfer_data(): poll()");
594             return;
595         }
596
597         /* Data available from client. */
598         if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
599             if (read_from_write_to(client, server) != 0) {
600                 /* EOF (or other error) */
601                 break;
602             }
603         }
604         /* Data available from server. */
605         if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
606             if (read_from_write_to(server, client) != 0) {
607                 /* EOF (or other error) */
608                 break;
609             }
610         }
611
612         /* Client closed connection. */
613         if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
614             break;
615         }
616         /* Server closed connection. */
617         if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
618             break;
619         }
620     }
621 }
622
623 /* Read available data from socket from and write it to socket to. At maximum
624  * 4096 bytes are read/written. */
625 static int read_from_write_to(int from, int to) {
626     ssize_t size_read;
627     ssize_t size_written;
628     char buffer[4096];
629
630     LOG(LOG_DEBUG, "read_from_write_to(): %d -> %d", from, to);
631
632     size_read = read(from, buffer, sizeof(buffer));
633     if (size_read < 0) {
634         LOG_PERROR(LOG_WARNING, "read_from_write_to(): read()");
635         return -1;
636     }
637     /* EOF */
638     if (size_read == 0) {
639         return -1;
640     }
641
642     size_written = write(to, buffer, (size_t)size_read);
643     if (size_written < 0) {
644         LOG_PERROR(LOG_WARNING, "read_from_write_to(): write()");
645         return -1;
646     }
647     if (size_read != size_written) {
648         LOG(LOG_ERROR, "read_from_write_to(): only written %ld of %ld bytes!",
649                        (long int)size_written, (long int)size_read);
650         return -1;
651     }
652
653     return 0;
654 }
655
656 /* Transfer data between client and server TLS connection until one closes the
657  * connection. */
658 static void transfer_data_tls(int client, int server,
659                               gnutls_session_t client_session,
660                               gnutls_session_t server_session) {
661     size_t buffer_size;
662
663     struct pollfd fds[2];
664     fds[0].fd      = client;
665     fds[0].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
666     fds[0].revents = 0;
667     fds[1].fd      = server;
668     fds[1].events  = POLLIN | POLLPRI | POLLHUP | POLLERR;
669     fds[1].revents = 0;
670
671     /* Get maximum possible buffer size. */
672     buffer_size = gnutls_record_get_max_size(client_session);
673     if (gnutls_record_get_max_size(server_session) < buffer_size) {
674         buffer_size = gnutls_record_get_max_size(server_session);
675     }
676     LOG(LOG_DEBUG, "transfer_data_tls(): suggested buffer size: %ld",
677                    (long int)buffer_size);
678
679     for (;;) {
680         int result = poll(fds, 2, -1 /* no timeout */);
681         if (result < 0) {
682             LOG_PERROR(LOG_ERROR, "transfer_data(): poll()");
683             return;
684         }
685
686         /* Data available from client. */
687         if (fds[0].revents & POLLIN || fds[0].revents & POLLPRI) {
688             if (read_from_write_to_tls(client_session, server_session,
689                                        buffer_size) != 0) {
690                 /* EOF (or other error) */
691                 break;
692             }
693         }
694         /* Data available from server. */
695         if (fds[1].revents & POLLIN || fds[1].revents & POLLPRI) {
696             if (read_from_write_to_tls(server_session, client_session,
697                                        buffer_size) != 0) {
698                 /* EOF (or other error) */
699                 break;
700             }
701         }
702
703         /* Client closed connection. */
704         if (fds[0].revents & POLLERR || fds[0].revents & POLLHUP) {
705             break;
706         }
707         /* Server closed connection. */
708         if (fds[1].revents & POLLERR || fds[1].revents & POLLHUP) {
709             break;
710         }
711     }
712 }
713
714 /* Read available data from session from and write to session to. */
715 static int read_from_write_to_tls(gnutls_session_t from,
716                                   gnutls_session_t to,
717                                   size_t buffer_size) {
718     ssize_t size_read;
719     ssize_t size_written;
720     char buffer[16384];
721
722     if (buffer_size > sizeof(buffer)) {
723         buffer_size = sizeof(buffer);
724     }
725     LOG(LOG_DEBUG, "read_from_write_to_tls(): used buffer size: %ld",
726                    (long int)buffer_size);
727
728     size_read = gnutls_record_recv(from, buffer, buffer_size);
729     if (size_read < 0) {
730         LOG(LOG_WARNING, "read_from_write_to_tls(): gnutls_record_recv(): %s",
731                          gnutls_strerror((int)size_read));
732         return -1;
733     }
734     /* EOF */
735     if (size_read == 0) {
736         return -1;
737     }
738
739     size_written = gnutls_record_send(to, buffer, (size_t)size_read);
740     if (size_written < 0) {
741         LOG(LOG_WARNING, "read_from_write_to_tls(): gnutls_record_send(): %s",
742                          gnutls_strerror((int)size_written));
743         return -1;
744     }
745     if (size_read != size_written) {
746         LOG(LOG_ERROR, "read_from_write_to_tls(): only written %ld of %ld bytes!",
747                        (long int)size_written, (long int)size_read);
748         return -1;
749     }
750
751     return 0;
752 }
753
754
755 static int connect_to_host(const char *hostname, const char *port) {
756     struct addrinfo gai_hints;
757     struct addrinfo *gai_result;
758     int gai_return;
759
760     int server_socket;
761     struct addrinfo *server;
762
763     if (hostname == NULL || port == NULL) {
764         return -1;
765     }
766
767     /* Get IP of hostname server. */
768     memset(&gai_hints, 0, sizeof(gai_hints));
769     gai_hints.ai_family   = AF_UNSPEC;
770     gai_hints.ai_socktype = SOCK_STREAM;
771     gai_hints.ai_protocol = 0;
772     gai_hints.ai_flags    = AI_NUMERICSERV /* given port is numeric */
773                           | AI_ADDRCONFIG  /* supported by this computer */
774                           | AI_V4MAPPED;   /* support IPv4 through IPv6 */
775     gai_return = getaddrinfo(hostname, port, &gai_hints, &gai_result);
776     if (gai_return != 0) {
777         LOG_PERROR(LOG_WARNING, "connect_to_host(): getaddrinfo()");
778         return -1;
779     }
780
781     /* Now try to connect to each server returned by getaddrinfo(), use the
782      * first successful connect. */
783     for (server = gai_result; server != NULL; server = server->ai_next) {
784         server_socket = socket(server->ai_family,
785                                server->ai_socktype,
786                                server->ai_protocol);
787         if (server_socket == -1) {
788             LOG_PERROR(LOG_DEBUG, "connect_to_host(): socket(), trying next");
789             continue;
790         }
791
792         if (connect(server_socket, server->ai_addr, server->ai_addrlen) != -1) {
793             break;
794         }
795         LOG_PERROR(LOG_DEBUG, "connect_to_host(): connect(), trying next");
796
797         close(server_socket);
798     }
799     /* Make sure we free the result from getaddrinfo(). */
800     freeaddrinfo(gai_result);
801
802     if (server == NULL) {
803         LOG_PERROR(LOG_WARNING, "connect_to_host(): no server found, abort");
804         return -1;
805     }
806
807     return server_socket;
808 }
809
810
811 /* Parse HTTP CONNECT request string and save its parameters.
812  *
813  * The following format is expected: "CONNECT host:port HTTP/1.x".
814  *
815  * request and host must have the same size! port must be at least 6 bytes
816  * long (5 + '\0').
817  */
818 static int parse_request(const char *request, char *host, char *port,
819                                               int *version_minor) {
820     int port_unused; /* just used to verify the port is numeric */
821     char *position;
822
823     /* scanf() doesn't check spaces. */
824     if (strncmp(request, "CONNECT ", 8)) {
825         return -1;
826     }
827     /* Check request and extract data, "host:port" is not yet separated. */
828     if (sscanf(request, "CONNECT %s HTTP/1.%d", host, version_minor) != 2) {
829         return -1;
830     }
831     /* Make sure ":port" is there. */
832     if ((position = strchr(host, ':')) == NULL) {
833         return -1;
834     }
835     /* Make sure port is numeric. */
836     if (sscanf(position + 1, "%d", &port_unused) != 1) {
837         return -1;
838     }
839     /* Store it in *port. */
840     strncpy(port, position + 1, 5);
841     port[5] = '\0';
842     /* And remove port from host. */
843     *position = '\0';
844
845     return 0;
846 }