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