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