process.c 50.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*

Copyright 1989, 1998  The Open Group

Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of The Open Group shall
not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization
from The Open Group.

*/

/*
 * Author:  Jim Fulton, MIT X Consortium
 */

33
34
35
36
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

37
38
39
#include "xauth.h"
#include <ctype.h>
#include <errno.h>
40
#include <stdint.h>
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
41
#include <sys/stat.h>
42
#ifndef WIN32
43
#include <sys/socket.h>
44
45
46
#else
#include <X11/Xwinsock.h>
#endif
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72

#include <signal.h>
#include <X11/X.h>			/* for Family constants */

#include <X11/Xlib.h>
#include <X11/extensions/security.h>

#ifndef DEFAULT_PROTOCOL_ABBREV		/* to make add command easier */
#define DEFAULT_PROTOCOL_ABBREV "."
#endif
#ifndef DEFAULT_PROTOCOL		/* for protocol abbreviation */
#define DEFAULT_PROTOCOL "MIT-MAGIC-COOKIE-1"
#endif

#define SECURERPC "SUN-DES-1"
#define K5AUTH "MIT-KERBEROS-5"

#define XAUTH_DEFAULT_RETRIES 10	/* number of competitors we expect */
#define XAUTH_DEFAULT_TIMEOUT 2		/* in seconds, be quick */
#define XAUTH_DEFAULT_DEADTIME 600L	/* 10 minutes in seconds */

typedef struct _AuthList {		/* linked list of entries */
    struct _AuthList *next;
    Xauth *auth;
} AuthList;

73
typedef int (*ProcessFunc)(const char *, int, int, const char**);
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
74

75
76
77
#define add_to_list(h,t,e) {if (t) (t)->next = (e); else (h) = (e); (t) = (e);}

typedef struct _CommandTable {		/* commands that are understood */
78
    const char *name;			/* full name */
79
80
    int minlen;				/* unique prefix */
    int maxlen;				/* strlen(name) */
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
81
    ProcessFunc processfunc;		/* handler */
82
    const char *helptext;		/* what to print for help */
83
84
85
86
} CommandTable;

struct _extract_data {			/* for iterating */
    FILE *fp;				/* input source */
87
    const char *filename;		/* name of input */
88
89
90
    Bool used_stdout;			/* whether or not need to close */
    Bool numeric;			/* format in which to write */
    int nwritten;			/* number of entries written */
91
    const char *cmd;			/* for error messages */
92
93
94
95
96
97
98
99
100
101
102
};

struct _list_data {			/* for iterating */
    FILE *fp;				/* output file */
    Bool numeric;			/* format in which to write */
};


/*
 * private data
 */
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
static const char *stdin_filename = "(stdin)";		/* for messages */
static const char *stdout_filename = "(stdout)";	/* for messages */
static const char *Yes = "yes";		/* for messages */
static const char *No = "no";		/* for messages */

static int do_help ( const char *inputfilename, int lineno, int argc, const char **argv );
static int do_questionmark ( const char *inputfilename, int lineno, int argc, const char **argv );
static int do_list ( const char *inputfilename, int lineno, int argc, const char **argv );
static int do_merge ( const char *inputfilename, int lineno, int argc, const char **argv );
static int do_extract ( const char *inputfilename, int lineno, int argc, const char **argv );
static int do_add ( const char *inputfilename, int lineno, int argc, const char **argv );
static int do_remove ( const char *inputfilename, int lineno, int argc, const char **argv );
static int do_info ( const char *inputfilename, int lineno, int argc, const char **argv );
static int do_exit ( const char *inputfilename, int lineno, int argc, const char **argv );
static int do_quit ( const char *inputfilename, int lineno, int argc, const char **argv );
static int do_source ( const char *inputfilename, int lineno, int argc, const char **argv );
static int do_generate ( const char *inputfilename, int lineno, int argc, const char **argv );
120
static int do_version ( const char *inputfilename, int lineno, int argc, const char **argv );
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148

