2 * Network proxy abstraction in PuTTY
4 * A proxy layer, if necessary, wedges itself between the network
5 * code and the higher level backend.
12 #define DEFINE_PLUG_METHOD_MACROS
17 #define do_proxy_dns \
18 (cfg.proxy_dns == 2 || \
19 (cfg.proxy_dns == 1 && cfg.proxy_type != PROXY_SOCKS))
22 * Call this when proxy negotiation is complete, so that this
23 * socket can begin working normally.
25 void proxy_activate (Proxy_Socket p)
29 long output_before, output_after;
31 p->state = PROXY_STATE_ACTIVE;
33 /* we want to ignore new receive events until we have sent
34 * all of our buffered receive data.
36 sk_set_frozen(p->sub_socket, 1);
38 /* how many bytes of output have we buffered? */
39 output_before = bufchain_size(&p->pending_oob_output_data) +
40 bufchain_size(&p->pending_output_data);
41 /* and keep track of how many bytes do not get sent. */
44 /* send buffered OOB writes */
45 while (bufchain_size(&p->pending_oob_output_data) > 0) {
46 bufchain_prefix(&p->pending_oob_output_data, &data, &len);
47 output_after += sk_write_oob(p->sub_socket, data, len);
48 bufchain_consume(&p->pending_oob_output_data, len);
51 /* send buffered normal writes */
52 while (bufchain_size(&p->pending_output_data) > 0) {
53 bufchain_prefix(&p->pending_output_data, &data, &len);
54 output_after += sk_write(p->sub_socket, data, len);
55 bufchain_consume(&p->pending_output_data, len);
58 /* if we managed to send any data, let the higher levels know. */
59 if (output_after < output_before)
60 plug_sent(p->plug, output_after);
62 /* if we were asked to flush the output during
63 * the proxy negotiation process, do so now.
65 if (p->pending_flush) sk_flush(p->sub_socket);
67 /* if the backend wanted the socket unfrozen, try to unfreeze.
68 * our set_frozen handler will flush buffered receive data before
69 * unfreezing the actual underlying socket.
72 sk_set_frozen((Socket)p, 0);
75 /* basic proxy socket functions */
77 static Plug sk_proxy_plug (Socket s, Plug p)
79 Proxy_Socket ps = (Proxy_Socket) s;
86 static void sk_proxy_close (Socket s)
88 Proxy_Socket ps = (Proxy_Socket) s;
90 sk_close(ps->sub_socket);
94 static int sk_proxy_write (Socket s, char *data, int len)
96 Proxy_Socket ps = (Proxy_Socket) s;
98 if (ps->state != PROXY_STATE_ACTIVE) {
99 bufchain_add(&ps->pending_output_data, data, len);
100 return bufchain_size(&ps->pending_output_data);
102 return sk_write(ps->sub_socket, data, len);
105 static int sk_proxy_write_oob (Socket s, char *data, int len)
107 Proxy_Socket ps = (Proxy_Socket) s;
109 if (ps->state != PROXY_STATE_ACTIVE) {
110 bufchain_clear(&ps->pending_output_data);
111 bufchain_clear(&ps->pending_oob_output_data);
112 bufchain_add(&ps->pending_oob_output_data, data, len);
115 return sk_write_oob(ps->sub_socket, data, len);
118 static void sk_proxy_flush (Socket s)
120 Proxy_Socket ps = (Proxy_Socket) s;
122 if (ps->state != PROXY_STATE_ACTIVE) {
123 ps->pending_flush = 1;
126 sk_flush(ps->sub_socket);
129 static void sk_proxy_set_private_ptr (Socket s, void *ptr)
131 Proxy_Socket ps = (Proxy_Socket) s;
132 sk_set_private_ptr(ps->sub_socket, ptr);
135 static void * sk_proxy_get_private_ptr (Socket s)
137 Proxy_Socket ps = (Proxy_Socket) s;
138 return sk_get_private_ptr(ps->sub_socket);
141 static void sk_proxy_set_frozen (Socket s, int is_frozen)
143 Proxy_Socket ps = (Proxy_Socket) s;
145 if (ps->state != PROXY_STATE_ACTIVE) {
146 ps->freeze = is_frozen;
150 /* handle any remaining buffered recv data first */
151 if (bufchain_size(&ps->pending_input_data) > 0) {
152 ps->freeze = is_frozen;
154 /* loop while we still have buffered data, and while we are
155 * unfrozen. the plug_receive call in the loop could result
156 * in a call back into this function refreezing the socket,
157 * so we have to check each time.
159 while (!ps->freeze && bufchain_size(&ps->pending_input_data) > 0) {
162 bufchain_prefix(&ps->pending_input_data, &data, &len);
163 plug_receive(ps->plug, 0, data, len);
164 bufchain_consume(&ps->pending_input_data, len);
167 /* if we're still frozen, we'll have to wait for another
168 * call from the backend to finish unbuffering the data.
170 if (ps->freeze) return;
173 sk_set_frozen(ps->sub_socket, is_frozen);
176 static char * sk_proxy_socket_error (Socket s)
178 Proxy_Socket ps = (Proxy_Socket) s;
179 if (ps->error != NULL || ps->sub_socket == NULL) {
182 return sk_socket_error(ps->sub_socket);
185 /* basic proxy plug functions */
187 static int plug_proxy_closing (Plug p, char *error_msg,
188 int error_code, int calling_back)
190 Proxy_Plug pp = (Proxy_Plug) p;
191 Proxy_Socket ps = pp->proxy_socket;
193 if (ps->state != PROXY_STATE_ACTIVE) {
194 ps->closing_error_msg = error_msg;
195 ps->closing_error_code = error_code;
196 ps->closing_calling_back = calling_back;
197 return ps->negotiate(ps, PROXY_CHANGE_CLOSING);
199 return plug_closing(ps->plug, error_msg,
200 error_code, calling_back);
203 static int plug_proxy_receive (Plug p, int urgent, char *data, int len)
205 Proxy_Plug pp = (Proxy_Plug) p;
206 Proxy_Socket ps = pp->proxy_socket;
208 if (ps->state != PROXY_STATE_ACTIVE) {
209 /* we will lose the urgentness of this data, but since most,
210 * if not all, of this data will be consumed by the negotiation
211 * process, hopefully it won't affect the protocol above us
213 bufchain_add(&ps->pending_input_data, data, len);
214 ps->receive_urgent = urgent;
215 ps->receive_data = data;
216 ps->receive_len = len;
217 return ps->negotiate(ps, PROXY_CHANGE_RECEIVE);
219 return plug_receive(ps->plug, urgent, data, len);
222 static void plug_proxy_sent (Plug p, int bufsize)
224 Proxy_Plug pp = (Proxy_Plug) p;
225 Proxy_Socket ps = pp->proxy_socket;
227 if (ps->state != PROXY_STATE_ACTIVE) {
228 ps->sent_bufsize = bufsize;
229 ps->negotiate(ps, PROXY_CHANGE_SENT);
232 plug_sent(ps->plug, bufsize);
235 static int plug_proxy_accepting (Plug p, void *sock)
237 Proxy_Plug pp = (Proxy_Plug) p;
238 Proxy_Socket ps = pp->proxy_socket;
240 if (ps->state != PROXY_STATE_ACTIVE) {
241 ps->accepting_sock = sock;
242 return ps->negotiate(ps, PROXY_CHANGE_ACCEPTING);
244 return plug_accepting(ps->plug, sock);
248 * This function can accept a NULL pointer as `addr', in which case
249 * it will only check the host name.
251 static int proxy_for_destination (SockAddr addr, char * hostname, int port)
255 int hostip_len, hostname_len;
259 * Check the host name and IP against the hard-coded
260 * representations of `localhost'.
262 if (!cfg.even_proxy_localhost &&
263 (sk_hostname_is_local(hostname) ||
264 (addr && sk_address_is_local(addr))))
265 return 0; /* do not proxy */
267 /* we want a string representation of the IP address for comparisons */
269 sk_getaddr(addr, hostip, 64);
270 hostip_len = strlen(hostip);
273 hostname_len = strlen(hostname);
275 exclude_list = cfg.proxy_exclude_list;
277 /* now parse the exclude list, and see if either our IP
278 * or hostname matches anything in it.
281 while (exclude_list[s]) {
282 while (exclude_list[s] &&
283 (isspace(exclude_list[s]) ||
284 exclude_list[s] == ',')) s++;
286 if (!exclude_list[s]) break;
290 while (exclude_list[e] &&
291 (isalnum(exclude_list[e]) ||
292 exclude_list[e] == '-' ||
293 exclude_list[e] == '.' ||
294 exclude_list[e] == '*')) e++;
296 if (exclude_list[s] == '*') {
297 /* wildcard at beginning of entry */
299 if ((addr && strnicmp(hostip + hostip_len - (e - s - 1),
300 exclude_list + s + 1, e - s - 1) == 0) ||
301 strnicmp(hostname + hostname_len - (e - s - 1),
302 exclude_list + s + 1, e - s - 1) == 0)
303 return 0; /* IP/hostname range excluded. do not use proxy. */
305 } else if (exclude_list[e-1] == '*') {
306 /* wildcard at end of entry */
308 if ((addr && strnicmp(hostip, exclude_list + s, e - s - 1) == 0) ||
309 strnicmp(hostname, exclude_list + s, e - s - 1) == 0)
310 return 0; /* IP/hostname range excluded. do not use proxy. */
313 /* no wildcard at either end, so let's try an absolute
314 * match (ie. a specific IP)
317 if (addr && stricmp(hostip, exclude_list + s) == 0)
318 return 0; /* IP/hostname excluded. do not use proxy. */
319 if (stricmp(hostname, exclude_list + s) == 0)
320 return 0; /* IP/hostname excluded. do not use proxy. */
325 /* Make sure we really have reached the next comma or end-of-string */
326 while (exclude_list[s] &&
327 !isspace(exclude_list[s]) &&
328 exclude_list[s] != ',') s++;
331 /* no matches in the exclude list, so use the proxy */
335 SockAddr name_lookup(char *host, int port, char **canonicalname)
337 if (cfg.proxy_type != PROXY_NONE &&
338 do_proxy_dns && proxy_for_destination(NULL, host, port)) {
339 *canonicalname = dupstr(host);
340 return sk_nonamelookup(host);
343 return sk_namelookup(host, canonicalname);
346 Socket new_connection(SockAddr addr, char *hostname,
347 int port, int privport,
348 int oobinline, int nodelay, Plug plug)
350 static const struct socket_function_table socket_fn_table = {
356 sk_proxy_set_private_ptr,
357 sk_proxy_get_private_ptr,
359 sk_proxy_socket_error
362 static const struct plug_function_table plug_fn_table = {
369 if (cfg.proxy_type != PROXY_NONE &&
370 proxy_for_destination(addr, hostname, port))
375 char *proxy_canonical_name, *err;
377 ret = smalloc(sizeof(struct Socket_proxy_tag));
378 ret->fn = &socket_fn_table;
380 ret->remote_addr = addr;
381 ret->remote_port = port;
384 ret->pending_flush = 0;
387 bufchain_init(&ret->pending_input_data);
388 bufchain_init(&ret->pending_output_data);
389 bufchain_init(&ret->pending_oob_output_data);
391 ret->sub_socket = NULL;
392 ret->state = PROXY_STATE_NEW;
393 ret->negotiate = NULL;
395 if (cfg.proxy_type == PROXY_HTTP) {
396 ret->negotiate = proxy_http_negotiate;
397 } else if (cfg.proxy_type == PROXY_SOCKS) {
398 if (cfg.proxy_socks_version == 4)
399 ret->negotiate = proxy_socks4_negotiate;
401 ret->negotiate = proxy_socks5_negotiate;
402 } else if (cfg.proxy_type == PROXY_TELNET) {
403 ret->negotiate = proxy_telnet_negotiate;
405 ret->error = "Proxy error: Unknown proxy method";
409 /* create the proxy plug to map calls from the actual
410 * socket into our proxy socket layer */
411 pplug = smalloc(sizeof(struct Plug_proxy_tag));
412 pplug->fn = &plug_fn_table;
413 pplug->proxy_socket = ret;
416 proxy_addr = sk_namelookup(cfg.proxy_host,
417 &proxy_canonical_name);
418 if ((err = sk_addr_error(proxy_addr))) {
419 ret->error = "Proxy error: Unable to resolve proxy host name";
422 sfree(proxy_canonical_name);
424 /* create the actual socket we will be using,
425 * connected to our proxy server and port.
427 ret->sub_socket = sk_new(proxy_addr, cfg.proxy_port,
429 nodelay, (Plug) pplug);
430 if (sk_socket_error(ret->sub_socket) != NULL)
433 sk_addr_free(proxy_addr);
435 /* start the proxy negotiation process... */
436 sk_set_frozen(ret->sub_socket, 0);
437 ret->negotiate(ret, PROXY_CHANGE_NEW);
442 /* no proxy, so just return the direct socket */
443 return sk_new(addr, port, privport, oobinline, nodelay, plug);
446 Socket new_listener(char *srcaddr, int port, Plug plug, int local_host_only)
448 /* TODO: SOCKS (and potentially others) support inbound
449 * TODO: connections via the proxy. support them.
452 return sk_newlistener(srcaddr, port, plug, local_host_only);
455 /* ----------------------------------------------------------------------
456 * HTTP CONNECT proxy type.
459 static int get_line_end (char * data, int len)
465 if (data[off] == '\n') {
466 /* we have a newline */
469 /* is that the only thing on this line? */
470 if (off <= 2) return off;
472 /* if not, then there is the possibility that this header
473 * continues onto the next line, if it starts with a space
478 data[off+1] != ' ' &&
479 data[off+1] != '\t') return off;
481 /* the line does continue, so we have to keep going
482 * until we see an the header's "real" end of line.
493 int proxy_http_negotiate (Proxy_Socket p, int change)
495 if (p->state == PROXY_STATE_NEW) {
496 /* we are just beginning the proxy negotiate process,
497 * so we'll send off the initial bits of the request.
498 * for this proxy method, it's just a simple HTTP
501 char *buf, dest[512];
503 sk_getaddr(p->remote_addr, dest, lenof(dest));
505 buf = dupprintf("CONNECT %s:%i HTTP/1.1\r\nHost: %s:%i\r\n",
506 dest, p->remote_port, dest, p->remote_port);
507 sk_write(p->sub_socket, buf, strlen(buf));
510 if (cfg.proxy_username[0] || cfg.proxy_password[0]) {
511 char buf[sizeof(cfg.proxy_username)+sizeof(cfg.proxy_password)];
512 char buf2[sizeof(buf)*4/3 + 100];
514 sprintf(buf, "%s:%s", cfg.proxy_username, cfg.proxy_password);
516 sprintf(buf2, "Proxy-Authorization: basic ");
517 for (i = 0, j = strlen(buf2); i < len; i += 3, j += 4)
518 base64_encode_atom(buf+i, (len-i > 3 ? 3 : len-i), buf2+j);
519 strcpy(buf2+j, "\r\n");
520 sk_write(p->sub_socket, buf2, strlen(buf2));
523 sk_write(p->sub_socket, "\r\n", 2);
529 if (change == PROXY_CHANGE_CLOSING) {
530 /* if our proxy negotiation process involves closing and opening
531 * new sockets, then we would want to intercept this closing
532 * callback when we were expecting it. if we aren't anticipating
533 * a socket close, then some error must have occurred. we'll
534 * just pass those errors up to the backend.
536 return plug_closing(p->plug, p->closing_error_msg,
537 p->closing_error_code,
538 p->closing_calling_back);
541 if (change == PROXY_CHANGE_SENT) {
542 /* some (or all) of what we wrote to the proxy was sent.
543 * we don't do anything new, however, until we receive the
544 * proxy's response. we might want to set a timer so we can
545 * timeout the proxy negotiation after a while...
550 if (change == PROXY_CHANGE_ACCEPTING) {
551 /* we should _never_ see this, as we are using our socket to
552 * connect to a proxy, not accepting inbound connections.
553 * what should we do? close the socket with an appropriate
556 return plug_accepting(p->plug, p->accepting_sock);
559 if (change == PROXY_CHANGE_RECEIVE) {
560 /* we have received data from the underlying socket, which
561 * we'll need to parse, process, and respond to appropriately.
570 int min_ver, maj_ver, status;
572 /* get the status line */
573 len = bufchain_size(&p->pending_input_data);
574 assert(len > 0); /* or we wouldn't be here */
576 bufchain_fetch(&p->pending_input_data, data, len);
578 eol = get_line_end(data, len);
585 /* We can't rely on whether the %n incremented the sscanf return */
586 if (sscanf((char *)data, "HTTP/%i.%i %n",
587 &maj_ver, &min_ver, &status) < 2 || status == -1) {
588 plug_closing(p->plug, "Proxy error: HTTP response was absent",
589 PROXY_ERROR_GENERAL, 0);
594 /* remove the status line from the input buffer. */
595 bufchain_consume(&p->pending_input_data, eol);
596 if (data[status] != '2') {
600 while (eol > status &&
601 (data[eol-1] == '\r' || data[eol-1] == '\n'))
603 buf = dupprintf("Proxy error: %s", data+status);
604 plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0);
617 /* get headers. we're done when we get a
618 * header of length 2, (ie. just "\r\n")
621 len = bufchain_size(&p->pending_input_data);
622 assert(len > 0); /* or we wouldn't be here */
625 bufchain_fetch(&p->pending_input_data, data, len);
627 eol = get_line_end(datap, len);
634 bufchain_consume(&p->pending_input_data, eol);
637 eol = get_line_end(datap, len);
642 bufchain_consume(&p->pending_input_data, 2);
644 /* proxy activate will have dealt with
645 * whatever is left of the buffer */
655 plug_closing(p->plug, "Proxy error: unexpected proxy error",
656 PROXY_ERROR_UNEXPECTED, 0);
660 /* ----------------------------------------------------------------------
664 /* SOCKS version 4 */
665 int proxy_socks4_negotiate (Proxy_Socket p, int change)
667 if (p->state == PROXY_CHANGE_NEW) {
670 * version number (1 byte) = 4
671 * command code (1 byte)
674 * dest. port (2 bytes) [network order]
675 * dest. address (4 bytes)
676 * user ID (variable length, null terminated string)
679 int length, type, namelen;
680 char *command, addr[4], hostname[512];
682 type = sk_addrtype(p->remote_addr);
683 if (type == ADDRTYPE_IPV6) {
684 plug_closing(p->plug, "Proxy error: SOCKS version 4 does"
685 " not support IPv6", PROXY_ERROR_GENERAL, 0);
687 } else if (type == ADDRTYPE_IPV4) {
689 sk_addrcopy(p->remote_addr, addr);
690 } else { /* type == ADDRTYPE_NAME */
691 sk_getaddr(p->remote_addr, hostname, lenof(hostname));
692 namelen = strlen(hostname) + 1; /* include the NUL */
693 addr[0] = addr[1] = addr[2] = 0;
697 length = strlen(cfg.proxy_username) + namelen + 9;
698 command = (char*) smalloc(length);
699 strcpy(command + 8, cfg.proxy_username);
701 command[0] = 4; /* version 4 */
702 command[1] = 1; /* CONNECT command */
705 command[2] = (char) (p->remote_port >> 8) & 0xff;
706 command[3] = (char) p->remote_port & 0xff;
709 memcpy(command + 4, addr, 4);
712 memcpy(command + 8 + strlen(cfg.proxy_username) + 1,
715 sk_write(p->sub_socket, command, length);
722 if (change == PROXY_CHANGE_CLOSING) {
723 /* if our proxy negotiation process involves closing and opening
724 * new sockets, then we would want to intercept this closing
725 * callback when we were expecting it. if we aren't anticipating
726 * a socket close, then some error must have occurred. we'll
727 * just pass those errors up to the backend.
729 return plug_closing(p->plug, p->closing_error_msg,
730 p->closing_error_code,
731 p->closing_calling_back);
734 if (change == PROXY_CHANGE_SENT) {
735 /* some (or all) of what we wrote to the proxy was sent.
736 * we don't do anything new, however, until we receive the
737 * proxy's response. we might want to set a timer so we can
738 * timeout the proxy negotiation after a while...
743 if (change == PROXY_CHANGE_ACCEPTING) {
744 /* we should _never_ see this, as we are using our socket to
745 * connect to a proxy, not accepting inbound connections.
746 * what should we do? close the socket with an appropriate
749 return plug_accepting(p->plug, p->accepting_sock);
752 if (change == PROXY_CHANGE_RECEIVE) {
753 /* we have received data from the underlying socket, which
754 * we'll need to parse, process, and respond to appropriately.
759 * version number (1 byte) = 4
760 * reply code (1 byte)
761 * 90 = request granted
762 * 91 = request rejected or failed
763 * 92 = request rejected due to lack of IDENTD on client
764 * 93 = request rejected due to difference in user ID
765 * (what we sent vs. what IDENTD said)
766 * dest. port (2 bytes)
767 * dest. address (4 bytes)
772 if (bufchain_size(&p->pending_input_data) < 8)
773 return 1; /* not got anything yet */
775 /* get the response */
776 bufchain_fetch(&p->pending_input_data, data, 8);
779 plug_closing(p->plug, "Proxy error: SOCKS proxy responded with "
780 "unexpected reply code version",
781 PROXY_ERROR_GENERAL, 0);
789 plug_closing(p->plug, "Proxy error: SOCKS server wanted IDENTD on client",
790 PROXY_ERROR_GENERAL, 0);
793 plug_closing(p->plug, "Proxy error: Username and IDENTD on client don't agree",
794 PROXY_ERROR_GENERAL, 0);
798 plug_closing(p->plug, "Proxy error: Error while communicating with proxy",
799 PROXY_ERROR_GENERAL, 0);
805 bufchain_consume(&p->pending_input_data, 8);
809 /* proxy activate will have dealt with
810 * whatever is left of the buffer */
815 plug_closing(p->plug, "Proxy error: unexpected proxy error",
816 PROXY_ERROR_UNEXPECTED, 0);
820 /* SOCKS version 5 */
821 int proxy_socks5_negotiate (Proxy_Socket p, int change)
823 if (p->state == PROXY_CHANGE_NEW) {
826 * version number (1 byte) = 5
827 * number of available authentication methods (1 byte)
828 * available authentication methods (1 byte * previous value)
829 * authentication methods:
830 * 0x00 = no authentication
832 * 0x02 = username/password
839 command[0] = 5; /* version 5 */
840 if (cfg.proxy_username[0] || cfg.proxy_password[0]) {
841 command[1] = 2; /* two methods supported: */
842 command[2] = 0x00; /* no authentication */
843 command[3] = 0x02; /* username/password */
846 command[1] = 1; /* one methods supported: */
847 command[2] = 0x00; /* no authentication */
851 sk_write(p->sub_socket, command, len);
857 if (change == PROXY_CHANGE_CLOSING) {
858 /* if our proxy negotiation process involves closing and opening
859 * new sockets, then we would want to intercept this closing
860 * callback when we were expecting it. if we aren't anticipating
861 * a socket close, then some error must have occurred. we'll
862 * just pass those errors up to the backend.
864 return plug_closing(p->plug, p->closing_error_msg,
865 p->closing_error_code,
866 p->closing_calling_back);
869 if (change == PROXY_CHANGE_SENT) {
870 /* some (or all) of what we wrote to the proxy was sent.
871 * we don't do anything new, however, until we receive the
872 * proxy's response. we might want to set a timer so we can
873 * timeout the proxy negotiation after a while...
878 if (change == PROXY_CHANGE_ACCEPTING) {
879 /* we should _never_ see this, as we are using our socket to
880 * connect to a proxy, not accepting inbound connections.
881 * what should we do? close the socket with an appropriate
884 return plug_accepting(p->plug, p->accepting_sock);
887 if (change == PROXY_CHANGE_RECEIVE) {
888 /* we have received data from the underlying socket, which
889 * we'll need to parse, process, and respond to appropriately.
895 * version number (1 byte) = 5
896 * authentication method (1 byte)
897 * authentication methods:
898 * 0x00 = no authentication
900 * 0x02 = username/password
902 * 0xff = no acceptable methods
906 if (bufchain_size(&p->pending_input_data) < 2)
907 return 1; /* not got anything yet */
909 /* get the response */
910 bufchain_fetch(&p->pending_input_data, data, 2);
913 plug_closing(p->plug, "Proxy error: SOCKS proxy returned unexpected version",
914 PROXY_ERROR_GENERAL, 0);
918 if (data[1] == 0x00) p->state = 2; /* no authentication needed */
919 else if (data[1] == 0x01) p->state = 4; /* GSSAPI authentication */
920 else if (data[1] == 0x02) p->state = 5; /* username/password authentication */
921 else if (data[1] == 0x03) p->state = 6; /* CHAP authentication */
923 plug_closing(p->plug, "Proxy error: SOCKS proxy did not accept our authentication",
924 PROXY_ERROR_GENERAL, 0);
927 bufchain_consume(&p->pending_input_data, 2);
932 /* password authentication reply format:
933 * version number (1 bytes) = 1
934 * reply code (1 byte)
940 if (bufchain_size(&p->pending_input_data) < 2)
941 return 1; /* not got anything yet */
943 /* get the response */
944 bufchain_fetch(&p->pending_input_data, data, 2);
947 plug_closing(p->plug, "Proxy error: SOCKS password "
948 "subnegotiation contained wrong version number",
949 PROXY_ERROR_GENERAL, 0);
955 plug_closing(p->plug, "Proxy error: SOCKS proxy refused"
956 " password authentication",
957 PROXY_ERROR_GENERAL, 0);
961 bufchain_consume(&p->pending_input_data, 2);
962 p->state = 2; /* now proceed as authenticated */
968 * version number (1 byte) = 5
969 * command code (1 byte)
973 * reserved (1 byte) = 0x00
974 * address type (1 byte)
976 * 3 = domainname (first byte has length, no terminating null)
978 * dest. address (variable)
979 * dest. port (2 bytes) [network order]
986 type = sk_addrtype(p->remote_addr);
987 if (type == ADDRTYPE_IPV4) {
988 len = 10; /* 4 hdr + 4 addr + 2 trailer */
989 command[3] = 1; /* IPv4 */
990 sk_addrcopy(p->remote_addr, command+4);
991 } else if (type == ADDRTYPE_IPV6) {
992 len = 22; /* 4 hdr + 16 addr + 2 trailer */
993 command[3] = 4; /* IPv6 */
994 sk_addrcopy(p->remote_addr, command+4);
995 } else if (type == ADDRTYPE_NAME) {
997 sk_getaddr(p->remote_addr, command+5, 256);
998 command[4] = strlen(command+5);
999 len = 7 + command[4]; /* 4 hdr, 1 len, N addr, 2 trailer */
1002 command[0] = 5; /* version 5 */
1003 command[1] = 1; /* CONNECT command */
1007 command[len-2] = (char) (p->remote_port >> 8) & 0xff;
1008 command[len-1] = (char) p->remote_port & 0xff;
1010 sk_write(p->sub_socket, command, len);
1016 if (p->state == 3) {
1019 * version number (1 bytes) = 5
1020 * reply code (1 byte)
1022 * 1 = general SOCKS server failure
1023 * 2 = connection not allowed by ruleset
1024 * 3 = network unreachable
1025 * 4 = host unreachable
1026 * 5 = connection refused
1028 * 7 = command not supported
1029 * 8 = address type not supported
1030 * reserved (1 byte) = x00
1031 * address type (1 byte)
1033 * 3 = domainname (first byte has length, no terminating null)
1035 * server bound address (variable)
1036 * server bound port (2 bytes) [network order]
1041 /* First 5 bytes of packet are enough to tell its length. */
1042 if (bufchain_size(&p->pending_input_data) < 5)
1043 return 1; /* not got anything yet */
1045 /* get the response */
1046 bufchain_fetch(&p->pending_input_data, data, 5);
1049 plug_closing(p->plug, "Proxy error: SOCKS proxy returned wrong version number",
1050 PROXY_ERROR_GENERAL, 0);
1057 strcpy(buf, "Proxy error: ");
1060 case 1: strcat(buf, "General SOCKS server failure"); break;
1061 case 2: strcat(buf, "Connection not allowed by ruleset"); break;
1062 case 3: strcat(buf, "Network unreachable"); break;
1063 case 4: strcat(buf, "Host unreachable"); break;
1064 case 5: strcat(buf, "Connection refused"); break;
1065 case 6: strcat(buf, "TTL expired"); break;
1066 case 7: strcat(buf, "Command not supported"); break;
1067 case 8: strcat(buf, "Address type not supported"); break;
1068 default: sprintf(buf+strlen(buf),
1069 "Unrecognised SOCKS error code %d",
1073 plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0);
1079 * Eat the rest of the reply packet.
1081 len = 6; /* first 4 bytes, last 2 */
1083 case 1: len += 4; break; /* IPv4 address */
1084 case 4: len += 16; break;/* IPv6 address */
1085 case 3: len += (unsigned char)data[4]; break; /* domain name */
1087 plug_closing(p->plug, "Proxy error: SOCKS proxy returned "
1088 "unrecognised address format",
1089 PROXY_ERROR_GENERAL, 0);
1092 if (bufchain_size(&p->pending_input_data) < len)
1093 return 1; /* not got whole reply yet */
1094 bufchain_consume(&p->pending_input_data, len);
1101 if (p->state == 4) {
1102 /* TODO: Handle GSSAPI authentication */
1103 plug_closing(p->plug, "Proxy error: We don't support GSSAPI authentication",
1104 PROXY_ERROR_GENERAL, 0);
1108 if (p->state == 5) {
1109 if (cfg.proxy_username[0] || cfg.proxy_password[0]) {
1110 char userpwbuf[514];
1112 ulen = strlen(cfg.proxy_username);
1113 if (ulen > 255) ulen = 255; if (ulen < 1) ulen = 1;
1114 plen = strlen(cfg.proxy_password);
1115 if (plen > 255) plen = 255; if (plen < 1) plen = 1;
1116 userpwbuf[0] = 1; /* version number of subnegotiation */
1117 userpwbuf[1] = ulen;
1118 memcpy(userpwbuf+2, cfg.proxy_username, ulen);
1119 userpwbuf[ulen+2] = plen;
1120 memcpy(userpwbuf+ulen+3, cfg.proxy_password, plen);
1121 sk_write(p->sub_socket, userpwbuf, ulen + plen + 3);
1124 plug_closing(p->plug, "Proxy error: Server chose "
1125 "username/password authentication but we "
1127 PROXY_ERROR_GENERAL, 0);
1131 if (p->state == 6) {
1132 /* TODO: Handle CHAP authentication */
1133 plug_closing(p->plug, "Proxy error: We don't support CHAP authentication",
1134 PROXY_ERROR_GENERAL, 0);
1140 plug_closing(p->plug, "Proxy error: Unexpected proxy error",
1141 PROXY_ERROR_UNEXPECTED, 0);
1145 /* ----------------------------------------------------------------------
1146 * `Telnet' proxy type.
1148 * (This is for ad-hoc proxies where you connect to the proxy's
1149 * telnet port and send a command such as `connect host port'. The
1150 * command is configurable, since this proxy type is typically not
1151 * standardised or at all well-defined.)
1154 int proxy_telnet_negotiate (Proxy_Socket p, int change)
1156 if (p->state == PROXY_CHANGE_NEW) {
1160 /* we need to escape \\, \%, \r, \n, \t, \x??, \0???,
1161 * %%, %host, %port, %user, and %pass
1164 while (cfg.proxy_telnet_command[eo] != 0) {
1166 /* scan forward until we hit end-of-line,
1167 * or an escape character (\ or %) */
1168 while (cfg.proxy_telnet_command[eo] != 0 &&
1169 cfg.proxy_telnet_command[eo] != '%' &&
1170 cfg.proxy_telnet_command[eo] != '\\') eo++;
1172 /* if we hit eol, break out of our escaping loop */
1173 if (cfg.proxy_telnet_command[eo] == 0) break;
1175 /* if there was any unescaped text before the escape
1176 * character, send that now */
1178 sk_write(p->sub_socket,
1179 cfg.proxy_telnet_command + so, eo - so);
1184 /* if the escape character was the last character of
1185 * the line, we'll just stop and send it. */
1186 if (cfg.proxy_telnet_command[eo] == 0) break;
1188 if (cfg.proxy_telnet_command[so] == '\\') {
1190 /* we recognize \\, \%, \r, \n, \t, \x??.
1191 * anything else, we just send unescaped (including the \).
1194 switch (cfg.proxy_telnet_command[eo]) {
1197 sk_write(p->sub_socket, "\\", 1);
1202 sk_write(p->sub_socket, "%%", 1);
1207 sk_write(p->sub_socket, "\r", 1);
1212 sk_write(p->sub_socket, "\n", 1);
1217 sk_write(p->sub_socket, "\t", 1);
1224 /* escaped hexadecimal value (ie. \xff) */
1225 unsigned char v = 0;
1230 if (cfg.proxy_telnet_command[eo] >= '0' &&
1231 cfg.proxy_telnet_command[eo] <= '9')
1232 v += cfg.proxy_telnet_command[eo] - '0';
1233 else if (cfg.proxy_telnet_command[eo] >= 'a' &&
1234 cfg.proxy_telnet_command[eo] <= 'f')
1235 v += cfg.proxy_telnet_command[eo] - 'a' + 10;
1236 else if (cfg.proxy_telnet_command[eo] >= 'A' &&
1237 cfg.proxy_telnet_command[eo] <= 'F')
1238 v += cfg.proxy_telnet_command[eo] - 'A' + 10;
1240 /* non hex character, so we abort and just
1241 * send the whole thing unescaped (including \x)
1243 sk_write(p->sub_socket, "\\", 1);
1248 /* we only extract two hex characters */
1250 sk_write(p->sub_socket, &v, 1);
1262 sk_write(p->sub_socket,
1263 cfg.proxy_telnet_command + so, 2);
1269 /* % escape. we recognize %%, %host, %port, %user, %pass.
1270 * anything else, we just send unescaped (including the %).
1273 if (cfg.proxy_telnet_command[eo] == '%') {
1274 sk_write(p->sub_socket, "%", 1);
1277 else if (strnicmp(cfg.proxy_telnet_command + eo,
1280 sk_getaddr(p->remote_addr, dest, lenof(dest));
1281 sk_write(p->sub_socket, dest, strlen(dest));
1284 else if (strnicmp(cfg.proxy_telnet_command + eo,
1287 sprintf(port, "%i", p->remote_port);
1288 sk_write(p->sub_socket, port, strlen(port));
1291 else if (strnicmp(cfg.proxy_telnet_command + eo,
1293 sk_write(p->sub_socket, cfg.proxy_username,
1294 strlen(cfg.proxy_username));
1297 else if (strnicmp(cfg.proxy_telnet_command + eo,
1299 sk_write(p->sub_socket, cfg.proxy_password,
1300 strlen(cfg.proxy_password));
1304 /* we don't escape this, so send the % now, and
1305 * don't advance eo, so that we'll consider the
1306 * text immediately following the % as unescaped.
1308 sk_write(p->sub_socket, "%", 1);
1312 /* resume scanning for additional escapes after this one. */
1316 /* if there is any unescaped text at the end of the line, send it */
1318 sk_write(p->sub_socket, cfg.proxy_telnet_command + so, eo - so);
1325 if (change == PROXY_CHANGE_CLOSING) {
1326 /* if our proxy negotiation process involves closing and opening
1327 * new sockets, then we would want to intercept this closing
1328 * callback when we were expecting it. if we aren't anticipating
1329 * a socket close, then some error must have occurred. we'll
1330 * just pass those errors up to the backend.
1332 return plug_closing(p->plug, p->closing_error_msg,
1333 p->closing_error_code,
1334 p->closing_calling_back);
1337 if (change == PROXY_CHANGE_SENT) {
1338 /* some (or all) of what we wrote to the proxy was sent.
1339 * we don't do anything new, however, until we receive the
1340 * proxy's response. we might want to set a timer so we can
1341 * timeout the proxy negotiation after a while...
1346 if (change == PROXY_CHANGE_ACCEPTING) {
1347 /* we should _never_ see this, as we are using our socket to
1348 * connect to a proxy, not accepting inbound connections.
1349 * what should we do? close the socket with an appropriate
1352 return plug_accepting(p->plug, p->accepting_sock);
1355 if (change == PROXY_CHANGE_RECEIVE) {
1356 /* we have received data from the underlying socket, which
1357 * we'll need to parse, process, and respond to appropriately.
1362 /* proxy activate will have dealt with
1363 * whatever is left of the buffer */
1367 plug_closing(p->plug, "Proxy error: Unexpected proxy error",
1368 PROXY_ERROR_UNEXPECTED, 0);