]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - proxy.c
first pass
[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 static char *dns_log_msg(const char *host, int addressfamily,
366                          const char *reason)
367 {
368     return dupprintf("Looking up host \"%s\"%s for %s", host,
369                      (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
370                       addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" :
371                       ""), reason);
372 }
373
374 SockAddr name_lookup(const char *host, int port, char **canonicalname,
375                      Conf *conf, int addressfamily, void *frontend,
376                      const char *reason)
377 {
378     char *logmsg;
379     if (conf_get_int(conf, CONF_proxy_type) != PROXY_NONE &&
380         do_proxy_dns(conf) &&
381         proxy_for_destination(NULL, host, port, conf)) {
382
383         if (frontend) {
384             logmsg = dupprintf("Leaving host lookup to proxy of \"%s\""
385                                " (for %s)", host, reason);
386             logevent(frontend, logmsg);
387             sfree(logmsg);
388         }
389
390         *canonicalname = dupstr(host);
391         return sk_nonamelookup(host);
392     } else {
393         if (frontend) {
394             logmsg = dns_log_msg(host, addressfamily, reason);
395             logevent(frontend, logmsg);
396             sfree(logmsg);
397         }
398
399         return sk_namelookup(host, canonicalname, addressfamily);
400     }
401 }
402
403 Socket new_connection(SockAddr addr, const char *hostname,
404                       int port, int privport,
405                       int oobinline, int nodelay, int keepalive,
406                       Plug plug, Conf *conf)
407 {
408     static const struct socket_function_table socket_fn_table = {
409         sk_proxy_plug,
410         sk_proxy_close,
411         sk_proxy_write,
412         sk_proxy_write_oob,
413         sk_proxy_write_eof,
414         sk_proxy_flush,
415         sk_proxy_set_frozen,
416         sk_proxy_socket_error,
417         NULL, /* peer_info */
418     };
419
420     static const struct plug_function_table plug_fn_table = {
421         plug_proxy_log,
422         plug_proxy_closing,
423         plug_proxy_receive,
424         plug_proxy_sent,
425         plug_proxy_accepting
426     };
427
428     if (conf_get_int(conf, CONF_proxy_type) != PROXY_NONE &&
429         proxy_for_destination(addr, hostname, port, conf))
430     {
431         Proxy_Socket ret;
432         Proxy_Plug pplug;
433         SockAddr proxy_addr;
434         char *proxy_canonical_name;
435         const char *proxy_type;
436         Socket sret;
437         int type;
438
439         if ((sret = platform_new_connection(addr, hostname, port, privport,
440                                             oobinline, nodelay, keepalive,
441                                             plug, conf)) !=
442             NULL)
443             return sret;
444
445         ret = snew(struct Socket_proxy_tag);
446         ret->fn = &socket_fn_table;
447         ret->conf = conf_copy(conf);
448         ret->plug = plug;
449         ret->remote_addr = addr;       /* will need to be freed on close */
450         ret->remote_port = port;
451
452         ret->error = NULL;
453         ret->pending_flush = 0;
454         ret->pending_eof = 0;
455         ret->freeze = 0;
456
457         bufchain_init(&ret->pending_input_data);
458         bufchain_init(&ret->pending_output_data);
459         bufchain_init(&ret->pending_oob_output_data);
460
461         ret->sub_socket = NULL;
462         ret->state = PROXY_STATE_NEW;
463         ret->negotiate = NULL;
464
465         type = conf_get_int(conf, CONF_proxy_type);
466         if (type == PROXY_HTTP) {
467             ret->negotiate = proxy_http_negotiate;
468             proxy_type = "HTTP";
469         } else if (type == PROXY_SOCKS4) {
470             ret->negotiate = proxy_socks4_negotiate;
471             proxy_type = "SOCKS 4";
472         } else if (type == PROXY_SOCKS5) {
473             ret->negotiate = proxy_socks5_negotiate;
474             proxy_type = "SOCKS 5";
475         } else if (type == PROXY_TELNET) {
476             ret->negotiate = proxy_telnet_negotiate;
477             proxy_type = "Telnet";
478         } else {
479             ret->error = "Proxy error: Unknown proxy method";
480             return (Socket) ret;
481         }
482
483         {
484             char *logmsg = dupprintf("Will use %s proxy at %s:%d to connect"
485                                       " to %s:%d", proxy_type,
486                                       conf_get_str(conf, CONF_proxy_host),
487                                       conf_get_int(conf, CONF_proxy_port),
488                                       hostname, port);
489             plug_log(plug, 2, NULL, 0, logmsg, 0);
490             sfree(logmsg);
491         }
492
493         /* create the proxy plug to map calls from the actual
494          * socket into our proxy socket layer */
495         pplug = snew(struct Plug_proxy_tag);
496         pplug->fn = &plug_fn_table;
497         pplug->proxy_socket = ret;
498
499         {
500             char *logmsg = dns_log_msg(conf_get_str(conf, CONF_proxy_host),
501                                        conf_get_int(conf, CONF_addressfamily),
502                                        "proxy");
503             plug_log(plug, 2, NULL, 0, logmsg, 0);
504             sfree(logmsg);
505         }
506
507         /* look-up proxy */
508         proxy_addr = sk_namelookup(conf_get_str(conf, CONF_proxy_host),
509                                    &proxy_canonical_name,
510                                    conf_get_int(conf, CONF_addressfamily));
511         if (sk_addr_error(proxy_addr) != NULL) {
512             ret->error = "Proxy error: Unable to resolve proxy host name";
513             sfree(pplug);
514             sk_addr_free(proxy_addr);
515             return (Socket)ret;
516         }
517         sfree(proxy_canonical_name);
518
519         {
520             char addrbuf[256], *logmsg;
521             sk_getaddr(proxy_addr, addrbuf, lenof(addrbuf));
522             logmsg = dupprintf("Connecting to %s proxy at %s port %d",
523                                proxy_type, addrbuf,
524                                conf_get_int(conf, CONF_proxy_port));
525             plug_log(plug, 2, NULL, 0, logmsg, 0);
526             sfree(logmsg);
527         }
528
529         /* create the actual socket we will be using,
530          * connected to our proxy server and port.
531          */
532         ret->sub_socket = sk_new(proxy_addr,
533                                  conf_get_int(conf, CONF_proxy_port),
534                                  privport, oobinline,
535                                  nodelay, keepalive, (Plug) pplug);
536         if (sk_socket_error(ret->sub_socket) != NULL)
537             return (Socket) ret;
538
539         /* start the proxy negotiation process... */
540         sk_set_frozen(ret->sub_socket, 0);
541         ret->negotiate(ret, PROXY_CHANGE_NEW);
542
543         return (Socket) ret;
544     }
545
546     /* no proxy, so just return the direct socket */
547     return sk_new(addr, port, privport, oobinline, nodelay, keepalive, plug);
548 }
549
550 Socket new_listener(const char *srcaddr, int port, Plug plug,
551                     int local_host_only, Conf *conf, int addressfamily)
552 {
553     /* TODO: SOCKS (and potentially others) support inbound
554      * TODO: connections via the proxy. support them.
555      */
556
557     return sk_newlistener(srcaddr, port, plug, local_host_only, addressfamily);
558 }
559
560 /* ----------------------------------------------------------------------
561  * HTTP CONNECT proxy type.
562  */
563
564 static int get_line_end (char * data, int len)
565 {
566     int off = 0;
567
568     while (off < len)
569     {
570         if (data[off] == '\n') {
571             /* we have a newline */
572             off++;
573
574             /* is that the only thing on this line? */
575             if (off <= 2) return off;
576
577             /* if not, then there is the possibility that this header
578              * continues onto the next line, if it starts with a space
579              * or a tab.
580              */
581
582             if (off + 1 < len &&
583                 data[off+1] != ' ' &&
584                 data[off+1] != '\t') return off;
585
586             /* the line does continue, so we have to keep going
587              * until we see an the header's "real" end of line.
588              */
589             off++;
590         }
591
592         off++;
593     }
594
595     return -1;
596 }
597
598 int proxy_http_negotiate (Proxy_Socket p, int change)
599 {
600     if (p->state == PROXY_STATE_NEW) {
601         /* we are just beginning the proxy negotiate process,
602          * so we'll send off the initial bits of the request.
603          * for this proxy method, it's just a simple HTTP
604          * request
605          */
606         char *buf, dest[512];
607         char *username, *password;
608
609         sk_getaddr(p->remote_addr, dest, lenof(dest));
610
611         buf = dupprintf("CONNECT %s:%i HTTP/1.1\r\nHost: %s:%i\r\n",
612                         dest, p->remote_port, dest, p->remote_port);
613         sk_write(p->sub_socket, buf, strlen(buf));
614         sfree(buf);
615
616         username = conf_get_str(p->conf, CONF_proxy_username);
617         password = conf_get_str(p->conf, CONF_proxy_password);
618         if (username[0] || password[0]) {
619             char *buf, *buf2;
620             int i, j, len;
621             buf = dupprintf("%s:%s", username, password);
622             len = strlen(buf);
623             buf2 = snewn(len * 4 / 3 + 100, char);
624             sprintf(buf2, "Proxy-Authorization: Basic ");
625             for (i = 0, j = strlen(buf2); i < len; i += 3, j += 4)
626                 base64_encode_atom((unsigned char *)(buf+i),
627                                    (len-i > 3 ? 3 : len-i), buf2+j);
628             strcpy(buf2+j, "\r\n");
629             sk_write(p->sub_socket, buf2, strlen(buf2));
630             sfree(buf);
631             sfree(buf2);
632         }
633
634         sk_write(p->sub_socket, "\r\n", 2);
635
636         p->state = 1;
637         return 0;
638     }
639
640     if (change == PROXY_CHANGE_CLOSING) {
641         /* if our proxy negotiation process involves closing and opening
642          * new sockets, then we would want to intercept this closing
643          * callback when we were expecting it. if we aren't anticipating
644          * a socket close, then some error must have occurred. we'll
645          * just pass those errors up to the backend.
646          */
647         return plug_closing(p->plug, p->closing_error_msg,
648                             p->closing_error_code,
649                             p->closing_calling_back);
650     }
651
652     if (change == PROXY_CHANGE_SENT) {
653         /* some (or all) of what we wrote to the proxy was sent.
654          * we don't do anything new, however, until we receive the
655          * proxy's response. we might want to set a timer so we can
656          * timeout the proxy negotiation after a while...
657          */
658         return 0;
659     }
660
661     if (change == PROXY_CHANGE_ACCEPTING) {
662         /* we should _never_ see this, as we are using our socket to
663          * connect to a proxy, not accepting inbound connections.
664          * what should we do? close the socket with an appropriate
665          * error message?
666          */
667         return plug_accepting(p->plug,
668                               p->accepting_constructor, p->accepting_ctx);
669     }
670
671     if (change == PROXY_CHANGE_RECEIVE) {
672         /* we have received data from the underlying socket, which
673          * we'll need to parse, process, and respond to appropriately.
674          */
675
676         char *data, *datap;
677         int len;
678         int eol;
679
680         if (p->state == 1) {
681
682             int min_ver, maj_ver, status;
683
684             /* get the status line */
685             len = bufchain_size(&p->pending_input_data);
686             assert(len > 0);           /* or we wouldn't be here */
687             data = snewn(len+1, char);
688             bufchain_fetch(&p->pending_input_data, data, len);
689             /*
690              * We must NUL-terminate this data, because Windows
691              * sscanf appears to require a NUL at the end of the
692              * string because it strlens it _first_. Sigh.
693              */
694             data[len] = '\0';
695
696             eol = get_line_end(data, len);
697             if (eol < 0) {
698                 sfree(data);
699                 return 1;
700             }
701
702             status = -1;
703             /* We can't rely on whether the %n incremented the sscanf return */
704             if (sscanf((char *)data, "HTTP/%i.%i %n",
705                        &maj_ver, &min_ver, &status) < 2 || status == -1) {
706                 plug_closing(p->plug, "Proxy error: HTTP response was absent",
707                              PROXY_ERROR_GENERAL, 0);
708                 sfree(data);
709                 return 1;
710             }
711
712             /* remove the status line from the input buffer. */
713             bufchain_consume(&p->pending_input_data, eol);
714             if (data[status] != '2') {
715                 /* error */
716                 char *buf;
717                 data[eol] = '\0';
718                 while (eol > status &&
719                        (data[eol-1] == '\r' || data[eol-1] == '\n'))
720                     data[--eol] = '\0';
721                 buf = dupprintf("Proxy error: %s", data+status);
722                 plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0);
723                 sfree(buf);
724                 sfree(data);
725                 return 1;
726             }
727
728             sfree(data);
729
730             p->state = 2;
731         }
732
733         if (p->state == 2) {
734
735             /* get headers. we're done when we get a
736              * header of length 2, (ie. just "\r\n")
737              */
738
739             len = bufchain_size(&p->pending_input_data);
740             assert(len > 0);           /* or we wouldn't be here */
741             data = snewn(len, char);
742             datap = data;
743             bufchain_fetch(&p->pending_input_data, data, len);
744
745             eol = get_line_end(datap, len);
746             if (eol < 0) {
747                 sfree(data);
748                 return 1;
749             }
750             while (eol > 2)
751             {
752                 bufchain_consume(&p->pending_input_data, eol);
753                 datap += eol;
754                 len   -= eol;
755                 eol = get_line_end(datap, len);
756             }
757
758             if (eol == 2) {
759                 /* we're done */
760                 bufchain_consume(&p->pending_input_data, 2);
761                 proxy_activate(p);
762                 /* proxy activate will have dealt with
763                  * whatever is left of the buffer */
764                 sfree(data);
765                 return 1;
766             }
767
768             sfree(data);
769             return 1;
770         }
771     }
772
773     plug_closing(p->plug, "Proxy error: unexpected proxy error",
774                  PROXY_ERROR_UNEXPECTED, 0);
775     return 1;
776 }
777
778 /* ----------------------------------------------------------------------
779  * SOCKS proxy type.
780  */
781
782 /* SOCKS version 4 */
783 int proxy_socks4_negotiate (Proxy_Socket p, int change)
784 {
785     if (p->state == PROXY_CHANGE_NEW) {
786
787         /* request format:
788          *  version number (1 byte) = 4
789          *  command code (1 byte)
790          *    1 = CONNECT
791          *    2 = BIND
792          *  dest. port (2 bytes) [network order]
793          *  dest. address (4 bytes)
794          *  user ID (variable length, null terminated string)
795          */
796
797         int length, type, namelen;
798         char *command, addr[4], hostname[512];
799         char *username;
800
801         type = sk_addrtype(p->remote_addr);
802         if (type == ADDRTYPE_IPV6) {
803             p->error = "Proxy error: SOCKS version 4 does not support IPv6";
804             return 1;
805         } else if (type == ADDRTYPE_IPV4) {
806             namelen = 0;
807             sk_addrcopy(p->remote_addr, addr);
808         } else {                       /* type == ADDRTYPE_NAME */
809             assert(type == ADDRTYPE_NAME);
810             sk_getaddr(p->remote_addr, hostname, lenof(hostname));
811             namelen = strlen(hostname) + 1;   /* include the NUL */
812             addr[0] = addr[1] = addr[2] = 0;
813             addr[3] = 1;
814         }
815
816         username = conf_get_str(p->conf, CONF_proxy_username);
817         length = strlen(username) + namelen + 9;
818         command = snewn(length, char);
819         strcpy(command + 8, username);
820
821         command[0] = 4; /* version 4 */
822         command[1] = 1; /* CONNECT command */
823
824         /* port */
825         command[2] = (char) (p->remote_port >> 8) & 0xff;
826         command[3] = (char) p->remote_port & 0xff;
827
828         /* address */
829         memcpy(command + 4, addr, 4);
830
831         /* hostname */
832         memcpy(command + 8 + strlen(username) + 1,
833                hostname, namelen);
834
835         sk_write(p->sub_socket, command, length);
836         sfree(username);
837         sfree(command);
838
839         p->state = 1;
840         return 0;
841     }
842
843     if (change == PROXY_CHANGE_CLOSING) {
844         /* if our proxy negotiation process involves closing and opening
845          * new sockets, then we would want to intercept this closing
846          * callback when we were expecting it. if we aren't anticipating
847          * a socket close, then some error must have occurred. we'll
848          * just pass those errors up to the backend.
849          */
850         return plug_closing(p->plug, p->closing_error_msg,
851                             p->closing_error_code,
852                             p->closing_calling_back);
853     }
854
855     if (change == PROXY_CHANGE_SENT) {
856         /* some (or all) of what we wrote to the proxy was sent.
857          * we don't do anything new, however, until we receive the
858          * proxy's response. we might want to set a timer so we can
859          * timeout the proxy negotiation after a while...
860          */
861         return 0;
862     }
863
864     if (change == PROXY_CHANGE_ACCEPTING) {
865         /* we should _never_ see this, as we are using our socket to
866          * connect to a proxy, not accepting inbound connections.
867          * what should we do? close the socket with an appropriate
868          * error message?
869          */
870         return plug_accepting(p->plug,
871                               p->accepting_constructor, p->accepting_ctx);
872     }
873
874     if (change == PROXY_CHANGE_RECEIVE) {
875         /* we have received data from the underlying socket, which
876          * we'll need to parse, process, and respond to appropriately.
877          */
878
879         if (p->state == 1) {
880             /* response format:
881              *  version number (1 byte) = 4
882              *  reply code (1 byte)
883              *    90 = request granted
884              *    91 = request rejected or failed
885              *    92 = request rejected due to lack of IDENTD on client
886              *    93 = request rejected due to difference in user ID 
887              *         (what we sent vs. what IDENTD said)
888              *  dest. port (2 bytes)
889              *  dest. address (4 bytes)
890              */
891
892             char data[8];
893
894             if (bufchain_size(&p->pending_input_data) < 8)
895                 return 1;              /* not got anything yet */
896             
897             /* get the response */
898             bufchain_fetch(&p->pending_input_data, data, 8);
899
900             if (data[0] != 0) {
901                 plug_closing(p->plug, "Proxy error: SOCKS proxy responded with "
902                                       "unexpected reply code version",
903                              PROXY_ERROR_GENERAL, 0);
904                 return 1;
905             }
906
907             if (data[1] != 90) {
908
909                 switch (data[1]) {
910                   case 92:
911                     plug_closing(p->plug, "Proxy error: SOCKS server wanted IDENTD on client",
912                                  PROXY_ERROR_GENERAL, 0);
913                     break;
914                   case 93:
915                     plug_closing(p->plug, "Proxy error: Username and IDENTD on client don't agree",
916                                  PROXY_ERROR_GENERAL, 0);
917                     break;
918                   case 91:
919                   default:
920                     plug_closing(p->plug, "Proxy error: Error while communicating with proxy",
921                                  PROXY_ERROR_GENERAL, 0);
922                     break;
923                 }
924
925                 return 1;
926             }
927             bufchain_consume(&p->pending_input_data, 8);
928
929             /* we're done */
930             proxy_activate(p);
931             /* proxy activate will have dealt with
932              * whatever is left of the buffer */
933             return 1;
934         }
935     }
936
937     plug_closing(p->plug, "Proxy error: unexpected proxy error",
938                  PROXY_ERROR_UNEXPECTED, 0);
939     return 1;
940 }
941
942 /* SOCKS version 5 */
943 int proxy_socks5_negotiate (Proxy_Socket p, int change)
944 {
945     if (p->state == PROXY_CHANGE_NEW) {
946
947         /* initial command:
948          *  version number (1 byte) = 5
949          *  number of available authentication methods (1 byte)
950          *  available authentication methods (1 byte * previous value)
951          *    authentication methods:
952          *     0x00 = no authentication
953          *     0x01 = GSSAPI
954          *     0x02 = username/password
955          *     0x03 = CHAP
956          */
957
958         char command[5];
959         char *username, *password;
960         int len;
961
962         command[0] = 5; /* version 5 */
963         username = conf_get_str(p->conf, CONF_proxy_username);
964         password = conf_get_str(p->conf, CONF_proxy_password);
965         if (username[0] || password[0]) {
966             command[2] = 0x00;         /* no authentication */
967             len = 3;
968             proxy_socks5_offerencryptedauth (command, &len);
969             command[len++] = 0x02;             /* username/password */
970             command[1] = len - 2;       /* Number of methods supported */
971         } else {
972             command[1] = 1;            /* one methods supported: */
973             command[2] = 0x00;         /* no authentication */
974             len = 3;
975         }
976
977         sk_write(p->sub_socket, command, len);
978
979         p->state = 1;
980         return 0;
981     }
982
983     if (change == PROXY_CHANGE_CLOSING) {
984         /* if our proxy negotiation process involves closing and opening
985          * new sockets, then we would want to intercept this closing
986          * callback when we were expecting it. if we aren't anticipating
987          * a socket close, then some error must have occurred. we'll
988          * just pass those errors up to the backend.
989          */
990         return plug_closing(p->plug, p->closing_error_msg,
991                             p->closing_error_code,
992                             p->closing_calling_back);
993     }
994
995     if (change == PROXY_CHANGE_SENT) {
996         /* some (or all) of what we wrote to the proxy was sent.
997          * we don't do anything new, however, until we receive the
998          * proxy's response. we might want to set a timer so we can
999          * timeout the proxy negotiation after a while...
1000          */
1001         return 0;
1002     }
1003
1004     if (change == PROXY_CHANGE_ACCEPTING) {
1005         /* we should _never_ see this, as we are using our socket to
1006          * connect to a proxy, not accepting inbound connections.
1007          * what should we do? close the socket with an appropriate
1008          * error message?
1009          */
1010         return plug_accepting(p->plug,
1011                               p->accepting_constructor, p->accepting_ctx);
1012     }
1013
1014     if (change == PROXY_CHANGE_RECEIVE) {
1015         /* we have received data from the underlying socket, which
1016          * we'll need to parse, process, and respond to appropriately.
1017          */
1018
1019         if (p->state == 1) {
1020
1021             /* initial response:
1022              *  version number (1 byte) = 5
1023              *  authentication method (1 byte)
1024              *    authentication methods:
1025              *     0x00 = no authentication
1026              *     0x01 = GSSAPI
1027              *     0x02 = username/password
1028              *     0x03 = CHAP
1029              *     0xff = no acceptable methods
1030              */
1031             char data[2];
1032
1033             if (bufchain_size(&p->pending_input_data) < 2)
1034                 return 1;              /* not got anything yet */
1035
1036             /* get the response */
1037             bufchain_fetch(&p->pending_input_data, data, 2);
1038
1039             if (data[0] != 5) {
1040                 plug_closing(p->plug, "Proxy error: SOCKS proxy returned unexpected version",
1041                              PROXY_ERROR_GENERAL, 0);
1042                 return 1;
1043             }
1044
1045             if (data[1] == 0x00) p->state = 2; /* no authentication needed */
1046             else if (data[1] == 0x01) p->state = 4; /* GSSAPI authentication */
1047             else if (data[1] == 0x02) p->state = 5; /* username/password authentication */
1048             else if (data[1] == 0x03) p->state = 6; /* CHAP authentication */
1049             else {
1050                 plug_closing(p->plug, "Proxy error: SOCKS proxy did not accept our authentication",
1051                              PROXY_ERROR_GENERAL, 0);
1052                 return 1;
1053             }
1054             bufchain_consume(&p->pending_input_data, 2);
1055         }
1056
1057         if (p->state == 7) {
1058
1059             /* password authentication reply format:
1060              *  version number (1 bytes) = 1
1061              *  reply code (1 byte)
1062              *    0 = succeeded
1063              *    >0 = failed
1064              */
1065             char data[2];
1066
1067             if (bufchain_size(&p->pending_input_data) < 2)
1068                 return 1;              /* not got anything yet */
1069
1070             /* get the response */
1071             bufchain_fetch(&p->pending_input_data, data, 2);
1072
1073             if (data[0] != 1) {
1074                 plug_closing(p->plug, "Proxy error: SOCKS password "
1075                              "subnegotiation contained wrong version number",
1076                              PROXY_ERROR_GENERAL, 0);
1077                 return 1;
1078             }
1079
1080             if (data[1] != 0) {
1081
1082                 plug_closing(p->plug, "Proxy error: SOCKS proxy refused"
1083                              " password authentication",
1084                              PROXY_ERROR_GENERAL, 0);
1085                 return 1;
1086             }
1087
1088             bufchain_consume(&p->pending_input_data, 2);
1089             p->state = 2;              /* now proceed as authenticated */
1090         }
1091
1092         if (p->state == 8) {
1093             int ret;
1094             ret = proxy_socks5_handlechap(p);
1095             if (ret) return ret;
1096         }
1097
1098         if (p->state == 2) {
1099
1100             /* request format:
1101              *  version number (1 byte) = 5
1102              *  command code (1 byte)
1103              *    1 = CONNECT
1104              *    2 = BIND
1105              *    3 = UDP ASSOCIATE
1106              *  reserved (1 byte) = 0x00
1107              *  address type (1 byte)
1108              *    1 = IPv4
1109              *    3 = domainname (first byte has length, no terminating null)
1110              *    4 = IPv6
1111              *  dest. address (variable)
1112              *  dest. port (2 bytes) [network order]
1113              */
1114
1115             char command[512];
1116             int len;
1117             int type;
1118
1119             type = sk_addrtype(p->remote_addr);
1120             if (type == ADDRTYPE_IPV4) {
1121                 len = 10;              /* 4 hdr + 4 addr + 2 trailer */
1122                 command[3] = 1; /* IPv4 */
1123                 sk_addrcopy(p->remote_addr, command+4);
1124             } else if (type == ADDRTYPE_IPV6) {
1125                 len = 22;              /* 4 hdr + 16 addr + 2 trailer */
1126                 command[3] = 4; /* IPv6 */
1127                 sk_addrcopy(p->remote_addr, command+4);
1128             } else {
1129                 assert(type == ADDRTYPE_NAME);
1130                 command[3] = 3;
1131                 sk_getaddr(p->remote_addr, command+5, 256);
1132                 command[4] = strlen(command+5);
1133                 len = 7 + command[4];  /* 4 hdr, 1 len, N addr, 2 trailer */
1134             }
1135
1136             command[0] = 5; /* version 5 */
1137             command[1] = 1; /* CONNECT command */
1138             command[2] = 0x00;
1139
1140             /* port */
1141             command[len-2] = (char) (p->remote_port >> 8) & 0xff;
1142             command[len-1] = (char) p->remote_port & 0xff;
1143
1144             sk_write(p->sub_socket, command, len);
1145
1146             p->state = 3;
1147             return 1;
1148         }
1149
1150         if (p->state == 3) {
1151
1152             /* reply format:
1153              *  version number (1 bytes) = 5
1154              *  reply code (1 byte)
1155              *    0 = succeeded
1156              *    1 = general SOCKS server failure
1157              *    2 = connection not allowed by ruleset
1158              *    3 = network unreachable
1159              *    4 = host unreachable
1160              *    5 = connection refused
1161              *    6 = TTL expired
1162              *    7 = command not supported
1163              *    8 = address type not supported
1164              * reserved (1 byte) = x00
1165              * address type (1 byte)
1166              *    1 = IPv4
1167              *    3 = domainname (first byte has length, no terminating null)
1168              *    4 = IPv6
1169              * server bound address (variable)
1170              * server bound port (2 bytes) [network order]
1171              */
1172             char data[5];
1173             int len;
1174
1175             /* First 5 bytes of packet are enough to tell its length. */ 
1176             if (bufchain_size(&p->pending_input_data) < 5)
1177                 return 1;              /* not got anything yet */
1178
1179             /* get the response */
1180             bufchain_fetch(&p->pending_input_data, data, 5);
1181
1182             if (data[0] != 5) {
1183                 plug_closing(p->plug, "Proxy error: SOCKS proxy returned wrong version number",
1184                              PROXY_ERROR_GENERAL, 0);
1185                 return 1;
1186             }
1187
1188             if (data[1] != 0) {
1189                 char buf[256];
1190
1191                 strcpy(buf, "Proxy error: ");
1192
1193                 switch (data[1]) {
1194                   case 1: strcat(buf, "General SOCKS server failure"); break;
1195                   case 2: strcat(buf, "Connection not allowed by ruleset"); break;
1196                   case 3: strcat(buf, "Network unreachable"); break;
1197                   case 4: strcat(buf, "Host unreachable"); break;
1198                   case 5: strcat(buf, "Connection refused"); break;
1199                   case 6: strcat(buf, "TTL expired"); break;
1200                   case 7: strcat(buf, "Command not supported"); break;
1201                   case 8: strcat(buf, "Address type not supported"); break;
1202                   default: sprintf(buf+strlen(buf),
1203                                    "Unrecognised SOCKS error code %d",
1204                                    data[1]);
1205                     break;
1206                 }
1207                 plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0);
1208
1209                 return 1;
1210             }
1211
1212             /*
1213              * Eat the rest of the reply packet.
1214              */
1215             len = 6;                   /* first 4 bytes, last 2 */
1216             switch (data[3]) {
1217               case 1: len += 4; break; /* IPv4 address */
1218               case 4: len += 16; break;/* IPv6 address */
1219               case 3: len += (unsigned char)data[4]; break; /* domain name */
1220               default:
1221                 plug_closing(p->plug, "Proxy error: SOCKS proxy returned "
1222                              "unrecognised address format",
1223                              PROXY_ERROR_GENERAL, 0);
1224                 return 1;
1225             }
1226             if (bufchain_size(&p->pending_input_data) < len)
1227                 return 1;              /* not got whole reply yet */
1228             bufchain_consume(&p->pending_input_data, len);
1229
1230             /* we're done */
1231             proxy_activate(p);
1232             return 1;
1233         }
1234
1235         if (p->state == 4) {
1236             /* TODO: Handle GSSAPI authentication */
1237             plug_closing(p->plug, "Proxy error: We don't support GSSAPI authentication",
1238                          PROXY_ERROR_GENERAL, 0);
1239             return 1;
1240         }
1241
1242         if (p->state == 5) {
1243             char *username = conf_get_str(p->conf, CONF_proxy_username);
1244             char *password = conf_get_str(p->conf, CONF_proxy_password);
1245             if (username[0] || password[0]) {
1246                 char userpwbuf[255 + 255 + 3];
1247                 int ulen, plen;
1248                 ulen = strlen(username);
1249                 if (ulen > 255) ulen = 255;
1250                 if (ulen < 1) ulen = 1;
1251                 plen = strlen(password);
1252                 if (plen > 255) plen = 255;
1253                 if (plen < 1) plen = 1;
1254                 userpwbuf[0] = 1;      /* version number of subnegotiation */
1255                 userpwbuf[1] = ulen;
1256                 memcpy(userpwbuf+2, username, ulen);
1257                 userpwbuf[ulen+2] = plen;
1258                 memcpy(userpwbuf+ulen+3, password, plen);
1259                 sk_write(p->sub_socket, userpwbuf, ulen + plen + 3);
1260                 p->state = 7;
1261             } else 
1262                 plug_closing(p->plug, "Proxy error: Server chose "
1263                              "username/password authentication but we "
1264                              "didn't offer it!",
1265                          PROXY_ERROR_GENERAL, 0);
1266             return 1;
1267         }
1268
1269         if (p->state == 6) {
1270             int ret;
1271             ret = proxy_socks5_selectchap(p);
1272             if (ret) return ret;
1273         }
1274
1275     }
1276
1277     plug_closing(p->plug, "Proxy error: Unexpected proxy error",
1278                  PROXY_ERROR_UNEXPECTED, 0);
1279     return 1;
1280 }
1281
1282 /* ----------------------------------------------------------------------
1283  * `Telnet' proxy type.
1284  *
1285  * (This is for ad-hoc proxies where you connect to the proxy's
1286  * telnet port and send a command such as `connect host port'. The
1287  * command is configurable, since this proxy type is typically not
1288  * standardised or at all well-defined.)
1289  */
1290
1291 char *format_telnet_command(SockAddr addr, int port, Conf *conf)
1292 {
1293     char *fmt = conf_get_str(conf, CONF_proxy_telnet_command);
1294     char *ret = NULL;
1295     int retlen = 0, retsize = 0;
1296     int so = 0, eo = 0;
1297 #define ENSURE(n) do { \
1298     if (retsize < retlen + n) { \
1299         retsize = retlen + n + 512; \
1300         ret = sresize(ret, retsize, char); \
1301     } \
1302 } while (0)
1303
1304     /* we need to escape \\, \%, \r, \n, \t, \x??, \0???, 
1305      * %%, %host, %port, %user, and %pass
1306      */
1307
1308     while (fmt[eo] != 0) {
1309
1310         /* scan forward until we hit end-of-line,
1311          * or an escape character (\ or %) */
1312         while (fmt[eo] != 0 && fmt[eo] != '%' && fmt[eo] != '\\')
1313             eo++;
1314
1315         /* if we hit eol, break out of our escaping loop */
1316         if (fmt[eo] == 0) break;
1317
1318         /* if there was any unescaped text before the escape
1319          * character, send that now */
1320         if (eo != so) {
1321             ENSURE(eo - so);
1322             memcpy(ret + retlen, fmt + so, eo - so);
1323             retlen += eo - so;
1324         }
1325
1326         so = eo++;
1327
1328         /* if the escape character was the last character of
1329          * the line, we'll just stop and send it. */
1330         if (fmt[eo] == 0) break;
1331
1332         if (fmt[so] == '\\') {
1333
1334             /* we recognize \\, \%, \r, \n, \t, \x??.
1335              * anything else, we just send unescaped (including the \).
1336              */
1337
1338             switch (fmt[eo]) {
1339
1340               case '\\':
1341                 ENSURE(1);
1342                 ret[retlen++] = '\\';
1343                 eo++;
1344                 break;
1345
1346               case '%':
1347                 ENSURE(1);
1348                 ret[retlen++] = '%';
1349                 eo++;
1350                 break;
1351
1352               case 'r':
1353                 ENSURE(1);
1354                 ret[retlen++] = '\r';
1355                 eo++;
1356                 break;
1357
1358               case 'n':
1359                 ENSURE(1);
1360                 ret[retlen++] = '\n';
1361                 eo++;
1362                 break;
1363
1364               case 't':
1365                 ENSURE(1);
1366                 ret[retlen++] = '\t';
1367                 eo++;
1368                 break;
1369
1370               case 'x':
1371               case 'X':
1372                 {
1373                     /* escaped hexadecimal value (ie. \xff) */
1374                     unsigned char v = 0;
1375                     int i = 0;
1376
1377                     for (;;) {
1378                         eo++;
1379                         if (fmt[eo] >= '0' && fmt[eo] <= '9')
1380                             v += fmt[eo] - '0';
1381                         else if (fmt[eo] >= 'a' && fmt[eo] <= 'f')
1382                             v += fmt[eo] - 'a' + 10;
1383                         else if (fmt[eo] >= 'A' && fmt[eo] <= 'F')
1384                             v += fmt[eo] - 'A' + 10;
1385                         else {
1386                             /* non hex character, so we abort and just
1387                              * send the whole thing unescaped (including \x)
1388                              */
1389                             ENSURE(1);
1390                             ret[retlen++] = '\\';
1391                             eo = so + 1;
1392                             break;
1393                         }
1394
1395                         /* we only extract two hex characters */
1396                         if (i == 1) {
1397                             ENSURE(1);
1398                             ret[retlen++] = v;
1399                             eo++;
1400                             break;
1401                         }
1402
1403                         i++;
1404                         v <<= 4;
1405                     }
1406                 }
1407                 break;
1408
1409               default:
1410                 ENSURE(2);
1411                 memcpy(ret+retlen, fmt + so, 2);
1412                 retlen += 2;
1413                 eo++;
1414                 break;
1415             }
1416         } else {
1417
1418             /* % escape. we recognize %%, %host, %port, %user, %pass.
1419              * %proxyhost, %proxyport. Anything else we just send
1420              * unescaped (including the %).
1421              */
1422
1423             if (fmt[eo] == '%') {
1424                 ENSURE(1);
1425                 ret[retlen++] = '%';
1426                 eo++;
1427             }
1428             else if (strnicmp(fmt + eo, "host", 4) == 0) {
1429                 char dest[512];
1430                 int destlen;
1431                 sk_getaddr(addr, dest, lenof(dest));
1432                 destlen = strlen(dest);
1433                 ENSURE(destlen);
1434                 memcpy(ret+retlen, dest, destlen);
1435                 retlen += destlen;
1436                 eo += 4;
1437             }
1438             else if (strnicmp(fmt + eo, "port", 4) == 0) {
1439                 char portstr[8], portlen;
1440                 portlen = sprintf(portstr, "%i", port);
1441                 ENSURE(portlen);
1442                 memcpy(ret + retlen, portstr, portlen);
1443                 retlen += portlen;
1444                 eo += 4;
1445             }
1446             else if (strnicmp(fmt + eo, "user", 4) == 0) {
1447                 char *username = conf_get_str(conf, CONF_proxy_username);
1448                 int userlen = strlen(username);
1449                 ENSURE(userlen);
1450                 memcpy(ret+retlen, username, userlen);
1451                 retlen += userlen;
1452                 eo += 4;
1453             }
1454             else if (strnicmp(fmt + eo, "pass", 4) == 0) {
1455                 char *password = conf_get_str(conf, CONF_proxy_password);
1456                 int passlen = strlen(password);
1457                 ENSURE(passlen);
1458                 memcpy(ret+retlen, password, passlen);
1459                 retlen += passlen;
1460                 eo += 4;
1461             }
1462             else if (strnicmp(fmt + eo, "proxyhost", 9) == 0) {
1463                 char *host = conf_get_str(conf, CONF_proxy_host);
1464                 int phlen = strlen(host);
1465                 ENSURE(phlen);
1466                 memcpy(ret+retlen, host, phlen);
1467                 retlen += phlen;
1468                 eo += 9;
1469             }
1470             else if (strnicmp(fmt + eo, "proxyport", 9) == 0) {
1471                 int port = conf_get_int(conf, CONF_proxy_port);
1472                 char pport[50];
1473                 int pplen;
1474                 sprintf(pport, "%d", port);
1475                 pplen = strlen(pport);
1476                 ENSURE(pplen);
1477                 memcpy(ret+retlen, pport, pplen);
1478                 retlen += pplen;
1479                 eo += 9;
1480             }
1481             else {
1482                 /* we don't escape this, so send the % now, and
1483                  * don't advance eo, so that we'll consider the
1484                  * text immediately following the % as unescaped.
1485                  */
1486                 ENSURE(1);
1487                 ret[retlen++] = '%';
1488             }
1489         }
1490
1491         /* resume scanning for additional escapes after this one. */
1492         so = eo;
1493     }
1494
1495     /* if there is any unescaped text at the end of the line, send it */
1496     if (eo != so) {
1497         ENSURE(eo - so);
1498         memcpy(ret + retlen, fmt + so, eo - so);
1499         retlen += eo - so;
1500     }
1501
1502     ENSURE(1);
1503     ret[retlen] = '\0';
1504     return ret;
1505
1506 #undef ENSURE
1507 }
1508
1509 int proxy_telnet_negotiate (Proxy_Socket p, int change)
1510 {
1511     if (p->state == PROXY_CHANGE_NEW) {
1512         char *formatted_cmd;
1513
1514         formatted_cmd = format_telnet_command(p->remote_addr, p->remote_port,
1515                                               p->conf);
1516
1517         {
1518             /*
1519              * Re-escape control chars in the command, for logging.
1520              */
1521             char *reescaped = snewn(4*strlen(formatted_cmd) + 1, char);
1522             const char *in;
1523             char *out;
1524             char *logmsg;
1525
1526             for (in = formatted_cmd, out = reescaped; *in; in++) {
1527                 if (*in == '\n') {
1528                     *out++ = '\\'; *out++ = 'n';
1529                 } else if (*in == '\r') {
1530                     *out++ = '\\'; *out++ = 'r';
1531                 } else if (*in == '\t') {
1532                     *out++ = '\\'; *out++ = 't';
1533                 } else if (*in == '\\') {
1534                     *out++ = '\\'; *out++ = '\\';
1535                 } else if ((unsigned)(((unsigned char)*in) - 0x20) <
1536                            (0x7F-0x20)) {
1537                     *out++ = *in;
1538                 } else {
1539                     out += sprintf(out, "\\x%02X", (unsigned)*in & 0xFF);
1540                 }
1541             }
1542             *out = '\0';
1543
1544             logmsg = dupprintf("Sending Telnet proxy command: %s", reescaped);
1545             plug_log(p->plug, 2, NULL, 0, logmsg, 0);
1546             sfree(logmsg);
1547             sfree(reescaped);
1548         }
1549
1550         sk_write(p->sub_socket, formatted_cmd, strlen(formatted_cmd));
1551         sfree(formatted_cmd);
1552
1553         p->state = 1;
1554         return 0;
1555     }
1556
1557     if (change == PROXY_CHANGE_CLOSING) {
1558         /* if our proxy negotiation process involves closing and opening
1559          * new sockets, then we would want to intercept this closing
1560          * callback when we were expecting it. if we aren't anticipating
1561          * a socket close, then some error must have occurred. we'll
1562          * just pass those errors up to the backend.
1563          */
1564         return plug_closing(p->plug, p->closing_error_msg,
1565                             p->closing_error_code,
1566                             p->closing_calling_back);
1567     }
1568
1569     if (change == PROXY_CHANGE_SENT) {
1570         /* some (or all) of what we wrote to the proxy was sent.
1571          * we don't do anything new, however, until we receive the
1572          * proxy's response. we might want to set a timer so we can
1573          * timeout the proxy negotiation after a while...
1574          */
1575         return 0;
1576     }
1577
1578     if (change == PROXY_CHANGE_ACCEPTING) {
1579         /* we should _never_ see this, as we are using our socket to
1580          * connect to a proxy, not accepting inbound connections.
1581          * what should we do? close the socket with an appropriate
1582          * error message?
1583          */
1584         return plug_accepting(p->plug,
1585                               p->accepting_constructor, p->accepting_ctx);
1586     }
1587
1588     if (change == PROXY_CHANGE_RECEIVE) {
1589         /* we have received data from the underlying socket, which
1590          * we'll need to parse, process, and respond to appropriately.
1591          */
1592
1593         /* we're done */
1594         proxy_activate(p);
1595         /* proxy activate will have dealt with
1596          * whatever is left of the buffer */
1597         return 1;
1598     }
1599
1600     plug_closing(p->plug, "Proxy error: Unexpected proxy error",
1601                  PROXY_ERROR_UNEXPECTED, 0);
1602     return 1;
1603 }