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