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