Imported Upstream version 2.3.8
[platform/upstream/gpg2.git] / tools / gpg-connect-agent.c
1 /* gpg-connect-agent.c - Tool to connect to the agent.
2  * Copyright (C) 2005, 2007, 2008, 2010 Free Software Foundation, Inc.
3  * Copyright (C) 2014 Werner Koch
4  *
5  * This file is part of GnuPG.
6  *
7  * GnuPG is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * GnuPG is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <https://www.gnu.org/licenses/>.
19  * SPDX-License-Identifier: GPL-3.0-or-later
20  */
21
22 #include <config.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <ctype.h>
28 #include <assuan.h>
29 #include <unistd.h>
30 #include <assert.h>
31
32 #define INCLUDED_BY_MAIN_MODULE 1
33 #include "../common/i18n.h"
34 #include "../common/util.h"
35 #include "../common/asshelp.h"
36 #include "../common/sysutils.h"
37 #include "../common/membuf.h"
38 #include "../common/ttyio.h"
39 #ifdef HAVE_W32_SYSTEM
40 #  include "../common/exechelp.h"
41 #endif
42 #include "../common/init.h"
43 #include "../common/comopt.h"
44
45
46 #define CONTROL_D ('D' - 'A' + 1)
47 #define octdigitp(p) (*(p) >= '0' && *(p) <= '7')
48
49 #define HISTORYNAME ".gpg-connect_history"
50
51
52 /* Constants to identify the commands and options. */
53 enum cmd_and_opt_values
54   {
55     aNull = 0,
56     oQuiet      = 'q',
57     oVerbose    = 'v',
58     oRawSocket  = 'S',
59     oTcpSocket  = 'T',
60     oExec       = 'E',
61     oRun        = 'r',
62     oSubst      = 's',
63     oUnBuffered = 'u',
64
65     oNoVerbose  = 500,
66     oHomedir,
67     oAgentProgram,
68     oDirmngrProgram,
69     oKeyboxdProgram,
70     oHex,
71     oDecode,
72     oNoExtConnect,
73     oDirmngr,
74     oKeyboxd,
75     oUIServer,
76     oNoHistory,
77     oNoAutostart,
78     oChUid,
79
80     oNoop
81   };
82
83
84 /* The list of commands and options. */
85 static gpgrt_opt_t opts[] = {
86   ARGPARSE_group (301, N_("@\nOptions:\n ")),
87
88   ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
89   ARGPARSE_s_n (oQuiet, "quiet",     N_("quiet")),
90   ARGPARSE_s_n (oHex,   "hex",       N_("print data out hex encoded")),
91   ARGPARSE_s_n (oDecode,"decode",    N_("decode received data lines")),
92   ARGPARSE_s_n (oDirmngr,"dirmngr",  N_("connect to the dirmngr")),
93   ARGPARSE_s_n (oKeyboxd,"keyboxd",  N_("connect to the keyboxd")),
94   ARGPARSE_s_n (oUIServer, "uiserver", "@"),
95   ARGPARSE_s_s (oRawSocket, "raw-socket",
96                 N_("|NAME|connect to Assuan socket NAME")),
97   ARGPARSE_s_s (oTcpSocket, "tcp-socket",
98                 N_("|ADDR|connect to Assuan server at ADDR")),
99   ARGPARSE_s_n (oExec, "exec",
100                 N_("run the Assuan server given on the command line")),
101   ARGPARSE_s_n (oNoExtConnect, "no-ext-connect",
102                 N_("do not use extended connect mode")),
103   ARGPARSE_s_s (oRun,  "run",
104                 N_("|FILE|run commands from FILE on startup")),
105   ARGPARSE_s_n (oSubst, "subst",     N_("run /subst on startup")),
106
107   ARGPARSE_s_n (oNoAutostart, "no-autostart", "@"),
108   ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
109   ARGPARSE_s_n (oNoHistory,"no-history",
110                 "do not use the command history file"),
111   ARGPARSE_s_s (oHomedir, "homedir", "@" ),
112   ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
113   ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"),
114   ARGPARSE_s_s (oKeyboxdProgram, "keyboxd-program", "@"),
115   ARGPARSE_s_s (oChUid,          "chuid",           "@"),
116   ARGPARSE_s_n (oUnBuffered,     "unbuffered", "@"),
117
118   ARGPARSE_end ()
119 };
120
121
122 /* We keep all global options in the structure OPT.  */
123 struct
124 {
125   int verbose;          /* Verbosity level.  */
126   int quiet;            /* Be extra quiet.  */
127   int autostart;        /* Start the server if not running.  */
128   const char *homedir;  /* Configuration directory name */
129   const char *agent_program;    /* Value of --agent-program.    */
130   const char *dirmngr_program;  /* Value of --dirmngr-program.  */
131   const char *keyboxd_program;  /* Value of --keyboxd-program.  */
132   int hex;              /* Print data lines in hex format. */
133   int decode;           /* Decode received data lines.  */
134   int use_dirmngr;      /* Use the dirmngr and not gpg-agent.  */
135   int use_keyboxd;      /* Use the keyboxd and not gpg-agent.  */
136   int use_uiserver;     /* Use the standard UI server.  */
137   const char *raw_socket; /* Name of socket to connect in raw mode. */
138   const char *tcp_socket; /* Name of server to connect in tcp mode. */
139   int exec;             /* Run the pgm given on the command line. */
140   unsigned int connect_flags;    /* Flags used for connecting. */
141   int enable_varsubst;  /* Set if variable substitution is enabled.  */
142   int trim_leading_spaces;
143   int no_history;
144   int unbuffered; /* Set if unbuffered mode for stdin/out is preferred.  */
145 } opt;
146
147
148
149 /* Definitions for /definq commands and a global linked list with all
150    the definitions. */
151 struct definq_s
152 {
153   struct definq_s *next;
154   char *name;     /* Name of inquiry or NULL for any name. */
155   int is_var;     /* True if FILE is a variable name. */
156   int is_prog;    /* True if FILE is a program to run. */
157   char file[1];   /* Name of file or program. */
158 };
159 typedef struct definq_s *definq_t;
160
161 static definq_t definq_list;
162 static definq_t *definq_list_tail = &definq_list;
163
164
165 /* Variable definitions and glovbal table.  */
166 struct variable_s
167 {
168   struct variable_s *next;
169   char *value;  /* Malloced value - always a string.  */
170   char name[1]; /* Name of the variable.  */
171 };
172 typedef struct variable_s *variable_t;
173
174 static variable_t variable_table;
175
176
177 /* To implement loops we store entire lines in a linked list.  */
178 struct loopline_s
179 {
180   struct loopline_s *next;
181   char line[1];
182 };
183 typedef struct loopline_s *loopline_t;
184
185
186 /* This is used to store the pid of the server.  */
187 static pid_t server_pid = (pid_t)(-1);
188
189 /* The current datasink file or NULL.  */
190 static estream_t current_datasink;
191
192 /* A list of open file descriptors. */
193 static struct
194 {
195   int inuse;
196 #ifdef HAVE_W32_SYSTEM
197   HANDLE handle;
198 #endif
199 } open_fd_table[256];
200
201
202 /*-- local prototypes --*/
203 static char *substitute_line_copy (const char *buffer);
204 static int read_and_print_response (assuan_context_t ctx, int withhash,
205                                     int *r_goterr);
206 static assuan_context_t start_agent (void);
207
208
209
210 \f
211 /* Print usage information and provide strings for help. */
212 static const char *
213 my_strusage( int level )
214 {
215   const char *p;
216
217   switch (level)
218     {
219     case  9: p = "GPL-3.0-or-later"; break;
220     case 11: p = "@GPG@-connect-agent (@GNUPG@)";
221       break;
222     case 13: p = VERSION; break;
223     case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break;
224     case 17: p = PRINTABLE_OS_NAME; break;
225     case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
226
227     case 1:
228     case 40: p = _("Usage: @GPG@-connect-agent [options] (-h for help)");
229       break;
230     case 41:
231       p = _("Syntax: @GPG@-connect-agent [options]\n"
232             "Connect to a running agent and send commands\n");
233       break;
234     case 31: p = "\nHome: "; break;
235     case 32: p = gnupg_homedir (); break;
236     case 33: p = "\n"; break;
237
238     default: p = NULL; break;
239     }
240   return p;
241 }
242
243
244 /* Unescape STRING and returned the malloced result.  The surrounding
245    quotes must already be removed from STRING.  */
246 static char *
247 unescape_string (const char *string)
248 {
249   const unsigned char *s;
250   int esc;
251   size_t n;
252   char *buffer;
253   unsigned char *d;
254
255   n = 0;
256   for (s = (const unsigned char*)string, esc=0; *s; s++)
257     {
258       if (esc)
259         {
260           switch (*s)
261             {
262             case 'b':
263             case 't':
264             case 'v':
265             case 'n':
266             case 'f':
267             case 'r':
268             case '"':
269             case '\'':
270             case '\\': n++; break;
271             case 'x':
272               if (s[1] && s[2] && hexdigitp (s+1) && hexdigitp (s+2))
273                 n++;
274               break;
275
276             default:
277               if (s[1] && s[2]
278                   && octdigitp (s) && octdigitp (s+1) && octdigitp (s+2))
279                 n++;
280               break;
281             }
282           esc = 0;
283         }
284       else if (*s == '\\')
285         esc = 1;
286       else
287         n++;
288     }
289
290   buffer = xmalloc (n+1);
291   d = (unsigned char*)buffer;
292   for (s = (const unsigned char*)string, esc=0; *s; s++)
293     {
294       if (esc)
295         {
296           switch (*s)
297             {
298             case 'b':  *d++ = '\b'; break;
299             case 't':  *d++ = '\t'; break;
300             case 'v':  *d++ = '\v'; break;
301             case 'n':  *d++ = '\n'; break;
302             case 'f':  *d++ = '\f'; break;
303             case 'r':  *d++ = '\r'; break;
304             case '"':  *d++ = '\"'; break;
305             case '\'': *d++ = '\''; break;
306             case '\\': *d++ = '\\'; break;
307             case 'x':
308               if (s[1] && s[2] && hexdigitp (s+1) && hexdigitp (s+2))
309                 {
310                   s++;
311                   *d++ = xtoi_2 (s);
312                   s++;
313                 }
314               break;
315
316             default:
317               if (s[1] && s[2]
318                   && octdigitp (s) && octdigitp (s+1) && octdigitp (s+2))
319                 {
320                   *d++ = (atoi_1 (s)*64) + (atoi_1 (s+1)*8) + atoi_1 (s+2);
321                   s += 2;
322                 }
323               break;
324             }
325           esc = 0;
326         }
327       else if (*s == '\\')
328         esc = 1;
329       else
330         *d++ = *s;
331     }
332   *d = 0;
333   return buffer;
334 }
335
336
337 /* Do the percent unescaping and return a newly malloced string.
338    If WITH_PLUS is set '+' characters will be changed to space. */
339 static char *
340 unpercent_string (const char *string, int with_plus)
341 {
342   const unsigned char *s;
343   unsigned char *buffer, *p;
344   size_t n;
345
346   n = 0;
347   for (s=(const unsigned char *)string; *s; s++)
348     {
349       if (*s == '%' && s[1] && s[2])
350         {
351           s++;
352           n++;
353           s++;
354         }
355       else if (with_plus && *s == '+')
356         n++;
357       else
358         n++;
359     }
360
361   buffer = xmalloc (n+1);
362   p = buffer;
363   for (s=(const unsigned char *)string; *s; s++)
364     {
365       if (*s == '%' && s[1] && s[2])
366         {
367           s++;
368           *p++ = xtoi_2 (s);
369           s++;
370         }
371       else if (with_plus && *s == '+')
372         *p++ = ' ';
373       else
374         *p++ = *s;
375     }
376   *p = 0;
377   return (char*)buffer;
378 }
379
380
381
382
383 \f
384 static const char *
385 set_var (const char *name, const char *value)
386 {
387   variable_t var;
388
389   for (var = variable_table; var; var = var->next)
390     if (!strcmp (var->name, name))
391       break;
392   if (!var)
393     {
394       var = xmalloc (sizeof *var + strlen (name));
395       var->value = NULL;
396       strcpy (var->name, name);
397       var->next = variable_table;
398       variable_table = var;
399     }
400   xfree (var->value);
401   var->value = value? xstrdup (value) : NULL;
402   return var->value;
403 }
404
405
406 static void
407 set_int_var (const char *name, int value)
408 {
409   char numbuf[35];
410
411   snprintf (numbuf, sizeof numbuf, "%d", value);
412   set_var (name, numbuf);
413 }
414
415
416 /* Return the value of a variable.  That value is valid until a
417    variable of the name is changed.  Return NULL if not found.  Note
418    that envvars are copied to our variable list at the first access
419    and not at oprogram start.  */
420 static const char *
421 get_var (const char *name)
422 {
423   variable_t var;
424   const char *s;
425
426   if (!*name)
427     return "";
428   for (var = variable_table; var; var = var->next)
429     if (!strcmp (var->name, name))
430       break;
431   if (!var && (s = getenv (name)))
432     return set_var (name, s);
433   if (!var || !var->value)
434     return NULL;
435   return var->value;
436 }
437
438
439 /* Perform some simple arithmetic operations.  Caller must release
440    the return value.  On error the return value is NULL.  */
441 static char *
442 arithmetic_op (int operator, const char *operands)
443 {
444   long result, value;
445   char numbuf[35];
446
447   while ( spacep (operands) )
448     operands++;
449   if (!*operands)
450     return NULL;
451   result = strtol (operands, NULL, 0);
452   while (*operands && !spacep (operands) )
453     operands++;
454   if (operator == '!')
455     result = !result;
456
457   while (*operands)
458     {
459       while ( spacep (operands) )
460         operands++;
461       if (!*operands)
462         break;
463       value = strtol (operands, NULL, 0);
464       while (*operands && !spacep (operands) )
465         operands++;
466       switch (operator)
467         {
468         case '+': result += value; break;
469         case '-': result -= value; break;
470         case '*': result *= value; break;
471         case '/':
472           if (!value)
473             return NULL;
474           result /= value;
475           break;
476         case '%':
477           if (!value)
478             return NULL;
479           result %= value;
480           break;
481         case '!': result = !value; break;
482         case '|': result = result || value; break;
483         case '&': result = result && value; break;
484         default:
485           log_error ("unknown arithmetic operator '%c'\n", operator);
486           return NULL;
487         }
488     }
489   snprintf (numbuf, sizeof numbuf, "%ld", result);
490   return xstrdup (numbuf);
491 }
492
493
494
495 /* Extended version of get_var.  This returns a malloced string and
496    understand the function syntax: "func args".
497
498    Defined functions are
499
500      get - Return a value described by the next argument:
501            cwd        - The current working directory.
502            homedir    - The gnupg homedir.
503            sysconfdir - GnuPG's system configuration directory.
504            bindir     - GnuPG's binary directory.
505            libdir     - GnuPG's library directory.
506            libexecdir - GnuPG's library directory for executable files.
507            datadir    - GnuPG's data directory.
508            serverpid  - The PID of the current server.
509
510      unescape ARGS
511            Remove C-style escapes from string.  Note that "\0" and
512            "\x00" terminate the string implicitly.  Use "\x7d" to
513            represent the closing brace.  The args start right after
514            the first space after the function name.
515
516      unpercent ARGS
517      unpercent+ ARGS
518            Remove percent style ecaping from string.  Note that "%00
519            terminates the string implicitly.  Use "%7d" to represetn
520            the closing brace.  The args start right after the first
521            space after the function name.  "unpercent+" also maps '+'
522            to space.
523
524      percent ARGS
525      percent+ ARGS
526            Escape the args using the percent style.  Tabs, formfeeds,
527            linefeeds, carriage return, and the plus sign are also
528            escaped.  "percent+" also maps spaces to plus characters.
529
530      errcode ARG
531            Assuming ARG is an integer, return the gpg-error code.
532
533      errsource ARG
534            Assuming ARG is an integer, return the gpg-error source.
535
536      errstring ARG
537            Assuming ARG is an integer return a formatted fpf error string.
538
539
540    Example: get_var_ext ("get sysconfdir") -> "/etc/gnupg"
541
542   */
543 static char *
544 get_var_ext (const char *name)
545 {
546   static int recursion_count;
547   const char *s;
548   char *result;
549   char *p;
550   char *free_me = NULL;
551   int intvalue;
552
553   if (recursion_count > 50)
554     {
555       log_error ("variables nested too deeply\n");
556       return NULL;
557     }
558
559   recursion_count++;
560   free_me = opt.enable_varsubst? substitute_line_copy (name) : NULL;
561   if (free_me)
562     name = free_me;
563   for (s=name; *s && !spacep (s); s++)
564     ;
565   if (!*s)
566     {
567       s = get_var (name);
568       result = s? xstrdup (s): NULL;
569     }
570   else if ( (s - name) == 3 && !strncmp (name, "get", 3))
571     {
572       while ( spacep (s) )
573         s++;
574       if (!strcmp (s, "cwd"))
575         {
576           result = gnupg_getcwd ();
577           if (!result)
578             log_error ("getcwd failed: %s\n", strerror (errno));
579         }
580       else if (!strcmp (s, "homedir"))
581         result = xstrdup (gnupg_homedir ());
582       else if (!strcmp (s, "sysconfdir"))
583         result = xstrdup (gnupg_sysconfdir ());
584       else if (!strcmp (s, "bindir"))
585         result = xstrdup (gnupg_bindir ());
586       else if (!strcmp (s, "libdir"))
587         result = xstrdup (gnupg_libdir ());
588       else if (!strcmp (s, "libexecdir"))
589         result = xstrdup (gnupg_libexecdir ());
590       else if (!strcmp (s, "datadir"))
591         result = xstrdup (gnupg_datadir ());
592       else if (!strcmp (s, "serverpid"))
593         result = xasprintf ("%d", (int)server_pid);
594       else
595         {
596           log_error ("invalid argument '%s' for variable function 'get'\n", s);
597           log_info  ("valid are: cwd, "
598                      "{home,bin,lib,libexec,data}dir, serverpid\n");
599           result = NULL;
600         }
601     }
602   else if ( (s - name) == 8 && !strncmp (name, "unescape", 8))
603     {
604       s++;
605       result = unescape_string (s);
606     }
607   else if ( (s - name) == 9 && !strncmp (name, "unpercent", 9))
608     {
609       s++;
610       result = unpercent_string (s, 0);
611     }
612   else if ( (s - name) == 10 && !strncmp (name, "unpercent+", 10))
613     {
614       s++;
615       result = unpercent_string (s, 1);
616     }
617   else if ( (s - name) == 7 && !strncmp (name, "percent", 7))
618     {
619       s++;
620       result = percent_escape (s, "+\t\r\n\f\v");
621     }
622   else if ( (s - name) == 8 && !strncmp (name, "percent+", 8))
623     {
624       s++;
625       result = percent_escape (s, "+\t\r\n\f\v");
626       for (p=result; *p; p++)
627         if (*p == ' ')
628           *p = '+';
629     }
630   else if ( (s - name) == 7 && !strncmp (name, "errcode", 7))
631     {
632       s++;
633       intvalue = (int)strtol (s, NULL, 0);
634       result = xasprintf ("%d", gpg_err_code (intvalue));
635     }
636   else if ( (s - name) == 9 && !strncmp (name, "errsource", 9))
637     {
638       s++;
639       intvalue = (int)strtol (s, NULL, 0);
640       result = xasprintf ("%d", gpg_err_source (intvalue));
641     }
642   else if ( (s - name) == 9 && !strncmp (name, "errstring", 9))
643     {
644       s++;
645       intvalue = (int)strtol (s, NULL, 0);
646       result = xasprintf ("%s <%s>",
647                           gpg_strerror (intvalue), gpg_strsource (intvalue));
648     }
649   else if ( (s - name) == 1 && strchr ("+-*/%!|&", *name))
650     {
651       result = arithmetic_op (*name, s+1);
652     }
653   else
654     {
655       log_error ("unknown variable function '%.*s'\n", (int)(s-name), name);
656       result = NULL;
657     }
658
659   xfree (free_me);
660   recursion_count--;
661   return result;
662 }
663
664
665 /* Substitute variables in LINE and return a new allocated buffer if
666    required.  The function might modify LINE if the expanded version
667    fits into it.  */
668 static char *
669 substitute_line (char *buffer)
670 {
671   char *line = buffer;
672   char *p, *pend;
673   const char *value;
674   size_t valuelen, n;
675   char *result = NULL;
676   char *freeme = NULL;
677
678   while (*line)
679     {
680       p = strchr (line, '$');
681       if (!p)
682         return result; /* No more variables.  */
683
684       if (p[1] == '$') /* Escaped dollar sign. */
685         {
686           memmove (p, p+1, strlen (p+1)+1);
687           line = p + 1;
688           continue;
689         }
690       if (p[1] == '{')
691         {
692           int count = 0;
693
694           for (pend=p+2; *pend; pend++)
695             {
696               if (*pend == '{')
697                 count++;
698               else if (*pend == '}')
699                 {
700                   if (--count < 0)
701                     break;
702                 }
703             }
704           if (!*pend)
705             return result; /* Unclosed - don't substitute.  */
706         }
707       else
708         {
709           for (pend=p+1; *pend && !spacep (pend) && *pend != '$' ; pend++)
710             ;
711         }
712       if (p[1] == '{' && *pend == '}')
713         {
714           int save = *pend;
715           *pend = 0;
716           freeme = get_var_ext (p+2);
717           value = freeme;
718           *pend++ = save;
719         }
720       else if (*pend)
721         {
722           int save = *pend;
723           *pend = 0;
724           value = get_var (p+1);
725           *pend = save;
726         }
727       else
728         value = get_var (p+1);
729       if (!value)
730         value = "";
731       valuelen = strlen (value);
732       if (valuelen <= pend - p)
733         {
734           memcpy (p, value, valuelen);
735           p += valuelen;
736           n = pend - p;
737           if (n)
738             memmove (p, p+n, strlen (p+n)+1);
739           line = p;
740         }
741       else
742         {
743           char *src = result? result : buffer;
744           char *dst;
745
746           dst = xmalloc (strlen (src) + valuelen + 1);
747           n = p - src;
748           memcpy (dst, src, n);
749           memcpy (dst + n, value, valuelen);
750           n += valuelen;
751           strcpy (dst + n, pend);
752           line = dst + n;
753           xfree (result);
754           result = dst;
755         }
756       xfree (freeme);
757       freeme = NULL;
758     }
759   return result;
760 }
761
762 /* Same as substitute_line but do not modify BUFFER.  */
763 static char *
764 substitute_line_copy (const char *buffer)
765 {
766   char *result, *p;
767
768   p = xstrdup (buffer?buffer:"");
769   result = substitute_line (p);
770   if (!result)
771     result = p;
772   else
773     xfree (p);
774   return result;
775 }
776
777
778 static void
779 assign_variable (char *line, int syslet)
780 {
781   char *name, *p, *tmp, *free_me, *buffer;
782
783   /* Get the  name. */
784   name = line;
785   for (p=name; *p && !spacep (p); p++)
786     ;
787   if (*p)
788     *p++ = 0;
789   while (spacep (p))
790     p++;
791
792   if (!*p)
793     set_var (name, NULL); /* Remove variable.  */
794   else if (syslet)
795     {
796       free_me = opt.enable_varsubst? substitute_line_copy (p) : NULL;
797       if (free_me)
798         p = free_me;
799       buffer = xmalloc (4 + strlen (p) + 1);
800       strcpy (stpcpy (buffer, "get "), p);
801       tmp = get_var_ext (buffer);
802       xfree (buffer);
803       set_var (name, tmp);
804       xfree (tmp);
805       xfree (free_me);
806     }
807   else
808     {
809       tmp = opt.enable_varsubst? substitute_line_copy (p) : NULL;
810       if (tmp)
811         {
812           set_var (name, tmp);
813           xfree (tmp);
814         }
815       else
816         set_var (name, p);
817     }
818 }
819
820
821 static void
822 show_variables (void)
823 {
824   variable_t var;
825
826   for (var = variable_table; var; var = var->next)
827     if (var->value)
828       printf ("%-20s %s\n", var->name, var->value);
829 }
830
831
832 /* Store an inquire response pattern.  Note, that this function may
833    change the content of LINE.  We assume that leading white spaces
834    are already removed. */
835 static void
836 add_definq (char *line, int is_var, int is_prog)
837 {
838   definq_t d;
839   char *name, *p;
840
841   /* Get name. */
842   name = line;
843   for (p=name; *p && !spacep (p); p++)
844     ;
845   if (*p)
846     *p++ = 0;
847   while (spacep (p))
848     p++;
849
850   d = xmalloc (sizeof *d + strlen (p) );
851   strcpy (d->file, p);
852   d->is_var  = is_var;
853   d->is_prog = is_prog;
854   if ( !strcmp (name, "*"))
855     d->name = NULL;
856   else
857     d->name = xstrdup (name);
858
859   d->next = NULL;
860   *definq_list_tail = d;
861   definq_list_tail = &d->next;
862 }
863
864
865 /* Show all inquiry definitions. */
866 static void
867 show_definq (void)
868 {
869   definq_t d;
870
871   for (d=definq_list; d; d = d->next)
872     if (d->name)
873       printf ("%-20s %c %s\n",
874               d->name, d->is_var? 'v' : d->is_prog? 'p':'f', d->file);
875   for (d=definq_list; d; d = d->next)
876     if (!d->name)
877       printf ("%-20s %c %s\n", "*",
878               d->is_var? 'v': d->is_prog? 'p':'f', d->file);
879 }
880
881
882 /* Clear all inquiry definitions. */
883 static void
884 clear_definq (void)
885 {
886   while (definq_list)
887     {
888       definq_t tmp = definq_list->next;
889       xfree (definq_list->name);
890       xfree (definq_list);
891       definq_list = tmp;
892     }
893   definq_list_tail = &definq_list;
894 }
895
896
897 static void
898 do_sendfd (assuan_context_t ctx, char *line)
899 {
900   estream_t fp;
901   char *name, *mode, *p;
902   int rc, fd;
903
904   /* Get file name. */
905   name = line;
906   for (p=name; *p && !spacep (p); p++)
907     ;
908   if (*p)
909     *p++ = 0;
910   while (spacep (p))
911     p++;
912
913   /* Get mode.  */
914   mode = p;
915   if (!*mode)
916     mode = "r";
917   else
918     {
919       for (p=mode; *p && !spacep (p); p++)
920         ;
921       if (*p)
922         *p++ = 0;
923     }
924
925   /* Open and send. */
926   fp = es_fopen (name, mode);
927   if (!fp)
928     {
929       log_error ("can't open '%s' in \"%s\" mode: %s\n",
930                  name, mode, strerror (errno));
931       return;
932     }
933   fd = es_fileno (fp);
934
935   if (opt.verbose)
936     log_error ("file '%s' opened in \"%s\" mode, fd=%d\n",
937                name, mode, fd);
938
939   rc = assuan_sendfd (ctx, INT2FD (fd) );
940   if (rc)
941     log_error ("sending descriptor %d failed: %s\n", fd, gpg_strerror (rc));
942   es_fclose (fp);
943 }
944
945
946 static void
947 do_recvfd (assuan_context_t ctx, char *line)
948 {
949   (void)ctx;
950   (void)line;
951   log_info ("This command has not yet been implemented\n");
952 }
953
954
955 static void
956 do_open (char *line)
957 {
958   estream_t fp;
959   char *varname, *name, *mode, *p;
960   int fd;
961
962 #ifdef HAVE_W32_SYSTEM
963   if (server_pid == (pid_t)(-1))
964     {
965       log_error ("the pid of the server is unknown\n");
966       log_info ("use command \"/serverpid\" first\n");
967       return;
968     }
969 #endif
970
971   /* Get variable name. */
972   varname = line;
973   for (p=varname; *p && !spacep (p); p++)
974     ;
975   if (*p)
976     *p++ = 0;
977   while (spacep (p))
978     p++;
979
980   /* Get file name. */
981   name = p;
982   for (p=name; *p && !spacep (p); p++)
983     ;
984   if (*p)
985     *p++ = 0;
986   while (spacep (p))
987     p++;
988
989   /* Get mode.  */
990   mode = p;
991   if (!*mode)
992     mode = "r";
993   else
994     {
995       for (p=mode; *p && !spacep (p); p++)
996         ;
997       if (*p)
998         *p++ = 0;
999     }
1000
1001   /* Open and send. */
1002   fp = es_fopen (name, mode);
1003   if (!fp)
1004     {
1005       log_error ("can't open '%s' in \"%s\" mode: %s\n",
1006                  name, mode, strerror (errno));
1007       return;
1008     }
1009   fd = dup (es_fileno (fp));
1010   if (fd >= 0 && fd < DIM (open_fd_table))
1011     {
1012       open_fd_table[fd].inuse = 1;
1013 #if defined(HAVE_W32_SYSTEM)
1014       {
1015         HANDLE prochandle, handle, newhandle;
1016
1017         handle = (void*)_get_osfhandle (fd);
1018
1019         prochandle = OpenProcess (PROCESS_DUP_HANDLE, FALSE, server_pid);
1020         if (!prochandle)
1021           {
1022             log_error ("failed to open the server process\n");
1023             close (fd);
1024             return;
1025           }
1026
1027         if (!DuplicateHandle (GetCurrentProcess(), handle,
1028                               prochandle, &newhandle, 0,
1029                               TRUE, DUPLICATE_SAME_ACCESS ))
1030           {
1031             log_error ("failed to duplicate the handle\n");
1032             close (fd);
1033             CloseHandle (prochandle);
1034             return;
1035           }
1036         CloseHandle (prochandle);
1037         open_fd_table[fd].handle = newhandle;
1038       }
1039       if (opt.verbose)
1040         log_info ("file '%s' opened in \"%s\" mode, fd=%d  (libc=%d)\n",
1041                    name, mode, (int)open_fd_table[fd].handle, fd);
1042       set_int_var (varname, (int)open_fd_table[fd].handle);
1043 #else /* Unix */
1044       if (opt.verbose)
1045         log_info ("file '%s' opened in \"%s\" mode, fd=%d\n",
1046                    name, mode, fd);
1047       set_int_var (varname, fd);
1048 #endif /* Unix */
1049     }
1050   else
1051     {
1052       log_error ("can't put fd %d into table\n", fd);
1053       if (fd != -1)
1054         close (fd); /* Table was full.  */
1055     }
1056   es_fclose (fp);
1057 }
1058
1059
1060 static void
1061 do_close (char *line)
1062 {
1063   int fd = atoi (line);
1064
1065 #ifdef HAVE_W32_SYSTEM
1066   int i;
1067
1068   for (i=0; i < DIM (open_fd_table); i++)
1069     if ( open_fd_table[i].inuse && open_fd_table[i].handle == (void*)fd)
1070       break;
1071   if (i < DIM (open_fd_table))
1072     fd = i;
1073   else
1074     {
1075       log_error ("given fd (system handle) has not been opened\n");
1076       return;
1077     }
1078 #endif
1079
1080   if (fd < 0 || fd >= DIM (open_fd_table))
1081     {
1082       log_error ("invalid fd\n");
1083       return;
1084     }
1085
1086   if (!open_fd_table[fd].inuse)
1087     {
1088       log_error ("given fd has not been opened\n");
1089       return;
1090     }
1091 #ifdef HAVE_W32_SYSTEM
1092   CloseHandle (open_fd_table[fd].handle); /* Close duped handle.  */
1093 #endif
1094   close (fd);
1095   open_fd_table[fd].inuse = 0;
1096 }
1097
1098
1099 static void
1100 do_showopen (void)
1101 {
1102   int i;
1103
1104   for (i=0; i < DIM (open_fd_table); i++)
1105     if (open_fd_table[i].inuse)
1106       {
1107 #ifdef HAVE_W32_SYSTEM
1108         printf ("%-15d (libc=%d)\n", (int)open_fd_table[i].handle, i);
1109 #else
1110         printf ("%-15d\n", i);
1111 #endif
1112       }
1113 }
1114
1115
1116
1117 static gpg_error_t
1118 getinfo_pid_cb (void *opaque, const void *buffer, size_t length)
1119 {
1120   membuf_t *mb = opaque;
1121   put_membuf (mb, buffer, length);
1122   return 0;
1123 }
1124
1125 /* Get the pid of the server and store it locally.  */
1126 static void
1127 do_serverpid (assuan_context_t ctx)
1128 {
1129   int rc;
1130   membuf_t mb;
1131   char *buffer;
1132
1133   init_membuf (&mb, 100);
1134   rc = assuan_transact (ctx, "GETINFO pid", getinfo_pid_cb, &mb,
1135                         NULL, NULL, NULL, NULL);
1136   put_membuf (&mb, "", 1);
1137   buffer = get_membuf (&mb, NULL);
1138   if (rc || !buffer)
1139     log_error ("command \"%s\" failed: %s\n",
1140                "GETINFO pid", gpg_strerror (rc));
1141   else
1142     {
1143       server_pid = (pid_t)strtoul (buffer, NULL, 10);
1144       if (opt.verbose)
1145         log_info ("server's PID is %lu\n", (unsigned long)server_pid);
1146     }
1147   xfree (buffer);
1148 }
1149
1150
1151 /* Return true if the command is either "HELP" or "SCD HELP".  */
1152 static int
1153 help_cmd_p (const char *line)
1154 {
1155   if (!ascii_strncasecmp (line, "SCD", 3)
1156       && (spacep (line+3) || !line[3]))
1157     {
1158       for (line += 3; spacep (line); line++)
1159         ;
1160     }
1161
1162   return (!ascii_strncasecmp (line, "HELP", 4)
1163           && (spacep (line+4) || !line[4]));
1164 }
1165
1166
1167 /* gpg-connect-agent's entry point. */
1168 int
1169 main (int argc, char **argv)
1170 {
1171   gpgrt_argparse_t pargs;
1172   int no_more_options = 0;
1173   assuan_context_t ctx;
1174   char *line, *p;
1175   char *tmpline;
1176   size_t linesize;
1177   int rc;
1178   int cmderr;
1179   const char *opt_run = NULL;
1180   gpgrt_stream_t script_fp = NULL;
1181   int use_tty, keep_line;
1182   struct {
1183     int collecting;
1184     loopline_t head;
1185     loopline_t *tail;
1186     loopline_t current;
1187     unsigned int nestlevel;
1188     int oneshot;
1189     char *condition;
1190   } loopstack[20];
1191   int        loopidx;
1192   char **cmdline_commands = NULL;
1193   char *historyname = NULL;
1194
1195   static const char *changeuser;
1196
1197
1198   early_system_init ();
1199   gnupg_rl_initialize ();
1200   gpgrt_set_strusage (my_strusage);
1201   log_set_prefix ("gpg-connect-agent",
1202                   GPGRT_LOG_WITH_PREFIX|GPGRT_LOG_NO_REGISTRY);
1203
1204   /* Make sure that our subsystems are ready.  */
1205   i18n_init();
1206   init_common_subsystems (&argc, &argv);
1207
1208   assuan_set_gpg_err_source (0);
1209
1210   gnupg_init_signals (0, NULL);
1211
1212   opt.autostart = 1;
1213   opt.connect_flags = 1;
1214
1215   /* Parse the command line. */
1216   pargs.argc  = &argc;
1217   pargs.argv  = &argv;
1218   pargs.flags = ARGPARSE_FLAG_KEEP;
1219   while (!no_more_options && gpgrt_argparse (NULL, &pargs, opts))
1220     {
1221       switch (pargs.r_opt)
1222         {
1223         case oQuiet:     opt.quiet = 1; break;
1224         case oVerbose:   opt.verbose++; break;
1225         case oNoVerbose: opt.verbose = 0; break;
1226         case oHomedir:   gnupg_set_homedir (pargs.r.ret_str); break;
1227         case oAgentProgram: opt.agent_program = pargs.r.ret_str;  break;
1228         case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str;  break;
1229         case oKeyboxdProgram: opt.keyboxd_program = pargs.r.ret_str;  break;
1230         case oNoAutostart:    opt.autostart = 0; break;
1231         case oNoHistory: opt.no_history = 1; break;
1232         case oHex:       opt.hex = 1; break;
1233         case oDecode:    opt.decode = 1; break;
1234         case oDirmngr:   opt.use_dirmngr = 1; break;
1235         case oKeyboxd:   opt.use_keyboxd = 1; break;
1236         case oUIServer:  opt.use_uiserver = 1; break;
1237         case oRawSocket: opt.raw_socket = pargs.r.ret_str; break;
1238         case oTcpSocket: opt.tcp_socket = pargs.r.ret_str; break;
1239         case oExec:      opt.exec = 1; break;
1240         case oNoExtConnect: opt.connect_flags &= ~(1); break;
1241         case oRun:       opt_run = pargs.r.ret_str; break;
1242         case oSubst:
1243           opt.enable_varsubst = 1;
1244           opt.trim_leading_spaces = 1;
1245           break;
1246         case oChUid:     changeuser = pargs.r.ret_str; break;
1247         case oUnBuffered: opt.unbuffered = 1; break;
1248
1249         default: pargs.err = 2; break;
1250         }
1251     }
1252   gpgrt_argparse (NULL, &pargs, NULL);  /* Release internal state.  */
1253
1254   if (changeuser && gnupg_chuid (changeuser, 0))
1255     log_inc_errorcount (); /* Force later termination.  */
1256
1257   if (log_get_errorcount (0))
1258     exit (2);
1259
1260   /* Process common component options.  Note that we set the config
1261    * dir only here so that --homedir will have an effect.  */
1262   gpgrt_set_confdir (GPGRT_CONFDIR_SYS, gnupg_sysconfdir ());
1263   gpgrt_set_confdir (GPGRT_CONFDIR_USER, gnupg_homedir ());
1264   if (parse_comopt (GNUPG_MODULE_NAME_CONNECT_AGENT, opt.verbose > 1))
1265     exit(2);
1266
1267   if (comopt.no_autostart)
1268      opt.autostart = 0;
1269
1270   /* --uiserver is a shortcut for a specific raw socket.  This comes
1271        in particular handy on Windows. */
1272   if (opt.use_uiserver)
1273     {
1274       opt.raw_socket = make_absfilename (gnupg_homedir (), "S.uiserver", NULL);
1275     }
1276
1277   /* Print a warning if an argument looks like an option.  */
1278   if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
1279     {
1280       int i;
1281
1282       for (i=0; i < argc; i++)
1283         if (argv[i][0] == '-' && argv[i][1] == '-')
1284           log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
1285     }
1286
1287
1288   use_tty = (gnupg_isatty (fileno (stdin)) && gnupg_isatty (fileno (stdout)));
1289
1290   if (opt.exec)
1291     {
1292       if (!argc)
1293         {
1294           log_error (_("option \"%s\" requires a program "
1295                        "and optional arguments\n"), "--exec" );
1296           exit (1);
1297         }
1298     }
1299   else if (argc)
1300     cmdline_commands = argv;
1301
1302   if (opt.exec && opt.raw_socket)
1303     {
1304       opt.raw_socket = NULL;
1305       log_info (_("option \"%s\" ignored due to \"%s\"\n"),
1306                 "--raw-socket", "--exec");
1307     }
1308   if (opt.exec && opt.tcp_socket)
1309     {
1310       opt.tcp_socket = NULL;
1311       log_info (_("option \"%s\" ignored due to \"%s\"\n"),
1312                 "--tcp-socket", "--exec");
1313     }
1314   if (opt.tcp_socket && opt.raw_socket)
1315     {
1316       opt.tcp_socket = NULL;
1317       log_info (_("option \"%s\" ignored due to \"%s\"\n"),
1318                 "--tcp-socket", "--raw-socket");
1319     }
1320
1321   if (opt_run && !(script_fp = gpgrt_fopen (opt_run, "r")))
1322     {
1323       log_error ("cannot open run file '%s': %s\n",
1324                  opt_run, strerror (errno));
1325       exit (1);
1326     }
1327
1328
1329   if (opt.exec)
1330     {
1331       assuan_fd_t no_close[3];
1332
1333       no_close[0] = assuan_fd_from_posix_fd (es_fileno (es_stderr));
1334       no_close[1] = ASSUAN_INVALID_FD;
1335
1336       rc = assuan_new (&ctx);
1337       if (rc)
1338         {
1339           log_error ("assuan_new failed: %s\n", gpg_strerror (rc));
1340           exit (1);
1341         }
1342
1343       rc = assuan_pipe_connect
1344         (ctx, *argv, (const char **)argv, no_close, NULL, NULL,
1345          (opt.connect_flags & 1) ? ASSUAN_PIPE_CONNECT_FDPASSING : 0);
1346       if (rc)
1347         {
1348           log_error ("assuan_pipe_connect_ext failed: %s\n",
1349                      gpg_strerror (rc));
1350           exit (1);
1351         }
1352
1353       if (opt.verbose)
1354         log_info ("server '%s' started\n", *argv);
1355
1356     }
1357   else if (opt.raw_socket)
1358     {
1359       rc = assuan_new (&ctx);
1360       if (rc)
1361         {
1362           log_error ("assuan_new failed: %s\n", gpg_strerror (rc));
1363           exit (1);
1364         }
1365
1366       rc = assuan_socket_connect
1367         (ctx, opt.raw_socket, 0,
1368          (opt.connect_flags & 1) ? ASSUAN_SOCKET_CONNECT_FDPASSING : 0);
1369       if (rc)
1370         {
1371           log_error ("can't connect to socket '%s': %s\n",
1372                      opt.raw_socket, gpg_strerror (rc));
1373           exit (1);
1374         }
1375
1376       if (opt.verbose)
1377         log_info ("connection to socket '%s' established\n", opt.raw_socket);
1378     }
1379   else if (opt.tcp_socket)
1380     {
1381       char *url;
1382
1383       url = xstrconcat ("assuan://", opt.tcp_socket, NULL);
1384
1385       rc = assuan_new (&ctx);
1386       if (rc)
1387         {
1388           log_error ("assuan_new failed: %s\n", gpg_strerror (rc));
1389           exit (1);
1390         }
1391
1392       rc = assuan_socket_connect (ctx, opt.tcp_socket, 0, 0);
1393       if (rc)
1394         {
1395           log_error ("can't connect to server '%s': %s\n",
1396                      opt.tcp_socket, gpg_strerror (rc));
1397           exit (1);
1398         }
1399
1400       if (opt.verbose)
1401         log_info ("connection to socket '%s' established\n", url);
1402
1403       xfree (url);
1404     }
1405   else
1406     ctx = start_agent ();
1407
1408   /* See whether there is a line pending from the server (in case
1409      assuan did not run the initial handshaking).  */
1410   if (assuan_pending_line (ctx))
1411     {
1412       rc = read_and_print_response (ctx, 0, &cmderr);
1413       if (rc)
1414         log_info (_("receiving line failed: %s\n"), gpg_strerror (rc) );
1415     }
1416
1417   if (!script_fp && opt.unbuffered)
1418     {
1419       gpgrt_setvbuf (gpgrt_stdin, NULL, _IONBF, 0);
1420       setvbuf (stdout, NULL, _IONBF, 0);
1421     }
1422
1423   for (loopidx=0; loopidx < DIM (loopstack); loopidx++)
1424     loopstack[loopidx].collecting = 0;
1425   loopidx = -1;
1426   line = NULL;
1427   linesize = 0;
1428   keep_line = 1;
1429   for (;;)
1430     {
1431       int n;
1432       size_t maxlength = 2048;
1433
1434       assert (loopidx < (int)DIM (loopstack));
1435       if (loopidx >= 0 && loopstack[loopidx].current)
1436         {
1437           keep_line = 0;
1438           xfree (line);
1439           line = xstrdup (loopstack[loopidx].current->line);
1440           n = strlen (line);
1441           /* Never go beyond of the final /end.  */
1442           if (loopstack[loopidx].current->next)
1443             loopstack[loopidx].current = loopstack[loopidx].current->next;
1444           else if (!strncmp (line, "/end", 4) && (!line[4]||spacep(line+4)))
1445             ;
1446           else
1447             log_fatal ("/end command vanished\n");
1448         }
1449       else if (cmdline_commands && *cmdline_commands && !script_fp)
1450         {
1451           keep_line = 0;
1452           xfree (line);
1453           line = xstrdup (*cmdline_commands);
1454           cmdline_commands++;
1455           n = strlen (line);
1456           if (n >= maxlength)
1457             maxlength = 0;
1458         }
1459       else if (use_tty && !script_fp)
1460         {
1461           keep_line = 0;
1462           xfree (line);
1463           if (!historyname && !opt.no_history)
1464             {
1465               historyname = make_filename (gnupg_homedir (), HISTORYNAME, NULL);
1466               if (tty_read_history (historyname, 500))
1467                 log_info ("error reading '%s': %s\n",
1468                           historyname,
1469                           gpg_strerror (gpg_error_from_syserror ()));
1470             }
1471
1472           line = tty_get ("> ");
1473           n = strlen (line);
1474           if (n==1 && *line == CONTROL_D)
1475             n = 0;
1476           if (n >= maxlength)
1477             maxlength = 0;
1478         }
1479       else
1480         {
1481           if (!keep_line)
1482             {
1483               xfree (line);
1484               line = NULL;
1485               linesize = 0;
1486               keep_line = 1;
1487             }
1488           n = gpgrt_read_line (script_fp ? script_fp : gpgrt_stdin,
1489                                &line, &linesize, &maxlength);
1490         }
1491       if (n < 0)
1492         {
1493           log_error (_("error reading input: %s\n"), strerror (errno));
1494           if (script_fp)
1495             {
1496               gpgrt_fclose (script_fp);
1497               script_fp = NULL;
1498               log_error ("stopping script execution\n");
1499               continue;
1500             }
1501           exit (1);
1502         }
1503       if (!n)
1504         {
1505           /* EOF */
1506           if (script_fp)
1507             {
1508               gpgrt_fclose (script_fp);
1509               script_fp = NULL;
1510               if (opt.verbose)
1511                 log_info ("end of script\n");
1512               continue;
1513             }
1514           break;
1515         }
1516       if (!maxlength)
1517         {
1518           log_error (_("line too long - skipped\n"));
1519           continue;
1520         }
1521       if (memchr (line, 0, n))
1522         log_info (_("line shortened due to embedded Nul character\n"));
1523       if (line[n-1] == '\n')
1524         line[n-1] = 0;
1525
1526       if (opt.trim_leading_spaces)
1527         {
1528           const char *s = line;
1529
1530           while (spacep (s))
1531             s++;
1532           if (s != line)
1533             {
1534               for (p=line; *s;)
1535                 *p++ = *s++;
1536               *p = 0;
1537               n = p - line;
1538             }
1539         }
1540
1541       if (loopidx+1 >= 0 && loopstack[loopidx+1].collecting)
1542         {
1543           loopline_t ll;
1544
1545           ll = xmalloc (sizeof *ll + strlen (line));
1546           ll->next = NULL;
1547           strcpy (ll->line, line);
1548           *loopstack[loopidx+1].tail = ll;
1549           loopstack[loopidx+1].tail = &ll->next;
1550
1551           if (!strncmp (line, "/end", 4) && (!line[4]||spacep(line+4)))
1552             loopstack[loopidx+1].nestlevel--;
1553           else if (!strncmp (line, "/while", 6) && (!line[6]||spacep(line+6)))
1554             loopstack[loopidx+1].nestlevel++;
1555
1556           if (loopstack[loopidx+1].nestlevel)
1557             continue;
1558           /* We reached the corresponding /end.  */
1559           loopstack[loopidx+1].collecting = 0;
1560           loopidx++;
1561         }
1562
1563       if (*line == '/')
1564         {
1565           /* Handle control commands. */
1566           char *cmd = line+1;
1567
1568           for (p=cmd; *p && !spacep (p); p++)
1569             ;
1570           if (*p)
1571             *p++ = 0;
1572           while (spacep (p))
1573             p++;
1574           if (!strcmp (cmd, "let"))
1575             {
1576               assign_variable (p, 0);
1577             }
1578           else if (!strcmp (cmd, "slet"))
1579             {
1580               /* Deprecated - never used in a released version.  */
1581               assign_variable (p, 1);
1582             }
1583           else if (!strcmp (cmd, "showvar"))
1584             {
1585               show_variables ();
1586             }
1587           else if (!strcmp (cmd, "definq"))
1588             {
1589               tmpline = opt.enable_varsubst? substitute_line (p) : NULL;
1590               if (tmpline)
1591                 {
1592                   add_definq (tmpline, 1, 0);
1593                   xfree (tmpline);
1594                 }
1595               else
1596                 add_definq (p, 1, 0);
1597             }
1598           else if (!strcmp (cmd, "definqfile"))
1599             {
1600               tmpline = opt.enable_varsubst? substitute_line (p) : NULL;
1601               if (tmpline)
1602                 {
1603                   add_definq (tmpline, 0, 0);
1604                   xfree (tmpline);
1605                 }
1606               else
1607                 add_definq (p, 0, 0);
1608             }
1609           else if (!strcmp (cmd, "definqprog"))
1610             {
1611               tmpline = opt.enable_varsubst? substitute_line (p) : NULL;
1612               if (tmpline)
1613                 {
1614                   add_definq (tmpline, 0, 1);
1615                   xfree (tmpline);
1616                 }
1617               else
1618                 add_definq (p, 0, 1);
1619             }
1620           else if (!strcmp (cmd, "datafile"))
1621             {
1622               const char *fname;
1623
1624               if (current_datasink)
1625                 {
1626                   if (current_datasink != es_stdout)
1627                     es_fclose (current_datasink);
1628                   current_datasink = NULL;
1629                 }
1630               tmpline = opt.enable_varsubst? substitute_line (p) : NULL;
1631               fname = tmpline? tmpline : p;
1632               if (fname && !strcmp (fname, "-"))
1633                 current_datasink = es_stdout;
1634               else if (fname && *fname)
1635                 {
1636                   current_datasink = es_fopen (fname, "wb");
1637                   if (!current_datasink)
1638                     log_error ("can't open '%s': %s\n",
1639                                fname, strerror (errno));
1640                 }
1641               xfree (tmpline);
1642             }
1643           else if (!strcmp (cmd, "showdef"))
1644             {
1645               show_definq ();
1646             }
1647           else if (!strcmp (cmd, "cleardef"))
1648             {
1649               clear_definq ();
1650             }
1651           else if (!strcmp (cmd, "echo"))
1652             {
1653               tmpline = opt.enable_varsubst? substitute_line (p) : NULL;
1654               if (tmpline)
1655                 {
1656                   puts (tmpline);
1657                   xfree (tmpline);
1658                 }
1659               else
1660                 puts (p);
1661             }
1662           else if (!strcmp (cmd, "sendfd"))
1663             {
1664               tmpline = opt.enable_varsubst? substitute_line (p) : NULL;
1665               if (tmpline)
1666                 {
1667                   do_sendfd (ctx, tmpline);
1668                   xfree (tmpline);
1669                 }
1670               else
1671                 do_sendfd (ctx, p);
1672               continue;
1673             }
1674           else if (!strcmp (cmd, "recvfd"))
1675             {
1676               tmpline = opt.enable_varsubst? substitute_line (p) : NULL;
1677               if (tmpline)
1678                 {
1679                   do_recvfd (ctx, tmpline);
1680                   xfree (tmpline);
1681                 }
1682               else
1683                 do_recvfd (ctx, p);
1684               continue;
1685             }
1686           else if (!strcmp (cmd, "open"))
1687             {
1688               tmpline = opt.enable_varsubst? substitute_line (p) : NULL;
1689               if (tmpline)
1690                 {
1691                   do_open (tmpline);
1692                   xfree (tmpline);
1693                 }
1694               else
1695                 do_open (p);
1696             }
1697           else if (!strcmp (cmd, "close"))
1698             {
1699               tmpline = opt.enable_varsubst? substitute_line (p) : NULL;
1700               if (tmpline)
1701                 {
1702                   do_close (tmpline);
1703                   xfree (tmpline);
1704                 }
1705               else
1706                 do_close (p);
1707             }
1708           else if (!strcmp (cmd, "showopen"))
1709             {
1710               do_showopen ();
1711             }
1712           else if (!strcmp (cmd, "serverpid"))
1713             {
1714               do_serverpid (ctx);
1715             }
1716           else if (!strcmp (cmd, "hex"))
1717             opt.hex = 1;
1718           else if (!strcmp (cmd, "nohex"))
1719             opt.hex = 0;
1720           else if (!strcmp (cmd, "decode"))
1721             opt.decode = 1;
1722           else if (!strcmp (cmd, "nodecode"))
1723             opt.decode = 0;
1724           else if (!strcmp (cmd, "subst"))
1725             {
1726               opt.enable_varsubst = 1;
1727               opt.trim_leading_spaces = 1;
1728             }
1729           else if (!strcmp (cmd, "nosubst"))
1730             opt.enable_varsubst = 0;
1731           else if (!strcmp (cmd, "run"))
1732             {
1733               char *p2;
1734
1735               for (p2=p; *p2 && !spacep (p2); p2++)
1736                 ;
1737               if (*p2)
1738                 *p2++ = 0;
1739               while (spacep (p2))
1740                 p++;
1741               if (*p2)
1742                 {
1743                   log_error ("syntax error in run command\n");
1744                   if (script_fp)
1745                     {
1746                       gpgrt_fclose (script_fp);
1747                       script_fp = NULL;
1748                     }
1749                 }
1750               else if (script_fp)
1751                 {
1752                   log_error ("cannot nest run commands - stop\n");
1753                   gpgrt_fclose (script_fp);
1754                   script_fp = NULL;
1755                 }
1756               else if (!(script_fp = gpgrt_fopen (p, "r")))
1757                 {
1758                   log_error ("cannot open run file '%s': %s\n",
1759                              p, strerror (errno));
1760                 }
1761               else if (opt.verbose)
1762                 log_info ("running commands from '%s'\n", p);
1763             }
1764           else if (!strcmp (cmd, "while"))
1765             {
1766               if (loopidx+2 >= (int)DIM(loopstack))
1767                 {
1768                   log_error ("blocks are nested too deep\n");
1769                   /* We should better die or break all loop in this
1770                      case as recovering from this error won't be
1771                      easy.  */
1772                 }
1773               else
1774                 {
1775                   loopstack[loopidx+1].head = NULL;
1776                   loopstack[loopidx+1].tail = &loopstack[loopidx+1].head;
1777                   loopstack[loopidx+1].current = NULL;
1778                   loopstack[loopidx+1].nestlevel = 1;
1779                   loopstack[loopidx+1].oneshot = 0;
1780                   loopstack[loopidx+1].condition = xstrdup (p);
1781                   loopstack[loopidx+1].collecting = 1;
1782                 }
1783             }
1784           else if (!strcmp (cmd, "if"))
1785             {
1786               if (loopidx+2 >= (int)DIM(loopstack))
1787                 {
1788                   log_error ("blocks are nested too deep\n");
1789                 }
1790               else
1791                 {
1792                   /* Note that we need to evaluate the condition right
1793                      away and not just at the end of the block as we
1794                      do with a WHILE. */
1795                   loopstack[loopidx+1].head = NULL;
1796                   loopstack[loopidx+1].tail = &loopstack[loopidx+1].head;
1797                   loopstack[loopidx+1].current = NULL;
1798                   loopstack[loopidx+1].nestlevel = 1;
1799                   loopstack[loopidx+1].oneshot = 1;
1800                   loopstack[loopidx+1].condition = substitute_line_copy (p);
1801                   loopstack[loopidx+1].collecting = 1;
1802                 }
1803             }
1804           else if (!strcmp (cmd, "end"))
1805             {
1806               if (loopidx < 0)
1807                 log_error ("stray /end command encountered - ignored\n");
1808               else
1809                 {
1810                   char *tmpcond;
1811                   const char *value;
1812                   long condition;
1813
1814                   /* Evaluate the condition.  */
1815                   tmpcond = xstrdup (loopstack[loopidx].condition);
1816                   if (loopstack[loopidx].oneshot)
1817                     {
1818                       xfree (loopstack[loopidx].condition);
1819                       loopstack[loopidx].condition = xstrdup ("0");
1820                     }
1821                   tmpline = substitute_line (tmpcond);
1822                   value = tmpline? tmpline : tmpcond;
1823                   /* "true" or "yes" are commonly used to mean TRUE;
1824                      all other strings will evaluate to FALSE due to
1825                      the strtoul.  */
1826                   if (!ascii_strcasecmp (value, "true")
1827                       || !ascii_strcasecmp (value, "yes"))
1828                     condition = 1;
1829                   else
1830                     condition = strtol (value, NULL, 0);
1831                   xfree (tmpline);
1832                   xfree (tmpcond);
1833
1834                   if (condition)
1835                     {
1836                       /* Run loop.  */
1837                       loopstack[loopidx].current = loopstack[loopidx].head;
1838                     }
1839                   else
1840                     {
1841                       /* Cleanup.  */
1842                       while (loopstack[loopidx].head)
1843                         {
1844                           loopline_t tmp = loopstack[loopidx].head->next;
1845                           xfree (loopstack[loopidx].head);
1846                           loopstack[loopidx].head = tmp;
1847                         }
1848                       loopstack[loopidx].tail = NULL;
1849                       loopstack[loopidx].current = NULL;
1850                       loopstack[loopidx].nestlevel = 0;
1851                       loopstack[loopidx].collecting = 0;
1852                       loopstack[loopidx].oneshot = 0;
1853                       xfree (loopstack[loopidx].condition);
1854                       loopstack[loopidx].condition = NULL;
1855                       loopidx--;
1856                     }
1857                 }
1858             }
1859           else if (!strcmp (cmd, "bye") || !strcmp (cmd, "quit"))
1860             {
1861               break;
1862             }
1863           else if (!strcmp (cmd, "sleep"))
1864             {
1865               gnupg_sleep (1);
1866             }
1867           else if (!strcmp (cmd, "history"))
1868             {
1869               if (!strcmp (p, "--clear"))
1870                 {
1871                   tty_read_history (NULL, 0);
1872                 }
1873               else
1874                 log_error ("Only \"/history --clear\" is supported\n");
1875             }
1876           else if (!strcmp (cmd, "help"))
1877             {
1878               puts (
1879 "Available commands:\n"
1880 "/echo ARGS             Echo ARGS.\n"
1881 "/let  NAME VALUE       Set variable NAME to VALUE.\n"
1882 "/showvar               Show all variables.\n"
1883 "/definq NAME VAR       Use content of VAR for inquiries with NAME.\n"
1884 "/definqfile NAME FILE  Use content of FILE for inquiries with NAME.\n"
1885 "/definqprog NAME PGM   Run PGM for inquiries with NAME.\n"
1886 "/datafile [NAME]       Write all D line content to file NAME.\n"
1887 "/showdef               Print all definitions.\n"
1888 "/cleardef              Delete all definitions.\n"
1889 "/sendfd FILE MODE      Open FILE and pass descriptor to server.\n"
1890 "/recvfd                Receive FD from server and print.\n"
1891 "/open VAR FILE MODE    Open FILE and assign the file descriptor to VAR.\n"
1892 "/close FD              Close file with descriptor FD.\n"
1893 "/showopen              Show descriptors of all open files.\n"
1894 "/serverpid             Retrieve the pid of the server.\n"
1895 "/[no]hex               Enable hex dumping of received data lines.\n"
1896 "/[no]decode            Enable decoding of received data lines.\n"
1897 "/[no]subst             Enable variable substitution.\n"
1898 "/run FILE              Run commands from FILE.\n"
1899 "/if VAR                Begin conditional block controlled by VAR.\n"
1900 "/while VAR             Begin loop controlled by VAR.\n"
1901 "/end                   End loop or condition\n"
1902 "/history               Manage the history\n"
1903 "/bye                   Terminate gpg-connect-agent.\n"
1904 "/help                  Print this help.");
1905             }
1906           else
1907             log_error (_("unknown command '%s'\n"), cmd );
1908
1909           continue;
1910         }
1911
1912       if (opt.verbose && script_fp)
1913         puts (line);
1914
1915       tmpline = opt.enable_varsubst? substitute_line (line) : NULL;
1916       if (tmpline)
1917         {
1918           rc = assuan_write_line (ctx, tmpline);
1919           xfree (tmpline);
1920         }
1921       else
1922         rc = assuan_write_line (ctx, line);
1923       if (rc)
1924         {
1925           log_info (_("sending line failed: %s\n"), gpg_strerror (rc) );
1926           break;
1927         }
1928       if (*line == '#' || !*line)
1929         continue; /* Don't expect a response for a comment line. */
1930
1931       rc = read_and_print_response (ctx, help_cmd_p (line), &cmderr);
1932       if (rc)
1933         log_info (_("receiving line failed: %s\n"), gpg_strerror (rc) );
1934       if ((rc || cmderr) && script_fp)
1935         {
1936           log_error ("stopping script execution\n");
1937           gpgrt_fclose (script_fp);
1938           script_fp = NULL;
1939         }
1940
1941
1942       /* FIXME: If the last command was BYE or the server died for
1943          some other reason, we won't notice until we get the next
1944          input command.  Probing the connection with a non-blocking
1945          read could help to notice termination or other problems
1946          early.  */
1947     }
1948
1949   if (opt.verbose)
1950     log_info ("closing connection to %s\n",
1951               opt.use_dirmngr? "dirmngr" :
1952               opt.use_keyboxd? "keyboxd" :
1953               "agent");
1954
1955
1956   if (historyname && tty_write_history (historyname))
1957     log_info ("error writing '%s': %s\n",
1958               historyname, gpg_strerror (gpg_error_from_syserror ()));
1959
1960
1961   /* XXX: We would like to release the context here, but libassuan
1962      nicely says good bye to the server, which results in a SIGPIPE if
1963      the server died.  Unfortunately, libassuan does not ignore
1964      SIGPIPE when used with UNIX sockets, hence we simply leak the
1965      context here.  */
1966   if (0)
1967     assuan_release (ctx);
1968   else
1969     gpgrt_annotate_leaked_object (ctx);
1970   xfree (historyname);
1971   xfree (line);
1972   return 0;
1973 }
1974
1975
1976 /* Handle an Inquire from the server.  Return False if it could not be
1977    handled; in this case the caller shll complete the operation.  LINE
1978    is the complete line as received from the server.  This function
1979    may change the content of LINE. */
1980 static int
1981 handle_inquire (assuan_context_t ctx, char *line)
1982 {
1983   const char *name;
1984   definq_t d;
1985   /* FIXME: Due to the use of popen we can't easily switch to estream.  */
1986   FILE *fp = NULL;
1987   char buffer[1024];
1988   int rc, n;
1989   int cancelled = 0;
1990
1991   /* Skip the command and trailing spaces. */
1992   for (; *line && !spacep (line); line++)
1993     ;
1994   while (spacep (line))
1995     line++;
1996   /* Get the name. */
1997   name = line;
1998   for (; *line && !spacep (line); line++)
1999     ;
2000   if (*line)
2001     *line++ = 0;
2002
2003   /* Now match it against our list.  The second loop is there to
2004      detect the match-all entry. */
2005   for (d=definq_list; d; d = d->next)
2006     if (d->name && !strcmp (d->name, name))
2007         break;
2008   if (!d)
2009     for (d=definq_list; d; d = d->next)
2010       if (!d->name)
2011         break;
2012   if (!d)
2013     {
2014       if (opt.verbose)
2015         log_info ("no handler for inquiry '%s' found\n", name);
2016       return 0;
2017     }
2018
2019   if (d->is_var)
2020     {
2021       char *tmpvalue = get_var_ext (d->file);
2022       if (tmpvalue)
2023         rc = assuan_send_data (ctx, tmpvalue, strlen (tmpvalue));
2024       else
2025         rc = assuan_send_data (ctx, "", 0);
2026       xfree (tmpvalue);
2027       if (rc)
2028         log_error ("sending data back failed: %s\n", gpg_strerror (rc) );
2029     }
2030   else
2031     {
2032       if (d->is_prog)
2033         {
2034           fp = popen (d->file, "r");
2035           if (!fp)
2036             log_error ("error executing '%s': %s\n",
2037                        d->file, strerror (errno));
2038           else if (opt.verbose)
2039             log_error ("handling inquiry '%s' by running '%s'\n",
2040                        name, d->file);
2041         }
2042       else
2043         {
2044           fp = fopen (d->file, "rb");
2045           if (!fp)
2046             log_error ("error opening '%s': %s\n", d->file, strerror (errno));
2047           else if (opt.verbose)
2048             log_error ("handling inquiry '%s' by returning content of '%s'\n",
2049                        name, d->file);
2050         }
2051       if (!fp)
2052         return 0;
2053
2054       while ( (n = fread (buffer, 1, sizeof buffer, fp)) )
2055         {
2056           rc = assuan_send_data (ctx, buffer, n);
2057           if (rc)
2058             {
2059               log_error ("sending data back failed: %s\n", gpg_strerror (rc) );
2060               break;
2061             }
2062         }
2063       if (ferror (fp))
2064         log_error ("error reading from '%s': %s\n", d->file, strerror (errno));
2065     }
2066
2067   if (d->is_var)
2068     ;
2069   else if (d->is_prog)
2070     {
2071       if (pclose (fp))
2072         cancelled = 1;
2073     }
2074   else
2075     fclose (fp);
2076
2077   rc = assuan_send_data (ctx, NULL, cancelled);
2078   if (rc)
2079     log_error ("sending data back failed: %s\n", gpg_strerror (rc) );
2080
2081   return 1;
2082 }
2083
2084
2085 /* Read all response lines from server and print them.  Returns 0 on
2086    success or an assuan error code.  If WITHHASH istrue, comment lines
2087    are printed.  Sets R_GOTERR to true if the command did not returned
2088    OK.  */
2089 static int
2090 read_and_print_response (assuan_context_t ctx, int withhash, int *r_goterr)
2091 {
2092   char *line;
2093   size_t linelen;
2094   gpg_error_t rc;
2095   int i, j;
2096   int need_lf = 0;
2097
2098   *r_goterr = 0;
2099   for (;;)
2100     {
2101       do
2102         {
2103           rc = assuan_read_line (ctx, &line, &linelen);
2104           if (rc)
2105             return rc;
2106
2107           if ((withhash || opt.verbose > 1) && *line == '#')
2108             {
2109               fwrite (line, linelen, 1, stdout);
2110               putchar ('\n');
2111             }
2112         }
2113       while (*line == '#' || !linelen);
2114
2115       if (linelen >= 1
2116           && line[0] == 'D' && line[1] == ' ')
2117         {
2118           if (current_datasink)
2119             {
2120               const unsigned char *s;
2121               int c = 0;
2122
2123               for (j=2, s=(unsigned char*)line+2; j < linelen; j++, s++ )
2124                 {
2125                   if (*s == '%' && j+2 < linelen)
2126                     {
2127                       s++; j++;
2128                       c = xtoi_2 ( s );
2129                       s++; j++;
2130                     }
2131                   else
2132                     c = *s;
2133                   es_putc (c, current_datasink);
2134                 }
2135             }
2136           else if (opt.hex)
2137             {
2138               for (i=2; i < linelen; )
2139                 {
2140                   int save_i = i;
2141
2142                   printf ("D[%04X] ", i-2);
2143                   for (j=0; j < 16 ; j++, i++)
2144                     {
2145                       if (j == 8)
2146                         putchar (' ');
2147                       if (i < linelen)
2148                         printf (" %02X", ((unsigned char*)line)[i]);
2149                       else
2150                         fputs ("   ", stdout);
2151                     }
2152                   fputs ("   ", stdout);
2153                   i= save_i;
2154                   for (j=0; j < 16; j++, i++)
2155                     {
2156                       unsigned int c = ((unsigned char*)line)[i];
2157                       if ( i >= linelen )
2158                         putchar (' ');
2159                       else if (isascii (c) && isprint (c) && !iscntrl (c))
2160                         putchar (c);
2161                       else
2162                         putchar ('.');
2163                     }
2164                   putchar ('\n');
2165                 }
2166             }
2167           else if (opt.decode)
2168             {
2169               const unsigned char *s;
2170               int need_d = 1;
2171               int c = 0;
2172
2173               for (j=2, s=(unsigned char*)line+2; j < linelen; j++, s++ )
2174                 {
2175                   if (need_d)
2176                     {
2177                       fputs ("D ", stdout);
2178                       need_d = 0;
2179                     }
2180                   if (*s == '%' && j+2 < linelen)
2181                     {
2182                       s++; j++;
2183                       c = xtoi_2 ( s );
2184                       s++; j++;
2185                     }
2186                   else
2187                     c = *s;
2188                   if (c == '\n')
2189                     need_d = 1;
2190                   putchar (c);
2191                 }
2192               need_lf = (c != '\n');
2193             }
2194           else
2195             {
2196               fwrite (line, linelen, 1, stdout);
2197               putchar ('\n');
2198             }
2199         }
2200       else
2201         {
2202           if (need_lf)
2203             {
2204               if (!current_datasink || current_datasink != es_stdout)
2205                 putchar ('\n');
2206               need_lf = 0;
2207             }
2208
2209           if (linelen >= 1
2210               && line[0] == 'S'
2211               && (line[1] == '\0' || line[1] == ' '))
2212             {
2213               if (!current_datasink || current_datasink != es_stdout)
2214                 {
2215                   fwrite (line, linelen, 1, stdout);
2216                   putchar ('\n');
2217                 }
2218             }
2219           else if (linelen >= 2
2220                    && line[0] == 'O' && line[1] == 'K'
2221                    && (line[2] == '\0' || line[2] == ' '))
2222             {
2223               if (!current_datasink || current_datasink != es_stdout)
2224                 {
2225                   fwrite (line, linelen, 1, stdout);
2226                   putchar ('\n');
2227                 }
2228               set_int_var ("?", 0);
2229               return 0;
2230             }
2231           else if (linelen >= 3
2232                    && line[0] == 'E' && line[1] == 'R' && line[2] == 'R'
2233                    && (line[3] == '\0' || line[3] == ' '))
2234             {
2235               int errval;
2236
2237               errval = strtol (line+3, NULL, 10);
2238               if (!errval)
2239                 errval = -1;
2240               set_int_var ("?", errval);
2241               if (!current_datasink || current_datasink != es_stdout)
2242                 {
2243                   fwrite (line, linelen, 1, stdout);
2244                   putchar ('\n');
2245                 }
2246               *r_goterr = 1;
2247               return 0;
2248             }
2249           else if (linelen >= 7
2250                    && line[0] == 'I' && line[1] == 'N' && line[2] == 'Q'
2251                    && line[3] == 'U' && line[4] == 'I' && line[5] == 'R'
2252                    && line[6] == 'E'
2253                    && (line[7] == '\0' || line[7] == ' '))
2254             {
2255               if (!current_datasink || current_datasink != es_stdout)
2256                 {
2257                   fwrite (line, linelen, 1, stdout);
2258                   putchar ('\n');
2259                 }
2260               if (!handle_inquire (ctx, line))
2261                 assuan_write_line (ctx, "CANCEL");
2262             }
2263           else if (linelen >= 3
2264                    && line[0] == 'E' && line[1] == 'N' && line[2] == 'D'
2265                    && (line[3] == '\0' || line[3] == ' '))
2266             {
2267               if (!current_datasink || current_datasink != es_stdout)
2268                 {
2269                   fwrite (line, linelen, 1, stdout);
2270                   putchar ('\n');
2271                 }
2272               /* Received from server, thus more responses are expected.  */
2273             }
2274           else
2275             return gpg_error (GPG_ERR_ASS_INV_RESPONSE);
2276         }
2277     }
2278 }
2279
2280
2281
2282
2283 /* Connect to the agent and send the standard options.  */
2284 static assuan_context_t
2285 start_agent (void)
2286 {
2287   gpg_error_t err;
2288   assuan_context_t ctx;
2289   session_env_t session_env;
2290
2291   session_env = session_env_new ();
2292   if (!session_env)
2293     log_fatal ("error allocating session environment block: %s\n",
2294                strerror (errno));
2295   if (opt.use_dirmngr)
2296     err = start_new_dirmngr (&ctx,
2297                              GPG_ERR_SOURCE_DEFAULT,
2298                              opt.dirmngr_program,
2299                              opt.autostart,
2300                              !opt.quiet, 0,
2301                              NULL, NULL);
2302   else if (opt.use_keyboxd)
2303     err = start_new_keyboxd (&ctx,
2304                              GPG_ERR_SOURCE_DEFAULT,
2305                              opt.keyboxd_program,
2306                              opt.autostart,
2307                              !opt.quiet, 0,
2308                              NULL, NULL);
2309   else
2310     err = start_new_gpg_agent (&ctx,
2311                                GPG_ERR_SOURCE_DEFAULT,
2312                                opt.agent_program,
2313                                NULL, NULL,
2314                                session_env,
2315                                opt.autostart,
2316                                !opt.quiet, 0,
2317                                NULL, NULL);
2318
2319   session_env_release (session_env);
2320   if (err)
2321     {
2322       if (!opt.autostart
2323           && (gpg_err_code (err)
2324               == (opt.use_dirmngr? GPG_ERR_NO_DIRMNGR :
2325                   opt.use_keyboxd? GPG_ERR_NO_KEYBOXD : GPG_ERR_NO_AGENT)))
2326         {
2327           /* In the no-autostart case we don't make gpg-connect-agent
2328              fail on a missing server.  */
2329           log_info (opt.use_dirmngr?
2330                     _("no dirmngr running in this session\n"):
2331                     opt.use_keyboxd?
2332                     _("no keybox daemon running in this session\n"):
2333                     _("no gpg-agent running in this session\n"));
2334           exit (0);
2335         }
2336       else
2337         {
2338           log_error (_("error sending standard options: %s\n"),
2339                      gpg_strerror (err));
2340           exit (1);
2341         }
2342     }
2343
2344   return ctx;
2345 }