summaryrefslogtreecommitdiffstats
path: root/sm/server.c
blob: 5341d315a73c125aabe4564f213960aa8d355df5 (plain)
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
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
/* server.c - Server mode and main entry point
 * Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
 *               2010 Free Software Foundation, Inc.
 *
 * This file is part of GnuPG.
 *
 * GnuPG 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.
 *
 * GnuPG 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 <https://www.gnu.org/licenses/>.
 */

#include <config.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <ctype.h>
#include <unistd.h>

#include "gpgsm.h"
#include <assuan.h>
#include "../common/sysutils.h"
#include "../common/server-help.h"
#include "../common/asshelp.h"
#include "../common/shareddefs.h"

#define set_error(e,t) assuan_set_error (ctx, gpg_error (e), (t))


/* The filepointer for status message used in non-server mode */
static FILE *statusfp;

/* Data used to assuciate an Assuan context with local server data */
struct server_local_s {
  assuan_context_t assuan_ctx;
  int message_fd;
  int list_internal;
  int list_external;
  int list_to_output;           /* Write keylistings to the output fd. */
  int enable_audit_log;         /* Use an audit log.  */
  certlist_t recplist;
  certlist_t signerlist;
  certlist_t default_recplist; /* As set by main() - don't release. */
  int allow_pinentry_notify;   /* Set if pinentry notifications should
                                  be passed back to the client. */
  int no_encrypt_to;           /* Local version of option.  */
};


/* Cookie definition for assuan data line output.  */
static gpgrt_ssize_t data_line_cookie_write (void *cookie,
                                             const void *buffer, size_t size);
static int data_line_cookie_close (void *cookie);
static es_cookie_io_functions_t data_line_cookie_functions =
  {
    NULL,
    data_line_cookie_write,
    NULL,
    data_line_cookie_close
  };



static int command_has_option (const char *cmd, const char *cmdopt);




/* Note that it is sufficient to allocate the target string D as
   long as the source string S, i.e.: strlen(s)+1; */
static void
strcpy_escaped_plus (char *d, const char *s)
{
  while (*s)
    {
      if (*s == '%' && s[1] && s[2])
        {
          s++;
          *d++ = xtoi_2 (s);
          s += 2;
        }
      else if (*s == '+')
        *d++ = ' ', s++;
      else
        *d++ = *s++;
    }
  *d = 0;
}


/* A write handler used by es_fopencookie to write assuan data
   lines.  */
static gpgrt_ssize_t
data_line_cookie_write (void *cookie, const void *buffer, size_t size)
{
  assuan_context_t ctx = cookie;

  if (assuan_send_data (ctx, buffer, size))
    {
      gpg_err_set_errno (EIO);
      return -1;
    }

  return (gpgrt_ssize_t)size;
}

static int
data_line_cookie_close (void *cookie)
{
  assuan_context_t ctx = cookie;

  if (assuan_send_data (ctx, NULL, 0))
    {
      gpg_err_set_errno (EIO);
      return -1;
    }

  return 0;
}


static void
close_message_fd (ctrl_t ctrl)
{
  if (ctrl->server_local->message_fd != -1)
    {
#ifdef HAVE_W32CE_SYSTEM
#warning Is this correct for W32/W32CE?
#endif
      close (ctrl->server_local->message_fd);
      ctrl->server_local->message_fd = -1;
    }
}


/* Start a new audit session if this has been enabled.  */
static gpg_error_t
start_audit_session (ctrl_t ctrl)
{
  audit_release (ctrl->audit);
  ctrl->audit = NULL;
  if (ctrl->server_local->enable_audit_log && !(ctrl->audit = audit_new ()) )
    return gpg_error_from_syserror ();

  return 0;
}


