Use strdup_or_die() in remember_connection()
[privoxy.git] / gateway.c
1 const char gateway_rcs[] = "$Id: gateway.c,v 1.88 2012/10/17 18:11:19 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 remembering 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
232    assert(reusable_connection[slot].gateway_host == NULL);
233    assert(reusable_connection[slot].gateway_port == 0);
234    assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
235    assert(reusable_connection[slot].forward_host == NULL);
236    assert(reusable_connection[slot].forward_port == 0);
237
238    reusable_connection[slot].forwarder_type = connection->forwarder_type;
239    if (NULL != connection->gateway_host)
240    {
241       reusable_connection[slot].gateway_host = strdup_or_die(connection->gateway_host);
242    }
243    else
244    {
245       reusable_connection[slot].gateway_host = NULL;
246    }
247    reusable_connection[slot].gateway_port = connection->gateway_port;
248
249    if (NULL != connection->forward_host)
250    {
251       reusable_connection[slot].forward_host = strdup_or_die(connection->forward_host);
252    }
253    else
254    {
255       reusable_connection[slot].forward_host = NULL;
256    }
257    reusable_connection[slot].forward_port = connection->forward_port;
258
259    privoxy_mutex_unlock(&connection_reuse_mutex);
260 }
261 #endif /* def FEATURE_CONNECTION_SHARING */
262
263
264 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
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->forwarder_type = SOCKS_NONE;
288    freez(closed_connection->gateway_host);
289    closed_connection->gateway_port = 0;
290    freez(closed_connection->forward_host);
291    closed_connection->forward_port = 0;
292 }
293 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
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. "
498                "Timestamp made %d seconds ago. Timeout: %d. Latency: %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             break;
505          }
506       }
507    }
508
509    privoxy_mutex_unlock(&connection_reuse_mutex);
510
511    return sfd;
512
513 }
514
515
516 /*********************************************************************
517  *
518  * Function    :  mark_connection_unused
519  *
520  * Description :  Gives a remembered connection free for reuse.
521  *
522  * Parameters  :
523  *          1  :  connection = The connection in question.
524  *
525  * Returns     :  TRUE => Socket found and marked as unused.
526  *                FALSE => Socket not found.
527  *
528  *********************************************************************/
529 static int mark_connection_unused(const struct reusable_connection *connection)
530 {
531    unsigned int slot = 0;
532    int socket_found = FALSE;
533
534    assert(connection->sfd != JB_INVALID_SOCKET);
535
536    privoxy_mutex_lock(&connection_reuse_mutex);
537
538    for (slot = 0; slot < SZ(reusable_connection); slot++)
539    {
540       if (reusable_connection[slot].sfd == connection->sfd)
541       {
542          assert(reusable_connection[slot].in_use);
543          socket_found = TRUE;
544          log_error(LOG_LEVEL_CONNECT,
545             "Marking open socket %d for %s:%d in slot %d as unused.",
546             connection->sfd, reusable_connection[slot].host,
547             reusable_connection[slot].port, slot);
548          reusable_connection[slot].in_use = 0;
549          reusable_connection[slot].timestamp = connection->timestamp;
550          break;
551       }
552    }
553
554    privoxy_mutex_unlock(&connection_reuse_mutex);
555
556    return socket_found;
557
558 }
559
560
561 /*********************************************************************
562  *
563  * Function    :  set_keep_alive_timeout
564  *
565  * Description :  Sets the timeout after which open
566  *                connections will no longer be reused.
567  *
568  * Parameters  :
569  *          1  :  timeout = The timeout in seconds.
570  *
571  * Returns     :  void
572  *
573  *********************************************************************/
574 void set_keep_alive_timeout(unsigned int timeout)
575 {
576    keep_alive_timeout = timeout;
577 }
578 #endif /* def FEATURE_CONNECTION_SHARING */
579
580
581 /*********************************************************************
582  *
583  * Function    :  forwarded_connect
584  *
585  * Description :  Connect to a specified web server, possibly via
586  *                a HTTP proxy and/or a SOCKS proxy.
587  *
588  * Parameters  :
589  *          1  :  fwd = the proxies to use when connecting.
590  *          2  :  http = the http request and apropos headers
591  *          3  :  csp = Current client state (buffers, headers, etc...)
592  *
593  * Returns     :  JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
594  *
595  *********************************************************************/
596 jb_socket forwarded_connect(const struct forward_spec * fwd,
597                             struct http_request *http,
598                             struct client_state *csp)
599 {
600    const char * dest_host;
601    int dest_port;
602    jb_socket sfd = JB_INVALID_SOCKET;
603
604 #ifdef FEATURE_CONNECTION_SHARING
605    if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
606       && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
607    {
608       sfd = get_reusable_connection(http, fwd);
609       if (JB_INVALID_SOCKET != sfd)
610       {
611          return sfd;
612       }
613    }
614 #endif /* def FEATURE_CONNECTION_SHARING */
615
616    /* Figure out if we need to connect to the web server or a HTTP proxy. */
617    if (fwd->forward_host)
618    {
619       /* HTTP proxy */
620       dest_host = fwd->forward_host;
621       dest_port = fwd->forward_port;
622    }
623    else
624    {
625       /* Web server */
626       dest_host = http->host;
627       dest_port = http->port;
628    }
629
630    /* Connect, maybe using a SOCKS proxy */
631    switch (fwd->type)
632    {
633       case SOCKS_NONE:
634          sfd = connect_to(dest_host, dest_port, csp);
635          break;
636       case SOCKS_4:
637       case SOCKS_4A:
638          sfd = socks4_connect(fwd, dest_host, dest_port, csp);
639          break;
640       case SOCKS_5:
641          sfd = socks5_connect(fwd, dest_host, dest_port, csp);
642          break;
643       default:
644          /* Should never get here */
645          log_error(LOG_LEVEL_FATAL,
646             "Internal error in forwarded_connect(). Bad proxy type: %d", fwd->type);
647    }
648
649    if (JB_INVALID_SOCKET != sfd)
650    {
651       log_error(LOG_LEVEL_CONNECT,
652          "Created new connection to %s:%d on socket %d.",
653          http->host, http->port, sfd);
654    }
655
656    return sfd;
657
658 }
659
660
661 /*********************************************************************
662  *
663  * Function    :  socks4_connect
664  *
665  * Description :  Connect to the SOCKS server, and connect through
666  *                it to the specified server.   This handles
667  *                all the SOCKS negotiation, and returns a file
668  *                descriptor for a socket which can be treated as a
669  *                normal (non-SOCKS) socket.
670  *
671  *                Logged error messages are saved to csp->error_message
672  *                and later reused by error_response() for the CGI
673  *                message. strdup allocation failures are handled there.
674  *
675  * Parameters  :
676  *          1  :  fwd = Specifies the SOCKS proxy to use.
677  *          2  :  target_host = The final server to connect to.
678  *          3  :  target_port = The final port to connect to.
679  *          4  :  csp = Current client state (buffers, headers, etc...)
680  *
681  * Returns     :  JB_INVALID_SOCKET => failure, else a socket file descriptor.
682  *
683  *********************************************************************/
684 static jb_socket socks4_connect(const struct forward_spec * fwd,
685                                 const char * target_host,
686                                 int target_port,
687                                 struct client_state *csp)
688 {
689    unsigned long web_server_addr;
690    char buf[BUFFER_SIZE];
691    struct socks_op    *c = (struct socks_op    *)buf;
692    struct socks_reply *s = (struct socks_reply *)buf;
693    size_t n;
694    size_t csiz;
695    jb_socket sfd;
696    int err = 0;
697    char *errstr = NULL;
698
699    if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
700    {
701       /* XXX: Shouldn't the config file parser prevent this? */
702       errstr = "NULL gateway host specified.";
703       err = 1;
704    }
705
706    if (fwd->gateway_port <= 0)
707    {
708       errstr = "invalid gateway port specified.";
709       err = 1;
710    }
711
712    if (err)
713    {
714       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
715       csp->error_message = strdup(errstr);
716       errno = EINVAL;
717       return(JB_INVALID_SOCKET);
718    }
719
720    /* build a socks request for connection to the web server */
721
722    strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
723
724    csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
725
726    switch (fwd->type)
727    {
728       case SOCKS_4:
729          web_server_addr = resolve_hostname_to_ip(target_host);
730          if (web_server_addr == INADDR_NONE)
731          {
732             errstr = "could not resolve target host";
733             log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
734             err = 1;
735          }
736          else
737          {
738             web_server_addr = htonl(web_server_addr);
739          }
740          break;
741       case SOCKS_4A:
742          web_server_addr = 0x00000001;
743          n = csiz + strlen(target_host) + 1;
744          if (n > sizeof(buf))
745          {
746             errno = EINVAL;
747             errstr = "buffer cbuf too small.";
748             log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
749             err = 1;
750          }
751          else
752          {
753             strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
754             /*
755              * What we forward to the socks4a server should have the
756              * size of socks_op, plus the length of the userid plus
757              * its \0 byte (which we don't have to add because the
758              * first byte of the userid is counted twice as it's also
759              * part of sock_op) minus the padding bytes (which are part
760              * of the userid as well), plus the length of the target_host
761              * (which is stored csiz bytes after the beginning of the buffer),
762              * plus another \0 byte.
763              */
764             assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
765             csiz = n;
766          }
767          break;
768       default:
769          /* Should never get here */
770          log_error(LOG_LEVEL_FATAL,
771             "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
772          /* Not reached */
773          return(JB_INVALID_SOCKET);
774    }
775
776    if (err)
777    {
778       csp->error_message = strdup(errstr);
779       return(JB_INVALID_SOCKET);
780    }
781
782    c->vn          = 4;
783    c->cd          = 1;
784    c->dstport[0]  = (unsigned char)((target_port       >> 8 ) & 0xff);
785    c->dstport[1]  = (unsigned char)((target_port            ) & 0xff);
786    c->dstip[0]    = (unsigned char)((web_server_addr   >> 24) & 0xff);
787    c->dstip[1]    = (unsigned char)((web_server_addr   >> 16) & 0xff);
788    c->dstip[2]    = (unsigned char)((web_server_addr   >>  8) & 0xff);
789    c->dstip[3]    = (unsigned char)((web_server_addr        ) & 0xff);
790
791    /* pass the request to the socks server */
792    sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
793
794    if (sfd == JB_INVALID_SOCKET)
795    {
796       /* The error an its reason have already been logged by connect_to()  */
797       return(JB_INVALID_SOCKET);
798    }
799    else if (write_socket(sfd, (char *)c, csiz))
800    {
801       errstr = "SOCKS4 negotiation write failed.";
802       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
803       err = 1;
804       close_socket(sfd);
805    }
806    else if (!data_is_available(sfd, csp->config->socket_timeout))
807    {
808       if (socket_is_still_alive(sfd))
809       {
810          errstr = "SOCKS4 negotiation timed out";
811       }
812       else
813       {
814          errstr = "SOCKS4 negotiation got aborted by the server";
815       }
816       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
817       err = 1;
818       close_socket(sfd);
819    }
820    else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
821    {
822       errstr = "SOCKS4 negotiation read failed.";
823       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
824       err = 1;
825       close_socket(sfd);
826    }
827
828    if (err)
829    {
830       csp->error_message = strdup(errstr);
831       return(JB_INVALID_SOCKET);
832    }
833
834    switch (s->cd)
835    {
836       case SOCKS4_REQUEST_GRANTED:
837          return(sfd);
838       case SOCKS4_REQUEST_REJECT:
839          errstr = "SOCKS request rejected or failed.";
840          errno = EINVAL;
841          break;
842       case SOCKS4_REQUEST_IDENT_FAILED:
843          errstr = "SOCKS request rejected because "
844             "SOCKS server cannot connect to identd on the client.";
845          errno = EACCES;
846          break;
847       case SOCKS4_REQUEST_IDENT_CONFLICT:
848          errstr = "SOCKS request rejected because "
849             "the client program and identd report "
850             "different user-ids.";
851          errno = EACCES;
852          break;
853       default:
854          errno = ENOENT;
855          snprintf(buf, sizeof(buf),
856             "SOCKS request rejected for reason code %d.", s->cd);
857          errstr = buf;
858    }
859
860    log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
861    csp->error_message = strdup(errstr);
862    close_socket(sfd);
863
864    return(JB_INVALID_SOCKET);
865
866 }
867
868 /*********************************************************************
869  *
870  * Function    :  translate_socks5_error
871  *
872  * Description :  Translates a SOCKS errors to a string.
873  *
874  * Parameters  :
875  *          1  :  socks_error = The error code to translate.
876  *
877  * Returns     :  The string translation.
878  *
879  *********************************************************************/
880 static const char *translate_socks5_error(int socks_error)
881 {
882    switch (socks_error)
883    {
884       /* XXX: these should be more descriptive */
885       case SOCKS5_REQUEST_FAILED:
886          return "SOCKS5 request failed";
887       case SOCKS5_REQUEST_DENIED:
888          return "SOCKS5 request denied";
889       case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
890          return "SOCKS5 network unreachable";
891       case SOCKS5_REQUEST_HOST_UNREACHABLE:
892          return "SOCKS5 host unreachable";
893       case SOCKS5_REQUEST_CONNECTION_REFUSED:
894          return "SOCKS5 connection refused";
895       case SOCKS5_REQUEST_TTL_EXPIRED:
896          return "SOCKS5 TTL expired";
897       case SOCKS5_REQUEST_PROTOCOL_ERROR:
898          return "SOCKS5 client protocol error";
899       case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
900          return "SOCKS5 domain names unsupported";
901       case SOCKS5_REQUEST_GRANTED:
902          return "everything's peachy";
903       default:
904          return "SOCKS5 negotiation protocol error";
905    }
906 }
907
908 /*********************************************************************
909  *
910  * Function    :  socks5_connect
911  *
912  * Description :  Connect to the SOCKS server, and connect through
913  *                it to the specified server.   This handles
914  *                all the SOCKS negotiation, and returns a file
915  *                descriptor for a socket which can be treated as a
916  *                normal (non-SOCKS) socket.
917  *
918  * Parameters  :
919  *          1  :  fwd = Specifies the SOCKS proxy to use.
920  *          2  :  target_host = The final server to connect to.
921  *          3  :  target_port = The final port to connect to.
922  *          4  :  csp = Current client state (buffers, headers, etc...)
923  *
924  * Returns     :  JB_INVALID_SOCKET => failure, else a socket file descriptor.
925  *
926  *********************************************************************/
927 static jb_socket socks5_connect(const struct forward_spec *fwd,
928                                 const char *target_host,
929                                 int target_port,
930                                 struct client_state *csp)
931 {
932    int err = 0;
933    char cbuf[300];
934    char sbuf[10];
935    size_t client_pos = 0;
936    int server_size = 0;
937    size_t hostlen = 0;
938    jb_socket sfd;
939    const char *errstr = NULL;
940
941    assert(fwd->gateway_host);
942    if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
943    {
944       errstr = "NULL gateway host specified";
945       err = 1;
946    }
947
948    if (fwd->gateway_port <= 0)
949    {
950       /*
951        * XXX: currently this can't happen because in
952        * case of invalid gateway ports we use the defaults.
953        * Of course we really shouldn't do that.
954        */
955       errstr = "invalid gateway port specified";
956       err = 1;
957    }
958
959    hostlen = strlen(target_host);
960    if (hostlen > (size_t)255)
961    {
962       errstr = "target host name is longer than 255 characters";
963       err = 1;
964    }
965
966    if (fwd->type != SOCKS_5)
967    {
968       /* Should never get here */
969       log_error(LOG_LEVEL_FATAL,
970          "SOCKS5 impossible internal error - bad SOCKS type");
971       err = 1;
972    }
973
974    if (err)
975    {
976       errno = EINVAL;
977       assert(errstr != NULL);
978       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
979       csp->error_message = strdup(errstr);
980       return(JB_INVALID_SOCKET);
981    }
982
983    /* pass the request to the socks server */
984    sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
985
986    if (sfd == JB_INVALID_SOCKET)
987    {
988       errstr = "socks5 server unreachable";
989       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
990       /* Free the generic error message provided by connect_to() */
991       freez(csp->error_message);
992       csp->error_message = strdup(errstr);
993       return(JB_INVALID_SOCKET);
994    }
995
996    client_pos = 0;
997    cbuf[client_pos++] = '\x05'; /* Version */
998    cbuf[client_pos++] = '\x01'; /* One authentication method supported */
999    cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1000
1001    if (write_socket(sfd, cbuf, client_pos))
1002    {
1003       errstr = "SOCKS5 negotiation write failed";
1004       csp->error_message = strdup(errstr);
1005       log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1006       close_socket(sfd);
1007       return(JB_INVALID_SOCKET);
1008    }
1009
1010    if (!data_is_available(sfd, csp->config->socket_timeout))
1011    {
1012       if (socket_is_still_alive(sfd))
1013       {
1014          errstr = "SOCKS5 negotiation timed out";
1015       }
1016       else
1017       {
1018          errstr = "SOCKS5 negotiation got aborted by the server";
1019       }
1020       err = 1;
1021    }
1022
1023    if (!err && read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1024    {
1025       errstr = "SOCKS5 negotiation read failed";
1026       err = 1;
1027    }
1028
1029    if (!err && (sbuf[0] != '\x05'))
1030    {
1031       errstr = "SOCKS5 negotiation protocol version error";
1032       err = 1;
1033    }
1034
1035    if (!err && (sbuf[1] == '\xff'))
1036    {
1037       errstr = "SOCKS5 authentication required";
1038       err = 1;
1039    }
1040
1041    if (!err && (sbuf[1] != '\x00'))
1042    {
1043       errstr = "SOCKS5 negotiation protocol error";
1044       err = 1;
1045    }
1046
1047    if (err)
1048    {
1049       assert(errstr != NULL);
1050       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1051       csp->error_message = strdup(errstr);
1052       close_socket(sfd);
1053       errno = EINVAL;
1054       return(JB_INVALID_SOCKET);
1055    }
1056
1057    client_pos = 0;
1058    cbuf[client_pos++] = '\x05'; /* Version */
1059    cbuf[client_pos++] = '\x01'; /* TCP connect */
1060    cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1061    cbuf[client_pos++] = '\x03'; /* Address is domain name */
1062    cbuf[client_pos++] = (char)(hostlen & 0xffu);
1063    assert(sizeof(cbuf) - client_pos > (size_t)255);
1064    /* Using strncpy because we really want the nul byte padding. */
1065    strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1066    client_pos += (hostlen & 0xffu);
1067    cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1068    cbuf[client_pos++] = (char)((target_port     ) & 0xff);
1069
1070    if (write_socket(sfd, cbuf, client_pos))
1071    {
1072       errstr = "SOCKS5 negotiation write failed";
1073       csp->error_message = strdup(errstr);
1074       log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1075       close_socket(sfd);
1076       errno = EINVAL;
1077       return(JB_INVALID_SOCKET);
1078    }
1079
1080    server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1081    if (server_size != sizeof(sbuf))
1082    {
1083       errstr = "SOCKS5 negotiation read failed";
1084    }
1085    else
1086    {
1087       if (sbuf[0] != '\x05')
1088       {
1089          errstr = "SOCKS5 negotiation protocol version error";
1090       }
1091       else if (sbuf[2] != '\x00')
1092       {
1093          errstr = "SOCKS5 negotiation protocol error";
1094       }
1095       else if (sbuf[1] != SOCKS5_REQUEST_GRANTED)
1096       {
1097          errstr = translate_socks5_error(sbuf[1]);
1098       }
1099       else
1100       {
1101          return(sfd);
1102       }
1103    }
1104
1105    assert(errstr != NULL);
1106    csp->error_message = strdup(errstr);
1107    log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1108    close_socket(sfd);
1109    errno = EINVAL;
1110
1111    return(JB_INVALID_SOCKET);
1112
1113 }
1114
1115 /*
1116   Local Variables:
1117   tab-width: 3
1118   end:
1119 */