merge Debian changes from 3.0.7 to 3.0.10
[privoxy.git] / gateway.c
1 const char gateway_rcs[] = "$Id: gateway.c,v 1.25 2008/02/07 18:09:46 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  *                proxy).
9  *
10  * Copyright   :  Written by and Copyright (C) 2001-2007 the SourceForge
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  * Revisions   :
36  *    $Log: gateway.c,v $
37  *    Revision 1.25  2008/02/07 18:09:46  fabiankeil
38  *    In socks5_connect:
39  *    - make the buffers quite a bit smaller.
40  *    - properly report "socks5 server unreachable" failures.
41  *    - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
42  *      wrong, but requires too much thinking as it doesn't depend on the buffer size.
43  *    - log a message if the socks5 server sends more data than expected.
44  *    - add some assertions and comments.
45  *
46  *    Revision 1.24  2008/02/04 14:56:29  fabiankeil
47  *    - Fix a compiler warning.
48  *    - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
49  *
50  *    Revision 1.23  2008/02/04 13:11:35  fabiankeil
51  *    Remember the cause of the SOCKS5 error for the CGI message.
52  *
53  *    Revision 1.22  2008/02/03 13:46:15  fabiankeil
54  *    Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
55  *
56  *    Revision 1.21  2007/07/28 12:30:03  fabiankeil
57  *    Modified patch from Song Weijia (#1762559) to
58  *    fix socks requests on big-endian platforms.
59  *
60  *    Revision 1.20  2007/05/14 10:23:48  fabiankeil
61  *    - Use strlcpy() instead of strcpy().
62  *    - Use the same buffer for socks requests and socks responses.
63  *    - Fix bogus warning about web_server_addr being used uninitialized.
64  *
65  *    Revision 1.19  2007/01/25 14:09:45  fabiankeil
66  *    - Save errors in socks4_connect() to csp->error_message.
67  *    - Silence some gcc43 warnings, hopefully the right way.
68  *
69  *    Revision 1.18  2006/07/18 14:48:46  david__schmidt
70  *    Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
71  *    with what was really the latest development (the v_3_0_branch branch)
72  *
73  *    Revision 1.16  2002/05/12 21:36:29  jongfoster
74  *    Correcting function comments
75  *
76  *    Revision 1.15  2002/03/26 22:29:54  swa
77  *    we have a new homepage!
78  *
79  *    Revision 1.14  2002/03/24 13:25:43  swa
80  *    name change related issues
81  *
82  *    Revision 1.13  2002/03/13 00:29:59  jongfoster
83  *    Killing warnings
84  *
85  *    Revision 1.12  2002/03/09 20:03:52  jongfoster
86  *    - Making various functions return int rather than size_t.
87  *      (Undoing a recent change).  Since size_t is unsigned on
88  *      Windows, functions like read_socket that return -1 on
89  *      error cannot return a size_t.
90  *
91  *      THIS WAS A MAJOR BUG - it caused frequent, unpredictable
92  *      crashes, and also frequently caused JB to jump to 100%
93  *      CPU and stay there.  (Because it thought it had just
94  *      read ((unsigned)-1) == 4Gb of data...)
95  *
96  *    - The signature of write_socket has changed, it now simply
97  *      returns success=0/failure=nonzero.
98  *
99  *    - Trying to get rid of a few warnings --with-debug on
100  *      Windows, I've introduced a new type "jb_socket".  This is
101  *      used for the socket file descriptors.  On Windows, this
102  *      is SOCKET (a typedef for unsigned).  Everywhere else, it's
103  *      an int.  The error value can't be -1 any more, so it's
104  *      now JB_INVALID_SOCKET (which is -1 on UNIX, and in
105  *      Windows it maps to the #define INVALID_SOCKET.)
106  *
107  *    - The signature of bind_port has changed.
108  *
109  *    Revision 1.11  2002/03/08 17:46:04  jongfoster
110  *    Fixing int/size_t warnings
111  *
112  *    Revision 1.10  2002/03/07 03:50:19  oes
113  *     - Improved handling of failed DNS lookups
114  *     - Fixed compiler warnings
115  *
116  *    Revision 1.9  2001/10/25 03:40:48  david__schmidt
117  *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
118  *    threads to call select() simultaneously.  So, it's time to do a real, live,
119  *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
120  *    (native). Both versions will work, but using __OS2__ offers multi-threading.
121  *
122  *    Revision 1.8  2001/09/13 20:10:12  jongfoster
123  *    Fixing missing #include under Windows
124  *
125  *    Revision 1.7  2001/09/12 17:58:26  steudten
126  *
127  *    add #include <string.h>
128  *
129  *    Revision 1.6  2001/09/10 10:41:16  oes
130  *    Added #include in.h
131  *
132  *    Revision 1.5  2001/07/29 18:47:57  jongfoster
133  *    Adding missing #include project.h
134  *
135  *    Revision 1.4  2001/07/24 12:47:06  oes
136  *    Applied BeOS support update by Eugenia
137  *
138  *    Revision 1.3  2001/06/09 10:55:28  jongfoster
139  *    Changing BUFSIZ ==> BUFFER_SIZE
140  *
141  *    Revision 1.2  2001/06/07 23:11:38  jongfoster
142  *    Removing gateways[] list - no longer used.
143  *    Replacing function pointer in struct gateway with a directly
144  *    called function forwarded_connect(), which can do the common
145  *    task of deciding whether to connect to the web server or HTTP
146  *    proxy.
147  *    Replacing struct gateway with struct forward_spec
148  *    Fixing bug with SOCKS4A and HTTP proxy server in combination.
149  *    It was a bug which led to the connection being made to the web
150  *    server rather than the HTTP proxy, and also a buffer overrun.
151  *
152  *    Revision 1.1.1.1  2001/05/15 13:58:54  oes
153  *    Initial import of version 2.9.3 source tree
154  *
155  *
156  *********************************************************************/
157 \f
158
159 #include "config.h"
160
161 #include <stdio.h>
162 #include <sys/types.h>
163
164 #ifndef _WIN32
165 #include <netinet/in.h>
166 #endif
167
168 #include <errno.h>
169 #include <string.h>
170 #include "assert.h"
171
172 #ifdef _WIN32
173 #include <winsock2.h>
174 #endif /* def _WIN32 */
175
176 #ifdef __BEOS__
177 #include <netdb.h>
178 #endif /* def __BEOS__ */
179
180 #ifdef __OS2__
181 #include <utils.h>
182 #endif /* def __OS2__ */
183
184 #include "project.h"
185 #include "jcc.h"
186 #include "errlog.h"
187 #include "jbsockets.h"
188 #include "gateway.h"
189 #include "miscutil.h"
190
191 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
192
193 static jb_socket socks4_connect(const struct forward_spec * fwd,
194                                 const char * target_host,
195                                 int target_port,
196                                 struct client_state *csp);
197
198 static jb_socket socks5_connect(const struct forward_spec *fwd,
199                                 const char *target_host,
200                                 int target_port,
201                                 struct client_state *csp);
202
203
204 #define SOCKS_REQUEST_GRANTED          90
205 #define SOCKS_REQUEST_REJECT           91
206 #define SOCKS_REQUEST_IDENT_FAILED     92
207 #define SOCKS_REQUEST_IDENT_CONFLICT   93
208
209 #define SOCKS5_REQUEST_GRANTED             0
210 #define SOCKS5_REQUEST_FAILED              1
211 #define SOCKS5_REQUEST_DENIED              2
212 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
213 #define SOCKS5_REQUEST_HOST_UNREACHABLE    4
214 #define SOCKS5_REQUEST_CONNECTION_REFUSED  5
215 #define SOCKS5_REQUEST_TTL_EXPIRED         6
216 #define SOCKS5_REQUEST_PROTOCOL_ERROR      7
217 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE    8
218
219 /* structure of a socks client operation */
220 struct socks_op {
221    unsigned char vn;          /* socks version number */
222    unsigned char cd;          /* command code */
223    unsigned char dstport[2];  /* destination port */
224    unsigned char dstip[4];    /* destination address */
225    char userid;               /* first byte of userid */
226    char padding[3];           /* make sure sizeof(struct socks_op) is endian-independent. */
227    /* more bytes of the userid follow, terminated by a NULL */
228 };
229
230 /* structure of a socks server reply */
231 struct socks_reply {
232    unsigned char vn;          /* socks version number */
233    unsigned char cd;          /* command code */
234    unsigned char dstport[2];  /* destination port */
235    unsigned char dstip[4];    /* destination address */
236 };
237
238 static const char socks_userid[] = "anonymous";
239
240
241 /*********************************************************************
242  *
243  * Function    :  forwarded_connect
244  *
245  * Description :  Connect to a specified web server, possibly via
246  *                a HTTP proxy and/or a SOCKS proxy.
247  *
248  * Parameters  :
249  *          1  :  fwd = the proxies to use when connecting.
250  *          2  :  http = the http request and apropos headers
251  *          3  :  csp = Current client state (buffers, headers, etc...)
252  *
253  * Returns     :  JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
254  *
255  *********************************************************************/
256 jb_socket forwarded_connect(const struct forward_spec * fwd,
257                             struct http_request *http,
258                             struct client_state *csp)
259 {
260    const char * dest_host;
261    int dest_port;
262
263    /* Figure out if we need to connect to the web server or a HTTP proxy. */
264    if (fwd->forward_host)
265    {
266       /* HTTP proxy */
267       dest_host = fwd->forward_host;
268       dest_port = fwd->forward_port;
269    }
270    else
271    {
272       /* Web server */
273       dest_host = http->host;
274       dest_port = http->port;
275    }
276
277    /* Connect, maybe using a SOCKS proxy */
278    switch (fwd->type)
279    {
280       case SOCKS_NONE:
281          return (connect_to(dest_host, dest_port, csp));
282
283       case SOCKS_4:
284       case SOCKS_4A:
285          return (socks4_connect(fwd, dest_host, dest_port, csp));
286
287       case SOCKS_5:
288          return (socks5_connect(fwd, dest_host, dest_port, csp));
289
290       default:
291          /* Should never get here */
292          log_error(LOG_LEVEL_FATAL, "SOCKS4 impossible internal error - bad SOCKS type.");
293          errno = EINVAL;
294          return(JB_INVALID_SOCKET);
295    }
296 }
297
298
299 /*********************************************************************
300  *
301  * Function    :  socks4_connect
302  *
303  * Description :  Connect to the SOCKS server, and connect through
304  *                it to the specified server.   This handles
305  *                all the SOCKS negotiation, and returns a file
306  *                descriptor for a socket which can be treated as a
307  *                normal (non-SOCKS) socket.
308  *
309  *                Logged error messages are saved to csp->error_message
310  *                and later reused by error_response() for the CGI
311  *                message. strdup allocation failures are handled there.
312  *
313  * Parameters  :
314  *          1  :  fwd = Specifies the SOCKS proxy to use.
315  *          2  :  target_host = The final server to connect to.
316  *          3  :  target_port = The final port to connect to.
317  *          4  :  csp = Current client state (buffers, headers, etc...)
318  *
319  * Returns     :  JB_INVALID_SOCKET => failure, else a socket file descriptor.
320  *
321  *********************************************************************/
322 static jb_socket socks4_connect(const struct forward_spec * fwd,
323                                 const char * target_host,
324                                 int target_port,
325                                 struct client_state *csp)
326 {
327    unsigned int web_server_addr;
328    char buf[BUFFER_SIZE];
329    struct socks_op    *c = (struct socks_op    *)buf;
330    struct socks_reply *s = (struct socks_reply *)buf;
331    size_t n;
332    size_t csiz;
333    jb_socket sfd;
334    int err = 0;
335    char *errstr = NULL;
336
337    if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
338    {
339       /* XXX: Shouldn't the config file parser prevent this? */
340       errstr = "NULL gateway host specified.";
341       err = 1;
342    }
343
344    if (fwd->gateway_port <= 0)
345    {
346       errstr = "invalid gateway port specified.";
347       err = 1;
348    }
349
350    if (err)
351    {
352       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
353       csp->error_message = strdup(errstr); 
354       errno = EINVAL;
355       return(JB_INVALID_SOCKET);
356    }
357
358    /* build a socks request for connection to the web server */
359
360    strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
361
362    csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
363
364    switch (fwd->type)
365    {
366       case SOCKS_4:
367          web_server_addr = resolve_hostname_to_ip(target_host);
368          if (web_server_addr == INADDR_NONE)
369          {
370             errstr = "could not resolve target host";
371             log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
372             err = 1;
373          }
374          else
375          {
376             web_server_addr = htonl(web_server_addr);
377          }
378          break;
379       case SOCKS_4A:
380          web_server_addr = 0x00000001;
381          n = csiz + strlen(target_host) + 1;
382          if (n > sizeof(buf))
383          {
384             errno = EINVAL;
385             errstr = "buffer cbuf too small.";
386             log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
387             err = 1;
388          }
389          else
390          {
391             strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
392             /*
393              * What we forward to the socks4a server should have the
394              * size of socks_op, plus the length of the userid plus
395              * its \0 byte (which we don't have to add because the
396              * first byte of the userid is counted twice as it's also
397              * part of sock_op) minus the padding bytes (which are part
398              * of the userid as well), plus the length of the target_host
399              * (which is stored csiz bytes after the beginning of the buffer),
400              * plus another \0 byte.
401              */
402             assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
403             csiz = n;
404          }
405          break;
406       default:
407          /* Should never get here */
408          log_error(LOG_LEVEL_FATAL,
409             "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
410          /* Not reached */
411          return(JB_INVALID_SOCKET);
412    }
413
414    if (err)
415    {
416       csp->error_message = strdup(errstr);
417       return(JB_INVALID_SOCKET);
418    }
419
420    c->vn          = 4;
421    c->cd          = 1;
422    c->dstport[0]  = (unsigned char)((target_port       >> 8  ) & 0xff);
423    c->dstport[1]  = (unsigned char)((target_port             ) & 0xff);
424    c->dstip[0]    = (unsigned char)((web_server_addr   >> 24 ) & 0xff);
425    c->dstip[1]    = (unsigned char)((web_server_addr   >> 16 ) & 0xff);
426    c->dstip[2]    = (unsigned char)((web_server_addr   >>  8 ) & 0xff);
427    c->dstip[3]    = (unsigned char)((web_server_addr         ) & 0xff);
428
429    /* pass the request to the socks server */
430    sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
431
432    if (sfd == JB_INVALID_SOCKET)
433    {
434       /*
435        * XXX: connect_to should fill in the exact reason.
436        * Most likely resolving the IP of the forwarder failed.
437        */
438       errstr = "connect_to failed: see logfile for details";
439       err = 1;
440    }
441    else if (write_socket(sfd, (char *)c, csiz))
442    {
443       errstr = "SOCKS4 negotiation write failed.";
444       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
445       err = 1;
446       close_socket(sfd);
447    }
448    else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
449    {
450       errstr = "SOCKS4 negotiation read failed.";
451       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
452       err = 1;
453       close_socket(sfd);
454    }
455
456    if (err)
457    {
458       csp->error_message = strdup(errstr);      
459       return(JB_INVALID_SOCKET);
460    }
461
462    switch (s->cd)
463    {
464       case SOCKS_REQUEST_GRANTED:
465          return(sfd);
466          break;
467       case SOCKS_REQUEST_REJECT:
468          errstr = "SOCKS request rejected or failed.";
469          errno = EINVAL;
470          break;
471       case SOCKS_REQUEST_IDENT_FAILED:
472          errstr = "SOCKS request rejected because "
473             "SOCKS server cannot connect to identd on the client.";
474          errno = EACCES;
475          break;
476       case SOCKS_REQUEST_IDENT_CONFLICT:
477          errstr = "SOCKS request rejected because "
478             "the client program and identd report "
479             "different user-ids.";
480          errno = EACCES;
481          break;
482       default:
483          errno = ENOENT;
484          snprintf(buf, sizeof(buf),
485             "SOCKS request rejected for reason code %d.", s->cd);
486          errstr = buf;
487    }
488
489    log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
490    csp->error_message = strdup(errstr);
491    close_socket(sfd);
492
493    return(JB_INVALID_SOCKET);
494
495 }
496
497 /*********************************************************************
498  *
499  * Function    :  translate_socks5_error
500  *
501  * Description :  Translates a SOCKS errors to a string.
502  *
503  * Parameters  :
504  *          1  :  socks_error = The error code to translate.
505  *
506  * Returns     :  The string translation.
507  *
508  *********************************************************************/
509 static const char *translate_socks5_error(int socks_error)
510 {
511    switch (socks_error)
512    {
513       /* XXX: these should be more descriptive */
514       case SOCKS5_REQUEST_FAILED:
515          return "SOCKS5 request failed";
516       case SOCKS5_REQUEST_DENIED:
517          return "SOCKS5 request denied";
518       case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
519          return "SOCKS5 network unreachable";
520       case SOCKS5_REQUEST_HOST_UNREACHABLE:
521          return "SOCKS5 host unreachable";
522       case SOCKS5_REQUEST_CONNECTION_REFUSED:
523          return "SOCKS5 connection refused";
524       case SOCKS5_REQUEST_TTL_EXPIRED:
525          return "SOCKS5 TTL expired";
526       case SOCKS5_REQUEST_PROTOCOL_ERROR:
527          return "SOCKS5 client protocol error";
528       case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
529          return "SOCKS5 domain names unsupported";
530       case SOCKS5_REQUEST_GRANTED:
531          return "everything's peachy";
532       default:
533          return "SOCKS5 negotiation protocol error";
534    }
535 }
536
537 /*********************************************************************
538  *
539  * Function    :  socks5_connect
540  *
541  * Description :  Connect to the SOCKS server, and connect through
542  *                it to the specified server.   This handles
543  *                all the SOCKS negotiation, and returns a file
544  *                descriptor for a socket which can be treated as a
545  *                normal (non-SOCKS) socket.
546  *
547  * Parameters  :
548  *          1  :  fwd = Specifies the SOCKS proxy to use.
549  *          2  :  target_host = The final server to connect to.
550  *          3  :  target_port = The final port to connect to.
551  *          4  :  csp = Current client state (buffers, headers, etc...)
552  *
553  * Returns     :  JB_INVALID_SOCKET => failure, else a socket file descriptor.
554  *
555  *********************************************************************/
556 static jb_socket socks5_connect(const struct forward_spec *fwd,
557                                 const char *target_host,
558                                 int target_port,
559                                 struct client_state *csp)
560 {
561    int err = 0;
562    char cbuf[300];
563    char sbuf[30];
564    size_t client_pos = 0;
565    int server_size = 0;
566    size_t hostlen = 0;
567    jb_socket sfd;
568    const char *errstr = NULL;
569
570    assert(fwd->gateway_host);
571    if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
572    {
573       errstr = "NULL gateway host specified";
574       err = 1;
575    }
576
577    if (fwd->gateway_port <= 0)
578    {
579       /*
580        * XXX: currently this can't happen because in
581        * case of invalid gateway ports we use the defaults.
582        * Of course we really shouldn't do that.
583        */
584       errstr = "invalid gateway port specified";
585       err = 1;
586    }
587
588    hostlen = strlen(target_host);
589    if (hostlen > 255)
590    {
591       errstr = "target host name is longer than 255 characters";
592       err = 1;
593    }
594
595    if (fwd->type != SOCKS_5)
596    {
597       /* Should never get here */
598       log_error(LOG_LEVEL_FATAL,
599          "SOCKS5 impossible internal error - bad SOCKS type");
600       err = 1;
601    }
602
603    if (err)
604    {
605       errno = EINVAL;
606       assert(errstr != NULL);
607       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
608       csp->error_message = strdup(errstr);
609       return(JB_INVALID_SOCKET);
610    }
611
612    /* pass the request to the socks server */
613    sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
614
615    if (sfd == JB_INVALID_SOCKET)
616    {
617       errstr = "socks5 server unreachable";
618       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
619       csp->error_message = strdup(errstr);
620       return(JB_INVALID_SOCKET);
621    }
622
623    client_pos = 0;
624    cbuf[client_pos++] = '\x05'; /* Version */
625    cbuf[client_pos++] = '\x01'; /* One authentication method supported */
626    cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
627
628    if (write_socket(sfd, cbuf, client_pos))
629    {
630       errstr = "SOCKS5 negotiation write failed";
631       csp->error_message = strdup(errstr);
632       log_error(LOG_LEVEL_CONNECT, "%s", errstr);
633       close_socket(sfd);
634       return(JB_INVALID_SOCKET);
635    }
636
637    if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
638    {
639       errstr = "SOCKS5 negotiation read failed";
640       err = 1;
641    }
642
643    if (!err && (sbuf[0] != '\x05'))
644    {
645       errstr = "SOCKS5 negotiation protocol version error";
646       err = 1;
647    }
648
649    if (!err && (sbuf[1] == '\xff'))
650    {
651       errstr = "SOCKS5 authentication required";
652       err = 1;
653    }
654
655    if (!err && (sbuf[1] != '\x00'))
656    {
657       errstr = "SOCKS5 negotiation protocol error";
658       err = 1;
659    }
660
661    if (err)
662    {
663       assert(errstr != NULL);
664       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
665       csp->error_message = strdup(errstr);
666       close_socket(sfd);
667       errno = EINVAL;
668       return(JB_INVALID_SOCKET);
669    }
670
671    client_pos = 0;
672    cbuf[client_pos++] = '\x05'; /* Version */
673    cbuf[client_pos++] = '\x01'; /* TCP connect */
674    cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
675    cbuf[client_pos++] = '\x03'; /* Address is domain name */
676    cbuf[client_pos++] = (char)(hostlen & 0xffu);
677    assert(sizeof(cbuf) - client_pos > 255);
678    /* Using strncpy because we really want the nul byte padding. */
679    strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
680    client_pos += (hostlen & 0xffu);
681    cbuf[client_pos++] = (char)((target_port >> 8) & 0xffu);
682    cbuf[client_pos++] = (char)((target_port     ) & 0xffu);
683
684    if (write_socket(sfd, cbuf, client_pos))
685    {
686       errstr = "SOCKS5 negotiation read failed";
687       csp->error_message = strdup(errstr);
688       log_error(LOG_LEVEL_CONNECT, "%s", errstr);
689       close_socket(sfd);
690       errno = EINVAL;
691       return(JB_INVALID_SOCKET);
692    }
693
694    server_size = read_socket(sfd, sbuf, sizeof(sbuf));
695    if (server_size < 3)
696    {
697       errstr = "SOCKS5 negotiation read failed";
698       err = 1;
699    }
700    else if (server_size > 20)
701    {
702       /* This is somewhat unexpected but doesn't realy matter. */
703       log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
704          "from socks server. Would have accepted up to %d.",
705          server_size, sizeof(sbuf));
706    }
707
708    if (!err && (sbuf[0] != '\x05'))
709    {
710       errstr = "SOCKS5 negotiation protocol version error";
711       err = 1;
712    }
713
714    if (!err && (sbuf[2] != '\x00'))
715    {
716       errstr = "SOCKS5 negotiation protocol error";
717       err = 1;
718    }
719
720    if (!err)
721    {
722       if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
723       {
724          return(sfd);
725       }
726       errstr = translate_socks5_error(sbuf[1]);
727       err = 1;
728    }
729
730    assert(errstr != NULL);
731    csp->error_message = strdup(errstr);
732    log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
733    close_socket(sfd);
734    errno = EINVAL;
735
736    return(JB_INVALID_SOCKET);
737
738 }
739
740 /*
741   Local Variables:
742   tab-width: 3
743   end:
744 */