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