static gpg_error_t
option_handler (assuan_context_t ctx, const char *key, const char *value)
{
  ctrl_t ctrl = assuan_get_pointer (ctx);
  gpg_error_t err = 0;

  if (!strcmp (key, "putenv"))
    {
      /* Change the session's environment to be used for the
         Pinentry.  Valid values are:
          <NAME>            Delete envvar NAME
          <KEY>=            Set envvar NAME to the empty string
          <KEY>=<VALUE>     Set envvar NAME to VALUE
      */
      err = session_env_putenv (opt.session_env, value);
    }
  else if (!strcmp (key, "display"))
    {
      err = session_env_setenv (opt.session_env, "DISPLAY", value);
    }
  else if (!strcmp (key, "ttyname"))
    {
      err = session_env_setenv (opt.session_env, "GPG_TTY", value);
    }
  else if (!strcmp (key, "ttytype"))
    {
      err = session_env_setenv (opt.session_env, "TERM", value);
    }
  else if (!strcmp (key, "lc-ctype"))
    {
      xfree (opt.lc_ctype);
      opt.lc_ctype = xtrystrdup (value);
      if (!opt.lc_ctype)
        err = gpg_error_from_syserror ();
    }
  else if (!strcmp (key, "lc-messages"))
    {
      xfree (opt.lc_messages);
      opt.lc_messages = xtrystrdup (value);
      if (!opt.lc_messages)
        err = gpg_error_from_syserror ();
    }
  else if (!strcmp (key, "xauthority"))
    {
      err = session_env_setenv (opt.session_env, "XAUTHORITY", value);
    }
  else if (!strcmp (key, "pinentry-user-data"))
    {
      err = session_env_setenv (opt.session_env, "PINENTRY_USER_DATA", value);
    }
  else if (!strcmp (key, "include-certs"))
    {
      int i = *value? atoi (value) : -1;
      if (ctrl->include_certs < -2)
        err = gpg_error (GPG_ERR_ASS_PARAMETER);
      else
        ctrl->include_certs = i;
    }
  else if (!strcmp (key, "list-mode"))
    {
      int i = *value? atoi (value) : 0;
      if (!i || i == 1) /* default and mode 1 */
        {
          ctrl->server_local->list_internal = 1;
          ctrl->server_local->list_external = 0;
        }
      else if (i == 2)
        {
          ctrl->server_local->list_internal = 0;
          ctrl->server_local->list_external = 1;
        }
      else if (i == 3)
        {
          ctrl->server_local->list_internal = 1;
          ctrl->server_local->list_external = 1;
        }
      else
        err = gpg_error (GPG_ERR_ASS_PARAMETER);
    }
  else if (!strcmp (key, "list-to-output"))
    {
      int i = *value? atoi (value) : 0;
      ctrl->server_local->list_to_output = i;
    }
  else if (!strcmp (key, "with-validation"))
    {
      int i = *value? atoi (value) : 0;
      ctrl->with_validation = i;
    }
  else if (!strcmp (key, "with-secret"))
    {
      int i = *value? atoi (value) : 0;
      ctrl->with_secret = i;
    }
  else if (!strcmp (key, "validation-model"))
    {
      int i = gpgsm_parse_validation_model (value);
      if ( i >= 0 && i <= 2 )
        ctrl->validation_model = i;
      else
        err = gpg_error (GPG_ERR_ASS_PARAMETER);
    }
  else if (!strcmp (key, "with-key-data"))
    {
      opt.with_key_data = 1;
    }
  else if (!strcmp (key, "enable-audit-log"))
    {
      int i = *value? atoi (value) : 0;
      ctrl->server_local->enable_audit_log = i;
    }
  else if (!strcmp (key, "allow-pinentry-notify"))
    {
      ctrl->server_local->allow_pinentry_notify = 1;
    }
  else if (!strcmp (key, "with-ephemeral-keys"))
    {
      int i = *value? atoi (value) : 0;
      ctrl->with_ephemeral_keys = i;
    }
  else if (!strcmp (key, "no-encrypt-to"))
    {
      ctrl->server_local->no_encrypt_to = 1;
    }
  else if (!strcmp (key, "offline"))
    {
      /* We ignore this option if gpgsm has been started with
         --disable-dirmngr (which also sets offline).  */
      if (!opt.disable_dirmngr)
        {
          int i = *value? !!atoi (value) : 1;
          ctrl->offline = i;
        }
    }
  else if (!strcmp (key, "request-origin"))
    {
      if (!opt.request_origin)
        {
          int i = parse_request_origin (value);
          if (i == -1)
            err = gpg_error (GPG_ERR_INV_VALUE);
          else
            opt.request_origin = i;
        }
    }
  else
    err = gpg_error (GPG_ERR_UNKNOWN_OPTION);

  return err;
}


static gpg_error_t
reset_notify (assuan_context_t ctx, char *line)
{
  ctrl_t ctrl = assuan_get_pointer (ctx);

  (void) line;

  gpgsm_release_certlist (ctrl->server_local->recplist);
  gpgsm_release_certlist (ctrl->server_local->signerlist);
  ctrl->server_local->recplist = NULL;
  ctrl->server_local->signerlist = NULL;
  close_message_fd (ctrl);
  assuan_close_input_fd (ctx);
  assuan_close_output_fd (ctx);
  return 0;
}


static gpg_error_t
input_notify (assuan_context_t ctx, char *line)
{
  ctrl_t ctrl = assuan_get_pointer (ctx);

  ctrl->autodetect_encoding = 0;
  ctrl->is_pem = 0;
  ctrl->is_base64 = 0;
  if (strstr (line, "--armor"))
    ctrl->is_pem = 1;
  else if (strstr (line, "--base64"))
    ctrl->is_base64 = 1;
  else if (strstr (line, "--binary"))
    ;
  else
    ctrl->autodetect_encoding = 1;
  return 0;
}

static gpg_error_t
output_notify (assuan_context_t ctx, char *line)
{
  ctrl_t ctrl = assuan_get_pointer (ctx);

  ctrl->create_pem = 0;
  ctrl->create_base64 = 0;
  if (strstr (line, "--armor"))
    ctrl->create_pem = 1;
  else if (strstr (line, "--base64"))
    ctrl->create_base64 = 1; /* just the raw output */
  return 0;
}


static const char hlp_recipient[] =
  "RECIPIENT <userID>\n"
  "\n"
  "Set the recipient for the encryption.  USERID shall be the\n"
  "internal representation of the key; the server may accept any other\n"
  "way of specification [we will support this].  If this is a valid and\n"
  "trusted recipient the server does respond with OK, otherwise the\n"
  "return is an ERR with the reason why the recipient can't be used,\n"
  "the encryption will then not be done for this recipient.  If the\n"
  "policy is not to encrypt at all if not all recipients are valid, the\n"
  "client has to take care of this.  All RECIPIENT commands are\n"
  "cumulative until a RESET or an successful ENCRYPT command.";
static gpg_error_t
cmd_recipient (assuan_context_t ctx, char *line)
{
  ctrl_t ctrl = assuan_get_pointer (ctx);
  int rc;

  if (!ctrl->audit)
    rc = start_audit_session (ctrl);
  else
    rc = 0;

  if (!rc)
    rc = gpgsm_add_to_certlist (ctrl, line, 0,
                                &ctrl->server_local->recplist, 0);
  if (rc)
    {
      gpgsm_status2 (ctrl, STATUS_INV_RECP,
                     get_inv_recpsgnr_code (rc), line, NULL);
    }

  return rc;
}


static const char hlp_signer[] =
  "SIGNER <userID>\n"
  "\n"
  "Set the signer's keys for the signature creation.  USERID should\n"
  "be the internal representation of the key; the server may accept any\n"
  "other way of specification [we will support this].  If this is a\n"
  "valid and usable signing key the server does respond with OK,\n"
  "otherwise it returns an ERR with the reason why the key can't be\n"
  "used, the signing will then not be done for this key.  If the policy\n"
  "is not to sign at all if not all signer keys are valid, the client\n"
  "has to take care of this.  All SIGNER commands are cumulative until\n"
  "a RESET but they are *not* reset by an SIGN command because it can\n"
  "be expected that set of signers are used for more than one sign\n"
  "operation.";
