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