~ubuntu-branches/ubuntu/dapper/gnupg2/dapper

« back to all changes in this revision

Viewing changes to sm/gpgsm.c

  • Committer: Bazaar Package Importer
  • Author(s): Andreas Mueller
  • Date: 2005-03-29 10:30:32 UTC
  • Revision ID: james.westby@ubuntu.com-20050329103032-sj42n2ain3ipx310
Tags: upstream-1.9.15
ImportĀ upstreamĀ versionĀ 1.9.15

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* gpgsm.c - GnuPG for S/MIME 
 
2
 * Copyright (C) 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
 
3
 *
 
4
 * This file is part of GnuPG.
 
5
 *
 
6
 * GnuPG is free software; you can redistribute it and/or modify
 
7
 * it under the terms of the GNU General Public License as published by
 
8
 * the Free Software Foundation; either version 2 of the License, or
 
9
 * (at your option) any later version.
 
10
 *
 
11
 * GnuPG is distributed in the hope that it will be useful,
 
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
14
 * GNU General Public License for more details.
 
15
 *
 
16
 * You should have received a copy of the GNU General Public License
 
17
 * along with this program; if not, write to the Free Software
 
18
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 
19
 */
 
20
 
 
21
#include <config.h>
 
22
#include <errno.h>
 
23
#include <stdio.h>
 
24
#include <stdlib.h>
 
25
#include <string.h>
 
26
#include <ctype.h>
 
27
#include <unistd.h>
 
28
#include <fcntl.h>
 
29
#ifdef USE_GNU_PTH
 
30
# include <pth.h>
 
31
#endif
 
32
 
 
33
#include "gpgsm.h"
 
34
#include <gcrypt.h>
 
35
#include <assuan.h> /* malloc hooks */
 
36
 
 
37
#include "../kbx/keybox.h" /* malloc hooks */
 
38
#include "i18n.h"
 
39
#include "keydb.h"
 
40
#include "sysutils.h"
 
41
 
 
42
 
 
43
#ifndef O_BINARY
 
44
#define O_BINARY 0
 
45
#endif
 
46
 
 
47
enum cmd_and_opt_values {
 
48
  aNull = 0,
 
49
  oArmor        = 'a',
 
50
  aDetachedSign = 'b',
 
51
  aSym          = 'c',
 
52
  aDecrypt      = 'd',
 
53
  aEncr         = 'e',
 
54
  oInteractive  = 'i',
 
55
  aListKeys     = 'k',
 
56
  aListSecretKeys = 'K',
 
57
  oDryRun       = 'n',
 
58
  oOutput       = 'o',
 
59
  oQuiet        = 'q',
 
60
  oRecipient    = 'r',
 
61
  aSign         = 's',
 
62
  oTextmodeShort= 't',
 
63
  oUser         = 'u',
 
64
  oVerbose      = 'v',
 
65
  oCompress     = 'z',
 
66
  oNotation     = 'N',
 
67
  oBatch        = 500,
 
68
  aClearsign,
 
69
  aStore,
 
70
  aKeygen,
 
71
  aSignEncr,
 
72
  aSignKey,
 
73
  aLSignKey,
 
74
  aListPackets,
 
75
  aEditKey,
 
76
  aDeleteKey,
 
77
  aImport,
 
78
  aVerify,
 
79
  aVerifyFiles,
 
80
  aListExternalKeys,
 
81
  aListSigs,
 
82
  aSendKeys,
 
83
  aRecvKeys,
 
84
  aExport,
 
85
  aExportSecretKeyP12,
 
86
  aCheckKeys, /* nyi */
 
87
  aServer,                        
 
88
  aLearnCard,
 
89
  aCallDirmngr,
 
90
  aCallProtectTool,
 
91
  aPasswd,
 
92
  aGPGConfList,
 
93
  aDumpKeys,
 
94
  aDumpSecretKeys,
 
95
  aDumpExternalKeys,
 
96
  aKeydbClearSomeCertFlags,
 
97
 
 
98
  oOptions,
 
99
  oDebug,
 
100
  oDebugLevel,
 
101
  oDebugAll,
 
102
  oDebugWait,
 
103
  oDebugAllowCoreDump,
 
104
  oDebugNoChainValidation,
 
105
  oDebugIgnoreExpiration,
 
106
  oFixedPassphrase,
 
107
  oLogFile,
 
108
 
 
109
  oEnableSpecialFilenames,
 
110
 
 
111
  oAgentProgram,
 
112
  oDisplay,
 
113
  oTTYname,
 
114
  oTTYtype,
 
115
  oLCctype,
 
116
  oLCmessages,
 
117
 
 
118
  oPreferSystemDirmngr,
 
119
  oDirmngrProgram,
 
120
  oProtectToolProgram,
 
121
  oFakedSystemTime,
 
122
 
 
123
 
 
124
  oAssumeArmor,
 
125
  oAssumeBase64,
 
126
  oAssumeBinary,
 
127
 
 
128
  oBase64,
 
129
  oNoArmor,
 
130
 
 
131
  oDisableCRLChecks,
 
132
  oEnableCRLChecks,
 
133
  oForceCRLRefresh,
 
134
 
 
135
  oDisableOCSP,
 
136
  oEnableOCSP,
 
137
 
 
138
  oIncludeCerts,
 
139
  oPolicyFile,
 
140
  oDisablePolicyChecks,
 
141
  oEnablePolicyChecks,
 
142
  oAutoIssuerKeyRetrieve,
 
143
  
 
144
 
 
145
  oTextmode,
 
146
  oFingerprint,
 
147
  oWithFingerprint,
 
148
  oWithMD5Fingerprint,
 
149
  oAnswerYes,
 
150
  oAnswerNo,
 
151
  oKeyring,
 
152
  oSecretKeyring,
 
153
  oDefaultKey,
 
154
  oDefRecipient,
 
155
  oDefRecipientSelf,
 
156
  oNoDefRecipient,
 
157
  oStatusFD,
 
158
  oNoComment,
 
159
  oNoVersion,
 
160
  oEmitVersion,
 
161
  oCompletesNeeded,
 
162
  oMarginalsNeeded,
 
163
  oMaxCertDepth,
 
164
  oLoadExtension,
 
165
  oRFC1991,
 
166
  oOpenPGP,
 
167
  oCipherAlgo,
 
168
  oDigestAlgo,
 
169
  oCompressAlgo,
 
170
  oCommandFD,
 
171
  oNoVerbose,
 
172
  oTrustDBName,
 
173
  oNoSecmemWarn,
 
174
  oNoDefKeyring,
 
175
  oNoGreeting,
 
176
  oNoTTY,
 
177
  oNoOptions,
 
178
  oNoBatch,
 
179
  oHomedir,
 
180
  oWithColons,
 
181
  oWithKeyData,
 
182
  oWithValidation,
 
183
  oWithEphemeralKeys,
 
184
  oSkipVerify,
 
185
  oCompressKeys,
 
186
  oCompressSigs,
 
187
  oAlwaysTrust,
 
188
  oRunAsShmCP,
 
189
  oSetFilename,
 
190
  oSetPolicyURL,
 
191
  oUseEmbeddedFilename,
 
192
  oComment,
 
193
  oDefaultComment,
 
194
  oThrowKeyid,
 
195
  oForceV3Sigs,
 
196
  oForceMDC,
 
197
  oS2KMode,
 
198
  oS2KDigest,
 
199
  oS2KCipher,
 
200
  oCharset,
 
201
  oNotDashEscaped,
 
202
  oEscapeFrom,
 
203
  oLockOnce,
 
204
  oLockMultiple,
 
205
  oLockNever,
 
206
  oKeyServer,
 
207
  oEncryptTo,
 
208
  oNoEncryptTo,
 
209
  oLoggerFD,
 
210
  oUtf8Strings,
 
211
  oNoUtf8Strings,
 
212
  oDisableCipherAlgo,
 
213
  oDisablePubkeyAlgo,
 
214
  oAllowNonSelfsignedUID,
 
215
  oAllowFreeformUID,
 
216
  oNoLiteral,
 
217
  oSetFilesize,
 
218
  oHonorHttpProxy,
 
219
  oFastListMode,
 
220
  oListOnly,
 
221
  oIgnoreTimeConflict,
 
222
  oNoRandomSeedFile,
 
223
  oNoAutoKeyRetrieve,
 
224
  oUseAgent,
 
225
  oMergeOnly,
 
226
  oTryAllSecrets,
 
227
  oTrustedKey,
 
228
  oEmuMDEncodeBug,
 
229
  aDummy
 
230
 };
 