static gpg_error_t
cmd_signer (assuan_context_t ctx, char *line)
{
  ctrl_t ctrl = assuan_get_pointer (ctx);
  int rc;

  rc = gpgsm_add_to_certlist (ctrl, line, 1,
                              &ctrl->server_local->signerlist, 0);
  if (rc)
    {
      gpgsm_status2 (ctrl, STATUS_INV_SGNR,
                     get_inv_recpsgnr_code (rc), line, NULL);
      /* For compatibility reasons we also issue the old code after the
         new one.  */
      gpgsm_status2 (ctrl, STATUS_INV_RECP,
                     get_inv_recpsgnr_code (rc), line, NULL);
    }
  return rc;
}


static const char hlp_encrypt[] =
  "ENCRYPT \n"
  "\n"
  "Do the actual encryption process. Takes the plaintext from the INPUT\n"
  "command, writes to the ciphertext to the file descriptor set with\n"
  "the OUTPUT command, take the recipients form all the recipients set\n"
  "so far.  If this command fails the clients should try to delete all\n"
  "output currently done or otherwise mark it as invalid.  GPGSM does\n"
  "ensure that there won't be any security problem with leftover data\n"
  "on the output in this case.\n"
  "\n"
  "This command should in general not fail, as all necessary checks\n"
  "have been done while setting the recipients.  The input and output\n"
  "pipes are closed.";
static gpg_error_t
cmd_encrypt (assuan_context_t ctx, char *line)
{
  ctrl_t ctrl = assuan_get_pointer (ctx);
  certlist_t cl;
  int inp_fd, out_fd;
  estream_t out_fp;
  int rc;

  (void)line;

  inp_fd = translate_sys2libc_fd (assuan_get_input_fd (ctx), 0);
  if (inp_fd == -1)
    return set_error (GPG_ERR_ASS_NO_INPUT, NULL);
  out_fd = translate_sys2libc_fd (assuan_get_output_fd (ctx), 1);
  if (out_fd == -1)
    return set_error (GPG_ERR_ASS_NO_OUTPUT, NULL);

  out_fp = es_fdopen_nc (out_fd, "w");
  if (!out_fp)
    return set_error (gpg_err_code_from_syserror (), "fdopen() failed");

  /* Now add all encrypt-to marked recipients from the default
     list. */
  rc = 0;
  if (!opt.no_encrypt_to && !ctrl->server_local->no_encrypt_to)
    {
      for (cl=ctrl->server_local->default_recplist; !rc && cl; cl = cl->next)
        if (cl->is_encrypt_to)
          rc = gpgsm_add_cert_to_certlist (ctrl, cl->cert,
                                           &ctrl->server_local->recplist, 1);
    }
  if (!rc)
    rc = ctrl->audit? 0 : start_audit_session (ctrl);
  if (!rc)
    rc = gpgsm_encrypt (assuan_get_pointer (ctx),
                        ctrl->server_local->recplist,
                        inp_fd, out_fp);
  es_fclose (out_fp);

  gpgsm_release_certlist (ctrl->server_local->recplist);
  ctrl->server_local->recplist = NULL;
  /* Close and reset the fd */
  close_message_fd (ctrl);
  assuan_close_input_fd (ctx);
  assuan_close_output_fd (ctx);
  return rc;
}


static const char hlp_decrypt[] =
  "DECRYPT\n"
  "\n"
  "This performs the decrypt operation after doing some check on the\n"
  "internal state. (e.g. that only needed data has been set).  Because\n"
  "it utilizes the GPG-Agent for the session key decryption, there is\n"
  "no need to ask the client for a protecting passphrase - GPG-Agent\n"
  "does take care of this by requesting this from the user.";
static gpg_error_t
cmd_decrypt (assuan_context_t ctx, char *line)
{
  ctrl_t ctrl = assuan_get_pointer (ctx);
  int inp_fd, out_fd;
  estream_t out_fp;
  int rc;

  (void)line;

  inp_fd = translate_sys2libc_fd (assuan_get_input_fd (ctx), 0);
  if (inp_fd == -1)
    return set_error (GPG_ERR_ASS_NO_INPUT, NULL);
  out_fd = translate_sys2libc_fd (assuan_get_output_fd (ctx), 1);
  if (out_fd == -1)
    return set_error (GPG_ERR_ASS_NO_OUTPUT, NULL);

  out_fp = es_fdopen_nc (out_fd, "w");
  if (!out_fp)
    return set_error (gpg_err_code_from_syserror (), "fdopen() failed");

  rc = start_audit_session (ctrl);
  if (!rc)
    rc = gpgsm_decrypt (ctrl, inp_fd, out_fp);
  es_fclose (out_fp);

  /* Close and reset the fds. */
  close_message_fd (ctrl);
  assuan_close_input_fd (ctx);
  assuan_close_output_fd (ctx);

  return rc;
}


static const char hlp_verify[] =
  "VERIFY\n"
  "\n"
  "This does a verify operation on the message send to the input FD.\n"
  "The result is written out using status lines.  If an output FD was\n"
  "given, the signed text will be written to that.\n"
  "\n"
  "If the signature is a detached one, the server will inquire about\n"
  "the signed material and the client must provide it.";
static gpg_error_t
cmd_verify (assuan_context_t ctx, char *line)
{
  int rc;
  ctrl_t ctrl = assuan_get_pointer (ctx);
  int fd = translate_sys2libc_fd (assuan_get_input_fd (ctx), 0);
  int out_fd = translate_sys2libc_fd (assuan_get_output_fd (ctx), 1);
  estream_t out_fp = NULL;

  (void)line;

  if (fd == -1)
    return set_error (GPG_ERR_ASS_NO_INPUT, NULL);

  if (out_fd != -1)
    {
      out_fp = es_fdopen_nc (out_fd, "w");
      if (!out_fp)
        return set_error (gpg_err_code_from_syserror (), "fdopen() failed");
    }

  rc = start_audit_session (ctrl);
  if (!rc)
    rc = gpgsm_verify (assuan_get_pointer (ctx), fd,
                       ctrl->server_local->message_fd, out_fp);
  es_fclose (out_fp);

  /* Close and reset the fd.  */
  close_message_fd (ctrl);
  assuan_close_input_fd (ctx);
  assuan_close_output_fd (ctx);

  return rc;
}


