]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - proxy.c
Support for doing DNS at the proxy end. I've invented a new type of
[PuTTY.git] / proxy.c
1 /*
2  * Network proxy abstraction in PuTTY
3  *
4  * A proxy layer, if necessary, wedges itself between the network
5  * code and the higher level backend.
6  */
7
8 #include <assert.h>
9 #include <ctype.h>
10 #include <string.h>
11
12 #define DEFINE_PLUG_METHOD_MACROS
13 #include "putty.h"
14 #include "network.h"
15 #include "proxy.h"
16
17 #define do_proxy_dns \
18     (cfg.proxy_dns == 2 || \
19          (cfg.proxy_dns == 1 && cfg.proxy_type != PROXY_SOCKS))
20
21 /*
22  * Call this when proxy negotiation is complete, so that this
23  * socket can begin working normally.
24  */
25 void proxy_activate (Proxy_Socket p)
26 {
27     void *data;
28     int len;
29     long output_before, output_after;
30     
31     p->state = PROXY_STATE_ACTIVE;
32
33     /* we want to ignore new receive events until we have sent
34      * all of our buffered receive data.
35      */
36     sk_set_frozen(p->sub_socket, 1);
37
38     /* how many bytes of output have we buffered? */
39     output_before = bufchain_size(&p->pending_oob_output_data) +
40         bufchain_size(&p->pending_output_data);
41     /* and keep track of how many bytes do not get sent. */
42     output_after = 0;
43     
44     /* send buffered OOB writes */
45     while (bufchain_size(&p->pending_oob_output_data) > 0) {
46         bufchain_prefix(&p->pending_oob_output_data, &data, &len);
47         output_after += sk_write_oob(p->sub_socket, data, len);
48         bufchain_consume(&p->pending_oob_output_data, len);
49     }
50
51     /* send buffered normal writes */
52     while (bufchain_size(&p->pending_output_data) > 0) {
53         bufchain_prefix(&p->pending_output_data, &data, &len);
54         output_after += sk_write(p->sub_socket, data, len);
55         bufchain_consume(&p->pending_output_data, len);
56     }
57
58     /* if we managed to send any data, let the higher levels know. */
59     if (output_after < output_before)
60         plug_sent(p->plug, output_after);
61
62     /* if we were asked to flush the output during
63      * the proxy negotiation process, do so now.
64      */
65     if (p->pending_flush) sk_flush(p->sub_socket);
66
67     /* if the backend wanted the socket unfrozen, try to unfreeze.
68      * our set_frozen handler will flush buffered receive data before
69      * unfreezing the actual underlying socket.
70      */
71     if (!p->freeze)
72         sk_set_frozen((Socket)p, 0);
73 }
74
75 /* basic proxy socket functions */
76
77 static Plug sk_proxy_plug (Socket s, Plug p)
78 {
79     Proxy_Socket ps = (Proxy_Socket) s;
80     Plug ret = ps->plug;
81     if (p)
82         ps->plug = p;
83     return ret;
84 }
85
86 static void sk_proxy_close (Socket s)
87 {
88     Proxy_Socket ps = (Proxy_Socket) s;
89
90     sk_close(ps->sub_socket);
91     sfree(ps);
92 }
93
94 static int sk_proxy_write (Socket s, char *data, int len)
95 {
96     Proxy_Socket ps = (Proxy_Socket) s;
97
98     if (ps->state != PROXY_STATE_ACTIVE) {
99         bufchain_add(&ps->pending_output_data, data, len);
100         return bufchain_size(&ps->pending_output_data);
101     }
102     return sk_write(ps->sub_socket, data, len);
103 }
104
105 static int sk_proxy_write_oob (Socket s, char *data, int len)
106 {
107     Proxy_Socket ps = (Proxy_Socket) s;
108
109     if (ps->state != PROXY_STATE_ACTIVE) {
110         bufchain_clear(&ps->pending_output_data);
111         bufchain_clear(&ps->pending_oob_output_data);
112         bufchain_add(&ps->pending_oob_output_data, data, len);
113         return len;
114     }
115     return sk_write_oob(ps->sub_socket, data, len);
116 }
117
118 static void sk_proxy_flush (Socket s)
119 {
120     Proxy_Socket ps = (Proxy_Socket) s;
121
122     if (ps->state != PROXY_STATE_ACTIVE) {
123         ps->pending_flush = 1;
124         return;
125     }
126     sk_flush(ps->sub_socket);
127 }
128
129 static void sk_proxy_set_private_ptr (Socket s, void *ptr)
130 {
131     Proxy_Socket ps = (Proxy_Socket) s;
132     sk_set_private_ptr(ps->sub_socket, ptr);
133 }
134
135 static void * sk_proxy_get_private_ptr (Socket s)
136 {
137     Proxy_Socket ps = (Proxy_Socket) s;
138     return sk_get_private_ptr(ps->sub_socket);
139 }
140
141 static void sk_proxy_set_frozen (Socket s, int is_frozen)
142 {
143     Proxy_Socket ps = (Proxy_Socket) s;
144
145     if (ps->state != PROXY_STATE_ACTIVE) {
146         ps->freeze = is_frozen;
147         return;
148     }
149     
150     /* handle any remaining buffered recv data first */
151     if (bufchain_size(&ps->pending_input_data) > 0) {
152         ps->freeze = is_frozen;
153
154         /* loop while we still have buffered data, and while we are
155          * unfrozen. the plug_receive call in the loop could result 
156          * in a call back into this function refreezing the socket, 
157          * so we have to check each time.
158          */
159         while (!ps->freeze && bufchain_size(&ps->pending_input_data) > 0) {
160             void *data;
161             int len;
162             bufchain_prefix(&ps->pending_input_data, &data, &len);
163             plug_receive(ps->plug, 0, data, len);
164             bufchain_consume(&ps->pending_input_data, len);
165         }
166
167         /* if we're still frozen, we'll have to wait for another
168          * call from the backend to finish unbuffering the data.
169          */
170         if (ps->freeze) return;
171     }
172     
173     sk_set_frozen(ps->sub_socket, is_frozen);
174 }
175
176 static char * sk_proxy_socket_error (Socket s)
177 {
178     Proxy_Socket ps = (Proxy_Socket) s;
179     if (ps->error != NULL || ps->sub_socket == NULL) {
180         return ps->error;
181     }
182     return sk_socket_error(ps->sub_socket);
183 }
184
185 /* basic proxy plug functions */
186
187 static int plug_proxy_closing (Plug p, char *error_msg,
188                                int error_code, int calling_back)
189 {
190     Proxy_Plug pp = (Proxy_Plug) p;
191     Proxy_Socket ps = pp->proxy_socket;
192
193     if (ps->state != PROXY_STATE_ACTIVE) {
194         ps->closing_error_msg = error_msg;
195         ps->closing_error_code = error_code;
196         ps->closing_calling_back = calling_back;
197         return ps->negotiate(ps, PROXY_CHANGE_CLOSING);
198     }
199     return plug_closing(ps->plug, error_msg,
200                         error_code, calling_back);
201 }
202
203 static int plug_proxy_receive (Plug p, int urgent, char *data, int len)
204 {
205     Proxy_Plug pp = (Proxy_Plug) p;
206     Proxy_Socket ps = pp->proxy_socket;
207
208     if (ps->state != PROXY_STATE_ACTIVE) {
209         /* we will lose the urgentness of this data, but since most,
210          * if not all, of this data will be consumed by the negotiation
211          * process, hopefully it won't affect the protocol above us
212          */
213         bufchain_add(&ps->pending_input_data, data, len);
214         ps->receive_urgent = urgent;
215         ps->receive_data = data;
216         ps->receive_len = len;
217         return ps->negotiate(ps, PROXY_CHANGE_RECEIVE);
218     }
219     return plug_receive(ps->plug, urgent, data, len);
220 }
221
222 static void plug_proxy_sent (Plug p, int bufsize)
223 {
224     Proxy_Plug pp = (Proxy_Plug) p;
225     Proxy_Socket ps = pp->proxy_socket;
226
227     if (ps->state != PROXY_STATE_ACTIVE) {
228         ps->sent_bufsize = bufsize;
229         ps->negotiate(ps, PROXY_CHANGE_SENT);
230         return;
231     }
232     plug_sent(ps->plug, bufsize);
233 }
234
235 static int plug_proxy_accepting (Plug p, void *sock)
236 {
237     Proxy_Plug pp = (Proxy_Plug) p;
238     Proxy_Socket ps = pp->proxy_socket;
239
240     if (ps->state != PROXY_STATE_ACTIVE) {
241         ps->accepting_sock = sock;
242         return ps->negotiate(ps, PROXY_CHANGE_ACCEPTING);
243     }
244     return plug_accepting(ps->plug, sock);
245 }
246
247 /*
248  * This function can accept a NULL pointer as `addr', in which case
249  * it will only check the host name.
250  */
251 static int proxy_for_destination (SockAddr addr, char * hostname, int port)
252 {
253     int s = 0, e = 0;
254     char hostip[64];
255     int hostip_len, hostname_len;
256     char * exclude_list;
257
258     /*
259      * Check the host name and IP against the hard-coded
260      * representations of `localhost'.
261      */
262     if (!cfg.even_proxy_localhost &&
263         (sk_hostname_is_local(hostname) ||
264          (addr && sk_address_is_local(addr))))
265         return 0;                      /* do not proxy */
266
267     /* we want a string representation of the IP address for comparisons */
268     if (addr) {
269         sk_getaddr(addr, hostip, 64);
270         hostip_len = strlen(hostip);
271     }
272
273     hostname_len = strlen(hostname);
274
275     exclude_list = cfg.proxy_exclude_list;
276
277     /* now parse the exclude list, and see if either our IP
278      * or hostname matches anything in it.
279      */
280
281     while (exclude_list[s]) {
282         while (exclude_list[s] &&
283                (isspace(exclude_list[s]) ||
284                 exclude_list[s] == ',')) s++;
285
286         if (!exclude_list[s]) break;
287
288         e = s;
289
290         while (exclude_list[e] &&
291                (isalnum(exclude_list[e]) ||
292                 exclude_list[e] == '-' ||
293                 exclude_list[e] == '.' ||
294                 exclude_list[e] == '*')) e++;
295
296         if (exclude_list[s] == '*') {
297             /* wildcard at beginning of entry */
298
299             if ((addr && strnicmp(hostip + hostip_len - (e - s - 1),
300                                   exclude_list + s + 1, e - s - 1) == 0) ||
301                 strnicmp(hostname + hostname_len - (e - s - 1),
302                          exclude_list + s + 1, e - s - 1) == 0)
303                 return 0; /* IP/hostname range excluded. do not use proxy. */
304
305         } else if (exclude_list[e-1] == '*') {
306             /* wildcard at end of entry */
307
308             if ((addr && strnicmp(hostip, exclude_list + s, e - s - 1) == 0) ||
309                 strnicmp(hostname, exclude_list + s, e - s - 1) == 0)
310                 return 0; /* IP/hostname range excluded. do not use proxy. */
311
312         } else {
313             /* no wildcard at either end, so let's try an absolute
314              * match (ie. a specific IP)
315              */
316
317             if (addr && stricmp(hostip, exclude_list + s) == 0)
318                 return 0; /* IP/hostname excluded. do not use proxy. */
319             if (stricmp(hostname, exclude_list + s) == 0)
320                 return 0; /* IP/hostname excluded. do not use proxy. */
321         }
322
323         s = e;
324     }
325
326     /* no matches in the exclude list, so use the proxy */
327     return 1;
328 }
329
330 SockAddr name_lookup(char *host, int port, char **canonicalname)
331 {
332     if (cfg.proxy_type != PROXY_NONE &&
333         do_proxy_dns && proxy_for_destination(NULL, host, port)) {
334         *canonicalname = dupstr(host);
335         return sk_nonamelookup(host);
336     }
337
338     return sk_namelookup(host, canonicalname);
339 }
340
341 Socket new_connection(SockAddr addr, char *hostname,
342                       int port, int privport,
343                       int oobinline, int nodelay, Plug plug)
344 {
345     static const struct socket_function_table socket_fn_table = {
346         sk_proxy_plug,
347         sk_proxy_close,
348         sk_proxy_write,
349         sk_proxy_write_oob,
350         sk_proxy_flush,
351         sk_proxy_set_private_ptr,
352         sk_proxy_get_private_ptr,
353         sk_proxy_set_frozen,
354         sk_proxy_socket_error
355     };
356
357     static const struct plug_function_table plug_fn_table = {
358         plug_proxy_closing,
359         plug_proxy_receive,
360         plug_proxy_sent,
361         plug_proxy_accepting
362     };
363
364     if (cfg.proxy_type != PROXY_NONE &&
365         proxy_for_destination(addr, hostname, port))
366     {
367         Proxy_Socket ret;
368         Proxy_Plug pplug;
369         SockAddr proxy_addr;
370         char *proxy_canonical_name, *err;
371
372         ret = smalloc(sizeof(struct Socket_proxy_tag));
373         ret->fn = &socket_fn_table;
374         ret->plug = plug;
375         ret->remote_addr = addr;
376         ret->remote_port = port;
377
378         ret->error = NULL;
379         ret->pending_flush = 0;
380         ret->freeze = 0;
381
382         bufchain_init(&ret->pending_input_data);
383         bufchain_init(&ret->pending_output_data);
384         bufchain_init(&ret->pending_oob_output_data);
385
386         ret->sub_socket = NULL;
387         ret->state = PROXY_STATE_NEW;
388         ret->negotiate = NULL;
389         
390         if (cfg.proxy_type == PROXY_HTTP) {
391             ret->negotiate = proxy_http_negotiate;
392         } else if (cfg.proxy_type == PROXY_SOCKS) {
393             if (cfg.proxy_socks_version == 4)
394                 ret->negotiate = proxy_socks4_negotiate;
395             else
396                 ret->negotiate = proxy_socks5_negotiate;
397         } else if (cfg.proxy_type == PROXY_TELNET) {
398             ret->negotiate = proxy_telnet_negotiate;
399         } else {
400             ret->error = "Proxy error: Unknown proxy method";
401             return (Socket) ret;
402         }
403
404         /* create the proxy plug to map calls from the actual
405          * socket into our proxy socket layer */
406         pplug = smalloc(sizeof(struct Plug_proxy_tag));
407         pplug->fn = &plug_fn_table;
408         pplug->proxy_socket = ret;
409
410         /* look-up proxy */
411         proxy_addr = sk_namelookup(cfg.proxy_host,
412                                    &proxy_canonical_name);
413         if ((err = sk_addr_error(proxy_addr))) {
414             ret->error = "Proxy error: Unable to resolve proxy host name";
415             return (Socket)ret;
416         }
417         sfree(proxy_canonical_name);
418
419         /* create the actual socket we will be using,
420          * connected to our proxy server and port.
421          */
422         ret->sub_socket = sk_new(proxy_addr, cfg.proxy_port,
423                                  privport, oobinline,
424                                  nodelay, (Plug) pplug);
425         if (sk_socket_error(ret->sub_socket) != NULL)
426             return (Socket) ret;
427
428         sk_addr_free(proxy_addr);
429
430         /* start the proxy negotiation process... */
431         sk_set_frozen(ret->sub_socket, 0);
432         ret->negotiate(ret, PROXY_CHANGE_NEW);
433
434         return (Socket) ret;
435     }
436
437     /* no proxy, so just return the direct socket */
438     return sk_new(addr, port, privport, oobinline, nodelay, plug);
439 }
440
441 Socket new_listener(char *srcaddr, int port, Plug plug, int local_host_only)
442 {
443     /* TODO: SOCKS (and potentially others) support inbound
444      * TODO: connections via the proxy. support them.
445      */
446
447     return sk_newlistener(srcaddr, port, plug, local_host_only);
448 }
449
450 /* ----------------------------------------------------------------------
451  * HTTP CONNECT proxy type.
452  */
453
454 static int get_line_end (char * data, int len)
455 {
456     int off = 0;
457
458     while (off < len)
459     {
460         if (data[off] == '\n') {
461             /* we have a newline */
462             off++;
463
464             /* is that the only thing on this line? */
465             if (off <= 2) return off;
466
467             /* if not, then there is the possibility that this header
468              * continues onto the next line, if it starts with a space
469              * or a tab.
470              */
471
472             if (off + 1 < len &&
473                 data[off+1] != ' ' &&
474                 data[off+1] != '\t') return off;
475
476             /* the line does continue, so we have to keep going
477              * until we see an the header's "real" end of line.
478              */
479             off++;
480         }
481
482         off++;
483     }
484
485     return -1;
486 }
487
488 int proxy_http_negotiate (Proxy_Socket p, int change)
489 {
490     if (p->state == PROXY_STATE_NEW) {
491         /* we are just beginning the proxy negotiate process,
492          * so we'll send off the initial bits of the request.
493          * for this proxy method, it's just a simple HTTP
494          * request
495          */
496         char *buf, dest[512];
497
498         sk_getaddr(p->remote_addr, dest, lenof(dest));
499
500         buf = dupprintf("CONNECT %s:%i HTTP/1.1\r\nHost: %s:%i\r\n",
501                         dest, p->remote_port, dest, p->remote_port);
502         sk_write(p->sub_socket, buf, strlen(buf));
503         sfree(buf);
504
505         if (cfg.proxy_username[0] || cfg.proxy_password[0]) {
506             char buf[sizeof(cfg.proxy_username)+sizeof(cfg.proxy_password)];
507             char buf2[sizeof(buf)*4/3 + 100];
508             int i, j, len;
509             sprintf(buf, "%s:%s", cfg.proxy_username, cfg.proxy_password);
510             len = strlen(buf);
511             sprintf(buf2, "Proxy-Authorization: basic ");
512             for (i = 0, j = strlen(buf2); i < len; i += 3, j += 4)
513                 base64_encode_atom(buf+i, (len-i > 3 ? 3 : len-i), buf2+j);
514             strcpy(buf2+j, "\r\n");
515             sk_write(p->sub_socket, buf2, strlen(buf2));
516         }
517
518         sk_write(p->sub_socket, "\r\n", 2);
519
520         p->state = 1;
521         return 0;
522     }
523
524     if (change == PROXY_CHANGE_CLOSING) {
525         /* if our proxy negotiation process involves closing and opening
526          * new sockets, then we would want to intercept this closing
527          * callback when we were expecting it. if we aren't anticipating
528          * a socket close, then some error must have occurred. we'll
529          * just pass those errors up to the backend.
530          */
531         return plug_closing(p->plug, p->closing_error_msg,
532                             p->closing_error_code,
533                             p->closing_calling_back);
534     }
535
536     if (change == PROXY_CHANGE_SENT) {
537         /* some (or all) of what we wrote to the proxy was sent.
538          * we don't do anything new, however, until we receive the
539          * proxy's response. we might want to set a timer so we can
540          * timeout the proxy negotiation after a while...
541          */
542         return 0;
543     }
544
545     if (change == PROXY_CHANGE_ACCEPTING) {
546         /* we should _never_ see this, as we are using our socket to
547          * connect to a proxy, not accepting inbound connections.
548          * what should we do? close the socket with an appropriate
549          * error message?
550          */
551         return plug_accepting(p->plug, p->accepting_sock);
552     }
553
554     if (change == PROXY_CHANGE_RECEIVE) {
555         /* we have received data from the underlying socket, which
556          * we'll need to parse, process, and respond to appropriately.
557          */
558
559         char *data, *datap;
560         int len;
561         int eol;
562
563         if (p->state == 1) {
564
565             int min_ver, maj_ver, status;
566
567             /* get the status line */
568             len = bufchain_size(&p->pending_input_data);
569             assert(len > 0);           /* or we wouldn't be here */
570             data = smalloc(len);
571             bufchain_fetch(&p->pending_input_data, data, len);
572
573             eol = get_line_end(data, len);
574             if (eol < 0) {
575                 sfree(data);
576                 return 1;
577             }
578
579             status = -1;
580             /* We can't rely on whether the %n incremented the sscanf return */
581             if (sscanf((char *)data, "HTTP/%i.%i %n",
582                        &maj_ver, &min_ver, &status) < 2 || status == -1) {
583                 plug_closing(p->plug, "Proxy error: HTTP response was absent",
584                              PROXY_ERROR_GENERAL, 0);
585                 sfree(data);
586                 return 1;
587             }
588
589             /* remove the status line from the input buffer. */
590             bufchain_consume(&p->pending_input_data, eol);
591             if (data[status] != '2') {
592                 /* error */
593                 char *buf;
594                 data[eol] = '\0';
595                 while (eol > status &&
596                        (data[eol-1] == '\r' || data[eol-1] == '\n'))
597                     data[--eol] = '\0';
598                 buf = dupprintf("Proxy error: %s", data+status);
599                 plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0);
600                 sfree(buf);
601                 sfree(data);
602                 return 1;
603             }
604
605             sfree(data);
606
607             p->state = 2;
608         }
609
610         if (p->state == 2) {
611
612             /* get headers. we're done when we get a
613              * header of length 2, (ie. just "\r\n")
614              */
615
616             len = bufchain_size(&p->pending_input_data);
617             assert(len > 0);           /* or we wouldn't be here */
618             data = smalloc(len);
619             datap = data;
620             bufchain_fetch(&p->pending_input_data, data, len);
621
622             eol = get_line_end(datap, len);
623             if (eol < 0) {
624                 sfree(data);
625                 return 1;
626             }
627             while (eol > 2)
628             {
629                 bufchain_consume(&p->pending_input_data, eol);
630                 datap += eol;
631                 len   -= eol;
632                 eol = get_line_end(datap, len);
633             }
634
635             if (eol == 2) {
636                 /* we're done */
637                 bufchain_consume(&p->pending_input_data, 2);
638                 proxy_activate(p);
639                 /* proxy activate will have dealt with
640                  * whatever is left of the buffer */
641                 sfree(data);
642                 return 1;
643             }
644
645             sfree(data);
646             return 1;
647         }
648     }
649
650     plug_closing(p->plug, "Proxy error: unexpected proxy error",
651                  PROXY_ERROR_UNEXPECTED, 0);
652     return 1;
653 }
654
655 /* ----------------------------------------------------------------------
656  * SOCKS proxy type.
657  */
658
659 /* SOCKS version 4 */
660 int proxy_socks4_negotiate (Proxy_Socket p, int change)
661 {
662     if (p->state == PROXY_CHANGE_NEW) {
663
664         /* request format:
665          *  version number (1 byte) = 4
666          *  command code (1 byte)
667          *    1 = CONNECT
668          *    2 = BIND
669          *  dest. port (2 bytes) [network order]
670          *  dest. address (4 bytes)
671          *  user ID (variable length, null terminated string)
672          */
673
674         int length, type, namelen;
675         char *command, addr[4], hostname[512];
676
677         type = sk_addrtype(p->remote_addr);
678         if (type == ADDRTYPE_IPV6) {
679             plug_closing(p->plug, "Proxy error: SOCKS version 4 does"
680                          " not support IPv6", PROXY_ERROR_GENERAL, 0);
681             return 1;
682         } else if (type == ADDRTYPE_IPV4) {
683             namelen = 0;
684             sk_addrcopy(p->remote_addr, addr);
685         } else {                       /* type == ADDRTYPE_NAME */
686             sk_getaddr(p->remote_addr, hostname, lenof(hostname));
687             namelen = strlen(hostname) + 1;   /* include the NUL */
688             addr[0] = addr[1] = addr[2] = 0;
689             addr[3] = 1;
690         }
691
692         length = strlen(cfg.proxy_username) + namelen + 9;
693         command = (char*) smalloc(length);
694         strcpy(command + 8, cfg.proxy_username);
695
696         command[0] = 4; /* version 4 */
697         command[1] = 1; /* CONNECT command */
698
699         /* port */
700         command[2] = (char) (p->remote_port >> 8) & 0xff;
701         command[3] = (char) p->remote_port & 0xff;
702
703         /* address */
704         memcpy(command + 4, addr, 4);
705
706         /* hostname */
707         memcpy(command + 8 + strlen(cfg.proxy_username) + 1,
708                hostname, namelen);
709
710         sk_write(p->sub_socket, command, length);
711         sfree(command);
712
713         p->state = 1;
714         return 0;
715     }
716
717     if (change == PROXY_CHANGE_CLOSING) {
718         /* if our proxy negotiation process involves closing and opening
719          * new sockets, then we would want to intercept this closing
720          * callback when we were expecting it. if we aren't anticipating
721          * a socket close, then some error must have occurred. we'll
722          * just pass those errors up to the backend.
723          */
724         return plug_closing(p->plug, p->closing_error_msg,
725                             p->closing_error_code,
726                             p->closing_calling_back);
727     }
728
729     if (change == PROXY_CHANGE_SENT) {
730         /* some (or all) of what we wrote to the proxy was sent.
731          * we don't do anything new, however, until we receive the
732          * proxy's response. we might want to set a timer so we can
733          * timeout the proxy negotiation after a while...
734          */
735         return 0;
736     }
737
738     if (change == PROXY_CHANGE_ACCEPTING) {
739         /* we should _never_ see this, as we are using our socket to
740          * connect to a proxy, not accepting inbound connections.
741          * what should we do? close the socket with an appropriate
742          * error message?
743          */
744         return plug_accepting(p->plug, p->accepting_sock);
745     }
746
747     if (change == PROXY_CHANGE_RECEIVE) {
748         /* we have received data from the underlying socket, which
749          * we'll need to parse, process, and respond to appropriately.
750          */
751
752         if (p->state == 1) {
753             /* response format:
754              *  version number (1 byte) = 4
755              *  reply code (1 byte)
756              *    90 = request granted
757              *    91 = request rejected or failed
758              *    92 = request rejected due to lack of IDENTD on client
759              *    93 = request rejected due to difference in user ID 
760              *         (what we sent vs. what IDENTD said)
761              *  dest. port (2 bytes)
762              *  dest. address (4 bytes)
763              */
764
765             char data[8];
766
767             if (bufchain_size(&p->pending_input_data) < 8)
768                 return 1;              /* not got anything yet */
769             
770             /* get the response */
771             bufchain_fetch(&p->pending_input_data, data, 8);
772
773             if (data[0] != 0) {
774                 plug_closing(p->plug, "Proxy error: SOCKS proxy responded with "
775                                       "unexpected reply code version",
776                              PROXY_ERROR_GENERAL, 0);
777                 return 1;
778             }
779
780             if (data[1] != 90) {
781
782                 switch (data[1]) {
783                   case 92:
784                     plug_closing(p->plug, "Proxy error: SOCKS server wanted IDENTD on client",
785                                  PROXY_ERROR_GENERAL, 0);
786                     break;
787                   case 93:
788                     plug_closing(p->plug, "Proxy error: Username and IDENTD on client don't agree",
789                                  PROXY_ERROR_GENERAL, 0);
790                     break;
791                   case 91:
792                   default:
793                     plug_closing(p->plug, "Proxy error: Error while communicating with proxy",
794                                  PROXY_ERROR_GENERAL, 0);
795                     break;
796                 }
797
798                 return 1;
799             }
800             bufchain_consume(&p->pending_input_data, 8);
801
802             /* we're done */
803             proxy_activate(p);
804             /* proxy activate will have dealt with
805              * whatever is left of the buffer */
806             return 1;
807         }
808     }
809
810     plug_closing(p->plug, "Proxy error: unexpected proxy error",
811                  PROXY_ERROR_UNEXPECTED, 0);
812     return 1;
813 }
814
815 /* SOCKS version 5 */
816 int proxy_socks5_negotiate (Proxy_Socket p, int change)
817 {
818     if (p->state == PROXY_CHANGE_NEW) {
819
820         /* initial command:
821          *  version number (1 byte) = 5
822          *  number of available authentication methods (1 byte)
823          *  available authentication methods (1 byte * previous value)
824          *    authentication methods:
825          *     0x00 = no authentication
826          *     0x01 = GSSAPI
827          *     0x02 = username/password
828          *     0x03 = CHAP
829          */
830
831         char command[4];
832         int len;
833
834         command[0] = 5; /* version 5 */
835         if (cfg.proxy_username[0] || cfg.proxy_password[0]) {
836             command[1] = 2;            /* two methods supported: */
837             command[2] = 0x00;         /* no authentication */
838             command[3] = 0x02;         /* username/password */
839             len = 4;
840         } else {
841             command[1] = 1;            /* one methods supported: */
842             command[2] = 0x00;         /* no authentication */
843             len = 3;
844         }
845
846         sk_write(p->sub_socket, command, len);
847
848         p->state = 1;
849         return 0;
850     }
851
852     if (change == PROXY_CHANGE_CLOSING) {
853         /* if our proxy negotiation process involves closing and opening
854          * new sockets, then we would want to intercept this closing
855          * callback when we were expecting it. if we aren't anticipating
856          * a socket close, then some error must have occurred. we'll
857          * just pass those errors up to the backend.
858          */
859         return plug_closing(p->plug, p->closing_error_msg,
860                             p->closing_error_code,
861                             p->closing_calling_back);
862     }
863
864     if (change == PROXY_CHANGE_SENT) {
865         /* some (or all) of what we wrote to the proxy was sent.
866          * we don't do anything new, however, until we receive the
867          * proxy's response. we might want to set a timer so we can
868          * timeout the proxy negotiation after a while...
869          */
870         return 0;
871     }
872
873     if (change == PROXY_CHANGE_ACCEPTING) {
874         /* we should _never_ see this, as we are using our socket to
875          * connect to a proxy, not accepting inbound connections.
876          * what should we do? close the socket with an appropriate
877          * error message?
878          */
879         return plug_accepting(p->plug, p->accepting_sock);
880     }
881
882     if (change == PROXY_CHANGE_RECEIVE) {
883         /* we have received data from the underlying socket, which
884          * we'll need to parse, process, and respond to appropriately.
885          */
886
887         if (p->state == 1) {
888
889             /* initial response:
890              *  version number (1 byte) = 5
891              *  authentication method (1 byte)
892              *    authentication methods:
893              *     0x00 = no authentication
894              *     0x01 = GSSAPI
895              *     0x02 = username/password 
896              *     0x03 = CHAP
897              *     0xff = no acceptable methods
898              */
899             char data[2];
900
901             if (bufchain_size(&p->pending_input_data) < 2)
902                 return 1;              /* not got anything yet */
903
904             /* get the response */
905             bufchain_fetch(&p->pending_input_data, data, 2);
906
907             if (data[0] != 5) {
908                 plug_closing(p->plug, "Proxy error: SOCKS proxy returned unexpected version",
909                              PROXY_ERROR_GENERAL, 0);
910                 return 1;
911             }
912
913             if (data[1] == 0x00) p->state = 2; /* no authentication needed */
914             else if (data[1] == 0x01) p->state = 4; /* GSSAPI authentication */
915             else if (data[1] == 0x02) p->state = 5; /* username/password authentication */
916             else if (data[1] == 0x03) p->state = 6; /* CHAP authentication */
917             else {
918                 plug_closing(p->plug, "Proxy error: SOCKS proxy did not accept our authentication",
919                              PROXY_ERROR_GENERAL, 0);
920                 return 1;
921             }
922             bufchain_consume(&p->pending_input_data, 2);
923         }
924
925         if (p->state == 7) {
926
927             /* password authentication reply format:
928              *  version number (1 bytes) = 1
929              *  reply code (1 byte)
930              *    0 = succeeded
931              *    >0 = failed
932              */
933             char data[2];
934
935             if (bufchain_size(&p->pending_input_data) < 2)
936                 return 1;              /* not got anything yet */
937
938             /* get the response */
939             bufchain_fetch(&p->pending_input_data, data, 2);
940
941             if (data[0] != 1) {
942                 plug_closing(p->plug, "Proxy error: SOCKS password "
943                              "subnegotiation contained wrong version number",
944                              PROXY_ERROR_GENERAL, 0);
945                 return 1;
946             }
947
948             if (data[1] != 0) {
949
950                 plug_closing(p->plug, "Proxy error: SOCKS proxy refused"
951                              " password authentication",
952                              PROXY_ERROR_GENERAL, 0);
953                 return 1;
954             }
955
956             bufchain_consume(&p->pending_input_data, 2);
957             p->state = 2;              /* now proceed as authenticated */
958         }
959
960         if (p->state == 2) {
961
962             /* request format:
963              *  version number (1 byte) = 5
964              *  command code (1 byte)
965              *    1 = CONNECT
966              *    2 = BIND
967              *    3 = UDP ASSOCIATE
968              *  reserved (1 byte) = 0x00
969              *  address type (1 byte)
970              *    1 = IPv4
971              *    3 = domainname (first byte has length, no terminating null)
972              *    4 = IPv6
973              *  dest. address (variable)
974              *  dest. port (2 bytes) [network order]
975              */
976
977             char command[512];
978             int len;
979             int type;
980
981             type = sk_addrtype(p->remote_addr);
982             if (type == ADDRTYPE_IPV4) {
983                 len = 10;              /* 4 hdr + 4 addr + 2 trailer */
984                 command[3] = 1; /* IPv4 */
985                 sk_addrcopy(p->remote_addr, command+4);
986             } else if (type == ADDRTYPE_IPV6) {
987                 len = 22;              /* 4 hdr + 16 addr + 2 trailer */
988                 command[3] = 4; /* IPv6 */
989                 sk_addrcopy(p->remote_addr, command+4);
990             } else if (type == ADDRTYPE_NAME) {
991                 command[3] = 3;
992                 sk_getaddr(p->remote_addr, command+5, 256);
993                 command[4] = strlen(command+5);
994                 len = 7 + command[4];  /* 4 hdr, 1 len, N addr, 2 trailer */
995             }
996
997             command[0] = 5; /* version 5 */
998             command[1] = 1; /* CONNECT command */
999             command[2] = 0x00;
1000
1001             /* port */
1002             command[len-2] = (char) (p->remote_port >> 8) & 0xff;
1003             command[len-1] = (char) p->remote_port & 0xff;
1004
1005             sk_write(p->sub_socket, command, len);
1006
1007             p->state = 3;
1008             return 1;
1009         }
1010
1011         if (p->state == 3) {
1012
1013             /* reply format:
1014              *  version number (1 bytes) = 5
1015              *  reply code (1 byte)
1016              *    0 = succeeded
1017              *    1 = general SOCKS server failure
1018              *    2 = connection not allowed by ruleset
1019              *    3 = network unreachable
1020              *    4 = host unreachable
1021              *    5 = connection refused
1022              *    6 = TTL expired
1023              *    7 = command not supported
1024              *    8 = address type not supported
1025              * reserved (1 byte) = x00
1026              * address type (1 byte)
1027              *    1 = IPv4
1028              *    3 = domainname (first byte has length, no terminating null)
1029              *    4 = IPv6
1030              * server bound address (variable)
1031              * server bound port (2 bytes) [network order]
1032              */
1033             char data[5];
1034             int len;
1035
1036             /* First 5 bytes of packet are enough to tell its length. */ 
1037             if (bufchain_size(&p->pending_input_data) < 5)
1038                 return 1;              /* not got anything yet */
1039
1040             /* get the response */
1041             bufchain_fetch(&p->pending_input_data, data, 5);
1042
1043             if (data[0] != 5) {
1044                 plug_closing(p->plug, "Proxy error: SOCKS proxy returned wrong version number",
1045                              PROXY_ERROR_GENERAL, 0);
1046                 return 1;
1047             }
1048
1049             if (data[1] != 0) {
1050                 char buf[256];
1051
1052                 strcpy(buf, "Proxy error: ");
1053
1054                 switch (data[1]) {
1055                   case 1: strcat(buf, "General SOCKS server failure"); break;
1056                   case 2: strcat(buf, "Connection not allowed by ruleset"); break;
1057                   case 3: strcat(buf, "Network unreachable"); break;
1058                   case 4: strcat(buf, "Host unreachable"); break;
1059                   case 5: strcat(buf, "Connection refused"); break;
1060                   case 6: strcat(buf, "TTL expired"); break;
1061                   case 7: strcat(buf, "Command not supported"); break;
1062                   case 8: strcat(buf, "Address type not supported"); break;
1063                   default: sprintf(buf+strlen(buf),
1064                                    "Unrecognised SOCKS error code %d",
1065                                    data[1]);
1066                     break;
1067                 }
1068                 plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0);
1069
1070                 return 1;
1071             }
1072
1073             /*
1074              * Eat the rest of the reply packet.
1075              */
1076             len = 6;                   /* first 4 bytes, last 2 */
1077             switch (data[3]) {
1078               case 1: len += 4; break; /* IPv4 address */
1079               case 4: len += 16; break;/* IPv6 address */
1080               case 3: len += (unsigned char)data[4]; break; /* domain name */
1081               default:
1082                 plug_closing(p->plug, "Proxy error: SOCKS proxy returned "
1083                              "unrecognised address format",
1084                              PROXY_ERROR_GENERAL, 0);
1085                 return 1;
1086             }
1087             if (bufchain_size(&p->pending_input_data) < len)
1088                 return 1;              /* not got whole reply yet */
1089             bufchain_consume(&p->pending_input_data, len);
1090
1091             /* we're done */
1092             proxy_activate(p);
1093             return 1;
1094         }
1095
1096         if (p->state == 4) {
1097             /* TODO: Handle GSSAPI authentication */
1098             plug_closing(p->plug, "Proxy error: We don't support GSSAPI authentication",
1099                          PROXY_ERROR_GENERAL, 0);
1100             return 1;
1101         }
1102
1103         if (p->state == 5) {
1104             if (cfg.proxy_username[0] || cfg.proxy_password[0]) {
1105                 char userpwbuf[514];
1106                 int ulen, plen;
1107                 ulen = strlen(cfg.proxy_username);
1108                 if (ulen > 255) ulen = 255; if (ulen < 1) ulen = 1;
1109                 plen = strlen(cfg.proxy_password);
1110                 if (plen > 255) plen = 255; if (plen < 1) plen = 1;
1111                 userpwbuf[0] = 1;      /* version number of subnegotiation */
1112                 userpwbuf[1] = ulen;
1113                 memcpy(userpwbuf+2, cfg.proxy_username, ulen);
1114                 userpwbuf[ulen+2] = plen;
1115                 memcpy(userpwbuf+ulen+3, cfg.proxy_password, plen);
1116                 sk_write(p->sub_socket, userpwbuf, ulen + plen + 3);
1117                 p->state = 7;
1118             } else 
1119                 plug_closing(p->plug, "Proxy error: Server chose "
1120                              "username/password authentication but we "
1121                              "didn't offer it!",
1122                          PROXY_ERROR_GENERAL, 0);
1123             return 1;
1124         }
1125
1126         if (p->state == 6) {
1127             /* TODO: Handle CHAP authentication */
1128             plug_closing(p->plug, "Proxy error: We don't support CHAP authentication",
1129                          PROXY_ERROR_GENERAL, 0);
1130             return 1;
1131         }
1132
1133     }
1134
1135     plug_closing(p->plug, "Proxy error: Unexpected proxy error",
1136                  PROXY_ERROR_UNEXPECTED, 0);
1137     return 1;
1138 }
1139
1140 /* ----------------------------------------------------------------------
1141  * `Telnet' proxy type.
1142  *
1143  * (This is for ad-hoc proxies where you connect to the proxy's
1144  * telnet port and send a command such as `connect host port'. The
1145  * command is configurable, since this proxy type is typically not
1146  * standardised or at all well-defined.)
1147  */
1148
1149 int proxy_telnet_negotiate (Proxy_Socket p, int change)
1150 {
1151     if (p->state == PROXY_CHANGE_NEW) {
1152
1153         int so = 0, eo = 0;
1154
1155         /* we need to escape \\, \%, \r, \n, \t, \x??, \0???, 
1156          * %%, %host, %port, %user, and %pass
1157          */
1158
1159         while (cfg.proxy_telnet_command[eo] != 0) {
1160
1161             /* scan forward until we hit end-of-line, 
1162              * or an escape character (\ or %) */
1163             while (cfg.proxy_telnet_command[eo] != 0 &&
1164                    cfg.proxy_telnet_command[eo] != '%' &&
1165                    cfg.proxy_telnet_command[eo] != '\\') eo++;
1166
1167             /* if we hit eol, break out of our escaping loop */
1168             if (cfg.proxy_telnet_command[eo] == 0) break;
1169
1170             /* if there was any unescaped text before the escape
1171              * character, send that now */
1172             if (eo != so) {
1173                 sk_write(p->sub_socket, 
1174                          cfg.proxy_telnet_command + so, eo - so);
1175             }
1176
1177             so = eo++;
1178
1179             /* if the escape character was the last character of
1180              * the line, we'll just stop and send it. */
1181             if (cfg.proxy_telnet_command[eo] == 0) break;
1182
1183             if (cfg.proxy_telnet_command[so] == '\\') {
1184
1185                 /* we recognize \\, \%, \r, \n, \t, \x??. 
1186                  * anything else, we just send unescaped (including the \). 
1187                  */
1188
1189                 switch (cfg.proxy_telnet_command[eo]) {
1190
1191                   case '\\':
1192                     sk_write(p->sub_socket, "\\", 1);
1193                     eo++;
1194                     break;
1195
1196                   case '%':
1197                     sk_write(p->sub_socket, "%%", 1);
1198                     eo++;
1199                     break;
1200
1201                   case 'r':
1202                     sk_write(p->sub_socket, "\r", 1);
1203                     eo++;
1204                     break;
1205
1206                   case 'n':
1207                     sk_write(p->sub_socket, "\n", 1);
1208                     eo++;
1209                     break;
1210
1211                   case 't':
1212                     sk_write(p->sub_socket, "\t", 1);
1213                     eo++;
1214                     break;
1215
1216                   case 'x':
1217                   case 'X':
1218                     {
1219                     /* escaped hexadecimal value (ie. \xff) */
1220                     unsigned char v = 0;
1221                     int i = 0;
1222
1223                     for (;;) {
1224                         eo++;
1225                         if (cfg.proxy_telnet_command[eo] >= '0' &&
1226                             cfg.proxy_telnet_command[eo] <= '9')
1227                             v += cfg.proxy_telnet_command[eo] - '0';
1228                         else if (cfg.proxy_telnet_command[eo] >= 'a' &&
1229                                  cfg.proxy_telnet_command[eo] <= 'f')
1230                             v += cfg.proxy_telnet_command[eo] - 'a' + 10;
1231                         else if (cfg.proxy_telnet_command[eo] >= 'A' &&
1232                                  cfg.proxy_telnet_command[eo] <= 'F')
1233                             v += cfg.proxy_telnet_command[eo] - 'A' + 10;
1234                         else {
1235                             /* non hex character, so we abort and just
1236                              * send the whole thing unescaped (including \x)
1237                              */
1238                             sk_write(p->sub_socket, "\\", 1);
1239                             eo = so + 1;
1240                             break;
1241                         }
1242
1243                         /* we only extract two hex characters */
1244                         if (i == 1) {
1245                             sk_write(p->sub_socket, &v, 1);
1246                             eo++;
1247                             break;
1248                         }
1249
1250                         i++;
1251                         v <<= 4;
1252                     }
1253                     }
1254                     break;
1255
1256                   default:
1257                     sk_write(p->sub_socket, 
1258                              cfg.proxy_telnet_command + so, 2);
1259                     eo++;
1260                     break;
1261                 }
1262             } else {
1263
1264                 /* % escape. we recognize %%, %host, %port, %user, %pass. 
1265                  * anything else, we just send unescaped (including the %). 
1266                  */
1267
1268                 if (cfg.proxy_telnet_command[eo] == '%') {
1269                     sk_write(p->sub_socket, "%", 1);
1270                     eo++;
1271                 }
1272                 else if (strnicmp(cfg.proxy_telnet_command + eo,
1273                                   "host", 4) == 0) {
1274                     char dest[512];
1275                     sk_getaddr(p->remote_addr, dest, lenof(dest));
1276                     sk_write(p->sub_socket, dest, strlen(dest));
1277                     eo += 4;
1278                 }
1279                 else if (strnicmp(cfg.proxy_telnet_command + eo,
1280                                   "port", 4) == 0) {
1281                     char port[8];
1282                     sprintf(port, "%i", p->remote_port);
1283                     sk_write(p->sub_socket, port, strlen(port));
1284                     eo += 4;
1285                 }
1286                 else if (strnicmp(cfg.proxy_telnet_command + eo,
1287                                   "user", 4) == 0) {
1288                     sk_write(p->sub_socket, cfg.proxy_username, 
1289                         strlen(cfg.proxy_username));
1290                     eo += 4;
1291                 }
1292                 else if (strnicmp(cfg.proxy_telnet_command + eo,
1293                                   "pass", 4) == 0) {
1294                     sk_write(p->sub_socket, cfg.proxy_password, 
1295                         strlen(cfg.proxy_password));
1296                     eo += 4;
1297                 }
1298                 else {
1299                     /* we don't escape this, so send the % now, and
1300                      * don't advance eo, so that we'll consider the
1301                      * text immediately following the % as unescaped.
1302                      */
1303                     sk_write(p->sub_socket, "%", 1);
1304                 }
1305             }
1306
1307             /* resume scanning for additional escapes after this one. */
1308             so = eo;
1309         }
1310
1311         /* if there is any unescaped text at the end of the line, send it */
1312         if (eo != so) {
1313             sk_write(p->sub_socket, cfg.proxy_telnet_command + so, eo - so);
1314         }
1315
1316         p->state = 1;
1317         return 0;
1318     }
1319
1320     if (change == PROXY_CHANGE_CLOSING) {
1321         /* if our proxy negotiation process involves closing and opening
1322          * new sockets, then we would want to intercept this closing
1323          * callback when we were expecting it. if we aren't anticipating
1324          * a socket close, then some error must have occurred. we'll
1325          * just pass those errors up to the backend.
1326          */
1327         return plug_closing(p->plug, p->closing_error_msg,
1328                             p->closing_error_code,
1329                             p->closing_calling_back);
1330     }
1331
1332     if (change == PROXY_CHANGE_SENT) {
1333         /* some (or all) of what we wrote to the proxy was sent.
1334          * we don't do anything new, however, until we receive the
1335          * proxy's response. we might want to set a timer so we can
1336          * timeout the proxy negotiation after a while...
1337          */
1338         return 0;
1339     }
1340
1341     if (change == PROXY_CHANGE_ACCEPTING) {
1342         /* we should _never_ see this, as we are using our socket to
1343          * connect to a proxy, not accepting inbound connections.
1344          * what should we do? close the socket with an appropriate
1345          * error message?
1346          */
1347         return plug_accepting(p->plug, p->accepting_sock);
1348     }
1349
1350     if (change == PROXY_CHANGE_RECEIVE) {
1351         /* we have received data from the underlying socket, which
1352          * we'll need to parse, process, and respond to appropriately.
1353          */
1354
1355         /* we're done */
1356         proxy_activate(p);
1357         /* proxy activate will have dealt with
1358          * whatever is left of the buffer */
1359         return 1;
1360     }
1361
1362     plug_closing(p->plug, "Proxy error: Unexpected proxy error",
1363                  PROXY_ERROR_UNEXPECTED, 0);
1364     return 1;
1365 }