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(cfg) \
18 (cfg->proxy_dns == FORCE_ON || \
19 (cfg->proxy_dns == AUTO && \
20 cfg->proxy_type != PROXY_SOCKS4 && \
21 cfg->proxy_type != PROXY_SOCKS5))
24 * Call this when proxy negotiation is complete, so that this
25 * socket can begin working normally.
27 void proxy_activate (Proxy_Socket p)
31 long output_before, output_after;
33 p->state = PROXY_STATE_ACTIVE;
35 /* we want to ignore new receive events until we have sent
36 * all of our buffered receive data.
38 sk_set_frozen(p->sub_socket, 1);
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. */
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);
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);
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);
64 /* if we were asked to flush the output during
65 * the proxy negotiation process, do so now.
67 if (p->pending_flush) sk_flush(p->sub_socket);
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.
74 sk_set_frozen((Socket)p, 0);
77 /* basic proxy socket functions */
79 static Plug sk_proxy_plug (Socket s, Plug p)
81 Proxy_Socket ps = (Proxy_Socket) s;
88 static void sk_proxy_close (Socket s)
90 Proxy_Socket ps = (Proxy_Socket) s;
92 sk_close(ps->sub_socket);
93 sk_addr_free(ps->remote_addr);
97 static int sk_proxy_write (Socket s, const char *data, int len)
99 Proxy_Socket ps = (Proxy_Socket) s;
101 if (ps->state != PROXY_STATE_ACTIVE) {
102 bufchain_add(&ps->pending_output_data, data, len);
103 return bufchain_size(&ps->pending_output_data);
105 return sk_write(ps->sub_socket, data, len);
108 static int sk_proxy_write_oob (Socket s, const char *data, int len)
110 Proxy_Socket ps = (Proxy_Socket) s;
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);
118 return sk_write_oob(ps->sub_socket, data, len);
121 static void sk_proxy_flush (Socket s)
123 Proxy_Socket ps = (Proxy_Socket) s;
125 if (ps->state != PROXY_STATE_ACTIVE) {
126 ps->pending_flush = 1;
129 sk_flush(ps->sub_socket);
132 static void sk_proxy_set_private_ptr (Socket s, void *ptr)
134 Proxy_Socket ps = (Proxy_Socket) s;
135 sk_set_private_ptr(ps->sub_socket, ptr);
138 static void * sk_proxy_get_private_ptr (Socket s)
140 Proxy_Socket ps = (Proxy_Socket) s;
141 return sk_get_private_ptr(ps->sub_socket);
144 static void sk_proxy_set_frozen (Socket s, int is_frozen)
146 Proxy_Socket ps = (Proxy_Socket) s;
148 if (ps->state != PROXY_STATE_ACTIVE) {
149 ps->freeze = is_frozen;
153 /* handle any remaining buffered recv data first */
154 if (bufchain_size(&ps->pending_input_data) > 0) {
155 ps->freeze = is_frozen;
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.
162 while (!ps->freeze && bufchain_size(&ps->pending_input_data) > 0) {
165 bufchain_prefix(&ps->pending_input_data, &data, &len);
166 plug_receive(ps->plug, 0, data, len);
167 bufchain_consume(&ps->pending_input_data, len);
170 /* if we're still frozen, we'll have to wait for another
171 * call from the backend to finish unbuffering the data.
173 if (ps->freeze) return;
176 sk_set_frozen(ps->sub_socket, is_frozen);
179 static const char * sk_proxy_socket_error (Socket s)
181 Proxy_Socket ps = (Proxy_Socket) s;
182 if (ps->error != NULL || ps->sub_socket == NULL) {
185 return sk_socket_error(ps->sub_socket);
188 /* basic proxy plug functions */
190 static int plug_proxy_closing (Plug p, const char *error_msg,
191 int error_code, int calling_back)
193 Proxy_Plug pp = (Proxy_Plug) p;
194 Proxy_Socket ps = pp->proxy_socket;
196 if (ps->state != PROXY_STATE_ACTIVE) {
197 ps->closing_error_msg = error_msg;
198 ps->closing_error_code = error_code;
199 ps->closing_calling_back = calling_back;
200 return ps->negotiate(ps, PROXY_CHANGE_CLOSING);
202 return plug_closing(ps->plug, error_msg,
203 error_code, calling_back);
206 static int plug_proxy_receive (Plug p, int urgent, char *data, int len)
208 Proxy_Plug pp = (Proxy_Plug) p;
209 Proxy_Socket ps = pp->proxy_socket;
211 if (ps->state != PROXY_STATE_ACTIVE) {
212 /* we will lose the urgentness of this data, but since most,
213 * if not all, of this data will be consumed by the negotiation
214 * process, hopefully it won't affect the protocol above us
216 bufchain_add(&ps->pending_input_data, data, len);
217 ps->receive_urgent = urgent;
218 ps->receive_data = data;
219 ps->receive_len = len;
220 return ps->negotiate(ps, PROXY_CHANGE_RECEIVE);
222 return plug_receive(ps->plug, urgent, data, len);
225 static void plug_proxy_sent (Plug p, int bufsize)
227 Proxy_Plug pp = (Proxy_Plug) p;
228 Proxy_Socket ps = pp->proxy_socket;
230 if (ps->state != PROXY_STATE_ACTIVE) {
231 ps->sent_bufsize = bufsize;
232 ps->negotiate(ps, PROXY_CHANGE_SENT);
235 plug_sent(ps->plug, bufsize);
238 static int plug_proxy_accepting (Plug p, OSSocket sock)
240 Proxy_Plug pp = (Proxy_Plug) p;
241 Proxy_Socket ps = pp->proxy_socket;
243 if (ps->state != PROXY_STATE_ACTIVE) {
244 ps->accepting_sock = sock;
245 return ps->negotiate(ps, PROXY_CHANGE_ACCEPTING);
247 return plug_accepting(ps->plug, sock);
251 * This function can accept a NULL pointer as `addr', in which case
252 * it will only check the host name.
254 static int proxy_for_destination (SockAddr addr, char *hostname, int port,
259 int hostip_len, hostname_len;
260 const char *exclude_list;
263 * Check the host name and IP against the hard-coded
264 * representations of `localhost'.
266 if (!cfg->even_proxy_localhost &&
267 (sk_hostname_is_local(hostname) ||
268 (addr && sk_address_is_local(addr))))
269 return 0; /* do not proxy */
271 /* we want a string representation of the IP address for comparisons */
273 sk_getaddr(addr, hostip, 64);
274 hostip_len = strlen(hostip);
276 hostip_len = 0; /* placate gcc; shouldn't be required */
278 hostname_len = strlen(hostname);
280 exclude_list = cfg->proxy_exclude_list;
282 /* now parse the exclude list, and see if either our IP
283 * or hostname matches anything in it.
286 while (exclude_list[s]) {
287 while (exclude_list[s] &&
288 (isspace((unsigned char)exclude_list[s]) ||
289 exclude_list[s] == ',')) s++;
291 if (!exclude_list[s]) break;
295 while (exclude_list[e] &&
296 (isalnum((unsigned char)exclude_list[e]) ||
297 exclude_list[e] == '-' ||
298 exclude_list[e] == '.' ||
299 exclude_list[e] == '*')) e++;
301 if (exclude_list[s] == '*') {
302 /* wildcard at beginning of entry */
304 if ((addr && strnicmp(hostip + hostip_len - (e - s - 1),
305 exclude_list + s + 1, e - s - 1) == 0) ||
306 strnicmp(hostname + hostname_len - (e - s - 1),
307 exclude_list + s + 1, e - s - 1) == 0)
308 return 0; /* IP/hostname range excluded. do not use proxy. */
310 } else if (exclude_list[e-1] == '*') {
311 /* wildcard at end of entry */
313 if ((addr && strnicmp(hostip, exclude_list + s, e - s - 1) == 0) ||
314 strnicmp(hostname, exclude_list + s, e - s - 1) == 0)
315 return 0; /* IP/hostname range excluded. do not use proxy. */
318 /* no wildcard at either end, so let's try an absolute
319 * match (ie. a specific IP)
322 if (addr && strnicmp(hostip, exclude_list + s, e - s) == 0)
323 return 0; /* IP/hostname excluded. do not use proxy. */
324 if (strnicmp(hostname, exclude_list + s, e - s) == 0)
325 return 0; /* IP/hostname excluded. do not use proxy. */
330 /* Make sure we really have reached the next comma or end-of-string */
331 while (exclude_list[s] &&
332 !isspace((unsigned char)exclude_list[s]) &&
333 exclude_list[s] != ',') s++;
336 /* no matches in the exclude list, so use the proxy */
340 SockAddr name_lookup(char *host, int port, char **canonicalname,
343 if (cfg->proxy_type != PROXY_NONE &&
345 proxy_for_destination(NULL, host, port, cfg)) {
346 *canonicalname = dupstr(host);
347 return sk_nonamelookup(host);
350 return sk_namelookup(host, canonicalname);
353 Socket new_connection(SockAddr addr, char *hostname,
354 int port, int privport,
355 int oobinline, int nodelay, Plug plug,
358 static const struct socket_function_table socket_fn_table = {
364 sk_proxy_set_private_ptr,
365 sk_proxy_get_private_ptr,
367 sk_proxy_socket_error
370 static const struct plug_function_table plug_fn_table = {
377 if (cfg->proxy_type != PROXY_NONE &&
378 proxy_for_destination(addr, hostname, port, cfg))
383 char *proxy_canonical_name;
386 if ((sret = platform_new_connection(addr, hostname, port, privport,
387 oobinline, nodelay, plug, cfg)) !=
391 ret = snew(struct Socket_proxy_tag);
392 ret->fn = &socket_fn_table;
393 ret->cfg = *cfg; /* STRUCTURE COPY */
395 ret->remote_addr = addr; /* will need to be freed on close */
396 ret->remote_port = port;
399 ret->pending_flush = 0;
402 bufchain_init(&ret->pending_input_data);
403 bufchain_init(&ret->pending_output_data);
404 bufchain_init(&ret->pending_oob_output_data);
406 ret->sub_socket = NULL;
407 ret->state = PROXY_STATE_NEW;
408 ret->negotiate = NULL;
410 if (cfg->proxy_type == PROXY_HTTP) {
411 ret->negotiate = proxy_http_negotiate;
412 } else if (cfg->proxy_type == PROXY_SOCKS4) {
413 ret->negotiate = proxy_socks4_negotiate;
414 } else if (cfg->proxy_type == PROXY_SOCKS5) {
415 ret->negotiate = proxy_socks5_negotiate;
416 } else if (cfg->proxy_type == PROXY_TELNET) {
417 ret->negotiate = proxy_telnet_negotiate;
419 ret->error = "Proxy error: Unknown proxy method";
423 /* create the proxy plug to map calls from the actual
424 * socket into our proxy socket layer */
425 pplug = snew(struct Plug_proxy_tag);
426 pplug->fn = &plug_fn_table;
427 pplug->proxy_socket = ret;
430 proxy_addr = sk_namelookup(cfg->proxy_host,
431 &proxy_canonical_name);
432 if (sk_addr_error(proxy_addr) != NULL) {
433 ret->error = "Proxy error: Unable to resolve proxy host name";
436 sfree(proxy_canonical_name);
438 /* create the actual socket we will be using,
439 * connected to our proxy server and port.
441 ret->sub_socket = sk_new(proxy_addr, cfg->proxy_port,
443 nodelay, (Plug) pplug);
444 if (sk_socket_error(ret->sub_socket) != NULL)
447 /* start the proxy negotiation process... */
448 sk_set_frozen(ret->sub_socket, 0);
449 ret->negotiate(ret, PROXY_CHANGE_NEW);
454 /* no proxy, so just return the direct socket */
455 return sk_new(addr, port, privport, oobinline, nodelay, plug);
458 Socket new_listener(char *srcaddr, int port, Plug plug, int local_host_only,
461 /* TODO: SOCKS (and potentially others) support inbound
462 * TODO: connections via the proxy. support them.
465 return sk_newlistener(srcaddr, port, plug, local_host_only);
468 /* ----------------------------------------------------------------------
469 * HTTP CONNECT proxy type.
472 static int get_line_end (char * data, int len)
478 if (data[off] == '\n') {
479 /* we have a newline */
482 /* is that the only thing on this line? */
483 if (off <= 2) return off;
485 /* if not, then there is the possibility that this header
486 * continues onto the next line, if it starts with a space
491 data[off+1] != ' ' &&
492 data[off+1] != '\t') return off;
494 /* the line does continue, so we have to keep going
495 * until we see an the header's "real" end of line.
506 int proxy_http_negotiate (Proxy_Socket p, int change)
508 if (p->state == PROXY_STATE_NEW) {
509 /* we are just beginning the proxy negotiate process,
510 * so we'll send off the initial bits of the request.
511 * for this proxy method, it's just a simple HTTP
514 char *buf, dest[512];
516 sk_getaddr(p->remote_addr, dest, lenof(dest));
518 buf = dupprintf("CONNECT %s:%i HTTP/1.1\r\nHost: %s:%i\r\n",
519 dest, p->remote_port, dest, p->remote_port);
520 sk_write(p->sub_socket, buf, strlen(buf));
523 if (p->cfg.proxy_username[0] || p->cfg.proxy_password[0]) {
524 char buf[sizeof(p->cfg.proxy_username)+sizeof(p->cfg.proxy_password)];
525 char buf2[sizeof(buf)*4/3 + 100];
527 sprintf(buf, "%s:%s", p->cfg.proxy_username, p->cfg.proxy_password);
529 sprintf(buf2, "Proxy-Authorization: Basic ");
530 for (i = 0, j = strlen(buf2); i < len; i += 3, j += 4)
531 base64_encode_atom((unsigned char *)(buf+i),
532 (len-i > 3 ? 3 : len-i), buf2+j);
533 strcpy(buf2+j, "\r\n");
534 sk_write(p->sub_socket, buf2, strlen(buf2));
537 sk_write(p->sub_socket, "\r\n", 2);
543 if (change == PROXY_CHANGE_CLOSING) {
544 /* if our proxy negotiation process involves closing and opening
545 * new sockets, then we would want to intercept this closing
546 * callback when we were expecting it. if we aren't anticipating
547 * a socket close, then some error must have occurred. we'll
548 * just pass those errors up to the backend.
550 return plug_closing(p->plug, p->closing_error_msg,
551 p->closing_error_code,
552 p->closing_calling_back);
555 if (change == PROXY_CHANGE_SENT) {
556 /* some (or all) of what we wrote to the proxy was sent.
557 * we don't do anything new, however, until we receive the
558 * proxy's response. we might want to set a timer so we can
559 * timeout the proxy negotiation after a while...
564 if (change == PROXY_CHANGE_ACCEPTING) {
565 /* we should _never_ see this, as we are using our socket to
566 * connect to a proxy, not accepting inbound connections.
567 * what should we do? close the socket with an appropriate
570 return plug_accepting(p->plug, p->accepting_sock);
573 if (change == PROXY_CHANGE_RECEIVE) {
574 /* we have received data from the underlying socket, which
575 * we'll need to parse, process, and respond to appropriately.
584 int min_ver, maj_ver, status;
586 /* get the status line */
587 len = bufchain_size(&p->pending_input_data);
588 assert(len > 0); /* or we wouldn't be here */
589 data = snewn(len, char);
590 bufchain_fetch(&p->pending_input_data, data, len);
592 eol = get_line_end(data, len);
599 /* We can't rely on whether the %n incremented the sscanf return */
600 if (sscanf((char *)data, "HTTP/%i.%i %n",
601 &maj_ver, &min_ver, &status) < 2 || status == -1) {
602 plug_closing(p->plug, "Proxy error: HTTP response was absent",
603 PROXY_ERROR_GENERAL, 0);
608 /* remove the status line from the input buffer. */
609 bufchain_consume(&p->pending_input_data, eol);
610 if (data[status] != '2') {
614 while (eol > status &&
615 (data[eol-1] == '\r' || data[eol-1] == '\n'))
617 buf = dupprintf("Proxy error: %s", data+status);
618 plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0);
631 /* get headers. we're done when we get a
632 * header of length 2, (ie. just "\r\n")
635 len = bufchain_size(&p->pending_input_data);
636 assert(len > 0); /* or we wouldn't be here */
637 data = snewn(len, char);
639 bufchain_fetch(&p->pending_input_data, data, len);
641 eol = get_line_end(datap, len);
648 bufchain_consume(&p->pending_input_data, eol);
651 eol = get_line_end(datap, len);
656 bufchain_consume(&p->pending_input_data, 2);
658 /* proxy activate will have dealt with
659 * whatever is left of the buffer */
669 plug_closing(p->plug, "Proxy error: unexpected proxy error",
670 PROXY_ERROR_UNEXPECTED, 0);
674 /* ----------------------------------------------------------------------
678 /* SOCKS version 4 */
679 int proxy_socks4_negotiate (Proxy_Socket p, int change)
681 if (p->state == PROXY_CHANGE_NEW) {
684 * version number (1 byte) = 4
685 * command code (1 byte)
688 * dest. port (2 bytes) [network order]
689 * dest. address (4 bytes)
690 * user ID (variable length, null terminated string)
693 int length, type, namelen;
694 char *command, addr[4], hostname[512];
696 type = sk_addrtype(p->remote_addr);
697 if (type == ADDRTYPE_IPV6) {
698 plug_closing(p->plug, "Proxy error: SOCKS version 4 does"
699 " not support IPv6", PROXY_ERROR_GENERAL, 0);
701 } else if (type == ADDRTYPE_IPV4) {
703 sk_addrcopy(p->remote_addr, addr);
704 } else { /* type == ADDRTYPE_NAME */
705 assert(type == ADDRTYPE_NAME);
706 sk_getaddr(p->remote_addr, hostname, lenof(hostname));
707 namelen = strlen(hostname) + 1; /* include the NUL */
708 addr[0] = addr[1] = addr[2] = 0;
712 length = strlen(p->cfg.proxy_username) + namelen + 9;
713 command = snewn(length, char);
714 strcpy(command + 8, p->cfg.proxy_username);
716 command[0] = 4; /* version 4 */
717 command[1] = 1; /* CONNECT command */
720 command[2] = (char) (p->remote_port >> 8) & 0xff;
721 command[3] = (char) p->remote_port & 0xff;
724 memcpy(command + 4, addr, 4);
727 memcpy(command + 8 + strlen(p->cfg.proxy_username) + 1,
730 sk_write(p->sub_socket, command, length);
737 if (change == PROXY_CHANGE_CLOSING) {
738 /* if our proxy negotiation process involves closing and opening
739 * new sockets, then we would want to intercept this closing
740 * callback when we were expecting it. if we aren't anticipating
741 * a socket close, then some error must have occurred. we'll
742 * just pass those errors up to the backend.
744 return plug_closing(p->plug, p->closing_error_msg,
745 p->closing_error_code,
746 p->closing_calling_back);
749 if (change == PROXY_CHANGE_SENT) {
750 /* some (or all) of what we wrote to the proxy was sent.
751 * we don't do anything new, however, until we receive the
752 * proxy's response. we might want to set a timer so we can
753 * timeout the proxy negotiation after a while...
758 if (change == PROXY_CHANGE_ACCEPTING) {
759 /* we should _never_ see this, as we are using our socket to
760 * connect to a proxy, not accepting inbound connections.
761 * what should we do? close the socket with an appropriate
764 return plug_accepting(p->plug, p->accepting_sock);
767 if (change == PROXY_CHANGE_RECEIVE) {
768 /* we have received data from the underlying socket, which
769 * we'll need to parse, process, and respond to appropriately.
774 * version number (1 byte) = 4
775 * reply code (1 byte)
776 * 90 = request granted
777 * 91 = request rejected or failed
778 * 92 = request rejected due to lack of IDENTD on client
779 * 93 = request rejected due to difference in user ID
780 * (what we sent vs. what IDENTD said)
781 * dest. port (2 bytes)
782 * dest. address (4 bytes)
787 if (bufchain_size(&p->pending_input_data) < 8)
788 return 1; /* not got anything yet */
790 /* get the response */
791 bufchain_fetch(&p->pending_input_data, data, 8);
794 plug_closing(p->plug, "Proxy error: SOCKS proxy responded with "
795 "unexpected reply code version",
796 PROXY_ERROR_GENERAL, 0);
804 plug_closing(p->plug, "Proxy error: SOCKS server wanted IDENTD on client",
805 PROXY_ERROR_GENERAL, 0);
808 plug_closing(p->plug, "Proxy error: Username and IDENTD on client don't agree",
809 PROXY_ERROR_GENERAL, 0);
813 plug_closing(p->plug, "Proxy error: Error while communicating with proxy",
814 PROXY_ERROR_GENERAL, 0);
820 bufchain_consume(&p->pending_input_data, 8);
824 /* proxy activate will have dealt with
825 * whatever is left of the buffer */
830 plug_closing(p->plug, "Proxy error: unexpected proxy error",
831 PROXY_ERROR_UNEXPECTED, 0);
835 /* SOCKS version 5 */
836 int proxy_socks5_negotiate (Proxy_Socket p, int change)
838 if (p->state == PROXY_CHANGE_NEW) {
841 * version number (1 byte) = 5
842 * number of available authentication methods (1 byte)
843 * available authentication methods (1 byte * previous value)
844 * authentication methods:
845 * 0x00 = no authentication
847 * 0x02 = username/password
854 command[0] = 5; /* version 5 */
855 if (p->cfg.proxy_username[0] || p->cfg.proxy_password[0]) {
856 command[1] = 2; /* two methods supported: */
857 command[2] = 0x00; /* no authentication */
858 command[3] = 0x02; /* username/password */
861 command[1] = 1; /* one methods supported: */
862 command[2] = 0x00; /* no authentication */
866 sk_write(p->sub_socket, command, len);
872 if (change == PROXY_CHANGE_CLOSING) {
873 /* if our proxy negotiation process involves closing and opening
874 * new sockets, then we would want to intercept this closing
875 * callback when we were expecting it. if we aren't anticipating
876 * a socket close, then some error must have occurred. we'll
877 * just pass those errors up to the backend.
879 return plug_closing(p->plug, p->closing_error_msg,
880 p->closing_error_code,
881 p->closing_calling_back);
884 if (change == PROXY_CHANGE_SENT) {
885 /* some (or all) of what we wrote to the proxy was sent.
886 * we don't do anything new, however, until we receive the
887 * proxy's response. we might want to set a timer so we can
888 * timeout the proxy negotiation after a while...
893 if (change == PROXY_CHANGE_ACCEPTING) {
894 /* we should _never_ see this, as we are using our socket to
895 * connect to a proxy, not accepting inbound connections.
896 * what should we do? close the socket with an appropriate
899 return plug_accepting(p->plug, p->accepting_sock);
902 if (change == PROXY_CHANGE_RECEIVE) {
903 /* we have received data from the underlying socket, which
904 * we'll need to parse, process, and respond to appropriately.
910 * version number (1 byte) = 5
911 * authentication method (1 byte)
912 * authentication methods:
913 * 0x00 = no authentication
915 * 0x02 = username/password
917 * 0xff = no acceptable methods
921 if (bufchain_size(&p->pending_input_data) < 2)
922 return 1; /* not got anything yet */
924 /* get the response */
925 bufchain_fetch(&p->pending_input_data, data, 2);
928 plug_closing(p->plug, "Proxy error: SOCKS proxy returned unexpected version",
929 PROXY_ERROR_GENERAL, 0);
933 if (data[1] == 0x00) p->state = 2; /* no authentication needed */
934 else if (data[1] == 0x01) p->state = 4; /* GSSAPI authentication */
935 else if (data[1] == 0x02) p->state = 5; /* username/password authentication */
936 else if (data[1] == 0x03) p->state = 6; /* CHAP authentication */
938 plug_closing(p->plug, "Proxy error: SOCKS proxy did not accept our authentication",
939 PROXY_ERROR_GENERAL, 0);
942 bufchain_consume(&p->pending_input_data, 2);
947 /* password authentication reply format:
948 * version number (1 bytes) = 1
949 * reply code (1 byte)
955 if (bufchain_size(&p->pending_input_data) < 2)
956 return 1; /* not got anything yet */
958 /* get the response */
959 bufchain_fetch(&p->pending_input_data, data, 2);
962 plug_closing(p->plug, "Proxy error: SOCKS password "
963 "subnegotiation contained wrong version number",
964 PROXY_ERROR_GENERAL, 0);
970 plug_closing(p->plug, "Proxy error: SOCKS proxy refused"
971 " password authentication",
972 PROXY_ERROR_GENERAL, 0);
976 bufchain_consume(&p->pending_input_data, 2);
977 p->state = 2; /* now proceed as authenticated */
983 * version number (1 byte) = 5
984 * command code (1 byte)
988 * reserved (1 byte) = 0x00
989 * address type (1 byte)
991 * 3 = domainname (first byte has length, no terminating null)
993 * dest. address (variable)
994 * dest. port (2 bytes) [network order]
1001 type = sk_addrtype(p->remote_addr);
1002 if (type == ADDRTYPE_IPV4) {
1003 len = 10; /* 4 hdr + 4 addr + 2 trailer */
1004 command[3] = 1; /* IPv4 */
1005 sk_addrcopy(p->remote_addr, command+4);
1006 } else if (type == ADDRTYPE_IPV6) {
1007 len = 22; /* 4 hdr + 16 addr + 2 trailer */
1008 command[3] = 4; /* IPv6 */
1009 sk_addrcopy(p->remote_addr, command+4);
1011 assert(type == ADDRTYPE_NAME);
1013 sk_getaddr(p->remote_addr, command+5, 256);
1014 command[4] = strlen(command+5);
1015 len = 7 + command[4]; /* 4 hdr, 1 len, N addr, 2 trailer */
1018 command[0] = 5; /* version 5 */
1019 command[1] = 1; /* CONNECT command */
1023 command[len-2] = (char) (p->remote_port >> 8) & 0xff;
1024 command[len-1] = (char) p->remote_port & 0xff;
1026 sk_write(p->sub_socket, command, len);
1032 if (p->state == 3) {
1035 * version number (1 bytes) = 5
1036 * reply code (1 byte)
1038 * 1 = general SOCKS server failure
1039 * 2 = connection not allowed by ruleset
1040 * 3 = network unreachable
1041 * 4 = host unreachable
1042 * 5 = connection refused
1044 * 7 = command not supported
1045 * 8 = address type not supported
1046 * reserved (1 byte) = x00
1047 * address type (1 byte)
1049 * 3 = domainname (first byte has length, no terminating null)
1051 * server bound address (variable)
1052 * server bound port (2 bytes) [network order]
1057 /* First 5 bytes of packet are enough to tell its length. */
1058 if (bufchain_size(&p->pending_input_data) < 5)
1059 return 1; /* not got anything yet */
1061 /* get the response */
1062 bufchain_fetch(&p->pending_input_data, data, 5);
1065 plug_closing(p->plug, "Proxy error: SOCKS proxy returned wrong version number",
1066 PROXY_ERROR_GENERAL, 0);
1073 strcpy(buf, "Proxy error: ");
1076 case 1: strcat(buf, "General SOCKS server failure"); break;
1077 case 2: strcat(buf, "Connection not allowed by ruleset"); break;
1078 case 3: strcat(buf, "Network unreachable"); break;
1079 case 4: strcat(buf, "Host unreachable"); break;
1080 case 5: strcat(buf, "Connection refused"); break;
1081 case 6: strcat(buf, "TTL expired"); break;
1082 case 7: strcat(buf, "Command not supported"); break;
1083 case 8: strcat(buf, "Address type not supported"); break;
1084 default: sprintf(buf+strlen(buf),
1085 "Unrecognised SOCKS error code %d",
1089 plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0);
1095 * Eat the rest of the reply packet.
1097 len = 6; /* first 4 bytes, last 2 */
1099 case 1: len += 4; break; /* IPv4 address */
1100 case 4: len += 16; break;/* IPv6 address */
1101 case 3: len += (unsigned char)data[4]; break; /* domain name */
1103 plug_closing(p->plug, "Proxy error: SOCKS proxy returned "
1104 "unrecognised address format",
1105 PROXY_ERROR_GENERAL, 0);
1108 if (bufchain_size(&p->pending_input_data) < len)
1109 return 1; /* not got whole reply yet */
1110 bufchain_consume(&p->pending_input_data, len);
1117 if (p->state == 4) {
1118 /* TODO: Handle GSSAPI authentication */
1119 plug_closing(p->plug, "Proxy error: We don't support GSSAPI authentication",
1120 PROXY_ERROR_GENERAL, 0);
1124 if (p->state == 5) {
1125 if (p->cfg.proxy_username[0] || p->cfg.proxy_password[0]) {
1126 char userpwbuf[514];
1128 ulen = strlen(p->cfg.proxy_username);
1129 if (ulen > 255) ulen = 255; if (ulen < 1) ulen = 1;
1130 plen = strlen(p->cfg.proxy_password);
1131 if (plen > 255) plen = 255; if (plen < 1) plen = 1;
1132 userpwbuf[0] = 1; /* version number of subnegotiation */
1133 userpwbuf[1] = ulen;
1134 memcpy(userpwbuf+2, p->cfg.proxy_username, ulen);
1135 userpwbuf[ulen+2] = plen;
1136 memcpy(userpwbuf+ulen+3, p->cfg.proxy_password, plen);
1137 sk_write(p->sub_socket, userpwbuf, ulen + plen + 3);
1140 plug_closing(p->plug, "Proxy error: Server chose "
1141 "username/password authentication but we "
1143 PROXY_ERROR_GENERAL, 0);
1147 if (p->state == 6) {
1148 /* TODO: Handle CHAP authentication */
1149 plug_closing(p->plug, "Proxy error: We don't support CHAP authentication",
1150 PROXY_ERROR_GENERAL, 0);
1156 plug_closing(p->plug, "Proxy error: Unexpected proxy error",
1157 PROXY_ERROR_UNEXPECTED, 0);
1161 /* ----------------------------------------------------------------------
1162 * `Telnet' proxy type.
1164 * (This is for ad-hoc proxies where you connect to the proxy's
1165 * telnet port and send a command such as `connect host port'. The
1166 * command is configurable, since this proxy type is typically not
1167 * standardised or at all well-defined.)
1170 char *format_telnet_command(SockAddr addr, int port, const Config *cfg)
1173 int retlen = 0, retsize = 0;
1175 #define ENSURE(n) do { \
1176 if (retsize < retlen + n) { \
1177 retsize = retlen + n + 512; \
1178 ret = sresize(ret, retsize, char); \
1182 /* we need to escape \\, \%, \r, \n, \t, \x??, \0???,
1183 * %%, %host, %port, %user, and %pass
1186 while (cfg->proxy_telnet_command[eo] != 0) {
1188 /* scan forward until we hit end-of-line,
1189 * or an escape character (\ or %) */
1190 while (cfg->proxy_telnet_command[eo] != 0 &&
1191 cfg->proxy_telnet_command[eo] != '%' &&
1192 cfg->proxy_telnet_command[eo] != '\\') eo++;
1194 /* if we hit eol, break out of our escaping loop */
1195 if (cfg->proxy_telnet_command[eo] == 0) break;
1197 /* if there was any unescaped text before the escape
1198 * character, send that now */
1201 memcpy(ret + retlen, cfg->proxy_telnet_command + so, eo - so);
1207 /* if the escape character was the last character of
1208 * the line, we'll just stop and send it. */
1209 if (cfg->proxy_telnet_command[eo] == 0) break;
1211 if (cfg->proxy_telnet_command[so] == '\\') {
1213 /* we recognize \\, \%, \r, \n, \t, \x??.
1214 * anything else, we just send unescaped (including the \).
1217 switch (cfg->proxy_telnet_command[eo]) {
1221 ret[retlen++] = '\\';
1227 ret[retlen++] = '%';
1233 ret[retlen++] = '\r';
1239 ret[retlen++] = '\n';
1245 ret[retlen++] = '\t';
1252 /* escaped hexadecimal value (ie. \xff) */
1253 unsigned char v = 0;
1258 if (cfg->proxy_telnet_command[eo] >= '0' &&
1259 cfg->proxy_telnet_command[eo] <= '9')
1260 v += cfg->proxy_telnet_command[eo] - '0';
1261 else if (cfg->proxy_telnet_command[eo] >= 'a' &&
1262 cfg->proxy_telnet_command[eo] <= 'f')
1263 v += cfg->proxy_telnet_command[eo] - 'a' + 10;
1264 else if (cfg->proxy_telnet_command[eo] >= 'A' &&
1265 cfg->proxy_telnet_command[eo] <= 'F')
1266 v += cfg->proxy_telnet_command[eo] - 'A' + 10;
1268 /* non hex character, so we abort and just
1269 * send the whole thing unescaped (including \x)
1272 ret[retlen++] = '\\';
1277 /* we only extract two hex characters */
1293 memcpy(ret+retlen, cfg->proxy_telnet_command + so, 2);
1300 /* % escape. we recognize %%, %host, %port, %user, %pass.
1301 * anything else, we just send unescaped (including the %).
1304 if (cfg->proxy_telnet_command[eo] == '%') {
1306 ret[retlen++] = '%';
1309 else if (strnicmp(cfg->proxy_telnet_command + eo,
1313 sk_getaddr(addr, dest, lenof(dest));
1314 destlen = strlen(dest);
1316 memcpy(ret+retlen, dest, destlen);
1320 else if (strnicmp(cfg->proxy_telnet_command + eo,
1322 char portstr[8], portlen;
1323 portlen = sprintf(portstr, "%i", port);
1325 memcpy(ret + retlen, portstr, portlen);
1329 else if (strnicmp(cfg->proxy_telnet_command + eo,
1331 int userlen = strlen(cfg->proxy_username);
1333 memcpy(ret+retlen, cfg->proxy_username, userlen);
1337 else if (strnicmp(cfg->proxy_telnet_command + eo,
1339 int passlen = strlen(cfg->proxy_password);
1341 memcpy(ret+retlen, cfg->proxy_password, passlen);
1346 /* we don't escape this, so send the % now, and
1347 * don't advance eo, so that we'll consider the
1348 * text immediately following the % as unescaped.
1351 ret[retlen++] = '%';
1355 /* resume scanning for additional escapes after this one. */
1359 /* if there is any unescaped text at the end of the line, send it */
1362 memcpy(ret + retlen, cfg->proxy_telnet_command + so, eo - so);
1373 int proxy_telnet_negotiate (Proxy_Socket p, int change)
1375 if (p->state == PROXY_CHANGE_NEW) {
1376 char *formatted_cmd;
1378 formatted_cmd = format_telnet_command(p->remote_addr, p->remote_port,
1381 sk_write(p->sub_socket, formatted_cmd, strlen(formatted_cmd));
1382 sfree(formatted_cmd);
1388 if (change == PROXY_CHANGE_CLOSING) {
1389 /* if our proxy negotiation process involves closing and opening
1390 * new sockets, then we would want to intercept this closing
1391 * callback when we were expecting it. if we aren't anticipating
1392 * a socket close, then some error must have occurred. we'll
1393 * just pass those errors up to the backend.
1395 return plug_closing(p->plug, p->closing_error_msg,
1396 p->closing_error_code,
1397 p->closing_calling_back);
1400 if (change == PROXY_CHANGE_SENT) {
1401 /* some (or all) of what we wrote to the proxy was sent.
1402 * we don't do anything new, however, until we receive the
1403 * proxy's response. we might want to set a timer so we can
1404 * timeout the proxy negotiation after a while...
1409 if (change == PROXY_CHANGE_ACCEPTING) {
1410 /* we should _never_ see this, as we are using our socket to
1411 * connect to a proxy, not accepting inbound connections.
1412 * what should we do? close the socket with an appropriate
1415 return plug_accepting(p->plug, p->accepting_sock);
1418 if (change == PROXY_CHANGE_RECEIVE) {
1419 /* we have received data from the underlying socket, which
1420 * we'll need to parse, process, and respond to appropriately.
1425 /* proxy activate will have dealt with
1426 * whatever is left of the buffer */
1430 plug_closing(p->plug, "Proxy error: Unexpected proxy error",
1431 PROXY_ERROR_UNEXPECTED, 0);