Move string_move() into miscutil.c and make it extern
[privoxy.git] / gateway.c
1 const char gateway_rcs[] = "$Id: gateway.c,v 1.91 2012/10/21 12:56:38 fabiankeil Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/gateway.c,v $
5  *
6  * Purpose     :  Contains functions to connect to a server, possibly
7  *                using a "forwarder" (i.e. HTTP proxy and/or a SOCKS4
8  *                or SOCKS5 proxy).
9  *
10  * Copyright   :  Written by and Copyright (C) 2001-2009 the
11  *                Privoxy team. http://www.privoxy.org/
12  *
13  *                Based on the Internet Junkbuster originally written
14  *                by and Copyright (C) 1997 Anonymous Coders and
15  *                Junkbusters Corporation.  http://www.junkbusters.com
16  *
17  *                This program is free software; you can redistribute it
18  *                and/or modify it under the terms of the GNU General
19  *                Public License as published by the Free Software
20  *                Foundation; either version 2 of the License, or (at
21  *                your option) any later version.
22  *
23  *                This program is distributed in the hope that it will
24  *                be useful, but WITHOUT ANY WARRANTY; without even the
25  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
26  *                PARTICULAR PURPOSE.  See the GNU General Public
27  *                License for more details.
28  *
29  *                The GNU General Public License should be included with
30  *                this file.  If not, you can view it at
31  *                http://www.gnu.org/copyleft/gpl.html
32  *                or write to the Free Software Foundation, Inc., 59
33  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
34  *
35  *********************************************************************/
36
37
38 #include "config.h"
39
40 #include <stdio.h>
41 #include <sys/types.h>
42
43 #ifndef _WIN32
44 #include <netinet/in.h>
45 #endif
46
47 #include <errno.h>
48 #include <string.h>
49 #include "assert.h"
50
51 #ifdef _WIN32
52 #include <winsock2.h>
53 #endif /* def _WIN32 */
54
55 #ifdef __BEOS__
56 #include <netdb.h>
57 #endif /* def __BEOS__ */
58
59 #ifdef __OS2__
60 #include <utils.h>
61 #endif /* def __OS2__ */
62
63 #include "project.h"
64 #include "jcc.h"
65 #include "errlog.h"
66 #include "jbsockets.h"
67 #include "gateway.h"
68 #include "miscutil.h"
69 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
70 #ifdef HAVE_POLL
71 #ifdef __GLIBC__
72 #include <sys/poll.h>
73 #else
74 #include <poll.h>
75 #endif /* def __GLIBC__ */
76 #endif /* HAVE_POLL */
77 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
78
79 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
80
81 static jb_socket socks4_connect(const struct forward_spec * fwd,
82                                 const char * target_host,
83                                 int target_port,
84                                 struct client_state *csp);
85
86 static jb_socket socks5_connect(const struct forward_spec *fwd,
87                                 const char *target_host,
88                                 int target_port,
89                                 struct client_state *csp);
90
91 enum {
92    SOCKS4_REQUEST_GRANTED        =  90,
93    SOCKS4_REQUEST_REJECT         =  91,
94    SOCKS4_REQUEST_IDENT_FAILED   =  92,
95    SOCKS4_REQUEST_IDENT_CONFLICT =  93
96 };
97
98 enum {
99    SOCKS5_REQUEST_GRANTED             = 0,
100    SOCKS5_REQUEST_FAILED              = 1,
101    SOCKS5_REQUEST_DENIED              = 2,
102    SOCKS5_REQUEST_NETWORK_UNREACHABLE = 3,
103    SOCKS5_REQUEST_HOST_UNREACHABLE    = 4,
104    SOCKS5_REQUEST_CONNECTION_REFUSED  = 5,
105    SOCKS5_REQUEST_TTL_EXPIRED         = 6,
106    SOCKS5_REQUEST_PROTOCOL_ERROR      = 7,
107    SOCKS5_REQUEST_BAD_ADDRESS_TYPE    = 8
108 };
109
110 /* structure of a socks client operation */
111 struct socks_op {
112    unsigned char vn;          /* socks version number */
113    unsigned char cd;          /* command code */
114    unsigned char dstport[2];  /* destination port */
115    unsigned char dstip[4];    /* destination address */
116    char userid;               /* first byte of userid */
117    char padding[3];           /* make sure sizeof(struct socks_op) is endian-independent. */
118    /* more bytes of the userid follow, terminated by a NULL */
119 };
120
121 /* structure of a socks server reply */
122 struct socks_reply {
123    unsigned char vn;          /* socks version number */
124    unsigned char cd;          /* command code */
125    unsigned char dstport[2];  /* destination port */
126    unsigned char dstip[4];    /* destination address */
127 };
128
129 static const char socks_userid[] = "anonymous";
130
131 #ifdef FEATURE_CONNECTION_SHARING
132
133 #define MAX_REUSABLE_CONNECTIONS 100
134 static unsigned int keep_alive_timeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
135
136 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
137 static int mark_connection_unused(const struct reusable_connection *connection);
138
139 /*********************************************************************
140  *
141  * Function    :  initialize_reusable_connections
142  *
143  * Description :  Initializes the reusable_connection structures.
144  *                Must be called with connection_reuse_mutex locked.
145  *
146  * Parameters  : N/A
147  *
148  * Returns     : void
149  *
150  *********************************************************************/
151 extern void initialize_reusable_connections(void)
152 {
153    unsigned int slot = 0;
154
155 #if !defined(HAVE_POLL) && !defined(_WIN32)
156    log_error(LOG_LEVEL_INFO,
157       "Detecting already dead connections might not work "
158       "correctly on your platform. In case of problems, "
159       "unset the keep-alive-timeout option.");
160 #endif
161
162    for (slot = 0; slot < SZ(reusable_connection); slot++)
163    {
164       mark_connection_closed(&reusable_connection[slot]);
165    }
166
167    log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
168 }
169
170
171 /*********************************************************************
172  *
173  * Function    :  remember_connection
174  *
175  * Description :  Remembers a server connection for reuse later on.
176  *
177  * Parameters  :
178  *          1  :  connection = The server connection to remember.
179  *
180  * Returns     : void
181  *
182  *********************************************************************/
183 void remember_connection(const struct reusable_connection *connection)
184 {
185    unsigned int slot = 0;
186    int free_slot_found = FALSE;
187
188    assert(NULL != connection);
189    assert(connection->sfd != JB_INVALID_SOCKET);
190
191    if (mark_connection_unused(connection))
192    {
193       return;
194    }
195
196    privoxy_mutex_lock(&connection_reuse_mutex);
197
198    /* Find free socket slot. */
199    for (slot = 0; slot < SZ(reusable_connection); slot++)
200    {
201       if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
202       {
203          assert(reusable_connection[slot].in_use == 0);
204          log_error(LOG_LEVEL_CONNECT,
205             "Remembering socket %d for %s:%d in slot %d.",
206             connection->sfd, connection->host, connection->port, slot);
207          free_slot_found = TRUE;
208          break;
209       }
210    }
211
212    if (!free_slot_found)
213    {
214       log_error(LOG_LEVEL_CONNECT,
215         "No free slots found to remember socket for %s:%d. Last slot %d.",
216         connection->host, connection->port, slot);
217       privoxy_mutex_unlock(&connection_reuse_mutex);
218       close_socket(connection->sfd);
219       return;
220    }
221
222    assert(NULL != connection->host);
223    reusable_connection[slot].host = strdup_or_die(connection->host);
224    reusable_connection[slot].sfd = connection->sfd;
225    reusable_connection[slot].port = connection->port;
226    reusable_connection[slot].in_use = 0;
227    reusable_connection[slot].timestamp = connection->timestamp;
228    reusable_connection[slot].request_sent = connection->request_sent;
229    reusable_connection[slot].response_received = connection->response_received;
230    reusable_connection[slot].keep_alive_timeout = connection->keep_alive_timeout;
231    reusable_connection[slot].requests_sent_total = connection->requests_sent_total;
232
233    assert(reusable_connection[slot].gateway_host == NULL);
234    assert(reusable_connection[slot].gateway_port == 0);
235    assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
236    assert(reusable_connection[slot].forward_host == NULL);
237    assert(reusable_connection[slot].forward_port == 0);
238
239    reusable_connection[slot].forwarder_type = connection->forwarder_type;
240    if (NULL != connection->gateway_host)
241    {
242       reusable_connection[slot].gateway_host = strdup_or_die(connection->gateway_host);
243    }
244    else
245    {
246       reusable_connection[slot].gateway_host = NULL;
247    }
248    reusable_connection[slot].gateway_port = connection->gateway_port;
249
250    if (NULL != connection->forward_host)
251    {
252       reusable_connection[slot].forward_host = strdup_or_die(connection->forward_host);
253    }
254    else
255    {
256       reusable_connection[slot].forward_host = NULL;
257    }
258    reusable_connection[slot].forward_port = connection->forward_port;
259
260    privoxy_mutex_unlock(&connection_reuse_mutex);
261 }
262 #endif /* def FEATURE_CONNECTION_SHARING */
263
264
265 /*********************************************************************
266  *
267  * Function    :  mark_connection_closed
268  *
269  * Description : Marks a reused connection closed.
270  *
271  * Parameters  :
272  *          1  :  closed_connection = The connection to mark as closed.
273  *
274  * Returns     : void
275  *
276  *********************************************************************/
277 void mark_connection_closed(struct reusable_connection *closed_connection)
278 {
279    closed_connection->in_use = FALSE;
280    closed_connection->sfd = JB_INVALID_SOCKET;
281    freez(closed_connection->host);
282    closed_connection->port = 0;
283    closed_connection->timestamp = 0;
284    closed_connection->request_sent = 0;
285    closed_connection->response_received = 0;
286    closed_connection->keep_alive_timeout = 0;
287    closed_connection->requests_sent_total = 0;
288    closed_connection->forwarder_type = SOCKS_NONE;
289    freez(closed_connection->gateway_host);
290    closed_connection->gateway_port = 0;
291    freez(closed_connection->forward_host);
292    closed_connection->forward_port = 0;
293 }
294
295
296 #ifdef FEATURE_CONNECTION_SHARING
297 /*********************************************************************
298  *
299  * Function    :  forget_connection
300  *
301  * Description :  Removes a previously remembered connection from
302  *                the list of reusable connections.
303  *
304  * Parameters  :
305  *          1  :  sfd = The socket belonging to the connection in question.
306  *
307  * Returns     : void
308  *
309  *********************************************************************/
310 void forget_connection(jb_socket sfd)
311 {
312    unsigned int slot = 0;
313
314    assert(sfd != JB_INVALID_SOCKET);
315
316    privoxy_mutex_lock(&connection_reuse_mutex);
317
318    for (slot = 0; slot < SZ(reusable_connection); slot++)
319    {
320       if (reusable_connection[slot].sfd == sfd)
321       {
322          assert(reusable_connection[slot].in_use);
323
324          log_error(LOG_LEVEL_CONNECT,
325             "Forgetting socket %d for %s:%d in slot %d.",
326             sfd, reusable_connection[slot].host,
327             reusable_connection[slot].port, slot);
328          mark_connection_closed(&reusable_connection[slot]);
329          break;
330       }
331    }
332
333    privoxy_mutex_unlock(&connection_reuse_mutex);
334
335 }
336 #endif /* def FEATURE_CONNECTION_SHARING */
337
338
339 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
340 /*********************************************************************
341  *
342  * Function    :  connection_destination_matches
343  *
344  * Description :  Determines whether a remembered connection can
345  *                be reused. That is, whether the destination and
346  *                the forwarding settings match.
347  *
348  * Parameters  :
349  *          1  :  connection = The connection to check.
350  *          2  :  http = The destination for the connection.
351  *          3  :  fwd  = The forwarder settings.
352  *
353  * Returns     :  TRUE for yes, FALSE otherwise.
354  *
355  *********************************************************************/
356 int connection_destination_matches(const struct reusable_connection *connection,
357                                    const struct http_request *http,
358                                    const struct forward_spec *fwd)
359 {
360    if ((connection->forwarder_type != fwd->type)
361     || (connection->gateway_port   != fwd->gateway_port)
362     || (connection->forward_port   != fwd->forward_port)
363     || (connection->port           != http->port))
364    {
365       return FALSE;
366    }
367
368    if ((    (NULL != connection->gateway_host)
369          && (NULL != fwd->gateway_host)
370          && strcmpic(connection->gateway_host, fwd->gateway_host))
371        && (connection->gateway_host != fwd->gateway_host))
372    {
373       log_error(LOG_LEVEL_CONNECT,
374          "Gateway mismatch. Previous gateway: %s. Current gateway: %s",
375          connection->gateway_host, fwd->gateway_host);
376       return FALSE;
377    }
378
379    if ((    (NULL != connection->forward_host)
380          && (NULL != fwd->forward_host)
381          && strcmpic(connection->forward_host, fwd->forward_host))
382       && (connection->forward_host != fwd->forward_host))
383    {
384       log_error(LOG_LEVEL_CONNECT,
385          "Forwarding proxy mismatch. Previous proxy: %s. Current proxy: %s",
386          connection->forward_host, fwd->forward_host);
387       return FALSE;
388    }
389
390    return (!strcmpic(connection->host, http->host));
391
392 }
393 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
394
395
396 #ifdef FEATURE_CONNECTION_SHARING
397 /*********************************************************************
398  *
399  * Function    :  close_unusable_connections
400  *
401  * Description :  Closes remembered connections that have timed
402  *                out or have been closed on the other side.
403  *
404  * Parameters  :  none
405  *
406  * Returns     :  Number of connections that are still alive.
407  *
408  *********************************************************************/
409 int close_unusable_connections(void)
410 {
411    unsigned int slot = 0;
412    int connections_alive = 0;
413
414    privoxy_mutex_lock(&connection_reuse_mutex);
415
416    for (slot = 0; slot < SZ(reusable_connection); slot++)
417    {
418       if (!reusable_connection[slot].in_use
419          && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
420       {
421          time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
422          time_t latency = (reusable_connection[slot].response_received -
423             reusable_connection[slot].request_sent) / 2;
424
425          if (reusable_connection[slot].keep_alive_timeout < time_open + latency)
426          {
427             log_error(LOG_LEVEL_CONNECT,
428                "The connection to %s:%d in slot %d timed out. "
429                "Closing socket %d. Timeout is: %d. Assumed latency: %d.",
430                reusable_connection[slot].host,
431                reusable_connection[slot].port, slot,
432                reusable_connection[slot].sfd,
433                reusable_connection[slot].keep_alive_timeout,
434                latency);
435             close_socket(reusable_connection[slot].sfd);
436             mark_connection_closed(&reusable_connection[slot]);
437          }
438          else if (!socket_is_still_alive(reusable_connection[slot].sfd))
439          {
440             log_error(LOG_LEVEL_CONNECT,
441                "The connection to %s:%d in slot %d is no longer usable. "
442                "Closing socket %d.", reusable_connection[slot].host,
443                reusable_connection[slot].port, slot,
444                reusable_connection[slot].sfd);
445             close_socket(reusable_connection[slot].sfd);
446             mark_connection_closed(&reusable_connection[slot]);
447          }
448          else
449          {
450             connections_alive++;
451          }
452       }
453    }
454
455    privoxy_mutex_unlock(&connection_reuse_mutex);
456
457    return connections_alive;
458
459 }
460
461
462 /*********************************************************************
463  *
464  * Function    :  get_reusable_connection
465  *
466  * Description :  Returns an open socket to a previously remembered
467  *                open connection (if there is one).
468  *
469  * Parameters  :
470  *          1  :  http = The destination for the connection.
471  *          2  :  fwd  = The forwarder settings.
472  *
473  * Returns     :  JB_INVALID_SOCKET => No reusable connection found,
474  *                otherwise a usable socket.
475  *
476  *********************************************************************/
477 static jb_socket get_reusable_connection(const struct http_request *http,
478                                          const struct forward_spec *fwd)
479 {
480    jb_socket sfd = JB_INVALID_SOCKET;
481    unsigned int slot = 0;
482
483    close_unusable_connections();
484
485    privoxy_mutex_lock(&connection_reuse_mutex);
486
487    for (slot = 0; slot < SZ(reusable_connection); slot++)
488    {
489       if (!reusable_connection[slot].in_use
490          && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
491       {
492          if (connection_destination_matches(&reusable_connection[slot], http, fwd))
493          {
494             reusable_connection[slot].in_use = TRUE;
495             sfd = reusable_connection[slot].sfd;
496             log_error(LOG_LEVEL_CONNECT,
497                "Found reusable socket %d for %s:%d in slot %d. Timestamp made %d "
498                "seconds ago. Timeout: %d. Latency: %d. Requests served: %d",
499                sfd, reusable_connection[slot].host, reusable_connection[slot].port,
500                slot, time(NULL) - reusable_connection[slot].timestamp,
501                reusable_connection[slot].keep_alive_timeout,
502                (int)(reusable_connection[slot].response_received -
503                reusable_connection[slot].request_sent),
504                reusable_connection[slot].requests_sent_total);
505             break;
506          }
507       }
508    }
509
510    privoxy_mutex_unlock(&connection_reuse_mutex);
511
512    return sfd;
513
514 }
515
516
517 /*********************************************************************
518  *
519  * Function    :  mark_connection_unused
520  *
521  * Description :  Gives a remembered connection free for reuse.
522  *
523  * Parameters  :
524  *          1  :  connection = The connection in question.
525  *
526  * Returns     :  TRUE => Socket found and marked as unused.
527  *                FALSE => Socket not found.
528  *
529  *********************************************************************/
530 static int mark_connection_unused(const struct reusable_connection *connection)
531 {
532    unsigned int slot = 0;
533    int socket_found = FALSE;
534
535    assert(connection->sfd != JB_INVALID_SOCKET);
536
537    privoxy_mutex_lock(&connection_reuse_mutex);
538
539    for (slot = 0; slot < SZ(reusable_connection); slot++)
540    {
541       if (reusable_connection[slot].sfd == connection->sfd)
542       {
543          assert(reusable_connection[slot].in_use);
544          socket_found = TRUE;
545          log_error(LOG_LEVEL_CONNECT,
546             "Marking open socket %d for %s:%d in slot %d as unused.",
547             connection->sfd, reusable_connection[slot].host,
548             reusable_connection[slot].port, slot);
549          reusable_connection[slot].in_use = 0;
550          reusable_connection[slot].timestamp = connection->timestamp;
551          break;
552       }
553    }
554
555    privoxy_mutex_unlock(&connection_reuse_mutex);
556
557    return socket_found;
558
559 }
560
561
562 /*********************************************************************
563  *
564  * Function    :  set_keep_alive_timeout
565  *
566  * Description :  Sets the timeout after which open
567  *                connections will no longer be reused.
568  *
569  * Parameters  :
570  *          1  :  timeout = The timeout in seconds.
571  *
572  * Returns     :  void
573  *
574  *********************************************************************/
575 void set_keep_alive_timeout(unsigned int timeout)
576 {
577    keep_alive_timeout = timeout;
578 }
579 #endif /* def FEATURE_CONNECTION_SHARING */
580
581
582 /*********************************************************************
583  *
584  * Function    :  forwarded_connect
585  *
586  * Description :  Connect to a specified web server, possibly via
587  *                a HTTP proxy and/or a SOCKS proxy.
588  *
589  * Parameters  :
590  *          1  :  fwd = the proxies to use when connecting.
591  *          2  :  http = the http request and apropos headers
592  *          3  :  csp = Current client state (buffers, headers, etc...)
593  *
594  * Returns     :  JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
595  *
596  *********************************************************************/
597 jb_socket forwarded_connect(const struct forward_spec * fwd,
598                             struct http_request *http,
599                             struct client_state *csp)
600 {
601    const char * dest_host;
602    int dest_port;
603    jb_socket sfd = JB_INVALID_SOCKET;
604
605 #ifdef FEATURE_CONNECTION_SHARING
606    if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
607       && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
608    {
609       sfd = get_reusable_connection(http, fwd);
610       if (JB_INVALID_SOCKET != sfd)
611       {
612          return sfd;
613       }
614    }
615 #endif /* def FEATURE_CONNECTION_SHARING */
616
617    /* Figure out if we need to connect to the web server or a HTTP proxy. */
618    if (fwd->forward_host)
619    {
620       /* HTTP proxy */
621       dest_host = fwd->forward_host;
622       dest_port = fwd->forward_port;
623    }
624    else
625    {
626       /* Web server */
627       dest_host = http->host;
628       dest_port = http->port;
629    }
630
631    /* Connect, maybe using a SOCKS proxy */
632    switch (fwd->type)
633    {
634       case SOCKS_NONE:
635          sfd = connect_to(dest_host, dest_port, csp);
636          break;
637       case SOCKS_4:
638       case SOCKS_4A:
639          sfd = socks4_connect(fwd, dest_host, dest_port, csp);
640          break;
641       case SOCKS_5:
642          sfd = socks5_connect(fwd, dest_host, dest_port, csp);
643          break;
644       default:
645          /* Should never get here */
646          log_error(LOG_LEVEL_FATAL,
647             "Internal error in forwarded_connect(). Bad proxy type: %d", fwd->type);
648    }
649
650    if (JB_INVALID_SOCKET != sfd)
651    {
652       log_error(LOG_LEVEL_CONNECT,
653          "Created new connection to %s:%d on socket %d.",
654          http->host, http->port, sfd);
655    }
656
657    return sfd;
658
659 }
660
661
662 /*********************************************************************
663  *
664  * Function    :  socks4_connect
665  *
666  * Description :  Connect to the SOCKS server, and connect through
667  *                it to the specified server.   This handles
668  *                all the SOCKS negotiation, and returns a file
669  *                descriptor for a socket which can be treated as a
670  *                normal (non-SOCKS) socket.
671  *
672  *                Logged error messages are saved to csp->error_message
673  *                and later reused by error_response() for the CGI
674  *                message. strdup allocation failures are handled there.
675  *
676  * Parameters  :
677  *          1  :  fwd = Specifies the SOCKS proxy to use.
678  *          2  :  target_host = The final server to connect to.
679  *          3  :  target_port = The final port to connect to.
680  *          4  :  csp = Current client state (buffers, headers, etc...)
681  *
682  * Returns     :  JB_INVALID_SOCKET => failure, else a socket file descriptor.
683  *
684  *********************************************************************/
685 static jb_socket socks4_connect(const struct forward_spec * fwd,
686                                 const char * target_host,
687                                 int target_port,
688                                 struct client_state *csp)
689 {
690    unsigned long web_server_addr;
691    char buf[BUFFER_SIZE];
692    struct socks_op    *c = (struct socks_op    *)buf;
693    struct socks_reply *s = (struct socks_reply *)buf;
694    size_t n;
695    size_t csiz;
696    jb_socket sfd;
697    int err = 0;
698    char *errstr = NULL;
699
700    if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
701    {
702       /* XXX: Shouldn't the config file parser prevent this? */
703       errstr = "NULL gateway host specified.";
704       err = 1;
705    }
706
707    if (fwd->gateway_port <= 0)
708    {
709       errstr = "invalid gateway port specified.";
710       err = 1;
711    }
712
713    if (err)
714    {
715       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
716       csp->error_message = strdup(errstr);
717       errno = EINVAL;
718       return(JB_INVALID_SOCKET);
719    }
720
721    /* build a socks request for connection to the web server */
722
723    strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
724
725    csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
726
727    switch (fwd->type)
728    {
729       case SOCKS_4:
730          web_server_addr = resolve_hostname_to_ip(target_host);
731          if (web_server_addr == INADDR_NONE)
732          {
733             errstr = "could not resolve target host";
734             log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
735             err = 1;
736          }
737          else
738          {
739             web_server_addr = htonl(web_server_addr);
740          }
741          break;
742       case SOCKS_4A:
743          web_server_addr = 0x00000001;
744          n = csiz + strlen(target_host) + 1;
745          if (n > sizeof(buf))
746          {
747             errno = EINVAL;
748             errstr = "buffer cbuf too small.";
749             log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
750             err = 1;
751          }
752          else
753          {
754             strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
755             /*
756              * What we forward to the socks4a server should have the
757              * size of socks_op, plus the length of the userid plus
758              * its \0 byte (which we don't have to add because the
759              * first byte of the userid is counted twice as it's also
760              * part of sock_op) minus the padding bytes (which are part
761              * of the userid as well), plus the length of the target_host
762              * (which is stored csiz bytes after the beginning of the buffer),
763              * plus another \0 byte.
764              */
765             assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
766             csiz = n;
767          }
768          break;
769       default:
770          /* Should never get here */
771          log_error(LOG_LEVEL_FATAL,
772             "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
773          /* Not reached */
774          return(JB_INVALID_SOCKET);
775    }
776
777    if (err)
778    {
779       csp->error_message = strdup(errstr);
780       return(JB_INVALID_SOCKET);
781    }
782
783    c->vn          = 4;
784    c->cd          = 1;
785    c->dstport[0]  = (unsigned char)((target_port       >> 8 ) & 0xff);
786    c->dstport[1]  = (unsigned char)((target_port            ) & 0xff);
787    c->dstip[0]    = (unsigned char)((web_server_addr   >> 24) & 0xff);
788    c->dstip[1]    = (unsigned char)((web_server_addr   >> 16) & 0xff);
789    c->dstip[2]    = (unsigned char)((web_server_addr   >>  8) & 0xff);
790    c->dstip[3]    = (unsigned char)((web_server_addr        ) & 0xff);
791
792    /* pass the request to the socks server */
793    sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
794
795    if (sfd == JB_INVALID_SOCKET)
796    {
797       /* The error an its reason have already been logged by connect_to()  */
798       return(JB_INVALID_SOCKET);
799    }
800    else if (write_socket(sfd, (char *)c, csiz))
801    {
802       errstr = "SOCKS4 negotiation write failed.";
803       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
804       err = 1;
805       close_socket(sfd);
806    }
807    else if (!data_is_available(sfd, csp->config->socket_timeout))
808    {
809       if (socket_is_still_alive(sfd))
810       {
811          errstr = "SOCKS4 negotiation timed out";
812       }
813       else
814       {
815          errstr = "SOCKS4 negotiation got aborted by the server";
816       }
817       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
818       err = 1;
819       close_socket(sfd);
820    }
821    else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
822    {
823       errstr = "SOCKS4 negotiation read failed.";
824       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
825       err = 1;
826       close_socket(sfd);
827    }
828
829    if (err)
830    {
831       csp->error_message = strdup(errstr);
832       return(JB_INVALID_SOCKET);
833    }
834
835    switch (s->cd)
836    {
837       case SOCKS4_REQUEST_GRANTED:
838          return(sfd);
839       case SOCKS4_REQUEST_REJECT:
840          errstr = "SOCKS request rejected or failed.";
841          errno = EINVAL;
842          break;
843       case SOCKS4_REQUEST_IDENT_FAILED:
844          errstr = "SOCKS request rejected because "
845             "SOCKS server cannot connect to identd on the client.";
846          errno = EACCES;
847          break;
848       case SOCKS4_REQUEST_IDENT_CONFLICT:
849          errstr = "SOCKS request rejected because "
850             "the client program and identd report "
851             "different user-ids.";
852          errno = EACCES;
853          break;
854       default:
855          errno = ENOENT;
856          snprintf(buf, sizeof(buf),
857             "SOCKS request rejected for reason code %d.", s->cd);
858          errstr = buf;
859    }
860
861    log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
862    csp->error_message = strdup(errstr);
863    close_socket(sfd);
864
865    return(JB_INVALID_SOCKET);
866
867 }
868
869 /*********************************************************************
870  *
871  * Function    :  translate_socks5_error
872  *
873  * Description :  Translates a SOCKS errors to a string.
874  *
875  * Parameters  :
876  *          1  :  socks_error = The error code to translate.
877  *
878  * Returns     :  The string translation.
879  *
880  *********************************************************************/
881 static const char *translate_socks5_error(int socks_error)
882 {
883    switch (socks_error)
884    {
885       /* XXX: these should be more descriptive */
886       case SOCKS5_REQUEST_FAILED:
887          return "SOCKS5 request failed";
888       case SOCKS5_REQUEST_DENIED:
889          return "SOCKS5 request denied";
890       case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
891          return "SOCKS5 network unreachable";
892       case SOCKS5_REQUEST_HOST_UNREACHABLE:
893          return "SOCKS5 host unreachable";
894       case SOCKS5_REQUEST_CONNECTION_REFUSED:
895          return "SOCKS5 connection refused";
896       case SOCKS5_REQUEST_TTL_EXPIRED:
897          return "SOCKS5 TTL expired";
898       case SOCKS5_REQUEST_PROTOCOL_ERROR:
899          return "SOCKS5 client protocol error";
900       case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
901          return "SOCKS5 domain names unsupported";
902       case SOCKS5_REQUEST_GRANTED:
903          return "everything's peachy";
904       default:
905          return "SOCKS5 negotiation protocol error";
906    }
907 }
908
909 /*********************************************************************
910  *
911  * Function    :  socks5_connect
912  *
913  * Description :  Connect to the SOCKS server, and connect through
914  *                it to the specified server.   This handles
915  *                all the SOCKS negotiation, and returns a file
916  *                descriptor for a socket which can be treated as a
917  *                normal (non-SOCKS) socket.
918  *
919  * Parameters  :
920  *          1  :  fwd = Specifies the SOCKS proxy to use.
921  *          2  :  target_host = The final server to connect to.
922  *          3  :  target_port = The final port to connect to.
923  *          4  :  csp = Current client state (buffers, headers, etc...)
924  *
925  * Returns     :  JB_INVALID_SOCKET => failure, else a socket file descriptor.
926  *
927  *********************************************************************/
928 static jb_socket socks5_connect(const struct forward_spec *fwd,
929                                 const char *target_host,
930                                 int target_port,
931                                 struct client_state *csp)
932 {
933    int err = 0;
934    char cbuf[300];
935    char sbuf[10];
936    size_t client_pos = 0;
937    int server_size = 0;
938    size_t hostlen = 0;
939    jb_socket sfd;
940    const char *errstr = NULL;
941
942    assert(fwd->gateway_host);
943    if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
944    {
945       errstr = "NULL gateway host specified";
946       err = 1;
947    }
948
949    if (fwd->gateway_port <= 0)
950    {
951       /*
952        * XXX: currently this can't happen because in
953        * case of invalid gateway ports we use the defaults.
954        * Of course we really shouldn't do that.
955        */
956       errstr = "invalid gateway port specified";
957       err = 1;
958    }
959
960    hostlen = strlen(target_host);
961    if (hostlen > (size_t)255)
962    {
963       errstr = "target host name is longer than 255 characters";
964       err = 1;
965    }
966
967    if (fwd->type != SOCKS_5)
968    {
969       /* Should never get here */
970       log_error(LOG_LEVEL_FATAL,
971          "SOCKS5 impossible internal error - bad SOCKS type");
972       err = 1;
973    }
974
975    if (err)
976    {
977       errno = EINVAL;
978       assert(errstr != NULL);
979       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
980       csp->error_message = strdup(errstr);
981       return(JB_INVALID_SOCKET);
982    }
983
984    /* pass the request to the socks server */
985    sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
986
987    if (sfd == JB_INVALID_SOCKET)
988    {
989       errstr = "socks5 server unreachable";
990       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
991       /* Free the generic error message provided by connect_to() */
992       freez(csp->error_message);
993       csp->error_message = strdup(errstr);
994       return(JB_INVALID_SOCKET);
995    }
996
997    client_pos = 0;
998    cbuf[client_pos++] = '\x05'; /* Version */
999    cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1000    cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1001
1002    if (write_socket(sfd, cbuf, client_pos))
1003    {
1004       errstr = "SOCKS5 negotiation write failed";
1005       csp->error_message = strdup(errstr);
1006       log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1007       close_socket(sfd);
1008       return(JB_INVALID_SOCKET);
1009    }
1010
1011    if (!data_is_available(sfd, csp->config->socket_timeout))
1012    {
1013       if (socket_is_still_alive(sfd))
1014       {
1015          errstr = "SOCKS5 negotiation timed out";
1016       }
1017       else
1018       {
1019          errstr = "SOCKS5 negotiation got aborted by the server";
1020       }
1021       err = 1;
1022    }
1023
1024    if (!err && read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1025    {
1026       errstr = "SOCKS5 negotiation read failed";
1027       err = 1;
1028    }
1029
1030    if (!err && (sbuf[0] != '\x05'))
1031    {
1032       errstr = "SOCKS5 negotiation protocol version error";
1033       err = 1;
1034    }
1035
1036    if (!err && (sbuf[1] == '\xff'))
1037    {
1038       errstr = "SOCKS5 authentication required";
1039       err = 1;
1040    }
1041
1042    if (!err && (sbuf[1] != '\x00'))
1043    {
1044       errstr = "SOCKS5 negotiation protocol error";
1045       err = 1;
1046    }
1047
1048    if (err)
1049    {
1050       assert(errstr != NULL);
1051       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1052       csp->error_message = strdup(errstr);
1053       close_socket(sfd);
1054       errno = EINVAL;
1055       return(JB_INVALID_SOCKET);
1056    }
1057
1058    client_pos = 0;
1059    cbuf[client_pos++] = '\x05'; /* Version */
1060    cbuf[client_pos++] = '\x01'; /* TCP connect */
1061    cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1062    cbuf[client_pos++] = '\x03'; /* Address is domain name */
1063    cbuf[client_pos++] = (char)(hostlen & 0xffu);
1064    assert(sizeof(cbuf) - client_pos > (size_t)255);
1065    /* Using strncpy because we really want the nul byte padding. */
1066    strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1067    client_pos += (hostlen & 0xffu);
1068    cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1069    cbuf[client_pos++] = (char)((target_port     ) & 0xff);
1070
1071    if (write_socket(sfd, cbuf, client_pos))
1072    {
1073       errstr = "SOCKS5 negotiation write failed";
1074       csp->error_message = strdup(errstr);
1075       log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1076       close_socket(sfd);
1077       errno = EINVAL;
1078       return(JB_INVALID_SOCKET);
1079    }
1080
1081    server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1082    if (server_size != sizeof(sbuf))
1083    {
1084       errstr = "SOCKS5 negotiation read failed";
1085    }
1086    else
1087    {
1088       if (sbuf[0] != '\x05')
1089       {
1090          errstr = "SOCKS5 negotiation protocol version error";
1091       }
1092       else if (sbuf[2] != '\x00')
1093       {
1094          errstr = "SOCKS5 negotiation protocol error";
1095       }
1096       else if (sbuf[1] != SOCKS5_REQUEST_GRANTED)
1097       {
1098          errstr = translate_socks5_error(sbuf[1]);
1099       }
1100       else
1101       {
1102          return(sfd);
1103       }
1104    }
1105
1106    assert(errstr != NULL);
1107    csp->error_message = strdup(errstr);
1108    log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1109    close_socket(sfd);
1110    errno = EINVAL;
1111
1112    return(JB_INVALID_SOCKET);
1113
1114 }
1115
1116 /*
1117   Local Variables:
1118   tab-width: 3
1119   end:
1120 */