OSDN Git Service

Fix project files.
[ffftp/ffftp.git] / putty / X11FWD.C
1 /*\r
2  * Platform-independent bits of X11 forwarding.\r
3  */\r
4 \r
5 #include <stdio.h>\r
6 #include <stdlib.h>\r
7 #include <assert.h>\r
8 #include <time.h>\r
9 \r
10 #include "putty.h"\r
11 #include "ssh.h"\r
12 #include "tree234.h"\r
13 \r
14 #define GET_16BIT(endian, cp) \\r
15   (endian=='B' ? GET_16BIT_MSB_FIRST(cp) : GET_16BIT_LSB_FIRST(cp))\r
16 \r
17 #define PUT_16BIT(endian, cp, val) \\r
18   (endian=='B' ? PUT_16BIT_MSB_FIRST(cp, val) : PUT_16BIT_LSB_FIRST(cp, val))\r
19 \r
20 const char *const x11_authnames[] = {\r
21     "", "MIT-MAGIC-COOKIE-1", "XDM-AUTHORIZATION-1"\r
22 };\r
23 \r
24 struct XDMSeen {\r
25     unsigned int time;\r
26     unsigned char clientid[6];\r
27 };\r
28 \r
29 struct X11Private {\r
30     const struct plug_function_table *fn;\r
31     /* the above variable absolutely *must* be the first in this structure */\r
32     unsigned char firstpkt[12];        /* first X data packet */\r
33     struct X11Display *disp;\r
34     char *auth_protocol;\r
35     unsigned char *auth_data;\r
36     int data_read, auth_plen, auth_psize, auth_dlen, auth_dsize;\r
37     int verified;\r
38     int throttled, throttle_override;\r
39     unsigned long peer_ip;\r
40     int peer_port;\r
41     void *c;                           /* data used by ssh.c */\r
42     Socket s;\r
43 };\r
44 \r
45 static int xdmseen_cmp(void *a, void *b)\r
46 {\r
47     struct XDMSeen *sa = a, *sb = b;\r
48     return sa->time > sb->time ? 1 :\r
49            sa->time < sb->time ? -1 :\r
50            memcmp(sa->clientid, sb->clientid, sizeof(sa->clientid));\r
51 }\r
52 \r
53 /* Do-nothing "plug" implementation, used by x11_setup_display() when it\r
54  * creates a trial connection (and then immediately closes it).\r
55  * XXX: bit out of place here, could in principle live in a platform-\r
56  *      independent network.c or something */\r
57 static void dummy_plug_log(Plug p, int type, SockAddr addr, int port,\r
58                            const char *error_msg, int error_code) { }\r
59 static int dummy_plug_closing\r
60      (Plug p, const char *error_msg, int error_code, int calling_back)\r
61 { return 1; }\r
62 static int dummy_plug_receive(Plug p, int urgent, char *data, int len)\r
63 { return 1; }\r
64 static void dummy_plug_sent(Plug p, int bufsize) { }\r
65 static int dummy_plug_accepting(Plug p, OSSocket sock) { return 1; }\r
66 static const struct plug_function_table dummy_plug = {\r
67     dummy_plug_log, dummy_plug_closing, dummy_plug_receive,\r
68     dummy_plug_sent, dummy_plug_accepting\r
69 };\r
70 \r
71 struct X11Display *x11_setup_display(char *display, int authtype,\r
72                                      const Config *cfg)\r
73 {\r
74     struct X11Display *disp = snew(struct X11Display);\r
75     char *localcopy;\r
76     int i;\r
77 \r
78     if (!display || !*display) {\r
79         localcopy = platform_get_x_display();\r
80         if (!localcopy || !*localcopy) {\r
81             sfree(localcopy);\r
82             localcopy = dupstr(":0");  /* plausible default for any platform */\r
83         }\r
84     } else\r
85         localcopy = dupstr(display);\r
86 \r
87     /*\r
88      * Parse the display name.\r
89      *\r
90      * We expect this to have one of the following forms:\r
91      * \r
92      *  - the standard X format which looks like\r
93      *    [ [ protocol '/' ] host ] ':' displaynumber [ '.' screennumber ]\r
94      *    (X11 also permits a double colon to indicate DECnet, but\r
95      *    that's not our problem, thankfully!)\r
96      *\r
97      *  - only seen in the wild on MacOS (so far): a pathname to a\r
98      *    Unix-domain socket, which will typically and confusingly\r
99      *    end in ":0", and which I'm currently distinguishing from\r
100      *    the standard scheme by noting that it starts with '/'.\r
101      */\r
102     if (localcopy[0] == '/') {\r
103         disp->unixsocketpath = localcopy;\r
104         disp->unixdomain = TRUE;\r
105         disp->hostname = NULL;\r
106         disp->displaynum = -1;\r
107         disp->screennum = 0;\r
108         disp->addr = NULL;\r
109     } else {\r
110         char *colon, *dot, *slash;\r
111         char *protocol, *hostname;\r
112 \r
113         colon = strrchr(localcopy, ':');\r
114         if (!colon) {\r
115             sfree(disp);\r
116             sfree(localcopy);\r
117             return NULL;               /* FIXME: report a specific error? */\r
118         }\r
119 \r
120         *colon++ = '\0';\r
121         dot = strchr(colon, '.');\r
122         if (dot)\r
123             *dot++ = '\0';\r
124 \r
125         disp->displaynum = atoi(colon);\r
126         if (dot)\r
127             disp->screennum = atoi(dot);\r
128         else\r
129             disp->screennum = 0;\r
130 \r
131         protocol = NULL;\r
132         hostname = localcopy;\r
133         if (colon > localcopy) {\r
134             slash = strchr(localcopy, '/');\r
135             if (slash) {\r
136                 *slash++ = '\0';\r
137                 protocol = localcopy;\r
138                 hostname = slash;\r
139             }\r
140         }\r
141 \r
142         disp->hostname = *hostname ? dupstr(hostname) : NULL;\r
143 \r
144         if (protocol)\r
145             disp->unixdomain = (!strcmp(protocol, "local") ||\r
146                                 !strcmp(protocol, "unix"));\r
147         else if (!*hostname || !strcmp(hostname, "unix"))\r
148             disp->unixdomain = platform_uses_x11_unix_by_default;\r
149         else\r
150             disp->unixdomain = FALSE;\r
151 \r
152         if (!disp->hostname && !disp->unixdomain)\r
153             disp->hostname = dupstr("localhost");\r
154 \r
155         disp->unixsocketpath = NULL;\r
156         disp->addr = NULL;\r
157 \r
158         sfree(localcopy);\r
159     }\r
160 \r
161     /*\r
162      * Look up the display hostname, if we need to.\r
163      */\r
164     if (!disp->unixdomain) {\r
165         const char *err;\r
166 \r
167         disp->port = 6000 + disp->displaynum;\r
168         disp->addr = name_lookup(disp->hostname, disp->port,\r
169                                  &disp->realhost, cfg, ADDRTYPE_UNSPEC);\r
170     \r
171         if ((err = sk_addr_error(disp->addr)) != NULL) {\r
172             sk_addr_free(disp->addr);\r
173             sfree(disp->hostname);\r
174             sfree(disp->unixsocketpath);\r
175             return NULL;               /* FIXME: report an error */\r
176         }\r
177     }\r
178 \r
179     /*\r
180      * Try upgrading an IP-style localhost display to a Unix-socket\r
181      * display (as the standard X connection libraries do).\r
182      */\r
183     if (!disp->unixdomain && sk_address_is_local(disp->addr)) {\r
184         SockAddr ux = platform_get_x11_unix_address(NULL, disp->displaynum);\r
185         const char *err = sk_addr_error(ux);\r
186         if (!err) {\r
187             /* Create trial connection to see if there is a useful Unix-domain\r
188              * socket */\r
189             const struct plug_function_table *dummy = &dummy_plug;\r
190             Socket s = sk_new(sk_addr_dup(ux), 0, 0, 0, 0, 0, (Plug)&dummy);\r
191             err = sk_socket_error(s);\r
192             sk_close(s);\r
193         }\r
194         if (err) {\r
195             sk_addr_free(ux);\r
196         } else {\r
197             sk_addr_free(disp->addr);\r
198             disp->unixdomain = TRUE;\r
199             disp->addr = ux;\r
200             /* Fill in the rest in a moment */\r
201         }\r
202     }\r
203 \r
204     if (disp->unixdomain) {\r
205         if (!disp->addr)\r
206             disp->addr = platform_get_x11_unix_address(disp->unixsocketpath,\r
207                                                        disp->displaynum);\r
208         if (disp->unixsocketpath)\r
209             disp->realhost = dupstr(disp->unixsocketpath);\r
210         else\r
211             disp->realhost = dupprintf("unix:%d", disp->displaynum);\r
212         disp->port = 0;\r
213     }\r
214 \r
215     /*\r
216      * Invent the remote authorisation details.\r
217      */\r
218     if (authtype == X11_MIT) {\r
219         disp->remoteauthproto = X11_MIT;\r
220 \r
221         /* MIT-MAGIC-COOKIE-1. Cookie size is 128 bits (16 bytes). */\r
222         disp->remoteauthdata = snewn(16, unsigned char);\r
223         for (i = 0; i < 16; i++)\r
224             disp->remoteauthdata[i] = random_byte();\r
225         disp->remoteauthdatalen = 16;\r
226 \r
227         disp->xdmseen = NULL;\r
228     } else {\r
229         assert(authtype == X11_XDM);\r
230         disp->remoteauthproto = X11_XDM;\r
231 \r
232         /* XDM-AUTHORIZATION-1. Cookie size is 16 bytes; byte 8 is zero. */\r
233         disp->remoteauthdata = snewn(16, unsigned char);\r
234         for (i = 0; i < 16; i++)\r
235             disp->remoteauthdata[i] = (i == 8 ? 0 : random_byte());\r
236         disp->remoteauthdatalen = 16;\r
237 \r
238         disp->xdmseen = newtree234(xdmseen_cmp);\r
239     }\r
240     disp->remoteauthprotoname = dupstr(x11_authnames[disp->remoteauthproto]);\r
241     disp->remoteauthdatastring = snewn(disp->remoteauthdatalen * 2 + 1, char);\r
242     for (i = 0; i < disp->remoteauthdatalen; i++)\r
243         sprintf(disp->remoteauthdatastring + i*2, "%02x",\r
244                 disp->remoteauthdata[i]);\r
245 \r
246     /*\r
247      * Fetch the local authorisation details.\r
248      */\r
249     disp->localauthproto = X11_NO_AUTH;\r
250     disp->localauthdata = NULL;\r
251     disp->localauthdatalen = 0;\r
252     platform_get_x11_auth(disp, cfg);\r
253 \r
254     return disp;\r
255 }\r
256 \r
257 void x11_free_display(struct X11Display *disp)\r
258 {\r
259     if (disp->xdmseen != NULL) {\r
260         struct XDMSeen *seen;\r
261         while ((seen = delpos234(disp->xdmseen, 0)) != NULL)\r
262             sfree(seen);\r
263         freetree234(disp->xdmseen);\r
264     }\r
265     sfree(disp->hostname);\r
266     sfree(disp->unixsocketpath);\r
267     if (disp->localauthdata)\r
268         memset(disp->localauthdata, 0, disp->localauthdatalen);\r
269     sfree(disp->localauthdata);\r
270     if (disp->remoteauthdata)\r
271         memset(disp->remoteauthdata, 0, disp->remoteauthdatalen);\r
272     sfree(disp->remoteauthdata);\r
273     sfree(disp->remoteauthprotoname);\r
274     sfree(disp->remoteauthdatastring);\r
275     sk_addr_free(disp->addr);\r
276     sfree(disp);\r
277 }\r
278 \r
279 #define XDM_MAXSKEW 20*60      /* 20 minute clock skew should be OK */\r
280 \r
281 static char *x11_verify(unsigned long peer_ip, int peer_port,\r
282                         struct X11Display *disp, char *proto,\r
283                         unsigned char *data, int dlen)\r
284 {\r
285     if (strcmp(proto, x11_authnames[disp->remoteauthproto]) != 0)\r
286         return "wrong authorisation protocol attempted";\r
287     if (disp->remoteauthproto == X11_MIT) {\r
288         if (dlen != disp->remoteauthdatalen)\r
289             return "MIT-MAGIC-COOKIE-1 data was wrong length";\r
290         if (memcmp(disp->remoteauthdata, data, dlen) != 0)\r
291             return "MIT-MAGIC-COOKIE-1 data did not match";\r
292     }\r
293     if (disp->remoteauthproto == X11_XDM) {\r
294         unsigned long t;\r
295         time_t tim;\r
296         int i;\r
297         struct XDMSeen *seen, *ret;\r
298 \r
299         if (dlen != 24)\r
300             return "XDM-AUTHORIZATION-1 data was wrong length";\r
301         if (peer_port == -1)\r
302             return "cannot do XDM-AUTHORIZATION-1 without remote address data";\r
303         des_decrypt_xdmauth(disp->remoteauthdata+9, data, 24);\r
304         if (memcmp(disp->remoteauthdata, data, 8) != 0)\r
305             return "XDM-AUTHORIZATION-1 data failed check"; /* cookie wrong */\r
306         if (GET_32BIT_MSB_FIRST(data+8) != peer_ip)\r
307             return "XDM-AUTHORIZATION-1 data failed check";   /* IP wrong */\r
308         if ((int)GET_16BIT_MSB_FIRST(data+12) != peer_port)\r
309             return "XDM-AUTHORIZATION-1 data failed check";   /* port wrong */\r
310         t = GET_32BIT_MSB_FIRST(data+14);\r
311         for (i = 18; i < 24; i++)\r
312             if (data[i] != 0)          /* zero padding wrong */\r
313                 return "XDM-AUTHORIZATION-1 data failed check";\r
314         tim = time(NULL);\r
315         if (abs(t - tim) > XDM_MAXSKEW)\r
316             return "XDM-AUTHORIZATION-1 time stamp was too far out";\r
317         seen = snew(struct XDMSeen);\r
318         seen->time = t;\r
319         memcpy(seen->clientid, data+8, 6);\r
320         assert(disp->xdmseen != NULL);\r
321         ret = add234(disp->xdmseen, seen);\r
322         if (ret != seen) {\r
323             sfree(seen);\r
324             return "XDM-AUTHORIZATION-1 data replayed";\r
325         }\r
326         /* While we're here, purge entries too old to be replayed. */\r
327         for (;;) {\r
328             seen = index234(disp->xdmseen, 0);\r
329             assert(seen != NULL);\r
330             if (t - seen->time <= XDM_MAXSKEW)\r
331                 break;\r
332             sfree(delpos234(disp->xdmseen, 0));\r
333         }\r
334     }\r
335     /* implement other protocols here if ever required */\r
336     return NULL;\r
337 }\r
338 \r
339 void x11_get_auth_from_authfile(struct X11Display *disp,\r
340                                 const char *authfilename)\r
341 {\r
342     FILE *authfp;\r
343     char *buf, *ptr, *str[4];\r
344     int len[4];\r
345     int family, protocol;\r
346     int ideal_match = FALSE;\r
347     char *ourhostname = get_hostname();\r
348 \r
349     /*\r
350      * Normally we should look for precisely the details specified in\r
351      * `disp'. However, there's an oddity when the display is local:\r
352      * displays like "localhost:0" usually have their details stored\r
353      * in a Unix-domain-socket record (even if there isn't actually a\r
354      * real Unix-domain socket available, as with OpenSSH's proxy X11\r
355      * server).\r
356      *\r
357      * This is apparently a fudge to get round the meaninglessness of\r
358      * "localhost" in a shared-home-directory context -- xauth entries\r
359      * for Unix-domain sockets already disambiguate this by storing\r
360      * the *local* hostname in the conveniently-blank hostname field,\r
361      * but IP "localhost" records couldn't do this. So, typically, an\r
362      * IP "localhost" entry in the auth database isn't present and if\r
363      * it were it would be ignored.\r
364      *\r
365      * However, we don't entirely trust that (say) Windows X servers\r
366      * won't rely on a straight "localhost" entry, bad idea though\r
367      * that is; so if we can't find a Unix-domain-socket entry we'll\r
368      * fall back to an IP-based entry if we can find one.\r
369      */\r
370     int localhost = !disp->unixdomain && sk_address_is_local(disp->addr);\r
371 \r
372     authfp = fopen(authfilename, "rb");\r
373     if (!authfp)\r
374         return;\r
375 \r
376     /* Records in .Xauthority contain four strings of up to 64K each */\r
377     buf = snewn(65537 * 4, char);\r
378 \r
379     while (!ideal_match) {\r
380         int c, i, j, match = FALSE;\r
381         \r
382 #define GET do { c = fgetc(authfp); if (c == EOF) goto done; c = (unsigned char)c; } while (0)\r
383         /* Expect a big-endian 2-byte number giving address family */\r
384         GET; family = c;\r
385         GET; family = (family << 8) | c;\r
386         /* Then expect four strings, each composed of a big-endian 2-byte\r
387          * length field followed by that many bytes of data */\r
388         ptr = buf;\r
389         for (i = 0; i < 4; i++) {\r
390             GET; len[i] = c;\r
391             GET; len[i] = (len[i] << 8) | c;\r
392             str[i] = ptr;\r
393             for (j = 0; j < len[i]; j++) {\r
394                 GET; *ptr++ = c;\r
395             }\r
396             *ptr++ = '\0';\r
397         }\r
398 #undef GET\r
399 \r
400         /*\r
401          * Now we have a full X authority record in memory. See\r
402          * whether it matches the display we're trying to\r
403          * authenticate to.\r
404          *\r
405          * The details we've just read should be interpreted as\r
406          * follows:\r
407          * \r
408          *  - 'family' is the network address family used to\r
409          *    connect to the display. 0 means IPv4; 6 means IPv6;\r
410          *    256 means Unix-domain sockets.\r
411          * \r
412          *  - str[0] is the network address itself. For IPv4 and\r
413          *    IPv6, this is a string of binary data of the\r
414          *    appropriate length (respectively 4 and 16 bytes)\r
415          *    representing the address in big-endian format, e.g.\r
416          *    7F 00 00 01 means IPv4 localhost. For Unix-domain\r
417          *    sockets, this is the host name of the machine on\r
418          *    which the Unix-domain display resides (so that an\r
419          *    .Xauthority file on a shared file system can contain\r
420          *    authority entries for Unix-domain displays on\r
421          *    several machines without them clashing).\r
422          * \r
423          *  - str[1] is the display number. I've no idea why\r
424          *    .Xauthority stores this as a string when it has a\r
425          *    perfectly good integer format, but there we go.\r
426          * \r
427          *  - str[2] is the authorisation method, encoded as its\r
428          *    canonical string name (i.e. "MIT-MAGIC-COOKIE-1",\r
429          *    "XDM-AUTHORIZATION-1" or something we don't\r
430          *    recognise).\r
431          * \r
432          *  - str[3] is the actual authorisation data, stored in\r
433          *    binary form.\r
434          */\r
435 \r
436         if (disp->displaynum < 0 || disp->displaynum != atoi(str[1]))\r
437             continue;                  /* not the one */\r
438 \r
439         for (protocol = 1; protocol < lenof(x11_authnames); protocol++)\r
440             if (!strcmp(str[2], x11_authnames[protocol]))\r
441                 break;\r
442         if (protocol == lenof(x11_authnames))\r
443             continue;  /* don't recognise this protocol, look for another */\r
444 \r
445         switch (family) {\r
446           case 0:   /* IPv4 */\r
447             if (!disp->unixdomain &&\r
448                 sk_addrtype(disp->addr) == ADDRTYPE_IPV4) {\r
449                 char buf[4];\r
450                 sk_addrcopy(disp->addr, buf);\r
451                 if (len[0] == 4 && !memcmp(str[0], buf, 4)) {\r
452                     match = TRUE;\r
453                     /* If this is a "localhost" entry, note it down\r
454                      * but carry on looking for a Unix-domain entry. */\r
455                     ideal_match = !localhost;\r
456                 }\r
457             }\r
458             break;\r
459           case 6:   /* IPv6 */\r
460             if (!disp->unixdomain &&\r
461                 sk_addrtype(disp->addr) == ADDRTYPE_IPV6) {\r
462                 char buf[16];\r
463                 sk_addrcopy(disp->addr, buf);\r
464                 if (len[0] == 16 && !memcmp(str[0], buf, 16)) {\r
465                     match = TRUE;\r
466                     ideal_match = !localhost;\r
467                 }\r
468             }\r
469             break;\r
470           case 256: /* Unix-domain / localhost */\r
471             if ((disp->unixdomain || localhost)\r
472                 && ourhostname && !strcmp(ourhostname, str[0]))\r
473                 /* A matching Unix-domain socket is always the best\r
474                  * match. */\r
475                 match = ideal_match = TRUE;\r
476             break;\r
477         }\r
478 \r
479         if (match) {\r
480             /* Current best guess -- may be overridden if !ideal_match */\r
481             disp->localauthproto = protocol;\r
482             sfree(disp->localauthdata); /* free previous guess, if any */\r
483             disp->localauthdata = snewn(len[3], unsigned char);\r
484             memcpy(disp->localauthdata, str[3], len[3]);\r
485             disp->localauthdatalen = len[3];\r
486         }\r
487     }\r
488 \r
489     done:\r
490     fclose(authfp);\r
491     memset(buf, 0, 65537 * 4);\r
492     sfree(buf);\r
493     sfree(ourhostname);\r
494 }\r
495 \r
496 static void x11_log(Plug p, int type, SockAddr addr, int port,\r
497                     const char *error_msg, int error_code)\r
498 {\r
499     /* We have no interface to the logging module here, so we drop these. */\r
500 }\r
501 \r
502 static int x11_closing(Plug plug, const char *error_msg, int error_code,\r
503                        int calling_back)\r
504 {\r
505     struct X11Private *pr = (struct X11Private *) plug;\r
506 \r
507     /*\r
508      * We have no way to communicate down the forwarded connection,\r
509      * so if an error occurred on the socket, we just ignore it\r
510      * and treat it like a proper close.\r
511      */\r
512     sshfwd_close(pr->c);\r
513     x11_close(pr->s);\r
514     return 1;\r
515 }\r
516 \r
517 static int x11_receive(Plug plug, int urgent, char *data, int len)\r
518 {\r
519     struct X11Private *pr = (struct X11Private *) plug;\r
520 \r
521     if (sshfwd_write(pr->c, data, len) > 0) {\r
522         pr->throttled = 1;\r
523         sk_set_frozen(pr->s, 1);\r
524     }\r
525 \r
526     return 1;\r
527 }\r
528 \r
529 static void x11_sent(Plug plug, int bufsize)\r
530 {\r
531     struct X11Private *pr = (struct X11Private *) plug;\r
532 \r
533     sshfwd_unthrottle(pr->c, bufsize);\r
534 }\r
535 \r
536 /*\r
537  * When setting up X forwarding, we should send the screen number\r
538  * from the specified local display. This function extracts it from\r
539  * the display string.\r
540  */\r
541 int x11_get_screen_number(char *display)\r
542 {\r
543     int n;\r
544 \r
545     n = strcspn(display, ":");\r
546     if (!display[n])\r
547         return 0;\r
548     n = strcspn(display, ".");\r
549     if (!display[n])\r
550         return 0;\r
551     return atoi(display + n + 1);\r
552 }\r
553 \r
554 /*\r
555  * Called to set up the raw connection.\r
556  * \r
557  * Returns an error message, or NULL on success.\r
558  * also, fills the SocketsStructure\r
559  */\r
560 extern const char *x11_init(Socket *s, struct X11Display *disp, void *c,\r
561                             const char *peeraddr, int peerport,\r
562                             const Config *cfg)\r
563 {\r
564     static const struct plug_function_table fn_table = {\r
565         x11_log,\r
566         x11_closing,\r
567         x11_receive,\r
568         x11_sent,\r
569         NULL\r
570     };\r
571 \r
572     const char *err;\r
573     struct X11Private *pr;\r
574 \r
575     /*\r
576      * Open socket.\r
577      */\r
578     pr = snew(struct X11Private);\r
579     pr->fn = &fn_table;\r
580     pr->auth_protocol = NULL;\r
581     pr->disp = disp;\r
582     pr->verified = 0;\r
583     pr->data_read = 0;\r
584     pr->throttled = pr->throttle_override = 0;\r
585     pr->c = c;\r
586 \r
587     pr->s = *s = new_connection(sk_addr_dup(disp->addr),\r
588                                 disp->realhost, disp->port,\r
589                                 0, 1, 0, 0, (Plug) pr, cfg);\r
590     if ((err = sk_socket_error(*s)) != NULL) {\r
591         sfree(pr);\r
592         return err;\r
593     }\r
594 \r
595     /*\r
596      * See if we can make sense of the peer address we were given.\r
597      */\r
598     {\r
599         int i[4];\r
600         if (peeraddr &&\r
601             4 == sscanf(peeraddr, "%d.%d.%d.%d", i+0, i+1, i+2, i+3)) {\r
602             pr->peer_ip = (i[0] << 24) | (i[1] << 16) | (i[2] << 8) | i[3];\r
603             pr->peer_port = peerport;\r
604         } else {\r
605             pr->peer_ip = 0;\r
606             pr->peer_port = -1;\r
607         }\r
608     }\r
609 \r
610     sk_set_private_ptr(*s, pr);\r
611     return NULL;\r
612 }\r
613 \r
614 void x11_close(Socket s)\r
615 {\r
616     struct X11Private *pr;\r
617     if (!s)\r
618         return;\r
619     pr = (struct X11Private *) sk_get_private_ptr(s);\r
620     if (pr->auth_protocol) {\r
621         sfree(pr->auth_protocol);\r
622         sfree(pr->auth_data);\r
623     }\r
624 \r
625     sfree(pr);\r
626 \r
627     sk_close(s);\r
628 }\r
629 \r
630 void x11_unthrottle(Socket s)\r
631 {\r
632     struct X11Private *pr;\r
633     if (!s)\r
634         return;\r
635     pr = (struct X11Private *) sk_get_private_ptr(s);\r
636 \r
637     pr->throttled = 0;\r
638     sk_set_frozen(s, pr->throttled || pr->throttle_override);\r
639 }\r
640 \r
641 void x11_override_throttle(Socket s, int enable)\r
642 {\r
643     struct X11Private *pr;\r
644     if (!s)\r
645         return;\r
646     pr = (struct X11Private *) sk_get_private_ptr(s);\r
647 \r
648     pr->throttle_override = enable;\r
649     sk_set_frozen(s, pr->throttled || pr->throttle_override);\r
650 }\r
651 \r
652 /*\r
653  * Called to send data down the raw connection.\r
654  */\r
655 int x11_send(Socket s, char *data, int len)\r
656 {\r
657     struct X11Private *pr;\r
658     if (!s)\r
659         return 0;\r
660     pr = (struct X11Private *) sk_get_private_ptr(s);\r
661 \r
662     /*\r
663      * Read the first packet.\r
664      */\r
665     while (len > 0 && pr->data_read < 12)\r
666         pr->firstpkt[pr->data_read++] = (unsigned char) (len--, *data++);\r
667     if (pr->data_read < 12)\r
668         return 0;\r
669 \r
670     /*\r
671      * If we have not allocated the auth_protocol and auth_data\r
672      * strings, do so now.\r
673      */\r
674     if (!pr->auth_protocol) {\r
675         pr->auth_plen = GET_16BIT(pr->firstpkt[0], pr->firstpkt + 6);\r
676         pr->auth_dlen = GET_16BIT(pr->firstpkt[0], pr->firstpkt + 8);\r
677         pr->auth_psize = (pr->auth_plen + 3) & ~3;\r
678         pr->auth_dsize = (pr->auth_dlen + 3) & ~3;\r
679         /* Leave room for a terminating zero, to make our lives easier. */\r
680         pr->auth_protocol = snewn(pr->auth_psize + 1, char);\r
681         pr->auth_data = snewn(pr->auth_dsize, unsigned char);\r
682     }\r
683 \r
684     /*\r
685      * Read the auth_protocol and auth_data strings.\r
686      */\r
687     while (len > 0 && pr->data_read < 12 + pr->auth_psize)\r
688         pr->auth_protocol[pr->data_read++ - 12] = (len--, *data++);\r
689     while (len > 0 && pr->data_read < 12 + pr->auth_psize + pr->auth_dsize)\r
690         pr->auth_data[pr->data_read++ - 12 -\r
691                       pr->auth_psize] = (unsigned char) (len--, *data++);\r
692     if (pr->data_read < 12 + pr->auth_psize + pr->auth_dsize)\r
693         return 0;\r
694 \r
695     /*\r
696      * If we haven't verified the authorisation, do so now.\r
697      */\r
698     if (!pr->verified) {\r
699         char *err;\r
700 \r
701         pr->auth_protocol[pr->auth_plen] = '\0';        /* ASCIZ */\r
702         err = x11_verify(pr->peer_ip, pr->peer_port,\r
703                          pr->disp, pr->auth_protocol,\r
704                          pr->auth_data, pr->auth_dlen);\r
705 \r
706         /*\r
707          * If authorisation failed, construct and send an error\r
708          * packet, then terminate the connection.\r
709          */\r
710         if (err) {\r
711             char *message;\r
712             int msglen, msgsize;\r
713             unsigned char *reply;\r
714 \r
715             message = dupprintf("%s X11 proxy: %s", appname, err);\r
716             msglen = strlen(message);\r
717             reply = snewn(8 + msglen+1 + 4, unsigned char); /* include zero */\r
718             msgsize = (msglen + 3) & ~3;\r
719             reply[0] = 0;              /* failure */\r
720             reply[1] = msglen;         /* length of reason string */\r
721             memcpy(reply + 2, pr->firstpkt + 2, 4);     /* major/minor proto vsn */\r
722             PUT_16BIT(pr->firstpkt[0], reply + 6, msgsize >> 2);/* data len */\r
723             memset(reply + 8, 0, msgsize);\r
724             memcpy(reply + 8, message, msglen);\r
725             sshfwd_write(pr->c, (char *)reply, 8 + msgsize);\r
726             sshfwd_close(pr->c);\r
727             x11_close(s);\r
728             sfree(reply);\r
729             sfree(message);\r
730             return 0;\r
731         }\r
732 \r
733         /*\r
734          * Now we know we're going to accept the connection. Strip\r
735          * the fake auth data, and optionally put real auth data in\r
736          * instead.\r
737          */\r
738         {\r
739             char realauthdata[64];\r
740             int realauthlen = 0;\r
741             int authstrlen = strlen(x11_authnames[pr->disp->localauthproto]);\r
742             int buflen = 0;            /* initialise to placate optimiser */\r
743             static const char zeroes[4] = { 0,0,0,0 };\r
744             void *buf;\r
745 \r
746             if (pr->disp->localauthproto == X11_MIT) {\r
747                 assert(pr->disp->localauthdatalen <= lenof(realauthdata));\r
748                 realauthlen = pr->disp->localauthdatalen;\r
749                 memcpy(realauthdata, pr->disp->localauthdata, realauthlen);\r
750             } else if (pr->disp->localauthproto == X11_XDM &&\r
751                        pr->disp->localauthdatalen == 16 &&\r
752                        ((buf = sk_getxdmdata(s, &buflen))!=0)) {\r
753                 time_t t;\r
754                 realauthlen = (buflen+12+7) & ~7;\r
755                 assert(realauthlen <= lenof(realauthdata));\r
756                 memset(realauthdata, 0, realauthlen);\r
757                 memcpy(realauthdata, pr->disp->localauthdata, 8);\r
758                 memcpy(realauthdata+8, buf, buflen);\r
759                 t = time(NULL);\r
760                 PUT_32BIT_MSB_FIRST(realauthdata+8+buflen, t);\r
761                 des_encrypt_xdmauth(pr->disp->localauthdata+9,\r
762                                     (unsigned char *)realauthdata,\r
763                                     realauthlen);\r
764                 sfree(buf);\r
765             }\r
766             /* implement other auth methods here if required */\r
767 \r
768             PUT_16BIT(pr->firstpkt[0], pr->firstpkt + 6, authstrlen);\r
769             PUT_16BIT(pr->firstpkt[0], pr->firstpkt + 8, realauthlen);\r
770         \r
771             sk_write(s, (char *)pr->firstpkt, 12);\r
772 \r
773             if (authstrlen) {\r
774                 sk_write(s, x11_authnames[pr->disp->localauthproto],\r
775                          authstrlen);\r
776                 sk_write(s, zeroes, 3 & (-authstrlen));\r
777             }\r
778             if (realauthlen) {\r
779                 sk_write(s, realauthdata, realauthlen);\r
780                 sk_write(s, zeroes, 3 & (-realauthlen));\r
781             }\r
782         }\r
783         pr->verified = 1;\r
784     }\r
785 \r
786     /*\r
787      * After initialisation, just copy data simply.\r
788      */\r
789 \r
790     return sk_write(s, data, len);\r
791 }\r