1 /* gpg.c - The GnuPG utility (main for gpg)
2 * Copyright (C) 1998-2011 Free Software Foundation, Inc.
3 * Copyright (C) 1997-2016 Werner Koch
4 * Copyright (C) 2015-2016 g10 Code GmbH
6 * This file is part of GnuPG.
8 * GnuPG is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * GnuPG is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <https://www.gnu.org/licenses/>.
30 #include <sys/stat.h> /* for stat() */
33 #ifdef HAVE_W32_SYSTEM
34 # ifdef HAVE_WINSOCK2_H
35 # include <winsock2.h>
40 #define INCLUDED_BY_MAIN_MODULE 1
43 #include "../common/iobuf.h"
56 #include "keyserver-internal.h"
58 #include "gc-opt-flags.h"
60 #include "call-dirmngr.h"
62 #include "../common/init.h"
63 #include "../common/mbox-util.h"
64 #include "../common/shareddefs.h"
66 #if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
67 #define MY_O_BINARY O_BINARY
77 enum cmd_and_opt_values
86 oHiddenRecipientFile = 'F',
93 oHiddenRecipient = 'R',
100 aListSecretKeys = 'K',
135 aDeleteSecretAndPublicKeys,
192 oWithSubkeyFingerprint,
246 oBZ2DecompressLowmem,
271 oSkipHiddenRecipients,
272 oNoSkipHiddenRecipients,
285 oUseEmbeddedFilename,
286 oNoUseEmbeddedFilename,
323 oEncryptToDefaultKey,
330 oAllowNonSelfsignedUID,
331 oNoAllowNonSelfsignedUID,
334 oAllowSecretKeyImport,
335 oEnableSpecialFilenames,
347 oOverrideSessionKeyFD,
357 oNoExpensiveTrustChecks,
363 oPreservePermissions,
364 oDefaultPreferenceList,
365 oDefaultKeyserverURL,
366 oPersonalCipherPreferences,
367 oPersonalDigestPreferences,
368 oPersonalCompressPreferences,
383 oNoMangleDosFilenames,
384 oEnableProgressFilter,
387 oExitOnStatusWriteError,
388 oLimitCardInsertTries,
397 oAllowMultisigVerification,
402 oAllowMultipleMessages,
403 oNoAllowMultipleMessages,
404 oAllowWeakDigestAlgos,
422 static ARGPARSE_OPTS opts[] = {
424 ARGPARSE_group (300, N_("@Commands:\n ")),
426 ARGPARSE_c (aSign, "sign", N_("make a signature")),
427 ARGPARSE_c (aClearsign, "clear-sign", N_("make a clear text signature")),
428 ARGPARSE_c (aClearsign, "clearsign", "@"),
429 ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")),
430 ARGPARSE_c (aEncr, "encrypt", N_("encrypt data")),
431 ARGPARSE_c (aEncrFiles, "encrypt-files", "@"),
432 ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")),
433 ARGPARSE_c (aStore, "store", "@"),
434 ARGPARSE_c (aDecrypt, "decrypt", N_("decrypt data (default)")),
435 ARGPARSE_c (aDecryptFiles, "decrypt-files", "@"),
436 ARGPARSE_c (aVerify, "verify" , N_("verify a signature")),
437 ARGPARSE_c (aVerifyFiles, "verify-files" , "@" ),
438 ARGPARSE_c (aListKeys, "list-keys", N_("list keys")),
439 ARGPARSE_c (aListKeys, "list-public-keys", "@" ),
440 ARGPARSE_c (aListSigs, "list-signatures", N_("list keys and signatures")),
441 ARGPARSE_c (aListSigs, "list-sigs", "@"),
442 ARGPARSE_c (aCheckKeys, "check-signatures",
443 N_("list and check key signatures")),
444 ARGPARSE_c (aCheckKeys, "check-sigs", "@"),
445 ARGPARSE_c (oFingerprint, "fingerprint", N_("list keys and fingerprints")),
446 ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")),
447 ARGPARSE_c (aKeygen, "generate-key",
448 N_("generate a new key pair")),
449 ARGPARSE_c (aKeygen, "gen-key", "@"),
450 ARGPARSE_c (aQuickKeygen, "quick-generate-key" ,
451 N_("quickly generate a new key pair")),
452 ARGPARSE_c (aQuickKeygen, "quick-gen-key", "@"),
453 ARGPARSE_c (aQuickAddUid, "quick-add-uid",
454 N_("quickly add a new user-id")),
455 ARGPARSE_c (aQuickAddUid, "quick-adduid", "@"),
456 ARGPARSE_c (aQuickAddKey, "quick-add-key", "@"),
457 ARGPARSE_c (aQuickAddKey, "quick-addkey", "@"),
458 ARGPARSE_c (aQuickRevUid, "quick-revoke-uid",
459 N_("quickly revoke a user-id")),
460 ARGPARSE_c (aQuickRevUid, "quick-revuid", "@"),
461 ARGPARSE_c (aQuickSetExpire, "quick-set-expire",
462 N_("quickly set a new expiration date")),
463 ARGPARSE_c (aFullKeygen, "full-generate-key" ,
464 N_("full featured key pair generation")),
465 ARGPARSE_c (aFullKeygen, "full-gen-key", "@"),
466 ARGPARSE_c (aGenRevoke, "generate-revocation",
467 N_("generate a revocation certificate")),
468 ARGPARSE_c (aGenRevoke, "gen-revoke", "@"),
469 ARGPARSE_c (aDeleteKeys,"delete-keys",
470 N_("remove keys from the public keyring")),
471 ARGPARSE_c (aDeleteSecretKeys, "delete-secret-keys",
472 N_("remove keys from the secret keyring")),
473 ARGPARSE_c (aQuickSignKey, "quick-sign-key" ,
474 N_("quickly sign a key")),
475 ARGPARSE_c (aQuickLSignKey, "quick-lsign-key",
476 N_("quickly sign a key locally")),
477 ARGPARSE_c (aSignKey, "sign-key" ,N_("sign a key")),
478 ARGPARSE_c (aLSignKey, "lsign-key" ,N_("sign a key locally")),
479 ARGPARSE_c (aEditKey, "edit-key" ,N_("sign or edit a key")),
480 ARGPARSE_c (aEditKey, "key-edit" ,"@"),
481 ARGPARSE_c (aPasswd, "change-passphrase", N_("change a passphrase")),
482 ARGPARSE_c (aPasswd, "passwd", "@"),
483 ARGPARSE_c (aDesigRevoke, "generate-designated-revocation", "@"),
484 ARGPARSE_c (aDesigRevoke, "desig-revoke","@" ),
485 ARGPARSE_c (aExport, "export" , N_("export keys") ),
486 ARGPARSE_c (aSendKeys, "send-keys" , N_("export keys to a keyserver") ),
487 ARGPARSE_c (aRecvKeys, "receive-keys" , N_("import keys from a keyserver") ),
488 ARGPARSE_c (aRecvKeys, "recv-keys" , "@"),
489 ARGPARSE_c (aSearchKeys, "search-keys" ,
490 N_("search for keys on a keyserver") ),
491 ARGPARSE_c (aRefreshKeys, "refresh-keys",
492 N_("update all keys from a keyserver")),
493 ARGPARSE_c (aLocateKeys, "locate-keys", "@"),
494 ARGPARSE_c (aFetchKeys, "fetch-keys" , "@" ),
495 ARGPARSE_c (aExportSecret, "export-secret-keys" , "@" ),
496 ARGPARSE_c (aExportSecretSub, "export-secret-subkeys" , "@" ),
497 ARGPARSE_c (aExportSshKey, "export-ssh-key", "@" ),
498 ARGPARSE_c (aImport, "import", N_("import/merge keys")),
499 ARGPARSE_c (aFastImport, "fast-import", "@"),
500 #ifdef ENABLE_CARD_SUPPORT
501 ARGPARSE_c (aCardStatus, "card-status", N_("print the card status")),
502 ARGPARSE_c (aCardEdit, "edit-card", N_("change data on a card")),
503 ARGPARSE_c (aCardEdit, "card-edit", "@"),
504 ARGPARSE_c (aChangePIN, "change-pin", N_("change a card's PIN")),
506 ARGPARSE_c (aListConfig, "list-config", "@"),
507 ARGPARSE_c (aListGcryptConfig, "list-gcrypt-config", "@"),
508 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@" ),
509 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@" ),
510 ARGPARSE_c (aListPackets, "list-packets","@"),
512 #ifndef NO_TRUST_MODELS
513 ARGPARSE_c (aExportOwnerTrust, "export-ownertrust", "@"),
514 ARGPARSE_c (aImportOwnerTrust, "import-ownertrust", "@"),
515 ARGPARSE_c (aUpdateTrustDB,"update-trustdb",
516 N_("update the trust database")),
517 ARGPARSE_c (aCheckTrustDB, "check-trustdb", "@"),
518 ARGPARSE_c (aFixTrustDB, "fix-trustdb", "@"),
521 ARGPARSE_c (aDeArmor, "dearmor", "@"),
522 ARGPARSE_c (aDeArmor, "dearmour", "@"),
523 ARGPARSE_c (aEnArmor, "enarmor", "@"),
524 ARGPARSE_c (aEnArmor, "enarmour", "@"),
525 ARGPARSE_c (aPrintMD, "print-md", N_("print message digests")),
526 ARGPARSE_c (aPrimegen, "gen-prime", "@" ),
527 ARGPARSE_c (aGenRandom,"gen-random", "@" ),
528 ARGPARSE_c (aServer, "server", N_("run in server mode")),
529 ARGPARSE_c (aTOFUPolicy, "tofu-policy",
530 N_("|VALUE|set the TOFU policy for a key")),
532 ARGPARSE_group (301, N_("@\nOptions:\n ")),
534 ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")),
535 ARGPARSE_s_n (oArmor, "armour", "@"),
537 ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")),
538 ARGPARSE_s_s (oHiddenRecipient, "hidden-recipient", "@"),
539 ARGPARSE_s_s (oRecipientFile, "recipient-file", "@"),
540 ARGPARSE_s_s (oHiddenRecipientFile, "hidden-recipient-file", "@"),
541 ARGPARSE_s_s (oRecipient, "remote-user", "@"), /* (old option name) */
542 ARGPARSE_s_s (oDefRecipient, "default-recipient", "@"),
543 ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", "@"),
544 ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"),
546 ARGPARSE_s_s (oTempDir, "temp-directory", "@"),
547 ARGPARSE_s_s (oExecPath, "exec-path", "@"),
548 ARGPARSE_s_s (oEncryptTo, "encrypt-to", "@"),
549 ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"),
550 ARGPARSE_s_s (oHiddenEncryptTo, "hidden-encrypt-to", "@"),
551 ARGPARSE_s_n (oEncryptToDefaultKey, "encrypt-to-default-key", "@"),
552 ARGPARSE_s_s (oLocalUser, "local-user",
553 N_("|USER-ID|use USER-ID to sign or decrypt")),
554 ARGPARSE_s_s (oSender, "sender", "@"),
556 ARGPARSE_s_s (oTrySecretKey, "try-secret-key", "@"),
558 ARGPARSE_s_i (oCompress, NULL,
559 N_("|N|set compress level to N (0 disables)")),
560 ARGPARSE_s_i (oCompressLevel, "compress-level", "@"),
561 ARGPARSE_s_i (oBZ2CompressLevel, "bzip2-compress-level", "@"),
562 ARGPARSE_s_n (oBZ2DecompressLowmem, "bzip2-decompress-lowmem", "@"),
564 ARGPARSE_s_n (oMimemode, "mimemode", "@"),
565 ARGPARSE_s_n (oTextmodeShort, NULL, "@"),
566 ARGPARSE_s_n (oTextmode, "textmode", N_("use canonical text mode")),
567 ARGPARSE_s_n (oNoTextmode, "no-textmode", "@"),
569 ARGPARSE_s_n (oExpert, "expert", "@"),
570 ARGPARSE_s_n (oNoExpert, "no-expert", "@"),
572 ARGPARSE_s_s (oDefSigExpire, "default-sig-expire", "@"),
573 ARGPARSE_s_n (oAskSigExpire, "ask-sig-expire", "@"),
574 ARGPARSE_s_n (oNoAskSigExpire, "no-ask-sig-expire", "@"),
575 ARGPARSE_s_s (oDefCertExpire, "default-cert-expire", "@"),
576 ARGPARSE_s_n (oAskCertExpire, "ask-cert-expire", "@"),
577 ARGPARSE_s_n (oNoAskCertExpire, "no-ask-cert-expire", "@"),
578 ARGPARSE_s_i (oDefCertLevel, "default-cert-level", "@"),
579 ARGPARSE_s_i (oMinCertLevel, "min-cert-level", "@"),
580 ARGPARSE_s_n (oAskCertLevel, "ask-cert-level", "@"),
581 ARGPARSE_s_n (oNoAskCertLevel, "no-ask-cert-level", "@"),
583 ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")),
584 ARGPARSE_p_u (oMaxOutput, "max-output", "@"),
585 ARGPARSE_s_s (oInputSizeHint, "input-size-hint", "@"),
587 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
588 ARGPARSE_s_n (oQuiet, "quiet", "@"),
589 ARGPARSE_s_n (oNoTTY, "no-tty", "@"),
591 ARGPARSE_s_n (oForceMDC, "force-mdc", "@"),
592 ARGPARSE_s_n (oNoForceMDC, "no-force-mdc", "@"),
593 ARGPARSE_s_n (oDisableMDC, "disable-mdc", "@"),
594 ARGPARSE_s_n (oNoDisableMDC, "no-disable-mdc", "@"),
596 ARGPARSE_s_n (oDisableSignerUID, "disable-signer-uid", "@"),
598 ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")),
599 ARGPARSE_s_n (oInteractive, "interactive", N_("prompt before overwriting")),
601 ARGPARSE_s_n (oBatch, "batch", "@"),
602 ARGPARSE_s_n (oAnswerYes, "yes", "@"),
603 ARGPARSE_s_n (oAnswerNo, "no", "@"),
604 ARGPARSE_s_s (oKeyring, "keyring", "@"),
605 ARGPARSE_s_s (oPrimaryKeyring, "primary-keyring", "@"),
606 ARGPARSE_s_s (oSecretKeyring, "secret-keyring", "@"),
607 ARGPARSE_s_n (oShowKeyring, "show-keyring", "@"),
608 ARGPARSE_s_s (oDefaultKey, "default-key", "@"),
610 ARGPARSE_s_s (oKeyServer, "keyserver", "@"),
611 ARGPARSE_s_s (oKeyServerOptions, "keyserver-options", "@"),
612 ARGPARSE_s_s (oImportOptions, "import-options", "@"),
613 ARGPARSE_s_s (oImportFilter, "import-filter", "@"),
614 ARGPARSE_s_s (oExportOptions, "export-options", "@"),
615 ARGPARSE_s_s (oExportFilter, "export-filter", "@"),
616 ARGPARSE_s_s (oListOptions, "list-options", "@"),
617 ARGPARSE_s_s (oVerifyOptions, "verify-options", "@"),
619 ARGPARSE_s_s (oDisplayCharset, "display-charset", "@"),
620 ARGPARSE_s_s (oDisplayCharset, "charset", "@"),
621 ARGPARSE_s_s (oOptions, "options", "@"),
623 ARGPARSE_s_s (oDebug, "debug", "@"),
624 ARGPARSE_s_s (oDebugLevel, "debug-level", "@"),
625 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
626 ARGPARSE_s_n (oDebugIOLBF, "debug-iolbf", "@"),
627 ARGPARSE_s_i (oStatusFD, "status-fd", "@"),
628 ARGPARSE_s_s (oStatusFile, "status-file", "@"),
629 ARGPARSE_s_i (oAttributeFD, "attribute-fd", "@"),
630 ARGPARSE_s_s (oAttributeFile, "attribute-file", "@"),
632 ARGPARSE_s_i (oCompletesNeeded, "completes-needed", "@"),
633 ARGPARSE_s_i (oMarginalsNeeded, "marginals-needed", "@"),
634 ARGPARSE_s_i (oMaxCertDepth, "max-cert-depth", "@" ),
635 ARGPARSE_s_s (oTrustedKey, "trusted-key", "@"),
637 ARGPARSE_s_s (oLoadExtension, "load-extension", "@"), /* Dummy. */
639 ARGPARSE_s_s (oCompliance, "compliance", "@"),
640 ARGPARSE_s_n (oGnuPG, "gnupg", "@"),
641 ARGPARSE_s_n (oGnuPG, "no-pgp2", "@"),
642 ARGPARSE_s_n (oGnuPG, "no-pgp6", "@"),
643 ARGPARSE_s_n (oGnuPG, "no-pgp7", "@"),
644 ARGPARSE_s_n (oGnuPG, "no-pgp8", "@"),
645 ARGPARSE_s_n (oRFC2440, "rfc2440", "@"),
646 ARGPARSE_s_n (oRFC4880, "rfc4880", "@"),
647 ARGPARSE_s_n (oRFC4880bis, "rfc4880bis", "@"),
648 ARGPARSE_s_n (oOpenPGP, "openpgp", N_("use strict OpenPGP behavior")),
649 ARGPARSE_s_n (oPGP6, "pgp6", "@"),
650 ARGPARSE_s_n (oPGP7, "pgp7", "@"),
651 ARGPARSE_s_n (oPGP8, "pgp8", "@"),
653 ARGPARSE_s_n (oRFC2440Text, "rfc2440-text", "@"),
654 ARGPARSE_s_n (oNoRFC2440Text, "no-rfc2440-text", "@"),
655 ARGPARSE_s_i (oS2KMode, "s2k-mode", "@"),
656 ARGPARSE_s_s (oS2KDigest, "s2k-digest-algo", "@"),
657 ARGPARSE_s_s (oS2KCipher, "s2k-cipher-algo", "@"),
658 ARGPARSE_s_i (oS2KCount, "s2k-count", "@"),
659 ARGPARSE_s_s (oCipherAlgo, "cipher-algo", "@"),
660 ARGPARSE_s_s (oDigestAlgo, "digest-algo", "@"),
661 ARGPARSE_s_s (oCertDigestAlgo, "cert-digest-algo", "@"),
662 ARGPARSE_s_s (oCompressAlgo,"compress-algo", "@"),
663 ARGPARSE_s_s (oCompressAlgo, "compression-algo", "@"), /* Alias */
664 ARGPARSE_s_n (oThrowKeyids, "throw-keyids", "@"),
665 ARGPARSE_s_n (oNoThrowKeyids, "no-throw-keyids", "@"),
666 ARGPARSE_s_n (oShowPhotos, "show-photos", "@"),
667 ARGPARSE_s_n (oNoShowPhotos, "no-show-photos", "@"),
668 ARGPARSE_s_s (oPhotoViewer, "photo-viewer", "@"),
669 ARGPARSE_s_s (oSetNotation, "set-notation", "@"),
670 ARGPARSE_s_s (oSigNotation, "sig-notation", "@"),
671 ARGPARSE_s_s (oCertNotation, "cert-notation", "@"),
673 ARGPARSE_group (302, N_(
674 "@\n(See the man page for a complete listing of all commands and options)\n"
677 ARGPARSE_group (303, N_("@\nExamples:\n\n"
678 " -se -r Bob [file] sign and encrypt for user Bob\n"
679 " --clear-sign [file] make a clear text signature\n"
680 " --detach-sign [file] make a detached signature\n"
681 " --list-keys [names] show keys\n"
682 " --fingerprint [names] show fingerprints\n")),
684 /* More hidden commands and options. */
685 ARGPARSE_c (aPrintMDs, "print-mds", "@"), /* old */
686 #ifndef NO_TRUST_MODELS
687 ARGPARSE_c (aListTrustDB, "list-trustdb", "@"),
691 ARGPARSE_c (aListTrustPath, "list-trust-path", "@"), */
692 ARGPARSE_c (aDeleteSecretAndPublicKeys,
693 "delete-secret-and-public-keys", "@"),
694 ARGPARSE_c (aRebuildKeydbCaches, "rebuild-keydb-caches", "@"),
696 ARGPARSE_s_s (oPassphrase, "passphrase", "@"),
697 ARGPARSE_s_i (oPassphraseFD, "passphrase-fd", "@"),
698 ARGPARSE_s_s (oPassphraseFile, "passphrase-file", "@"),
699 ARGPARSE_s_i (oPassphraseRepeat,"passphrase-repeat", "@"),
700 ARGPARSE_s_s (oPinentryMode, "pinentry-mode", "@"),
701 ARGPARSE_s_i (oCommandFD, "command-fd", "@"),
702 ARGPARSE_s_s (oCommandFile, "command-file", "@"),
703 ARGPARSE_s_n (oQuickRandom, "debug-quick-random", "@"),
704 ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
706 #ifndef NO_TRUST_MODELS
707 ARGPARSE_s_s (oTrustDBName, "trustdb-name", "@"),
708 ARGPARSE_s_n (oAutoCheckTrustDB, "auto-check-trustdb", "@"),
709 ARGPARSE_s_n (oNoAutoCheckTrustDB, "no-auto-check-trustdb", "@"),
710 ARGPARSE_s_s (oForceOwnertrust, "force-ownertrust", "@"),
713 ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"),
714 ARGPARSE_s_n (oRequireSecmem, "require-secmem", "@"),
715 ARGPARSE_s_n (oNoRequireSecmem, "no-require-secmem", "@"),
716 ARGPARSE_s_n (oNoPermissionWarn, "no-permission-warning", "@"),
717 ARGPARSE_s_n (oNoMDCWarn, "no-mdc-warning", "@"),
718 ARGPARSE_s_n (oNoArmor, "no-armor", "@"),
719 ARGPARSE_s_n (oNoArmor, "no-armour", "@"),
720 ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"),
721 ARGPARSE_s_n (oNoKeyring, "no-keyring", "@"),
722 ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
723 ARGPARSE_s_n (oNoOptions, "no-options", "@"),
724 ARGPARSE_s_s (oHomedir, "homedir", "@"),
725 ARGPARSE_s_n (oNoBatch, "no-batch", "@"),
726 ARGPARSE_s_n (oWithColons, "with-colons", "@"),
727 ARGPARSE_s_n (oWithTofuInfo,"with-tofu-info", "@"),
728 ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"),
729 ARGPARSE_s_n (oWithSigList,"with-sig-list", "@"),
730 ARGPARSE_s_n (oWithSigCheck,"with-sig-check", "@"),
731 ARGPARSE_c (aListKeys, "list-key", "@"), /* alias */
732 ARGPARSE_c (aListSigs, "list-sig", "@"), /* alias */
733 ARGPARSE_c (aCheckKeys, "check-sig", "@"), /* alias */
734 ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"),
735 ARGPARSE_s_n (oSkipHiddenRecipients, "skip-hidden-recipients", "@"),
736 ARGPARSE_s_n (oNoSkipHiddenRecipients, "no-skip-hidden-recipients", "@"),
737 ARGPARSE_s_i (oDefCertLevel, "default-cert-check-level", "@"), /* old */
738 #ifndef NO_TRUST_MODELS
739 ARGPARSE_s_n (oAlwaysTrust, "always-trust", "@"),
741 ARGPARSE_s_s (oTrustModel, "trust-model", "@"),
742 ARGPARSE_s_s (oTOFUDefaultPolicy, "tofu-default-policy", "@"),
743 ARGPARSE_s_s (oSetFilename, "set-filename", "@"),
744 ARGPARSE_s_n (oForYourEyesOnly, "for-your-eyes-only", "@"),
745 ARGPARSE_s_n (oNoForYourEyesOnly, "no-for-your-eyes-only", "@"),
746 ARGPARSE_s_s (oSetPolicyURL, "set-policy-url", "@"),
747 ARGPARSE_s_s (oSigPolicyURL, "sig-policy-url", "@"),
748 ARGPARSE_s_s (oCertPolicyURL, "cert-policy-url", "@"),
749 ARGPARSE_s_n (oShowPolicyURL, "show-policy-url", "@"),
750 ARGPARSE_s_n (oNoShowPolicyURL, "no-show-policy-url", "@"),
751 ARGPARSE_s_s (oSigKeyserverURL, "sig-keyserver-url", "@"),
752 ARGPARSE_s_n (oShowNotation, "show-notation", "@"),
753 ARGPARSE_s_n (oNoShowNotation, "no-show-notation", "@"),
754 ARGPARSE_s_s (oComment, "comment", "@"),
755 ARGPARSE_s_n (oDefaultComment, "default-comment", "@"),
756 ARGPARSE_s_n (oNoComments, "no-comments", "@"),
757 ARGPARSE_s_n (oEmitVersion, "emit-version", "@"),
758 ARGPARSE_s_n (oNoEmitVersion, "no-emit-version", "@"),
759 ARGPARSE_s_n (oNoEmitVersion, "no-version", "@"), /* alias */
760 ARGPARSE_s_n (oNotDashEscaped, "not-dash-escaped", "@"),
761 ARGPARSE_s_n (oEscapeFrom, "escape-from-lines", "@"),
762 ARGPARSE_s_n (oNoEscapeFrom, "no-escape-from-lines", "@"),
763 ARGPARSE_s_n (oLockOnce, "lock-once", "@"),
764 ARGPARSE_s_n (oLockMultiple, "lock-multiple", "@"),
765 ARGPARSE_s_n (oLockNever, "lock-never", "@"),
766 ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"),
767 ARGPARSE_s_s (oLoggerFile, "log-file", "@"),
768 ARGPARSE_s_s (oLoggerFile, "logger-file", "@"), /* 1.4 compatibility. */
769 ARGPARSE_s_n (oUseEmbeddedFilename, "use-embedded-filename", "@"),
770 ARGPARSE_s_n (oNoUseEmbeddedFilename, "no-use-embedded-filename", "@"),
771 ARGPARSE_s_n (oUtf8Strings, "utf8-strings", "@"),
772 ARGPARSE_s_n (oNoUtf8Strings, "no-utf8-strings", "@"),
773 ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"),
774 ARGPARSE_s_n (oWithSubkeyFingerprint, "with-subkey-fingerprint", "@"),
775 ARGPARSE_s_n (oWithSubkeyFingerprint, "with-subkey-fingerprints", "@"),
776 ARGPARSE_s_n (oWithICAOSpelling, "with-icao-spelling", "@"),
777 ARGPARSE_s_n (oWithKeygrip, "with-keygrip", "@"),
778 ARGPARSE_s_n (oWithSecret, "with-secret", "@"),
779 ARGPARSE_s_n (oWithWKDHash, "with-wkd-hash", "@"),
780 ARGPARSE_s_s (oDisableCipherAlgo, "disable-cipher-algo", "@"),
781 ARGPARSE_s_s (oDisablePubkeyAlgo, "disable-pubkey-algo", "@"),
782 ARGPARSE_s_n (oAllowNonSelfsignedUID, "allow-non-selfsigned-uid", "@"),
783 ARGPARSE_s_n (oNoAllowNonSelfsignedUID, "no-allow-non-selfsigned-uid", "@"),
784 ARGPARSE_s_n (oAllowFreeformUID, "allow-freeform-uid", "@"),
785 ARGPARSE_s_n (oNoAllowFreeformUID, "no-allow-freeform-uid", "@"),
786 ARGPARSE_s_n (oNoLiteral, "no-literal", "@"),
787 ARGPARSE_p_u (oSetFilesize, "set-filesize", "@"),
788 ARGPARSE_s_n (oFastListMode, "fast-list-mode", "@"),
789 ARGPARSE_s_n (oFixedListMode, "fixed-list-mode", "@"),
790 ARGPARSE_s_n (oLegacyListMode, "legacy-list-mode", "@"),
791 ARGPARSE_s_n (oListOnly, "list-only", "@"),
792 ARGPARSE_s_n (oPrintPKARecords, "print-pka-records", "@"),
793 ARGPARSE_s_n (oPrintDANERecords, "print-dane-records", "@"),
794 ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"),
795 ARGPARSE_s_n (oIgnoreValidFrom, "ignore-valid-from", "@"),
796 ARGPARSE_s_n (oIgnoreCrcError, "ignore-crc-error", "@"),
797 ARGPARSE_s_n (oIgnoreMDCError, "ignore-mdc-error", "@"),
798 ARGPARSE_s_n (oShowSessionKey, "show-session-key", "@"),
799 ARGPARSE_s_s (oOverrideSessionKey, "override-session-key", "@"),
800 ARGPARSE_s_i (oOverrideSessionKeyFD, "override-session-key-fd", "@"),
801 ARGPARSE_s_n (oNoRandomSeedFile, "no-random-seed-file", "@"),
802 ARGPARSE_s_n (oAutoKeyRetrieve, "auto-key-retrieve", "@"),
803 ARGPARSE_s_n (oNoAutoKeyRetrieve, "no-auto-key-retrieve", "@"),
804 ARGPARSE_s_n (oNoSigCache, "no-sig-cache", "@"),
805 ARGPARSE_s_n (oMergeOnly, "merge-only", "@" ),
806 ARGPARSE_s_n (oAllowSecretKeyImport, "allow-secret-key-import", "@"),
807 ARGPARSE_s_n (oTryAllSecrets, "try-all-secrets", "@"),
808 ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"),
809 ARGPARSE_s_n (oNoExpensiveTrustChecks, "no-expensive-trust-checks", "@"),
810 ARGPARSE_s_n (oPreservePermissions, "preserve-permissions", "@"),
811 ARGPARSE_s_s (oDefaultPreferenceList, "default-preference-list", "@"),
812 ARGPARSE_s_s (oDefaultKeyserverURL, "default-keyserver-url", "@"),
813 ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-preferences","@"),
814 ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-preferences","@"),
815 ARGPARSE_s_s (oPersonalCompressPreferences,
816 "personal-compress-preferences", "@"),
817 ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
818 ARGPARSE_s_s (oWeakDigest, "weak-digest","@"),
819 ARGPARSE_s_n (oUnwrap, "unwrap", "@"),
820 ARGPARSE_s_n (oOnlySignTextIDs, "only-sign-text-ids", "@"),
822 /* Aliases. I constantly mistype these, and assume other people do
824 ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-prefs", "@"),
825 ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-prefs", "@"),
826 ARGPARSE_s_s (oPersonalCompressPreferences, "personal-compress-prefs", "@"),
828 ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
829 ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"),
830 ARGPARSE_s_s (oDisplay, "display", "@"),
831 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
832 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
833 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
834 ARGPARSE_s_s (oLCmessages, "lc-messages","@"),
835 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
836 ARGPARSE_s_s (oGroup, "group", "@"),
837 ARGPARSE_s_s (oUnGroup, "ungroup", "@"),
838 ARGPARSE_s_n (oNoGroups, "no-groups", "@"),
839 ARGPARSE_s_n (oStrict, "strict", "@"),
840 ARGPARSE_s_n (oNoStrict, "no-strict", "@"),
841 ARGPARSE_s_n (oMangleDosFilenames, "mangle-dos-filenames", "@"),
842 ARGPARSE_s_n (oNoMangleDosFilenames, "no-mangle-dos-filenames", "@"),
843 ARGPARSE_s_n (oEnableProgressFilter, "enable-progress-filter", "@"),
844 ARGPARSE_s_n (oMultifile, "multifile", "@"),
845 ARGPARSE_s_s (oKeyidFormat, "keyid-format", "@"),
846 ARGPARSE_s_n (oExitOnStatusWriteError, "exit-on-status-write-error", "@"),
847 ARGPARSE_s_i (oLimitCardInsertTries, "limit-card-insert-tries", "@"),
849 ARGPARSE_s_n (oAllowMultisigVerification,
850 "allow-multisig-verification", "@"),
851 ARGPARSE_s_n (oEnableLargeRSA, "enable-large-rsa", "@"),
852 ARGPARSE_s_n (oDisableLargeRSA, "disable-large-rsa", "@"),
853 ARGPARSE_s_n (oEnableDSA2, "enable-dsa2", "@"),
854 ARGPARSE_s_n (oDisableDSA2, "disable-dsa2", "@"),
855 ARGPARSE_s_n (oAllowMultipleMessages, "allow-multiple-messages", "@"),
856 ARGPARSE_s_n (oNoAllowMultipleMessages, "no-allow-multiple-messages", "@"),
857 ARGPARSE_s_n (oAllowWeakDigestAlgos, "allow-weak-digest-algos", "@"),
859 ARGPARSE_s_s (oDefaultNewKeyAlgo, "default-new-key-algo", "@"),
861 /* These two are aliases to help users of the PGP command line
862 product use gpg with minimal pain. Many commands are common
863 already as they seem to have borrowed commands from us. Now I'm
864 returning the favor. */
865 ARGPARSE_s_s (oLocalUser, "sign-with", "@"),
866 ARGPARSE_s_s (oRecipient, "user", "@"),
868 ARGPARSE_s_n (oRequireCrossCert, "require-backsigs", "@"),
869 ARGPARSE_s_n (oRequireCrossCert, "require-cross-certification", "@"),
870 ARGPARSE_s_n (oNoRequireCrossCert, "no-require-backsigs", "@"),
871 ARGPARSE_s_n (oNoRequireCrossCert, "no-require-cross-certification", "@"),
873 /* New options. Fixme: Should go more to the top. */
874 ARGPARSE_s_s (oAutoKeyLocate, "auto-key-locate", "@"),
875 ARGPARSE_s_n (oNoAutoKeyLocate, "no-auto-key-locate", "@"),
876 ARGPARSE_s_n (oNoAutostart, "no-autostart", "@"),
878 /* Dummy options with warnings. */
879 ARGPARSE_s_n (oUseAgent, "use-agent", "@"),
880 ARGPARSE_s_n (oNoUseAgent, "no-use-agent", "@"),
881 ARGPARSE_s_s (oGpgAgentInfo, "gpg-agent-info", "@"),
882 ARGPARSE_s_s (oReaderPort, "reader-port", "@"),
883 ARGPARSE_s_s (octapiDriver, "ctapi-driver", "@"),
884 ARGPARSE_s_s (opcscDriver, "pcsc-driver", "@"),
885 ARGPARSE_s_n (oDisableCCID, "disable-ccid", "@"),
886 ARGPARSE_s_n (oHonorHttpProxy, "honor-http-proxy", "@"),
887 ARGPARSE_s_s (oTOFUDBFormat, "tofu-db-format", "@"),
890 ARGPARSE_s_n (oNoop, "sk-comments", "@"),
891 ARGPARSE_s_n (oNoop, "no-sk-comments", "@"),
892 ARGPARSE_s_n (oNoop, "compress-keys", "@"),
893 ARGPARSE_s_n (oNoop, "compress-sigs", "@"),
894 ARGPARSE_s_n (oNoop, "force-v3-sigs", "@"),
895 ARGPARSE_s_n (oNoop, "no-force-v3-sigs", "@"),
896 ARGPARSE_s_n (oNoop, "force-v4-certs", "@"),
897 ARGPARSE_s_n (oNoop, "no-force-v4-certs", "@"),
903 /* The list of supported debug flags. */
904 static struct debug_flags_s debug_flags [] =
906 { DBG_PACKET_VALUE , "packet" },
907 { DBG_MPI_VALUE , "mpi" },
908 { DBG_CRYPTO_VALUE , "crypto" },
909 { DBG_FILTER_VALUE , "filter" },
910 { DBG_IOBUF_VALUE , "iobuf" },
911 { DBG_MEMORY_VALUE , "memory" },
912 { DBG_CACHE_VALUE , "cache" },
913 { DBG_MEMSTAT_VALUE, "memstat" },
914 { DBG_TRUST_VALUE , "trust" },
915 { DBG_HASHING_VALUE, "hashing" },
916 { DBG_IPC_VALUE , "ipc" },
917 { DBG_CLOCK_VALUE , "clock" },
918 { DBG_LOOKUP_VALUE , "lookup" },
919 { DBG_EXTPROG_VALUE, "extprog" },
924 #ifdef ENABLE_SELINUX_HACKS
925 #define ALWAYS_ADD_KEYRINGS 1
927 #define ALWAYS_ADD_KEYRINGS 0
931 int g10_errors_seen = 0;
933 static int utf8_strings = 0;
934 static int maybe_setuid = 1;
936 static char *build_list( const char *text, char letter,
937 const char *(*mapf)(int), int (*chkf)(int) );
938 static void set_cmd( enum cmd_and_opt_values *ret_cmd,
939 enum cmd_and_opt_values new_cmd );
940 static void print_mds( const char *fname, int algo );
941 static void add_notation_data( const char *string, int which );
942 static void add_policy_url( const char *string, int which );
943 static void add_keyserver_url( const char *string, int which );
944 static void emergency_cleanup (void);
945 static void read_sessionkey_from_fd (int fd);
949 make_libversion (const char *libname, const char *(*getfnc)(const char*))
956 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
960 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
961 strcpy (stpcpy (stpcpy (result, libname), " "), s);
967 build_list_pk_test_algo (int algo)
969 /* Show only one "RSA" string. If RSA_E or RSA_S is available RSA
970 is also available. */
971 if (algo == PUBKEY_ALGO_RSA_E
972 || algo == PUBKEY_ALGO_RSA_S)
973 return GPG_ERR_DIGEST_ALGO;
975 return openpgp_pk_test_algo (algo);
979 build_list_pk_algo_name (int algo)
981 return openpgp_pk_algo_name (algo);
985 build_list_cipher_test_algo (int algo)
987 return openpgp_cipher_test_algo (algo);
991 build_list_cipher_algo_name (int algo)
993 return openpgp_cipher_algo_name (algo);
997 build_list_md_test_algo (int algo)
999 /* By default we do not accept MD5 based signatures. To avoid
1000 confusion we do not announce support for it either. */
1001 if (algo == DIGEST_ALGO_MD5)
1002 return GPG_ERR_DIGEST_ALGO;
1004 return openpgp_md_test_algo (algo);
1008 build_list_md_algo_name (int algo)
1010 return openpgp_md_algo_name (algo);
1015 my_strusage( int level )
1017 static char *digests, *pubkeys, *ciphers, *zips, *ver_gcry;
1021 case 11: p = "@GPG@ (@GNUPG@)";
1023 case 13: p = VERSION; break;
1024 case 17: p = PRINTABLE_OS_NAME; break;
1025 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
1029 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
1033 #ifdef IS_DEVELOPMENT_VERSION
1035 p="NOTE: THIS IS A DEVELOPMENT VERSION!";
1038 p="It is only intended for test purposes and should NOT be";
1041 p="used in a production environment or with production keys!";
1047 _("Usage: @GPG@ [options] [files] (-h for help)");
1050 _("Syntax: @GPG@ [options] [files]\n"
1051 "Sign, check, encrypt or decrypt\n"
1052 "Default operation depends on the input data\n");
1055 case 31: p = "\nHome: "; break;
1057 case 32: p = gnupg_homedir (); break;
1058 #else /* __riscos__ */
1059 case 32: p = make_filename(gnupg_homedir (), NULL); break;
1060 #endif /* __riscos__ */
1061 case 33: p = _("\nSupported algorithms:\n"); break;
1064 pubkeys = build_list (_("Pubkey: "), 1,
1065 build_list_pk_algo_name,
1066 build_list_pk_test_algo );
1071 ciphers = build_list(_("Cipher: "), 'S',
1072 build_list_cipher_algo_name,
1073 build_list_cipher_test_algo );
1078 digests = build_list(_("Hash: "), 'H',
1079 build_list_md_algo_name,
1080 build_list_md_test_algo );
1085 zips = build_list(_("Compression: "),'Z',
1086 compress_algo_to_string,
1087 check_compress_algo);
1098 build_list (const char *text, char letter,
1099 const char * (*mapf)(int), int (*chkf)(int))
1108 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
1110 indent = utf8_charcount (text, -1);
1112 init_membuf (&mb, 512);
1114 for (i=0; i <= 110; i++ )
1116 if (!chkf (i) && (s = mapf (i)))
1118 if (mb.len - len > 60)
1120 put_membuf_str (&mb, ",\n");
1122 for (j=0; j < indent; j++)
1123 put_membuf_str (&mb, " ");
1126 put_membuf_str (&mb, ", ");
1128 put_membuf_str (&mb, text);
1130 put_membuf_str (&mb, s);
1131 if (opt.verbose && letter)
1135 snprintf (num, sizeof num, " (%d)", i);
1137 snprintf (num, sizeof num, " (%c%d)", letter, i);
1138 put_membuf_str (&mb, num);
1143 put_membuf_str (&mb, "\n");
1144 put_membuf (&mb, "", 1);
1146 string = get_membuf (&mb, NULL);
1147 return xrealloc (string, strlen (string)+1);
1152 wrong_args( const char *text)
1154 es_fprintf (es_stderr, _("usage: %s [options] %s\n"), GPG_NAME, text);
1160 make_username( const char *string )
1164 p = xstrdup(string);
1166 p = native_to_utf8( string );
1172 set_opt_session_env (const char *name, const char *value)
1176 err = session_env_setenv (opt.session_env, name, value);
1178 log_fatal ("error setting session environment: %s\n",
1179 gpg_strerror (err));
1183 /* Setup the debugging. With a LEVEL of NULL only the active debug
1184 flags are propagated to the subsystems. With LEVEL set, a specific
1185 set of debug flags is set; thus overriding all flags already
1188 set_debug (const char *level)
1190 int numok = (level && digitp (level));
1191 int numlvl = numok? atoi (level) : 0;
1195 else if (!strcmp (level, "none") || (numok && numlvl < 1))
1197 else if (!strcmp (level, "basic") || (numok && numlvl <= 2))
1198 opt.debug = DBG_MEMSTAT_VALUE;
1199 else if (!strcmp (level, "advanced") || (numok && numlvl <= 5))
1200 opt.debug = DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE;
1201 else if (!strcmp (level, "expert") || (numok && numlvl <= 8))
1202 opt.debug = (DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE
1203 |DBG_CACHE_VALUE|DBG_LOOKUP|DBG_FILTER_VALUE|DBG_PACKET_VALUE);
1204 else if (!strcmp (level, "guru") || numok)
1207 /* Unless the "guru" string has been used we don't want to allow
1208 hashing debugging. The rationale is that people tend to
1209 select the highest debug value and would then clutter their
1210 disk with debug files which may reveal confidential data. */
1212 opt.debug &= ~(DBG_HASHING_VALUE);
1216 log_error (_("invalid debug-level '%s' given\n"), level);
1220 if ((opt.debug & DBG_MEMORY_VALUE))
1221 memory_debug_mode = 1;
1222 if ((opt.debug & DBG_MEMSTAT_VALUE))
1223 memory_stat_debug_mode = 1;
1225 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
1227 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
1228 if ((opt.debug & DBG_IOBUF_VALUE))
1229 iobuf_debug_mode = 1;
1230 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1233 parse_debug_flag (NULL, &opt.debug, debug_flags);
1237 /* We set the screen dimensions for UI purposes. Do not allow screens
1238 smaller than 80x24 for the sake of simplicity. */
1240 set_screen_dimensions(void)
1242 #ifndef HAVE_W32_SYSTEM
1245 str=getenv("COLUMNS");
1247 opt.screen_columns=atoi(str);
1249 str=getenv("LINES");
1251 opt.screen_lines=atoi(str);
1254 if(opt.screen_columns<80 || opt.screen_columns>255)
1255 opt.screen_columns=80;
1257 if(opt.screen_lines<24 || opt.screen_lines>255)
1258 opt.screen_lines=24;
1262 /* Helper to open a file FNAME either for reading or writing to be
1263 used with --status-file etc functions. Not generally useful but it
1264 avoids the riscos specific functions and well some Windows people
1265 might like it too. Prints an error message and returns -1 on
1266 error. On success the file descriptor is returned. */
1268 open_info_file (const char *fname, int for_write, int binary)
1271 return riscos_fdopenfile (fname, for_write);
1272 #elif defined (ENABLE_SELINUX_HACKS)
1273 /* We can't allow these even when testing for a secured filename
1274 because files to be secured might not yet been secured. This is
1275 similar to the option file but in that case it is unlikely that
1276 sensitive information may be retrieved by means of error
1286 binary = MY_O_BINARY;
1288 /* if (is_secured_filename (fname)) */
1291 /* gpg_err_set_errno (EPERM); */
1298 fd = open (fname, O_CREAT | O_TRUNC | O_WRONLY | binary,
1299 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
1301 fd = open (fname, O_RDONLY | binary);
1303 while (fd == -1 && errno == EINTR);
1306 log_error ( for_write? _("can't create '%s': %s\n")
1307 : _("can't open '%s': %s\n"), fname, strerror(errno));
1314 set_cmd( enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd )
1316 enum cmd_and_opt_values cmd = *ret_cmd;
1318 if( !cmd || cmd == new_cmd )
1320 else if( cmd == aSign && new_cmd == aEncr )
1322 else if( cmd == aEncr && new_cmd == aSign )
1324 else if( cmd == aSign && new_cmd == aSym )
1326 else if( cmd == aSym && new_cmd == aSign )
1328 else if( cmd == aSym && new_cmd == aEncr )
1330 else if( cmd == aEncr && new_cmd == aSym )
1332 else if (cmd == aSignEncr && new_cmd == aSym)
1334 else if (cmd == aSignSym && new_cmd == aEncr)
1336 else if (cmd == aEncrSym && new_cmd == aSign)
1338 else if( ( cmd == aSign && new_cmd == aClearsign )
1339 || ( cmd == aClearsign && new_cmd == aSign ) )
1342 log_error(_("conflicting commands\n"));
1351 add_group(char *string)
1354 struct groupitem *item;
1356 /* Break off the group name */
1357 name=strsep(&string,"=");
1360 log_error(_("no = sign found in group definition '%s'\n"),name);
1364 trim_trailing_ws(name,strlen(name));
1366 /* Does this group already exist? */
1367 for(item=opt.grouplist;item;item=item->next)
1368 if(strcasecmp(item->name,name)==0)
1373 item=xmalloc(sizeof(struct groupitem));
1375 item->next=opt.grouplist;
1380 /* Break apart the values */
1381 while ((value= strsep(&string," \t")))
1384 add_to_strlist2(&item->values,value,utf8_strings);
1390 rm_group(char *name)
1392 struct groupitem *item,*last=NULL;
1394 trim_trailing_ws(name,strlen(name));
1396 for(item=opt.grouplist;item;last=item,item=item->next)
1398 if(strcasecmp(item->name,name)==0)
1401 last->next=item->next;
1403 opt.grouplist=item->next;
1405 free_strlist(item->values);
1413 /* We need to check three things.
1415 0) The homedir. It must be x00, a directory, and owned by the
1418 1) The options/gpg.conf file. Okay unless it or its containing
1419 directory is group or other writable or not owned by us. Disable
1422 2) Extensions. Same as #1.
1424 Returns true if the item is unsafe. */
1426 check_permissions (const char *path, int item)
1428 #if defined(HAVE_STAT) && !defined(HAVE_DOSISH_SYSTEM)
1429 static int homedir_cache=-1;
1431 struct stat statbuf,dirbuf;
1432 int homedir=0,ret=0,checkonly=0;
1433 int perm=0,own=0,enc_dir_perm=0,enc_dir_own=0;
1435 if(opt.no_perm_warn)
1438 log_assert(item==0 || item==1 || item==2);
1440 /* extensions may attach a path */
1441 if(item==2 && path[0]!=DIRSEP_C)
1443 if(strchr(path,DIRSEP_C))
1444 tmppath=make_filename(path,NULL);
1446 tmppath=make_filename(gnupg_libdir (),path,NULL);
1449 tmppath=xstrdup(path);
1451 /* If the item is located in the homedir, but isn't the homedir,
1452 don't continue if we already checked the homedir itself. This is
1453 to avoid user confusion with an extra options file warning which
1454 could be rectified if the homedir itself had proper
1456 if(item!=0 && homedir_cache>-1
1457 && !ascii_strncasecmp (gnupg_homedir (), tmppath,
1458 strlen (gnupg_homedir ())))
1464 /* It's okay if the file or directory doesn't exist */
1465 if(stat(tmppath,&statbuf)!=0)
1471 /* Now check the enclosing directory. Theoretically, we could walk
1472 this test up to the root directory /, but for the sake of sanity,
1473 I'm stopping at one level down. */
1474 dir=make_dirname(tmppath);
1476 if(stat(dir,&dirbuf)!=0 || !S_ISDIR(dirbuf.st_mode))
1485 /* Assume failure */
1490 /* The homedir must be x00, a directory, and owned by the user. */
1492 if(S_ISDIR(statbuf.st_mode))
1494 if(statbuf.st_uid==getuid())
1496 if((statbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1507 else if(item==1 || item==2)
1509 /* The options or extension file. Okay unless it or its
1510 containing directory is group or other writable or not owned
1513 if(S_ISREG(statbuf.st_mode))
1515 if(statbuf.st_uid==getuid() || statbuf.st_uid==0)
1517 if((statbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1519 /* it's not writable, so make sure the enclosing
1520 directory is also not writable */
1521 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1523 if((dirbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1533 /* it's writable, so the enclosing directory had
1534 better not let people get to it. */
1535 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1537 if((dirbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1540 perm=enc_dir_perm=1; /* unclear which one to fix! */
1558 log_info(_("WARNING: unsafe ownership on"
1559 " homedir '%s'\n"),tmppath);
1561 log_info(_("WARNING: unsafe ownership on"
1562 " configuration file '%s'\n"),tmppath);
1564 log_info(_("WARNING: unsafe ownership on"
1565 " extension '%s'\n"),tmppath);
1570 log_info(_("WARNING: unsafe permissions on"
1571 " homedir '%s'\n"),tmppath);
1573 log_info(_("WARNING: unsafe permissions on"
1574 " configuration file '%s'\n"),tmppath);
1576 log_info(_("WARNING: unsafe permissions on"
1577 " extension '%s'\n"),tmppath);
1582 log_info(_("WARNING: unsafe enclosing directory ownership on"
1583 " homedir '%s'\n"),tmppath);
1585 log_info(_("WARNING: unsafe enclosing directory ownership on"
1586 " configuration file '%s'\n"),tmppath);
1588 log_info(_("WARNING: unsafe enclosing directory ownership on"
1589 " extension '%s'\n"),tmppath);
1594 log_info(_("WARNING: unsafe enclosing directory permissions on"
1595 " homedir '%s'\n"),tmppath);
1597 log_info(_("WARNING: unsafe enclosing directory permissions on"
1598 " configuration file '%s'\n"),tmppath);
1600 log_info(_("WARNING: unsafe enclosing directory permissions on"
1601 " extension '%s'\n"),tmppath);
1613 #else /*!(HAVE_STAT && !HAVE_DOSISH_SYSTEM)*/
1617 #endif /*!(HAVE_STAT && !HAVE_DOSISH_SYSTEM)*/
1621 /* Print the OpenPGP defined algo numbers. */
1623 print_algo_numbers(int (*checker)(int))
1642 print_algo_names(int (*checker)(int),const char *(*mapper)(int))
1654 es_printf ("%s",mapper(i));
1659 /* In the future, we can do all sorts of interesting configuration
1660 output here. For now, just give "group" as the Enigmail folks need
1661 it, and pubkey, cipher, hash, and compress as they may be useful
1664 list_config(char *items)
1666 int show_all = !items;
1669 struct groupitem *giter;
1672 if(!opt.with_colons)
1675 while(show_all || (name=strsep(&items," ")))
1679 if(show_all || ascii_strcasecmp(name,"group")==0)
1681 for (giter = opt.grouplist; giter; giter = giter->next)
1685 es_fprintf (es_stdout, "cfg:group:");
1686 es_write_sanitized (es_stdout, giter->name, strlen(giter->name),
1688 es_putc (':', es_stdout);
1690 for(sl=giter->values; sl; sl=sl->next)
1692 es_write_sanitized (es_stdout, sl->d, strlen (sl->d),
1704 if(show_all || ascii_strcasecmp(name,"version")==0)
1706 es_printf("cfg:version:");
1707 es_write_sanitized (es_stdout, VERSION, strlen(VERSION), ":", NULL);
1712 if(show_all || ascii_strcasecmp(name,"pubkey")==0)
1714 es_printf ("cfg:pubkey:");
1715 print_algo_numbers (build_list_pk_test_algo);
1720 if(show_all || ascii_strcasecmp(name,"pubkeyname")==0)
1722 es_printf ("cfg:pubkeyname:");
1723 print_algo_names (build_list_pk_test_algo,
1724 build_list_pk_algo_name);
1729 if(show_all || ascii_strcasecmp(name,"cipher")==0)
1731 es_printf ("cfg:cipher:");
1732 print_algo_numbers (build_list_cipher_test_algo);
1737 if (show_all || !ascii_strcasecmp (name,"ciphername"))
1739 es_printf ("cfg:ciphername:");
1740 print_algo_names (build_list_cipher_test_algo,
1741 build_list_cipher_algo_name);
1747 || ascii_strcasecmp(name,"digest")==0
1748 || ascii_strcasecmp(name,"hash")==0)
1750 es_printf ("cfg:digest:");
1751 print_algo_numbers (build_list_md_test_algo);
1757 || !ascii_strcasecmp(name,"digestname")
1758 || !ascii_strcasecmp(name,"hashname"))
1760 es_printf ("cfg:digestname:");
1761 print_algo_names (build_list_md_test_algo,
1762 build_list_md_algo_name);
1767 if(show_all || ascii_strcasecmp(name,"compress")==0)
1769 es_printf ("cfg:compress:");
1770 print_algo_numbers(check_compress_algo);
1775 if(show_all || ascii_strcasecmp (name, "compressname") == 0)
1777 es_printf ("cfg:compressname:");
1778 print_algo_names (check_compress_algo,
1779 compress_algo_to_string);
1784 if (show_all || !ascii_strcasecmp(name,"ccid-reader-id"))
1786 /* We ignore this for GnuPG 1.4 backward compatibility. */
1790 if (show_all || !ascii_strcasecmp (name,"curve"))
1792 es_printf ("cfg:curve:");
1793 for (iter=0, first=1; (s = openpgp_enum_curves (&iter)); first=0)
1794 es_printf ("%s%s", first?"":";", s);
1799 /* Curve OIDs are rarely useful and thus only printed if requested. */
1800 if (name && !ascii_strcasecmp (name,"curveoid"))
1802 es_printf ("cfg:curveoid:");
1803 for (iter=0, first=1; (s = openpgp_enum_curves (&iter)); first = 0)
1805 s = openpgp_curve_to_oid (s, NULL);
1806 es_printf ("%s%s", first?"":";", s? s:"[?]");
1816 log_error(_("unknown configuration item '%s'\n"),name);
1821 /* List options and default values in the GPG Conf format. This is a
1822 new tool distributed with gnupg 1.9.x but we also want some limited
1823 support in older gpg versions. The output is the name of the
1824 configuration file and a list of options available for editing by
1827 gpgconf_list (const char *configfile)
1829 char *configfile_esc = percent_escape (configfile, NULL);
1831 es_printf ("%s-%s.conf:%lu:\"%s\n",
1832 GPGCONF_NAME, GPG_NAME,
1833 GC_OPT_FLAG_DEFAULT,
1834 configfile_esc ? configfile_esc : "/dev/null");
1835 es_printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
1836 es_printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
1837 es_printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
1838 es_printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE);
1839 es_printf ("default-key:%lu:\n", GC_OPT_FLAG_NONE);
1840 es_printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_NONE);
1841 es_printf ("try-secret-key:%lu:\n", GC_OPT_FLAG_NONE);
1842 es_printf ("auto-key-locate:%lu:\n", GC_OPT_FLAG_NONE);
1843 es_printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE);
1844 es_printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
1845 es_printf ("group:%lu:\n", GC_OPT_FLAG_NONE);
1846 es_printf ("compliance:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT, "gnupg");
1847 es_printf ("default-new-key-algo:%lu:\n", GC_OPT_FLAG_NONE);
1848 es_printf ("trust-model:%lu:\n", GC_OPT_FLAG_NONE);
1850 /* The next one is an info only item and should match the macros at
1851 the top of keygen.c */
1852 es_printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1853 get_default_pubkey_algo ());
1855 xfree (configfile_esc);
1860 parse_subpacket_list(char *list)
1863 byte subpackets[128],i;
1868 /* No arguments means all subpackets */
1869 memset(subpackets+1,1,sizeof(subpackets)-1);
1874 memset(subpackets,0,sizeof(subpackets));
1876 /* Merge with earlier copy */
1877 if(opt.show_subpackets)
1881 for(in=opt.show_subpackets;*in;in++)
1883 if(*in>127 || *in<1)
1886 if(!subpackets[*in])
1892 while((tok=strsep(&list," ,")))
1907 xfree(opt.show_subpackets);
1908 opt.show_subpackets=xmalloc(count+1);
1909 opt.show_subpackets[count--]=0;
1911 for(i=1;i<128 && count>=0;i++)
1913 opt.show_subpackets[count--]=i;
1920 parse_list_options(char *str)
1922 char *subpackets=""; /* something that isn't NULL */
1923 struct parse_options lopts[]=
1925 {"show-photos",LIST_SHOW_PHOTOS,NULL,
1926 N_("display photo IDs during key listings")},
1927 {"show-usage",LIST_SHOW_USAGE,NULL,
1928 N_("show key usage information during key listings")},
1929 {"show-policy-urls",LIST_SHOW_POLICY_URLS,NULL,
1930 N_("show policy URLs during signature listings")},
1931 {"show-notations",LIST_SHOW_NOTATIONS,NULL,
1932 N_("show all notations during signature listings")},
1933 {"show-std-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1934 N_("show IETF standard notations during signature listings")},
1935 {"show-standard-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1937 {"show-user-notations",LIST_SHOW_USER_NOTATIONS,NULL,
1938 N_("show user-supplied notations during signature listings")},
1939 {"show-keyserver-urls",LIST_SHOW_KEYSERVER_URLS,NULL,
1940 N_("show preferred keyserver URLs during signature listings")},
1941 {"show-uid-validity",LIST_SHOW_UID_VALIDITY,NULL,
1942 N_("show user ID validity during key listings")},
1943 {"show-unusable-uids",LIST_SHOW_UNUSABLE_UIDS,NULL,
1944 N_("show revoked and expired user IDs in key listings")},
1945 {"show-unusable-subkeys",LIST_SHOW_UNUSABLE_SUBKEYS,NULL,
1946 N_("show revoked and expired subkeys in key listings")},
1947 {"show-keyring",LIST_SHOW_KEYRING,NULL,
1948 N_("show the keyring name in key listings")},
1949 {"show-sig-expire",LIST_SHOW_SIG_EXPIRE,NULL,
1950 N_("show expiration dates during signature listings")},
1951 {"show-sig-subpackets",LIST_SHOW_SIG_SUBPACKETS,NULL,
1956 /* C99 allows for non-constant initializers, but we'd like to
1957 compile everywhere, so fill in the show-sig-subpackets argument
1958 here. Note that if the parse_options array changes, we'll have
1959 to change the subscript here. */
1960 lopts[13].value=&subpackets;
1962 if(parse_options(str,&opt.list_options,lopts,1))
1964 if(opt.list_options&LIST_SHOW_SIG_SUBPACKETS)
1966 /* Unset so users can pass multiple lists in. */
1967 opt.list_options&=~LIST_SHOW_SIG_SUBPACKETS;
1968 if(!parse_subpacket_list(subpackets))
1971 else if(subpackets==NULL && opt.show_subpackets)
1973 /* User did 'no-show-subpackets' */
1974 xfree(opt.show_subpackets);
1975 opt.show_subpackets=NULL;
1985 /* Collapses argc/argv into a single string that must be freed */
1987 collapse_args(int argc,char *argv[])
1990 int i,first=1,len=0;
1994 len+=strlen(argv[i])+2;
1995 str=xrealloc(str,len);
2004 strcat(str,argv[i]);
2011 #ifndef NO_TRUST_MODELS
2013 parse_trust_model(const char *model)
2015 if(ascii_strcasecmp(model,"pgp")==0)
2016 opt.trust_model=TM_PGP;
2017 else if(ascii_strcasecmp(model,"classic")==0)
2018 opt.trust_model=TM_CLASSIC;
2019 else if(ascii_strcasecmp(model,"always")==0)
2020 opt.trust_model=TM_ALWAYS;
2021 else if(ascii_strcasecmp(model,"direct")==0)
2022 opt.trust_model=TM_DIRECT;
2024 else if(ascii_strcasecmp(model,"tofu")==0)
2025 opt.trust_model=TM_TOFU;
2026 else if(ascii_strcasecmp(model,"tofu+pgp")==0)
2027 opt.trust_model=TM_TOFU_PGP;
2029 else if(ascii_strcasecmp(model,"auto")==0)
2030 opt.trust_model=TM_AUTO;
2032 log_error("unknown trust model '%s'\n",model);
2034 #endif /*NO_TRUST_MODELS*/
2038 parse_tofu_policy (const char *policystr)
2041 struct { const char *keyword; int policy; } list[] = {
2042 { "auto", TOFU_POLICY_AUTO },
2043 { "good", TOFU_POLICY_GOOD },
2044 { "unknown", TOFU_POLICY_UNKNOWN },
2045 { "bad", TOFU_POLICY_BAD },
2046 { "ask", TOFU_POLICY_ASK }
2050 if (!ascii_strcasecmp (policystr, "help"))
2052 log_info (_("valid values for option '%s':\n"), "--tofu-policy");
2053 for (i=0; i < DIM (list); i++)
2054 log_info (" %s\n", list[i].keyword);
2058 for (i=0; i < DIM (list); i++)
2059 if (!ascii_strcasecmp (policystr, list[i].keyword))
2060 return list[i].policy;
2063 log_error (_("unknown TOFU policy '%s'\n"), policystr);
2065 log_info (_("(use \"help\" to list choices)\n"));
2070 /* Parse the value of --compliance. */
2072 parse_compliance_option (const char *string)
2074 struct { const char *keyword; enum cmd_and_opt_values option; } list[] = {
2075 { "gnupg", oGnuPG },
2076 { "openpgp", oOpenPGP },
2077 { "rfc4880bis", oRFC4880bis },
2078 { "rfc4880", oRFC4880 },
2079 { "rfc2440", oRFC2440 },
2087 if (!ascii_strcasecmp (string, "help"))
2089 log_info (_("valid values for option '%s':\n"), "--compliance");
2090 for (i=0; i < DIM (list); i++)
2091 log_info (" %s\n", list[i].keyword);
2095 for (i=0; i < DIM (list); i++)
2096 if (!ascii_strcasecmp (string, list[i].keyword))
2097 return list[i].option;
2099 log_error (_("invalid value for option '%s'\n"), "--compliance");
2101 log_info (_("(use \"help\" to list choices)\n"));
2107 /* Helper to set compliance related options. This is a separte
2108 * function so that it can also be used by the --compliance option
2111 set_compliance_option (enum cmd_and_opt_values option)
2116 opt.flags.rfc4880bis = 1;
2120 /* This is effectively the same as RFC2440, but with
2121 "--enable-dsa2 --no-rfc2440-text --escape-from-lines
2122 --require-cross-certification". */
2123 opt.compliance = CO_RFC4880;
2125 opt.flags.require_cross_cert = 1;
2126 opt.rfc2440_text = 0;
2127 opt.allow_non_selfsigned_uid = 1;
2128 opt.allow_freeform_uid = 1;
2129 opt.escape_from = 1;
2130 opt.not_dash_escaped = 0;
2131 opt.def_cipher_algo = 0;
2132 opt.def_digest_algo = 0;
2133 opt.cert_digest_algo = 0;
2134 opt.compress_algo = -1;
2135 opt.s2k_mode = 3; /* iterated+salted */
2136 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2137 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2140 opt.compliance = CO_RFC2440;
2142 opt.rfc2440_text = 1;
2143 opt.allow_non_selfsigned_uid = 1;
2144 opt.allow_freeform_uid = 1;
2145 opt.escape_from = 0;
2146 opt.not_dash_escaped = 0;
2147 opt.def_cipher_algo = 0;
2148 opt.def_digest_algo = 0;
2149 opt.cert_digest_algo = 0;
2150 opt.compress_algo = -1;
2151 opt.s2k_mode = 3; /* iterated+salted */
2152 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2153 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2155 case oPGP6: opt.compliance = CO_PGP6; break;
2156 case oPGP7: opt.compliance = CO_PGP7; break;
2157 case oPGP8: opt.compliance = CO_PGP8; break;
2158 case oGnuPG: opt.compliance = CO_GNUPG; break;
2161 set_compliance_option (oOpenPGP);
2162 opt.compliance = CO_DE_VS;
2163 /* Fixme: Change other options. */
2176 /* This function called to initialized a new control object. It is
2177 assumed that this object has been zeroed out before calling this
2180 gpg_init_default_ctrl (ctrl_t ctrl)
2186 /* This function is called to deinitialize a control object. It is
2189 gpg_deinit_default_ctrl (ctrl_t ctrl)
2192 tofu_closedbs (ctrl);
2194 gpg_dirmngr_deinit_session_data (ctrl);
2199 get_default_configname (void)
2201 char *configname = NULL;
2202 char *name = xstrdup (GPG_NAME EXTSEP_S "conf-" SAFE_VERSION);
2203 char *ver = &name[strlen (GPG_NAME EXTSEP_S "conf-")];
2214 if ((tok = strrchr (ver, SAFE_VERSION_DASH)))
2216 else if ((tok = strrchr (ver, SAFE_VERSION_DOT)))
2222 configname = make_filename (gnupg_homedir (), name, NULL);
2224 while (access (configname, R_OK));
2229 configname = make_filename (gnupg_homedir (),
2230 GPG_NAME EXTSEP_S "conf", NULL);
2231 if (! access (configname, R_OK))
2233 /* Print a warning when both config files are present. */
2234 char *p = make_filename (gnupg_homedir (), "options", NULL);
2235 if (! access (p, R_OK))
2236 log_info (_("Note: old default options file '%s' ignored\n"), p);
2241 /* Use the old default only if it exists. */
2242 char *p = make_filename (gnupg_homedir (), "options", NULL);
2243 if (!access (p, R_OK))
2256 main (int argc, char **argv)
2258 ARGPARSE_ARGS pargs;
2267 strlist_t remusr = NULL;
2268 strlist_t locusr = NULL;
2269 strlist_t nrings = NULL;
2270 armor_filter_context_t *afx = NULL;
2271 int detached_sig = 0;
2272 FILE *configfp = NULL;
2273 char *configname = NULL;
2274 char *save_configname = NULL;
2275 char *default_configname = NULL;
2276 unsigned configlineno;
2277 int parse_debug = 0;
2278 int default_config = 1;
2279 int default_keyring = 1;
2282 char *logfile = NULL;
2283 int use_random_seed = 1;
2284 enum cmd_and_opt_values cmd = 0;
2285 const char *debug_level = NULL;
2286 #ifndef NO_TRUST_MODELS
2287 const char *trustdb_name = NULL;
2288 #endif /*!NO_TRUST_MODELS*/
2289 char *def_cipher_string = NULL;
2290 char *def_digest_string = NULL;
2291 char *compress_algo_string = NULL;
2292 char *cert_digest_string = NULL;
2293 char *s2k_cipher_string = NULL;
2294 char *s2k_digest_string = NULL;
2295 char *pers_cipher_list = NULL;
2296 char *pers_digest_list = NULL;
2297 char *pers_compress_list = NULL;
2301 int ovrseskeyfd = -1;
2302 int fpr_maybe_cmd = 0; /* --fingerprint maybe a command. */
2303 int any_explicit_recipient = 0;
2304 int require_secmem = 0;
2306 struct assuan_malloc_hooks malloc_hooks;
2309 static int print_dane_records;
2310 static int print_pka_records;
2315 #endif /* __riscos__ */
2317 /* Please note that we may running SUID(ROOT), so be very CAREFUL
2318 when adding any stuff between here and the call to
2319 secmem_init() somewhere after the option parsing. */
2320 early_system_init ();
2321 gnupg_reopen_std (GPG_NAME);
2323 gnupg_rl_initialize ();
2324 set_strusage (my_strusage);
2325 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
2326 log_set_prefix (GPG_NAME, GPGRT_LOG_WITH_PREFIX);
2328 /* Make sure that our subsystems are ready. */
2330 init_common_subsystems (&argc, &argv);
2332 /* Use our own logging handler for Libcgrypt. */
2333 setup_libgcrypt_logging ();
2335 /* Put random number into secure memory */
2336 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
2338 may_coredump = disable_core_dumps();
2340 gnupg_init_signals (0, emergency_cleanup);
2342 dotlock_create (NULL, 0); /* Register lock file cleanup. */
2345 opt.session_env = session_env_new ();
2346 if (!opt.session_env)
2347 log_fatal ("error allocating session environment block: %s\n",
2350 opt.command_fd = -1; /* no command fd */
2351 opt.compress_level = -1; /* defaults to standard compress level */
2352 opt.bz2_compress_level = -1; /* defaults to standard compress level */
2353 /* note: if you change these lines, look at oOpenPGP */
2354 opt.def_cipher_algo = 0;
2355 opt.def_digest_algo = 0;
2356 opt.cert_digest_algo = 0;
2357 opt.compress_algo = -1; /* defaults to DEFAULT_COMPRESS_ALGO */
2358 opt.s2k_mode = 3; /* iterated+salted */
2359 opt.s2k_count = 0; /* Auto-calibrate when needed. */
2360 opt.s2k_cipher_algo = DEFAULT_CIPHER_ALGO;
2361 opt.completes_needed = 1;
2362 opt.marginals_needed = 3;
2363 opt.max_cert_depth = 5;
2364 opt.escape_from = 1;
2365 opt.flags.require_cross_cert = 1;
2366 opt.import_options = 0;
2367 opt.export_options = EXPORT_ATTRIBUTES;
2368 opt.keyserver_options.import_options = IMPORT_REPAIR_PKS_SUBKEY_BUG;
2369 opt.keyserver_options.export_options = EXPORT_ATTRIBUTES;
2370 opt.keyserver_options.options = KEYSERVER_HONOR_PKA_RECORD;
2371 opt.verify_options = (LIST_SHOW_UID_VALIDITY
2372 | VERIFY_SHOW_POLICY_URLS
2373 | VERIFY_SHOW_STD_NOTATIONS
2374 | VERIFY_SHOW_KEYSERVER_URLS);
2375 opt.list_options = (LIST_SHOW_UID_VALIDITY
2377 #ifdef NO_TRUST_MODELS
2378 opt.trust_model = TM_ALWAYS;
2380 opt.trust_model = TM_AUTO;
2382 opt.tofu_default_policy = TOFU_POLICY_AUTO;
2383 opt.mangle_dos_filenames = 0;
2384 opt.min_cert_level = 2;
2385 set_screen_dimensions ();
2386 opt.keyid_format = KF_NONE;
2387 opt.def_sig_expire = "0";
2388 opt.def_cert_expire = "0";
2389 gnupg_set_homedir (NULL);
2390 opt.passphrase_repeat = 1;
2391 opt.emit_version = 0;
2392 opt.weak_digests = NULL;
2393 additional_weak_digest("MD5");
2395 /* Check whether we have a config file on the command line. */
2400 pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
2401 while( arg_parse( &pargs, opts) ) {
2402 if( pargs.r_opt == oDebug || pargs.r_opt == oDebugAll )
2404 else if (pargs.r_opt == oDebugIOLBF)
2405 es_setvbuf (es_stdout, NULL, _IOLBF, 0);
2406 else if( pargs.r_opt == oOptions ) {
2407 /* yes there is one, so we do not try the default one, but
2408 * read the option file when it is encountered at the commandline
2412 else if( pargs.r_opt == oNoOptions )
2414 default_config = 0; /* --no-options */
2415 opt.no_homedir_creation = 1;
2417 else if( pargs.r_opt == oHomedir )
2418 gnupg_set_homedir (pargs.r.ret_str);
2419 else if( pargs.r_opt == oNoPermissionWarn )
2421 else if (pargs.r_opt == oStrict )
2425 else if (pargs.r_opt == oNoStrict )
2431 #ifdef HAVE_DOSISH_SYSTEM
2432 if ( strchr (gnupg_homedir (), '\\') ) {
2433 char *d, *buf = xmalloc (strlen (gnupg_homedir ())+1);
2435 for (d=buf, s = gnupg_homedir (); *s; s++)
2437 *d++ = *s == '\\'? '/': *s;
2438 #ifdef HAVE_W32_SYSTEM
2439 if (s[1] && IsDBCSLeadByte (*s))
2444 gnupg_set_homedir (buf);
2448 /* Initialize the secure memory. */
2449 if (!gcry_control (GCRYCTL_INIT_SECMEM, SECMEM_BUFFER_SIZE, 0))
2451 #if defined(HAVE_GETUID) && defined(HAVE_GETEUID)
2452 /* There should be no way to get to this spot while still carrying
2453 setuid privs. Just in case, bomb out if we are. */
2454 if ( getuid () != geteuid () )
2459 /* Okay, we are now working under our real uid */
2461 /* malloc hooks go here ... */
2462 malloc_hooks.malloc = gcry_malloc;
2463 malloc_hooks.realloc = gcry_realloc;
2464 malloc_hooks.free = gcry_free;
2465 assuan_set_malloc_hooks (&malloc_hooks);
2466 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
2467 setup_libassuan_logging (&opt.debug, NULL);
2469 /* Try for a version specific config file first */
2470 default_configname = get_default_configname ();
2472 configname = xstrdup (default_configname);
2478 pargs.flags= ARGPARSE_FLAG_KEEP;
2480 /* By this point we have a homedir, and cannot change it. */
2481 check_permissions (gnupg_homedir (), 0);
2485 if(check_permissions(configname,1))
2487 /* If any options file is unsafe, then disable any external
2488 programs for keyserver calls or photo IDs. Since the
2489 external program to call is set in the options file, a
2490 unsafe options file can lead to an arbitrary program
2497 configfp = fopen( configname, "r" );
2498 if (configfp && is_secured_file (fileno (configfp)))
2502 gpg_err_set_errno (EPERM);
2505 if( default_config ) {
2507 log_info(_("Note: no default option file '%s'\n"),
2511 log_error(_("option file '%s': %s\n"),
2512 configname, strerror(errno) );
2515 xfree(configname); configname = NULL;
2517 if( parse_debug && configname )
2518 log_info(_("reading options from '%s'\n"), configname );
2522 while( optfile_parse( configfp, configname, &configlineno,
2525 switch( pargs.r_opt )
2528 case aListGcryptConfig:
2531 set_cmd (&cmd, pargs.r_opt);
2532 /* Do not register a keyring for these commands. */
2533 default_keyring = -1;
2546 #ifdef ENABLE_CARD_SUPPORT
2550 #endif /* ENABLE_CARD_SUPPORT*/
2555 case aExportSecretSub:
2567 case aUpdateTrustDB:
2569 case aListTrustPath:
2574 case aQuickLSignKey:
2582 case aQuickSetExpire:
2583 case aExportOwnerTrust:
2584 case aImportOwnerTrust:
2585 case aRebuildKeydbCaches:
2586 set_cmd (&cmd, pargs.r_opt);
2592 case aDeleteSecretKeys:
2593 case aDeleteSecretAndPublicKeys:
2596 set_cmd (&cmd, pargs.r_opt);
2600 case aDetachedSign: detached_sig = 1; set_cmd( &cmd, aSign ); break;
2602 case aDecryptFiles: multifile=1; /* fall through */
2603 case aDecrypt: set_cmd( &cmd, aDecrypt); break;
2605 case aEncrFiles: multifile=1; /* fall through */
2606 case aEncr: set_cmd( &cmd, aEncr); break;
2608 case aVerifyFiles: multifile=1; /* fall through */
2609 case aVerify: set_cmd( &cmd, aVerify); break;
2612 set_cmd (&cmd, pargs.r_opt);
2617 set_cmd (&cmd, pargs.r_opt);
2620 case oArmor: opt.armor = 1; opt.no_armor=0; break;
2621 case oOutput: opt.outfile = pargs.r.ret_str; break;
2623 case oMaxOutput: opt.max_output = pargs.r.ret_ulong; break;
2625 case oInputSizeHint:
2626 opt.input_size_hint = string_to_u64 (pargs.r.ret_str);
2629 case oQuiet: opt.quiet = 1; break;
2630 case oNoTTY: tty_no_terminal(1); break;
2631 case oDryRun: opt.dry_run = 1; break;
2632 case oInteractive: opt.interactive = 1; break;
2635 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2636 opt.list_options|=LIST_SHOW_UNUSABLE_UIDS;
2637 opt.list_options|=LIST_SHOW_UNUSABLE_SUBKEYS;
2645 case oUseAgent: /* Dummy. */
2649 obsolete_option (configname, configlineno, "no-use-agent");
2652 obsolete_option (configname, configlineno, "gpg-agent-info");
2655 obsolete_scdaemon_option (configname, configlineno, "reader-port");
2658 obsolete_scdaemon_option (configname, configlineno, "ctapi-driver");
2661 obsolete_scdaemon_option (configname, configlineno, "pcsc-driver");
2664 obsolete_scdaemon_option (configname, configlineno, "disable-ccid");
2666 case oHonorHttpProxy:
2667 obsolete_option (configname, configlineno, "honor-http-proxy");
2670 case oAnswerYes: opt.answer_yes = 1; break;
2671 case oAnswerNo: opt.answer_no = 1; break;
2672 case oKeyring: append_to_strlist( &nrings, pargs.r.ret_str); break;
2673 case oPrimaryKeyring:
2674 sl = append_to_strlist (&nrings, pargs.r.ret_str);
2675 sl->flags = KEYDB_RESOURCE_FLAG_PRIMARY;
2678 deprecated_warning(configname,configlineno,"--show-keyring",
2679 "--list-options ","show-keyring");
2680 opt.list_options|=LIST_SHOW_KEYRING;
2684 if (parse_debug_flag (pargs.r.ret_str, &opt.debug, debug_flags))
2686 pargs.r_opt = ARGPARSE_INVALID_ARG;
2687 pargs.err = ARGPARSE_PRINT_ERROR;
2691 case oDebugAll: opt.debug = ~0; break;
2692 case oDebugLevel: debug_level = pargs.r.ret_str; break;
2694 case oDebugIOLBF: break; /* Already set in pre-parse step. */
2697 set_status_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
2700 set_status_fd ( open_info_file (pargs.r.ret_str, 1, 0) );
2703 set_attrib_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
2705 case oAttributeFile:
2706 set_attrib_fd ( open_info_file (pargs.r.ret_str, 1, 1) );
2709 log_set_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1));
2712 logfile = pargs.r.ret_str;
2715 case oWithFingerprint:
2716 opt.with_fingerprint = 1;
2719 case oWithSubkeyFingerprint:
2720 opt.with_subkey_fingerprint = 1;
2722 case oWithICAOSpelling:
2723 opt.with_icao_spelling = 1;
2731 opt.with_keygrip = 1;
2735 opt.with_secret = 1;
2739 opt.with_wkd_hash = 1;
2742 case oSecretKeyring:
2743 /* Ignore this old option. */
2747 /* config files may not be nested (silently ignore them) */
2750 configname = xstrdup(pargs.r.ret_str);
2754 case oNoArmor: opt.no_armor=1; opt.armor=0; break;
2757 if (default_keyring > 0)
2758 default_keyring = 0;
2761 default_keyring = -1;
2764 case oNoGreeting: nogreeting = 1; break;
2767 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2771 gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
2773 case oEmitVersion: opt.emit_version++; break;
2774 case oNoEmitVersion: opt.emit_version=0; break;
2775 case oCompletesNeeded: opt.completes_needed = pargs.r.ret_int; break;
2776 case oMarginalsNeeded: opt.marginals_needed = pargs.r.ret_int; break;
2777 case oMaxCertDepth: opt.max_cert_depth = pargs.r.ret_int; break;
2779 #ifndef NO_TRUST_MODELS
2780 case oTrustDBName: trustdb_name = pargs.r.ret_str; break;
2782 #endif /*!NO_TRUST_MODELS*/
2784 sl = add_to_strlist (&opt.def_secret_key, pargs.r.ret_str);
2785 sl->flags = (pargs.r_opt << PK_LIST_SHIFT);
2787 sl->flags |= PK_LIST_CONFIG;
2790 if( *pargs.r.ret_str )
2792 xfree (opt.def_recipient);
2793 opt.def_recipient = make_username(pargs.r.ret_str);
2796 case oDefRecipientSelf:
2797 xfree(opt.def_recipient); opt.def_recipient = NULL;
2798 opt.def_recipient_self = 1;
2800 case oNoDefRecipient:
2801 xfree(opt.def_recipient); opt.def_recipient = NULL;
2802 opt.def_recipient_self = 0;
2804 case oNoOptions: opt.no_homedir_creation = 1; break; /* no-options */
2805 case oHomedir: break;
2806 case oNoBatch: opt.batch = 0; break;
2808 case oWithTofuInfo: opt.with_tofu_info = 1; break;
2810 case oWithKeyData: opt.with_key_data=1; /*FALLTHRU*/
2811 case oWithColons: opt.with_colons=':'; break;
2813 case oWithSigCheck: opt.check_sigs = 1; /*FALLTHRU*/
2814 case oWithSigList: opt.list_sigs = 1; break;
2816 case oSkipVerify: opt.skip_verify=1; break;
2818 case oSkipHiddenRecipients: opt.skip_hidden_recipients = 1; break;
2819 case oNoSkipHiddenRecipients: opt.skip_hidden_recipients = 0; break;
2821 case aListSecretKeys: set_cmd( &cmd, aListSecretKeys); break;
2823 #ifndef NO_TRUST_MODELS
2824 /* There are many programs (like mutt) that call gpg with
2825 --always-trust so keep this option around for a long
2827 case oAlwaysTrust: opt.trust_model=TM_ALWAYS; break;
2829 parse_trust_model(pargs.r.ret_str);
2831 #endif /*!NO_TRUST_MODELS*/
2832 case oTOFUDefaultPolicy:
2833 opt.tofu_default_policy = parse_tofu_policy (pargs.r.ret_str);
2836 obsolete_option (configname, configlineno, "tofu-db-format");
2839 case oForceOwnertrust:
2840 log_info(_("Note: %s is not for normal use!\n"),
2841 "--force-ownertrust");
2842 opt.force_ownertrust=string_to_trust_value(pargs.r.ret_str);
2843 if(opt.force_ownertrust==-1)
2845 log_error("invalid ownertrust '%s'\n",pargs.r.ret_str);
2846 opt.force_ownertrust=0;
2849 case oLoadExtension:
2850 /* Dummy so that gpg 1.4 conf files can work. Should
2851 eventually be removed. */
2855 set_compliance_option (parse_compliance_option (pargs.r.ret_str));
2865 set_compliance_option (pargs.r_opt);
2868 case oRFC2440Text: opt.rfc2440_text=1; break;
2869 case oNoRFC2440Text: opt.rfc2440_text=0; break;
2873 opt.set_filename = pargs.r.ret_str;
2875 opt.set_filename = native_to_utf8(pargs.r.ret_str);
2877 case oForYourEyesOnly: eyes_only = 1; break;
2878 case oNoForYourEyesOnly: eyes_only = 0; break;
2880 add_policy_url(pargs.r.ret_str,0);
2881 add_policy_url(pargs.r.ret_str,1);
2883 case oSigPolicyURL: add_policy_url(pargs.r.ret_str,0); break;
2884 case oCertPolicyURL: add_policy_url(pargs.r.ret_str,1); break;
2885 case oShowPolicyURL:
2886 deprecated_warning(configname,configlineno,"--show-policy-url",
2887 "--list-options ","show-policy-urls");
2888 deprecated_warning(configname,configlineno,"--show-policy-url",
2889 "--verify-options ","show-policy-urls");
2890 opt.list_options|=LIST_SHOW_POLICY_URLS;
2891 opt.verify_options|=VERIFY_SHOW_POLICY_URLS;
2893 case oNoShowPolicyURL:
2894 deprecated_warning(configname,configlineno,"--no-show-policy-url",
2895 "--list-options ","no-show-policy-urls");
2896 deprecated_warning(configname,configlineno,"--no-show-policy-url",
2897 "--verify-options ","no-show-policy-urls");
2898 opt.list_options&=~LIST_SHOW_POLICY_URLS;
2899 opt.verify_options&=~VERIFY_SHOW_POLICY_URLS;
2901 case oSigKeyserverURL: add_keyserver_url(pargs.r.ret_str,0); break;
2902 case oUseEmbeddedFilename:
2903 opt.flags.use_embedded_filename=1;
2905 case oNoUseEmbeddedFilename:
2906 opt.flags.use_embedded_filename=0;
2909 if(pargs.r.ret_str[0])
2910 append_to_strlist(&opt.comments,pargs.r.ret_str);
2912 case oDefaultComment:
2913 deprecated_warning(configname,configlineno,
2914 "--default-comment","--no-comments","");
2917 free_strlist(opt.comments);
2920 case oThrowKeyids: opt.throw_keyids = 1; break;
2921 case oNoThrowKeyids: opt.throw_keyids = 0; break;
2923 deprecated_warning(configname,configlineno,"--show-photos",
2924 "--list-options ","show-photos");
2925 deprecated_warning(configname,configlineno,"--show-photos",
2926 "--verify-options ","show-photos");
2927 opt.list_options|=LIST_SHOW_PHOTOS;
2928 opt.verify_options|=VERIFY_SHOW_PHOTOS;
2931 deprecated_warning(configname,configlineno,"--no-show-photos",
2932 "--list-options ","no-show-photos");
2933 deprecated_warning(configname,configlineno,"--no-show-photos",
2934 "--verify-options ","no-show-photos");
2935 opt.list_options&=~LIST_SHOW_PHOTOS;
2936 opt.verify_options&=~VERIFY_SHOW_PHOTOS;
2938 case oPhotoViewer: opt.photo_viewer = pargs.r.ret_str; break;
2940 case oForceMDC: opt.force_mdc = 1; break;
2941 case oNoForceMDC: opt.force_mdc = 0; break;
2942 case oDisableMDC: opt.disable_mdc = 1; break;
2943 case oNoDisableMDC: opt.disable_mdc = 0; break;
2945 case oDisableSignerUID: opt.flags.disable_signer_uid = 1; break;
2947 case oS2KMode: opt.s2k_mode = pargs.r.ret_int; break;
2948 case oS2KDigest: s2k_digest_string = xstrdup(pargs.r.ret_str); break;
2949 case oS2KCipher: s2k_cipher_string = xstrdup(pargs.r.ret_str); break;
2951 if (pargs.r.ret_int)
2952 opt.s2k_count = encode_s2k_iterations (pargs.r.ret_int);
2954 opt.s2k_count = 0; /* Auto-calibrate when needed. */
2958 case oHiddenRecipient:
2959 case oRecipientFile:
2960 case oHiddenRecipientFile:
2961 /* Store the recipient. Note that we also store the
2962 * option as private data in the flags. This is achieved
2963 * by shifting the option value to the left so to keep
2964 * enough space for the flags. */
2965 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2966 sl->flags = (pargs.r_opt << PK_LIST_SHIFT);
2968 sl->flags |= PK_LIST_CONFIG;
2969 if (pargs.r_opt == oHiddenRecipient
2970 || pargs.r_opt == oHiddenRecipientFile)
2971 sl->flags |= PK_LIST_HIDDEN;
2972 if (pargs.r_opt == oRecipientFile
2973 || pargs.r_opt == oHiddenRecipientFile)
2974 sl->flags |= PK_LIST_FROM_FILE;
2975 any_explicit_recipient = 1;
2979 case oHiddenEncryptTo:
2980 /* Store an additional recipient. */
2981 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2982 sl->flags = ((pargs.r_opt << PK_LIST_SHIFT) | PK_LIST_ENCRYPT_TO);
2984 sl->flags |= PK_LIST_CONFIG;
2985 if (pargs.r_opt == oHiddenEncryptTo)
2986 sl->flags |= PK_LIST_HIDDEN;
2990 opt.no_encrypt_to = 1;
2992 case oEncryptToDefaultKey:
2993 opt.encrypt_to_default_key = configfp ? 2 : 1;
2997 add_to_strlist2 (&opt.secret_keys_to_try,
2998 pargs.r.ret_str, utf8_strings);
3001 case oMimemode: opt.mimemode = opt.textmode = 1; break;
3002 case oTextmodeShort: opt.textmode = 2; break;
3003 case oTextmode: opt.textmode=1; break;
3004 case oNoTextmode: opt.textmode=opt.mimemode=0; break;
3006 case oExpert: opt.expert = 1; break;
3007 case oNoExpert: opt.expert = 0; break;
3009 if(*pargs.r.ret_str!='\0')
3011 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
3012 log_error(_("'%s' is not a valid signature expiration\n"),
3015 opt.def_sig_expire=pargs.r.ret_str;
3018 case oAskSigExpire: opt.ask_sig_expire = 1; break;
3019 case oNoAskSigExpire: opt.ask_sig_expire = 0; break;
3020 case oDefCertExpire:
3021 if(*pargs.r.ret_str!='\0')
3023 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
3024 log_error(_("'%s' is not a valid signature expiration\n"),
3027 opt.def_cert_expire=pargs.r.ret_str;
3030 case oAskCertExpire: opt.ask_cert_expire = 1; break;
3031 case oNoAskCertExpire: opt.ask_cert_expire = 0; break;
3032 case oDefCertLevel: opt.def_cert_level=pargs.r.ret_int; break;
3033 case oMinCertLevel: opt.min_cert_level=pargs.r.ret_int; break;
3034 case oAskCertLevel: opt.ask_cert_level = 1; break;
3035 case oNoAskCertLevel: opt.ask_cert_level = 0; break;
3036 case oLocalUser: /* store the local users */
3037 sl = add_to_strlist2( &locusr, pargs.r.ret_str, utf8_strings );
3038 sl->flags = (pargs.r_opt << PK_LIST_SHIFT);
3040 sl->flags |= PK_LIST_CONFIG;
3044 char *mbox = mailbox_from_userid (pargs.r.ret_str);
3046 log_error (_("\"%s\" is not a proper mail address\n"),
3050 add_to_strlist (&opt.sender_list, mbox);
3056 /* this is the -z command line option */
3057 opt.compress_level = opt.bz2_compress_level = pargs.r.ret_int;
3059 case oCompressLevel: opt.compress_level = pargs.r.ret_int; break;
3060 case oBZ2CompressLevel: opt.bz2_compress_level = pargs.r.ret_int; break;
3061 case oBZ2DecompressLowmem: opt.bz2_decompress_lowmem=1; break;
3063 set_passphrase_from_string(pargs.r.ret_str);
3066 pwfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
3068 case oPassphraseFile:
3069 pwfd = open_info_file (pargs.r.ret_str, 0, 1);
3071 case oPassphraseRepeat:
3072 opt.passphrase_repeat = pargs.r.ret_int;
3076 opt.pinentry_mode = parse_pinentry_mode (pargs.r.ret_str);
3077 if (opt.pinentry_mode == -1)
3078 log_error (_("invalid pinentry mode '%s'\n"), pargs.r.ret_str);
3082 opt.command_fd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
3083 if (! gnupg_fd_valid (opt.command_fd))
3084 log_fatal ("command-fd is invalid: %s\n", strerror (errno));
3087 opt.command_fd = open_info_file (pargs.r.ret_str, 0, 1);
3090 def_cipher_string = xstrdup(pargs.r.ret_str);
3093 def_digest_string = xstrdup(pargs.r.ret_str);
3096 /* If it is all digits, stick a Z in front of it for
3097 later. This is for backwards compatibility with
3098 versions that took the compress algorithm number. */
3100 char *pt=pargs.r.ret_str;
3103 if (!isascii (*pt) || !isdigit (*pt))
3111 compress_algo_string=xmalloc(strlen(pargs.r.ret_str)+2);
3112 strcpy(compress_algo_string,"Z");
3113 strcat(compress_algo_string,pargs.r.ret_str);
3116 compress_algo_string = xstrdup(pargs.r.ret_str);
3119 case oCertDigestAlgo:
3120 cert_digest_string = xstrdup(pargs.r.ret_str);
3124 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
3127 case oRequireSecmem: require_secmem=1; break;
3128 case oNoRequireSecmem: require_secmem=0; break;
3129 case oNoPermissionWarn: opt.no_perm_warn=1; break;
3130 case oNoMDCWarn: opt.no_mdc_warn=1; break;
3131 case oDisplayCharset:
3132 if( set_native_charset( pargs.r.ret_str ) )
3133 log_error(_("'%s' is not a valid character set\n"),
3136 case oNotDashEscaped: opt.not_dash_escaped = 1; break;
3137 case oEscapeFrom: opt.escape_from = 1; break;
3138 case oNoEscapeFrom: opt.escape_from = 0; break;
3139 case oLockOnce: opt.lock_once = 1; break;
3146 #else /* __riscos__ */
3147 riscos_not_implemented("lock-multiple");
3148 #endif /* __riscos__ */
3152 keyserver_spec_t keyserver;
3153 keyserver = parse_keyserver_uri (pargs.r.ret_str, 0);
3155 log_error (_("could not parse keyserver URL\n"));
3158 /* We only support a single keyserver. Later ones
3159 override earlier ones. (Since we parse the
3160 config file first and then the command line
3161 arguments, the command line takes
3164 free_keyserver_spec (opt.keyserver);
3165 opt.keyserver = keyserver;
3169 case oKeyServerOptions:
3170 if(!parse_keyserver_options(pargs.r.ret_str))
3173 log_error(_("%s:%d: invalid keyserver options\n"),
3174 configname,configlineno);
3176 log_error(_("invalid keyserver options\n"));
3179 case oImportOptions:
3180 if(!parse_import_options(pargs.r.ret_str,&opt.import_options,1))
3183 log_error(_("%s:%d: invalid import options\n"),
3184 configname,configlineno);
3186 log_error(_("invalid import options\n"));
3190 rc = parse_and_set_import_filter (pargs.r.ret_str);
3192 log_error (_("invalid filter option: %s\n"), gpg_strerror (rc));
3194 case oExportOptions:
3195 if(!parse_export_options(pargs.r.ret_str,&opt.export_options,1))
3198 log_error(_("%s:%d: invalid export options\n"),
3199 configname,configlineno);
3201 log_error(_("invalid export options\n"));
3205 rc = parse_and_set_export_filter (pargs.r.ret_str);
3207 log_error (_("invalid filter option: %s\n"), gpg_strerror (rc));
3210 if(!parse_list_options(pargs.r.ret_str))
3213 log_error(_("%s:%d: invalid list options\n"),
3214 configname,configlineno);
3216 log_error(_("invalid list options\n"));
3219 case oVerifyOptions:
3221 struct parse_options vopts[]=
3223 {"show-photos",VERIFY_SHOW_PHOTOS,NULL,
3224 N_("display photo IDs during signature verification")},
3225 {"show-policy-urls",VERIFY_SHOW_POLICY_URLS,NULL,
3226 N_("show policy URLs during signature verification")},
3227 {"show-notations",VERIFY_SHOW_NOTATIONS,NULL,
3228 N_("show all notations during signature verification")},
3229 {"show-std-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
3230 N_("show IETF standard notations during signature verification")},
3231 {"show-standard-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
3233 {"show-user-notations",VERIFY_SHOW_USER_NOTATIONS,NULL,
3234 N_("show user-supplied notations during signature verification")},
3235 {"show-keyserver-urls",VERIFY_SHOW_KEYSERVER_URLS,NULL,
3236 N_("show preferred keyserver URLs during signature verification")},
3237 {"show-uid-validity",VERIFY_SHOW_UID_VALIDITY,NULL,
3238 N_("show user ID validity during signature verification")},
3239 {"show-unusable-uids",VERIFY_SHOW_UNUSABLE_UIDS,NULL,
3240 N_("show revoked and expired user IDs in signature verification")},
3241 {"show-primary-uid-only",VERIFY_SHOW_PRIMARY_UID_ONLY,NULL,
3242 N_("show only the primary user ID in signature verification")},
3243 {"pka-lookups",VERIFY_PKA_LOOKUPS,NULL,
3244 N_("validate signatures with PKA data")},
3245 {"pka-trust-increase",VERIFY_PKA_TRUST_INCREASE,NULL,
3246 N_("elevate the trust of signatures with valid PKA data")},
3250 if(!parse_options(pargs.r.ret_str,&opt.verify_options,vopts,1))
3253 log_error(_("%s:%d: invalid verify options\n"),
3254 configname,configlineno);
3256 log_error(_("invalid verify options\n"));
3260 case oTempDir: opt.temp_dir=pargs.r.ret_str; break;
3262 if(set_exec_path(pargs.r.ret_str))
3263 log_error(_("unable to set exec-path to %s\n"),pargs.r.ret_str);
3265 opt.exec_path_set=1;
3268 add_notation_data( pargs.r.ret_str, 0 );
3269 add_notation_data( pargs.r.ret_str, 1 );
3271 case oSigNotation: add_notation_data( pargs.r.ret_str, 0 ); break;
3272 case oCertNotation: add_notation_data( pargs.r.ret_str, 1 ); break;
3274 deprecated_warning(configname,configlineno,"--show-notation",
3275 "--list-options ","show-notations");
3276 deprecated_warning(configname,configlineno,"--show-notation",
3277 "--verify-options ","show-notations");
3278 opt.list_options|=LIST_SHOW_NOTATIONS;
3279 opt.verify_options|=VERIFY_SHOW_NOTATIONS;
3281 case oNoShowNotation:
3282 deprecated_warning(configname,configlineno,"--no-show-notation",
3283 "--list-options ","no-show-notations");
3284 deprecated_warning(configname,configlineno,"--no-show-notation",
3285 "--verify-options ","no-show-notations");
3286 opt.list_options&=~LIST_SHOW_NOTATIONS;
3287 opt.verify_options&=~VERIFY_SHOW_NOTATIONS;
3289 case oUtf8Strings: utf8_strings = 1; break;
3290 case oNoUtf8Strings: utf8_strings = 0; break;
3291 case oDisableCipherAlgo:
3293 int algo = string_to_cipher_algo (pargs.r.ret_str);
3294 gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
3297 case oDisablePubkeyAlgo:
3299 int algo = gcry_pk_map_name (pargs.r.ret_str);
3300 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
3303 case oNoSigCache: opt.no_sig_cache = 1; break;
3304 case oAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid = 1; break;
3305 case oNoAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid=0; break;
3306 case oAllowFreeformUID: opt.allow_freeform_uid = 1; break;
3307 case oNoAllowFreeformUID: opt.allow_freeform_uid = 0; break;
3308 case oNoLiteral: opt.no_literal = 1; break;
3309 case oSetFilesize: opt.set_filesize = pargs.r.ret_ulong; break;
3310 case oFastListMode: opt.fast_list_mode = 1; break;
3311 case oFixedListMode: /* Dummy */ break;
3312 case oLegacyListMode: opt.legacy_list_mode = 1; break;
3313 case oPrintPKARecords: print_pka_records = 1; break;
3314 case oPrintDANERecords: print_dane_records = 1; break;
3315 case oListOnly: opt.list_only=1; break;
3316 case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
3317 case oIgnoreValidFrom: opt.ignore_valid_from = 1; break;
3318 case oIgnoreCrcError: opt.ignore_crc_error = 1; break;
3319 case oIgnoreMDCError: opt.ignore_mdc_error = 1; break;
3320 case oNoRandomSeedFile: use_random_seed = 0; break;
3321 case oAutoKeyRetrieve:
3322 case oNoAutoKeyRetrieve:
3323 if(pargs.r_opt==oAutoKeyRetrieve)
3324 opt.keyserver_options.options|=KEYSERVER_AUTO_KEY_RETRIEVE;
3326 opt.keyserver_options.options&=~KEYSERVER_AUTO_KEY_RETRIEVE;
3328 case oShowSessionKey: opt.show_session_key = 1; break;
3329 case oOverrideSessionKey:
3330 opt.override_session_key = pargs.r.ret_str;
3332 case oOverrideSessionKeyFD:
3333 ovrseskeyfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
3336 deprecated_warning(configname,configlineno,"--merge-only",
3337 "--import-options ","merge-only");
3338 opt.import_options|=IMPORT_MERGE_ONLY;
3340 case oAllowSecretKeyImport: /* obsolete */ break;
3341 case oTryAllSecrets: opt.try_all_secrets = 1; break;
3342 case oTrustedKey: register_trusted_key( pargs.r.ret_str ); break;
3344 case oEnableSpecialFilenames:
3345 enable_special_filenames ();
3348 case oNoExpensiveTrustChecks: opt.no_expensive_trust_checks=1; break;
3349 case oAutoCheckTrustDB: opt.no_auto_check_trustdb=0; break;
3350 case oNoAutoCheckTrustDB: opt.no_auto_check_trustdb=1; break;
3351 case oPreservePermissions: opt.preserve_permissions=1; break;
3352 case oDefaultPreferenceList:
3353 opt.def_preference_list = pargs.r.ret_str;
3355 case oDefaultKeyserverURL:
3357 keyserver_spec_t keyserver;
3358 keyserver = parse_keyserver_uri (pargs.r.ret_str,1 );
3360 log_error (_("could not parse keyserver URL\n"));
3362 free_keyserver_spec (keyserver);
3364 opt.def_keyserver_url = pargs.r.ret_str;
3367 case oPersonalCipherPreferences:
3368 pers_cipher_list=pargs.r.ret_str;
3370 case oPersonalDigestPreferences:
3371 pers_digest_list=pargs.r.ret_str;
3373 case oPersonalCompressPreferences:
3374 pers_compress_list=pargs.r.ret_str;
3376 case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
3377 case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break;
3379 additional_weak_digest(pargs.r.ret_str);
3382 opt.unwrap_encryption = 1;
3384 case oOnlySignTextIDs:
3385 opt.only_sign_text_ids = 1;
3389 set_opt_session_env ("DISPLAY", pargs.r.ret_str);
3392 set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
3395 set_opt_session_env ("TERM", pargs.r.ret_str);
3398 set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
3401 case oLCctype: opt.lc_ctype = pargs.r.ret_str; break;
3402 case oLCmessages: opt.lc_messages = pargs.r.ret_str; break;
3404 case oGroup: add_group(pargs.r.ret_str); break;
3405 case oUnGroup: rm_group(pargs.r.ret_str); break;
3407 while(opt.grouplist)
3409 struct groupitem *iter=opt.grouplist;
3410 free_strlist(iter->values);
3411 opt.grouplist=opt.grouplist->next;
3421 case oMangleDosFilenames: opt.mangle_dos_filenames = 1; break;
3422 case oNoMangleDosFilenames: opt.mangle_dos_filenames = 0; break;
3423 case oEnableProgressFilter: opt.enable_progress_filter = 1; break;
3424 case oMultifile: multifile=1; break;
3426 if(ascii_strcasecmp(pargs.r.ret_str,"short")==0)
3427 opt.keyid_format=KF_SHORT;
3428 else if(ascii_strcasecmp(pargs.r.ret_str,"long")==0)
3429 opt.keyid_format=KF_LONG;
3430 else if(ascii_strcasecmp(pargs.r.ret_str,"0xshort")==0)
3431 opt.keyid_format=KF_0xSHORT;
3432 else if(ascii_strcasecmp(pargs.r.ret_str,"0xlong")==0)
3433 opt.keyid_format=KF_0xLONG;
3434 else if(ascii_strcasecmp(pargs.r.ret_str,"none")==0)
3435 opt.keyid_format = KF_NONE;
3437 log_error("unknown keyid-format '%s'\n",pargs.r.ret_str);
3440 case oExitOnStatusWriteError:
3441 opt.exit_on_status_write_error = 1;
3444 case oLimitCardInsertTries:
3445 opt.limit_card_insert_tries = pargs.r.ret_int;
3448 case oRequireCrossCert: opt.flags.require_cross_cert=1; break;
3449 case oNoRequireCrossCert: opt.flags.require_cross_cert=0; break;
3451 case oAutoKeyLocate:
3452 if(!parse_auto_key_locate(pargs.r.ret_str))
3455 log_error(_("%s:%d: invalid auto-key-locate list\n"),
3456 configname,configlineno);
3458 log_error(_("invalid auto-key-locate list\n"));
3461 case oNoAutoKeyLocate:
3465 case oEnableLargeRSA:
3466 #if SECMEM_BUFFER_SIZE >= 65536
3467 opt.flags.large_rsa=1;
3470 log_info("%s:%d: WARNING: gpg not built with large secure "
3471 "memory buffer. Ignoring enable-large-rsa\n",
3472 configname,configlineno);
3474 log_info("WARNING: gpg not built with large secure "
3475 "memory buffer. Ignoring --enable-large-rsa\n");
3476 #endif /* SECMEM_BUFFER_SIZE >= 65536 */
3478 case oDisableLargeRSA: opt.flags.large_rsa=0;
3481 case oEnableDSA2: opt.flags.dsa2=1; break;
3482 case oDisableDSA2: opt.flags.dsa2=0; break;
3484 case oAllowMultisigVerification:
3485 case oAllowMultipleMessages:
3486 opt.flags.allow_multiple_messages=1;
3489 case oNoAllowMultipleMessages:
3490 opt.flags.allow_multiple_messages=0;
3493 case oAllowWeakDigestAlgos:
3494 opt.flags.allow_weak_digest_algos = 1;
3497 case oFakedSystemTime:
3499 size_t len = strlen (pargs.r.ret_str);
3503 if (len > 0 && pargs.r.ret_str[len-1] == '!')
3506 pargs.r.ret_str[len-1] = '\0';
3509 faked_time = isotime2epoch (pargs.r.ret_str);
3510 if (faked_time == (time_t)(-1))
3511 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
3512 gnupg_set_time (faked_time, freeze);
3516 case oNoAutostart: opt.autostart = 0; break;
3518 case oDefaultNewKeyAlgo:
3519 opt.def_new_key_algo = pargs.r.ret_str;
3525 pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
3534 /* Remember the first config file name. */
3535 if (!save_configname)
3536 save_configname = configname;
3542 xfree(configname); configname = NULL;
3543 if (log_get_errorcount (0))
3546 /* The command --gpgconf-list is pretty simple and may be called
3547 directly after the option parsing. */
3548 if (cmd == aGPGConfList)
3550 gpgconf_list (save_configname ? save_configname : default_configname);
3553 xfree (save_configname);
3554 xfree (default_configname);
3556 if (print_dane_records)
3557 log_error ("invalid option \"%s\"; use \"%s\" instead\n",
3558 "--print-dane-records",
3559 "--export-options export-dane");
3560 if (print_pka_records)
3561 log_error ("invalid option \"%s\"; use \"%s\" instead\n",
3562 "--print-pks-records",
3563 "--export-options export-pka");
3564 if (log_get_errorcount (0))
3573 es_fprintf (es_stderr, "%s %s; %s\n",
3574 strusage(11), strusage(13), strusage(14) );
3575 es_fprintf (es_stderr, "%s\n", strusage(15) );
3577 #ifdef IS_DEVELOPMENT_VERSION
3582 if((s=strusage(25)))
3584 if((s=strusage(26)))
3586 if((s=strusage(27)))
3591 /* FIXME: We should use logging to a file only in server mode;
3592 however we have not yet implemetyed that. Thus we try to get
3593 away with --batch as indication for logging to file
3595 if (logfile && opt.batch)
3597 log_set_file (logfile);
3598 log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
3601 if (opt.verbose > 2)
3602 log_info ("using character set '%s'\n", get_native_charset ());
3604 if( may_coredump && !opt.quiet )
3605 log_info(_("WARNING: program may create a core file!\n"));
3607 if (opt.flags.rfc4880bis)
3608 log_info ("WARNING: using experimental features from RFC4880bis!\n");
3611 opt.mimemode = 0; /* This will use text mode instead. */
3615 if (opt.set_filename)
3616 log_info(_("WARNING: %s overrides %s\n"),
3617 "--for-your-eyes-only","--set-filename");
3619 opt.set_filename="_CONSOLE";
3622 if (opt.no_literal) {
3623 log_info(_("Note: %s is not for normal use!\n"), "--no-literal");
3625 log_error(_("%s not allowed with %s!\n"),
3626 "--textmode", "--no-literal" );
3627 if (opt.set_filename)
3628 log_error(_("%s makes no sense with %s!\n"),
3629 eyes_only?"--for-your-eyes-only":"--set-filename",
3634 if (opt.set_filesize)
3635 log_info(_("Note: %s is not for normal use!\n"), "--set-filesize");
3639 if (gnupg_faked_time_p ())
3641 gnupg_isotime_t tbuf;
3643 log_info (_("WARNING: running with faked system time: "));
3644 gnupg_get_isotime (tbuf);
3645 dump_isotime (tbuf);
3649 /* Print a warning if an argument looks like an option. */
3650 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
3654 for (i=0; i < argc; i++)
3655 if (argv[i][0] == '-' && argv[i][1] == '-')
3656 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
3660 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
3662 if(require_secmem && !got_secmem)
3664 log_info(_("will not run with insecure memory due to %s\n"),
3665 "--require-secmem");
3669 set_debug (debug_level);
3671 log_clock ("start");
3673 /* Do these after the switch(), so they can override settings. */
3676 /* That does not anymore work because we have no more support
3677 for v3 signatures. */
3680 opt.ask_sig_expire=0;
3684 /* That does not anymore work because we have no more support
3685 for v3 signatures. */
3687 opt.ask_sig_expire=0;
3695 if( def_cipher_string ) {
3696 opt.def_cipher_algo = string_to_cipher_algo (def_cipher_string);
3697 xfree(def_cipher_string); def_cipher_string = NULL;
3698 if ( openpgp_cipher_test_algo (opt.def_cipher_algo) )
3699 log_error(_("selected cipher algorithm is invalid\n"));
3701 if( def_digest_string ) {
3702 opt.def_digest_algo = string_to_digest_algo (def_digest_string);
3703 xfree(def_digest_string); def_digest_string = NULL;
3704 if ( openpgp_md_test_algo (opt.def_digest_algo) )
3705 log_error(_("selected digest algorithm is invalid\n"));
3707 if( compress_algo_string ) {
3708 opt.compress_algo = string_to_compress_algo(compress_algo_string);
3709 xfree(compress_algo_string); compress_algo_string = NULL;
3710 if( check_compress_algo(opt.compress_algo) )
3711 log_error(_("selected compression algorithm is invalid\n"));
3713 if( cert_digest_string ) {
3714 opt.cert_digest_algo = string_to_digest_algo (cert_digest_string);
3715 xfree(cert_digest_string); cert_digest_string = NULL;
3716 if (openpgp_md_test_algo(opt.cert_digest_algo))
3717 log_error(_("selected certification digest algorithm is invalid\n"));
3719 if( s2k_cipher_string ) {
3720 opt.s2k_cipher_algo = string_to_cipher_algo (s2k_cipher_string);
3721 xfree(s2k_cipher_string); s2k_cipher_string = NULL;
3722 if (openpgp_cipher_test_algo (opt.s2k_cipher_algo))
3723 log_error(_("selected cipher algorithm is invalid\n"));
3725 if( s2k_digest_string ) {
3726 opt.s2k_digest_algo = string_to_digest_algo (s2k_digest_string);
3727 xfree(s2k_digest_string); s2k_digest_string = NULL;
3728 if (openpgp_md_test_algo(opt.s2k_digest_algo))
3729 log_error(_("selected digest algorithm is invalid\n"));
3731 if( opt.completes_needed < 1 )
3732 log_error(_("completes-needed must be greater than 0\n"));
3733 if( opt.marginals_needed < 2 )
3734 log_error(_("marginals-needed must be greater than 1\n"));
3735 if( opt.max_cert_depth < 1 || opt.max_cert_depth > 255 )
3736 log_error(_("max-cert-depth must be in the range from 1 to 255\n"));
3737 if(opt.def_cert_level<0 || opt.def_cert_level>3)
3738 log_error(_("invalid default-cert-level; must be 0, 1, 2, or 3\n"));
3739 if( opt.min_cert_level < 1 || opt.min_cert_level > 3 )
3740 log_error(_("invalid min-cert-level; must be 1, 2, or 3\n"));
3741 switch( opt.s2k_mode ) {
3743 log_info(_("Note: simple S2K mode (0) is strongly discouraged\n"));
3745 case 1: case 3: break;
3747 log_error(_("invalid S2K mode; must be 0, 1 or 3\n"));
3750 /* This isn't actually needed, but does serve to error out if the
3751 string is invalid. */
3752 if(opt.def_preference_list &&
3753 keygen_set_std_prefs(opt.def_preference_list,0))
3754 log_error(_("invalid default preferences\n"));
3756 if(pers_cipher_list &&
3757 keygen_set_std_prefs(pers_cipher_list,PREFTYPE_SYM))
3758 log_error(_("invalid personal cipher preferences\n"));
3760 if(pers_digest_list &&
3761 keygen_set_std_prefs(pers_digest_list,PREFTYPE_HASH))
3762 log_error(_("invalid personal digest preferences\n"));
3764 if(pers_compress_list &&
3765 keygen_set_std_prefs(pers_compress_list,PREFTYPE_ZIP))
3766 log_error(_("invalid personal compress preferences\n"));
3768 /* We don't support all possible commands with multifile yet */
3779 cmdname="--sign --encrypt";
3782 cmdname="--clear-sign";
3785 cmdname="--detach-sign";
3788 cmdname="--symmetric";
3791 cmdname="--symmetric --encrypt";
3802 log_error(_("%s does not yet work with %s\n"),cmdname,"--multifile");
3805 if( log_get_errorcount(0) )
3808 if(opt.compress_level==0)
3809 opt.compress_algo=COMPRESS_ALGO_NONE;
3811 /* Check our chosen algorithms against the list of legal
3816 const char *badalg=NULL;
3817 preftype_t badtype=PREFTYPE_NONE;
3819 if(opt.def_cipher_algo
3820 && !algo_available(PREFTYPE_SYM,opt.def_cipher_algo,NULL))
3822 badalg = openpgp_cipher_algo_name (opt.def_cipher_algo);
3823 badtype = PREFTYPE_SYM;
3825 else if(opt.def_digest_algo
3826 && !algo_available(PREFTYPE_HASH,opt.def_digest_algo,NULL))
3828 badalg = gcry_md_algo_name (opt.def_digest_algo);
3829 badtype = PREFTYPE_HASH;
3831 else if(opt.cert_digest_algo
3832 && !algo_available(PREFTYPE_HASH,opt.cert_digest_algo,NULL))
3834 badalg = gcry_md_algo_name (opt.cert_digest_algo);
3835 badtype = PREFTYPE_HASH;
3837 else if(opt.compress_algo!=-1
3838 && !algo_available(PREFTYPE_ZIP,opt.compress_algo,NULL))
3840 badalg = compress_algo_to_string(opt.compress_algo);
3841 badtype = PREFTYPE_ZIP;
3849 log_info(_("you may not use cipher algorithm '%s'"
3850 " while in %s mode\n"),
3851 badalg,compliance_option_string());
3854 log_info(_("you may not use digest algorithm '%s'"
3855 " while in %s mode\n"),
3856 badalg,compliance_option_string());
3859 log_info(_("you may not use compression algorithm '%s'"
3860 " while in %s mode\n"),
3861 badalg,compliance_option_string());
3867 compliance_failure();
3871 /* Set the random seed file. */
3872 if( use_random_seed ) {
3873 char *p = make_filename (gnupg_homedir (), "random_seed", NULL );
3874 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
3875 if (!access (p, F_OK))
3876 register_secured_file (p);
3880 /* If there is no command but the --fingerprint is given, default
3881 to the --list-keys command. */
3882 if (!cmd && fpr_maybe_cmd)
3884 set_cmd (&cmd, aListKeys);
3888 if( opt.verbose > 1 )
3889 set_packet_list_mode(1);
3891 /* Add the keyrings, but not for some special commands. We always
3892 * need to add the keyrings if we are running under SELinux, this
3893 * is so that the rings are added to the list of secured files.
3894 * We do not add any keyring if --no-keyring has been used. */
3895 if (default_keyring >= 0
3896 && (ALWAYS_ADD_KEYRINGS
3897 || (cmd != aDeArmor && cmd != aEnArmor && cmd != aGPGConfTest)))
3899 if (!nrings || default_keyring > 0) /* Add default ring. */
3900 keydb_add_resource ("pubring" EXTSEP_S GPGEXT_GPG,
3901 KEYDB_RESOURCE_FLAG_DEFAULT);
3902 for (sl = nrings; sl; sl = sl->next )
3903 keydb_add_resource (sl->d, sl->flags);
3905 FREE_STRLIST(nrings);
3907 if (opt.pinentry_mode == PINENTRY_MODE_LOOPBACK)
3908 /* In loopback mode, never ask for the password multiple
3911 opt.passphrase_repeat = 0;
3914 if (cmd == aGPGConfTest)
3918 if (pwfd != -1) /* Read the passphrase now. */
3919 read_passphrase_from_fd (pwfd);
3921 if (ovrseskeyfd != -1 ) /* Read the sessionkey now. */
3922 read_sessionkey_from_fd (ovrseskeyfd);
3924 fname = argc? *argv : NULL;
3926 if(fname && utf8_strings)
3927 opt.flags.utf8_filename=1;
3929 ctrl = xcalloc (1, sizeof *ctrl);
3930 gpg_init_default_ctrl (ctrl);
3932 #ifndef NO_TRUST_MODELS
3942 case aListGcryptConfig:
3945 case aExportOwnerTrust:
3946 rc = setup_trustdb (0, trustdb_name);
3949 rc = setup_trustdb (argc? 1:0, trustdb_name);
3952 /* If we are using TM_ALWAYS, we do not need to create the
3954 rc = setup_trustdb (opt.trust_model != TM_ALWAYS, trustdb_name);
3958 log_error (_("failed to initialize the TrustDB: %s\n"),
3960 #endif /*!NO_TRUST_MODELS*/
3969 if (!opt.quiet && any_explicit_recipient)
3970 log_info (_("WARNING: recipients (-r) given "
3971 "without using public key encryption\n"));
3978 /* Check for certain command whether we need to migrate a
3979 secring.gpg to the gpg-agent. */
3982 case aListSecretKeys:
3993 case aDeleteSecretKeys:
3994 case aDeleteSecretAndPublicKeys:
4003 case aExportSecretSub:
4008 migrate_secring (ctrl);
4011 if (opt.with_secret)
4012 migrate_secring (ctrl);
4018 /* The command dispatcher. */
4025 case aStore: /* only store the file */
4027 wrong_args("--store [filename]");
4028 if( (rc = encrypt_store(fname)) )
4030 write_status_failure ("store", rc);
4031 log_error ("storing '%s' failed: %s\n",
4032 print_fname_stdin(fname),gpg_strerror (rc) );
4035 case aSym: /* encrypt the given file only with the symmetric cipher */
4037 wrong_args("--symmetric [filename]");
4038 if( (rc = encrypt_symmetric(fname)) )
4040 write_status_failure ("symencrypt", rc);
4041 log_error (_("symmetric encryption of '%s' failed: %s\n"),
4042 print_fname_stdin(fname),gpg_strerror (rc) );
4046 case aEncr: /* encrypt the given file */
4048 encrypt_crypt_files (ctrl, argc, argv, remusr);
4052 wrong_args("--encrypt [filename]");
4053 if( (rc = encrypt_crypt (ctrl, -1, fname, remusr, 0, NULL, -1)) )
4055 write_status_failure ("encrypt", rc);
4056 log_error("%s: encryption failed: %s\n",
4057 print_fname_stdin(fname), gpg_strerror (rc) );
4063 /* This works with PGP 8 in the sense that it acts just like a
4064 symmetric message. It doesn't work at all with 2 or 6. It
4065 might work with 7, but alas, I don't have a copy to test
4068 wrong_args("--symmetric --encrypt [filename]");
4069 else if(opt.s2k_mode==0)
4070 log_error(_("you cannot use --symmetric --encrypt"
4071 " with --s2k-mode 0\n"));
4072 else if(PGP6 || PGP7)
4073 log_error(_("you cannot use --symmetric --encrypt"
4074 " while in %s mode\n"),compliance_option_string());
4077 if( (rc = encrypt_crypt (ctrl, -1, fname, remusr, 1, NULL, -1)) )
4079 write_status_failure ("encrypt", rc);
4080 log_error ("%s: encryption failed: %s\n",
4081 print_fname_stdin(fname), gpg_strerror (rc) );
4086 case aSign: /* sign the given file */
4088 if( detached_sig ) { /* sign all files */
4089 for( ; argc; argc--, argv++ )
4090 add_to_strlist( &sl, *argv );
4094 wrong_args("--sign [filename]");
4096 sl = xmalloc_clear( sizeof *sl + strlen(fname));
4097 strcpy(sl->d, fname);
4100 if ((rc = sign_file (ctrl, sl, detached_sig, locusr, 0, NULL, NULL)))
4102 write_status_failure ("sign", rc);
4103 log_error ("signing failed: %s\n", gpg_strerror (rc) );
4108 case aSignEncr: /* sign and encrypt the given file */
4110 wrong_args("--sign --encrypt [filename]");
4112 sl = xmalloc_clear( sizeof *sl + strlen(fname));
4113 strcpy(sl->d, fname);
4117 if ((rc = sign_file (ctrl, sl, detached_sig, locusr, 1, remusr, NULL)))
4119 write_status_failure ("sign-encrypt", rc);
4120 log_error("%s: sign+encrypt failed: %s\n",
4121 print_fname_stdin(fname), gpg_strerror (rc) );
4126 case aSignEncrSym: /* sign and encrypt the given file */
4128 wrong_args("--symmetric --sign --encrypt [filename]");
4129 else if(opt.s2k_mode==0)
4130 log_error(_("you cannot use --symmetric --sign --encrypt"
4131 " with --s2k-mode 0\n"));
4132 else if(PGP6 || PGP7)
4133 log_error(_("you cannot use --symmetric --sign --encrypt"
4134 " while in %s mode\n"),compliance_option_string());
4139 sl = xmalloc_clear( sizeof *sl + strlen(fname));
4140 strcpy(sl->d, fname);
4144 if ((rc = sign_file (ctrl, sl, detached_sig, locusr,
4147 write_status_failure ("sign-encrypt", rc);
4148 log_error("%s: symmetric+sign+encrypt failed: %s\n",
4149 print_fname_stdin(fname), gpg_strerror (rc) );
4155 case aSignSym: /* sign and conventionally encrypt the given file */
4157 wrong_args("--sign --symmetric [filename]");
4158 rc = sign_symencrypt_file (ctrl, fname, locusr);
4161 write_status_failure ("sign-symencrypt", rc);
4162 log_error("%s: sign+symmetric failed: %s\n",
4163 print_fname_stdin(fname), gpg_strerror (rc) );
4167 case aClearsign: /* make a clearsig */
4169 wrong_args("--clear-sign [filename]");
4170 if( (rc = clearsign_file (ctrl, fname, locusr, NULL)) )
4172 write_status_failure ("sign", rc);
4173 log_error("%s: clear-sign failed: %s\n",
4174 print_fname_stdin(fname), gpg_strerror (rc) );
4181 if ((rc = verify_files (ctrl, argc, argv)))
4182 log_error("verify files failed: %s\n", gpg_strerror (rc) );
4186 if ((rc = verify_signatures (ctrl, argc, argv)))
4187 log_error("verify signatures failed: %s\n", gpg_strerror (rc) );
4190 write_status_failure ("verify", rc);
4195 decrypt_messages (ctrl, argc, argv);
4199 wrong_args("--decrypt [filename]");
4200 if( (rc = decrypt_message (ctrl, fname) ))
4202 write_status_failure ("decrypt", rc);
4203 log_error("decrypt_message failed: %s\n", gpg_strerror (rc) );
4209 case aQuickLSignKey:
4214 wrong_args ("--quick-[l]sign-key fingerprint [userids]");
4215 fpr = *argv++; argc--;
4217 for( ; argc; argc--, argv++)
4218 append_to_strlist2 (&sl, *argv, utf8_strings);
4219 keyedit_quick_sign (ctrl, fpr, sl, locusr, (cmd == aQuickLSignKey));
4226 wrong_args("--sign-key user-id");
4230 wrong_args("--lsign-key user-id");
4236 append_to_strlist(&sl,"sign");
4237 else if(cmd==aLSignKey)
4238 append_to_strlist(&sl,"lsign");
4242 append_to_strlist( &sl, "save" );
4243 username = make_username( fname );
4244 keyedit_menu (ctrl, username, locusr, sl, 0, 0 );
4249 case aEditKey: /* Edit a key signature */
4251 wrong_args("--edit-key user-id [commands]");
4252 username = make_username( fname );
4255 for( argc--, argv++ ; argc; argc--, argv++ )
4256 append_to_strlist( &sl, *argv );
4257 keyedit_menu (ctrl, username, locusr, sl, 0, 1 );
4261 keyedit_menu (ctrl, username, locusr, NULL, 0, 1 );
4267 wrong_args("--change-passphrase <user-id>");
4270 username = make_username (fname);
4271 keyedit_passwd (ctrl, username);
4277 case aDeleteSecretKeys:
4278 case aDeleteSecretAndPublicKeys:
4280 /* I'm adding these in reverse order as add_to_strlist2
4281 reverses them again, and it's easier to understand in the
4283 for( ; argc; argc-- )
4284 add_to_strlist2( &sl, argv[argc-1], utf8_strings );
4285 delete_keys(sl,cmd==aDeleteSecretKeys,cmd==aDeleteSecretAndPublicKeys);
4295 for( ; argc; argc--, argv++ )
4296 add_to_strlist2( &sl, *argv, utf8_strings );
4297 public_key_list (ctrl, sl, 0);
4300 case aListSecretKeys:
4302 for( ; argc; argc--, argv++ )
4303 add_to_strlist2( &sl, *argv, utf8_strings );
4304 secret_key_list (ctrl, sl);
4309 for (; argc; argc--, argv++)
4310 add_to_strlist2( &sl, *argv, utf8_strings );
4311 public_key_list (ctrl, sl, 1);
4317 const char *x_algo, *x_usage, *x_expire;
4319 if (argc < 1 || argc > 4)
4320 wrong_args("--quick-generate-key USER-ID [ALGO [USAGE [EXPIRE]]]");
4321 username = make_username (fname);
4328 x_algo = *argv++; argc--;
4331 x_usage = *argv++; argc--;
4334 x_expire = *argv++; argc--;
4338 quick_generate_keypair (ctrl, username, x_algo, x_usage, x_expire);
4343 case aKeygen: /* generate a key */
4346 wrong_args("--generate-key [parameterfile]");
4347 generate_keypair (ctrl, 0, argc? *argv : NULL, NULL, 0);
4350 if (opt.command_fd != -1 && argc)
4353 wrong_args("--generate-key [parameterfile]");
4356 generate_keypair (ctrl, 0, argc? *argv : NULL, NULL, 0);
4359 wrong_args ("--generate-key");
4361 generate_keypair (ctrl, 0, NULL, NULL, 0);
4365 case aFullKeygen: /* Generate a key with all options. */
4369 wrong_args ("--full-generate-key [parameterfile]");
4370 generate_keypair (ctrl, 1, argc? *argv : NULL, NULL, 0);
4375 wrong_args("--full-generate-key");
4376 generate_keypair (ctrl, 1, NULL, NULL, 0);
4382 const char *uid, *newuid;
4385 wrong_args ("--quick-add-uid USER-ID NEW-USER-ID");
4386 uid = *argv++; argc--;
4387 newuid = *argv++; argc--;
4388 keyedit_quick_adduid (ctrl, uid, newuid);
4394 const char *x_fpr, *x_algo, *x_usage, *x_expire;
4396 if (argc < 1 || argc > 4)
4397 wrong_args ("--quick-add-key FINGERPRINT [ALGO [USAGE [EXPIRE]]]");
4398 x_fpr = *argv++; argc--;
4404 x_algo = *argv++; argc--;
4407 x_usage = *argv++; argc--;
4410 x_expire = *argv++; argc--;
4414 keyedit_quick_addkey (ctrl, x_fpr, x_algo, x_usage, x_expire);
4420 const char *uid, *uidtorev;
4423 wrong_args ("--quick-revoke-uid USER-ID USER-ID-TO-REVOKE");
4424 uid = *argv++; argc--;
4425 uidtorev = *argv++; argc--;
4426 keyedit_quick_revuid (ctrl, uid, uidtorev);
4430 case aQuickSetExpire:
4432 const char *x_fpr, *x_expire;
4435 wrong_args ("--quick-set-exipre FINGERPRINT EXPIRE");
4436 x_fpr = *argv++; argc--;
4437 x_expire = *argv++; argc--;
4438 keyedit_quick_set_expire (ctrl, x_fpr, x_expire);
4443 opt.import_options |= IMPORT_FAST;
4445 import_keys (ctrl, argc? argv:NULL, argc, NULL, opt.import_options);
4448 /* TODO: There are a number of command that use this same
4449 "make strlist, call function, report error, free strlist"
4450 pattern. Join them together here and avoid all that
4457 for( ; argc; argc--, argv++ )
4458 append_to_strlist2( &sl, *argv, utf8_strings );
4459 if( cmd == aSendKeys )
4460 rc = keyserver_export (ctrl, sl );
4461 else if( cmd == aRecvKeys )
4462 rc = keyserver_import (ctrl, sl );
4465 export_stats_t stats = export_new_stats ();
4466 rc = export_pubkeys (ctrl, sl, opt.export_options, stats);
4467 export_print_stats (stats);
4468 export_release_stats (stats);
4474 write_status_failure ("send-keys", rc);
4475 log_error(_("keyserver send failed: %s\n"),gpg_strerror (rc));
4477 else if(cmd==aRecvKeys)
4479 write_status_failure ("recv-keys", rc);
4480 log_error (_("keyserver receive failed: %s\n"),
4485 write_status_failure ("export", rc);
4486 log_error (_("key export failed: %s\n"), gpg_strerror (rc));
4494 wrong_args ("--export-ssh-key <user-id>");
4495 rc = export_ssh_key (ctrl, argv[0]);
4498 write_status_failure ("export-ssh-key", rc);
4499 log_error (_("export as ssh key failed: %s\n"), gpg_strerror (rc));
4505 for (; argc; argc--, argv++)
4506 append_to_strlist2 (&sl, *argv, utf8_strings);
4507 rc = keyserver_search (ctrl, sl);
4510 write_status_failure ("search-keys", rc);
4511 log_error (_("keyserver search failed: %s\n"), gpg_strerror (rc));
4518 for( ; argc; argc--, argv++ )
4519 append_to_strlist2( &sl, *argv, utf8_strings );
4520 rc = keyserver_refresh (ctrl, sl);
4523 write_status_failure ("refresh-keys", rc);
4524 log_error (_("keyserver refresh failed: %s\n"),gpg_strerror (rc));
4531 for( ; argc; argc--, argv++ )
4532 append_to_strlist2( &sl, *argv, utf8_strings );
4533 rc = keyserver_fetch (ctrl, sl);
4536 write_status_failure ("fetch-keys", rc);
4537 log_error ("key fetch failed: %s\n",gpg_strerror (rc));
4544 for( ; argc; argc--, argv++ )
4545 add_to_strlist2( &sl, *argv, utf8_strings );
4547 export_stats_t stats = export_new_stats ();
4548 export_seckeys (ctrl, sl, stats);
4549 export_print_stats (stats);
4550 export_release_stats (stats);
4555 case aExportSecretSub:
4557 for( ; argc; argc--, argv++ )
4558 add_to_strlist2( &sl, *argv, utf8_strings );
4560 export_stats_t stats = export_new_stats ();
4561 export_secsubkeys (ctrl, sl, stats);
4562 export_print_stats (stats);
4563 export_release_stats (stats);
4570 wrong_args("--generate-revocation user-id");
4571 username = make_username(*argv);
4572 gen_revoke( username );
4578 wrong_args ("--generate-designated-revocation user-id");
4579 username = make_username (*argv);
4580 gen_desig_revoke (ctrl, username, locusr);
4586 wrong_args("--dearmor [file]");
4587 rc = dearmor_file( argc? *argv: NULL );
4590 write_status_failure ("dearmor", rc);
4591 log_error (_("dearmoring failed: %s\n"), gpg_strerror (rc));
4597 wrong_args("--enarmor [file]");
4598 rc = enarmor_file( argc? *argv: NULL );
4601 write_status_failure ("enarmor", rc);
4602 log_error (_("enarmoring failed: %s\n"), gpg_strerror (rc));
4609 { int mode = argc < 2 ? 0 : atoi(*argv);
4611 if( mode == 1 && argc == 2 ) {
4612 mpi_print (es_stdout,
4613 generate_public_prime( atoi(argv[1]) ), 1);
4615 else if( mode == 2 && argc == 3 ) {
4616 mpi_print (es_stdout, generate_elg_prime(
4618 atoi(argv[2]), NULL,NULL ), 1);
4620 else if( mode == 3 && argc == 3 ) {
4622 mpi_print (es_stdout, generate_elg_prime(
4624 atoi(argv[2]), NULL,&factors ), 1);
4625 es_putc ('\n', es_stdout);
4626 mpi_print (es_stdout, factors[0], 1 ); /* print q */
4628 else if( mode == 4 && argc == 3 ) {
4629 MPI g = mpi_alloc(1);
4630 mpi_print (es_stdout, generate_elg_prime(
4632 atoi(argv[2]), g, NULL ), 1);
4633 es_putc ('\n', es_stdout);
4634 mpi_print (es_stdout, g, 1 );
4638 wrong_args("--gen-prime mode bits [qbits] ");
4639 es_putc ('\n', es_stdout);
4642 wrong_args("--gen-prime not yet supported ");
4647 int level = argc ? atoi(*argv):0;
4648 int count = argc > 1 ? atoi(argv[1]): 0;
4649 int endless = !count;
4651 if( argc < 1 || argc > 2 || level < 0 || level > 2 || count < 0 )
4652 wrong_args("--gen-random 0|1|2 [count]");
4654 while( endless || count ) {
4656 /* Wee need a multiple of 3, so that in case of
4657 armored output we get a correct string. No
4658 linefolding is done, as it is best to levae this to
4660 size_t n = !endless && count < 99? count : 99;
4662 p = gcry_random_bytes (n, level);
4663 #ifdef HAVE_DOSISH_SYSTEM
4664 setmode ( fileno(stdout), O_BINARY );
4667 char *tmp = make_radix64_string (p, n);
4668 es_fputs (tmp, es_stdout);
4671 es_putc ('=', es_stdout);
4673 es_putc ('=', es_stdout);
4675 es_fwrite( p, n, 1, es_stdout );
4682 es_putc ('\n', es_stdout);
4688 wrong_args("--print-md algo [files]");
4690 int all_algos = (**argv=='*' && !(*argv)[1]);
4691 int algo = all_algos? 0 : gcry_md_map_name (*argv);
4693 if( !algo && !all_algos )
4694 log_error(_("invalid hash algorithm '%s'\n"), *argv );
4698 print_mds(NULL, algo);
4700 for(; argc; argc--, argv++ )
4701 print_mds(*argv, algo);
4707 case aPrintMDs: /* old option */
4711 for(; argc; argc--, argv++ )
4716 #ifndef NO_TRUST_MODELS
4719 list_trustdb (es_stdout, NULL);
4721 for( ; argc; argc--, argv++ )
4722 list_trustdb (es_stdout, *argv );
4726 case aUpdateTrustDB:
4728 wrong_args("--update-trustdb");
4729 update_trustdb (ctrl);
4733 /* Old versions allowed for arguments - ignore them */
4734 check_trustdb (ctrl);
4738 how_to_fix_the_trustdb ();
4741 case aListTrustPath:
4743 wrong_args("--list-trust-path <user-ids>");
4744 for( ; argc; argc--, argv++ ) {
4745 username = make_username( *argv );
4746 list_trust_path( username );
4751 case aExportOwnerTrust:
4753 wrong_args("--export-ownertrust");
4754 export_ownertrust();
4757 case aImportOwnerTrust:
4759 wrong_args("--import-ownertrust [file]");
4760 import_ownertrust( argc? *argv:NULL );
4762 #endif /*!NO_TRUST_MODELS*/
4764 case aRebuildKeydbCaches:
4766 wrong_args ("--rebuild-keydb-caches");
4767 keydb_rebuild_caches (1);
4770 #ifdef ENABLE_CARD_SUPPORT
4773 wrong_args ("--card-status");
4774 card_status (es_stdout, NULL, 0);
4780 for (argc--, argv++ ; argc; argc--, argv++)
4781 append_to_strlist (&sl, *argv);
4782 card_edit (ctrl, sl);
4786 card_edit (ctrl, NULL);
4793 change_pin (atoi (*argv),1);
4795 wrong_args ("--change-pin [no]");
4797 #endif /* ENABLE_CARD_SUPPORT*/
4801 char *str=collapse_args(argc,argv);
4807 case aListGcryptConfig:
4808 /* Fixme: It would be nice to integrate that with
4809 --list-config but unfortunately there is no way yet to have
4810 libgcrypt print it to an estream for further parsing. */
4811 gcry_control (GCRYCTL_PRINT_CONFIG, stdout);
4822 wrong_args ("--tofu-policy POLICY KEYID [KEYID...]");
4824 policy = parse_tofu_policy (argv[0]);
4830 tofu_begin_batch_update (ctrl);
4832 for (i = 1; i < argc; i ++)
4834 KEYDB_SEARCH_DESC desc;
4837 rc = classify_user_id (argv[i], &desc, 0);
4840 log_error (_("error parsing key specification '%s': %s\n"),
4841 argv[i], gpg_strerror (rc));
4845 if (! (desc.mode == KEYDB_SEARCH_MODE_SHORT_KID
4846 || desc.mode == KEYDB_SEARCH_MODE_LONG_KID
4847 || desc.mode == KEYDB_SEARCH_MODE_FPR16
4848 || desc.mode == KEYDB_SEARCH_MODE_FPR20
4849 || desc.mode == KEYDB_SEARCH_MODE_FPR
4850 || desc.mode == KEYDB_SEARCH_MODE_KEYGRIP))
4852 log_error (_("'%s' does not appear to be a valid"
4853 " key ID, fingerprint or keygrip\n"),
4858 rc = keydb_search_reset (hd);
4861 /* This should not happen, thus no need to tranalate
4863 log_error ("keydb_search_reset failed: %s\n",
4868 rc = keydb_search (hd, &desc, 1, NULL);
4871 log_error (_("key \"%s\" not found: %s\n"), argv[i],
4876 rc = keydb_get_keyblock (hd, &kb);
4879 log_error (_("error reading keyblock: %s\n"),
4884 merge_keys_and_selfsig (kb);
4885 if (tofu_set_policy (ctrl, kb, policy))
4888 release_kbnode (kb);
4891 tofu_end_batch_update (ctrl);
4900 log_info (_("WARNING: no command supplied."
4901 " Trying to guess what you mean ...\n"));
4905 wrong_args("[filename]");
4906 /* Issue some output for the unix newbie */
4907 if (!fname && !opt.outfile
4908 && gnupg_isatty (fileno (stdin))
4909 && gnupg_isatty (fileno (stdout))
4910 && gnupg_isatty (fileno (stderr)))
4911 log_info(_("Go ahead and type your message ...\n"));
4913 a = iobuf_open(fname);
4914 if (a && is_secured_file (iobuf_get_fd (a)))
4918 gpg_err_set_errno (EPERM);
4921 log_error(_("can't open '%s'\n"), print_fname_stdin(fname));
4924 if( !opt.no_armor ) {
4925 if( use_armor_filter( a ) ) {
4926 afx = new_armor_context ();
4927 push_armor_filter (afx, a);
4930 if( cmd == aListPackets ) {
4932 set_packet_list_mode(1);
4934 rc = proc_packets (ctrl, NULL, a );
4937 write_status_failure ("-", rc);
4938 log_error ("processing message failed: %s\n",
4947 gpg_deinit_default_ctrl (ctrl);
4949 release_armor_context (afx);
4950 FREE_STRLIST(remusr);
4951 FREE_STRLIST(locusr);
4953 return 8; /*NEVER REACHED*/
4957 /* Note: This function is used by signal handlers!. */
4959 emergency_cleanup (void)
4961 gcry_control (GCRYCTL_TERM_SECMEM );
4968 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
4972 if ( (opt.debug & DBG_MEMSTAT_VALUE) )
4974 keydb_dump_stats ();
4975 gcry_control (GCRYCTL_DUMP_MEMORY_STATS);
4976 gcry_control (GCRYCTL_DUMP_RANDOM_STATS);
4979 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
4981 emergency_cleanup ();
4983 rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0;
4988 /* Pretty-print hex hashes. This assumes at least an 80-character
4989 display, but there are a few other similar assumptions in the
4992 print_hex (gcry_md_hd_t md, int algo, const char *fname)
4994 int i,n,count,indent=0;
4998 indent = es_printf("%s: ",fname);
5006 if (algo==DIGEST_ALGO_RMD160)
5007 indent += es_printf("RMD160 = ");
5009 indent += es_printf("%6s = ", gcry_md_algo_name (algo));
5015 p = gcry_md_read (md, algo);
5016 n = gcry_md_get_algo_dlen (algo);
5018 count += es_printf ("%02X",*p++);
5020 for(i=1;i<n;i++,p++)
5026 es_printf ("\n%*s",indent," ");
5030 count += es_printf(" ");
5033 count += es_printf(" ");
5041 es_printf ("\n%*s",indent," ");
5045 count += es_printf(" ");
5049 count += es_printf(" ");
5057 es_printf ("\n%*s",indent," ");
5061 count += es_printf(" ");
5065 count += es_printf("%02X",*p);
5072 print_hashline( gcry_md_hd_t md, int algo, const char *fname )
5079 for (p = fname; *p; p++ )
5081 if ( *p <= 32 || *p > 127 || *p == ':' || *p == '%' )
5082 es_printf ("%%%02X", *p );
5084 es_putc (*p, es_stdout);
5087 es_putc (':', es_stdout);
5088 es_printf ("%d:", algo);
5089 p = gcry_md_read (md, algo);
5090 n = gcry_md_get_algo_dlen (algo);
5091 for(i=0; i < n ; i++, p++ )
5092 es_printf ("%02X", *p);
5093 es_fputs (":\n", es_stdout);
5098 print_mds( const char *fname, int algo )
5112 fp = es_fopen (fname, "rb" );
5113 if (fp && is_secured_file (es_fileno (fp)))
5117 gpg_err_set_errno (EPERM);
5122 log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
5126 gcry_md_open (&md, 0, 0);
5128 gcry_md_enable (md, algo);
5131 if (!gcry_md_test_algo (GCRY_MD_MD5))
5132 gcry_md_enable (md, GCRY_MD_MD5);
5133 gcry_md_enable (md, GCRY_MD_SHA1);
5134 if (!gcry_md_test_algo (GCRY_MD_RMD160))
5135 gcry_md_enable (md, GCRY_MD_RMD160);
5136 if (!gcry_md_test_algo (GCRY_MD_SHA224))
5137 gcry_md_enable (md, GCRY_MD_SHA224);
5138 if (!gcry_md_test_algo (GCRY_MD_SHA256))
5139 gcry_md_enable (md, GCRY_MD_SHA256);
5140 if (!gcry_md_test_algo (GCRY_MD_SHA384))
5141 gcry_md_enable (md, GCRY_MD_SHA384);
5142 if (!gcry_md_test_algo (GCRY_MD_SHA512))
5143 gcry_md_enable (md, GCRY_MD_SHA512);
5146 while ((n=es_fread (buf, 1, DIM(buf), fp)))
5147 gcry_md_write (md, buf, n);
5150 log_error ("%s: %s\n", fname?fname:"[stdin]", strerror(errno));
5154 if (opt.with_colons)
5157 print_hashline (md, algo, fname);
5160 if (!gcry_md_test_algo (GCRY_MD_MD5))
5161 print_hashline( md, GCRY_MD_MD5, fname );
5162 print_hashline( md, GCRY_MD_SHA1, fname );
5163 if (!gcry_md_test_algo (GCRY_MD_RMD160))
5164 print_hashline( md, GCRY_MD_RMD160, fname );
5165 if (!gcry_md_test_algo (GCRY_MD_SHA224))
5166 print_hashline (md, GCRY_MD_SHA224, fname);
5167 if (!gcry_md_test_algo (GCRY_MD_SHA256))
5168 print_hashline( md, GCRY_MD_SHA256, fname );
5169 if (!gcry_md_test_algo (GCRY_MD_SHA384))
5170 print_hashline ( md, GCRY_MD_SHA384, fname );
5171 if (!gcry_md_test_algo (GCRY_MD_SHA512))
5172 print_hashline ( md, GCRY_MD_SHA512, fname );
5178 print_hex (md, -algo, fname);
5181 if (!gcry_md_test_algo (GCRY_MD_MD5))
5182 print_hex (md, GCRY_MD_MD5, fname);
5183 print_hex (md, GCRY_MD_SHA1, fname );
5184 if (!gcry_md_test_algo (GCRY_MD_RMD160))
5185 print_hex (md, GCRY_MD_RMD160, fname );
5186 if (!gcry_md_test_algo (GCRY_MD_SHA224))
5187 print_hex (md, GCRY_MD_SHA224, fname);
5188 if (!gcry_md_test_algo (GCRY_MD_SHA256))
5189 print_hex (md, GCRY_MD_SHA256, fname );
5190 if (!gcry_md_test_algo (GCRY_MD_SHA384))
5191 print_hex (md, GCRY_MD_SHA384, fname );
5192 if (!gcry_md_test_algo (GCRY_MD_SHA512))
5193 print_hex (md, GCRY_MD_SHA512, fname );
5205 * Check the supplied name,value string and add it to the notation
5206 * data to be used for signatures. which==0 for sig notations, and 1
5207 * for cert notations.
5210 add_notation_data( const char *string, int which )
5212 struct notation *notation;
5214 notation=string_to_notation(string,utf8_strings);
5219 notation->next=opt.cert_notations;
5220 opt.cert_notations=notation;
5224 notation->next=opt.sig_notations;
5225 opt.sig_notations=notation;
5231 add_policy_url( const char *string, int which )
5233 unsigned int i,critical=0;
5242 for(i=0;i<strlen(string);i++)
5243 if( !isascii (string[i]) || iscntrl(string[i]))
5246 if(i==0 || i<strlen(string))
5249 log_error(_("the given certification policy URL is invalid\n"));
5251 log_error(_("the given signature policy URL is invalid\n"));
5255 sl=add_to_strlist( &opt.cert_policy_url, string );
5257 sl=add_to_strlist( &opt.sig_policy_url, string );
5264 add_keyserver_url( const char *string, int which )
5266 unsigned int i,critical=0;
5275 for(i=0;i<strlen(string);i++)
5276 if( !isascii (string[i]) || iscntrl(string[i]))
5279 if(i==0 || i<strlen(string))
5284 log_error(_("the given preferred keyserver URL is invalid\n"));
5290 sl=add_to_strlist( &opt.sig_keyserver_url, string );
5298 read_sessionkey_from_fd (int fd)
5303 if (! gnupg_fd_valid (fd))
5304 log_fatal ("override-session-key-fd is invalid: %s\n", strerror (errno));
5306 for (line = NULL, i = len = 100; ; i++ )
5312 line = xmalloc_secure (len);
5315 memcpy (line, tmp, i);
5321 if (read (fd, line + i, 1) != 1 || line[i] == '\n')
5325 log_debug ("seskey: %s\n", line);
5326 gpgrt_annotate_leaked_object (line);
5327 opt.override_session_key = line;