a8f42e0b74095a4cd6b3d86dea201fcdcef21ba5
[platform/upstream/gpg2.git] / g10 / gpg.c
1 /* gpg.c - The GnuPG utility (main for gpg)
2  * Copyright (C) 1998-2019 Free Software Foundation, Inc.
3  * Copyright (C) 1997-2019 Werner Koch
4  * Copyright (C) 2015-2019 g10 Code GmbH
5  *
6  * This file is part of GnuPG.
7  *
8  * GnuPG is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * GnuPG is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, see <https://www.gnu.org/licenses/>.
20  */
21
22 #include <config.h>
23 #include <errno.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <ctype.h>
28 #include <unistd.h>
29 #ifdef HAVE_STAT
30 #include <sys/stat.h> /* for stat() */
31 #endif
32 #include <fcntl.h>
33 #ifdef HAVE_W32_SYSTEM
34 # ifdef HAVE_WINSOCK2_H
35 #  include <winsock2.h>
36 # endif
37 # include <windows.h>
38 #endif
39
40 #define INCLUDED_BY_MAIN_MODULE 1
41 #include "gpg.h"
42 #include <assuan.h>
43 #include "../common/iobuf.h"
44 #include "../common/util.h"
45 #include "packet.h"
46 #include "../common/membuf.h"
47 #include "main.h"
48 #include "options.h"
49 #include "keydb.h"
50 #include "trustdb.h"
51 #include "filter.h"
52 #include "../common/ttyio.h"
53 #include "../common/i18n.h"
54 #include "../common/sysutils.h"
55 #include "../common/status.h"
56 #include "keyserver-internal.h"
57 #include "exec.h"
58 #include "../common/gc-opt-flags.h"
59 #include "../common/asshelp.h"
60 #include "call-dirmngr.h"
61 #include "tofu.h"
62 #include "../common/init.h"
63 #include "../common/mbox-util.h"
64 #include "../common/shareddefs.h"
65 #include "../common/compliance.h"
66
67 #if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
68 #define MY_O_BINARY  O_BINARY
69 #ifndef S_IRGRP
70 # define S_IRGRP 0
71 # define S_IWGRP 0
72 #endif
73 #else
74 #define MY_O_BINARY  0
75 #endif
76
77 #ifdef __MINGW32__
78 int _dowildcard = -1;
79 #endif
80
81 enum cmd_and_opt_values
82   {
83     aNull = 0,
84     oArmor        = 'a',
85     aDetachedSign = 'b',
86     aSym          = 'c',
87     aDecrypt      = 'd',
88     aEncr         = 'e',
89     oRecipientFile       = 'f',
90     oHiddenRecipientFile = 'F',
91     oInteractive  = 'i',
92     aListKeys     = 'k',
93     oDryRun       = 'n',
94     oOutput       = 'o',
95     oQuiet        = 'q',
96     oRecipient    = 'r',
97     oHiddenRecipient = 'R',
98     aSign         = 's',
99     oTextmodeShort= 't',
100     oLocalUser    = 'u',
101     oVerbose      = 'v',
102     oCompress     = 'z',
103     oSetNotation  = 'N',
104     aListSecretKeys = 'K',
105     oBatch        = 500,
106     oMaxOutput,
107     oInputSizeHint,
108     oSigNotation,
109     oCertNotation,
110     oShowNotation,
111     oNoShowNotation,
112     oKnownNotation,
113     aEncrFiles,
114     aEncrSym,
115     aDecryptFiles,
116     aClearsign,
117     aStore,
118     aQuickKeygen,
119     aFullKeygen,
120     aKeygen,
121     aSignEncr,
122     aSignEncrSym,
123     aSignSym,
124     aSignKey,
125     aLSignKey,
126     aQuickSignKey,
127     aQuickLSignKey,
128     aQuickAddUid,
129     aQuickAddKey,
130     aQuickRevUid,
131     aQuickSetExpire,
132     aQuickSetPrimaryUid,
133     aListConfig,
134     aListGcryptConfig,
135     aGPGConfList,
136     aGPGConfTest,
137     aListPackets,
138     aEditKey,
139     aDeleteKeys,
140     aDeleteSecretKeys,
141     aDeleteSecretAndPublicKeys,
142     aImport,
143     aFastImport,
144     aVerify,
145     aVerifyFiles,
146     aListSigs,
147     aSendKeys,
148     aRecvKeys,
149     aLocateKeys,
150     aSearchKeys,
151     aRefreshKeys,
152     aFetchKeys,
153     aShowKeys,
154     aExport,
155     aExportSecret,
156     aExportSecretSub,
157     aExportSshKey,
158     aCheckKeys,
159     aGenRevoke,
160     aDesigRevoke,
161     aPrimegen,
162     aPrintMD,
163     aPrintMDs,
164     aCheckTrustDB,
165     aUpdateTrustDB,
166     aFixTrustDB,
167     aListTrustDB,
168     aListTrustPath,
169     aExportOwnerTrust,
170     aImportOwnerTrust,
171     aDeArmor,
172     aEnArmor,
173     aGenRandom,
174     aRebuildKeydbCaches,
175     aCardStatus,
176     aCardEdit,
177     aChangePIN,
178     aPasswd,
179     aServer,
180     aTOFUPolicy,
181
182     oMimemode,
183     oTextmode,
184     oNoTextmode,
185     oExpert,
186     oNoExpert,
187     oDefSigExpire,
188     oAskSigExpire,
189     oNoAskSigExpire,
190     oDefCertExpire,
191     oAskCertExpire,
192     oNoAskCertExpire,
193     oDefCertLevel,
194     oMinCertLevel,
195     oAskCertLevel,
196     oNoAskCertLevel,
197     oFingerprint,
198     oWithFingerprint,
199     oWithSubkeyFingerprint,
200     oWithICAOSpelling,
201     oWithKeygrip,
202     oWithSecret,
203     oWithWKDHash,
204     oWithColons,
205     oWithKeyData,
206     oWithKeyOrigin,
207     oWithTofuInfo,
208     oWithSigList,
209     oWithSigCheck,
210     oAnswerYes,
211     oAnswerNo,
212     oKeyring,
213     oPrimaryKeyring,
214     oSecretKeyring,
215     oShowKeyring,
216     oDefaultKey,
217     oDefRecipient,
218     oDefRecipientSelf,
219     oNoDefRecipient,
220     oTrySecretKey,
221     oOptions,
222     oDebug,
223     oDebugLevel,
224     oDebugAll,
225     oDebugIOLBF,
226     oStatusFD,
227     oStatusFile,
228     oAttributeFD,
229     oAttributeFile,
230     oEmitVersion,
231     oNoEmitVersion,
232     oCompletesNeeded,
233     oMarginalsNeeded,
234     oMaxCertDepth,
235     oLoadExtension,
236     oCompliance,
237     oGnuPG,
238     oRFC2440,
239     oRFC4880,
240     oRFC4880bis,
241     oOpenPGP,
242     oPGP6,
243     oPGP7,
244     oPGP8,
245     oDE_VS,
246     oRFC2440Text,
247     oNoRFC2440Text,
248     oCipherAlgo,
249     oDigestAlgo,
250     oCertDigestAlgo,
251     oCompressAlgo,
252     oCompressLevel,
253     oBZ2CompressLevel,
254     oBZ2DecompressLowmem,
255     oPassphrase,
256     oPassphraseFD,
257     oPassphraseFile,
258     oPassphraseRepeat,
259     oPinentryMode,
260     oCommandFD,
261     oCommandFile,
262     oQuickRandom,
263     oNoVerbose,
264     oTrustDBName,
265     oNoSecmemWarn,
266     oRequireSecmem,
267     oNoRequireSecmem,
268     oNoPermissionWarn,
269     oNoArmor,
270     oNoDefKeyring,
271     oNoKeyring,
272     oNoGreeting,
273     oNoTTY,
274     oNoOptions,
275     oNoBatch,
276     oHomedir,
277     oSkipVerify,
278     oSkipHiddenRecipients,
279     oNoSkipHiddenRecipients,
280     oAlwaysTrust,
281     oTrustModel,
282     oForceOwnertrust,
283     oSetFilename,
284     oForYourEyesOnly,
285     oNoForYourEyesOnly,
286     oSetPolicyURL,
287     oSigPolicyURL,
288     oCertPolicyURL,
289     oShowPolicyURL,
290     oNoShowPolicyURL,
291     oSigKeyserverURL,
292     oUseEmbeddedFilename,
293     oNoUseEmbeddedFilename,
294     oComment,
295     oDefaultComment,
296     oNoComments,
297     oThrowKeyids,
298     oNoThrowKeyids,
299     oShowPhotos,
300     oNoShowPhotos,
301     oPhotoViewer,
302     oS2KMode,
303     oS2KDigest,
304     oS2KCipher,
305     oS2KCount,
306     oDisplayCharset,
307     oNotDashEscaped,
308     oEscapeFrom,
309     oNoEscapeFrom,
310     oLockOnce,
311     oLockMultiple,
312     oLockNever,
313     oKeyServer,
314     oKeyServerOptions,
315     oImportOptions,
316     oImportFilter,
317     oExportOptions,
318     oExportFilter,
319     oListOptions,
320     oVerifyOptions,
321     oTempDir,
322     oExecPath,
323     oEncryptTo,
324     oHiddenEncryptTo,
325     oNoEncryptTo,
326     oEncryptToDefaultKey,
327     oLoggerFD,
328     oLoggerFile,
329     oUtf8Strings,
330     oNoUtf8Strings,
331     oDisableCipherAlgo,
332     oDisablePubkeyAlgo,
333     oAllowNonSelfsignedUID,
334     oNoAllowNonSelfsignedUID,
335     oAllowFreeformUID,
336     oNoAllowFreeformUID,
337     oAllowSecretKeyImport,
338     oEnableSpecialFilenames,
339     oNoLiteral,
340     oSetFilesize,
341     oHonorHttpProxy,
342     oFastListMode,
343     oListOnly,
344     oIgnoreTimeConflict,
345     oIgnoreValidFrom,
346     oIgnoreCrcError,
347     oIgnoreMDCError,
348     oShowSessionKey,
349     oOverrideSessionKey,
350     oOverrideSessionKeyFD,
351     oNoRandomSeedFile,
352     oAutoKeyRetrieve,
353     oNoAutoKeyRetrieve,
354     oUseAgent,
355     oNoUseAgent,
356     oGpgAgentInfo,
357     oMergeOnly,
358     oTryAllSecrets,
359     oTrustedKey,
360     oNoExpensiveTrustChecks,
361     oFixedListMode,
362     oLegacyListMode,
363     oNoSigCache,
364     oAutoCheckTrustDB,
365     oNoAutoCheckTrustDB,
366     oPreservePermissions,
367     oDefaultPreferenceList,
368     oDefaultKeyserverURL,
369     oPersonalCipherPreferences,
370     oPersonalDigestPreferences,
371     oPersonalCompressPreferences,
372     oAgentProgram,
373     oDirmngrProgram,
374     oDisableDirmngr,
375     oDisplay,
376     oTTYname,
377     oTTYtype,
378     oLCctype,
379     oLCmessages,
380     oXauthority,
381     oGroup,
382     oUnGroup,
383     oNoGroups,
384     oStrict,
385     oNoStrict,
386     oMangleDosFilenames,
387     oNoMangleDosFilenames,
388     oEnableProgressFilter,
389     oMultifile,
390     oKeyidFormat,
391     oExitOnStatusWriteError,
392     oLimitCardInsertTries,
393     oReaderPort,
394     octapiDriver,
395     opcscDriver,
396     oDisableCCID,
397     oRequireCrossCert,
398     oNoRequireCrossCert,
399     oAutoKeyLocate,
400     oNoAutoKeyLocate,
401     oAllowMultisigVerification,
402     oEnableLargeRSA,
403     oDisableLargeRSA,
404     oEnableDSA2,
405     oDisableDSA2,
406     oAllowMultipleMessages,
407     oNoAllowMultipleMessages,
408     oAllowWeakDigestAlgos,
409     oFakedSystemTime,
410     oNoAutostart,
411     oPrintPKARecords,
412     oPrintDANERecords,
413     oTOFUDefaultPolicy,
414     oTOFUDBFormat,
415     oDefaultNewKeyAlgo,
416     oWeakDigest,
417     oUnwrap,
418     oOnlySignTextIDs,
419     oDisableSignerUID,
420     oSender,
421     oKeyOrigin,
422     oRequestOrigin,
423     oNoSymkeyCache,
424
425     oNoop
426   };
427
428
429 static ARGPARSE_OPTS opts[] = {
430
431   ARGPARSE_group (300, N_("@Commands:\n ")),
432
433   ARGPARSE_c (aSign, "sign", N_("make a signature")),
434   ARGPARSE_c (aClearsign, "clear-sign", N_("make a clear text signature")),
435   ARGPARSE_c (aClearsign, "clearsign", "@"),
436   ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")),
437   ARGPARSE_c (aEncr, "encrypt",   N_("encrypt data")),
438   ARGPARSE_c (aEncrFiles, "encrypt-files", "@"),
439   ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")),
440   ARGPARSE_c (aStore, "store",     "@"),
441   ARGPARSE_c (aDecrypt, "decrypt",   N_("decrypt data (default)")),
442   ARGPARSE_c (aDecryptFiles, "decrypt-files", "@"),
443   ARGPARSE_c (aVerify, "verify"   , N_("verify a signature")),
444   ARGPARSE_c (aVerifyFiles, "verify-files" , "@" ),
445   ARGPARSE_c (aListKeys, "list-keys", N_("list keys")),
446   ARGPARSE_c (aListKeys, "list-public-keys", "@" ),
447   ARGPARSE_c (aListSigs, "list-signatures", N_("list keys and signatures")),
448   ARGPARSE_c (aListSigs, "list-sigs", "@"),
449   ARGPARSE_c (aCheckKeys, "check-signatures",
450               N_("list and check key signatures")),
451   ARGPARSE_c (aCheckKeys, "check-sigs", "@"),
452   ARGPARSE_c (oFingerprint, "fingerprint", N_("list keys and fingerprints")),
453   ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")),
454   ARGPARSE_c (aKeygen,      "generate-key",
455               N_("generate a new key pair")),
456   ARGPARSE_c (aKeygen,      "gen-key", "@"),
457   ARGPARSE_c (aQuickKeygen, "quick-generate-key" ,
458               N_("quickly generate a new key pair")),
459   ARGPARSE_c (aQuickKeygen, "quick-gen-key", "@"),
460   ARGPARSE_c (aQuickAddUid,  "quick-add-uid",
461               N_("quickly add a new user-id")),
462   ARGPARSE_c (aQuickAddUid,  "quick-adduid", "@"),
463   ARGPARSE_c (aQuickAddKey,  "quick-add-key", "@"),
464   ARGPARSE_c (aQuickAddKey,  "quick-addkey", "@"),
465   ARGPARSE_c (aQuickRevUid,  "quick-revoke-uid",
466               N_("quickly revoke a user-id")),
467   ARGPARSE_c (aQuickRevUid,  "quick-revuid", "@"),
468   ARGPARSE_c (aQuickSetExpire,  "quick-set-expire",
469               N_("quickly set a new expiration date")),
470   ARGPARSE_c (aQuickSetPrimaryUid,  "quick-set-primary-uid", "@"),
471   ARGPARSE_c (aFullKeygen,  "full-generate-key" ,
472               N_("full featured key pair generation")),
473   ARGPARSE_c (aFullKeygen,  "full-gen-key", "@"),
474   ARGPARSE_c (aGenRevoke, "generate-revocation",
475               N_("generate a revocation certificate")),
476   ARGPARSE_c (aGenRevoke, "gen-revoke", "@"),
477   ARGPARSE_c (aDeleteKeys,"delete-keys",
478               N_("remove keys from the public keyring")),
479   ARGPARSE_c (aDeleteSecretKeys, "delete-secret-keys",
480               N_("remove keys from the secret keyring")),
481   ARGPARSE_c (aQuickSignKey,  "quick-sign-key" ,
482               N_("quickly sign a key")),
483   ARGPARSE_c (aQuickLSignKey, "quick-lsign-key",
484               N_("quickly sign a key locally")),
485   ARGPARSE_c (aSignKey,  "sign-key"   ,N_("sign a key")),
486   ARGPARSE_c (aLSignKey, "lsign-key"  ,N_("sign a key locally")),
487   ARGPARSE_c (aEditKey,  "edit-key"   ,N_("sign or edit a key")),
488   ARGPARSE_c (aEditKey,  "key-edit"   ,"@"),
489   ARGPARSE_c (aPasswd,   "change-passphrase", N_("change a passphrase")),
490   ARGPARSE_c (aPasswd,   "passwd", "@"),
491   ARGPARSE_c (aDesigRevoke, "generate-designated-revocation", "@"),
492   ARGPARSE_c (aDesigRevoke, "desig-revoke","@" ),
493   ARGPARSE_c (aExport, "export"           , N_("export keys") ),
494   ARGPARSE_c (aSendKeys, "send-keys"     , N_("export keys to a keyserver") ),
495   ARGPARSE_c (aRecvKeys, "receive-keys" , N_("import keys from a keyserver") ),
496   ARGPARSE_c (aRecvKeys, "recv-keys"     , "@"),
497   ARGPARSE_c (aSearchKeys, "search-keys" ,
498               N_("search for keys on a keyserver") ),
499   ARGPARSE_c (aRefreshKeys, "refresh-keys",
500               N_("update all keys from a keyserver")),
501   ARGPARSE_c (aLocateKeys, "locate-keys", "@"),
502   ARGPARSE_c (aFetchKeys, "fetch-keys" , "@" ),
503   ARGPARSE_c (aShowKeys, "show-keys" , "@" ),
504   ARGPARSE_c (aExportSecret, "export-secret-keys" , "@" ),
505   ARGPARSE_c (aExportSecretSub, "export-secret-subkeys" , "@" ),
506   ARGPARSE_c (aExportSshKey, "export-ssh-key", "@" ),
507   ARGPARSE_c (aImport, "import", N_("import/merge keys")),
508   ARGPARSE_c (aFastImport, "fast-import", "@"),
509 #ifdef ENABLE_CARD_SUPPORT
510   ARGPARSE_c (aCardStatus,  "card-status", N_("print the card status")),
511   ARGPARSE_c (aCardEdit,   "edit-card",  N_("change data on a card")),
512   ARGPARSE_c (aCardEdit,   "card-edit", "@"),
513   ARGPARSE_c (aChangePIN,  "change-pin", N_("change a card's PIN")),
514 #endif
515   ARGPARSE_c (aListConfig, "list-config", "@"),
516   ARGPARSE_c (aListGcryptConfig, "list-gcrypt-config", "@"),
517   ARGPARSE_c (aGPGConfList, "gpgconf-list", "@" ),
518   ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@" ),
519   ARGPARSE_c (aListPackets, "list-packets","@"),
520
521 #ifndef NO_TRUST_MODELS
522   ARGPARSE_c (aExportOwnerTrust, "export-ownertrust", "@"),
523   ARGPARSE_c (aImportOwnerTrust, "import-ownertrust", "@"),
524   ARGPARSE_c (aUpdateTrustDB,"update-trustdb",
525               N_("update the trust database")),
526   ARGPARSE_c (aCheckTrustDB, "check-trustdb", "@"),
527   ARGPARSE_c (aFixTrustDB, "fix-trustdb", "@"),
528 #endif
529
530   ARGPARSE_c (aDeArmor, "dearmor", "@"),
531   ARGPARSE_c (aDeArmor, "dearmour", "@"),
532   ARGPARSE_c (aEnArmor, "enarmor", "@"),
533   ARGPARSE_c (aEnArmor, "enarmour", "@"),
534   ARGPARSE_c (aPrintMD, "print-md", N_("print message digests")),
535   ARGPARSE_c (aPrimegen, "gen-prime", "@" ),
536   ARGPARSE_c (aGenRandom,"gen-random", "@" ),
537   ARGPARSE_c (aServer,   "server",  N_("run in server mode")),
538   ARGPARSE_c (aTOFUPolicy, "tofu-policy",
539               N_("|VALUE|set the TOFU policy for a key")),
540
541   ARGPARSE_group (301, N_("@\nOptions:\n ")),
542
543   ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")),
544   ARGPARSE_s_n (oArmor, "armour", "@"),
545
546   ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")),
547   ARGPARSE_s_s (oHiddenRecipient, "hidden-recipient", "@"),
548   ARGPARSE_s_s (oRecipientFile, "recipient-file", "@"),
549   ARGPARSE_s_s (oHiddenRecipientFile, "hidden-recipient-file", "@"),
550   ARGPARSE_s_s (oRecipient, "remote-user", "@"),  /* (old option name) */
551   ARGPARSE_s_s (oDefRecipient, "default-recipient", "@"),
552   ARGPARSE_s_n (oDefRecipientSelf,  "default-recipient-self", "@"),
553   ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"),
554
555   ARGPARSE_s_s (oTempDir,  "temp-directory", "@"),
556   ARGPARSE_s_s (oExecPath, "exec-path", "@"),
557   ARGPARSE_s_s (oEncryptTo,      "encrypt-to", "@"),
558   ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"),
559   ARGPARSE_s_s (oHiddenEncryptTo, "hidden-encrypt-to", "@"),
560   ARGPARSE_s_n (oEncryptToDefaultKey, "encrypt-to-default-key", "@"),
561   ARGPARSE_s_s (oLocalUser, "local-user",
562                 N_("|USER-ID|use USER-ID to sign or decrypt")),
563   ARGPARSE_s_s (oSender, "sender", "@"),
564
565   ARGPARSE_s_s (oTrySecretKey, "try-secret-key", "@"),
566
567   ARGPARSE_s_i (oCompress, NULL,
568                 N_("|N|set compress level to N (0 disables)")),
569   ARGPARSE_s_i (oCompressLevel, "compress-level", "@"),
570   ARGPARSE_s_i (oBZ2CompressLevel, "bzip2-compress-level", "@"),
571   ARGPARSE_s_n (oBZ2DecompressLowmem, "bzip2-decompress-lowmem", "@"),
572
573   ARGPARSE_s_n (oMimemode, "mimemode", "@"),
574   ARGPARSE_s_n (oTextmodeShort, NULL, "@"),
575   ARGPARSE_s_n (oTextmode,   "textmode", N_("use canonical text mode")),
576   ARGPARSE_s_n (oNoTextmode, "no-textmode", "@"),
577
578   ARGPARSE_s_n (oExpert,      "expert", "@"),
579   ARGPARSE_s_n (oNoExpert, "no-expert", "@"),
580
581   ARGPARSE_s_s (oDefSigExpire, "default-sig-expire", "@"),
582   ARGPARSE_s_n (oAskSigExpire,      "ask-sig-expire", "@"),
583   ARGPARSE_s_n (oNoAskSigExpire, "no-ask-sig-expire", "@"),
584   ARGPARSE_s_s (oDefCertExpire, "default-cert-expire", "@"),
585   ARGPARSE_s_n (oAskCertExpire,      "ask-cert-expire", "@"),
586   ARGPARSE_s_n (oNoAskCertExpire, "no-ask-cert-expire", "@"),
587   ARGPARSE_s_i (oDefCertLevel, "default-cert-level", "@"),
588   ARGPARSE_s_i (oMinCertLevel, "min-cert-level", "@"),
589   ARGPARSE_s_n (oAskCertLevel,      "ask-cert-level", "@"),
590   ARGPARSE_s_n (oNoAskCertLevel, "no-ask-cert-level", "@"),
591
592   ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")),
593   ARGPARSE_p_u (oMaxOutput, "max-output", "@"),
594   ARGPARSE_s_s (oInputSizeHint, "input-size-hint", "@"),
595
596   ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
597   ARGPARSE_s_n (oQuiet,   "quiet",   "@"),
598   ARGPARSE_s_n (oNoTTY,   "no-tty",  "@"),
599
600   ARGPARSE_s_n (oDisableSignerUID, "disable-signer-uid", "@"),
601
602   ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")),
603   ARGPARSE_s_n (oInteractive, "interactive", N_("prompt before overwriting")),
604
605   ARGPARSE_s_n (oBatch, "batch", "@"),
606   ARGPARSE_s_n (oAnswerYes, "yes", "@"),
607   ARGPARSE_s_n (oAnswerNo, "no", "@"),
608   ARGPARSE_s_s (oKeyring, "keyring", "@"),
609   ARGPARSE_s_s (oPrimaryKeyring, "primary-keyring", "@"),
610   ARGPARSE_s_s (oSecretKeyring, "secret-keyring", "@"),
611   ARGPARSE_s_n (oShowKeyring, "show-keyring", "@"),
612   ARGPARSE_s_s (oDefaultKey, "default-key", "@"),
613
614   ARGPARSE_s_s (oKeyServer, "keyserver", "@"),
615   ARGPARSE_s_s (oKeyServerOptions, "keyserver-options", "@"),
616   ARGPARSE_s_s (oKeyOrigin, "key-origin", "@"),
617   ARGPARSE_s_s (oImportOptions, "import-options", "@"),
618   ARGPARSE_s_s (oImportFilter,  "import-filter", "@"),
619   ARGPARSE_s_s (oExportOptions, "export-options", "@"),
620   ARGPARSE_s_s (oExportFilter,  "export-filter", "@"),
621   ARGPARSE_s_s (oListOptions,   "list-options", "@"),
622   ARGPARSE_s_s (oVerifyOptions, "verify-options", "@"),
623
624   ARGPARSE_s_s (oDisplayCharset, "display-charset", "@"),
625   ARGPARSE_s_s (oDisplayCharset, "charset", "@"),
626   ARGPARSE_s_s (oOptions, "options", "@"),
627
628   ARGPARSE_s_s (oDebug, "debug", "@"),
629   ARGPARSE_s_s (oDebugLevel, "debug-level", "@"),
630   ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
631   ARGPARSE_s_n (oDebugIOLBF, "debug-iolbf", "@"),
632   ARGPARSE_s_i (oStatusFD, "status-fd", "@"),
633   ARGPARSE_s_s (oStatusFile, "status-file", "@"),
634   ARGPARSE_s_i (oAttributeFD, "attribute-fd", "@"),
635   ARGPARSE_s_s (oAttributeFile, "attribute-file", "@"),
636
637   ARGPARSE_s_i (oCompletesNeeded, "completes-needed", "@"),
638   ARGPARSE_s_i (oMarginalsNeeded, "marginals-needed", "@"),
639   ARGPARSE_s_i (oMaxCertDepth,  "max-cert-depth", "@" ),
640   ARGPARSE_s_s (oTrustedKey, "trusted-key", "@"),
641
642   ARGPARSE_s_s (oLoadExtension, "load-extension", "@"),  /* Dummy.  */
643
644   ARGPARSE_s_s (oCompliance, "compliance",   "@"),
645   ARGPARSE_s_n (oGnuPG, "gnupg",   "@"),
646   ARGPARSE_s_n (oGnuPG, "no-pgp2", "@"),
647   ARGPARSE_s_n (oGnuPG, "no-pgp6", "@"),
648   ARGPARSE_s_n (oGnuPG, "no-pgp7", "@"),
649   ARGPARSE_s_n (oGnuPG, "no-pgp8", "@"),
650   ARGPARSE_s_n (oRFC2440, "rfc2440", "@"),
651   ARGPARSE_s_n (oRFC4880, "rfc4880", "@"),
652   ARGPARSE_s_n (oRFC4880bis, "rfc4880bis", "@"),
653   ARGPARSE_s_n (oOpenPGP, "openpgp", N_("use strict OpenPGP behavior")),
654   ARGPARSE_s_n (oPGP6, "pgp6", "@"),
655   ARGPARSE_s_n (oPGP7, "pgp7", "@"),
656   ARGPARSE_s_n (oPGP8, "pgp8", "@"),
657
658   ARGPARSE_s_n (oRFC2440Text,      "rfc2440-text", "@"),
659   ARGPARSE_s_n (oNoRFC2440Text, "no-rfc2440-text", "@"),
660   ARGPARSE_s_i (oS2KMode, "s2k-mode", "@"),
661   ARGPARSE_s_s (oS2KDigest, "s2k-digest-algo", "@"),
662   ARGPARSE_s_s (oS2KCipher, "s2k-cipher-algo", "@"),
663   ARGPARSE_s_i (oS2KCount, "s2k-count", "@"),
664   ARGPARSE_s_s (oCipherAlgo, "cipher-algo", "@"),
665   ARGPARSE_s_s (oDigestAlgo, "digest-algo", "@"),
666   ARGPARSE_s_s (oCertDigestAlgo, "cert-digest-algo", "@"),
667   ARGPARSE_s_s (oCompressAlgo,"compress-algo", "@"),
668   ARGPARSE_s_s (oCompressAlgo, "compression-algo", "@"), /* Alias */
669   ARGPARSE_s_n (oThrowKeyids, "throw-keyids", "@"),
670   ARGPARSE_s_n (oNoThrowKeyids, "no-throw-keyids", "@"),
671   ARGPARSE_s_n (oShowPhotos,   "show-photos", "@"),
672   ARGPARSE_s_n (oNoShowPhotos, "no-show-photos", "@"),
673   ARGPARSE_s_s (oPhotoViewer,  "photo-viewer", "@"),
674   ARGPARSE_s_s (oSetNotation,  "set-notation", "@"),
675   ARGPARSE_s_s (oSigNotation,  "sig-notation", "@"),
676   ARGPARSE_s_s (oCertNotation, "cert-notation", "@"),
677   ARGPARSE_s_s (oKnownNotation, "known-notation", "@"),
678
679   ARGPARSE_group (302, N_(
680   "@\n(See the man page for a complete listing of all commands and options)\n"
681                       )),
682
683   ARGPARSE_group (303, N_("@\nExamples:\n\n"
684     " -se -r Bob [file]          sign and encrypt for user Bob\n"
685     " --clear-sign [file]        make a clear text signature\n"
686     " --detach-sign [file]       make a detached signature\n"
687     " --list-keys [names]        show keys\n"
688     " --fingerprint [names]      show fingerprints\n")),
689
690   /* More hidden commands and options. */
691   ARGPARSE_c (aPrintMDs, "print-mds", "@"), /* old */
692 #ifndef NO_TRUST_MODELS
693   ARGPARSE_c (aListTrustDB, "list-trustdb", "@"),
694 #endif
695
696   /* Not yet used:
697      ARGPARSE_c (aListTrustPath, "list-trust-path", "@"), */
698   ARGPARSE_c (aDeleteSecretAndPublicKeys,
699               "delete-secret-and-public-keys", "@"),
700   ARGPARSE_c (aRebuildKeydbCaches, "rebuild-keydb-caches", "@"),
701
702   ARGPARSE_s_s (oPassphrase,      "passphrase", "@"),
703   ARGPARSE_s_i (oPassphraseFD,    "passphrase-fd", "@"),
704   ARGPARSE_s_s (oPassphraseFile,  "passphrase-file", "@"),
705   ARGPARSE_s_i (oPassphraseRepeat,"passphrase-repeat", "@"),
706   ARGPARSE_s_s (oPinentryMode,    "pinentry-mode", "@"),
707   ARGPARSE_s_s (oRequestOrigin,   "request-origin", "@"),
708   ARGPARSE_s_i (oCommandFD, "command-fd", "@"),
709   ARGPARSE_s_s (oCommandFile, "command-file", "@"),
710   ARGPARSE_s_n (oQuickRandom, "debug-quick-random", "@"),
711   ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
712
713 #ifndef NO_TRUST_MODELS
714   ARGPARSE_s_s (oTrustDBName, "trustdb-name", "@"),
715   ARGPARSE_s_n (oAutoCheckTrustDB, "auto-check-trustdb", "@"),
716   ARGPARSE_s_n (oNoAutoCheckTrustDB, "no-auto-check-trustdb", "@"),
717   ARGPARSE_s_s (oForceOwnertrust, "force-ownertrust", "@"),
718 #endif
719
720   ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"),
721   ARGPARSE_s_n (oRequireSecmem, "require-secmem", "@"),
722   ARGPARSE_s_n (oNoRequireSecmem, "no-require-secmem", "@"),
723   ARGPARSE_s_n (oNoPermissionWarn, "no-permission-warning", "@"),
724   ARGPARSE_s_n (oNoArmor, "no-armor", "@"),
725   ARGPARSE_s_n (oNoArmor, "no-armour", "@"),
726   ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"),
727   ARGPARSE_s_n (oNoKeyring, "no-keyring", "@"),
728   ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
729   ARGPARSE_s_n (oNoOptions, "no-options", "@"),
730   ARGPARSE_s_s (oHomedir, "homedir", "@"),
731   ARGPARSE_s_n (oNoBatch, "no-batch", "@"),
732   ARGPARSE_s_n (oWithColons, "with-colons", "@"),
733   ARGPARSE_s_n (oWithTofuInfo,"with-tofu-info", "@"),
734   ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"),
735   ARGPARSE_s_n (oWithSigList,"with-sig-list", "@"),
736   ARGPARSE_s_n (oWithSigCheck,"with-sig-check", "@"),
737   ARGPARSE_c (aListKeys, "list-key", "@"),   /* alias */
738   ARGPARSE_c (aListSigs, "list-sig", "@"),   /* alias */
739   ARGPARSE_c (aCheckKeys, "check-sig", "@"), /* alias */
740   ARGPARSE_c (aShowKeys,  "show-key", "@"), /* alias */
741   ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"),
742   ARGPARSE_s_n (oSkipHiddenRecipients, "skip-hidden-recipients", "@"),
743   ARGPARSE_s_n (oNoSkipHiddenRecipients, "no-skip-hidden-recipients", "@"),
744   ARGPARSE_s_i (oDefCertLevel, "default-cert-check-level", "@"), /* old */
745 #ifndef NO_TRUST_MODELS
746   ARGPARSE_s_n (oAlwaysTrust, "always-trust", "@"),
747 #endif
748   ARGPARSE_s_s (oTrustModel, "trust-model", "@"),
749   ARGPARSE_s_s (oTOFUDefaultPolicy, "tofu-default-policy", "@"),
750   ARGPARSE_s_s (oSetFilename, "set-filename", "@"),
751   ARGPARSE_s_n (oForYourEyesOnly, "for-your-eyes-only", "@"),
752   ARGPARSE_s_n (oNoForYourEyesOnly, "no-for-your-eyes-only", "@"),
753   ARGPARSE_s_s (oSetPolicyURL,  "set-policy-url", "@"),
754   ARGPARSE_s_s (oSigPolicyURL,  "sig-policy-url", "@"),
755   ARGPARSE_s_s (oCertPolicyURL, "cert-policy-url", "@"),
756   ARGPARSE_s_n (oShowPolicyURL,      "show-policy-url", "@"),
757   ARGPARSE_s_n (oNoShowPolicyURL, "no-show-policy-url", "@"),
758   ARGPARSE_s_s (oSigKeyserverURL, "sig-keyserver-url", "@"),
759   ARGPARSE_s_n (oShowNotation,      "show-notation", "@"),
760   ARGPARSE_s_n (oNoShowNotation, "no-show-notation", "@"),
761   ARGPARSE_s_s (oComment, "comment", "@"),
762   ARGPARSE_s_n (oDefaultComment, "default-comment", "@"),
763   ARGPARSE_s_n (oNoComments, "no-comments", "@"),
764   ARGPARSE_s_n (oEmitVersion,      "emit-version", "@"),
765   ARGPARSE_s_n (oNoEmitVersion, "no-emit-version", "@"),
766   ARGPARSE_s_n (oNoEmitVersion, "no-version", "@"), /* alias */
767   ARGPARSE_s_n (oNotDashEscaped, "not-dash-escaped", "@"),
768   ARGPARSE_s_n (oEscapeFrom,      "escape-from-lines", "@"),
769   ARGPARSE_s_n (oNoEscapeFrom, "no-escape-from-lines", "@"),
770   ARGPARSE_s_n (oLockOnce,     "lock-once", "@"),
771   ARGPARSE_s_n (oLockMultiple, "lock-multiple", "@"),
772   ARGPARSE_s_n (oLockNever,    "lock-never", "@"),
773   ARGPARSE_s_i (oLoggerFD,   "logger-fd", "@"),
774   ARGPARSE_s_s (oLoggerFile, "log-file", "@"),
775   ARGPARSE_s_s (oLoggerFile, "logger-file", "@"),  /* 1.4 compatibility.  */
776   ARGPARSE_s_n (oUseEmbeddedFilename,      "use-embedded-filename", "@"),
777   ARGPARSE_s_n (oNoUseEmbeddedFilename, "no-use-embedded-filename", "@"),
778   ARGPARSE_s_n (oUtf8Strings,      "utf8-strings", "@"),
779   ARGPARSE_s_n (oNoUtf8Strings, "no-utf8-strings", "@"),
780   ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"),
781   ARGPARSE_s_n (oWithSubkeyFingerprint, "with-subkey-fingerprint", "@"),
782   ARGPARSE_s_n (oWithSubkeyFingerprint, "with-subkey-fingerprints", "@"),
783   ARGPARSE_s_n (oWithICAOSpelling, "with-icao-spelling", "@"),
784   ARGPARSE_s_n (oWithKeygrip,     "with-keygrip", "@"),
785   ARGPARSE_s_n (oWithSecret,      "with-secret", "@"),
786   ARGPARSE_s_n (oWithWKDHash,     "with-wkd-hash", "@"),
787   ARGPARSE_s_n (oWithKeyOrigin,   "with-key-origin", "@"),
788   ARGPARSE_s_s (oDisableCipherAlgo,  "disable-cipher-algo", "@"),
789   ARGPARSE_s_s (oDisablePubkeyAlgo,  "disable-pubkey-algo", "@"),
790   ARGPARSE_s_n (oAllowNonSelfsignedUID,      "allow-non-selfsigned-uid", "@"),
791   ARGPARSE_s_n (oNoAllowNonSelfsignedUID, "no-allow-non-selfsigned-uid", "@"),
792   ARGPARSE_s_n (oAllowFreeformUID,      "allow-freeform-uid", "@"),
793   ARGPARSE_s_n (oNoAllowFreeformUID, "no-allow-freeform-uid", "@"),
794   ARGPARSE_s_n (oNoLiteral, "no-literal", "@"),
795   ARGPARSE_p_u (oSetFilesize, "set-filesize", "@"),
796   ARGPARSE_s_n (oFastListMode, "fast-list-mode", "@"),
797   ARGPARSE_s_n (oFixedListMode, "fixed-list-mode", "@"),
798   ARGPARSE_s_n (oLegacyListMode, "legacy-list-mode", "@"),
799   ARGPARSE_s_n (oListOnly, "list-only", "@"),
800   ARGPARSE_s_n (oPrintPKARecords, "print-pka-records", "@"),
801   ARGPARSE_s_n (oPrintDANERecords, "print-dane-records", "@"),
802   ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"),
803   ARGPARSE_s_n (oIgnoreValidFrom,    "ignore-valid-from", "@"),
804   ARGPARSE_s_n (oIgnoreCrcError, "ignore-crc-error", "@"),
805   ARGPARSE_s_n (oIgnoreMDCError, "ignore-mdc-error", "@"),
806   ARGPARSE_s_n (oShowSessionKey, "show-session-key", "@"),
807   ARGPARSE_s_s (oOverrideSessionKey, "override-session-key", "@"),
808   ARGPARSE_s_i (oOverrideSessionKeyFD, "override-session-key-fd", "@"),
809   ARGPARSE_s_n (oNoRandomSeedFile,  "no-random-seed-file", "@"),
810   ARGPARSE_s_n (oAutoKeyRetrieve, "auto-key-retrieve", "@"),
811   ARGPARSE_s_n (oNoAutoKeyRetrieve, "no-auto-key-retrieve", "@"),
812   ARGPARSE_s_n (oNoSigCache,         "no-sig-cache", "@"),
813   ARGPARSE_s_n (oMergeOnly,       "merge-only", "@" ),
814   ARGPARSE_s_n (oAllowSecretKeyImport, "allow-secret-key-import", "@"),
815   ARGPARSE_s_n (oTryAllSecrets,  "try-all-secrets", "@"),
816   ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"),
817   ARGPARSE_s_n (oNoExpensiveTrustChecks, "no-expensive-trust-checks", "@"),
818   ARGPARSE_s_n (oPreservePermissions, "preserve-permissions", "@"),
819   ARGPARSE_s_s (oDefaultPreferenceList,  "default-preference-list", "@"),
820   ARGPARSE_s_s (oDefaultKeyserverURL,  "default-keyserver-url", "@"),
821   ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-preferences","@"),
822   ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-preferences","@"),
823   ARGPARSE_s_s (oPersonalCompressPreferences,
824                                          "personal-compress-preferences", "@"),
825   ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
826   ARGPARSE_s_s (oWeakDigest, "weak-digest","@"),
827   ARGPARSE_s_n (oUnwrap, "unwrap", "@"),
828   ARGPARSE_s_n (oOnlySignTextIDs, "only-sign-text-ids", "@"),
829
830   /* Aliases.  I constantly mistype these, and assume other people do
831      as well. */
832   ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-prefs", "@"),
833   ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-prefs", "@"),
834   ARGPARSE_s_s (oPersonalCompressPreferences, "personal-compress-prefs", "@"),
835
836   ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
837   ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"),
838   ARGPARSE_s_n (oDisableDirmngr, "disable-dirmngr", "@"),
839   ARGPARSE_s_s (oDisplay,    "display",    "@"),
840   ARGPARSE_s_s (oTTYname,    "ttyname",    "@"),
841   ARGPARSE_s_s (oTTYtype,    "ttytype",    "@"),
842   ARGPARSE_s_s (oLCctype,    "lc-ctype",   "@"),
843   ARGPARSE_s_s (oLCmessages, "lc-messages","@"),
844   ARGPARSE_s_s (oXauthority, "xauthority", "@"),
845   ARGPARSE_s_s (oGroup,      "group",      "@"),
846   ARGPARSE_s_s (oUnGroup,    "ungroup",    "@"),
847   ARGPARSE_s_n (oNoGroups,   "no-groups",  "@"),
848   ARGPARSE_s_n (oStrict,     "strict",     "@"),
849   ARGPARSE_s_n (oNoStrict,   "no-strict",  "@"),
850   ARGPARSE_s_n (oMangleDosFilenames,      "mangle-dos-filenames", "@"),
851   ARGPARSE_s_n (oNoMangleDosFilenames, "no-mangle-dos-filenames", "@"),
852   ARGPARSE_s_n (oEnableProgressFilter, "enable-progress-filter", "@"),
853   ARGPARSE_s_n (oMultifile, "multifile", "@"),
854   ARGPARSE_s_s (oKeyidFormat, "keyid-format", "@"),
855   ARGPARSE_s_n (oExitOnStatusWriteError, "exit-on-status-write-error", "@"),
856   ARGPARSE_s_i (oLimitCardInsertTries, "limit-card-insert-tries", "@"),
857
858   ARGPARSE_s_n (oAllowMultisigVerification,
859                 "allow-multisig-verification", "@"),
860   ARGPARSE_s_n (oEnableLargeRSA, "enable-large-rsa", "@"),
861   ARGPARSE_s_n (oDisableLargeRSA, "disable-large-rsa", "@"),
862   ARGPARSE_s_n (oEnableDSA2, "enable-dsa2", "@"),
863   ARGPARSE_s_n (oDisableDSA2, "disable-dsa2", "@"),
864   ARGPARSE_s_n (oAllowMultipleMessages,      "allow-multiple-messages", "@"),
865   ARGPARSE_s_n (oNoAllowMultipleMessages, "no-allow-multiple-messages", "@"),
866   ARGPARSE_s_n (oAllowWeakDigestAlgos, "allow-weak-digest-algos", "@"),
867
868   ARGPARSE_s_s (oDefaultNewKeyAlgo, "default-new-key-algo", "@"),
869
870   /* These two are aliases to help users of the PGP command line
871      product use gpg with minimal pain.  Many commands are common
872      already as they seem to have borrowed commands from us.  Now I'm
873      returning the favor. */
874   ARGPARSE_s_s (oLocalUser, "sign-with", "@"),
875   ARGPARSE_s_s (oRecipient, "user", "@"),
876
877   ARGPARSE_s_n (oRequireCrossCert, "require-backsigs", "@"),
878   ARGPARSE_s_n (oRequireCrossCert, "require-cross-certification", "@"),
879   ARGPARSE_s_n (oNoRequireCrossCert, "no-require-backsigs", "@"),
880   ARGPARSE_s_n (oNoRequireCrossCert, "no-require-cross-certification", "@"),
881
882   /* New options.  Fixme: Should go more to the top.  */
883   ARGPARSE_s_s (oAutoKeyLocate, "auto-key-locate", "@"),
884   ARGPARSE_s_n (oNoAutoKeyLocate, "no-auto-key-locate", "@"),
885   ARGPARSE_s_n (oNoAutostart, "no-autostart", "@"),
886   ARGPARSE_s_n (oNoSymkeyCache, "no-symkey-cache", "@"),
887
888   /* Dummy options with warnings.  */
889   ARGPARSE_s_n (oUseAgent,      "use-agent", "@"),
890   ARGPARSE_s_n (oNoUseAgent, "no-use-agent", "@"),
891   ARGPARSE_s_s (oGpgAgentInfo, "gpg-agent-info", "@"),
892   ARGPARSE_s_s (oReaderPort, "reader-port", "@"),
893   ARGPARSE_s_s (octapiDriver, "ctapi-driver", "@"),
894   ARGPARSE_s_s (opcscDriver, "pcsc-driver", "@"),
895   ARGPARSE_s_n (oDisableCCID, "disable-ccid", "@"),
896   ARGPARSE_s_n (oHonorHttpProxy, "honor-http-proxy", "@"),
897   ARGPARSE_s_s (oTOFUDBFormat, "tofu-db-format", "@"),
898
899   /* Dummy options.  */
900   ARGPARSE_s_n (oNoop, "sk-comments", "@"),
901   ARGPARSE_s_n (oNoop, "no-sk-comments", "@"),
902   ARGPARSE_s_n (oNoop, "compress-keys", "@"),
903   ARGPARSE_s_n (oNoop, "compress-sigs", "@"),
904   ARGPARSE_s_n (oNoop, "force-v3-sigs", "@"),
905   ARGPARSE_s_n (oNoop, "no-force-v3-sigs", "@"),
906   ARGPARSE_s_n (oNoop, "force-v4-certs", "@"),
907   ARGPARSE_s_n (oNoop, "no-force-v4-certs", "@"),
908   ARGPARSE_s_n (oNoop, "no-mdc-warning", "@"),
909   ARGPARSE_s_n (oNoop, "force-mdc", "@"),
910   ARGPARSE_s_n (oNoop, "no-force-mdc", "@"),
911   ARGPARSE_s_n (oNoop, "disable-mdc", "@"),
912   ARGPARSE_s_n (oNoop, "no-disable-mdc", "@"),
913
914
915   ARGPARSE_end ()
916 };
917
918
919 /* The list of supported debug flags.  */
920 static struct debug_flags_s debug_flags [] =
921   {
922     { DBG_PACKET_VALUE , "packet"  },
923     { DBG_MPI_VALUE    , "mpi"     },
924     { DBG_CRYPTO_VALUE , "crypto"  },
925     { DBG_FILTER_VALUE , "filter"  },
926     { DBG_IOBUF_VALUE  , "iobuf"   },
927     { DBG_MEMORY_VALUE , "memory"  },
928     { DBG_CACHE_VALUE  , "cache"   },
929     { DBG_MEMSTAT_VALUE, "memstat" },
930     { DBG_TRUST_VALUE  , "trust"   },
931     { DBG_HASHING_VALUE, "hashing" },
932     { DBG_IPC_VALUE    , "ipc"     },
933     { DBG_CLOCK_VALUE  , "clock"   },
934     { DBG_LOOKUP_VALUE , "lookup"  },
935     { DBG_EXTPROG_VALUE, "extprog" },
936     { 0, NULL }
937   };
938
939
940 #ifdef ENABLE_SELINUX_HACKS
941 #define ALWAYS_ADD_KEYRINGS 1
942 #else
943 #define ALWAYS_ADD_KEYRINGS 0
944 #endif
945
946
947 int g10_errors_seen = 0;
948
949 static int utf8_strings = 0;
950 static int maybe_setuid = 1;
951
952 static char *build_list( const char *text, char letter,
953                          const char *(*mapf)(int), int (*chkf)(int) );
954 static void set_cmd( enum cmd_and_opt_values *ret_cmd,
955                         enum cmd_and_opt_values new_cmd );
956 static void print_mds( const char *fname, int algo );
957 static void add_notation_data( const char *string, int which );
958 static void add_policy_url( const char *string, int which );
959 static void add_keyserver_url( const char *string, int which );
960 static void emergency_cleanup (void);
961 static void read_sessionkey_from_fd (int fd);
962
963
964 static char *
965 make_libversion (const char *libname, const char *(*getfnc)(const char*))
966 {
967   const char *s;
968   char *result;
969
970   if (maybe_setuid)
971     {
972       gcry_control (GCRYCTL_INIT_SECMEM, 0, 0);  /* Drop setuid. */
973       maybe_setuid = 0;
974     }
975   s = getfnc (NULL);
976   result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
977   strcpy (stpcpy (stpcpy (result, libname), " "), s);
978   return result;
979 }
980
981
982 static int
983 build_list_pk_test_algo (int algo)
984 {
985   /* Show only one "RSA" string.  If RSA_E or RSA_S is available RSA
986      is also available.  */
987   if (algo == PUBKEY_ALGO_RSA_E
988       || algo == PUBKEY_ALGO_RSA_S)
989     return GPG_ERR_DIGEST_ALGO;
990
991   return openpgp_pk_test_algo (algo);
992 }
993
994 static const char *
995 build_list_pk_algo_name (int algo)
996 {
997   return openpgp_pk_algo_name (algo);
998 }
999
1000 static int
1001 build_list_cipher_test_algo (int algo)
1002 {
1003   return openpgp_cipher_test_algo (algo);
1004 }
1005
1006 static const char *
1007 build_list_cipher_algo_name (int algo)
1008 {
1009   return openpgp_cipher_algo_name (algo);
1010 }
1011
1012 static int
1013 build_list_md_test_algo (int algo)
1014 {
1015   /* By default we do not accept MD5 based signatures.  To avoid
1016      confusion we do not announce support for it either.  */
1017   if (algo == DIGEST_ALGO_MD5)
1018     return GPG_ERR_DIGEST_ALGO;
1019
1020   return openpgp_md_test_algo (algo);
1021 }
1022
1023 static const char *
1024 build_list_md_algo_name (int algo)
1025 {
1026   return openpgp_md_algo_name (algo);
1027 }
1028
1029
1030 static const char *
1031 my_strusage( int level )
1032 {
1033   static char *digests, *pubkeys, *ciphers, *zips, *ver_gcry;
1034   const char *p;
1035
1036     switch( level ) {
1037       case 11: p = "@GPG@ (@GNUPG@)";
1038         break;
1039       case 13: p = VERSION; break;
1040       case 17: p = PRINTABLE_OS_NAME; break;
1041       case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
1042
1043     case 20:
1044       if (!ver_gcry)
1045         ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
1046       p = ver_gcry;
1047       break;
1048
1049 #ifdef IS_DEVELOPMENT_VERSION
1050       case 25:
1051         p="NOTE: THIS IS A DEVELOPMENT VERSION!";
1052         break;
1053       case 26:
1054         p="It is only intended for test purposes and should NOT be";
1055         break;
1056       case 27:
1057         p="used in a production environment or with production keys!";
1058         break;
1059 #endif
1060
1061       case 1:
1062       case 40:  p =
1063             _("Usage: @GPG@ [options] [files] (-h for help)");
1064         break;
1065       case 41:  p =
1066             _("Syntax: @GPG@ [options] [files]\n"
1067               "Sign, check, encrypt or decrypt\n"
1068               "Default operation depends on the input data\n");
1069         break;
1070
1071       case 31: p = "\nHome: "; break;
1072 #ifndef __riscos__
1073       case 32: p = gnupg_homedir (); break;
1074 #else /* __riscos__ */
1075       case 32: p = make_filename(gnupg_homedir (), NULL); break;
1076 #endif /* __riscos__ */
1077       case 33: p = _("\nSupported algorithms:\n"); break;
1078       case 34:
1079         if (!pubkeys)
1080             pubkeys = build_list (_("Pubkey: "), 1,
1081                                   build_list_pk_algo_name,
1082                                   build_list_pk_test_algo );
1083         p = pubkeys;
1084         break;
1085       case 35:
1086         if( !ciphers )
1087             ciphers = build_list(_("Cipher: "), 'S',
1088                                  build_list_cipher_algo_name,
1089                                  build_list_cipher_test_algo );
1090         p = ciphers;
1091         break;
1092       case 36:
1093         if( !digests )
1094             digests = build_list(_("Hash: "), 'H',
1095                                  build_list_md_algo_name,
1096                                  build_list_md_test_algo );
1097         p = digests;
1098         break;
1099       case 37:
1100         if( !zips )
1101             zips = build_list(_("Compression: "),'Z',
1102                               compress_algo_to_string,
1103                               check_compress_algo);
1104         p = zips;
1105         break;
1106
1107       default:  p = NULL;
1108     }
1109     return p;
1110 }
1111
1112
1113 static char *
1114 build_list (const char *text, char letter,
1115             const char * (*mapf)(int), int (*chkf)(int))
1116 {
1117   membuf_t mb;
1118   int indent;
1119   int i, j, len;
1120   const char *s;
1121   char *string;
1122
1123   if (maybe_setuid)
1124     gcry_control (GCRYCTL_INIT_SECMEM, 0, 0);  /* Drop setuid. */
1125
1126   indent = utf8_charcount (text, -1);
1127   len = 0;
1128   init_membuf (&mb, 512);
1129
1130   for (i=0; i <= 110; i++ )
1131     {
1132       if (!chkf (i) && (s = mapf (i)))
1133         {
1134           if (mb.len - len > 60)
1135             {
1136               put_membuf_str (&mb, ",\n");
1137               len = mb.len;
1138               for (j=0; j < indent; j++)
1139                 put_membuf_str (&mb, " ");
1140             }
1141           else if (mb.len)
1142             put_membuf_str (&mb, ", ");
1143           else
1144             put_membuf_str (&mb, text);
1145
1146           put_membuf_str (&mb, s);
1147           if (opt.verbose && letter)
1148             {
1149               char num[20];
1150               if (letter == 1)
1151                 snprintf (num, sizeof num, " (%d)", i);
1152               else
1153                 snprintf (num, sizeof num, " (%c%d)", letter, i);
1154               put_membuf_str (&mb, num);
1155             }
1156         }
1157     }
1158   if (mb.len)
1159     put_membuf_str (&mb, "\n");
1160   put_membuf (&mb, "", 1);
1161
1162   string = get_membuf (&mb, NULL);
1163   return xrealloc (string, strlen (string)+1);
1164 }
1165
1166
1167 static void
1168 wrong_args( const char *text)
1169 {
1170   es_fprintf (es_stderr, _("usage: %s [options] %s\n"), GPG_NAME, text);
1171   log_inc_errorcount ();
1172   g10_exit(2);
1173 }
1174
1175
1176 static char *
1177 make_username( const char *string )
1178 {
1179     char *p;
1180     if( utf8_strings )
1181         p = xstrdup(string);
1182     else
1183         p = native_to_utf8( string );
1184     return p;
1185 }
1186
1187
1188 static void
1189 set_opt_session_env (const char *name, const char *value)
1190 {
1191   gpg_error_t err;
1192
1193   err = session_env_setenv (opt.session_env, name, value);
1194   if (err)
1195     log_fatal ("error setting session environment: %s\n",
1196                gpg_strerror (err));
1197 }
1198
1199
1200 /* Setup the debugging.  With a LEVEL of NULL only the active debug
1201    flags are propagated to the subsystems.  With LEVEL set, a specific
1202    set of debug flags is set; thus overriding all flags already
1203    set. */
1204 static void
1205 set_debug (const char *level)
1206 {
1207   int numok = (level && digitp (level));
1208   int numlvl = numok? atoi (level) : 0;
1209
1210   if (!level)
1211     ;
1212   else if (!strcmp (level, "none") || (numok && numlvl < 1))
1213     opt.debug = 0;
1214   else if (!strcmp (level, "basic") || (numok && numlvl <= 2))
1215     opt.debug = DBG_MEMSTAT_VALUE;
1216   else if (!strcmp (level, "advanced") || (numok && numlvl <= 5))
1217     opt.debug = DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE;
1218   else if (!strcmp (level, "expert")  || (numok && numlvl <= 8))
1219     opt.debug = (DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE
1220                  |DBG_CACHE_VALUE|DBG_LOOKUP|DBG_FILTER_VALUE|DBG_PACKET_VALUE);
1221   else if (!strcmp (level, "guru") || numok)
1222     {
1223       opt.debug = ~0;
1224       /* Unless the "guru" string has been used we don't want to allow
1225          hashing debugging.  The rationale is that people tend to
1226          select the highest debug value and would then clutter their
1227          disk with debug files which may reveal confidential data.  */
1228       if (numok)
1229         opt.debug &= ~(DBG_HASHING_VALUE);
1230     }
1231   else
1232     {
1233       log_error (_("invalid debug-level '%s' given\n"), level);
1234       g10_exit (2);
1235     }
1236
1237   if ((opt.debug & DBG_MEMORY_VALUE))
1238     memory_debug_mode = 1;
1239   if ((opt.debug & DBG_MEMSTAT_VALUE))
1240     memory_stat_debug_mode = 1;
1241   if (DBG_MPI)
1242     gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
1243   if (DBG_CRYPTO)
1244     gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
1245   if ((opt.debug & DBG_IOBUF_VALUE))
1246     iobuf_debug_mode = 1;
1247   gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1248
1249   if (opt.debug)
1250     parse_debug_flag (NULL, &opt.debug, debug_flags);
1251 }
1252
1253
1254 /* We set the screen dimensions for UI purposes.  Do not allow screens
1255    smaller than 80x24 for the sake of simplicity. */
1256 static void
1257 set_screen_dimensions(void)
1258 {
1259 #ifndef HAVE_W32_SYSTEM
1260   char *str;
1261
1262   str=getenv("COLUMNS");
1263   if(str)
1264     opt.screen_columns=atoi(str);
1265
1266   str=getenv("LINES");
1267   if(str)
1268     opt.screen_lines=atoi(str);
1269 #endif
1270
1271   if(opt.screen_columns<80 || opt.screen_columns>255)
1272     opt.screen_columns=80;
1273
1274   if(opt.screen_lines<24 || opt.screen_lines>255)
1275     opt.screen_lines=24;
1276 }
1277
1278
1279 /* Helper to open a file FNAME either for reading or writing to be
1280    used with --status-file etc functions.  Not generally useful but it
1281    avoids the riscos specific functions and well some Windows people
1282    might like it too.  Prints an error message and returns -1 on
1283    error.  On success the file descriptor is returned.  */
1284 static int
1285 open_info_file (const char *fname, int for_write, int binary)
1286 {
1287 #ifdef __riscos__
1288   return riscos_fdopenfile (fname, for_write);
1289 #elif defined (ENABLE_SELINUX_HACKS)
1290   /* We can't allow these even when testing for a secured filename
1291      because files to be secured might not yet been secured.  This is
1292      similar to the option file but in that case it is unlikely that
1293      sensitive information may be retrieved by means of error
1294      messages.  */
1295   (void)fname;
1296   (void)for_write;
1297   (void)binary;
1298   return -1;
1299 #else
1300   int fd;
1301
1302   if (binary)
1303     binary = MY_O_BINARY;
1304
1305 /*   if (is_secured_filename (fname)) */
1306 /*     { */
1307 /*       fd = -1; */
1308 /*       gpg_err_set_errno (EPERM); */
1309 /*     } */
1310 /*   else */
1311 /*     { */
1312       do
1313         {
1314           if (for_write)
1315             fd = open (fname, O_CREAT | O_TRUNC | O_WRONLY | binary,
1316                         S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
1317           else
1318             fd = open (fname, O_RDONLY | binary);
1319         }
1320       while (fd == -1 && errno == EINTR);
1321 /*     } */
1322   if ( fd == -1)
1323     log_error ( for_write? _("can't create '%s': %s\n")
1324                          : _("can't open '%s': %s\n"), fname, strerror(errno));
1325
1326   return fd;
1327 #endif
1328 }
1329
1330 static void
1331 set_cmd( enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd )
1332 {
1333     enum cmd_and_opt_values cmd = *ret_cmd;
1334
1335     if( !cmd || cmd == new_cmd )
1336         cmd = new_cmd;
1337     else if( cmd == aSign && new_cmd == aEncr )
1338         cmd = aSignEncr;
1339     else if( cmd == aEncr && new_cmd == aSign )
1340         cmd = aSignEncr;
1341     else if( cmd == aSign && new_cmd == aSym )
1342         cmd = aSignSym;
1343     else if( cmd == aSym && new_cmd == aSign )
1344         cmd = aSignSym;
1345     else if( cmd == aSym && new_cmd == aEncr )
1346         cmd = aEncrSym;
1347     else if( cmd == aEncr && new_cmd == aSym )
1348         cmd = aEncrSym;
1349     else if (cmd == aSignEncr && new_cmd == aSym)
1350         cmd = aSignEncrSym;
1351     else if (cmd == aSignSym && new_cmd == aEncr)
1352         cmd = aSignEncrSym;
1353     else if (cmd == aEncrSym && new_cmd == aSign)
1354         cmd = aSignEncrSym;
1355     else if(    ( cmd == aSign     && new_cmd == aClearsign )
1356              || ( cmd == aClearsign && new_cmd == aSign )  )
1357         cmd = aClearsign;
1358     else {
1359         log_error(_("conflicting commands\n"));
1360         g10_exit(2);
1361     }
1362
1363     *ret_cmd = cmd;
1364 }
1365
1366
1367 static void
1368 add_group(char *string)
1369 {
1370   char *name,*value;
1371   struct groupitem *item;
1372
1373   /* Break off the group name */
1374   name=strsep(&string,"=");
1375   if(string==NULL)
1376     {
1377       log_error(_("no = sign found in group definition '%s'\n"),name);
1378       return;
1379     }
1380
1381   trim_trailing_ws(name,strlen(name));
1382
1383   /* Does this group already exist? */
1384   for(item=opt.grouplist;item;item=item->next)
1385     if(strcasecmp(item->name,name)==0)
1386       break;
1387
1388   if(!item)
1389     {
1390       item=xmalloc(sizeof(struct groupitem));
1391       item->name=name;
1392       item->next=opt.grouplist;
1393       item->values=NULL;
1394       opt.grouplist=item;
1395     }
1396
1397   /* Break apart the values */
1398   while ((value= strsep(&string," \t")))
1399     {
1400       if (*value)
1401         add_to_strlist2(&item->values,value,utf8_strings);
1402     }
1403 }
1404
1405
1406 static void
1407 rm_group(char *name)
1408 {
1409   struct groupitem *item,*last=NULL;
1410
1411   trim_trailing_ws(name,strlen(name));
1412
1413   for(item=opt.grouplist;item;last=item,item=item->next)
1414     {
1415       if(strcasecmp(item->name,name)==0)
1416         {
1417           if(last)
1418             last->next=item->next;
1419           else
1420             opt.grouplist=item->next;
1421
1422           free_strlist(item->values);
1423           xfree(item);
1424           break;
1425         }
1426     }
1427 }
1428
1429
1430 /* We need to check three things.
1431
1432    0) The homedir.  It must be x00, a directory, and owned by the
1433    user.
1434
1435    1) The options/gpg.conf file.  Okay unless it or its containing
1436    directory is group or other writable or not owned by us.  Disable
1437    exec in this case.
1438
1439    2) Extensions.  Same as #1.
1440
1441    Returns true if the item is unsafe. */
1442 static int
1443 check_permissions (const char *path, int item)
1444 {
1445 #if defined(HAVE_STAT) && !defined(HAVE_DOSISH_SYSTEM)
1446   static int homedir_cache=-1;
1447   char *tmppath,*dir;
1448   struct stat statbuf,dirbuf;
1449   int homedir=0,ret=0,checkonly=0;
1450   int perm=0,own=0,enc_dir_perm=0,enc_dir_own=0;
1451
1452   if(opt.no_perm_warn)
1453     return 0;
1454
1455   log_assert(item==0 || item==1 || item==2);
1456
1457   /* extensions may attach a path */
1458   if(item==2 && path[0]!=DIRSEP_C)
1459     {
1460       if(strchr(path,DIRSEP_C))
1461         tmppath=make_filename(path,NULL);
1462       else
1463         tmppath=make_filename(gnupg_libdir (),path,NULL);
1464     }
1465   else
1466     tmppath=xstrdup(path);
1467
1468   /* If the item is located in the homedir, but isn't the homedir,
1469      don't continue if we already checked the homedir itself.  This is
1470      to avoid user confusion with an extra options file warning which
1471      could be rectified if the homedir itself had proper
1472      permissions. */
1473   if(item!=0 && homedir_cache>-1
1474      && !ascii_strncasecmp (gnupg_homedir (), tmppath,
1475                             strlen (gnupg_homedir ())))
1476     {
1477       ret=homedir_cache;
1478       goto end;
1479     }
1480
1481   /* It's okay if the file or directory doesn't exist */
1482   if(stat(tmppath,&statbuf)!=0)
1483     {
1484       ret=0;
1485       goto end;
1486     }
1487
1488   /* Now check the enclosing directory.  Theoretically, we could walk
1489      this test up to the root directory /, but for the sake of sanity,
1490      I'm stopping at one level down. */
1491   dir=make_dirname(tmppath);
1492
1493   if(stat(dir,&dirbuf)!=0 || !S_ISDIR(dirbuf.st_mode))
1494     {
1495       /* Weird error */
1496       ret=1;
1497       goto end;
1498     }
1499
1500   xfree(dir);
1501
1502   /* Assume failure */
1503   ret=1;
1504
1505   if(item==0)
1506     {
1507       /* The homedir must be x00, a directory, and owned by the user. */
1508
1509       if(S_ISDIR(statbuf.st_mode))
1510         {
1511           if(statbuf.st_uid==getuid())
1512             {
1513               if((statbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1514                 ret=0;
1515               else
1516                 perm=1;
1517             }
1518           else
1519             own=1;
1520
1521           homedir_cache=ret;
1522         }
1523     }
1524   else if(item==1 || item==2)
1525     {
1526       /* The options or extension file.  Okay unless it or its
1527          containing directory is group or other writable or not owned
1528          by us or root. */
1529
1530       if(S_ISREG(statbuf.st_mode))
1531         {
1532           if(statbuf.st_uid==getuid() || statbuf.st_uid==0)
1533             {
1534               if((statbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1535                 {
1536                   /* it's not writable, so make sure the enclosing
1537                      directory is also not writable */
1538                   if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1539                     {
1540                       if((dirbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1541                         ret=0;
1542                       else
1543                         enc_dir_perm=1;
1544                     }
1545                   else
1546                     enc_dir_own=1;
1547                 }
1548               else
1549                 {
1550                   /* it's writable, so the enclosing directory had
1551                      better not let people get to it. */
1552                   if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1553                     {
1554                       if((dirbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1555                         ret=0;
1556                       else
1557                         perm=enc_dir_perm=1; /* unclear which one to fix! */
1558                     }
1559                   else
1560                     enc_dir_own=1;
1561                 }
1562             }
1563           else
1564             own=1;
1565         }
1566     }
1567   else
1568     BUG();
1569
1570   if(!checkonly)
1571     {
1572       if(own)
1573         {
1574           if(item==0)
1575             log_info(_("WARNING: unsafe ownership on"
1576                        " homedir '%s'\n"),tmppath);
1577           else if(item==1)
1578             log_info(_("WARNING: unsafe ownership on"
1579                        " configuration file '%s'\n"),tmppath);
1580           else
1581             log_info(_("WARNING: unsafe ownership on"
1582                        " extension '%s'\n"),tmppath);
1583         }
1584       if(perm)
1585         {
1586           if(item==0)
1587             log_info(_("WARNING: unsafe permissions on"
1588                        " homedir '%s'\n"),tmppath);
1589           else if(item==1)
1590             log_info(_("WARNING: unsafe permissions on"
1591                        " configuration file '%s'\n"),tmppath);
1592           else
1593             log_info(_("WARNING: unsafe permissions on"
1594                        " extension '%s'\n"),tmppath);
1595         }
1596       if(enc_dir_own)
1597         {
1598           if(item==0)
1599             log_info(_("WARNING: unsafe enclosing directory ownership on"
1600                        " homedir '%s'\n"),tmppath);
1601           else if(item==1)
1602             log_info(_("WARNING: unsafe enclosing directory ownership on"
1603                        " configuration file '%s'\n"),tmppath);
1604           else
1605             log_info(_("WARNING: unsafe enclosing directory ownership on"
1606                        " extension '%s'\n"),tmppath);
1607         }
1608       if(enc_dir_perm)
1609         {
1610           if(item==0)
1611             log_info(_("WARNING: unsafe enclosing directory permissions on"
1612                        " homedir '%s'\n"),tmppath);
1613           else if(item==1)
1614             log_info(_("WARNING: unsafe enclosing directory permissions on"
1615                        " configuration file '%s'\n"),tmppath);
1616           else
1617             log_info(_("WARNING: unsafe enclosing directory permissions on"
1618                        " extension '%s'\n"),tmppath);
1619         }
1620     }
1621
1622  end:
1623   xfree(tmppath);
1624
1625   if(homedir)
1626     homedir_cache=ret;
1627
1628   return ret;
1629
1630 #else /*!(HAVE_STAT && !HAVE_DOSISH_SYSTEM)*/
1631   (void)path;
1632   (void)item;
1633   return 0;
1634 #endif /*!(HAVE_STAT && !HAVE_DOSISH_SYSTEM)*/
1635 }
1636
1637
1638 /* Print the OpenPGP defined algo numbers.  */
1639 static void
1640 print_algo_numbers(int (*checker)(int))
1641 {
1642   int i,first=1;
1643
1644   for(i=0;i<=110;i++)
1645     {
1646       if(!checker(i))
1647         {
1648           if(first)
1649             first=0;
1650           else
1651             es_printf (";");
1652           es_printf ("%d",i);
1653         }
1654     }
1655 }
1656
1657
1658 static void
1659 print_algo_names(int (*checker)(int),const char *(*mapper)(int))
1660 {
1661   int i,first=1;
1662
1663   for(i=0;i<=110;i++)
1664     {
1665       if(!checker(i))
1666         {
1667           if(first)
1668             first=0;
1669           else
1670             es_printf (";");
1671           es_printf ("%s",mapper(i));
1672         }
1673     }
1674 }
1675
1676 /* In the future, we can do all sorts of interesting configuration
1677    output here.  For now, just give "group" as the Enigmail folks need
1678    it, and pubkey, cipher, hash, and compress as they may be useful
1679    for frontends. */
1680 static void
1681 list_config(char *items)
1682 {
1683   int show_all = !items;
1684   char *name = NULL;
1685   const char *s;
1686   struct groupitem *giter;
1687   int first, iter;
1688
1689   if(!opt.with_colons)
1690     return;
1691
1692   while(show_all || (name=strsep(&items," ")))
1693     {
1694       int any=0;
1695
1696       if(show_all || ascii_strcasecmp(name,"group")==0)
1697         {
1698           for (giter = opt.grouplist; giter; giter = giter->next)
1699             {
1700               strlist_t sl;
1701
1702               es_fprintf (es_stdout, "cfg:group:");
1703               es_write_sanitized (es_stdout, giter->name, strlen(giter->name),
1704                                   ":", NULL);
1705               es_putc (':', es_stdout);
1706
1707               for(sl=giter->values; sl; sl=sl->next)
1708                 {
1709                   es_write_sanitized (es_stdout, sl->d, strlen (sl->d),
1710                                       ":;", NULL);
1711                   if(sl->next)
1712                     es_printf(";");
1713                 }
1714
1715               es_printf("\n");
1716             }
1717
1718           any=1;
1719         }
1720
1721       if(show_all || ascii_strcasecmp(name,"version")==0)
1722         {
1723           es_printf("cfg:version:");
1724           es_write_sanitized (es_stdout, VERSION, strlen(VERSION), ":", NULL);
1725           es_printf ("\n");
1726           any=1;
1727         }
1728
1729       if(show_all || ascii_strcasecmp(name,"pubkey")==0)
1730         {
1731           es_printf ("cfg:pubkey:");
1732           print_algo_numbers (build_list_pk_test_algo);
1733           es_printf ("\n");
1734           any=1;
1735         }
1736
1737       if(show_all || ascii_strcasecmp(name,"pubkeyname")==0)
1738         {
1739           es_printf ("cfg:pubkeyname:");
1740           print_algo_names (build_list_pk_test_algo,
1741                             build_list_pk_algo_name);
1742           es_printf ("\n");
1743           any=1;
1744         }
1745
1746       if(show_all || ascii_strcasecmp(name,"cipher")==0)
1747         {
1748           es_printf ("cfg:cipher:");
1749           print_algo_numbers (build_list_cipher_test_algo);
1750           es_printf ("\n");
1751           any=1;
1752         }
1753
1754       if (show_all || !ascii_strcasecmp (name,"ciphername"))
1755         {
1756           es_printf ("cfg:ciphername:");
1757           print_algo_names (build_list_cipher_test_algo,
1758                             build_list_cipher_algo_name);
1759           es_printf ("\n");
1760           any = 1;
1761         }
1762
1763       if(show_all
1764          || ascii_strcasecmp(name,"digest")==0
1765          || ascii_strcasecmp(name,"hash")==0)
1766         {
1767           es_printf ("cfg:digest:");
1768           print_algo_numbers (build_list_md_test_algo);
1769           es_printf ("\n");
1770           any=1;
1771         }
1772
1773       if (show_all
1774           || !ascii_strcasecmp(name,"digestname")
1775           || !ascii_strcasecmp(name,"hashname"))
1776         {
1777           es_printf ("cfg:digestname:");
1778           print_algo_names (build_list_md_test_algo,
1779                             build_list_md_algo_name);
1780           es_printf ("\n");
1781           any=1;
1782         }
1783
1784       if(show_all || ascii_strcasecmp(name,"compress")==0)
1785         {
1786           es_printf ("cfg:compress:");
1787           print_algo_numbers(check_compress_algo);
1788           es_printf ("\n");
1789           any=1;
1790         }
1791
1792       if(show_all || ascii_strcasecmp (name, "compressname") == 0)
1793         {
1794           es_printf ("cfg:compressname:");
1795           print_algo_names (check_compress_algo,
1796                             compress_algo_to_string);
1797           es_printf ("\n");
1798           any=1;
1799         }
1800
1801       if (show_all || !ascii_strcasecmp(name,"ccid-reader-id"))
1802         {
1803           /* We ignore this for GnuPG 1.4 backward compatibility.  */
1804           any=1;
1805         }
1806
1807       if (show_all || !ascii_strcasecmp (name,"curve"))
1808         {
1809           es_printf ("cfg:curve:");
1810           for (iter=0, first=1; (s = openpgp_enum_curves (&iter)); first=0)
1811             es_printf ("%s%s", first?"":";", s);
1812           es_printf ("\n");
1813           any=1;
1814         }
1815
1816       /* Curve OIDs are rarely useful and thus only printed if requested.  */
1817       if (name && !ascii_strcasecmp (name,"curveoid"))
1818         {
1819           es_printf ("cfg:curveoid:");
1820           for (iter=0, first=1; (s = openpgp_enum_curves (&iter)); first = 0)
1821             {
1822               s = openpgp_curve_to_oid (s, NULL);
1823               es_printf ("%s%s", first?"":";", s? s:"[?]");
1824             }
1825           es_printf ("\n");
1826           any=1;
1827         }
1828
1829       if(show_all)
1830         break;
1831
1832       if(!any)
1833         log_error(_("unknown configuration item '%s'\n"),name);
1834     }
1835 }
1836
1837
1838 /* List options and default values in the GPG Conf format.  This is a
1839    new tool distributed with gnupg 1.9.x but we also want some limited
1840    support in older gpg versions.  The output is the name of the
1841    configuration file and a list of options available for editing by
1842    gpgconf.  */
1843 static void
1844 gpgconf_list (const char *configfile)
1845 {
1846   char *configfile_esc = percent_escape (configfile, NULL);
1847
1848   es_printf ("%s-%s.conf:%lu:\"%s\n",
1849              GPGCONF_NAME, GPG_NAME,
1850              GC_OPT_FLAG_DEFAULT,
1851              configfile_esc ? configfile_esc : "/dev/null");
1852   es_printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
1853   es_printf ("quiet:%lu:\n",   GC_OPT_FLAG_NONE);
1854   es_printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
1855   es_printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE);
1856   es_printf ("default-key:%lu:\n", GC_OPT_FLAG_NONE);
1857   es_printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_NONE);
1858   es_printf ("try-secret-key:%lu:\n", GC_OPT_FLAG_NONE);
1859   es_printf ("auto-key-locate:%lu:\n", GC_OPT_FLAG_NONE);
1860   es_printf ("auto-key-retrieve:%lu:\n", GC_OPT_FLAG_NONE);
1861   es_printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE);
1862   es_printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
1863   es_printf ("group:%lu:\n", GC_OPT_FLAG_NONE);
1864   es_printf ("compliance:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT, "gnupg");
1865   es_printf ("default-new-key-algo:%lu:\n", GC_OPT_FLAG_NONE);
1866   es_printf ("trust-model:%lu:\n", GC_OPT_FLAG_NONE);
1867   es_printf ("disable-dirmngr:%lu:\n", GC_OPT_FLAG_NONE);
1868   es_printf ("max-cert-depth:%lu:\n", GC_OPT_FLAG_NONE);
1869   es_printf ("completes-needed:%lu:\n", GC_OPT_FLAG_NONE);
1870   es_printf ("marginals-needed:%lu:\n", GC_OPT_FLAG_NONE);
1871
1872   /* The next one is an info only item and should match the macros at
1873      the top of keygen.c  */
1874   es_printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1875              get_default_pubkey_algo ());
1876
1877   xfree (configfile_esc);
1878 }
1879
1880
1881 static int
1882 parse_subpacket_list(char *list)
1883 {
1884   char *tok;
1885   byte subpackets[128],i;
1886   int count=0;
1887
1888   if(!list)
1889     {
1890       /* No arguments means all subpackets */
1891       memset(subpackets+1,1,sizeof(subpackets)-1);
1892       count=127;
1893     }
1894   else
1895     {
1896       memset(subpackets,0,sizeof(subpackets));
1897
1898       /* Merge with earlier copy */
1899       if(opt.show_subpackets)
1900         {
1901           byte *in;
1902
1903           for(in=opt.show_subpackets;*in;in++)
1904             {
1905               if(*in>127 || *in<1)
1906                 BUG();
1907
1908               if(!subpackets[*in])
1909                 count++;
1910               subpackets[*in]=1;
1911             }
1912         }
1913
1914       while((tok=strsep(&list," ,")))
1915         {
1916           if(!*tok)
1917             continue;
1918
1919           i=atoi(tok);
1920           if(i>127 || i<1)
1921             return 0;
1922
1923           if(!subpackets[i])
1924             count++;
1925           subpackets[i]=1;
1926         }
1927     }
1928
1929   xfree(opt.show_subpackets);
1930   opt.show_subpackets=xmalloc(count+1);
1931   opt.show_subpackets[count--]=0;
1932
1933   for(i=1;i<128 && count>=0;i++)
1934     if(subpackets[i])
1935       opt.show_subpackets[count--]=i;
1936
1937   return 1;
1938 }
1939
1940
1941 static int
1942 parse_list_options(char *str)
1943 {
1944   char *subpackets=""; /* something that isn't NULL */
1945   struct parse_options lopts[]=
1946     {
1947       {"show-photos",LIST_SHOW_PHOTOS,NULL,
1948        N_("display photo IDs during key listings")},
1949       {"show-usage",LIST_SHOW_USAGE,NULL,
1950        N_("show key usage information during key listings")},
1951       {"show-policy-urls",LIST_SHOW_POLICY_URLS,NULL,
1952        N_("show policy URLs during signature listings")},
1953       {"show-notations",LIST_SHOW_NOTATIONS,NULL,
1954        N_("show all notations during signature listings")},
1955       {"show-std-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1956        N_("show IETF standard notations during signature listings")},
1957       {"show-standard-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1958        NULL},
1959       {"show-user-notations",LIST_SHOW_USER_NOTATIONS,NULL,
1960        N_("show user-supplied notations during signature listings")},
1961       {"show-keyserver-urls",LIST_SHOW_KEYSERVER_URLS,NULL,
1962        N_("show preferred keyserver URLs during signature listings")},
1963       {"show-uid-validity",LIST_SHOW_UID_VALIDITY,NULL,
1964        N_("show user ID validity during key listings")},
1965       {"show-unusable-uids",LIST_SHOW_UNUSABLE_UIDS,NULL,
1966        N_("show revoked and expired user IDs in key listings")},
1967       {"show-unusable-subkeys",LIST_SHOW_UNUSABLE_SUBKEYS,NULL,
1968        N_("show revoked and expired subkeys in key listings")},
1969       {"show-keyring",LIST_SHOW_KEYRING,NULL,
1970        N_("show the keyring name in key listings")},
1971       {"show-sig-expire",LIST_SHOW_SIG_EXPIRE,NULL,
1972        N_("show expiration dates during signature listings")},
1973       {"show-sig-subpackets",LIST_SHOW_SIG_SUBPACKETS,NULL,
1974        NULL},
1975       {"show-only-fpr-mbox",LIST_SHOW_ONLY_FPR_MBOX, NULL,
1976        NULL},
1977       {NULL,0,NULL,NULL}
1978     };
1979
1980   /* C99 allows for non-constant initializers, but we'd like to
1981      compile everywhere, so fill in the show-sig-subpackets argument
1982      here.  Note that if the parse_options array changes, we'll have
1983      to change the subscript here. */
1984   lopts[13].value=&subpackets;
1985
1986   if(parse_options(str,&opt.list_options,lopts,1))
1987     {
1988       if(opt.list_options&LIST_SHOW_SIG_SUBPACKETS)
1989         {
1990           /* Unset so users can pass multiple lists in. */
1991           opt.list_options&=~LIST_SHOW_SIG_SUBPACKETS;
1992           if(!parse_subpacket_list(subpackets))
1993             return 0;
1994         }
1995       else if(subpackets==NULL && opt.show_subpackets)
1996         {
1997           /* User did 'no-show-subpackets' */
1998           xfree(opt.show_subpackets);
1999           opt.show_subpackets=NULL;
2000         }
2001
2002       return 1;
2003     }
2004   else
2005     return 0;
2006 }
2007
2008
2009 /* Collapses argc/argv into a single string that must be freed */
2010 static char *
2011 collapse_args(int argc,char *argv[])
2012 {
2013   char *str=NULL;
2014   int i,first=1,len=0;
2015
2016   for(i=0;i<argc;i++)
2017     {
2018       len+=strlen(argv[i])+2;
2019       str=xrealloc(str,len);
2020       if(first)
2021         {
2022           str[0]='\0';
2023           first=0;
2024         }
2025       else
2026         strcat(str," ");
2027
2028       strcat(str,argv[i]);
2029     }
2030
2031   return str;
2032 }
2033
2034
2035 #ifndef NO_TRUST_MODELS
2036 static void
2037 parse_trust_model(const char *model)
2038 {
2039   if(ascii_strcasecmp(model,"pgp")==0)
2040     opt.trust_model=TM_PGP;
2041   else if(ascii_strcasecmp(model,"classic")==0)
2042     opt.trust_model=TM_CLASSIC;
2043   else if(ascii_strcasecmp(model,"always")==0)
2044     opt.trust_model=TM_ALWAYS;
2045   else if(ascii_strcasecmp(model,"direct")==0)
2046     opt.trust_model=TM_DIRECT;
2047 #ifdef USE_TOFU
2048   else if(ascii_strcasecmp(model,"tofu")==0)
2049     opt.trust_model=TM_TOFU;
2050   else if(ascii_strcasecmp(model,"tofu+pgp")==0)
2051     opt.trust_model=TM_TOFU_PGP;
2052 #endif /*USE_TOFU*/
2053   else if(ascii_strcasecmp(model,"auto")==0)
2054     opt.trust_model=TM_AUTO;
2055   else
2056     log_error("unknown trust model '%s'\n",model);
2057 }
2058 #endif /*NO_TRUST_MODELS*/
2059
2060
2061 static int
2062 parse_tofu_policy (const char *policystr)
2063 {
2064 #ifdef USE_TOFU
2065   struct { const char *keyword; int policy; } list[] = {
2066     { "auto",    TOFU_POLICY_AUTO },
2067     { "good",    TOFU_POLICY_GOOD },
2068     { "unknown", TOFU_POLICY_UNKNOWN },
2069     { "bad",     TOFU_POLICY_BAD },
2070     { "ask",     TOFU_POLICY_ASK }
2071   };
2072   int i;
2073
2074   if (!ascii_strcasecmp (policystr, "help"))
2075     {
2076       log_info (_("valid values for option '%s':\n"), "--tofu-policy");
2077       for (i=0; i < DIM (list); i++)
2078         log_info ("  %s\n", list[i].keyword);
2079       g10_exit (1);
2080     }
2081
2082   for (i=0; i < DIM (list); i++)
2083     if (!ascii_strcasecmp (policystr, list[i].keyword))
2084       return list[i].policy;
2085 #endif /*USE_TOFU*/
2086
2087   log_error (_("unknown TOFU policy '%s'\n"), policystr);
2088   if (!opt.quiet)
2089     log_info (_("(use \"help\" to list choices)\n"));
2090   g10_exit (1);
2091 }
2092
2093
2094 static struct gnupg_compliance_option compliance_options[] =
2095   {
2096     { "gnupg",      oGnuPG },
2097     { "openpgp",    oOpenPGP },
2098     { "rfc4880bis", oRFC4880bis },
2099     { "rfc4880",    oRFC4880 },
2100     { "rfc2440",    oRFC2440 },
2101     { "pgp6",       oPGP6 },
2102     { "pgp7",       oPGP7 },
2103     { "pgp8",       oPGP8 },
2104     { "de-vs",      oDE_VS }
2105   };
2106
2107
2108 /* Helper to set compliance related options.  This is a separate
2109  * function so that it can also be used by the --compliance option
2110  * parser.  */
2111 static void
2112 set_compliance_option (enum cmd_and_opt_values option)
2113 {
2114   switch (option)
2115     {
2116     case oRFC4880bis:
2117       opt.flags.rfc4880bis = 1;
2118       /* fall through.  */
2119     case oOpenPGP:
2120     case oRFC4880:
2121       /* This is effectively the same as RFC2440, but with
2122          "--enable-dsa2 --no-rfc2440-text --escape-from-lines
2123          --require-cross-certification". */
2124       opt.compliance = CO_RFC4880;
2125       opt.flags.dsa2 = 1;
2126       opt.flags.require_cross_cert = 1;
2127       opt.rfc2440_text = 0;
2128       opt.allow_non_selfsigned_uid = 1;
2129       opt.allow_freeform_uid = 1;
2130       opt.escape_from = 1;
2131       opt.not_dash_escaped = 0;
2132       opt.def_cipher_algo = 0;
2133       opt.def_digest_algo = 0;
2134       opt.cert_digest_algo = 0;
2135       opt.compress_algo = -1;
2136       opt.s2k_mode = 3; /* iterated+salted */
2137       opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2138       opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2139       break;
2140     case oRFC2440:
2141       opt.compliance = CO_RFC2440;
2142       opt.flags.dsa2 = 0;
2143       opt.rfc2440_text = 1;
2144       opt.allow_non_selfsigned_uid = 1;
2145       opt.allow_freeform_uid = 1;
2146       opt.escape_from = 0;
2147       opt.not_dash_escaped = 0;
2148       opt.def_cipher_algo = 0;
2149       opt.def_digest_algo = 0;
2150       opt.cert_digest_algo = 0;
2151       opt.compress_algo = -1;
2152       opt.s2k_mode = 3; /* iterated+salted */
2153       opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2154       opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2155       break;
2156     case oPGP6:  opt.compliance = CO_PGP6;  break;
2157     case oPGP7:  opt.compliance = CO_PGP7;  break;
2158     case oPGP8:  opt.compliance = CO_PGP8;  break;
2159     case oGnuPG: opt.compliance = CO_GNUPG; break;
2160
2161     case oDE_VS:
2162       set_compliance_option (oOpenPGP);
2163       opt.compliance = CO_DE_VS;
2164       /* Fixme: Change other options.  */
2165       break;
2166
2167     default:
2168       BUG ();
2169     }
2170 }
2171
2172
2173
2174
2175
2176
2177 /* This function called to initialized a new control object.  It is
2178    assumed that this object has been zeroed out before calling this
2179    function. */
2180 static void
2181 gpg_init_default_ctrl (ctrl_t ctrl)
2182 {
2183   ctrl->magic = SERVER_CONTROL_MAGIC;
2184 }
2185
2186
2187 /* This function is called to deinitialize a control object.  It is
2188    not deallocated. */
2189 static void
2190 gpg_deinit_default_ctrl (ctrl_t ctrl)
2191 {
2192 #ifdef USE_TOFU
2193   tofu_closedbs (ctrl);
2194 #endif
2195   gpg_dirmngr_deinit_session_data (ctrl);
2196
2197   keydb_release (ctrl->cached_getkey_kdb);
2198 }
2199
2200
2201 char *
2202 get_default_configname (void)
2203 {
2204   char *configname = NULL;
2205   char *name = xstrdup (GPG_NAME EXTSEP_S "conf-" SAFE_VERSION);
2206   char *ver = &name[strlen (GPG_NAME EXTSEP_S "conf-")];
2207
2208   do
2209     {
2210       if (configname)
2211         {
2212           char *tok;
2213
2214           xfree (configname);
2215           configname = NULL;
2216
2217           if ((tok = strrchr (ver, SAFE_VERSION_DASH)))
2218             *tok='\0';
2219           else if ((tok = strrchr (ver, SAFE_VERSION_DOT)))
2220             *tok='\0';
2221           else
2222             break;
2223         }
2224
2225       configname = make_filename (gnupg_homedir (), name, NULL);
2226     }
2227   while (access (configname, R_OK));
2228
2229   xfree(name);
2230
2231   if (! configname)
2232     configname = make_filename (gnupg_homedir (),
2233                                 GPG_NAME EXTSEP_S "conf", NULL);
2234   if (! access (configname, R_OK))
2235     {
2236       /* Print a warning when both config files are present.  */
2237       char *p = make_filename (gnupg_homedir (), "options", NULL);
2238       if (! access (p, R_OK))
2239         log_info (_("Note: old default options file '%s' ignored\n"), p);
2240       xfree (p);
2241     }
2242   else
2243     {
2244       /* Use the old default only if it exists.  */
2245       char *p = make_filename (gnupg_homedir (), "options", NULL);
2246       if (!access (p, R_OK))
2247         {
2248           xfree (configname);
2249           configname = p;
2250         }
2251       else
2252         xfree (p);
2253     }
2254
2255   return configname;
2256 }
2257
2258 int
2259 main (int argc, char **argv)
2260 {
2261     ARGPARSE_ARGS pargs;
2262     IOBUF a;
2263     int rc=0;
2264     int orig_argc;
2265     char **orig_argv;
2266     const char *fname;
2267     char *username;
2268     int may_coredump;
2269     strlist_t sl;
2270     strlist_t remusr = NULL;
2271     strlist_t locusr = NULL;
2272     strlist_t nrings = NULL;
2273     armor_filter_context_t *afx = NULL;
2274     int detached_sig = 0;
2275     FILE *configfp = NULL;
2276     char *configname = NULL;
2277     char *save_configname = NULL;
2278     char *default_configname = NULL;
2279     unsigned configlineno;
2280     int parse_debug = 0;
2281     int default_config = 1;
2282     int default_keyring = 1;
2283     int greeting = 0;
2284     int nogreeting = 0;
2285     char *logfile = NULL;
2286     int use_random_seed = 1;
2287     enum cmd_and_opt_values cmd = 0;
2288     const char *debug_level = NULL;
2289 #ifndef NO_TRUST_MODELS
2290     const char *trustdb_name = NULL;
2291 #endif /*!NO_TRUST_MODELS*/
2292     char *def_cipher_string = NULL;
2293     char *def_digest_string = NULL;
2294     char *compress_algo_string = NULL;
2295     char *cert_digest_string = NULL;
2296     char *s2k_cipher_string = NULL;
2297     char *s2k_digest_string = NULL;
2298     char *pers_cipher_list = NULL;
2299     char *pers_digest_list = NULL;
2300     char *pers_compress_list = NULL;
2301     int eyes_only=0;
2302     int multifile=0;
2303     int pwfd = -1;
2304     int ovrseskeyfd = -1;
2305     int fpr_maybe_cmd = 0; /* --fingerprint maybe a command.  */
2306     int any_explicit_recipient = 0;
2307     int default_akl = 1;
2308     int require_secmem = 0;
2309     int got_secmem = 0;
2310     struct assuan_malloc_hooks malloc_hooks;
2311     ctrl_t ctrl;
2312
2313     static int print_dane_records;
2314     static int print_pka_records;
2315
2316
2317 #ifdef __riscos__
2318     opt.lock_once = 1;
2319 #endif /* __riscos__ */
2320
2321     /* Please note that we may running SUID(ROOT), so be very CAREFUL
2322        when adding any stuff between here and the call to
2323        secmem_init() somewhere after the option parsing. */
2324     early_system_init ();
2325     gnupg_reopen_std (GPG_NAME);
2326     trap_unaligned ();
2327     gnupg_rl_initialize ();
2328     set_strusage (my_strusage);
2329     gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
2330     log_set_prefix (GPG_NAME, GPGRT_LOG_WITH_PREFIX);
2331
2332     /* Make sure that our subsystems are ready.  */
2333     i18n_init();
2334     init_common_subsystems (&argc, &argv);
2335
2336     /* Use our own logging handler for Libcgrypt.  */
2337     setup_libgcrypt_logging ();
2338
2339     /* Put random number into secure memory */
2340     gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
2341
2342     may_coredump = disable_core_dumps();
2343
2344     gnupg_init_signals (0, emergency_cleanup);
2345
2346     dotlock_create (NULL, 0); /* Register lock file cleanup. */
2347
2348     /* Tell the compliance module who we are.  */
2349     gnupg_initialize_compliance (GNUPG_MODULE_NAME_GPG);
2350
2351     opt.autostart = 1;
2352     opt.session_env = session_env_new ();
2353     if (!opt.session_env)
2354       log_fatal ("error allocating session environment block: %s\n",
2355                  strerror (errno));
2356
2357     opt.command_fd = -1; /* no command fd */
2358     opt.compress_level = -1; /* defaults to standard compress level */
2359     opt.bz2_compress_level = -1; /* defaults to standard compress level */
2360     /* note: if you change these lines, look at oOpenPGP */
2361     opt.def_cipher_algo = 0;
2362     opt.def_digest_algo = 0;
2363     opt.cert_digest_algo = 0;
2364     opt.compress_algo = -1; /* defaults to DEFAULT_COMPRESS_ALGO */
2365     opt.s2k_mode = 3; /* iterated+salted */
2366     opt.s2k_count = 0; /* Auto-calibrate when needed.  */
2367     opt.s2k_cipher_algo = DEFAULT_CIPHER_ALGO;
2368     opt.completes_needed = 1;
2369     opt.marginals_needed = 3;
2370     opt.max_cert_depth = 5;
2371     opt.escape_from = 1;
2372     opt.flags.require_cross_cert = 1;
2373     opt.import_options = IMPORT_REPAIR_KEYS;
2374     opt.export_options = EXPORT_ATTRIBUTES;
2375     opt.keyserver_options.import_options = (IMPORT_REPAIR_KEYS
2376                                             | IMPORT_REPAIR_PKS_SUBKEY_BUG);
2377     opt.keyserver_options.export_options = EXPORT_ATTRIBUTES;
2378     opt.keyserver_options.options = KEYSERVER_HONOR_PKA_RECORD;
2379     opt.verify_options = (LIST_SHOW_UID_VALIDITY
2380                           | VERIFY_SHOW_POLICY_URLS
2381                           | VERIFY_SHOW_STD_NOTATIONS
2382                           | VERIFY_SHOW_KEYSERVER_URLS);
2383     opt.list_options   = (LIST_SHOW_UID_VALIDITY
2384                           | LIST_SHOW_USAGE);
2385 #ifdef NO_TRUST_MODELS
2386     opt.trust_model = TM_ALWAYS;
2387 #else
2388     opt.trust_model = TM_AUTO;
2389 #endif
2390     opt.tofu_default_policy = TOFU_POLICY_AUTO;
2391     opt.mangle_dos_filenames = 0;
2392     opt.min_cert_level = 2;
2393     set_screen_dimensions ();
2394     opt.keyid_format = KF_NONE;
2395     opt.def_sig_expire = "0";
2396     opt.def_cert_expire = "0";
2397     gnupg_set_homedir (NULL);
2398     opt.passphrase_repeat = 1;
2399     opt.emit_version = 0;
2400     opt.weak_digests = NULL;
2401
2402     /* Check whether we have a config file on the command line.  */
2403     orig_argc = argc;
2404     orig_argv = argv;
2405     pargs.argc = &argc;
2406     pargs.argv = &argv;
2407     pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
2408     while( arg_parse( &pargs, opts) ) {
2409         if( pargs.r_opt == oDebug || pargs.r_opt == oDebugAll )
2410             parse_debug++;
2411         else if (pargs.r_opt == oDebugIOLBF)
2412             es_setvbuf (es_stdout, NULL, _IOLBF, 0);
2413         else if( pargs.r_opt == oOptions ) {
2414             /* yes there is one, so we do not try the default one, but
2415              * read the option file when it is encountered at the commandline
2416              */
2417             default_config = 0;
2418         }
2419         else if( pargs.r_opt == oNoOptions )
2420           {
2421             default_config = 0; /* --no-options */
2422             opt.no_homedir_creation = 1;
2423           }
2424         else if( pargs.r_opt == oHomedir )
2425             gnupg_set_homedir (pargs.r.ret_str);
2426         else if( pargs.r_opt == oNoPermissionWarn )
2427             opt.no_perm_warn=1;
2428         else if (pargs.r_opt == oStrict )
2429           {
2430             /* Not used */
2431           }
2432         else if (pargs.r_opt == oNoStrict )
2433           {
2434             /* Not used */
2435           }
2436     }
2437
2438 #ifdef HAVE_DOSISH_SYSTEM
2439     if ( strchr (gnupg_homedir (), '\\') ) {
2440       char *d, *buf = xmalloc (strlen (gnupg_homedir ())+1);
2441       const char *s;
2442       for (d=buf, s = gnupg_homedir (); *s; s++)
2443           {
2444             *d++ = *s == '\\'? '/': *s;
2445 #ifdef HAVE_W32_SYSTEM
2446             if (s[1] && IsDBCSLeadByte (*s))
2447               *d++ = *++s;
2448 #endif
2449           }
2450         *d = 0;
2451         gnupg_set_homedir (buf);
2452     }
2453 #endif
2454
2455     /* Initialize the secure memory. */
2456     if (!gcry_control (GCRYCTL_INIT_SECMEM, SECMEM_BUFFER_SIZE, 0))
2457       got_secmem = 1;
2458 #if defined(HAVE_GETUID) && defined(HAVE_GETEUID)
2459     /* There should be no way to get to this spot while still carrying
2460        setuid privs.  Just in case, bomb out if we are. */
2461     if ( getuid () != geteuid () )
2462       BUG ();
2463 #endif
2464     maybe_setuid = 0;
2465
2466     /* Okay, we are now working under our real uid */
2467
2468     /* malloc hooks go here ... */
2469     malloc_hooks.malloc = gcry_malloc;
2470     malloc_hooks.realloc = gcry_realloc;
2471     malloc_hooks.free = gcry_free;
2472     assuan_set_malloc_hooks (&malloc_hooks);
2473     assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
2474     setup_libassuan_logging (&opt.debug, NULL);
2475
2476     /* Set default options which require that malloc stuff is ready.  */
2477     additional_weak_digest ("MD5");
2478     parse_auto_key_locate ("local,wkd");
2479
2480     /* Try for a version specific config file first */
2481     default_configname = get_default_configname ();
2482     if (default_config)
2483       configname = xstrdup (default_configname);
2484
2485     argc = orig_argc;
2486     argv = orig_argv;
2487     pargs.argc = &argc;
2488     pargs.argv = &argv;
2489     pargs.flags= ARGPARSE_FLAG_KEEP;
2490
2491     /* By this point we have a homedir, and cannot change it. */
2492     check_permissions (gnupg_homedir (), 0);
2493
2494   next_pass:
2495     if( configname ) {
2496       if(check_permissions(configname,1))
2497         {
2498           /* If any options file is unsafe, then disable any external
2499              programs for keyserver calls or photo IDs.  Since the
2500              external program to call is set in the options file, a
2501              unsafe options file can lead to an arbitrary program
2502              being run. */
2503
2504           opt.exec_disable=1;
2505         }
2506
2507         configlineno = 0;
2508         configfp = fopen( configname, "r" );
2509         if (configfp && is_secured_file (fileno (configfp)))
2510           {
2511             fclose (configfp);
2512             configfp = NULL;
2513             gpg_err_set_errno (EPERM);
2514           }
2515         if( !configfp ) {
2516             if( default_config ) {
2517                 if( parse_debug )
2518                     log_info(_("Note: no default option file '%s'\n"),
2519                                                             configname );
2520             }
2521             else {
2522                 log_error(_("option file '%s': %s\n"),
2523                                     configname, strerror(errno) );
2524                 g10_exit(2);
2525             }
2526             xfree(configname); configname = NULL;
2527         }
2528         if( parse_debug && configname )
2529             log_info(_("reading options from '%s'\n"), configname );
2530         default_config = 0;
2531     }
2532
2533     while( optfile_parse( configfp, configname, &configlineno,
2534                                                 &pargs, opts) )
2535       {
2536         switch( pargs.r_opt )
2537           {
2538           case aListConfig:
2539           case aListGcryptConfig:
2540           case aGPGConfList:
2541           case aGPGConfTest:
2542             set_cmd (&cmd, pargs.r_opt);
2543             /* Do not register a keyring for these commands.  */
2544             default_keyring = -1;
2545             break;
2546
2547           case aCheckKeys:
2548           case aListPackets:
2549           case aImport:
2550           case aFastImport:
2551           case aSendKeys:
2552           case aRecvKeys:
2553           case aSearchKeys:
2554           case aRefreshKeys:
2555           case aFetchKeys:
2556           case aExport:
2557 #ifdef ENABLE_CARD_SUPPORT
2558           case aCardStatus:
2559           case aCardEdit:
2560           case aChangePIN:
2561 #endif /* ENABLE_CARD_SUPPORT*/
2562           case aListKeys:
2563           case aLocateKeys:
2564           case aListSigs:
2565           case aExportSecret:
2566           case aExportSecretSub:
2567           case aExportSshKey:
2568           case aSym:
2569           case aClearsign:
2570           case aGenRevoke:
2571           case aDesigRevoke:
2572           case aPrimegen:
2573           case aGenRandom:
2574           case aPrintMD:
2575           case aPrintMDs:
2576           case aListTrustDB:
2577           case aCheckTrustDB:
2578           case aUpdateTrustDB:
2579           case aFixTrustDB:
2580           case aListTrustPath:
2581           case aDeArmor:
2582           case aEnArmor:
2583           case aSign:
2584           case aQuickSignKey:
2585           case aQuickLSignKey:
2586           case aSignKey:
2587           case aLSignKey:
2588           case aStore:
2589           case aQuickKeygen:
2590           case aQuickAddUid:
2591           case aQuickAddKey:
2592           case aQuickRevUid:
2593           case aQuickSetExpire:
2594           case aQuickSetPrimaryUid:
2595           case aExportOwnerTrust:
2596           case aImportOwnerTrust:
2597           case aRebuildKeydbCaches:
2598             set_cmd (&cmd, pargs.r_opt);
2599             break;
2600
2601           case aKeygen:
2602           case aFullKeygen:
2603           case aEditKey:
2604           case aDeleteSecretKeys:
2605           case aDeleteSecretAndPublicKeys:
2606           case aDeleteKeys:
2607           case aPasswd:
2608             set_cmd (&cmd, pargs.r_opt);
2609             greeting=1;
2610             break;
2611
2612           case aShowKeys:
2613             set_cmd (&cmd, pargs.r_opt);
2614             opt.import_options |= IMPORT_SHOW;
2615             opt.import_options |= IMPORT_DRY_RUN;
2616             opt.import_options &= ~IMPORT_REPAIR_KEYS;
2617             opt.list_options |= LIST_SHOW_UNUSABLE_UIDS;
2618             opt.list_options |= LIST_SHOW_UNUSABLE_SUBKEYS;
2619             opt.list_options |= LIST_SHOW_NOTATIONS;
2620             opt.list_options |= LIST_SHOW_POLICY_URLS;
2621             break;
2622
2623           case aDetachedSign: detached_sig = 1; set_cmd( &cmd, aSign ); break;
2624
2625           case aDecryptFiles: multifile=1; /* fall through */
2626           case aDecrypt: set_cmd( &cmd, aDecrypt); break;
2627
2628           case aEncrFiles: multifile=1; /* fall through */
2629           case aEncr: set_cmd( &cmd, aEncr); break;
2630
2631           case aVerifyFiles: multifile=1; /* fall through */
2632           case aVerify: set_cmd( &cmd, aVerify); break;
2633
2634           case aServer:
2635             set_cmd (&cmd, pargs.r_opt);
2636             opt.batch = 1;
2637             break;
2638
2639           case aTOFUPolicy:
2640             set_cmd (&cmd, pargs.r_opt);
2641             break;
2642
2643           case oArmor: opt.armor = 1; opt.no_armor=0; break;
2644           case oOutput: opt.outfile = pargs.r.ret_str; break;
2645
2646           case oMaxOutput: opt.max_output = pargs.r.ret_ulong; break;
2647
2648           case oInputSizeHint:
2649             opt.input_size_hint = string_to_u64 (pargs.r.ret_str);
2650             break;
2651
2652           case oQuiet: opt.quiet = 1; break;
2653           case oNoTTY: tty_no_terminal(1); break;
2654           case oDryRun: opt.dry_run = 1; break;
2655           case oInteractive: opt.interactive = 1; break;
2656           case oVerbose:
2657             opt.verbose++;
2658             gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2659             opt.list_options|=LIST_SHOW_UNUSABLE_UIDS;
2660             opt.list_options|=LIST_SHOW_UNUSABLE_SUBKEYS;
2661             break;
2662
2663           case oBatch:
2664             opt.batch = 1;
2665             nogreeting = 1;
2666             break;
2667
2668           case oUseAgent: /* Dummy. */
2669             break;
2670
2671           case oNoUseAgent:
2672             obsolete_option (configname, configlineno, "no-use-agent");
2673             break;
2674           case oGpgAgentInfo:
2675             obsolete_option (configname, configlineno, "gpg-agent-info");
2676             break;
2677           case oReaderPort:
2678             obsolete_scdaemon_option (configname, configlineno, "reader-port");
2679             break;
2680           case octapiDriver:
2681             obsolete_scdaemon_option (configname, configlineno, "ctapi-driver");
2682             break;
2683           case opcscDriver:
2684             obsolete_scdaemon_option (configname, configlineno, "pcsc-driver");
2685             break;
2686           case oDisableCCID:
2687             obsolete_scdaemon_option (configname, configlineno, "disable-ccid");
2688             break;
2689           case oHonorHttpProxy:
2690             obsolete_option (configname, configlineno, "honor-http-proxy");
2691             break;
2692
2693           case oAnswerYes: opt.answer_yes = 1; break;
2694           case oAnswerNo: opt.answer_no = 1; break;
2695           case oKeyring: append_to_strlist( &nrings, pargs.r.ret_str); break;
2696           case oPrimaryKeyring:
2697             sl = append_to_strlist (&nrings, pargs.r.ret_str);
2698             sl->flags = KEYDB_RESOURCE_FLAG_PRIMARY;
2699             break;
2700           case oShowKeyring:
2701             deprecated_warning(configname,configlineno,"--show-keyring",
2702                                "--list-options ","show-keyring");
2703             opt.list_options|=LIST_SHOW_KEYRING;
2704             break;
2705
2706           case oDebug:
2707             if (parse_debug_flag (pargs.r.ret_str, &opt.debug, debug_flags))
2708               {
2709                 pargs.r_opt = ARGPARSE_INVALID_ARG;
2710                 pargs.err = ARGPARSE_PRINT_ERROR;
2711               }
2712             break;
2713
2714           case oDebugAll: opt.debug = ~0; break;
2715           case oDebugLevel: debug_level = pargs.r.ret_str; break;
2716
2717           case oDebugIOLBF: break; /* Already set in pre-parse step.  */
2718
2719           case oStatusFD:
2720             set_status_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
2721             break;
2722           case oStatusFile:
2723             set_status_fd ( open_info_file (pargs.r.ret_str, 1, 0) );
2724             break;
2725           case oAttributeFD:
2726             set_attrib_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
2727             break;
2728           case oAttributeFile:
2729             set_attrib_fd ( open_info_file (pargs.r.ret_str, 1, 1) );
2730             break;
2731           case oLoggerFD:
2732             log_set_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1));
2733             break;
2734           case oLoggerFile:
2735             logfile = pargs.r.ret_str;
2736             break;
2737
2738           case oWithFingerprint:
2739             opt.with_fingerprint = 1;
2740             opt.fingerprint++;
2741             break;
2742           case oWithSubkeyFingerprint:
2743             opt.with_subkey_fingerprint = 1;
2744             break;
2745           case oWithICAOSpelling:
2746             opt.with_icao_spelling = 1;
2747             break;
2748           case oFingerprint:
2749             opt.fingerprint++;
2750             fpr_maybe_cmd = 1;
2751             break;
2752
2753           case oWithKeygrip:
2754             opt.with_keygrip = 1;
2755             break;
2756
2757           case oWithSecret:
2758             opt.with_secret = 1;
2759             break;
2760
2761           case oWithWKDHash:
2762             opt.with_wkd_hash = 1;
2763             break;
2764
2765           case oWithKeyOrigin:
2766             opt.with_key_origin = 1;
2767             break;
2768
2769           case oSecretKeyring:
2770             /* Ignore this old option.  */
2771             break;
2772
2773           case oOptions:
2774             /* config files may not be nested (silently ignore them) */
2775             if( !configfp ) {
2776                 xfree(configname);
2777                 configname = xstrdup(pargs.r.ret_str);
2778                 goto next_pass;
2779             }
2780             break;
2781           case oNoArmor: opt.no_armor=1; opt.armor=0; break;
2782
2783           case oNoDefKeyring:
2784             if (default_keyring > 0)
2785               default_keyring = 0;
2786             break;
2787           case oNoKeyring:
2788             default_keyring = -1;
2789             break;
2790
2791           case oNoGreeting: nogreeting = 1; break;
2792           case oNoVerbose:
2793             opt.verbose = 0;
2794             gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2795             opt.list_sigs=0;
2796             break;
2797           case oQuickRandom:
2798             gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
2799             break;
2800           case oEmitVersion: opt.emit_version++; break;
2801           case oNoEmitVersion: opt.emit_version=0; break;
2802           case oCompletesNeeded: opt.completes_needed = pargs.r.ret_int; break;
2803           case oMarginalsNeeded: opt.marginals_needed = pargs.r.ret_int; break;
2804           case oMaxCertDepth: opt.max_cert_depth = pargs.r.ret_int; break;
2805
2806 #ifndef NO_TRUST_MODELS
2807           case oTrustDBName: trustdb_name = pargs.r.ret_str; break;
2808
2809 #endif /*!NO_TRUST_MODELS*/
2810           case oDefaultKey:
2811             sl = add_to_strlist (&opt.def_secret_key, pargs.r.ret_str);
2812             sl->flags = (pargs.r_opt << PK_LIST_SHIFT);
2813             if (configfp)
2814               sl->flags |= PK_LIST_CONFIG;
2815             break;
2816           case oDefRecipient:
2817             if( *pargs.r.ret_str )
2818               {
2819                 xfree (opt.def_recipient);
2820                 opt.def_recipient = make_username(pargs.r.ret_str);
2821               }
2822             break;
2823           case oDefRecipientSelf:
2824             xfree(opt.def_recipient); opt.def_recipient = NULL;
2825             opt.def_recipient_self = 1;
2826             break;
2827           case oNoDefRecipient:
2828             xfree(opt.def_recipient); opt.def_recipient = NULL;
2829             opt.def_recipient_self = 0;
2830             break;
2831           case oNoOptions: opt.no_homedir_creation = 1; break; /* no-options */
2832           case oHomedir: break;
2833           case oNoBatch: opt.batch = 0; break;
2834
2835           case oWithTofuInfo: opt.with_tofu_info = 1; break;
2836
2837           case oWithKeyData: opt.with_key_data=1; /*FALLTHRU*/
2838           case oWithColons: opt.with_colons=':'; break;
2839
2840           case oWithSigCheck: opt.check_sigs = 1; /*FALLTHRU*/
2841           case oWithSigList: opt.list_sigs = 1; break;
2842
2843           case oSkipVerify: opt.skip_verify=1; break;
2844
2845           case oSkipHiddenRecipients: opt.skip_hidden_recipients = 1; break;
2846           case oNoSkipHiddenRecipients: opt.skip_hidden_recipients = 0; break;
2847
2848           case aListSecretKeys: set_cmd( &cmd, aListSecretKeys); break;
2849
2850 #ifndef NO_TRUST_MODELS
2851             /* There are many programs (like mutt) that call gpg with
2852                --always-trust so keep this option around for a long
2853                time. */
2854           case oAlwaysTrust: opt.trust_model=TM_ALWAYS; break;
2855           case oTrustModel:
2856             parse_trust_model(pargs.r.ret_str);
2857             break;
2858 #endif /*!NO_TRUST_MODELS*/
2859           case oTOFUDefaultPolicy:
2860             opt.tofu_default_policy = parse_tofu_policy (pargs.r.ret_str);
2861             break;
2862           case oTOFUDBFormat:
2863             obsolete_option (configname, configlineno, "tofu-db-format");
2864             break;
2865
2866           case oForceOwnertrust:
2867             log_info(_("Note: %s is not for normal use!\n"),
2868                      "--force-ownertrust");
2869             opt.force_ownertrust=string_to_trust_value(pargs.r.ret_str);
2870             if(opt.force_ownertrust==-1)
2871               {
2872                 log_error("invalid ownertrust '%s'\n",pargs.r.ret_str);
2873                 opt.force_ownertrust=0;
2874               }
2875             break;
2876           case oLoadExtension:
2877             /* Dummy so that gpg 1.4 conf files can work. Should
2878                eventually be removed.  */
2879             break;
2880
2881           case oCompliance:
2882             {
2883               int compliance = gnupg_parse_compliance_option
2884                 (pargs.r.ret_str,
2885                  compliance_options, DIM (compliance_options),
2886                  opt.quiet);
2887               if (compliance < 0)
2888                 g10_exit (1);
2889               set_compliance_option (compliance);
2890             }
2891             break;
2892           case oOpenPGP:
2893           case oRFC2440:
2894           case oRFC4880:
2895           case oRFC4880bis:
2896           case oPGP6:
2897           case oPGP7:
2898           case oPGP8:
2899           case oGnuPG:
2900             set_compliance_option (pargs.r_opt);
2901             break;
2902
2903           case oRFC2440Text: opt.rfc2440_text=1; break;
2904           case oNoRFC2440Text: opt.rfc2440_text=0; break;
2905
2906           case oSetFilename:
2907             if(utf8_strings)
2908               opt.set_filename = pargs.r.ret_str;
2909             else
2910               opt.set_filename = native_to_utf8(pargs.r.ret_str);
2911             break;
2912           case oForYourEyesOnly: eyes_only = 1; break;
2913           case oNoForYourEyesOnly: eyes_only = 0; break;
2914           case oSetPolicyURL:
2915             add_policy_url(pargs.r.ret_str,0);
2916             add_policy_url(pargs.r.ret_str,1);
2917             break;
2918           case oSigPolicyURL: add_policy_url(pargs.r.ret_str,0); break;
2919           case oCertPolicyURL: add_policy_url(pargs.r.ret_str,1); break;
2920           case oShowPolicyURL:
2921             deprecated_warning(configname,configlineno,"--show-policy-url",
2922                                "--list-options ","show-policy-urls");
2923             deprecated_warning(configname,configlineno,"--show-policy-url",
2924                                "--verify-options ","show-policy-urls");
2925             opt.list_options|=LIST_SHOW_POLICY_URLS;
2926             opt.verify_options|=VERIFY_SHOW_POLICY_URLS;
2927             break;
2928           case oNoShowPolicyURL:
2929             deprecated_warning(configname,configlineno,"--no-show-policy-url",
2930                                "--list-options ","no-show-policy-urls");
2931             deprecated_warning(configname,configlineno,"--no-show-policy-url",
2932                                "--verify-options ","no-show-policy-urls");
2933             opt.list_options&=~LIST_SHOW_POLICY_URLS;
2934             opt.verify_options&=~VERIFY_SHOW_POLICY_URLS;
2935             break;
2936           case oSigKeyserverURL: add_keyserver_url(pargs.r.ret_str,0); break;
2937           case oUseEmbeddedFilename:
2938             opt.flags.use_embedded_filename=1;
2939             break;
2940           case oNoUseEmbeddedFilename:
2941             opt.flags.use_embedded_filename=0;
2942             break;
2943           case oComment:
2944             if(pargs.r.ret_str[0])
2945               append_to_strlist(&opt.comments,pargs.r.ret_str);
2946             break;
2947           case oDefaultComment:
2948             deprecated_warning(configname,configlineno,
2949                                "--default-comment","--no-comments","");
2950             /* fall through */
2951           case oNoComments:
2952             free_strlist(opt.comments);
2953             opt.comments=NULL;
2954             break;
2955           case oThrowKeyids: opt.throw_keyids = 1; break;
2956           case oNoThrowKeyids: opt.throw_keyids = 0; break;
2957           case oShowPhotos:
2958             deprecated_warning(configname,configlineno,"--show-photos",
2959                                "--list-options ","show-photos");
2960             deprecated_warning(configname,configlineno,"--show-photos",
2961                                "--verify-options ","show-photos");
2962             opt.list_options|=LIST_SHOW_PHOTOS;
2963             opt.verify_options|=VERIFY_SHOW_PHOTOS;
2964             break;
2965           case oNoShowPhotos:
2966             deprecated_warning(configname,configlineno,"--no-show-photos",
2967                                "--list-options ","no-show-photos");
2968             deprecated_warning(configname,configlineno,"--no-show-photos",
2969                                "--verify-options ","no-show-photos");
2970             opt.list_options&=~LIST_SHOW_PHOTOS;
2971             opt.verify_options&=~VERIFY_SHOW_PHOTOS;
2972             break;
2973           case oPhotoViewer: opt.photo_viewer = pargs.r.ret_str; break;
2974
2975           case oDisableSignerUID: opt.flags.disable_signer_uid = 1; break;
2976
2977           case oS2KMode:   opt.s2k_mode = pargs.r.ret_int; break;
2978           case oS2KDigest: s2k_digest_string = xstrdup(pargs.r.ret_str); break;
2979           case oS2KCipher: s2k_cipher_string = xstrdup(pargs.r.ret_str); break;
2980           case oS2KCount:
2981             if (pargs.r.ret_int)
2982               opt.s2k_count = encode_s2k_iterations (pargs.r.ret_int);
2983             else
2984               opt.s2k_count = 0;  /* Auto-calibrate when needed.  */
2985             break;
2986
2987           case oRecipient:
2988           case oHiddenRecipient:
2989           case oRecipientFile:
2990           case oHiddenRecipientFile:
2991             /* Store the recipient.  Note that we also store the
2992              * option as private data in the flags.  This is achieved
2993              * by shifting the option value to the left so to keep
2994              * enough space for the flags.  */
2995             sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2996             sl->flags = (pargs.r_opt << PK_LIST_SHIFT);
2997             if (configfp)
2998               sl->flags |= PK_LIST_CONFIG;
2999             if (pargs.r_opt == oHiddenRecipient
3000                 || pargs.r_opt == oHiddenRecipientFile)
3001               sl->flags |= PK_LIST_HIDDEN;
3002             if (pargs.r_opt == oRecipientFile
3003                 || pargs.r_opt == oHiddenRecipientFile)
3004               sl->flags |= PK_LIST_FROM_FILE;
3005             any_explicit_recipient = 1;
3006             break;
3007
3008           case oEncryptTo:
3009           case oHiddenEncryptTo:
3010             /* Store an additional recipient.  */
3011             sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
3012             sl->flags = ((pargs.r_opt << PK_LIST_SHIFT) | PK_LIST_ENCRYPT_TO);
3013             if (configfp)
3014               sl->flags |= PK_LIST_CONFIG;
3015             if (pargs.r_opt == oHiddenEncryptTo)
3016               sl->flags |= PK_LIST_HIDDEN;
3017             break;
3018
3019           case oNoEncryptTo:
3020             opt.no_encrypt_to = 1;
3021             break;
3022           case oEncryptToDefaultKey:
3023             opt.encrypt_to_default_key = configfp ? 2 : 1;
3024             break;
3025
3026           case oTrySecretKey:
3027             add_to_strlist2 (&opt.secret_keys_to_try,
3028                              pargs.r.ret_str, utf8_strings);
3029             break;
3030
3031           case oMimemode: opt.mimemode = opt.textmode = 1; break;
3032           case oTextmodeShort: opt.textmode = 2; break;
3033           case oTextmode: opt.textmode=1;  break;
3034           case oNoTextmode: opt.textmode=opt.mimemode=0;  break;
3035
3036           case oExpert: opt.expert = 1; break;
3037           case oNoExpert: opt.expert = 0; break;
3038           case oDefSigExpire:
3039             if(*pargs.r.ret_str!='\0')
3040               {
3041                 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
3042                   log_error(_("'%s' is not a valid signature expiration\n"),
3043                             pargs.r.ret_str);
3044                 else
3045                   opt.def_sig_expire=pargs.r.ret_str;
3046               }
3047             break;
3048           case oAskSigExpire: opt.ask_sig_expire = 1; break;
3049           case oNoAskSigExpire: opt.ask_sig_expire = 0; break;
3050           case oDefCertExpire:
3051             if(*pargs.r.ret_str!='\0')
3052               {
3053                 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
3054                   log_error(_("'%s' is not a valid signature expiration\n"),
3055                             pargs.r.ret_str);
3056                 else
3057                   opt.def_cert_expire=pargs.r.ret_str;
3058               }
3059             break;
3060           case oAskCertExpire: opt.ask_cert_expire = 1; break;
3061           case oNoAskCertExpire: opt.ask_cert_expire = 0; break;
3062           case oDefCertLevel: opt.def_cert_level=pargs.r.ret_int; break;
3063           case oMinCertLevel: opt.min_cert_level=pargs.r.ret_int; break;
3064           case oAskCertLevel: opt.ask_cert_level = 1; break;
3065           case oNoAskCertLevel: opt.ask_cert_level = 0; break;
3066           case oLocalUser: /* store the local users */
3067             sl = add_to_strlist2( &locusr, pargs.r.ret_str, utf8_strings );
3068             sl->flags = (pargs.r_opt << PK_LIST_SHIFT);
3069             if (configfp)
3070               sl->flags |= PK_LIST_CONFIG;
3071             break;
3072           case oSender:
3073             {
3074               char *mbox = mailbox_from_userid (pargs.r.ret_str);
3075               if (!mbox)
3076                 log_error (_("\"%s\" is not a proper mail address\n"),
3077                            pargs.r.ret_str);
3078               else
3079                 {
3080                   add_to_strlist (&opt.sender_list, mbox);
3081                   xfree (mbox);
3082                 }
3083             }
3084             break;
3085           case oCompress:
3086             /* this is the -z command line option */
3087             opt.compress_level = opt.bz2_compress_level = pargs.r.ret_int;
3088             break;
3089           case oCompressLevel: opt.compress_level = pargs.r.ret_int; break;
3090           case oBZ2CompressLevel: opt.bz2_compress_level = pargs.r.ret_int; break;
3091           case oBZ2DecompressLowmem: opt.bz2_decompress_lowmem=1; break;
3092           case oPassphrase:
3093             set_passphrase_from_string(pargs.r.ret_str);
3094             break;
3095           case oPassphraseFD:
3096             pwfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
3097             break;
3098           case oPassphraseFile:
3099             pwfd = open_info_file (pargs.r.ret_str, 0, 1);
3100             break;
3101           case oPassphraseRepeat:
3102             opt.passphrase_repeat = pargs.r.ret_int;
3103             break;
3104
3105           case oPinentryMode:
3106             opt.pinentry_mode = parse_pinentry_mode (pargs.r.ret_str);
3107             if (opt.pinentry_mode == -1)
3108               log_error (_("invalid pinentry mode '%s'\n"), pargs.r.ret_str);
3109             break;
3110
3111           case oRequestOrigin:
3112             opt.request_origin = parse_request_origin (pargs.r.ret_str);
3113             if (opt.request_origin == -1)
3114               log_error (_("invalid request origin '%s'\n"), pargs.r.ret_str);
3115             break;
3116
3117           case oCommandFD:
3118             opt.command_fd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
3119             if (! gnupg_fd_valid (opt.command_fd))
3120               log_error ("command-fd is invalid: %s\n", strerror (errno));
3121             break;
3122           case oCommandFile:
3123             opt.command_fd = open_info_file (pargs.r.ret_str, 0, 1);
3124             break;
3125           case oCipherAlgo:
3126             def_cipher_string = xstrdup(pargs.r.ret_str);
3127             break;
3128           case oDigestAlgo:
3129             def_digest_string = xstrdup(pargs.r.ret_str);
3130             break;
3131           case oCompressAlgo:
3132             /* If it is all digits, stick a Z in front of it for
3133                later.  This is for backwards compatibility with
3134                versions that took the compress algorithm number. */
3135             {
3136               char *pt=pargs.r.ret_str;
3137               while(*pt)
3138                 {
3139                   if (!isascii (*pt) || !isdigit (*pt))
3140                     break;
3141
3142                   pt++;
3143                 }
3144
3145               if(*pt=='\0')
3146                 {
3147                   compress_algo_string=xmalloc(strlen(pargs.r.ret_str)+2);
3148                   strcpy(compress_algo_string,"Z");
3149                   strcat(compress_algo_string,pargs.r.ret_str);
3150                 }
3151               else
3152                 compress_algo_string = xstrdup(pargs.r.ret_str);
3153             }
3154             break;
3155           case oCertDigestAlgo:
3156             cert_digest_string = xstrdup(pargs.r.ret_str);
3157             break;
3158
3159           case oNoSecmemWarn:
3160             gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
3161             break;
3162
3163           case oRequireSecmem: require_secmem=1; break;
3164           case oNoRequireSecmem: require_secmem=0; break;
3165           case oNoPermissionWarn: opt.no_perm_warn=1; break;
3166           case oDisplayCharset:
3167             if( set_native_charset( pargs.r.ret_str ) )
3168                 log_error(_("'%s' is not a valid character set\n"),
3169                           pargs.r.ret_str);
3170             break;
3171           case oNotDashEscaped: opt.not_dash_escaped = 1; break;
3172           case oEscapeFrom: opt.escape_from = 1; break;
3173           case oNoEscapeFrom: opt.escape_from = 0; break;
3174           case oLockOnce: opt.lock_once = 1; break;
3175           case oLockNever:
3176             dotlock_disable ();
3177             break;
3178           case oLockMultiple:
3179 #ifndef __riscos__
3180             opt.lock_once = 0;
3181 #else /* __riscos__ */
3182             riscos_not_implemented("lock-multiple");
3183 #endif /* __riscos__ */
3184             break;
3185           case oKeyServer:
3186             {
3187               keyserver_spec_t keyserver;
3188               keyserver = parse_keyserver_uri (pargs.r.ret_str, 0);
3189               if (!keyserver)
3190                 log_error (_("could not parse keyserver URL\n"));
3191               else
3192                 {
3193                   /* We only support a single keyserver.  Later ones
3194                      override earlier ones.  (Since we parse the
3195                      config file first and then the command line
3196                      arguments, the command line takes
3197                      precedence.)  */
3198                   if (opt.keyserver)
3199                     free_keyserver_spec (opt.keyserver);
3200                   opt.keyserver = keyserver;
3201                 }
3202             }
3203             break;
3204           case oKeyServerOptions:
3205             if(!parse_keyserver_options(pargs.r.ret_str))
3206               {
3207                 if(configname)
3208                   log_error(_("%s:%d: invalid keyserver options\n"),
3209                             configname,configlineno);
3210                 else
3211                   log_error(_("invalid keyserver options\n"));
3212               }
3213             break;
3214           case oImportOptions:
3215             if(!parse_import_options(pargs.r.ret_str,&opt.import_options,1))
3216               {
3217                 if(configname)
3218                   log_error(_("%s:%d: invalid import options\n"),
3219                             configname,configlineno);
3220                 else
3221                   log_error(_("invalid import options\n"));
3222               }
3223             break;
3224           case oImportFilter:
3225             rc = parse_and_set_import_filter (pargs.r.ret_str);
3226             if (rc)
3227               log_error (_("invalid filter option: %s\n"), gpg_strerror (rc));
3228             break;
3229           case oExportOptions:
3230             if(!parse_export_options(pargs.r.ret_str,&opt.export_options,1))
3231               {
3232                 if(configname)
3233                   log_error(_("%s:%d: invalid export options\n"),
3234                             configname,configlineno);
3235                 else
3236                   log_error(_("invalid export options\n"));
3237               }
3238             break;
3239           case oExportFilter:
3240             rc = parse_and_set_export_filter (pargs.r.ret_str);
3241             if (rc)
3242               log_error (_("invalid filter option: %s\n"), gpg_strerror (rc));
3243             break;
3244           case oListOptions:
3245             if(!parse_list_options(pargs.r.ret_str))
3246               {
3247                 if(configname)
3248                   log_error(_("%s:%d: invalid list options\n"),
3249                             configname,configlineno);
3250                 else
3251                   log_error(_("invalid list options\n"));
3252               }
3253             break;
3254           case oVerifyOptions:
3255             {
3256               struct parse_options vopts[]=
3257                 {
3258                   {"show-photos",VERIFY_SHOW_PHOTOS,NULL,
3259                    N_("display photo IDs during signature verification")},
3260                   {"show-policy-urls",VERIFY_SHOW_POLICY_URLS,NULL,
3261                    N_("show policy URLs during signature verification")},
3262                   {"show-notations",VERIFY_SHOW_NOTATIONS,NULL,
3263                    N_("show all notations during signature verification")},
3264                   {"show-std-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
3265                    N_("show IETF standard notations during signature verification")},
3266                   {"show-standard-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
3267                    NULL},
3268                   {"show-user-notations",VERIFY_SHOW_USER_NOTATIONS,NULL,
3269                    N_("show user-supplied notations during signature verification")},
3270                   {"show-keyserver-urls",VERIFY_SHOW_KEYSERVER_URLS,NULL,
3271                    N_("show preferred keyserver URLs during signature verification")},
3272                   {"show-uid-validity",VERIFY_SHOW_UID_VALIDITY,NULL,
3273                    N_("show user ID validity during signature verification")},
3274                   {"show-unusable-uids",VERIFY_SHOW_UNUSABLE_UIDS,NULL,
3275                    N_("show revoked and expired user IDs in signature verification")},
3276                   {"show-primary-uid-only",VERIFY_SHOW_PRIMARY_UID_ONLY,NULL,
3277                    N_("show only the primary user ID in signature verification")},
3278                   {"pka-lookups",VERIFY_PKA_LOOKUPS,NULL,
3279                    N_("validate signatures with PKA data")},
3280                   {"pka-trust-increase",VERIFY_PKA_TRUST_INCREASE,NULL,
3281                    N_("elevate the trust of signatures with valid PKA data")},
3282                   {NULL,0,NULL,NULL}
3283                 };
3284
3285               if(!parse_options(pargs.r.ret_str,&opt.verify_options,vopts,1))
3286                 {
3287                   if(configname)
3288                     log_error(_("%s:%d: invalid verify options\n"),
3289                               configname,configlineno);
3290                   else
3291                     log_error(_("invalid verify options\n"));
3292                 }
3293             }
3294             break;
3295           case oTempDir: opt.temp_dir=pargs.r.ret_str; break;
3296           case oExecPath:
3297             if(set_exec_path(pargs.r.ret_str))
3298               log_error(_("unable to set exec-path to %s\n"),pargs.r.ret_str);
3299             else
3300               opt.exec_path_set=1;
3301             break;
3302           case oSetNotation:
3303             add_notation_data( pargs.r.ret_str, 0 );
3304             add_notation_data( pargs.r.ret_str, 1 );
3305             break;
3306           case oSigNotation: add_notation_data( pargs.r.ret_str, 0 ); break;
3307           case oCertNotation: add_notation_data( pargs.r.ret_str, 1 ); break;
3308           case oKnownNotation: register_known_notation (pargs.r.ret_str); break;
3309           case oShowNotation:
3310             deprecated_warning(configname,configlineno,"--show-notation",
3311                                "--list-options ","show-notations");
3312             deprecated_warning(configname,configlineno,"--show-notation",
3313                                "--verify-options ","show-notations");
3314             opt.list_options|=LIST_SHOW_NOTATIONS;
3315             opt.verify_options|=VERIFY_SHOW_NOTATIONS;
3316             break;
3317           case oNoShowNotation:
3318             deprecated_warning(configname,configlineno,"--no-show-notation",
3319                                "--list-options ","no-show-notations");
3320             deprecated_warning(configname,configlineno,"--no-show-notation",
3321                                "--verify-options ","no-show-notations");
3322             opt.list_options&=~LIST_SHOW_NOTATIONS;
3323             opt.verify_options&=~VERIFY_SHOW_NOTATIONS;
3324             break;
3325           case oUtf8Strings: utf8_strings = 1; break;
3326           case oNoUtf8Strings: utf8_strings = 0; break;
3327           case oDisableCipherAlgo:
3328             {
3329               int algo = string_to_cipher_algo (pargs.r.ret_str);
3330               gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
3331             }
3332             break;
3333           case oDisablePubkeyAlgo:
3334             {
3335               int algo = gcry_pk_map_name (pargs.r.ret_str);
3336               gcry_pk_ctl (GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
3337             }
3338             break;
3339           case oNoSigCache: opt.no_sig_cache = 1; break;
3340           case oAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid = 1; break;
3341           case oNoAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid=0; break;
3342           case oAllowFreeformUID: opt.allow_freeform_uid = 1; break;
3343           case oNoAllowFreeformUID: opt.allow_freeform_uid = 0; break;
3344           case oNoLiteral: opt.no_literal = 1; break;
3345           case oSetFilesize: opt.set_filesize = pargs.r.ret_ulong; break;
3346           case oFastListMode: opt.fast_list_mode = 1; break;
3347           case oFixedListMode: /* Dummy */ break;
3348           case oLegacyListMode: opt.legacy_list_mode = 1; break;
3349           case oPrintPKARecords: print_pka_records = 1; break;
3350           case oPrintDANERecords: print_dane_records = 1; break;
3351           case oListOnly: opt.list_only=1; break;
3352           case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
3353           case oIgnoreValidFrom: opt.ignore_valid_from = 1; break;
3354           case oIgnoreCrcError: opt.ignore_crc_error = 1; break;
3355           case oIgnoreMDCError: opt.ignore_mdc_error = 1; break;
3356           case oNoRandomSeedFile: use_random_seed = 0; break;
3357
3358           case oAutoKeyRetrieve:
3359             opt.keyserver_options.options |= KEYSERVER_AUTO_KEY_RETRIEVE;
3360             break;
3361           case oNoAutoKeyRetrieve:
3362             opt.keyserver_options.options &= ~KEYSERVER_AUTO_KEY_RETRIEVE;
3363             break;
3364
3365           case oShowSessionKey: opt.show_session_key = 1; break;
3366           case oOverrideSessionKey:
3367                 opt.override_session_key = pargs.r.ret_str;
3368                 break;
3369           case oOverrideSessionKeyFD:
3370                 ovrseskeyfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
3371                 break;
3372           case oMergeOnly:
3373                 deprecated_warning(configname,configlineno,"--merge-only",
3374                                    "--import-options ","merge-only");
3375                 opt.import_options|=IMPORT_MERGE_ONLY;
3376             break;
3377           case oAllowSecretKeyImport: /* obsolete */ break;
3378           case oTryAllSecrets: opt.try_all_secrets = 1; break;
3379           case oTrustedKey: register_trusted_key( pargs.r.ret_str ); break;
3380
3381           case oEnableSpecialFilenames:
3382             enable_special_filenames ();
3383             break;
3384
3385           case oNoExpensiveTrustChecks: opt.no_expensive_trust_checks=1; break;
3386           case oAutoCheckTrustDB: opt.no_auto_check_trustdb=0; break;
3387           case oNoAutoCheckTrustDB: opt.no_auto_check_trustdb=1; break;
3388           case oPreservePermissions: opt.preserve_permissions=1; break;
3389           case oDefaultPreferenceList:
3390             opt.def_preference_list = pargs.r.ret_str;
3391             break;
3392           case oDefaultKeyserverURL:
3393             {
3394               keyserver_spec_t keyserver;
3395               keyserver = parse_keyserver_uri (pargs.r.ret_str,1 );
3396               if (!keyserver)
3397                 log_error (_("could not parse keyserver URL\n"));
3398               else
3399                 free_keyserver_spec (keyserver);
3400
3401               opt.def_keyserver_url = pargs.r.ret_str;
3402             }
3403             break;
3404           case oPersonalCipherPreferences:
3405             pers_cipher_list=pargs.r.ret_str;
3406             break;
3407           case oPersonalDigestPreferences:
3408             pers_digest_list=pargs.r.ret_str;
3409             break;
3410           case oPersonalCompressPreferences:
3411             pers_compress_list=pargs.r.ret_str;
3412             break;
3413           case oAgentProgram: opt.agent_program = pargs.r.ret_str;  break;
3414           case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break;
3415           case oDisableDirmngr: opt.disable_dirmngr = 1;  break;
3416           case oWeakDigest:
3417             additional_weak_digest(pargs.r.ret_str);
3418             break;
3419           case oUnwrap:
3420             opt.unwrap_encryption = 1;
3421             break;
3422           case oOnlySignTextIDs:
3423             opt.only_sign_text_ids = 1;
3424             break;
3425
3426           case oDisplay:
3427             set_opt_session_env ("DISPLAY", pargs.r.ret_str);
3428             break;
3429           case oTTYname:
3430             set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
3431             break;
3432           case oTTYtype:
3433             set_opt_session_env ("TERM", pargs.r.ret_str);
3434             break;
3435           case oXauthority:
3436             set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
3437             break;
3438
3439           case oLCctype: opt.lc_ctype = pargs.r.ret_str; break;
3440           case oLCmessages: opt.lc_messages = pargs.r.ret_str; break;
3441
3442           case oGroup: add_group(pargs.r.ret_str); break;
3443           case oUnGroup: rm_group(pargs.r.ret_str); break;
3444           case oNoGroups:
3445             while(opt.grouplist)
3446               {
3447                 struct groupitem *iter=opt.grouplist;
3448                 free_strlist(iter->values);
3449                 opt.grouplist=opt.grouplist->next;
3450                 xfree(iter);
3451               }
3452             break;
3453
3454           case oStrict:
3455           case oNoStrict:
3456             /* Not used */
3457             break;
3458
3459           case oMangleDosFilenames: opt.mangle_dos_filenames = 1; break;
3460           case oNoMangleDosFilenames: opt.mangle_dos_filenames = 0; break;
3461           case oEnableProgressFilter: opt.enable_progress_filter = 1; break;
3462           case oMultifile: multifile=1; break;
3463           case oKeyidFormat:
3464             if(ascii_strcasecmp(pargs.r.ret_str,"short")==0)
3465               opt.keyid_format=KF_SHORT;
3466             else if(ascii_strcasecmp(pargs.r.ret_str,"long")==0)
3467               opt.keyid_format=KF_LONG;
3468             else if(ascii_strcasecmp(pargs.r.ret_str,"0xshort")==0)
3469               opt.keyid_format=KF_0xSHORT;
3470             else if(ascii_strcasecmp(pargs.r.ret_str,"0xlong")==0)
3471               opt.keyid_format=KF_0xLONG;
3472             else if(ascii_strcasecmp(pargs.r.ret_str,"none")==0)
3473               opt.keyid_format = KF_NONE;
3474             else
3475               log_error("unknown keyid-format '%s'\n",pargs.r.ret_str);
3476             break;
3477
3478           case oExitOnStatusWriteError:
3479             opt.exit_on_status_write_error = 1;
3480             break;
3481
3482           case oLimitCardInsertTries:
3483             opt.limit_card_insert_tries = pargs.r.ret_int;
3484             break;
3485
3486           case oRequireCrossCert: opt.flags.require_cross_cert=1; break;
3487           case oNoRequireCrossCert: opt.flags.require_cross_cert=0; break;
3488
3489           case oAutoKeyLocate:
3490             if (default_akl)
3491               {
3492                 /* This is the first time --auto-key-locate is seen.
3493                  * We need to reset the default akl.  */
3494                 default_akl = 0;
3495                 release_akl();
3496               }
3497             if(!parse_auto_key_locate(pargs.r.ret_str))
3498               {
3499                 if(configname)
3500                   log_error(_("%s:%d: invalid auto-key-locate list\n"),
3501                             configname,configlineno);
3502                 else
3503                   log_error(_("invalid auto-key-locate list\n"));
3504               }
3505             break;
3506           case oNoAutoKeyLocate:
3507             release_akl();
3508             break;
3509
3510           case oKeyOrigin:
3511             if(!parse_key_origin (pargs.r.ret_str))
3512               log_error (_("invalid argument for option \"%.50s\"\n"),
3513                          "--key-origin");
3514             break;
3515
3516           case oEnableLargeRSA:
3517 #if SECMEM_BUFFER_SIZE >= 65536
3518             opt.flags.large_rsa=1;
3519 #else
3520             if (configname)
3521               log_info("%s:%d: WARNING: gpg not built with large secure "
3522                          "memory buffer.  Ignoring enable-large-rsa\n",
3523                         configname,configlineno);
3524             else
3525               log_info("WARNING: gpg not built with large secure "
3526                          "memory buffer.  Ignoring --enable-large-rsa\n");
3527 #endif /* SECMEM_BUFFER_SIZE >= 65536 */
3528             break;
3529           case oDisableLargeRSA: opt.flags.large_rsa=0;
3530             break;
3531
3532           case oEnableDSA2: opt.flags.dsa2=1; break;
3533           case oDisableDSA2: opt.flags.dsa2=0; break;
3534
3535           case oAllowMultisigVerification:
3536           case oAllowMultipleMessages:
3537             opt.flags.allow_multiple_messages=1;
3538             break;
3539
3540           case oNoAllowMultipleMessages:
3541             opt.flags.allow_multiple_messages=0;
3542             break;
3543
3544           case oAllowWeakDigestAlgos:
3545             opt.flags.allow_weak_digest_algos = 1;
3546             break;
3547
3548           case oFakedSystemTime:
3549             {
3550               size_t len = strlen (pargs.r.ret_str);
3551               int freeze = 0;
3552               time_t faked_time;
3553
3554               if (len > 0 && pargs.r.ret_str[len-1] == '!')
3555                 {
3556                   freeze = 1;
3557                   pargs.r.ret_str[len-1] = '\0';
3558                 }
3559
3560               faked_time = isotime2epoch (pargs.r.ret_str);
3561               if (faked_time == (time_t)(-1))
3562                 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
3563               gnupg_set_time (faked_time, freeze);
3564             }
3565             break;
3566
3567           case oNoAutostart: opt.autostart = 0; break;
3568           case oNoSymkeyCache: opt.no_symkey_cache = 1; break;
3569
3570           case oDefaultNewKeyAlgo:
3571             opt.def_new_key_algo = pargs.r.ret_str;
3572             break;
3573
3574           case oNoop: break;
3575
3576           default:
3577             if (configfp)
3578               pargs.err = ARGPARSE_PRINT_WARNING;
3579             else
3580               {
3581                 pargs.err = ARGPARSE_PRINT_ERROR;
3582                 /* The argparse fucntion calls a plain exit and thus
3583                  * we need to print a status here.  */
3584                 write_status_failure ("option-parser",
3585                                       gpg_error(GPG_ERR_GENERAL));
3586               }
3587             break;
3588           }
3589       }
3590
3591     if (configfp)
3592       {
3593         fclose( configfp );
3594         configfp = NULL;
3595         /* Remember the first config file name. */
3596         if (!save_configname)
3597           save_configname = configname;
3598         else
3599           xfree(configname);
3600         configname = NULL;
3601         goto next_pass;
3602       }
3603     xfree(configname); configname = NULL;
3604     if (log_get_errorcount (0))
3605       {
3606         write_status_failure ("option-parser", gpg_error(GPG_ERR_GENERAL));
3607         g10_exit(2);
3608       }
3609
3610     /* The command --gpgconf-list is pretty simple and may be called
3611        directly after the option parsing. */
3612     if (cmd == aGPGConfList)
3613       {
3614         gpgconf_list (save_configname ? save_configname : default_configname);
3615         g10_exit (0);
3616       }
3617     xfree (save_configname);
3618     xfree (default_configname);
3619
3620     if (print_dane_records)
3621       log_error ("invalid option \"%s\"; use \"%s\" instead\n",
3622                  "--print-dane-records",
3623                  "--export-options export-dane");
3624     if (print_pka_records)
3625       log_error ("invalid option \"%s\"; use \"%s\" instead\n",
3626                  "--print-pks-records",
3627                  "--export-options export-pka");
3628     if (log_get_errorcount (0))
3629       {
3630         write_status_failure ("option-checking", gpg_error(GPG_ERR_GENERAL));
3631         g10_exit(2);
3632       }
3633
3634
3635     if( nogreeting )
3636         greeting = 0;
3637
3638     if( greeting )
3639       {
3640         es_fprintf (es_stderr, "%s %s; %s\n",
3641                     strusage(11), strusage(13), strusage(14) );
3642         es_fprintf (es_stderr, "%s\n", strusage(15) );
3643       }
3644 #ifdef IS_DEVELOPMENT_VERSION
3645     if (!opt.batch)
3646       {
3647         const char *s;
3648
3649         if((s=strusage(25)))
3650           log_info("%s\n",s);
3651         if((s=strusage(26)))
3652           log_info("%s\n",s);
3653         if((s=strusage(27)))
3654           log_info("%s\n",s);
3655       }
3656 #endif
3657
3658     /* FIXME: We should use logging to a file only in server mode;
3659        however we have not yet implemetyed that.  Thus we try to get
3660        away with --batch as indication for logging to file
3661        required. */
3662     if (logfile && opt.batch)
3663       {
3664         log_set_file (logfile);
3665         log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
3666       }
3667
3668     if (opt.verbose > 2)
3669         log_info ("using character set '%s'\n", get_native_charset ());
3670
3671     if( may_coredump && !opt.quiet )
3672         log_info(_("WARNING: program may create a core file!\n"));
3673
3674     if (opt.flags.rfc4880bis)
3675         log_info ("WARNING: using experimental features from RFC4880bis!\n");
3676     else
3677       {
3678         opt.mimemode = 0; /* This will use text mode instead.  */
3679       }
3680
3681     if (eyes_only) {
3682       if (opt.set_filename)
3683           log_info(_("WARNING: %s overrides %s\n"),
3684                    "--for-your-eyes-only","--set-filename");
3685
3686       opt.set_filename="_CONSOLE";
3687     }
3688
3689     if (opt.no_literal) {
3690         log_info(_("Note: %s is not for normal use!\n"), "--no-literal");
3691         if (opt.textmode)
3692             log_error(_("%s not allowed with %s!\n"),
3693                        "--textmode", "--no-literal" );
3694         if (opt.set_filename)
3695             log_error(_("%s makes no sense with %s!\n"),
3696                         eyes_only?"--for-your-eyes-only":"--set-filename",
3697                         "--no-literal" );
3698     }
3699
3700
3701     if (opt.set_filesize)
3702         log_info(_("Note: %s is not for normal use!\n"), "--set-filesize");
3703     if( opt.batch )
3704         tty_batchmode( 1 );
3705
3706     if (gnupg_faked_time_p ())
3707       {
3708         gnupg_isotime_t tbuf;
3709
3710         log_info (_("WARNING: running with faked system time: "));
3711         gnupg_get_isotime (tbuf);
3712         dump_isotime (tbuf);
3713         log_printf ("\n");
3714       }
3715
3716     /* Print a warning if an argument looks like an option.  */
3717     if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
3718       {
3719         int i;
3720
3721         for (i=0; i < argc; i++)
3722           if (argv[i][0] == '-' && argv[i][1] == '-')
3723             log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
3724       }
3725
3726
3727     gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
3728
3729     if(require_secmem && !got_secmem)
3730       {
3731         log_info(_("will not run with insecure memory due to %s\n"),
3732                  "--require-secmem");
3733         write_status_failure ("option-checking", gpg_error(GPG_ERR_GENERAL));
3734         g10_exit(2);
3735       }
3736
3737     set_debug (debug_level);
3738     if (DBG_CLOCK)
3739       log_clock ("start");
3740
3741     /* Do these after the switch(), so they can override settings. */
3742     if(PGP6)
3743       {
3744         /* That does not anymore work because we have no more support
3745            for v3 signatures.  */
3746         opt.escape_from=1;
3747         opt.ask_sig_expire=0;
3748       }
3749     else if(PGP7)
3750       {
3751         /* That does not anymore work because we have no more support
3752            for v3 signatures.  */
3753         opt.escape_from=1;
3754         opt.ask_sig_expire=0;
3755       }
3756     else if(PGP8)
3757       {
3758         opt.escape_from=1;
3759       }
3760
3761
3762     if( def_cipher_string ) {
3763         opt.def_cipher_algo = string_to_cipher_algo (def_cipher_string);
3764         xfree(def_cipher_string); def_cipher_string = NULL;
3765         if ( openpgp_cipher_test_algo (opt.def_cipher_algo) )
3766             log_error(_("selected cipher algorithm is invalid\n"));
3767     }
3768     if( def_digest_string ) {
3769         opt.def_digest_algo = string_to_digest_algo (def_digest_string);
3770         xfree(def_digest_string); def_digest_string = NULL;
3771         if ( openpgp_md_test_algo (opt.def_digest_algo) )
3772             log_error(_("selected digest algorithm is invalid\n"));
3773     }
3774     if( compress_algo_string ) {
3775         opt.compress_algo = string_to_compress_algo(compress_algo_string);
3776         xfree(compress_algo_string); compress_algo_string = NULL;
3777         if( check_compress_algo(opt.compress_algo) )
3778           log_error(_("selected compression algorithm is invalid\n"));
3779     }
3780     if( cert_digest_string ) {
3781         opt.cert_digest_algo = string_to_digest_algo (cert_digest_string);
3782         xfree(cert_digest_string); cert_digest_string = NULL;
3783         if (openpgp_md_test_algo(opt.cert_digest_algo))
3784           log_error(_("selected certification digest algorithm is invalid\n"));
3785     }
3786     if( s2k_cipher_string ) {
3787         opt.s2k_cipher_algo = string_to_cipher_algo (s2k_cipher_string);
3788         xfree(s2k_cipher_string); s2k_cipher_string = NULL;
3789         if (openpgp_cipher_test_algo (opt.s2k_cipher_algo))
3790           log_error(_("selected cipher algorithm is invalid\n"));
3791     }
3792     if( s2k_digest_string ) {
3793         opt.s2k_digest_algo = string_to_digest_algo (s2k_digest_string);
3794         xfree(s2k_digest_string); s2k_digest_string = NULL;
3795         if (openpgp_md_test_algo(opt.s2k_digest_algo))
3796           log_error(_("selected digest algorithm is invalid\n"));
3797     }
3798     if( opt.completes_needed < 1 )
3799       log_error(_("completes-needed must be greater than 0\n"));
3800     if( opt.marginals_needed < 2 )
3801       log_error(_("marginals-needed must be greater than 1\n"));
3802     if( opt.max_cert_depth < 1 || opt.max_cert_depth > 255 )
3803       log_error(_("max-cert-depth must be in the range from 1 to 255\n"));
3804     if(opt.def_cert_level<0 || opt.def_cert_level>3)
3805       log_error(_("invalid default-cert-level; must be 0, 1, 2, or 3\n"));
3806     if( opt.min_cert_level < 1 || opt.min_cert_level > 3 )
3807       log_error(_("invalid min-cert-level; must be 1, 2, or 3\n"));
3808     switch( opt.s2k_mode ) {
3809       case 0:
3810         log_info(_("Note: simple S2K mode (0) is strongly discouraged\n"));
3811         break;
3812       case 1: case 3: break;
3813       default:
3814         log_error(_("invalid S2K mode; must be 0, 1 or 3\n"));
3815     }
3816
3817     /* This isn't actually needed, but does serve to error out if the
3818        string is invalid. */
3819     if(opt.def_preference_list &&
3820         keygen_set_std_prefs(opt.def_preference_list,0))
3821       log_error(_("invalid default preferences\n"));
3822
3823     if(pers_cipher_list &&
3824        keygen_set_std_prefs(pers_cipher_list,PREFTYPE_SYM))
3825       log_error(_("invalid personal cipher preferences\n"));
3826
3827     if(pers_digest_list &&
3828        keygen_set_std_prefs(pers_digest_list,PREFTYPE_HASH))
3829       log_error(_("invalid personal digest preferences\n"));
3830
3831     if(pers_compress_list &&
3832        keygen_set_std_prefs(pers_compress_list,PREFTYPE_ZIP))
3833       log_error(_("invalid personal compress preferences\n"));
3834
3835     /* We don't support all possible commands with multifile yet */
3836     if(multifile)
3837       {
3838         char *cmdname;
3839
3840         switch(cmd)
3841           {
3842           case aSign:
3843             cmdname="--sign";
3844             break;
3845           case aSignEncr:
3846             cmdname="--sign --encrypt";
3847             break;
3848           case aClearsign:
3849             cmdname="--clear-sign";
3850             break;
3851           case aDetachedSign:
3852             cmdname="--detach-sign";
3853             break;
3854           case aSym:
3855             cmdname="--symmetric";
3856             break;
3857           case aEncrSym:
3858             cmdname="--symmetric --encrypt";
3859             break;
3860           case aStore:
3861             cmdname="--store";
3862             break;
3863           default:
3864             cmdname=NULL;
3865             break;
3866           }
3867
3868         if(cmdname)
3869           log_error(_("%s does not yet work with %s\n"),cmdname,"--multifile");
3870       }
3871
3872     if( log_get_errorcount(0) )
3873       {
3874         write_status_failure ("option-postprocessing",
3875                               gpg_error(GPG_ERR_GENERAL));
3876         g10_exit (2);
3877       }
3878
3879     if(opt.compress_level==0)
3880       opt.compress_algo=COMPRESS_ALGO_NONE;
3881
3882     /* Check our chosen algorithms against the list of legal
3883        algorithms. */
3884
3885     if(!GNUPG)
3886       {
3887         const char *badalg=NULL;
3888         preftype_t badtype=PREFTYPE_NONE;
3889
3890         if(opt.def_cipher_algo
3891            && !algo_available(PREFTYPE_SYM,opt.def_cipher_algo,NULL))
3892           {
3893             badalg = openpgp_cipher_algo_name (opt.def_cipher_algo);
3894             badtype = PREFTYPE_SYM;
3895           }
3896         else if(opt.def_digest_algo
3897                 && !algo_available(PREFTYPE_HASH,opt.def_digest_algo,NULL))
3898           {
3899             badalg = gcry_md_algo_name (opt.def_digest_algo);
3900             badtype = PREFTYPE_HASH;
3901           }
3902         else if(opt.cert_digest_algo
3903                 && !algo_available(PREFTYPE_HASH,opt.cert_digest_algo,NULL))
3904           {
3905             badalg = gcry_md_algo_name (opt.cert_digest_algo);
3906             badtype = PREFTYPE_HASH;
3907           }
3908         else if(opt.compress_algo!=-1
3909                 && !algo_available(PREFTYPE_ZIP,opt.compress_algo,NULL))
3910           {
3911             badalg = compress_algo_to_string(opt.compress_algo);
3912             badtype = PREFTYPE_ZIP;
3913           }
3914
3915         if(badalg)
3916           {
3917             switch(badtype)
3918               {
3919               case PREFTYPE_SYM:
3920                 log_info (_("cipher algorithm '%s'"
3921                             " may not be used in %s mode\n"),
3922                          badalg,
3923                           gnupg_compliance_option_string (opt.compliance));
3924                 break;
3925               case PREFTYPE_HASH:
3926                 log_info (_("digest algorithm '%s'"
3927                             " may not be used in %s mode\n"),
3928                           badalg,
3929                           gnupg_compliance_option_string (opt.compliance));
3930                 break;
3931               case PREFTYPE_ZIP:
3932                 log_info (_("compression algorithm '%s'"
3933                             " may not be used in %s mode\n"),
3934                           badalg,
3935                           gnupg_compliance_option_string (opt.compliance));
3936                 break;
3937               default:
3938                 BUG();
3939               }
3940
3941             compliance_failure();
3942           }
3943       }
3944
3945     /* Check our chosen algorithms against the list of allowed
3946      * algorithms in the current compliance mode, and fail hard if it
3947      * is not.  This is us being nice to the user informing her early
3948      * that the chosen algorithms are not available.  We also check
3949      * and enforce this right before the actual operation.  */
3950     if (opt.def_cipher_algo
3951         && ! gnupg_cipher_is_allowed (opt.compliance,
3952                                       cmd == aEncr
3953                                       || cmd == aSignEncr
3954                                       || cmd == aEncrSym
3955                                       || cmd == aSym
3956                                       || cmd == aSignSym
3957                                       || cmd == aSignEncrSym,
3958                                       opt.def_cipher_algo,
3959                                       GCRY_CIPHER_MODE_NONE))
3960       log_error (_("cipher algorithm '%s' may not be used in %s mode\n"),
3961                  openpgp_cipher_algo_name (opt.def_cipher_algo),
3962                  gnupg_compliance_option_string (opt.compliance));
3963
3964     if (opt.def_digest_algo
3965         && ! gnupg_digest_is_allowed (opt.compliance,
3966                                       cmd == aSign
3967                                       || cmd == aSignEncr
3968                                       || cmd == aSignEncrSym
3969                                       || cmd == aSignSym
3970                                       || cmd == aClearsign,
3971                                       opt.def_digest_algo))
3972       log_error (_("digest algorithm '%s' may not be used in %s mode\n"),
3973                  gcry_md_algo_name (opt.def_digest_algo),
3974                  gnupg_compliance_option_string (opt.compliance));
3975
3976     /* Fail hard.  */
3977     if (log_get_errorcount (0))
3978       {
3979         write_status_failure ("option-checking", gpg_error(GPG_ERR_GENERAL));
3980         g10_exit (2);
3981       }
3982
3983     /* Set the random seed file. */
3984     if( use_random_seed ) {
3985       char *p = make_filename (gnupg_homedir (), "random_seed", NULL );
3986         gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
3987         if (!access (p, F_OK))
3988           register_secured_file (p);
3989         xfree(p);
3990     }
3991
3992     /* If there is no command but the --fingerprint is given, default
3993        to the --list-keys command.  */
3994     if (!cmd && fpr_maybe_cmd)
3995       {
3996         set_cmd (&cmd, aListKeys);
3997       }
3998
3999
4000     if( opt.verbose > 1 )
4001         set_packet_list_mode(1);
4002
4003     /* Add the keyrings, but not for some special commands.  We always
4004      * need to add the keyrings if we are running under SELinux, this
4005      * is so that the rings are added to the list of secured files.
4006      * We do not add any keyring if --no-keyring has been used.  */
4007     if (default_keyring >= 0
4008         && (ALWAYS_ADD_KEYRINGS
4009             || (cmd != aDeArmor && cmd != aEnArmor && cmd != aGPGConfTest)))
4010       {
4011         if (!nrings || default_keyring > 0)  /* Add default ring. */
4012             keydb_add_resource ("pubring" EXTSEP_S GPGEXT_GPG,
4013                                 KEYDB_RESOURCE_FLAG_DEFAULT);
4014         for (sl = nrings; sl; sl = sl->next )
4015           keydb_add_resource (sl->d, sl->flags);
4016       }
4017     FREE_STRLIST(nrings);
4018
4019     if (opt.pinentry_mode == PINENTRY_MODE_LOOPBACK)
4020       /* In loopback mode, never ask for the password multiple
4021          times.  */
4022       {
4023         opt.passphrase_repeat = 0;
4024       }
4025
4026     if (cmd == aGPGConfTest)
4027       g10_exit(0);
4028
4029
4030     if (pwfd != -1)  /* Read the passphrase now. */
4031       read_passphrase_from_fd (pwfd);
4032
4033     if (ovrseskeyfd != -1 )  /* Read the sessionkey now. */
4034       read_sessionkey_from_fd (ovrseskeyfd);
4035
4036     fname = argc? *argv : NULL;
4037
4038     if(fname && utf8_strings)
4039       opt.flags.utf8_filename=1;
4040
4041     ctrl = xcalloc (1, sizeof *ctrl);
4042     gpg_init_default_ctrl (ctrl);
4043
4044 #ifndef NO_TRUST_MODELS
4045     switch (cmd)
4046       {
4047       case aPrimegen:
4048       case aPrintMD:
4049       case aPrintMDs:
4050       case aGenRandom:
4051       case aDeArmor:
4052       case aEnArmor:
4053       case aListConfig:
4054       case aListGcryptConfig:
4055         break;
4056       case aFixTrustDB:
4057       case aExportOwnerTrust:
4058         rc = setup_trustdb (0, trustdb_name);
4059         break;
4060       case aListTrustDB:
4061         rc = setup_trustdb (argc? 1:0, trustdb_name);
4062         break;
4063       case aKeygen:
4064       case aFullKeygen:
4065       case aQuickKeygen:
4066         rc = setup_trustdb (1, trustdb_name);
4067         break;
4068       default:
4069         /* If we are using TM_ALWAYS, we do not need to create the
4070            trustdb.  */
4071         rc = setup_trustdb (opt.trust_model != TM_ALWAYS, trustdb_name);
4072         break;
4073       }
4074     if (rc)
4075       log_error (_("failed to initialize the TrustDB: %s\n"),
4076                  gpg_strerror (rc));
4077 #endif /*!NO_TRUST_MODELS*/
4078
4079     switch (cmd)
4080       {
4081       case aStore:
4082       case aSym:
4083       case aSign:
4084       case aSignSym:
4085       case aClearsign:
4086         if (!opt.quiet && any_explicit_recipient)
4087           log_info (_("WARNING: recipients (-r) given "
4088                       "without using public key encryption\n"));
4089         break;
4090       default:
4091         break;
4092       }
4093
4094
4095     /* Check for certain command whether we need to migrate a
4096        secring.gpg to the gpg-agent. */
4097     switch (cmd)
4098       {
4099       case aListSecretKeys:
4100       case aSign:
4101       case aSignEncr:
4102       case aSignEncrSym:
4103       case aSignSym:
4104       case aClearsign:
4105       case aDecrypt:
4106       case aSignKey:
4107       case aLSignKey:
4108       case aEditKey:
4109       case aPasswd:
4110       case aDeleteSecretKeys:
4111       case aDeleteSecretAndPublicKeys:
4112       case aQuickKeygen:
4113       case aQuickAddUid:
4114       case aQuickAddKey:
4115       case aQuickRevUid:
4116       case aQuickSetPrimaryUid:
4117       case aFullKeygen:
4118       case aKeygen:
4119       case aImport:
4120       case aExportSecret:
4121       case aExportSecretSub:
4122       case aGenRevoke:
4123       case aDesigRevoke:
4124       case aCardEdit:
4125       case aChangePIN:
4126         migrate_secring (ctrl);
4127         break;
4128       case aListKeys:
4129         if (opt.with_secret)
4130           migrate_secring (ctrl);
4131         break;
4132       default:
4133         break;
4134       }
4135
4136     /* The command dispatcher.  */
4137     switch( cmd )
4138       {
4139       case aServer:
4140         gpg_server (ctrl);
4141         break;
4142
4143       case aStore: /* only store the file */
4144         if( argc > 1 )
4145             wrong_args("--store [filename]");
4146         if( (rc = encrypt_store(fname)) )
4147           {
4148             write_status_failure ("store", rc);
4149             log_error ("storing '%s' failed: %s\n",
4150                        print_fname_stdin(fname),gpg_strerror (rc) );
4151           }
4152         break;
4153       case aSym: /* encrypt the given file only with the symmetric cipher */
4154         if( argc > 1 )
4155             wrong_args("--symmetric [filename]");
4156         if( (rc = encrypt_symmetric(fname)) )
4157           {
4158             write_status_failure ("symencrypt", rc);
4159             log_error (_("symmetric encryption of '%s' failed: %s\n"),
4160                         print_fname_stdin(fname),gpg_strerror (rc) );
4161           }
4162         break;
4163
4164       case aEncr: /* encrypt the given file */
4165         if(multifile)
4166           encrypt_crypt_files (ctrl, argc, argv, remusr);
4167         else
4168           {
4169             if( argc > 1 )
4170               wrong_args("--encrypt [filename]");
4171             if( (rc = encrypt_crypt (ctrl, -1, fname, remusr, 0, NULL, -1)) )
4172               {
4173                 write_status_failure ("encrypt", rc);
4174                 log_error("%s: encryption failed: %s\n",
4175                           print_fname_stdin(fname), gpg_strerror (rc) );
4176               }
4177           }
4178         break;
4179
4180       case aEncrSym:
4181         /* This works with PGP 8 in the sense that it acts just like a
4182            symmetric message.  It doesn't work at all with 2 or 6.  It
4183            might work with 7, but alas, I don't have a copy to test
4184            with right now. */
4185         if( argc > 1 )
4186           wrong_args("--symmetric --encrypt [filename]");
4187         else if(opt.s2k_mode==0)
4188           log_error(_("you cannot use --symmetric --encrypt"
4189                       " with --s2k-mode 0\n"));
4190         else if(PGP6 || PGP7)
4191           log_error(_("you cannot use --symmetric --encrypt"
4192                       " in %s mode\n"),
4193                     gnupg_compliance_option_string (opt.compliance));
4194         else
4195           {
4196             if( (rc = encrypt_crypt (ctrl, -1, fname, remusr, 1, NULL, -1)) )
4197               {
4198                 write_status_failure ("encrypt", rc);
4199                 log_error ("%s: encryption failed: %s\n",
4200                            print_fname_stdin(fname), gpg_strerror (rc) );
4201               }
4202           }
4203         break;
4204
4205       case aSign: /* sign the given file */
4206         sl = NULL;
4207         if( detached_sig ) { /* sign all files */
4208             for( ; argc; argc--, argv++ )
4209                 add_to_strlist( &sl, *argv );
4210         }
4211         else {
4212             if( argc > 1 )
4213                 wrong_args("--sign [filename]");
4214             if( argc ) {
4215                 sl = xmalloc_clear( sizeof *sl + strlen(fname));
4216                 strcpy(sl->d, fname);
4217             }
4218         }
4219         if ((rc = sign_file (ctrl, sl, detached_sig, locusr, 0, NULL, NULL)))
4220           {
4221             write_status_failure ("sign", rc);
4222             log_error ("signing failed: %s\n", gpg_strerror (rc) );
4223           }
4224         free_strlist(sl);
4225         break;
4226
4227       case aSignEncr: /* sign and encrypt the given file */
4228         if( argc > 1 )
4229             wrong_args("--sign --encrypt [filename]");
4230         if( argc ) {
4231             sl = xmalloc_clear( sizeof *sl + strlen(fname));
4232             strcpy(sl->d, fname);
4233         }
4234         else
4235             sl = NULL;
4236         if ((rc = sign_file (ctrl, sl, detached_sig, locusr, 1, remusr, NULL)))
4237           {
4238             write_status_failure ("sign-encrypt", rc);
4239             log_error("%s: sign+encrypt failed: %s\n",
4240                       print_fname_stdin(fname), gpg_strerror (rc) );
4241           }
4242         free_strlist(sl);
4243         break;
4244
4245       case aSignEncrSym: /* sign and encrypt the given file */
4246         if( argc > 1 )
4247             wrong_args("--symmetric --sign --encrypt [filename]");
4248         else if(opt.s2k_mode==0)
4249           log_error(_("you cannot use --symmetric --sign --encrypt"
4250                       " with --s2k-mode 0\n"));
4251         else if(PGP6 || PGP7)
4252           log_error(_("you cannot use --symmetric --sign --encrypt"
4253                       " in %s mode\n"),
4254                     gnupg_compliance_option_string (opt.compliance));
4255         else
4256           {
4257             if( argc )
4258               {
4259                 sl = xmalloc_clear( sizeof *sl + strlen(fname));
4260                 strcpy(sl->d, fname);
4261               }
4262             else
4263               sl = NULL;
4264             if ((rc = sign_file (ctrl, sl, detached_sig, locusr,
4265                                  2, remusr, NULL)))
4266               {
4267                 write_status_failure ("sign-encrypt", rc);
4268                 log_error("%s: symmetric+sign+encrypt failed: %s\n",
4269                           print_fname_stdin(fname), gpg_strerror (rc) );
4270               }
4271             free_strlist(sl);
4272           }
4273         break;
4274
4275       case aSignSym: /* sign and conventionally encrypt the given file */
4276         if (argc > 1)
4277             wrong_args("--sign --symmetric [filename]");
4278         rc = sign_symencrypt_file (ctrl, fname, locusr);
4279         if (rc)
4280           {
4281             write_status_failure ("sign-symencrypt", rc);
4282             log_error("%s: sign+symmetric failed: %s\n",
4283                       print_fname_stdin(fname), gpg_strerror (rc) );
4284           }
4285         break;
4286
4287       case aClearsign: /* make a clearsig */
4288         if( argc > 1 )
4289             wrong_args("--clear-sign [filename]");
4290         if( (rc = clearsign_file (ctrl, fname, locusr, NULL)) )
4291           {
4292             write_status_failure ("sign", rc);
4293             log_error("%s: clear-sign failed: %s\n",
4294                       print_fname_stdin(fname), gpg_strerror (rc) );
4295           }
4296         break;
4297
4298       case aVerify:
4299         if (multifile)
4300           {
4301             if ((rc = verify_files (ctrl, argc, argv)))
4302               log_error("verify files failed: %s\n", gpg_strerror (rc) );
4303           }
4304         else
4305           {
4306             if ((rc = verify_signatures (ctrl, argc, argv)))
4307               log_error("verify signatures failed: %s\n", gpg_strerror (rc) );
4308           }
4309         if (rc)
4310           write_status_failure ("verify", rc);
4311         break;
4312
4313       case aDecrypt:
4314         if (multifile)
4315           decrypt_messages (ctrl, argc, argv);
4316         else
4317           {
4318             if( argc > 1 )
4319               wrong_args("--decrypt [filename]");
4320             if( (rc = decrypt_message (ctrl, fname) ))
4321               {
4322                 write_status_failure ("decrypt", rc);
4323                 log_error("decrypt_message failed: %s\n", gpg_strerror (rc) );
4324               }
4325           }
4326         break;
4327
4328       case aQuickSignKey:
4329       case aQuickLSignKey:
4330         {
4331           const char *fpr;
4332
4333           if (argc < 1)
4334             wrong_args ("--quick-[l]sign-key fingerprint [userids]");
4335           fpr = *argv++; argc--;
4336           sl = NULL;
4337           for( ; argc; argc--, argv++)
4338             append_to_strlist2 (&sl, *argv, utf8_strings);
4339           keyedit_quick_sign (ctrl, fpr, sl, locusr, (cmd == aQuickLSignKey));
4340           free_strlist (sl);
4341         }
4342         break;
4343
4344       case aSignKey:
4345         if( argc != 1 )
4346           wrong_args("--sign-key user-id");
4347         /* fall through */
4348       case aLSignKey:
4349         if( argc != 1 )
4350           wrong_args("--lsign-key user-id");
4351         /* fall through */
4352
4353         sl=NULL;
4354
4355         if(cmd==aSignKey)
4356           append_to_strlist(&sl,"sign");
4357         else if(cmd==aLSignKey)
4358           append_to_strlist(&sl,"lsign");
4359         else
4360           BUG();
4361
4362         append_to_strlist( &sl, "save" );
4363         username = make_username( fname );
4364         keyedit_menu (ctrl, username, locusr, sl, 0, 0 );
4365         xfree(username);
4366         free_strlist(sl);
4367         break;
4368
4369       case aEditKey: /* Edit a key signature */
4370         if( !argc )
4371             wrong_args("--edit-key user-id [commands]");
4372         username = make_username( fname );
4373         if( argc > 1 ) {
4374             sl = NULL;
4375             for( argc--, argv++ ; argc; argc--, argv++ )
4376                 append_to_strlist( &sl, *argv );
4377             keyedit_menu (ctrl, username, locusr, sl, 0, 1 );
4378             free_strlist(sl);
4379         }
4380         else
4381             keyedit_menu (ctrl, username, locusr, NULL, 0, 1 );
4382         xfree(username);
4383         break;
4384
4385       case aPasswd:
4386         if (argc != 1)
4387           wrong_args("--change-passphrase <user-id>");
4388         else
4389           {
4390             username = make_username (fname);
4391             keyedit_passwd (ctrl, username);
4392             xfree (username);
4393           }
4394         break;
4395
4396       case aDeleteKeys:
4397       case aDeleteSecretKeys:
4398       case aDeleteSecretAndPublicKeys:
4399         sl = NULL;
4400         /* I'm adding these in reverse order as add_to_strlist2
4401            reverses them again, and it's easier to understand in the
4402            proper order :) */
4403         for( ; argc; argc-- )
4404           add_to_strlist2( &sl, argv[argc-1], utf8_strings );
4405         delete_keys (ctrl, sl,
4406                      cmd==aDeleteSecretKeys, cmd==aDeleteSecretAndPublicKeys);
4407         free_strlist(sl);
4408         break;
4409
4410       case aCheckKeys:
4411         opt.check_sigs = 1; /* fall through */
4412       case aListSigs:
4413         opt.list_sigs = 1; /* fall through */
4414       case aListKeys:
4415         sl = NULL;
4416         for( ; argc; argc--, argv++ )
4417             add_to_strlist2( &sl, *argv, utf8_strings );
4418         public_key_list (ctrl, sl, 0);
4419         free_strlist(sl);
4420         break;
4421       case aListSecretKeys:
4422         sl = NULL;
4423         for( ; argc; argc--, argv++ )
4424             add_to_strlist2( &sl, *argv, utf8_strings );
4425         secret_key_list (ctrl, sl);
4426         free_strlist(sl);
4427         break;
4428       case aLocateKeys:
4429         sl = NULL;
4430         for (; argc; argc--, argv++)
4431           add_to_strlist2( &sl, *argv, utf8_strings );
4432         public_key_list (ctrl, sl, 1);
4433         free_strlist (sl);
4434         break;
4435
4436       case aQuickKeygen:
4437         {
4438           const char *x_algo, *x_usage, *x_expire;
4439
4440           if (argc < 1 || argc > 4)
4441             wrong_args("--quick-generate-key USER-ID [ALGO [USAGE [EXPIRE]]]");
4442           username = make_username (fname);
4443           argv++, argc--;
4444           x_algo = "";
4445           x_usage = "";
4446           x_expire = "";
4447           if (argc)
4448             {
4449               x_algo = *argv++; argc--;
4450               if (argc)
4451                 {
4452                   x_usage = *argv++; argc--;
4453                   if (argc)
4454                     {
4455                       x_expire = *argv++; argc--;
4456                     }
4457                 }
4458             }
4459           quick_generate_keypair (ctrl, username, x_algo, x_usage, x_expire);
4460           xfree (username);
4461         }
4462         break;
4463
4464       case aKeygen: /* generate a key */
4465         if( opt.batch ) {
4466             if( argc > 1 )
4467                 wrong_args("--generate-key [parameterfile]");
4468             generate_keypair (ctrl, 0, argc? *argv : NULL, NULL, 0);
4469         }
4470         else {
4471             if (opt.command_fd != -1 && argc)
4472               {
4473                 if( argc > 1 )
4474                   wrong_args("--generate-key [parameterfile]");
4475
4476                 opt.batch = 1;
4477                 generate_keypair (ctrl, 0, argc? *argv : NULL, NULL, 0);
4478               }
4479             else if (argc)
4480               wrong_args ("--generate-key");
4481             else
4482               generate_keypair (ctrl, 0, NULL, NULL, 0);
4483         }
4484         break;
4485
4486       case aFullKeygen: /* Generate a key with all options. */
4487         if (opt.batch)
4488           {
4489             if (argc > 1)
4490               wrong_args ("--full-generate-key [parameterfile]");
4491             generate_keypair (ctrl, 1, argc? *argv : NULL, NULL, 0);
4492           }
4493         else
4494           {
4495             if (argc)
4496               wrong_args("--full-generate-key");
4497             generate_keypair (ctrl, 1, NULL, NULL, 0);
4498         }
4499         break;
4500
4501       case aQuickAddUid:
4502         {
4503           const char *uid, *newuid;
4504
4505           if (argc != 2)
4506             wrong_args ("--quick-add-uid USER-ID NEW-USER-ID");
4507           uid = *argv++; argc--;
4508           newuid = *argv++; argc--;
4509           keyedit_quick_adduid (ctrl, uid, newuid);
4510         }
4511         break;
4512
4513       case aQuickAddKey:
4514         {
4515           const char *x_fpr, *x_algo, *x_usage, *x_expire;
4516
4517           if (argc < 1 || argc > 4)
4518             wrong_args ("--quick-add-key FINGERPRINT [ALGO [USAGE [EXPIRE]]]");
4519           x_fpr = *argv++; argc--;
4520           x_algo = "";
4521           x_usage = "";
4522           x_expire = "";
4523           if (argc)
4524             {
4525               x_algo = *argv++; argc--;
4526               if (argc)
4527                 {
4528                   x_usage = *argv++; argc--;
4529                   if (argc)
4530                    {
4531                      x_expire = *argv++; argc--;
4532                    }
4533                 }
4534             }
4535           keyedit_quick_addkey (ctrl, x_fpr, x_algo, x_usage, x_expire);
4536         }
4537         break;
4538
4539       case aQuickRevUid:
4540         {
4541           const char *uid, *uidtorev;
4542
4543           if (argc != 2)
4544             wrong_args ("--quick-revoke-uid USER-ID USER-ID-TO-REVOKE");
4545           uid = *argv++; argc--;
4546           uidtorev = *argv++; argc--;
4547           keyedit_quick_revuid (ctrl, uid, uidtorev);
4548         }
4549         break;
4550
4551       case aQuickSetExpire:
4552         {
4553           const char *x_fpr, *x_expire;
4554
4555           if (argc < 2)
4556             wrong_args ("--quick-set-exipre FINGERPRINT EXPIRE [SUBKEY-FPRS]");
4557           x_fpr = *argv++; argc--;
4558           x_expire = *argv++; argc--;
4559           keyedit_quick_set_expire (ctrl, x_fpr, x_expire, argv);
4560         }
4561         break;
4562
4563       case aQuickSetPrimaryUid:
4564         {
4565           const char *uid, *primaryuid;
4566
4567           if (argc != 2)
4568             wrong_args ("--quick-set-primary-uid USER-ID PRIMARY-USER-ID");
4569           uid = *argv++; argc--;
4570           primaryuid = *argv++; argc--;
4571           keyedit_quick_set_primary (ctrl, uid, primaryuid);
4572         }
4573         break;
4574
4575       case aFastImport:
4576         opt.import_options |= IMPORT_FAST; /* fall through */
4577       case aImport:
4578       case aShowKeys:
4579         import_keys (ctrl, argc? argv:NULL, argc, NULL,
4580                      opt.import_options, opt.key_origin, opt.key_origin_url);
4581         break;
4582
4583         /* TODO: There are a number of command that use this same
4584            "make strlist, call function, report error, free strlist"
4585            pattern.  Join them together here and avoid all that
4586            duplicated code. */
4587
4588       case aExport:
4589       case aSendKeys:
4590       case aRecvKeys:
4591         sl = NULL;
4592         for( ; argc; argc--, argv++ )
4593             append_to_strlist2( &sl, *argv, utf8_strings );
4594         if( cmd == aSendKeys )
4595             rc = keyserver_export (ctrl, sl );
4596         else if( cmd == aRecvKeys )
4597             rc = keyserver_import (ctrl, sl );
4598         else
4599           {
4600             export_stats_t stats = export_new_stats ();
4601             rc = export_pubkeys (ctrl, sl, opt.export_options, stats);
4602             export_print_stats (stats);
4603             export_release_stats (stats);
4604           }
4605         if(rc)
4606           {
4607             if(cmd==aSendKeys)
4608               {
4609                 write_status_failure ("send-keys", rc);
4610                 log_error(_("keyserver send failed: %s\n"),gpg_strerror (rc));
4611               }
4612             else if(cmd==aRecvKeys)
4613               {
4614                 write_status_failure ("recv-keys", rc);
4615                 log_error (_("keyserver receive failed: %s\n"),
4616                            gpg_strerror (rc));
4617               }
4618             else
4619               {
4620                 write_status_failure ("export", rc);
4621                 log_error (_("key export failed: %s\n"), gpg_strerror (rc));
4622               }
4623           }
4624         free_strlist(sl);
4625         break;
4626
4627       case aExportSshKey:
4628         if (argc != 1)
4629           wrong_args ("--export-ssh-key <user-id>");
4630         rc = export_ssh_key (ctrl, argv[0]);
4631         if (rc)
4632           {
4633             write_status_failure ("export-ssh-key", rc);
4634             log_error (_("export as ssh key failed: %s\n"), gpg_strerror (rc));
4635           }
4636         break;
4637
4638      case aSearchKeys:
4639         sl = NULL;
4640         for (; argc; argc--, argv++)
4641           append_to_strlist2 (&sl, *argv, utf8_strings);
4642         rc = keyserver_search (ctrl, sl);
4643         if (rc)
4644           {
4645             write_status_failure ("search-keys", rc);
4646             log_error (_("keyserver search failed: %s\n"), gpg_strerror (rc));
4647           }
4648         free_strlist (sl);
4649         break;
4650
4651       case aRefreshKeys:
4652         sl = NULL;
4653         for( ; argc; argc--, argv++ )
4654             append_to_strlist2( &sl, *argv, utf8_strings );
4655         rc = keyserver_refresh (ctrl, sl);
4656         if(rc)
4657           {
4658             write_status_failure ("refresh-keys", rc);
4659             log_error (_("keyserver refresh failed: %s\n"),gpg_strerror (rc));
4660           }
4661         free_strlist(sl);
4662         break;
4663
4664       case aFetchKeys:
4665         sl = NULL;
4666         for( ; argc; argc--, argv++ )
4667             append_to_strlist2( &sl, *argv, utf8_strings );
4668         rc = keyserver_fetch (ctrl, sl, opt.key_origin);
4669         if(rc)
4670           {
4671             write_status_failure ("fetch-keys", rc);
4672             log_error ("key fetch failed: %s\n",gpg_strerror (rc));
4673           }
4674         free_strlist(sl);
4675         break;
4676
4677       case aExportSecret:
4678         sl = NULL;
4679         for( ; argc; argc--, argv++ )
4680             add_to_strlist2( &sl, *argv, utf8_strings );
4681         {
4682           export_stats_t stats = export_new_stats ();
4683           export_seckeys (ctrl, sl, opt.export_options, stats);
4684           export_print_stats (stats);
4685           export_release_stats (stats);
4686         }
4687         free_strlist(sl);
4688         break;
4689
4690       case aExportSecretSub:
4691         sl = NULL;
4692         for( ; argc; argc--, argv++ )
4693             add_to_strlist2( &sl, *argv, utf8_strings );
4694         {
4695           export_stats_t stats = export_new_stats ();
4696           export_secsubkeys (ctrl, sl, opt.export_options, stats);
4697           export_print_stats (stats);
4698           export_release_stats (stats);
4699         }
4700         free_strlist(sl);
4701         break;
4702
4703       case aGenRevoke:
4704         if( argc != 1 )
4705             wrong_args("--generate-revocation user-id");
4706         username =  make_username(*argv);
4707         gen_revoke (ctrl, username );
4708         xfree( username );
4709         break;
4710
4711       case aDesigRevoke:
4712         if (argc != 1)
4713             wrong_args ("--generate-designated-revocation user-id");
4714         username = make_username (*argv);
4715         gen_desig_revoke (ctrl, username, locusr);
4716         xfree (username);
4717         break;
4718
4719       case aDeArmor:
4720         if( argc > 1 )
4721             wrong_args("--dearmor [file]");
4722         rc = dearmor_file( argc? *argv: NULL );
4723         if( rc )
4724           {
4725             write_status_failure ("dearmor", rc);
4726             log_error (_("dearmoring failed: %s\n"), gpg_strerror (rc));
4727           }
4728         break;
4729
4730       case aEnArmor:
4731         if( argc > 1 )
4732             wrong_args("--enarmor [file]");
4733         rc = enarmor_file( argc? *argv: NULL );
4734         if( rc )
4735           {
4736             write_status_failure ("enarmor", rc);
4737             log_error (_("enarmoring failed: %s\n"), gpg_strerror (rc));
4738           }
4739         break;
4740
4741
4742       case aPrimegen:
4743 #if 0 /*FIXME*/
4744         {   int mode = argc < 2 ? 0 : atoi(*argv);
4745
4746             if( mode == 1 && argc == 2 ) {
4747                 mpi_print (es_stdout,
4748                            generate_public_prime( atoi(argv[1]) ), 1);
4749             }
4750             else if( mode == 2 && argc == 3 ) {
4751                 mpi_print (es_stdout, generate_elg_prime(
4752                                              0, atoi(argv[1]),
4753                                              atoi(argv[2]), NULL,NULL ), 1);
4754             }
4755             else if( mode == 3 && argc == 3 ) {
4756                 MPI *factors;
4757                 mpi_print (es_stdout, generate_elg_prime(
4758                                              1, atoi(argv[1]),
4759                                              atoi(argv[2]), NULL,&factors ), 1);
4760                 es_putc ('\n', es_stdout);
4761                 mpi_print (es_stdout, factors[0], 1 ); /* print q */
4762             }
4763             else if( mode == 4 && argc == 3 ) {
4764                 MPI g = mpi_alloc(1);
4765                 mpi_print (es_stdout, generate_elg_prime(
4766                                                  0, atoi(argv[1]),
4767                                                  atoi(argv[2]), g, NULL ), 1);
4768                 es_putc ('\n', es_stdout);
4769                 mpi_print (es_stdout, g, 1 );
4770                 mpi_free (g);
4771             }
4772             else
4773                 wrong_args("--gen-prime mode bits [qbits] ");
4774             es_putc ('\n', es_stdout);
4775         }
4776 #endif
4777         wrong_args("--gen-prime not yet supported ");
4778         break;
4779
4780       case aGenRandom:
4781         {
4782             int level = argc ? atoi(*argv):0;
4783             int count = argc > 1 ? atoi(argv[1]): 0;
4784             int endless = !count;
4785
4786             if( argc < 1 || argc > 2 || level < 0 || level > 2 || count < 0 )
4787                 wrong_args("--gen-random 0|1|2 [count]");
4788
4789             while( endless || count ) {
4790                 byte *p;
4791                 /* Wee need a multiple of 3, so that in case of
4792                    armored output we get a correct string.  No
4793                    linefolding is done, as it is best to levae this to
4794                    other tools */
4795                 size_t n = !endless && count < 99? count : 99;
4796
4797                 p = gcry_random_bytes (n, level);
4798 #ifdef HAVE_DOSISH_SYSTEM
4799                 setmode ( fileno(stdout), O_BINARY );
4800 #endif
4801                 if (opt.armor) {
4802                     char *tmp = make_radix64_string (p, n);
4803                     es_fputs (tmp, es_stdout);
4804                     xfree (tmp);
4805                     if (n%3 == 1)
4806                       es_putc ('=', es_stdout);
4807                     if (n%3)
4808                       es_putc ('=', es_stdout);
4809                 } else {
4810                     es_fwrite( p, n, 1, es_stdout );
4811                 }
4812                 xfree(p);
4813                 if( !endless )
4814                     count -= n;
4815             }
4816             if (opt.armor)
4817               es_putc ('\n', es_stdout);
4818         }
4819         break;
4820
4821       case aPrintMD:
4822         if( argc < 1)
4823             wrong_args("--print-md algo [files]");
4824         {
4825             int all_algos = (**argv=='*' && !(*argv)[1]);
4826             int algo = all_algos? 0 : gcry_md_map_name (*argv);
4827
4828             if( !algo && !all_algos )
4829                 log_error(_("invalid hash algorithm '%s'\n"), *argv );
4830             else {
4831                 argc--; argv++;
4832                 if( !argc )
4833                     print_mds(NULL, algo);
4834                 else {
4835                     for(; argc; argc--, argv++ )
4836                         print_mds(*argv, algo);
4837                 }
4838             }
4839         }
4840         break;
4841
4842       case aPrintMDs: /* old option */
4843         if( !argc )
4844             print_mds(NULL,0);
4845         else {
4846             for(; argc; argc--, argv++ )
4847                 print_mds(*argv,0);
4848         }
4849         break;
4850
4851 #ifndef NO_TRUST_MODELS
4852       case aListTrustDB:
4853         if( !argc )
4854           list_trustdb (ctrl, es_stdout, NULL);
4855         else {
4856             for( ; argc; argc--, argv++ )
4857               list_trustdb (ctrl, es_stdout, *argv );
4858         }
4859         break;
4860
4861       case aUpdateTrustDB:
4862         if( argc )
4863             wrong_args("--update-trustdb");
4864         update_trustdb (ctrl);
4865         break;
4866
4867       case aCheckTrustDB:
4868         /* Old versions allowed for arguments - ignore them */
4869         check_trustdb (ctrl);
4870         break;
4871
4872       case aFixTrustDB:
4873         how_to_fix_the_trustdb ();
4874         break;
4875
4876       case aListTrustPath:
4877         if( !argc )
4878             wrong_args("--list-trust-path <user-ids>");
4879         for( ; argc; argc--, argv++ ) {
4880             username = make_username( *argv );
4881             list_trust_path( username );
4882             xfree(username);
4883         }
4884         break;
4885
4886       case aExportOwnerTrust:
4887         if( argc )
4888             wrong_args("--export-ownertrust");
4889         export_ownertrust (ctrl);
4890         break;
4891
4892       case aImportOwnerTrust:
4893         if( argc > 1 )
4894             wrong_args("--import-ownertrust [file]");
4895         import_ownertrust (ctrl, argc? *argv:NULL );
4896         break;
4897 #endif /*!NO_TRUST_MODELS*/
4898
4899       case aRebuildKeydbCaches:
4900         if (argc)
4901             wrong_args ("--rebuild-keydb-caches");
4902         keydb_rebuild_caches (ctrl, 1);
4903         break;
4904
4905 #ifdef ENABLE_CARD_SUPPORT
4906       case aCardStatus:
4907         if (argc == 0)
4908             card_status (ctrl, es_stdout, NULL);
4909         else if (argc == 1)
4910             card_status (ctrl, es_stdout, *argv);
4911         else
4912             wrong_args ("--card-status [serialno]");
4913         break;
4914
4915       case aCardEdit:
4916         if (argc) {
4917             sl = NULL;
4918             for (argc--, argv++ ; argc; argc--, argv++)
4919                 append_to_strlist (&sl, *argv);
4920             card_edit (ctrl, sl);
4921             free_strlist (sl);
4922         }
4923         else
4924           card_edit (ctrl, NULL);
4925         break;
4926
4927       case aChangePIN:
4928         if (!argc)
4929             change_pin (0,1);
4930         else if (argc == 1)
4931             change_pin (atoi (*argv),1);
4932         else
4933             wrong_args ("--change-pin [no]");
4934         break;
4935 #endif /* ENABLE_CARD_SUPPORT*/
4936
4937       case aListConfig:
4938         {
4939           char *str=collapse_args(argc,argv);
4940           list_config(str);
4941           xfree(str);
4942         }
4943         break;
4944
4945       case aListGcryptConfig:
4946         /* Fixme: It would be nice to integrate that with
4947            --list-config but unfortunately there is no way yet to have
4948            libgcrypt print it to an estream for further parsing.  */
4949         gcry_control (GCRYCTL_PRINT_CONFIG, stdout);
4950         break;
4951
4952       case aTOFUPolicy:
4953 #ifdef USE_TOFU
4954         {
4955           int policy;
4956           int i;
4957           KEYDB_HANDLE hd;
4958
4959           if (argc < 2)
4960             wrong_args ("--tofu-policy POLICY KEYID [KEYID...]");
4961
4962           policy = parse_tofu_policy (argv[0]);
4963
4964           hd = keydb_new ();
4965           if (! hd)
4966             {
4967               write_status_failure ("tofu-driver", gpg_error(GPG_ERR_GENERAL));
4968               g10_exit (1);
4969             }
4970
4971           tofu_begin_batch_update (ctrl);
4972
4973           for (i = 1; i < argc; i ++)
4974             {
4975               KEYDB_SEARCH_DESC desc;
4976               kbnode_t kb;
4977
4978               rc = classify_user_id (argv[i], &desc, 0);
4979               if (rc)
4980                 {
4981                   log_error (_("error parsing key specification '%s': %s\n"),
4982                              argv[i], gpg_strerror (rc));
4983                   write_status_failure ("tofu-driver", rc);
4984                   g10_exit (1);
4985                 }
4986
4987               if (! (desc.mode == KEYDB_SEARCH_MODE_SHORT_KID
4988                      || desc.mode == KEYDB_SEARCH_MODE_LONG_KID
4989                      || desc.mode == KEYDB_SEARCH_MODE_FPR16
4990                      || desc.mode == KEYDB_SEARCH_MODE_FPR20
4991                      || desc.mode == KEYDB_SEARCH_MODE_FPR
4992                      || desc.mode == KEYDB_SEARCH_MODE_KEYGRIP))
4993                 {
4994                   log_error (_("'%s' does not appear to be a valid"
4995                                " key ID, fingerprint or keygrip\n"),
4996                              argv[i]);
4997                   write_status_failure ("tofu-driver",
4998                                         gpg_error(GPG_ERR_GENERAL));
4999                   g10_exit (1);
5000                 }
5001
5002               rc = keydb_search_reset (hd);
5003               if (rc)
5004                 {
5005                   /* This should not happen, thus no need to tranalate
5006                      the string.  */
5007                   log_error ("keydb_search_reset failed: %s\n",
5008                              gpg_strerror (rc));
5009                   write_status_failure ("tofu-driver", rc);
5010                   g10_exit (1);
5011                 }
5012
5013               rc = keydb_search (hd, &desc, 1, NULL);
5014               if (rc)
5015                 {
5016                   log_error (_("key \"%s\" not found: %s\n"), argv[i],
5017                              gpg_strerror (rc));
5018                   write_status_failure ("tofu-driver", rc);
5019                   g10_exit (1);
5020                 }
5021
5022               rc = keydb_get_keyblock (hd, &kb);
5023               if (rc)
5024                 {
5025                   log_error (_("error reading keyblock: %s\n"),
5026                              gpg_strerror (rc));
5027                   write_status_failure ("tofu-driver", rc);
5028                   g10_exit (1);
5029                 }
5030
5031               merge_keys_and_selfsig (ctrl, kb);
5032               if (tofu_set_policy (ctrl, kb, policy))
5033                 {
5034                   write_status_failure ("tofu-driver", rc);
5035                   g10_exit (1);
5036                 }
5037
5038               release_kbnode (kb);
5039             }
5040
5041           tofu_end_batch_update (ctrl);
5042
5043           keydb_release (hd);
5044         }
5045 #endif /*USE_TOFU*/
5046         break;
5047
5048       default:
5049         if (!opt.quiet)
5050           log_info (_("WARNING: no command supplied."
5051                       "  Trying to guess what you mean ...\n"));
5052         /*FALLTHRU*/
5053       case aListPackets:
5054         if( argc > 1 )
5055             wrong_args("[filename]");
5056         /* Issue some output for the unix newbie */
5057         if (!fname && !opt.outfile
5058             && gnupg_isatty (fileno (stdin))
5059             && gnupg_isatty (fileno (stdout))
5060             && gnupg_isatty (fileno (stderr)))
5061             log_info(_("Go ahead and type your message ...\n"));
5062
5063         a = iobuf_open(fname);
5064         if (a && is_secured_file (iobuf_get_fd (a)))
5065           {
5066             iobuf_close (a);
5067             a = NULL;
5068             gpg_err_set_errno (EPERM);
5069           }
5070         if( !a )
5071             log_error(_("can't open '%s'\n"), print_fname_stdin(fname));
5072         else {
5073
5074             if( !opt.no_armor ) {
5075                 if( use_armor_filter( a ) ) {
5076                     afx = new_armor_context ();
5077                     push_armor_filter (afx, a);
5078                 }
5079             }
5080             if( cmd == aListPackets ) {
5081                 opt.list_packets=1;
5082                 set_packet_list_mode(1);
5083             }
5084             rc = proc_packets (ctrl, NULL, a );
5085             if( rc )
5086               {
5087                 write_status_failure ("-", rc);
5088                 log_error ("processing message failed: %s\n",
5089                            gpg_strerror (rc));
5090               }
5091             iobuf_close(a);
5092         }
5093         break;
5094       }
5095
5096     /* cleanup */
5097     gpg_deinit_default_ctrl (ctrl);
5098     xfree (ctrl);
5099     release_armor_context (afx);
5100     FREE_STRLIST(remusr);
5101     FREE_STRLIST(locusr);
5102     g10_exit(0);
5103     return 8; /*NEVER REACHED*/
5104 }
5105
5106
5107 /* Note: This function is used by signal handlers!. */
5108 static void
5109 emergency_cleanup (void)
5110 {
5111   gcry_control (GCRYCTL_TERM_SECMEM );
5112 }
5113
5114
5115 void
5116 g10_exit( int rc )
5117 {
5118   /* If we had an error but not printed an error message, do it now.
5119    * Note that write_status_failure will never print a second failure
5120    * status line. */
5121   if (rc)
5122     write_status_failure ("gpg-exit", gpg_error (GPG_ERR_GENERAL));
5123
5124   gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
5125   if (DBG_CLOCK)
5126     log_clock ("stop");
5127
5128   if ( (opt.debug & DBG_MEMSTAT_VALUE) )
5129     {
5130       keydb_dump_stats ();
5131       sig_check_dump_stats ();
5132       gcry_control (GCRYCTL_DUMP_MEMORY_STATS);
5133       gcry_control (GCRYCTL_DUMP_RANDOM_STATS);
5134     }
5135   if (opt.debug)
5136     gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
5137
5138   emergency_cleanup ();
5139
5140   rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0;
5141   exit (rc);
5142 }
5143
5144
5145 /* Pretty-print hex hashes.  This assumes at least an 80-character
5146    display, but there are a few other similar assumptions in the
5147    display code. */
5148 static void
5149 print_hex (gcry_md_hd_t md, int algo, const char *fname)
5150 {
5151   int i,n,count,indent=0;
5152   const byte *p;
5153
5154   if (fname)
5155     indent = es_printf("%s: ",fname);
5156
5157   if (indent>40)
5158     {
5159       es_printf ("\n");
5160       indent=0;
5161     }
5162
5163   if (algo==DIGEST_ALGO_RMD160)
5164     indent += es_printf("RMD160 = ");
5165   else if (algo>0)
5166     indent += es_printf("%6s = ", gcry_md_algo_name (algo));
5167   else
5168     algo = abs(algo);
5169
5170   count = indent;
5171
5172   p = gcry_md_read (md, algo);
5173   n = gcry_md_get_algo_dlen (algo);
5174
5175   count += es_printf ("%02X",*p++);
5176
5177   for(i=1;i<n;i++,p++)
5178     {
5179       if(n==16)
5180         {
5181           if(count+2>79)
5182             {
5183               es_printf ("\n%*s",indent," ");
5184               count = indent;
5185             }
5186           else
5187             count += es_printf(" ");
5188
5189           if (!(i%8))
5190             count += es_printf(" ");
5191         }
5192       else if (n==20)
5193         {
5194           if(!(i%2))
5195             {
5196               if(count+4>79)
5197                 {
5198                   es_printf ("\n%*s",indent," ");
5199                   count=indent;
5200                 }
5201               else
5202                 count += es_printf(" ");
5203             }
5204
5205           if (!(i%10))
5206             count += es_printf(" ");
5207         }
5208       else
5209         {
5210           if(!(i%4))
5211             {
5212               if (count+8>79)
5213                 {
5214                   es_printf ("\n%*s",indent," ");
5215                   count=indent;
5216                 }
5217               else
5218                 count += es_printf(" ");
5219             }
5220         }
5221
5222       count += es_printf("%02X",*p);
5223     }
5224
5225   es_printf ("\n");
5226 }
5227
5228 static void
5229 print_hashline( gcry_md_hd_t md, int algo, const char *fname )
5230 {
5231   int i, n;
5232   const byte *p;
5233
5234   if ( fname )
5235     {
5236       for (p = fname; *p; p++ )
5237         {
5238           if ( *p <= 32 || *p > 127 || *p == ':' || *p == '%' )
5239             es_printf ("%%%02X", *p );
5240           else
5241             es_putc (*p, es_stdout);
5242         }
5243     }
5244   es_putc (':', es_stdout);
5245   es_printf ("%d:", algo);
5246   p = gcry_md_read (md, algo);
5247   n = gcry_md_get_algo_dlen (algo);
5248   for(i=0; i < n ; i++, p++ )
5249     es_printf ("%02X", *p);
5250   es_fputs (":\n", es_stdout);
5251 }
5252
5253
5254 static void
5255 print_mds( const char *fname, int algo )
5256 {
5257   estream_t fp;
5258   char buf[1024];
5259   size_t n;
5260   gcry_md_hd_t md;
5261
5262   if (!fname)
5263     {
5264       fp = es_stdin;
5265       es_set_binary (fp);
5266     }
5267   else
5268     {
5269       fp = es_fopen (fname, "rb" );
5270       if (fp && is_secured_file (es_fileno (fp)))
5271         {
5272           es_fclose (fp);
5273           fp = NULL;
5274           gpg_err_set_errno (EPERM);
5275         }
5276     }
5277   if (!fp)
5278     {
5279       log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
5280       return;
5281     }
5282
5283   gcry_md_open (&md, 0, 0);
5284   if (algo)
5285     gcry_md_enable (md, algo);
5286   else
5287     {
5288       if (!gcry_md_test_algo (GCRY_MD_MD5))
5289         gcry_md_enable (md, GCRY_MD_MD5);
5290       gcry_md_enable (md, GCRY_MD_SHA1);
5291       if (!gcry_md_test_algo (GCRY_MD_RMD160))
5292         gcry_md_enable (md, GCRY_MD_RMD160);
5293       if (!gcry_md_test_algo (GCRY_MD_SHA224))
5294         gcry_md_enable (md, GCRY_MD_SHA224);
5295       if (!gcry_md_test_algo (GCRY_MD_SHA256))
5296         gcry_md_enable (md, GCRY_MD_SHA256);
5297       if (!gcry_md_test_algo (GCRY_MD_SHA384))
5298         gcry_md_enable (md, GCRY_MD_SHA384);
5299       if (!gcry_md_test_algo (GCRY_MD_SHA512))
5300         gcry_md_enable (md, GCRY_MD_SHA512);
5301     }
5302
5303   while ((n=es_fread (buf, 1, DIM(buf), fp)))
5304     gcry_md_write (md, buf, n);
5305
5306   if (es_ferror(fp))
5307     log_error ("%s: %s\n", fname?fname:"[stdin]", strerror(errno));
5308   else
5309     {
5310       gcry_md_final (md);
5311       if (opt.with_colons)
5312         {
5313           if ( algo )
5314             print_hashline (md, algo, fname);
5315           else
5316             {
5317               if (!gcry_md_test_algo (GCRY_MD_MD5))
5318                 print_hashline( md, GCRY_MD_MD5, fname );
5319               print_hashline( md, GCRY_MD_SHA1, fname );
5320               if (!gcry_md_test_algo (GCRY_MD_RMD160))
5321                 print_hashline( md, GCRY_MD_RMD160, fname );
5322               if (!gcry_md_test_algo (GCRY_MD_SHA224))
5323                 print_hashline (md, GCRY_MD_SHA224, fname);
5324               if (!gcry_md_test_algo (GCRY_MD_SHA256))
5325                 print_hashline( md, GCRY_MD_SHA256, fname );
5326               if (!gcry_md_test_algo (GCRY_MD_SHA384))
5327                 print_hashline ( md, GCRY_MD_SHA384, fname );
5328               if (!gcry_md_test_algo (GCRY_MD_SHA512))
5329                 print_hashline ( md, GCRY_MD_SHA512, fname );
5330             }
5331         }
5332       else
5333         {
5334           if (algo)
5335             print_hex (md, -algo, fname);
5336           else
5337             {
5338               if (!gcry_md_test_algo (GCRY_MD_MD5))
5339                 print_hex (md, GCRY_MD_MD5, fname);
5340               print_hex (md, GCRY_MD_SHA1, fname );
5341               if (!gcry_md_test_algo (GCRY_MD_RMD160))
5342                 print_hex (md, GCRY_MD_RMD160, fname );
5343               if (!gcry_md_test_algo (GCRY_MD_SHA224))
5344                 print_hex (md, GCRY_MD_SHA224, fname);
5345               if (!gcry_md_test_algo (GCRY_MD_SHA256))
5346                 print_hex (md, GCRY_MD_SHA256, fname );
5347               if (!gcry_md_test_algo (GCRY_MD_SHA384))
5348                 print_hex (md, GCRY_MD_SHA384, fname );
5349               if (!gcry_md_test_algo (GCRY_MD_SHA512))
5350                 print_hex (md, GCRY_MD_SHA512, fname );
5351             }
5352         }
5353     }
5354   gcry_md_close (md);
5355
5356   if (fp != es_stdin)
5357     es_fclose (fp);
5358 }
5359
5360
5361 /****************
5362  * Check the supplied name,value string and add it to the notation
5363  * data to be used for signatures.  which==0 for sig notations, and 1
5364  * for cert notations.
5365 */
5366 static void
5367 add_notation_data( const char *string, int which )
5368 {
5369   struct notation *notation;
5370
5371   notation=string_to_notation(string,utf8_strings);
5372   if(notation)
5373     {
5374       if(which)
5375         {
5376           notation->next=opt.cert_notations;
5377           opt.cert_notations=notation;
5378         }
5379       else
5380         {
5381           notation->next=opt.sig_notations;
5382           opt.sig_notations=notation;
5383         }
5384     }
5385 }
5386
5387 static void
5388 add_policy_url( const char *string, int which )
5389 {
5390   unsigned int i,critical=0;
5391   strlist_t sl;
5392
5393   if(*string=='!')
5394     {
5395       string++;
5396       critical=1;
5397     }
5398
5399   for(i=0;i<strlen(string);i++)
5400     if( !isascii (string[i]) || iscntrl(string[i]))
5401       break;
5402
5403   if(i==0 || i<strlen(string))
5404     {
5405       if(which)
5406         log_error(_("the given certification policy URL is invalid\n"));
5407       else
5408         log_error(_("the given signature policy URL is invalid\n"));
5409     }
5410
5411   if(which)
5412     sl=add_to_strlist( &opt.cert_policy_url, string );
5413   else
5414     sl=add_to_strlist( &opt.sig_policy_url, string );
5415
5416   if(critical)
5417     sl->flags |= 1;
5418 }
5419
5420 static void
5421 add_keyserver_url( const char *string, int which )
5422 {
5423   unsigned int i,critical=0;
5424   strlist_t sl;
5425
5426   if(*string=='!')
5427     {
5428       string++;
5429       critical=1;
5430     }
5431
5432   for(i=0;i<strlen(string);i++)
5433     if( !isascii (string[i]) || iscntrl(string[i]))
5434       break;
5435
5436   if(i==0 || i<strlen(string))
5437     {
5438       if(which)
5439         BUG();
5440       else
5441         log_error(_("the given preferred keyserver URL is invalid\n"));
5442     }
5443
5444   if(which)
5445     BUG();
5446   else
5447     sl=add_to_strlist( &opt.sig_keyserver_url, string );
5448
5449   if(critical)
5450     sl->flags |= 1;
5451 }
5452
5453
5454 static void
5455 read_sessionkey_from_fd (int fd)
5456 {
5457   int i, len;
5458   char *line;
5459
5460   if (! gnupg_fd_valid (fd))
5461     log_fatal ("override-session-key-fd is invalid: %s\n", strerror (errno));
5462
5463   for (line = NULL, i = len = 100; ; i++ )
5464     {
5465       if (i >= len-1 )
5466         {
5467           char *tmp = line;
5468           len += 100;
5469           line = xmalloc_secure (len);
5470           if (tmp)
5471             {
5472               memcpy (line, tmp, i);
5473               xfree (tmp);
5474             }
5475           else
5476             i=0;
5477         }
5478       if (read (fd, line + i, 1) != 1 || line[i] == '\n')
5479         break;
5480     }
5481   line[i] = 0;
5482   log_debug ("seskey: %s\n", line);
5483   gpgrt_annotate_leaked_object (line);
5484   opt.override_session_key = line;
5485 }