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