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