File: scd.c

package info (click to toggle)
poldi 0.4.1-3
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 2,892 kB
  • ctags: 1,112
  • sloc: ansic: 9,554; sh: 4,684; makefile: 245; sed: 16
file content (951 lines) | stat: -rw-r--r-- 21,222 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
/* scd.c - Interface to Scdaemon
   Copyright (C) 2001, 2002, 2005 Free Software Foundation, Inc.
   Copyright (C) 2007, 2008 g10code GmbH. 

   This file is part of Poldi.
 
   Poldi is free software; you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.
 
   Poldi is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.
 
   You should have received a copy of the GNU General Public License
   along with this program; if not, see
   <http://www.gnu.org/licenses/>.  */

#include <poldi.h>

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <unistd.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>

#include <gpg-error.h>
#include <gcrypt.h>

#include "scd.h"
#include "assuan.h"
#include "util/util.h"
#include "util/membuf.h"
#include "util/support.h"
#include "util/simplelog.h"

#ifdef _POSIX_OPEN_MAX
#define MAX_OPEN_FDS _POSIX_OPEN_MAX
#else
#define MAX_OPEN_FDS 20
#endif



/* Initializer objet for struct scd_cardinfo instances.  */
struct scd_cardinfo scd_cardinfo_null;



struct scd_context
{
  assuan_context_t assuan_ctx;
  unsigned int flags;
  log_handle_t loghandle;
  scd_pincb_t pincb;
  void *pincb_cookie;
};

/* Callback parameter for learn card */
struct learn_parm_s
{
  void (*kpinfo_cb)(void*, const char *);
  void *kpinfo_cb_arg;
  void (*certinfo_cb)(void*, const char *);
  void *certinfo_cb_arg;
  void (*sinfo_cb)(void*, const char *, size_t, const char *);
  void *sinfo_cb_arg;
};

struct inq_needpin_s 
{
  scd_context_t ctx;
  int (*getpin_cb)(void *, const char *, char*, size_t);
  void *getpin_cb_arg;
};


/* Local prototypes.  */
static assuan_error_t membuf_data_cb (void *opaque,
                                      const void *buffer, size_t length);




static gpg_error_t scd_serialno_internal (assuan_context_t ctx,
					  int agent, char **r_serialno);



/* Helper function for get_scd_socket_from_agent(), which is used by
   scd_connect().

   Try to connect to gpg-agent, which is to be found through the
   info-string contained in AGENT_INFOSTR.  On success, *AGENT_CTX is
   filled with an assuan context.  Return proper error code or zero on
   success. */
static int
agent_connect_from_infostr (const char *agent_infostr,
			    assuan_context_t *agent_ctx,
			    log_handle_t loghandle)
{
  char *infostr;
  int prot;
  int pid;
  int rc;
  char *p;

  *agent_ctx = NULL;
  rc = 0;

  infostr = xtrystrdup (agent_infostr);
  if (!infostr)
    {
      rc = gpg_error_from_syserror ();
      log_msg_error (loghandle,
		     _("failed to duplicate %s: %s"),
		     "agent infostring", gpg_strerror (rc));
      goto out;
    }

  p = strchr (infostr, ':');
  if (!p || p == infostr)
    {
      log_msg_info (loghandle,
		    _("malformed GPG_AGENT_INFO environment variable"));
      /* FIXME: what error code is more appropriate here?  -mo */
      rc = gpg_error (GPG_ERR_ASS_CONNECT_FAILED);
      goto out;
    }
  *p++ = 0;
  pid = atoi (p);
  while (*p && *p != ':')
    p++;
  prot = *p? atoi (p+1) : 0;
  if (prot != 1)
    {
      log_msg_error (loghandle,
		     _("agent protocol version %d is not supported"),
		     prot);
      /* FIXME: what error code is more appropriate here?  -mo */
      rc = gpg_error (GPG_ERR_ASS_CONNECT_FAILED);
      goto out;
    
    }

  /* Connect!  */
  rc = assuan_socket_connect (agent_ctx, infostr, pid);

 out:

  xfree (infostr);

  return rc;
}