231
 
 
232
 
 
233
static ARGPARSE_OPTS opts[] = {
 
234
 
 
235
    { 300, NULL, 0, N_("@Commands:\n ") },
 
236
 
 
237
    { aSign, "sign",      256, N_("|[FILE]|make a signature")},
 
238
    { aClearsign, "clearsign", 256, N_("|[FILE]|make a clear text signature") },
 
239
    { aDetachedSign, "detach-sign", 256, N_("make a detached signature")},
 
240
    { aEncr, "encrypt",   256, N_("encrypt data")},
 
241
    { aSym, "symmetric", 256, N_("encryption only with symmetric cipher")},
 
242
    { aDecrypt, "decrypt",   256, N_("decrypt data (default)")},
 
243
    { aVerify, "verify"   , 256, N_("verify a signature")},
 
244
    { aVerifyFiles, "verify-files" , 256, "@" },
 
245
    { aListKeys, "list-keys", 256, N_("list keys")},
 
246
    { aListExternalKeys, "list-external-keys", 256, N_("list external keys")},
 
247
    { aListSecretKeys, "list-secret-keys", 256, N_("list secret keys")},
 
248
    { aListSigs,   "list-sigs", 256, N_("list certificate chain")}, 
 
249
    { aListSigs,   "check-sigs",256, "@"},
 
250
    { oFingerprint, "fingerprint", 256, N_("list keys and fingerprints")},
 
251
    { aKeygen,     "gen-key",  256, N_("generate a new key pair")},
 
252
    { aDeleteKey, "delete-key",256, N_("remove key from the public keyring")},
 
253
    { aSendKeys, "send-keys"     , 256, N_("export keys to a key server") },
 
254
    { aRecvKeys, "recv-keys"     , 256, N_("import keys from a key server") },
 
255
    { aImport, "import",      256     , N_("import certificates")},
 
256
    { aExport, "export",      256     , N_("export certificates")},
 
257
    { aLearnCard, "learn-card", 256 ,N_("register a smartcard")},
 
258
    { aServer, "server",      256, N_("run in server mode")},
 
259
    { aCallDirmngr, "call-dirmngr", 256, N_("pass a command to the dirmngr")},
 
260
    { aCallProtectTool, "call-protect-tool", 256,
 
261
                                   N_("invoke gpg-protect-tool")},
 
262
    { aPasswd, "passwd",      256, N_("change a passphrase")},
 
263
    { aGPGConfList, "gpgconf-list", 256, "@" },
 
264
 
 
265
    { aDumpKeys, "dump-keys", 256, "@"},
 
266
    { aDumpExternalKeys, "dump-external-keys", 256, "@"},
 
267
    { aDumpSecretKeys, "dump-secret-keys", 256, "@"},
 
268
    { aKeydbClearSomeCertFlags, "keydb-clear-some-cert-flags", 256, "@"},
 
269
 
 
270
    { 301, NULL, 0, N_("@\nOptions:\n ") },
 
271
 
 
272
    { oArmor, "armor",     0, N_("create ascii armored output")},
 
273
    { oArmor, "armour",    0, "@" },
 
274
    { oBase64, "base64",    0, N_("create base-64 encoded output")},
 
275
    
 
276
    { oAssumeArmor,  "assume-armor", 0, N_("assume input is in PEM format")},
 
277
    { oAssumeBase64, "assume-base64", 0,
 
278
                                      N_("assume input is in base-64 format")},
 
279
    { oAssumeBinary, "assume-binary", 0,
 
280
                                      N_("assume input is in binary format")},
 
281
 
 
282
    { oRecipient, "recipient", 2, N_("|NAME|encrypt for NAME")},
 
283
 
 
284
    { oPreferSystemDirmngr,"prefer-system-dirmngr", 0,
 
285
      N_("use system's dirmngr if available")},
 
286
    { oDisableCRLChecks, "disable-crl-checks", 0, N_("never consult a CRL")},
 
287
    { oEnableCRLChecks, "enable-crl-checks", 0, "@"},
 
288
    { oForceCRLRefresh, "force-crl-refresh", 0, "@"},
 
289
 
 
290
    { oDisableOCSP, "disable-ocsp", 0, "@" },
 
291
    { oEnableOCSP,  "enable-ocsp", 0, N_("check validity using OCSP")},
 
292
 
 
293
    { oIncludeCerts, "include-certs", 1,
 
294
                                 N_("|N|number of certificates to include") },
 
295
 
 
296
    { oPolicyFile, "policy-file", 2,
 
297
                    N_("|FILE|take policy information from FILE") },
 
298
 
 
299
    { oDisablePolicyChecks, "disable-policy-checks", 0,
 
300
                           N_("do not check certificate policies")},
 
301
    { oEnablePolicyChecks, "enable-policy-checks", 0, "@"},
 
302
 
 
303
    { oAutoIssuerKeyRetrieve, "auto-issuer-key-retrieve", 0, 
 
304
      N_("fetch missing issuer certificates")},
 
305
 
 
306
#if 0
 
307
    { oDefRecipient, "default-recipient" ,2,
 
308
                                  N_("|NAME|use NAME as default recipient")},
 
309
    { oDefRecipientSelf, "default-recipient-self" ,0,
 
310
                                N_("use the default key as default recipient")},
 
311
    { oNoDefRecipient, "no-default-recipient", 0, "@" },
 
312
#endif
 
313
    { oEncryptTo, "encrypt-to", 2, "@" },
 
314
    { oNoEncryptTo, "no-encrypt-to", 0, "@" },
 
315
 
 
316
    { oUser, "local-user",2, N_("use this user-id to sign or decrypt")},
 
317
 
 
318
#if 0
 
319
    { oCompress, NULL,        1, N_("|N|set compress level N (0 disables)") },
 
320
    { oTextmodeShort, NULL,   0, "@"},
 
321
    { oTextmode, "textmode",  0, N_("use canonical text mode")},
 
322
#endif
 
323
 
 
324
    { oOutput, "output",    2, N_("use as output file")},
 
325
    { oVerbose, "verbose",   0, N_("verbose") },
 
326
    { oQuiet,   "quiet",   0, N_("be somewhat more quiet") },
 
327
    { oNoTTY, "no-tty", 0, N_("don't use the terminal at all") },
 
328
    { oLogFile, "log-file"   ,2, N_("use a log file for the server")},
 
329
#if 0
 
330
    { oForceV3Sigs, "force-v3-sigs", 0, N_("force v3 signatures") },
 
331
    { oForceMDC, "force-mdc", 0, N_("always use a MDC for encryption") },
 
332
#endif
 
333
    { oDryRun, "dry-run",   0, N_("do not make any changes") },
 
334
  /*{ oInteractive, "interactive", 0, N_("prompt before overwriting") }, */
 
335
    /*{ oUseAgent, "use-agent",0, N_("use the gpg-agent")},*/
 
336
    { oBatch, "batch",     0, N_("batch mode: never ask")},
 
337
    { oAnswerYes, "yes",       0, N_("assume yes on most questions")},
 
338
    { oAnswerNo,  "no",        0, N_("assume no on most questions")},
 
339
 
 
340
    { oKeyring, "keyring"   ,2, N_("add this keyring to the list of keyrings")},
 
341
    { oSecretKeyring, "secret-keyring" ,2, N_("add this secret keyring to the list")},
 
342
    { oDefaultKey, "default-key" ,2, N_("|NAME|use NAME as default secret key")},
 
343
    { oKeyServer, "keyserver",2, N_("|HOST|use this keyserver to lookup keys")},
 
344
    { oCharset, "charset"   , 2, N_("|NAME|set terminal charset to NAME") },
 
345
    { oOptions, "options"   , 2, N_("read options from file")},
 
346
 
 
347
    { oDebug, "debug"     ,4|16, "@"},
 
348
    { oDebugLevel, "debug-level" ,2, N_("|LEVEL|set the debugging level to LEVEL")},
 
349
    { oDebugAll, "debug-all" ,0, "@"},
 
350
    { oDebugWait, "debug-wait" ,1, "@"},
 
351
    { oDebugAllowCoreDump, "debug-allow-core-dump", 0, "@" },
 
352
    { oDebugNoChainValidation, "debug-no-chain-validation", 0, "@"},
 
353
    { oDebugIgnoreExpiration,  "debug-ignore-expiration", 0, "@"},
 
354
    { oFixedPassphrase,        "fixed-passphrase", 2, "@"},
 
355
    { oStatusFD, "status-fd" ,1, N_("|FD|write status info to this FD") },
 
356
    { aDummy, "no-comment", 0,   "@"},
 
357
    { aDummy, "completes-needed", 1, "@"},
 
358
    { aDummy, "marginals-needed", 1, "@"},
 
359
    { oMaxCertDepth,    "max-cert-depth", 1, "@" },
 
360
    { aDummy, "trusted-key", 2, "@"},
 
361
    { oLoadExtension, "load-extension" ,2,
 
362
      N_("|FILE|load extension module FILE")},
 
363
    { aDummy, "rfc1991",   0, "@"},
 
364
    { aDummy, "openpgp",   0, "@"},
 
365
    { aDummy, "s2k-mode",  1, "@"},
 
366
    { aDummy, "s2k-digest-algo",2, "@"},
 
367
    { aDummy, "s2k-cipher-algo",2, "@"},
 
368
    { oCipherAlgo, "cipher-algo", 2 , N_("|NAME|use cipher algorithm NAME")},
 
369
    { oDigestAlgo, "digest-algo", 2 ,
 
370
      N_("|NAME|use message digest algorithm NAME")},
 
371
#if 0
 
372
    { oCompressAlgo, "compress-algo", 1 , N_("|N|use compress algorithm N")},
 
373
#endif
 
374
    { aDummy, "throw-keyid", 0, "@"},
 
375
    { aDummy, "notation-data", 2, "@"},
 
376
    { aExportSecretKeyP12, "export-secret-key-p12", 256, "@"}, 
 
377
    
 
378
 
 
379
    { 302, NULL, 0, N_(
 
380
  "@\n(See the man page for a complete listing of all commands and options)\n"
 
381
                      )},
 
382
 
 
383
    { 303, NULL, 0, N_("@\nExamples:\n\n"
 
384
    " -se -r Bob [file]          sign and encrypt for user Bob\n"
 
385
    " --clearsign [file]         make a clear text signature\n"
 
386
    " --detach-sign [file]       make a detached signature\n"
 
387
    " --list-keys [names]        show keys\n"
 
388
    " --fingerprint [names]      show fingerprints\n"  ) },
 
389
 
 
390
  /* hidden options */
 
391
    { oNoVerbose, "no-verbose", 0, "@"},
 
392
 
 
393
    { oEnableSpecialFilenames, "enable-special-filenames", 0, "@" },
 
394
 
 
395
 
 
396
    { oTrustDBName, "trustdb-name", 2, "@" },
 
397
    { oNoSecmemWarn, "no-secmem-warning", 0, "@" }, 
 
398
    { oNoArmor, "no-armor",   0, "@"},
 
399
    { oNoArmor, "no-armour",   0, "@"},
 
400
    { oNoDefKeyring, "no-default-keyring", 0, "@" },
 
401
    { oNoGreeting, "no-greeting", 0, "@" },
 
402
    { oNoOptions, "no-options", 0, "@" }, /* shortcut for --options /dev/null */
 
403
    { oHomedir, "homedir", 2, "@" },   /* defaults to "~/.gnupg" */
 
404
    { oAgentProgram, "agent-program", 2 , "@" },
 
405
    { oDisplay,    "display",     2, "@" },
 
406
    { oTTYname,    "ttyname",     2, "@" },
 
407
    { oTTYtype,    "ttytype",     2, "@" },
 
408
    { oLCctype,    "lc-ctype",    2, "@" },
 
409
    { oLCmessages, "lc-messages", 2, "@" },
 
410
    { oDirmngrProgram, "dirmngr-program", 2 , "@" },
 
411
    { oProtectToolProgram, "protect-tool-program", 2 , "@" },
 
412
    { oFakedSystemTime, "faked-system-time", 4, "@" }, /* (epoch time) */
 
413
 
 
414
 
 
415
    { oNoBatch, "no-batch", 0, "@" },
 
416
    { oWithColons, "with-colons", 0, "@"},
 
417
    { oWithKeyData,"with-key-data", 0, "@"},
 
418
    { oWithValidation, "with-validation", 0, "@"},
 
419
    { oWithMD5Fingerprint, "with-md5-fingerprint", 0, "@"},
 
420
    { oWithEphemeralKeys,  "with-ephemeral-keys", 0, "@"},
 
421
    { aListKeys, "list-key", 0, "@" }, /* alias */
 
422
    { aListSigs, "list-sig", 0, "@" }, /* alias */
 
423
    { aListSigs, "check-sig",0, "@" }, /* alias */
 
424
    { oSkipVerify, "skip-verify",0, "@" },
 
425
    { oCompressKeys, "compress-keys",0, "@"},
 
426
    { oCompressSigs, "compress-sigs",0, "@"},
 
427
    { oAlwaysTrust, "always-trust", 0, "@"},
 
428
    { oNoVersion, "no-version", 0, "@"},
 
429
    { oLockOnce, "lock-once", 0, "@" },
 
430
    { oLockMultiple, "lock-multiple", 0, "@" },
 
431
    { oLockNever, "lock-never", 0, "@" },
 
432
    { oLoggerFD, "logger-fd",1, "@" },
 
433
    { oWithFingerprint, "with-fingerprint", 0, "@" },
 
434
    { oDisableCipherAlgo,  "disable-cipher-algo", 2, "@" },
 
435
    { oDisablePubkeyAlgo,  "disable-pubkey-algo", 2, "@" },
 
436
    { oHonorHttpProxy,"honor-http-proxy", 0, "@" },
 
437
    { oListOnly, "list-only", 0, "@"},
 
438
    { oIgnoreTimeConflict, "ignore-time-conflict", 0, "@" },
 
439
    { oNoRandomSeedFile,  "no-random-seed-file", 0, "@" },
 
440
{0} };
 
