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