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