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