chiark / gitweb /
dirmngr: Drop useless housekeeping.
[gnupg2.git] / g10 / call-agent.c
1 /* call-agent.c - Divert GPG operations to the agent.
2  * Copyright (C) 2001-2003, 2006-2011, 2013 Free Software Foundation, Inc.
3  * Copyright (C) 2013-2015  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  */
20
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <unistd.h>
27 #include <time.h>
28 #ifdef HAVE_LOCALE_H
29 #include <locale.h>
30 #endif
31
32 #include "gpg.h"
33 #include <assuan.h>
34 #include "util.h"
35 #include "membuf.h"
36 #include "options.h"
37 #include "i18n.h"
38 #include "asshelp.h"
39 #include "sysutils.h"
40 #include "call-agent.h"
41 #include "status.h"
42 #include "../common/shareddefs.h"
43 #include "host2net.h"
44
45 #define CONTROL_D ('D' - 'A' + 1)
46
47
48 static assuan_context_t agent_ctx = NULL;
49 static int did_early_card_test;
50
51 struct default_inq_parm_s
52 {
53   ctrl_t ctrl;
54   assuan_context_t ctx;
55   struct {
56     u32 *keyid;
57     u32 *mainkeyid;
58     int pubkey_algo;
59   } keyinfo;
60 };
61
62 struct cipher_parm_s
63 {
64   struct default_inq_parm_s *dflt;
65   assuan_context_t ctx;
66   unsigned char *ciphertext;
67   size_t ciphertextlen;
68 };
69
70 struct writecert_parm_s
71 {
72   struct default_inq_parm_s *dflt;
73   const unsigned char *certdata;
74   size_t certdatalen;
75 };
76
77 struct writekey_parm_s
78 {
79   struct default_inq_parm_s *dflt;
80   const unsigned char *keydata;
81   size_t keydatalen;
82 };
83
84 struct genkey_parm_s
85 {
86   struct default_inq_parm_s *dflt;
87   const char *keyparms;
88   const char *passphrase;
89 };
90
91 struct import_key_parm_s
92 {
93   struct default_inq_parm_s *dflt;
94   const void *key;
95   size_t keylen;
96 };
97
98
99 struct cache_nonce_parm_s
100 {
101   char **cache_nonce_addr;
102   char **passwd_nonce_addr;
103 };
104
105
106 static gpg_error_t learn_status_cb (void *opaque, const char *line);
107
108
109 \f
110 /* If RC is not 0, write an appropriate status message. */
111 static void
112 status_sc_op_failure (int rc)
113 {
114   switch (gpg_err_code (rc))
115     {
116     case 0:
117       break;
118     case GPG_ERR_CANCELED:
119     case GPG_ERR_FULLY_CANCELED:
120       write_status_text (STATUS_SC_OP_FAILURE, "1");
121       break;
122     case GPG_ERR_BAD_PIN:
123       write_status_text (STATUS_SC_OP_FAILURE, "2");
124       break;
125     default:
126       write_status (STATUS_SC_OP_FAILURE);
127       break;
128     }
129 }
130
131
132 /* This is the default inquiry callback.  It mainly handles the
133    Pinentry notifications.  */
134 static gpg_error_t
135 default_inq_cb (void *opaque, const char *line)
136 {
137   gpg_error_t err = 0;
138   struct default_inq_parm_s *parm = opaque;
139
140   if (has_leading_keyword (line, "PINENTRY_LAUNCHED"))
141     {
142       err = gpg_proxy_pinentry_notify (parm->ctrl, line);
143       if (err)
144         log_error (_("failed to proxy %s inquiry to client\n"),
145                    "PINENTRY_LAUNCHED");
146       /* We do not pass errors to avoid breaking other code.  */
147     }
148   else if ((has_leading_keyword (line, "PASSPHRASE")
149             || has_leading_keyword (line, "NEW_PASSPHRASE"))
150            && opt.pinentry_mode == PINENTRY_MODE_LOOPBACK)
151     {
152       if (have_static_passphrase ())
153         {
154           const char *s = get_static_passphrase ();
155           err = assuan_send_data (parm->ctx, s, strlen (s));
156         }
157       else
158         {
159           char *pw;
160           char buf[32];
161
162           if (parm->keyinfo.keyid)
163             emit_status_need_passphrase (parm->keyinfo.keyid,
164                                          parm->keyinfo.mainkeyid,
165                                          parm->keyinfo.pubkey_algo);
166
167           snprintf (buf, sizeof (buf), "%u", 100);
168           write_status_text (STATUS_INQUIRE_MAXLEN, buf);
169           pw = cpr_get_hidden ("passphrase.enter", _("Enter passphrase: "));
170           cpr_kill_prompt ();
171           if (*pw == CONTROL_D && !pw[1])
172             err = gpg_error (GPG_ERR_CANCELED);
173           else
174             err = assuan_send_data (parm->ctx, pw, strlen (pw));
175           xfree (pw);
176         }
177     }
178   else
179     log_debug ("ignoring gpg-agent inquiry '%s'\n", line);
180
181   return err;
182 }
183
184
185 /* Print a warning if the server's version number is less than our
186    version number.  Returns an error code on a connection problem.  */
187 static gpg_error_t
188 warn_version_mismatch (assuan_context_t ctx, const char *servername, int mode)
189 {
190   gpg_error_t err;
191   char *serverversion;
192   const char *myversion = strusage (13);
193
194   err = get_assuan_server_version (ctx, mode, &serverversion);
195   if (err)
196     log_error (_("error getting version from '%s': %s\n"),
197                servername, gpg_strerror (err));
198   else if (compare_version_strings (serverversion, myversion) < 0)
199     {
200       char *warn;
201
202       warn = xtryasprintf (_("server '%s' is older than us (%s < %s)"),
203                            servername, serverversion, myversion);
204       if (!warn)
205         err = gpg_error_from_syserror ();
206       else
207         {
208           log_info (_("WARNING: %s\n"), warn);
209           write_status_strings (STATUS_WARNING, "server_version_mismatch 0",
210                                 " ", warn, NULL);
211           xfree (warn);
212         }
213     }
214   xfree (serverversion);
215   return err;
216 }
217
218
219 /* Try to connect to the agent via socket or fork it off and work by
220    pipes.  Handle the server's initial greeting */
221 static int
222 start_agent (ctrl_t ctrl, int for_card)
223 {
224   int rc;
225
226   (void)ctrl;  /* Not yet used.  */
227
228   /* Fixme: We need a context for each thread or serialize the access
229      to the agent. */
230   if (agent_ctx)
231     rc = 0;
232   else
233     {
234       rc = start_new_gpg_agent (&agent_ctx,
235                                 GPG_ERR_SOURCE_DEFAULT,
236                                 opt.agent_program,
237                                 opt.lc_ctype, opt.lc_messages,
238                                 opt.session_env,
239                                 opt.autostart, opt.verbose, DBG_IPC,
240                                 NULL, NULL);
241       if (!opt.autostart && gpg_err_code (rc) == GPG_ERR_NO_AGENT)
242         {
243           static int shown;
244
245           if (!shown)
246             {
247               shown = 1;
248               log_info (_("no gpg-agent running in this session\n"));
249             }
250         }
251       else if (!rc
252                && !(rc = warn_version_mismatch (agent_ctx, GPG_AGENT_NAME, 0)))
253         {
254           /* Tell the agent that we support Pinentry notifications.
255              No error checking so that it will work also with older
256              agents.  */
257           assuan_transact (agent_ctx, "OPTION allow-pinentry-notify",
258                            NULL, NULL, NULL, NULL, NULL, NULL);
259           /* Tell the agent about what version we are aware.  This is
260              here used to indirectly enable GPG_ERR_FULLY_CANCELED.  */
261           assuan_transact (agent_ctx, "OPTION agent-awareness=2.1.0",
262                            NULL, NULL, NULL, NULL, NULL, NULL);
263           /* Pass on the pinentry mode.  */
264           if (opt.pinentry_mode)
265             {
266               char *tmp = xasprintf ("OPTION pinentry-mode=%s",
267                                      str_pinentry_mode (opt.pinentry_mode));
268               rc = assuan_transact (agent_ctx, tmp,
269                                NULL, NULL, NULL, NULL, NULL, NULL);
270               xfree (tmp);
271               if (rc)
272                 {
273                   log_error ("setting pinentry mode '%s' failed: %s\n",
274                              str_pinentry_mode (opt.pinentry_mode),
275                              gpg_strerror (rc));
276                   write_status_error ("set_pinentry_mode", rc);
277                 }
278             }
279         }
280     }
281
282   if (!rc && for_card && !did_early_card_test)
283     {
284       /* Request the serial number of the card for an early test.  */
285       struct agent_card_info_s info;
286
287       memset (&info, 0, sizeof info);
288
289       rc = warn_version_mismatch (agent_ctx, SCDAEMON_NAME, 2);
290       if (!rc)
291         rc = assuan_transact (agent_ctx, "SCD SERIALNO openpgp",
292                               NULL, NULL, NULL, NULL,
293                               learn_status_cb, &info);
294       if (rc)
295         {
296           switch (gpg_err_code (rc))
297             {
298             case GPG_ERR_NOT_SUPPORTED:
299             case GPG_ERR_NO_SCDAEMON:
300               write_status_text (STATUS_CARDCTRL, "6");
301               break;
302             case GPG_ERR_OBJ_TERM_STATE:
303               write_status_text (STATUS_CARDCTRL, "7");
304               break;
305             default:
306               write_status_text (STATUS_CARDCTRL, "4");
307               log_info ("selecting openpgp failed: %s\n", gpg_strerror (rc));
308               break;
309             }
310         }
311
312       if (!rc && is_status_enabled () && info.serialno)
313         {
314           char *buf;
315
316           buf = xasprintf ("3 %s", info.serialno);
317           write_status_text (STATUS_CARDCTRL, buf);
318           xfree (buf);
319         }
320
321       agent_release_card_info (&info);
322
323       if (!rc)
324         did_early_card_test = 1;
325     }
326
327
328   return rc;
329 }
330
331
332 /* Return a new malloced string by unescaping the string S.  Escaping
333    is percent escaping and '+'/space mapping.  A binary nul will
334    silently be replaced by a 0xFF.  Function returns NULL to indicate
335    an out of memory status. */
336 static char *
337 unescape_status_string (const unsigned char *s)
338 {
339   return percent_plus_unescape (s, 0xff);
340 }
341
342
343 /* Take a 20 byte hexencoded string and put it into the the provided
344    20 byte buffer FPR in binary format. */
345 static int
346 unhexify_fpr (const char *hexstr, unsigned char *fpr)
347 {
348   const char *s;
349   int n;
350
351   for (s=hexstr, n=0; hexdigitp (s); s++, n++)
352     ;
353   if (*s || (n != 40))
354     return 0; /* no fingerprint (invalid or wrong length). */
355   for (s=hexstr, n=0; *s; s += 2, n++)
356     fpr[n] = xtoi_2 (s);
357   return 1; /* okay */
358 }
359
360 /* Take the serial number from LINE and return it verbatim in a newly
361    allocated string.  We make sure that only hex characters are
362    returned. */
363 static char *
364 store_serialno (const char *line)
365 {
366   const char *s;
367   char *p;
368
369   for (s=line; hexdigitp (s); s++)
370     ;
371   p = xtrymalloc (s + 1 - line);
372   if (p)
373     {
374       memcpy (p, line, s-line);
375       p[s-line] = 0;
376     }
377   return p;
378 }
379
380
381 \f
382 /* This is a dummy data line callback.  */
383 static gpg_error_t
384 dummy_data_cb (void *opaque, const void *buffer, size_t length)
385 {
386   (void)opaque;
387   (void)buffer;
388   (void)length;
389   return 0;
390 }
391
392 /* A simple callback used to return the serialnumber of a card.  */
393 static gpg_error_t
394 get_serialno_cb (void *opaque, const char *line)
395 {
396   char **serialno = opaque;
397   const char *keyword = line;
398   const char *s;
399   int keywordlen, n;
400
401   for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
402     ;
403   while (spacep (line))
404     line++;
405
406   if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen))
407     {
408       if (*serialno)
409         return gpg_error (GPG_ERR_CONFLICT); /* Unexpected status line. */
410       for (n=0,s=line; hexdigitp (s); s++, n++)
411         ;
412       if (!n || (n&1)|| !(spacep (s) || !*s) )
413         return gpg_error (GPG_ERR_ASS_PARAMETER);
414       *serialno = xtrymalloc (n+1);
415       if (!*serialno)
416         return out_of_core ();
417       memcpy (*serialno, line, n);
418       (*serialno)[n] = 0;
419     }
420
421   return 0;
422 }
423
424
425
426 /* Release the card info structure INFO. */
427 void
428 agent_release_card_info (struct agent_card_info_s *info)
429 {
430   int i;
431
432   if (!info)
433     return;
434
435   xfree (info->reader); info->reader = NULL;
436   xfree (info->serialno); info->serialno = NULL;
437   xfree (info->apptype); info->apptype = NULL;
438   xfree (info->disp_name); info->disp_name = NULL;
439   xfree (info->disp_lang); info->disp_lang = NULL;
440   xfree (info->pubkey_url); info->pubkey_url = NULL;
441   xfree (info->login_data); info->login_data = NULL;
442   info->cafpr1valid = info->cafpr2valid = info->cafpr3valid = 0;
443   info->fpr1valid = info->fpr2valid = info->fpr3valid = 0;
444   for (i=0; i < DIM(info->private_do); i++)
445     {
446       xfree (info->private_do[i]);
447       info->private_do[i] = NULL;
448     }
449 }
450
451
452 static gpg_error_t
453 learn_status_cb (void *opaque, const char *line)
454 {
455   struct agent_card_info_s *parm = opaque;
456   const char *keyword = line;
457   int keywordlen;
458   int i;
459
460   for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
461     ;
462   while (spacep (line))
463     line++;
464
465   if (keywordlen == 6 && !memcmp (keyword, "READER", keywordlen))
466     {
467       xfree (parm->reader);
468       parm->reader = unescape_status_string (line);
469     }
470   else if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen))
471     {
472       xfree (parm->serialno);
473       parm->serialno = store_serialno (line);
474       parm->is_v2 = (strlen (parm->serialno) >= 16
475                      && xtoi_2 (parm->serialno+12) >= 2 );
476     }
477   else if (keywordlen == 7 && !memcmp (keyword, "APPTYPE", keywordlen))
478     {
479       xfree (parm->apptype);
480       parm->apptype = unescape_status_string (line);
481     }
482   else if (keywordlen == 9 && !memcmp (keyword, "DISP-NAME", keywordlen))
483     {
484       xfree (parm->disp_name);
485       parm->disp_name = unescape_status_string (line);
486     }
487   else if (keywordlen == 9 && !memcmp (keyword, "DISP-LANG", keywordlen))
488     {
489       xfree (parm->disp_lang);
490       parm->disp_lang = unescape_status_string (line);
491     }
492   else if (keywordlen == 8 && !memcmp (keyword, "DISP-SEX", keywordlen))
493     {
494       parm->disp_sex = *line == '1'? 1 : *line == '2' ? 2: 0;
495     }
496   else if (keywordlen == 10 && !memcmp (keyword, "PUBKEY-URL", keywordlen))
497     {
498       xfree (parm->pubkey_url);
499       parm->pubkey_url = unescape_status_string (line);
500     }
501   else if (keywordlen == 10 && !memcmp (keyword, "LOGIN-DATA", keywordlen))
502     {
503       xfree (parm->login_data);
504       parm->login_data = unescape_status_string (line);
505     }
506   else if (keywordlen == 11 && !memcmp (keyword, "SIG-COUNTER", keywordlen))
507     {
508       parm->sig_counter = strtoul (line, NULL, 0);
509     }
510   else if (keywordlen == 10 && !memcmp (keyword, "CHV-STATUS", keywordlen))
511     {
512       char *p, *buf;
513
514       buf = p = unescape_status_string (line);
515       if (buf)
516         {
517           while (spacep (p))
518             p++;
519           parm->chv1_cached = atoi (p);
520           while (*p && !spacep (p))
521             p++;
522           while (spacep (p))
523             p++;
524           for (i=0; *p && i < 3; i++)
525             {
526               parm->chvmaxlen[i] = atoi (p);
527               while (*p && !spacep (p))
528                 p++;
529               while (spacep (p))
530                 p++;
531             }
532           for (i=0; *p && i < 3; i++)
533             {
534               parm->chvretry[i] = atoi (p);
535               while (*p && !spacep (p))
536                 p++;
537               while (spacep (p))
538                 p++;
539             }
540           xfree (buf);
541         }
542     }
543   else if (keywordlen == 6 && !memcmp (keyword, "EXTCAP", keywordlen))
544     {
545       char *p, *p2, *buf;
546       int abool;
547
548       buf = p = unescape_status_string (line);
549       if (buf)
550         {
551           for (p = strtok (buf, " "); p; p = strtok (NULL, " "))
552             {
553               p2 = strchr (p, '=');
554               if (p2)
555                 {
556                   *p2++ = 0;
557                   abool = (*p2 == '1');
558                   if (!strcmp (p, "ki"))
559                     parm->extcap.ki = abool;
560                   else if (!strcmp (p, "aac"))
561                     parm->extcap.aac = abool;
562                   else if (!strcmp (p, "si"))
563                     parm->status_indicator = strtoul (p2, NULL, 10);
564                 }
565             }
566           xfree (buf);
567         }
568     }
569   else if (keywordlen == 7 && !memcmp (keyword, "KEY-FPR", keywordlen))
570     {
571       int no = atoi (line);
572       while (*line && !spacep (line))
573         line++;
574       while (spacep (line))
575         line++;
576       if (no == 1)
577         parm->fpr1valid = unhexify_fpr (line, parm->fpr1);
578       else if (no == 2)
579         parm->fpr2valid = unhexify_fpr (line, parm->fpr2);
580       else if (no == 3)
581         parm->fpr3valid = unhexify_fpr (line, parm->fpr3);
582     }
583   else if (keywordlen == 8 && !memcmp (keyword, "KEY-TIME", keywordlen))
584     {
585       int no = atoi (line);
586       while (* line && !spacep (line))
587         line++;
588       while (spacep (line))
589         line++;
590       if (no == 1)
591         parm->fpr1time = strtoul (line, NULL, 10);
592       else if (no == 2)
593         parm->fpr2time = strtoul (line, NULL, 10);
594       else if (no == 3)
595         parm->fpr3time = strtoul (line, NULL, 10);
596     }
597   else if (keywordlen == 6 && !memcmp (keyword, "CA-FPR", keywordlen))
598     {
599       int no = atoi (line);
600       while (*line && !spacep (line))
601         line++;
602       while (spacep (line))
603         line++;
604       if (no == 1)
605         parm->cafpr1valid = unhexify_fpr (line, parm->cafpr1);
606       else if (no == 2)
607         parm->cafpr2valid = unhexify_fpr (line, parm->cafpr2);
608       else if (no == 3)
609         parm->cafpr3valid = unhexify_fpr (line, parm->cafpr3);
610     }
611   else if (keywordlen == 8 && !memcmp (keyword, "KEY-ATTR", keywordlen))
612     {
613       int keyno = 0;
614       int algo = PUBKEY_ALGO_RSA;
615       int n = 0;
616
617       sscanf (line, "%d %d %n", &keyno, &algo, &n);
618       keyno--;
619       if (keyno < 0 || keyno >= DIM (parm->key_attr))
620         return 0;
621
622       parm->key_attr[keyno].algo = algo;
623       if (algo == PUBKEY_ALGO_RSA)
624         parm->key_attr[keyno].nbits = strtoul (line+n+3, NULL, 10);
625       else if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA
626                || algo == PUBKEY_ALGO_EDDSA)
627         parm->key_attr[keyno].curve = openpgp_is_curve_supported (line + n,
628                                                                   NULL, NULL);
629     }
630   else if (keywordlen == 12 && !memcmp (keyword, "PRIVATE-DO-", 11)
631            && strchr("1234", keyword[11]))
632     {
633       int no = keyword[11] - '1';
634       log_assert (no >= 0 && no <= 3);
635       xfree (parm->private_do[no]);
636       parm->private_do[no] = unescape_status_string (line);
637     }
638
639   return 0;
640 }
641
642 /* Call the scdaemon to learn about a smartcard */
643 int
644 agent_scd_learn (struct agent_card_info_s *info, int force)
645 {
646   int rc;
647   struct default_inq_parm_s parm;
648   struct agent_card_info_s dummyinfo;
649
650   if (!info)
651     info = &dummyinfo;
652   memset (info, 0, sizeof *info);
653   memset (&parm, 0, sizeof parm);
654
655   rc = start_agent (NULL, 1);
656   if (rc)
657     return rc;
658
659   /* Send the serialno command to initialize the connection.  We don't
660      care about the data returned.  If the card has already been
661      initialized, this is a very fast command.  The main reason we
662      need to do this here is to handle a card removed case so that an
663      "l" command in --edit-card can be used to show ta newly inserted
664      card.  We request the openpgp card because that is what we
665      expect. */
666   rc = assuan_transact (agent_ctx, "SCD SERIALNO openpgp",
667                         NULL, NULL, NULL, NULL, NULL, NULL);
668   if (rc)
669     return rc;
670
671   parm.ctx = agent_ctx;
672   rc = assuan_transact (agent_ctx,
673                         force ? "LEARN --sendinfo --force" : "LEARN --sendinfo",
674                         dummy_data_cb, NULL, default_inq_cb, &parm,
675                         learn_status_cb, info);
676   /* Also try to get the key attributes.  */
677   if (!rc)
678     agent_scd_getattr ("KEY-ATTR", info);
679
680   if (info == &dummyinfo)
681     agent_release_card_info (info);
682
683   return rc;
684 }
685
686
687 /* Send an APDU to the current card.  On success the status word is
688    stored at R_SW.  With HEXAPDU being NULL only a RESET command is
689    send to scd.  With HEXAPDU being the string "undefined" the command
690    "SERIALNO undefined" is send to scd. */
691 gpg_error_t
692 agent_scd_apdu (const char *hexapdu, unsigned int *r_sw)
693 {
694   gpg_error_t err;
695
696   /* Start the agent but not with the card flag so that we do not
697      autoselect the openpgp application.  */
698   err = start_agent (NULL, 0);
699   if (err)
700     return err;
701
702   if (!hexapdu)
703     {
704       err = assuan_transact (agent_ctx, "SCD RESET",
705                              NULL, NULL, NULL, NULL, NULL, NULL);
706
707     }
708   else if (!strcmp (hexapdu, "undefined"))
709     {
710       err = assuan_transact (agent_ctx, "SCD SERIALNO undefined",
711                              NULL, NULL, NULL, NULL, NULL, NULL);
712     }
713   else
714     {
715       char line[ASSUAN_LINELENGTH];
716       membuf_t mb;
717       unsigned char *data;
718       size_t datalen;
719
720       init_membuf (&mb, 256);
721
722       snprintf (line, DIM(line), "SCD APDU %s", hexapdu);
723       err = assuan_transact (agent_ctx, line,
724                              put_membuf_cb, &mb, NULL, NULL, NULL, NULL);
725       if (!err)
726         {
727           data = get_membuf (&mb, &datalen);
728           if (!data)
729             err = gpg_error_from_syserror ();
730           else if (datalen < 2) /* Ooops */
731             err = gpg_error (GPG_ERR_CARD);
732           else
733             {
734               *r_sw = buf16_to_uint (data+datalen-2);
735             }
736           xfree (data);
737         }
738     }
739
740   return err;
741 }
742
743
744 int
745 agent_keytocard (const char *hexgrip, int keyno, int force,
746                  const char *serialno, const char *timestamp)
747 {
748   int rc;
749   char line[ASSUAN_LINELENGTH];
750   struct default_inq_parm_s parm;
751
752   memset (&parm, 0, sizeof parm);
753
754   snprintf (line, DIM(line), "KEYTOCARD %s%s %s OPENPGP.%d %s",
755             force?"--force ": "", hexgrip, serialno, keyno, timestamp);
756
757   rc = start_agent (NULL, 1);
758   if (rc)
759     return rc;
760   parm.ctx = agent_ctx;
761
762   rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &parm,
763                         NULL, NULL);
764   if (rc)
765     return rc;
766
767   return rc;
768 }
769 \f
770 /* Call the agent to retrieve a data object.  This function returns
771    the data in the same structure as used by the learn command.  It is
772    allowed to update such a structure using this commmand. */
773 int
774 agent_scd_getattr (const char *name, struct agent_card_info_s *info)
775 {
776   int rc;
777   char line[ASSUAN_LINELENGTH];
778   struct default_inq_parm_s parm;
779
780   memset (&parm, 0, sizeof parm);
781
782   if (!*name)
783     return gpg_error (GPG_ERR_INV_VALUE);
784
785   /* We assume that NAME does not need escaping. */
786   if (12 + strlen (name) > DIM(line)-1)
787     return gpg_error (GPG_ERR_TOO_LARGE);
788   stpcpy (stpcpy (line, "SCD GETATTR "), name);
789
790   rc = start_agent (NULL, 1);
791   if (rc)
792     return rc;
793
794   parm.ctx = agent_ctx;
795   rc = assuan_transact (agent_ctx, line, NULL, NULL, default_inq_cb, &parm,
796                         learn_status_cb, info);
797
798   return rc;
799 }
800
801 \f
802 /* Send an setattr command to the SCdaemon.  SERIALNO is not actually
803    used here but required by gpg 1.4's implementation of this code in
804    cardglue.c. */
805 int
806 agent_scd_setattr (const char *name,
807                    const unsigned char *value, size_t valuelen,
808                    const char *serialno)
809 {
810   int rc;
811   char line[ASSUAN_LINELENGTH];
812   char *p;
813   struct default_inq_parm_s parm;
814
815   memset (&parm, 0, sizeof parm);
816
817   (void)serialno;
818
819   if (!*name || !valuelen)
820     return gpg_error (GPG_ERR_INV_VALUE);
821
822   /* We assume that NAME does not need escaping. */
823   if (12 + strlen (name) > DIM(line)-1)
824     return gpg_error (GPG_ERR_TOO_LARGE);
825
826   p = stpcpy (stpcpy (line, "SCD SETATTR "), name);
827   *p++ = ' ';
828   for (; valuelen; value++, valuelen--)
829     {
830       if (p >= line + DIM(line)-5 )
831         return gpg_error (GPG_ERR_TOO_LARGE);
832       if (*value < ' ' || *value == '+' || *value == '%')
833         {
834           sprintf (p, "%%%02X", *value);
835           p += 3;
836         }
837       else if (*value == ' ')
838         *p++ = '+';
839       else
840         *p++ = *value;
841     }
842   *p = 0;
843
844   rc = start_agent (NULL, 1);
845   if (!rc)
846     {
847       parm.ctx = agent_ctx;
848       rc = assuan_transact (agent_ctx, line, NULL, NULL,
849                             default_inq_cb, &parm, NULL, NULL);
850     }
851
852   status_sc_op_failure (rc);
853   return rc;
854 }
855
856
857 \f
858 /* Handle a CERTDATA inquiry.  Note, we only send the data,
859    assuan_transact takes care of flushing and writing the END
860    command. */
861 static gpg_error_t
862 inq_writecert_parms (void *opaque, const char *line)
863 {
864   int rc;
865   struct writecert_parm_s *parm = opaque;
866
867   if (has_leading_keyword (line, "CERTDATA"))
868     {
869       rc = assuan_send_data (parm->dflt->ctx,
870                              parm->certdata, parm->certdatalen);
871     }
872   else
873     rc = default_inq_cb (parm->dflt, line);
874
875   return rc;
876 }
877
878
879 /* Send a WRITECERT command to the SCdaemon. */
880 int
881 agent_scd_writecert (const char *certidstr,
882                      const unsigned char *certdata, size_t certdatalen)
883 {
884   int rc;
885   char line[ASSUAN_LINELENGTH];
886   struct writecert_parm_s parms;
887   struct default_inq_parm_s dfltparm;
888
889   memset (&dfltparm, 0, sizeof dfltparm);
890
891   rc = start_agent (NULL, 1);
892   if (rc)
893     return rc;
894
895   memset (&parms, 0, sizeof parms);
896
897   snprintf (line, DIM(line), "SCD WRITECERT %s", certidstr);
898   dfltparm.ctx = agent_ctx;
899   parms.dflt = &dfltparm;
900   parms.certdata = certdata;
901   parms.certdatalen = certdatalen;
902
903   rc = assuan_transact (agent_ctx, line, NULL, NULL,
904                         inq_writecert_parms, &parms, NULL, NULL);
905
906   return rc;
907 }
908
909
910 \f
911 /* Handle a KEYDATA inquiry.  Note, we only send the data,
912    assuan_transact takes care of flushing and writing the end */
913 static gpg_error_t
914 inq_writekey_parms (void *opaque, const char *line)
915 {
916   int rc;
917   struct writekey_parm_s *parm = opaque;
918
919   if (has_leading_keyword (line, "KEYDATA"))
920     {
921       rc = assuan_send_data (parm->dflt->ctx, parm->keydata, parm->keydatalen);
922     }
923   else
924     rc = default_inq_cb (parm->dflt, line);
925
926   return rc;
927 }
928
929
930 /* Send a WRITEKEY command to the SCdaemon. */
931 int
932 agent_scd_writekey (int keyno, const char *serialno,
933                     const unsigned char *keydata, size_t keydatalen)
934 {
935   int rc;
936   char line[ASSUAN_LINELENGTH];
937   struct writekey_parm_s parms;
938   struct default_inq_parm_s dfltparm;
939
940   memset (&dfltparm, 0, sizeof dfltparm);
941
942   (void)serialno;
943
944   rc = start_agent (NULL, 1);
945   if (rc)
946     return rc;
947
948   memset (&parms, 0, sizeof parms);
949
950   snprintf (line, DIM(line), "SCD WRITEKEY --force OPENPGP.%d", keyno);
951   dfltparm.ctx = agent_ctx;
952   parms.dflt = &dfltparm;
953   parms.keydata = keydata;
954   parms.keydatalen = keydatalen;
955
956   rc = assuan_transact (agent_ctx, line, NULL, NULL,
957                         inq_writekey_parms, &parms, NULL, NULL);
958
959   status_sc_op_failure (rc);
960   return rc;
961 }
962
963
964 \f
965 /* Status callback for the SCD GENKEY command. */
966 static gpg_error_t
967 scd_genkey_cb (void *opaque, const char *line)
968 {
969   u32 *createtime = opaque;
970   const char *keyword = line;
971   int keywordlen;
972
973   for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
974     ;
975   while (spacep (line))
976     line++;
977
978  if (keywordlen == 14 && !memcmp (keyword,"KEY-CREATED-AT", keywordlen))
979     {
980       *createtime = (u32)strtoul (line, NULL, 10);
981     }
982   else if (keywordlen == 8 && !memcmp (keyword, "PROGRESS", keywordlen))
983     {
984       write_status_text (STATUS_PROGRESS, line);
985     }
986
987   return 0;
988 }
989
990 /* Send a GENKEY command to the SCdaemon.  If *CREATETIME is not 0,
991   the value will be passed to SCDAEMON with --timestamp option so that
992   the key is created with this.  Otherwise, timestamp was generated by
993   SCDEAMON.  On success, creation time is stored back to
994   CREATETIME.  */
995 int
996 agent_scd_genkey (int keyno, int force, u32 *createtime)
997 {
998   int rc;
999   char line[ASSUAN_LINELENGTH];
1000   gnupg_isotime_t tbuf;
1001   struct default_inq_parm_s dfltparm;
1002
1003   memset (&dfltparm, 0, sizeof dfltparm);
1004
1005   rc = start_agent (NULL, 1);
1006   if (rc)
1007     return rc;
1008
1009   if (*createtime)
1010     epoch2isotime (tbuf, *createtime);
1011   else
1012     *tbuf = 0;
1013
1014   snprintf (line, DIM(line), "SCD GENKEY %s%s %s %d",
1015             *tbuf? "--timestamp=":"", tbuf,
1016             force? "--force":"",
1017             keyno);
1018
1019   dfltparm.ctx = agent_ctx;
1020   rc = assuan_transact (agent_ctx, line,
1021                         NULL, NULL, default_inq_cb, &dfltparm,
1022                         scd_genkey_cb, createtime);
1023
1024   status_sc_op_failure (rc);
1025   return rc;
1026 }
1027
1028
1029
1030 \f
1031 /* Issue an SCD SERIALNO openpgp command and if SERIALNO is not NULL
1032    ask the user to insert the requested card.  */
1033 gpg_error_t
1034 select_openpgp (const char *serialno)
1035 {
1036   gpg_error_t err;
1037
1038   /* Send the serialno command to initialize the connection.  Without
1039      a given S/N we don't care about the data returned.  If the card
1040      has already been initialized, this is a very fast command.  We
1041      request the openpgp card because that is what we expect.
1042
1043      Note that an opt.limit_card_insert_tries of 1 means: No tries at
1044      all whereas 0 means do not limit the number of tries.  Due to the
1045      sue of a pinentry prompt with a cancel option we use it here in a
1046      boolean sense.  */
1047   if (!serialno || opt.limit_card_insert_tries == 1)
1048     err = assuan_transact (agent_ctx, "SCD SERIALNO openpgp",
1049                            NULL, NULL, NULL, NULL, NULL, NULL);
1050   else
1051     {
1052       char *this_sn = NULL;
1053       char *desc;
1054       int ask;
1055       char *want_sn;
1056       char *p;
1057
1058       want_sn = xtrystrdup (serialno);
1059       if (!want_sn)
1060         return gpg_error_from_syserror ();
1061       p = strchr (want_sn, '/');
1062       if (p)
1063         *p = 0;
1064
1065       do
1066         {
1067           ask = 0;
1068           err = assuan_transact (agent_ctx, "SCD SERIALNO openpgp",
1069                                  NULL, NULL, NULL, NULL,
1070                                  get_serialno_cb, &this_sn);
1071           if (gpg_err_code (err) == GPG_ERR_CARD_NOT_PRESENT)
1072             ask = 1;
1073           else if (gpg_err_code (err) == GPG_ERR_NOT_SUPPORTED)
1074             ask = 2;
1075           else if (err)
1076             ;
1077           else if (this_sn)
1078             {
1079               if (strcmp (want_sn, this_sn))
1080                 ask = 2;
1081             }
1082
1083           xfree (this_sn);
1084           this_sn = NULL;
1085
1086           if (ask)
1087             {
1088               char *formatted = NULL;
1089               char *ocodeset = i18n_switchto_utf8 ();
1090
1091               if (!strncmp (want_sn, "D27600012401", 12)
1092                   && strlen (want_sn) == 32 )
1093                 formatted = xtryasprintf ("(%.4s) %.8s",
1094                                           want_sn + 16, want_sn + 20);
1095
1096               err = 0;
1097               desc = xtryasprintf
1098                 ("%s:\n\n"
1099                  "  \"%s\"",
1100                  ask == 1
1101                  ? _("Please insert the card with serial number")
1102                  : _("Please remove the current card and "
1103                      "insert the one with serial number"),
1104                  formatted? formatted : want_sn);
1105               if (!desc)
1106                 err = gpg_error_from_syserror ();
1107               xfree (formatted);
1108               i18n_switchback (ocodeset);
1109               if (!err)
1110                 err = gpg_agent_get_confirmation (desc);
1111               xfree (desc);
1112             }
1113         }
1114       while (ask && !err);
1115       xfree (want_sn);
1116     }
1117
1118   return err;
1119 }
1120
1121
1122 \f
1123 /* Send a READCERT command to the SCdaemon. */
1124 int
1125 agent_scd_readcert (const char *certidstr,
1126                     void **r_buf, size_t *r_buflen)
1127 {
1128   int rc;
1129   char line[ASSUAN_LINELENGTH];
1130   membuf_t data;
1131   size_t len;
1132   struct default_inq_parm_s dfltparm;
1133
1134   memset (&dfltparm, 0, sizeof dfltparm);
1135
1136   *r_buf = NULL;
1137   rc = start_agent (NULL, 1);
1138   if (rc)
1139     return rc;
1140
1141   dfltparm.ctx = agent_ctx;
1142
1143   init_membuf (&data, 2048);
1144
1145   snprintf (line, DIM(line), "SCD READCERT %s", certidstr);
1146   rc = assuan_transact (agent_ctx, line,
1147                         put_membuf_cb, &data,
1148                         default_inq_cb, &dfltparm,
1149                         NULL, NULL);
1150   if (rc)
1151     {
1152       xfree (get_membuf (&data, &len));
1153       return rc;
1154     }
1155   *r_buf = get_membuf (&data, r_buflen);
1156   if (!*r_buf)
1157     return gpg_error (GPG_ERR_ENOMEM);
1158
1159   return 0;
1160 }
1161
1162
1163 \f
1164 /* Change the PIN of an OpenPGP card or reset the retry counter.
1165    CHVNO 1: Change the PIN
1166          2: For v1 cards: Same as 1.
1167             For v2 cards: Reset the PIN using the Reset Code.
1168          3: Change the admin PIN
1169        101: Set a new PIN and reset the retry counter
1170        102: For v1 cars: Same as 101.
1171             For v2 cards: Set a new Reset Code.
1172    SERIALNO is not used.
1173  */
1174 int
1175 agent_scd_change_pin (int chvno, const char *serialno)
1176 {
1177   int rc;
1178   char line[ASSUAN_LINELENGTH];
1179   const char *reset = "";
1180   struct default_inq_parm_s dfltparm;
1181
1182   memset (&dfltparm, 0, sizeof dfltparm);
1183
1184   (void)serialno;
1185
1186   if (chvno >= 100)
1187     reset = "--reset";
1188   chvno %= 100;
1189
1190   rc = start_agent (NULL, 1);
1191   if (rc)
1192     return rc;
1193   dfltparm.ctx = agent_ctx;
1194
1195   snprintf (line, DIM(line), "SCD PASSWD %s %d", reset, chvno);
1196   rc = assuan_transact (agent_ctx, line,
1197                         NULL, NULL,
1198                         default_inq_cb, &dfltparm,
1199                         NULL, NULL);
1200   status_sc_op_failure (rc);
1201   return rc;
1202 }
1203
1204
1205 /* Perform a CHECKPIN operation.  SERIALNO should be the serial
1206    number of the card - optionally followed by the fingerprint;
1207    however the fingerprint is ignored here. */
1208 int
1209 agent_scd_checkpin  (const char *serialno)
1210 {
1211   int rc;
1212   char line[ASSUAN_LINELENGTH];
1213   struct default_inq_parm_s dfltparm;
1214
1215   memset (&dfltparm, 0, sizeof dfltparm);
1216
1217   rc = start_agent (NULL, 1);
1218   if (rc)
1219     return rc;
1220   dfltparm.ctx = agent_ctx;
1221
1222   snprintf (line, DIM(line), "SCD CHECKPIN %s", serialno);
1223   rc = assuan_transact (agent_ctx, line,
1224                         NULL, NULL,
1225                         default_inq_cb, &dfltparm,
1226                         NULL, NULL);
1227   status_sc_op_failure (rc);
1228   return rc;
1229 }
1230
1231
1232 /* Dummy function, only used by the gpg 1.4 implementation. */
1233 void
1234 agent_clear_pin_cache (const char *sn)
1235 {
1236   (void)sn;
1237 }
1238
1239
1240
1241 \f
1242 /* Note: All strings shall be UTF-8. On success the caller needs to
1243    free the string stored at R_PASSPHRASE. On error NULL will be
1244    stored at R_PASSPHRASE and an appropriate fpf error code
1245    returned. */
1246 gpg_error_t
1247 agent_get_passphrase (const char *cache_id,
1248                       const char *err_msg,
1249                       const char *prompt,
1250                       const char *desc_msg,
1251                       int repeat,
1252                       int check,
1253                       char **r_passphrase)
1254 {
1255   int rc;
1256   char line[ASSUAN_LINELENGTH];
1257   char *arg1 = NULL;
1258   char *arg2 = NULL;
1259   char *arg3 = NULL;
1260   char *arg4 = NULL;
1261   membuf_t data;
1262   struct default_inq_parm_s dfltparm;
1263
1264   memset (&dfltparm, 0, sizeof dfltparm);
1265
1266   *r_passphrase = NULL;
1267
1268   rc = start_agent (NULL, 0);
1269   if (rc)
1270     return rc;
1271   dfltparm.ctx = agent_ctx;
1272
1273   /* Check that the gpg-agent understands the repeat option.  */
1274   if (assuan_transact (agent_ctx,
1275                        "GETINFO cmd_has_option GET_PASSPHRASE repeat",
1276                        NULL, NULL, NULL, NULL, NULL, NULL))
1277     return gpg_error (GPG_ERR_NOT_SUPPORTED);
1278
1279   if (cache_id && *cache_id)
1280     if (!(arg1 = percent_plus_escape (cache_id)))
1281       goto no_mem;
1282   if (err_msg && *err_msg)
1283     if (!(arg2 = percent_plus_escape (err_msg)))
1284       goto no_mem;
1285   if (prompt && *prompt)
1286     if (!(arg3 = percent_plus_escape (prompt)))
1287       goto no_mem;
1288   if (desc_msg && *desc_msg)
1289     if (!(arg4 = percent_plus_escape (desc_msg)))
1290       goto no_mem;
1291
1292   snprintf (line, DIM(line),
1293             "GET_PASSPHRASE --data --repeat=%d%s -- %s %s %s %s",
1294             repeat,
1295             check? " --check --qualitybar":"",
1296             arg1? arg1:"X",
1297             arg2? arg2:"X",
1298             arg3? arg3:"X",
1299             arg4? arg4:"X");
1300   xfree (arg1);
1301   xfree (arg2);
1302   xfree (arg3);
1303   xfree (arg4);
1304
1305   init_membuf_secure (&data, 64);
1306   rc = assuan_transact (agent_ctx, line,
1307                         put_membuf_cb, &data,
1308                         default_inq_cb, &dfltparm,
1309                         NULL, NULL);
1310
1311   if (rc)
1312     xfree (get_membuf (&data, NULL));
1313   else
1314     {
1315       put_membuf (&data, "", 1);
1316       *r_passphrase = get_membuf (&data, NULL);
1317       if (!*r_passphrase)
1318         rc = gpg_error_from_syserror ();
1319     }
1320   return rc;
1321  no_mem:
1322   rc = gpg_error_from_syserror ();
1323   xfree (arg1);
1324   xfree (arg2);
1325   xfree (arg3);
1326   xfree (arg4);
1327   return rc;
1328 }
1329
1330
1331 gpg_error_t
1332 agent_clear_passphrase (const char *cache_id)
1333 {
1334   int rc;
1335   char line[ASSUAN_LINELENGTH];
1336   struct default_inq_parm_s dfltparm;
1337
1338   memset (&dfltparm, 0, sizeof dfltparm);
1339
1340   if (!cache_id || !*cache_id)
1341     return 0;
1342
1343   rc = start_agent (NULL, 0);
1344   if (rc)
1345     return rc;
1346   dfltparm.ctx = agent_ctx;
1347
1348   snprintf (line, DIM(line), "CLEAR_PASSPHRASE %s", cache_id);
1349   return assuan_transact (agent_ctx, line,
1350                           NULL, NULL,
1351                           default_inq_cb, &dfltparm,
1352                           NULL, NULL);
1353 }
1354
1355
1356 /* Ask the agent to pop up a confirmation dialog with the text DESC
1357    and an okay and cancel button. */
1358 gpg_error_t
1359 gpg_agent_get_confirmation (const char *desc)
1360 {
1361   int rc;
1362   char *tmp;
1363   char line[ASSUAN_LINELENGTH];
1364   struct default_inq_parm_s dfltparm;
1365
1366   memset (&dfltparm, 0, sizeof dfltparm);
1367
1368   rc = start_agent (NULL, 0);
1369   if (rc)
1370     return rc;
1371   dfltparm.ctx = agent_ctx;
1372
1373   tmp = percent_plus_escape (desc);
1374   if (!tmp)
1375     return gpg_error_from_syserror ();
1376   snprintf (line, DIM(line), "GET_CONFIRMATION %s", tmp);
1377   xfree (tmp);
1378
1379   rc = assuan_transact (agent_ctx, line,
1380                         NULL, NULL,
1381                         default_inq_cb, &dfltparm,
1382                         NULL, NULL);
1383   return rc;
1384 }
1385
1386
1387 /* Return the S2K iteration count as computed by gpg-agent.  */
1388 gpg_error_t
1389 agent_get_s2k_count (unsigned long *r_count)
1390 {
1391   gpg_error_t err;
1392   membuf_t data;
1393   char *buf;
1394
1395   *r_count = 0;
1396
1397   err = start_agent (NULL, 0);
1398   if (err)
1399     return err;
1400
1401   init_membuf (&data, 32);
1402   err = assuan_transact (agent_ctx, "GETINFO s2k_count",
1403                         put_membuf_cb, &data,
1404                         NULL, NULL, NULL, NULL);
1405   if (err)
1406     xfree (get_membuf (&data, NULL));
1407   else
1408     {
1409       put_membuf (&data, "", 1);
1410       buf = get_membuf (&data, NULL);
1411       if (!buf)
1412         err = gpg_error_from_syserror ();
1413       else
1414         {
1415           *r_count = strtoul (buf, NULL, 10);
1416           xfree (buf);
1417         }
1418     }
1419   return err;
1420 }
1421
1422
1423 \f
1424 /* Ask the agent whether a secret key for the given public key is
1425    available.  Returns 0 if available.  */
1426 gpg_error_t
1427 agent_probe_secret_key (ctrl_t ctrl, PKT_public_key *pk)
1428 {
1429   gpg_error_t err;
1430   char line[ASSUAN_LINELENGTH];
1431   char *hexgrip;
1432
1433   err = start_agent (ctrl, 0);
1434   if (err)
1435     return err;
1436
1437   err = hexkeygrip_from_pk (pk, &hexgrip);
1438   if (err)
1439     return err;
1440
1441   snprintf (line, sizeof line, "HAVEKEY %s", hexgrip);
1442   xfree (hexgrip);
1443
1444   err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL);
1445   return err;
1446 }
1447
1448 /* Ask the agent whether a secret key is available for any of the
1449    keys (primary or sub) in KEYBLOCK.  Returns 0 if available.  */
1450 gpg_error_t
1451 agent_probe_any_secret_key (ctrl_t ctrl, kbnode_t keyblock)
1452 {
1453   gpg_error_t err;
1454   char line[ASSUAN_LINELENGTH];
1455   char *p;
1456   kbnode_t kbctx, node;
1457   int nkeys;
1458   unsigned char grip[20];
1459
1460   err = start_agent (ctrl, 0);
1461   if (err)
1462     return err;
1463
1464   err = gpg_error (GPG_ERR_NO_SECKEY); /* Just in case no key was
1465                                           found in KEYBLOCK.  */
1466   p = stpcpy (line, "HAVEKEY");
1467   for (kbctx=NULL, nkeys=0; (node = walk_kbnode (keyblock, &kbctx, 0)); )
1468     if (node->pkt->pkttype == PKT_PUBLIC_KEY
1469         || node->pkt->pkttype == PKT_PUBLIC_SUBKEY
1470         || node->pkt->pkttype == PKT_SECRET_KEY
1471         || node->pkt->pkttype == PKT_SECRET_SUBKEY)
1472       {
1473         if (nkeys && ((p - line) + 41) > (ASSUAN_LINELENGTH - 2))
1474           {
1475             err = assuan_transact (agent_ctx, line,
1476                                    NULL, NULL, NULL, NULL, NULL, NULL);
1477             if (err != gpg_err_code (GPG_ERR_NO_SECKEY))
1478               break; /* Seckey available or unexpected error - ready.  */
1479             p = stpcpy (line, "HAVEKEY");
1480             nkeys = 0;
1481           }
1482
1483         err = keygrip_from_pk (node->pkt->pkt.public_key, grip);
1484         if (err)
1485           return err;
1486         *p++ = ' ';
1487         bin2hex (grip, 20, p);
1488         p += 40;
1489         nkeys++;
1490       }
1491
1492   if (!err && nkeys)
1493     err = assuan_transact (agent_ctx, line,
1494                            NULL, NULL, NULL, NULL, NULL, NULL);
1495
1496   return err;
1497 }
1498
1499
1500 \f
1501 struct keyinfo_data_parm_s
1502 {
1503   char *serialno;
1504   int cleartext;
1505 };
1506
1507
1508 static gpg_error_t
1509 keyinfo_status_cb (void *opaque, const char *line)
1510 {
1511   struct keyinfo_data_parm_s *data = opaque;
1512   int is_smartcard;
1513   char *s;
1514
1515   if ((s = has_leading_keyword (line, "KEYINFO")) && data)
1516     {
1517       /* Parse the arguments:
1518        *      0        1        2        3       4          5
1519        *   <keygrip> <type> <serialno> <idstr> <cached> <protection>
1520        */
1521       char *fields[6];
1522
1523       if (split_fields (s, fields, DIM (fields)) == 6)
1524         {
1525           is_smartcard = (fields[1][0] == 'T');
1526           if (is_smartcard && !data->serialno && strcmp (fields[2], "-"))
1527             data->serialno = xtrystrdup (fields[2]);
1528           /* 'P' for protected, 'C' for clear */
1529           data->cleartext = (fields[5][0] == 'C');
1530         }
1531     }
1532   return 0;
1533 }
1534
1535
1536 /* Return the serial number for a secret key.  If the returned serial
1537    number is NULL, the key is not stored on a smartcard.  Caller needs
1538    to free R_SERIALNO.
1539
1540    if r_cleartext is not NULL, the referenced int will be set to 1 if
1541    the agent's copy of the key is stored in the clear, or 0 otherwise
1542 */
1543 gpg_error_t
1544 agent_get_keyinfo (ctrl_t ctrl, const char *hexkeygrip,
1545                    char **r_serialno, int *r_cleartext)
1546 {
1547   gpg_error_t err;
1548   char line[ASSUAN_LINELENGTH];
1549   struct keyinfo_data_parm_s keyinfo;
1550
1551   memset (&keyinfo, 0,sizeof keyinfo);
1552
1553   *r_serialno = NULL;
1554
1555   err = start_agent (ctrl, 0);
1556   if (err)
1557     return err;
1558
1559   if (!hexkeygrip || strlen (hexkeygrip) != 40)
1560     return gpg_error (GPG_ERR_INV_VALUE);
1561
1562   snprintf (line, DIM(line), "KEYINFO %s", hexkeygrip);
1563
1564   err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL,
1565                          keyinfo_status_cb, &keyinfo);
1566   if (!err && keyinfo.serialno)
1567     {
1568       /* Sanity check for bad characters.  */
1569       if (strpbrk (keyinfo.serialno, ":\n\r"))
1570         err = GPG_ERR_INV_VALUE;
1571     }
1572   if (err)
1573     xfree (keyinfo.serialno);
1574   else
1575     {
1576       *r_serialno = keyinfo.serialno;
1577       if (r_cleartext)
1578         *r_cleartext = keyinfo.cleartext;
1579     }
1580   return err;
1581 }
1582
1583 \f
1584 /* Status callback for agent_import_key, agent_export_key and
1585    agent_genkey.  */
1586 static gpg_error_t
1587 cache_nonce_status_cb (void *opaque, const char *line)
1588 {
1589   struct cache_nonce_parm_s *parm = opaque;
1590   const char *s;
1591
1592   if ((s = has_leading_keyword (line, "CACHE_NONCE")))
1593     {
1594       if (parm->cache_nonce_addr)
1595         {
1596           xfree (*parm->cache_nonce_addr);
1597           *parm->cache_nonce_addr = xtrystrdup (s);
1598         }
1599     }
1600   else if ((s = has_leading_keyword (line, "PASSWD_NONCE")))
1601     {
1602       if (parm->passwd_nonce_addr)
1603         {
1604           xfree (*parm->passwd_nonce_addr);
1605           *parm->passwd_nonce_addr = xtrystrdup (s);
1606         }
1607     }
1608   else if ((s = has_leading_keyword (line, "PROGRESS")))
1609     {
1610       if (opt.enable_progress_filter)
1611         write_status_text (STATUS_PROGRESS, s);
1612     }
1613
1614   return 0;
1615 }
1616
1617
1618 \f
1619 /* Handle a KEYPARMS inquiry.  Note, we only send the data,
1620    assuan_transact takes care of flushing and writing the end */
1621 static gpg_error_t
1622 inq_genkey_parms (void *opaque, const char *line)
1623 {
1624   struct genkey_parm_s *parm = opaque;
1625   gpg_error_t err;
1626
1627   if (has_leading_keyword (line, "KEYPARAM"))
1628     {
1629       err = assuan_send_data (parm->dflt->ctx,
1630                               parm->keyparms, strlen (parm->keyparms));
1631     }
1632   else if (has_leading_keyword (line, "NEWPASSWD") && parm->passphrase)
1633     {
1634       err = assuan_send_data (parm->dflt->ctx,
1635                               parm->passphrase,  strlen (parm->passphrase));
1636     }
1637   else
1638     err = default_inq_cb (parm->dflt, line);
1639
1640   return err;
1641 }
1642
1643
1644 /* Call the agent to generate a new key.  KEYPARMS is the usual
1645    S-expression giving the parameters of the key.  gpg-agent passes it
1646    gcry_pk_genkey.  If NO_PROTECTION is true the agent is advised not
1647    to protect the generated key.  If NO_PROTECTION is not set and
1648    PASSPHRASE is not NULL the agent is requested to protect the key
1649    with that passphrase instead of asking for one.  */
1650 gpg_error_t
1651 agent_genkey (ctrl_t ctrl, char **cache_nonce_addr, char **passwd_nonce_addr,
1652               const char *keyparms, int no_protection,
1653               const char *passphrase, gcry_sexp_t *r_pubkey)
1654 {
1655   gpg_error_t err;
1656   struct genkey_parm_s gk_parm;
1657   struct cache_nonce_parm_s cn_parm;
1658   struct default_inq_parm_s dfltparm;
1659   membuf_t data;
1660   size_t len;
1661   unsigned char *buf;
1662   char line[ASSUAN_LINELENGTH];
1663
1664   memset (&dfltparm, 0, sizeof dfltparm);
1665   dfltparm.ctrl = ctrl;
1666
1667   *r_pubkey = NULL;
1668   err = start_agent (ctrl, 0);
1669   if (err)
1670     return err;
1671   dfltparm.ctx = agent_ctx;
1672
1673   if (passwd_nonce_addr && *passwd_nonce_addr)
1674     ; /* A RESET would flush the passwd nonce cache.  */
1675   else
1676     {
1677       err = assuan_transact (agent_ctx, "RESET",
1678                              NULL, NULL, NULL, NULL, NULL, NULL);
1679       if (err)
1680         return err;
1681     }
1682
1683   init_membuf (&data, 1024);
1684   gk_parm.dflt     = &dfltparm;
1685   gk_parm.keyparms = keyparms;
1686   gk_parm.passphrase = passphrase;
1687   snprintf (line, sizeof line, "GENKEY%s%s%s%s%s",
1688             no_protection? " --no-protection" :
1689             passphrase   ? " --inq-passwd" :
1690             /*          */ "",
1691             passwd_nonce_addr && *passwd_nonce_addr? " --passwd-nonce=":"",
1692             passwd_nonce_addr && *passwd_nonce_addr? *passwd_nonce_addr:"",
1693             cache_nonce_addr && *cache_nonce_addr? " ":"",
1694             cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:"");
1695   cn_parm.cache_nonce_addr = cache_nonce_addr;
1696   cn_parm.passwd_nonce_addr = NULL;
1697   err = assuan_transact (agent_ctx, line,
1698                          put_membuf_cb, &data,
1699                          inq_genkey_parms, &gk_parm,
1700                          cache_nonce_status_cb, &cn_parm);
1701   if (err)
1702     {
1703       xfree (get_membuf (&data, &len));
1704       return err;
1705     }
1706
1707   buf = get_membuf (&data, &len);
1708   if (!buf)
1709     err = gpg_error_from_syserror ();
1710   else
1711     {
1712       err = gcry_sexp_sscan (r_pubkey, NULL, buf, len);
1713       xfree (buf);
1714     }
1715   return err;
1716 }
1717
1718
1719 \f
1720 /* Call the agent to read the public key part for a given keygrip.  If
1721    FROMCARD is true, the key is directly read from the current
1722    smartcard. In this case HEXKEYGRIP should be the keyID
1723    (e.g. OPENPGP.3). */
1724 gpg_error_t
1725 agent_readkey (ctrl_t ctrl, int fromcard, const char *hexkeygrip,
1726                unsigned char **r_pubkey)
1727 {
1728   gpg_error_t err;
1729   membuf_t data;
1730   size_t len;
1731   unsigned char *buf;
1732   char line[ASSUAN_LINELENGTH];
1733   struct default_inq_parm_s dfltparm;
1734
1735   memset (&dfltparm, 0, sizeof dfltparm);
1736   dfltparm.ctrl = ctrl;
1737
1738   *r_pubkey = NULL;
1739   err = start_agent (ctrl, 0);
1740   if (err)
1741     return err;
1742   dfltparm.ctx = agent_ctx;
1743
1744   err = assuan_transact (agent_ctx, "RESET",NULL, NULL, NULL, NULL, NULL, NULL);
1745   if (err)
1746     return err;
1747
1748   snprintf (line, DIM(line), "READKEY %s%s", fromcard? "--card ":"",
1749             hexkeygrip);
1750
1751   init_membuf (&data, 1024);
1752   err = assuan_transact (agent_ctx, line,
1753                          put_membuf_cb, &data,
1754                          default_inq_cb, &dfltparm,
1755                          NULL, NULL);
1756   if (err)
1757     {
1758       xfree (get_membuf (&data, &len));
1759       return err;
1760     }
1761   buf = get_membuf (&data, &len);
1762   if (!buf)
1763     return gpg_error_from_syserror ();
1764   if (!gcry_sexp_canon_len (buf, len, NULL, NULL))
1765     {
1766       xfree (buf);
1767       return gpg_error (GPG_ERR_INV_SEXP);
1768     }
1769   *r_pubkey = buf;
1770   return 0;
1771 }
1772
1773
1774 \f
1775 /* Call the agent to do a sign operation using the key identified by
1776    the hex string KEYGRIP.  DESC is a description of the key to be
1777    displayed if the agent needs to ask for the PIN.  DIGEST and
1778    DIGESTLEN is the hash value to sign and DIGESTALGO the algorithm id
1779    used to compute the digest.  If CACHE_NONCE is used the agent is
1780    advised to first try a passphrase associated with that nonce. */
1781 gpg_error_t
1782 agent_pksign (ctrl_t ctrl, const char *cache_nonce,
1783               const char *keygrip, const char *desc,
1784               u32 *keyid, u32 *mainkeyid, int pubkey_algo,
1785               unsigned char *digest, size_t digestlen, int digestalgo,
1786               gcry_sexp_t *r_sigval)
1787 {
1788   gpg_error_t err;
1789   char line[ASSUAN_LINELENGTH];
1790   membuf_t data;
1791   struct default_inq_parm_s dfltparm;
1792
1793   memset (&dfltparm, 0, sizeof dfltparm);
1794   dfltparm.ctrl = ctrl;
1795   dfltparm.keyinfo.keyid       = keyid;
1796   dfltparm.keyinfo.mainkeyid   = mainkeyid;
1797   dfltparm.keyinfo.pubkey_algo = pubkey_algo;
1798
1799   *r_sigval = NULL;
1800   err = start_agent (ctrl, 0);
1801   if (err)
1802     return err;
1803   dfltparm.ctx = agent_ctx;
1804
1805   if (digestlen*2 + 50 > DIM(line))
1806     return gpg_error (GPG_ERR_GENERAL);
1807
1808   err = assuan_transact (agent_ctx, "RESET",
1809                          NULL, NULL, NULL, NULL, NULL, NULL);
1810   if (err)
1811     return err;
1812
1813   snprintf (line, DIM(line), "SIGKEY %s", keygrip);
1814   err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL);
1815   if (err)
1816     return err;
1817
1818   if (desc)
1819     {
1820       snprintf (line, DIM(line), "SETKEYDESC %s", desc);
1821       err = assuan_transact (agent_ctx, line,
1822                             NULL, NULL, NULL, NULL, NULL, NULL);
1823       if (err)
1824         return err;
1825     }
1826
1827   snprintf (line, sizeof line, "SETHASH %d ", digestalgo);
1828   bin2hex (digest, digestlen, line + strlen (line));
1829   err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL);
1830   if (err)
1831     return err;
1832
1833   init_membuf (&data, 1024);
1834
1835   snprintf (line, sizeof line, "PKSIGN%s%s",
1836             cache_nonce? " -- ":"",
1837             cache_nonce? cache_nonce:"");
1838   err = assuan_transact (agent_ctx, line,
1839                          put_membuf_cb, &data,
1840                          default_inq_cb, &dfltparm,
1841                          NULL, NULL);
1842   if (err)
1843     xfree (get_membuf (&data, NULL));
1844   else
1845     {
1846       unsigned char *buf;
1847       size_t len;
1848
1849       buf = get_membuf (&data, &len);
1850       if (!buf)
1851         err = gpg_error_from_syserror ();
1852       else
1853         {
1854           err = gcry_sexp_sscan (r_sigval, NULL, buf, len);
1855           xfree (buf);
1856         }
1857     }
1858   return err;
1859 }
1860
1861
1862 \f
1863 /* Handle a CIPHERTEXT inquiry.  Note, we only send the data,
1864    assuan_transact takes care of flushing and writing the END. */
1865 static gpg_error_t
1866 inq_ciphertext_cb (void *opaque, const char *line)
1867 {
1868   struct cipher_parm_s *parm = opaque;
1869   int rc;
1870
1871   if (has_leading_keyword (line, "CIPHERTEXT"))
1872     {
1873       assuan_begin_confidential (parm->ctx);
1874       rc = assuan_send_data (parm->dflt->ctx,
1875                              parm->ciphertext, parm->ciphertextlen);
1876       assuan_end_confidential (parm->ctx);
1877     }
1878   else
1879     rc = default_inq_cb (parm->dflt, line);
1880
1881   return rc;
1882 }
1883
1884
1885 /* Check whether there is any padding info from the agent.  */
1886 static gpg_error_t
1887 padding_info_cb (void *opaque, const char *line)
1888 {
1889   int *r_padding = opaque;
1890   const char *s;
1891
1892   if ((s=has_leading_keyword (line, "PADDING")))
1893     {
1894       *r_padding = atoi (s);
1895     }
1896
1897   return 0;
1898 }
1899
1900
1901 /* Call the agent to do a decrypt operation using the key identified
1902    by the hex string KEYGRIP and the input data S_CIPHERTEXT.  On the
1903    success the decoded value is stored verbatim at R_BUF and its
1904    length at R_BUF; the callers needs to release it.  KEYID, MAINKEYID
1905    and PUBKEY_ALGO are used to construct additional promots or status
1906    messages.   The padding information is stored at R_PADDING with -1
1907    for not known.  */
1908 gpg_error_t
1909 agent_pkdecrypt (ctrl_t ctrl, const char *keygrip, const char *desc,
1910                  u32 *keyid, u32 *mainkeyid, int pubkey_algo,
1911                  gcry_sexp_t s_ciphertext,
1912                  unsigned char **r_buf, size_t *r_buflen, int *r_padding)
1913 {
1914   gpg_error_t err;
1915   char line[ASSUAN_LINELENGTH];
1916   membuf_t data;
1917   size_t n, len;
1918   char *p, *buf, *endp;
1919   struct default_inq_parm_s dfltparm;
1920
1921   memset (&dfltparm, 0, sizeof dfltparm);
1922   dfltparm.ctrl = ctrl;
1923   dfltparm.keyinfo.keyid       = keyid;
1924   dfltparm.keyinfo.mainkeyid   = mainkeyid;
1925   dfltparm.keyinfo.pubkey_algo = pubkey_algo;
1926
1927   if (!keygrip || strlen(keygrip) != 40
1928       || !s_ciphertext || !r_buf || !r_buflen || !r_padding)
1929     return gpg_error (GPG_ERR_INV_VALUE);
1930
1931   *r_buf = NULL;
1932   *r_padding = -1;
1933
1934   err = start_agent (ctrl, 0);
1935   if (err)
1936     return err;
1937   dfltparm.ctx = agent_ctx;
1938
1939   err = assuan_transact (agent_ctx, "RESET",
1940                          NULL, NULL, NULL, NULL, NULL, NULL);
1941   if (err)
1942     return err;
1943
1944   snprintf (line, sizeof line, "SETKEY %s", keygrip);
1945   err = assuan_transact (agent_ctx, line, NULL, NULL, NULL, NULL, NULL, NULL);
1946   if (err)
1947     return err;
1948
1949   if (desc)
1950     {
1951       snprintf (line, DIM(line), "SETKEYDESC %s", desc);
1952       err = assuan_transact (agent_ctx, line,
1953                             NULL, NULL, NULL, NULL, NULL, NULL);
1954       if (err)
1955         return err;
1956     }
1957
1958   init_membuf_secure (&data, 1024);
1959   {
1960     struct cipher_parm_s parm;
1961
1962     parm.dflt = &dfltparm;
1963     parm.ctx = agent_ctx;
1964     err = make_canon_sexp (s_ciphertext, &parm.ciphertext, &parm.ciphertextlen);
1965     if (err)
1966       return err;
1967     err = assuan_transact (agent_ctx, "PKDECRYPT",
1968                            put_membuf_cb, &data,
1969                            inq_ciphertext_cb, &parm,
1970                            padding_info_cb, r_padding);
1971     xfree (parm.ciphertext);
1972   }
1973   if (err)
1974     {
1975       xfree (get_membuf (&data, &len));
1976       return err;
1977     }
1978
1979   put_membuf (&data, "", 1); /* Make sure it is 0 terminated.  */
1980   buf = get_membuf (&data, &len);
1981   if (!buf)
1982     return gpg_error_from_syserror ();
1983   log_assert (len); /* (we forced Nul termination.)  */
1984
1985   if (*buf != '(')
1986     {
1987       xfree (buf);
1988       return gpg_error (GPG_ERR_INV_SEXP);
1989     }
1990
1991   if (len < 13 || memcmp (buf, "(5:value", 8) ) /* "(5:valueN:D)\0" */
1992     {
1993       xfree (buf);
1994       return gpg_error (GPG_ERR_INV_SEXP);
1995     }
1996   len -= 10;   /* Count only the data of the second part. */
1997   p = buf + 8; /* Skip leading parenthesis and the value tag. */
1998
1999   n = strtoul (p, &endp, 10);
2000   if (!n || *endp != ':')
2001     {
2002       xfree (buf);
2003       return gpg_error (GPG_ERR_INV_SEXP);
2004     }
2005   endp++;
2006   if (endp-p+n > len)
2007     {
2008       xfree (buf);
2009       return gpg_error (GPG_ERR_INV_SEXP); /* Oops: Inconsistent S-Exp. */
2010     }
2011
2012   memmove (buf, endp, n);
2013
2014   *r_buflen = n;
2015   *r_buf = buf;
2016   return 0;
2017 }
2018
2019
2020 \f
2021 /* Retrieve a key encryption key from the agent.  With FOREXPORT true
2022    the key shall be used for export, with false for import.  On success
2023    the new key is stored at R_KEY and its length at R_KEKLEN.  */
2024 gpg_error_t
2025 agent_keywrap_key (ctrl_t ctrl, int forexport, void **r_kek, size_t *r_keklen)
2026 {
2027   gpg_error_t err;
2028   membuf_t data;
2029   size_t len;
2030   unsigned char *buf;
2031   char line[ASSUAN_LINELENGTH];
2032   struct default_inq_parm_s dfltparm;
2033
2034   memset (&dfltparm, 0, sizeof dfltparm);
2035   dfltparm.ctrl = ctrl;
2036
2037   *r_kek = NULL;
2038   err = start_agent (ctrl, 0);
2039   if (err)
2040     return err;
2041   dfltparm.ctx = agent_ctx;
2042
2043   snprintf (line, DIM(line), "KEYWRAP_KEY %s",
2044             forexport? "--export":"--import");
2045
2046   init_membuf_secure (&data, 64);
2047   err = assuan_transact (agent_ctx, line,
2048                          put_membuf_cb, &data,
2049                          default_inq_cb, &dfltparm,
2050                          NULL, NULL);
2051   if (err)
2052     {
2053       xfree (get_membuf (&data, &len));
2054       return err;
2055     }
2056   buf = get_membuf (&data, &len);
2057   if (!buf)
2058     return gpg_error_from_syserror ();
2059   *r_kek = buf;
2060   *r_keklen = len;
2061   return 0;
2062 }
2063
2064
2065 \f
2066 /* Handle the inquiry for an IMPORT_KEY command.  */
2067 static gpg_error_t
2068 inq_import_key_parms (void *opaque, const char *line)
2069 {
2070   struct import_key_parm_s *parm = opaque;
2071   gpg_error_t err;
2072
2073   if (has_leading_keyword (line, "KEYDATA"))
2074     {
2075       err = assuan_send_data (parm->dflt->ctx, parm->key, parm->keylen);
2076     }
2077   else
2078     err = default_inq_cb (parm->dflt, line);
2079
2080   return err;
2081 }
2082
2083
2084 /* Call the agent to import a key into the agent.  */
2085 gpg_error_t
2086 agent_import_key (ctrl_t ctrl, const char *desc, char **cache_nonce_addr,
2087                   const void *key, size_t keylen, int unattended, int force)
2088 {
2089   gpg_error_t err;
2090   struct import_key_parm_s parm;
2091   struct cache_nonce_parm_s cn_parm;
2092   char line[ASSUAN_LINELENGTH];
2093   struct default_inq_parm_s dfltparm;
2094
2095   memset (&dfltparm, 0, sizeof dfltparm);
2096   dfltparm.ctrl = ctrl;
2097
2098   err = start_agent (ctrl, 0);
2099   if (err)
2100     return err;
2101   dfltparm.ctx = agent_ctx;
2102
2103   if (desc)
2104     {
2105       snprintf (line, DIM(line), "SETKEYDESC %s", desc);
2106       err = assuan_transact (agent_ctx, line,
2107                             NULL, NULL, NULL, NULL, NULL, NULL);
2108       if (err)
2109         return err;
2110     }
2111
2112   parm.dflt   = &dfltparm;
2113   parm.key    = key;
2114   parm.keylen = keylen;
2115
2116   snprintf (line, sizeof line, "IMPORT_KEY%s%s%s%s",
2117             unattended? " --unattended":"",
2118             force? " --force":"",
2119             cache_nonce_addr && *cache_nonce_addr? " ":"",
2120             cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:"");
2121   cn_parm.cache_nonce_addr = cache_nonce_addr;
2122   cn_parm.passwd_nonce_addr = NULL;
2123   err = assuan_transact (agent_ctx, line,
2124                          NULL, NULL,
2125                          inq_import_key_parms, &parm,
2126                          cache_nonce_status_cb, &cn_parm);
2127   return err;
2128 }
2129
2130
2131 \f
2132 /* Receive a secret key from the agent.  HEXKEYGRIP is the hexified
2133    keygrip, DESC a prompt to be displayed with the agent's passphrase
2134    question (needs to be plus+percent escaped).  if OPENPGP_PROTECTED
2135    is not zero, ensure that the key material is returned in RFC
2136    4880-compatible passphrased-protected form.  If CACHE_NONCE_ADDR is
2137    not NULL the agent is advised to first try a passphrase associated
2138    with that nonce.  On success the key is stored as a canonical
2139    S-expression at R_RESULT and R_RESULTLEN.  */
2140 gpg_error_t
2141 agent_export_key (ctrl_t ctrl, const char *hexkeygrip, const char *desc,
2142                   int openpgp_protected, char **cache_nonce_addr,
2143                   unsigned char **r_result, size_t *r_resultlen)
2144 {
2145   gpg_error_t err;
2146   struct cache_nonce_parm_s cn_parm;
2147   membuf_t data;
2148   size_t len;
2149   unsigned char *buf;
2150   char line[ASSUAN_LINELENGTH];
2151   struct default_inq_parm_s dfltparm;
2152
2153   memset (&dfltparm, 0, sizeof dfltparm);
2154   dfltparm.ctrl = ctrl;
2155
2156   *r_result = NULL;
2157
2158   err = start_agent (ctrl, 0);
2159   if (err)
2160     return err;
2161   dfltparm.ctx = agent_ctx;
2162
2163   if (desc)
2164     {
2165       snprintf (line, DIM(line), "SETKEYDESC %s", desc);
2166       err = assuan_transact (agent_ctx, line,
2167                              NULL, NULL, NULL, NULL, NULL, NULL);
2168       if (err)
2169         return err;
2170     }
2171
2172   snprintf (line, DIM(line), "EXPORT_KEY %s%s%s %s",
2173             openpgp_protected ? "--openpgp ":"",
2174             cache_nonce_addr && *cache_nonce_addr? "--cache-nonce=":"",
2175             cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:"",
2176             hexkeygrip);
2177
2178   init_membuf_secure (&data, 1024);
2179   cn_parm.cache_nonce_addr = cache_nonce_addr;
2180   cn_parm.passwd_nonce_addr = NULL;
2181   err = assuan_transact (agent_ctx, line,
2182                          put_membuf_cb, &data,
2183                          default_inq_cb, &dfltparm,
2184                          cache_nonce_status_cb, &cn_parm);
2185   if (err)
2186     {
2187       xfree (get_membuf (&data, &len));
2188       return err;
2189     }
2190   buf = get_membuf (&data, &len);
2191   if (!buf)
2192     return gpg_error_from_syserror ();
2193   *r_result = buf;
2194   *r_resultlen = len;
2195   return 0;
2196 }
2197
2198
2199 \f
2200 /* Ask the agent to delete the key identified by HEXKEYGRIP.  If DESC
2201    is not NULL, display DESC instead of the default description
2202    message.  If FORCE is true the agent is advised not to ask for
2203    confirmation. */
2204 gpg_error_t
2205 agent_delete_key (ctrl_t ctrl, const char *hexkeygrip, const char *desc,
2206                   int force)
2207 {
2208   gpg_error_t err;
2209   char line[ASSUAN_LINELENGTH];
2210   struct default_inq_parm_s dfltparm;
2211
2212   memset (&dfltparm, 0, sizeof dfltparm);
2213   dfltparm.ctrl = ctrl;
2214
2215   err = start_agent (ctrl, 0);
2216   if (err)
2217     return err;
2218
2219   if (!hexkeygrip || strlen (hexkeygrip) != 40)
2220     return gpg_error (GPG_ERR_INV_VALUE);
2221
2222   if (desc)
2223     {
2224       snprintf (line, DIM(line), "SETKEYDESC %s", desc);
2225       err = assuan_transact (agent_ctx, line,
2226                              NULL, NULL, NULL, NULL, NULL, NULL);
2227       if (err)
2228         return err;
2229     }
2230
2231   snprintf (line, DIM(line), "DELETE_KEY%s %s",
2232             force? " --force":"", hexkeygrip);
2233   err = assuan_transact (agent_ctx, line, NULL, NULL,
2234                          default_inq_cb, &dfltparm,
2235                          NULL, NULL);
2236   return err;
2237 }
2238
2239
2240 \f
2241 /* Ask the agent to change the passphrase of the key identified by
2242  * HEXKEYGRIP.  If DESC is not NULL, display DESC instead of the
2243  * default description message.  If CACHE_NONCE_ADDR is not NULL the
2244  * agent is advised to first try a passphrase associated with that
2245  * nonce.  If PASSWD_NONCE_ADDR is not NULL the agent will try to use
2246  * the passphrase associated with that nonce for the new passphrase.
2247  * If VERIFY is true the passphrase is only verified.  */
2248 gpg_error_t
2249 agent_passwd (ctrl_t ctrl, const char *hexkeygrip, const char *desc, int verify,
2250               char **cache_nonce_addr, char **passwd_nonce_addr)
2251 {
2252   gpg_error_t err;
2253   struct cache_nonce_parm_s cn_parm;
2254   char line[ASSUAN_LINELENGTH];
2255   struct default_inq_parm_s dfltparm;
2256
2257   memset (&dfltparm, 0, sizeof dfltparm);
2258   dfltparm.ctrl = ctrl;
2259
2260   err = start_agent (ctrl, 0);
2261   if (err)
2262     return err;
2263   dfltparm.ctx = agent_ctx;
2264
2265   if (!hexkeygrip || strlen (hexkeygrip) != 40)
2266     return gpg_error (GPG_ERR_INV_VALUE);
2267
2268   if (desc)
2269     {
2270       snprintf (line, DIM(line), "SETKEYDESC %s", desc);
2271       err = assuan_transact (agent_ctx, line,
2272                              NULL, NULL, NULL, NULL, NULL, NULL);
2273       if (err)
2274         return err;
2275     }
2276
2277   if (verify)
2278     snprintf (line, DIM(line), "PASSWD %s%s --verify %s",
2279               cache_nonce_addr && *cache_nonce_addr? "--cache-nonce=":"",
2280               cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:"",
2281               hexkeygrip);
2282   else
2283     snprintf (line, DIM(line), "PASSWD %s%s %s%s %s",
2284               cache_nonce_addr && *cache_nonce_addr? "--cache-nonce=":"",
2285               cache_nonce_addr && *cache_nonce_addr? *cache_nonce_addr:"",
2286               passwd_nonce_addr && *passwd_nonce_addr? "--passwd-nonce=":"",
2287               passwd_nonce_addr && *passwd_nonce_addr? *passwd_nonce_addr:"",
2288               hexkeygrip);
2289   cn_parm.cache_nonce_addr = cache_nonce_addr;
2290   cn_parm.passwd_nonce_addr = passwd_nonce_addr;
2291   err = assuan_transact (agent_ctx, line, NULL, NULL,
2292                          default_inq_cb, &dfltparm,
2293                          cache_nonce_status_cb, &cn_parm);
2294   return err;
2295 }
2296
2297
2298 /* Return the version reported by gpg-agent.  */
2299 gpg_error_t
2300 agent_get_version (ctrl_t ctrl, char **r_version)
2301 {
2302   gpg_error_t err;
2303
2304   err = start_agent (ctrl, 0);
2305   if (err)
2306     return err;
2307
2308   err = get_assuan_server_version (agent_ctx, 0, r_version);
2309   return err;
2310 }