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