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