2008-02-09 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / gpg.c
blob1a033ebd9e5c0ff7e75bb755754e61a6ade9167c
1 /* gpg.c - The GnuPG utility (main for gpg)
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006, 2007 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
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.
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.
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/>.
21 #include <config.h>
22 #include <errno.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <ctype.h>
27 #include <unistd.h>
28 #include <assert.h>
29 #ifdef HAVE_STAT
30 #include <sys/stat.h> /* for stat() */
31 #endif
32 #include <fcntl.h>
33 #include <assuan.h>
34 #ifdef HAVE_W32_SYSTEM
35 #include <windows.h>
36 #endif
38 #define INCLUDED_BY_MAIN_MODULE 1
39 #include "gpg.h"
40 #include "packet.h"
41 #include "../common/iobuf.h"
42 #include "util.h"
43 #include "main.h"
44 #include "options.h"
45 #include "keydb.h"
46 #include "trustdb.h"
47 #include "cipher.h"
48 #include "filter.h"
49 #include "ttyio.h"
50 #include "i18n.h"
51 #include "sysutils.h"
52 #include "status.h"
53 #include "keyserver-internal.h"
54 #include "exec.h"
55 #include "gc-opt-flags.h"
57 #if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
58 #define MY_O_BINARY O_BINARY
59 #ifndef S_IRGRP
60 # define S_IRGRP 0
61 # define S_IWGRP 0
62 #endif
63 #else
64 #define MY_O_BINARY 0
65 #endif
68 enum cmd_and_opt_values
70 aNull = 0,
71 oArmor = 'a',
72 aDetachedSign = 'b',
73 aSym = 'c',
74 aDecrypt = 'd',
75 aEncr = 'e',
76 oInteractive = 'i',
77 aListKeys = 'k',
78 oDryRun = 'n',
79 oOutput = 'o',
80 oQuiet = 'q',
81 oRecipient = 'r',
82 oHiddenRecipient = 'R',
83 aSign = 's',
84 oTextmodeShort= 't',
85 oLocalUser = 'u',
86 oVerbose = 'v',
87 oCompress = 'z',
88 oSetNotation = 'N',
89 aListSecretKeys = 'K',
90 oBatch = 500,
91 oMaxOutput,
92 oSigNotation,
93 oCertNotation,
94 oShowNotation,
95 oNoShowNotation,
96 aEncrFiles,
97 aEncrSym,
98 aDecryptFiles,
99 aClearsign,
100 aStore,
101 aKeygen,
102 aSignEncr,
103 aSignEncrSym,
104 aSignSym,
105 aSignKey,
106 aLSignKey,
107 aListConfig,
108 aGPGConfList,
109 aGPGConfTest,
110 aListPackets,
111 aEditKey,
112 aDeleteKeys,
113 aDeleteSecretKeys,
114 aDeleteSecretAndPublicKeys,
115 aImport,
116 aFastImport,
117 aVerify,
118 aVerifyFiles,
119 aListSigs,
120 aSendKeys,
121 aRecvKeys,
122 aSearchKeys,
123 aRefreshKeys,
124 aFetchKeys,
125 aExport,
126 aExportSecret,
127 aExportSecretSub,
128 aCheckKeys,
129 aGenRevoke,
130 aDesigRevoke,
131 aPrimegen,
132 aPrintMD,
133 aPrintMDs,
134 aCheckTrustDB,
135 aUpdateTrustDB,
136 aFixTrustDB,
137 aListTrustDB,
138 aListTrustPath,
139 aExportOwnerTrust,
140 aImportOwnerTrust,
141 aDeArmor,
142 aEnArmor,
143 aGenRandom,
144 aRebuildKeydbCaches,
145 aCardStatus,
146 aCardEdit,
147 aChangePIN,
148 aServer,
150 oTextmode,
151 oNoTextmode,
152 oExpert,
153 oNoExpert,
154 oDefSigExpire,
155 oAskSigExpire,
156 oNoAskSigExpire,
157 oDefCertExpire,
158 oAskCertExpire,
159 oNoAskCertExpire,
160 oDefCertLevel,
161 oMinCertLevel,
162 oAskCertLevel,
163 oNoAskCertLevel,
164 oFingerprint,
165 oWithFingerprint,
166 oAnswerYes,
167 oAnswerNo,
168 oKeyring,
169 oPrimaryKeyring,
170 oSecretKeyring,
171 oShowKeyring,
172 oDefaultKey,
173 oDefRecipient,
174 oDefRecipientSelf,
175 oNoDefRecipient,
176 oOptions,
177 oDebug,
178 oDebugLevel,
179 oDebugAll,
180 oDebugCCIDDriver,
181 oStatusFD,
182 oStatusFile,
183 oAttributeFD,
184 oAttributeFile,
185 oEmitVersion,
186 oNoEmitVersion,
187 oCompletesNeeded,
188 oMarginalsNeeded,
189 oMaxCertDepth,
190 oLoadExtension,
191 oGnuPG,
192 oRFC1991,
193 oRFC2440,
194 oRFC4880,
195 oOpenPGP,
196 oPGP2,
197 oPGP6,
198 oPGP7,
199 oPGP8,
200 oRFC2440Text,
201 oNoRFC2440Text,
202 oCipherAlgo,
203 oDigestAlgo,
204 oCertDigestAlgo,
205 oCompressAlgo,
206 oCompressLevel,
207 oBZ2CompressLevel,
208 oBZ2DecompressLowmem,
209 oPasswd,
210 oPasswdFD,
211 oPasswdFile,
212 oPasswdRepeat,
213 oCommandFD,
214 oCommandFile,
215 oQuickRandom,
216 oNoVerbose,
217 oTrustDBName,
218 oNoSecmemWarn,
219 oRequireSecmem,
220 oNoRequireSecmem,
221 oNoPermissionWarn,
222 oNoMDCWarn,
223 oNoArmor,
224 oNoDefKeyring,
225 oNoGreeting,
226 oNoTTY,
227 oNoOptions,
228 oNoBatch,
229 oHomedir,
230 oWithColons,
231 oWithKeyData,
232 oSkipVerify,
233 oCompressKeys,
234 oCompressSigs,
235 oAlwaysTrust,
236 oTrustModel,
237 oForceOwnertrust,
238 oSetFilename,
239 oForYourEyesOnly,
240 oNoForYourEyesOnly,
241 oSetPolicyURL,
242 oSigPolicyURL,
243 oCertPolicyURL,
244 oShowPolicyURL,
245 oNoShowPolicyURL,
246 oSigKeyserverURL,
247 oUseEmbeddedFilename,
248 oNoUseEmbeddedFilename,
249 oComment,
250 oDefaultComment,
251 oNoComments,
252 oThrowKeyids,
253 oNoThrowKeyids,
254 oShowPhotos,
255 oNoShowPhotos,
256 oPhotoViewer,
257 oForceV3Sigs,
258 oNoForceV3Sigs,
259 oForceV4Certs,
260 oNoForceV4Certs,
261 oForceMDC,
262 oNoForceMDC,
263 oDisableMDC,
264 oNoDisableMDC,
265 oS2KMode,
266 oS2KDigest,
267 oS2KCipher,
268 oS2KCount,
269 oSimpleSKChecksum,
270 oDisplayCharset,
271 oNotDashEscaped,
272 oEscapeFrom,
273 oNoEscapeFrom,
274 oLockOnce,
275 oLockMultiple,
276 oLockNever,
277 oKeyServer,
278 oKeyServerOptions,
279 oImportOptions,
280 oExportOptions,
281 oListOptions,
282 oVerifyOptions,
283 oTempDir,
284 oExecPath,
285 oEncryptTo,
286 oHiddenEncryptTo,
287 oNoEncryptTo,
288 oLoggerFD,
289 oLoggerFile,
290 oUtf8Strings,
291 oNoUtf8Strings,
292 oDisableCipherAlgo,
293 oDisablePubkeyAlgo,
294 oAllowNonSelfsignedUID,
295 oNoAllowNonSelfsignedUID,
296 oAllowFreeformUID,
297 oNoAllowFreeformUID,
298 oAllowSecretKeyImport,
299 oEnableSpecialFilenames,
300 oNoLiteral,
301 oSetFilesize,
302 oHonorHttpProxy,
303 oFastListMode,
304 oListOnly,
305 oIgnoreTimeConflict,
306 oIgnoreValidFrom,
307 oIgnoreCrcError,
308 oIgnoreMDCError,
309 oShowSessionKey,
310 oOverrideSessionKey,
311 oNoRandomSeedFile,
312 oAutoKeyRetrieve,
313 oNoAutoKeyRetrieve,
314 oUseAgent,
315 oNoUseAgent,
316 oGpgAgentInfo,
317 oMergeOnly,
318 oTryAllSecrets,
319 oTrustedKey,
320 oNoExpensiveTrustChecks,
321 oFixedListMode,
322 oNoSigCache,
323 oNoSigCreateCheck,
324 oAutoCheckTrustDB,
325 oNoAutoCheckTrustDB,
326 oPreservePermissions,
327 oDefaultPreferenceList,
328 oDefaultKeyserverURL,
329 oPersonalCipherPreferences,
330 oPersonalDigestPreferences,
331 oPersonalCompressPreferences,
332 oAgentProgram,
333 oDisplay,
334 oTTYname,
335 oTTYtype,
336 oLCctype,
337 oLCmessages,
338 oXauthority,
339 oGroup,
340 oUnGroup,
341 oNoGroups,
342 oStrict,
343 oNoStrict,
344 oMangleDosFilenames,
345 oNoMangleDosFilenames,
346 oEnableProgressFilter,
347 oMultifile,
348 oKeyidFormat,
349 oExitOnStatusWriteError,
350 oLimitCardInsertTries,
351 oRequireCrossCert,
352 oNoRequireCrossCert,
353 oAutoKeyLocate,
354 oNoAutoKeyLocate,
355 oAllowMultisigVerification,
356 oEnableDSA2,
357 oDisableDSA2,
358 oAllowMultipleMessages,
359 oNoAllowMultipleMessages,
361 oNoop
365 static ARGPARSE_OPTS opts[] = {
367 { 300, NULL, 0, N_("@Commands:\n ") },
369 { aSign, "sign", 256, N_("|[file]|make a signature")},
370 { aClearsign, "clearsign", 256, N_("|[file]|make a clear text signature")},
371 { aDetachedSign, "detach-sign", 256, N_("make a detached signature")},
372 { aEncr, "encrypt", 256, N_("encrypt data")},
373 { aEncrFiles, "encrypt-files", 256, "@"},
374 { aSym, "symmetric", 256, N_("encryption only with symmetric cipher")},
375 { aStore, "store", 256, "@"},
376 { aDecrypt, "decrypt", 256, N_("decrypt data (default)")},
377 { aDecryptFiles, "decrypt-files", 256, "@"},
378 { aVerify, "verify" , 256, N_("verify a signature")},
379 { aVerifyFiles, "verify-files" , 256, "@" },
380 { aListKeys, "list-keys", 256, N_("list keys")},
381 { aListKeys, "list-public-keys", 256, "@" },
382 { aListSigs, "list-sigs", 256, N_("list keys and signatures")},
383 { aCheckKeys, "check-sigs",256, N_("list and check key signatures")},
384 { oFingerprint, "fingerprint", 256, N_("list keys and fingerprints")},
385 { aListSecretKeys, "list-secret-keys", 256, N_("list secret keys")},
386 { aKeygen, "gen-key", 256, N_("generate a new key pair")},
387 { aDeleteKeys,"delete-keys",256,N_("remove keys from the public keyring")},
388 { aDeleteSecretKeys, "delete-secret-keys",256,
389 N_("remove keys from the secret keyring")},
390 { aSignKey, "sign-key" ,256, N_("sign a key")},
391 { aLSignKey, "lsign-key" ,256, N_("sign a key locally")},
392 { aEditKey, "edit-key" ,256, N_("sign or edit a key")},
393 { aGenRevoke, "gen-revoke",256, N_("generate a revocation certificate")},
394 { aDesigRevoke, "desig-revoke",256, "@" },
395 { aExport, "export" , 256, N_("export keys") },
396 { aSendKeys, "send-keys" , 256, N_("export keys to a key server") },
397 { aRecvKeys, "recv-keys" , 256, N_("import keys from a key server") },
398 { aSearchKeys, "search-keys" , 256,
399 N_("search for keys on a key server") },
400 { aRefreshKeys, "refresh-keys", 256,
401 N_("update all keys from a keyserver")},
402 { aFetchKeys, "fetch-keys" , 256, "@" },
403 { aExportSecret, "export-secret-keys" , 256, "@" },
404 { aExportSecretSub, "export-secret-subkeys" , 256, "@" },
405 { aImport, "import", 256 , N_("import/merge keys")},
406 { aFastImport, "fast-import", 256 , "@"},
407 #ifdef ENABLE_CARD_SUPPORT
408 { aCardStatus, "card-status", 256, N_("print the card status")},
409 { aCardEdit, "card-edit", 256, N_("change data on a card")},
410 { aChangePIN, "change-pin", 256, N_("change a card's PIN")},
411 #endif
412 { aListConfig, "list-config", 256, "@"},
413 { aGPGConfList, "gpgconf-list", 256, "@" },
414 { aGPGConfTest, "gpgconf-test", 256, "@" },
415 { aListPackets, "list-packets",256, "@"},
416 { aExportOwnerTrust, "export-ownertrust", 256, "@"},
417 { aImportOwnerTrust, "import-ownertrust", 256, "@"},
418 { aUpdateTrustDB,
419 "update-trustdb",0 , N_("update the trust database")},
420 { aCheckTrustDB, "check-trustdb", 0, "@"},
421 { aFixTrustDB, "fix-trustdb", 0, "@"},
422 { aDeArmor, "dearmor", 256, "@"},
423 { aDeArmor, "dearmour", 256, "@"},
424 { aEnArmor, "enarmor", 256, "@"},
425 { aEnArmor, "enarmour", 256, "@"},
426 { aPrintMD, "print-md" , 256, N_("|algo [files]|print message digests")},
427 { aPrimegen, "gen-prime" , 256, "@" },
428 { aGenRandom, "gen-random", 256, "@" },
429 { aServer, "server", 256, N_("run in server mode")},
431 { 301, NULL, 0, N_("@\nOptions:\n ") },
433 { oArmor, "armor", 0, N_("create ascii armored output")},
434 { oArmor, "armour", 0, "@" },
435 { oRecipient, "recipient", 2, N_("|NAME|encrypt for NAME")},
436 { oHiddenRecipient, "hidden-recipient", 2, "@" },
437 { oRecipient, "remote-user", 2, "@"}, /* old option name */
438 { oDefRecipient, "default-recipient", 2, "@"},
439 { oDefRecipientSelf, "default-recipient-self", 0, "@"},
440 { oNoDefRecipient, "no-default-recipient", 0, "@" },
441 { oTempDir, "temp-directory", 2, "@" },
442 { oExecPath, "exec-path", 2, "@" },
443 { oEncryptTo, "encrypt-to", 2, "@" },
444 { oHiddenEncryptTo, "hidden-encrypt-to", 2, "@" },
445 { oNoEncryptTo, "no-encrypt-to", 0, "@" },
446 { oLocalUser, "local-user",2, N_("use this user-id to sign or decrypt")},
447 { oCompress, NULL, 1, N_("|N|set compress level N (0 disables)") },
448 { oCompressLevel, "compress-level", 1, "@" },
449 { oBZ2CompressLevel, "bzip2-compress-level", 1, "@" },
450 { oBZ2DecompressLowmem, "bzip2-decompress-lowmem", 0, "@" },
451 { oTextmodeShort, NULL, 0, "@"},
452 { oTextmode, "textmode", 0, N_("use canonical text mode")},
453 { oNoTextmode, "no-textmode", 0, "@"},
454 { oExpert, "expert", 0, "@"},
455 { oNoExpert, "no-expert", 0, "@"},
456 { oDefSigExpire, "default-sig-expire", 2, "@"},
457 { oAskSigExpire, "ask-sig-expire", 0, "@"},
458 { oNoAskSigExpire, "no-ask-sig-expire", 0, "@"},
459 { oDefCertExpire, "default-cert-expire", 2, "@"},
460 { oAskCertExpire, "ask-cert-expire", 0, "@"},
461 { oNoAskCertExpire, "no-ask-cert-expire", 0, "@"},
462 { oDefCertLevel, "default-cert-level", 1, "@"},
463 { oMinCertLevel, "min-cert-level", 1, "@"},
464 { oAskCertLevel, "ask-cert-level", 0, "@"},
465 { oNoAskCertLevel, "no-ask-cert-level", 0, "@"},
466 { oOutput, "output", 2, N_("|FILE|write output to FILE")},
467 { oMaxOutput, "max-output", 16|4, "@" },
468 { oVerbose, "verbose", 0, N_("verbose") },
469 { oQuiet, "quiet", 0, "@"},
470 { oNoTTY, "no-tty", 0, "@"},
471 { oForceV3Sigs, "force-v3-sigs", 0, "@"},
472 { oNoForceV3Sigs, "no-force-v3-sigs", 0, "@"},
473 { oForceV4Certs, "force-v4-certs", 0, "@"},
474 { oNoForceV4Certs, "no-force-v4-certs", 0, "@"},
475 { oForceMDC, "force-mdc", 0, "@"},
476 { oNoForceMDC, "no-force-mdc", 0, "@" },
477 { oDisableMDC, "disable-mdc", 0, "@"},
478 { oNoDisableMDC, "no-disable-mdc", 0, "@" },
479 { oDryRun, "dry-run", 0, N_("do not make any changes") },
480 { oInteractive, "interactive", 0, N_("prompt before overwriting") },
481 { oUseAgent, "use-agent",0, "@"},
482 { oNoUseAgent, "no-use-agent",0, "@"},
483 { oGpgAgentInfo, "gpg-agent-info",2, "@"},
484 { oBatch, "batch", 0, "@"},
485 { oAnswerYes, "yes", 0, "@"},
486 { oAnswerNo, "no", 0, "@"},
487 { oKeyring, "keyring", 2, "@"},
488 { oPrimaryKeyring, "primary-keyring",2, "@" },
489 { oSecretKeyring, "secret-keyring", 2, "@"},
490 { oShowKeyring, "show-keyring", 0, "@"},
491 { oDefaultKey, "default-key", 2, "@"},
492 { oKeyServer, "keyserver", 2, "@"},
493 { oKeyServerOptions, "keyserver-options",2,"@"},
494 { oImportOptions, "import-options",2,"@"},
495 { oExportOptions, "export-options",2,"@"},
496 { oListOptions, "list-options",2,"@"},
497 { oVerifyOptions, "verify-options",2,"@"},
498 { oDisplayCharset, "display-charset", 2, "@"},
499 { oDisplayCharset, "charset", 2, "@"},
500 { oOptions, "options", 2, "@"},
501 { oDebug, "debug" ,4|16, "@"},
502 { oDebugLevel, "debug-level" ,2, "@"},
503 { oDebugAll, "debug-all" ,0, "@"},
504 { oStatusFD, "status-fd" ,1, "@"},
505 { oStatusFile, "status-file" ,2, "@"},
506 { oAttributeFD, "attribute-fd" ,1, "@" },
507 { oAttributeFile, "attribute-file" ,2, "@" },
508 { oNoop, "sk-comments", 0, "@"},
509 { oNoop, "no-sk-comments", 0, "@"},
510 { oCompletesNeeded, "completes-needed", 1, "@"},
511 { oMarginalsNeeded, "marginals-needed", 1, "@"},
512 { oMaxCertDepth, "max-cert-depth", 1, "@" },
513 { oTrustedKey, "trusted-key", 2, "@"},
514 { oLoadExtension, "load-extension", 2, "@"},
515 { oGnuPG, "gnupg", 0, "@"},
516 { oGnuPG, "no-pgp2", 0, "@"},
517 { oGnuPG, "no-pgp6", 0, "@"},
518 { oGnuPG, "no-pgp7", 0, "@"},
519 { oGnuPG, "no-pgp8", 0, "@"},
520 { oRFC1991, "rfc1991", 0, "@"},
521 { oRFC2440, "rfc2440", 0, "@" },
522 { oRFC4880, "rfc4880", 0, "@" },
523 { oOpenPGP, "openpgp", 0, N_("use strict OpenPGP behavior")},
524 { oPGP2, "pgp2", 0, N_("generate PGP 2.x compatible messages")},
525 { oPGP6, "pgp6", 0, "@"},
526 { oPGP7, "pgp7", 0, "@"},
527 { oPGP8, "pgp8", 0, "@"},
528 { oRFC2440Text, "rfc2440-text", 0, "@"},
529 { oNoRFC2440Text, "no-rfc2440-text", 0, "@"},
530 { oS2KMode, "s2k-mode", 1, "@"},
531 { oS2KDigest, "s2k-digest-algo", 2, "@"},
532 { oS2KCipher, "s2k-cipher-algo", 2, "@"},
533 { oS2KCount, "s2k-count", 1, "@"},
534 { oSimpleSKChecksum, "simple-sk-checksum", 0, "@"},
535 { oCipherAlgo, "cipher-algo", 2, "@"},
536 { oDigestAlgo, "digest-algo", 2, "@"},
537 { oCertDigestAlgo, "cert-digest-algo", 2 , "@" },
538 { oCompressAlgo,"compress-algo", 2, "@"},
539 { oCompressAlgo, "compression-algo", 2, "@"}, /* Alias */
540 { oThrowKeyids, "throw-keyid", 0, "@"},
541 { oThrowKeyids, "throw-keyids", 0, "@"},
542 { oNoThrowKeyids, "no-throw-keyid", 0, "@" },
543 { oNoThrowKeyids, "no-throw-keyids", 0, "@" },
544 { oShowPhotos, "show-photos", 0, "@" },
545 { oNoShowPhotos, "no-show-photos", 0, "@" },
546 { oPhotoViewer, "photo-viewer", 2, "@" },
547 { oSetNotation, "set-notation", 2, "@" },
548 { oSetNotation, "notation-data", 2, "@" }, /* Alias */
549 { oSigNotation, "sig-notation", 2, "@" },
550 { oCertNotation, "cert-notation", 2, "@" },
552 { 302, NULL, 0, N_(
553 "@\n(See the man page for a complete listing of all commands and options)\n"
556 { 303, NULL, 0, N_("@\nExamples:\n\n"
557 " -se -r Bob [file] sign and encrypt for user Bob\n"
558 " --clearsign [file] make a clear text signature\n"
559 " --detach-sign [file] make a detached signature\n"
560 " --list-keys [names] show keys\n"
561 " --fingerprint [names] show fingerprints\n" ) },
563 /* hidden options */
564 { aPrintMDs, "print-mds" , 256, "@"}, /* old */
565 { aListTrustDB, "list-trustdb",0 , "@"},
566 /* Not yet used */
567 /* { aListTrustPath, "list-trust-path",0, "@"}, */
568 { oPasswd, "passphrase",2, "@" },
569 { oPasswdFD, "passphrase-fd",1, "@" },
570 { oPasswdFile, "passphrase-file",2, "@" },
571 { oPasswdRepeat, "passphrase-repeat", 1, "@"},
572 { oCommandFD, "command-fd",1, "@" },
573 { oCommandFile, "command-file",2, "@" },
574 { oQuickRandom, "debug-quick-random", 0, "@"},
575 { oNoVerbose, "no-verbose", 0, "@"},
576 { oTrustDBName, "trustdb-name", 2, "@" },
577 { oNoSecmemWarn, "no-secmem-warning", 0, "@" },
578 { oRequireSecmem,"require-secmem", 0, "@" },
579 { oNoRequireSecmem,"no-require-secmem", 0, "@" },
580 { oNoPermissionWarn, "no-permission-warning", 0, "@" },
581 { oNoMDCWarn, "no-mdc-warning", 0, "@" },
582 { oNoArmor, "no-armor", 0, "@"},
583 { oNoArmor, "no-armour", 0, "@"},
584 { oNoDefKeyring, "no-default-keyring", 0, "@" },
585 { oNoGreeting, "no-greeting", 0, "@" },
586 { oNoOptions, "no-options", 0, "@" }, /* shortcut for --options /dev/null */
587 { oHomedir, "homedir", 2, "@" }, /* defaults to "~/.gnupg" */
588 { oNoBatch, "no-batch", 0, "@" },
589 { oWithColons, "with-colons", 0, "@"},
590 { oWithKeyData,"with-key-data", 0, "@"},
591 { aListKeys, "list-key", 0, "@" }, /* alias */
592 { aListSigs, "list-sig", 0, "@" }, /* alias */
593 { aCheckKeys, "check-sig",0, "@" }, /* alias */
594 { oSkipVerify, "skip-verify",0, "@" },
595 { oCompressKeys, "compress-keys",0, "@"},
596 { oCompressSigs, "compress-sigs",0, "@"},
597 { oDefCertLevel, "default-cert-check-level", 1, "@"}, /* Old option */
598 { oAlwaysTrust, "always-trust", 0, "@"},
599 { oTrustModel, "trust-model", 2, "@"},
600 { oForceOwnertrust, "force-ownertrust", 2, "@"},
601 { oSetFilename, "set-filename", 2, "@" },
602 { oForYourEyesOnly, "for-your-eyes-only", 0, "@" },
603 { oNoForYourEyesOnly, "no-for-your-eyes-only", 0, "@" },
604 { oSetPolicyURL, "set-policy-url", 2, "@" },
605 { oSigPolicyURL, "sig-policy-url", 2, "@" },
606 { oCertPolicyURL, "cert-policy-url", 2, "@" },
607 { oShowPolicyURL, "show-policy-url", 0, "@" },
608 { oNoShowPolicyURL, "no-show-policy-url", 0, "@" },
609 { oSigKeyserverURL, "sig-keyserver-url", 2, "@" },
610 { oShowNotation, "show-notation", 0, "@" },
611 { oNoShowNotation, "no-show-notation", 0, "@" },
612 { oComment, "comment", 2, "@" },
613 { oDefaultComment, "default-comment", 0, "@" },
614 { oNoComments, "no-comments", 0, "@" },
615 { oEmitVersion, "emit-version", 0, "@"},
616 { oNoEmitVersion, "no-emit-version", 0, "@"},
617 { oNoEmitVersion, "no-version", 0, "@"}, /* alias */
618 { oNotDashEscaped, "not-dash-escaped", 0, "@" },
619 { oEscapeFrom, "escape-from-lines", 0, "@" },
620 { oNoEscapeFrom, "no-escape-from-lines", 0, "@" },
621 { oLockOnce, "lock-once", 0, "@" },
622 { oLockMultiple, "lock-multiple", 0, "@" },
623 { oLockNever, "lock-never", 0, "@" },
624 { oLoggerFD, "logger-fd",1, "@" },
625 { oLoggerFile, "log-file",2, "@" },
626 { oLoggerFile, "logger-file",2, "@" }, /* For 1.4 compatibility. */
627 { oUseEmbeddedFilename, "use-embedded-filename", 0, "@" },
628 { oNoUseEmbeddedFilename, "no-use-embedded-filename", 0, "@" },
629 { oUtf8Strings, "utf8-strings", 0, "@" },
630 { oNoUtf8Strings, "no-utf8-strings", 0, "@" },
631 { oWithFingerprint, "with-fingerprint", 0, "@" },
632 { oDisableCipherAlgo, "disable-cipher-algo", 2, "@" },
633 { oDisablePubkeyAlgo, "disable-pubkey-algo", 2, "@" },
634 { oAllowNonSelfsignedUID, "allow-non-selfsigned-uid", 0, "@" },
635 { oNoAllowNonSelfsignedUID, "no-allow-non-selfsigned-uid", 0, "@" },
636 { oAllowFreeformUID, "allow-freeform-uid", 0, "@" },
637 { oNoAllowFreeformUID, "no-allow-freeform-uid", 0, "@" },
638 { oNoLiteral, "no-literal", 0, "@" },
639 { oSetFilesize, "set-filesize", 20, "@" },
640 { oHonorHttpProxy,"honor-http-proxy", 0, "@" },
641 { oFastListMode,"fast-list-mode", 0, "@" },
642 { oFixedListMode,"fixed-list-mode", 0, "@" },
643 { oListOnly, "list-only", 0, "@"},
644 { oIgnoreTimeConflict, "ignore-time-conflict", 0, "@" },
645 { oIgnoreValidFrom, "ignore-valid-from", 0, "@" },
646 { oIgnoreCrcError, "ignore-crc-error", 0,"@" },
647 { oIgnoreMDCError, "ignore-mdc-error", 0,"@" },
648 { oShowSessionKey, "show-session-key", 0, "@" },
649 { oOverrideSessionKey, "override-session-key", 2, "@" },
650 { oNoRandomSeedFile, "no-random-seed-file", 0, "@" },
651 { oAutoKeyRetrieve, "auto-key-retrieve", 0, "@" },
652 { oNoAutoKeyRetrieve, "no-auto-key-retrieve", 0, "@" },
653 { oNoSigCache, "no-sig-cache", 0, "@" },
654 { oNoSigCreateCheck, "no-sig-create-check", 0, "@" },
655 { oAutoCheckTrustDB, "auto-check-trustdb", 0, "@"},
656 { oNoAutoCheckTrustDB, "no-auto-check-trustdb", 0, "@"},
657 { oMergeOnly, "merge-only", 0, "@" },
658 { oAllowSecretKeyImport, "allow-secret-key-import", 0, "@" },
659 { oTryAllSecrets, "try-all-secrets", 0, "@" },
660 { oEnableSpecialFilenames, "enable-special-filenames", 0, "@" },
661 { oNoExpensiveTrustChecks, "no-expensive-trust-checks", 0, "@" },
662 { aDeleteSecretAndPublicKeys, "delete-secret-and-public-keys",256, "@" },
663 { aRebuildKeydbCaches, "rebuild-keydb-caches", 256, "@"},
664 { oPreservePermissions, "preserve-permissions", 0, "@"},
665 { oDefaultPreferenceList, "default-preference-list", 2, "@"},
666 { oDefaultKeyserverURL, "default-keyserver-url", 2, "@"},
667 { oPersonalCipherPreferences, "personal-cipher-preferences", 2, "@"},
668 { oPersonalDigestPreferences, "personal-digest-preferences", 2, "@"},
669 { oPersonalCompressPreferences, "personal-compress-preferences", 2, "@"},
670 /* Aliases. I constantly mistype these, and assume other people
671 do as well. */
672 { oPersonalCipherPreferences, "personal-cipher-prefs", 2, "@"},
673 { oPersonalDigestPreferences, "personal-digest-prefs", 2, "@"},
674 { oPersonalCompressPreferences, "personal-compress-prefs", 2, "@"},
675 { oAgentProgram, "agent-program", 2 , "@" },
676 { oDisplay, "display", 2, "@" },
677 { oTTYname, "ttyname", 2, "@" },
678 { oTTYtype, "ttytype", 2, "@" },
679 { oLCctype, "lc-ctype", 2, "@" },
680 { oLCmessages, "lc-messages", 2, "@" },
681 { oXauthority, "xauthority", 2, "@" },
682 { oGroup, "group", 2, "@" },
683 { oUnGroup, "ungroup", 2, "@" },
684 { oNoGroups, "no-groups", 0, "@" },
685 { oStrict, "strict", 0, "@" },
686 { oNoStrict, "no-strict", 0, "@" },
687 { oMangleDosFilenames, "mangle-dos-filenames", 0, "@" },
688 { oNoMangleDosFilenames, "no-mangle-dos-filenames", 0, "@" },
689 { oEnableProgressFilter, "enable-progress-filter", 0, "@" },
690 { oMultifile, "multifile", 0, "@" },
691 { oKeyidFormat, "keyid-format", 2, "@" },
692 { oExitOnStatusWriteError, "exit-on-status-write-error", 0, "@" },
693 { oLimitCardInsertTries, "limit-card-insert-tries", 1, "@"},
695 { oAllowMultisigVerification, "allow-multisig-verification", 0, "@"},
696 { oEnableDSA2, "enable-dsa2", 0, "@"},
697 { oDisableDSA2, "disable-dsa2", 0, "@"},
698 { oAllowMultipleMessages, "allow-multiple-messages", 0, "@"},
699 { oNoAllowMultipleMessages, "no-allow-multiple-messages", 0, "@"},
701 /* These two are aliases to help users of the PGP command line
702 product use gpg with minimal pain. Many commands are common
703 already as they seem to have borrowed commands from us. Now
704 I'm returning the favor. */
705 { oLocalUser, "sign-with", 2, "@" },
706 { oRecipient, "user", 2, "@" },
707 { oRequireCrossCert, "require-backsigs", 0, "@"},
708 { oRequireCrossCert, "require-cross-certification", 0, "@"},
709 { oNoRequireCrossCert, "no-require-backsigs", 0, "@"},
710 { oNoRequireCrossCert, "no-require-cross-certification", 0, "@"},
711 { oAutoKeyLocate, "auto-key-locate", 2, "@"},
712 { oNoAutoKeyLocate, "no-auto-key-locate", 0, "@"},
714 {0,NULL,0,NULL}
718 #ifdef ENABLE_SELINUX_HACKS
719 #define ALWAYS_ADD_KEYRINGS 1
720 #else
721 #define ALWAYS_ADD_KEYRINGS 0
722 #endif
725 int g10_errors_seen = 0;
727 static int utf8_strings = 0;
728 static int maybe_setuid = 1;
730 static char *build_list( const char *text, char letter,
731 const char *(*mapf)(int), int (*chkf)(int) );
732 static char *build_lib_list (const char *text);
733 static void set_cmd( enum cmd_and_opt_values *ret_cmd,
734 enum cmd_and_opt_values new_cmd );
735 static void print_mds( const char *fname, int algo );
736 static void add_notation_data( const char *string, int which );
737 static void add_policy_url( const char *string, int which );
738 static void add_keyserver_url( const char *string, int which );
739 static void emergency_cleanup (void);
742 static const char *
743 my_strusage( int level )
745 static char *digests, *pubkeys, *ciphers, *zips, *libs;
746 const char *p;
747 switch( level ) {
748 case 11: p = "gpg (GnuPG)";
749 break;
750 case 13: p = VERSION; break;
751 case 17: p = PRINTABLE_OS_NAME; break;
752 case 19: p =
753 _("Please report bugs to <gnupg-bugs@gnu.org>.\n");
754 break;
756 #ifdef IS_DEVELOPMENT_VERSION
757 case 20:
758 p="NOTE: THIS IS A DEVELOPMENT VERSION!";
759 break;
760 case 21:
761 p="It is only intended for test purposes and should NOT be";
762 break;
763 case 22:
764 p="used in a production environment or with production keys!";
765 break;
766 #endif
768 case 1:
769 case 40: p =
770 _("Usage: gpg [options] [files] (-h for help)");
771 break;
772 case 41: p =
773 _("Syntax: gpg [options] [files]\n"
774 "sign, check, encrypt or decrypt\n"
775 "default operation depends on the input data\n");
776 break;
778 case 31: p = "\nHome: "; break;
779 #ifndef __riscos__
780 case 32: p = opt.homedir; break;
781 #else /* __riscos__ */
782 case 32: p = make_filename(opt.homedir, NULL); break;
783 #endif /* __riscos__ */
784 case 33: p = _("\nSupported algorithms:\n"); break;
785 case 34:
786 if (!pubkeys)
787 pubkeys = build_list (_("Pubkey: "), 0,
788 gcry_pk_algo_name,
789 openpgp_pk_test_algo );
790 p = pubkeys;
791 break;
792 case 35:
793 if( !ciphers )
794 ciphers = build_list(_("Cipher: "), 'S',
795 openpgp_cipher_algo_name,
796 openpgp_cipher_test_algo );
797 p = ciphers;
798 break;
799 case 36:
800 if( !digests )
801 digests = build_list(_("Hash: "), 'H',
802 gcry_md_algo_name,
803 openpgp_md_test_algo );
804 p = digests;
805 break;
806 case 37:
807 if( !zips )
808 zips = build_list(_("Compression: "),'Z',
809 compress_algo_to_string,
810 check_compress_algo);
811 p = zips;
812 break;
813 case 38:
814 if (!libs)
815 libs = build_lib_list(_("Used libraries:"));
816 p = libs;
817 break;
819 default: p = NULL;
821 return p;
825 static char *
826 build_list( const char *text, char letter,
827 const char * (*mapf)(int), int (*chkf)(int) )
829 int i;
830 const char *s;
831 size_t n=strlen(text)+2;
832 char *list, *p, *line=NULL;
834 if (maybe_setuid)
835 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
837 for(i=0; i <= 110; i++ )
838 if( !chkf(i) && (s=mapf(i)) )
839 n += strlen(s) + 7 + 2;
840 list = xmalloc( 21 + n ); *list = 0;
841 for(p=NULL, i=0; i <= 110; i++ ) {
842 if( !chkf(i) && (s=mapf(i)) ) {
843 if( !p ) {
844 p = stpcpy( list, text );
845 line=p;
847 else
848 p = stpcpy( p, ", ");
850 if(strlen(line)>60) {
851 int spaces=strlen(text);
853 list=xrealloc(list,n+spaces+1);
854 /* realloc could move the block, so find the end again */
855 p=list;
856 while(*p)
857 p++;
859 p=stpcpy(p, "\n");
860 line=p;
861 for(;spaces;spaces--)
862 p=stpcpy(p, " ");
865 p = stpcpy(p, s );
866 if(opt.verbose && letter)
868 char num[8];
869 sprintf(num," (%c%d)",letter,i);
870 p = stpcpy(p,num);
874 if( p )
875 p = stpcpy(p, "\n" );
876 return list;
880 static char *
881 build_lib_list (const char *text)
883 struct { const char *name; const char *version; } array[3];
884 int idx;
885 size_t n;
886 char *list, *p;
888 if (maybe_setuid)
889 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
891 idx = 0;
892 array[idx].name = "gcrypt";
893 array[idx++].version = gcry_check_version (NULL);
894 array[idx].name = NULL;
895 array[idx++].version = NULL;
897 n = strlen (text) + 1;
898 for (idx=0; array[idx].name; idx++)
900 n += 2 + strlen (array[idx].name);
901 if (array[idx].version)
902 n += 1 + strlen (array[idx].version) + 1;
904 n++;
905 list = xmalloc (n+1);
906 p = stpcpy (stpcpy (list, text), " ");
907 for (idx=0; array[idx].name; idx++)
909 if (idx)
910 p = stpcpy (p, ", ");
911 p = stpcpy (p, array[idx].name);
912 if (array[idx].version)
913 p = stpcpy (stpcpy (stpcpy (p, "("), array[idx].version), ")");
915 strcpy (p, "\n");
916 return list;
920 static void
921 wrong_args( const char *text)
923 fputs(_("usage: gpg [options] "),stderr);
924 fputs(text,stderr);
925 putc('\n',stderr);
926 g10_exit(2);
930 static char *
931 make_username( const char *string )
933 char *p;
934 if( utf8_strings )
935 p = xstrdup(string);
936 else
937 p = native_to_utf8( string );
938 return p;
942 /* Setup the debugging. With a LEVEL of NULL only the active debug
943 flags are propagated to the subsystems. With LEVEL set, a specific
944 set of debug flags is set; thus overriding all flags already
945 set. */
946 static void
947 set_debug (const char *level)
949 if (!level)
951 else if (!strcmp (level, "none"))
952 opt.debug = 0;
953 else if (!strcmp (level, "basic"))
954 opt.debug = DBG_MEMSTAT_VALUE;
955 else if (!strcmp (level, "advanced"))
956 opt.debug = DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE;
957 else if (!strcmp (level, "expert"))
958 opt.debug = (DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE
959 |DBG_CACHE_VALUE|DBG_FILTER_VALUE|DBG_PACKET_VALUE);
960 else if (!strcmp (level, "guru"))
961 opt.debug = ~0;
962 else
964 log_error (_("invalid debug-level `%s' given\n"), level);
965 g10_exit (2);
968 if (opt.debug & DBG_MEMORY_VALUE )
969 memory_debug_mode = 1;
970 if (opt.debug & DBG_MEMSTAT_VALUE )
971 memory_stat_debug_mode = 1;
972 if (opt.debug & DBG_MPI_VALUE)
973 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
974 if (opt.debug & DBG_CIPHER_VALUE )
975 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
976 if (opt.debug & DBG_IOBUF_VALUE )
977 iobuf_debug_mode = 1;
978 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
983 /* We need the home directory also in some other directories, so make
984 sure that both variables are always in sync. */
985 static void
986 set_homedir (const char *dir)
988 if (!dir)
989 dir = "";
990 opt.homedir = dir;
994 /* We set the screen dimensions for UI purposes. Do not allow screens
995 smaller than 80x24 for the sake of simplicity. */
996 static void
997 set_screen_dimensions(void)
999 #ifndef HAVE_W32_SYSTEM
1000 char *str;
1002 str=getenv("COLUMNS");
1003 if(str)
1004 opt.screen_columns=atoi(str);
1006 str=getenv("LINES");
1007 if(str)
1008 opt.screen_lines=atoi(str);
1009 #endif
1011 if(opt.screen_columns<80 || opt.screen_columns>255)
1012 opt.screen_columns=80;
1014 if(opt.screen_lines<24 || opt.screen_lines>255)
1015 opt.screen_lines=24;
1019 /* Helper to open a file FNAME either for reading or writing to be
1020 used with --status-file etc functions. Not generally useful but it
1021 avoids the riscos specific functions and well some Windows people
1022 might like it too. Prints an error message and returns -1 on
1023 error. On success the file descriptor is returned. */
1024 static int
1025 open_info_file (const char *fname, int for_write)
1027 #ifdef __riscos__
1028 return riscos_fdopenfile (fname, for_write);
1029 #elif defined (ENABLE_SELINUX_HACKS)
1030 /* We can't allow these even when testing for a secured filename
1031 because files to be secured might not yet been secured. This is
1032 similar to the option file but in that case it is unlikely that
1033 sensitive information may be retrieved by means of error
1034 messages. */
1035 return -1;
1036 #else
1037 int fd;
1039 /* if (is_secured_filename (fname)) */
1040 /* { */
1041 /* fd = -1; */
1042 /* errno = EPERM; */
1043 /* } */
1044 /* else */
1045 /* { */
1048 if (for_write)
1049 fd = open (fname, O_CREAT | O_TRUNC | O_WRONLY,
1050 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
1051 else
1052 fd = open (fname, O_RDONLY | MY_O_BINARY);
1054 while (fd == -1 && errno == EINTR);
1055 /* } */
1056 if ( fd == -1)
1057 log_error ( for_write? _("can't create `%s': %s\n")
1058 : _("can't open `%s': %s\n"), fname, strerror(errno));
1060 return fd;
1061 #endif
1064 static void
1065 set_cmd( enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd )
1067 enum cmd_and_opt_values cmd = *ret_cmd;
1069 if( !cmd || cmd == new_cmd )
1070 cmd = new_cmd;
1071 else if( cmd == aSign && new_cmd == aEncr )
1072 cmd = aSignEncr;
1073 else if( cmd == aEncr && new_cmd == aSign )
1074 cmd = aSignEncr;
1075 else if( cmd == aSign && new_cmd == aSym )
1076 cmd = aSignSym;
1077 else if( cmd == aSym && new_cmd == aSign )
1078 cmd = aSignSym;
1079 else if( cmd == aSym && new_cmd == aEncr )
1080 cmd = aEncrSym;
1081 else if( cmd == aEncr && new_cmd == aSym )
1082 cmd = aEncrSym;
1083 else if (cmd == aSignEncr && new_cmd == aSym)
1084 cmd = aSignEncrSym;
1085 else if (cmd == aSignSym && new_cmd == aEncr)
1086 cmd = aSignEncrSym;
1087 else if (cmd == aEncrSym && new_cmd == aSign)
1088 cmd = aSignEncrSym;
1089 else if( ( cmd == aSign && new_cmd == aClearsign )
1090 || ( cmd == aClearsign && new_cmd == aSign ) )
1091 cmd = aClearsign;
1092 else {
1093 log_error(_("conflicting commands\n"));
1094 g10_exit(2);
1097 *ret_cmd = cmd;
1101 static void
1102 add_group(char *string)
1104 char *name,*value;
1105 struct groupitem *item;
1107 /* Break off the group name */
1108 name=strsep(&string,"=");
1109 if(string==NULL)
1111 log_error(_("no = sign found in group definition `%s'\n"),name);
1112 return;
1115 trim_trailing_ws(name,strlen(name));
1117 /* Does this group already exist? */
1118 for(item=opt.grouplist;item;item=item->next)
1119 if(strcasecmp(item->name,name)==0)
1120 break;
1122 if(!item)
1124 item=xmalloc(sizeof(struct groupitem));
1125 item->name=name;
1126 item->next=opt.grouplist;
1127 item->values=NULL;
1128 opt.grouplist=item;
1131 /* Break apart the values */
1132 while ((value= strsep(&string," \t")))
1134 if (*value)
1135 add_to_strlist2(&item->values,value,utf8_strings);
1140 static void
1141 rm_group(char *name)
1143 struct groupitem *item,*last=NULL;
1145 trim_trailing_ws(name,strlen(name));
1147 for(item=opt.grouplist;item;last=item,item=item->next)
1149 if(strcasecmp(item->name,name)==0)
1151 if(last)
1152 last->next=item->next;
1153 else
1154 opt.grouplist=item->next;
1156 free_strlist(item->values);
1157 xfree(item);
1158 break;
1164 /* We need to check three things.
1166 0) The homedir. It must be x00, a directory, and owned by the
1167 user.
1169 1) The options/gpg.conf file. Okay unless it or its containing
1170 directory is group or other writable or not owned by us. Disable
1171 exec in this case.
1173 2) Extensions. Same as #1.
1175 Returns true if the item is unsafe. */
1176 static int
1177 check_permissions(const char *path,int item)
1179 #if defined(HAVE_STAT) && !defined(HAVE_DOSISH_SYSTEM)
1180 static int homedir_cache=-1;
1181 char *tmppath,*dir;
1182 struct stat statbuf,dirbuf;
1183 int homedir=0,ret=0,checkonly=0;
1184 int perm=0,own=0,enc_dir_perm=0,enc_dir_own=0;
1186 if(opt.no_perm_warn)
1187 return 0;
1189 assert(item==0 || item==1 || item==2);
1191 /* extensions may attach a path */
1192 if(item==2 && path[0]!=DIRSEP_C)
1194 if(strchr(path,DIRSEP_C))
1195 tmppath=make_filename(path,NULL);
1196 else
1197 tmppath=make_filename(gnupg_libdir (),path,NULL);
1199 else
1200 tmppath=xstrdup(path);
1202 /* If the item is located in the homedir, but isn't the homedir,
1203 don't continue if we already checked the homedir itself. This is
1204 to avoid user confusion with an extra options file warning which
1205 could be rectified if the homedir itself had proper
1206 permissions. */
1207 if(item!=0 && homedir_cache>-1
1208 && ascii_strncasecmp(opt.homedir,tmppath,strlen(opt.homedir))==0)
1210 ret=homedir_cache;
1211 goto end;
1214 /* It's okay if the file or directory doesn't exist */
1215 if(stat(tmppath,&statbuf)!=0)
1217 ret=0;
1218 goto end;
1221 /* Now check the enclosing directory. Theoretically, we could walk
1222 this test up to the root directory /, but for the sake of sanity,
1223 I'm stopping at one level down. */
1224 dir=make_dirname(tmppath);
1226 if(stat(dir,&dirbuf)!=0 || !S_ISDIR(dirbuf.st_mode))
1228 /* Weird error */
1229 ret=1;
1230 goto end;
1233 xfree(dir);
1235 /* Assume failure */
1236 ret=1;
1238 if(item==0)
1240 /* The homedir must be x00, a directory, and owned by the user. */
1242 if(S_ISDIR(statbuf.st_mode))
1244 if(statbuf.st_uid==getuid())
1246 if((statbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1247 ret=0;
1248 else
1249 perm=1;
1251 else
1252 own=1;
1254 homedir_cache=ret;
1257 else if(item==1 || item==2)
1259 /* The options or extension file. Okay unless it or its
1260 containing directory is group or other writable or not owned
1261 by us or root. */
1263 if(S_ISREG(statbuf.st_mode))
1265 if(statbuf.st_uid==getuid() || statbuf.st_uid==0)
1267 if((statbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1269 /* it's not writable, so make sure the enclosing
1270 directory is also not writable */
1271 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1273 if((dirbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1274 ret=0;
1275 else
1276 enc_dir_perm=1;
1278 else
1279 enc_dir_own=1;
1281 else
1283 /* it's writable, so the enclosing directory had
1284 better not let people get to it. */
1285 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1287 if((dirbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1288 ret=0;
1289 else
1290 perm=enc_dir_perm=1; /* unclear which one to fix! */
1292 else
1293 enc_dir_own=1;
1296 else
1297 own=1;
1300 else
1301 BUG();
1303 if(!checkonly)
1305 if(own)
1307 if(item==0)
1308 log_info(_("WARNING: unsafe ownership on"
1309 " homedir `%s'\n"),tmppath);
1310 else if(item==1)
1311 log_info(_("WARNING: unsafe ownership on"
1312 " configuration file `%s'\n"),tmppath);
1313 else
1314 log_info(_("WARNING: unsafe ownership on"
1315 " extension `%s'\n"),tmppath);
1317 if(perm)
1319 if(item==0)
1320 log_info(_("WARNING: unsafe permissions on"
1321 " homedir `%s'\n"),tmppath);
1322 else if(item==1)
1323 log_info(_("WARNING: unsafe permissions on"
1324 " configuration file `%s'\n"),tmppath);
1325 else
1326 log_info(_("WARNING: unsafe permissions on"
1327 " extension `%s'\n"),tmppath);
1329 if(enc_dir_own)
1331 if(item==0)
1332 log_info(_("WARNING: unsafe enclosing directory ownership on"
1333 " homedir `%s'\n"),tmppath);
1334 else if(item==1)
1335 log_info(_("WARNING: unsafe enclosing directory ownership on"
1336 " configuration file `%s'\n"),tmppath);
1337 else
1338 log_info(_("WARNING: unsafe enclosing directory ownership on"
1339 " extension `%s'\n"),tmppath);
1341 if(enc_dir_perm)
1343 if(item==0)
1344 log_info(_("WARNING: unsafe enclosing directory permissions on"
1345 " homedir `%s'\n"),tmppath);
1346 else if(item==1)
1347 log_info(_("WARNING: unsafe enclosing directory permissions on"
1348 " configuration file `%s'\n"),tmppath);
1349 else
1350 log_info(_("WARNING: unsafe enclosing directory permissions on"
1351 " extension `%s'\n"),tmppath);
1355 end:
1356 xfree(tmppath);
1358 if(homedir)
1359 homedir_cache=ret;
1361 return ret;
1363 #endif /* HAVE_STAT && !HAVE_DOSISH_SYSTEM */
1365 return 0;
1369 static void
1370 print_algo_numbers(int (*checker)(int))
1372 int i,first=1;
1374 for(i=0;i<=110;i++)
1376 if(!checker(i))
1378 if(first)
1379 first=0;
1380 else
1381 printf(";");
1382 printf("%d",i);
1388 static void
1389 print_algo_names(int (*checker)(int),const char *(*mapper)(int))
1391 int i,first=1;
1393 for(i=0;i<=110;i++)
1395 if(!checker(i))
1397 if(first)
1398 first=0;
1399 else
1400 printf(";");
1401 printf("%s",mapper(i));
1406 /* In the future, we can do all sorts of interesting configuration
1407 output here. For now, just give "group" as the Enigmail folks need
1408 it, and pubkey, cipher, hash, and compress as they may be useful
1409 for frontends. */
1410 static void
1411 list_config(char *items)
1413 int show_all=(items==NULL);
1414 char *name=NULL;
1416 if(!opt.with_colons)
1417 return;
1419 while(show_all || (name=strsep(&items," ")))
1421 int any=0;
1423 if(show_all || ascii_strcasecmp(name,"group")==0)
1425 struct groupitem *iter;
1427 for(iter=opt.grouplist;iter;iter=iter->next)
1429 strlist_t sl;
1431 printf("cfg:group:");
1432 print_string(stdout,iter->name,strlen(iter->name),':');
1433 printf(":");
1435 for(sl=iter->values;sl;sl=sl->next)
1437 print_sanitized_string2 (stdout, sl->d, ':',';');
1438 if(sl->next)
1439 printf(";");
1442 printf("\n");
1445 any=1;
1448 if(show_all || ascii_strcasecmp(name,"version")==0)
1450 printf("cfg:version:");
1451 print_string(stdout,VERSION,strlen(VERSION),':');
1452 printf("\n");
1453 any=1;
1456 if(show_all || ascii_strcasecmp(name,"pubkey")==0)
1458 printf("cfg:pubkey:");
1459 print_algo_numbers (openpgp_pk_test_algo);
1460 printf("\n");
1461 any=1;
1464 if(show_all || ascii_strcasecmp(name,"cipher")==0)
1466 printf("cfg:cipher:");
1467 print_algo_numbers(openpgp_cipher_test_algo);
1468 printf("\n");
1469 any=1;
1472 if (show_all || !ascii_strcasecmp (name,"ciphername"))
1474 printf ("cfg:ciphername:");
1475 print_algo_names (openpgp_cipher_test_algo,openpgp_cipher_algo_name);
1476 printf ("\n");
1477 any = 1;
1480 if(show_all
1481 || ascii_strcasecmp(name,"digest")==0
1482 || ascii_strcasecmp(name,"hash")==0)
1484 printf("cfg:digest:");
1485 print_algo_numbers(openpgp_md_test_algo);
1486 printf("\n");
1487 any=1;
1490 if (show_all
1491 || !ascii_strcasecmp(name,"digestname")
1492 || !ascii_strcasecmp(name,"hashname"))
1494 printf ("cfg:digestname:");
1495 print_algo_names (openpgp_md_test_algo, gcry_md_algo_name);
1496 printf("\n");
1497 any=1;
1500 if(show_all || ascii_strcasecmp(name,"compress")==0)
1502 printf("cfg:compress:");
1503 print_algo_numbers(check_compress_algo);
1504 printf("\n");
1505 any=1;
1508 if(show_all || ascii_strcasecmp(name,"ccid-reader-id")==0)
1510 #if defined(ENABLE_CARD_SUPPORT) && defined(HAVE_LIBUSB) \
1511 && GNUPG_MAJOR_VERSION == 1
1513 char *p, *p2, *list = ccid_get_reader_list ();
1515 for (p=list; p && (p2 = strchr (p, '\n')); p = p2+1)
1517 *p2 = 0;
1518 printf("cfg:ccid-reader-id:%s\n", p);
1520 free (list);
1521 #endif
1522 any=1;
1525 if(show_all)
1526 break;
1528 if(!any)
1529 log_error(_("unknown configuration item `%s'\n"),name);
1534 /* List options and default values in the GPG Conf format. This is a
1535 new tool distributed with gnupg 1.9.x but we also want some limited
1536 support in older gpg versions. The output is the name of the
1537 configuration file and a list of options available for editing by
1538 gpgconf. */
1539 static void
1540 gpgconf_list (const char *configfile)
1542 char *configfile_esc = percent_escape (configfile, NULL);
1544 printf ("gpgconf-gpg.conf:%lu:\"%s\n",
1545 GC_OPT_FLAG_DEFAULT, configfile_esc ? configfile_esc : "/dev/null");
1546 printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
1547 printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
1548 printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
1549 printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE);
1550 printf ("default-key:%lu:\n", GC_OPT_FLAG_NONE);
1551 printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_NONE);
1553 xfree (configfile_esc);
1557 static int
1558 parse_subpacket_list(char *list)
1560 char *tok;
1561 byte subpackets[128],i;
1562 int count=0;
1564 if(!list)
1566 /* No arguments means all subpackets */
1567 memset(subpackets+1,1,sizeof(subpackets)-1);
1568 count=127;
1570 else
1572 memset(subpackets,0,sizeof(subpackets));
1574 /* Merge with earlier copy */
1575 if(opt.show_subpackets)
1577 byte *in;
1579 for(in=opt.show_subpackets;*in;in++)
1581 if(*in>127 || *in<1)
1582 BUG();
1584 if(!subpackets[*in])
1585 count++;
1586 subpackets[*in]=1;
1590 while((tok=strsep(&list," ,")))
1592 if(!*tok)
1593 continue;
1595 i=atoi(tok);
1596 if(i>127 || i<1)
1597 return 0;
1599 if(!subpackets[i])
1600 count++;
1601 subpackets[i]=1;
1605 xfree(opt.show_subpackets);
1606 opt.show_subpackets=xmalloc(count+1);
1607 opt.show_subpackets[count--]=0;
1609 for(i=1;i<128 && count>=0;i++)
1610 if(subpackets[i])
1611 opt.show_subpackets[count--]=i;
1613 return 1;
1617 static int
1618 parse_list_options(char *str)
1620 char *subpackets=""; /* something that isn't NULL */
1621 struct parse_options lopts[]=
1623 {"show-photos",LIST_SHOW_PHOTOS,NULL,
1624 N_("display photo IDs during key listings")},
1625 {"show-policy-urls",LIST_SHOW_POLICY_URLS,NULL,
1626 N_("show policy URLs during signature listings")},
1627 {"show-notations",LIST_SHOW_NOTATIONS,NULL,
1628 N_("show all notations during signature listings")},
1629 {"show-std-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1630 N_("show IETF standard notations during signature listings")},
1631 {"show-standard-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1632 NULL},
1633 {"show-user-notations",LIST_SHOW_USER_NOTATIONS,NULL,
1634 N_("show user-supplied notations during signature listings")},
1635 {"show-keyserver-urls",LIST_SHOW_KEYSERVER_URLS,NULL,
1636 N_("show preferred keyserver URLs during signature listings")},
1637 {"show-uid-validity",LIST_SHOW_UID_VALIDITY,NULL,
1638 N_("show user ID validity during key listings")},
1639 {"show-unusable-uids",LIST_SHOW_UNUSABLE_UIDS,NULL,
1640 N_("show revoked and expired user IDs in key listings")},
1641 {"show-unusable-subkeys",LIST_SHOW_UNUSABLE_SUBKEYS,NULL,
1642 N_("show revoked and expired subkeys in key listings")},
1643 {"show-keyring",LIST_SHOW_KEYRING,NULL,
1644 N_("show the keyring name in key listings")},
1645 {"show-sig-expire",LIST_SHOW_SIG_EXPIRE,NULL,
1646 N_("show expiration dates during signature listings")},
1647 {"show-sig-subpackets",LIST_SHOW_SIG_SUBPACKETS,NULL,
1648 NULL},
1649 {NULL,0,NULL,NULL}
1652 /* C99 allows for non-constant initializers, but we'd like to
1653 compile everywhere, so fill in the show-sig-subpackets argument
1654 here. Note that if the parse_options array changes, we'll have
1655 to change the subscript here. */
1656 lopts[12].value=&subpackets;
1658 if(parse_options(str,&opt.list_options,lopts,1))
1660 if(opt.list_options&LIST_SHOW_SIG_SUBPACKETS)
1662 /* Unset so users can pass multiple lists in. */
1663 opt.list_options&=~LIST_SHOW_SIG_SUBPACKETS;
1664 if(!parse_subpacket_list(subpackets))
1665 return 0;
1667 else if(subpackets==NULL && opt.show_subpackets)
1669 /* User did 'no-show-subpackets' */
1670 xfree(opt.show_subpackets);
1671 opt.show_subpackets=NULL;
1674 return 1;
1676 else
1677 return 0;
1681 /* Collapses argc/argv into a single string that must be freed */
1682 static char *
1683 collapse_args(int argc,char *argv[])
1685 char *str=NULL;
1686 int i,first=1,len=0;
1688 for(i=0;i<argc;i++)
1690 len+=strlen(argv[i])+2;
1691 str=xrealloc(str,len);
1692 if(first)
1694 str[0]='\0';
1695 first=0;
1697 else
1698 strcat(str," ");
1700 strcat(str,argv[i]);
1703 return str;
1706 static void
1707 parse_trust_model(const char *model)
1709 if(ascii_strcasecmp(model,"pgp")==0)
1710 opt.trust_model=TM_PGP;
1711 else if(ascii_strcasecmp(model,"classic")==0)
1712 opt.trust_model=TM_CLASSIC;
1713 else if(ascii_strcasecmp(model,"always")==0)
1714 opt.trust_model=TM_ALWAYS;
1715 else if(ascii_strcasecmp(model,"direct")==0)
1716 opt.trust_model=TM_DIRECT;
1717 else if(ascii_strcasecmp(model,"auto")==0)
1718 opt.trust_model=TM_AUTO;
1719 else
1720 log_error("unknown trust model `%s'\n",model);
1724 /* Pack an s2k iteration count into the form specified in 2440. If
1725 we're in between valid values, round up. */
1726 static unsigned char
1727 encode_s2k_iterations(int iterations)
1729 unsigned char c=0,result;
1730 unsigned int count;
1732 if(iterations<=1024)
1733 return 0;
1735 if(iterations>=65011712)
1736 return 255;
1738 /* Need count to be in the range 16-31 */
1739 for(count=iterations>>6;count>=32;count>>=1)
1740 c++;
1742 result=(c<<4)|(count-16);
1744 if(S2K_DECODE_COUNT(result)<iterations)
1745 result++;
1747 return result;
1751 /* This fucntion called to initialized a new control object. It is
1752 assumed that this object has been zeroed out before calling this
1753 function. */
1754 static void
1755 gpg_init_default_ctrl (ctrl_t ctrl)
1760 /* This function is called to deinitialize a control object. It is
1761 not deallocated. */
1762 static void
1763 gpg_deinit_default_ctrl (ctrl_t ctrl)
1768 char *
1769 get_default_configname (void)
1771 char *configname = NULL;
1772 char *name = xstrdup ("gpg" EXTSEP_S "conf-" SAFE_VERSION);
1773 char *ver = &name[strlen ("gpg" EXTSEP_S "conf-")];
1777 if (configname)
1779 char *tok;
1781 xfree (configname);
1782 configname = NULL;
1784 if ((tok = strrchr (ver, SAFE_VERSION_DASH)))
1785 *tok='\0';
1786 else if ((tok = strrchr (ver, SAFE_VERSION_DOT)))
1787 *tok='\0';
1788 else
1789 break;
1792 configname = make_filename (opt.homedir, name, NULL);
1794 while (access (configname, R_OK));
1796 xfree(name);
1798 if (! configname)
1799 configname = make_filename (opt.homedir, "gpg" EXTSEP_S "conf", NULL);
1800 if (! access (configname, R_OK))
1802 /* Print a warning when both config files are present. */
1803 char *p = make_filename (opt.homedir, "options", NULL);
1804 if (! access (p, R_OK))
1805 log_info (_("NOTE: old default options file `%s' ignored\n"), p);
1806 xfree (p);
1808 else
1810 /* Use the old default only if it exists. */
1811 char *p = make_filename (opt.homedir, "options", NULL);
1812 if (!access (p, R_OK))
1814 xfree (configname);
1815 configname = p;
1817 else
1818 xfree (p);
1821 return configname;
1826 main (int argc, char **argv)
1828 ARGPARSE_ARGS pargs;
1829 IOBUF a;
1830 int rc=0;
1831 int orig_argc;
1832 char **orig_argv;
1833 const char *fname;
1834 char *username;
1835 int may_coredump;
1836 strlist_t sl, remusr= NULL, locusr=NULL;
1837 strlist_t nrings=NULL, sec_nrings=NULL;
1838 armor_filter_context_t *afx = NULL;
1839 int detached_sig = 0;
1840 FILE *configfp = NULL;
1841 char *configname = NULL;
1842 char *save_configname = NULL;
1843 char *default_configname = NULL;
1844 unsigned configlineno;
1845 int parse_debug = 0;
1846 int default_config = 1;
1847 int default_keyring = 1;
1848 int greeting = 0;
1849 int nogreeting = 0;
1850 char *logfile = NULL;
1851 int use_random_seed = 1;
1852 enum cmd_and_opt_values cmd = 0;
1853 const char *debug_level = NULL;
1854 const char *trustdb_name = NULL;
1855 char *def_cipher_string = NULL;
1856 char *def_digest_string = NULL;
1857 char *compress_algo_string = NULL;
1858 char *cert_digest_string = NULL;
1859 char *s2k_cipher_string = NULL;
1860 char *s2k_digest_string = NULL;
1861 char *pers_cipher_list = NULL;
1862 char *pers_digest_list = NULL;
1863 char *pers_compress_list = NULL;
1864 int eyes_only=0;
1865 int multifile=0;
1866 int pwfd = -1;
1867 int with_fpr = 0; /* make an option out of --fingerprint */
1868 int any_explicit_recipient = 0;
1869 int require_secmem=0,got_secmem=0;
1871 #ifdef __riscos__
1872 opt.lock_once = 1;
1873 #endif /* __riscos__ */
1876 /* Please note that we may running SUID(ROOT), so be very CAREFUL
1877 when adding any stuff between here and the call to
1878 secmem_init() somewhere after the option parsing. */
1879 gnupg_reopen_std ("gpg");
1880 trap_unaligned ();
1881 gnupg_rl_initialize ();
1882 set_strusage (my_strusage);
1883 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
1884 /* We don't need any locking in libgcrypt unless we use any kind of
1885 threading. */
1886 gcry_control (GCRYCTL_DISABLE_INTERNAL_LOCKING);
1887 log_set_prefix ("gpg", 1);
1889 /* Make sure that our subsystems are ready. */
1890 init_common_subsystems ();
1892 /* Check that the libraries are suitable. Do it right here because the
1893 option parsing may need services of the library. */
1894 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
1896 log_fatal ( _("libgcrypt is too old (need %s, have %s)\n"),
1897 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
1900 /* Put random number into secure memory */
1901 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
1903 may_coredump = disable_core_dumps();
1905 gnupg_init_signals (0, emergency_cleanup);
1907 create_dotlock(NULL); /* Register locking cleanup. */
1909 i18n_init();
1911 opt.command_fd = -1; /* no command fd */
1912 opt.compress_level = -1; /* defaults to standard compress level */
1913 opt.bz2_compress_level = -1; /* defaults to standard compress level */
1914 /* note: if you change these lines, look at oOpenPGP */
1915 opt.def_cipher_algo = 0;
1916 opt.def_digest_algo = 0;
1917 opt.cert_digest_algo = 0;
1918 opt.compress_algo = -1; /* defaults to DEFAULT_COMPRESS_ALGO */
1919 opt.s2k_mode = 3; /* iterated+salted */
1920 opt.s2k_count = 96; /* 65536 iterations */
1921 #ifdef USE_CAST5
1922 opt.s2k_cipher_algo = CIPHER_ALGO_CAST5;
1923 #else
1924 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
1925 #endif
1926 opt.completes_needed = 1;
1927 opt.marginals_needed = 3;
1928 opt.max_cert_depth = 5;
1929 opt.pgp2_workarounds = 1;
1930 opt.escape_from = 1;
1931 opt.flags.require_cross_cert = 1;
1932 opt.import_options=IMPORT_SK2PK;
1933 opt.export_options=EXPORT_ATTRIBUTES;
1934 opt.keyserver_options.import_options=IMPORT_REPAIR_PKS_SUBKEY_BUG;
1935 opt.keyserver_options.export_options=EXPORT_ATTRIBUTES;
1936 opt.keyserver_options.options=
1937 KEYSERVER_HONOR_KEYSERVER_URL|KEYSERVER_HONOR_PKA_RECORD;
1938 opt.verify_options=
1939 VERIFY_SHOW_POLICY_URLS|VERIFY_SHOW_STD_NOTATIONS|VERIFY_SHOW_KEYSERVER_URLS;
1940 opt.trust_model=TM_AUTO;
1941 opt.mangle_dos_filenames=0;
1942 opt.min_cert_level=2;
1943 set_screen_dimensions();
1944 opt.keyid_format=KF_SHORT;
1945 opt.def_sig_expire="0";
1946 opt.def_cert_expire="0";
1947 set_homedir ( default_homedir () );
1948 opt.passwd_repeat=1;
1950 /* Check whether we have a config file on the command line. */
1951 orig_argc = argc;
1952 orig_argv = argv;
1953 pargs.argc = &argc;
1954 pargs.argv = &argv;
1955 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
1956 while( arg_parse( &pargs, opts) ) {
1957 if( pargs.r_opt == oDebug || pargs.r_opt == oDebugAll )
1958 parse_debug++;
1959 else if( pargs.r_opt == oOptions ) {
1960 /* yes there is one, so we do not try the default one, but
1961 * read the option file when it is encountered at the commandline
1963 default_config = 0;
1965 else if( pargs.r_opt == oNoOptions )
1967 default_config = 0; /* --no-options */
1968 opt.no_homedir_creation = 1;
1970 else if( pargs.r_opt == oHomedir )
1971 set_homedir ( pargs.r.ret_str );
1972 else if( pargs.r_opt == oNoPermissionWarn )
1973 opt.no_perm_warn=1;
1974 else if (pargs.r_opt == oStrict )
1976 /* Not used */
1978 else if (pargs.r_opt == oNoStrict )
1980 /* Not used */
1984 #ifdef HAVE_DOSISH_SYSTEM
1985 if ( strchr (opt.homedir,'\\') ) {
1986 char *d, *buf = xmalloc (strlen (opt.homedir)+1);
1987 const char *s = opt.homedir;
1988 for (d=buf,s=opt.homedir; *s; s++)
1990 *d++ = *s == '\\'? '/': *s;
1991 #ifdef HAVE_W32_SYSTEM
1992 if (s[1] && IsDBCSLeadByte (*s))
1993 *d++ = *++s;
1994 #endif
1996 *d = 0;
1997 set_homedir (buf);
1999 #endif
2001 /* Initialize the secure memory. */
2002 if (!gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0))
2003 got_secmem = 1;
2004 #if defined(HAVE_GETUID) && defined(HAVE_GETEUID)
2005 /* There should be no way to get to this spot while still carrying
2006 setuid privs. Just in case, bomb out if we are. */
2007 if(getuid()!=geteuid())
2008 BUG();
2009 #endif
2010 maybe_setuid = 0;
2012 /* Okay, we are now working under our real uid */
2014 /* malloc hooks go here ... */
2015 assuan_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
2016 assuan_set_assuan_err_source (GPG_ERR_SOURCE_DEFAULT);
2019 /* Try for a version specific config file first */
2020 default_configname = get_default_configname ();
2021 if (default_config)
2022 configname = xstrdup (default_configname);
2024 argc = orig_argc;
2025 argv = orig_argv;
2026 pargs.argc = &argc;
2027 pargs.argv = &argv;
2028 pargs.flags= 1; /* do not remove the args */
2030 /* By this point we have a homedir, and cannot change it. */
2031 check_permissions(opt.homedir,0);
2033 next_pass:
2034 if( configname ) {
2035 if(check_permissions(configname,1))
2037 /* If any options file is unsafe, then disable any external
2038 programs for keyserver calls or photo IDs. Since the
2039 external program to call is set in the options file, a
2040 unsafe options file can lead to an arbitrary program
2041 being run. */
2043 opt.exec_disable=1;
2046 configlineno = 0;
2047 configfp = fopen( configname, "r" );
2048 if (configfp && is_secured_file (fileno (configfp)))
2050 fclose (configfp);
2051 configfp = NULL;
2052 errno = EPERM;
2054 if( !configfp ) {
2055 if( default_config ) {
2056 if( parse_debug )
2057 log_info(_("NOTE: no default option file `%s'\n"),
2058 configname );
2060 else {
2061 log_error(_("option file `%s': %s\n"),
2062 configname, strerror(errno) );
2063 g10_exit(2);
2065 xfree(configname); configname = NULL;
2067 if( parse_debug && configname )
2068 log_info(_("reading options from `%s'\n"), configname );
2069 default_config = 0;
2072 while( optfile_parse( configfp, configname, &configlineno,
2073 &pargs, opts) )
2075 switch( pargs.r_opt )
2077 case aCheckKeys:
2078 case aListConfig:
2079 case aGPGConfList:
2080 case aGPGConfTest:
2081 case aListPackets:
2082 case aImport:
2083 case aFastImport:
2084 case aSendKeys:
2085 case aRecvKeys:
2086 case aSearchKeys:
2087 case aRefreshKeys:
2088 case aFetchKeys:
2089 case aExport:
2090 #ifdef ENABLE_CARD_SUPPORT
2091 case aCardStatus:
2092 case aCardEdit:
2093 case aChangePIN:
2094 #endif /* ENABLE_CARD_SUPPORT*/
2095 case aListKeys:
2096 case aListSigs:
2097 case aExportSecret:
2098 case aExportSecretSub:
2099 case aSym:
2100 case aClearsign:
2101 case aGenRevoke:
2102 case aDesigRevoke:
2103 case aPrimegen:
2104 case aGenRandom:
2105 case aPrintMD:
2106 case aPrintMDs:
2107 case aListTrustDB:
2108 case aCheckTrustDB:
2109 case aUpdateTrustDB:
2110 case aFixTrustDB:
2111 case aListTrustPath:
2112 case aDeArmor:
2113 case aEnArmor:
2114 case aSign:
2115 case aSignKey:
2116 case aLSignKey:
2117 case aStore:
2118 case aExportOwnerTrust:
2119 case aImportOwnerTrust:
2120 case aRebuildKeydbCaches:
2121 set_cmd (&cmd, pargs.r_opt);
2122 break;
2124 case aKeygen:
2125 case aEditKey:
2126 case aDeleteSecretKeys:
2127 case aDeleteSecretAndPublicKeys:
2128 case aDeleteKeys:
2129 set_cmd (&cmd, pargs.r_opt);
2130 greeting=1;
2131 break;
2133 case aDetachedSign: detached_sig = 1; set_cmd( &cmd, aSign ); break;
2135 case aDecryptFiles: multifile=1; /* fall through */
2136 case aDecrypt: set_cmd( &cmd, aDecrypt); break;
2138 case aEncrFiles: multifile=1; /* fall through */
2139 case aEncr: set_cmd( &cmd, aEncr); break;
2141 case aVerifyFiles: multifile=1; /* fall through */
2142 case aVerify: set_cmd( &cmd, aVerify); break;
2144 case aServer:
2145 set_cmd (&cmd, pargs.r_opt);
2146 opt.batch = 1;
2147 break;
2149 case oArmor: opt.armor = 1; opt.no_armor=0; break;
2150 case oOutput: opt.outfile = pargs.r.ret_str; break;
2151 case oMaxOutput: opt.max_output = pargs.r.ret_ulong; break;
2152 case oQuiet: opt.quiet = 1; break;
2153 case oNoTTY: tty_no_terminal(1); break;
2154 case oDryRun: opt.dry_run = 1; break;
2155 case oInteractive: opt.interactive = 1; break;
2156 case oVerbose:
2157 opt.verbose++;
2158 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2159 opt.list_options|=LIST_SHOW_UNUSABLE_UIDS;
2160 opt.list_options|=LIST_SHOW_UNUSABLE_SUBKEYS;
2161 break;
2163 case oBatch:
2164 opt.batch = 1;
2165 nogreeting = 1;
2166 break;
2168 case oUseAgent: /* Dummy. */
2169 break;
2170 case oNoUseAgent:
2171 obsolete_option (configname, configlineno, "--no-use-agent");
2172 break;
2173 case oGpgAgentInfo:
2174 obsolete_option (configname, configlineno, "--gpg-agent-info");
2175 break;
2177 case oAnswerYes: opt.answer_yes = 1; break;
2178 case oAnswerNo: opt.answer_no = 1; break;
2179 case oKeyring: append_to_strlist( &nrings, pargs.r.ret_str); break;
2180 case oPrimaryKeyring:
2181 sl=append_to_strlist( &nrings, pargs.r.ret_str);
2182 sl->flags=2;
2183 break;
2184 case oShowKeyring:
2185 deprecated_warning(configname,configlineno,"--show-keyring",
2186 "--list-options ","show-keyring");
2187 opt.list_options|=LIST_SHOW_KEYRING;
2188 break;
2190 case oDebug: opt.debug |= pargs.r.ret_ulong; break;
2191 case oDebugAll: opt.debug = ~0; break;
2192 case oDebugLevel: debug_level = pargs.r.ret_str; break;
2194 case oStatusFD:
2195 set_status_fd( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
2196 break;
2197 case oStatusFile:
2198 set_status_fd ( open_info_file (pargs.r.ret_str, 1) );
2199 break;
2200 case oAttributeFD:
2201 set_attrib_fd(translate_sys2libc_fd_int (pargs.r.ret_int, 1));
2202 break;
2203 case oAttributeFile:
2204 set_attrib_fd ( open_info_file (pargs.r.ret_str, 1) );
2205 break;
2206 case oLoggerFD:
2207 log_set_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1));
2208 break;
2209 case oLoggerFile:
2210 logfile = pargs.r.ret_str;
2211 break;
2213 case oWithFingerprint:
2214 opt.with_fingerprint = 1;
2215 with_fpr=1; /*fall thru*/
2216 case oFingerprint: opt.fingerprint++; break;
2217 case oSecretKeyring:
2218 append_to_strlist( &sec_nrings, pargs.r.ret_str);
2219 break;
2220 case oOptions:
2221 /* config files may not be nested (silently ignore them) */
2222 if( !configfp ) {
2223 xfree(configname);
2224 configname = xstrdup(pargs.r.ret_str);
2225 goto next_pass;
2227 break;
2228 case oNoArmor: opt.no_armor=1; opt.armor=0; break;
2229 case oNoDefKeyring: default_keyring = 0; break;
2230 case oNoGreeting: nogreeting = 1; break;
2231 case oNoVerbose:
2232 opt.verbose = 0;
2233 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2234 opt.list_sigs=0;
2235 break;
2236 case oQuickRandom:
2237 gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
2238 break;
2239 case oEmitVersion: opt.no_version=0; break;
2240 case oNoEmitVersion: opt.no_version=1; break;
2241 case oCompletesNeeded: opt.completes_needed = pargs.r.ret_int; break;
2242 case oMarginalsNeeded: opt.marginals_needed = pargs.r.ret_int; break;
2243 case oMaxCertDepth: opt.max_cert_depth = pargs.r.ret_int; break;
2244 case oTrustDBName: trustdb_name = pargs.r.ret_str; break;
2245 case oDefaultKey: opt.def_secret_key = pargs.r.ret_str; break;
2246 case oDefRecipient:
2247 if( *pargs.r.ret_str )
2248 opt.def_recipient = make_username(pargs.r.ret_str);
2249 break;
2250 case oDefRecipientSelf:
2251 xfree(opt.def_recipient); opt.def_recipient = NULL;
2252 opt.def_recipient_self = 1;
2253 break;
2254 case oNoDefRecipient:
2255 xfree(opt.def_recipient); opt.def_recipient = NULL;
2256 opt.def_recipient_self = 0;
2257 break;
2258 case oNoOptions: opt.no_homedir_creation = 1; break; /* no-options */
2259 case oHomedir: break;
2260 case oNoBatch: opt.batch = 0; break;
2261 case oWithKeyData: opt.with_key_data=1; /* fall thru */
2262 case oWithColons: opt.with_colons=':'; break;
2264 case oSkipVerify: opt.skip_verify=1; break;
2265 case oCompressKeys: opt.compress_keys = 1; break;
2266 case aListSecretKeys: set_cmd( &cmd, aListSecretKeys); break;
2267 /* There are many programs (like mutt) that call gpg with
2268 --always-trust so keep this option around for a long
2269 time. */
2270 case oAlwaysTrust: opt.trust_model=TM_ALWAYS; break;
2271 case oTrustModel:
2272 parse_trust_model(pargs.r.ret_str);
2273 break;
2274 case oForceOwnertrust:
2275 log_info(_("NOTE: %s is not for normal use!\n"),
2276 "--force-ownertrust");
2277 opt.force_ownertrust=string_to_trust_value(pargs.r.ret_str);
2278 if(opt.force_ownertrust==-1)
2280 log_error("invalid ownertrust `%s'\n",pargs.r.ret_str);
2281 opt.force_ownertrust=0;
2283 break;
2284 case oLoadExtension:
2285 /* Dummy so that gpg 1.4 conf files can work. Should
2286 eventually be removed. */
2287 break;
2288 case oRFC1991:
2289 opt.compliance = CO_RFC1991;
2290 opt.force_v4_certs = 0;
2291 opt.escape_from = 1;
2292 break;
2293 case oOpenPGP:
2294 case oRFC4880:
2295 /* This is effectively the same as RFC2440, but with
2296 "--enable-dsa2 --no-rfc2440-text --escape-from-lines
2297 --require-cross-certification". */
2298 opt.compliance = CO_RFC4880;
2299 opt.flags.dsa2 = 1;
2300 opt.flags.require_cross_cert = 1;
2301 opt.rfc2440_text = 0;
2302 opt.allow_non_selfsigned_uid = 1;
2303 opt.allow_freeform_uid = 1;
2304 opt.pgp2_workarounds = 0;
2305 opt.escape_from = 1;
2306 opt.force_v3_sigs = 0;
2307 opt.compress_keys = 0; /* not mandated, but we do it */
2308 opt.compress_sigs = 0; /* ditto. */
2309 opt.not_dash_escaped = 0;
2310 opt.def_cipher_algo = 0;
2311 opt.def_digest_algo = 0;
2312 opt.cert_digest_algo = 0;
2313 opt.compress_algo = -1;
2314 opt.s2k_mode = 3; /* iterated+salted */
2315 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2316 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2317 break;
2318 case oRFC2440:
2319 opt.compliance = CO_RFC2440;
2320 opt.flags.dsa2 = 0;
2321 opt.rfc2440_text = 1;
2322 opt.allow_non_selfsigned_uid = 1;
2323 opt.allow_freeform_uid = 1;
2324 opt.pgp2_workarounds = 0;
2325 opt.escape_from = 0;
2326 opt.force_v3_sigs = 0;
2327 opt.compress_keys = 0; /* not mandated, but we do it */
2328 opt.compress_sigs = 0; /* ditto. */
2329 opt.not_dash_escaped = 0;
2330 opt.def_cipher_algo = 0;
2331 opt.def_digest_algo = 0;
2332 opt.cert_digest_algo = 0;
2333 opt.compress_algo = -1;
2334 opt.s2k_mode = 3; /* iterated+salted */
2335 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2336 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2337 break;
2338 case oPGP2: opt.compliance = CO_PGP2; break;
2339 case oPGP6: opt.compliance = CO_PGP6; break;
2340 case oPGP7: opt.compliance = CO_PGP7; break;
2341 case oPGP8: opt.compliance = CO_PGP8; break;
2342 case oGnuPG: opt.compliance = CO_GNUPG; break;
2343 case oCompressSigs: opt.compress_sigs = 1; break;
2344 case oRFC2440Text: opt.rfc2440_text=1; break;
2345 case oNoRFC2440Text: opt.rfc2440_text=0; break;
2346 case oSetFilename:
2347 if(utf8_strings)
2348 opt.set_filename = pargs.r.ret_str;
2349 else
2350 opt.set_filename = native_to_utf8(pargs.r.ret_str);
2351 break;
2352 case oForYourEyesOnly: eyes_only = 1; break;
2353 case oNoForYourEyesOnly: eyes_only = 0; break;
2354 case oSetPolicyURL:
2355 add_policy_url(pargs.r.ret_str,0);
2356 add_policy_url(pargs.r.ret_str,1);
2357 break;
2358 case oSigPolicyURL: add_policy_url(pargs.r.ret_str,0); break;
2359 case oCertPolicyURL: add_policy_url(pargs.r.ret_str,1); break;
2360 case oShowPolicyURL:
2361 deprecated_warning(configname,configlineno,"--show-policy-url",
2362 "--list-options ","show-policy-urls");
2363 deprecated_warning(configname,configlineno,"--show-policy-url",
2364 "--verify-options ","show-policy-urls");
2365 opt.list_options|=LIST_SHOW_POLICY_URLS;
2366 opt.verify_options|=VERIFY_SHOW_POLICY_URLS;
2367 break;
2368 case oNoShowPolicyURL:
2369 deprecated_warning(configname,configlineno,"--no-show-policy-url",
2370 "--list-options ","no-show-policy-urls");
2371 deprecated_warning(configname,configlineno,"--no-show-policy-url",
2372 "--verify-options ","no-show-policy-urls");
2373 opt.list_options&=~LIST_SHOW_POLICY_URLS;
2374 opt.verify_options&=~VERIFY_SHOW_POLICY_URLS;
2375 break;
2376 case oSigKeyserverURL: add_keyserver_url(pargs.r.ret_str,0); break;
2377 case oUseEmbeddedFilename:
2378 opt.flags.use_embedded_filename=1;
2379 break;
2380 case oNoUseEmbeddedFilename:
2381 opt.flags.use_embedded_filename=0;
2382 break;
2383 case oComment:
2384 if(pargs.r.ret_str[0])
2385 append_to_strlist(&opt.comments,pargs.r.ret_str);
2386 break;
2387 case oDefaultComment:
2388 deprecated_warning(configname,configlineno,
2389 "--default-comment","--no-comments","");
2390 /* fall through */
2391 case oNoComments:
2392 free_strlist(opt.comments);
2393 opt.comments=NULL;
2394 break;
2395 case oThrowKeyids: opt.throw_keyid = 1; break;
2396 case oNoThrowKeyids: opt.throw_keyid = 0; break;
2397 case oShowPhotos:
2398 deprecated_warning(configname,configlineno,"--show-photos",
2399 "--list-options ","show-photos");
2400 deprecated_warning(configname,configlineno,"--show-photos",
2401 "--verify-options ","show-photos");
2402 opt.list_options|=LIST_SHOW_PHOTOS;
2403 opt.verify_options|=VERIFY_SHOW_PHOTOS;
2404 break;
2405 case oNoShowPhotos:
2406 deprecated_warning(configname,configlineno,"--no-show-photos",
2407 "--list-options ","no-show-photos");
2408 deprecated_warning(configname,configlineno,"--no-show-photos",
2409 "--verify-options ","no-show-photos");
2410 opt.list_options&=~LIST_SHOW_PHOTOS;
2411 opt.verify_options&=~VERIFY_SHOW_PHOTOS;
2412 break;
2413 case oPhotoViewer: opt.photo_viewer = pargs.r.ret_str; break;
2414 case oForceV3Sigs: opt.force_v3_sigs = 1; break;
2415 case oNoForceV3Sigs: opt.force_v3_sigs = 0; break;
2416 case oForceV4Certs: opt.force_v4_certs = 1; break;
2417 case oNoForceV4Certs: opt.force_v4_certs = 0; break;
2418 case oForceMDC: opt.force_mdc = 1; break;
2419 case oNoForceMDC: opt.force_mdc = 0; break;
2420 case oDisableMDC: opt.disable_mdc = 1; break;
2421 case oNoDisableMDC: opt.disable_mdc = 0; break;
2422 case oS2KMode: opt.s2k_mode = pargs.r.ret_int; break;
2423 case oS2KDigest: s2k_digest_string = xstrdup(pargs.r.ret_str); break;
2424 case oS2KCipher: s2k_cipher_string = xstrdup(pargs.r.ret_str); break;
2425 case oS2KCount:
2426 opt.s2k_count=encode_s2k_iterations(pargs.r.ret_int);
2427 break;
2428 case oSimpleSKChecksum: opt.simple_sk_checksum = 1; break;
2429 case oNoEncryptTo: opt.no_encrypt_to = 1; break;
2430 case oEncryptTo: /* store the recipient in the second list */
2431 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2432 sl->flags = 1;
2433 break;
2434 case oHiddenEncryptTo: /* store the recipient in the second list */
2435 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2436 sl->flags = 1|2;
2437 break;
2438 case oRecipient: /* store the recipient */
2439 add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2440 any_explicit_recipient = 1;
2441 break;
2442 case oHiddenRecipient: /* store the recipient with a flag */
2443 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2444 sl->flags = 2;
2445 any_explicit_recipient = 1;
2446 break;
2447 case oTextmodeShort: opt.textmode = 2; break;
2448 case oTextmode: opt.textmode=1; break;
2449 case oNoTextmode: opt.textmode=0; break;
2450 case oExpert: opt.expert = 1; break;
2451 case oNoExpert: opt.expert = 0; break;
2452 case oDefSigExpire:
2453 if(*pargs.r.ret_str!='\0')
2455 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
2456 log_error(_("`%s' is not a valid signature expiration\n"),
2457 pargs.r.ret_str);
2458 else
2459 opt.def_sig_expire=pargs.r.ret_str;
2461 break;
2462 case oAskSigExpire: opt.ask_sig_expire = 1; break;
2463 case oNoAskSigExpire: opt.ask_sig_expire = 0; break;
2464 case oDefCertExpire:
2465 if(*pargs.r.ret_str!='\0')
2467 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
2468 log_error(_("`%s' is not a valid signature expiration\n"),
2469 pargs.r.ret_str);
2470 else
2471 opt.def_cert_expire=pargs.r.ret_str;
2473 break;
2474 case oAskCertExpire: opt.ask_cert_expire = 1; break;
2475 case oNoAskCertExpire: opt.ask_cert_expire = 0; break;
2476 case oDefCertLevel: opt.def_cert_level=pargs.r.ret_int; break;
2477 case oMinCertLevel: opt.min_cert_level=pargs.r.ret_int; break;
2478 case oAskCertLevel: opt.ask_cert_level = 1; break;
2479 case oNoAskCertLevel: opt.ask_cert_level = 0; break;
2480 case oLocalUser: /* store the local users */
2481 add_to_strlist2( &locusr, pargs.r.ret_str, utf8_strings );
2482 break;
2483 case oCompress:
2484 /* this is the -z command line option */
2485 opt.compress_level = opt.bz2_compress_level = pargs.r.ret_int;
2486 break;
2487 case oCompressLevel: opt.compress_level = pargs.r.ret_int; break;
2488 case oBZ2CompressLevel: opt.bz2_compress_level = pargs.r.ret_int; break;
2489 case oBZ2DecompressLowmem: opt.bz2_decompress_lowmem=1; break;
2490 case oPasswd:
2491 set_passphrase_from_string(pargs.r.ret_str);
2492 break;
2493 case oPasswdFD:
2494 pwfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
2495 break;
2496 case oPasswdFile:
2497 pwfd = open_info_file (pargs.r.ret_str, 0);
2498 break;
2499 case oPasswdRepeat: opt.passwd_repeat=pargs.r.ret_int; break;
2500 case oCommandFD:
2501 opt.command_fd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
2502 break;
2503 case oCommandFile:
2504 opt.command_fd = open_info_file (pargs.r.ret_str, 0);
2505 break;
2506 case oCipherAlgo:
2507 def_cipher_string = xstrdup(pargs.r.ret_str);
2508 break;
2509 case oDigestAlgo:
2510 def_digest_string = xstrdup(pargs.r.ret_str);
2511 break;
2512 case oCompressAlgo:
2513 /* If it is all digits, stick a Z in front of it for
2514 later. This is for backwards compatibility with
2515 versions that took the compress algorithm number. */
2517 char *pt=pargs.r.ret_str;
2518 while(*pt)
2520 if (!isascii (*pt) || !isdigit (*pt))
2521 break;
2523 pt++;
2526 if(*pt=='\0')
2528 compress_algo_string=xmalloc(strlen(pargs.r.ret_str)+2);
2529 strcpy(compress_algo_string,"Z");
2530 strcat(compress_algo_string,pargs.r.ret_str);
2532 else
2533 compress_algo_string = xstrdup(pargs.r.ret_str);
2535 break;
2536 case oCertDigestAlgo:
2537 cert_digest_string = xstrdup(pargs.r.ret_str);
2538 break;
2540 case oNoSecmemWarn:
2541 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
2542 break;
2544 case oRequireSecmem: require_secmem=1; break;
2545 case oNoRequireSecmem: require_secmem=0; break;
2546 case oNoPermissionWarn: opt.no_perm_warn=1; break;
2547 case oNoMDCWarn: opt.no_mdc_warn=1; break;
2548 case oDisplayCharset:
2549 if( set_native_charset( pargs.r.ret_str ) )
2550 log_error(_("`%s' is not a valid character set\n"),
2551 pargs.r.ret_str);
2552 break;
2553 case oNotDashEscaped: opt.not_dash_escaped = 1; break;
2554 case oEscapeFrom: opt.escape_from = 1; break;
2555 case oNoEscapeFrom: opt.escape_from = 0; break;
2556 case oLockOnce: opt.lock_once = 1; break;
2557 case oLockNever:
2558 disable_dotlock ();
2559 break;
2560 case oLockMultiple:
2561 #ifndef __riscos__
2562 opt.lock_once = 0;
2563 #else /* __riscos__ */
2564 riscos_not_implemented("lock-multiple");
2565 #endif /* __riscos__ */
2566 break;
2567 case oKeyServer:
2569 struct keyserver_spec *keyserver;
2570 keyserver=parse_keyserver_uri(pargs.r.ret_str,0,
2571 configname,configlineno);
2572 if(!keyserver)
2573 log_error(_("could not parse keyserver URL\n"));
2574 else
2576 keyserver->next=opt.keyserver;
2577 opt.keyserver=keyserver;
2580 break;
2581 case oKeyServerOptions:
2582 if(!parse_keyserver_options(pargs.r.ret_str))
2584 if(configname)
2585 log_error(_("%s:%d: invalid keyserver options\n"),
2586 configname,configlineno);
2587 else
2588 log_error(_("invalid keyserver options\n"));
2590 break;
2591 case oImportOptions:
2592 if(!parse_import_options(pargs.r.ret_str,&opt.import_options,1))
2594 if(configname)
2595 log_error(_("%s:%d: invalid import options\n"),
2596 configname,configlineno);
2597 else
2598 log_error(_("invalid import options\n"));
2600 break;
2601 case oExportOptions:
2602 if(!parse_export_options(pargs.r.ret_str,&opt.export_options,1))
2604 if(configname)
2605 log_error(_("%s:%d: invalid export options\n"),
2606 configname,configlineno);
2607 else
2608 log_error(_("invalid export options\n"));
2610 break;
2611 case oListOptions:
2612 if(!parse_list_options(pargs.r.ret_str))
2614 if(configname)
2615 log_error(_("%s:%d: invalid list options\n"),
2616 configname,configlineno);
2617 else
2618 log_error(_("invalid list options\n"));
2620 break;
2621 case oVerifyOptions:
2623 struct parse_options vopts[]=
2625 {"show-photos",VERIFY_SHOW_PHOTOS,NULL,
2626 N_("display photo IDs during signature verification")},
2627 {"show-policy-urls",VERIFY_SHOW_POLICY_URLS,NULL,
2628 N_("show policy URLs during signature verification")},
2629 {"show-notations",VERIFY_SHOW_NOTATIONS,NULL,
2630 N_("show all notations during signature verification")},
2631 {"show-std-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
2632 N_("show IETF standard notations during signature verification")},
2633 {"show-standard-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
2634 NULL},
2635 {"show-user-notations",VERIFY_SHOW_USER_NOTATIONS,NULL,
2636 N_("show user-supplied notations during signature verification")},
2637 {"show-keyserver-urls",VERIFY_SHOW_KEYSERVER_URLS,NULL,
2638 N_("show preferred keyserver URLs during signature verification")},
2639 {"show-uid-validity",VERIFY_SHOW_UID_VALIDITY,NULL,
2640 N_("show user ID validity during signature verification")},
2641 {"show-unusable-uids",VERIFY_SHOW_UNUSABLE_UIDS,NULL,
2642 N_("show revoked and expired user IDs in signature verification")},
2643 {"show-primary-uid-only",VERIFY_SHOW_PRIMARY_UID_ONLY,NULL,
2644 N_("show only the primary user ID in signature verification")},
2645 {"pka-lookups",VERIFY_PKA_LOOKUPS,NULL,
2646 N_("validate signatures with PKA data")},
2647 {"pka-trust-increase",VERIFY_PKA_TRUST_INCREASE,NULL,
2648 N_("elevate the trust of signatures with valid PKA data")},
2649 {NULL,0,NULL,NULL}
2652 if(!parse_options(pargs.r.ret_str,&opt.verify_options,vopts,1))
2654 if(configname)
2655 log_error(_("%s:%d: invalid verify options\n"),
2656 configname,configlineno);
2657 else
2658 log_error(_("invalid verify options\n"));
2661 break;
2662 case oTempDir: opt.temp_dir=pargs.r.ret_str; break;
2663 case oExecPath:
2664 if(set_exec_path(pargs.r.ret_str))
2665 log_error(_("unable to set exec-path to %s\n"),pargs.r.ret_str);
2666 else
2667 opt.exec_path_set=1;
2668 break;
2669 case oSetNotation:
2670 add_notation_data( pargs.r.ret_str, 0 );
2671 add_notation_data( pargs.r.ret_str, 1 );
2672 break;
2673 case oSigNotation: add_notation_data( pargs.r.ret_str, 0 ); break;
2674 case oCertNotation: add_notation_data( pargs.r.ret_str, 1 ); break;
2675 case oShowNotation:
2676 deprecated_warning(configname,configlineno,"--show-notation",
2677 "--list-options ","show-notations");
2678 deprecated_warning(configname,configlineno,"--show-notation",
2679 "--verify-options ","show-notations");
2680 opt.list_options|=LIST_SHOW_NOTATIONS;
2681 opt.verify_options|=VERIFY_SHOW_NOTATIONS;
2682 break;
2683 case oNoShowNotation:
2684 deprecated_warning(configname,configlineno,"--no-show-notation",
2685 "--list-options ","no-show-notations");
2686 deprecated_warning(configname,configlineno,"--no-show-notation",
2687 "--verify-options ","no-show-notations");
2688 opt.list_options&=~LIST_SHOW_NOTATIONS;
2689 opt.verify_options&=~VERIFY_SHOW_NOTATIONS;
2690 break;
2691 case oUtf8Strings: utf8_strings = 1; break;
2692 case oNoUtf8Strings: utf8_strings = 0; break;
2693 case oDisableCipherAlgo:
2695 int algo = string_to_cipher_algo (pargs.r.ret_str);
2696 gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
2698 break;
2699 case oDisablePubkeyAlgo:
2701 int algo = gcry_pk_map_name (pargs.r.ret_str);
2702 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
2704 break;
2705 case oNoSigCache: opt.no_sig_cache = 1; break;
2706 case oNoSigCreateCheck: opt.no_sig_create_check = 1; break;
2707 case oAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid = 1; break;
2708 case oNoAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid=0; break;
2709 case oAllowFreeformUID: opt.allow_freeform_uid = 1; break;
2710 case oNoAllowFreeformUID: opt.allow_freeform_uid = 0; break;
2711 case oNoLiteral: opt.no_literal = 1; break;
2712 case oSetFilesize: opt.set_filesize = pargs.r.ret_ulong; break;
2713 case oHonorHttpProxy:
2714 add_to_strlist(&opt.keyserver_options.other,"http-proxy");
2715 deprecated_warning(configname,configlineno,
2716 "--honor-http-proxy",
2717 "--keyserver-options ","http-proxy");
2718 break;
2719 case oFastListMode: opt.fast_list_mode = 1; break;
2720 case oFixedListMode: opt.fixed_list_mode = 1; break;
2721 case oListOnly: opt.list_only=1; break;
2722 case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
2723 case oIgnoreValidFrom: opt.ignore_valid_from = 1; break;
2724 case oIgnoreCrcError: opt.ignore_crc_error = 1; break;
2725 case oIgnoreMDCError: opt.ignore_mdc_error = 1; break;
2726 case oNoRandomSeedFile: use_random_seed = 0; break;
2727 case oAutoKeyRetrieve:
2728 case oNoAutoKeyRetrieve:
2729 if(pargs.r_opt==oAutoKeyRetrieve)
2730 opt.keyserver_options.options|=KEYSERVER_AUTO_KEY_RETRIEVE;
2731 else
2732 opt.keyserver_options.options&=~KEYSERVER_AUTO_KEY_RETRIEVE;
2734 deprecated_warning(configname,configlineno,
2735 pargs.r_opt==oAutoKeyRetrieve?"--auto-key-retrieve":
2736 "--no-auto-key-retrieve","--keyserver-options ",
2737 pargs.r_opt==oAutoKeyRetrieve?"auto-key-retrieve":
2738 "no-auto-key-retrieve");
2739 break;
2740 case oShowSessionKey: opt.show_session_key = 1; break;
2741 case oOverrideSessionKey:
2742 opt.override_session_key = pargs.r.ret_str;
2743 break;
2744 case oMergeOnly:
2745 deprecated_warning(configname,configlineno,"--merge-only",
2746 "--import-options ","merge-only");
2747 opt.import_options|=IMPORT_MERGE_ONLY;
2748 break;
2749 case oAllowSecretKeyImport: /* obsolete */ break;
2750 case oTryAllSecrets: opt.try_all_secrets = 1; break;
2751 case oTrustedKey: register_trusted_key( pargs.r.ret_str ); break;
2752 case oEnableSpecialFilenames:
2753 iobuf_enable_special_filenames (1);
2754 break;
2755 case oNoExpensiveTrustChecks: opt.no_expensive_trust_checks=1; break;
2756 case oAutoCheckTrustDB: opt.no_auto_check_trustdb=0; break;
2757 case oNoAutoCheckTrustDB: opt.no_auto_check_trustdb=1; break;
2758 case oPreservePermissions: opt.preserve_permissions=1; break;
2759 case oDefaultPreferenceList:
2760 opt.def_preference_list = pargs.r.ret_str;
2761 break;
2762 case oDefaultKeyserverURL:
2764 struct keyserver_spec *keyserver;
2765 keyserver=parse_keyserver_uri(pargs.r.ret_str,1,
2766 configname,configlineno);
2767 if(!keyserver)
2768 log_error(_("could not parse keyserver URL\n"));
2769 else
2770 free_keyserver_spec(keyserver);
2772 opt.def_keyserver_url = pargs.r.ret_str;
2774 break;
2775 case oPersonalCipherPreferences:
2776 pers_cipher_list=pargs.r.ret_str;
2777 break;
2778 case oPersonalDigestPreferences:
2779 pers_digest_list=pargs.r.ret_str;
2780 break;
2781 case oPersonalCompressPreferences:
2782 pers_compress_list=pargs.r.ret_str;
2783 break;
2784 case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
2785 case oDisplay: opt.display = pargs.r.ret_str; break;
2786 case oTTYname: opt.ttyname = pargs.r.ret_str; break;
2787 case oTTYtype: opt.ttytype = pargs.r.ret_str; break;
2788 case oLCctype: opt.lc_ctype = pargs.r.ret_str; break;
2789 case oLCmessages: opt.lc_messages = pargs.r.ret_str; break;
2790 case oXauthority: opt.xauthority = pargs.r.ret_str; break;
2791 case oGroup: add_group(pargs.r.ret_str); break;
2792 case oUnGroup: rm_group(pargs.r.ret_str); break;
2793 case oNoGroups:
2794 while(opt.grouplist)
2796 struct groupitem *iter=opt.grouplist;
2797 free_strlist(iter->values);
2798 opt.grouplist=opt.grouplist->next;
2799 xfree(iter);
2801 break;
2803 case oStrict:
2804 case oNoStrict:
2805 /* Not used */
2806 break;
2808 case oMangleDosFilenames: opt.mangle_dos_filenames = 1; break;
2809 case oNoMangleDosFilenames: opt.mangle_dos_filenames = 0; break;
2810 case oEnableProgressFilter: opt.enable_progress_filter = 1; break;
2811 case oMultifile: multifile=1; break;
2812 case oKeyidFormat:
2813 if(ascii_strcasecmp(pargs.r.ret_str,"short")==0)
2814 opt.keyid_format=KF_SHORT;
2815 else if(ascii_strcasecmp(pargs.r.ret_str,"long")==0)
2816 opt.keyid_format=KF_LONG;
2817 else if(ascii_strcasecmp(pargs.r.ret_str,"0xshort")==0)
2818 opt.keyid_format=KF_0xSHORT;
2819 else if(ascii_strcasecmp(pargs.r.ret_str,"0xlong")==0)
2820 opt.keyid_format=KF_0xLONG;
2821 else
2822 log_error("unknown keyid-format `%s'\n",pargs.r.ret_str);
2823 break;
2825 case oExitOnStatusWriteError:
2826 opt.exit_on_status_write_error = 1;
2827 break;
2829 case oLimitCardInsertTries:
2830 opt.limit_card_insert_tries = pargs.r.ret_int;
2831 break;
2833 case oRequireCrossCert: opt.flags.require_cross_cert=1; break;
2834 case oNoRequireCrossCert: opt.flags.require_cross_cert=0; break;
2836 case oAutoKeyLocate:
2837 if(!parse_auto_key_locate(pargs.r.ret_str))
2839 if(configname)
2840 log_error(_("%s:%d: invalid auto-key-locate list\n"),
2841 configname,configlineno);
2842 else
2843 log_error(_("invalid auto-key-locate list\n"));
2845 break;
2846 case oNoAutoKeyLocate:
2847 release_akl();
2848 break;
2850 case oEnableDSA2: opt.flags.dsa2=1; break;
2851 case oDisableDSA2: opt.flags.dsa2=0; break;
2853 case oAllowMultisigVerification:
2854 case oAllowMultipleMessages:
2855 opt.flags.allow_multiple_messages=1;
2856 break;
2858 case oNoAllowMultipleMessages:
2859 opt.flags.allow_multiple_messages=0;
2860 break;
2862 case oNoop: break;
2864 default : pargs.err = configfp? 1:2; break;
2869 if( configfp ) {
2870 fclose( configfp );
2871 configfp = NULL;
2872 /* Remember the first config file name. */
2873 if (!save_configname)
2874 save_configname = configname;
2875 else
2876 xfree(configname);
2877 configname = NULL;
2878 goto next_pass;
2880 xfree( configname ); configname = NULL;
2881 if( log_get_errorcount(0) )
2882 g10_exit(2);
2884 /* The command --gpgconf-list is pretty simple and may be called
2885 directly after the option parsing. */
2886 if (cmd == aGPGConfList)
2888 gpgconf_list (save_configname ? save_configname : default_configname);
2889 g10_exit (0);
2891 xfree (save_configname);
2892 xfree (default_configname);
2894 if( nogreeting )
2895 greeting = 0;
2897 if( greeting ) {
2898 fprintf(stderr, "%s %s; %s\n",
2899 strusage(11), strusage(13), strusage(14) );
2900 fprintf(stderr, "%s\n", strusage(15) );
2902 #ifdef IS_DEVELOPMENT_VERSION
2903 if( !opt.batch )
2905 const char *s;
2907 if((s=strusage(20)))
2908 log_info("%s\n",s);
2909 if((s=strusage(21)))
2910 log_info("%s\n",s);
2911 if((s=strusage(22)))
2912 log_info("%s\n",s);
2914 #endif
2916 /* FIXME: We should use logging to a file only in server mode;
2917 however we have not yet implemetyed that. Thus we try to get
2918 away with --batch as indication for logging to file
2919 required. */
2920 if (logfile && opt.batch)
2922 log_set_file (logfile);
2923 log_set_prefix (NULL, 1|2|4);
2926 #ifdef USE_CAMELLIA
2927 /* We better also print a runtime warning if people build it with
2928 support for Camellia (which is not yet defined by OpenPGP). */
2929 log_info ("WARNING: This version has been built with support for the "
2930 "Camellia cipher.\n");
2931 log_info (" It is for testing only and is NOT for production "
2932 "use!\n");
2933 #endif
2935 if (opt.verbose > 2)
2936 log_info ("using character set `%s'\n", get_native_charset ());
2938 if( may_coredump && !opt.quiet )
2939 log_info(_("WARNING: program may create a core file!\n"));
2941 if (eyes_only) {
2942 if (opt.set_filename)
2943 log_info(_("WARNING: %s overrides %s\n"),
2944 "--for-your-eyes-only","--set-filename");
2946 opt.set_filename="_CONSOLE";
2949 if (opt.no_literal) {
2950 log_info(_("NOTE: %s is not for normal use!\n"), "--no-literal");
2951 if (opt.textmode)
2952 log_error(_("%s not allowed with %s!\n"),
2953 "--textmode", "--no-literal" );
2954 if (opt.set_filename)
2955 log_error(_("%s makes no sense with %s!\n"),
2956 eyes_only?"--for-your-eyes-only":"--set-filename",
2957 "--no-literal" );
2961 if (opt.set_filesize)
2962 log_info(_("NOTE: %s is not for normal use!\n"), "--set-filesize");
2963 if( opt.batch )
2964 tty_batchmode( 1 );
2966 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
2968 if(require_secmem && !got_secmem)
2970 log_info(_("will not run with insecure memory due to %s\n"),
2971 "--require-secmem");
2972 g10_exit(2);
2975 set_debug (debug_level);
2977 /* Do these after the switch(), so they can override settings. */
2978 if(PGP2)
2980 int unusable=0;
2982 if(cmd==aSign && !detached_sig)
2984 log_info(_("you can only make detached or clear signatures "
2985 "while in --pgp2 mode\n"));
2986 unusable=1;
2988 else if(cmd==aSignEncr || cmd==aSignSym)
2990 log_info(_("you can't sign and encrypt at the "
2991 "same time while in --pgp2 mode\n"));
2992 unusable=1;
2994 else if(argc==0 && (cmd==aSign || cmd==aEncr || cmd==aSym))
2996 log_info(_("you must use files (and not a pipe) when "
2997 "working with --pgp2 enabled.\n"));
2998 unusable=1;
3000 else if(cmd==aEncr || cmd==aSym)
3002 /* Everything else should work without IDEA (except using
3003 a secret key encrypted with IDEA and setting an IDEA
3004 preference, but those have their own error
3005 messages). */
3007 if (openpgp_cipher_test_algo(CIPHER_ALGO_IDEA))
3009 log_info(_("encrypting a message in --pgp2 mode requires "
3010 "the IDEA cipher\n"));
3011 idea_cipher_warn(1);
3012 unusable=1;
3014 else if(cmd==aSym)
3016 /* This only sets IDEA for symmetric encryption
3017 since it is set via select_algo_from_prefs for
3018 pk encryption. */
3019 xfree(def_cipher_string);
3020 def_cipher_string = xstrdup("idea");
3023 /* PGP2 can't handle the output from the textmode
3024 filter, so we disable it for anything that could
3025 create a literal packet (only encryption and
3026 symmetric encryption, since we disable signing
3027 above). */
3028 if(!unusable)
3029 opt.textmode=0;
3032 if(unusable)
3033 compliance_failure();
3034 else
3036 opt.force_v4_certs = 0;
3037 opt.escape_from = 1;
3038 opt.force_v3_sigs = 1;
3039 opt.pgp2_workarounds = 1;
3040 opt.ask_sig_expire = 0;
3041 opt.ask_cert_expire = 0;
3042 xfree(def_digest_string);
3043 def_digest_string = xstrdup("md5");
3044 xfree(s2k_digest_string);
3045 s2k_digest_string = xstrdup("md5");
3046 opt.compress_algo = COMPRESS_ALGO_ZIP;
3049 else if(PGP6)
3051 opt.escape_from=1;
3052 opt.force_v3_sigs=1;
3053 opt.ask_sig_expire=0;
3055 else if(PGP7)
3057 opt.escape_from=1;
3058 opt.force_v3_sigs=1;
3059 opt.ask_sig_expire=0;
3061 else if(PGP8)
3063 opt.escape_from=1;
3067 if( def_cipher_string ) {
3068 opt.def_cipher_algo = string_to_cipher_algo (def_cipher_string);
3069 if(opt.def_cipher_algo==0 &&
3070 (ascii_strcasecmp(def_cipher_string,"idea")==0
3071 || ascii_strcasecmp(def_cipher_string,"s1")==0))
3072 idea_cipher_warn(1);
3073 xfree(def_cipher_string); def_cipher_string = NULL;
3074 if ( openpgp_cipher_test_algo (opt.def_cipher_algo) )
3075 log_error(_("selected cipher algorithm is invalid\n"));
3077 if( def_digest_string ) {
3078 opt.def_digest_algo = string_to_digest_algo (def_digest_string);
3079 xfree(def_digest_string); def_digest_string = NULL;
3080 if ( openpgp_md_test_algo (opt.def_digest_algo) )
3081 log_error(_("selected digest algorithm is invalid\n"));
3083 if( compress_algo_string ) {
3084 opt.compress_algo = string_to_compress_algo(compress_algo_string);
3085 xfree(compress_algo_string); compress_algo_string = NULL;
3086 if( check_compress_algo(opt.compress_algo) )
3087 log_error(_("selected compression algorithm is invalid\n"));
3089 if( cert_digest_string ) {
3090 opt.cert_digest_algo = string_to_digest_algo (cert_digest_string);
3091 xfree(cert_digest_string); cert_digest_string = NULL;
3092 if (openpgp_md_test_algo(opt.cert_digest_algo))
3093 log_error(_("selected certification digest algorithm is invalid\n"));
3095 if( s2k_cipher_string ) {
3096 opt.s2k_cipher_algo = string_to_cipher_algo (s2k_cipher_string);
3097 xfree(s2k_cipher_string); s2k_cipher_string = NULL;
3098 if (openpgp_cipher_test_algo (opt.s2k_cipher_algo))
3099 log_error(_("selected cipher algorithm is invalid\n"));
3101 if( s2k_digest_string ) {
3102 opt.s2k_digest_algo = string_to_digest_algo (s2k_digest_string);
3103 xfree(s2k_digest_string); s2k_digest_string = NULL;
3104 if (openpgp_md_test_algo(opt.s2k_digest_algo))
3105 log_error(_("selected digest algorithm is invalid\n"));
3107 if( opt.completes_needed < 1 )
3108 log_error(_("completes-needed must be greater than 0\n"));
3109 if( opt.marginals_needed < 2 )
3110 log_error(_("marginals-needed must be greater than 1\n"));
3111 if( opt.max_cert_depth < 1 || opt.max_cert_depth > 255 )
3112 log_error(_("max-cert-depth must be in the range from 1 to 255\n"));
3113 if(opt.def_cert_level<0 || opt.def_cert_level>3)
3114 log_error(_("invalid default-cert-level; must be 0, 1, 2, or 3\n"));
3115 if( opt.min_cert_level < 1 || opt.min_cert_level > 3 )
3116 log_error(_("invalid min-cert-level; must be 1, 2, or 3\n"));
3117 switch( opt.s2k_mode ) {
3118 case 0:
3119 log_info(_("NOTE: simple S2K mode (0) is strongly discouraged\n"));
3120 break;
3121 case 1: case 3: break;
3122 default:
3123 log_error(_("invalid S2K mode; must be 0, 1 or 3\n"));
3126 /* This isn't actually needed, but does serve to error out if the
3127 string is invalid. */
3128 if(opt.def_preference_list &&
3129 keygen_set_std_prefs(opt.def_preference_list,0))
3130 log_error(_("invalid default preferences\n"));
3132 /* We provide defaults for the personal digest list. This is
3133 SHA-1. */
3134 if(!pers_digest_list)
3135 pers_digest_list="h2";
3137 if(pers_cipher_list &&
3138 keygen_set_std_prefs(pers_cipher_list,PREFTYPE_SYM))
3139 log_error(_("invalid personal cipher preferences\n"));
3141 if(pers_digest_list &&
3142 keygen_set_std_prefs(pers_digest_list,PREFTYPE_HASH))
3143 log_error(_("invalid personal digest preferences\n"));
3145 if(pers_compress_list &&
3146 keygen_set_std_prefs(pers_compress_list,PREFTYPE_ZIP))
3147 log_error(_("invalid personal compress preferences\n"));
3149 /* We don't support all possible commands with multifile yet */
3150 if(multifile)
3152 char *cmdname;
3154 switch(cmd)
3156 case aSign:
3157 cmdname="--sign";
3158 break;
3159 case aClearsign:
3160 cmdname="--clearsign";
3161 break;
3162 case aDetachedSign:
3163 cmdname="--detach-sign";
3164 break;
3165 case aSym:
3166 cmdname="--symmetric";
3167 break;
3168 case aEncrSym:
3169 cmdname="--symmetric --encrypt";
3170 break;
3171 case aStore:
3172 cmdname="--store";
3173 break;
3174 default:
3175 cmdname=NULL;
3176 break;
3179 if(cmdname)
3180 log_error(_("%s does not yet work with %s\n"),cmdname,"--multifile");
3183 if( log_get_errorcount(0) )
3184 g10_exit(2);
3186 if(opt.compress_level==0)
3187 opt.compress_algo=COMPRESS_ALGO_NONE;
3189 /* Check our chosen algorithms against the list of legal
3190 algorithms. */
3192 if(!GNUPG)
3194 const char *badalg=NULL;
3195 preftype_t badtype=PREFTYPE_NONE;
3197 if(opt.def_cipher_algo
3198 && !algo_available(PREFTYPE_SYM,opt.def_cipher_algo,NULL))
3200 badalg = openpgp_cipher_algo_name (opt.def_cipher_algo);
3201 badtype = PREFTYPE_SYM;
3203 else if(opt.def_digest_algo
3204 && !algo_available(PREFTYPE_HASH,opt.def_digest_algo,NULL))
3206 badalg = gcry_md_algo_name (opt.def_digest_algo);
3207 badtype = PREFTYPE_HASH;
3209 else if(opt.cert_digest_algo
3210 && !algo_available(PREFTYPE_HASH,opt.cert_digest_algo,NULL))
3212 badalg = gcry_md_algo_name (opt.cert_digest_algo);
3213 badtype = PREFTYPE_HASH;
3215 else if(opt.compress_algo!=-1
3216 && !algo_available(PREFTYPE_ZIP,opt.compress_algo,NULL))
3218 badalg = compress_algo_to_string(opt.compress_algo);
3219 badtype = PREFTYPE_ZIP;
3222 if(badalg)
3224 switch(badtype)
3226 case PREFTYPE_SYM:
3227 log_info(_("you may not use cipher algorithm `%s'"
3228 " while in %s mode\n"),
3229 badalg,compliance_option_string());
3230 break;
3231 case PREFTYPE_HASH:
3232 log_info(_("you may not use digest algorithm `%s'"
3233 " while in %s mode\n"),
3234 badalg,compliance_option_string());
3235 break;
3236 case PREFTYPE_ZIP:
3237 log_info(_("you may not use compression algorithm `%s'"
3238 " while in %s mode\n"),
3239 badalg,compliance_option_string());
3240 break;
3241 default:
3242 BUG();
3245 compliance_failure();
3249 /* Set the random seed file. */
3250 if( use_random_seed ) {
3251 char *p = make_filename(opt.homedir, "random_seed", NULL );
3252 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
3253 if (!access (p, F_OK))
3254 register_secured_file (p);
3255 xfree(p);
3258 if( !cmd && opt.fingerprint && !with_fpr ) {
3259 set_cmd( &cmd, aListKeys);
3262 /* kludge to let -sat generate a clear text signature */
3263 if( opt.textmode == 2 && !detached_sig && opt.armor && cmd == aSign )
3265 log_info ("compatibility note:\n");
3266 log_info ("\"-sat\" won't generate clear signed messages in "
3267 "future versions\n");
3268 log_info ("Use \"--clearsign\" instead of \"-sat\"\n");
3269 cmd = aClearsign;
3272 if( opt.verbose > 1 )
3273 set_packet_list_mode(1);
3275 /* Add the keyrings, but not for some special commands. Also
3276 avoid adding the secret keyring for a couple of commands to
3277 avoid unneeded access in case the secrings are stored on a
3278 floppy.
3280 We always need to add the keyrings if we are running under
3281 SELinux, this is so that the rings are added to the list of
3282 secured files. */
3283 if( ALWAYS_ADD_KEYRINGS
3284 || (cmd != aDeArmor && cmd != aEnArmor && cmd != aGPGConfTest) )
3286 if (ALWAYS_ADD_KEYRINGS
3287 || (cmd != aCheckKeys && cmd != aListSigs && cmd != aListKeys
3288 && cmd != aVerify && cmd != aSym))
3290 if (!sec_nrings || default_keyring) /* add default secret rings */
3291 keydb_add_resource ("secring" EXTSEP_S "gpg", 4, 1);
3292 for (sl = sec_nrings; sl; sl = sl->next)
3293 keydb_add_resource ( sl->d, 0, 1 );
3295 if( !nrings || default_keyring ) /* add default ring */
3296 keydb_add_resource ("pubring" EXTSEP_S "gpg", 4, 0);
3297 for(sl = nrings; sl; sl = sl->next )
3298 keydb_add_resource ( sl->d, sl->flags, 0 );
3300 FREE_STRLIST(nrings);
3301 FREE_STRLIST(sec_nrings);
3303 if (cmd == aGPGConfTest)
3304 g10_exit(0);
3307 if( pwfd != -1 ) /* Read the passphrase now. */
3308 read_passphrase_from_fd( pwfd );
3310 fname = argc? *argv : NULL;
3312 if(fname && utf8_strings)
3313 opt.flags.utf8_filename=1;
3315 switch( cmd ) {
3316 case aPrimegen:
3317 case aPrintMD:
3318 case aPrintMDs:
3319 case aGenRandom:
3320 case aDeArmor:
3321 case aEnArmor:
3322 case aFixTrustDB:
3323 break;
3324 case aExportOwnerTrust: rc = setup_trustdb( 0, trustdb_name ); break;
3325 case aListTrustDB: rc = setup_trustdb( argc? 1:0, trustdb_name ); break;
3326 default: rc = setup_trustdb(1, trustdb_name ); break;
3328 if( rc )
3329 log_error(_("failed to initialize the TrustDB: %s\n"), g10_errstr(rc));
3332 switch (cmd)
3334 case aStore:
3335 case aSym:
3336 case aSign:
3337 case aSignSym:
3338 case aClearsign:
3339 if (!opt.quiet && any_explicit_recipient)
3340 log_info (_("WARNING: recipients (-r) given "
3341 "without using public key encryption\n"));
3342 break;
3343 default:
3344 break;
3347 switch( cmd )
3349 case aServer:
3351 ctrl_t ctrl = xtrycalloc (1, sizeof *ctrl);
3352 gpg_init_default_ctrl (ctrl);
3353 gpg_server (ctrl);
3354 gpg_deinit_default_ctrl (ctrl);
3355 xfree (ctrl);
3357 break;
3359 case aStore: /* only store the file */
3360 if( argc > 1 )
3361 wrong_args(_("--store [filename]"));
3362 if( (rc = encode_store(fname)) )
3363 log_error ("storing `%s' failed: %s\n",
3364 print_fname_stdin(fname),g10_errstr(rc) );
3365 break;
3366 case aSym: /* encrypt the given file only with the symmetric cipher */
3367 if( argc > 1 )
3368 wrong_args(_("--symmetric [filename]"));
3369 if( (rc = encode_symmetric(fname)) )
3370 log_error (_("symmetric encryption of `%s' failed: %s\n"),
3371 print_fname_stdin(fname),g10_errstr(rc) );
3372 break;
3374 case aEncr: /* encrypt the given file */
3375 if(multifile)
3376 encode_crypt_files(argc, argv, remusr);
3377 else
3379 if( argc > 1 )
3380 wrong_args(_("--encrypt [filename]"));
3381 if( (rc = encode_crypt(fname,remusr,0)) )
3382 log_error("%s: encryption failed: %s\n",
3383 print_fname_stdin(fname), g10_errstr(rc) );
3385 break;
3387 case aEncrSym:
3388 /* This works with PGP 8 in the sense that it acts just like a
3389 symmetric message. It doesn't work at all with 2 or 6. It
3390 might work with 7, but alas, I don't have a copy to test
3391 with right now. */
3392 if( argc > 1 )
3393 wrong_args(_("--symmetric --encrypt [filename]"));
3394 else if(opt.s2k_mode==0)
3395 log_error(_("you cannot use --symmetric --encrypt"
3396 " with --s2k-mode 0\n"));
3397 else if(PGP2 || PGP6 || PGP7 || RFC1991)
3398 log_error(_("you cannot use --symmetric --encrypt"
3399 " while in %s mode\n"),compliance_option_string());
3400 else
3402 if( (rc = encode_crypt(fname,remusr,1)) )
3403 log_error("%s: encryption failed: %s\n",
3404 print_fname_stdin(fname), g10_errstr(rc) );
3406 break;
3408 case aSign: /* sign the given file */
3409 sl = NULL;
3410 if( detached_sig ) { /* sign all files */
3411 for( ; argc; argc--, argv++ )
3412 add_to_strlist( &sl, *argv );
3414 else {
3415 if( argc > 1 )
3416 wrong_args(_("--sign [filename]"));
3417 if( argc ) {
3418 sl = xmalloc_clear( sizeof *sl + strlen(fname));
3419 strcpy(sl->d, fname);
3422 if( (rc = sign_file( sl, detached_sig, locusr, 0, NULL, NULL)) )
3423 log_error("signing failed: %s\n", g10_errstr(rc) );
3424 free_strlist(sl);
3425 break;
3427 case aSignEncr: /* sign and encrypt the given file */
3428 if( argc > 1 )
3429 wrong_args(_("--sign --encrypt [filename]"));
3430 if( argc ) {
3431 sl = xmalloc_clear( sizeof *sl + strlen(fname));
3432 strcpy(sl->d, fname);
3434 else
3435 sl = NULL;
3436 if( (rc = sign_file(sl, detached_sig, locusr, 1, remusr, NULL)) )
3437 log_error("%s: sign+encrypt failed: %s\n",
3438 print_fname_stdin(fname), g10_errstr(rc) );
3439 free_strlist(sl);
3440 break;
3442 case aSignEncrSym: /* sign and encrypt the given file */
3443 if( argc > 1 )
3444 wrong_args(_("--symmetric --sign --encrypt [filename]"));
3445 else if(opt.s2k_mode==0)
3446 log_error(_("you cannot use --symmetric --sign --encrypt"
3447 " with --s2k-mode 0\n"));
3448 else if(PGP2 || PGP6 || PGP7 || RFC1991)
3449 log_error(_("you cannot use --symmetric --sign --encrypt"
3450 " while in %s mode\n"),compliance_option_string());
3451 else
3453 if( argc )
3455 sl = xmalloc_clear( sizeof *sl + strlen(fname));
3456 strcpy(sl->d, fname);
3458 else
3459 sl = NULL;
3460 if( (rc = sign_file(sl, detached_sig, locusr, 2, remusr, NULL)) )
3461 log_error("%s: symmetric+sign+encrypt failed: %s\n",
3462 print_fname_stdin(fname), g10_errstr(rc) );
3463 free_strlist(sl);
3465 break;
3467 case aSignSym: /* sign and conventionally encrypt the given file */
3468 if (argc > 1)
3469 wrong_args(_("--sign --symmetric [filename]"));
3470 rc = sign_symencrypt_file (fname, locusr);
3471 if (rc)
3472 log_error("%s: sign+symmetric failed: %s\n",
3473 print_fname_stdin(fname), g10_errstr(rc) );
3474 break;
3476 case aClearsign: /* make a clearsig */
3477 if( argc > 1 )
3478 wrong_args(_("--clearsign [filename]"));
3479 if( (rc = clearsign_file(fname, locusr, NULL)) )
3480 log_error("%s: clearsign failed: %s\n",
3481 print_fname_stdin(fname), g10_errstr(rc) );
3482 break;
3484 case aVerify:
3485 if(multifile)
3487 if( (rc = verify_files( argc, argv ) ))
3488 log_error("verify files failed: %s\n", g10_errstr(rc) );
3490 else
3492 if( (rc = verify_signatures( argc, argv ) ))
3493 log_error("verify signatures failed: %s\n", g10_errstr(rc) );
3495 break;
3497 case aDecrypt:
3498 if(multifile)
3499 decrypt_messages(argc, argv);
3500 else
3502 if( argc > 1 )
3503 wrong_args(_("--decrypt [filename]"));
3504 if( (rc = decrypt_message( fname ) ))
3505 log_error("decrypt_message failed: %s\n", g10_errstr(rc) );
3507 break;
3509 case aSignKey:
3510 if( argc != 1 )
3511 wrong_args(_("--sign-key user-id"));
3512 /* fall through */
3513 case aLSignKey:
3514 if( argc != 1 )
3515 wrong_args(_("--lsign-key user-id"));
3516 /* fall through */
3518 sl=NULL;
3520 if(cmd==aSignKey)
3521 append_to_strlist(&sl,"sign");
3522 else if(cmd==aLSignKey)
3523 append_to_strlist(&sl,"lsign");
3524 else
3525 BUG();
3527 append_to_strlist( &sl, "save" );
3528 username = make_username( fname );
3529 keyedit_menu(fname, locusr, sl, 0, 0 );
3530 xfree(username);
3531 free_strlist(sl);
3532 break;
3534 case aEditKey: /* Edit a key signature */
3535 if( !argc )
3536 wrong_args(_("--edit-key user-id [commands]"));
3537 username = make_username( fname );
3538 if( argc > 1 ) {
3539 sl = NULL;
3540 for( argc--, argv++ ; argc; argc--, argv++ )
3541 append_to_strlist( &sl, *argv );
3542 keyedit_menu( username, locusr, sl, 0, 1 );
3543 free_strlist(sl);
3545 else
3546 keyedit_menu(username, locusr, NULL, 0, 1 );
3547 xfree(username);
3548 break;
3550 case aDeleteKeys:
3551 case aDeleteSecretKeys:
3552 case aDeleteSecretAndPublicKeys:
3553 sl = NULL;
3554 /* I'm adding these in reverse order as add_to_strlist2
3555 reverses them again, and it's easier to understand in the
3556 proper order :) */
3557 for( ; argc; argc-- )
3558 add_to_strlist2( &sl, argv[argc-1], utf8_strings );
3559 delete_keys(sl,cmd==aDeleteSecretKeys,cmd==aDeleteSecretAndPublicKeys);
3560 free_strlist(sl);
3561 break;
3563 case aCheckKeys:
3564 opt.check_sigs = 1;
3565 case aListSigs:
3566 opt.list_sigs = 1;
3567 case aListKeys:
3568 sl = NULL;
3569 for( ; argc; argc--, argv++ )
3570 add_to_strlist2( &sl, *argv, utf8_strings );
3571 public_key_list( sl );
3572 free_strlist(sl);
3573 break;
3574 case aListSecretKeys:
3575 sl = NULL;
3576 for( ; argc; argc--, argv++ )
3577 add_to_strlist2( &sl, *argv, utf8_strings );
3578 secret_key_list( sl );
3579 free_strlist(sl);
3580 break;
3582 case aKeygen: /* generate a key */
3583 if( opt.batch ) {
3584 if( argc > 1 )
3585 wrong_args("--gen-key [parameterfile]");
3586 generate_keypair( argc? *argv : NULL, NULL, NULL );
3588 else {
3589 if( argc )
3590 wrong_args("--gen-key");
3591 generate_keypair(NULL, NULL, NULL);
3593 break;
3595 case aFastImport:
3596 opt.import_options |= IMPORT_FAST;
3597 case aImport:
3598 import_keys( argc? argv:NULL, argc, NULL, opt.import_options );
3599 break;
3601 /* TODO: There are a number of command that use this same
3602 "make strlist, call function, report error, free strlist"
3603 pattern. Join them together here and avoid all that
3604 duplicated code. */
3606 case aExport:
3607 case aSendKeys:
3608 case aRecvKeys:
3609 sl = NULL;
3610 for( ; argc; argc--, argv++ )
3611 append_to_strlist2( &sl, *argv, utf8_strings );
3612 if( cmd == aSendKeys )
3613 rc=keyserver_export( sl );
3614 else if( cmd == aRecvKeys )
3615 rc=keyserver_import( sl );
3616 else
3617 rc=export_pubkeys( sl, opt.export_options );
3618 if(rc)
3620 if(cmd==aSendKeys)
3621 log_error(_("keyserver send failed: %s\n"),g10_errstr(rc));
3622 else if(cmd==aRecvKeys)
3623 log_error(_("keyserver receive failed: %s\n"),g10_errstr(rc));
3624 else
3625 log_error(_("key export failed: %s\n"),g10_errstr(rc));
3627 free_strlist(sl);
3628 break;
3630 case aSearchKeys:
3631 sl = NULL;
3632 for( ; argc; argc--, argv++ )
3633 append_to_strlist2( &sl, *argv, utf8_strings );
3634 rc=keyserver_search( sl );
3635 if(rc)
3636 log_error(_("keyserver search failed: %s\n"),g10_errstr(rc));
3637 free_strlist(sl);
3638 break;
3640 case aRefreshKeys:
3641 sl = NULL;
3642 for( ; argc; argc--, argv++ )
3643 append_to_strlist2( &sl, *argv, utf8_strings );
3644 rc=keyserver_refresh(sl);
3645 if(rc)
3646 log_error(_("keyserver refresh failed: %s\n"),g10_errstr(rc));
3647 free_strlist(sl);
3648 break;
3650 case aFetchKeys:
3651 sl = NULL;
3652 for( ; argc; argc--, argv++ )
3653 append_to_strlist2( &sl, *argv, utf8_strings );
3654 rc=keyserver_fetch(sl);
3655 if(rc)
3656 log_error("key fetch failed: %s\n",g10_errstr(rc));
3657 free_strlist(sl);
3658 break;
3660 case aExportSecret:
3661 sl = NULL;
3662 for( ; argc; argc--, argv++ )
3663 add_to_strlist2( &sl, *argv, utf8_strings );
3664 export_seckeys( sl );
3665 free_strlist(sl);
3666 break;
3668 case aExportSecretSub:
3669 sl = NULL;
3670 for( ; argc; argc--, argv++ )
3671 add_to_strlist2( &sl, *argv, utf8_strings );
3672 export_secsubkeys( sl );
3673 free_strlist(sl);
3674 break;
3676 case aGenRevoke:
3677 if( argc != 1 )
3678 wrong_args("--gen-revoke user-id");
3679 username = make_username(*argv);
3680 gen_revoke( username );
3681 xfree( username );
3682 break;
3684 case aDesigRevoke:
3685 if( argc != 1 )
3686 wrong_args("--desig-revoke user-id");
3687 username = make_username(*argv);
3688 gen_desig_revoke( username, locusr );
3689 xfree( username );
3690 break;
3692 case aDeArmor:
3693 if( argc > 1 )
3694 wrong_args("--dearmor [file]");
3695 rc = dearmor_file( argc? *argv: NULL );
3696 if( rc )
3697 log_error(_("dearmoring failed: %s\n"), g10_errstr(rc));
3698 break;
3700 case aEnArmor:
3701 if( argc > 1 )
3702 wrong_args("--enarmor [file]");
3703 rc = enarmor_file( argc? *argv: NULL );
3704 if( rc )
3705 log_error(_("enarmoring failed: %s\n"), g10_errstr(rc));
3706 break;
3709 case aPrimegen:
3710 #if 0 /*FIXME*/
3711 { int mode = argc < 2 ? 0 : atoi(*argv);
3713 if( mode == 1 && argc == 2 ) {
3714 mpi_print( stdout, generate_public_prime( atoi(argv[1]) ), 1);
3716 else if( mode == 2 && argc == 3 ) {
3717 mpi_print( stdout, generate_elg_prime(
3718 0, atoi(argv[1]),
3719 atoi(argv[2]), NULL,NULL ), 1);
3721 else if( mode == 3 && argc == 3 ) {
3722 MPI *factors;
3723 mpi_print( stdout, generate_elg_prime(
3724 1, atoi(argv[1]),
3725 atoi(argv[2]), NULL,&factors ), 1);
3726 putchar('\n');
3727 mpi_print( stdout, factors[0], 1 ); /* print q */
3729 else if( mode == 4 && argc == 3 ) {
3730 MPI g = mpi_alloc(1);
3731 mpi_print( stdout, generate_elg_prime(
3732 0, atoi(argv[1]),
3733 atoi(argv[2]), g, NULL ), 1);
3734 putchar('\n');
3735 mpi_print( stdout, g, 1 );
3736 mpi_free(g);
3738 else
3739 wrong_args("--gen-prime mode bits [qbits] ");
3740 putchar('\n');
3742 #endif
3743 wrong_args("--gen-prime not yet supported ");
3744 break;
3746 case aGenRandom:
3748 int level = argc ? atoi(*argv):0;
3749 int count = argc > 1 ? atoi(argv[1]): 0;
3750 int endless = !count;
3752 if( argc < 1 || argc > 2 || level < 0 || level > 2 || count < 0 )
3753 wrong_args("--gen-random 0|1|2 [count]");
3755 while( endless || count ) {
3756 byte *p;
3757 /* Wee need a multiple of 3, so that in case of
3758 armored output we get a correct string. No
3759 linefolding is done, as it is best to levae this to
3760 other tools */
3761 size_t n = !endless && count < 99? count : 99;
3763 p = gcry_random_bytes (n, level);
3764 #ifdef HAVE_DOSISH_SYSTEM
3765 setmode ( fileno(stdout), O_BINARY );
3766 #endif
3767 if (opt.armor) {
3768 char *tmp = make_radix64_string (p, n);
3769 fputs (tmp, stdout);
3770 xfree (tmp);
3771 if (n%3 == 1)
3772 putchar ('=');
3773 if (n%3)
3774 putchar ('=');
3775 } else {
3776 fwrite( p, n, 1, stdout );
3778 xfree(p);
3779 if( !endless )
3780 count -= n;
3782 if (opt.armor)
3783 putchar ('\n');
3785 break;
3787 case aPrintMD:
3788 if( argc < 1)
3789 wrong_args("--print-md algo [files]");
3791 int all_algos = (**argv=='*' && !(*argv)[1]);
3792 int algo = all_algos? 0 : gcry_md_map_name (*argv);
3794 if( !algo && !all_algos )
3795 log_error(_("invalid hash algorithm `%s'\n"), *argv );
3796 else {
3797 argc--; argv++;
3798 if( !argc )
3799 print_mds(NULL, algo);
3800 else {
3801 for(; argc; argc--, argv++ )
3802 print_mds(*argv, algo);
3806 break;
3808 case aPrintMDs: /* old option */
3809 if( !argc )
3810 print_mds(NULL,0);
3811 else {
3812 for(; argc; argc--, argv++ )
3813 print_mds(*argv,0);
3815 break;
3817 case aListTrustDB:
3818 if( !argc )
3819 list_trustdb(NULL);
3820 else {
3821 for( ; argc; argc--, argv++ )
3822 list_trustdb( *argv );
3824 break;
3826 case aUpdateTrustDB:
3827 if( argc )
3828 wrong_args("--update-trustdb");
3829 update_trustdb();
3830 break;
3832 case aCheckTrustDB:
3833 /* Old versions allowed for arguments - ignore them */
3834 check_trustdb();
3835 break;
3837 case aFixTrustDB:
3838 log_error("this command is not yet implemented.\n");
3839 log_error("A workaround is to use \"--export-ownertrust\", remove\n");
3840 log_error("the trustdb file and do an \"--import-ownertrust\".\n" );
3841 break;
3843 case aListTrustPath:
3844 if( !argc )
3845 wrong_args("--list-trust-path <user-ids>");
3846 for( ; argc; argc--, argv++ ) {
3847 username = make_username( *argv );
3848 list_trust_path( username );
3849 xfree(username);
3851 break;
3853 case aExportOwnerTrust:
3854 if( argc )
3855 wrong_args("--export-ownertrust");
3856 export_ownertrust();
3857 break;
3859 case aImportOwnerTrust:
3860 if( argc > 1 )
3861 wrong_args("--import-ownertrust [file]");
3862 import_ownertrust( argc? *argv:NULL );
3863 break;
3865 case aRebuildKeydbCaches:
3866 if (argc)
3867 wrong_args ("--rebuild-keydb-caches");
3868 keydb_rebuild_caches (1);
3869 break;
3871 #ifdef ENABLE_CARD_SUPPORT
3872 case aCardStatus:
3873 if (argc)
3874 wrong_args ("--card-status");
3875 card_status (stdout, NULL, 0);
3876 break;
3878 case aCardEdit:
3879 if (argc) {
3880 sl = NULL;
3881 for (argc--, argv++ ; argc; argc--, argv++)
3882 append_to_strlist (&sl, *argv);
3883 card_edit (sl);
3884 free_strlist (sl);
3886 else
3887 card_edit (NULL);
3888 break;
3890 case aChangePIN:
3891 if (!argc)
3892 change_pin (0,1);
3893 else if (argc == 1)
3894 change_pin (atoi (*argv),1);
3895 else
3896 wrong_args ("--change-pin [no]");
3897 break;
3898 #endif /* ENABLE_CARD_SUPPORT*/
3900 case aListConfig:
3902 char *str=collapse_args(argc,argv);
3903 list_config(str);
3904 xfree(str);
3906 break;
3908 case aListPackets:
3909 opt.list_packets=2;
3910 default:
3911 if( argc > 1 )
3912 wrong_args(_("[filename]"));
3913 /* Issue some output for the unix newbie */
3914 if( !fname && !opt.outfile && isatty( fileno(stdin) )
3915 && isatty( fileno(stdout) ) && isatty( fileno(stderr) ) )
3916 log_info(_("Go ahead and type your message ...\n"));
3918 a = iobuf_open(fname);
3919 if (a && is_secured_file (iobuf_get_fd (a)))
3921 iobuf_close (a);
3922 a = NULL;
3923 errno = EPERM;
3925 if( !a )
3926 log_error(_("can't open `%s'\n"), print_fname_stdin(fname));
3927 else {
3929 if( !opt.no_armor ) {
3930 if( use_armor_filter( a ) ) {
3931 afx = new_armor_context ();
3932 push_armor_filter (afx, a);
3935 if( cmd == aListPackets ) {
3936 set_packet_list_mode(1);
3937 opt.list_packets=1;
3939 rc = proc_packets(NULL, a );
3940 if( rc )
3941 log_error("processing message failed: %s\n", g10_errstr(rc) );
3942 iobuf_close(a);
3944 break;
3947 /* cleanup */
3948 release_armor_context (afx);
3949 FREE_STRLIST(remusr);
3950 FREE_STRLIST(locusr);
3951 g10_exit(0);
3952 return 8; /*NEVER REACHED*/
3956 /* Note: This function is used by signal handlers!. */
3957 static void
3958 emergency_cleanup (void)
3960 gcry_control (GCRYCTL_TERM_SECMEM );
3964 void
3965 g10_exit( int rc )
3967 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
3968 if ( (opt.debug & DBG_MEMSTAT_VALUE) )
3970 gcry_control (GCRYCTL_DUMP_MEMORY_STATS);
3971 gcry_control (GCRYCTL_DUMP_RANDOM_STATS);
3973 if (opt.debug)
3974 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
3976 emergency_cleanup ();
3978 rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0;
3979 exit (rc);
3983 /* Pretty-print hex hashes. This assumes at least an 80-character
3984 display, but there are a few other similar assumptions in the
3985 display code. */
3986 static void
3987 print_hex( gcry_md_hd_t md, int algo, const char *fname )
3989 int i,n,count,indent=0;
3990 const byte *p;
3992 if(fname)
3993 indent=printf("%s: ",fname);
3995 if(indent>40)
3997 printf("\n");
3998 indent=0;
4001 if(algo==DIGEST_ALGO_RMD160)
4002 indent+=printf("RMD160 = ");
4003 else if(algo>0)
4004 indent+=printf("%6s = ", gcry_md_algo_name (algo));
4005 else
4006 algo=abs(algo);
4008 count=indent;
4010 p = gcry_md_read (md, algo);
4011 n = gcry_md_get_algo_dlen (algo);
4013 count += printf ("%02X",*p++);
4015 for(i=1;i<n;i++,p++)
4017 if(n==16)
4019 if(count+2>79)
4021 printf("\n%*s",indent," ");
4022 count=indent;
4024 else
4025 count+=printf(" ");
4027 if(!(i%8))
4028 count+=printf(" ");
4030 else if (n==20)
4032 if(!(i%2))
4034 if(count+4>79)
4036 printf("\n%*s",indent," ");
4037 count=indent;
4039 else
4040 count+=printf(" ");
4043 if(!(i%10))
4044 count+=printf(" ");
4046 else
4048 if(!(i%4))
4050 if(count+8>79)
4052 printf("\n%*s",indent," ");
4053 count=indent;
4055 else
4056 count+=printf(" ");
4060 count+=printf("%02X",*p);
4063 printf("\n");
4066 static void
4067 print_hashline( gcry_md_hd_t md, int algo, const char *fname )
4069 int i, n;
4070 const byte *p;
4072 if ( fname ) {
4073 for (p = fname; *p; p++ ) {
4074 if ( *p <= 32 || *p > 127 || *p == ':' || *p == '%' )
4075 printf("%%%02X", *p );
4076 else
4077 putchar( *p );
4080 putchar(':');
4081 printf("%d:", algo );
4082 p = gcry_md_read (md, algo);
4083 n = gcry_md_get_algo_dlen (algo);
4084 for(i=0; i < n ; i++, p++ )
4085 printf("%02X", *p );
4086 putchar(':');
4087 putchar('\n');
4090 static void
4091 print_mds( const char *fname, int algo )
4093 FILE *fp;
4094 char buf[1024];
4095 size_t n;
4096 gcry_md_hd_t md;
4098 if( !fname ) {
4099 fp = stdin;
4100 #ifdef HAVE_DOSISH_SYSTEM
4101 setmode ( fileno(fp) , O_BINARY );
4102 #endif
4104 else {
4105 fp = fopen( fname, "rb" );
4106 if (fp && is_secured_file (fileno (fp)))
4108 fclose (fp);
4109 fp = NULL;
4110 errno = EPERM;
4113 if( !fp ) {
4114 log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
4115 return;
4118 gcry_md_open (&md, 0, 0);
4119 if( algo )
4120 gcry_md_enable (md, algo);
4121 else {
4122 gcry_md_enable (md, GCRY_MD_MD5);
4123 gcry_md_enable (md, GCRY_MD_SHA1);
4124 gcry_md_enable (md, GCRY_MD_RMD160);
4125 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA224))
4126 gcry_md_enable (md, DIGEST_ALGO_SHA224);
4127 if (!openpgp_md_test_algo (GCRY_MD_SHA256))
4128 gcry_md_enable (md, GCRY_MD_SHA256);
4129 if (!openpgp_md_test_algo (GCRY_MD_SHA384))
4130 gcry_md_enable (md, GCRY_MD_SHA384);
4131 if (!openpgp_md_test_algo (GCRY_MD_SHA512))
4132 gcry_md_enable (md, GCRY_MD_SHA512);
4135 while( (n=fread( buf, 1, DIM(buf), fp )) )
4136 gcry_md_write (md, buf, n);
4137 if( ferror(fp) )
4138 log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
4139 else {
4140 gcry_md_final (md);
4141 if ( opt.with_colons ) {
4142 if ( algo )
4143 print_hashline( md, algo, fname );
4144 else {
4145 print_hashline( md, GCRY_MD_MD5, fname );
4146 print_hashline( md, GCRY_MD_SHA1, fname );
4147 print_hashline( md, GCRY_MD_RMD160, fname );
4148 if (!gcry_md_test_algo (DIGEST_ALGO_SHA224))
4149 print_hashline (md, DIGEST_ALGO_SHA224, fname);
4150 if (!gcry_md_test_algo (GCRY_MD_SHA256))
4151 print_hashline( md, GCRY_MD_SHA256, fname );
4152 if (!gcry_md_test_algo (GCRY_MD_SHA384))
4153 print_hashline ( md, GCRY_MD_SHA384, fname );
4154 if (!gcry_md_test_algo (GCRY_MD_SHA512))
4155 print_hashline ( md, GCRY_MD_SHA512, fname );
4158 else {
4159 if( algo )
4160 print_hex(md,-algo,fname);
4161 else {
4162 print_hex( md, GCRY_MD_MD5, fname );
4163 print_hex( md, GCRY_MD_SHA1, fname );
4164 print_hex( md, GCRY_MD_RMD160, fname );
4165 if (!gcry_md_test_algo (DIGEST_ALGO_SHA224))
4166 print_hex (md, DIGEST_ALGO_SHA224, fname);
4167 if (!gcry_md_test_algo (GCRY_MD_SHA256))
4168 print_hex( md, GCRY_MD_SHA256, fname );
4169 if (!gcry_md_test_algo (GCRY_MD_SHA384))
4170 print_hex( md, GCRY_MD_SHA384, fname );
4171 if (!gcry_md_test_algo (GCRY_MD_SHA512))
4172 print_hex( md, GCRY_MD_SHA512, fname );
4176 gcry_md_close(md);
4178 if( fp != stdin )
4179 fclose(fp);
4183 /****************
4184 * Check the supplied name,value string and add it to the notation
4185 * data to be used for signatures. which==0 for sig notations, and 1
4186 * for cert notations.
4188 static void
4189 add_notation_data( const char *string, int which )
4191 struct notation *notation;
4193 notation=string_to_notation(string,utf8_strings);
4194 if(notation)
4196 if(which)
4198 notation->next=opt.cert_notations;
4199 opt.cert_notations=notation;
4201 else
4203 notation->next=opt.sig_notations;
4204 opt.sig_notations=notation;
4209 static void
4210 add_policy_url( const char *string, int which )
4212 unsigned int i,critical=0;
4213 strlist_t sl;
4215 if(*string=='!')
4217 string++;
4218 critical=1;
4221 for(i=0;i<strlen(string);i++)
4222 if( !isascii (string[i]) || iscntrl(string[i]))
4223 break;
4225 if(i==0 || i<strlen(string))
4227 if(which)
4228 log_error(_("the given certification policy URL is invalid\n"));
4229 else
4230 log_error(_("the given signature policy URL is invalid\n"));
4233 if(which)
4234 sl=add_to_strlist( &opt.cert_policy_url, string );
4235 else
4236 sl=add_to_strlist( &opt.sig_policy_url, string );
4238 if(critical)
4239 sl->flags |= 1;
4242 static void
4243 add_keyserver_url( const char *string, int which )
4245 unsigned int i,critical=0;
4246 strlist_t sl;
4248 if(*string=='!')
4250 string++;
4251 critical=1;
4254 for(i=0;i<strlen(string);i++)
4255 if( !isascii (string[i]) || iscntrl(string[i]))
4256 break;
4258 if(i==0 || i<strlen(string))
4260 if(which)
4261 BUG();
4262 else
4263 log_error(_("the given preferred keyserver URL is invalid\n"));
4266 if(which)
4267 BUG();
4268 else
4269 sl=add_to_strlist( &opt.sig_keyserver_url, string );
4271 if(critical)
4272 sl->flags |= 1;