static const char hlp_sign[] =
  "SIGN [--detached]\n"
  "\n"
  "Sign the data set with the INPUT command and write it to the sink\n"
  "set by OUTPUT.  With \"--detached\", a detached signature is\n"
  "created (surprise).";
static gpg_error_t
cmd_sign (assuan_context_t ctx, char *line)
{
  ctrl_t ctrl = assuan_get_pointer (ctx);
  int inp_fd, out_fd;
  estream_t out_fp;
  int detached;
  int rc;

  inp_fd = translate_sys2libc_fd (assuan_get_input_fd (ctx), 0);
  if (inp_fd == -1)
    return set_error (GPG_ERR_ASS_NO_INPUT, NULL);
  out_fd = translate_sys2libc_fd (assuan_get_output_fd (ctx), 1);
  if (out_fd == -1)
    return set_error (GPG_ERR_ASS_NO_OUTPUT, NULL);

  detached = has_option (line, "--detached");

  out_fp = es_fdopen_nc (out_fd, "w");
  if (!out_fp)
    return set_error (GPG_ERR_ASS_GENERAL, "fdopen() failed");

  rc = start_audit_session (ctrl);
  if (!rc)
    rc = gpgsm_sign (assuan_get_pointer (ctx), ctrl->server_local->signerlist,
                     inp_fd, detached, out_fp);
  es_fclose (out_fp);

  /* close and reset the fd */
  close_message_fd (ctrl);
  assuan_close_input_fd (ctx);
  assuan_close_output_fd (ctx);

  return rc;
}


static const char hlp_import[] =
  "IMPORT [--re-import]\n"
  "\n"
  "Import the certificates read form the input-fd, return status\n"
  "message for each imported one.  The import checks the validity of\n"
  "the certificate but not of the entire chain.  It is possible to\n"
  "import expired certificates.\n"
  "\n"
  "With the option --re-import the input data is expected to a be a LF\n"
  "separated list of fingerprints.  The command will re-import these\n"
  "certificates, meaning that they are made permanent by removing\n"
  "their ephemeral flag.";
static gpg_error_t
cmd_import (assuan_context_t ctx, char *line)
{
  ctrl_t ctrl = assuan_get_pointer (ctx);
  int rc;
  int fd = translate_sys2libc_fd (assuan_get_input_fd (ctx), 0);
  int reimport = has_option (line, "--re-import");

  (void)line;

  if (fd == -1)
    return set_error (GPG_ERR_ASS_NO_INPUT, NULL);

  rc = gpgsm_import (assuan_get_pointer (ctx), fd, reimport);

  /* close and reset the fd */
  close_message_fd (ctrl);
  assuan_close_input_fd (ctx);
  assuan_close_output_fd (ctx);

  return rc;
}


static const char hlp_export[] =
  "EXPORT [--data [--armor|--base64]] [--secret [--(raw|pkcs12)] [--] <pattern>\n"
  "\n"
  "Export the certificates selected by PATTERN.  With --data the output\n"
  "is returned using Assuan D lines; the default is to use the sink given\n"
  "by the last \"OUTPUT\" command.  The options --armor or --base64 encode \n"
  "the output using the PEM respective a plain base-64 format; the default\n"
  "is a binary format which is only suitable for a single certificate.\n"
  "With --secret the secret key is exported using the PKCS#8 format,\n"
  "with --raw using PKCS#1, and with --pkcs12 as full PKCS#12 container.";
static gpg_error_t
cmd_export (assuan_context_t ctx, char *line)
{
  ctrl_t ctrl = assuan_get_pointer (ctx);
  char *p;
  strlist_t list, sl;
  int use_data;
  int opt_secret;
  int opt_raw = 0;
  int opt_pkcs12 = 0;

  use_data = has_option (line, "--data");
  if (use_data)
    {
      /* We need to override any possible setting done by an OUTPUT command. */
      ctrl->create_pem = has_option (line, "--armor");
      ctrl->create_base64 = has_option (line, "--base64");
    }
  opt_secret = has_option (line, "--secret");
  if (opt_secret)
    {
      opt_raw = has_option (line, "--raw");
      opt_pkcs12 = has_option (line, "--pkcs12");
    }

  line = skip_options (line);

  /* Break the line down into an strlist_t. */
  list = NULL;
  for (p=line; *p; line = p)
    {
      while (*p && *p != ' ')
        p++;
      if (*p)
        *p++ = 0;
      if (*line)
        {
          sl = xtrymalloc (sizeof *sl + strlen (line));
          if (!sl)
            {
              free_strlist (list);
              return out_of_core ();
            }
          sl->flags = 0;
          strcpy_escaped_plus (sl->d, line);
          sl->next = list;
          list = sl;
        }
    }

  if (opt_secret)
    {
      if (!list)
        return set_error (GPG_ERR_NO_DATA, "No key given");
      if (!*list->d)
        {
          free_strlist (list);
          return set_error (GPG_ERR_NO_DATA, "No key given");
        }
      if (list->next)
        return set_error (GPG_ERR_TOO_MANY, "Only one key allowed");
  }

  if (use_data)
    {
      estream_t stream;

      stream = es_fopencookie (ctx, "w", data_line_cookie_functions);
      if (!stream)
        {
          free_strlist (list);
          return set_error (GPG_ERR_ASS_GENERAL,
                            "error setting up a data stream");
        }
      if (opt_secret)
        gpgsm_p12_export (ctrl, list->d, stream,
                          opt_raw? 2 : opt_pkcs12 ? 0 : 1);
      else
        gpgsm_export (ctrl, list, stream);
      es_fclose (stream);
    }
  else
    {
      int fd = translate_sys2libc_fd (assuan_get_output_fd (ctx), 1);
      estream_t out_fp;

      if (fd == -1)
        {
          free_strlist (list);
          return set_error (GPG_ERR_ASS_NO_OUTPUT, NULL);
        }
      out_fp = es_fdopen_nc (fd, "w");
      if (!out_fp)
        {
          free_strlist (list);
          return set_error (gpg_err_code_from_syserror (), "fdopen() failed");
        }

      if (opt_secret)
        gpgsm_p12_export (ctrl, list->d, out_fp,
                          opt_raw? 2 : opt_pkcs12 ? 0 : 1);
      else
        gpgsm_export (ctrl, list, out_fp);
      es_fclose (out_fp);
    }

  free_strlist (list);
  /* Close and reset the fds. */
  close_message_fd (ctrl);
  assuan_close_input_fd (ctx);
  assuan_close_output_fd (ctx);
  return 0;
}



