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