static CommandTable command_table[] = {	/* table of known commands */
    { "add",      2, 3, do_add,
	"add dpyname protoname hexkey   add entry" },
    { "exit",     3, 4, do_exit,
	"exit                           save changes and exit program" },
    { "extract",  3, 7, do_extract,
	"extract filename dpyname...    extract entries into file" },
    { "help",     1, 4, do_help,
	"help [topic]                   print help" },
    { "info",     1, 4, do_info,
	"info                           print information about entries" },
    { "list",     1, 4, do_list,
	"list [dpyname...]              list entries" },
    { "merge",    1, 5, do_merge,
	"merge filename...              merge entries from files" },
    { "nextract", 2, 8, do_extract,
	"nextract filename dpyname...   numerically extract entries" },
    { "nlist",    2, 5, do_list,
	"nlist [dpyname...]             numerically list entries" },
    { "nmerge",   2, 6, do_merge,
	"nmerge filename...             numerically merge entries" },
    { "quit",     1, 4, do_quit,
	"quit                           abort changes and exit program" },
    { "remove",   1, 6, do_remove,
	"remove dpyname...              remove entries" },
    { "source",   1, 6, do_source,
	"source filename                read commands from file" },
149
150
    { "version",  1, 7, do_version,
	"version                        show version number of xauth" },
151
152
153
    { "?",        1, 1, do_questionmark,
	"?                              list available commands" },
    { "generate", 1, 8, do_generate,
Alan Coopersmith's avatar
Alan Coopersmith committed
154
	"generate dpyname protoname [options]  use server to generate entry\n"
155
156
157
158
159
160
        "    options are:\n"
        "      timeout n    authorization expiration time in seconds\n"
        "      trusted      clients using this entry are trusted\n"
        "      untrusted    clients using this entry are untrusted\n"
        "      group n      clients using this entry belong to application group n\n"
        "      data hexkey  auth protocol specific data needed to generate the entry\n"
Alan Coopersmith's avatar
Alan Coopersmith committed
161
    },
162
163
164
165
166
167
168
169
    { NULL,       0, 0, NULL, NULL },
};

#define COMMAND_NAMES_PADDED_WIDTH 10	/* wider than anything above */


static Bool okay_to_use_stdin = True;	/* set to false after using */

170
static const char *hex_table[] = {	/* for printing hex digits */
Alan Coopersmith's avatar
Alan Coopersmith committed
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
    "00", "01", "02", "03", "04", "05", "06", "07",
    "08", "09", "0a", "0b", "0c", "0d", "0e", "0f",
    "10", "11", "12", "13", "14", "15", "16", "17",
    "18", "19", "1a", "1b", "1c", "1d", "1e", "1f",
    "20", "21", "22", "23", "24", "25", "26", "27",
    "28", "29", "2a", "2b", "2c", "2d", "2e", "2f",
    "30", "31", "32", "33", "34", "35", "36", "37",
    "38", "39", "3a", "3b", "3c", "3d", "3e", "3f",
    "40", "41", "42", "43", "44", "45", "46", "47",
    "48", "49", "4a", "4b", "4c", "4d", "4e", "4f",
    "50", "51", "52", "53", "54", "55", "56", "57",
    "58", "59", "5a", "5b", "5c", "5d", "5e", "5f",
    "60", "61", "62", "63", "64", "65", "66", "67",
    "68", "69", "6a", "6b", "6c", "6d", "6e", "6f",
    "70", "71", "72", "73", "74", "75", "76", "77",
    "78", "79", "7a", "7b", "7c", "7d", "7e", "7f",
    "80", "81", "82", "83", "84", "85", "86", "87",
    "88", "89", "8a", "8b", "8c", "8d", "8e", "8f",
    "90", "91", "92", "93", "94", "95", "96", "97",
    "98", "99", "9a", "9b", "9c", "9d", "9e", "9f",
    "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7",
    "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af",
    "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7",
    "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf",
    "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7",
    "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf",
    "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7",
    "d8", "d9", "da", "db", "dc", "dd", "de", "df",
    "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7",
    "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef",
    "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7",
    "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff",
203
204
205
206
207
208
209
210
211
212
213
};

static unsigned int hexvalues[256];	/* for parsing hex input */

static int original_umask = 0;		/* for restoring */


/*
 * private utility procedures
 */

Alan Coopersmith's avatar
Alan Coopersmith committed
214
static void
215
prefix(const char *fn, int n)
216
217
218
219
{
    fprintf (stderr, "%s: %s:%d:  ", ProgramName, fn, n);
}

Alan Coopersmith's avatar
Alan Coopersmith committed
220
static void
221
baddisplayname(const char *dpy, const char *cmd)
222
223
224
225
226
{
    fprintf (stderr, "bad display name \"%s\" in \"%s\" command\n",
	     dpy, cmd);
}