static const char hlp_delkeys[] =
  "DELKEYS <patterns>\n"
  "\n"
  "Delete the certificates specified by PATTERNS.  Each pattern shall be\n"
  "a percent-plus escaped certificate specification.  Usually a\n"
  "fingerprint will be used for this.";
static gpg_error_t
cmd_delkeys (assuan_context_t ctx, char *line)
{
  ctrl_t ctrl = assuan_get_pointer (ctx);
  char *p;
  strlist_t list, sl;
  int rc;

  /* break the line down into an strlist_t */
  list = NULL;
  for (p=line; *p; line = p)
    {
      while (*p && *p != ' ')
        p++;
      if (*p)
        *p++ = 0;
      if (*line)
        {
          sl = xtrymalloc (sizeof *sl + strlen (line));
          if (!sl)
            {
              free_strlist (list);
              return out_of_core ();
            }
          sl->flags = 0;
          strcpy_escaped_plus (sl->d, line);
          sl->next = list;
          list = sl;
        }
    }

  rc = gpgsm_delete (ctrl, list);
  free_strlist (list);

  /* close and reset the fd */
  close_message_fd (ctrl);
  assuan_close_input_fd (ctx);
  assuan_close_output_fd (ctx);

  return rc;
}



static const char hlp_output[] =
  "OUTPUT FD[=<n>]\n"
  "\n"
  "Set the file descriptor to write the output data to N.  If N is not\n"
  "given and the operating system supports file descriptor passing, the\n"
  "file descriptor currently in flight will be used.  See also the\n"
  "\"INPUT\" and \"MESSAGE\" commands.";
static const char hlp_input[] =
  "INPUT FD[=<n>]\n"
  "\n"
  "Set the file descriptor to read the input data to N.  If N is not\n"
  "given and the operating system supports file descriptor passing, the\n"
  "file descriptor currently in flight will be used.  See also the\n"
  "\"MESSAGE\" and \"OUTPUT\" commands.";
static const char hlp_message[] =
  "MESSAGE FD[=<n>]\n"
  "\n"
  "Set the file descriptor to read the message for a detached\n"
  "signatures to N.  If N is not given and the operating system\n"
  "supports file descriptor passing, the file descriptor currently in\n"
  "flight will be used.  See also the \"INPUT\" and \"OUTPUT\" commands.";
static gpg_error_t
cmd_message (assuan_context_t ctx, char *line)
{
  int rc;
  gnupg_fd_t sysfd;
  int fd;
  ctrl_t ctrl = assuan_get_pointer (ctx);

  rc = assuan_command_parse_fd (ctx, line, &sysfd);
  if (rc)
    return rc;

#ifdef HAVE_W32CE_SYSTEM
  sysfd = _assuan_w32ce_finish_pipe ((int)sysfd, 0);
  if (sysfd == INVALID_HANDLE_VALUE)
    return set_error (gpg_err_code_from_syserror (),
		      "rvid conversion failed");
#endif

  fd = translate_sys2libc_fd (sysfd, 0);
  if (fd == -1)
    return set_error (GPG_ERR_ASS_NO_INPUT, NULL);
  ctrl->server_local->message_fd = fd;
  return 0;
}



static const char hlp_listkeys[] =
  "LISTKEYS [<patterns>]\n"
  "LISTSECRETKEYS [<patterns>]\n"
  "DUMPKEYS [<patterns>]\n"
  "DUMPSECRETKEYS [<patterns>]\n"
  "\n"
  "List all certificates or only those specified by PATTERNS.  Each\n"
  "pattern shall be a percent-plus escaped certificate specification.\n"
  "The \"SECRET\" versions of the command filter the output to include\n"
  "only certificates where the secret key is available or a corresponding\n"
  "smartcard has been registered.  The \"DUMP\" versions of the command\n"
  "are only useful for debugging.  The output format is a percent escaped\n"
  "colon delimited listing as described in the manual.\n"
  "\n"
  "These \"OPTION\" command keys effect the output::\n"
  "\n"
  "  \"list-mode\" set to 0: List only local certificates (default).\n"
  "                     1: Ditto.\n"
  "                     2: List only external certificates.\n"
  "                     3: List local and external certificates.\n"
  "\n"
  "  \"with-validation\" set to true: Validate each certificate.\n"
  "\n"
  "  \"with-ephemeral-key\" set to true: Always include ephemeral\n"
  "                                    certificates.\n"
  "\n"
  "  \"list-to-output\" set to true: Write output to the file descriptor\n"
  "                                given by the last \"OUTPUT\" command.";
