]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/uxpgnt.c
b8738fac55dfd88574b186d6cd01806ba08e3922
[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_ret = pageant_pubkey_copy(&key_in);
555             sfree(key_in.blob);
556             filename_free(fn);
557             return key_ret;
558         } else if (keytype == SSH_KEYTYPE_SSH2 ||
559                    keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
560                    keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
561             const char *error;
562
563             if ((key_in.blob = ssh2_userkey_loadpub(fn, NULL,
564                                                     &key_in.bloblen,
565                                                     NULL, &error)) == NULL) {
566                 if (file_errors) {
567                     *retstr = dupprintf("unable to load file '%s': %s",
568                                         string, error);
569                     filename_free(fn);
570                     return NULL;
571                 }
572             }
573
574             /*
575              * If we've successfully loaded the file, stop here - we
576              * already have a key blob and need not go to the agent to
577              * list things.
578              */
579             key_in.ssh_version = 2;
580             key_ret = pageant_pubkey_copy(&key_in);
581             sfree(key_in.blob);
582             filename_free(fn);
583             return key_ret;
584         } else {
585             if (file_errors) {
586                 *retstr = dupprintf("unable to load key file '%s': %s",
587                                     string, key_type_to_str(keytype));
588                 filename_free(fn);
589                 return NULL;
590             }
591         }
592         filename_free(fn);
593     }
594
595     /*
596      * Failing that, go through the keys in the agent, and match
597      * against fingerprints and comments as appropriate.
598      */
599     ctx->string = string;
600     ctx->match_fp = try_fp;
601     ctx->match_comment = try_comment;
602     ctx->found = NULL;
603     ctx->nfound = 0;
604     if (pageant_enum_keys(key_find_callback, ctx, retstr) ==
605         PAGEANT_ACTION_FAILURE)
606         return NULL;
607
608     if (ctx->nfound == 0) {
609         *retstr = dupstr("no key matched");
610         assert(!ctx->found);
611         return NULL;
612     } else if (ctx->nfound > 1) {
613         *retstr = dupstr("multiple keys matched");
614         assert(ctx->found);
615         pageant_pubkey_free(ctx->found);
616         return NULL;
617     }
618
619     assert(ctx->found);
620     return ctx->found;
621 }
622
623 void run_client(void)
624 {
625     const struct cmdline_key_action *act;
626     struct pageant_pubkey *key;
627     int errors = FALSE;
628     char *retstr;
629
630     if (!agent_exists()) {
631         fprintf(stderr, "pageant: no agent running to talk to\n");
632         exit(1);
633     }
634
635     for (act = keyact_head; act; act = act->next) {
636         switch (act->action) {
637           case KEYACT_CLIENT_ADD:
638             if (!unix_add_keyfile(act->filename))
639                 errors = TRUE;
640             break;
641           case KEYACT_CLIENT_LIST:
642             if (pageant_enum_keys(key_list_callback, NULL, &retstr) ==
643                 PAGEANT_ACTION_FAILURE) {
644                 fprintf(stderr, "pageant: listing keys: %s\n", retstr);
645                 sfree(retstr);
646                 errors = TRUE;
647             }
648             break;
649           case KEYACT_CLIENT_DEL:
650             key = NULL;
651             if (!(key = find_key(act->filename, &retstr)) ||
652                 pageant_delete_key(key, &retstr) == PAGEANT_ACTION_FAILURE) {
653                 fprintf(stderr, "pageant: deleting key '%s': %s\n",
654                         act->filename, retstr);
655                 sfree(retstr);
656                 errors = TRUE;
657             }
658             if (key)
659                 pageant_pubkey_free(key);
660             break;
661           case KEYACT_CLIENT_PUBLIC_OPENSSH:
662           case KEYACT_CLIENT_PUBLIC:
663             key = NULL;
664             if (!(key = find_key(act->filename, &retstr))) {
665                 fprintf(stderr, "pageant: finding key '%s': %s\n",
666                         act->filename, retstr);
667                 sfree(retstr);
668                 errors = TRUE;
669             } else {
670                 FILE *fp = stdout;     /* FIXME: add a -o option? */
671
672                 if (key->ssh_version == 1) {
673                     struct RSAKey rkey;
674                     memset(&rkey, 0, sizeof(rkey));
675                     rkey.comment = dupstr(key->comment);
676                     makekey(key->blob, key->bloblen, &rkey, NULL, 0);
677                     ssh1_write_pubkey(fp, &rkey);
678                     freersakey(&rkey);
679                 } else {
680                     ssh2_write_pubkey(fp, key->comment, key->blob,key->bloblen,
681                                       (act->action == KEYACT_CLIENT_PUBLIC ?
682                                        SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 :
683                                        SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH));
684                 }
685                 pageant_pubkey_free(key);
686             }
687             break;
688           case KEYACT_CLIENT_DEL_ALL:
689             if (pageant_delete_all_keys(&retstr) == PAGEANT_ACTION_FAILURE) {
690                 fprintf(stderr, "pageant: deleting all keys: %s\n", retstr);
691                 sfree(retstr);
692                 errors = TRUE;
693             }
694             break;
695           default:
696             assert(0 && "Invalid client action found");
697         }
698     }
699
700     if (errors)
701         exit(1);
702 }
703
704 void run_agent(void)
705 {
706     const char *err;
707     char *username, *socketdir;
708     struct pageant_listen_state *pl;
709     Socket sock;
710     unsigned long now;
711     int *fdlist;
712     int fd;
713     int i, fdcount, fdsize, fdstate;
714     int termination_pid = -1;
715     int errors = FALSE;
716     Conf *conf;
717     const struct cmdline_key_action *act;
718
719     fdlist = NULL;
720     fdcount = fdsize = 0;
721
722     pageant_init();
723
724     /*
725      * Start by loading any keys provided on the command line.
726      */
727     for (act = keyact_head; act; act = act->next) {
728         assert(act->action == KEYACT_AGENT_LOAD);
729         if (!unix_add_keyfile(act->filename))
730             errors = TRUE;
731     }
732     if (errors)
733         exit(1);
734
735     /*
736      * Set up a listening socket and run Pageant on it.
737      */
738     username = get_username();
739     socketdir = dupprintf("%s.%s", PAGEANT_DIR_PREFIX, username);
740     sfree(username);
741     assert(*socketdir == '/');
742     if ((err = make_dir_and_check_ours(socketdir)) != NULL) {
743         fprintf(stderr, "pageant: %s: %s\n", socketdir, err);
744         exit(1);
745     }
746     socketname = dupprintf("%s/pageant.%d", socketdir, (int)getpid());
747     pl = pageant_listener_new();
748     sock = new_unix_listener(unix_sock_addr(socketname), (Plug)pl);
749     if ((err = sk_socket_error(sock)) != NULL) {
750         fprintf(stderr, "pageant: %s: %s\n", socketname, err);
751         exit(1);
752     }
753     pageant_listener_got_socket(pl, sock);
754
755     conf = conf_new();
756     conf_set_int(conf, CONF_proxy_type, PROXY_NONE);
757
758     /*
759      * Lifetime preparations.
760      */
761     signalpipe[0] = signalpipe[1] = -1;
762     if (life == LIFE_X11) {
763         struct X11Display *disp;
764         void *greeting;
765         int greetinglen;
766         Socket s;
767         struct X11Connection *conn;
768
769         static const struct plug_function_table fn_table = {
770             x11_log,
771             x11_closing,
772             x11_receive,
773             x11_sent,
774             NULL
775         };
776
777         if (!display) {
778             fprintf(stderr, "pageant: no DISPLAY for -X mode\n");
779             exit(1);
780         }
781         disp = x11_setup_display(display, conf);
782
783         conn = snew(struct X11Connection);
784         conn->fn = &fn_table;
785         s = new_connection(sk_addr_dup(disp->addr),
786                            disp->realhost, disp->port,
787                            0, 1, 0, 0, (Plug)conn, conf);
788         if ((err = sk_socket_error(s)) != NULL) {
789             fprintf(stderr, "pageant: unable to connect to X server: %s", err);
790             exit(1);
791         }
792         greeting = x11_make_greeting('B', 11, 0, disp->localauthproto,
793                                      disp->localauthdata,
794                                      disp->localauthdatalen,
795                                      NULL, 0, &greetinglen);
796         sk_write(s, greeting, greetinglen);
797         smemclr(greeting, greetinglen);
798         sfree(greeting);
799
800         pageant_fork_and_print_env(FALSE);
801     } else if (life == LIFE_TTY) {
802         schedule_timer(TTY_LIFE_POLL_INTERVAL,
803                        tty_life_timer, &dummy_timer_ctx);
804         pageant_fork_and_print_env(TRUE);
805     } else if (life == LIFE_PERM) {
806         pageant_fork_and_print_env(FALSE);
807     } else if (life == LIFE_DEBUG) {
808         pageant_print_env(getpid());
809         pageant_logfp = stdout;
810     } else if (life == LIFE_EXEC) {
811         pid_t agentpid, pid;
812
813         agentpid = getpid();
814
815         /*
816          * Set up the pipe we'll use to tell us about SIGCHLD.
817          */
818         if (pipe(signalpipe) < 0) {
819             perror("pipe");
820             exit(1);
821         }
822         putty_signal(SIGCHLD, sigchld);
823
824         pid = fork();
825         if (pid < 0) {
826             perror("fork");
827             exit(1);
828         } else if (pid == 0) {
829             setenv("SSH_AUTH_SOCK", socketname, TRUE);
830             setenv("SSH_AGENT_PID", dupprintf("%d", (int)agentpid), TRUE);
831             execvp(exec_args[0], exec_args);
832             perror("exec");
833             _exit(127);
834         } else {
835             termination_pid = pid;
836         }
837     }
838
839     /*
840      * Now we've decided on our logging arrangements, pass them on to
841      * pageant.c.
842      */
843     pageant_listener_set_logfn(pl, NULL, pageant_logfp ? pageant_log : NULL);
844
845     now = GETTICKCOUNT();
846
847     while (!time_to_die) {
848         fd_set rset, wset, xset;
849         int maxfd;
850         int rwx;
851         int ret;
852         unsigned long next;
853
854         FD_ZERO(&rset);
855         FD_ZERO(&wset);
856         FD_ZERO(&xset);
857         maxfd = 0;
858
859         if (signalpipe[0] >= 0) {
860             FD_SET_MAX(signalpipe[0], maxfd, rset);
861         }
862
863         /* Count the currently active fds. */
864         i = 0;
865         for (fd = first_fd(&fdstate, &rwx); fd >= 0;
866              fd = next_fd(&fdstate, &rwx)) i++;
867
868         /* Expand the fdlist buffer if necessary. */
869         if (i > fdsize) {
870             fdsize = i + 16;
871             fdlist = sresize(fdlist, fdsize, int);
872         }
873
874         /*
875          * Add all currently open fds to the select sets, and store
876          * them in fdlist as well.
877          */
878         fdcount = 0;
879         for (fd = first_fd(&fdstate, &rwx); fd >= 0;
880              fd = next_fd(&fdstate, &rwx)) {
881             fdlist[fdcount++] = fd;
882             if (rwx & 1)
883                 FD_SET_MAX(fd, maxfd, rset);
884             if (rwx & 2)
885                 FD_SET_MAX(fd, maxfd, wset);
886             if (rwx & 4)
887                 FD_SET_MAX(fd, maxfd, xset);
888         }
889
890         if (toplevel_callback_pending()) {
891             struct timeval tv;
892             tv.tv_sec = 0;
893             tv.tv_usec = 0;
894             ret = select(maxfd, &rset, &wset, &xset, &tv);
895         } else if (run_timers(now, &next)) {
896             unsigned long then;
897             long ticks;
898             struct timeval tv;
899
900             then = now;
901             now = GETTICKCOUNT();
902             if (now - then > next - then)
903                 ticks = 0;
904             else
905                 ticks = next - now;
906             tv.tv_sec = ticks / 1000;
907             tv.tv_usec = ticks % 1000 * 1000;
908             ret = select(maxfd, &rset, &wset, &xset, &tv);
909             if (ret == 0)
910                 now = next;
911             else
912                 now = GETTICKCOUNT();
913         } else {
914             ret = select(maxfd, &rset, &wset, &xset, NULL);
915         }
916
917         if (ret < 0 && errno == EINTR)
918             continue;
919
920         if (ret < 0) {
921             perror("select");
922             exit(1);
923         }
924
925         if (life == LIFE_TTY) {
926             /*
927              * Every time we wake up (whether it was due to tty_timer
928              * elapsing or for any other reason), poll to see if we
929              * still have a controlling terminal. If we don't, then
930              * our containing tty session has ended, so it's time to
931              * clean up and leave.
932              */
933             if (!have_controlling_tty()) {
934                 time_to_die = TRUE;
935                 break;
936             }
937         }
938
939         for (i = 0; i < fdcount; i++) {
940             fd = fdlist[i];
941             /*
942              * We must process exceptional notifications before
943              * ordinary readability ones, or we may go straight
944              * past the urgent marker.
945              */
946             if (FD_ISSET(fd, &xset))
947                 select_result(fd, 4);
948             if (FD_ISSET(fd, &rset))
949                 select_result(fd, 1);
950             if (FD_ISSET(fd, &wset))
951                 select_result(fd, 2);
952         }
953
954         if (signalpipe[0] >= 0 && FD_ISSET(signalpipe[0], &rset)) {
955             char c[1];
956             if (read(signalpipe[0], c, 1) <= 0)
957                 /* ignore error */;
958             /* ignore its value; it'll be `x' */
959             while (1) {
960                 int status;
961                 pid_t pid;
962                 pid = waitpid(-1, &status, WNOHANG);
963                 if (pid <= 0)
964                     break;
965                 if (pid == termination_pid)
966                     time_to_die = TRUE;
967             }
968         }
969
970         run_toplevel_callbacks();
971     }
972
973     /*
974      * When we come here, we're terminating, and should clean up our
975      * Unix socket file if possible.
976      */
977     if (unlink(socketname) < 0) {
978         fprintf(stderr, "pageant: %s: %s\n", socketname, strerror(errno));
979         exit(1);
980     }
981 }
982
983 int main(int argc, char **argv)
984 {
985     int doing_opts = TRUE;
986     keyact curr_keyact = KEYACT_AGENT_LOAD;
987
988     /*
989      * Process the command line.
990      */
991     while (--argc > 0) {
992         char *p = *++argv;
993         if (*p == '-' && doing_opts) {
994             if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
995                 version();
996             } else if (!strcmp(p, "--help")) {
997                 usage();
998                 exit(0);
999             } else if (!strcmp(p, "-v")) {
1000                 pageant_logfp = stderr;
1001             } else if (!strcmp(p, "-a")) {
1002                 curr_keyact = KEYACT_CLIENT_ADD;
1003             } else if (!strcmp(p, "-d")) {
1004                 curr_keyact = KEYACT_CLIENT_DEL;
1005             } else if (!strcmp(p, "-s")) {
1006                 shell_type = SHELL_SH;
1007             } else if (!strcmp(p, "-c")) {
1008                 shell_type = SHELL_CSH;
1009             } else if (!strcmp(p, "-D")) {
1010                 add_keyact(KEYACT_CLIENT_DEL_ALL, NULL);
1011             } else if (!strcmp(p, "-l")) {
1012                 add_keyact(KEYACT_CLIENT_LIST, NULL);
1013             } else if (!strcmp(p, "--public")) {
1014                 curr_keyact = KEYACT_CLIENT_PUBLIC;
1015             } else if (!strcmp(p, "--public-openssh")) {
1016                 curr_keyact = KEYACT_CLIENT_PUBLIC_OPENSSH;
1017             } else if (!strcmp(p, "-X")) {
1018                 life = LIFE_X11;
1019             } else if (!strcmp(p, "-T")) {
1020                 life = LIFE_TTY;
1021             } else if (!strcmp(p, "--debug")) {
1022                 life = LIFE_DEBUG;
1023             } else if (!strcmp(p, "--permanent")) {
1024                 life = LIFE_PERM;
1025             } else if (!strcmp(p, "--exec")) {
1026                 life = LIFE_EXEC;
1027                 /* Now all subsequent arguments go to the exec command. */
1028                 if (--argc > 0) {
1029                     exec_args = ++argv;
1030                     argc = 0;          /* force end of option processing */
1031                 } else {
1032                     fprintf(stderr, "pageant: expected a command "
1033                             "after --exec\n");
1034                     exit(1);
1035                 }
1036             } else if (!strcmp(p, "--")) {
1037                 doing_opts = FALSE;
1038             }
1039         } else {
1040             /*
1041              * Non-option arguments (apart from those after --exec,
1042              * which are treated specially above) are interpreted as
1043              * the names of private key files to either add or delete
1044              * from an agent.
1045              */
1046             add_keyact(curr_keyact, p);
1047         }
1048     }
1049
1050     if (life == LIFE_EXEC && !exec_args) {
1051         fprintf(stderr, "pageant: expected a command with --exec\n");
1052         exit(1);
1053     }
1054
1055     /*
1056      * Block SIGPIPE, so that we'll get EPIPE individually on
1057      * particular network connections that go wrong.
1058      */
1059     putty_signal(SIGPIPE, SIG_IGN);
1060
1061     sk_init();
1062     uxsel_init();
1063
1064     if (!display) {
1065         display = getenv("DISPLAY");
1066         if (display && !*display)
1067             display = NULL;
1068     }
1069
1070     /*
1071      * Now distinguish our two main running modes. Either we're
1072      * actually starting up an agent, in which case we should have a
1073      * lifetime mode, and no key actions of KEYACT_CLIENT_* type; or
1074      * else we're contacting an existing agent to add or remove keys,
1075      * in which case we should have no lifetime mode, and no key
1076      * actions of KEYACT_AGENT_* type.
1077      */
1078     {
1079         int has_agent_actions = FALSE;
1080         int has_client_actions = FALSE;
1081         int has_lifetime = FALSE;
1082         const struct cmdline_key_action *act;
1083
1084         for (act = keyact_head; act; act = act->next) {
1085             if (is_agent_action(act->action))
1086                 has_agent_actions = TRUE;
1087             else
1088                 has_client_actions = TRUE;
1089         }
1090         if (life != LIFE_UNSPEC)
1091             has_lifetime = TRUE;
1092
1093         if (has_lifetime && has_client_actions) {
1094             fprintf(stderr, "pageant: client key actions (-a, -d, -D, -l, -L)"
1095                     " do not go with an agent lifetime option\n");
1096             exit(1);
1097         }
1098         if (!has_lifetime && has_agent_actions) {
1099             fprintf(stderr, "pageant: expected an agent lifetime option with"
1100                     " bare key file arguments\n");
1101             exit(1);
1102         }
1103         if (!has_lifetime && !has_client_actions) {
1104             fprintf(stderr, "pageant: expected an agent lifetime option"
1105                     " or a client key action\n");
1106             exit(1);
1107         }
1108
1109         if (has_lifetime) {
1110             run_agent();
1111         } else if (has_client_actions) {
1112             run_client();
1113         }
1114     }
1115
1116     return 0;
1117 }