/* Helper function for get_scd_socket_from_agent(), which is used by
   scd_connect().

   Try to retrieve the SCDaemons socket naem from the gpg-agent
   context CTX.  On success, *SOCKET_NAME is filled with a copy ot the
   socket name.  Return proper error code or zero on success. */
static int
agent_scd_getinfo_socket_name (assuan_context_t ctx, char **socket_name,
			       log_handle_t loghandle)
{
  unsigned char *databuf;
  size_t datalen;
  membuf_t data;
  char *res;
  int rc;

  init_membuf (&data, 256);
  *socket_name = NULL;
  res = NULL;
  rc = 0;

  rc = assuan_transact (ctx, "SCD GETINFO socket_name", membuf_data_cb, &data,
			NULL, NULL, NULL, NULL);
  if (rc)
    goto out;

  databuf = get_membuf (&data, &datalen);
  if (databuf && datalen)
    {
      res = xtrymalloc (datalen + 1);
      if (!res)
	{
	  log_msg_error (loghandle,
			 _("warning: can't store getinfo data: %s"),
			 strerror (errno));
	}
      else
	{
	  memcpy (res, databuf, datalen);
	  res[datalen] = 0;
	  *socket_name = res;
	}
    }

 out:

  xfree (get_membuf (&data, &datalen));

  return rc;
}

/* Retrieve SCDaemons socket name through a running gpg-agent, which
   is to be found through the info-string AGENT_INFOSTR.  On Success,
   *SOCKET_NAME contains a copy of the socket name.  Returns proper
   error code or zero on success.  */
static int
get_scd_socket_from_agent (const char *agent_infostr, char **socket_name,
			   log_handle_t loghandle)
{
  assuan_context_t ctx;
  int rc;

  *socket_name = NULL;
  ctx = NULL;
  rc = 0;

  rc = agent_connect_from_infostr (agent_infostr, &ctx, loghandle);
  if (rc)
    goto out;

  rc = agent_scd_getinfo_socket_name (ctx, socket_name, loghandle);

 out:

  assuan_disconnect (ctx);

  return rc;
}

/* Send a RESTART to SCDaemon.  */
static void
restart_scd (scd_context_t ctx)
{
  assuan_transact (ctx->assuan_ctx, "RESTART",
		   NULL, NULL, NULL, NULL, NULL, NULL);
}



/* Try to connect to scdaemon.  We support three methods to access
   scdaemon.  First: connect to a specified socket, second: connect to
   a running gpg-agent, retrieve scdaemon socket name through the
   agent and connect to that socket, third: fork of a new scdaemon.
   Returns proper error code or zero on success.  */
