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