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