441
 
 
442
 
 
443
 
 
444
int gpgsm_errors_seen = 0;
 
445
 
 
446
/* It is possible that we are currentlu running under setuid permissions */
 
447
static int maybe_setuid = 1;
 
448
 
 
449
/* Helper to implement --debug-level and --debug*/
 
450
static const char *debug_level;
 
451
static unsigned int debug_value;
 
452
 
 
453
/* Option --enable-special-filenames */
 
454
static int allow_special_filenames;
 
455
 
 
456
 
 
457
static char *build_list (const char *text,
 
458
                         const char *(*mapf)(int), int (*chkf)(int));
 
459
static void set_cmd (enum cmd_and_opt_values *ret_cmd,
 
460
                     enum cmd_and_opt_values new_cmd );
 
461
 
 
462
static void emergency_cleanup (void);
 
463
static int check_special_filename (const char *fname);
 
464
static int open_read (const char *filename);
 
465
static FILE *open_fwrite (const char *filename);
 
466
static void run_protect_tool (int argc, char **argv);
 
467
 
 
468
 
 
469
static int
 
470
our_pk_test_algo (int algo)
 
471
{
 
472
  return 1;
 
473
}
 
474
 
 
475
static int
 
476
our_cipher_test_algo (int algo)
 
477
{
 
478
  return 1;
 
479
}
 
480
 
 
481
static int
 
482
our_md_test_algo (int algo)
 
483
{
 
484
  return 1;
 
485
}
 
486
 
 
487
static const char *
 
488
my_strusage( int level )
 
489
{
 
490
  static char *digests, *pubkeys, *ciphers;
 
491
  const char *p;
 
492
 
 
493
  switch (level)
 
494
    {
 
495
    case 11: p = "gpgsm (GnuPG)";
 
496
      break;
 
497
    case 13: p = VERSION; break;
 
498
    case 17: p = PRINTABLE_OS_NAME; break;
 
499
    case 19: p = _("Please report bugs to <" PACKAGE_BUGREPORT ">.\n");
 
500
      break;
 
501
    case 1:
 
502
    case 40: p = _("Usage: gpgsm [options] [files] (-h for help)");
 
503
      break;
 
504
    case 41:
 
505
      p = _("Syntax: gpgsm [options] [files]\n"
 
506
            "sign, check, encrypt or decrypt using the S/MIME protocol\n"
 
507
            "default operation depends on the input data\n");
 
508
      break;
 
509
 
 
510
    case 31: p = "\nHome: "; break;
 
511
    case 32: p = opt.homedir; break;
 
512
    case 33: p = _("\nSupported algorithms:\n"); break;
 
513
    case 34:
 
514
      if (!ciphers)
 
515
        ciphers = build_list ("Cipher: ", gcry_cipher_algo_name,
 
516
                              our_cipher_test_algo );
 
517
      p = ciphers;
 
518
      break;
 
519
    case 35:
 
520
      if (!pubkeys)
 
521
        pubkeys = build_list ("Pubkey: ", gcry_pk_algo_name,
 
522
                              our_pk_test_algo );
 
523
      p = pubkeys;
 
524
      break;
 
525
    case 36:
 
526
      if (!digests)
 
527
        digests = build_list("Hash: ", gcry_md_algo_name, our_md_test_algo );
 
528
      p = digests;
 
529
      break;
 
530
      
 
531
    default: p = NULL; break;
 
532
    }
 
533
  return p;
 
534
}
 
535
 
 
536
 
 
537
static char *
 
538
build_list (const char *text, const char * (*mapf)(int), int (*chkf)(int))
 
539
{
 
540
  int i;
 
541
  size_t n=strlen(text)+2;
 
542
  char *list, *p;
 
543
  
 
544
  if (maybe_setuid) {
 
545
    gcry_control (GCRYCTL_DROP_PRIVS); /* drop setuid */
 
546
  }
 
547
 
 
548
  for (i=1; i < 110; i++ )
 
549
    if (!chkf(i))
 
550
      n += strlen(mapf(i)) + 2;
 
551
  list = xmalloc (21 + n);
 
552
  *list = 0;
 
553
  for (p=NULL, i=1; i < 110; i++)
 
554
    {
 
555
      if (!chkf(i))
 
556
        {
 
557
          if( !p )
 
558
            p = stpcpy (list, text );
 
559
          else
 
560
            p = stpcpy (p, ", ");
 
561
          p = stpcpy (p, mapf(i) );
 
562
        }
 
563
    }
 
564
  if (p)
 
565
    p = stpcpy(p, "\n" );
 
566
  return list;
 
567
}
 
568
 
 
569
 
 
570
/* Set the file pointer into binary mode if required.  */
 
571
static void
 
572
set_binary (FILE *fp)
 
573
{
 
574
#ifdef HAVE_DOSISH_SYSTEM
 
575
  setmode (fileno (fp), O_BINARY);
 
576
#endif
 
577
}
 
578
 
 
579
 
 
580
 
 
581
static void
 
582
i18n_init(void)
 
583
{
 
584
#ifdef USE_SIMPLE_GETTEXT
 
585
  set_gettext_file (PACKAGE_GT);
 
586
#else
 
587
# ifdef ENABLE_NLS
 
588
  setlocale (LC_ALL, "" );
 
589
  bindtextdomain (PACKAGE_GT, LOCALEDIR);
 
590
  textdomain (PACKAGE_GT);
 
591
# endif
 
592
#endif
 
593
}
 
594
 
 
595
 
 
596
static void
 
597
wrong_args (const char *text)
 
598
{
 
599
  fputs (_("usage: gpgsm [options] "), stderr);
 
600
  fputs (text, stderr);
 
601
  putc ('\n', stderr);
 
602
  gpgsm_exit (2);
 
603
}
 
604
 
 
605
 
 
606
/* Setup the debugging.  With a DEBUG_LEVEL of NULL only the active
 
607
   debug flags are propagated to the subsystems.  With DEBUG_LEVEL
 
608
   set, a specific set of debug flags is set; and individual debugging
 
609
   flags will be added on top.  */
 
610
static void
 
611
set_debug (void)
 
612
{
 
613
  if (!debug_level)
 
614
    ;
 
615
  else if (!strcmp (debug_level, "none"))
 
616
    opt.debug = 0;
 
617
  else if (!strcmp (debug_level, "basic"))
 
618
    opt.debug = DBG_ASSUAN_VALUE;
 
619
  else if (!strcmp (debug_level, "advanced"))
 
620
    opt.debug = DBG_ASSUAN_VALUE|DBG_X509_VALUE;
 
621
  else if (!strcmp (debug_level, "expert"))
 
622
    opt.debug = (DBG_ASSUAN_VALUE|DBG_X509_VALUE
 
623
                 |DBG_CACHE_VALUE|DBG_CRYPTO_VALUE);
 
624
  else if (!strcmp (debug_level, "guru"))
 
625
    opt.debug = ~0;
 
626
  else
 
627
    {
 
628
      log_error (_("invalid debug-level `%s' given\n"), debug_level);
 
629
      gpgsm_exit(2);
 
630
    }
 
631
 
 
632
  opt.debug |= debug_value;
 
633
 
 
634
  if (opt.debug && !opt.verbose)
 
635
    opt.verbose = 1;
 
636
  if (opt.debug)
 
637
    opt.quiet = 0;
 
638
 
 
639
  if (opt.debug & DBG_MPI_VALUE)
 
640
    gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
 
641
  if (opt.debug & DBG_CRYPTO_VALUE )
 
642
    gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
 
643
  gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
 
644
}
 
