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