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