]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/uxpgnt.c
Unix Pageant: support -d, to delete a key from the agent.
[PuTTY.git] / unix / uxpgnt.c
1 /*
2  * Unix Pageant, more or less similar to ssh-agent.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <errno.h>
8 #include <assert.h>
9 #include <signal.h>
10 #include <ctype.h>
11
12 #include <sys/types.h>
13 #include <sys/wait.h>
14 #include <fcntl.h>
15 #include <unistd.h>
16
17 #define PUTTY_DO_GLOBALS               /* actually _define_ globals */
18 #include "putty.h"
19 #include "ssh.h"
20 #include "misc.h"
21 #include "pageant.h"
22
23 SockAddr unix_sock_addr(const char *path);
24 Socket new_unix_listener(SockAddr listenaddr, Plug plug);
25
26 void fatalbox(char *p, ...)
27 {
28     va_list ap;
29     fprintf(stderr, "FATAL ERROR: ");
30     va_start(ap, p);
31     vfprintf(stderr, p, ap);
32     va_end(ap);
33     fputc('\n', stderr);
34     exit(1);
35 }
36 void modalfatalbox(char *p, ...)
37 {
38     va_list ap;
39     fprintf(stderr, "FATAL ERROR: ");
40     va_start(ap, p);
41     vfprintf(stderr, p, ap);
42     va_end(ap);
43     fputc('\n', stderr);
44     exit(1);
45 }
46 void nonfatal(char *p, ...)
47 {
48     va_list ap;
49     fprintf(stderr, "ERROR: ");
50     va_start(ap, p);
51     vfprintf(stderr, p, ap);
52     va_end(ap);
53     fputc('\n', stderr);
54 }
55 void connection_fatal(void *frontend, char *p, ...)
56 {
57     va_list ap;
58     fprintf(stderr, "FATAL ERROR: ");
59     va_start(ap, p);
60     vfprintf(stderr, p, ap);
61     va_end(ap);
62     fputc('\n', stderr);
63     exit(1);
64 }
65 void cmdline_error(char *p, ...)
66 {
67     va_list ap;
68     fprintf(stderr, "pageant: ");
69     va_start(ap, p);
70     vfprintf(stderr, p, ap);
71     va_end(ap);
72     fputc('\n', stderr);
73     exit(1);
74 }
75
76 FILE *pageant_logfp = NULL;
77 void pageant_log(void *ctx, const char *fmt, va_list ap)
78 {
79     if (!pageant_logfp)
80         return;
81
82     fprintf(pageant_logfp, "pageant: ");
83     vfprintf(pageant_logfp, fmt, ap);
84     fprintf(pageant_logfp, "\n");
85 }
86
87 /*
88  * In Pageant our selects are synchronous, so these functions are
89  * empty stubs.
90  */
91 int uxsel_input_add(int fd, int rwx) { return 0; }
92 void uxsel_input_remove(int id) { }
93
94 /*
95  * More stubs.
96  */
97 void random_save_seed(void) {}
98 void random_destroy_seed(void) {}
99 void noise_ultralight(unsigned long data) {}
100 char *platform_default_s(const char *name) { return NULL; }
101 int platform_default_i(const char *name, int def) { return def; }
102 FontSpec *platform_default_fontspec(const char *name) { return fontspec_new(""); }
103 Filename *platform_default_filename(const char *name) { return filename_from_str(""); }
104 char *x_get_default(const char *key) { return NULL; }
105 void log_eventlog(void *handle, const char *event) {}
106
107 /*
108  * Short description of parameters.
109  */
110 static void usage(void)
111 {
112     printf("Pageant: SSH agent\n");
113     printf("%s\n", ver);
114     printf("FIXME\n");
115     exit(1);
116 }
117
118 static void version(void)
119 {
120     printf("pageant: %s\n", ver);
121     exit(1);
122 }
123
124 void keylist_update(void)
125 {
126     /* Nothing needs doing in Unix Pageant */
127 }
128
129 #define PAGEANT_DIR_PREFIX "/tmp/pageant"
130
131 const char *const appname = "Pageant";
132
133 static int time_to_die = FALSE;
134
135 /* Stub functions to permit linking against x11fwd.c. These never get
136  * used, because in LIFE_X11 mode we connect to the X server using a
137  * straightforward Socket and don't try to create an ersatz SSH
138  * forwarding too. */
139 int sshfwd_write(struct ssh_channel *c, char *data, int len) { return 0; }
140 void sshfwd_write_eof(struct ssh_channel *c) { }
141 void sshfwd_unclean_close(struct ssh_channel *c, const char *err) { }
142 void sshfwd_unthrottle(struct ssh_channel *c, int bufsize) {}
143 Conf *sshfwd_get_conf(struct ssh_channel *c) { return NULL; }
144 void sshfwd_x11_sharing_handover(struct ssh_channel *c,
145                                  void *share_cs, void *share_chan,
146                                  const char *peer_addr, int peer_port,
147                                  int endian, int protomajor, int protominor,
148                                  const void *initial_data, int initial_len) {}
149 void sshfwd_x11_is_local(struct ssh_channel *c) {}
150
151 /*
152  * These functions are part of the plug for our connection to the X
153  * display, so they do get called. They needn't actually do anything,
154  * except that x11_closing has to signal back to the main loop that
155  * it's time to terminate.
156  */
157 static void x11_log(Plug p, int type, SockAddr addr, int port,
158                     const char *error_msg, int error_code) {}
159 static int x11_receive(Plug plug, int urgent, char *data, int len) {return 0;}
160 static void x11_sent(Plug plug, int bufsize) {}
161 static int x11_closing(Plug plug, const char *error_msg, int error_code,
162                        int calling_back)
163 {
164     time_to_die = TRUE;
165     return 1;
166 }
167 struct X11Connection {
168     const struct plug_function_table *fn;
169 };
170
171 char *socketname;
172 void pageant_print_env(int pid)
173 {
174     printf("SSH_AUTH_SOCK=%s; export SSH_AUTH_SOCK;\n"
175            "SSH_AGENT_PID=%d; export SSH_AGENT_PID;\n",
176            socketname, (int)pid);
177 }
178
179 void pageant_fork_and_print_env(int retain_tty)
180 {
181     pid_t pid = fork();
182     if (pid == -1) {
183         perror("fork");
184         exit(1);
185     } else if (pid != 0) {
186         pageant_print_env(pid);
187         exit(0);
188     }
189
190     /*
191      * Having forked off, we now daemonise ourselves as best we can.
192      * It's good practice in general to setsid() ourself out of any
193      * process group we didn't want to be part of, and to chdir("/")
194      * to avoid holding any directories open that we don't need in
195      * case someone wants to umount them; also, we should definitely
196      * close standard output (because it will very likely be pointing
197      * at a pipe from which some parent process is trying to read our
198      * environment variable dump, so if we hold open another copy of
199      * it then that process will never finish reading). We close
200      * standard input too on general principles, but not standard
201      * error, since we might need to shout a panicky error message
202      * down that one.
203      */
204     if (chdir("/") < 0) {
205         /* should there be an error condition, nothing we can do about
206          * it anyway */
207     }
208     close(0);
209     close(1);
210     if (retain_tty) {
211         /* Get out of our previous process group, to avoid being
212          * blasted by passing signals. But keep our controlling tty,
213          * so we can keep checking to see if we still have one. */
214         setpgrp();
215     } else {
216         /* Do that, but also leave our entire session and detach from
217          * the controlling tty (if any). */
218         setsid();
219     }
220 }
221
222 int signalpipe[2];
223
224 void sigchld(int signum)
225 {
226     if (write(signalpipe[1], "x", 1) <= 0)
227         /* not much we can do about it */;
228 }
229
230 #define TTY_LIFE_POLL_INTERVAL (TICKSPERSEC * 30)
231 void *dummy_timer_ctx;
232 static void tty_life_timer(void *ctx, unsigned long now)
233 {
234     schedule_timer(TTY_LIFE_POLL_INTERVAL, tty_life_timer, &dummy_timer_ctx);
235 }
236
237 typedef enum {
238     KEYACT_AGENT_LOAD,
239     KEYACT_CLIENT_ADD,
240     KEYACT_CLIENT_DEL,
241     KEYACT_CLIENT_DEL_ALL,
242     KEYACT_CLIENT_LIST,
243     KEYACT_CLIENT_LIST_FULL,
244 } keyact;
245 struct cmdline_key_action {
246     struct cmdline_key_action *next;
247     keyact action;
248     const char *filename;
249 };
250
251 int is_agent_action(keyact action)
252 {
253     return action == KEYACT_AGENT_LOAD;
254 }
255
256 struct cmdline_key_action *keyact_head = NULL, *keyact_tail = NULL;
257
258 void add_keyact(keyact action, const char *filename)
259 {
260     struct cmdline_key_action *a = snew(struct cmdline_key_action);
261     a->action = action;
262     a->filename = filename;
263     a->next = NULL;
264     if (keyact_tail)
265         keyact_tail->next = a;
266     else
267         keyact_head = a;
268     keyact_tail = a;
269 }
270
271 char **exec_args = NULL;
272 enum {
273     LIFE_UNSPEC, LIFE_X11, LIFE_TTY, LIFE_DEBUG, LIFE_PERM, LIFE_EXEC
274 } life = LIFE_UNSPEC;
275 const char *display = NULL;
276
277 static char *askpass(const char *comment)
278 {
279     prompts_t *p = new_prompts(NULL);
280     int ret;
281
282     /*
283      * FIXME: if we don't have a terminal, and have to do this by X11,
284      * there's a big missing piece.
285      */
286
287     p->to_server = FALSE;
288     p->name = dupstr("Pageant passphrase prompt");
289     add_prompt(p,
290                dupprintf("Enter passphrase to load key '%s': ", comment),
291                FALSE);
292     ret = console_get_userpass_input(p, NULL, 0);
293     assert(ret >= 0);
294
295     if (!ret) {
296         perror("pageant: unable to read passphrase");
297         free_prompts(p);
298         return NULL;
299     } else {
300         char *passphrase = dupstr(p->prompts[0]->result);
301         free_prompts(p);
302         return passphrase;
303     }
304 }
305
306 static int unix_add_keyfile(const char *filename_str)
307 {
308     Filename *filename = filename_from_str(filename_str);
309     int status, ret;
310     char *err;
311
312     ret = TRUE;
313
314     /*
315      * Try without a passphrase.
316      */
317     status = pageant_add_keyfile(filename, NULL, &err);
318     if (status == PAGEANT_ACTION_OK) {
319         goto cleanup;
320     } else if (status == PAGEANT_ACTION_FAILURE) {
321         fprintf(stderr, "pageant: %s: %s\n", filename_str, err);
322         sfree(err);
323         ret = FALSE;
324         goto cleanup;
325     }
326
327     /*
328      * And now try prompting for a passphrase.
329      */
330     while (1) {
331         char *passphrase = askpass(err);
332         sfree(err);
333         if (!passphrase)
334             break;
335
336         status = pageant_add_keyfile(filename, passphrase, &err);
337
338         smemclr(passphrase, strlen(passphrase));
339         sfree(passphrase);
340         passphrase = NULL;
341
342         if (status == PAGEANT_ACTION_OK) {
343             goto cleanup;
344         } else if (status == PAGEANT_ACTION_FAILURE) {
345             fprintf(stderr, "pageant: %s: %s\n", filename_str, err);
346             sfree(err);
347             ret = FALSE;
348             goto cleanup;
349         }
350     }
351
352   cleanup:
353     sfree(err);
354     filename_free(filename);
355     return ret;
356 }
357
358 void key_list_callback(void *ctx, const char *fingerprint,
359                        const char *comment, struct pageant_pubkey *key)
360 {
361     printf("%s %s\n", fingerprint, comment);
362 }
363
364 struct key_find_ctx {
365     const char *string;
366     int match_fp, match_comment;
367     struct pageant_pubkey *found;
368     int nfound;
369 };
370
371 int match_fingerprint_string(const char *string, const char *fingerprint)
372 {
373     const char *hash;
374
375     /* Find the hash in the fingerprint string. It'll be the word at the end. */
376     hash = strrchr(fingerprint, ' ');
377     assert(hash);
378     hash++;
379
380     /* Now see if the search string is a prefix of the full hash,
381      * neglecting colons and case differences. */
382     while (1) {
383         while (*string == ':') string++;
384         while (*hash == ':') hash++;
385         if (!*string)
386             return TRUE;
387         if (tolower((unsigned char)*string) != tolower((unsigned char)*hash))
388             return FALSE;
389         string++;
390         hash++;
391     }
392 }
393
394 void key_find_callback(void *vctx, const char *fingerprint,
395                        const char *comment, struct pageant_pubkey *key)
396 {
397     struct key_find_ctx *ctx = (struct key_find_ctx *)vctx;
398
399     if ((ctx->match_comment && !strcmp(ctx->string, comment)) ||
400         (ctx->match_fp && match_fingerprint_string(ctx->string, fingerprint)))
401     {
402         if (!ctx->found)
403             ctx->found = pageant_pubkey_copy(key);
404         ctx->nfound++;
405     }
406 }
407
408 struct pageant_pubkey *find_key(const char *string, char **retstr)
409 {
410     struct key_find_ctx actx, *ctx = &actx;
411     struct pageant_pubkey key_in, *key_ret;
412     int try_file = TRUE, try_fp = TRUE, try_comment = TRUE;
413     int file_errors = FALSE;
414
415     /*
416      * Trim off disambiguating prefixes telling us how to interpret
417      * the provided string.
418      */
419     if (!strncmp(string, "file:", 5)) {
420         string += 5;
421         try_fp = try_comment = FALSE;
422         file_errors = TRUE; /* also report failure to load the file */
423     } else if (!strncmp(string, "comment:", 8)) {
424         string += 8;
425         try_file = try_fp = FALSE;
426     } else if (!strncmp(string, "fp:", 3)) {
427         string += 3;
428         try_file = try_comment = FALSE;
429     } else if (!strncmp(string, "fingerprint:", 12)) {
430         string += 12;
431         try_file = try_comment = FALSE;
432     }
433
434     /*
435      * Try interpreting the string as a key file name.
436      */
437     if (try_file) {
438         Filename *fn = filename_from_str(string);
439         int keytype = key_type(fn);
440         if (keytype == SSH_KEYTYPE_SSH1 ||
441             keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
442             const char *error;
443
444             if (!rsakey_pubblob(fn, &key_in.blob, &key_in.bloblen,
445                                 NULL, &error)) {
446                 if (file_errors) {
447                     *retstr = dupprintf("unable to load file '%s': %s",
448                                         string, error);
449                     filename_free(fn);
450                     return NULL;
451                 }
452             }
453
454             /*
455              * If we've successfully loaded the file, stop here - we
456              * already have a key blob and need not go to the agent to
457              * list things.
458              */
459             key_in.ssh_version = 1;
460             key_ret = pageant_pubkey_copy(&key_in);
461             sfree(key_in.blob);
462             filename_free(fn);
463             return key_ret;
464         } else if (keytype == SSH_KEYTYPE_SSH2 ||
465                    keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
466                    keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
467             const char *error;
468
469             if ((key_in.blob = ssh2_userkey_loadpub(fn, NULL,
470                                                     &key_in.bloblen,
471                                                     NULL, &error)) == NULL) {
472                 if (file_errors) {
473                     *retstr = dupprintf("unable to load file '%s': %s",
474                                         string, error);
475                     filename_free(fn);
476                     return NULL;
477                 }
478             }
479
480             /*
481              * If we've successfully loaded the file, stop here - we
482              * already have a key blob and need not go to the agent to
483              * list things.
484              */
485             key_in.ssh_version = 2;
486             key_ret = pageant_pubkey_copy(&key_in);
487             sfree(key_in.blob);
488             filename_free(fn);
489             return key_ret;
490         } else {
491             if (file_errors) {
492                 *retstr = dupprintf("unable to load key file '%s': %s",
493                                     string, key_type_to_str(keytype));
494                 filename_free(fn);
495                 return NULL;
496             }
497         }
498         filename_free(fn);
499     }
500
501     /*
502      * Failing that, go through the keys in the agent, and match
503      * against fingerprints and comments as appropriate.
504      */
505     ctx->string = string;
506     ctx->match_fp = try_fp;
507     ctx->match_comment = try_comment;
508     ctx->found = NULL;
509     ctx->nfound = 0;
510     if (pageant_enum_keys(key_find_callback, ctx, retstr) ==
511         PAGEANT_ACTION_FAILURE)
512         return NULL;
513
514     if (ctx->nfound == 0) {
515         *retstr = dupstr("no key matched");
516         assert(!ctx->found);
517         return NULL;
518     } else if (ctx->nfound > 1) {
519         *retstr = dupstr("multiple keys matched");
520         assert(ctx->found);
521         pageant_pubkey_free(ctx->found);
522         return NULL;
523     }
524
525     assert(ctx->found);
526     return ctx->found;
527 }
528
529 void run_client(void)
530 {
531     const struct cmdline_key_action *act;
532     struct pageant_pubkey *key;
533     int errors = FALSE;
534     char *retstr;
535
536     if (!agent_exists()) {
537         fprintf(stderr, "pageant: no agent running to talk to\n");
538         exit(1);
539     }
540
541     for (act = keyact_head; act; act = act->next) {
542         switch (act->action) {
543           case KEYACT_CLIENT_ADD:
544             if (!unix_add_keyfile(act->filename))
545                 errors = TRUE;
546             break;
547           case KEYACT_CLIENT_LIST:
548             if (pageant_enum_keys(key_list_callback, NULL, &retstr) ==
549                 PAGEANT_ACTION_FAILURE) {
550                 fprintf(stderr, "pageant: listing keys: %s\n", retstr);
551                 sfree(retstr);
552                 errors = TRUE;
553             }
554             break;
555           case KEYACT_CLIENT_DEL:
556             key = NULL;
557             if (!(key = find_key(act->filename, &retstr)) ||
558                 pageant_delete_key(key, &retstr) == PAGEANT_ACTION_FAILURE) {
559                 fprintf(stderr, "pageant: deleting key '%s': %s\n",
560                         act->filename, retstr);
561                 sfree(retstr);
562                 errors = TRUE;
563             }
564             if (key)
565                 pageant_pubkey_free(key);
566             break;
567           case KEYACT_CLIENT_DEL_ALL:
568           case KEYACT_CLIENT_LIST_FULL:
569             fprintf(stderr, "NYI\n");
570             errors = TRUE;
571             break;
572           default:
573             assert(0 && "Invalid client action found");
574         }
575     }
576
577     if (errors)
578         exit(1);
579 }
580
581 void run_agent(void)
582 {
583     const char *err;
584     char *username, *socketdir;
585     struct pageant_listen_state *pl;
586     Socket sock;
587     unsigned long now;
588     int *fdlist;
589     int fd;
590     int i, fdcount, fdsize, fdstate;
591     int termination_pid = -1;
592     int errors = FALSE;
593     Conf *conf;
594     const struct cmdline_key_action *act;
595
596     fdlist = NULL;
597     fdcount = fdsize = 0;
598
599     pageant_init();
600
601     /*
602      * Start by loading any keys provided on the command line.
603      */
604     for (act = keyact_head; act; act = act->next) {
605         assert(act->action == KEYACT_AGENT_LOAD);
606         if (!unix_add_keyfile(act->filename))
607             errors = TRUE;
608     }
609     if (errors)
610         exit(1);
611
612     /*
613      * Set up a listening socket and run Pageant on it.
614      */
615     username = get_username();
616     socketdir = dupprintf("%s.%s", PAGEANT_DIR_PREFIX, username);
617     sfree(username);
618     assert(*socketdir == '/');
619     if ((err = make_dir_and_check_ours(socketdir)) != NULL) {
620         fprintf(stderr, "pageant: %s: %s\n", socketdir, err);
621         exit(1);
622     }
623     socketname = dupprintf("%s/pageant.%d", socketdir, (int)getpid());
624     pl = pageant_listener_new();
625     sock = new_unix_listener(unix_sock_addr(socketname), (Plug)pl);
626     if ((err = sk_socket_error(sock)) != NULL) {
627         fprintf(stderr, "pageant: %s: %s\n", socketname, err);
628         exit(1);
629     }
630     pageant_listener_got_socket(pl, sock);
631
632     conf = conf_new();
633     conf_set_int(conf, CONF_proxy_type, PROXY_NONE);
634
635     /*
636      * Lifetime preparations.
637      */
638     signalpipe[0] = signalpipe[1] = -1;
639     if (life == LIFE_X11) {
640         struct X11Display *disp;
641         void *greeting;
642         int greetinglen;
643         Socket s;
644         struct X11Connection *conn;
645
646         static const struct plug_function_table fn_table = {
647             x11_log,
648             x11_closing,
649             x11_receive,
650             x11_sent,
651             NULL
652         };
653
654         if (!display)
655             display = getenv("DISPLAY");
656         if (!display) {
657             fprintf(stderr, "pageant: no DISPLAY for -X mode\n");
658             exit(1);
659         }
660         disp = x11_setup_display(display, conf);
661
662         conn = snew(struct X11Connection);
663         conn->fn = &fn_table;
664         s = new_connection(sk_addr_dup(disp->addr),
665                            disp->realhost, disp->port,
666                            0, 1, 0, 0, (Plug)conn, conf);
667         if ((err = sk_socket_error(s)) != NULL) {
668             fprintf(stderr, "pageant: unable to connect to X server: %s", err);
669             exit(1);
670         }
671         greeting = x11_make_greeting('B', 11, 0, disp->localauthproto,
672                                      disp->localauthdata,
673                                      disp->localauthdatalen,
674                                      NULL, 0, &greetinglen);
675         sk_write(s, greeting, greetinglen);
676         smemclr(greeting, greetinglen);
677         sfree(greeting);
678
679         pageant_fork_and_print_env(FALSE);
680     } else if (life == LIFE_TTY) {
681         schedule_timer(TTY_LIFE_POLL_INTERVAL,
682                        tty_life_timer, &dummy_timer_ctx);
683         pageant_fork_and_print_env(TRUE);
684     } else if (life == LIFE_PERM) {
685         pageant_fork_and_print_env(FALSE);
686     } else if (life == LIFE_DEBUG) {
687         pageant_print_env(getpid());
688         pageant_logfp = stdout;
689     } else if (life == LIFE_EXEC) {
690         pid_t agentpid, pid;
691
692         agentpid = getpid();
693
694         /*
695          * Set up the pipe we'll use to tell us about SIGCHLD.
696          */
697         if (pipe(signalpipe) < 0) {
698             perror("pipe");
699             exit(1);
700         }
701         putty_signal(SIGCHLD, sigchld);
702
703         pid = fork();
704         if (pid < 0) {
705             perror("fork");
706             exit(1);
707         } else if (pid == 0) {
708             setenv("SSH_AUTH_SOCK", socketname, TRUE);
709             setenv("SSH_AGENT_PID", dupprintf("%d", (int)agentpid), TRUE);
710             execvp(exec_args[0], exec_args);
711             perror("exec");
712             _exit(127);
713         } else {
714             termination_pid = pid;
715         }
716     }
717
718     /*
719      * Now we've decided on our logging arrangements, pass them on to
720      * pageant.c.
721      */
722     pageant_listener_set_logfn(pl, NULL, pageant_logfp ? pageant_log : NULL);
723
724     now = GETTICKCOUNT();
725
726     while (!time_to_die) {
727         fd_set rset, wset, xset;
728         int maxfd;
729         int rwx;
730         int ret;
731         unsigned long next;
732
733         FD_ZERO(&rset);
734         FD_ZERO(&wset);
735         FD_ZERO(&xset);
736         maxfd = 0;
737
738         if (signalpipe[0] >= 0) {
739             FD_SET_MAX(signalpipe[0], maxfd, rset);
740         }
741
742         /* Count the currently active fds. */
743         i = 0;
744         for (fd = first_fd(&fdstate, &rwx); fd >= 0;
745              fd = next_fd(&fdstate, &rwx)) i++;
746
747         /* Expand the fdlist buffer if necessary. */
748         if (i > fdsize) {
749             fdsize = i + 16;
750             fdlist = sresize(fdlist, fdsize, int);
751         }
752
753         /*
754          * Add all currently open fds to the select sets, and store
755          * them in fdlist as well.
756          */
757         fdcount = 0;
758         for (fd = first_fd(&fdstate, &rwx); fd >= 0;
759              fd = next_fd(&fdstate, &rwx)) {
760             fdlist[fdcount++] = fd;
761             if (rwx & 1)
762                 FD_SET_MAX(fd, maxfd, rset);
763             if (rwx & 2)
764                 FD_SET_MAX(fd, maxfd, wset);
765             if (rwx & 4)
766                 FD_SET_MAX(fd, maxfd, xset);
767         }
768
769         if (toplevel_callback_pending()) {
770             struct timeval tv;
771             tv.tv_sec = 0;
772             tv.tv_usec = 0;
773             ret = select(maxfd, &rset, &wset, &xset, &tv);
774         } else if (run_timers(now, &next)) {
775             unsigned long then;
776             long ticks;
777             struct timeval tv;
778
779             then = now;
780             now = GETTICKCOUNT();
781             if (now - then > next - then)
782                 ticks = 0;
783             else
784                 ticks = next - now;
785             tv.tv_sec = ticks / 1000;
786             tv.tv_usec = ticks % 1000 * 1000;
787             ret = select(maxfd, &rset, &wset, &xset, &tv);
788             if (ret == 0)
789                 now = next;
790             else
791                 now = GETTICKCOUNT();
792         } else {
793             ret = select(maxfd, &rset, &wset, &xset, NULL);
794         }
795
796         if (ret < 0 && errno == EINTR)
797             continue;
798
799         if (ret < 0) {
800             perror("select");
801             exit(1);
802         }
803
804         if (life == LIFE_TTY) {
805             /*
806              * Every time we wake up (whether it was due to tty_timer
807              * elapsing or for any other reason), poll to see if we
808              * still have a controlling terminal. If we don't, then
809              * our containing tty session has ended, so it's time to
810              * clean up and leave.
811              */
812             int fd = open("/dev/tty", O_RDONLY);
813             if (fd < 0) {
814                 if (errno != ENXIO) {
815                     perror("/dev/tty: open");
816                     exit(1);
817                 }
818                 time_to_die = TRUE;
819                 break;
820             } else {
821                 close(fd);
822             }
823         }
824
825         for (i = 0; i < fdcount; i++) {
826             fd = fdlist[i];
827             /*
828              * We must process exceptional notifications before
829              * ordinary readability ones, or we may go straight
830              * past the urgent marker.
831              */
832             if (FD_ISSET(fd, &xset))
833                 select_result(fd, 4);
834             if (FD_ISSET(fd, &rset))
835                 select_result(fd, 1);
836             if (FD_ISSET(fd, &wset))
837                 select_result(fd, 2);
838         }
839
840         if (signalpipe[0] >= 0 && FD_ISSET(signalpipe[0], &rset)) {
841             char c[1];
842             if (read(signalpipe[0], c, 1) <= 0)
843                 /* ignore error */;
844             /* ignore its value; it'll be `x' */
845             while (1) {
846                 int status;
847                 pid_t pid;
848                 pid = waitpid(-1, &status, WNOHANG);
849                 if (pid <= 0)
850                     break;
851                 if (pid == termination_pid)
852                     time_to_die = TRUE;
853             }
854         }
855
856         run_toplevel_callbacks();
857     }
858
859     /*
860      * When we come here, we're terminating, and should clean up our
861      * Unix socket file if possible.
862      */
863     if (unlink(socketname) < 0) {
864         fprintf(stderr, "pageant: %s: %s\n", socketname, strerror(errno));
865         exit(1);
866     }
867 }
868
869 int main(int argc, char **argv)
870 {
871     int doing_opts = TRUE;
872     keyact curr_keyact = KEYACT_AGENT_LOAD;
873
874     /*
875      * Process the command line.
876      */
877     while (--argc > 0) {
878         char *p = *++argv;
879         if (*p == '-' && doing_opts) {
880             if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
881                 version();
882             } else if (!strcmp(p, "--help")) {
883                 usage();
884                 exit(0);
885             } else if (!strcmp(p, "-v")) {
886                 pageant_logfp = stderr;
887             } else if (!strcmp(p, "-a")) {
888                 curr_keyact = KEYACT_CLIENT_ADD;
889             } else if (!strcmp(p, "-d")) {
890                 curr_keyact = KEYACT_CLIENT_DEL;
891             } else if (!strcmp(p, "-D")) {
892                 add_keyact(KEYACT_CLIENT_DEL_ALL, NULL);
893             } else if (!strcmp(p, "-l")) {
894                 add_keyact(KEYACT_CLIENT_LIST, NULL);
895             } else if (!strcmp(p, "-L")) {
896                 add_keyact(KEYACT_CLIENT_LIST_FULL, NULL);
897             } else if (!strcmp(p, "-X")) {
898                 life = LIFE_X11;
899             } else if (!strcmp(p, "-T")) {
900                 life = LIFE_TTY;
901             } else if (!strcmp(p, "--debug")) {
902                 life = LIFE_DEBUG;
903             } else if (!strcmp(p, "--permanent")) {
904                 life = LIFE_PERM;
905             } else if (!strcmp(p, "--exec")) {
906                 life = LIFE_EXEC;
907                 /* Now all subsequent arguments go to the exec command. */
908                 if (--argc > 0) {
909                     exec_args = ++argv;
910                     argc = 0;          /* force end of option processing */
911                 } else {
912                     fprintf(stderr, "pageant: expected a command "
913                             "after --exec\n");
914                     exit(1);
915                 }
916             } else if (!strcmp(p, "--")) {
917                 doing_opts = FALSE;
918             }
919         } else {
920             /*
921              * Non-option arguments (apart from those after --exec,
922              * which are treated specially above) are interpreted as
923              * the names of private key files to either add or delete
924              * from an agent.
925              */
926             add_keyact(curr_keyact, p);
927         }
928     }
929
930     if (life == LIFE_EXEC && !exec_args) {
931         fprintf(stderr, "pageant: expected a command with --exec\n");
932         exit(1);
933     }
934
935     /*
936      * Block SIGPIPE, so that we'll get EPIPE individually on
937      * particular network connections that go wrong.
938      */
939     putty_signal(SIGPIPE, SIG_IGN);
940
941     sk_init();
942     uxsel_init();
943
944     /*
945      * Now distinguish our two main running modes. Either we're
946      * actually starting up an agent, in which case we should have a
947      * lifetime mode, and no key actions of KEYACT_CLIENT_* type; or
948      * else we're contacting an existing agent to add or remove keys,
949      * in which case we should have no lifetime mode, and no key
950      * actions of KEYACT_AGENT_* type.
951      */
952     {
953         int has_agent_actions = FALSE;
954         int has_client_actions = FALSE;
955         int has_lifetime = FALSE;
956         const struct cmdline_key_action *act;
957
958         for (act = keyact_head; act; act = act->next) {
959             if (is_agent_action(act->action))
960                 has_agent_actions = TRUE;
961             else
962                 has_client_actions = TRUE;
963         }
964         if (life != LIFE_UNSPEC)
965             has_lifetime = TRUE;
966
967         if (has_lifetime && has_client_actions) {
968             fprintf(stderr, "pageant: client key actions (-a, -d, -D, -l, -L)"
969                     " do not go with an agent lifetime option\n");
970             exit(1);
971         }
972         if (!has_lifetime && has_agent_actions) {
973             fprintf(stderr, "pageant: expected an agent lifetime option with"
974                     " bare key file arguments\n");
975             exit(1);
976         }
977         if (!has_lifetime && !has_client_actions) {
978             fprintf(stderr, "pageant: expected an agent lifetime option"
979                     " or a client key action\n");
980             exit(1);
981         }
982
983         if (has_lifetime) {
984             run_agent();
985         } else if (has_client_actions) {
986             run_client();
987         }
988     }
989
990     return 0;
991 }