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