Alan Coopersmith's avatar
Alan Coopersmith committed
227
static void
228
badcommandline(const char *cmd)
229
230
231
232
{
    fprintf (stderr, "bad \"%s\" command line\n", cmd);
}

Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
233
234
static char *
skip_space(register char *s)
235
236
237
238
239
240
241
242
243
{
    if (!s) return NULL;

    for ( ; *s && isascii(*s) && isspace(*s); s++)
	;
    return s;
}


Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
244
245
static char *
skip_nonspace(register char *s)
246
247
248
249
250
251
252
253
254
{
    if (!s) return NULL;

    /* put quoting into loop if need be */
    for ( ; *s && isascii(*s) && !isspace(*s); s++)
	;
    return s;
}

255
256
257
258
259
260
261
262
263
264
265
266
#ifndef HAVE_REALLOCARRAY
static inline void *
reallocarray(void *optr, size_t nmemb, size_t size)
{
    if ((nmemb > 0) && (SIZE_MAX / nmemb < size)) {
        errno = ENOMEM;
        return NULL;
    }
    return realloc(optr, size * nmemb);
}
#endif

267
static const char **
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
268
split_into_words(char *src, int *argcp)  /* argvify string */
269
270
271
{
    char *jword;
    char savec;
272
    const char **argv;
273
274
275
276
    int cur, total;

    *argcp = 0;
#define WORDSTOALLOC 4			/* most lines are short */
277
    argv = malloc (WORDSTOALLOC * sizeof (char *));
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
    if (!argv) return NULL;
    cur = 0;
    total = WORDSTOALLOC;

    /*
     * split the line up into separate, nul-terminated tokens; the last
     * "token" will point to the empty string so that it can be bashed into
     * a null pointer.
     */

    do {
	jword = skip_space (src);
	src = skip_nonspace (jword);
	savec = *src;
	*src = '\0';
	if (cur == total) {
294
	    const char **new_argv;
295
	    total += WORDSTOALLOC;
296
	    new_argv = reallocarray (argv, total, sizeof (char *));
297
298
299
300
301
302
	    if (new_argv != NULL) {
		argv = new_argv;
	    } else {
		free(argv);
		return NULL;
	    }
303
304
305
306
307
308
309
310
311
312
313
	}
	argv[cur++] = jword;
	if (savec) src++;		/* if not last on line advance */
    } while (jword != src);

    argv[--cur] = NULL;			/* smash empty token to end list */
    *argcp = cur;
    return argv;
}


Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
314
static FILE *
315
316
open_file(const char **filenamep,
	  const char *mode,
Alan Coopersmith's avatar
Alan Coopersmith committed
317
	  Bool *usedstdp,
318
	  const char *srcfn,
Alan Coopersmith's avatar
Alan Coopersmith committed
319
	  int srcln,
320
	  const char *cmd)
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
{
    FILE *fp;

    if (strcmp (*filenamep, "-") == 0) {
	*usedstdp = True;
					/* select std descriptor to use */
	if (mode[0] == 'r') {
	    if (okay_to_use_stdin) {
		okay_to_use_stdin = False;
		*filenamep = stdin_filename;
		return stdin;
	    } else {
		prefix (srcfn, srcln);
		fprintf (stderr, "%s:  stdin already in use\n", cmd);
		return NULL;
	    }
	} else {
	    *filenamep = stdout_filename;
	    return stdout;		/* always okay to use stdout */
	}
    }

    fp = fopen (*filenamep, mode);
    if (!fp) {
	prefix (srcfn, srcln);
	fprintf (stderr, "%s:  unable to open file %s\n", cmd, *filenamep);
    }
    return fp;
}

Alan Coopersmith's avatar
Alan Coopersmith committed
351
static int
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
352
getinput(FILE *fp)
353
354
355
356
357
358
359
{
    register int c;

    while ((c = getc (fp)) != EOF && isascii(c) && c != '\n' && isspace(c)) ;
    return c;
}

