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