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