Alan Coopersmith's avatar
Alan Coopersmith committed
360
static int
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
361
get_short(FILE *fp, unsigned short *sp)	/* for reading numeric input */
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
{
    int c;
    int i;
    unsigned short us = 0;

    /*
     * read family:  written with %04x
     */
    for (i = 0; i < 4; i++) {
	switch (c = getinput (fp)) {
	  case EOF:
	  case '\n':
	    return 0;
	}
	if (c < 0 || c > 255) return 0;
	us = (us * 16) + hexvalues[c];	/* since msb */
    }
    *sp = us;
    return 1;
}

Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
383
384
static int
get_bytes(FILE *fp, unsigned int n, char **ptr)	/* for reading numeric input */
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
{
    char *s;
    register char *cp;
    int c1, c2;

    cp = s = malloc (n);
    if (!cp) return 0;

    while (n > 0) {
	if ((c1 = getinput (fp)) == EOF || c1 == '\n' ||
	    (c2 = getinput (fp)) == EOF || c2 == '\n') {
	    free (s);
	    return 0;
	}
	*cp = (char) ((hexvalues[c1] * 16) + hexvalues[c2]);
	cp++;
	n--;
    }

    *ptr = s;
    return 1;
}


Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
409
410
static Xauth *
read_numeric(FILE *fp)
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
{
    Xauth *auth;

    auth = (Xauth *) malloc (sizeof (Xauth));
    if (!auth) goto bad;
    auth->family = 0;
    auth->address = NULL;
    auth->address_length = 0;
    auth->number = NULL;
    auth->number_length = 0;
    auth->name = NULL;
    auth->name_length = 0;
    auth->data = NULL;
    auth->data_length = 0;

    if (!get_short (fp, (unsigned short *) &auth->family))
      goto bad;
    if (!get_short (fp, (unsigned short *) &auth->address_length))
      goto bad;
    if (!get_bytes (fp, (unsigned int) auth->address_length, &auth->address))
      goto bad;
    if (!get_short (fp, (unsigned short *) &auth->number_length))
      goto bad;
    if (!get_bytes (fp, (unsigned int) auth->number_length, &auth->number))
      goto bad;
    if (!get_short (fp, (unsigned short *) &auth->name_length))
      goto bad;
    if (!get_bytes (fp, (unsigned int) auth->name_length, &auth->name))
      goto bad;
    if (!get_short (fp, (unsigned short *) &auth->data_length))
      goto bad;
    if (!get_bytes (fp, (unsigned int) auth->data_length, &auth->data))
      goto bad;
Alan Coopersmith's avatar
Alan Coopersmith committed
444

445
446
447
448
449
450
451
452
453
454
455
    switch (getinput (fp)) {		/* get end of line */
      case EOF:
      case '\n':
	return auth;
    }

  bad:
    if (auth) XauDisposeAuth (auth);	/* won't free null pointers */
    return NULL;
}

Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
456
457
typedef Xauth *(*ReadFunc)(FILE *);

Alan Coopersmith's avatar
Alan Coopersmith committed
458
static int
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
459
read_auth_entries(FILE *fp, Bool numeric, AuthList **headp, AuthList **tailp)
460
{
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
461
    ReadFunc readfunc = (numeric ? read_numeric : XauReadAuth);
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
    Xauth *auth;
    AuthList *head, *tail;
    int n;

    head = tail = NULL;
    n = 0;
					/* put all records into linked list */
    while ((auth = ((*readfunc) (fp))) != NULL) {
	AuthList *l = (AuthList *) malloc (sizeof (AuthList));
	if (!l) {
	    fprintf (stderr,
		     "%s:  unable to alloc entry reading auth file\n",
		     ProgramName);
	    exit (1);
	}
	l->next = NULL;
	l->auth = auth;
	if (tail) 			/* if not first time through append */
	  tail->next = l;
	else
	  head = l;			/* first time through, so assign */
	tail = l;
	n++;
    }
    *headp = head;
    *tailp = tail;
    return n;
}