gpg_error_t
scd_connect (scd_context_t *scd_ctx,
	     const char *scdaemon_socket,
	     const char *agent_infostr,
	     const char *scd_path,
	     unsigned int flags,
	     log_handle_t loghandle)
{
  assuan_context_t assuan_ctx;
  scd_context_t ctx;
  int rc = 0;

  assuan_ctx = NULL;

  ctx = xtrymalloc (sizeof (*ctx));
  if (! ctx)
    {
      rc = gpg_error_from_syserror ();
      goto out;
    }

  ctx->assuan_ctx = NULL;
  ctx->flags = 0;

#if 0
  /* Scdaemon is not yet able to run as a system daemon, thus this
     code is disabled. */

  if (scdaemon_socket)
    {
      /* This has the highest priority; connect to system scdaemon. */

      rc = assuan_socket_connect (&assuan_ctx, scdaemon_socket, 0);
      if (!rc)
	{
	  log_msg_debug (loghandle,
			 _("connected to system scdaemon through socket '%s'"),
			 scdaemon_socket);
	  goto out;
	}
    }
#endif

  if (agent_infostr && *agent_infostr)
    {
      /* Somehow connecting to a system scdaemon didn't work.  Try to
	 retrieve a scdaemon socket name from gpg-agent. */

      char *scd_socket;

      rc = get_scd_socket_from_agent (agent_infostr, &scd_socket, loghandle);
      if (!rc)
	rc = assuan_socket_connect (&assuan_ctx, scd_socket, 0);

      if (!rc)
	log_msg_debug (loghandle,
		       _("got scdaemon socket name from gpg-agent, "
			 "connected to socket '%s'"), scd_socket);
      
      xfree (scd_socket);

      if (!rc)
	goto out;
    }

  if (1)
    {
      /* Neither of the above scdaemon connect methods worked,
	 fallback: spawn a new scdaemon.  */

      const char *pgmname;
      const char *argv[6];
      int no_close_list[3];
      int i;

      if (flags & SCD_FLAG_VERBOSE)
	log_msg_debug (loghandle,
		       _("no running scdaemon - starting one"));

      if (fflush (NULL))
        {
          rc = gpg_error_from_syserror ();
	  log_msg_error (loghandle,
			 _("error flushing pending output: %s"),
			 strerror (errno));
	  goto out;
        }

      if (!scd_path || !*scd_path)
        scd_path = GNUPG_DEFAULT_SCD;
      if ( !(pgmname = strrchr (scd_path, '/')))
        pgmname = scd_path;
      else
        pgmname++;

      argv[0] = pgmname;
      argv[1] = "--server";
      argv[2] = "--options";
      argv[3] = "/etc/poldi/scdaemon.conf";
      if (flags & SCD_FLAG_VERBOSE)
	argv[4] = "-v";
      else
	argv[4] = NULL;
      argv[5] = NULL;

      i=0;

      /* FIXME! Am I right in assumung that we do not need this?
	 -mo */
#if 0
      if (log_get_fd () != -1)
        no_close_list[i++] = log_get_fd ();
#endif
      if (flags & SCD_FLAG_VERBOSE)
	no_close_list[i++] = fileno (stderr);
      no_close_list[i] = -1;

      /* connect to the agent and perform initial handshaking */
      rc = assuan_pipe_connect (&assuan_ctx, scd_path, argv,
                                no_close_list);
      if (!rc)
	{
	  log_msg_debug (loghandle,
			 _("spawned a new scdaemon (path: '%s')"),
			 scd_path);
	  goto out;
	}
    }

  log_msg_error (loghandle,
		 _("could not connect to any scdaemon: %s"),
		 gpg_strerror (rc));

 out:

  if (rc)
    {
      assuan_disconnect (assuan_ctx);
      xfree (ctx);

    }
  else
    {
      /* FIXME: is this the best way?  -mo */
      //reset_scd (assuan_ctx);
      scd_serialno_internal (assuan_ctx, 0, NULL);

      ctx->assuan_ctx = assuan_ctx;
      ctx->flags = flags;
      ctx->loghandle = loghandle;
      *scd_ctx = ctx;
      if (flags & SCD_FLAG_VERBOSE)
	log_msg_debug (loghandle,
		       _("connection to scdaemon established"));
    }

  return rc;
}

/* Disconnect from SCDaemon; destroy the context SCD_CTX.  */
void
scd_disconnect (scd_context_t scd_ctx)
{
  if (scd_ctx)
    {
      restart_scd (scd_ctx);
      assuan_disconnect (scd_ctx->assuan_ctx);
      xfree (scd_ctx);
    }
}


void
scd_set_pincb (scd_context_t scd_ctx,
	       scd_pincb_t pincb, void *cookie)
{
  assert (scd_ctx);

  scd_ctx->pincb = pincb;
  scd_ctx->pincb_cookie = cookie;
}




/* Return a new malloced string by unescaping the string S.  Escaping
   is percent escaping and '+'/space mapping.  A binary Nul will
   silently be replaced by a 0xFF.  Function returns NULL to indicate
   an out of memory status. */
static char *
unescape_status_string (const unsigned char *s)
{
  char *buffer, *d;

  buffer = d = xtrymalloc (strlen ((const char*)s)+1);
  if (!buffer)
    return NULL;
  while (*s)
    {
      if (*s == '%' && s[1] && s[2])
        { 
          s++;
          *d = xtoi_2 (s);
          if (!*d)
            *d = '\xff';
          d++;
          s += 2;
        }
      else if (*s == '+')
        {
          *d++ = ' ';
          s++;
        }
      else
        *d++ = *s++;
    }
  *d = 0; 
  return buffer;
}




/* CARD LEARNING.  */

/* Take a 20 byte hexencoded string and put it into the the provided
   20 byte buffer FPR in binary format. */
