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