645
 
 
646
 
 
647
 
 
648
static void
 
649
set_cmd (enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd)
 
650
{
 
651
  enum cmd_and_opt_values cmd = *ret_cmd;
 
652
 
 
653
  if (!cmd || cmd == new_cmd)
 
654
    cmd = new_cmd;
 
655
  else if ( cmd == aSign && new_cmd == aEncr )
 
656
    cmd = aSignEncr;
 
657
  else if ( cmd == aEncr && new_cmd == aSign )
 
658
    cmd = aSignEncr;
 
659
  else if ( (cmd == aSign && new_cmd == aClearsign)
 
660
            || (cmd == aClearsign && new_cmd == aSign) )
 
661
    cmd = aClearsign;
 
662
  else 
 
663
    {
 
664
      log_error(_("conflicting commands\n"));
 
665
      gpgsm_exit(2);
 
666
    }
 
667
 
 
668
  *ret_cmd = cmd;
 
669
}
 
670
 
 
671
 
 
672
/* Helper to add recipients to a list. */
 
673
static void
 
674
do_add_recipient (ctrl_t ctrl, const char *name,
 
675
                  certlist_t *recplist, int is_encrypt_to)
 
676
{
 
677
  int rc = gpgsm_add_to_certlist (ctrl, name, 0, recplist, is_encrypt_to);
 
678
  if (rc)
 
679
    {
 
680
      log_error (_("can't encrypt to `%s': %s\n"), name, gpg_strerror (rc));
 
681
      gpgsm_status2 (ctrl, STATUS_INV_RECP,
 
682
                     gpg_err_code (rc) == -1?                         "1":
 
683
                     gpg_err_code (rc) == GPG_ERR_NO_PUBKEY?          "1":
 
684
                     gpg_err_code (rc) == GPG_ERR_AMBIGUOUS_NAME?     "2":
 
685
                     gpg_err_code (rc) == GPG_ERR_WRONG_KEY_USAGE?    "3":
 
686
                     gpg_err_code (rc) == GPG_ERR_CERT_REVOKED?       "4":
 
687
                     gpg_err_code (rc) == GPG_ERR_CERT_EXPIRED?       "5":
 
688
                     gpg_err_code (rc) == GPG_ERR_NO_CRL_KNOWN?       "6":
 
689
                     gpg_err_code (rc) == GPG_ERR_CRL_TOO_OLD?        "7":
 
690
                     gpg_err_code (rc) == GPG_ERR_NO_POLICY_MATCH?    "8":
 
691
                     "0",
 
692
                     name, NULL);
 
693
    }
 
694
}
 
695
 
 
696
 
 
697
int
 
698
main ( int argc, char **argv)
 