static int
unhexify_fpr (const char *hexstr, unsigned char *fpr)
{
  const char *s;
  int n;

  for (s=hexstr, n=0; hexdigitp (s); s++, n++)
    ;
  if (*s || (n != 40))
    return 0; /* no fingerprint (invalid or wrong length). */
  n /= 2;
  for (s=hexstr, n=0; *s; s += 2, n++)
    fpr[n] = xtoi_2 (s);
  return 1; /* okay */
}

/* Take the serial number from LINE and return it verbatim in a newly
   allocated string.  We make sure that only hex characters are
   returned. */
static char *
store_serialno (const char *line)
{
  const char *s;
  char *p;

  for (s=line; hexdigitp (s); s++)
    ;
  p = xtrymalloc (s + 1 - line);
  if (p)
    {
      memcpy (p, line, s-line);
      p[s-line] = 0;
    }
  return p;
}

static int
learn_status_cb (void *opaque, const char *line)
{
  struct scd_cardinfo *parm = opaque;
  const char *keyword = line;
  int keywordlen;
  //int i;

  for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
    ;
  while (spacep (line))
    line++;

  if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen))
    {
      xfree (parm->serialno);
      parm->serialno = store_serialno (line);
    }
  else if (keywordlen == 9 && !memcmp (keyword, "DISP-NAME", keywordlen))
    {
      xfree (parm->disp_name);
      parm->disp_name = unescape_status_string (line);
    }
  else if (keywordlen == 10 && !memcmp (keyword, "PUBKEY-URL", keywordlen))
    {
      xfree (parm->pubkey_url);
      parm->pubkey_url = unescape_status_string (line);
    }
  else if (keywordlen == 10 && !memcmp (keyword, "LOGIN-DATA", keywordlen))
    {
      xfree (parm->login_data);
      parm->login_data = unescape_status_string (line);
    }
  else if (keywordlen == 7 && !memcmp (keyword, "KEY-FPR", keywordlen))
    {
      int no = atoi (line);
      while (*line && !spacep (line))
        line++;
      while (spacep (line))
        line++;
      if (no == 1)
        parm->fpr1valid = unhexify_fpr (line, parm->fpr1);
      else if (no == 2)
        parm->fpr2valid = unhexify_fpr (line, parm->fpr2);
      else if (no == 3)
        parm->fpr3valid = unhexify_fpr (line, parm->fpr3);
    }
  
  return 0;
}

/* Read information from card and fill the cardinfo structure
   CARDINFO.  Returns proper error code, zero on success.  */
int
scd_learn (scd_context_t ctx,
	   struct scd_cardinfo *cardinfo)
{
  int rc;

  *cardinfo = scd_cardinfo_null;
  rc = assuan_transact (ctx->assuan_ctx, "LEARN --force",
                        NULL, NULL, NULL, NULL,
                        learn_status_cb, cardinfo);

  return rc;
}

/* Simply release the cardinfo structure INFO.  INFO being NULL is
   okay.  */
void
scd_release_cardinfo (struct scd_cardinfo info)
{
  xfree (info.serialno);
  xfree (info.disp_name);
  xfree (info.login_data);
  xfree (info.pubkey_url);
}




/* CMD: SERIALNO.  */

static int
get_serialno_cb (void *opaque, const char *line)
{
  char **serialno = opaque;
  const char *keyword = line;
  const char *s;
  int keywordlen, n;

  for (keywordlen=0; *line && !spacep (line); line++, keywordlen++)
    ;
  while (spacep (line))
    line++;

  if (keywordlen == 8 && !memcmp (keyword, "SERIALNO", keywordlen))
    {
      if (*serialno)
        return gpg_error (GPG_ERR_CONFLICT); /* Unexpected status line. */
      for (n=0,s=line; hexdigitp (s); s++, n++)
        ;
      if (!n || (n&1)|| !(spacep (s) || !*s) )
        return gpg_error (GPG_ERR_ASS_PARAMETER);
      *serialno = xtrymalloc (n+1);
      if (!*serialno)
	return gpg_error_from_errno (errno);
      memcpy (*serialno, line, n);
      (*serialno)[n] = 0;
    }

  return 0;
}