Alan Coopersmith's avatar
Alan Coopersmith committed
491
static Bool
492
get_displayname_auth(const char *displayname, AuthList **authl)
493
494
495
496
497
498
{
    int family;
    char *host = NULL, *rest = NULL;
    int dpynum, scrnum;
    char *cp;
    int prelen = 0;
499
500
    struct addrlist *addrlist_head, *addrlist_cur;
    AuthList *authl_cur = NULL;
501

502
    *authl = NULL;
503
504
505
506
507
508
509
    /*
     * check to see if the display name is of the form "host/unix:"
     * which is how the list routine prints out local connections
     */
    cp = strchr(displayname, '/');
    if (cp && strncmp (cp, "/unix:", 6) == 0)
      prelen = (cp - displayname);
Alan Coopersmith's avatar
Alan Coopersmith committed
510

511
512
513
514
515
    if (!parse_displayname (displayname + ((prelen > 0) ? prelen + 1 : 0),
			    &family, &host, &dpynum, &scrnum, &rest)) {
	return False;
    }

516
517
    addrlist_head = get_address_info(family, displayname, prelen, host);
    if (addrlist_head) {
518
	char buf[40];			/* want to hold largest display num */
519
	unsigned short dpylen;
520
521
522

	buf[0] = '\0';
	sprintf (buf, "%d", dpynum);
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
	dpylen = strlen (buf);
	if (dpylen > 0) {
	    for (addrlist_cur = addrlist_head; addrlist_cur != NULL;
		 addrlist_cur = addrlist_cur->next) {
		AuthList *newal = malloc(sizeof(AuthList));
		Xauth *auth = malloc(sizeof(Xauth));

		if ((newal == NULL) || (auth == NULL)) {
		    if (newal != NULL) free(newal);
		    if (auth != NULL) free(auth);
		    break;
		}

		if (authl_cur == NULL) {
		    *authl = authl_cur = newal;
		} else {
		    authl_cur->next = newal;
		    authl_cur = newal;
		}

		newal->next = NULL;
		newal->auth = auth;

		auth->family = addrlist_cur->family;
		auth->address = addrlist_cur->address;
		auth->address_length = addrlist_cur->len;
		auth->number = copystring(buf, dpylen);
		auth->number_length = dpylen;
		auth->name = NULL;
		auth->name_length = 0;
		auth->data = NULL;
		auth->data_length = 0;
	    }
556
557
558
559
560
561
	}
    }

    if (host) free (host);
    if (rest) free (rest);

562
    if (*authl != NULL) {
563
564
565
566
567
568
	return True;
    } else {
	return False;
    }
}

Alan Coopersmith's avatar
Alan Coopersmith committed
569
static int
570
cvthexkey(const char *hexstr, char **ptrp) /* turn hex key string into octets */
571
572
573
{
    int i;
    int len = 0;
574
575
    char *retval;
    const char *s;
576
577
578
579
580
581
582
583
584
585
586
587
    unsigned char *us;
    char c;
    char savec = '\0';

    /* count */
    for (s = hexstr; *s; s++) {
	if (!isascii(*s)) return -1;
	if (isspace(*s)) continue;
	if (!isxdigit(*s)) return -1;
	len++;
    }

588
589
    /* if 0 or odd, then there was an error */
    if (len == 0 || (len & 1) == 1) return -1;
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620


    /* now we know that the input is good */
    len >>= 1;
    retval = malloc (len);
    if (!retval) {
	fprintf (stderr, "%s:  unable to allocate %d bytes for hexkey\n",
		 ProgramName, len);
	return -1;
    }

    for (us = (unsigned char *) retval, i = len; i > 0; hexstr++) {
	c = *hexstr;
	if (isspace(c)) continue;	 /* already know it is ascii */
	if (isupper(c))
	    c = tolower(c);
	if (savec) {
#define atoh(c) ((c) - (((c) >= '0' && (c) <= '9') ? '0' : ('a'-10)))
	    *us = (unsigned char)((atoh(savec) << 4) + atoh(c));
#undef atoh
	    savec = 0;		/* ready for next character */
	    us++;
	    i--;
	} else {
	    savec = c;
	}
    }
    *ptrp = retval;
    return len;
}

Alan Coopersmith's avatar
Alan Coopersmith committed
621
static int
622
dispatch_command(const char *inputfilename,
Alan Coopersmith's avatar
Alan Coopersmith committed
623
624
		 int lineno,
		 int argc,
625
		 const char **argv,
Alan Coopersmith's avatar
Alan Coopersmith committed
626
		 CommandTable *tab,
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
627
		 int *statusp)
628
629
{
    CommandTable *ct;
630
    const char *cmd;
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
    int n;
					/* scan table for command */
    cmd = argv[0];
    n = strlen (cmd);
    for (ct = tab; ct->name; ct++) {
					/* look for unique prefix */
	if (n >= ct->minlen && n <= ct->maxlen &&
	    strncmp (cmd, ct->name, n) == 0) {
	    *statusp = (*(ct->processfunc))(inputfilename, lineno, argc, argv);
	    return 1;
	}
    }

    *statusp = 1;
    return 0;
}


