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