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