static AuthList *xauth_head = NULL;	/* list of auth entries */
static Bool xauth_existed = False;	/* if was present at initialize */
static Bool xauth_modified = False;	/* if added, removed, or merged */
static Bool xauth_allowed = True;	/* if allowed to write auth file */
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
653
static Bool xauth_locked = False;     /* if has been locked */
654
static const char *xauth_filename = NULL;
655
static volatile Bool dieing = False;
656
657


658
659
660
/* poor man's puts(), for under signal handlers, 
   extended to ignore warn_unused_result */
#define WRITES(fd, S) {if(write((fd), (S), strlen((S))));}
661
662

/* ARGSUSED */
663
_X_NORETURN
664
static void
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
665
die(int sig)
666
667
{
    dieing = True;
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
668
    _exit (auth_finalize ());
669
670
671
    /* NOTREACHED */
}

672
_X_NORETURN
673
static void
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
674
catchsig(int sig)
675
676
677
678
{
#ifdef SYSV
    if (sig > 0) signal (sig, die);	/* re-establish signal handler */
#endif
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
679
680
681
682
683
684
685
686
687
    /*
     * fileno() might not be reentrant, avoid it if possible, and use
     * stderr instead of stdout
     */
#ifdef STDERR_FILENO
    if (verbose && xauth_modified) WRITES(STDERR_FILENO, "\r\n");
#else
    if (verbose && xauth_modified) WRITES(fileno(stderr), "\r\n");
#endif
688
689
690
691
    die (sig);
    /* NOTREACHED */
}

Alan Coopersmith's avatar
Alan Coopersmith committed
692
static void
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
693
register_signals(void)
694
695
696
697
698
{
    signal (SIGINT, catchsig);
    signal (SIGTERM, catchsig);
#ifdef SIGHUP
    signal (SIGHUP, catchsig);
699
700
701
#endif
#ifdef SIGPIPE
    signal (SIGPIPE, catchsig);
702
703
704
705
706
707
708
709
710
#endif
    return;
}


/*
 * public procedures for parsing lines of input
 */

Alan Coopersmith's avatar
Alan Coopersmith committed
711
int
712
auth_initialize(const char *authfilename)
713
714
715
716
717
718
{
    int n;
    AuthList *head, *tail;
    FILE *authfp;
    Bool exists;

719
720
721
722
    if (strlen(authfilename) > 1022) {
	fprintf (stderr, "%s: authority file name \"%s\" too long\n",
		 ProgramName, authfilename);
    }
Alan Coopersmith's avatar
Alan Coopersmith committed
723
    xauth_filename = authfilename;    /* used in cleanup, prevent race with
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
                                         signals */
    register_signals ();

    bzero ((char *) hexvalues, sizeof hexvalues);
    hexvalues['0'] = 0;
    hexvalues['1'] = 1;
    hexvalues['2'] = 2;
    hexvalues['3'] = 3;
    hexvalues['4'] = 4;
    hexvalues['5'] = 5;
    hexvalues['6'] = 6;
    hexvalues['7'] = 7;
    hexvalues['8'] = 8;
    hexvalues['9'] = 9;
    hexvalues['a'] = hexvalues['A'] = 0xa;
    hexvalues['b'] = hexvalues['B'] = 0xb;
    hexvalues['c'] = hexvalues['C'] = 0xc;
    hexvalues['d'] = hexvalues['D'] = 0xd;
    hexvalues['e'] = hexvalues['E'] = 0xe;
    hexvalues['f'] = hexvalues['F'] = 0xf;

    if (break_locks && verbose) {
	printf ("Attempting to break locks on authority file %s\n",
		authfilename);
    }

    if (ignore_locks) {
	if (break_locks) XauUnlockAuth (authfilename);
    } else {
	n = XauLockAuth (authfilename, XAUTH_DEFAULT_RETRIES,
Alan Coopersmith's avatar
Alan Coopersmith committed
754
			 XAUTH_DEFAULT_TIMEOUT,
755
756
			 (break_locks ? 0L : XAUTH_DEFAULT_DEADTIME));
	if (n != LOCK_SUCCESS) {
757
	    const char *reason = "unknown error";
758
759
760
761
762
763
764
765
766
767
768
	    switch (n) {
	      case LOCK_ERROR:
		reason = "error";
		break;
	      case LOCK_TIMEOUT:
		reason = "timeout";
		break;
	    }
	    fprintf (stderr, "%s:  %s in locking authority file %s\n",
		     ProgramName, reason, authfilename);
	    return -1;
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
769
770
	} else
	    xauth_locked = True;
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
    }

    /* these checks can only be done reliably after the file is locked */
    exists = (access (authfilename, F_OK) == 0);
    if (exists && access (authfilename, W_OK) != 0) {
	fprintf (stderr,
	 "%s:  %s not writable, changes will be ignored\n",
		 ProgramName, authfilename);
	xauth_allowed = False;
    }

    original_umask = umask (0077);	/* disallow non-owner access */

    authfp = fopen (authfilename, "rb");
    if (!authfp) {
	int olderrno = errno;

					/* if file there then error */
	if (access (authfilename, F_OK) == 0) {	 /* then file does exist! */
	    errno = olderrno;
	    return -1;
	}				/* else ignore it */
Alan Coopersmith's avatar
Alan Coopersmith committed
793
	fprintf (stderr,
794
		 "%s:  file %s does not exist\n",
795
796
797
798
799
800
801
802
803
804
805
806
807
808
		 ProgramName, authfilename);
    } else {
	xauth_existed = True;
	n = read_auth_entries (authfp, False, &head, &tail);
	(void) fclose (authfp);
	if (n < 0) {
	    fprintf (stderr,
		     "%s:  unable to read auth entries from file \"%s\"\n",
		     ProgramName, authfilename);
	    return -1;
	}
	xauth_head = head;
    }

809
810
    xauth_filename = strdup(authfilename);
    if (!xauth_filename) {
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
811
812
813
	fprintf(stderr,"cannot allocate memory\n");
	return -1;
    }
Alan Coopersmith's avatar
Alan Coopersmith committed
814

815
816
817
    xauth_modified = False;

    if (verbose) {
Alan Coopersmith's avatar
Alan Coopersmith committed
818
	printf ("%s authority file %s\n",
819
820
821
822
823
		ignore_locks ? "Ignoring locks on" : "Using", authfilename);
    }
    return 0;
}