static gpg_error_t
scd_serialno_internal (assuan_context_t ctx, int agent, char **r_serialno)
{
  char *serialno;
  int rc;

  serialno = NULL;

  rc = assuan_transact (ctx, agent ? "SCD SERIALNO" : "SERIALNO",
                        NULL, NULL, NULL, NULL,
                        get_serialno_cb, &serialno);
  if (rc)
    goto out;

  if (r_serialno)
    *r_serialno = serialno;
  else
    xfree (serialno);

 out:

  return rc;
}

/* Return the serial number of the card or an appropriate error.  The
   serial number is returned as a hexstring. */
gpg_error_t
scd_serialno (scd_context_t ctx, char **r_serialno)
{
  gpg_error_t err;

  err = scd_serialno_internal (ctx->assuan_ctx, 0, r_serialno);

  return err;
}

/* CMD: PKSIGN.  */



static int
membuf_data_cb (void *opaque, const void *buffer, size_t length)
{
  membuf_t *data = opaque;

  if (buffer)
    put_membuf (data, buffer, length);
  return 0;
}
  
/* Handle the NEEDPIN inquiry. */
static int
inq_needpin (void *opaque, const char *line)
{
  struct inq_needpin_s *parm = opaque;
  char *pin;
  size_t pinlen;
  int rc;

  rc = 0;

  if (!strncmp (line, "NEEDPIN", 7) && (line[7] == ' ' || !line[7]))
    {
      if (!parm->getpin_cb)
	{
	  rc = GPG_ERR_BAD_PIN;
	  goto out;
	}

      line += 7;
      while (*line == ' ')
        line++;
      
      pinlen = 90;
      pin = xtrymalloc_secure (pinlen);
      if (!pin)
	{
	  rc = gpg_error_from_errno (errno);
	  goto out;
	}

      rc = parm->getpin_cb (parm->getpin_cb_arg, line, pin, pinlen);
      if (!rc)
        rc = assuan_send_data (parm->ctx->assuan_ctx, pin, pinlen);
      xfree (pin);
    }
  else if (!strncmp (line, "POPUPKEYPADPROMPT", 17)
           && (line[17] == ' ' || !line[17]))
    {
      if (!parm->getpin_cb)
	{
	  rc = GPG_ERR_BAD_PIN;
	  goto out;
	}

      line += 17;
      while (*line == ' ')
        line++;
      
      rc = parm->getpin_cb (parm->getpin_cb_arg, line, NULL, 1);
    }
  else if (!strncmp (line, "DISMISSKEYPADPROMPT", 19)
           && (line[19] == ' ' || !line[19]))
    {
      if (!parm->getpin_cb)
	{
	  rc = GPG_ERR_BAD_PIN;
	  goto out;
	}

      rc = parm->getpin_cb (parm->getpin_cb_arg, "", NULL, 0);
    }
  else
    {
      log_msg_error (parm->ctx->loghandle,
		     "received unsupported inquiry from scdaemon `%s'",
		     line);
      rc = gpg_error (GPG_ERR_ASS_UNKNOWN_INQUIRE);
    }

 out:

  return gpg_error (rc);
}


/* Create a signature using the current card. CTX is the handle for
   the scd subsystem.  KEYID identifies the key on the card to use for
   signing. GETPIN_CB is the callback, which is called for querying of
   the PIN, GETPIN_CB_ARG is passed as opaque argument to
   GETPIN_CB. INDATA/INDATALEN is the input for the signature
   function.  The signature created is written into newly allocated
   memory in *R_BUF, *R_BUFLEN will hold the length of the
   signature. */