static int
do_listkeys (assuan_context_t ctx, char *line, int mode)
{
  ctrl_t ctrl = assuan_get_pointer (ctx);
  estream_t fp;
  char *p;
  strlist_t list, sl;
  unsigned int listmode;
  gpg_error_t err;

  /* Break the line down into an strlist. */
  list = NULL;
  for (p=line; *p; line = p)
    {
      while (*p && *p != ' ')
        p++;
      if (*p)
        *p++ = 0;
      if (*line)
        {
          sl = xtrymalloc (sizeof *sl + strlen (line));
          if (!sl)
            {
              free_strlist (list);
              return out_of_core ();
            }
          sl->flags = 0;
          strcpy_escaped_plus (sl->d, line);
          sl->next = list;
          list = sl;
        }
    }

  if (ctrl->server_local->list_to_output)
    {
      int outfd = translate_sys2libc_fd (assuan_get_output_fd (ctx), 1);

      if ( outfd == -1 )
        {
          free_strlist (list);
          return set_error (GPG_ERR_ASS_NO_OUTPUT, NULL);
        }
      fp = es_fdopen_nc (outfd, "w");
      if (!fp)
        {
          free_strlist (list);
          return set_error (gpg_err_code_from_syserror (),
                            "es_fdopen() failed");
        }
    }
  else
    {
      fp = es_fopencookie (ctx, "w", data_line_cookie_functions);
      if (!fp)
        {
          free_strlist (list);
          return set_error (GPG_ERR_ASS_GENERAL,
                            "error setting up a data stream");
        }
    }

  ctrl->with_colons = 1;
  listmode = mode;
  if (ctrl->server_local->list_internal)
    listmode |= (1<<6);
  if (ctrl->server_local->list_external)
    listmode |= (1<<7);
  err = gpgsm_list_keys (assuan_get_pointer (ctx), list, fp, listmode);
  free_strlist (list);
  es_fclose (fp);
  if (ctrl->server_local->list_to_output)
    assuan_close_output_fd (ctx);
  return err;
}

static gpg_error_t
cmd_listkeys (assuan_context_t ctx, char *line)
{
  return do_listkeys (ctx, line, 3);
}

static gpg_error_t
cmd_dumpkeys (assuan_context_t ctx, char *line)
{
  return do_listkeys (ctx, line, 259);
}

static gpg_error_t
cmd_listsecretkeys (assuan_context_t ctx, char *line)
{
  return do_listkeys (ctx, line, 2);
}

static gpg_error_t
cmd_dumpsecretkeys (assuan_context_t ctx, char *line)
{
  return do_listkeys (ctx, line, 258);
}



static const char hlp_genkey[] =
  "GENKEY\n"
  "\n"
  "Read the parameters in native format from the input fd and write a\n"
  "certificate request to the output.";
static gpg_error_t
cmd_genkey (assuan_context_t ctx, char *line)
{
  ctrl_t ctrl = assuan_get_pointer (ctx);
  int inp_fd, out_fd;
  estream_t in_stream, out_stream;
  int rc;

  (void)line;

  inp_fd = translate_sys2libc_fd (assuan_get_input_fd (ctx), 0);
  if (inp_fd == -1)
    return set_error (GPG_ERR_ASS_NO_INPUT, NULL);
  out_fd = translate_sys2libc_fd (assuan_get_output_fd (ctx), 1);
  if (out_fd == -1)
    return set_error (GPG_ERR_ASS_NO_OUTPUT, NULL);

  in_stream = es_fdopen_nc (inp_fd, "r");
  if (!in_stream)
    return set_error (GPG_ERR_ASS_GENERAL, "es_fdopen failed");

  out_stream = es_fdopen_nc (out_fd, "w");
  if (!out_stream)
    {
      es_fclose (in_stream);
      return set_error (gpg_err_code_from_syserror (), "fdopen() failed");
    }
  rc = gpgsm_genkey (ctrl, in_stream, out_stream);
  es_fclose (out_stream);
  es_fclose (in_stream);

  /* close and reset the fds */
  assuan_close_input_fd (ctx);
  assuan_close_output_fd (ctx);

  return rc;
}



static const char hlp_getauditlog[] =
  "GETAUDITLOG [--data] [--html]\n"
  "\n"
  "If --data is used, the output is send using D-lines and not to the\n"
  "file descriptor given by an OUTPUT command.\n"
  "\n"
  "If --html is used the output is formatted as an XHTML block. This is\n"
  "designed to be incorporated into a HTML document.";
static gpg_error_t
cmd_getauditlog (assuan_context_t ctx, char *line)
{
  ctrl_t ctrl = assuan_get_pointer (ctx);
  int  out_fd;
  estream_t out_stream;
  int opt_data, opt_html;
  int rc;

  opt_data = has_option (line, "--data");
  opt_html = has_option (line, "--html");
  /* Not needed: line = skip_options (line); */

  if (!ctrl->audit)
    return gpg_error (GPG_ERR_NO_DATA);

  if (opt_data)
    {
      out_stream = es_fopencookie (ctx, "w", data_line_cookie_functions);
      if (!out_stream)
        return set_error (GPG_ERR_ASS_GENERAL,
                          "error setting up a data stream");
    }
  else
    {
      out_fd = translate_sys2libc_fd (assuan_get_output_fd (ctx), 1);
      if (out_fd == -1)
        return set_error (GPG_ERR_ASS_NO_OUTPUT, NULL);

      out_stream = es_fdopen_nc (out_fd, "w");
      if (!out_stream)
        {
          return set_error (GPG_ERR_ASS_GENERAL, "es_fdopen() failed");
        }
    }

  audit_print_result (ctrl->audit, out_stream, opt_html);
  rc = 0;

  es_fclose (out_stream);

  /* Close and reset the fd. */
  if (!opt_data)
    assuan_close_output_fd (ctx);
  return rc;
}

static const char hlp_getinfo[] =
  "GETINFO <what>\n"
  "\n"
  "Multipurpose function to return a variety of information.\n"
  "Supported values for WHAT are:\n"
  "\n"
  "  version     - Return the version of the program.\n"
  "  pid         - Return the process id of the server.\n"
  "  agent-check - Return success if the agent is running.\n"
  "  cmd_has_option CMD OPT\n"
  "              - Returns OK if the command CMD implements the option OPT.\n"
  "  offline     - Returns OK if the connection is in offline mode.";