Alan Coopersmith's avatar
Alan Coopersmith committed
824
static int
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
825
write_auth_file(char *tmp_nam)
826
{
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
827
828
    FILE *fp = NULL;
    int fd;
829
830
831
832
833
834
835
836
    AuthList *list;

    /*
     * xdm and auth spec assumes auth file is 12 or fewer characters
     */
    strcpy (tmp_nam, xauth_filename);
    strcat (tmp_nam, "-n");		/* for new */
    (void) unlink (tmp_nam);
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
837
838
839
    /* CPhipps 2000/02/12 - fix file unlink/fopen race */
    fd = open(tmp_nam, O_WRONLY | O_CREAT | O_EXCL, 0600);
    if (fd != -1) fp = fdopen (fd, "wb");
840
    if (!fp) {
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
841
        if (fd != -1) close(fd);
842
843
844
	fprintf (stderr, "%s:  unable to open tmp file \"%s\"\n",
		 ProgramName, tmp_nam);
	return -1;
Alan Coopersmith's avatar
Alan Coopersmith committed
845
    }
846
847
848
849
850
851
852

    /*
     * Write MIT-MAGIC-COOKIE-1 first, because R4 Xlib knows
     * only that and uses the first authorization it finds.
     */
    for (list = xauth_head; list; list = list->next) {
	if (list->auth->name_length == 18
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
853
854
855
856
857
	    && strncmp(list->auth->name, "MIT-MAGIC-COOKIE-1", 18) == 0) {
	    if (!XauWriteAuth(fp, list->auth)) {
		(void) fclose(fp);
		return -1;
	    }
858
859
860
861
	}
    }
    for (list = xauth_head; list; list = list->next) {
	if (list->auth->name_length != 18
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
862
863
864
865
866
	    || strncmp(list->auth->name, "MIT-MAGIC-COOKIE-1", 18) != 0) {
	    if (!XauWriteAuth(fp, list->auth)) {
		(void) fclose(fp);
		return -1;
	    }
867
868
869
	}
    }

870
871
872
873
    if (fclose(fp)) {
	return -1;
    }

874
875
876
    return 0;
}

