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