gpg_error_t
scd_pksign (scd_context_t ctx,
	    const char *keyid,
	    const unsigned char *indata, size_t indatalen,
	    unsigned char **r_buf, size_t *r_buflen)
{
  int rc;
  char *p, line[ASSUAN_LINELENGTH];
  membuf_t data;
  struct inq_needpin_s inqparm;
  size_t len;
  unsigned char *sigbuf;
  size_t sigbuflen;

  *r_buf = NULL;
  *r_buflen = 0;
  rc = 0;

  init_membuf (&data, 1024);

  if (indatalen*2 + 50 > DIM(line)) /* FIXME: Are such long inputs
				       allowed? Should we handle them
				       differently?  */
    {
      rc = gpg_error (GPG_ERR_GENERAL);
      goto out;
    }

  /* Inform scdaemon about the data to be signed. */

  sprintf (line, "SETDATA ");
  p = line + strlen (line);
  bin2hex (indata, indatalen, p);

  rc = assuan_transact (ctx->assuan_ctx, line,
                        NULL, NULL, NULL, NULL, NULL, NULL);
  if (rc)
    goto out;

  /* Setup NEEDPIN inquiry handler.  */

  inqparm.ctx = ctx;
  inqparm.getpin_cb = ctx->pincb;
  inqparm.getpin_cb_arg = ctx->pincb_cookie;

  /* Go, sign it. */

  snprintf (line, DIM(line)-1, "PKSIGN %s", keyid);
  line[DIM(line)-1] = 0;
  rc = assuan_transact (ctx->assuan_ctx, line,
                        membuf_data_cb, &data,
                        inq_needpin, &inqparm,
                        NULL, NULL);
  if (rc)
    goto out;

  /* Extract signature.  FIXME: can't we do this easier?  By reusing
     membuf, without another alloc/free? */

  sigbuf = get_membuf (&data, &sigbuflen);
  *r_buflen = sigbuflen;
  p = xtrymalloc (*r_buflen);
  *r_buf = (unsigned char*)p;
  if (!p)
    {
      rc = gpg_error_from_syserror ();
      goto out;
    }

  memcpy (p, sigbuf, sigbuflen);
  
 out:

  xfree (get_membuf (&data, &len));

  return rc;
}



/* CMD: READKEY.  */

/* Read a key with ID and return it in an allocate buffer pointed to
   by r_BUF as a valid S-expression. */
int
scd_readkey (scd_context_t ctx,
	     const char *id, gcry_sexp_t *key)
{
  int rc;
  char line[ASSUAN_LINELENGTH];
  membuf_t data;
  size_t buflen;
  unsigned char *buffer;

  *key = NULL;
  buffer = NULL;
  init_membuf (&data, 1024);

  /* Execute READKEY command.  */
  snprintf (line, DIM(line)-1, "READKEY %s", id);
  line[DIM(line)-1] = 0;
  rc = assuan_transact (ctx->assuan_ctx, line,
                        membuf_data_cb, &data,
                        NULL, NULL,
                        NULL, NULL);
  if (rc)
    goto out;

  buffer = get_membuf (&data, &buflen);
  if (!buffer)
    {
      rc = gpg_error (GPG_ERR_ENOMEM);
      goto out;
    }

  if (!gcry_sexp_canon_len (buffer, buflen, NULL, NULL))
    {
      rc = gpg_error (GPG_ERR_INV_VALUE);
      *key = NULL;
    }
  else
    rc = gcry_sexp_new (key, buffer, buflen, 1);

 out:

  xfree (buffer);
    
  return rc;
}




/* Sends a GETINFO command for WHAT to the scdaemon through CTX.  The
   newly allocated result is stored in *RESULT.  Returns proper error
   code, zero on success.  */
int
scd_getinfo (scd_context_t ctx, const char *what, char **result)
{
  int rc;
  char line[ASSUAN_LINELENGTH];
  membuf_t data;
  unsigned char *databuf;
  size_t datalen;
  char *res;

  *result = NULL;

  sprintf (line, "GETINFO %s", what);
  init_membuf (&data, 256);

  rc = assuan_transact (ctx->assuan_ctx, line, membuf_data_cb, &data,
			NULL, NULL, NULL, NULL);
  if (rc)
    goto out;

  databuf = get_membuf (&data, &datalen);
  if (databuf && datalen)
    {
      res = xtrymalloc (datalen + 1);
      if (!res)
	{
	  log_msg_error (ctx->loghandle,
			 _("warning: can't store getinfo data: %s"),
			 strerror (errno));
	  rc = gpg_error_from_syserror ();
	}
      else
	{
	  memcpy (res, databuf, datalen);
	  res[datalen] = 0;
	  *result = res;
	}
    }

 out:

  xfree (get_membuf (&data, &datalen));

  return rc;
}

/* END */