]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/uxpgnt.c
Unix Pageant: fix a double-free when adding keys.
[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_PUBLIC_OPENSSH,
244     KEYACT_CLIENT_PUBLIC
245 } keyact;
246 struct cmdline_key_action {
247     struct cmdline_key_action *next;
248     keyact action;
249     const char *filename;
250 };
251
252 int is_agent_action(keyact action)
253 {
254     return action == KEYACT_AGENT_LOAD;
255 }
256
257 struct cmdline_key_action *keyact_head = NULL, *keyact_tail = NULL;
258
259 void add_keyact(keyact action, const char *filename)
260 {
261     struct cmdline_key_action *a = snew(struct cmdline_key_action);
262     a->action = action;
263     a->filename = filename;
264     a->next = NULL;
265     if (keyact_tail)
266         keyact_tail->next = a;
267     else
268         keyact_head = a;
269     keyact_tail = a;
270 }
271
272 char **exec_args = NULL;
273 enum {
274     LIFE_UNSPEC, LIFE_X11, LIFE_TTY, LIFE_DEBUG, LIFE_PERM, LIFE_EXEC
275 } life = LIFE_UNSPEC;
276 const char *display = NULL;
277
278 static char *askpass(const char *comment)
279 {
280     prompts_t *p = new_prompts(NULL);
281     int ret;
282
283     /*
284      * FIXME: if we don't have a terminal, and have to do this by X11,
285      * there's a big missing piece.
286      */
287
288     p->to_server = FALSE;
289     p->name = dupstr("Pageant passphrase prompt");
290     add_prompt(p,
291                dupprintf("Enter passphrase to load key '%s': ", comment),
292                FALSE);
293     ret = console_get_userpass_input(p, NULL, 0);
294     assert(ret >= 0);
295
296     if (!ret) {
297         perror("pageant: unable to read passphrase");
298         free_prompts(p);
299         return NULL;
300     } else {
301         char *passphrase = dupstr(p->prompts[0]->result);
302         free_prompts(p);
303         return passphrase;
304     }
305 }
306
307 static int unix_add_keyfile(const char *filename_str)
308 {
309     Filename *filename = filename_from_str(filename_str);
310     int status, ret;
311     char *err;
312
313     ret = TRUE;
314
315     /*
316      * Try without a passphrase.
317      */
318     status = pageant_add_keyfile(filename, NULL, &err);
319     if (status == PAGEANT_ACTION_OK) {
320         goto cleanup;
321     } else if (status == PAGEANT_ACTION_FAILURE) {
322         fprintf(stderr, "pageant: %s: %s\n", filename_str, err);
323         sfree(err);
324         ret = FALSE;
325         goto cleanup;
326     }
327
328     /*
329      * And now try prompting for a passphrase.
330      */
331     while (1) {
332         char *passphrase = askpass(err);
333         sfree(err);
334         err = NULL;
335         if (!passphrase)
336             break;
337
338         status = pageant_add_keyfile(filename, passphrase, &err);
339
340         smemclr(passphrase, strlen(passphrase));
341         sfree(passphrase);
342         passphrase = NULL;
343
344         if (status == PAGEANT_ACTION_OK) {
345             goto cleanup;
346         } else if (status == PAGEANT_ACTION_FAILURE) {
347             fprintf(stderr, "pageant: %s: %s\n", filename_str, err);
348             sfree(err);
349             ret = FALSE;
350             goto cleanup;
351         }
352     }
353
354   cleanup:
355     sfree(err);
356     filename_free(filename);
357     return ret;
358 }
359
360 void key_list_callback(void *ctx, const char *fingerprint,
361                        const char *comment, struct pageant_pubkey *key)
362 {
363     printf("%s %s\n", fingerprint, comment);
364 }
365
366 struct key_find_ctx {
367     const char *string;
368     int match_fp, match_comment;
369     struct pageant_pubkey *found;
370     int nfound;
371 };
372
373 int match_fingerprint_string(const char *string, const char *fingerprint)
374 {
375     const char *hash;
376
377     /* Find the hash in the fingerprint string. It'll be the word at the end. */
378     hash = strrchr(fingerprint, ' ');
379     assert(hash);
380     hash++;
381
382     /* Now see if the search string is a prefix of the full hash,
383      * neglecting colons and case differences. */
384     while (1) {
385         while (*string == ':') string++;
386         while (*hash == ':') hash++;
387         if (!*string)
388             return TRUE;
389         if (tolower((unsigned char)*string) != tolower((unsigned char)*hash))
390             return FALSE;
391         string++;
392         hash++;
393     }
394 }
395
396 void key_find_callback(void *vctx, const char *fingerprint,
397                        const char *comment, struct pageant_pubkey *key)
398 {
399     struct key_find_ctx *ctx = (struct key_find_ctx *)vctx;
400
401     if ((ctx->match_comment && !strcmp(ctx->string, comment)) ||
402         (ctx->match_fp && match_fingerprint_string(ctx->string, fingerprint)))
403     {
404         if (!ctx->found)
405             ctx->found = pageant_pubkey_copy(key);
406         ctx->nfound++;
407     }
408 }
409
410 struct pageant_pubkey *find_key(const char *string, char **retstr)
411 {
412     struct key_find_ctx actx, *ctx = &actx;
413     struct pageant_pubkey key_in, *key_ret;
414     int try_file = TRUE, try_fp = TRUE, try_comment = TRUE;
415     int file_errors = FALSE;
416
417     /*
418      * Trim off disambiguating prefixes telling us how to interpret
419      * the provided string.
420      */
421     if (!strncmp(string, "file:", 5)) {
422         string += 5;
423         try_fp = try_comment = FALSE;
424         file_errors = TRUE; /* also report failure to load the file */
425     } else if (!strncmp(string, "comment:", 8)) {
426         string += 8;
427         try_file = try_fp = FALSE;
428     } else if (!strncmp(string, "fp:", 3)) {
429         string += 3;
430         try_file = try_comment = FALSE;
431     } else if (!strncmp(string, "fingerprint:", 12)) {
432         string += 12;
433         try_file = try_comment = FALSE;
434     }
435
436     /*
437      * Try interpreting the string as a key file name.
438      */
439     if (try_file) {
440         Filename *fn = filename_from_str(string);
441         int keytype = key_type(fn);
442         if (keytype == SSH_KEYTYPE_SSH1 ||
443             keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
444             const char *error;
445
446             if (!rsakey_pubblob(fn, &key_in.blob, &key_in.bloblen,
447                                 NULL, &error)) {
448                 if (file_errors) {
449                     *retstr = dupprintf("unable to load file '%s': %s",
450                                         string, error);
451                     filename_free(fn);
452                     return NULL;
453                 }
454             }
455
456             /*
457              * If we've successfully loaded the file, stop here - we
458              * already have a key blob and need not go to the agent to
459              * list things.
460              */
461             key_in.ssh_version = 1;
462             key_ret = pageant_pubkey_copy(&key_in);
463             sfree(key_in.blob);
464             filename_free(fn);
465             return key_ret;
466         } else if (keytype == SSH_KEYTYPE_SSH2 ||
467                    keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
468                    keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
469             const char *error;
470
471             if ((key_in.blob = ssh2_userkey_loadpub(fn, NULL,
472                                                     &key_in.bloblen,
473                                                     NULL, &error)) == NULL) {
474                 if (file_errors) {
475                     *retstr = dupprintf("unable to load file '%s': %s",
476                                         string, error);
477                     filename_free(fn);
478                     return NULL;
479                 }
480             }
481
482             /*
483              * If we've successfully loaded the file, stop here - we
484              * already have a key blob and need not go to the agent to
485              * list things.
486              */
487             key_in.ssh_version = 2;
488             key_ret = pageant_pubkey_copy(&key_in);
489             sfree(key_in.blob);
490             filename_free(fn);
491             return key_ret;
492         } else {
493             if (file_errors) {
494                 *retstr = dupprintf("unable to load key file '%s': %s",
495                                     string, key_type_to_str(keytype));
496                 filename_free(fn);
497                 return NULL;
498             }
499         }
500         filename_free(fn);
501     }
502
503     /*
504      * Failing that, go through the keys in the agent, and match
505      * against fingerprints and comments as appropriate.
506      */
507     ctx->string = string;
508     ctx->match_fp = try_fp;
509     ctx->match_comment = try_comment;
510     ctx->found = NULL;
511     ctx->nfound = 0;
512     if (pageant_enum_keys(key_find_callback, ctx, retstr) ==
513         PAGEANT_ACTION_FAILURE)
514         return NULL;
515
516     if (ctx->nfound == 0) {
517         *retstr = dupstr("no key matched");
518         assert(!ctx->found);
519         return NULL;
520     } else if (ctx->nfound > 1) {
521         *retstr = dupstr("multiple keys matched");
522         assert(ctx->found);
523         pageant_pubkey_free(ctx->found);
524         return NULL;
525     }
526
527     assert(ctx->found);
528     return ctx->found;
529 }
530
531 void run_client(void)
532 {
533     const struct cmdline_key_action *act;
534     struct pageant_pubkey *key;
535     int errors = FALSE;
536     char *retstr;
537
538     if (!agent_exists()) {
539         fprintf(stderr, "pageant: no agent running to talk to\n");
540         exit(1);
541     }
542
543     for (act = keyact_head; act; act = act->next) {
544         switch (act->action) {
545           case KEYACT_CLIENT_ADD:
546             if (!unix_add_keyfile(act->filename))
547                 errors = TRUE;
548             break;
549           case KEYACT_CLIENT_LIST:
550             if (pageant_enum_keys(key_list_callback, NULL, &retstr) ==
551                 PAGEANT_ACTION_FAILURE) {
552                 fprintf(stderr, "pageant: listing keys: %s\n", retstr);
553                 sfree(retstr);
554                 errors = TRUE;
555             }
556             break;
557           case KEYACT_CLIENT_DEL:
558             key = NULL;
559             if (!(key = find_key(act->filename, &retstr)) ||
560                 pageant_delete_key(key, &retstr) == PAGEANT_ACTION_FAILURE) {
561                 fprintf(stderr, "pageant: deleting key '%s': %s\n",
562                         act->filename, retstr);
563                 sfree(retstr);
564                 errors = TRUE;
565             }
566             if (key)
567                 pageant_pubkey_free(key);
568             break;
569           case KEYACT_CLIENT_PUBLIC_OPENSSH:
570           case KEYACT_CLIENT_PUBLIC:
571             key = NULL;
572             if (!(key = find_key(act->filename, &retstr))) {
573                 fprintf(stderr, "pageant: finding key '%s': %s\n",
574                         act->filename, retstr);
575                 sfree(retstr);
576                 errors = TRUE;
577             } else {
578                 FILE *fp = stdout;     /* FIXME: add a -o option? */
579
580                 if (key->ssh_version == 1) {
581                     struct RSAKey rkey;
582                     memset(&rkey, 0, sizeof(rkey));
583                     rkey.comment = dupstr(key->comment);
584                     makekey(key->blob, key->bloblen, &rkey, NULL, 0);
585                     ssh1_write_pubkey(fp, &rkey);
586                     freersakey(&rkey);
587                 } else {
588                     ssh2_write_pubkey(fp, key->comment, key->blob,key->bloblen,
589                                       (act->action == KEYACT_CLIENT_PUBLIC ?
590                                        SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 :
591                                        SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH));
592                 }
593                 pageant_pubkey_free(key);
594             }
595             break;
596           case KEYACT_CLIENT_DEL_ALL:
597             if (pageant_delete_all_keys(&retstr) == PAGEANT_ACTION_FAILURE) {
598                 fprintf(stderr, "pageant: deleting all keys: %s\n", retstr);
599                 sfree(retstr);
600                 errors = TRUE;
601             }
602             break;
603           default:
604             assert(0 && "Invalid client action found");
605         }
606     }
607
608     if (errors)
609         exit(1);
610 }
611
612 void run_agent(void)
613 {
614     const char *err;
615     char *username, *socketdir;
616     struct pageant_listen_state *pl;
617     Socket sock;
618     unsigned long now;
619     int *fdlist;
620     int fd;
621     int i, fdcount, fdsize, fdstate;
622     int termination_pid = -1;
623     int errors = FALSE;
624     Conf *conf;
625     const struct cmdline_key_action *act;
626
627     fdlist = NULL;
628     fdcount = fdsize = 0;
629
630     pageant_init();
631
632     /*
633      * Start by loading any keys provided on the command line.
634      */
635     for (act = keyact_head; act; act = act->next) {
636         assert(act->action == KEYACT_AGENT_LOAD);
637         if (!unix_add_keyfile(act->filename))
638             errors = TRUE;
639     }
640     if (errors)
641         exit(1);
642
643     /*
644      * Set up a listening socket and run Pageant on it.
645      */
646     username = get_username();
647     socketdir = dupprintf("%s.%s", PAGEANT_DIR_PREFIX, username);
648     sfree(username);
649     assert(*socketdir == '/');
650     if ((err = make_dir_and_check_ours(socketdir)) != NULL) {
651         fprintf(stderr, "pageant: %s: %s\n", socketdir, err);
652         exit(1);
653     }
654     socketname = dupprintf("%s/pageant.%d", socketdir, (int)getpid());
655     pl = pageant_listener_new();
656     sock = new_unix_listener(unix_sock_addr(socketname), (Plug)pl);
657     if ((err = sk_socket_error(sock)) != NULL) {
658         fprintf(stderr, "pageant: %s: %s\n", socketname, err);
659         exit(1);
660     }
661     pageant_listener_got_socket(pl, sock);
662
663     conf = conf_new();
664     conf_set_int(conf, CONF_proxy_type, PROXY_NONE);
665
666     /*
667      * Lifetime preparations.
668      */
669     signalpipe[0] = signalpipe[1] = -1;
670     if (life == LIFE_X11) {
671         struct X11Display *disp;
672         void *greeting;
673         int greetinglen;
674         Socket s;
675         struct X11Connection *conn;
676
677         static const struct plug_function_table fn_table = {
678             x11_log,
679             x11_closing,
680             x11_receive,
681             x11_sent,
682             NULL
683         };
684
685         if (!display)
686             display = getenv("DISPLAY");
687         if (!display) {
688             fprintf(stderr, "pageant: no DISPLAY for -X mode\n");
689             exit(1);
690         }
691         disp = x11_setup_display(display, conf);
692
693         conn = snew(struct X11Connection);
694         conn->fn = &fn_table;
695         s = new_connection(sk_addr_dup(disp->addr),
696                            disp->realhost, disp->port,
697                            0, 1, 0, 0, (Plug)conn, conf);
698         if ((err = sk_socket_error(s)) != NULL) {
699             fprintf(stderr, "pageant: unable to connect to X server: %s", err);
700             exit(1);
701         }
702         greeting = x11_make_greeting('B', 11, 0, disp->localauthproto,
703                                      disp->localauthdata,
704                                      disp->localauthdatalen,
705                                      NULL, 0, &greetinglen);
706         sk_write(s, greeting, greetinglen);
707         smemclr(greeting, greetinglen);
708         sfree(greeting);
709
710         pageant_fork_and_print_env(FALSE);
711     } else if (life == LIFE_TTY) {
712         schedule_timer(TTY_LIFE_POLL_INTERVAL,
713                        tty_life_timer, &dummy_timer_ctx);
714         pageant_fork_and_print_env(TRUE);
715     } else if (life == LIFE_PERM) {
716         pageant_fork_and_print_env(FALSE);
717     } else if (life == LIFE_DEBUG) {
718         pageant_print_env(getpid());
719         pageant_logfp = stdout;
720     } else if (life == LIFE_EXEC) {
721         pid_t agentpid, pid;
722
723         agentpid = getpid();
724
725         /*
726          * Set up the pipe we'll use to tell us about SIGCHLD.
727          */
728         if (pipe(signalpipe) < 0) {
729             perror("pipe");
730             exit(1);
731         }
732         putty_signal(SIGCHLD, sigchld);
733
734         pid = fork();
735         if (pid < 0) {
736             perror("fork");
737             exit(1);
738         } else if (pid == 0) {
739             setenv("SSH_AUTH_SOCK", socketname, TRUE);
740             setenv("SSH_AGENT_PID", dupprintf("%d", (int)agentpid), TRUE);
741             execvp(exec_args[0], exec_args);
742             perror("exec");
743             _exit(127);
744         } else {
745             termination_pid = pid;
746         }
747     }
748
749     /*
750      * Now we've decided on our logging arrangements, pass them on to
751      * pageant.c.
752      */
753     pageant_listener_set_logfn(pl, NULL, pageant_logfp ? pageant_log : NULL);
754
755     now = GETTICKCOUNT();
756
757     while (!time_to_die) {
758         fd_set rset, wset, xset;
759         int maxfd;
760         int rwx;
761         int ret;
762         unsigned long next;
763
764         FD_ZERO(&rset);
765         FD_ZERO(&wset);
766         FD_ZERO(&xset);
767         maxfd = 0;
768
769         if (signalpipe[0] >= 0) {
770             FD_SET_MAX(signalpipe[0], maxfd, rset);
771         }
772
773         /* Count the currently active fds. */
774         i = 0;
775         for (fd = first_fd(&fdstate, &rwx); fd >= 0;
776              fd = next_fd(&fdstate, &rwx)) i++;
777
778         /* Expand the fdlist buffer if necessary. */
779         if (i > fdsize) {
780             fdsize = i + 16;
781             fdlist = sresize(fdlist, fdsize, int);
782         }
783
784         /*
785          * Add all currently open fds to the select sets, and store
786          * them in fdlist as well.
787          */
788         fdcount = 0;
789         for (fd = first_fd(&fdstate, &rwx); fd >= 0;
790              fd = next_fd(&fdstate, &rwx)) {
791             fdlist[fdcount++] = fd;
792             if (rwx & 1)
793                 FD_SET_MAX(fd, maxfd, rset);
794             if (rwx & 2)
795                 FD_SET_MAX(fd, maxfd, wset);
796             if (rwx & 4)
797                 FD_SET_MAX(fd, maxfd, xset);
798         }
799
800         if (toplevel_callback_pending()) {
801             struct timeval tv;
802             tv.tv_sec = 0;
803             tv.tv_usec = 0;
804             ret = select(maxfd, &rset, &wset, &xset, &tv);
805         } else if (run_timers(now, &next)) {
806             unsigned long then;
807             long ticks;
808             struct timeval tv;
809
810             then = now;
811             now = GETTICKCOUNT();
812             if (now - then > next - then)
813                 ticks = 0;
814             else
815                 ticks = next - now;
816             tv.tv_sec = ticks / 1000;
817             tv.tv_usec = ticks % 1000 * 1000;
818             ret = select(maxfd, &rset, &wset, &xset, &tv);
819             if (ret == 0)
820                 now = next;
821             else
822                 now = GETTICKCOUNT();
823         } else {
824             ret = select(maxfd, &rset, &wset, &xset, NULL);
825         }
826
827         if (ret < 0 && errno == EINTR)
828             continue;
829
830         if (ret < 0) {
831             perror("select");
832             exit(1);
833         }
834
835         if (life == LIFE_TTY) {
836             /*
837              * Every time we wake up (whether it was due to tty_timer
838              * elapsing or for any other reason), poll to see if we
839              * still have a controlling terminal. If we don't, then
840              * our containing tty session has ended, so it's time to
841              * clean up and leave.
842              */
843             int fd = open("/dev/tty", O_RDONLY);
844             if (fd < 0) {
845                 if (errno != ENXIO) {
846                     perror("/dev/tty: open");
847                     exit(1);
848                 }
849                 time_to_die = TRUE;
850                 break;
851             } else {
852                 close(fd);
853             }
854         }
855
856         for (i = 0; i < fdcount; i++) {
857             fd = fdlist[i];
858             /*
859              * We must process exceptional notifications before
860              * ordinary readability ones, or we may go straight
861              * past the urgent marker.
862              */
863             if (FD_ISSET(fd, &xset))
864                 select_result(fd, 4);
865             if (FD_ISSET(fd, &rset))
866                 select_result(fd, 1);
867             if (FD_ISSET(fd, &wset))
868                 select_result(fd, 2);
869         }
870
871         if (signalpipe[0] >= 0 && FD_ISSET(signalpipe[0], &rset)) {
872             char c[1];
873             if (read(signalpipe[0], c, 1) <= 0)
874                 /* ignore error */;
875             /* ignore its value; it'll be `x' */
876             while (1) {
877                 int status;
878                 pid_t pid;
879                 pid = waitpid(-1, &status, WNOHANG);
880                 if (pid <= 0)
881                     break;
882                 if (pid == termination_pid)
883                     time_to_die = TRUE;
884             }
885         }
886
887         run_toplevel_callbacks();
888     }
889
890     /*
891      * When we come here, we're terminating, and should clean up our
892      * Unix socket file if possible.
893      */
894     if (unlink(socketname) < 0) {
895         fprintf(stderr, "pageant: %s: %s\n", socketname, strerror(errno));
896         exit(1);
897     }
898 }
899
900 int main(int argc, char **argv)
901 {
902     int doing_opts = TRUE;
903     keyact curr_keyact = KEYACT_AGENT_LOAD;
904
905     /*
906      * Process the command line.
907      */
908     while (--argc > 0) {
909         char *p = *++argv;
910         if (*p == '-' && doing_opts) {
911             if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
912                 version();
913             } else if (!strcmp(p, "--help")) {
914                 usage();
915                 exit(0);
916             } else if (!strcmp(p, "-v")) {
917                 pageant_logfp = stderr;
918             } else if (!strcmp(p, "-a")) {
919                 curr_keyact = KEYACT_CLIENT_ADD;
920             } else if (!strcmp(p, "-d")) {
921                 curr_keyact = KEYACT_CLIENT_DEL;
922             } else if (!strcmp(p, "-D")) {
923                 add_keyact(KEYACT_CLIENT_DEL_ALL, NULL);
924             } else if (!strcmp(p, "-l")) {
925                 add_keyact(KEYACT_CLIENT_LIST, NULL);
926             } else if (!strcmp(p, "--public")) {
927                 curr_keyact = KEYACT_CLIENT_PUBLIC;
928             } else if (!strcmp(p, "--public-openssh")) {
929                 curr_keyact = KEYACT_CLIENT_PUBLIC_OPENSSH;
930             } else if (!strcmp(p, "-X")) {
931                 life = LIFE_X11;
932             } else if (!strcmp(p, "-T")) {
933                 life = LIFE_TTY;
934             } else if (!strcmp(p, "--debug")) {
935                 life = LIFE_DEBUG;
936             } else if (!strcmp(p, "--permanent")) {
937                 life = LIFE_PERM;
938             } else if (!strcmp(p, "--exec")) {
939                 life = LIFE_EXEC;
940                 /* Now all subsequent arguments go to the exec command. */
941                 if (--argc > 0) {
942                     exec_args = ++argv;
943                     argc = 0;          /* force end of option processing */
944                 } else {
945                     fprintf(stderr, "pageant: expected a command "
946                             "after --exec\n");
947                     exit(1);
948                 }
949             } else if (!strcmp(p, "--")) {
950                 doing_opts = FALSE;
951             }
952         } else {
953             /*
954              * Non-option arguments (apart from those after --exec,
955              * which are treated specially above) are interpreted as
956              * the names of private key files to either add or delete
957              * from an agent.
958              */
959             add_keyact(curr_keyact, p);
960         }
961     }
962
963     if (life == LIFE_EXEC && !exec_args) {
964         fprintf(stderr, "pageant: expected a command with --exec\n");
965         exit(1);
966     }
967
968     /*
969      * Block SIGPIPE, so that we'll get EPIPE individually on
970      * particular network connections that go wrong.
971      */
972     putty_signal(SIGPIPE, SIG_IGN);
973
974     sk_init();
975     uxsel_init();
976
977     /*
978      * Now distinguish our two main running modes. Either we're
979      * actually starting up an agent, in which case we should have a
980      * lifetime mode, and no key actions of KEYACT_CLIENT_* type; or
981      * else we're contacting an existing agent to add or remove keys,
982      * in which case we should have no lifetime mode, and no key
983      * actions of KEYACT_AGENT_* type.
984      */
985     {
986         int has_agent_actions = FALSE;
987         int has_client_actions = FALSE;
988         int has_lifetime = FALSE;
989         const struct cmdline_key_action *act;
990
991         for (act = keyact_head; act; act = act->next) {
992             if (is_agent_action(act->action))
993                 has_agent_actions = TRUE;
994             else
995                 has_client_actions = TRUE;
996         }
997         if (life != LIFE_UNSPEC)
998             has_lifetime = TRUE;
999
1000         if (has_lifetime && has_client_actions) {
1001             fprintf(stderr, "pageant: client key actions (-a, -d, -D, -l, -L)"
1002                     " do not go with an agent lifetime option\n");
1003             exit(1);
1004         }
1005         if (!has_lifetime && has_agent_actions) {
1006             fprintf(stderr, "pageant: expected an agent lifetime option with"
1007                     " bare key file arguments\n");
1008             exit(1);
1009         }
1010         if (!has_lifetime && !has_client_actions) {
1011             fprintf(stderr, "pageant: expected an agent lifetime option"
1012                     " or a client key action\n");
1013             exit(1);
1014         }
1015
1016         if (has_lifetime) {
1017             run_agent();
1018         } else if (has_client_actions) {
1019             run_client();
1020         }
1021     }
1022
1023     return 0;
1024 }