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