static gpg_error_t
cmd_getinfo (assuan_context_t ctx, char *line)
{
  ctrl_t ctrl = assuan_get_pointer (ctx);
  int rc = 0;

  if (!strcmp (line, "version"))
    {
      const char *s = VERSION;
      rc = assuan_send_data (ctx, s, strlen (s));
    }
  else if (!strcmp (line, "pid"))
    {
      char numbuf[50];

      snprintf (numbuf, sizeof numbuf, "%lu", (unsigned long)getpid ());
      rc = assuan_send_data (ctx, numbuf, strlen (numbuf));
    }
  else if (!strcmp (line, "agent-check"))
    {
      rc = gpgsm_agent_send_nop (ctrl);
    }
  else if (!strncmp (line, "cmd_has_option", 14)
           && (line[14] == ' ' || line[14] == '\t' || !line[14]))
    {
      char *cmd, *cmdopt;
      line += 14;
      while (*line == ' ' || *line == '\t')
        line++;
      if (!*line)
        rc = gpg_error (GPG_ERR_MISSING_VALUE);
      else
        {
          cmd = line;
          while (*line && (*line != ' ' && *line != '\t'))
            line++;
          if (!*line)
            rc = gpg_error (GPG_ERR_MISSING_VALUE);
          else
            {
              *line++ = 0;
              while (*line == ' ' || *line == '\t')
                line++;
              if (!*line)
                rc = gpg_error (GPG_ERR_MISSING_VALUE);
              else
                {
                  cmdopt = line;
                  if (!command_has_option (cmd, cmdopt))
                    rc = gpg_error (GPG_ERR_FALSE);
                }
            }
        }
    }
  else if (!strcmp (line, "offline"))
    {
      rc = ctrl->offline? 0 : gpg_error (GPG_ERR_FALSE);
    }
  else
    rc = set_error (GPG_ERR_ASS_PARAMETER, "unknown value for WHAT");

  return rc;
}


static const char hlp_passwd[] =
  "PASSWD <userID>\n"
  "\n"
  "Change the passphrase of the secret key for USERID.";
static gpg_error_t
cmd_passwd (assuan_context_t ctx, char *line)
{
  ctrl_t ctrl = assuan_get_pointer (ctx);
  gpg_error_t err;
  ksba_cert_t cert = NULL;
  char *grip = NULL;

  line = skip_options (line);

  err = gpgsm_find_cert (ctrl, line, NULL, &cert, 0);
  if (err)
    ;
  else if (!(grip = gpgsm_get_keygrip_hexstring (cert)))
    err = gpg_error (GPG_ERR_INTERNAL);
  else
    {
      char *desc = gpgsm_format_keydesc (cert);
      err = gpgsm_agent_passwd (ctrl, grip, desc);
      xfree (desc);
    }

  xfree (grip);
  ksba_cert_release (cert);

  return err;
}



/* Return true if the command CMD implements the option OPT.  */
static int
command_has_option (const char *cmd, const char *cmdopt)
{
  if (!strcmp (cmd, "IMPORT"))
    {
      if (!strcmp (cmdopt, "re-import"))
        return 1;
    }

  return 0;
}


/* Tell the assuan library about our commands */
static int
register_commands (assuan_context_t ctx)
{
  static struct {
    const char *name;
    assuan_handler_t handler;
    const char * const help;
  } table[] = {
    { "RECIPIENT",     cmd_recipient, hlp_recipient },
    { "SIGNER",        cmd_signer,    hlp_signer },
    { "ENCRYPT",       cmd_encrypt,   hlp_encrypt },
    { "DECRYPT",       cmd_decrypt,   hlp_decrypt },
    { "VERIFY",        cmd_verify,    hlp_verify },
    { "SIGN",          cmd_sign,      hlp_sign },
    { "IMPORT",        cmd_import,    hlp_import },
    { "EXPORT",        cmd_export,    hlp_export },
    { "INPUT",         NULL,          hlp_input },
    { "OUTPUT",        NULL,          hlp_output },
    { "MESSAGE",       cmd_message,   hlp_message },
    { "LISTKEYS",      cmd_listkeys,  hlp_listkeys },
    { "DUMPKEYS",      cmd_dumpkeys,  hlp_listkeys },
    { "LISTSECRETKEYS",cmd_listsecretkeys, hlp_listkeys },
    { "DUMPSECRETKEYS",cmd_dumpsecretkeys, hlp_listkeys },
    { "GENKEY",        cmd_genkey,    hlp_genkey },
    { "DELKEYS",       cmd_delkeys,   hlp_delkeys },
    { "GETAUDITLOG",   cmd_getauditlog,    hlp_getauditlog },
    { "GETINFO",       cmd_getinfo,   hlp_getinfo },
    { "PASSWD",        cmd_passwd,    hlp_passwd },
    { NULL }
  };
  int i, rc;

  for (i=0; table[i].name; i++)
    {
      rc = assuan_register_command (ctx, table[i].name, table[i].handler,
                                    table[i].help);
      if (rc)
        return rc;
    }
  return 0;
}

/* Startup the server. DEFAULT_RECPLIST is the list of recipients as
   set from the command line or config file.  We only require those
   marked as encrypt-to. */
