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