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