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