2006-09-06 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / gpg.c
blob826cdd30537abc1fdfe98b3edcfd3883cfac41db
1 /* gpg.c - The GnuPG utility (main for gpg)
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3 * 2006 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 2 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, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
20 * USA.
23 #include <config.h>
24 #include <errno.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <ctype.h>
29 #include <unistd.h>
30 #include <assert.h>
31 #ifdef HAVE_DOSISH_SYSTEM
32 #include <fcntl.h> /* for setmode() */
33 #endif
34 #ifdef HAVE_STAT
35 #include <sys/stat.h> /* for stat() */
36 #endif
37 #include <fcntl.h>
38 #include <assuan.h>
39 #ifdef HAVE_W32_SYSTEM
40 #include <windows.h>
41 #endif
43 #define INCLUDED_BY_MAIN_MODULE 1
44 #include "gpg.h"
45 #include "packet.h"
46 #include "../common/iobuf.h"
47 #include "util.h"
48 #include "main.h"
49 #include "options.h"
50 #include "keydb.h"
51 #include "trustdb.h"
52 #include "cipher.h"
53 #include "filter.h"
54 #include "ttyio.h"
55 #include "i18n.h"
56 #include "status.h"
57 #include "keyserver-internal.h"
58 #include "exec.h"
61 #if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
62 #define MY_O_BINARY O_BINARY
63 #ifndef S_IRGRP
64 # define S_IRGRP 0
65 # define S_IWGRP 0
66 #endif
67 #else
68 #define MY_O_BINARY 0
69 #endif
72 enum cmd_and_opt_values
74 aNull = 0,
75 oArmor = 'a',
76 aDetachedSign = 'b',
77 aSym = 'c',
78 aDecrypt = 'd',
79 aEncr = 'e',
80 oInteractive = 'i',
81 oKOption = 'k',
82 oDryRun = 'n',
83 oOutput = 'o',
84 oQuiet = 'q',
85 oRecipient = 'r',
86 oHiddenRecipient = 'R',
87 aSign = 's',
88 oTextmodeShort= 't',
89 oLocalUser = 'u',
90 oVerbose = 'v',
91 oCompress = 'z',
92 oSetNotation = 'N',
93 aListSecretKeys = 'K',
94 oBatch = 500,
95 oMaxOutput,
96 oSigNotation,
97 oCertNotation,
98 oShowNotation,
99 oNoShowNotation,
100 aEncrFiles,
101 aEncrSym,
102 aDecryptFiles,
103 aClearsign,
104 aStore,
105 aKeygen,
106 aSignEncr,
107 aSignEncrSym,
108 aSignSym,
109 aSignKey,
110 aLSignKey,
111 aListConfig,
112 aGPGConfList,
113 aListPackets,
114 aEditKey,
115 aDeleteKeys,
116 aDeleteSecretKeys,
117 aDeleteSecretAndPublicKeys,
118 aKMode,
119 aKModeC,
120 aImport,
121 aFastImport,
122 aVerify,
123 aVerifyFiles,
124 aListKeys,
125 aListSigs,
126 aSendKeys,
127 aRecvKeys,
128 aSearchKeys,
129 aRefreshKeys,
130 aFetchKeys,
131 aExport,
132 aExportSecret,
133 aExportSecretSub,
134 aCheckKeys,
135 aGenRevoke,
136 aDesigRevoke,
137 aPrimegen,
138 aPrintMD,
139 aPrintMDs,
140 aCheckTrustDB,
141 aUpdateTrustDB,
142 aFixTrustDB,
143 aListTrustDB,
144 aListTrustPath,
145 aExportOwnerTrust,
146 aListOwnerTrust,
147 aImportOwnerTrust,
148 aDeArmor,
149 aEnArmor,
150 aGenRandom,
151 aRebuildKeydbCaches,
152 aCardStatus,
153 aCardEdit,
154 aChangePIN,
156 oTextmode,
157 oNoTextmode,
158 oExpert,
159 oNoExpert,
160 oDefSigExpire,
161 oAskSigExpire,
162 oNoAskSigExpire,
163 oDefCertExpire,
164 oAskCertExpire,
165 oNoAskCertExpire,
166 oDefCertLevel,
167 oMinCertLevel,
168 oAskCertLevel,
169 oNoAskCertLevel,
170 oFingerprint,
171 oWithFingerprint,
172 oAnswerYes,
173 oAnswerNo,
174 oKeyring,
175 oPrimaryKeyring,
176 oSecretKeyring,
177 oShowKeyring,
178 oDefaultKey,
179 oDefRecipient,
180 oDefRecipientSelf,
181 oNoDefRecipient,
182 oOptions,
183 oDebug,
184 oDebugLevel,
185 oDebugAll,
186 oDebugCCIDDriver,
187 oStatusFD,
188 oStatusFile,
189 oAttributeFD,
190 oAttributeFile,
191 oEmitVersion,
192 oNoEmitVersion,
193 oCompletesNeeded,
194 oMarginalsNeeded,
195 oMaxCertDepth,
196 oLoadExtension,
197 oGnuPG,
198 oRFC1991,
199 oRFC2440,
200 oOpenPGP,
201 oPGP2,
202 oPGP6,
203 oPGP7,
204 oPGP8,
205 oRFC2440Text,
206 oNoRFC2440Text,
207 oCipherAlgo,
208 oDigestAlgo,
209 oCertDigestAlgo,
210 oCompressAlgo,
211 oCompressLevel,
212 oBZ2CompressLevel,
213 oBZ2DecompressLowmem,
214 oPasswd,
215 oPasswdFD,
216 oPasswdFile,
217 oCommandFD,
218 oCommandFile,
219 oQuickRandom,
220 oNoVerbose,
221 oTrustDBName,
222 oNoSecmemWarn,
223 oRequireSecmem,
224 oNoRequireSecmem,
225 oNoPermissionWarn,
226 oNoMDCWarn,
227 oNoArmor,
228 oNoDefKeyring,
229 oNoGreeting,
230 oNoTTY,
231 oNoOptions,
232 oNoBatch,
233 oHomedir,
234 oWithColons,
235 oWithKeyData,
236 oSkipVerify,
237 oCompressKeys,
238 oCompressSigs,
239 oAlwaysTrust,
240 oTrustModel,
241 oForceOwnertrust,
242 oSetFilename,
243 oForYourEyesOnly,
244 oNoForYourEyesOnly,
245 oSetPolicyURL,
246 oSigPolicyURL,
247 oCertPolicyURL,
248 oShowPolicyURL,
249 oNoShowPolicyURL,
250 oSigKeyserverURL,
251 oUseEmbeddedFilename,
252 oNoUseEmbeddedFilename,
253 oComment,
254 oDefaultComment,
255 oNoComments,
256 oThrowKeyids,
257 oNoThrowKeyids,
258 oShowPhotos,
259 oNoShowPhotos,
260 oPhotoViewer,
261 oForceV3Sigs,
262 oNoForceV3Sigs,
263 oForceV4Certs,
264 oNoForceV4Certs,
265 oForceMDC,
266 oNoForceMDC,
267 oDisableMDC,
268 oNoDisableMDC,
269 oS2KMode,
270 oS2KDigest,
271 oS2KCipher,
272 oSimpleSKChecksum,
273 oDisplayCharset,
274 oNotDashEscaped,
275 oEscapeFrom,
276 oNoEscapeFrom,
277 oLockOnce,
278 oLockMultiple,
279 oLockNever,
280 oKeyServer,
281 oKeyServerOptions,
282 oImportOptions,
283 oExportOptions,
284 oListOptions,
285 oVerifyOptions,
286 oTempDir,
287 oExecPath,
288 oEncryptTo,
289 oHiddenEncryptTo,
290 oNoEncryptTo,
291 oLoggerFD,
292 oLoggerFile,
293 oUtf8Strings,
294 oNoUtf8Strings,
295 oDisableCipherAlgo,
296 oDisablePubkeyAlgo,
297 oAllowNonSelfsignedUID,
298 oNoAllowNonSelfsignedUID,
299 oAllowFreeformUID,
300 oNoAllowFreeformUID,
301 oAllowSecretKeyImport,
302 oEnableSpecialFilenames,
303 oNoLiteral,
304 oSetFilesize,
305 oHonorHttpProxy,
306 oFastListMode,
307 oListOnly,
308 oIgnoreTimeConflict,
309 oIgnoreValidFrom,
310 oIgnoreCrcError,
311 oIgnoreMDCError,
312 oShowSessionKey,
313 oOverrideSessionKey,
314 oNoRandomSeedFile,
315 oAutoKeyRetrieve,
316 oNoAutoKeyRetrieve,
317 oUseAgent,
318 oNoUseAgent,
319 oGpgAgentInfo,
320 oMergeOnly,
321 oTryAllSecrets,
322 oTrustedKey,
323 oNoExpensiveTrustChecks,
324 oFixedListMode,
325 oNoSigCache,
326 oNoSigCreateCheck,
327 oAutoCheckTrustDB,
328 oNoAutoCheckTrustDB,
329 oPreservePermissions,
330 oDefaultPreferenceList,
331 oDefaultKeyserverURL,
332 oPersonalCipherPreferences,
333 oPersonalDigestPreferences,
334 oPersonalCompressPreferences,
335 oAgentProgram,
336 oDisplay,
337 oTTYname,
338 oTTYtype,
339 oLCctype,
340 oLCmessages,
341 oGroup,
342 oUnGroup,
343 oNoGroups,
344 oStrict,
345 oNoStrict,
346 oMangleDosFilenames,
347 oNoMangleDosFilenames,
348 oEnableProgressFilter,
349 oMultifile,
350 oKeyidFormat,
351 oExitOnStatusWriteError,
352 oLimitCardInsertTries,
353 oRequireCrossCert,
354 oNoRequireCrossCert,
355 oAutoKeyLocate,
356 oNoAutoKeyLocate,
357 oAllowMultisigVerification,
358 oEnableDSA2,
359 oDisableDSA2,
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 { aListPackets, "list-packets",256, "@"},
415 { aExportOwnerTrust, "export-ownertrust", 256, "@"},
416 { aImportOwnerTrust, "import-ownertrust", 256, "@"},
417 { aUpdateTrustDB,
418 "update-trustdb",0 , N_("update the trust database")},
419 { aCheckTrustDB, "check-trustdb", 0, "@"},
420 { aFixTrustDB, "fix-trustdb", 0, "@"},
421 { aDeArmor, "dearmor", 256, "@"},
422 { aDeArmor, "dearmour", 256, "@"},
423 { aEnArmor, "enarmor", 256, "@"},
424 { aEnArmor, "enarmour", 256, "@"},
425 { aPrintMD, "print-md" , 256, N_("|algo [files]|print message digests")},
426 { aPrimegen, "gen-prime" , 256, "@" },
427 { aGenRandom, "gen-random" , 256, "@" },
429 { 301, NULL, 0, N_("@\nOptions:\n ") },
431 { oArmor, "armor", 0, N_("create ascii armored output")},
432 { oArmor, "armour", 0, "@" },
433 { oRecipient, "recipient", 2, N_("|NAME|encrypt for NAME")},
434 { oHiddenRecipient, "hidden-recipient", 2, "@" },
435 { oRecipient, "remote-user", 2, "@"}, /* old option name */
436 { oDefRecipient, "default-recipient", 2, "@"},
437 { oDefRecipientSelf, "default-recipient-self", 0, "@"},
438 { oNoDefRecipient, "no-default-recipient", 0, "@" },
439 { oTempDir, "temp-directory", 2, "@" },
440 { oExecPath, "exec-path", 2, "@" },
441 { oEncryptTo, "encrypt-to", 2, "@" },
442 { oHiddenEncryptTo, "hidden-encrypt-to", 2, "@" },
443 { oNoEncryptTo, "no-encrypt-to", 0, "@" },
444 { oLocalUser, "local-user",2, N_("use this user-id to sign or decrypt")},
445 { oCompress, NULL, 1, N_("|N|set compress level N (0 disables)") },
446 { oCompressLevel, "compress-level", 1, "@" },
447 { oBZ2CompressLevel, "bzip2-compress-level", 1, "@" },
448 { oBZ2DecompressLowmem, "bzip2-decompress-lowmem", 0, "@" },
449 { oTextmodeShort, NULL, 0, "@"},
450 { oTextmode, "textmode", 0, N_("use canonical text mode")},
451 { oNoTextmode, "no-textmode", 0, "@"},
452 { oExpert, "expert", 0, "@"},
453 { oNoExpert, "no-expert", 0, "@"},
454 { oDefSigExpire, "default-sig-expire", 2, "@"},
455 { oAskSigExpire, "ask-sig-expire", 0, "@"},
456 { oNoAskSigExpire, "no-ask-sig-expire", 0, "@"},
457 { oDefCertExpire, "default-cert-expire", 2, "@"},
458 { oAskCertExpire, "ask-cert-expire", 0, "@"},
459 { oNoAskCertExpire, "no-ask-cert-expire", 0, "@"},
460 { oDefCertLevel, "default-cert-level", 1, "@"},
461 { oMinCertLevel, "min-cert-level", 1, "@"},
462 { oAskCertLevel, "ask-cert-level", 0, "@"},
463 { oNoAskCertLevel, "no-ask-cert-level", 0, "@"},
464 { oOutput, "output", 2, N_("use as output file")},
465 { oMaxOutput, "max-output", 16|4, "@" },
466 { oVerbose, "verbose", 0, N_("verbose") },
467 { oQuiet, "quiet", 0, "@"},
468 { oNoTTY, "no-tty", 0, "@"},
469 { oForceV3Sigs, "force-v3-sigs", 0, "@"},
470 { oNoForceV3Sigs, "no-force-v3-sigs", 0, "@"},
471 { oForceV4Certs, "force-v4-certs", 0, "@"},
472 { oNoForceV4Certs, "no-force-v4-certs", 0, "@"},
473 { oForceMDC, "force-mdc", 0, "@"},
474 { oNoForceMDC, "no-force-mdc", 0, "@" },
475 { oDisableMDC, "disable-mdc", 0, "@"},
476 { oNoDisableMDC, "no-disable-mdc", 0, "@" },
477 { oDryRun, "dry-run", 0, N_("do not make any changes") },
478 { oInteractive, "interactive", 0, N_("prompt before overwriting") },
479 { oUseAgent, "use-agent",0, "@"},
480 { oNoUseAgent, "no-use-agent",0, "@"},
481 { oGpgAgentInfo, "gpg-agent-info",2, "@"},
482 { oBatch, "batch", 0, "@"},
483 { oAnswerYes, "yes", 0, "@"},
484 { oAnswerNo, "no", 0, "@"},
485 { oKeyring, "keyring", 2, "@"},
486 { oPrimaryKeyring, "primary-keyring",2, "@" },
487 { oSecretKeyring, "secret-keyring", 2, "@"},
488 { oShowKeyring, "show-keyring", 0, "@"},
489 { oDefaultKey, "default-key", 2, "@"},
490 { oKeyServer, "keyserver", 2, "@"},
491 { oKeyServerOptions, "keyserver-options",2,"@"},
492 { oImportOptions, "import-options",2,"@"},
493 { oExportOptions, "export-options",2,"@"},
494 { oListOptions, "list-options",2,"@"},
495 { oVerifyOptions, "verify-options",2,"@"},
496 { oDisplayCharset, "display-charset", 2, "@"},
497 { oDisplayCharset, "charset", 2, "@"},
498 { oOptions, "options", 2, "@"},
499 { oDebug, "debug" ,4|16, "@"},
500 { oDebugLevel, "debug-level" ,2, "@"},
501 { oDebugAll, "debug-all" ,0, "@"},
502 { oStatusFD, "status-fd" ,1, "@"},
503 { oStatusFile, "status-file" ,2, "@"},
504 { oAttributeFD, "attribute-fd" ,1, "@" },
505 { oAttributeFile, "attribute-file" ,2, "@" },
506 { oNoop, "sk-comments", 0, "@"},
507 { oNoop, "no-sk-comments", 0, "@"},
508 { oCompletesNeeded, "completes-needed", 1, "@"},
509 { oMarginalsNeeded, "marginals-needed", 1, "@"},
510 { oMaxCertDepth, "max-cert-depth", 1, "@" },
511 { oTrustedKey, "trusted-key", 2, "@"},
512 { oLoadExtension, "load-extension", 2, "@"},
513 { oGnuPG, "gnupg", 0, "@"},
514 { oGnuPG, "no-pgp2", 0, "@"},
515 { oGnuPG, "no-pgp6", 0, "@"},
516 { oGnuPG, "no-pgp7", 0, "@"},
517 { oGnuPG, "no-pgp8", 0, "@"},
518 { oRFC1991, "rfc1991", 0, "@"},
519 { oRFC2440, "rfc2440", 0, "@" },
520 { oOpenPGP, "openpgp", 0, N_("use strict OpenPGP behavior")},
521 { oPGP2, "pgp2", 0, N_("generate PGP 2.x compatible messages")},
522 { oPGP6, "pgp6", 0, "@"},
523 { oPGP7, "pgp7", 0, "@"},
524 { oPGP8, "pgp8", 0, "@"},
525 { oRFC2440Text, "rfc2440-text", 0, "@"},
526 { oNoRFC2440Text, "no-rfc2440-text", 0, "@"},
527 { oS2KMode, "s2k-mode", 1, "@"},
528 { oS2KDigest, "s2k-digest-algo", 2, "@"},
529 { oS2KCipher, "s2k-cipher-algo", 2, "@"},
530 { oSimpleSKChecksum, "simple-sk-checksum", 0, "@"},
531 { oCipherAlgo, "cipher-algo", 2, "@"},
532 { oDigestAlgo, "digest-algo", 2, "@"},
533 { oCertDigestAlgo, "cert-digest-algo", 2 , "@" },
534 { oCompressAlgo,"compress-algo", 2, "@"},
535 { oCompressAlgo, "compression-algo", 2, "@"}, /* Alias */
536 { oThrowKeyids, "throw-keyid", 0, "@"},
537 { oThrowKeyids, "throw-keyids", 0, "@"},
538 { oNoThrowKeyids, "no-throw-keyid", 0, "@" },
539 { oNoThrowKeyids, "no-throw-keyids", 0, "@" },
540 { oShowPhotos, "show-photos", 0, "@" },
541 { oNoShowPhotos, "no-show-photos", 0, "@" },
542 { oPhotoViewer, "photo-viewer", 2, "@" },
543 { oSetNotation, "set-notation", 2, "@" },
544 { oSetNotation, "notation-data", 2, "@" }, /* Alias */
545 { oSigNotation, "sig-notation", 2, "@" },
546 { oCertNotation, "cert-notation", 2, "@" },
548 { 302, NULL, 0, N_(
549 "@\n(See the man page for a complete listing of all commands and options)\n"
552 { 303, NULL, 0, N_("@\nExamples:\n\n"
553 " -se -r Bob [file] sign and encrypt for user Bob\n"
554 " --clearsign [file] make a clear text signature\n"
555 " --detach-sign [file] make a detached signature\n"
556 " --list-keys [names] show keys\n"
557 " --fingerprint [names] show fingerprints\n" ) },
559 /* hidden options */
560 { aListOwnerTrust, "list-ownertrust", 256, "@"}, /* deprecated */
561 { aPrintMDs, "print-mds" , 256, "@"}, /* old */
562 { aListTrustDB, "list-trustdb",0 , "@"},
563 /* Not yet used */
564 /* { aListTrustPath, "list-trust-path",0, "@"}, */
565 { oKOption, NULL, 0, "@"},
566 { oPasswd, "passphrase",2, "@" },
567 { oPasswdFD, "passphrase-fd",1, "@" },
568 { oPasswdFile, "passphrase-file",2, "@" },
569 { oCommandFD, "command-fd",1, "@" },
570 { oCommandFile, "command-file",2, "@" },
571 { oQuickRandom, "debug-quick-random", 0, "@"},
572 { oNoVerbose, "no-verbose", 0, "@"},
573 { oTrustDBName, "trustdb-name", 2, "@" },
574 { oNoSecmemWarn, "no-secmem-warning", 0, "@" },
575 { oRequireSecmem,"require-secmem", 0, "@" },
576 { oNoRequireSecmem,"no-require-secmem", 0, "@" },
577 { oNoPermissionWarn, "no-permission-warning", 0, "@" },
578 { oNoMDCWarn, "no-mdc-warning", 0, "@" },
579 { oNoArmor, "no-armor", 0, "@"},
580 { oNoArmor, "no-armour", 0, "@"},
581 { oNoDefKeyring, "no-default-keyring", 0, "@" },
582 { oNoGreeting, "no-greeting", 0, "@" },
583 { oNoOptions, "no-options", 0, "@" }, /* shortcut for --options /dev/null */
584 { oHomedir, "homedir", 2, "@" }, /* defaults to "~/.gnupg" */
585 { oNoBatch, "no-batch", 0, "@" },
586 { oWithColons, "with-colons", 0, "@"},
587 { oWithKeyData,"with-key-data", 0, "@"},
588 { aListKeys, "list-key", 0, "@" }, /* alias */
589 { aListSigs, "list-sig", 0, "@" }, /* alias */
590 { aCheckKeys, "check-sig",0, "@" }, /* alias */
591 { oSkipVerify, "skip-verify",0, "@" },
592 { oCompressKeys, "compress-keys",0, "@"},
593 { oCompressSigs, "compress-sigs",0, "@"},
594 { oDefCertLevel, "default-cert-check-level", 1, "@"}, /* Old option */
595 { oAlwaysTrust, "always-trust", 0, "@"},
596 { oTrustModel, "trust-model", 2, "@"},
597 { oForceOwnertrust, "force-ownertrust", 2, "@"},
598 { oSetFilename, "set-filename", 2, "@" },
599 { oForYourEyesOnly, "for-your-eyes-only", 0, "@" },
600 { oNoForYourEyesOnly, "no-for-your-eyes-only", 0, "@" },
601 { oSetPolicyURL, "set-policy-url", 2, "@" },
602 { oSigPolicyURL, "sig-policy-url", 2, "@" },
603 { oCertPolicyURL, "cert-policy-url", 2, "@" },
604 { oShowPolicyURL, "show-policy-url", 0, "@" },
605 { oNoShowPolicyURL, "no-show-policy-url", 0, "@" },
606 { oSigKeyserverURL, "sig-keyserver-url", 2, "@" },
607 { oShowNotation, "show-notation", 0, "@" },
608 { oNoShowNotation, "no-show-notation", 0, "@" },
609 { oComment, "comment", 2, "@" },
610 { oDefaultComment, "default-comment", 0, "@" },
611 { oNoComments, "no-comments", 0, "@" },
612 { oEmitVersion, "emit-version", 0, "@"},
613 { oNoEmitVersion, "no-emit-version", 0, "@"},
614 { oNoEmitVersion, "no-version", 0, "@"}, /* alias */
615 { oNotDashEscaped, "not-dash-escaped", 0, "@" },
616 { oEscapeFrom, "escape-from-lines", 0, "@" },
617 { oNoEscapeFrom, "no-escape-from-lines", 0, "@" },
618 { oLockOnce, "lock-once", 0, "@" },
619 { oLockMultiple, "lock-multiple", 0, "@" },
620 { oLockNever, "lock-never", 0, "@" },
621 { oLoggerFD, "logger-fd",1, "@" },
622 { oLoggerFile, "log-file",2, "@" },
623 { oUseEmbeddedFilename, "use-embedded-filename", 0, "@" },
624 { oNoUseEmbeddedFilename, "no-use-embedded-filename", 0, "@" },
625 { oUtf8Strings, "utf8-strings", 0, "@" },
626 { oNoUtf8Strings, "no-utf8-strings", 0, "@" },
627 { oWithFingerprint, "with-fingerprint", 0, "@" },
628 { oDisableCipherAlgo, "disable-cipher-algo", 2, "@" },
629 { oDisablePubkeyAlgo, "disable-pubkey-algo", 2, "@" },
630 { oAllowNonSelfsignedUID, "allow-non-selfsigned-uid", 0, "@" },
631 { oNoAllowNonSelfsignedUID, "no-allow-non-selfsigned-uid", 0, "@" },
632 { oAllowFreeformUID, "allow-freeform-uid", 0, "@" },
633 { oNoAllowFreeformUID, "no-allow-freeform-uid", 0, "@" },
634 { oNoLiteral, "no-literal", 0, "@" },
635 { oSetFilesize, "set-filesize", 20, "@" },
636 { oHonorHttpProxy,"honor-http-proxy", 0, "@" },
637 { oFastListMode,"fast-list-mode", 0, "@" },
638 { oFixedListMode,"fixed-list-mode", 0, "@" },
639 { oListOnly, "list-only", 0, "@"},
640 { oIgnoreTimeConflict, "ignore-time-conflict", 0, "@" },
641 { oIgnoreValidFrom, "ignore-valid-from", 0, "@" },
642 { oIgnoreCrcError, "ignore-crc-error", 0,"@" },
643 { oIgnoreMDCError, "ignore-mdc-error", 0,"@" },
644 { oShowSessionKey, "show-session-key", 0, "@" },
645 { oOverrideSessionKey, "override-session-key", 2, "@" },
646 { oNoRandomSeedFile, "no-random-seed-file", 0, "@" },
647 { oAutoKeyRetrieve, "auto-key-retrieve", 0, "@" },
648 { oNoAutoKeyRetrieve, "no-auto-key-retrieve", 0, "@" },
649 { oNoSigCache, "no-sig-cache", 0, "@" },
650 { oNoSigCreateCheck, "no-sig-create-check", 0, "@" },
651 { oAutoCheckTrustDB, "auto-check-trustdb", 0, "@"},
652 { oNoAutoCheckTrustDB, "no-auto-check-trustdb", 0, "@"},
653 { oMergeOnly, "merge-only", 0, "@" },
654 { oAllowSecretKeyImport, "allow-secret-key-import", 0, "@" },
655 { oTryAllSecrets, "try-all-secrets", 0, "@" },
656 { oEnableSpecialFilenames, "enable-special-filenames", 0, "@" },
657 { oNoExpensiveTrustChecks, "no-expensive-trust-checks", 0, "@" },
658 { aDeleteSecretAndPublicKeys, "delete-secret-and-public-keys",256, "@" },
659 { aRebuildKeydbCaches, "rebuild-keydb-caches", 256, "@"},
660 { oPreservePermissions, "preserve-permissions", 0, "@"},
661 { oDefaultPreferenceList, "default-preference-list", 2, "@"},
662 { oDefaultKeyserverURL, "default-keyserver-url", 2, "@"},
663 { oPersonalCipherPreferences, "personal-cipher-preferences", 2, "@"},
664 { oPersonalDigestPreferences, "personal-digest-preferences", 2, "@"},
665 { oPersonalCompressPreferences, "personal-compress-preferences", 2, "@"},
666 /* Aliases. I constantly mistype these, and assume other people
667 do as well. */
668 { oPersonalCipherPreferences, "personal-cipher-prefs", 2, "@"},
669 { oPersonalDigestPreferences, "personal-digest-prefs", 2, "@"},
670 { oPersonalCompressPreferences, "personal-compress-prefs", 2, "@"},
671 { oAgentProgram, "agent-program", 2 , "@" },
672 { oDisplay, "display", 2, "@" },
673 { oTTYname, "ttyname", 2, "@" },
674 { oTTYtype, "ttytype", 2, "@" },
675 { oLCctype, "lc-ctype", 2, "@" },
676 { oLCmessages, "lc-messages", 2, "@" },
677 { oGroup, "group", 2, "@" },
678 { oUnGroup, "ungroup", 2, "@" },
679 { oNoGroups, "no-groups", 0, "@" },
680 { oStrict, "strict", 0, "@" },
681 { oNoStrict, "no-strict", 0, "@" },
682 { oMangleDosFilenames, "mangle-dos-filenames", 0, "@" },
683 { oNoMangleDosFilenames, "no-mangle-dos-filenames", 0, "@" },
684 { oEnableProgressFilter, "enable-progress-filter", 0, "@" },
685 { oMultifile, "multifile", 0, "@" },
686 { oKeyidFormat, "keyid-format", 2, "@" },
687 { oExitOnStatusWriteError, "exit-on-status-write-error", 0, "@" },
688 { oLimitCardInsertTries, "limit-card-insert-tries", 1, "@"},
690 { oAllowMultisigVerification, "allow-multisig-verification", 0, "@"},
691 { oEnableDSA2, "enable-dsa2", 0, "@"},
692 { oDisableDSA2, "disable-dsa2", 0, "@"},
694 /* These two are aliases to help users of the PGP command line
695 product use gpg with minimal pain. Many commands are common
696 already as they seem to have borrowed commands from us. Now
697 I'm returning the favor. */
698 { oLocalUser, "sign-with", 2, "@" },
699 { oRecipient, "user", 2, "@" },
700 { oRequireCrossCert, "require-backsigs", 0, "@"},
701 { oRequireCrossCert, "require-cross-certification", 0, "@"},
702 { oNoRequireCrossCert, "no-require-backsigs", 0, "@"},
703 { oNoRequireCrossCert, "no-require-cross-certification", 0, "@"},
704 { oAutoKeyLocate, "auto-key-locate", 2, "@"},
705 { oNoAutoKeyLocate, "no-auto-key-locate", 0, "@"},
707 {0,NULL,0,NULL}
711 #ifdef ENABLE_SELINUX_HACKS
712 #define ALWAYS_ADD_KEYRINGS 1
713 #else
714 #define ALWAYS_ADD_KEYRINGS 0
715 #endif
718 int g10_errors_seen = 0;
720 static int utf8_strings = 0;
721 static int maybe_setuid = 1;
723 static char *build_list( const char *text, char letter,
724 const char *(*mapf)(int), int (*chkf)(int) );
725 static void set_cmd( enum cmd_and_opt_values *ret_cmd,
726 enum cmd_and_opt_values new_cmd );
727 static void print_mds( const char *fname, int algo );
728 static void add_notation_data( const char *string, int which );
729 static void add_policy_url( const char *string, int which );
730 static void add_keyserver_url( const char *string, int which );
731 static void emergency_cleanup (void);
734 static const char *
735 my_strusage( int level )
737 static char *digests, *pubkeys, *ciphers, *zips;
738 const char *p;
739 switch( level ) {
740 case 11: p = "gpg (GnuPG)";
741 break;
742 case 13: p = VERSION; break;
743 case 17: p = PRINTABLE_OS_NAME; break;
744 case 19: p =
745 _("Please report bugs to <gnupg-bugs@gnu.org>.\n");
746 break;
748 #ifdef IS_DEVELOPMENT_VERSION
749 case 20:
750 p="NOTE: THIS IS A DEVELOPMENT VERSION!";
751 break;
752 case 21:
753 p="It is only intended for test purposes and should NOT be";
754 break;
755 case 22:
756 p="used in a production environment or with production keys!";
757 break;
758 #endif
760 case 1:
761 case 40: p =
762 _("Usage: gpg [options] [files] (-h for help)");
763 break;
764 case 41: p =
765 _("Syntax: gpg [options] [files]\n"
766 "sign, check, encrypt or decrypt\n"
767 "default operation depends on the input data\n");
768 break;
770 case 31: p = "\nHome: "; break;
771 #ifndef __riscos__
772 case 32: p = opt.homedir; break;
773 #else /* __riscos__ */
774 case 32: p = make_filename(opt.homedir, NULL); break;
775 #endif /* __riscos__ */
776 case 33: p = _("\nSupported algorithms:\n"); break;
777 case 34:
778 if (!pubkeys)
779 pubkeys = build_list (_("Pubkey: "), 0,
780 gcry_pk_algo_name,
781 openpgp_pk_test_algo );
782 p = pubkeys;
783 break;
784 case 35:
785 if( !ciphers )
786 ciphers = build_list(_("Cipher: "), 'S',
787 gcry_cipher_algo_name,
788 openpgp_cipher_test_algo );
789 p = ciphers;
790 break;
791 case 36:
792 if( !digests )
793 digests = build_list(_("Hash: "), 'H',
794 gcry_md_algo_name,
795 openpgp_md_test_algo );
796 p = digests;
797 break;
798 case 37:
799 if( !zips )
800 zips = build_list(_("Compression: "),'Z',
801 compress_algo_to_string,
802 check_compress_algo);
803 p = zips;
804 break;
806 default: p = NULL;
808 return p;
812 static char *
813 build_list( const char *text, char letter,
814 const char * (*mapf)(int), int (*chkf)(int) )
816 int i;
817 const char *s;
818 size_t n=strlen(text)+2;
819 char *list, *p, *line=NULL;
821 if (maybe_setuid)
822 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
824 for(i=0; i <= 110; i++ )
825 if( !chkf(i) && (s=mapf(i)) )
826 n += strlen(s) + 7 + 2;
827 list = xmalloc( 21 + n ); *list = 0;
828 for(p=NULL, i=0; i <= 110; i++ ) {
829 if( !chkf(i) && (s=mapf(i)) ) {
830 if( !p ) {
831 p = stpcpy( list, text );
832 line=p;
834 else
835 p = stpcpy( p, ", ");
837 if(strlen(line)>60) {
838 int spaces=strlen(text);
840 list=xrealloc(list,n+spaces+1);
841 /* realloc could move the block, so find the end again */
842 p=list;
843 while(*p)
844 p++;
846 p=stpcpy(p, "\n");
847 line=p;
848 for(;spaces;spaces--)
849 p=stpcpy(p, " ");
852 p = stpcpy(p, s );
853 if(opt.verbose && letter)
855 char num[8];
856 sprintf(num," (%c%d)",letter,i);
857 p = stpcpy(p,num);
861 if( p )
862 p = stpcpy(p, "\n" );
863 return list;
867 static void
868 i18n_init(void)
870 #ifdef USE_SIMPLE_GETTEXT
871 set_gettext_file (PACKAGE_GT, "Software\\GNU\\GnuPG");
872 #else
873 #ifdef ENABLE_NLS
874 setlocale (LC_ALL, "");
875 bindtextdomain (PACKAGE_GT, LOCALEDIR);
876 textdomain (PACKAGE_GT);
877 #endif
878 #endif
881 static void
882 wrong_args( const char *text)
884 fputs(_("usage: gpg [options] "),stderr);
885 fputs(text,stderr);
886 putc('\n',stderr);
887 g10_exit(2);
891 static char *
892 make_username( const char *string )
894 char *p;
895 if( utf8_strings )
896 p = xstrdup(string);
897 else
898 p = native_to_utf8( string );
899 return p;
903 /* Setup the debugging. With a LEVEL of NULL only the active debug
904 flags are propagated to the subsystems. With LEVEL set, a specific
905 set of debug flags is set; thus overriding all flags already
906 set. */
907 static void
908 set_debug (const char *level)
910 if (!level)
912 else if (!strcmp (level, "none"))
913 opt.debug = 0;
914 else if (!strcmp (level, "basic"))
915 opt.debug = DBG_MEMSTAT_VALUE;
916 else if (!strcmp (level, "advanced"))
917 opt.debug = DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE;
918 else if (!strcmp (level, "expert"))
919 opt.debug = (DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE
920 |DBG_CACHE_VALUE|DBG_FILTER_VALUE|DBG_PACKET_VALUE);
921 else if (!strcmp (level, "guru"))
922 opt.debug = ~0;
923 else
925 log_error (_("invalid debug-level `%s' given\n"), level);
926 g10_exit (2);
929 if (opt.debug & DBG_MEMORY_VALUE )
930 memory_debug_mode = 1;
931 if (opt.debug & DBG_MEMSTAT_VALUE )
932 memory_stat_debug_mode = 1;
933 if (opt.debug & DBG_MPI_VALUE)
934 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
935 if (opt.debug & DBG_CIPHER_VALUE )
936 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
937 if (opt.debug & DBG_IOBUF_VALUE )
938 iobuf_debug_mode = 1;
939 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
944 /* We need the home directory also in some other directories, so make
945 sure that both variables are always in sync. */
946 static void
947 set_homedir (const char *dir)
949 if (!dir)
950 dir = "";
951 opt.homedir = dir;
955 /* We set the screen dimensions for UI purposes. Do not allow screens
956 smaller than 80x24 for the sake of simplicity. */
957 static void
958 set_screen_dimensions(void)
960 #ifndef HAVE_W32_SYSTEM
961 char *str;
963 str=getenv("COLUMNS");
964 if(str)
965 opt.screen_columns=atoi(str);
967 str=getenv("LINES");
968 if(str)
969 opt.screen_lines=atoi(str);
970 #endif
972 if(opt.screen_columns<80 || opt.screen_columns>255)
973 opt.screen_columns=80;
975 if(opt.screen_lines<24 || opt.screen_lines>255)
976 opt.screen_lines=24;
980 /* Helper to open a file FNAME either for reading or writing to be
981 used with --status-file etc functions. Not generally useful but it
982 avoids the riscos specific functions and well some Windows people
983 might like it too. Prints an error message and returns -1 on
984 error. On success the file descriptor is returned. */
985 static int
986 open_info_file (const char *fname, int for_write)
988 #ifdef __riscos__
989 return riscos_fdopenfile (fname, for_write);
990 #elif defined (ENABLE_SELINUX_HACKS)
991 /* We can't allow these even when testing for a secured filename
992 because files to be secured might not yet been secured. This is
993 similar to the option file but in that case it is unlikely that
994 sensitive information may be retrieved by means of error
995 messages. */
996 return -1;
997 #else
998 int fd;
1000 /* if (is_secured_filename (fname)) */
1001 /* { */
1002 /* fd = -1; */
1003 /* errno = EPERM; */
1004 /* } */
1005 /* else */
1006 /* { */
1009 if (for_write)
1010 fd = open (fname, O_CREAT | O_TRUNC | O_WRONLY,
1011 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
1012 else
1013 fd = open (fname, O_RDONLY | MY_O_BINARY);
1015 while (fd == -1 && errno == EINTR);
1016 /* } */
1017 if ( fd == -1)
1018 log_error ( for_write? _("can't create `%s': %s\n")
1019 : _("can't open `%s': %s\n"), fname, strerror(errno));
1021 return fd;
1022 #endif
1025 static void
1026 set_cmd( enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd )
1028 enum cmd_and_opt_values cmd = *ret_cmd;
1030 if( !cmd || cmd == new_cmd )
1031 cmd = new_cmd;
1032 else if( cmd == aSign && new_cmd == aEncr )
1033 cmd = aSignEncr;
1034 else if( cmd == aEncr && new_cmd == aSign )
1035 cmd = aSignEncr;
1036 else if( cmd == aSign && new_cmd == aSym )
1037 cmd = aSignSym;
1038 else if( cmd == aSym && new_cmd == aSign )
1039 cmd = aSignSym;
1040 else if( cmd == aSym && new_cmd == aEncr )
1041 cmd = aEncrSym;
1042 else if( cmd == aEncr && new_cmd == aSym )
1043 cmd = aEncrSym;
1044 else if( cmd == aKMode && new_cmd == aSym )
1045 cmd = aKModeC;
1046 else if (cmd == aSignEncr && new_cmd == aSym)
1047 cmd = aSignEncrSym;
1048 else if (cmd == aSignSym && new_cmd == aEncr)
1049 cmd = aSignEncrSym;
1050 else if (cmd == aEncrSym && new_cmd == aSign)
1051 cmd = aSignEncrSym;
1052 else if( ( cmd == aSign && new_cmd == aClearsign )
1053 || ( cmd == aClearsign && new_cmd == aSign ) )
1054 cmd = aClearsign;
1055 else {
1056 log_error(_("conflicting commands\n"));
1057 g10_exit(2);
1060 *ret_cmd = cmd;
1064 static void
1065 add_group(char *string)
1067 char *name,*value;
1068 struct groupitem *item;
1070 /* Break off the group name */
1071 name=strsep(&string,"=");
1072 if(string==NULL)
1074 log_error(_("no = sign found in group definition `%s'\n"),name);
1075 return;
1078 trim_trailing_ws(name,strlen(name));
1080 /* Does this group already exist? */
1081 for(item=opt.grouplist;item;item=item->next)
1082 if(strcasecmp(item->name,name)==0)
1083 break;
1085 if(!item)
1087 item=xmalloc(sizeof(struct groupitem));
1088 item->name=name;
1089 item->next=opt.grouplist;
1090 item->values=NULL;
1091 opt.grouplist=item;
1094 /* Break apart the values */
1095 while ((value= strsep(&string," \t")))
1097 if (*value)
1098 add_to_strlist2(&item->values,value,utf8_strings);
1103 static void
1104 rm_group(char *name)
1106 struct groupitem *item,*last=NULL;
1108 trim_trailing_ws(name,strlen(name));
1110 for(item=opt.grouplist;item;last=item,item=item->next)
1112 if(strcasecmp(item->name,name)==0)
1114 if(last)
1115 last->next=item->next;
1116 else
1117 opt.grouplist=item->next;
1119 free_strlist(item->values);
1120 xfree(item);
1121 break;
1127 /* We need to check three things.
1129 0) The homedir. It must be x00, a directory, and owned by the
1130 user.
1132 1) The options/gpg.conf file. Okay unless it or its containing
1133 directory is group or other writable or not owned by us. Disable
1134 exec in this case.
1136 2) Extensions. Same as #1.
1138 Returns true if the item is unsafe. */
1139 static int
1140 check_permissions(const char *path,int item)
1142 #if defined(HAVE_STAT) && !defined(HAVE_DOSISH_SYSTEM)
1143 static int homedir_cache=-1;
1144 char *tmppath,*dir;
1145 struct stat statbuf,dirbuf;
1146 int homedir=0,ret=0,checkonly=0;
1147 int perm=0,own=0,enc_dir_perm=0,enc_dir_own=0;
1149 if(opt.no_perm_warn)
1150 return 0;
1152 assert(item==0 || item==1 || item==2);
1154 /* extensions may attach a path */
1155 if(item==2 && path[0]!=DIRSEP_C)
1157 if(strchr(path,DIRSEP_C))
1158 tmppath=make_filename(path,NULL);
1159 else
1160 tmppath=make_filename(GNUPG_LIBDIR,path,NULL);
1162 else
1163 tmppath=xstrdup(path);
1165 /* If the item is located in the homedir, but isn't the homedir,
1166 don't continue if we already checked the homedir itself. This is
1167 to avoid user confusion with an extra options file warning which
1168 could be rectified if the homedir itself had proper
1169 permissions. */
1170 if(item!=0 && homedir_cache>-1
1171 && ascii_strncasecmp(opt.homedir,tmppath,strlen(opt.homedir))==0)
1173 ret=homedir_cache;
1174 goto end;
1177 /* It's okay if the file or directory doesn't exist */
1178 if(stat(tmppath,&statbuf)!=0)
1180 ret=0;
1181 goto end;
1184 /* Now check the enclosing directory. Theoretically, we could walk
1185 this test up to the root directory /, but for the sake of sanity,
1186 I'm stopping at one level down. */
1187 dir=make_dirname(tmppath);
1189 if(stat(dir,&dirbuf)!=0 || !S_ISDIR(dirbuf.st_mode))
1191 /* Weird error */
1192 ret=1;
1193 goto end;
1196 xfree(dir);
1198 /* Assume failure */
1199 ret=1;
1201 if(item==0)
1203 /* The homedir must be x00, a directory, and owned by the user. */
1205 if(S_ISDIR(statbuf.st_mode))
1207 if(statbuf.st_uid==getuid())
1209 if((statbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1210 ret=0;
1211 else
1212 perm=1;
1214 else
1215 own=1;
1217 homedir_cache=ret;
1220 else if(item==1 || item==2)
1222 /* The options or extension file. Okay unless it or its
1223 containing directory is group or other writable or not owned
1224 by us or root. */
1226 if(S_ISREG(statbuf.st_mode))
1228 if(statbuf.st_uid==getuid() || statbuf.st_uid==0)
1230 if((statbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1232 /* it's not writable, so make sure the enclosing
1233 directory is also not writable */
1234 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1236 if((dirbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1237 ret=0;
1238 else
1239 enc_dir_perm=1;
1241 else
1242 enc_dir_own=1;
1244 else
1246 /* it's writable, so the enclosing directory had
1247 better not let people get to it. */
1248 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1250 if((dirbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1251 ret=0;
1252 else
1253 perm=enc_dir_perm=1; /* unclear which one to fix! */
1255 else
1256 enc_dir_own=1;
1259 else
1260 own=1;
1263 else
1264 BUG();
1266 if(!checkonly)
1268 if(own)
1270 if(item==0)
1271 log_info(_("WARNING: unsafe ownership on"
1272 " homedir `%s'\n"),tmppath);
1273 else if(item==1)
1274 log_info(_("WARNING: unsafe ownership on"
1275 " configuration file `%s'\n"),tmppath);
1276 else
1277 log_info(_("WARNING: unsafe ownership on"
1278 " extension `%s'\n"),tmppath);
1280 if(perm)
1282 if(item==0)
1283 log_info(_("WARNING: unsafe permissions on"
1284 " homedir `%s'\n"),tmppath);
1285 else if(item==1)
1286 log_info(_("WARNING: unsafe permissions on"
1287 " configuration file `%s'\n"),tmppath);
1288 else
1289 log_info(_("WARNING: unsafe permissions on"
1290 " extension `%s'\n"),tmppath);
1292 if(enc_dir_own)
1294 if(item==0)
1295 log_info(_("WARNING: unsafe enclosing directory ownership on"
1296 " homedir `%s'\n"),tmppath);
1297 else if(item==1)
1298 log_info(_("WARNING: unsafe enclosing directory ownership on"
1299 " configuration file `%s'\n"),tmppath);
1300 else
1301 log_info(_("WARNING: unsafe enclosing directory ownership on"
1302 " extension `%s'\n"),tmppath);
1304 if(enc_dir_perm)
1306 if(item==0)
1307 log_info(_("WARNING: unsafe enclosing directory permissions on"
1308 " homedir `%s'\n"),tmppath);
1309 else if(item==1)
1310 log_info(_("WARNING: unsafe enclosing directory permissions on"
1311 " configuration file `%s'\n"),tmppath);
1312 else
1313 log_info(_("WARNING: unsafe enclosing directory permissions on"
1314 " extension `%s'\n"),tmppath);
1318 end:
1319 xfree(tmppath);
1321 if(homedir)
1322 homedir_cache=ret;
1324 return ret;
1326 #endif /* HAVE_STAT && !HAVE_DOSISH_SYSTEM */
1328 return 0;
1332 static void
1333 print_algo_numbers(int (*checker)(int))
1335 int i,first=1;
1337 for(i=0;i<=110;i++)
1339 if(!checker(i))
1341 if(first)
1342 first=0;
1343 else
1344 printf(";");
1345 printf("%d",i);
1351 /* In the future, we can do all sorts of interesting configuration
1352 output here. For now, just give "group" as the Enigmail folks need
1353 it, and pubkey, cipher, hash, and compress as they may be useful
1354 for frontends. */
1355 static void
1356 list_config(char *items)
1358 int show_all=(items==NULL);
1359 char *name=NULL;
1361 if(!opt.with_colons)
1362 return;
1364 while(show_all || (name=strsep(&items," ")))
1366 int any=0;
1368 if(show_all || ascii_strcasecmp(name,"group")==0)
1370 struct groupitem *iter;
1372 for(iter=opt.grouplist;iter;iter=iter->next)
1374 STRLIST sl;
1376 printf("cfg:group:");
1377 print_string(stdout,iter->name,strlen(iter->name),':');
1378 printf(":");
1380 for(sl=iter->values;sl;sl=sl->next)
1382 print_sanitized_string2 (stdout, sl->d, ':',';');
1383 if(sl->next)
1384 printf(";");
1387 printf("\n");
1390 any=1;
1393 if(show_all || ascii_strcasecmp(name,"version")==0)
1395 printf("cfg:version:");
1396 print_string(stdout,VERSION,strlen(VERSION),':');
1397 printf("\n");
1398 any=1;
1401 if(show_all || ascii_strcasecmp(name,"pubkey")==0)
1403 printf("cfg:pubkey:");
1404 print_algo_numbers (openpgp_pk_test_algo);
1405 printf("\n");
1406 any=1;
1409 if(show_all || ascii_strcasecmp(name,"cipher")==0)
1411 printf("cfg:cipher:");
1412 print_algo_numbers(openpgp_cipher_test_algo);
1413 printf("\n");
1414 any=1;
1417 if(show_all
1418 || ascii_strcasecmp(name,"digest")==0
1419 || ascii_strcasecmp(name,"hash")==0)
1421 printf("cfg:digest:");
1422 print_algo_numbers(openpgp_md_test_algo);
1423 printf("\n");
1424 any=1;
1427 if(show_all || ascii_strcasecmp(name,"compress")==0)
1429 printf("cfg:compress:");
1430 print_algo_numbers(check_compress_algo);
1431 printf("\n");
1432 any=1;
1435 if(show_all || ascii_strcasecmp(name,"ccid-reader-id")==0)
1437 #if defined(ENABLE_CARD_SUPPORT) && defined(HAVE_LIBUSB) \
1438 && GNUPG_MAJOR_VERSION == 1
1440 char *p, *p2, *list = ccid_get_reader_list ();
1442 for (p=list; p && (p2 = strchr (p, '\n')); p = p2+1)
1444 *p2 = 0;
1445 printf("cfg:ccid-reader-id:%s\n", p);
1447 free (list);
1448 #endif
1449 any=1;
1452 if(show_all)
1453 break;
1455 if(!any)
1456 log_error(_("unknown configuration item `%s'\n"),name);
1461 /* List options and default values in the GPG Conf format. This is a
1462 new tool distributed with gnupg 1.9.x but we also want some limited
1463 support in older gpg versions. The output is the name of the
1464 configuration file and a list of options available for editing by
1465 gpgconf. */
1466 static void
1467 gpgconf_list (const char *configfile)
1469 /* The following definitions are taken from gnupg/tools/gpgconf-comp.c. */
1470 #define GC_OPT_FLAG_NONE 0UL
1471 #define GC_OPT_FLAG_DEFAULT (1UL << 4)
1473 printf ("gpgconf-gpg.conf:%lu:\"%s\n",
1474 GC_OPT_FLAG_DEFAULT,configfile?configfile:"/dev/null");
1475 printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
1476 printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
1477 printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
1478 printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE);
1482 static int
1483 parse_subpacket_list(char *list)
1485 char *tok;
1486 byte subpackets[128],i;
1487 int count=0;
1489 if(!list)
1491 /* No arguments means all subpackets */
1492 memset(subpackets+1,1,sizeof(subpackets)-1);
1493 count=127;
1495 else
1497 memset(subpackets,0,sizeof(subpackets));
1499 /* Merge with earlier copy */
1500 if(opt.show_subpackets)
1502 byte *in;
1504 for(in=opt.show_subpackets;*in;in++)
1506 if(*in>127 || *in<1)
1507 BUG();
1509 if(!subpackets[*in])
1510 count++;
1511 subpackets[*in]=1;
1515 while((tok=strsep(&list," ,")))
1517 if(!*tok)
1518 continue;
1520 i=atoi(tok);
1521 if(i>127 || i<1)
1522 return 0;
1524 if(!subpackets[i])
1525 count++;
1526 subpackets[i]=1;
1530 xfree(opt.show_subpackets);
1531 opt.show_subpackets=xmalloc(count+1);
1532 opt.show_subpackets[count--]=0;
1534 for(i=1;i<128 && count>=0;i++)
1535 if(subpackets[i])
1536 opt.show_subpackets[count--]=i;
1538 return 1;
1542 static int
1543 parse_list_options(char *str)
1545 char *subpackets=""; /* something that isn't NULL */
1546 struct parse_options lopts[]=
1548 {"show-photos",LIST_SHOW_PHOTOS,NULL,
1549 N_("display photo IDs during key listings")},
1550 {"show-policy-urls",LIST_SHOW_POLICY_URLS,NULL,
1551 N_("show policy URLs during signature listings")},
1552 {"show-notations",LIST_SHOW_NOTATIONS,NULL,
1553 N_("show all notations during signature listings")},
1554 {"show-std-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1555 N_("show IETF standard notations during signature listings")},
1556 {"show-standard-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1557 NULL},
1558 {"show-user-notations",LIST_SHOW_USER_NOTATIONS,NULL,
1559 N_("show user-supplied notations during signature listings")},
1560 {"show-keyserver-urls",LIST_SHOW_KEYSERVER_URLS,NULL,
1561 N_("show preferred keyserver URLs during signature listings")},
1562 {"show-uid-validity",LIST_SHOW_UID_VALIDITY,NULL,
1563 N_("show user ID validity during key listings")},
1564 {"show-unusable-uids",LIST_SHOW_UNUSABLE_UIDS,NULL,
1565 N_("show revoked and expired user IDs in key listings")},
1566 {"show-unusable-subkeys",LIST_SHOW_UNUSABLE_SUBKEYS,NULL,
1567 N_("show revoked and expired subkeys in key listings")},
1568 {"show-keyring",LIST_SHOW_KEYRING,NULL,
1569 N_("show the keyring name in key listings")},
1570 {"show-sig-expire",LIST_SHOW_SIG_EXPIRE,NULL,
1571 N_("show expiration dates during signature listings")},
1572 {"show-sig-subpackets",LIST_SHOW_SIG_SUBPACKETS,NULL,
1573 NULL},
1574 {NULL,0,NULL,NULL}
1577 /* C99 allows for non-constant initializers, but we'd like to
1578 compile everywhere, so fill in the show-sig-subpackets argument
1579 here. Note that if the parse_options array changes, we'll have
1580 to change the subscript here. */
1581 lopts[12].value=&subpackets;
1583 if(parse_options(str,&opt.list_options,lopts,1))
1585 if(opt.list_options&LIST_SHOW_SIG_SUBPACKETS)
1587 /* Unset so users can pass multiple lists in. */
1588 opt.list_options&=~LIST_SHOW_SIG_SUBPACKETS;
1589 if(!parse_subpacket_list(subpackets))
1590 return 0;
1592 else if(subpackets==NULL && opt.show_subpackets)
1594 /* User did 'no-show-subpackets' */
1595 xfree(opt.show_subpackets);
1596 opt.show_subpackets=NULL;
1599 return 1;
1601 else
1602 return 0;
1606 /* Collapses argc/argv into a single string that must be freed */
1607 static char *
1608 collapse_args(int argc,char *argv[])
1610 char *str=NULL;
1611 int i,first=1,len=0;
1613 for(i=0;i<argc;i++)
1615 len+=strlen(argv[i])+2;
1616 str=xrealloc(str,len);
1617 if(first)
1619 str[0]='\0';
1620 first=0;
1622 else
1623 strcat(str," ");
1625 strcat(str,argv[i]);
1628 return str;
1631 static void
1632 parse_trust_model(const char *model)
1634 if(ascii_strcasecmp(model,"pgp")==0)
1635 opt.trust_model=TM_PGP;
1636 else if(ascii_strcasecmp(model,"classic")==0)
1637 opt.trust_model=TM_CLASSIC;
1638 else if(ascii_strcasecmp(model,"always")==0)
1639 opt.trust_model=TM_ALWAYS;
1640 else if(ascii_strcasecmp(model,"direct")==0)
1641 opt.trust_model=TM_DIRECT;
1642 else if(ascii_strcasecmp(model,"auto")==0)
1643 opt.trust_model=TM_AUTO;
1644 else
1645 log_error("unknown trust model `%s'\n",model);
1650 /* Make sure that the standard file descriptors are opened. Obviously
1651 some folks close them before an exec and the next file we open will
1652 get one of them assigned and thus any output (i.e. diagnostics) end
1653 up in that file (e.g. the trustdb). Not actually a gpg problem as
1654 this will hapenn with almost all utilities when called in a wrong
1655 way. However we try to minimize the damage here and raise
1656 awareness of the problem.
1658 Must be called before we open any files! */
1659 static void
1660 reopen_std(void)
1662 #if defined(HAVE_STAT) && !defined(HAVE_W32_SYSTEM)
1663 struct stat statbuf;
1664 int did_stdin=0,did_stdout=0,did_stderr=0;
1665 FILE *complain;
1667 if(fstat(STDIN_FILENO,&statbuf)==-1 && errno==EBADF)
1669 if(open("/dev/null",O_RDONLY)==STDIN_FILENO)
1670 did_stdin=1;
1671 else
1672 did_stdin=2;
1675 if(fstat(STDOUT_FILENO,&statbuf)==-1 && errno==EBADF)
1677 if(open("/dev/null",O_WRONLY)==STDOUT_FILENO)
1678 did_stdout=1;
1679 else
1680 did_stdout=2;
1683 if(fstat(STDERR_FILENO,&statbuf)==-1 && errno==EBADF)
1685 if(open("/dev/null",O_WRONLY)==STDERR_FILENO)
1686 did_stderr=1;
1687 else
1688 did_stderr=2;
1691 /* It's hard to log this sort of thing since the filehandle we would
1692 complain to may be closed... */
1693 if(did_stderr==0)
1694 complain=stderr;
1695 else if(did_stdout==0)
1696 complain=stdout;
1697 else
1698 complain=NULL;
1700 if(complain)
1702 if(did_stdin==1)
1703 fprintf(complain,"gpg: WARNING: standard input reopened\n");
1704 if(did_stdout==1)
1705 fprintf(complain,"gpg: WARNING: standard output reopened\n");
1706 if(did_stderr==1)
1707 fprintf(complain,"gpg: WARNING: standard error reopened\n");
1709 if(did_stdin==2 || did_stdout==2 || did_stderr==2)
1710 fprintf(complain,"gpg: fatal: unable to reopen standard input,"
1711 " output, or error\n");
1714 if(did_stdin==2 || did_stdout==2 || did_stderr==2)
1715 exit(3);
1716 #endif /* HAVE_STAT && !HAVE_W32_SYSTEM */
1721 main (int argc, char **argv )
1723 ARGPARSE_ARGS pargs;
1724 IOBUF a;
1725 int rc=0;
1726 int orig_argc;
1727 char **orig_argv;
1728 const char *fname;
1729 char *username;
1730 int may_coredump;
1731 STRLIST sl, remusr= NULL, locusr=NULL;
1732 STRLIST nrings=NULL, sec_nrings=NULL;
1733 armor_filter_context_t afx;
1734 int detached_sig = 0;
1735 FILE *configfp = NULL;
1736 char *configname = NULL;
1737 char *save_configname = NULL;
1738 unsigned configlineno;
1739 int parse_debug = 0;
1740 int default_config = 1;
1741 int default_keyring = 1;
1742 int greeting = 0;
1743 int nogreeting = 0;
1744 char *logfile = NULL;
1745 int use_random_seed = 1;
1746 enum cmd_and_opt_values cmd = 0;
1747 const char *debug_level = NULL;
1748 const char *trustdb_name = NULL;
1749 char *def_cipher_string = NULL;
1750 char *def_digest_string = NULL;
1751 char *compress_algo_string = NULL;
1752 char *cert_digest_string = NULL;
1753 char *s2k_cipher_string = NULL;
1754 char *s2k_digest_string = NULL;
1755 char *pers_cipher_list = NULL;
1756 char *pers_digest_list = NULL;
1757 char *pers_compress_list = NULL;
1758 int eyes_only=0;
1759 int multifile=0;
1760 int pwfd = -1;
1761 int with_fpr = 0; /* make an option out of --fingerprint */
1762 int any_explicit_recipient = 0;
1763 int require_secmem=0,got_secmem=0;
1765 #ifdef __riscos__
1766 opt.lock_once = 1;
1767 #endif /* __riscos__ */
1770 /* Please note that we may running SUID(ROOT), so be very CAREFUL
1771 when adding any stuff between here and the call to
1772 secmem_init() somewhere after the option parsing. */
1773 reopen_std ();
1774 trap_unaligned();
1775 set_strusage (my_strusage);
1776 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
1777 /* We don't need any locking in libgcrypt unless we use any kind of
1778 threading. */
1779 gcry_control (GCRYCTL_DISABLE_INTERNAL_LOCKING);
1780 log_set_prefix ("gpg", 1);
1782 /* Check that the libraries are suitable. Do it right here because the
1783 option parsing may need services of the library. */
1784 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
1786 log_fatal ( _("libgcrypt is too old (need %s, have %s)\n"),
1787 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
1790 /* Put random number into secure memory */
1791 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
1793 may_coredump = disable_core_dumps();
1795 gnupg_init_signals (0, emergency_cleanup);
1797 create_dotlock(NULL); /* Register locking cleanup. */
1799 i18n_init();
1801 opt.command_fd = -1; /* no command fd */
1802 opt.compress_level = -1; /* defaults to standard compress level */
1803 opt.bz2_compress_level = -1; /* defaults to standard compress level */
1804 /* note: if you change these lines, look at oOpenPGP */
1805 opt.def_cipher_algo = 0;
1806 opt.def_digest_algo = 0;
1807 opt.cert_digest_algo = 0;
1808 opt.compress_algo = -1; /* defaults to DEFAULT_COMPRESS_ALGO */
1809 opt.s2k_mode = 3; /* iterated+salted */
1810 #ifdef USE_CAST5
1811 opt.s2k_cipher_algo = CIPHER_ALGO_CAST5;
1812 #else
1813 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
1814 #endif
1815 opt.completes_needed = 1;
1816 opt.marginals_needed = 3;
1817 opt.max_cert_depth = 5;
1818 opt.pgp2_workarounds = 1;
1819 opt.force_v3_sigs = 1;
1820 opt.escape_from = 1;
1821 opt.import_options=IMPORT_SK2PK;
1822 opt.export_options=EXPORT_ATTRIBUTES;
1823 opt.keyserver_options.import_options=IMPORT_REPAIR_PKS_SUBKEY_BUG;
1824 opt.keyserver_options.export_options=EXPORT_ATTRIBUTES;
1825 opt.keyserver_options.options=
1826 KEYSERVER_HONOR_KEYSERVER_URL|KEYSERVER_HONOR_PKA_RECORD;
1827 opt.verify_options=
1828 VERIFY_SHOW_POLICY_URLS|VERIFY_SHOW_STD_NOTATIONS|VERIFY_SHOW_KEYSERVER_URLS;
1829 opt.trust_model=TM_AUTO;
1830 opt.mangle_dos_filenames=0;
1831 opt.min_cert_level=2;
1832 set_screen_dimensions();
1833 opt.keyid_format=KF_SHORT;
1834 opt.rfc2440_text=1;
1835 opt.def_sig_expire="0";
1836 opt.def_cert_expire="0";
1837 set_homedir ( default_homedir () );
1839 /* Check whether we have a config file on the command line. */
1840 orig_argc = argc;
1841 orig_argv = argv;
1842 pargs.argc = &argc;
1843 pargs.argv = &argv;
1844 pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
1845 while( arg_parse( &pargs, opts) ) {
1846 if( pargs.r_opt == oDebug || pargs.r_opt == oDebugAll )
1847 parse_debug++;
1848 else if( pargs.r_opt == oOptions ) {
1849 /* yes there is one, so we do not try the default one, but
1850 * read the option file when it is encountered at the commandline
1852 default_config = 0;
1854 else if( pargs.r_opt == oNoOptions )
1855 default_config = 0; /* --no-options */
1856 else if( pargs.r_opt == oHomedir )
1857 set_homedir ( pargs.r.ret_str );
1858 else if( pargs.r_opt == oNoPermissionWarn )
1859 opt.no_perm_warn=1;
1860 else if (pargs.r_opt == oStrict )
1862 /* Not used */
1864 else if (pargs.r_opt == oNoStrict )
1866 /* Not used */
1870 #ifdef HAVE_DOSISH_SYSTEM
1871 if ( strchr (opt.homedir,'\\') ) {
1872 char *d, *buf = xmalloc (strlen (opt.homedir)+1);
1873 const char *s = opt.homedir;
1874 for (d=buf,s=opt.homedir; *s; s++)
1876 *d++ = *s == '\\'? '/': *s;
1877 #ifdef HAVE_W32_SYSTEM
1878 if (s[1] && IsDBCSLeadByte (*s))
1879 *d++ = *++s;
1880 #endif
1882 *d = 0;
1883 set_homedir (buf);
1885 #endif
1887 /* Initialize the secure memory. */
1888 gcry_control (GCRYCTL_INIT_SECMEM, 32768, 0);
1889 got_secmem = 1; /* FIXME: gcry_control should return an indicator. */
1890 #if defined(HAVE_GETUID) && defined(HAVE_GETEUID)
1891 /* There should be no way to get to this spot while still carrying
1892 setuid privs. Just in case, bomb out if we are. */
1893 if(getuid()!=geteuid())
1894 BUG();
1895 #endif
1896 maybe_setuid = 0;
1898 /* Okay, we are now working under our real uid */
1900 /* malloc hooks go here ... */
1901 assuan_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
1902 assuan_set_assuan_err_source (GPG_ERR_SOURCE_DEFAULT);
1905 set_native_charset (NULL); /* Try to auto set the character set */
1907 /* Try for a version specific config file first */
1908 if( default_config )
1910 char *name=xstrdup("gpg" EXTSEP_S "conf-" SAFE_VERSION);
1911 char *ver=&name[strlen("gpg" EXTSEP_S "conf-")];
1915 if(configname)
1917 char *tok;
1919 xfree(configname);
1920 configname=NULL;
1922 if((tok=strrchr(ver,SAFE_VERSION_DASH)))
1923 *tok='\0';
1924 else if((tok=strrchr(ver,SAFE_VERSION_DOT)))
1925 *tok='\0';
1926 else
1927 break;
1930 configname = make_filename(opt.homedir,name,NULL);
1932 while(access(configname,R_OK));
1934 xfree(name);
1936 if(!configname)
1937 configname=make_filename(opt.homedir, "gpg" EXTSEP_S "conf", NULL );
1938 if (!access (configname, R_OK))
1939 { /* Print a warning when both config files are present. */
1940 char *p = make_filename(opt.homedir, "options", NULL );
1941 if (!access (p, R_OK))
1942 log_info (_("NOTE: old default options file `%s' ignored\n"), p);
1943 xfree (p);
1945 else
1946 { /* Keep on using the old default one. */
1947 xfree (configname);
1948 configname = make_filename(opt.homedir, "options", NULL );
1951 argc = orig_argc;
1952 argv = orig_argv;
1953 pargs.argc = &argc;
1954 pargs.argv = &argv;
1955 pargs.flags= 1; /* do not remove the args */
1957 /* By this point we have a homedir, and cannot change it. */
1958 check_permissions(opt.homedir,0);
1960 next_pass:
1961 if( configname ) {
1962 if(check_permissions(configname,1))
1964 /* If any options file is unsafe, then disable any external
1965 programs for keyserver calls or photo IDs. Since the
1966 external program to call is set in the options file, a
1967 unsafe options file can lead to an arbitrary program
1968 being run. */
1970 opt.exec_disable=1;
1973 configlineno = 0;
1974 configfp = fopen( configname, "r" );
1975 if (configfp && is_secured_file (fileno (configfp)))
1977 fclose (configfp);
1978 configfp = NULL;
1979 errno = EPERM;
1981 if( !configfp ) {
1982 if( default_config ) {
1983 if( parse_debug )
1984 log_info(_("NOTE: no default option file `%s'\n"),
1985 configname );
1987 else {
1988 log_error(_("option file `%s': %s\n"),
1989 configname, strerror(errno) );
1990 g10_exit(2);
1992 xfree(configname); configname = NULL;
1994 if( parse_debug && configname )
1995 log_info(_("reading options from `%s'\n"), configname );
1996 default_config = 0;
1999 while( optfile_parse( configfp, configname, &configlineno,
2000 &pargs, opts) )
2002 switch( pargs.r_opt )
2004 case aCheckKeys:
2005 case aListConfig:
2006 case aGPGConfList:
2007 case aListPackets:
2008 case aImport:
2009 case aFastImport:
2010 case aSendKeys:
2011 case aRecvKeys:
2012 case aSearchKeys:
2013 case aRefreshKeys:
2014 case aFetchKeys:
2015 case aExport:
2016 #ifdef ENABLE_CARD_SUPPORT
2017 case aCardStatus:
2018 case aCardEdit:
2019 case aChangePIN:
2020 #endif /* ENABLE_CARD_SUPPORT*/
2021 set_cmd (&cmd, pargs.r_opt);
2022 break;
2024 case aListKeys: set_cmd( &cmd, aListKeys); break;
2025 case aListSigs: set_cmd( &cmd, aListSigs); break;
2026 case aExportSecret: set_cmd( &cmd, aExportSecret); break;
2027 case aExportSecretSub: set_cmd( &cmd, aExportSecretSub); break;
2028 case aDeleteSecretKeys:
2029 set_cmd( &cmd, aDeleteSecretKeys);
2030 greeting=1;
2031 break;
2032 case aDeleteSecretAndPublicKeys:
2033 set_cmd( &cmd, aDeleteSecretAndPublicKeys);
2034 greeting=1;
2035 break;
2036 case aDeleteKeys: set_cmd( &cmd, aDeleteKeys); greeting=1; break;
2038 case aDetachedSign: detached_sig = 1; set_cmd( &cmd, aSign ); break;
2039 case aSym: set_cmd( &cmd, aSym); break;
2041 case aDecryptFiles: multifile=1; /* fall through */
2042 case aDecrypt: set_cmd( &cmd, aDecrypt); break;
2044 case aEncrFiles: multifile=1; /* fall through */
2045 case aEncr: set_cmd( &cmd, aEncr); break;
2047 case aVerifyFiles: multifile=1; /* fall through */
2048 case aVerify: set_cmd( &cmd, aVerify); break;
2050 case aSign: set_cmd( &cmd, aSign ); break;
2051 case aKeygen: set_cmd( &cmd, aKeygen); greeting=1; break;
2052 case aSignKey: set_cmd( &cmd, aSignKey); break;
2053 case aLSignKey: set_cmd( &cmd, aLSignKey); break;
2054 case aStore: set_cmd( &cmd, aStore); break;
2055 case aEditKey: set_cmd( &cmd, aEditKey); greeting=1; break;
2056 case aClearsign: set_cmd( &cmd, aClearsign); break;
2057 case aGenRevoke: set_cmd( &cmd, aGenRevoke); break;
2058 case aDesigRevoke: set_cmd( &cmd, aDesigRevoke); break;
2059 case aPrimegen: set_cmd( &cmd, aPrimegen); break;
2060 case aGenRandom: set_cmd( &cmd, aGenRandom); break;
2061 case aPrintMD: set_cmd( &cmd, aPrintMD); break;
2062 case aPrintMDs: set_cmd( &cmd, aPrintMDs); break;
2063 case aListTrustDB: set_cmd( &cmd, aListTrustDB); break;
2064 case aCheckTrustDB: set_cmd( &cmd, aCheckTrustDB); break;
2065 case aUpdateTrustDB: set_cmd( &cmd, aUpdateTrustDB); break;
2066 case aFixTrustDB: set_cmd( &cmd, aFixTrustDB); break;
2067 case aListTrustPath: set_cmd( &cmd, aListTrustPath); break;
2068 case aDeArmor: set_cmd( &cmd, aDeArmor); break;
2069 case aEnArmor: set_cmd( &cmd, aEnArmor); break;
2070 case aListOwnerTrust:
2071 deprecated_warning(configname,configlineno,
2072 "--list-ownertrust","--export-ownertrust","");
2073 case aExportOwnerTrust: set_cmd( &cmd, aExportOwnerTrust); break;
2074 case aImportOwnerTrust: set_cmd( &cmd, aImportOwnerTrust); break;
2075 case aRebuildKeydbCaches: set_cmd( &cmd, aRebuildKeydbCaches); break;
2077 case oArmor: opt.armor = 1; opt.no_armor=0; break;
2078 case oOutput: opt.outfile = pargs.r.ret_str; break;
2079 case oMaxOutput: opt.max_output = pargs.r.ret_ulong; break;
2080 case oQuiet: opt.quiet = 1; break;
2081 case oNoTTY: tty_no_terminal(1); break;
2082 case oDryRun: opt.dry_run = 1; break;
2083 case oInteractive: opt.interactive = 1; break;
2084 case oVerbose:
2085 opt.verbose++;
2086 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2087 opt.list_options|=LIST_SHOW_UNUSABLE_UIDS;
2088 opt.list_options|=LIST_SHOW_UNUSABLE_SUBKEYS;
2089 break;
2090 case oKOption: set_cmd( &cmd, aKMode ); break;
2092 case oBatch: opt.batch = 1; nogreeting = 1; break;
2093 case oUseAgent:
2094 #ifndef __riscos__
2095 opt.use_agent = 1;
2096 #else /* __riscos__ */
2097 opt.use_agent = 0;
2098 riscos_not_implemented("use-agent");
2099 #endif /* __riscos__ */
2100 break;
2101 case oNoUseAgent: opt.use_agent = 0; break;
2102 case oGpgAgentInfo: opt.gpg_agent_info = pargs.r.ret_str; break;
2103 case oAnswerYes: opt.answer_yes = 1; break;
2104 case oAnswerNo: opt.answer_no = 1; break;
2105 case oKeyring: append_to_strlist( &nrings, pargs.r.ret_str); break;
2106 case oPrimaryKeyring:
2107 sl=append_to_strlist( &nrings, pargs.r.ret_str);
2108 sl->flags=2;
2109 break;
2110 case oShowKeyring:
2111 deprecated_warning(configname,configlineno,"--show-keyring",
2112 "--list-options ","show-keyring");
2113 opt.list_options|=LIST_SHOW_KEYRING;
2114 break;
2116 case oDebug: opt.debug |= pargs.r.ret_ulong; break;
2117 case oDebugAll: opt.debug = ~0; break;
2118 case oDebugLevel: debug_level = pargs.r.ret_str; break;
2120 case oStatusFD:
2121 set_status_fd( iobuf_translate_file_handle (pargs.r.ret_int, 1) );
2122 break;
2123 case oStatusFile:
2124 set_status_fd ( open_info_file (pargs.r.ret_str, 1) );
2125 break;
2126 case oAttributeFD:
2127 set_attrib_fd(iobuf_translate_file_handle (pargs.r.ret_int, 1));
2128 break;
2129 case oAttributeFile:
2130 set_attrib_fd ( open_info_file (pargs.r.ret_str, 1) );
2131 break;
2132 case oLoggerFD:
2133 log_set_fd (iobuf_translate_file_handle (pargs.r.ret_int, 1));
2134 break;
2135 case oLoggerFile:
2136 logfile = pargs.r.ret_str;
2137 break;
2139 case oWithFingerprint:
2140 opt.with_fingerprint = 1;
2141 with_fpr=1; /*fall thru*/
2142 case oFingerprint: opt.fingerprint++; break;
2143 case oSecretKeyring:
2144 append_to_strlist( &sec_nrings, pargs.r.ret_str);
2145 break;
2146 case oOptions:
2147 /* config files may not be nested (silently ignore them) */
2148 if( !configfp ) {
2149 xfree(configname);
2150 configname = xstrdup(pargs.r.ret_str);
2151 goto next_pass;
2153 break;
2154 case oNoArmor: opt.no_armor=1; opt.armor=0; break;
2155 case oNoDefKeyring: default_keyring = 0; break;
2156 case oNoGreeting: nogreeting = 1; break;
2157 case oNoVerbose:
2158 opt.verbose = 0;
2159 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2160 opt.list_sigs=0;
2161 break;
2162 case oQuickRandom:
2163 gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
2164 break;
2165 case oEmitVersion: opt.no_version=0; break;
2166 case oNoEmitVersion: opt.no_version=1; break;
2167 case oCompletesNeeded: opt.completes_needed = pargs.r.ret_int; break;
2168 case oMarginalsNeeded: opt.marginals_needed = pargs.r.ret_int; break;
2169 case oMaxCertDepth: opt.max_cert_depth = pargs.r.ret_int; break;
2170 case oTrustDBName: trustdb_name = pargs.r.ret_str; break;
2171 case oDefaultKey: opt.def_secret_key = pargs.r.ret_str; break;
2172 case oDefRecipient:
2173 if( *pargs.r.ret_str )
2174 opt.def_recipient = make_username(pargs.r.ret_str);
2175 break;
2176 case oDefRecipientSelf:
2177 xfree(opt.def_recipient); opt.def_recipient = NULL;
2178 opt.def_recipient_self = 1;
2179 break;
2180 case oNoDefRecipient:
2181 xfree(opt.def_recipient); opt.def_recipient = NULL;
2182 opt.def_recipient_self = 0;
2183 break;
2184 case oNoOptions: opt.no_homedir_creation = 1; break; /* no-options */
2185 case oHomedir: break;
2186 case oNoBatch: opt.batch = 0; break;
2187 case oWithKeyData: opt.with_key_data=1; /* fall thru */
2188 case oWithColons: opt.with_colons=':'; break;
2190 case oSkipVerify: opt.skip_verify=1; break;
2191 case oCompressKeys: opt.compress_keys = 1; break;
2192 case aListSecretKeys: set_cmd( &cmd, aListSecretKeys); break;
2193 /* There are many programs (like mutt) that call gpg with
2194 --always-trust so keep this option around for a long
2195 time. */
2196 case oAlwaysTrust: opt.trust_model=TM_ALWAYS; break;
2197 case oTrustModel:
2198 parse_trust_model(pargs.r.ret_str);
2199 break;
2200 case oForceOwnertrust:
2201 log_info(_("NOTE: %s is not for normal use!\n"),
2202 "--force-ownertrust");
2203 opt.force_ownertrust=string_to_trust_value(pargs.r.ret_str);
2204 if(opt.force_ownertrust==-1)
2206 log_error("invalid ownertrust `%s'\n",pargs.r.ret_str);
2207 opt.force_ownertrust=0;
2209 break;
2210 case oLoadExtension:
2211 #ifndef __riscos__
2212 #if defined(USE_DYNAMIC_LINKING) || defined(_WIN32)
2213 if(check_permissions(pargs.r.ret_str,2))
2214 log_info(_("cipher extension `%s' not loaded due to"
2215 " unsafe permissions\n"),pargs.r.ret_str);
2216 else
2217 register_cipher_extension(orig_argc? *orig_argv:NULL,
2218 pargs.r.ret_str);
2219 #endif
2220 #else /* __riscos__ */
2221 riscos_not_implemented("load-extension");
2222 #endif /* __riscos__ */
2223 break;
2224 case oRFC1991:
2225 opt.compliance = CO_RFC1991;
2226 opt.force_v4_certs = 0;
2227 opt.escape_from = 1;
2228 break;
2229 case oOpenPGP:
2230 case oRFC2440:
2231 /* TODO: When 2440bis becomes a RFC, set new values for
2232 oOpenPGP. */
2233 opt.rfc2440_text=1;
2234 opt.compliance = CO_RFC2440;
2235 opt.allow_non_selfsigned_uid = 1;
2236 opt.allow_freeform_uid = 1;
2237 opt.pgp2_workarounds = 0;
2238 opt.escape_from = 0;
2239 opt.force_v3_sigs = 0;
2240 opt.compress_keys = 0; /* not mandated, but we do it */
2241 opt.compress_sigs = 0; /* ditto. */
2242 opt.not_dash_escaped = 0;
2243 opt.def_cipher_algo = 0;
2244 opt.def_digest_algo = 0;
2245 opt.cert_digest_algo = 0;
2246 opt.compress_algo = -1;
2247 opt.s2k_mode = 3; /* iterated+salted */
2248 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2249 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2250 break;
2251 case oPGP2: opt.compliance = CO_PGP2; break;
2252 case oPGP6: opt.compliance = CO_PGP6; break;
2253 case oPGP7: opt.compliance = CO_PGP7; break;
2254 case oPGP8: opt.compliance = CO_PGP8; break;
2255 case oGnuPG: opt.compliance = CO_GNUPG; break;
2256 case oCompressSigs: opt.compress_sigs = 1; break;
2257 case oRFC2440Text: opt.rfc2440_text=1; break;
2258 case oNoRFC2440Text: opt.rfc2440_text=0; break;
2259 case oSetFilename:
2260 if(utf8_strings)
2261 opt.set_filename = pargs.r.ret_str;
2262 else
2263 opt.set_filename = native_to_utf8(pargs.r.ret_str);
2264 break;
2265 case oForYourEyesOnly: eyes_only = 1; break;
2266 case oNoForYourEyesOnly: eyes_only = 0; break;
2267 case oSetPolicyURL:
2268 add_policy_url(pargs.r.ret_str,0);
2269 add_policy_url(pargs.r.ret_str,1);
2270 break;
2271 case oSigPolicyURL: add_policy_url(pargs.r.ret_str,0); break;
2272 case oCertPolicyURL: add_policy_url(pargs.r.ret_str,1); break;
2273 case oShowPolicyURL:
2274 deprecated_warning(configname,configlineno,"--show-policy-url",
2275 "--list-options ","show-policy-urls");
2276 deprecated_warning(configname,configlineno,"--show-policy-url",
2277 "--verify-options ","show-policy-urls");
2278 opt.list_options|=LIST_SHOW_POLICY_URLS;
2279 opt.verify_options|=VERIFY_SHOW_POLICY_URLS;
2280 break;
2281 case oNoShowPolicyURL:
2282 deprecated_warning(configname,configlineno,"--no-show-policy-url",
2283 "--list-options ","no-show-policy-urls");
2284 deprecated_warning(configname,configlineno,"--no-show-policy-url",
2285 "--verify-options ","no-show-policy-urls");
2286 opt.list_options&=~LIST_SHOW_POLICY_URLS;
2287 opt.verify_options&=~VERIFY_SHOW_POLICY_URLS;
2288 break;
2289 case oSigKeyserverURL: add_keyserver_url(pargs.r.ret_str,0); break;
2290 case oUseEmbeddedFilename:
2291 opt.flags.use_embedded_filename=1;
2292 break;
2293 case oNoUseEmbeddedFilename:
2294 opt.flags.use_embedded_filename=0;
2295 break;
2296 case oComment:
2297 if(pargs.r.ret_str[0])
2298 append_to_strlist(&opt.comments,pargs.r.ret_str);
2299 break;
2300 case oDefaultComment:
2301 deprecated_warning(configname,configlineno,
2302 "--default-comment","--no-comments","");
2303 /* fall through */
2304 case oNoComments:
2305 free_strlist(opt.comments);
2306 opt.comments=NULL;
2307 break;
2308 case oThrowKeyids: opt.throw_keyid = 1; break;
2309 case oNoThrowKeyids: opt.throw_keyid = 0; break;
2310 case oShowPhotos:
2311 deprecated_warning(configname,configlineno,"--show-photos",
2312 "--list-options ","show-photos");
2313 deprecated_warning(configname,configlineno,"--show-photos",
2314 "--verify-options ","show-photos");
2315 opt.list_options|=LIST_SHOW_PHOTOS;
2316 opt.verify_options|=VERIFY_SHOW_PHOTOS;
2317 break;
2318 case oNoShowPhotos:
2319 deprecated_warning(configname,configlineno,"--no-show-photos",
2320 "--list-options ","no-show-photos");
2321 deprecated_warning(configname,configlineno,"--no-show-photos",
2322 "--verify-options ","no-show-photos");
2323 opt.list_options&=~LIST_SHOW_PHOTOS;
2324 opt.verify_options&=~VERIFY_SHOW_PHOTOS;
2325 break;
2326 case oPhotoViewer: opt.photo_viewer = pargs.r.ret_str; break;
2327 case oForceV3Sigs: opt.force_v3_sigs = 1; break;
2328 case oNoForceV3Sigs: opt.force_v3_sigs = 0; break;
2329 case oForceV4Certs: opt.force_v4_certs = 1; break;
2330 case oNoForceV4Certs: opt.force_v4_certs = 0; break;
2331 case oForceMDC: opt.force_mdc = 1; break;
2332 case oNoForceMDC: opt.force_mdc = 0; break;
2333 case oDisableMDC: opt.disable_mdc = 1; break;
2334 case oNoDisableMDC: opt.disable_mdc = 0; break;
2335 case oS2KMode: opt.s2k_mode = pargs.r.ret_int; break;
2336 case oS2KDigest: s2k_digest_string = xstrdup(pargs.r.ret_str); break;
2337 case oS2KCipher: s2k_cipher_string = xstrdup(pargs.r.ret_str); break;
2338 case oSimpleSKChecksum: opt.simple_sk_checksum = 1; break;
2339 case oNoEncryptTo: opt.no_encrypt_to = 1; break;
2340 case oEncryptTo: /* store the recipient in the second list */
2341 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2342 sl->flags = 1;
2343 break;
2344 case oHiddenEncryptTo: /* store the recipient in the second list */
2345 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2346 sl->flags = 1|2;
2347 break;
2348 case oRecipient: /* store the recipient */
2349 add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2350 any_explicit_recipient = 1;
2351 break;
2352 case oHiddenRecipient: /* store the recipient with a flag */
2353 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2354 sl->flags = 2;
2355 any_explicit_recipient = 1;
2356 break;
2357 case oTextmodeShort: opt.textmode = 2; break;
2358 case oTextmode: opt.textmode=1; break;
2359 case oNoTextmode: opt.textmode=0; break;
2360 case oExpert: opt.expert = 1; break;
2361 case oNoExpert: opt.expert = 0; break;
2362 case oDefSigExpire:
2363 if(*pargs.r.ret_str!='\0')
2365 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
2366 log_error(_("`%s' is not a valid signature expiration\n"),
2367 pargs.r.ret_str);
2368 else
2369 opt.def_sig_expire=pargs.r.ret_str;
2371 break;
2372 case oAskSigExpire: opt.ask_sig_expire = 1; break;
2373 case oNoAskSigExpire: opt.ask_sig_expire = 0; break;
2374 case oDefCertExpire:
2375 if(*pargs.r.ret_str!='\0')
2377 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
2378 log_error(_("`%s' is not a valid signature expiration\n"),
2379 pargs.r.ret_str);
2380 else
2381 opt.def_cert_expire=pargs.r.ret_str;
2383 break;
2384 case oAskCertExpire: opt.ask_cert_expire = 1; break;
2385 case oNoAskCertExpire: opt.ask_cert_expire = 0; break;
2386 case oDefCertLevel: opt.def_cert_level=pargs.r.ret_int; break;
2387 case oMinCertLevel: opt.min_cert_level=pargs.r.ret_int; break;
2388 case oAskCertLevel: opt.ask_cert_level = 1; break;
2389 case oNoAskCertLevel: opt.ask_cert_level = 0; break;
2390 case oLocalUser: /* store the local users */
2391 add_to_strlist2( &locusr, pargs.r.ret_str, utf8_strings );
2392 break;
2393 case oCompress:
2394 /* this is the -z command line option */
2395 opt.compress_level = opt.bz2_compress_level = pargs.r.ret_int;
2396 break;
2397 case oCompressLevel: opt.compress_level = pargs.r.ret_int; break;
2398 case oBZ2CompressLevel: opt.bz2_compress_level = pargs.r.ret_int; break;
2399 case oBZ2DecompressLowmem: opt.bz2_decompress_lowmem=1; break;
2400 case oPasswd:
2401 set_passphrase_from_string(pargs.r.ret_str);
2402 break;
2403 case oPasswdFD:
2404 pwfd = iobuf_translate_file_handle (pargs.r.ret_int, 0);
2405 opt.use_agent = 0;
2406 break;
2407 case oPasswdFile:
2408 pwfd = open_info_file (pargs.r.ret_str, 0);
2409 break;
2410 case oCommandFD:
2411 opt.command_fd = iobuf_translate_file_handle (pargs.r.ret_int, 0);
2412 break;
2413 case oCommandFile:
2414 opt.command_fd = open_info_file (pargs.r.ret_str, 0);
2415 break;
2416 case oCipherAlgo:
2417 def_cipher_string = xstrdup(pargs.r.ret_str);
2418 break;
2419 case oDigestAlgo:
2420 def_digest_string = xstrdup(pargs.r.ret_str);
2421 break;
2422 case oCompressAlgo:
2423 /* If it is all digits, stick a Z in front of it for
2424 later. This is for backwards compatibility with
2425 versions that took the compress algorithm number. */
2427 char *pt=pargs.r.ret_str;
2428 while(*pt)
2430 if (!isascii (*pt) || !isdigit (*pt))
2431 break;
2433 pt++;
2436 if(*pt=='\0')
2438 compress_algo_string=xmalloc(strlen(pargs.r.ret_str)+2);
2439 strcpy(compress_algo_string,"Z");
2440 strcat(compress_algo_string,pargs.r.ret_str);
2442 else
2443 compress_algo_string = xstrdup(pargs.r.ret_str);
2445 break;
2446 case oCertDigestAlgo:
2447 cert_digest_string = xstrdup(pargs.r.ret_str);
2448 break;
2450 case oNoSecmemWarn:
2451 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
2452 break;
2454 case oRequireSecmem: require_secmem=1; break;
2455 case oNoRequireSecmem: require_secmem=0; break;
2456 case oNoPermissionWarn: opt.no_perm_warn=1; break;
2457 case oNoMDCWarn: opt.no_mdc_warn=1; break;
2458 case oDisplayCharset:
2459 if( set_native_charset( pargs.r.ret_str ) )
2460 log_error(_("`%s' is not a valid character set\n"),
2461 pargs.r.ret_str);
2462 break;
2463 case oNotDashEscaped: opt.not_dash_escaped = 1; break;
2464 case oEscapeFrom: opt.escape_from = 1; break;
2465 case oNoEscapeFrom: opt.escape_from = 0; break;
2466 case oLockOnce: opt.lock_once = 1; break;
2467 case oLockNever:
2468 disable_dotlock ();
2469 break;
2470 case oLockMultiple:
2471 #ifndef __riscos__
2472 opt.lock_once = 0;
2473 #else /* __riscos__ */
2474 riscos_not_implemented("lock-multiple");
2475 #endif /* __riscos__ */
2476 break;
2477 case oKeyServer:
2479 struct keyserver_spec *keyserver;
2480 keyserver=parse_keyserver_uri(pargs.r.ret_str,0,
2481 configname,configlineno);
2482 if(!keyserver)
2483 log_error(_("could not parse keyserver URL\n"));
2484 else
2486 keyserver->next=opt.keyserver;
2487 opt.keyserver=keyserver;
2490 break;
2491 case oKeyServerOptions:
2492 if(!parse_keyserver_options(pargs.r.ret_str))
2494 if(configname)
2495 log_error(_("%s:%d: invalid keyserver options\n"),
2496 configname,configlineno);
2497 else
2498 log_error(_("invalid keyserver options\n"));
2500 break;
2501 case oImportOptions:
2502 if(!parse_import_options(pargs.r.ret_str,&opt.import_options,1))
2504 if(configname)
2505 log_error(_("%s:%d: invalid import options\n"),
2506 configname,configlineno);
2507 else
2508 log_error(_("invalid import options\n"));
2510 break;
2511 case oExportOptions:
2512 if(!parse_export_options(pargs.r.ret_str,&opt.export_options,1))
2514 if(configname)
2515 log_error(_("%s:%d: invalid export options\n"),
2516 configname,configlineno);
2517 else
2518 log_error(_("invalid export options\n"));
2520 break;
2521 case oListOptions:
2522 if(!parse_list_options(pargs.r.ret_str))
2524 if(configname)
2525 log_error(_("%s:%d: invalid list options\n"),
2526 configname,configlineno);
2527 else
2528 log_error(_("invalid list options\n"));
2530 break;
2531 case oVerifyOptions:
2533 struct parse_options vopts[]=
2535 {"show-photos",VERIFY_SHOW_PHOTOS,NULL,
2536 N_("display photo IDs during signature verification")},
2537 {"show-policy-urls",VERIFY_SHOW_POLICY_URLS,NULL,
2538 N_("show policy URLs during signature verification")},
2539 {"show-notations",VERIFY_SHOW_NOTATIONS,NULL,
2540 N_("show all notations during signature verification")},
2541 {"show-std-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
2542 N_("show IETF standard notations during signature verification")},
2543 {"show-standard-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
2544 NULL},
2545 {"show-user-notations",VERIFY_SHOW_USER_NOTATIONS,NULL,
2546 N_("show user-supplied notations during signature verification")},
2547 {"show-keyserver-urls",VERIFY_SHOW_KEYSERVER_URLS,NULL,
2548 N_("show preferred keyserver URLs during signature verification")},
2549 {"show-uid-validity",VERIFY_SHOW_UID_VALIDITY,NULL,
2550 N_("show user ID validity during signature verification")},
2551 {"show-unusable-uids",VERIFY_SHOW_UNUSABLE_UIDS,NULL,
2552 N_("show revoked and expired user IDs in signature verification")},
2553 {"pka-lookups",VERIFY_PKA_LOOKUPS,NULL,
2554 N_("validate signatures with PKA data")},
2555 {"pka-trust-increase",VERIFY_PKA_TRUST_INCREASE,NULL,
2556 N_("elevate the trust of signatures with valid PKA data")},
2557 {NULL,0,NULL,NULL}
2560 if(!parse_options(pargs.r.ret_str,&opt.verify_options,vopts,1))
2562 if(configname)
2563 log_error(_("%s:%d: invalid verify options\n"),
2564 configname,configlineno);
2565 else
2566 log_error(_("invalid verify options\n"));
2569 break;
2570 case oTempDir: opt.temp_dir=pargs.r.ret_str; break;
2571 case oExecPath:
2572 if(set_exec_path(pargs.r.ret_str))
2573 log_error(_("unable to set exec-path to %s\n"),pargs.r.ret_str);
2574 else
2575 opt.exec_path_set=1;
2576 break;
2577 case oSetNotation:
2578 add_notation_data( pargs.r.ret_str, 0 );
2579 add_notation_data( pargs.r.ret_str, 1 );
2580 break;
2581 case oSigNotation: add_notation_data( pargs.r.ret_str, 0 ); break;
2582 case oCertNotation: add_notation_data( pargs.r.ret_str, 1 ); break;
2583 case oShowNotation:
2584 deprecated_warning(configname,configlineno,"--show-notation",
2585 "--list-options ","show-notations");
2586 deprecated_warning(configname,configlineno,"--show-notation",
2587 "--verify-options ","show-notations");
2588 opt.list_options|=LIST_SHOW_NOTATIONS;
2589 opt.verify_options|=VERIFY_SHOW_NOTATIONS;
2590 break;
2591 case oNoShowNotation:
2592 deprecated_warning(configname,configlineno,"--no-show-notation",
2593 "--list-options ","no-show-notations");
2594 deprecated_warning(configname,configlineno,"--no-show-notation",
2595 "--verify-options ","no-show-notations");
2596 opt.list_options&=~LIST_SHOW_NOTATIONS;
2597 opt.verify_options&=~VERIFY_SHOW_NOTATIONS;
2598 break;
2599 case oUtf8Strings: utf8_strings = 1; break;
2600 case oNoUtf8Strings: utf8_strings = 0; break;
2601 case oDisableCipherAlgo:
2603 int algo = string_to_cipher_algo (pargs.r.ret_str);
2604 gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
2606 break;
2607 case oDisablePubkeyAlgo:
2609 int algo = gcry_pk_map_name (pargs.r.ret_str);
2610 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
2612 break;
2613 case oNoSigCache: opt.no_sig_cache = 1; break;
2614 case oNoSigCreateCheck: opt.no_sig_create_check = 1; break;
2615 case oAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid = 1; break;
2616 case oNoAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid=0; break;
2617 case oAllowFreeformUID: opt.allow_freeform_uid = 1; break;
2618 case oNoAllowFreeformUID: opt.allow_freeform_uid = 0; break;
2619 case oNoLiteral: opt.no_literal = 1; break;
2620 case oSetFilesize: opt.set_filesize = pargs.r.ret_ulong; break;
2621 case oHonorHttpProxy:
2622 add_to_strlist(&opt.keyserver_options.other,"http-proxy");
2623 deprecated_warning(configname,configlineno,
2624 "--honor-http-proxy",
2625 "--keyserver-options ","http-proxy");
2626 break;
2627 case oFastListMode: opt.fast_list_mode = 1; break;
2628 case oFixedListMode: opt.fixed_list_mode = 1; break;
2629 case oListOnly: opt.list_only=1; break;
2630 case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
2631 case oIgnoreValidFrom: opt.ignore_valid_from = 1; break;
2632 case oIgnoreCrcError: opt.ignore_crc_error = 1; break;
2633 case oIgnoreMDCError: opt.ignore_mdc_error = 1; break;
2634 case oNoRandomSeedFile: use_random_seed = 0; break;
2635 case oAutoKeyRetrieve:
2636 case oNoAutoKeyRetrieve:
2637 if(pargs.r_opt==oAutoKeyRetrieve)
2638 opt.keyserver_options.options|=KEYSERVER_AUTO_KEY_RETRIEVE;
2639 else
2640 opt.keyserver_options.options&=~KEYSERVER_AUTO_KEY_RETRIEVE;
2642 deprecated_warning(configname,configlineno,
2643 pargs.r_opt==oAutoKeyRetrieve?"--auto-key-retrieve":
2644 "--no-auto-key-retrieve","--keyserver-options ",
2645 pargs.r_opt==oAutoKeyRetrieve?"auto-key-retrieve":
2646 "no-auto-key-retrieve");
2647 break;
2648 case oShowSessionKey: opt.show_session_key = 1; break;
2649 case oOverrideSessionKey:
2650 opt.override_session_key = pargs.r.ret_str;
2651 break;
2652 case oMergeOnly:
2653 deprecated_warning(configname,configlineno,"--merge-only",
2654 "--import-options ","merge-only");
2655 opt.import_options|=IMPORT_MERGE_ONLY;
2656 break;
2657 case oAllowSecretKeyImport: /* obsolete */ break;
2658 case oTryAllSecrets: opt.try_all_secrets = 1; break;
2659 case oTrustedKey: register_trusted_key( pargs.r.ret_str ); break;
2660 case oEnableSpecialFilenames:
2661 iobuf_enable_special_filenames (1);
2662 break;
2663 case oNoExpensiveTrustChecks: opt.no_expensive_trust_checks=1; break;
2664 case oAutoCheckTrustDB: opt.no_auto_check_trustdb=0; break;
2665 case oNoAutoCheckTrustDB: opt.no_auto_check_trustdb=1; break;
2666 case oPreservePermissions: opt.preserve_permissions=1; break;
2667 case oDefaultPreferenceList:
2668 opt.def_preference_list = pargs.r.ret_str;
2669 break;
2670 case oDefaultKeyserverURL:
2672 struct keyserver_spec *keyserver;
2673 keyserver=parse_keyserver_uri(pargs.r.ret_str,1,
2674 configname,configlineno);
2675 if(!keyserver)
2676 log_error(_("could not parse keyserver URL\n"));
2677 else
2678 free_keyserver_spec(keyserver);
2680 opt.def_keyserver_url = pargs.r.ret_str;
2682 break;
2683 case oPersonalCipherPreferences:
2684 pers_cipher_list=pargs.r.ret_str;
2685 break;
2686 case oPersonalDigestPreferences:
2687 pers_digest_list=pargs.r.ret_str;
2688 break;
2689 case oPersonalCompressPreferences:
2690 pers_compress_list=pargs.r.ret_str;
2691 break;
2692 case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
2693 case oDisplay: opt.display = pargs.r.ret_str; break;
2694 case oTTYname: opt.ttyname = pargs.r.ret_str; break;
2695 case oTTYtype: opt.ttytype = pargs.r.ret_str; break;
2696 case oLCctype: opt.lc_ctype = pargs.r.ret_str; break;
2697 case oLCmessages: opt.lc_messages = pargs.r.ret_str; break;
2698 case oGroup: add_group(pargs.r.ret_str); break;
2699 case oUnGroup: rm_group(pargs.r.ret_str); break;
2700 case oNoGroups:
2701 while(opt.grouplist)
2703 struct groupitem *iter=opt.grouplist;
2704 free_strlist(iter->values);
2705 opt.grouplist=opt.grouplist->next;
2706 xfree(iter);
2708 break;
2710 case oStrict:
2711 case oNoStrict:
2712 /* Not used */
2713 break;
2715 case oMangleDosFilenames: opt.mangle_dos_filenames = 1; break;
2716 case oNoMangleDosFilenames: opt.mangle_dos_filenames = 0; break;
2717 case oEnableProgressFilter: opt.enable_progress_filter = 1; break;
2718 case oMultifile: multifile=1; break;
2719 case oKeyidFormat:
2720 if(ascii_strcasecmp(pargs.r.ret_str,"short")==0)
2721 opt.keyid_format=KF_SHORT;
2722 else if(ascii_strcasecmp(pargs.r.ret_str,"long")==0)
2723 opt.keyid_format=KF_LONG;
2724 else if(ascii_strcasecmp(pargs.r.ret_str,"0xshort")==0)
2725 opt.keyid_format=KF_0xSHORT;
2726 else if(ascii_strcasecmp(pargs.r.ret_str,"0xlong")==0)
2727 opt.keyid_format=KF_0xLONG;
2728 else
2729 log_error("unknown keyid-format `%s'\n",pargs.r.ret_str);
2730 break;
2732 case oExitOnStatusWriteError:
2733 opt.exit_on_status_write_error = 1;
2734 break;
2736 case oLimitCardInsertTries:
2737 opt.limit_card_insert_tries = pargs.r.ret_int;
2738 break;
2740 case oRequireCrossCert: opt.flags.require_cross_cert=1; break;
2741 case oNoRequireCrossCert: opt.flags.require_cross_cert=0; break;
2743 case oAutoKeyLocate:
2744 if(!parse_auto_key_locate(pargs.r.ret_str))
2746 if(configname)
2747 log_error(_("%s:%d: invalid auto-key-locate list\n"),
2748 configname,configlineno);
2749 else
2750 log_error(_("invalid auto-key-locate list\n"));
2752 break;
2753 case oNoAutoKeyLocate:
2754 release_akl();
2755 break;
2757 case oAllowMultisigVerification:
2758 opt.allow_multisig_verification = 1;
2759 break;
2761 case oEnableDSA2: opt.flags.dsa2=1; break;
2762 case oDisableDSA2: opt.flags.dsa2=0; break;
2764 case oNoop: break;
2766 default : pargs.err = configfp? 1:2; break;
2771 if( configfp ) {
2772 fclose( configfp );
2773 configfp = NULL;
2774 /* Remember the first config file name. */
2775 if (!save_configname)
2776 save_configname = configname;
2777 else
2778 xfree(configname);
2779 configname = NULL;
2780 goto next_pass;
2782 xfree( configname ); configname = NULL;
2783 if( log_get_errorcount(0) )
2784 g10_exit(2);
2786 /* The command --gpgconf-list is pretty simple and may be called
2787 directly after the option parsing. */
2788 if (cmd == aGPGConfList)
2790 gpgconf_list (save_configname);
2791 g10_exit (0);
2793 xfree (save_configname);
2795 if( nogreeting )
2796 greeting = 0;
2798 if( greeting ) {
2799 fprintf(stderr, "%s %s; %s\n",
2800 strusage(11), strusage(13), strusage(14) );
2801 fprintf(stderr, "%s\n", strusage(15) );
2803 #ifdef IS_DEVELOPMENT_VERSION
2804 if( !opt.batch )
2806 const char *s;
2808 if((s=strusage(20)))
2809 log_info("%s\n",s);
2810 if((s=strusage(21)))
2811 log_info("%s\n",s);
2812 if((s=strusage(22)))
2813 log_info("%s\n",s);
2815 #endif
2817 log_info ("WARNING: This version of gpg is not ready for use, use gpg 1.4.x\n");
2819 /* FIXME: We should use logging to a file only in server mode;
2820 however we have not yet implemetyed that. Thus we try to get
2821 away with --batch as indication for logging to file
2822 required. */
2823 if (logfile && opt.batch)
2825 log_set_file (logfile);
2826 log_set_prefix (NULL, 1|2|4);
2829 if (opt.verbose > 2)
2830 log_info ("using character set `%s'\n", get_native_charset ());
2832 if( may_coredump && !opt.quiet )
2833 log_info(_("WARNING: program may create a core file!\n"));
2835 if (eyes_only) {
2836 if (opt.set_filename)
2837 log_info(_("WARNING: %s overrides %s\n"),
2838 "--for-your-eyes-only","--set-filename");
2840 opt.set_filename="_CONSOLE";
2843 if (opt.no_literal) {
2844 log_info(_("NOTE: %s is not for normal use!\n"), "--no-literal");
2845 if (opt.textmode)
2846 log_error(_("%s not allowed with %s!\n"),
2847 "--textmode", "--no-literal" );
2848 if (opt.set_filename)
2849 log_error(_("%s makes no sense with %s!\n"),
2850 eyes_only?"--for-your-eyes-only":"--set-filename",
2851 "--no-literal" );
2855 if (opt.set_filesize)
2856 log_info(_("NOTE: %s is not for normal use!\n"), "--set-filesize");
2857 if( opt.batch )
2858 tty_batchmode( 1 );
2860 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
2862 if(require_secmem && !got_secmem)
2864 log_info(_("will not run with insecure memory due to %s\n"),
2865 "--require-secmem");
2866 g10_exit(2);
2869 set_debug (debug_level);
2871 /* Do these after the switch(), so they can override settings. */
2872 if(PGP2)
2874 int unusable=0;
2876 if(cmd==aSign && !detached_sig)
2878 log_info(_("you can only make detached or clear signatures "
2879 "while in --pgp2 mode\n"));
2880 unusable=1;
2882 else if(cmd==aSignEncr || cmd==aSignSym)
2884 log_info(_("you can't sign and encrypt at the "
2885 "same time while in --pgp2 mode\n"));
2886 unusable=1;
2888 else if(argc==0 && (cmd==aSign || cmd==aEncr || cmd==aSym))
2890 log_info(_("you must use files (and not a pipe) when "
2891 "working with --pgp2 enabled.\n"));
2892 unusable=1;
2894 else if(cmd==aEncr || cmd==aSym)
2896 /* Everything else should work without IDEA (except using
2897 a secret key encrypted with IDEA and setting an IDEA
2898 preference, but those have their own error
2899 messages). */
2901 if (openpgp_cipher_test_algo(CIPHER_ALGO_IDEA))
2903 log_info(_("encrypting a message in --pgp2 mode requires "
2904 "the IDEA cipher\n"));
2905 idea_cipher_warn(1);
2906 unusable=1;
2908 else if(cmd==aSym)
2910 /* This only sets IDEA for symmetric encryption
2911 since it is set via select_algo_from_prefs for
2912 pk encryption. */
2913 xfree(def_cipher_string);
2914 def_cipher_string = xstrdup("idea");
2917 /* PGP2 can't handle the output from the textmode
2918 filter, so we disable it for anything that could
2919 create a literal packet (only encryption and
2920 symmetric encryption, since we disable signing
2921 above). */
2922 if(!unusable)
2923 opt.textmode=0;
2926 if(unusable)
2927 compliance_failure();
2928 else
2930 opt.force_v4_certs = 0;
2931 opt.escape_from = 1;
2932 opt.force_v3_sigs = 1;
2933 opt.pgp2_workarounds = 1;
2934 opt.ask_sig_expire = 0;
2935 opt.ask_cert_expire = 0;
2936 xfree(def_digest_string);
2937 def_digest_string = xstrdup("md5");
2938 xfree(s2k_digest_string);
2939 s2k_digest_string = xstrdup("md5");
2940 opt.compress_algo = COMPRESS_ALGO_ZIP;
2943 else if(PGP6)
2945 opt.escape_from=1;
2946 opt.force_v3_sigs=1;
2947 opt.ask_sig_expire=0;
2949 else if(PGP7)
2951 opt.escape_from=1;
2952 opt.force_v3_sigs=1;
2953 opt.ask_sig_expire=0;
2955 else if(PGP8)
2957 opt.escape_from=1;
2961 if( def_cipher_string ) {
2962 opt.def_cipher_algo = string_to_cipher_algo (def_cipher_string);
2963 if(opt.def_cipher_algo==0 &&
2964 (ascii_strcasecmp(def_cipher_string,"idea")==0
2965 || ascii_strcasecmp(def_cipher_string,"s1")==0))
2966 idea_cipher_warn(1);
2967 xfree(def_cipher_string); def_cipher_string = NULL;
2968 if ( openpgp_cipher_test_algo (opt.def_cipher_algo) )
2969 log_error(_("selected cipher algorithm is invalid\n"));
2971 if( def_digest_string ) {
2972 opt.def_digest_algo = string_to_digest_algo (def_digest_string);
2973 xfree(def_digest_string); def_digest_string = NULL;
2974 if ( openpgp_md_test_algo (opt.def_digest_algo) )
2975 log_error(_("selected digest algorithm is invalid\n"));
2977 if( compress_algo_string ) {
2978 opt.compress_algo = string_to_compress_algo(compress_algo_string);
2979 xfree(compress_algo_string); compress_algo_string = NULL;
2980 if( check_compress_algo(opt.compress_algo) )
2981 log_error(_("selected compression algorithm is invalid\n"));
2983 if( cert_digest_string ) {
2984 opt.cert_digest_algo = string_to_digest_algo (cert_digest_string);
2985 xfree(cert_digest_string); cert_digest_string = NULL;
2986 if (openpgp_md_test_algo(opt.cert_digest_algo))
2987 log_error(_("selected certification digest algorithm is invalid\n"));
2989 if( s2k_cipher_string ) {
2990 opt.s2k_cipher_algo = string_to_cipher_algo (s2k_cipher_string);
2991 xfree(s2k_cipher_string); s2k_cipher_string = NULL;
2992 if (openpgp_cipher_test_algo (opt.s2k_cipher_algo))
2993 log_error(_("selected cipher algorithm is invalid\n"));
2995 if( s2k_digest_string ) {
2996 opt.s2k_digest_algo = string_to_digest_algo (s2k_digest_string);
2997 xfree(s2k_digest_string); s2k_digest_string = NULL;
2998 if (openpgp_md_test_algo(opt.s2k_digest_algo))
2999 log_error(_("selected digest algorithm is invalid\n"));
3001 if( opt.completes_needed < 1 )
3002 log_error(_("completes-needed must be greater than 0\n"));
3003 if( opt.marginals_needed < 2 )
3004 log_error(_("marginals-needed must be greater than 1\n"));
3005 if( opt.max_cert_depth < 1 || opt.max_cert_depth > 255 )
3006 log_error(_("max-cert-depth must be in the range from 1 to 255\n"));
3007 if(opt.def_cert_level<0 || opt.def_cert_level>3)
3008 log_error(_("invalid default-cert-level; must be 0, 1, 2, or 3\n"));
3009 if( opt.min_cert_level < 1 || opt.min_cert_level > 3 )
3010 log_error(_("invalid min-cert-level; must be 1, 2, or 3\n"));
3011 switch( opt.s2k_mode ) {
3012 case 0:
3013 log_info(_("NOTE: simple S2K mode (0) is strongly discouraged\n"));
3014 break;
3015 case 1: case 3: break;
3016 default:
3017 log_error(_("invalid S2K mode; must be 0, 1 or 3\n"));
3020 /* This isn't actually needed, but does serve to error out if the
3021 string is invalid. */
3022 if(opt.def_preference_list &&
3023 keygen_set_std_prefs(opt.def_preference_list,0))
3024 log_error(_("invalid default preferences\n"));
3026 /* We provide defaults for the personal digest list. This is
3027 SHA-1. */
3028 if(!pers_digest_list)
3029 pers_digest_list="h2";
3031 if(pers_cipher_list &&
3032 keygen_set_std_prefs(pers_cipher_list,PREFTYPE_SYM))
3033 log_error(_("invalid personal cipher preferences\n"));
3035 if(pers_digest_list &&
3036 keygen_set_std_prefs(pers_digest_list,PREFTYPE_HASH))
3037 log_error(_("invalid personal digest preferences\n"));
3039 if(pers_compress_list &&
3040 keygen_set_std_prefs(pers_compress_list,PREFTYPE_ZIP))
3041 log_error(_("invalid personal compress preferences\n"));
3043 /* We don't support all possible commands with multifile yet */
3044 if(multifile)
3046 char *cmdname;
3048 switch(cmd)
3050 case aSign:
3051 cmdname="--sign";
3052 break;
3053 case aClearsign:
3054 cmdname="--clearsign";
3055 break;
3056 case aDetachedSign:
3057 cmdname="--detach-sign";
3058 break;
3059 case aSym:
3060 cmdname="--symmetric";
3061 break;
3062 case aEncrSym:
3063 cmdname="--symmetric --encrypt";
3064 break;
3065 case aStore:
3066 cmdname="--store";
3067 break;
3068 default:
3069 cmdname=NULL;
3070 break;
3073 if(cmdname)
3074 log_error(_("%s does not yet work with %s\n"),cmdname,"--multifile");
3077 if( log_get_errorcount(0) )
3078 g10_exit(2);
3080 if(opt.compress_level==0)
3081 opt.compress_algo=COMPRESS_ALGO_NONE;
3083 /* Check our chosen algorithms against the list of legal
3084 algorithms. */
3086 if(!GNUPG)
3088 const char *badalg=NULL;
3089 preftype_t badtype=PREFTYPE_NONE;
3091 if(opt.def_cipher_algo
3092 && !algo_available(PREFTYPE_SYM,opt.def_cipher_algo,NULL))
3094 badalg = gcry_cipher_algo_name (opt.def_cipher_algo);
3095 badtype = PREFTYPE_SYM;
3097 else if(opt.def_digest_algo
3098 && !algo_available(PREFTYPE_HASH,opt.def_digest_algo,NULL))
3100 badalg = gcry_md_algo_name (opt.def_digest_algo);
3101 badtype = PREFTYPE_HASH;
3103 else if(opt.cert_digest_algo
3104 && !algo_available(PREFTYPE_HASH,opt.cert_digest_algo,NULL))
3106 badalg = gcry_md_algo_name (opt.cert_digest_algo);
3107 badtype = PREFTYPE_HASH;
3109 else if(opt.compress_algo!=-1
3110 && !algo_available(PREFTYPE_ZIP,opt.compress_algo,NULL))
3112 badalg = compress_algo_to_string(opt.compress_algo);
3113 badtype = PREFTYPE_ZIP;
3116 if(badalg)
3118 switch(badtype)
3120 case PREFTYPE_SYM:
3121 log_info(_("you may not use cipher algorithm `%s'"
3122 " while in %s mode\n"),
3123 badalg,compliance_option_string());
3124 break;
3125 case PREFTYPE_HASH:
3126 log_info(_("you may not use digest algorithm `%s'"
3127 " while in %s mode\n"),
3128 badalg,compliance_option_string());
3129 break;
3130 case PREFTYPE_ZIP:
3131 log_info(_("you may not use compression algorithm `%s'"
3132 " while in %s mode\n"),
3133 badalg,compliance_option_string());
3134 break;
3135 default:
3136 BUG();
3139 compliance_failure();
3143 /* Set the random seed file. */
3144 if( use_random_seed ) {
3145 char *p = make_filename(opt.homedir, "random_seed", NULL );
3146 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
3147 if (!access (p, F_OK))
3148 register_secured_file (p);
3149 xfree(p);
3152 if( !cmd && opt.fingerprint && !with_fpr ) {
3153 set_cmd( &cmd, aListKeys);
3156 if( cmd == aKMode || cmd == aKModeC ) { /* kludge to be compatible to pgp */
3157 if( cmd == aKModeC ) {
3158 opt.fingerprint = 1;
3159 cmd = aKMode;
3161 opt.list_sigs = 0;
3162 if( opt.verbose > 2 )
3163 opt.check_sigs++;
3164 if( opt.verbose > 1 )
3165 opt.list_sigs++;
3167 opt.verbose = opt.verbose > 1;
3170 /* kludge to let -sat generate a clear text signature */
3171 if( opt.textmode == 2 && !detached_sig && opt.armor && cmd == aSign )
3172 cmd = aClearsign;
3174 if( opt.verbose > 1 )
3175 set_packet_list_mode(1);
3177 /* Add the keyrings, but not for some special commands and not in
3178 case of "-kvv userid keyring". Also avoid adding the secret
3179 keyring for a couple of commands to avoid unneeded access in
3180 case the secrings are stored on a floppy.
3182 We always need to add the keyrings if we are running under
3183 SELinux, this is so that the rings are added to the list of
3184 secured files. */
3185 if( ALWAYS_ADD_KEYRINGS
3186 || (cmd != aDeArmor && cmd != aEnArmor
3187 && !(cmd == aKMode && argc == 2 )) )
3189 if (ALWAYS_ADD_KEYRINGS
3190 || (cmd != aCheckKeys && cmd != aListSigs && cmd != aListKeys
3191 && cmd != aVerify && cmd != aSym))
3193 if (!sec_nrings || default_keyring) /* add default secret rings */
3194 keydb_add_resource ("secring" EXTSEP_S "gpg", 4, 1);
3195 for (sl = sec_nrings; sl; sl = sl->next)
3196 keydb_add_resource ( sl->d, 0, 1 );
3198 if( !nrings || default_keyring ) /* add default ring */
3199 keydb_add_resource ("pubring" EXTSEP_S "gpg", 4, 0);
3200 for(sl = nrings; sl; sl = sl->next )
3201 keydb_add_resource ( sl->d, sl->flags, 0 );
3203 FREE_STRLIST(nrings);
3204 FREE_STRLIST(sec_nrings);
3207 if( pwfd != -1 ) /* read the passphrase now. */
3208 read_passphrase_from_fd( pwfd );
3210 fname = argc? *argv : NULL;
3212 if(fname && utf8_strings)
3213 opt.flags.utf8_filename=1;
3215 switch( cmd ) {
3216 case aPrimegen:
3217 case aPrintMD:
3218 case aPrintMDs:
3219 case aGenRandom:
3220 case aDeArmor:
3221 case aEnArmor:
3222 case aFixTrustDB:
3223 break;
3224 case aExportOwnerTrust: rc = setup_trustdb( 0, trustdb_name ); break;
3225 case aListTrustDB: rc = setup_trustdb( argc? 1:0, trustdb_name ); break;
3226 default: rc = setup_trustdb(1, trustdb_name ); break;
3228 if( rc )
3229 log_error(_("failed to initialize the TrustDB: %s\n"), g10_errstr(rc));
3232 switch (cmd)
3234 case aStore:
3235 case aSym:
3236 case aSign:
3237 case aSignSym:
3238 case aClearsign:
3239 if (!opt.quiet && any_explicit_recipient)
3240 log_info (_("WARNING: recipients (-r) given "
3241 "without using public key encryption\n"));
3242 break;
3243 default:
3244 break;
3247 switch( cmd )
3249 case aStore: /* only store the file */
3250 if( argc > 1 )
3251 wrong_args(_("--store [filename]"));
3252 if( (rc = encode_store(fname)) )
3253 log_error ("storing `%s' failed: %s\n",
3254 print_fname_stdin(fname),g10_errstr(rc) );
3255 break;
3256 case aSym: /* encrypt the given file only with the symmetric cipher */
3257 if( argc > 1 )
3258 wrong_args(_("--symmetric [filename]"));
3259 if( (rc = encode_symmetric(fname)) )
3260 log_error (_("symmetric encryption of `%s' failed: %s\n"),
3261 print_fname_stdin(fname),g10_errstr(rc) );
3262 break;
3264 case aEncr: /* encrypt the given file */
3265 if(multifile)
3266 encode_crypt_files(argc, argv, remusr);
3267 else
3269 if( argc > 1 )
3270 wrong_args(_("--encrypt [filename]"));
3271 if( (rc = encode_crypt(fname,remusr,0)) )
3272 log_error("%s: encryption failed: %s\n",
3273 print_fname_stdin(fname), g10_errstr(rc) );
3275 break;
3277 case aEncrSym:
3278 /* This works with PGP 8 in the sense that it acts just like a
3279 symmetric message. It doesn't work at all with 2 or 6. It
3280 might work with 7, but alas, I don't have a copy to test
3281 with right now. */
3282 if( argc > 1 )
3283 wrong_args(_("--symmetric --encrypt [filename]"));
3284 else if(opt.s2k_mode==0)
3285 log_error(_("you cannot use --symmetric --encrypt"
3286 " with --s2k-mode 0\n"));
3287 else if(PGP2 || PGP6 || PGP7 || RFC1991)
3288 log_error(_("you cannot use --symmetric --encrypt"
3289 " while in %s mode\n"),compliance_option_string());
3290 else
3292 if( (rc = encode_crypt(fname,remusr,1)) )
3293 log_error("%s: encryption failed: %s\n",
3294 print_fname_stdin(fname), g10_errstr(rc) );
3296 break;
3298 case aSign: /* sign the given file */
3299 sl = NULL;
3300 if( detached_sig ) { /* sign all files */
3301 for( ; argc; argc--, argv++ )
3302 add_to_strlist( &sl, *argv );
3304 else {
3305 if( argc > 1 )
3306 wrong_args(_("--sign [filename]"));
3307 if( argc ) {
3308 sl = xmalloc_clear( sizeof *sl + strlen(fname));
3309 strcpy(sl->d, fname);
3312 if( (rc = sign_file( sl, detached_sig, locusr, 0, NULL, NULL)) )
3313 log_error("signing failed: %s\n", g10_errstr(rc) );
3314 free_strlist(sl);
3315 break;
3317 case aSignEncr: /* sign and encrypt the given file */
3318 if( argc > 1 )
3319 wrong_args(_("--sign --encrypt [filename]"));
3320 if( argc ) {
3321 sl = xmalloc_clear( sizeof *sl + strlen(fname));
3322 strcpy(sl->d, fname);
3324 else
3325 sl = NULL;
3326 if( (rc = sign_file(sl, detached_sig, locusr, 1, remusr, NULL)) )
3327 log_error("%s: sign+encrypt failed: %s\n",
3328 print_fname_stdin(fname), g10_errstr(rc) );
3329 free_strlist(sl);
3330 break;
3332 case aSignEncrSym: /* sign and encrypt the given file */
3333 if( argc > 1 )
3334 wrong_args(_("--symmetric --sign --encrypt [filename]"));
3335 else if(opt.s2k_mode==0)
3336 log_error(_("you cannot use --symmetric --sign --encrypt"
3337 " with --s2k-mode 0\n"));
3338 else if(PGP2 || PGP6 || PGP7 || RFC1991)
3339 log_error(_("you cannot use --symmetric --sign --encrypt"
3340 " while in %s mode\n"),compliance_option_string());
3341 else
3343 if( argc )
3345 sl = xmalloc_clear( sizeof *sl + strlen(fname));
3346 strcpy(sl->d, fname);
3348 else
3349 sl = NULL;
3350 if( (rc = sign_file(sl, detached_sig, locusr, 2, remusr, NULL)) )
3351 log_error("%s: symmetric+sign+encrypt failed: %s\n",
3352 print_fname_stdin(fname), g10_errstr(rc) );
3353 free_strlist(sl);
3355 break;
3357 case aSignSym: /* sign and conventionally encrypt the given file */
3358 if (argc > 1)
3359 wrong_args(_("--sign --symmetric [filename]"));
3360 rc = sign_symencrypt_file (fname, locusr);
3361 if (rc)
3362 log_error("%s: sign+symmetric failed: %s\n",
3363 print_fname_stdin(fname), g10_errstr(rc) );
3364 break;
3366 case aClearsign: /* make a clearsig */
3367 if( argc > 1 )
3368 wrong_args(_("--clearsign [filename]"));
3369 if( (rc = clearsign_file(fname, locusr, NULL)) )
3370 log_error("%s: clearsign failed: %s\n",
3371 print_fname_stdin(fname), g10_errstr(rc) );
3372 break;
3374 case aVerify:
3375 if(multifile)
3377 if( (rc = verify_files( argc, argv ) ))
3378 log_error("verify files failed: %s\n", g10_errstr(rc) );
3380 else
3382 if( (rc = verify_signatures( argc, argv ) ))
3383 log_error("verify signatures failed: %s\n", g10_errstr(rc) );
3385 break;
3387 case aDecrypt:
3388 if(multifile)
3389 decrypt_messages(argc, argv);
3390 else
3392 if( argc > 1 )
3393 wrong_args(_("--decrypt [filename]"));
3394 if( (rc = decrypt_message( fname ) ))
3395 log_error("decrypt_message failed: %s\n", g10_errstr(rc) );
3397 break;
3399 case aSignKey:
3400 if( argc != 1 )
3401 wrong_args(_("--sign-key user-id"));
3402 /* fall through */
3403 case aLSignKey:
3404 if( argc != 1 )
3405 wrong_args(_("--lsign-key user-id"));
3406 /* fall through */
3408 sl=NULL;
3410 if(cmd==aSignKey)
3411 append_to_strlist(&sl,"sign");
3412 else if(cmd==aLSignKey)
3413 append_to_strlist(&sl,"lsign");
3414 else
3415 BUG();
3417 append_to_strlist( &sl, "save" );
3418 username = make_username( fname );
3419 keyedit_menu(fname, locusr, sl, 0, 0 );
3420 xfree(username);
3421 free_strlist(sl);
3422 break;
3424 case aEditKey: /* Edit a key signature */
3425 if( !argc )
3426 wrong_args(_("--edit-key user-id [commands]"));
3427 username = make_username( fname );
3428 if( argc > 1 ) {
3429 sl = NULL;
3430 for( argc--, argv++ ; argc; argc--, argv++ )
3431 append_to_strlist( &sl, *argv );
3432 keyedit_menu( username, locusr, sl, 0, 1 );
3433 free_strlist(sl);
3435 else
3436 keyedit_menu(username, locusr, NULL, 0, 1 );
3437 xfree(username);
3438 break;
3440 case aDeleteKeys:
3441 case aDeleteSecretKeys:
3442 case aDeleteSecretAndPublicKeys:
3443 sl = NULL;
3444 /* I'm adding these in reverse order as add_to_strlist2
3445 reverses them again, and it's easier to understand in the
3446 proper order :) */
3447 for( ; argc; argc-- )
3448 add_to_strlist2( &sl, argv[argc-1], utf8_strings );
3449 delete_keys(sl,cmd==aDeleteSecretKeys,cmd==aDeleteSecretAndPublicKeys);
3450 free_strlist(sl);
3451 break;
3453 case aCheckKeys:
3454 opt.check_sigs = 1;
3455 case aListSigs:
3456 opt.list_sigs = 1;
3457 case aListKeys:
3458 sl = NULL;
3459 for( ; argc; argc--, argv++ )
3460 add_to_strlist2( &sl, *argv, utf8_strings );
3461 public_key_list( sl );
3462 free_strlist(sl);
3463 break;
3464 case aListSecretKeys:
3465 sl = NULL;
3466 for( ; argc; argc--, argv++ )
3467 add_to_strlist2( &sl, *argv, utf8_strings );
3468 secret_key_list( sl );
3469 free_strlist(sl);
3470 break;
3472 case aKMode: /* list keyring -- NOTE: This will be removed soon */
3473 if( argc < 2 ) { /* -kv [userid] */
3474 sl = NULL;
3475 if (argc && **argv)
3476 add_to_strlist2( &sl, *argv, utf8_strings );
3477 public_key_list( sl );
3478 free_strlist(sl);
3480 else if( argc == 2 ) { /* -kv userid keyring */
3481 if( access( argv[1], R_OK ) ) {
3482 log_error(_("can't open `%s': %s\n"),
3483 print_fname_stdin(argv[1]), strerror(errno));
3485 else {
3486 /* add keyring (default keyrings are not registered in this
3487 * special case */
3488 keydb_add_resource( argv[1], 0, 0 );
3489 sl = NULL;
3490 if (**argv)
3491 add_to_strlist2( &sl, *argv, utf8_strings );
3492 public_key_list( sl );
3493 free_strlist(sl);
3496 else
3497 wrong_args(_("-k[v][v][v][c] [user-id] [keyring]") );
3498 break;
3500 case aKeygen: /* generate a key */
3501 if( opt.batch ) {
3502 if( argc > 1 )
3503 wrong_args("--gen-key [parameterfile]");
3504 generate_keypair( argc? *argv : NULL, NULL, NULL );
3506 else {
3507 if( argc )
3508 wrong_args("--gen-key");
3509 generate_keypair(NULL, NULL, NULL);
3511 break;
3513 case aFastImport:
3514 opt.import_options |= IMPORT_FAST;
3515 case aImport:
3516 import_keys( argc? argv:NULL, argc, NULL, opt.import_options );
3517 break;
3519 /* TODO: There are a number of command that use this same
3520 "make strlist, call function, report error, free strlist"
3521 pattern. Join them together here and avoid all that
3522 duplicated code. */
3524 case aExport:
3525 case aSendKeys:
3526 case aRecvKeys:
3527 sl = NULL;
3528 for( ; argc; argc--, argv++ )
3529 append_to_strlist2( &sl, *argv, utf8_strings );
3530 if( cmd == aSendKeys )
3531 rc=keyserver_export( sl );
3532 else if( cmd == aRecvKeys )
3533 rc=keyserver_import( sl );
3534 else
3535 rc=export_pubkeys( sl, opt.export_options );
3536 if(rc)
3538 if(cmd==aSendKeys)
3539 log_error(_("keyserver send failed: %s\n"),g10_errstr(rc));
3540 else if(cmd==aRecvKeys)
3541 log_error(_("keyserver receive failed: %s\n"),g10_errstr(rc));
3542 else
3543 log_error(_("key export failed: %s\n"),g10_errstr(rc));
3545 free_strlist(sl);
3546 break;
3548 case aSearchKeys:
3549 sl = NULL;
3550 for( ; argc; argc--, argv++ )
3551 append_to_strlist2( &sl, *argv, utf8_strings );
3552 rc=keyserver_search( sl );
3553 if(rc)
3554 log_error(_("keyserver search failed: %s\n"),g10_errstr(rc));
3555 free_strlist(sl);
3556 break;
3558 case aRefreshKeys:
3559 sl = NULL;
3560 for( ; argc; argc--, argv++ )
3561 append_to_strlist2( &sl, *argv, utf8_strings );
3562 rc=keyserver_refresh(sl);
3563 if(rc)
3564 log_error(_("keyserver refresh failed: %s\n"),g10_errstr(rc));
3565 free_strlist(sl);
3566 break;
3568 case aFetchKeys:
3569 sl = NULL;
3570 for( ; argc; argc--, argv++ )
3571 append_to_strlist2( &sl, *argv, utf8_strings );
3572 rc=keyserver_fetch(sl);
3573 if(rc)
3574 log_error("key fetch failed: %s\n",g10_errstr(rc));
3575 free_strlist(sl);
3576 break;
3578 case aExportSecret:
3579 sl = NULL;
3580 for( ; argc; argc--, argv++ )
3581 add_to_strlist2( &sl, *argv, utf8_strings );
3582 export_seckeys( sl );
3583 free_strlist(sl);
3584 break;
3586 case aExportSecretSub:
3587 sl = NULL;
3588 for( ; argc; argc--, argv++ )
3589 add_to_strlist2( &sl, *argv, utf8_strings );
3590 export_secsubkeys( sl );
3591 free_strlist(sl);
3592 break;
3594 case aGenRevoke:
3595 if( argc != 1 )
3596 wrong_args("--gen-revoke user-id");
3597 username = make_username(*argv);
3598 gen_revoke( username );
3599 xfree( username );
3600 break;
3602 case aDesigRevoke:
3603 if( argc != 1 )
3604 wrong_args("--desig-revoke user-id");
3605 username = make_username(*argv);
3606 gen_desig_revoke( username, locusr );
3607 xfree( username );
3608 break;
3610 case aDeArmor:
3611 if( argc > 1 )
3612 wrong_args("--dearmor [file]");
3613 rc = dearmor_file( argc? *argv: NULL );
3614 if( rc )
3615 log_error(_("dearmoring failed: %s\n"), g10_errstr(rc));
3616 break;
3618 case aEnArmor:
3619 if( argc > 1 )
3620 wrong_args("--enarmor [file]");
3621 rc = enarmor_file( argc? *argv: NULL );
3622 if( rc )
3623 log_error(_("enarmoring failed: %s\n"), g10_errstr(rc));
3624 break;
3627 case aPrimegen:
3628 #if 0 /*FIXME*/
3629 { int mode = argc < 2 ? 0 : atoi(*argv);
3631 if( mode == 1 && argc == 2 ) {
3632 mpi_print( stdout, generate_public_prime( atoi(argv[1]) ), 1);
3634 else if( mode == 2 && argc == 3 ) {
3635 mpi_print( stdout, generate_elg_prime(
3636 0, atoi(argv[1]),
3637 atoi(argv[2]), NULL,NULL ), 1);
3639 else if( mode == 3 && argc == 3 ) {
3640 MPI *factors;
3641 mpi_print( stdout, generate_elg_prime(
3642 1, atoi(argv[1]),
3643 atoi(argv[2]), NULL,&factors ), 1);
3644 putchar('\n');
3645 mpi_print( stdout, factors[0], 1 ); /* print q */
3647 else if( mode == 4 && argc == 3 ) {
3648 MPI g = mpi_alloc(1);
3649 mpi_print( stdout, generate_elg_prime(
3650 0, atoi(argv[1]),
3651 atoi(argv[2]), g, NULL ), 1);
3652 putchar('\n');
3653 mpi_print( stdout, g, 1 );
3654 mpi_free(g);
3656 else
3657 wrong_args("--gen-prime mode bits [qbits] ");
3658 putchar('\n');
3660 #endif
3661 wrong_args("--gen-prime not yet supported ");
3662 break;
3664 case aGenRandom:
3666 int level = argc ? atoi(*argv):0;
3667 int count = argc > 1 ? atoi(argv[1]): 0;
3668 int endless = !count;
3670 if( argc < 1 || argc > 2 || level < 0 || level > 2 || count < 0 )
3671 wrong_args("--gen-random 0|1|2 [count]");
3673 while( endless || count ) {
3674 byte *p;
3675 /* Wee need a multiple of 3, so that in case of
3676 armored output we get a correct string. No
3677 linefolding is done, as it is best to levae this to
3678 other tools */
3679 size_t n = !endless && count < 99? count : 99;
3681 p = gcry_random_bytes (n, level);
3682 #ifdef HAVE_DOSISH_SYSTEM
3683 setmode ( fileno(stdout), O_BINARY );
3684 #endif
3685 if (opt.armor) {
3686 char *tmp = make_radix64_string (p, n);
3687 fputs (tmp, stdout);
3688 xfree (tmp);
3689 if (n%3 == 1)
3690 putchar ('=');
3691 if (n%3)
3692 putchar ('=');
3693 } else {
3694 fwrite( p, n, 1, stdout );
3696 xfree(p);
3697 if( !endless )
3698 count -= n;
3700 if (opt.armor)
3701 putchar ('\n');
3703 break;
3705 case aPrintMD:
3706 if( argc < 1)
3707 wrong_args("--print-md algo [files]");
3709 int all_algos = (**argv=='*' && !(*argv)[1]);
3710 int algo = all_algos? 0 : gcry_md_map_name (*argv);
3712 if( !algo && !all_algos )
3713 log_error(_("invalid hash algorithm `%s'\n"), *argv );
3714 else {
3715 argc--; argv++;
3716 if( !argc )
3717 print_mds(NULL, algo);
3718 else {
3719 for(; argc; argc--, argv++ )
3720 print_mds(*argv, algo);
3724 break;
3726 case aPrintMDs: /* old option */
3727 if( !argc )
3728 print_mds(NULL,0);
3729 else {
3730 for(; argc; argc--, argv++ )
3731 print_mds(*argv,0);
3733 break;
3735 case aListTrustDB:
3736 if( !argc )
3737 list_trustdb(NULL);
3738 else {
3739 for( ; argc; argc--, argv++ )
3740 list_trustdb( *argv );
3742 break;
3744 case aUpdateTrustDB:
3745 if( argc )
3746 wrong_args("--update-trustdb");
3747 update_trustdb();
3748 break;
3750 case aCheckTrustDB:
3751 /* Old versions allowed for arguments - ignore them */
3752 check_trustdb();
3753 break;
3755 case aFixTrustDB:
3756 log_error("this command is not yet implemented.\n");
3757 log_error("A workaround is to use \"--export-ownertrust\", remove\n");
3758 log_error("the trustdb file and do an \"--import-ownertrust\".\n" );
3759 break;
3761 case aListTrustPath:
3762 if( !argc )
3763 wrong_args("--list-trust-path <user-ids>");
3764 for( ; argc; argc--, argv++ ) {
3765 username = make_username( *argv );
3766 list_trust_path( username );
3767 xfree(username);
3769 break;
3771 case aExportOwnerTrust:
3772 if( argc )
3773 wrong_args("--export-ownertrust");
3774 export_ownertrust();
3775 break;
3777 case aImportOwnerTrust:
3778 if( argc > 1 )
3779 wrong_args("--import-ownertrust [file]");
3780 import_ownertrust( argc? *argv:NULL );
3781 break;
3783 case aRebuildKeydbCaches:
3784 if (argc)
3785 wrong_args ("--rebuild-keydb-caches");
3786 keydb_rebuild_caches (1);
3787 break;
3789 #ifdef ENABLE_CARD_SUPPORT
3790 case aCardStatus:
3791 if (argc)
3792 wrong_args ("--card-status");
3793 card_status (stdout, NULL, 0);
3794 break;
3796 case aCardEdit:
3797 if (argc) {
3798 sl = NULL;
3799 for (argc--, argv++ ; argc; argc--, argv++)
3800 append_to_strlist (&sl, *argv);
3801 card_edit (sl);
3802 free_strlist (sl);
3804 else
3805 card_edit (NULL);
3806 break;
3808 case aChangePIN:
3809 if (!argc)
3810 change_pin (0,1);
3811 else if (argc == 1)
3812 change_pin (atoi (*argv),1);
3813 else
3814 wrong_args ("--change-pin [no]");
3815 break;
3816 #endif /* ENABLE_CARD_SUPPORT*/
3818 case aListConfig:
3820 char *str=collapse_args(argc,argv);
3821 list_config(str);
3822 xfree(str);
3824 break;
3826 case aListPackets:
3827 opt.list_packets=2;
3828 default:
3829 if( argc > 1 )
3830 wrong_args(_("[filename]"));
3831 /* Issue some output for the unix newbie */
3832 if( !fname && !opt.outfile && isatty( fileno(stdin) )
3833 && isatty( fileno(stdout) ) && isatty( fileno(stderr) ) )
3834 log_info(_("Go ahead and type your message ...\n"));
3836 a = iobuf_open(fname);
3837 if (a && is_secured_file (iobuf_get_fd (a)))
3839 iobuf_close (a);
3840 a = NULL;
3841 errno = EPERM;
3843 if( !a )
3844 log_error(_("can't open `%s'\n"), print_fname_stdin(fname));
3845 else {
3847 if( !opt.no_armor ) {
3848 if( use_armor_filter( a ) ) {
3849 memset( &afx, 0, sizeof afx);
3850 iobuf_push_filter( a, armor_filter, &afx );
3853 if( cmd == aListPackets ) {
3854 set_packet_list_mode(1);
3855 opt.list_packets=1;
3857 rc = proc_packets(NULL, a );
3858 if( rc )
3859 log_error("processing message failed: %s\n", g10_errstr(rc) );
3860 iobuf_close(a);
3862 break;
3865 /* cleanup */
3866 FREE_STRLIST(remusr);
3867 FREE_STRLIST(locusr);
3868 g10_exit(0);
3869 return 8; /*NEVER REACHED*/
3873 /* Note: This function is used by signal handlers!. */
3874 static void
3875 emergency_cleanup (void)
3877 gcry_control (GCRYCTL_TERM_SECMEM );
3881 void
3882 g10_exit( int rc )
3884 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
3885 if ( (opt.debug & DBG_MEMSTAT_VALUE) )
3887 gcry_control (GCRYCTL_DUMP_MEMORY_STATS);
3888 gcry_control (GCRYCTL_DUMP_RANDOM_STATS);
3890 if (opt.debug)
3891 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
3893 emergency_cleanup ();
3895 rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0;
3896 exit (rc);
3900 /* Pretty-print hex hashes. This assumes at least an 80-character
3901 display, but there are a few other similar assumptions in the
3902 display code. */
3903 static void
3904 print_hex( gcry_md_hd_t md, int algo, const char *fname )
3906 int i,n,count,indent=0;
3907 const byte *p;
3909 if(fname)
3910 indent=printf("%s: ",fname);
3912 if(indent>40)
3914 printf("\n");
3915 indent=0;
3918 if(algo==DIGEST_ALGO_RMD160)
3919 indent+=printf("RMD160 = ");
3920 else if(algo>0)
3921 indent+=printf("%6s = ", gcry_md_algo_name (algo));
3922 else
3923 algo=abs(algo);
3925 count=indent;
3927 p = gcry_md_read (md, algo);
3928 n = gcry_md_get_algo_dlen (algo);
3930 count += printf ("%02X",*p++);
3932 for(i=1;i<n;i++,p++)
3934 if(n==16)
3936 if(count+2>79)
3938 printf("\n%*s",indent," ");
3939 count=indent;
3941 else
3942 count+=printf(" ");
3944 if(!(i%8))
3945 count+=printf(" ");
3947 else if (n==20)
3949 if(!(i%2))
3951 if(count+4>79)
3953 printf("\n%*s",indent," ");
3954 count=indent;
3956 else
3957 count+=printf(" ");
3960 if(!(i%10))
3961 count+=printf(" ");
3963 else
3965 if(!(i%4))
3967 if(count+8>79)
3969 printf("\n%*s",indent," ");
3970 count=indent;
3972 else
3973 count+=printf(" ");
3977 count+=printf("%02X",*p);
3980 printf("\n");
3983 static void
3984 print_hashline( gcry_md_hd_t md, int algo, const char *fname )
3986 int i, n;
3987 const byte *p;
3989 if ( fname ) {
3990 for (p = fname; *p; p++ ) {
3991 if ( *p <= 32 || *p > 127 || *p == ':' || *p == '%' )
3992 printf("%%%02X", *p );
3993 else
3994 putchar( *p );
3997 putchar(':');
3998 printf("%d:", algo );
3999 p = gcry_md_read (md, algo);
4000 n = gcry_md_get_algo_dlen (algo);
4001 for(i=0; i < n ; i++, p++ )
4002 printf("%02X", *p );
4003 putchar(':');
4004 putchar('\n');
4007 static void
4008 print_mds( const char *fname, int algo )
4010 FILE *fp;
4011 char buf[1024];
4012 size_t n;
4013 gcry_md_hd_t md;
4015 if( !fname ) {
4016 fp = stdin;
4017 #ifdef HAVE_DOSISH_SYSTEM
4018 setmode ( fileno(fp) , O_BINARY );
4019 #endif
4021 else {
4022 fp = fopen( fname, "rb" );
4023 if (fp && is_secured_file (fileno (fp)))
4025 fclose (fp);
4026 fp = NULL;
4027 errno = EPERM;
4030 if( !fp ) {
4031 log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
4032 return;
4035 gcry_md_open (&md, 0, 0);
4036 if( algo )
4037 gcry_md_enable (md, algo);
4038 else {
4039 gcry_md_enable (md, GCRY_MD_MD5);
4040 gcry_md_enable (md, GCRY_MD_SHA1);
4041 gcry_md_enable (md, GCRY_MD_RMD160);
4042 if (!openpgp_md_test_algo (DIGEST_ALGO_SHA224))
4043 gcry_md_enable (md, DIGEST_ALGO_SHA224);
4044 if (!openpgp_md_test_algo (GCRY_MD_SHA256))
4045 gcry_md_enable (md, GCRY_MD_SHA256);
4046 if (!openpgp_md_test_algo (GCRY_MD_SHA384))
4047 gcry_md_enable (md, GCRY_MD_SHA384);
4048 if (!openpgp_md_test_algo (GCRY_MD_SHA512))
4049 gcry_md_enable (md, GCRY_MD_SHA512);
4052 while( (n=fread( buf, 1, DIM(buf), fp )) )
4053 gcry_md_write (md, buf, n);
4054 if( ferror(fp) )
4055 log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
4056 else {
4057 gcry_md_final (md);
4058 if ( opt.with_colons ) {
4059 if ( algo )
4060 print_hashline( md, algo, fname );
4061 else {
4062 print_hashline( md, GCRY_MD_MD5, fname );
4063 print_hashline( md, GCRY_MD_SHA1, fname );
4064 print_hashline( md, GCRY_MD_RMD160, fname );
4065 if (!gcry_md_test_algo (DIGEST_ALGO_SHA224))
4066 print_hashline (md, DIGEST_ALGO_SHA224, fname);
4067 if (!gcry_md_test_algo (GCRY_MD_SHA256))
4068 print_hashline( md, GCRY_MD_SHA256, fname );
4069 if (!gcry_md_test_algo (GCRY_MD_SHA384))
4070 print_hashline ( md, GCRY_MD_SHA384, fname );
4071 if (!gcry_md_test_algo (GCRY_MD_SHA512))
4072 print_hashline ( md, GCRY_MD_SHA512, fname );
4075 else {
4076 if( algo )
4077 print_hex(md,-algo,fname);
4078 else {
4079 print_hex( md, GCRY_MD_MD5, fname );
4080 print_hex( md, GCRY_MD_SHA1, fname );
4081 print_hex( md, GCRY_MD_RMD160, fname );
4082 if (!gcry_md_test_algo (DIGEST_ALGO_SHA224))
4083 print_hex (md, DIGEST_ALGO_SHA224, fname);
4084 if (!gcry_md_test_algo (GCRY_MD_SHA256))
4085 print_hex( md, GCRY_MD_SHA256, fname );
4086 if (!gcry_md_test_algo (GCRY_MD_SHA384))
4087 print_hex( md, GCRY_MD_SHA384, fname );
4088 if (!gcry_md_test_algo (GCRY_MD_SHA512))
4089 print_hex( md, GCRY_MD_SHA512, fname );
4093 gcry_md_close(md);
4095 if( fp != stdin )
4096 fclose(fp);
4100 /****************
4101 * Check the supplied name,value string and add it to the notation
4102 * data to be used for signatures. which==0 for sig notations, and 1
4103 * for cert notations.
4105 static void
4106 add_notation_data( const char *string, int which )
4108 struct notation *notation;
4110 notation=string_to_notation(string,utf8_strings);
4111 if(notation)
4113 if(which)
4115 notation->next=opt.cert_notations;
4116 opt.cert_notations=notation;
4118 else
4120 notation->next=opt.sig_notations;
4121 opt.sig_notations=notation;
4126 static void
4127 add_policy_url( const char *string, int which )
4129 unsigned int i,critical=0;
4130 STRLIST sl;
4132 if(*string=='!')
4134 string++;
4135 critical=1;
4138 for(i=0;i<strlen(string);i++)
4139 if( !isascii (string[i]) || iscntrl(string[i]))
4140 break;
4142 if(i==0 || i<strlen(string))
4144 if(which)
4145 log_error(_("the given certification policy URL is invalid\n"));
4146 else
4147 log_error(_("the given signature policy URL is invalid\n"));
4150 if(which)
4151 sl=add_to_strlist( &opt.cert_policy_url, string );
4152 else
4153 sl=add_to_strlist( &opt.sig_policy_url, string );
4155 if(critical)
4156 sl->flags |= 1;
4159 static void
4160 add_keyserver_url( const char *string, int which )
4162 unsigned int i,critical=0;
4163 STRLIST sl;
4165 if(*string=='!')
4167 string++;
4168 critical=1;
4171 for(i=0;i<strlen(string);i++)
4172 if( !isascii (string[i]) || iscntrl(string[i]))
4173 break;
4175 if(i==0 || i<strlen(string))
4177 if(which)
4178 BUG();
4179 else
4180 log_error(_("the given preferred keyserver URL is invalid\n"));
4183 if(which)
4184 BUG();
4185 else
4186 sl=add_to_strlist( &opt.sig_keyserver_url, string );
4188 if(critical)
4189 sl->flags |= 1;