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