699
{
 
700
  ARGPARSE_ARGS pargs;
 
701
  int orig_argc;
 
702
  char **orig_argv;
 
703
  const char *fname;
 
704
  /*  char *username;*/
 
705
  int may_coredump;
 
706
  STRLIST sl, remusr= NULL, locusr=NULL;
 
707
  STRLIST nrings=NULL;
 
708
  int detached_sig = 0;
 
709
  FILE *configfp = NULL;
 
710
  char *configname = NULL;
 
711
  unsigned configlineno;
 
712
  int parse_debug = 0;
 
713
  int no_more_options = 0;
 
714
  int default_config =1;
 
715
  int default_keyring = 1;
 
716
  char *logfile = NULL;
 
717
  int greeting = 0;
 
718
  int nogreeting = 0;
 
719
  int debug_wait = 0;
 
720
  int use_random_seed = 1;
 
721
  int with_fpr = 0;
 
722
  char *def_digest_string = NULL;
 
723
  enum cmd_and_opt_values cmd = 0;
 
724
  struct server_control_s ctrl;
 
725
  CERTLIST recplist = NULL;
 
726
  CERTLIST signerlist = NULL;
 
727
  int do_not_setup_keys = 0;
 
728
 
 
729
 
 
730
  /* trap_unaligned ();*/
 
731
  set_strusage (my_strusage);
 
732
  gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
 
733
  /* We don't need any locking in libgcrypt unless we use any kind of
 
734
     threading. */
 
735
  gcry_control (GCRYCTL_DISABLE_INTERNAL_LOCKING);
 
736
 
 
737
  /* Please note that we may running SUID(ROOT), so be very CAREFUL
 
738
     when adding any stuff between here and the call to secmem_init()
 
739
     somewhere after the option parsing */
 
740
  log_set_prefix ("gpgsm", 1);
 
741
 
 
742
  /* Try to auto set the character set.  */
 
743
  set_native_charset (NULL); 
 
744
 
 
745
  /* Check that the libraries are suitable.  Do it here because the
 
746
     option parse may need services of the library */
 
747
  if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
 
748
    {
 
749
      log_fatal( _("libgcrypt is too old (need %s, have %s)\n"),
 
750
                 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
 
751
    }
 
752
  if (!ksba_check_version (NEED_KSBA_VERSION) )
 
753
    {
 
754
      log_fatal( _("libksba is too old (need %s, have %s)\n"),
 
755
                 NEED_KSBA_VERSION, ksba_check_version (NULL) );
 
756
    }
 
757
 
 
758
#ifdef HAVE_W32_SYSTEM
 
759
  /* For W32 we need pth.  */
 
760
  pth_init ();
 
761
#endif
 
762
 
 
763
 
 
764
  gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
 
765
 
 
766
  may_coredump = disable_core_dumps ();
 
767
  
 
768
  gnupg_init_signals (0, emergency_cleanup);
 
769
  
 
770
  create_dotlock (NULL); /* register locking cleanup */
 
771
  i18n_init();
 
772
 
 
773
  opt.def_cipher_algoid = "1.2.840.113549.3.7";  /*des-EDE3-CBC*/
 
774
 
 
775
  opt.homedir = default_homedir ();
 
776
#ifdef HAVE_W32_SYSTEM
 
777
  opt.no_crl_check = 1;
 
778
#endif
 
779
 
 
780
  /* First check whether we have a config file on the commandline */
 
781
  orig_argc = argc;
 
782
  orig_argv = argv;
 
783
  pargs.argc = &argc;
 
784
  pargs.argv = &argv;
 
785
  pargs.flags= 1|(1<<6);  /* do not remove the args, ignore version */
 
786
  while (arg_parse( &pargs, opts))
 
787
    {
 
788
      if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
 
789
        parse_debug++;
 
790
      else if (pargs.r_opt == oOptions)
 
791
        { /* yes there is one, so we do not try the default one but
 
792
             read the config file when it is encountered at the
 
793
             commandline */
 
794
          default_config = 0;
 
795
        }
 
796
      else if (pargs.r_opt == oNoOptions)
 
797
        default_config = 0; /* --no-options */
 
798
      else if (pargs.r_opt == oHomedir)
 
799
        opt.homedir = pargs.r.ret_str;
 
800
      else if (pargs.r_opt == aCallProtectTool)
 
801
        break; /* This break makes sure that --version and --help are
 
802
                  passed to the protect-tool. */
 
803
    }
 
804
  
 
805
  
 
806
  /* initialize the secure memory. */
 
807
  gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
 
808
  maybe_setuid = 0;
 
809
 
 
810
  /* 
 
811
     Now we are now working under our real uid 
 
812
  */
 
813
 
 
814
  ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
 
815
 
 
816
  assuan_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
 
817
  assuan_set_assuan_log_stream (log_get_stream ());
 
818
  assuan_set_assuan_log_prefix (log_get_prefix (NULL));
 
819
 
 
820
  keybox_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
 
821
 
 
822
  /* Setup a default control structure for command line mode */
 
823
  memset (&ctrl, 0, sizeof ctrl);
 
824
  gpgsm_init_default_ctrl (&ctrl);
 
825
  ctrl.no_server = 1;
 
826
  ctrl.status_fd = -1; /* not status output */
 
827
  ctrl.autodetect_encoding = 1;
 
828
 
 
829
  /* Set the default option file */
 
830
  if (default_config )
 
831
    configname = make_filename (opt.homedir, "gpgsm.conf", NULL);
 
832
  /* Set the default policy file */
 
833
  opt.policy_file = make_filename (opt.homedir, "policies.txt", NULL);
 
834
  
 
835
  argc        = orig_argc;
 
836
  argv        = orig_argv;
 
837
  pargs.argc  = &argc;
 
838
  pargs.argv  = &argv;
 
839
  pargs.flags =  1;  /* do not remove the args */
 
840
 
 
841
 next_pass:
 
842
  if (configname) {
 
843
    configlineno = 0;
 
844
    configfp = fopen (configname, "r");
 
845
    if (!configfp)
 
846
      {
 
847
        if (default_config)
 
848
          {
 
849
            if (parse_debug)
 
850
              log_info (_("NOTE: no default option file `%s'\n"), configname);
 
851
          }
 
852
        else 
 
853
          {
 
854
            log_error (_("option file `%s': %s\n"), configname, strerror(errno));
 
855
            gpgsm_exit(2);
 
856
          }
 
857
        xfree(configname);
 
858
        configname = NULL;
 
859
      }
 
860
    if (parse_debug && configname)
 
861
      log_info (_("reading options from `%s'\n"), configname);
 
862
    default_config = 0;
 
863
  }
 
864
 
 
865
  while (!no_more_options 
 
866
         && optfile_parse (configfp, configname, &configlineno, &pargs, opts))
 
867
    {
 
868
      switch (pargs.r_opt)
 
869
        {
 
870
        case aGPGConfList: 
 
871
          set_cmd (&cmd, pargs.r_opt);
 
872
          do_not_setup_keys = 1;
 
873
          nogreeting = 1;
 
874
          break;
 
875
 
 
876
        case aServer: 
 
877
          opt.batch = 1;
 
878
          set_cmd (&cmd, aServer);
 
879
          break;
 
880
 
 
881
        case aCallDirmngr:
 
882
          opt.batch = 1;
 
883
          set_cmd (&cmd, aCallDirmngr);
 
884
          do_not_setup_keys = 1;
 
885
          break;
 
886
 
 
887
        case aCallProtectTool:
 
888
          opt.batch = 1;
 
889
          set_cmd (&cmd, aCallProtectTool);
 
890
          no_more_options = 1; /* Stop parsing. */
 
891
          do_not_setup_keys = 1;
 
892
          break;
 
893
        
 
894
        case aDeleteKey:
 
895
          set_cmd (&cmd, aDeleteKey);
 
896
          /*greeting=1;*/
 
897
          do_not_setup_keys = 1;
 
898
          break;
 
899
 
 
900
        case aDetachedSign:
 
901
          detached_sig = 1;
 
902
          set_cmd (&cmd, aSign ); 
 
903
          break;
 
904
 
 
905
        case aKeygen:
 
906
          set_cmd (&cmd, aKeygen);
 
907
          greeting=1; 
 
908
          do_not_setup_keys = 1;
 
909
          break;
 
910
 
 
911
        case aCheckKeys:
 
912
        case aImport: 
 
913
        case aSendKeys: 
 
914
        case aRecvKeys: 
 
915
        case aExport: 
 
916
        case aExportSecretKeyP12: 
 
917
        case aDumpKeys:
 
918
        case aDumpExternalKeys: 
 
919
        case aDumpSecretKeys: 
 
920
        case aListKeys:
 
921
        case aListExternalKeys: 
 
922
        case aListSecretKeys: 
 
923
        case aListSigs: 
 
924
        case aLearnCard: 
 
925
        case aPasswd: 
 
926
        case aKeydbClearSomeCertFlags:
 
927
          do_not_setup_keys = 1;
 
928
          set_cmd (&cmd, pargs.r_opt);
 
929
          break;
 
930
 
 
931
        case aSym:
 
932
        case aDecrypt: 
 
933
        case aEncr: 
 
934
        case aSign: 
 
935
        case aClearsign: 
 
936
        case aVerify: 
 
937
          set_cmd (&cmd, pargs.r_opt);
 
938
          break;
 
939
 
 
940
          /* output encoding selection */
 
941
        case oArmor:
 
942
          ctrl.create_pem = 1;
 
943
          break;
 
944
        case oBase64: 
 
945
          ctrl.create_pem = 0;
 
946
          ctrl.create_base64 = 1;
 
947
          break;
 
948
        case oNoArmor: 
 
949
          ctrl.create_pem = 0;
 
950
          ctrl.create_base64 = 0;
 
951
          break;
 
952
          
 
953
          /* Input encoding selection */
 
954
        case oAssumeArmor:
 
955
          ctrl.autodetect_encoding = 0;
 
956
          ctrl.is_pem = 1;
 
957
          ctrl.is_base64 = 0;
 
958
          break;
 
959
        case oAssumeBase64:
 
960
          ctrl.autodetect_encoding = 0;
 
961
          ctrl.is_pem = 0;
 
962
          ctrl.is_base64 = 1;
 
963
          break;
 
964
        case oAssumeBinary:
 
965
          ctrl.autodetect_encoding = 0;
 
966
          ctrl.is_pem = 0;
 
967
          ctrl.is_base64 = 0;
 
968
          break;
 
969
 
 
970
        case oDisableCRLChecks:
 
971
          opt.no_crl_check = 1;
 
972
          break;
 
973
        case oEnableCRLChecks:
 
974
          opt.no_crl_check = 0;
 
975
          break;
 
976
        case oForceCRLRefresh:
 
977
          opt.force_crl_refresh = 1;
 
978
          break;
 
979
 
 
980
        case oDisableOCSP:
 
981
          ctrl.use_ocsp = opt.enable_ocsp = 0;
 
982
          break;
 
983
        case oEnableOCSP:
 
984
          ctrl.use_ocsp = opt.enable_ocsp = 1;
 
985
          break;
 
986
 
 
987
        case oIncludeCerts: ctrl.include_certs = pargs.r.ret_int; break;
 
988
 
 
989
        case oPolicyFile:
 
990
          xfree (opt.policy_file);
 
991
          if (*pargs.r.ret_str)
 
992
            opt.policy_file = xstrdup (pargs.r.ret_str);
 
993
          else
 
994
            opt.policy_file = NULL;
 
995
          break;
 
996
 
 
997
        case oDisablePolicyChecks:
 
998
          opt.no_policy_check = 1;
 
999
          break;
 
1000
        case oEnablePolicyChecks:
 
1001
          opt.no_policy_check = 0;
 
1002
          break;
 
1003
          
 
1004
        case oAutoIssuerKeyRetrieve:
 
1005
          opt.auto_issuer_key_retrieve = 1;
 
1006
          break;
 
1007
 
 
1008
        case oOutput: opt.outfile = pargs.r.ret_str; break;
 
1009
 
 
1010
        
 
1011
        case oQuiet: opt.quiet = 1; break;
 
1012
        case oNoTTY: /* fixme:tty_no_terminal(1);*/ break;
 
1013
        case oDryRun: opt.dry_run = 1; break;
 
1014
 
 
1015
        case oVerbose:
 
1016
          opt.verbose++;
 
1017
          gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
 
1018
          break;
 
1019
        case oNoVerbose:
 
1020
          opt.verbose = 0;
 
1021
          gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
 
1022
          break;
 
1023
 
 
1024
        case oLogFile: logfile = pargs.r.ret_str; break;
 
1025
          
 
1026
        case oBatch: 
 
1027
          opt.batch = 1;
 
1028
          greeting = 0;
 
1029
          break;
 
1030
        case oNoBatch: opt.batch = 0; break;
 
1031
          
 
1032
        case oAnswerYes: opt.answer_yes = 1; break;
 
1033
        case oAnswerNo: opt.answer_no = 1; break;
 
1034
 
 
1035
        case oKeyring: append_to_strlist (&nrings, pargs.r.ret_str); break;
 
1036
 
 
1037
        case oDebug: debug_value |= pargs.r.ret_ulong; break;
 
1038
        case oDebugAll: debug_value = ~0; break;
 
1039
        case oDebugLevel: debug_level = pargs.r.ret_str; break;
 
1040
        case oDebugWait: debug_wait = pargs.r.ret_int; break;
 
1041
        case oDebugAllowCoreDump:
 
1042
          may_coredump = enable_core_dumps ();
 
1043
          break;
 
1044
        case oDebugNoChainValidation: opt.no_chain_validation = 1; break;
 
1045
        case oDebugIgnoreExpiration: opt.ignore_expiration = 1; break;
 
1046
        case oFixedPassphrase: opt.fixed_passphrase = pargs.r.ret_str; break;
 
1047
 
 
1048
        case oStatusFD: ctrl.status_fd = pargs.r.ret_int; break;
 
1049
        case oLoggerFD: log_set_fd (pargs.r.ret_int ); break;
 
1050
        case oWithMD5Fingerprint:
 
1051
          opt.with_md5_fingerprint=1; /*fall thru*/
 
1052
        case oWithFingerprint:
 
1053
          with_fpr=1; /*fall thru*/
 
1054
        case oFingerprint:
 
1055
          opt.fingerprint++;
 
1056
          break;
 
1057
 
 
1058
        case oOptions:
 
1059
          /* config files may not be nested (silently ignore them) */
 
1060
          if (!configfp)
 
1061
            {
 
1062
              xfree(configname);
 
1063
              configname = xstrdup (pargs.r.ret_str);
 
1064
              goto next_pass;
 
1065
            }
 
1066
          break;
 
1067
        case oNoOptions: break; /* no-options */
 
1068
        case oHomedir: opt.homedir = pargs.r.ret_str; break;
 
1069
        case oAgentProgram: opt.agent_program = pargs.r.ret_str;  break;
 
1070
        case oDisplay: opt.display = xstrdup (pargs.r.ret_str); break;
 
1071
        case oTTYname: opt.ttyname = xstrdup (pargs.r.ret_str); break;
 
1072
        case oTTYtype: opt.ttytype = xstrdup (pargs.r.ret_str); break;
 
1073
        case oLCctype: opt.lc_ctype = xstrdup (pargs.r.ret_str); break;
 
1074
        case oLCmessages: opt.lc_messages = xstrdup (pargs.r.ret_str); break;
 
1075
        case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str;  break;
 
1076
        case oPreferSystemDirmngr: opt.prefer_system_dirmngr = 1; break;
 
1077
        case oProtectToolProgram:
 
1078
          opt.protect_tool_program = pargs.r.ret_str; 
 
1079
          break;
 
1080
          
 
1081
        case oFakedSystemTime:
 
1082
          gnupg_set_time ( (time_t)pargs.r.ret_ulong, 0);
 
1083
          break;
 
1084
 
 
1085
        case oNoDefKeyring: default_keyring = 0; break;
 
1086
        case oNoGreeting: nogreeting = 1; break;
 
1087
 
 
1088
        case oDefaultKey:
 
1089
          /* fixme:opt.def_secret_key = pargs.r.ret_str;*/
 
1090
          log_info ("WARNING: --default-key has not yet been implemented\n");
 
1091
          break;
 
1092
        case oDefRecipient:
 
1093
          if (*pargs.r.ret_str)
 
1094
            opt.def_recipient = xstrdup (pargs.r.ret_str);
 
1095
          break;
 
1096
        case oDefRecipientSelf:
 
1097
          xfree (opt.def_recipient);
 
1098
          opt.def_recipient = NULL;
 
1099
          opt.def_recipient_self = 1;
 
1100
          break;
 
1101
        case oNoDefRecipient:
 
1102
          xfree (opt.def_recipient);
 
1103
          opt.def_recipient = NULL;
 
1104
          opt.def_recipient_self = 0;
 
1105
          break;
 
1106
 
 
1107
        case oWithKeyData: opt.with_key_data=1; /* fall thru */
 
1108
        case oWithColons: ctrl.with_colons = 1; break;
 
1109
        case oWithValidation: ctrl.with_validation=1; break;
 
1110
        case oWithEphemeralKeys: opt.with_ephemeral_keys=1; break;
 
1111
 
 
1112
        case oSkipVerify: opt.skip_verify=1; break;
 
1113
 
 
1114
        case oNoEncryptTo: opt.no_encrypt_to = 1; break;
 
1115
        case oEncryptTo: /* Store the recipient in the second list */
 
1116
          sl = add_to_strlist (&remusr, pargs.r.ret_str);
 
1117
          sl->flags = 1;
 
1118
          break;
 
1119
 
 
1120
        case oRecipient: /* store the recipient */
 
1121
          add_to_strlist ( &remusr, pargs.r.ret_str);
 
1122
          break;
 
1123
 
 
1124
        case oTextmodeShort: /*fixme:opt.textmode = 2;*/ break;
 
1125
        case oTextmode: /*fixme:opt.textmode=1;*/  break;
 
1126
 
 
1127
        case oUser: /* store the local users, the first one is the default */
 
1128
          if (!opt.local_user)
 
1129
            opt.local_user = pargs.r.ret_str;
 
1130
          add_to_strlist (&locusr, pargs.r.ret_str);
 
1131
          break;
 
1132
 
 
1133
        case oNoSecmemWarn:
 
1134
          gcry_control (GCRYCTL_DISABLE_SECMEM_WARN); 
 
1135
          break;
 
1136
 
 
1137
        case oCipherAlgo:
 
1138
          opt.def_cipher_algoid = pargs.r.ret_str;
 
1139
          break;
 
1140
 
 
1141
        case oDisableCipherAlgo: 
 
1142
          {
 
1143
            int algo = gcry_cipher_map_name (pargs.r.ret_str);
 
1144
            gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
 
1145
          }
 
1146
          break;
 
1147
        case oDisablePubkeyAlgo: 
 
1148
          {
 
1149
            int algo = gcry_pk_map_name (pargs.r.ret_str);
 
1150
            gcry_pk_ctl (GCRYCTL_DISABLE_ALGO,&algo, sizeof algo );
 
1151
          }
 
1152
          break;
 
1153
 
 
1154
        case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
 
1155
        case oNoRandomSeedFile: use_random_seed = 0; break;
 
1156
 
 
1157
        case oEnableSpecialFilenames: allow_special_filenames =1; break;
 
1158
          
 
1159
 
 
1160
        case aDummy:
 
1161
          break;
 
1162
        default: 
 
1163
          pargs.err = configfp? 1:2; 
 
1164
          break;
 
1165
        }
 
1166
    }
 
1167
 
 
1168
  if (configfp)
 
1169
    {
 
1170
      fclose (configfp);
 
1171
      configfp = NULL;
 
1172
      /* Keep a copy of the config filename. */
 
1173
      opt.config_filename = configname;
 
1174
      configname = NULL;
 
1175
      goto next_pass;
 
1176
    }
 
1177
  xfree (configname);
 
1178
  configname = NULL;
 
1179
 
 
1180
  if (!opt.config_filename)
 
1181
    opt.config_filename = make_filename (opt.homedir, "gpgsm.conf", NULL);
 
1182
 
 
1183
  if (log_get_errorcount(0))
 
1184
    gpgsm_exit(2);
 
1185
  
 
1186
  if (nogreeting)
 
1187
    greeting = 0;
 
1188
  
 
1189
  if (greeting)
 
1190
    {
 
1191
      fprintf(stderr, "%s %s; %s\n",
 
1192
              strusage(11), strusage(13), strusage(14) );
 
1193
      fprintf(stderr, "%s\n", strusage(15) );
 
1194
    }
 
1195
#  ifdef IS_DEVELOPMENT_VERSION
 
1196
  if (!opt.batch)
 
1197
    {
 
1198
      log_info ("NOTE: THIS IS A DEVELOPMENT VERSION!\n");
 
1199
      log_info ("It is only intended for test purposes and should NOT be\n");
 
1200
      log_info ("used in a production environment or with production keys!\n");
 
1201
    }
 
1202
#  endif
 
1203
 
 
1204
  if (may_coredump && !opt.quiet)
 
1205
    log_info (_("WARNING: program may create a core file!\n"));
 
1206
 
 
1207
  if (logfile && cmd == aServer)
 
1208
    {
 
1209
      log_set_file (logfile);
 
1210
      log_set_prefix (NULL, 1|2|4);
 
1211
    }
 
1212
 
 
1213
  if (gnupg_faked_time_p ())
 
1214
    {
 
1215
      gnupg_isotime_t tbuf;
 
1216
 
 
1217
      log_info (_("WARNING: running with faked system time: "));
 
1218
      gnupg_get_isotime (tbuf);
 
1219
      gpgsm_dump_time (tbuf);
 
1220
      log_printf ("\n");
 
1221
    }
 
1222
  
 
1223
/*FIXME    if (opt.batch) */
 
1224
/*      tty_batchmode (1); */
 
1225
 
 
1226
  gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
 
1227
 
 
1228
  set_debug ();
 
1229
 
 
1230
  /* Although we alwasy use gpgsm_exit, we better install a regualr
 
1231
     exit handler so that at least the secure memory gets wiped
 
1232
     out. */
 
1233
  if (atexit (emergency_cleanup))
 
1234
    {
 
1235
      log_error ("atexit failed\n");
 
1236
      gpgsm_exit (2);
 
1237
    }
 
1238
 
 
1239
  /* Must do this after dropping setuid, because the mapping functions
 
1240
     may try to load an module and we may have disabled an algorithm. */
 
1241
  if ( !gcry_cipher_map_name (opt.def_cipher_algoid)
 
1242
       || !gcry_cipher_mode_from_oid (opt.def_cipher_algoid))
 
1243
    log_error (_("selected cipher algorithm is invalid\n"));
 
1244
 
 
1245
  if (def_digest_string)
 
1246
    {
 
1247
      opt.def_digest_algo = gcry_md_map_name (def_digest_string);
 
1248
      xfree (def_digest_string);
 
1249
      def_digest_string = NULL;
 
1250
      if (our_md_test_algo(opt.def_digest_algo) )
 
1251
        log_error (_("selected digest algorithm is invalid\n"));
 
1252
    }
 
1253
 
 
1254
  if (log_get_errorcount(0))
 
1255
    gpgsm_exit(2);
 
1256
  
 
1257
  /* Set the random seed file. */
 
1258
  if (use_random_seed) {
 
1259
    char *p = make_filename (opt.homedir, "random_seed", NULL);
 
1260
    gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
 
1261
    xfree(p);
 
1262
  }
 
1263
 
 
1264
 
 
1265
  if (!cmd && opt.fingerprint && !with_fpr)
 
1266
    set_cmd (&cmd, aListKeys);
 
1267
  
 
1268
  if (!nrings && default_keyring)  /* add default keybox */
 
1269
    keydb_add_resource ("pubring.kbx", 0, 0);
 
1270
  for (sl = nrings; sl; sl = sl->next)
 
1271
    keydb_add_resource (sl->d, 0, 0);
 
1272
  FREE_STRLIST(nrings);
 
1273
 
 
1274
  if (!do_not_setup_keys)
 
1275
    {
 
1276
      for (sl = locusr; sl ; sl = sl->next)
 
1277
        {
 
1278
          int rc = gpgsm_add_to_certlist (&ctrl, sl->d, 1, &signerlist, 0);
 
1279
          if (rc)
 
1280
            {
 
1281
              log_error (_("can't sign using `%s': %s\n"),
 
1282
                         sl->d, gpg_strerror (rc));
 
1283
              gpgsm_status2 (&ctrl, STATUS_INV_RECP,
 
1284
                         gpg_err_code (rc) == -1?                      "1":
 
1285
                         gpg_err_code (rc) == GPG_ERR_NO_PUBKEY?       "1":
 
1286
                         gpg_err_code (rc) == GPG_ERR_AMBIGUOUS_NAME?  "2":
 
1287
                         gpg_err_code (rc) == GPG_ERR_WRONG_KEY_USAGE? "3":
 
1288
                         gpg_err_code (rc) == GPG_ERR_CERT_REVOKED?    "4":
 
1289
                         gpg_err_code (rc) == GPG_ERR_CERT_EXPIRED?    "5":
 
1290
                         gpg_err_code (rc) == GPG_ERR_NO_CRL_KNOWN?    "6":
 
1291
                         gpg_err_code (rc) == GPG_ERR_CRL_TOO_OLD?     "7":
 
1292
                         gpg_err_code (rc) == GPG_ERR_NO_POLICY_MATCH? "8":
 
1293
                         gpg_err_code (rc) == GPG_ERR_NO_SECKEY?       "9":
 
1294
                         "0",
 
1295
                         sl->d, NULL);
 
1296
            }
 
1297
        }
 
1298
      
 
1299
      /* Build the recipient list.  We first add the regular ones and then
 
1300
         the encrypt-to ones because the underlying function will silenty
 
1301
         ignore duplicates and we can't allow to keep a duplicate which is
 
1302
         flagged as encrypt-to as the actually encrypt function would then
 
1303
         complain about no (regular) recipients. */
 
1304
      for (sl = remusr; sl; sl = sl->next)
 
1305
        if (!(sl->flags & 1))
 
1306
          do_add_recipient (&ctrl, sl->d, &recplist, 0);
 
1307
      if (!opt.no_encrypt_to)
 
1308
        {
 
1309
          for (sl = remusr; sl; sl = sl->next)
 
1310
            if ((sl->flags & 1))
 
1311
              do_add_recipient (&ctrl, sl->d, &recplist, 1);
 
1312
        }
 
1313
    }
 
1314
 
 
1315
  if (log_get_errorcount(0))
 
1316
    gpgsm_exit(1); /* must stop for invalid recipients */
 
1317
  
 
1318
  fname = argc? *argv : NULL;
 
1319
  
 
1320
  switch (cmd)
 
1321
    {
 
1322
    case aGPGConfList: 
 
1323
      { /* List options and default values in the GPG Conf format.  */
 
1324
 
 
1325
        /* The following list is taken from gnupg/tools/gpgconf-comp.c.  */
 
1326
        /* Option flags.  YOU MUST NOT CHANGE THE NUMBERS OF THE EXISTING
 
1327
           FLAGS, AS THEY ARE PART OF THE EXTERNAL INTERFACE.  */
 
1328
#define GC_OPT_FLAG_NONE        0UL
 
1329
        /* The RUNTIME flag for an option indicates that the option can be
 
1330
           changed at runtime.  */
 
1331
#define GC_OPT_FLAG_RUNTIME     (1UL << 3)
 
1332
        /* The DEFAULT flag for an option indicates that the option has a
 
1333
           default value.  */
 
1334
#define GC_OPT_FLAG_DEFAULT     (1UL << 4)
 
1335
        /* The DEF_DESC flag for an option indicates that the option has a
 
1336
           default, which is described by the value of the default field.  */
 
1337
#define GC_OPT_FLAG_DEF_DESC    (1UL << 5)
 
1338
        /* The NO_ARG_DESC flag for an option indicates that the argument has
 
1339
           a default, which is described by the value of the ARGDEF field.  */
 
1340
#define GC_OPT_FLAG_NO_ARG_DESC (1UL << 6)
 
1341
 
 
1342
        printf ("gpgconf-gpgsm.conf:%lu:\"%s\n",
 
1343
                GC_OPT_FLAG_DEFAULT, opt.config_filename);
 
1344
        
 
1345
        printf ("verbose:%lu:\n"
 
1346
                "quiet:%lu:\n"
 
1347
                "debug-level:%lu:\"none:\n"
 
1348
                "log-file:%lu:\n",
 
1349
                GC_OPT_FLAG_NONE,
 
1350
                GC_OPT_FLAG_NONE,
 
1351
                GC_OPT_FLAG_DEFAULT,
 
1352
                GC_OPT_FLAG_NONE );
 
1353
        printf ("disable-crl-checks:%lu:\n",
 
1354
                GC_OPT_FLAG_NONE );
 
1355
        printf ("enable-ocsp:%lu:\n",
 
1356
                GC_OPT_FLAG_NONE );
 
1357
        printf ("include-certs:%lu:1:\n",
 
1358
                GC_OPT_FLAG_DEFAULT );
 
1359
        printf ("disable-policy-checks:%lu:\n",
 
1360
                GC_OPT_FLAG_NONE );
 
1361
        printf ("auto-issuer-key-retrieve:%lu:\n",
 
1362
                GC_OPT_FLAG_NONE );
 
1363
        printf ("prefer-system-dirmngr:%lu:\n",
 
1364
                GC_OPT_FLAG_NONE );
 
1365
 
 
1366
      }
 
1367
      break;
 
1368
 
 
1369
    case aServer:
 
1370
      if (debug_wait)
 
1371
        {
 
1372
          log_debug ("waiting for debugger - my pid is %u .....\n",
 
1373
                     (unsigned int)getpid());
 
1374
          sleep (debug_wait);
 
1375
          log_debug ("... okay\n");
 
1376
         }
 
1377
      gpgsm_server (recplist);
 
1378
      break;
 
1379
 
 
1380
    case aCallDirmngr:
 
1381
      if (!argc)
 
1382
        wrong_args ("--call-dirmngr <command> {args}");
 
1383
      else
 
1384
        if (gpgsm_dirmngr_run_command (&ctrl, *argv, argc-1, argv+1))
 
1385
          gpgsm_exit (1);
 
1386
      break;
 
1387
 
 
1388
    case aCallProtectTool:
 
1389
      run_protect_tool (argc, argv);
 
1390
      break;
 
1391
 
 
1392
    case aEncr: /* encrypt the given file */
 
1393
      set_binary (stdin);
 
1394
      set_binary (stdout);
 
1395
      if (!argc)
 
1396
        gpgsm_encrypt (&ctrl, recplist, 0, stdout); /* from stdin */
 
1397
      else if (argc == 1)
 
1398
        gpgsm_encrypt (&ctrl, recplist, open_read (*argv), stdout); /* from file */
 
1399
      else
 
1400
        wrong_args ("--encrypt [datafile]");
 
1401
      break;
 
1402
 
 
1403
    case aSign: /* sign the given file */
 
1404
      /* FIXME: We don't handle --output yet. We should also allow
 
1405
         to concatenate multiple files for signing because that is
 
1406
         what gpg does.*/
 
1407
      set_binary (stdin);
 
1408
      set_binary (stdout);
 
1409
      if (!argc)
 
1410
        gpgsm_sign (&ctrl, signerlist,
 
1411
                    0, detached_sig, stdout); /* create from stdin */
 
1412
      else if (argc == 1)
 
1413
        gpgsm_sign (&ctrl, signerlist,
 
1414
                    open_read (*argv), detached_sig, stdout); /* from file */
 
1415
      else
 
1416
        wrong_args ("--sign [datafile]");
 
1417
      break;
 
1418
        
 
1419
    case aSignEncr: /* sign and encrypt the given file */
 
1420
      log_error ("this command has not yet been implemented\n");
 
1421
      break;
 
1422
 
 
1423
    case aClearsign: /* make a clearsig */
 
1424
      log_error ("this command has not yet been implemented\n");
 
1425
      break;
 
1426
 
 
1427
    case aVerify:
 
1428
      {
 
1429
        FILE *fp = NULL;
 
1430
 
 
1431
        set_binary (stdin);
 
1432
        if (argc == 2 && opt.outfile)
 
1433
          log_info ("option --output ignored for a detached signature\n");
 
1434
        else if (opt.outfile)
 
1435
          fp = open_fwrite (opt.outfile);
 
1436
 
 
1437
        if (!argc)
 
1438
          gpgsm_verify (&ctrl, 0, -1, fp); /* normal signature from stdin */
 
1439
        else if (argc == 1)
 
1440
          gpgsm_verify (&ctrl, open_read (*argv), -1, fp); /* std signature */
 
1441
        else if (argc == 2) /* detached signature (sig, detached) */
 
1442
          gpgsm_verify (&ctrl, open_read (*argv), open_read (argv[1]), NULL); 
 
1443
        else
 
1444
          wrong_args ("--verify [signature [detached_data]]");
 
1445
 
 
1446
        if (fp && fp != stdout)
 
1447
          fclose (fp);
 
1448
      }
 
1449
      break;
 
1450
 
 
1451
    case aVerifyFiles:
 
1452
      log_error (_("this command has not yet been implemented\n"));
 
1453
      break;
 
1454
 
 
1455
    case aDecrypt:
 
1456
      set_binary (stdin);
 
1457
      set_binary (stdout);
 
1458
      if (!argc)
 
1459
        gpgsm_decrypt (&ctrl, 0, stdout); /* from stdin */
 
1460
      else if (argc == 1)
 
1461
        gpgsm_decrypt (&ctrl, open_read (*argv), stdout); /* from file */
 
1462
      else
 
1463
        wrong_args ("--decrypt [filename]");
 
1464
      break;
 
1465
 
 
1466
    case aDeleteKey:
 
1467
      for (sl=NULL; argc; argc--, argv++)
 
1468
        add_to_strlist (&sl, *argv);
 
1469
      gpgsm_delete (&ctrl, sl);
 
1470
      free_strlist(sl);
 
1471
      break;
 
1472
 
 
1473
    case aListSigs:
 
1474
      ctrl.with_chain = 1;
 
1475
    case aListKeys:
 
1476
      for (sl=NULL; argc; argc--, argv++)
 
1477
        add_to_strlist (&sl, *argv);
 
1478
      gpgsm_list_keys (&ctrl, sl, stdout, (0 | (1<<6)));
 
1479
      free_strlist(sl);
 
1480
      break;
 
1481
 
 
1482
    case aDumpKeys:
 
1483
      for (sl=NULL; argc; argc--, argv++)
 
1484
        add_to_strlist (&sl, *argv);
 
1485
      gpgsm_list_keys (&ctrl, sl, stdout, (256 | (1<<6)));
 
1486
      free_strlist(sl);
 
1487
      break;
 
1488
 
 
1489
    case aListExternalKeys:
 
1490
      for (sl=NULL; argc; argc--, argv++)
 
1491
        add_to_strlist (&sl, *argv);
 
1492
      gpgsm_list_keys (&ctrl, sl, stdout,
 
1493
                       (0 | (1<<7)));
 
1494
      free_strlist(sl);
 
1495
      break;
 
1496
 
 
1497
    case aDumpExternalKeys:
 
1498
      for (sl=NULL; argc; argc--, argv++)
 
1499
        add_to_strlist (&sl, *argv);
 
1500
      gpgsm_list_keys (&ctrl, sl, stdout,
 
1501
                       (256 | (1<<7)));
 
1502
      free_strlist(sl);
 
1503
      break;
 
1504
 
 
1505
    case aListSecretKeys:
 
1506
      for (sl=NULL; argc; argc--, argv++)
 
1507
        add_to_strlist (&sl, *argv);
 
1508
      gpgsm_list_keys (&ctrl, sl, stdout, (2 | (1<<6)));
 
1509
      free_strlist(sl);
 
1510
      break;
 
1511
 
 
1512
    case aDumpSecretKeys:
 
1513
      for (sl=NULL; argc; argc--, argv++)
 
1514
        add_to_strlist (&sl, *argv);
 
1515
      gpgsm_list_keys (&ctrl, sl, stdout, (256 | 2 | (1<<6)));
 
1516
      free_strlist(sl);
 
1517
      break;
 
1518
 
 
1519
    case aKeygen: /* generate a key */
 
1520
      log_error ("this function is not yet available from the commandline\n");
 
1521
      break;
 
1522
 
 
1523
    case aImport:
 
1524
      gpgsm_import_files (&ctrl, argc, argv, open_read);
 
1525
      break;
 
1526
 
 
1527
    case aExport:
 
1528
      set_binary (stdout);
 
1529
      for (sl=NULL; argc; argc--, argv++)
 
1530
        add_to_strlist (&sl, *argv);
 
1531
      gpgsm_export (&ctrl, sl, stdout);
 
1532
      free_strlist(sl);
 
1533
      break;
 
1534
 
 
1535
    case aExportSecretKeyP12:
 
1536
      set_binary (stdout);
 
1537
      if (argc == 1)
 
1538
        gpgsm_p12_export (&ctrl, *argv, stdout);
 
1539
      else
 
1540
        wrong_args ("--export-secret-key-p12 KEY-ID");
 
1541
      break;
 
1542
      
 
1543
    case aSendKeys:
 
1544
    case aRecvKeys:
 
1545
      log_error ("this command has not yet been implemented\n");
 
1546
      break;
 
1547
 
 
1548
 
 
1549
    case aLearnCard:
 
1550
      if (argc)
 
1551
        wrong_args ("--learn-card");
 
1552
      else
 
1553
        {
 
1554
          int rc = gpgsm_agent_learn (&ctrl);
 
1555
          if (rc)
 
1556
            log_error ("error learning card: %s\n", gpg_strerror (rc));
 
1557
        }
 
1558
      break;
 
1559
 
 
1560
    case aPasswd:
 
1561
      if (argc != 1)
 
1562
        wrong_args ("--passwd <key-Id>");
 
1563
      else
 
1564
        {
 
1565
          int rc;
 
1566
          ksba_cert_t cert = NULL;
 
1567
          char *grip = NULL;
 
1568
 
 
1569
          rc = gpgsm_find_cert (*argv, &cert);
 
1570
          if (rc)
 
1571
            ;
 
1572
          else if (!(grip = gpgsm_get_keygrip_hexstring (cert)))
 
1573
            rc = gpg_error (GPG_ERR_BUG);
 
1574
          else 
 
1575
            {
 
1576
              char *desc = gpgsm_format_keydesc (cert);
 
1577
              rc = gpgsm_agent_passwd (&ctrl, grip, desc);
 
1578
              xfree (desc);
 
1579
            }
 
1580
          if (rc)
 
1581
            log_error ("error changing passphrase: %s\n", gpg_strerror (rc));
 
1582
          xfree (grip);
 
1583
          ksba_cert_release (cert);
 
1584
        }
 
1585
      break;
 
1586
 
 
1587
    case aKeydbClearSomeCertFlags:
 
1588
      for (sl=NULL; argc; argc--, argv++)
 
1589
        add_to_strlist (&sl, *argv);
 
1590
      keydb_clear_some_cert_flags (&ctrl, sl);
 
1591
      free_strlist(sl);
 
1592
      break;
 
1593
 
 
1594
 
 
1595
    default:
 
1596
        log_error ("invalid command (there is no implicit command)\n");
 
1597
        break;
 
1598
    }
 
1599
  
 
1600
  /* cleanup */
 
1601
  gpgsm_release_certlist (recplist);
 
1602
  gpgsm_release_certlist (signerlist);
 
1603
  FREE_STRLIST(remusr);
 
1604
  FREE_STRLIST(locusr);
 
1605
  gpgsm_exit(0);
 
1606
  return 8; /*NEVER REACHED*/
 
1607
}
 
1608
 
 
1609
/* Note: This function is used by signal handlers!. */
 
1610
static void
 
1611
emergency_cleanup (void)
 
1612
{
 
1613
  gcry_control (GCRYCTL_TERM_SECMEM );
 
1614
}
 
1615
 
 
1616
 
 
1617
void
 
1618
gpgsm_exit (int rc)
 
1619
{
 
1620
  gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
 
1621
  if (opt.debug & DBG_MEMSTAT_VALUE)
 
1622
    {
 
1623
      gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
 
1624
      gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
 
1625
    }
 
1626
  if (opt.debug)
 
1627
    gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
 
1628
  emergency_cleanup ();
 
1629
  rc = rc? rc : log_get_errorcount(0)? 2 : gpgsm_errors_seen? 1 : 0;
 
1630
  exit (rc);
 
1631
}
 
1632
 
 
1633
 
 
1634
void
 
1635
gpgsm_init_default_ctrl (struct server_control_s *ctrl)
 
1636
{
 
1637
  ctrl->include_certs = 1;  /* only include the signer's cert */
 
1638
  ctrl->use_ocsp = opt.enable_ocsp;
 
1639
}
 
1640
 
 
1641
 
 
1642
 
 
1643
/* Check whether the filename has the form "-&nnnn", where n is a
 
1644
   non-zero number.  Returns this number or -1 if it is not the case.  */
 
1645
static int
 
1646
check_special_filename (const char *fname)
 
1647
{
 
1648
  if (allow_special_filenames
 
1649
      && fname && *fname == '-' && fname[1] == '&' ) {
 
1650
    int i;
 
1651
    
 
1652
    fname += 2;
 
1653
    for (i=0; isdigit (fname[i]); i++ )
 
1654
      ;
 
1655
    if ( !fname[i] ) 
 
1656
      return atoi (fname);
 
1657
  }
 
1658
  return -1;
 
1659
}
 
1660
 
 
1661
 
 
1662
 
 
1663
/* Open the FILENAME for read and return the filedescriptor.  Stop
 
1664
   with an error message in case of problems.  "-" denotes stdin and
 
1665
   if special filenames are allowed the given fd is opened instead. */
 
1666
static int 
 
1667
open_read (const char *filename)
 
1668
{
 
1669
  int fd;
 
1670
 
 
1671
  if (filename[0] == '-' && !filename[1])
 
1672
    {
 
1673
      set_binary (stdin);
 
1674
      return 0; /* stdin */
 
1675
    }
 
1676
  fd = check_special_filename (filename);
 
1677
  if (fd != -1)
 
1678
    return fd;
 
1679
  fd = open (filename, O_RDONLY | O_BINARY);
 
1680
  if (fd == -1)
 
1681
    {
 
1682
      log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
 
1683
      gpgsm_exit (2);
 
1684
    }
 
1685
  return fd;
 
1686
}
 
1687
 
 
1688
/* Open FILENAME for fwrite and return the stream.  Stop with an error
 
1689
   message in case of problems.  "-" denotes stdout and if special
 
1690
   filenames are allowed the given fd is opened instead. Caller must
 
1691
   close the returned stream unless it is stdout. */
 
1692
static FILE *
 
1693
open_fwrite (const char *filename)
 
1694
{
 
1695
  int fd;
 
1696
  FILE *fp;
 
1697
 
 
1698
  if (filename[0] == '-' && !filename[1])
 
1699
    {
 
1700
      set_binary (stdout);
 
1701
      return stdout;
 
1702
    }
 
1703
 
 
1704
  fd = check_special_filename (filename);
 
1705
  if (fd != -1)
 
1706
    {
 
1707
      fp = fdopen (dup (fd), "wb");
 
1708
      if (!fp)
 
1709
        {
 
1710
          log_error ("fdopen(%d) failed: %s\n", fd, strerror (errno));
 
1711
          gpgsm_exit (2);
 
1712
        }
 
1713
      set_binary (fp);
 
1714
      return fp;
 
1715
    }
 
1716
  fp = fopen (filename, "wb");
 
1717
  if (!fp)
 
1718
    {
 
1719
      log_error (_("can't open `%s': %s\n"), filename, strerror (errno));
 
1720
      gpgsm_exit (2);
 
1721
    }
 
1722
  return fp;
 
1723
}
 
1724
 
 
1725
 
 
1726
static void
 
1727
run_protect_tool (int argc, char **argv)
 
1728
{
 
1729
#ifndef HAVE_W32_SYSTEM
 
1730
  const char *pgm;
 
1731
  char **av;
 
1732
  int i;
 
1733
 
 
1734
  if (!opt.protect_tool_program || !*opt.protect_tool_program)
 
1735
    pgm = GNUPG_DEFAULT_PROTECT_TOOL;
 
1736
  else
 
1737
    pgm = opt.protect_tool_program;
 
1738
 
 
1739
  av = xcalloc (argc+2, sizeof *av);
 
1740
  av[0] = strrchr (pgm, '/');
 
1741
  if (!av[0])
 
1742
    av[0] = xstrdup (pgm);
 
1743
  for (i=1; argc; i++, argc--, argv++)
 
1744
    av[i] = *argv;
 
1745
  av[i] = NULL;
 
1746
  execv (pgm, av); 
 
1747
  log_error ("error executing `%s': %s\n", pgm, strerror (errno));
 
1748
#endif /*HAVE_W32_SYSTEM*/
 
1749
  gpgsm_exit (2);
 
1750
}