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