OSDN Git Service

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