void
gpgsm_server (certlist_t default_recplist)
{
  int rc;
  assuan_fd_t filedes[2];
  assuan_context_t ctx;
  struct server_control_s ctrl;
  static const char hello[] = ("GNU Privacy Guard's S/M server "
                               VERSION " ready");

  memset (&ctrl, 0, sizeof ctrl);
  gpgsm_init_default_ctrl (&ctrl);

  /* We use a pipe based server so that we can work from scripts.
     assuan_init_pipe_server will automagically detect when we are
     called with a socketpair and ignore FILEDES in this case. */
#ifdef HAVE_W32CE_SYSTEM
  #define SERVER_STDIN es_fileno(es_stdin)
  #define SERVER_STDOUT es_fileno(es_stdout)
#else
#define SERVER_STDIN 0
#define SERVER_STDOUT 1
#endif
  filedes[0] = assuan_fdopen (SERVER_STDIN);
  filedes[1] = assuan_fdopen (SERVER_STDOUT);
  rc = assuan_new (&ctx);
  if (rc)
    {
      log_error ("failed to allocate assuan context: %s\n",
                 gpg_strerror (rc));
      gpgsm_exit (2);
    }

  rc = assuan_init_pipe_server (ctx, filedes);
  if (rc)
    {
      log_error ("failed to initialize the server: %s\n",
                 gpg_strerror (rc));
      gpgsm_exit (2);
    }
  rc = register_commands (ctx);
  if (rc)
    {
      log_error ("failed to the register commands with Assuan: %s\n",
                 gpg_strerror(rc));
      gpgsm_exit (2);
    }
  if (opt.verbose || opt.debug)
    {
      char *tmp;

      /* Fixme: Use the really used socket name.  */
      if (asprintf (&tmp,
                    "Home: %s\n"
                    "Config: %s\n"
                    "DirmngrInfo: %s\n"
                    "%s",
                    gnupg_homedir (),
                    opt.config_filename,
                    dirmngr_socket_name (),
                    hello) > 0)
        {
          assuan_set_hello_line (ctx, tmp);
          free (tmp);
        }
    }
  else
    assuan_set_hello_line (ctx, hello);

  assuan_register_reset_notify (ctx, reset_notify);
  assuan_register_input_notify (ctx, input_notify);
  assuan_register_output_notify (ctx, output_notify);
  assuan_register_option_handler (ctx, option_handler);

  assuan_set_pointer (ctx, &ctrl);
  ctrl.server_local = xcalloc (1, sizeof *ctrl.server_local);
  ctrl.server_local->assuan_ctx = ctx;
  ctrl.server_local->message_fd = -1;
  ctrl.server_local->list_internal = 1;
  ctrl.server_local->list_external = 0;
  ctrl.server_local->default_recplist = default_recplist;

  for (;;)
    {
      rc = assuan_accept (ctx);
      if (rc == -1)
        {
          break;
        }
      else if (rc)
        {
          log_info ("Assuan accept problem: %s\n", gpg_strerror (rc));
          break;
        }

      rc = assuan_process (ctx);
      if (rc)
        {
          log_info ("Assuan processing failed: %s\n", gpg_strerror (rc));
          continue;
        }
    }

  gpgsm_release_certlist (ctrl.server_local->recplist);
  ctrl.server_local->recplist = NULL;
  gpgsm_release_certlist (ctrl.server_local->signerlist);
  ctrl.server_local->signerlist = NULL;
  xfree (ctrl.server_local);

  audit_release (ctrl.audit);
  ctrl.audit = NULL;

  assuan_release (ctx);
}



gpg_error_t
gpgsm_status2 (ctrl_t ctrl, int no, ...)
{
  gpg_error_t err = 0;
  va_list arg_ptr;
  const char *text;

  va_start (arg_ptr, no);

  if (ctrl->no_server && ctrl->status_fd == -1)
    ; /* No status wanted. */
  else if (ctrl->no_server)
    {
      if (!statusfp)
        {
          if (ctrl->status_fd == 1)
            statusfp = stdout;
          else if (ctrl->status_fd == 2)
            statusfp = stderr;
          else
            statusfp = fdopen (ctrl->status_fd, "w");

          if (!statusfp)
            {
              log_fatal ("can't open fd %d for status output: %s\n",
                         ctrl->status_fd, strerror(errno));
            }
        }

      fputs ("[GNUPG:] ", statusfp);
      fputs (get_status_string (no), statusfp);

      while ( (text = va_arg (arg_ptr, const char*) ))
        {
          putc ( ' ', statusfp );
          for (; *text; text++)
            {
              if (*text == '\n')
                fputs ( "\\n", statusfp );
              else if (*text == '\r')
                fputs ( "\\r", statusfp );
              else
                putc ( *(const byte *)text,  statusfp );
            }
        }
      putc ('\n', statusfp);
      fflush (statusfp);
    }
  else
    {
      err = vprint_assuan_status_strings (ctrl->server_local->assuan_ctx,
                                          get_status_string (no), arg_ptr);
    }

  va_end (arg_ptr);
  return err;
}

gpg_error_t
gpgsm_status (ctrl_t ctrl, int no, const char *text)
{
  return gpgsm_status2 (ctrl, no, text, NULL);
}

gpg_error_t
gpgsm_status_with_err_code (ctrl_t ctrl, int no, const char *text,
                            gpg_err_code_t ec)
{
  char buf[30];

  sprintf (buf, "%u", (unsigned int)ec);
  if (text)
    return gpgsm_status2 (ctrl, no, text, buf, NULL);
  else
    return gpgsm_status2 (ctrl, no, buf, NULL);
}

gpg_error_t
gpgsm_status_with_error (ctrl_t ctrl, int no, const char *text,
                         gpg_error_t err)
{
  char buf[30];

  snprintf (buf, sizeof buf, "%u", err);
  if (text)
    return gpgsm_status2 (ctrl, no, text, buf, NULL);
  else
    return gpgsm_status2 (ctrl, no, buf, NULL);
}


/* Helper to notify the client about Pinentry events.  Because that
   might disturb some older clients, this is only done when enabled
   via an option.  Returns an gpg error code. */
gpg_error_t
gpgsm_proxy_pinentry_notify (ctrl_t ctrl, const unsigned char *line)
{
  if (!ctrl || !ctrl->server_local
      || !ctrl->server_local->allow_pinentry_notify)
    return 0;
  return assuan_inquire (ctrl->server_local->assuan_ctx, line, NULL, NULL, 0);
}