Fix include order with Xdmcp on WIN32
[free-sw/xcb/libxcb] / src / xcb_auth.c
1 /* Copyright (C) 2001-2004 Bart Massey and Jamey Sharp.
2  *
3  * Permission is hereby granted, free of charge, to any person obtaining a
4  * copy of this software and associated documentation files (the "Software"),
5  * to deal in the Software without restriction, including without limitation
6  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
7  * and/or sell copies of the Software, and to permit persons to whom the
8  * Software is furnished to do so, subject to the following conditions:
9  * 
10  * The above copyright notice and this permission notice shall be included in
11  * all copies or substantial portions of the Software.
12  * 
13  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16  * AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
17  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19  * 
20  * Except as contained in this notice, the names of the authors or their
21  * institutions shall not be used in advertising or otherwise to promote the
22  * sale, use or other dealings in this Software without prior written
23  * authorization from the authors.
24  */
25
26 /* Authorization systems for the X protocol. */
27
28 #include <assert.h>
29 #include <X11/Xauth.h>
30 #include <sys/param.h>
31 #include <unistd.h>
32 #include <stdlib.h>
33
34 #ifdef __INTERIX
35 /* _don't_ ask. interix has INADDR_LOOPBACK in here. */
36 #include <rpc/types.h>
37 #endif
38
39 #ifdef HASXDMAUTH
40 #include <X11/Xdmcp.h>
41 #endif
42
43 #ifdef _WIN32
44 #include "xcb_windefs.h"
45 #else
46 #include <arpa/inet.h>
47 #include <sys/socket.h>
48 #include <netinet/in.h>
49 #include <sys/un.h>
50 #endif /* _WIN32 */
51
52 #include "xcb.h"
53 #include "xcbint.h"
54
55
56 enum auth_protos {
57 #ifdef HASXDMAUTH
58     AUTH_XA1,
59 #endif
60     AUTH_MC1,
61     N_AUTH_PROTOS
62 };
63
64 #define AUTH_PROTO_XDM_AUTHORIZATION "XDM-AUTHORIZATION-1"
65 #define AUTH_PROTO_MIT_MAGIC_COOKIE "MIT-MAGIC-COOKIE-1"
66
67 static char *authnames[N_AUTH_PROTOS] = {
68 #ifdef HASXDMAUTH
69     AUTH_PROTO_XDM_AUTHORIZATION,
70 #endif
71     AUTH_PROTO_MIT_MAGIC_COOKIE,
72 };
73
74 static int authnameslen[N_AUTH_PROTOS] = {
75 #ifdef HASXDMAUTH
76     sizeof(AUTH_PROTO_XDM_AUTHORIZATION) - 1,
77 #endif
78     sizeof(AUTH_PROTO_MIT_MAGIC_COOKIE) - 1,
79 };
80
81 static size_t memdup(char **dst, void *src, size_t len)
82 {
83     if(len)
84         *dst = malloc(len);
85     else
86         *dst = 0;
87     if(!*dst)
88         return 0;
89     memcpy(*dst, src, len);
90     return len;
91 }
92
93 static int authname_match(enum auth_protos kind, char *name, size_t namelen)
94 {
95     if(authnameslen[kind] != namelen)
96         return 0;
97     if(memcmp(authnames[kind], name, namelen))
98         return 0;
99     return 1;
100 }
101
102 #define SIN6_ADDR(s) (&((struct sockaddr_in6 *)s)->sin6_addr)
103
104 static Xauth *get_authptr(struct sockaddr *sockname, int display)
105 {
106     char *addr = 0;
107     int addrlen = 0;
108     unsigned short family;
109     char hostnamebuf[256];   /* big enough for max hostname */
110     char dispbuf[40];   /* big enough to hold more than 2^64 base 10 */
111     int dispbuflen;
112
113     family = FamilyLocal; /* 256 */
114     switch(sockname->sa_family)
115     {
116 #ifdef AF_INET6
117     case AF_INET6:
118         addr = (char *) SIN6_ADDR(sockname);
119         addrlen = sizeof(*SIN6_ADDR(sockname));
120         if(!IN6_IS_ADDR_V4MAPPED(SIN6_ADDR(sockname)))
121         {
122             if(!IN6_IS_ADDR_LOOPBACK(SIN6_ADDR(sockname)))
123                 family = XCB_FAMILY_INTERNET_6;
124             break;
125         }
126         addr += 12;
127         /* if v4-mapped, fall through. */
128 #endif
129     case AF_INET:
130         if(!addr)
131             addr = (char *) &((struct sockaddr_in *)sockname)->sin_addr;
132         addrlen = sizeof(((struct sockaddr_in *)sockname)->sin_addr);
133         if(*(in_addr_t *) addr != htonl(INADDR_LOOPBACK))
134             family = XCB_FAMILY_INTERNET;
135         break;
136     case AF_UNIX:
137         break;
138     default:
139         return 0;   /* cannot authenticate this family */
140     }
141
142     dispbuflen = snprintf(dispbuf, sizeof(dispbuf), "%d", display);
143     if(dispbuflen < 0)
144         return 0;
145     /* snprintf may have truncate our text */
146     dispbuflen = MIN(dispbuflen, sizeof(dispbuf) - 1);
147
148     if (family == FamilyLocal) {
149         if (gethostname(hostnamebuf, sizeof(hostnamebuf)) == -1)
150             return 0;   /* do not know own hostname */
151         addr = hostnamebuf;
152         addrlen = strlen(addr);
153     }
154
155     return XauGetBestAuthByAddr (family,
156                                  (unsigned short) addrlen, addr,
157                                  (unsigned short) dispbuflen, dispbuf,
158                                  N_AUTH_PROTOS, authnames, authnameslen);
159 }
160
161 #ifdef HASXDMAUTH
162 static int next_nonce(void)
163 {
164     static int nonce = 0;
165     static pthread_mutex_t nonce_mutex = PTHREAD_MUTEX_INITIALIZER;
166     int ret;
167     pthread_mutex_lock(&nonce_mutex);
168     ret = nonce++;
169     pthread_mutex_unlock(&nonce_mutex);
170     return ret;
171 }
172
173 static void do_append(char *buf, int *idxp, void *val, size_t valsize) {
174     memcpy(buf + *idxp, val, valsize);
175     *idxp += valsize;
176 }
177 #endif
178      
179 static int compute_auth(xcb_auth_info_t *info, Xauth *authptr, struct sockaddr *sockname)
180 {
181     if (authname_match(AUTH_MC1, authptr->name, authptr->name_length)) {
182         info->datalen = memdup(&info->data, authptr->data, authptr->data_length);
183         if(!info->datalen)
184             return 0;
185         return 1;
186     }
187 #ifdef HASXDMAUTH
188 #define APPEND(buf,idx,val) do_append((buf),&(idx),&(val),sizeof(val))
189     if (authname_match(AUTH_XA1, authptr->name, authptr->name_length)) {
190         int j;
191
192         info->data = malloc(192 / 8);
193         if(!info->data)
194             return 0;
195
196         for (j = 0; j < 8; j++)
197             info->data[j] = authptr->data[j];
198         switch(sockname->sa_family) {
199         case AF_INET:
200             /*block*/ {
201             struct sockaddr_in *si = (struct sockaddr_in *) sockname;
202             APPEND(info->data, j, si->sin_addr.s_addr);
203             APPEND(info->data, j, si->sin_port);
204         }
205         break;
206 #ifdef AF_INET6
207         case AF_INET6:
208             /*block*/ {
209             struct sockaddr_in6 *si6 = (struct sockaddr_in6 *) sockname;
210             if(IN6_IS_ADDR_V4MAPPED(SIN6_ADDR(sockname)))
211             {
212                 do_append(info->data, &j, &si6->sin6_addr.s6_addr[12], 4);
213                 APPEND(info->data, j, si6->sin6_port);
214             }
215             else
216             {
217                 /* XDM-AUTHORIZATION-1 does not handle IPv6 correctly.  Do the
218                    same thing Xlib does: use all zeroes for the 4-byte address
219                    and 2-byte port number. */
220                 uint32_t fakeaddr = 0;
221                 uint16_t fakeport = 0;
222                 APPEND(info->data, j, fakeaddr);
223                 APPEND(info->data, j, fakeport);
224             }
225         }
226         break;
227 #endif
228         case AF_UNIX:
229             /*block*/ {
230             uint32_t fakeaddr = htonl(0xffffffff - next_nonce());
231             uint16_t fakeport = htons(getpid());
232             APPEND(info->data, j, fakeaddr);
233             APPEND(info->data, j, fakeport);
234         }
235         break;
236         default:
237             free(info->data);
238             return 0;   /* do not know how to build this */
239         }
240         {
241             uint32_t now = htonl(time(0));
242             APPEND(info->data, j, now);
243         }
244         assert(j <= 192 / 8);
245         while (j < 192 / 8)
246             info->data[j++] = 0;
247         info->datalen = j;
248         XdmcpWrap ((unsigned char *) info->data, (unsigned char *) authptr->data + 8, (unsigned char *) info->data, info->datalen);
249         return 1;
250     }
251 #undef APPEND
252 #endif
253
254     return 0;   /* Unknown authorization type */
255 }
256
257 /* `sockaddr_un.sun_path' typical size usually ranges between 92 and 108 */
258 #define INITIAL_SOCKNAME_SLACK 108
259
260 /* Return a dynamically allocated socket address structure according
261    to the value returned by either getpeername() or getsockname()
262    (according to POSIX, applications should not assume a particular
263    length for `sockaddr_un.sun_path') */
264 static struct sockaddr *get_peer_sock_name(int (*socket_func)(int,
265                                                               struct sockaddr *,
266                                                               socklen_t *),
267                                            int fd)
268 {
269     socklen_t socknamelen = sizeof(struct sockaddr) + INITIAL_SOCKNAME_SLACK;
270     socklen_t actual_socknamelen = socknamelen;
271     struct sockaddr *sockname = malloc(socknamelen);
272
273     if (sockname == NULL)
274         return NULL;
275
276     /* Both getpeername() and getsockname() truncates sockname if
277        there is not enough space and set the required length in
278        actual_socknamelen */
279     if (socket_func(fd, sockname, &actual_socknamelen) == -1)
280         goto sock_or_realloc_error;
281
282     if (actual_socknamelen > socknamelen)
283     {
284         struct sockaddr *new_sockname = NULL;
285         socknamelen = actual_socknamelen;
286
287         if ((new_sockname = realloc(sockname, actual_socknamelen)) == NULL)
288             goto sock_or_realloc_error;
289
290         sockname = new_sockname;
291
292         if (socket_func(fd, sockname, &actual_socknamelen) == -1 ||
293             actual_socknamelen > socknamelen)
294             goto sock_or_realloc_error;
295     }
296
297     return sockname;
298
299  sock_or_realloc_error:
300     free(sockname);
301     return NULL;
302 }
303
304 int _xcb_get_auth_info(int fd, xcb_auth_info_t *info, int display)
305 {
306     /* code adapted from Xlib/ConnDis.c, xtrans/Xtranssocket.c,
307        xtrans/Xtransutils.c */
308     struct sockaddr *sockname = NULL;
309     int gotsockname = 0;
310     Xauth *authptr = 0;
311     int ret = 1;
312
313     /* Some systems like hpux or Hurd do not expose peer names
314      * for UNIX Domain Sockets, but this is irrelevant,
315      * since compute_auth() ignores the peer name in this
316      * case anyway.*/
317     if ((sockname = get_peer_sock_name(getpeername, fd)) == NULL)
318     {
319         if ((sockname = get_peer_sock_name(getsockname, fd)) == NULL)
320             return 0;   /* can only authenticate sockets */
321         if (sockname->sa_family != AF_UNIX)
322         {
323             free(sockname);
324             return 0;   /* except for AF_UNIX, sockets should have peernames */
325         }
326         gotsockname = 1;
327     }
328
329     authptr = get_authptr(sockname, display);
330     if (authptr == 0)
331     {
332         free(sockname);
333         return 0;   /* cannot find good auth data */
334     }
335
336     info->namelen = memdup(&info->name, authptr->name, authptr->name_length);
337     if (!info->namelen)
338         goto no_auth;   /* out of memory */
339
340     if (!gotsockname)
341     {
342         free(sockname);
343
344         if ((sockname = get_peer_sock_name(getsockname, fd)) == NULL)
345         {
346             free(info->name);
347             goto no_auth;   /* can only authenticate sockets */
348         }
349     }
350
351     ret = compute_auth(info, authptr, sockname);
352     if(!ret)
353     {
354         free(info->name);
355         goto no_auth;   /* cannot build auth record */
356     }
357
358     free(sockname);
359     sockname = NULL;
360
361     XauDisposeAuth(authptr);
362     return ret;
363
364  no_auth:
365     free(sockname);
366
367     info->name = 0;
368     info->namelen = 0;
369     XauDisposeAuth(authptr);
370     return 0;
371 }