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