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