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