Alan Coopersmith's avatar
Alan Coopersmith committed
877
int
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
878
auth_finalize(void)
879
{
880
    char temp_name[1025];	/* large filename size */
881
882
883
884

    if (xauth_modified) {
	if (dieing) {
	    if (verbose) {
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
885
886
887
888
889
890
891
892
893
894
895
896
897
898
		/*
		 * called from a signal handler -- printf is *not* reentrant; also
		 * fileno() might not be reentrant, avoid it if possible, and use
		 * stderr instead of stdout
		 */
#ifdef STDERR_FILENO
		WRITES(STDERR_FILENO, "\nAborting changes to authority file ");
		WRITES(STDERR_FILENO, xauth_filename);
		WRITES(STDERR_FILENO, "\n");
#else
		WRITES(fileno(stderr), "\nAborting changes to authority file ");
		WRITES(fileno(stderr), xauth_filename);
		WRITES(fileno(stderr), "\n");
#endif
899
900
	    }
	} else if (!xauth_allowed) {
Alan Coopersmith's avatar
Alan Coopersmith committed
901
	    fprintf (stderr,
902
903
904
905
		     "%s:  %s not writable, changes ignored\n",
		     ProgramName, xauth_filename);
	} else {
	    if (verbose) {
Alan Coopersmith's avatar
Alan Coopersmith committed
906
		printf ("%s authority file %s\n",
907
908
909
910
911
912
913
914
915
			ignore_locks ? "Ignoring locks and writing" :
			"Writing", xauth_filename);
	    }
	    temp_name[0] = '\0';
	    if (write_auth_file (temp_name) == -1) {
		fprintf (stderr,
			 "%s:  unable to write authority file %s\n",
			 ProgramName, temp_name);
	    } else {
916
		if (rename(temp_name, xauth_filename) == -1) {
917
		    fprintf (stderr,
918
		     "%s:  unable to rename authority file %s, use %s\n",
919
			     ProgramName, xauth_filename, temp_name);
920
                    unlink(temp_name);
921
922
923
924
925
		}
	    }
	}
    }

Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
926
    if (xauth_locked) {
927
928
929
930
931
932
	XauUnlockAuth (xauth_filename);
    }
    (void) umask (original_umask);
    return 0;
}

Alan Coopersmith's avatar
Alan Coopersmith committed
933
int
934
process_command(const char *inputfilename, int lineno, int argc, const char **argv)
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
{
    int status;

    if (argc < 1 || !argv || !argv[0]) return 1;

    if (dispatch_command (inputfilename, lineno, argc, argv,
			  command_table, &status))
      return status;

    prefix (inputfilename, lineno);
    fprintf (stderr, "unknown command \"%s\"\n", argv[0]);
    return 1;
}


/*
 * utility routines
 */

Alan Coopersmith's avatar
Alan Coopersmith committed
954
static char *
955
bintohex(unsigned int len, const char *bindata)
956
957
958
959
{
    char *hexdata, *starthex;

    /* two chars per byte, plus null termination */
Alan Coopersmith's avatar
Alan Coopersmith committed
960
    starthex = hexdata = (char *)malloc(2*len + 1);
961
962
963
964
    if (!hexdata)
	return NULL;

    for (; len > 0; len--, bindata++) {
965
	register const char *s = hex_table[(unsigned char)*bindata];
966
967
968
969
970
971
972
	*hexdata++ = s[0];
	*hexdata++ = s[1];
    }
    *hexdata = '\0';
    return starthex;
}

Alan Coopersmith's avatar
Alan Coopersmith committed
973
static void
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
974
fprintfhex(register FILE *fp, int len, char *cp)
975
976
977
978
{
    char *hex;

    hex = bintohex(len, cp);
Michael Scherer's avatar
Michael Scherer committed
979
    fprintf(fp, "%s", hex);
980
981
982
    free(hex);
}

983
static int
Kaleb Keithley Keithley's avatar
Kaleb Keithley Keithley committed
984
dump_numeric(register FILE *fp, register Xauth *auth)
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
{
    fprintf (fp, "%04x", auth->family);  /* unsigned short */
    fprintf (fp, " %04x ", auth->address_length);  /* short */
    fprintfhex (fp, auth->address_length, auth->address);
    fprintf (fp, " %04x ", auth->number_length);  /* short */
    fprintfhex (fp, auth->number_length, auth->number);
    fprintf (fp, " %04x ", auth->name_length);  /* short */
    fprintfhex (fp, auth->name_length, auth->name);
    fprintf (fp, " %04x ", auth->data_length);  /* short */
    fprintfhex (fp, auth->data_length, auth->data);
    putc ('\n', fp);
    return 1;
}

/* ARGSUSED */
Alan Coopersmith's avatar
Alan Coopersmith committed
1000
static int
For faster browsing, not all history is shown. View entire blame