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