1 /* gpg.c - The GnuPG OpenPGP tool
2 * Copyright (C) 1998-2020 Free Software Foundation, Inc.
3 * Copyright (C) 1997-2019 Werner Koch
4 * Copyright (C) 2015-2022 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/>.
20 * SPDX-License-Identifier: GPL-3.0-or-later
31 #include <sys/stat.h> /* for stat() */
34 #ifdef HAVE_W32_SYSTEM
35 # ifdef HAVE_WINSOCK2_H
36 # include <winsock2.h>
42 #define INCLUDED_BY_MAIN_MODULE 1
45 #include "../common/iobuf.h"
46 #include "../common/util.h"
48 #include "../common/membuf.h"
54 #include "../common/ttyio.h"
55 #include "../common/i18n.h"
56 #include "../common/sysutils.h"
57 #include "../common/status.h"
58 #include "keyserver-internal.h"
60 #include "../common/gc-opt-flags.h"
61 #include "../common/asshelp.h"
62 #include "call-dirmngr.h"
65 #include "../common/init.h"
66 #include "../common/mbox-util.h"
67 #include "../common/zb32.h"
68 #include "../common/shareddefs.h"
69 #include "../common/compliance.h"
70 #include "../common/comopt.h"
71 #include "../kbx/keybox.h"
73 #if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
74 #define MY_O_BINARY O_BINARY
83 enum cmd_and_opt_values
92 oHiddenRecipientFile = 'F',
99 oHiddenRecipient = 'R',
106 aListSecretKeys = 'K',
147 aDeleteSecretAndPublicKeys,
207 oWithSubkeyFingerprint,
236 oDebugAllowLargeChunks,
237 oDebugIgnoreExpiration,
266 oBZ2DecompressLowmem,
290 oSkipHiddenRecipients,
291 oNoSkipHiddenRecipients,
305 oUseEmbeddedFilename,
306 oNoUseEmbeddedFilename,
341 oEncryptToDefaultKey,
349 oAllowNonSelfsignedUID,
350 oNoAllowNonSelfsignedUID,
353 oAllowSecretKeyImport,
354 oAllowOldCipherAlgos,
355 oEnableSpecialFilenames,
367 oOverrideSessionKeyFD,
380 oNoExpensiveTrustChecks,
386 oPreservePermissions,
387 oDefaultPreferenceList,
388 oDefaultKeyserverURL,
389 oPersonalCipherPreferences,
390 oPersonalDigestPreferences,
391 oPersonalCompressPreferences,
408 oNoMangleDosFilenames,
409 oEnableProgressFilter,
412 oExitOnStatusWriteError,
413 oLimitCardInsertTries,
426 oAllowWeakDigestAlgos,
427 oAllowWeakKeySignatures,
459 static gpgrt_opt_t opts[] = {
461 ARGPARSE_group (300, N_("@Commands:\n ")),
463 ARGPARSE_c (aSign, "sign", N_("make a signature")),
464 ARGPARSE_c (aClearsign, "clear-sign", N_("make a clear text signature")),
465 ARGPARSE_c (aClearsign, "clearsign", "@"),
466 ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")),
467 ARGPARSE_c (aEncr, "encrypt", N_("encrypt data")),
468 ARGPARSE_c (aEncrFiles, "encrypt-files", "@"),
469 ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")),
470 ARGPARSE_c (aStore, "store", "@"),
471 ARGPARSE_c (aDecrypt, "decrypt", N_("decrypt data (default)")),
472 ARGPARSE_c (aDecryptFiles, "decrypt-files", "@"),
473 ARGPARSE_c (aVerify, "verify" , N_("verify a signature")),
474 ARGPARSE_c (aVerifyFiles, "verify-files" , "@" ),
475 ARGPARSE_c (aListKeys, "list-keys", N_("list keys")),
476 ARGPARSE_c (aListKeys, "list-public-keys", "@" ),
477 ARGPARSE_c (aListSigs, "list-signatures", N_("list keys and signatures")),
478 ARGPARSE_c (aListSigs, "list-sigs", "@"),
479 ARGPARSE_c (aCheckKeys, "check-signatures",
480 N_("list and check key signatures")),
481 ARGPARSE_c (aCheckKeys, "check-sigs", "@"),
482 ARGPARSE_c (oFingerprint, "fingerprint", N_("list keys and fingerprints")),
483 ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")),
484 ARGPARSE_c (aKeygen, "generate-key",
485 N_("generate a new key pair")),
486 ARGPARSE_c (aKeygen, "gen-key", "@"),
487 ARGPARSE_c (aQuickKeygen, "quick-generate-key" ,
488 N_("quickly generate a new key pair")),
489 ARGPARSE_c (aQuickKeygen, "quick-gen-key", "@"),
490 ARGPARSE_c (aQuickAddUid, "quick-add-uid",
491 N_("quickly add a new user-id")),
492 ARGPARSE_c (aQuickAddUid, "quick-adduid", "@"),
493 ARGPARSE_c (aQuickAddKey, "quick-add-key", "@"),
494 ARGPARSE_c (aQuickAddKey, "quick-addkey", "@"),
495 ARGPARSE_c (aQuickAddADSK, "quick-add-adsk", "@"),
496 ARGPARSE_c (aQuickRevUid, "quick-revoke-uid",
497 N_("quickly revoke a user-id")),
498 ARGPARSE_c (aQuickRevUid, "quick-revuid", "@"),
499 ARGPARSE_c (aQuickSetExpire, "quick-set-expire",
500 N_("quickly set a new expiration date")),
501 ARGPARSE_c (aQuickSetPrimaryUid, "quick-set-primary-uid", "@"),
502 ARGPARSE_c (aQuickUpdatePref, "quick-update-pref", "@"),
503 ARGPARSE_c (aFullKeygen, "full-generate-key" ,
504 N_("full featured key pair generation")),
505 ARGPARSE_c (aFullKeygen, "full-gen-key", "@"),
506 ARGPARSE_c (aGenRevoke, "generate-revocation",
507 N_("generate a revocation certificate")),
508 ARGPARSE_c (aGenRevoke, "gen-revoke", "@"),
509 ARGPARSE_c (aDeleteKeys,"delete-keys",
510 N_("remove keys from the public keyring")),
511 ARGPARSE_c (aDeleteSecretKeys, "delete-secret-keys",
512 N_("remove keys from the secret keyring")),
513 ARGPARSE_c (aQuickSignKey, "quick-sign-key" ,
514 N_("quickly sign a key")),
515 ARGPARSE_c (aQuickLSignKey, "quick-lsign-key",
516 N_("quickly sign a key locally")),
517 ARGPARSE_c (aQuickRevSig, "quick-revoke-sig" ,
518 N_("quickly revoke a key signature")),
519 ARGPARSE_c (aSignKey, "sign-key" ,N_("sign a key")),
520 ARGPARSE_c (aLSignKey, "lsign-key" ,N_("sign a key locally")),
521 ARGPARSE_c (aEditKey, "edit-key" ,N_("sign or edit a key")),
522 ARGPARSE_c (aEditKey, "key-edit" ,"@"),
523 ARGPARSE_c (aPasswd, "change-passphrase", N_("change a passphrase")),
524 ARGPARSE_c (aPasswd, "passwd", "@"),
525 ARGPARSE_c (aDesigRevoke, "generate-designated-revocation", "@"),
526 ARGPARSE_c (aDesigRevoke, "desig-revoke","@" ),
527 ARGPARSE_c (aExport, "export" , N_("export keys") ),
528 ARGPARSE_c (aSendKeys, "send-keys" , N_("export keys to a keyserver") ),
529 ARGPARSE_c (aRecvKeys, "receive-keys" , N_("import keys from a keyserver") ),
530 ARGPARSE_c (aRecvKeys, "recv-keys" , "@"),
531 ARGPARSE_c (aSearchKeys, "search-keys" ,
532 N_("search for keys on a keyserver") ),
533 ARGPARSE_c (aRefreshKeys, "refresh-keys",
534 N_("update all keys from a keyserver")),
535 ARGPARSE_c (aLocateKeys, "locate-keys", "@"),
536 ARGPARSE_c (aLocateExtKeys, "locate-external-keys", "@"),
537 ARGPARSE_c (aFetchKeys, "fetch-keys" , "@" ),
538 ARGPARSE_c (aShowKeys, "show-keys" , "@" ),
539 ARGPARSE_c (aExportSecret, "export-secret-keys" , "@" ),
540 ARGPARSE_c (aExportSecretSub, "export-secret-subkeys" , "@" ),
541 ARGPARSE_c (aExportSshKey, "export-ssh-key", "@" ),
542 ARGPARSE_c (aExportSecretSshKey, "export-secret-ssh-key", "@" ),
543 ARGPARSE_c (aImport, "import", N_("import/merge keys")),
544 ARGPARSE_c (aFastImport, "fast-import", "@"),
545 #ifdef ENABLE_CARD_SUPPORT
546 ARGPARSE_c (aCardStatus, "card-status", N_("print the card status")),
547 ARGPARSE_c (aCardEdit, "edit-card", N_("change data on a card")),
548 ARGPARSE_c (aCardEdit, "card-edit", "@"),
549 ARGPARSE_c (aChangePIN, "change-pin", N_("change a card's PIN")),
551 ARGPARSE_c (aListConfig, "list-config", "@"),
552 ARGPARSE_c (aListGcryptConfig, "list-gcrypt-config", "@"),
553 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@" ),
554 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@" ),
555 ARGPARSE_c (aListPackets, "list-packets","@"),
557 #ifndef NO_TRUST_MODELS
558 ARGPARSE_c (aExportOwnerTrust, "export-ownertrust", "@"),
559 ARGPARSE_c (aImportOwnerTrust, "import-ownertrust", "@"),
560 ARGPARSE_c (aUpdateTrustDB,"update-trustdb",
561 N_("update the trust database")),
562 ARGPARSE_c (aCheckTrustDB, "check-trustdb", "@"),
563 ARGPARSE_c (aFixTrustDB, "fix-trustdb", "@"),
564 ARGPARSE_c (aListTrustDB, "list-trustdb", "@"),
567 ARGPARSE_c (aDeArmor, "dearmor", "@"),
568 ARGPARSE_c (aDeArmor, "dearmour", "@"),
569 ARGPARSE_c (aEnArmor, "enarmor", "@"),
570 ARGPARSE_c (aEnArmor, "enarmour", "@"),
571 ARGPARSE_c (aPrintMD, "print-md", N_("print message digests")),
572 ARGPARSE_c (aPrintMDs, "print-mds", "@"), /* old */
573 ARGPARSE_c (aPrimegen, "gen-prime", "@" ),
574 ARGPARSE_c (aGenRandom,"gen-random", "@" ),
575 ARGPARSE_c (aServer, "server", N_("run in server mode")),
576 ARGPARSE_c (aTOFUPolicy, "tofu-policy",
577 N_("|VALUE|set the TOFU policy for a key")),
579 ARGPARSE_c (aListTrustPath, "list-trust-path", "@"), */
580 ARGPARSE_c (aDeleteSecretAndPublicKeys,
581 "delete-secret-and-public-keys", "@"),
582 ARGPARSE_c (aRebuildKeydbCaches, "rebuild-keydb-caches", "@"),
583 ARGPARSE_c (aListKeys, "list-key", "@"), /* alias */
584 ARGPARSE_c (aListSigs, "list-sig", "@"), /* alias */
585 ARGPARSE_c (aCheckKeys, "check-sig", "@"), /* alias */
586 ARGPARSE_c (aShowKeys, "show-key", "@"), /* alias */
590 ARGPARSE_header ("Monitor", N_("Options controlling the diagnostic output")),
592 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
593 ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
594 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
595 ARGPARSE_s_n (oNoTTY, "no-tty", "@"),
596 ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
597 ARGPARSE_s_s (oDebug, "debug", "@"),
598 ARGPARSE_s_s (oDebugLevel, "debug-level", "@"),
599 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
600 ARGPARSE_s_n (oDebugIOLBF, "debug-iolbf", "@"),
601 ARGPARSE_s_u (oDebugSetIobufSize, "debug-set-iobuf-size", "@"),
602 ARGPARSE_s_u (oDebugAllowLargeChunks, "debug-allow-large-chunks", "@"),
603 ARGPARSE_s_s (oDisplayCharset, "display-charset", "@"),
604 ARGPARSE_s_s (oDisplayCharset, "charset", "@"),
605 ARGPARSE_conffile (oOptions, "options", N_("|FILE|read options from FILE")),
606 ARGPARSE_noconffile (oNoOptions, "no-options", "@"),
607 ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"),
608 ARGPARSE_s_s (oLoggerFile, "log-file",
609 N_("|FILE|write server mode logs to FILE")),
610 ARGPARSE_s_s (oLoggerFile, "logger-file", "@"), /* 1.4 compatibility. */
611 ARGPARSE_s_n (oLogTime, "log-time", "@"),
614 ARGPARSE_header ("Configuration",
615 N_("Options controlling the configuration")),
617 ARGPARSE_s_s (oHomedir, "homedir", "@"),
618 ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
619 ARGPARSE_s_s (oDefaultKey, "default-key",
620 N_("|NAME|use NAME as default secret key")),
621 ARGPARSE_s_s (oEncryptTo, "encrypt-to",
622 N_("|NAME|encrypt to user ID NAME as well")),
623 ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"),
624 ARGPARSE_s_s (oHiddenEncryptTo, "hidden-encrypt-to", "@"),
625 ARGPARSE_s_n (oEncryptToDefaultKey, "encrypt-to-default-key", "@"),
626 ARGPARSE_s_s (oDefRecipient, "default-recipient", "@"),
627 ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", "@"),
628 ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"),
629 ARGPARSE_s_s (oGroup, "group",
630 N_("|SPEC|set up email aliases")),
631 ARGPARSE_s_s (oUnGroup, "ungroup", "@"),
632 ARGPARSE_s_n (oNoGroups, "no-groups", "@"),
633 ARGPARSE_s_s (oCompliance, "compliance", "@"),
634 ARGPARSE_s_n (oGnuPG, "gnupg", "@"),
635 ARGPARSE_s_n (oGnuPG, "no-pgp2", "@"),
636 ARGPARSE_s_n (oGnuPG, "no-pgp6", "@"),
637 ARGPARSE_s_n (oGnuPG, "no-pgp7", "@"),
638 ARGPARSE_s_n (oGnuPG, "no-pgp8", "@"),
639 ARGPARSE_s_n (oRFC2440, "rfc2440", "@"),
640 ARGPARSE_s_n (oRFC4880, "rfc4880", "@"),
641 ARGPARSE_s_n (oOpenPGP, "openpgp", N_("use strict OpenPGP behavior")),
642 ARGPARSE_s_n (oPGP7, "pgp6", "@"),
643 ARGPARSE_s_n (oPGP7, "pgp7", "@"),
644 ARGPARSE_s_n (oPGP8, "pgp8", "@"),
645 ARGPARSE_s_s (oDefaultNewKeyAlgo, "default-new-key-algo", "@"),
646 ARGPARSE_p_u (oMinRSALength, "min-rsa-length", "@"),
647 #ifndef NO_TRUST_MODELS
648 ARGPARSE_s_n (oAlwaysTrust, "always-trust", "@"),
650 ARGPARSE_s_s (oTrustModel, "trust-model", "@"),
651 ARGPARSE_s_s (oPhotoViewer, "photo-viewer", "@"),
652 ARGPARSE_s_s (oKnownNotation, "known-notation", "@"),
653 ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
654 ARGPARSE_s_s (oKeyboxdProgram, "keyboxd-program", "@"),
655 ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"),
656 ARGPARSE_s_n (oExitOnStatusWriteError, "exit-on-status-write-error", "@"),
657 ARGPARSE_s_i (oLimitCardInsertTries, "limit-card-insert-tries", "@"),
658 ARGPARSE_s_n (oEnableProgressFilter, "enable-progress-filter", "@"),
659 ARGPARSE_s_s (oTempDir, "temp-directory", "@"),
660 ARGPARSE_s_s (oExecPath, "exec-path", "@"),
661 ARGPARSE_s_n (oExpert, "expert", "@"),
662 ARGPARSE_s_n (oNoExpert, "no-expert", "@"),
663 ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"),
664 ARGPARSE_s_n (oRequireSecmem, "require-secmem", "@"),
665 ARGPARSE_s_n (oNoRequireSecmem, "no-require-secmem", "@"),
666 ARGPARSE_s_n (oNoPermissionWarn, "no-permission-warning", "@"),
667 ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")),
668 ARGPARSE_s_n (oInteractive, "interactive", N_("prompt before overwriting")),
669 ARGPARSE_s_s (oDefSigExpire, "default-sig-expire", "@"),
670 ARGPARSE_s_n (oAskSigExpire, "ask-sig-expire", "@"),
671 ARGPARSE_s_n (oNoAskSigExpire, "no-ask-sig-expire", "@"),
672 ARGPARSE_s_s (oDefCertExpire, "default-cert-expire", "@"),
673 ARGPARSE_s_n (oAskCertExpire, "ask-cert-expire", "@"),
674 ARGPARSE_s_n (oNoAskCertExpire, "no-ask-cert-expire", "@"),
675 ARGPARSE_s_i (oDefCertLevel, "default-cert-level", "@"),
676 ARGPARSE_s_i (oMinCertLevel, "min-cert-level", "@"),
677 ARGPARSE_s_n (oAskCertLevel, "ask-cert-level", "@"),
678 ARGPARSE_s_n (oNoAskCertLevel, "no-ask-cert-level", "@"),
679 ARGPARSE_s_n (oOnlySignTextIDs, "only-sign-text-ids", "@"),
680 ARGPARSE_s_n (oEnableLargeRSA, "enable-large-rsa", "@"),
681 ARGPARSE_s_n (oDisableLargeRSA, "disable-large-rsa", "@"),
682 ARGPARSE_s_n (oEnableDSA2, "enable-dsa2", "@"),
683 ARGPARSE_s_n (oDisableDSA2, "disable-dsa2", "@"),
684 ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-preferences","@"),
685 ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-preferences","@"),
686 ARGPARSE_s_s (oPersonalCompressPreferences,
687 "personal-compress-preferences", "@"),
688 ARGPARSE_s_s (oDefaultPreferenceList, "default-preference-list", "@"),
689 ARGPARSE_s_s (oDefaultKeyserverURL, "default-keyserver-url", "@"),
690 ARGPARSE_s_n (oNoExpensiveTrustChecks, "no-expensive-trust-checks", "@"),
691 ARGPARSE_s_n (oAllowNonSelfsignedUID, "allow-non-selfsigned-uid", "@"),
692 ARGPARSE_s_n (oNoAllowNonSelfsignedUID, "no-allow-non-selfsigned-uid", "@"),
693 ARGPARSE_s_n (oAllowFreeformUID, "allow-freeform-uid", "@"),
694 ARGPARSE_s_n (oNoAllowFreeformUID, "no-allow-freeform-uid", "@"),
695 ARGPARSE_s_n (oPreservePermissions, "preserve-permissions", "@"),
696 ARGPARSE_s_i (oDefCertLevel, "default-cert-check-level", "@"), /* old */
697 ARGPARSE_s_s (oTOFUDefaultPolicy, "tofu-default-policy", "@"),
698 ARGPARSE_s_n (oLockOnce, "lock-once", "@"),
699 ARGPARSE_s_n (oLockMultiple, "lock-multiple", "@"),
700 ARGPARSE_s_n (oLockNever, "lock-never", "@"),
701 ARGPARSE_s_n (oNoCompress, "no-compress", "@"),
702 ARGPARSE_s_s (oCompressAlgo,"compress-algo", "@"),
703 ARGPARSE_s_s (oCompressAlgo, "compression-algo", "@"), /* Alias */
704 ARGPARSE_s_n (oBZ2DecompressLowmem, "bzip2-decompress-lowmem", "@"),
705 ARGPARSE_s_i (oCompletesNeeded, "completes-needed", "@"),
706 ARGPARSE_s_i (oMarginalsNeeded, "marginals-needed", "@"),
707 ARGPARSE_s_i (oMaxCertDepth, "max-cert-depth", "@" ),
708 #ifndef NO_TRUST_MODELS
709 ARGPARSE_s_s (oTrustDBName, "trustdb-name", "@"),
710 ARGPARSE_s_n (oAutoCheckTrustDB, "auto-check-trustdb", "@"),
711 ARGPARSE_s_n (oNoAutoCheckTrustDB, "no-auto-check-trustdb", "@"),
712 ARGPARSE_s_s (oForceOwnertrust, "force-ownertrust", "@"),
713 ARGPARSE_s_n (oNoAutoTrustNewKey, "no-auto-trust-new-key", "@"),
715 ARGPARSE_s_s (oAddDesigRevoker, "add-desig-revoker", "@"),
716 ARGPARSE_s_s (oAssertSigner, "assert-signer", "@"),
718 ARGPARSE_header ("Input", N_("Options controlling the input")),
720 ARGPARSE_s_n (oMultifile, "multifile", "@"),
721 ARGPARSE_s_s (oInputSizeHint, "input-size-hint", "@"),
722 ARGPARSE_s_n (oUtf8Strings, "utf8-strings", "@"),
723 ARGPARSE_s_n (oNoUtf8Strings, "no-utf8-strings", "@"),
724 ARGPARSE_p_u (oSetFilesize, "set-filesize", "@"),
725 ARGPARSE_s_n (oNoLiteral, "no-literal", "@"),
726 ARGPARSE_s_s (oSetNotation, "set-notation", "@"),
727 ARGPARSE_s_s (oSigNotation, "sig-notation", "@"),
728 ARGPARSE_s_s (oCertNotation, "cert-notation", "@"),
729 ARGPARSE_s_s (oSetPolicyURL, "set-policy-url", "@"),
730 ARGPARSE_s_s (oSigPolicyURL, "sig-policy-url", "@"),
731 ARGPARSE_s_s (oCertPolicyURL, "cert-policy-url", "@"),
732 ARGPARSE_s_s (oSigKeyserverURL, "sig-keyserver-url", "@"),
736 ARGPARSE_header ("Output", N_("Options controlling the output")),
738 ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")),
739 ARGPARSE_s_n (oArmor, "armour", "@"),
740 ARGPARSE_s_n (oNoArmor, "no-armor", "@"),
741 ARGPARSE_s_n (oNoArmor, "no-armour", "@"),
742 ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")),
743 ARGPARSE_p_u (oMaxOutput, "max-output", "@"),
744 ARGPARSE_s_s (oComment, "comment", "@"),
745 ARGPARSE_s_n (oDefaultComment, "default-comment", "@"),
746 ARGPARSE_s_n (oNoComments, "no-comments", "@"),
747 ARGPARSE_s_n (oEmitVersion, "emit-version", "@"),
748 ARGPARSE_s_n (oNoEmitVersion, "no-emit-version", "@"),
749 ARGPARSE_s_n (oNoEmitVersion, "no-version", "@"), /* alias */
750 ARGPARSE_s_n (oNotDashEscaped, "not-dash-escaped", "@"),
751 ARGPARSE_s_n (oEscapeFrom, "escape-from-lines", "@"),
752 ARGPARSE_s_n (oNoEscapeFrom, "no-escape-from-lines", "@"),
753 ARGPARSE_s_n (oMimemode, "mimemode", "@"),
754 ARGPARSE_s_n (oTextmodeShort, NULL, "@"),
755 ARGPARSE_s_n (oTextmode, "textmode", N_("use canonical text mode")),
756 ARGPARSE_s_n (oNoTextmode, "no-textmode", "@"),
757 ARGPARSE_s_s (oSetFilename, "set-filename", "@"),
758 ARGPARSE_s_n (oForYourEyesOnly, "for-your-eyes-only", "@"),
759 ARGPARSE_s_n (oNoForYourEyesOnly, "no-for-your-eyes-only", "@"),
760 ARGPARSE_s_n (oShowNotation, "show-notation", "@"),
761 ARGPARSE_s_n (oNoShowNotation, "no-show-notation", "@"),
762 ARGPARSE_s_n (oShowSessionKey, "show-session-key", "@"),
763 ARGPARSE_s_n (oUseEmbeddedFilename, "use-embedded-filename", "@"),
764 ARGPARSE_s_n (oNoUseEmbeddedFilename, "no-use-embedded-filename", "@"),
765 ARGPARSE_s_n (oUnwrap, "unwrap", "@"),
766 ARGPARSE_s_n (oMangleDosFilenames, "mangle-dos-filenames", "@"),
767 ARGPARSE_s_n (oNoMangleDosFilenames, "no-mangle-dos-filenames", "@"),
768 ARGPARSE_s_i (oChunkSize, "chunk-size", "@"),
769 ARGPARSE_s_n (oNoSymkeyCache, "no-symkey-cache", "@"),
770 ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"),
771 ARGPARSE_s_n (oListOnly, "list-only", "@"),
772 ARGPARSE_s_i (oCompress, NULL,
773 N_("|N|set compress level to N (0 disables)")),
774 ARGPARSE_s_i (oCompressLevel, "compress-level", "@"),
775 ARGPARSE_s_i (oBZ2CompressLevel, "bzip2-compress-level", "@"),
776 ARGPARSE_s_n (oDisableSignerUID, "disable-signer-uid", "@"),
778 ARGPARSE_header ("ImportExport",
779 N_("Options controlling key import and export")),
781 ARGPARSE_s_s (oAutoKeyLocate, "auto-key-locate",
782 N_("|MECHANISMS|use MECHANISMS to locate keys by mail address")),
783 ARGPARSE_s_n (oNoAutoKeyLocate, "no-auto-key-locate", "@"),
784 ARGPARSE_s_n (oAutoKeyImport, "auto-key-import",
785 N_("import missing key from a signature")),
786 ARGPARSE_s_n (oNoAutoKeyImport, "no-auto-key-import", "@"),
787 ARGPARSE_s_n (oAutoKeyRetrieve, "auto-key-retrieve", "@"),
788 ARGPARSE_s_n (oNoAutoKeyRetrieve, "no-auto-key-retrieve", "@"),
789 ARGPARSE_s_n (oIncludeKeyBlock, "include-key-block",
790 N_("include the public key in signatures")),
791 ARGPARSE_s_n (oNoIncludeKeyBlock, "no-include-key-block", "@"),
792 ARGPARSE_s_n (oDisableDirmngr, "disable-dirmngr",
793 N_("disable all access to the dirmngr")),
794 ARGPARSE_s_s (oKeyServer, "keyserver", "@"), /* Deprecated. */
795 ARGPARSE_s_s (oKeyServerOptions, "keyserver-options", "@"),
796 ARGPARSE_s_s (oKeyOrigin, "key-origin", "@"),
797 ARGPARSE_s_s (oImportOptions, "import-options", "@"),
798 ARGPARSE_s_s (oImportFilter, "import-filter", "@"),
799 ARGPARSE_s_s (oExportOptions, "export-options", "@"),
800 ARGPARSE_s_s (oExportFilter, "export-filter", "@"),
801 ARGPARSE_s_n (oMergeOnly, "merge-only", "@" ),
802 ARGPARSE_s_n (oAllowSecretKeyImport, "allow-secret-key-import", "@"),
805 ARGPARSE_header ("Keylist", N_("Options controlling key listings")),
807 ARGPARSE_s_s (oListOptions, "list-options", "@"),
808 ARGPARSE_s_s (oListFilter, "list-filter", "@"),
809 ARGPARSE_s_n (oFullTimestrings, "full-timestrings", "@"),
810 ARGPARSE_s_n (oShowPhotos, "show-photos", "@"),
811 ARGPARSE_s_n (oNoShowPhotos, "no-show-photos", "@"),
812 ARGPARSE_s_n (oShowPolicyURL, "show-policy-url", "@"),
813 ARGPARSE_s_n (oNoShowPolicyURL, "no-show-policy-url", "@"),
814 ARGPARSE_s_n (oWithColons, "with-colons", "@"),
815 ARGPARSE_s_n (oWithTofuInfo,"with-tofu-info", "@"),
816 ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"),
817 ARGPARSE_s_n (oWithSigList,"with-sig-list", "@"),
818 ARGPARSE_s_n (oWithSigCheck,"with-sig-check", "@"),
819 ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"),
820 ARGPARSE_s_n (oWithSubkeyFingerprint, "with-subkey-fingerprint", "@"),
821 ARGPARSE_s_n (oWithSubkeyFingerprint, "with-subkey-fingerprints", "@"),
822 ARGPARSE_s_n (oWithICAOSpelling, "with-icao-spelling", "@"),
823 ARGPARSE_s_n (oWithKeygrip, "with-keygrip", "@"),
824 ARGPARSE_s_n (oWithKeyScreening,"with-key-screening", "@"),
825 ARGPARSE_s_n (oWithSecret, "with-secret", "@"),
826 ARGPARSE_s_n (oWithWKDHash, "with-wkd-hash", "@"),
827 ARGPARSE_s_n (oWithKeyOrigin, "with-key-origin", "@"),
828 ARGPARSE_s_n (oFastListMode, "fast-list-mode", "@"),
829 ARGPARSE_s_n (oFixedListMode, "fixed-list-mode", "@"),
830 ARGPARSE_s_n (oLegacyListMode, "legacy-list-mode", "@"),
831 ARGPARSE_s_n (oPrintDANERecords, "print-dane-records", "@"),
832 ARGPARSE_s_s (oKeyidFormat, "keyid-format", "@"),
833 ARGPARSE_s_n (oShowKeyring, "show-keyring", "@"),
836 ARGPARSE_header (NULL, N_("Options to specify keys")),
838 ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")),
839 ARGPARSE_s_s (oHiddenRecipient, "hidden-recipient", "@"),
840 ARGPARSE_s_s (oRecipientFile, "recipient-file", "@"),
841 ARGPARSE_s_s (oHiddenRecipientFile, "hidden-recipient-file", "@"),
842 ARGPARSE_s_s (oRecipient, "remote-user", "@"), /* (old option name) */
843 ARGPARSE_s_n (oThrowKeyids, "throw-keyids", "@"),
844 ARGPARSE_s_n (oNoThrowKeyids, "no-throw-keyids", "@"),
845 ARGPARSE_s_s (oLocalUser, "local-user",
846 N_("|USER-ID|use USER-ID to sign or decrypt")),
847 ARGPARSE_s_s (oTrustedKey, "trusted-key", "@"),
848 ARGPARSE_s_s (oSender, "sender", "@"),
849 ARGPARSE_s_s (oTrySecretKey, "try-secret-key", "@"),
850 ARGPARSE_s_n (oTryAllSecrets, "try-all-secrets", "@"),
851 ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"),
852 ARGPARSE_s_n (oNoKeyring, "no-keyring", "@"),
853 ARGPARSE_s_s (oKeyring, "keyring", "@"),
854 ARGPARSE_s_s (oPrimaryKeyring, "primary-keyring", "@"),
855 ARGPARSE_s_s (oSecretKeyring, "secret-keyring", "@"),
856 ARGPARSE_s_n (oSkipHiddenRecipients, "skip-hidden-recipients", "@"),
857 ARGPARSE_s_n (oNoSkipHiddenRecipients, "no-skip-hidden-recipients", "@"),
858 ARGPARSE_s_s (oOverrideSessionKey, "override-session-key", "@"),
859 ARGPARSE_s_i (oOverrideSessionKeyFD, "override-session-key-fd", "@"),
861 ARGPARSE_header ("Security", N_("Options controlling the security")),
863 ARGPARSE_s_i (oS2KMode, "s2k-mode", "@"),
864 ARGPARSE_s_s (oS2KDigest, "s2k-digest-algo", "@"),
865 ARGPARSE_s_s (oS2KCipher, "s2k-cipher-algo", "@"),
866 ARGPARSE_s_i (oS2KCount, "s2k-count", "@"),
867 ARGPARSE_s_n (oForceAEAD, "force-ocb", "@"),
868 ARGPARSE_s_n (oForceAEAD, "force-aead", "@"), /*(old name)*/
869 ARGPARSE_s_n (oRequireCrossCert, "require-backsigs", "@"),
870 ARGPARSE_s_n (oRequireCrossCert, "require-cross-certification", "@"),
871 ARGPARSE_s_n (oNoRequireCrossCert, "no-require-backsigs", "@"),
872 ARGPARSE_s_n (oNoRequireCrossCert, "no-require-cross-certification", "@"),
873 /* Options to override new security defaults. */
874 ARGPARSE_s_n (oAllowWeakKeySignatures, "allow-weak-key-signatures", "@"),
875 ARGPARSE_s_n (oAllowWeakDigestAlgos, "allow-weak-digest-algos", "@"),
876 ARGPARSE_s_n (oAllowOldCipherAlgos, "allow-old-cipher-algos", "@"),
877 ARGPARSE_s_s (oWeakDigest, "weak-digest","@"),
878 ARGPARSE_s_s (oVerifyOptions, "verify-options", "@"),
879 ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"),
880 ARGPARSE_s_n (oNoRandomSeedFile, "no-random-seed-file", "@"),
881 ARGPARSE_s_n (oNoSigCache, "no-sig-cache", "@"),
882 ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"),
883 ARGPARSE_s_n (oIgnoreValidFrom, "ignore-valid-from", "@"),
884 ARGPARSE_s_n (oIgnoreCrcError, "ignore-crc-error", "@"),
885 ARGPARSE_s_n (oIgnoreMDCError, "ignore-mdc-error", "@"),
886 ARGPARSE_s_s (oDisableCipherAlgo, "disable-cipher-algo", "@"),
887 ARGPARSE_s_s (oDisablePubkeyAlgo, "disable-pubkey-algo", "@"),
888 ARGPARSE_s_s (oCipherAlgo, "cipher-algo", "@"),
889 ARGPARSE_s_s (oDigestAlgo, "digest-algo", "@"),
890 ARGPARSE_s_s (oCertDigestAlgo, "cert-digest-algo", "@"),
893 ARGPARSE_header (NULL, N_("Options for unattended use")),
895 ARGPARSE_s_n (oBatch, "batch", "@"),
896 ARGPARSE_s_n (oNoBatch, "no-batch", "@"),
897 ARGPARSE_s_n (oAnswerYes, "yes", "@"),
898 ARGPARSE_s_n (oAnswerNo, "no", "@"),
899 ARGPARSE_s_i (oStatusFD, "status-fd", "@"),
900 ARGPARSE_s_s (oStatusFile, "status-file", "@"),
901 ARGPARSE_s_i (oAttributeFD, "attribute-fd", "@"),
902 ARGPARSE_s_s (oAttributeFile, "attribute-file", "@"),
903 ARGPARSE_s_i (oCommandFD, "command-fd", "@"),
904 ARGPARSE_s_s (oCommandFile, "command-file", "@"),
905 ARGPARSE_o_s (oPassphrase, "passphrase", "@"),
906 ARGPARSE_s_i (oPassphraseFD, "passphrase-fd", "@"),
907 ARGPARSE_s_s (oPassphraseFile, "passphrase-file", "@"),
908 ARGPARSE_s_i (oPassphraseRepeat,"passphrase-repeat", "@"),
909 ARGPARSE_s_s (oPinentryMode, "pinentry-mode", "@"),
910 ARGPARSE_s_n (oForceSignKey, "force-sign-key", "@"),
912 ARGPARSE_header (NULL, N_("Other options")),
914 ARGPARSE_s_s (oRequestOrigin, "request-origin", "@"),
915 ARGPARSE_s_s (oDisplay, "display", "@"),
916 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
917 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
918 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
919 ARGPARSE_s_s (oLCmessages, "lc-messages","@"),
920 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
921 ARGPARSE_s_s (oChUid, "chuid", "@"),
922 ARGPARSE_s_n (oNoAutostart, "no-autostart", "@"),
923 ARGPARSE_s_n (oUseKeyboxd, "use-keyboxd", "@"),
924 ARGPARSE_s_n (oForbidGenKey, "forbid-gen-key", "@"),
925 ARGPARSE_s_n (oRequireCompliance, "require-compliance", "@"),
926 ARGPARSE_s_s (oCompatibilityFlags, "compatibility-flags", "@"),
927 /* Options which can be used in special circumstances. They are not
928 * published and we hope they are never required. */
929 ARGPARSE_s_n (oUseOnlyOpenPGPCard, "use-only-openpgp-card", "@"),
930 /* Esoteric compatibility options. */
931 ARGPARSE_s_n (oRFC2440Text, "rfc2440-text", "@"),
932 ARGPARSE_s_n (oNoRFC2440Text, "no-rfc2440-text", "@"),
933 ARGPARSE_p_u (oKbxBufferSize, "kbx-buffer-size", "@"),
934 ARGPARSE_s_n (oQuickRandom, "debug-quick-random", "@"),
935 ARGPARSE_s_n (oDebugIgnoreExpiration, "debug-ignore-expiration", "@"),
937 ARGPARSE_header (NULL, ""), /* Stop the header group. */
939 /* Aliases. I constantly mistype these, and assume other people do
941 ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-prefs", "@"),
942 ARGPARSE_s_s (oPersonalCompressPreferences, "personal-compress-prefs", "@"),
944 /* These two are aliases to help users of the PGP command line
945 product use gpg with minimal pain. Many commands are common
946 already as they seem to have borrowed commands from us. Now I'm
947 returning the favor. */
948 ARGPARSE_s_s (oLocalUser, "sign-with", "@"),
949 ARGPARSE_s_s (oRecipient, "user", "@"),
952 /* Dummy options with warnings. */
953 ARGPARSE_s_n (oUseAgent, "use-agent", "@"),
954 ARGPARSE_s_n (oNoUseAgent, "no-use-agent", "@"),
955 ARGPARSE_s_s (oGpgAgentInfo, "gpg-agent-info", "@"),
956 ARGPARSE_s_s (oReaderPort, "reader-port", "@"),
957 ARGPARSE_s_s (octapiDriver, "ctapi-driver", "@"),
958 ARGPARSE_s_s (opcscDriver, "pcsc-driver", "@"),
959 ARGPARSE_s_n (oDisableCCID, "disable-ccid", "@"),
960 ARGPARSE_s_n (oHonorHttpProxy, "honor-http-proxy", "@"),
961 ARGPARSE_s_s (oTOFUDBFormat, "tofu-db-format", "@"),
964 ARGPARSE_ignore (oStrict, "strict"),
965 ARGPARSE_ignore (oNoStrict, "no-strict"),
966 ARGPARSE_ignore (oLoadExtension, "load-extension"), /* from 1.4. */
968 ARGPARSE_s_n (oNoop, "sk-comments", "@"),
969 ARGPARSE_s_n (oNoop, "no-sk-comments", "@"),
970 ARGPARSE_s_n (oNoop, "compress-keys", "@"),
971 ARGPARSE_s_n (oNoop, "compress-sigs", "@"),
972 ARGPARSE_s_n (oNoop, "force-v3-sigs", "@"),
973 ARGPARSE_s_n (oNoop, "no-force-v3-sigs", "@"),
974 ARGPARSE_s_n (oNoop, "force-v4-certs", "@"),
975 ARGPARSE_s_n (oNoop, "no-force-v4-certs", "@"),
976 ARGPARSE_s_n (oNoop, "no-mdc-warning", "@"),
977 ARGPARSE_s_n (oNoop, "force-mdc", "@"),
978 ARGPARSE_s_n (oNoop, "no-force-mdc", "@"),
979 ARGPARSE_s_n (oNoop, "disable-mdc", "@"),
980 ARGPARSE_s_n (oNoop, "no-disable-mdc", "@"),
981 ARGPARSE_s_n (oNoop, "allow-multisig-verification", "@"),
982 ARGPARSE_s_n (oNoop, "allow-multiple-messages", "@"),
983 ARGPARSE_s_n (oNoop, "no-allow-multiple-messages", "@"),
984 ARGPARSE_s_s (oNoop, "aead-algo", "@"),
985 ARGPARSE_s_s (oNoop, "personal-aead-preferences","@"),
986 ARGPARSE_s_n (oNoop, "rfc4880bis", "@"),
987 ARGPARSE_s_n (oNoop, "override-compliance-check", "@"),
990 ARGPARSE_group (302, N_(
991 "@\n(See the man page for a complete listing of all commands and options)\n"
994 ARGPARSE_group (303, N_("@\nExamples:\n\n"
995 " -se -r Bob [file] sign and encrypt for user Bob\n"
996 " --clear-sign [file] make a clear text signature\n"
997 " --detach-sign [file] make a detached signature\n"
998 " --list-keys [names] show keys\n"
999 " --fingerprint [names] show fingerprints\n")),
1006 /* The list of supported debug flags. */
1007 static struct debug_flags_s debug_flags [] =
1009 { DBG_PACKET_VALUE , "packet" },
1010 { DBG_MPI_VALUE , "mpi" },
1011 { DBG_CRYPTO_VALUE , "crypto" },
1012 { DBG_FILTER_VALUE , "filter" },
1013 { DBG_IOBUF_VALUE , "iobuf" },
1014 { DBG_MEMORY_VALUE , "memory" },
1015 { DBG_CACHE_VALUE , "cache" },
1016 { DBG_MEMSTAT_VALUE, "memstat" },
1017 { DBG_TRUST_VALUE , "trust" },
1018 { DBG_HASHING_VALUE, "hashing" },
1019 { DBG_IPC_VALUE , "ipc" },
1020 { DBG_CLOCK_VALUE , "clock" },
1021 { DBG_LOOKUP_VALUE , "lookup" },
1022 { DBG_EXTPROG_VALUE, "extprog" },
1027 /* The list of compatibility flags. */
1028 static struct compatibility_flags_s compatibility_flags [] =
1034 #ifdef ENABLE_SELINUX_HACKS
1035 #define ALWAYS_ADD_KEYRINGS 1
1037 #define ALWAYS_ADD_KEYRINGS 0
1040 /* The list of the default AKL methods. */
1041 #define DEFAULT_AKL_LIST "local,wkd"
1043 /* Can be set to true to force gpg to return with EXIT_FAILURE. */
1044 int g10_errors_seen = 0;
1045 /* If opt.assert_signer_list is used and this variabale is not true
1046 * gpg will be forced to return EXIT_FAILURE. */
1047 int assert_signer_true = 0;
1050 static int utf8_strings =
1051 #ifdef HAVE_W32_SYSTEM
1057 static int maybe_setuid = 1;
1058 static unsigned int opt_set_iobuf_size;
1059 static unsigned int opt_set_iobuf_size_used;
1060 static int opt_log_time;
1062 /* Collection of options used only in this module. */
1064 unsigned int forbid_gen_key;
1068 static char *build_list( const char *text, char letter,
1069 const char *(*mapf)(int), int (*chkf)(int) );
1070 static void set_cmd( enum cmd_and_opt_values *ret_cmd,
1071 enum cmd_and_opt_values new_cmd );
1072 static void print_mds( const char *fname, int algo );
1073 static void add_notation_data( const char *string, int which );
1074 static void add_policy_url( const char *string, int which );
1075 static void add_keyserver_url( const char *string, int which );
1076 static void emergency_cleanup (void);
1077 static void read_sessionkey_from_fd (int fd);
1081 /* NPth wrapper function definitions. */
1082 ASSUAN_SYSTEM_NPTH_IMPL;
1086 make_libversion (const char *libname, const char *(*getfnc)(const char*))
1093 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
1097 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
1098 strcpy (stpcpy (stpcpy (result, libname), " "), s);
1104 build_list_pk_test_algo (int algo)
1106 /* Show only one "RSA" string. If RSA_E or RSA_S is available RSA
1107 is also available. */
1108 if (algo == PUBKEY_ALGO_RSA_E
1109 || algo == PUBKEY_ALGO_RSA_S)
1110 return GPG_ERR_DIGEST_ALGO;
1112 return openpgp_pk_test_algo (algo);
1116 build_list_pk_algo_name (int algo)
1118 return openpgp_pk_algo_name (algo);
1122 build_list_cipher_test_algo (int algo)
1124 return openpgp_cipher_test_algo (algo);
1128 build_list_cipher_algo_name (int algo)
1130 return openpgp_cipher_algo_name (algo);
1134 build_list_md_test_algo (int algo)
1136 /* By default we do not accept MD5 based signatures. To avoid
1137 confusion we do not announce support for it either. */
1138 if (algo == DIGEST_ALGO_MD5)
1139 return GPG_ERR_DIGEST_ALGO;
1141 return openpgp_md_test_algo (algo);
1145 build_list_md_algo_name (int algo)
1147 return openpgp_md_algo_name (algo);
1152 my_strusage( int level )
1154 static char *digests, *pubkeys, *ciphers, *zips, *ver_gcry;
1158 case 9: p = "GPL-3.0-or-later"; break;
1159 case 11: p = "@GPG@ (@GNUPG@)";
1161 case 13: p = VERSION; break;
1162 case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break;
1164 case 17: p = PRINTABLE_OS_NAME; break;
1165 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
1169 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
1173 #ifdef IS_DEVELOPMENT_VERSION
1175 p="NOTE: THIS IS A DEVELOPMENT VERSION!";
1178 p="It is only intended for test purposes and should NOT be";
1181 p="used in a production environment or with production keys!";
1187 _("Usage: @GPG@ [options] [files] (-h for help)");
1190 _("Syntax: @GPG@ [options] [files]\n"
1191 "Sign, check, encrypt or decrypt\n"
1192 "Default operation depends on the input data\n");
1195 case 31: p = "\nHome: "; break;
1197 case 32: p = gnupg_homedir (); break;
1198 #else /* __riscos__ */
1199 case 32: p = make_filename(gnupg_homedir (), NULL); break;
1200 #endif /* __riscos__ */
1201 case 33: p = _("\nSupported algorithms:\n"); break;
1204 pubkeys = build_list (_("Pubkey: "), 1,
1205 build_list_pk_algo_name,
1206 build_list_pk_test_algo );
1211 ciphers = build_list(_("Cipher: "), 'S',
1212 build_list_cipher_algo_name,
1213 build_list_cipher_test_algo );
1218 digests = build_list(_("Hash: "), 'H',
1219 build_list_md_algo_name,
1220 build_list_md_test_algo );
1225 zips = build_list(_("Compression: "),'Z',
1226 compress_algo_to_string,
1227 check_compress_algo);
1232 p = "1"; /* <-- Enable globbing under Windows (see init.c) */
1242 build_list (const char *text, char letter,
1243 const char * (*mapf)(int), int (*chkf)(int))
1253 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
1255 indent = utf8_charcount (text, -1);
1257 init_membuf (&mb, 512);
1259 limit = (letter == 'A')? 4 : 110;
1260 for (i=0; i <= limit; i++ )
1262 if (!chkf (i) && (s = mapf (i)))
1264 if (mb.len - len > 60)
1266 put_membuf_str (&mb, ",\n");
1268 for (j=0; j < indent; j++)
1269 put_membuf_str (&mb, " ");
1272 put_membuf_str (&mb, ", ");
1274 put_membuf_str (&mb, text);
1276 put_membuf_str (&mb, s);
1277 if (opt.verbose && letter)
1281 snprintf (num, sizeof num, " (%d)", i);
1283 snprintf (num, sizeof num, " (%c%d)", letter, i);
1284 put_membuf_str (&mb, num);
1289 put_membuf_str (&mb, "\n");
1290 put_membuf (&mb, "", 1);
1292 string = get_membuf (&mb, NULL);
1293 return xrealloc (string, strlen (string)+1);
1298 wrong_args( const char *text)
1300 es_fprintf (es_stderr, _("usage: %s [options] %s\n"), GPG_NAME, text);
1301 log_inc_errorcount ();
1307 make_username( const char *string )
1311 p = xstrdup(string);
1313 p = native_to_utf8( string );
1319 set_opt_session_env (const char *name, const char *value)
1323 err = session_env_setenv (opt.session_env, name, value);
1325 log_fatal ("error setting session environment: %s\n",
1326 gpg_strerror (err));
1330 /* Setup the debugging. With a LEVEL of NULL only the active debug
1331 flags are propagated to the subsystems. With LEVEL set, a specific
1332 set of debug flags is set; thus overriding all flags already
1335 set_debug (const char *level)
1337 int numok = (level && digitp (level));
1338 int numlvl = numok? atoi (level) : 0;
1342 else if (!strcmp (level, "none") || (numok && numlvl < 1))
1344 else if (!strcmp (level, "basic") || (numok && numlvl <= 2))
1345 opt.debug = DBG_MEMSTAT_VALUE;
1346 else if (!strcmp (level, "advanced") || (numok && numlvl <= 5))
1347 opt.debug = DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE;
1348 else if (!strcmp (level, "expert") || (numok && numlvl <= 8))
1349 opt.debug = (DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE
1350 |DBG_CACHE_VALUE|DBG_LOOKUP|DBG_FILTER_VALUE|DBG_PACKET_VALUE);
1351 else if (!strcmp (level, "guru") || numok)
1354 /* Unless the "guru" string has been used we don't want to allow
1355 hashing debugging. The rationale is that people tend to
1356 select the highest debug value and would then clutter their
1357 disk with debug files which may reveal confidential data. */
1359 opt.debug &= ~(DBG_HASHING_VALUE);
1363 log_error (_("invalid debug-level '%s' given\n"), level);
1367 if ((opt.debug & DBG_MEMORY_VALUE))
1368 memory_debug_mode = 1;
1369 if ((opt.debug & DBG_MEMSTAT_VALUE))
1370 memory_stat_debug_mode = 1;
1372 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
1374 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
1375 if ((opt.debug & DBG_IOBUF_VALUE))
1376 iobuf_debug_mode = 1;
1377 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1380 parse_debug_flag (NULL, &opt.debug, debug_flags);
1382 /* Make sure that we are --verbose in debug mode. */
1383 if (opt.debug && !opt.verbose)
1385 if (opt.debug && opt.quiet)
1388 if (opt_set_iobuf_size || opt_set_iobuf_size_used)
1389 log_debug ("iobuf buffer size is %uk\n",
1390 iobuf_set_buffer_size (opt_set_iobuf_size));
1394 /* We set the screen dimensions for UI purposes. Do not allow screens
1395 smaller than 80x24 for the sake of simplicity. */
1397 set_screen_dimensions(void)
1399 #ifndef HAVE_W32_SYSTEM
1402 str=getenv("COLUMNS");
1404 opt.screen_columns=atoi(str);
1406 str=getenv("LINES");
1408 opt.screen_lines=atoi(str);
1411 if(opt.screen_columns<80 || opt.screen_columns>255)
1412 opt.screen_columns=80;
1414 if(opt.screen_lines<24 || opt.screen_lines>255)
1415 opt.screen_lines=24;
1419 /* Helper to open a file FNAME either for reading or writing to be
1420 used with --status-file etc functions. Not generally useful but it
1421 avoids the riscos specific functions and well some Windows people
1422 might like it too. Prints an error message and returns -1 on
1423 error. On success the file descriptor is returned. */
1425 open_info_file (const char *fname, int for_write, int binary)
1428 return riscos_fdopenfile (fname, for_write);
1429 #elif defined (ENABLE_SELINUX_HACKS)
1430 /* We can't allow these even when testing for a secured filename
1431 because files to be secured might not yet been secured. This is
1432 similar to the option file but in that case it is unlikely that
1433 sensitive information may be retrieved by means of error
1443 binary = MY_O_BINARY;
1445 /* if (is_secured_filename (fname)) */
1448 /* gpg_err_set_errno (EPERM); */
1455 fd = gnupg_open (fname, O_CREAT | O_TRUNC | O_WRONLY | binary,
1456 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
1458 fd = gnupg_open (fname, O_RDONLY | binary, 0);
1460 while (fd == -1 && errno == EINTR);
1463 log_error ( for_write? _("can't create '%s': %s\n")
1464 : _("can't open '%s': %s\n"), fname, strerror(errno));
1471 set_cmd( enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd )
1473 enum cmd_and_opt_values cmd = *ret_cmd;
1475 if( !cmd || cmd == new_cmd )
1477 else if( cmd == aSign && new_cmd == aEncr )
1479 else if( cmd == aEncr && new_cmd == aSign )
1481 else if( cmd == aSign && new_cmd == aSym )
1483 else if( cmd == aSym && new_cmd == aSign )
1485 else if( cmd == aSym && new_cmd == aEncr )
1487 else if( cmd == aEncr && new_cmd == aSym )
1489 else if (cmd == aSignEncr && new_cmd == aSym)
1491 else if (cmd == aSignSym && new_cmd == aEncr)
1493 else if (cmd == aEncrSym && new_cmd == aSign)
1495 else if( ( cmd == aSign && new_cmd == aClearsign )
1496 || ( cmd == aClearsign && new_cmd == aSign ) )
1499 log_error(_("conflicting commands\n"));
1508 add_group(char *string)
1511 struct groupitem *item;
1513 /* Break off the group name */
1514 name=strsep(&string,"=");
1517 log_error(_("no = sign found in group definition '%s'\n"),name);
1521 trim_trailing_ws(name,strlen(name));
1523 /* Does this group already exist? */
1524 for(item=opt.grouplist;item;item=item->next)
1525 if(strcasecmp(item->name,name)==0)
1530 item=xmalloc(sizeof(struct groupitem));
1532 item->next=opt.grouplist;
1537 /* Break apart the values */
1538 while ((value= strsep(&string," \t")))
1541 add_to_strlist2(&item->values,value,utf8_strings);
1547 rm_group(char *name)
1549 struct groupitem *item,*last=NULL;
1551 trim_trailing_ws(name,strlen(name));
1553 for(item=opt.grouplist;item;last=item,item=item->next)
1555 if(strcasecmp(item->name,name)==0)
1558 last->next=item->next;
1560 opt.grouplist=item->next;
1562 free_strlist(item->values);
1570 /* We need to check three things.
1572 0) The homedir. It must be x00, a directory, and owned by the
1575 1) The options/gpg.conf file. Okay unless it or its containing
1576 directory is group or other writable or not owned by us. Disable
1579 2) Extensions. Same as #1.
1581 Returns true if the item is unsafe. */
1583 check_permissions (const char *path, int item)
1585 #if defined(HAVE_STAT) && !defined(HAVE_DOSISH_SYSTEM)
1586 static int homedir_cache=-1;
1588 struct stat statbuf,dirbuf;
1589 int homedir=0,ret=0,checkonly=0;
1590 int perm=0,own=0,enc_dir_perm=0,enc_dir_own=0;
1592 if(opt.no_perm_warn)
1595 log_assert(item==0 || item==1 || item==2);
1597 /* extensions may attach a path */
1598 if(item==2 && path[0]!=DIRSEP_C)
1600 if(strchr(path,DIRSEP_C))
1601 tmppath=make_filename(path,NULL);
1603 tmppath=make_filename(gnupg_libdir (),path,NULL);
1606 tmppath=xstrdup(path);
1608 /* If the item is located in the homedir, but isn't the homedir,
1609 don't continue if we already checked the homedir itself. This is
1610 to avoid user confusion with an extra options file warning which
1611 could be rectified if the homedir itself had proper
1613 if(item!=0 && homedir_cache>-1
1614 && !ascii_strncasecmp (gnupg_homedir (), tmppath,
1615 strlen (gnupg_homedir ())))
1621 /* It's okay if the file or directory doesn't exist */
1622 if (gnupg_stat (tmppath,&statbuf))
1628 /* Now check the enclosing directory. Theoretically, we could walk
1629 this test up to the root directory /, but for the sake of sanity,
1630 I'm stopping at one level down. */
1631 dir=make_dirname(tmppath);
1633 if (gnupg_stat (dir,&dirbuf) || !S_ISDIR (dirbuf.st_mode))
1643 /* Assume failure */
1648 /* The homedir must be x00, a directory, and owned by the user. */
1650 if(S_ISDIR(statbuf.st_mode))
1652 if(statbuf.st_uid==getuid())
1654 if((statbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1665 else if(item==1 || item==2)
1667 /* The options or extension file. Okay unless it or its
1668 containing directory is group or other writable or not owned
1671 if(S_ISREG(statbuf.st_mode))
1673 if(statbuf.st_uid==getuid() || statbuf.st_uid==0)
1675 if((statbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1677 /* it's not writable, so make sure the enclosing
1678 directory is also not writable */
1679 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1681 if((dirbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1691 /* it's writable, so the enclosing directory had
1692 better not let people get to it. */
1693 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1695 if((dirbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1698 perm=enc_dir_perm=1; /* unclear which one to fix! */
1716 log_info(_("WARNING: unsafe ownership on"
1717 " homedir '%s'\n"),tmppath);
1719 log_info(_("WARNING: unsafe ownership on"
1720 " configuration file '%s'\n"),tmppath);
1722 log_info(_("WARNING: unsafe ownership on"
1723 " extension '%s'\n"),tmppath);
1728 log_info(_("WARNING: unsafe permissions on"
1729 " homedir '%s'\n"),tmppath);
1731 log_info(_("WARNING: unsafe permissions on"
1732 " configuration file '%s'\n"),tmppath);
1734 log_info(_("WARNING: unsafe permissions on"
1735 " extension '%s'\n"),tmppath);
1740 log_info(_("WARNING: unsafe enclosing directory ownership on"
1741 " homedir '%s'\n"),tmppath);
1743 log_info(_("WARNING: unsafe enclosing directory ownership on"
1744 " configuration file '%s'\n"),tmppath);
1746 log_info(_("WARNING: unsafe enclosing directory ownership on"
1747 " extension '%s'\n"),tmppath);
1752 log_info(_("WARNING: unsafe enclosing directory permissions on"
1753 " homedir '%s'\n"),tmppath);
1755 log_info(_("WARNING: unsafe enclosing directory permissions on"
1756 " configuration file '%s'\n"),tmppath);
1758 log_info(_("WARNING: unsafe enclosing directory permissions on"
1759 " extension '%s'\n"),tmppath);
1771 #else /*!(HAVE_STAT && !HAVE_DOSISH_SYSTEM)*/
1775 #endif /*!(HAVE_STAT && !HAVE_DOSISH_SYSTEM)*/
1779 /* Print the OpenPGP defined algo numbers. */
1781 print_algo_numbers(int (*checker)(int))
1800 print_algo_names(int (*checker)(int),const char *(*mapper)(int))
1812 es_printf ("%s",mapper(i));
1817 /* In the future, we can do all sorts of interesting configuration
1818 output here. For now, just give "group" as the Enigmail folks need
1819 it, and pubkey, cipher, hash, and compress as they may be useful
1822 list_config(char *items)
1824 int show_all = !items;
1827 struct groupitem *giter;
1830 if(!opt.with_colons)
1833 while(show_all || (name=strsep(&items," ")))
1837 if(show_all || ascii_strcasecmp(name,"group")==0)
1839 for (giter = opt.grouplist; giter; giter = giter->next)
1843 es_fprintf (es_stdout, "cfg:group:");
1844 es_write_sanitized (es_stdout, giter->name, strlen(giter->name),
1846 es_putc (':', es_stdout);
1848 for(sl=giter->values; sl; sl=sl->next)
1850 es_write_sanitized (es_stdout, sl->d, strlen (sl->d),
1862 if(show_all || ascii_strcasecmp(name,"version")==0)
1864 es_printf("cfg:version:");
1865 es_write_sanitized (es_stdout, VERSION, strlen(VERSION), ":", NULL);
1870 if(show_all || ascii_strcasecmp(name,"pubkey")==0)
1872 es_printf ("cfg:pubkey:");
1873 print_algo_numbers (build_list_pk_test_algo);
1878 if(show_all || ascii_strcasecmp(name,"pubkeyname")==0)
1880 es_printf ("cfg:pubkeyname:");
1881 print_algo_names (build_list_pk_test_algo,
1882 build_list_pk_algo_name);
1887 if(show_all || ascii_strcasecmp(name,"cipher")==0)
1889 es_printf ("cfg:cipher:");
1890 print_algo_numbers (build_list_cipher_test_algo);
1895 if (show_all || !ascii_strcasecmp (name,"ciphername"))
1897 es_printf ("cfg:ciphername:");
1898 print_algo_names (build_list_cipher_test_algo,
1899 build_list_cipher_algo_name);
1905 || ascii_strcasecmp(name,"digest")==0
1906 || ascii_strcasecmp(name,"hash")==0)
1908 es_printf ("cfg:digest:");
1909 print_algo_numbers (build_list_md_test_algo);
1915 || !ascii_strcasecmp(name,"digestname")
1916 || !ascii_strcasecmp(name,"hashname"))
1918 es_printf ("cfg:digestname:");
1919 print_algo_names (build_list_md_test_algo,
1920 build_list_md_algo_name);
1925 if(show_all || ascii_strcasecmp(name,"compress")==0)
1927 es_printf ("cfg:compress:");
1928 print_algo_numbers(check_compress_algo);
1933 if(show_all || ascii_strcasecmp (name, "compressname") == 0)
1935 es_printf ("cfg:compressname:");
1936 print_algo_names (check_compress_algo,
1937 compress_algo_to_string);
1942 if (show_all || !ascii_strcasecmp(name,"ccid-reader-id"))
1944 /* We ignore this for GnuPG 1.4 backward compatibility. */
1948 if (show_all || !ascii_strcasecmp (name,"curve"))
1950 es_printf ("cfg:curve:");
1951 for (iter=0, first=1; (s = openpgp_enum_curves (&iter)); first=0)
1952 es_printf ("%s%s", first?"":";", s);
1957 /* Curve OIDs are rarely useful and thus only printed if requested. */
1958 if (name && !ascii_strcasecmp (name,"curveoid"))
1960 es_printf ("cfg:curveoid:");
1961 for (iter=0, first=1; (s = openpgp_enum_curves (&iter)); first = 0)
1963 s = openpgp_curve_to_oid (s, NULL, NULL);
1964 es_printf ("%s%s", first?"":";", s? s:"[?]");
1974 log_error(_("unknown configuration item '%s'\n"),name);
1979 /* List default values for use by gpgconf. */
1983 es_printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
1984 es_printf ("compliance:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT, "gnupg");
1986 /* The next one is an info only item and should match the macros at
1987 the top of keygen.c */
1988 es_printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1989 get_default_pubkey_algo ());
1990 /* This info only mode tells whether the we are running in de-vs
1991 * compliance mode. This does not test all parameters but the basic
1992 * conditions like a proper RNG and Libgcrypt. AS of now we always
1993 * return 0 because this version of gnupg has not yet received an
1995 es_printf ("compliance_de_vs:%lu:%d:\n", GC_OPT_FLAG_DEFAULT,
1996 0 /*gnupg_rng_is_compliant (CO_DE_VS)*/);
1998 es_printf ("use_keyboxd:%lu:%d:\n", GC_OPT_FLAG_DEFAULT, opt.use_keyboxd);
2004 parse_subpacket_list(char *list)
2007 byte subpackets[128],i;
2012 /* No arguments means all subpackets */
2013 memset(subpackets+1,1,sizeof(subpackets)-1);
2018 memset(subpackets,0,sizeof(subpackets));
2020 /* Merge with earlier copy */
2021 if(opt.show_subpackets)
2025 for(in=opt.show_subpackets;*in;in++)
2027 if(*in>127 || *in<1)
2030 if(!subpackets[*in])
2036 while((tok=strsep(&list," ,")))
2051 xfree(opt.show_subpackets);
2052 opt.show_subpackets=xmalloc(count+1);
2053 opt.show_subpackets[count--]=0;
2055 for(i=1;i<128 && count>=0;i++)
2057 opt.show_subpackets[count--]=i;
2064 parse_list_options(char *str)
2066 char *subpackets=""; /* something that isn't NULL */
2067 struct parse_options lopts[]=
2069 {"show-sig-subpackets",LIST_SHOW_SIG_SUBPACKETS,NULL,
2071 {"show-photos",LIST_SHOW_PHOTOS,NULL,
2072 N_("display photo IDs during key listings")},
2073 {"show-usage",LIST_SHOW_USAGE,NULL,
2074 N_("show key usage information during key listings")},
2075 {"show-policy-urls",LIST_SHOW_POLICY_URLS,NULL,
2076 N_("show policy URLs during signature listings")},
2077 {"show-notations",LIST_SHOW_NOTATIONS,NULL,
2078 N_("show all notations during signature listings")},
2079 {"show-std-notations",LIST_SHOW_STD_NOTATIONS,NULL,
2080 N_("show IETF standard notations during signature listings")},
2081 {"show-standard-notations",LIST_SHOW_STD_NOTATIONS,NULL,
2083 {"show-user-notations",LIST_SHOW_USER_NOTATIONS,NULL,
2084 N_("show user-supplied notations during signature listings")},
2085 {"show-keyserver-urls",LIST_SHOW_KEYSERVER_URLS,NULL,
2086 N_("show preferred keyserver URLs during signature listings")},
2087 {"show-uid-validity",LIST_SHOW_UID_VALIDITY,NULL,
2088 N_("show user ID validity during key listings")},
2089 {"show-unusable-uids",LIST_SHOW_UNUSABLE_UIDS,NULL,
2090 N_("show revoked and expired user IDs in key listings")},
2091 {"show-unusable-subkeys",LIST_SHOW_UNUSABLE_SUBKEYS,NULL,
2092 N_("show revoked and expired subkeys in key listings")},
2093 {"show-unusable-sigs",LIST_SHOW_UNUSABLE_SIGS,NULL,
2094 N_("show signatures with invalid algorithms during signature listings")},
2095 {"show-keyring",LIST_SHOW_KEYRING,NULL,
2096 N_("show the keyring name in key listings")},
2097 {"show-sig-expire",LIST_SHOW_SIG_EXPIRE,NULL,
2098 N_("show expiration dates during signature listings")},
2099 {"show-pref", LIST_SHOW_PREF, NULL,
2100 N_("show preferences")},
2101 {"show-pref-verbose", LIST_SHOW_PREF_VERBOSE, NULL,
2102 N_("show preferences")},
2103 {"show-only-fpr-mbox",LIST_SHOW_ONLY_FPR_MBOX, NULL,
2105 {"sort-sigs", LIST_SORT_SIGS, NULL,
2111 /* C99 allows for non-constant initializers, but we'd like to
2112 compile everywhere, so fill in the show-sig-subpackets argument
2113 here. Note that if the parse_options array changes, we'll have
2114 to change the subscript here. We use a loop here in case the
2115 list above is reordered. */
2116 for (i=0; lopts[i].name; i++)
2117 if (lopts[i].bit == LIST_SHOW_SIG_SUBPACKETS)
2119 lopts[i].value = &subpackets;
2123 if(parse_options(str,&opt.list_options,lopts,1))
2125 if(opt.list_options&LIST_SHOW_SIG_SUBPACKETS)
2127 /* Unset so users can pass multiple lists in. */
2128 opt.list_options&=~LIST_SHOW_SIG_SUBPACKETS;
2129 if(!parse_subpacket_list(subpackets))
2132 else if(subpackets==NULL && opt.show_subpackets)
2134 /* User did 'no-show-subpackets' */
2135 xfree(opt.show_subpackets);
2136 opt.show_subpackets=NULL;
2146 /* Collapses argc/argv into a single string that must be freed */
2148 collapse_args(int argc,char *argv[])
2151 int i,first=1,len=0;
2155 len+=strlen(argv[i])+2;
2156 str=xrealloc(str,len);
2165 strcat(str,argv[i]);
2172 #ifndef NO_TRUST_MODELS
2174 parse_trust_model(const char *model)
2176 if(ascii_strcasecmp(model,"pgp")==0)
2177 opt.trust_model=TM_PGP;
2178 else if(ascii_strcasecmp(model,"classic")==0)
2179 opt.trust_model=TM_CLASSIC;
2180 else if(ascii_strcasecmp(model,"always")==0)
2181 opt.trust_model=TM_ALWAYS;
2182 else if(ascii_strcasecmp(model,"direct")==0)
2183 opt.trust_model=TM_DIRECT;
2185 else if(ascii_strcasecmp(model,"tofu")==0)
2186 opt.trust_model=TM_TOFU;
2187 else if(ascii_strcasecmp(model,"tofu+pgp")==0)
2188 opt.trust_model=TM_TOFU_PGP;
2190 else if(ascii_strcasecmp(model,"auto")==0)
2191 opt.trust_model=TM_AUTO;
2193 log_error("unknown trust model '%s'\n",model);
2195 #endif /*NO_TRUST_MODELS*/
2199 parse_tofu_policy (const char *policystr)
2202 struct { const char *keyword; int policy; } list[] = {
2203 { "auto", TOFU_POLICY_AUTO },
2204 { "good", TOFU_POLICY_GOOD },
2205 { "unknown", TOFU_POLICY_UNKNOWN },
2206 { "bad", TOFU_POLICY_BAD },
2207 { "ask", TOFU_POLICY_ASK }
2211 if (!ascii_strcasecmp (policystr, "help"))
2213 log_info (_("valid values for option '%s':\n"), "--tofu-policy");
2214 for (i=0; i < DIM (list); i++)
2215 log_info (" %s\n", list[i].keyword);
2219 for (i=0; i < DIM (list); i++)
2220 if (!ascii_strcasecmp (policystr, list[i].keyword))
2221 return list[i].policy;
2224 log_error (_("unknown TOFU policy '%s'\n"), policystr);
2226 log_info (_("(use \"help\" to list choices)\n"));
2231 static struct gnupg_compliance_option compliance_options[] =
2233 { "gnupg", oGnuPG },
2234 { "openpgp", oOpenPGP },
2235 { "rfc4880bis", oGnuPG },
2236 { "rfc4880", oRFC4880 },
2237 { "rfc2440", oRFC2440 },
2245 /* Helper to set compliance related options. This is a separate
2246 * function so that it can also be used by the --compliance option
2249 set_compliance_option (enum cmd_and_opt_values option)
2255 /* This is effectively the same as RFC2440, but with
2256 "--enable-dsa2 --no-rfc2440-text --escape-from-lines
2257 --require-cross-certification". */
2258 opt.compliance = CO_RFC4880;
2260 opt.flags.require_cross_cert = 1;
2261 opt.rfc2440_text = 0;
2262 opt.allow_non_selfsigned_uid = 1;
2263 opt.allow_freeform_uid = 1;
2264 opt.escape_from = 1;
2265 opt.not_dash_escaped = 0;
2266 opt.def_cipher_algo = 0;
2267 opt.def_digest_algo = 0;
2268 opt.cert_digest_algo = 0;
2269 opt.compress_algo = -1;
2270 opt.s2k_mode = 3; /* iterated+salted */
2271 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2272 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2273 opt.flags.allow_old_cipher_algos = 1;
2276 opt.compliance = CO_RFC2440;
2278 opt.rfc2440_text = 1;
2279 opt.allow_non_selfsigned_uid = 1;
2280 opt.allow_freeform_uid = 1;
2281 opt.escape_from = 0;
2282 opt.not_dash_escaped = 0;
2283 opt.def_cipher_algo = 0;
2284 opt.def_digest_algo = 0;
2285 opt.cert_digest_algo = 0;
2286 opt.compress_algo = -1;
2287 opt.s2k_mode = 3; /* iterated+salted */
2288 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2289 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2290 opt.flags.allow_old_cipher_algos = 1;
2292 case oPGP7: opt.compliance = CO_PGP7; break;
2293 case oPGP8: opt.compliance = CO_PGP8; break;
2295 opt.compliance = CO_GNUPG;
2299 set_compliance_option (oOpenPGP);
2300 opt.compliance = CO_DE_VS;
2301 /* We divert here from the backward compatible rfc4880 algos. */
2302 opt.s2k_digest_algo = DIGEST_ALGO_SHA256;
2303 opt.s2k_cipher_algo = CIPHER_ALGO_AES256;
2313 gen_key_forbidden (void)
2315 write_status_failure ("gen-key", gpg_error (GPG_ERR_NOT_ENABLED));
2316 log_error (_("This command is not allowed while in %s mode.\n"),
2321 /* This function called to initialized a new control object. It is
2322 assumed that this object has been zeroed out before calling this
2325 gpg_init_default_ctrl (ctrl_t ctrl)
2327 ctrl->magic = SERVER_CONTROL_MAGIC;
2331 /* This function is called to deinitialize a control object. It is
2334 gpg_deinit_default_ctrl (ctrl_t ctrl)
2337 tofu_closedbs (ctrl);
2339 gpg_dirmngr_deinit_session_data (ctrl);
2341 keydb_release (ctrl->cached_getkey_kdb);
2342 gpg_keyboxd_deinit_session_data (ctrl);
2343 xfree (ctrl->secret_keygrips);
2344 ctrl->secret_keygrips = NULL;
2349 main (int argc, char **argv)
2351 gpgrt_argparse_t pargs;
2360 strlist_t remusr = NULL;
2361 strlist_t locusr = NULL;
2362 strlist_t nrings = NULL;
2363 armor_filter_context_t *afx = NULL;
2364 int detached_sig = 0;
2365 char *last_configname = NULL;
2366 const char *configname = NULL; /* NULL or points to last_configname.
2367 * NULL also indicates that we are
2368 * processing options from the cmdline. */
2369 int debug_argparser = 0;
2370 int default_keyring = 1;
2373 char *logfile = NULL;
2374 int use_random_seed = 1;
2375 enum cmd_and_opt_values cmd = 0;
2376 const char *debug_level = NULL;
2377 #ifndef NO_TRUST_MODELS
2378 const char *trustdb_name = NULL;
2379 #endif /*!NO_TRUST_MODELS*/
2380 char *def_cipher_string = NULL;
2381 char *def_digest_string = NULL;
2382 char *compress_algo_string = NULL;
2383 char *cert_digest_string = NULL;
2384 char *s2k_cipher_string = NULL;
2385 char *s2k_digest_string = NULL;
2386 char *pers_cipher_list = NULL;
2387 char *pers_digest_list = NULL;
2388 char *pers_compress_list = NULL;
2392 int ovrseskeyfd = -1;
2393 int fpr_maybe_cmd = 0; /* --fingerprint maybe a command. */
2394 int any_explicit_recipient = 0;
2395 int default_akl = 1;
2396 int require_secmem = 0;
2398 struct assuan_malloc_hooks malloc_hooks;
2401 static int print_dane_records;
2402 static int allow_large_chunks;
2403 static const char *homedirvalue;
2404 static const char *changeuser;
2409 #endif /* __riscos__ */
2411 /* Please note that we may running SUID(ROOT), so be very CAREFUL
2412 when adding any stuff between here and the call to
2413 secmem_init() somewhere after the option parsing. */
2414 early_system_init ();
2415 gnupg_reopen_std (GPG_NAME);
2417 gnupg_rl_initialize ();
2418 gpgrt_set_strusage (my_strusage);
2419 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
2420 log_set_prefix (GPG_NAME, GPGRT_LOG_WITH_PREFIX|GPGRT_LOG_NO_REGISTRY);
2422 /* Make sure that our subsystems are ready. */
2424 init_common_subsystems (&argc, &argv);
2426 /* Use our own logging handler for Libcgrypt. */
2427 setup_libgcrypt_logging ();
2429 /* Put random number into secure memory */
2430 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
2432 may_coredump = disable_core_dumps();
2434 gnupg_init_signals (0, emergency_cleanup);
2436 dotlock_create (NULL, 0); /* Register lock file cleanup. */
2438 /* Tell the compliance module who we are. */
2439 gnupg_initialize_compliance (GNUPG_MODULE_NAME_GPG);
2442 opt.session_env = session_env_new ();
2443 if (!opt.session_env)
2444 log_fatal ("error allocating session environment block: %s\n",
2447 opt.command_fd = -1; /* no command fd */
2448 opt.compress_level = -1; /* defaults to standard compress level */
2449 opt.bz2_compress_level = -1; /* defaults to standard compress level */
2450 /* note: if you change these lines, look at oOpenPGP */
2451 opt.def_cipher_algo = 0;
2452 opt.def_digest_algo = 0;
2453 opt.cert_digest_algo = 0;
2454 opt.compress_algo = -1; /* defaults to DEFAULT_COMPRESS_ALGO */
2455 opt.s2k_mode = 3; /* iterated+salted */
2456 opt.s2k_count = 0; /* Auto-calibrate when needed. */
2457 opt.s2k_cipher_algo = DEFAULT_CIPHER_ALGO;
2458 opt.completes_needed = 1;
2459 opt.marginals_needed = 3;
2460 opt.max_cert_depth = 5;
2461 opt.escape_from = 1;
2462 opt.flags.require_cross_cert = 1;
2463 opt.import_options = (IMPORT_REPAIR_KEYS
2464 | IMPORT_COLLAPSE_UIDS
2465 | IMPORT_COLLAPSE_SUBKEYS);
2466 opt.export_options = EXPORT_ATTRIBUTES;
2467 opt.keyserver_options.import_options = (IMPORT_REPAIR_KEYS
2468 | IMPORT_REPAIR_PKS_SUBKEY_BUG
2469 | IMPORT_SELF_SIGS_ONLY
2470 | IMPORT_COLLAPSE_UIDS
2471 | IMPORT_COLLAPSE_SUBKEYS
2473 opt.keyserver_options.export_options = EXPORT_ATTRIBUTES;
2474 opt.keyserver_options.options = 0;
2475 opt.verify_options = (LIST_SHOW_UID_VALIDITY
2476 | VERIFY_SHOW_POLICY_URLS
2477 | VERIFY_SHOW_STD_NOTATIONS
2478 | VERIFY_SHOW_KEYSERVER_URLS);
2479 opt.list_options = (LIST_SHOW_UID_VALIDITY
2482 #ifdef NO_TRUST_MODELS
2483 opt.trust_model = TM_ALWAYS;
2485 opt.trust_model = TM_AUTO;
2487 opt.tofu_default_policy = TOFU_POLICY_AUTO;
2488 opt.mangle_dos_filenames = 0;
2489 opt.min_cert_level = 2;
2490 set_screen_dimensions ();
2491 opt.keyid_format = KF_NONE;
2492 opt.def_sig_expire = "0";
2493 opt.def_cert_expire = "0";
2494 opt.passphrase_repeat = 1;
2495 opt.emit_version = 0;
2496 opt.weak_digests = NULL;
2497 opt.compliance = CO_GNUPG;
2499 /* Check special options given on the command line. */
2504 pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
2505 while (gpgrt_argparse (NULL, &pargs, opts))
2507 switch (pargs.r_opt)
2515 es_setvbuf (es_stdout, NULL, _IOLBF, 0);
2519 /* Set here here because the homedir would otherwise be
2520 * created before main option parsing starts. */
2521 opt.no_homedir_creation = 1;
2525 homedirvalue = pargs.r.ret_str;
2529 changeuser = pargs.r.ret_str;
2532 case oNoPermissionWarn:
2533 opt.no_perm_warn = 1;
2537 /* Reset the flags. */
2538 pargs.flags &= ~(ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
2540 #ifdef HAVE_DOSISH_SYSTEM
2541 /* FIXME: Do we still need this? No: gnupg_homedir calls
2542 * make_filename which changes the slashed anyway. IsDBCSLeadByte still
2543 * needed? See bug #561. */
2544 if ( strchr (gnupg_homedir (), '\\') ) {
2545 char *d, *buf = xmalloc (strlen (gnupg_homedir ())+1);
2547 for (d=buf, s = gnupg_homedir (); *s; s++)
2549 *d++ = *s == '\\'? '/': *s;
2550 #ifdef HAVE_W32_SYSTEM
2551 if (s[1] && IsDBCSLeadByte (*s))
2556 gnupg_set_homedir (buf);
2560 /* Initialize the secure memory. */
2561 if (!gcry_control (GCRYCTL_INIT_SECMEM, SECMEM_BUFFER_SIZE, 0))
2563 #if defined(HAVE_GETUID) && defined(HAVE_GETEUID)
2564 /* There should be no way to get to this spot while still carrying
2565 setuid privs. Just in case, bomb out if we are. */
2566 if ( getuid () != geteuid () )
2571 /* Okay, we are now working under our real uid */
2573 /* malloc hooks go here ... */
2574 malloc_hooks.malloc = gcry_malloc;
2575 malloc_hooks.realloc = gcry_realloc;
2576 malloc_hooks.free = gcry_free;
2577 assuan_set_malloc_hooks (&malloc_hooks);
2578 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
2579 setup_libassuan_logging (&opt.debug, NULL);
2581 /* Change UID and then set the homedir. */
2582 if (changeuser && gnupg_chuid (changeuser, 0))
2583 log_inc_errorcount (); /* Force later termination. */
2584 gnupg_set_homedir (homedirvalue);
2586 /* Set default options which require that malloc stuff is ready. */
2587 additional_weak_digest ("MD5");
2588 parse_auto_key_locate (DEFAULT_AKL_LIST);
2594 /* We are re-using the struct, thus the reset flag. We OR the
2595 * flags so that the internal intialized flag won't be cleared. */
2596 pargs.flags |= (ARGPARSE_FLAG_RESET
2597 | ARGPARSE_FLAG_KEEP
2599 | ARGPARSE_FLAG_USER
2600 | ARGPARSE_FLAG_USERVERS);
2602 /* By this point we have a homedir, and cannot change it. */
2603 check_permissions (gnupg_homedir (), 0);
2605 /* The configuraton directories for use by gpgrt_argparser. */
2606 gpgrt_set_confdir (GPGRT_CONFDIR_SYS, gnupg_sysconfdir ());
2607 gpgrt_set_confdir (GPGRT_CONFDIR_USER, gnupg_homedir ());
2609 while (gpgrt_argparser (&pargs, opts, GPG_NAME EXTSEP_S "conf" ))
2611 switch (pargs.r_opt)
2613 case ARGPARSE_CONFFILE:
2614 if (debug_argparser)
2615 log_info (_("reading options from '%s'\n"),
2616 pargs.r_type? pargs.r.ret_str: "[cmdline]");
2619 xfree (last_configname);
2620 last_configname = xstrdup (pargs.r.ret_str);
2621 configname = last_configname;
2622 if (is_secured_filename (configname))
2624 pargs.r_opt = ARGPARSE_PERMISSION_ERROR;
2625 pargs.err = ARGPARSE_PRINT_ERROR;
2627 else if (strncmp (configname, gnupg_sysconfdir (),
2628 strlen (gnupg_sysconfdir ())))
2630 /* This is not the global config file and thus we
2631 * need to check the permissions: If the file is
2632 * unsafe, then disable any external programs for
2633 * keyserver calls or photo IDs. Since the
2634 * external program to call is set in the options
2635 * file, a unsafe options file can lead to an
2636 * arbitrary program being run. */
2637 if (check_permissions (configname, 1))
2645 /* case oOptions: */
2646 /* case oNoOptions: */
2647 /* We will never see these options here because
2648 * gpgrt_argparse handles them for us. */
2652 case aListGcryptConfig:
2655 set_cmd (&cmd, pargs.r_opt);
2656 /* Do not register a keyring for these commands. */
2657 default_keyring = -1;
2670 #ifdef ENABLE_CARD_SUPPORT
2674 #endif /* ENABLE_CARD_SUPPORT*/
2677 case aLocateExtKeys:
2680 case aExportSecretSub:
2682 case aExportSecretSshKey:
2693 case aUpdateTrustDB:
2695 case aListTrustPath:
2700 case aQuickLSignKey:
2710 case aQuickSetExpire:
2711 case aQuickSetPrimaryUid:
2712 case aQuickUpdatePref:
2713 case aExportOwnerTrust:
2714 case aImportOwnerTrust:
2715 case aRebuildKeydbCaches:
2716 set_cmd (&cmd, pargs.r_opt);
2722 case aDeleteSecretKeys:
2723 case aDeleteSecretAndPublicKeys:
2726 set_cmd (&cmd, pargs.r_opt);
2731 set_cmd (&cmd, pargs.r_opt);
2732 opt.import_options |= IMPORT_SHOW;
2733 opt.import_options |= IMPORT_DRY_RUN;
2734 opt.import_options &= ~IMPORT_REPAIR_KEYS;
2735 opt.list_options |= LIST_SHOW_UNUSABLE_UIDS;
2736 opt.list_options |= LIST_SHOW_UNUSABLE_SUBKEYS;
2737 opt.list_options |= LIST_SHOW_NOTATIONS;
2738 opt.list_options |= LIST_SHOW_POLICY_URLS;
2741 case aDetachedSign: detached_sig = 1; set_cmd( &cmd, aSign ); break;
2743 case aDecryptFiles: multifile=1; /* fall through */
2744 case aDecrypt: set_cmd( &cmd, aDecrypt); break;
2746 case aEncrFiles: multifile=1; /* fall through */
2747 case aEncr: set_cmd( &cmd, aEncr); break;
2749 case aVerifyFiles: multifile=1; /* fall through */
2750 case aVerify: set_cmd( &cmd, aVerify); break;
2753 set_cmd (&cmd, pargs.r_opt);
2758 set_cmd (&cmd, pargs.r_opt);
2761 case oArmor: opt.armor = 1; opt.no_armor=0; break;
2762 case oOutput: opt.outfile = pargs.r.ret_str; break;
2764 case oMaxOutput: opt.max_output = pargs.r.ret_ulong; break;
2766 case oInputSizeHint:
2767 opt.input_size_hint = string_to_u64 (pargs.r.ret_str);
2771 opt.chunk_size = pargs.r.ret_int;
2774 case oQuiet: opt.quiet = 1; break;
2775 case oNoTTY: tty_no_terminal(1); break;
2776 case oDryRun: opt.dry_run = 1; break;
2777 case oInteractive: opt.interactive = 1; break;
2780 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2781 opt.list_options|=LIST_SHOW_UNUSABLE_UIDS;
2782 opt.list_options|=LIST_SHOW_UNUSABLE_SUBKEYS;
2790 case oUseAgent: /* Dummy. */
2794 obsolete_option (configname, pargs.lineno, "no-use-agent");
2797 obsolete_option (configname, pargs.lineno, "gpg-agent-info");
2801 opt.use_keyboxd = 1;
2805 obsolete_scdaemon_option (configname, pargs.lineno, "reader-port");
2808 obsolete_scdaemon_option (configname, pargs.lineno, "ctapi-driver");
2811 obsolete_scdaemon_option (configname, pargs.lineno, "pcsc-driver");
2814 obsolete_scdaemon_option (configname, pargs.lineno, "disable-ccid");
2816 case oHonorHttpProxy:
2817 obsolete_option (configname, pargs.lineno, "honor-http-proxy");
2820 case oAnswerYes: opt.answer_yes = 1; break;
2821 case oAnswerNo: opt.answer_no = 1; break;
2823 case oForceSignKey: opt.flags.force_sign_key = 1; break;
2825 case oKeyring: append_to_strlist( &nrings, pargs.r.ret_str); break;
2826 case oPrimaryKeyring:
2827 sl = append_to_strlist (&nrings, pargs.r.ret_str);
2828 sl->flags = KEYDB_RESOURCE_FLAG_PRIMARY;
2831 deprecated_warning(configname,pargs.lineno,"--show-keyring",
2832 "--list-options ","show-keyring");
2833 opt.list_options|=LIST_SHOW_KEYRING;
2837 if (parse_debug_flag (pargs.r.ret_str, &opt.debug, debug_flags))
2839 pargs.r_opt = ARGPARSE_INVALID_ARG;
2840 pargs.err = ARGPARSE_PRINT_ERROR;
2844 case oDebugAll: opt.debug = ~0; break;
2845 case oDebugLevel: debug_level = pargs.r.ret_str; break;
2847 case oDebugIOLBF: break; /* Already set in pre-parse step. */
2849 case oDebugSetIobufSize:
2850 opt_set_iobuf_size = pargs.r.ret_ulong;
2851 opt_set_iobuf_size_used = 1;
2854 case oDebugAllowLargeChunks:
2855 allow_large_chunks = 1;
2858 case oDebugIgnoreExpiration:
2859 opt.ignore_expiration = 1;
2862 case oCompatibilityFlags:
2863 if (parse_compatibility_flags (pargs.r.ret_str, &opt.compat_flags,
2864 compatibility_flags))
2866 pargs.r_opt = ARGPARSE_INVALID_ARG;
2867 pargs.err = ARGPARSE_PRINT_ERROR;
2872 set_status_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
2875 set_status_fd ( open_info_file (pargs.r.ret_str, 1, 0) );
2878 set_attrib_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
2880 case oAttributeFile:
2881 set_attrib_fd ( open_info_file (pargs.r.ret_str, 1, 1) );
2884 log_set_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1));
2887 logfile = pargs.r.ret_str;
2893 case oWithFingerprint:
2894 opt.with_fingerprint = 1;
2897 case oWithSubkeyFingerprint:
2898 opt.with_subkey_fingerprint = 1;
2900 case oWithICAOSpelling:
2901 opt.with_icao_spelling = 1;
2909 opt.with_keygrip = 1;
2912 case oWithKeyScreening:
2913 opt.with_key_screening = 1;
2917 opt.with_secret = 1;
2921 opt.with_wkd_hash = 1;
2924 case oWithKeyOrigin:
2925 opt.with_key_origin = 1;
2928 case oSecretKeyring:
2929 obsolete_option (configname, pargs.lineno, "secret-keyring");
2932 case oNoArmor: opt.no_armor=1; opt.armor=0; break;
2935 if (default_keyring > 0)
2936 default_keyring = 0;
2939 default_keyring = -1;
2942 case oNoGreeting: nogreeting = 1; break;
2945 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2949 gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
2951 case oEmitVersion: opt.emit_version++; break;
2952 case oNoEmitVersion: opt.emit_version=0; break;
2953 case oCompletesNeeded: opt.completes_needed = pargs.r.ret_int; break;
2954 case oMarginalsNeeded: opt.marginals_needed = pargs.r.ret_int; break;
2955 case oMaxCertDepth: opt.max_cert_depth = pargs.r.ret_int; break;
2957 #ifndef NO_TRUST_MODELS
2958 case oTrustDBName: trustdb_name = pargs.r.ret_str; break;
2960 #endif /*!NO_TRUST_MODELS*/
2962 sl = add_to_strlist (&opt.def_secret_key, pargs.r.ret_str);
2963 sl->flags = (pargs.r_opt << PK_LIST_SHIFT);
2965 sl->flags |= PK_LIST_CONFIG;
2968 if( *pargs.r.ret_str )
2970 xfree (opt.def_recipient);
2971 opt.def_recipient = make_username(pargs.r.ret_str);
2974 case oDefRecipientSelf:
2975 xfree(opt.def_recipient); opt.def_recipient = NULL;
2976 opt.def_recipient_self = 1;
2978 case oNoDefRecipient:
2979 xfree(opt.def_recipient); opt.def_recipient = NULL;
2980 opt.def_recipient_self = 0;
2982 case oHomedir: break;
2983 case oChUid: break; /* Command line only (see above). */
2984 case oNoBatch: opt.batch = 0; break;
2986 case oWithTofuInfo: opt.with_tofu_info = 1; break;
2988 case oWithKeyData: opt.with_key_data=1; /*FALLTHRU*/
2989 case oWithColons: opt.with_colons=':'; break;
2991 case oWithSigCheck: opt.check_sigs = 1; /*FALLTHRU*/
2992 case oWithSigList: opt.list_sigs = 1; break;
2994 case oSkipVerify: opt.skip_verify=1; break;
2996 case oSkipHiddenRecipients: opt.skip_hidden_recipients = 1; break;
2997 case oNoSkipHiddenRecipients: opt.skip_hidden_recipients = 0; break;
2999 case aListSecretKeys: set_cmd( &cmd, aListSecretKeys); break;
3001 #ifndef NO_TRUST_MODELS
3002 /* There are many programs (like mutt) that call gpg with
3003 --always-trust so keep this option around for a long
3005 case oAlwaysTrust: opt.trust_model=TM_ALWAYS; break;
3007 parse_trust_model(pargs.r.ret_str);
3009 #endif /*!NO_TRUST_MODELS*/
3010 case oTOFUDefaultPolicy:
3011 opt.tofu_default_policy = parse_tofu_policy (pargs.r.ret_str);
3014 obsolete_option (configname, pargs.lineno, "tofu-db-format");
3017 case oForceOwnertrust:
3018 log_info(_("Note: %s is not for normal use!\n"),
3019 "--force-ownertrust");
3020 opt.force_ownertrust=string_to_trust_value(pargs.r.ret_str);
3021 if(opt.force_ownertrust==-1)
3023 log_error("invalid ownertrust '%s'\n",pargs.r.ret_str);
3024 opt.force_ownertrust=0;
3028 case oNoAutoTrustNewKey: opt.flags.no_auto_trust_new_key = 1; break;
3032 int compliance = gnupg_parse_compliance_option
3034 compliance_options, DIM (compliance_options),
3038 set_compliance_option (compliance);
3047 set_compliance_option (pargs.r_opt);
3050 case oMinRSALength: opt.min_rsa_length = pargs.r.ret_ulong; break;
3052 case oRFC2440Text: opt.rfc2440_text=1; break;
3053 case oNoRFC2440Text: opt.rfc2440_text=0; break;
3057 opt.set_filename = pargs.r.ret_str;
3059 opt.set_filename = native_to_utf8(pargs.r.ret_str);
3061 case oForYourEyesOnly: eyes_only = 1; break;
3062 case oNoForYourEyesOnly: eyes_only = 0; break;
3064 add_policy_url(pargs.r.ret_str,0);
3065 add_policy_url(pargs.r.ret_str,1);
3067 case oSigPolicyURL: add_policy_url(pargs.r.ret_str,0); break;
3068 case oCertPolicyURL: add_policy_url(pargs.r.ret_str,1); break;
3069 case oShowPolicyURL:
3070 deprecated_warning(configname,pargs.lineno,"--show-policy-url",
3071 "--list-options ","show-policy-urls");
3072 deprecated_warning(configname,pargs.lineno,"--show-policy-url",
3073 "--verify-options ","show-policy-urls");
3074 opt.list_options|=LIST_SHOW_POLICY_URLS;
3075 opt.verify_options|=VERIFY_SHOW_POLICY_URLS;
3077 case oNoShowPolicyURL:
3078 deprecated_warning(configname,pargs.lineno,"--no-show-policy-url",
3079 "--list-options ","no-show-policy-urls");
3080 deprecated_warning(configname,pargs.lineno,"--no-show-policy-url",
3081 "--verify-options ","no-show-policy-urls");
3082 opt.list_options&=~LIST_SHOW_POLICY_URLS;
3083 opt.verify_options&=~VERIFY_SHOW_POLICY_URLS;
3085 case oSigKeyserverURL: add_keyserver_url(pargs.r.ret_str,0); break;
3086 case oUseEmbeddedFilename:
3087 opt.flags.use_embedded_filename=1;
3089 case oNoUseEmbeddedFilename:
3090 opt.flags.use_embedded_filename=0;
3093 if(pargs.r.ret_str[0])
3094 append_to_strlist(&opt.comments,pargs.r.ret_str);
3096 case oDefaultComment:
3097 deprecated_warning(configname,pargs.lineno,
3098 "--default-comment","--no-comments","");
3101 free_strlist(opt.comments);
3104 case oThrowKeyids: opt.throw_keyids = 1; break;
3105 case oNoThrowKeyids: opt.throw_keyids = 0; break;
3107 deprecated_warning(configname,pargs.lineno,"--show-photos",
3108 "--list-options ","show-photos");
3109 deprecated_warning(configname,pargs.lineno,"--show-photos",
3110 "--verify-options ","show-photos");
3111 opt.list_options|=LIST_SHOW_PHOTOS;
3112 opt.verify_options|=VERIFY_SHOW_PHOTOS;
3115 deprecated_warning(configname,pargs.lineno,"--no-show-photos",
3116 "--list-options ","no-show-photos");
3117 deprecated_warning(configname,pargs.lineno,"--no-show-photos",
3118 "--verify-options ","no-show-photos");
3119 opt.list_options&=~LIST_SHOW_PHOTOS;
3120 opt.verify_options&=~VERIFY_SHOW_PHOTOS;
3122 case oPhotoViewer: opt.photo_viewer = pargs.r.ret_str; break;
3124 case oForceAEAD: opt.force_aead = 1; break;
3126 case oDisableSignerUID: opt.flags.disable_signer_uid = 1; break;
3127 case oIncludeKeyBlock: opt.flags.include_key_block = 1; break;
3128 case oNoIncludeKeyBlock: opt.flags.include_key_block = 0; break;
3130 case oS2KMode: opt.s2k_mode = pargs.r.ret_int; break;
3131 case oS2KDigest: s2k_digest_string = xstrdup(pargs.r.ret_str); break;
3132 case oS2KCipher: s2k_cipher_string = xstrdup(pargs.r.ret_str); break;
3134 if (pargs.r.ret_int)
3135 opt.s2k_count = encode_s2k_iterations (pargs.r.ret_int);
3137 opt.s2k_count = 0; /* Auto-calibrate when needed. */
3141 case oHiddenRecipient:
3142 case oRecipientFile:
3143 case oHiddenRecipientFile:
3144 /* Store the recipient. Note that we also store the
3145 * option as private data in the flags. This is achieved
3146 * by shifting the option value to the left so to keep
3147 * enough space for the flags. */
3148 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
3149 sl->flags = (pargs.r_opt << PK_LIST_SHIFT);
3151 sl->flags |= PK_LIST_CONFIG;
3152 if (pargs.r_opt == oHiddenRecipient
3153 || pargs.r_opt == oHiddenRecipientFile)
3154 sl->flags |= PK_LIST_HIDDEN;
3155 if (pargs.r_opt == oRecipientFile
3156 || pargs.r_opt == oHiddenRecipientFile)
3157 sl->flags |= PK_LIST_FROM_FILE;
3158 any_explicit_recipient = 1;
3162 case oHiddenEncryptTo:
3163 /* Store an additional recipient. */
3164 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
3165 sl->flags = ((pargs.r_opt << PK_LIST_SHIFT) | PK_LIST_ENCRYPT_TO);
3167 sl->flags |= PK_LIST_CONFIG;
3168 if (pargs.r_opt == oHiddenEncryptTo)
3169 sl->flags |= PK_LIST_HIDDEN;
3173 opt.no_encrypt_to = 1;
3175 case oEncryptToDefaultKey:
3176 opt.encrypt_to_default_key = configname ? 2 : 1;
3180 add_to_strlist2 (&opt.secret_keys_to_try,
3181 pargs.r.ret_str, utf8_strings);
3184 case oMimemode: opt.mimemode = opt.textmode = 1; break;
3185 case oTextmodeShort: opt.textmode = 2; break;
3186 case oTextmode: opt.textmode=1; break;
3187 case oNoTextmode: opt.textmode=opt.mimemode=0; break;
3189 case oExpert: opt.expert = 1; break;
3190 case oNoExpert: opt.expert = 0; break;
3192 if(*pargs.r.ret_str!='\0')
3194 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
3195 log_error(_("'%s' is not a valid signature expiration\n"),
3198 opt.def_sig_expire=pargs.r.ret_str;
3201 case oAskSigExpire: opt.ask_sig_expire = 1; break;
3202 case oNoAskSigExpire: opt.ask_sig_expire = 0; break;
3203 case oDefCertExpire:
3204 if(*pargs.r.ret_str!='\0')
3206 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
3207 log_error(_("'%s' is not a valid signature expiration\n"),
3210 opt.def_cert_expire=pargs.r.ret_str;
3213 case oAskCertExpire: opt.ask_cert_expire = 1; break;
3214 case oNoAskCertExpire: opt.ask_cert_expire = 0; break;
3215 case oDefCertLevel: opt.def_cert_level=pargs.r.ret_int; break;
3216 case oMinCertLevel: opt.min_cert_level=pargs.r.ret_int; break;
3217 case oAskCertLevel: opt.ask_cert_level = 1; break;
3218 case oNoAskCertLevel: opt.ask_cert_level = 0; break;
3219 case oLocalUser: /* store the local users */
3220 sl = add_to_strlist2( &locusr, pargs.r.ret_str, utf8_strings );
3221 sl->flags = (pargs.r_opt << PK_LIST_SHIFT);
3223 sl->flags |= PK_LIST_CONFIG;
3227 char *mbox = mailbox_from_userid (pargs.r.ret_str, 0);
3229 log_error (_("\"%s\" is not a proper mail address\n"),
3233 add_to_strlist (&opt.sender_list, mbox);
3239 /* this is the -z command line option */
3240 opt.compress_level = opt.bz2_compress_level = pargs.r.ret_int;
3241 opt.explicit_compress_option = 1;
3244 /* --no-compress is the same as -z0 */
3245 opt.compress_level = opt.bz2_compress_level = 0;
3246 opt.explicit_compress_option = 1;
3248 case oCompressLevel: opt.compress_level = pargs.r.ret_int; break;
3249 case oBZ2CompressLevel: opt.bz2_compress_level = pargs.r.ret_int; break;
3250 case oBZ2DecompressLowmem: opt.bz2_decompress_lowmem=1; break;
3252 set_passphrase_from_string (pargs.r_type ? pargs.r.ret_str : "");
3255 pwfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
3257 case oPassphraseFile:
3258 pwfd = open_info_file (pargs.r.ret_str, 0, 1);
3260 case oPassphraseRepeat:
3261 opt.passphrase_repeat = pargs.r.ret_int;
3265 opt.pinentry_mode = parse_pinentry_mode (pargs.r.ret_str);
3266 if (opt.pinentry_mode == -1)
3267 log_error (_("invalid pinentry mode '%s'\n"), pargs.r.ret_str);
3270 case oRequestOrigin:
3271 opt.request_origin = parse_request_origin (pargs.r.ret_str);
3272 if (opt.request_origin == -1)
3273 log_error (_("invalid request origin '%s'\n"), pargs.r.ret_str);
3277 opt.command_fd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
3278 if (! gnupg_fd_valid (opt.command_fd))
3279 log_error ("command-fd is invalid: %s\n", strerror (errno));
3282 opt.command_fd = open_info_file (pargs.r.ret_str, 0, 1);
3285 def_cipher_string = xstrdup(pargs.r.ret_str);
3288 def_digest_string = xstrdup(pargs.r.ret_str);
3291 /* If it is all digits, stick a Z in front of it for
3292 later. This is for backwards compatibility with
3293 versions that took the compress algorithm number. */
3295 char *pt=pargs.r.ret_str;
3298 if (!isascii (*pt) || !isdigit (*pt))
3306 compress_algo_string=xmalloc(strlen(pargs.r.ret_str)+2);
3307 strcpy(compress_algo_string,"Z");
3308 strcat(compress_algo_string,pargs.r.ret_str);
3311 compress_algo_string = xstrdup(pargs.r.ret_str);
3314 case oCertDigestAlgo:
3315 cert_digest_string = xstrdup(pargs.r.ret_str);
3319 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
3322 case oRequireSecmem: require_secmem=1; break;
3323 case oNoRequireSecmem: require_secmem=0; break;
3324 case oNoPermissionWarn: opt.no_perm_warn=1; break;
3325 case oDisplayCharset:
3326 if( set_native_charset( pargs.r.ret_str ) )
3327 log_error(_("'%s' is not a valid character set\n"),
3330 case oNotDashEscaped: opt.not_dash_escaped = 1; break;
3331 case oEscapeFrom: opt.escape_from = 1; break;
3332 case oNoEscapeFrom: opt.escape_from = 0; break;
3333 case oLockOnce: opt.lock_once = 1; break;
3340 #else /* __riscos__ */
3341 riscos_not_implemented("lock-multiple");
3342 #endif /* __riscos__ */
3346 keyserver_spec_t keyserver;
3347 keyserver = parse_keyserver_uri (pargs.r.ret_str, 0);
3349 log_error (_("could not parse keyserver URL\n"));
3352 /* We only support a single keyserver. Later ones
3353 override earlier ones. (Since we parse the
3354 config file first and then the command line
3355 arguments, the command line takes
3358 free_keyserver_spec (opt.keyserver);
3359 opt.keyserver = keyserver;
3363 case oKeyServerOptions:
3364 if(!parse_keyserver_options(pargs.r.ret_str))
3367 log_error(_("%s:%d: invalid keyserver options\n"),
3368 configname,pargs.lineno);
3370 log_error(_("invalid keyserver options\n"));
3373 case oImportOptions:
3374 if(!parse_import_options(pargs.r.ret_str,&opt.import_options,1))
3377 log_error(_("%s:%d: invalid import options\n"),
3378 configname,pargs.lineno);
3380 log_error(_("invalid import options\n"));
3384 rc = parse_and_set_import_filter (pargs.r.ret_str);
3386 log_error (_("invalid filter option: %s\n"), gpg_strerror (rc));
3388 case oExportOptions:
3389 if(!parse_export_options(pargs.r.ret_str,&opt.export_options,1))
3392 log_error(_("%s:%d: invalid export options\n"),
3393 configname,pargs.lineno);
3395 log_error(_("invalid export options\n"));
3399 rc = parse_and_set_export_filter (pargs.r.ret_str);
3401 log_error (_("invalid filter option: %s\n"), gpg_strerror (rc));
3404 rc = parse_and_set_list_filter (pargs.r.ret_str);
3406 log_error (_("invalid filter option: %s\n"), gpg_strerror (rc));
3409 if(!parse_list_options(pargs.r.ret_str))
3412 log_error(_("%s:%d: invalid list options\n"),
3413 configname,pargs.lineno);
3415 log_error(_("invalid list options\n"));
3418 case oVerifyOptions:
3420 struct parse_options vopts[]=
3422 {"show-photos",VERIFY_SHOW_PHOTOS,NULL,
3423 N_("display photo IDs during signature verification")},
3424 {"show-policy-urls",VERIFY_SHOW_POLICY_URLS,NULL,
3425 N_("show policy URLs during signature verification")},
3426 {"show-notations",VERIFY_SHOW_NOTATIONS,NULL,
3427 N_("show all notations during signature verification")},
3428 {"show-std-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
3429 N_("show IETF standard notations during signature verification")},
3430 {"show-standard-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
3432 {"show-user-notations",VERIFY_SHOW_USER_NOTATIONS,NULL,
3433 N_("show user-supplied notations during signature verification")},
3434 {"show-keyserver-urls",VERIFY_SHOW_KEYSERVER_URLS,NULL,
3435 N_("show preferred keyserver URLs during signature verification")},
3436 {"show-uid-validity",VERIFY_SHOW_UID_VALIDITY,NULL,
3437 N_("show user ID validity during signature verification")},
3438 {"show-unusable-uids",VERIFY_SHOW_UNUSABLE_UIDS,NULL,
3439 N_("show revoked and expired user IDs in signature verification")},
3440 {"show-primary-uid-only",VERIFY_SHOW_PRIMARY_UID_ONLY,NULL,
3441 N_("show only the primary user ID in signature verification")},
3445 if(!parse_options(pargs.r.ret_str,&opt.verify_options,vopts,1))
3448 log_error(_("%s:%d: invalid verify options\n"),
3449 configname,pargs.lineno);
3451 log_error(_("invalid verify options\n"));
3455 case oTempDir: opt.temp_dir=pargs.r.ret_str; break;
3457 if(set_exec_path(pargs.r.ret_str))
3458 log_error(_("unable to set exec-path to %s\n"),pargs.r.ret_str);
3460 opt.exec_path_set=1;
3463 add_notation_data( pargs.r.ret_str, 0 );
3464 add_notation_data( pargs.r.ret_str, 1 );
3466 case oSigNotation: add_notation_data( pargs.r.ret_str, 0 ); break;
3467 case oCertNotation: add_notation_data( pargs.r.ret_str, 1 ); break;
3468 case oKnownNotation: register_known_notation (pargs.r.ret_str); break;
3470 deprecated_warning(configname,pargs.lineno,"--show-notation",
3471 "--list-options ","show-notations");
3472 deprecated_warning(configname,pargs.lineno,"--show-notation",
3473 "--verify-options ","show-notations");
3474 opt.list_options|=LIST_SHOW_NOTATIONS;
3475 opt.verify_options|=VERIFY_SHOW_NOTATIONS;
3477 case oNoShowNotation:
3478 deprecated_warning(configname,pargs.lineno,"--no-show-notation",
3479 "--list-options ","no-show-notations");
3480 deprecated_warning(configname,pargs.lineno,"--no-show-notation",
3481 "--verify-options ","no-show-notations");
3482 opt.list_options&=~LIST_SHOW_NOTATIONS;
3483 opt.verify_options&=~VERIFY_SHOW_NOTATIONS;
3485 case oUtf8Strings: utf8_strings = 1; break;
3486 case oNoUtf8Strings:
3487 #ifdef HAVE_W32_SYSTEM
3491 case oDisableCipherAlgo:
3493 int algo = string_to_cipher_algo (pargs.r.ret_str);
3494 gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
3497 case oDisablePubkeyAlgo:
3499 int algo = gcry_pk_map_name (pargs.r.ret_str);
3500 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
3503 case oNoSigCache: opt.no_sig_cache = 1; break;
3504 case oAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid = 1; break;
3505 case oNoAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid=0; break;
3506 case oAllowFreeformUID: opt.allow_freeform_uid = 1; break;
3507 case oNoAllowFreeformUID: opt.allow_freeform_uid = 0; break;
3508 case oNoLiteral: opt.no_literal = 1; break;
3511 /* There are restricts on the value (e.g. < 2^32); you
3512 * need to check the entire code to understand this. */
3513 opt.set_filesize = pargs.r.ret_ulong;
3516 case oFastListMode: opt.fast_list_mode = 1; break;
3517 case oFixedListMode: /* Dummy */ break;
3518 case oLegacyListMode: opt.legacy_list_mode = 1; break;
3519 case oPrintDANERecords: print_dane_records = 1; break;
3520 case oListOnly: opt.list_only=1; break;
3521 case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
3522 case oIgnoreValidFrom: opt.ignore_valid_from = 1; break;
3523 case oIgnoreCrcError: opt.ignore_crc_error = 1; break;
3524 case oIgnoreMDCError: opt.ignore_mdc_error = 1; break;
3525 case oNoRandomSeedFile: use_random_seed = 0; break;
3527 case oAutoKeyImport: opt.flags.auto_key_import = 1; break;
3528 case oNoAutoKeyImport: opt.flags.auto_key_import = 0; break;
3530 case oAutoKeyRetrieve:
3531 opt.keyserver_options.options |= KEYSERVER_AUTO_KEY_RETRIEVE;
3533 case oNoAutoKeyRetrieve:
3534 opt.keyserver_options.options &= ~KEYSERVER_AUTO_KEY_RETRIEVE;
3537 case oShowSessionKey: opt.show_session_key = 1; break;
3538 case oOverrideSessionKey:
3539 opt.override_session_key = pargs.r.ret_str;
3541 case oOverrideSessionKeyFD:
3542 ovrseskeyfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
3545 deprecated_warning(configname,pargs.lineno,"--merge-only",
3546 "--import-options ","merge-only");
3547 opt.import_options|=IMPORT_MERGE_ONLY;
3549 case oAllowSecretKeyImport: /* obsolete */ break;
3550 case oTryAllSecrets: opt.try_all_secrets = 1; break;
3551 case oTrustedKey: register_trusted_key( pargs.r.ret_str ); break;
3553 case oEnableSpecialFilenames:
3554 enable_special_filenames ();
3557 case oNoExpensiveTrustChecks: opt.no_expensive_trust_checks=1; break;
3558 case oAutoCheckTrustDB: opt.no_auto_check_trustdb=0; break;
3559 case oNoAutoCheckTrustDB: opt.no_auto_check_trustdb=1; break;
3560 case oPreservePermissions: opt.preserve_permissions=1; break;
3561 case oDefaultPreferenceList:
3562 opt.def_preference_list = pargs.r.ret_str;
3564 case oDefaultKeyserverURL:
3566 keyserver_spec_t keyserver;
3567 keyserver = parse_keyserver_uri (pargs.r.ret_str,1 );
3569 log_error (_("could not parse keyserver URL\n"));
3571 free_keyserver_spec (keyserver);
3573 opt.def_keyserver_url = pargs.r.ret_str;
3576 case oPersonalCipherPreferences:
3577 pers_cipher_list=pargs.r.ret_str;
3579 case oPersonalDigestPreferences:
3580 pers_digest_list=pargs.r.ret_str;
3582 case oPersonalCompressPreferences:
3583 pers_compress_list=pargs.r.ret_str;
3585 case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
3586 case oKeyboxdProgram: opt.keyboxd_program = pargs.r.ret_str; break;
3587 case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break;
3588 case oDisableDirmngr: opt.disable_dirmngr = 1; break;
3590 additional_weak_digest(pargs.r.ret_str);
3593 opt.unwrap_encryption = 1;
3595 case oOnlySignTextIDs:
3596 opt.only_sign_text_ids = 1;
3600 set_opt_session_env ("DISPLAY", pargs.r.ret_str);
3603 set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
3606 set_opt_session_env ("TERM", pargs.r.ret_str);
3609 set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
3612 case oLCctype: opt.lc_ctype = pargs.r.ret_str; break;
3613 case oLCmessages: opt.lc_messages = pargs.r.ret_str; break;
3615 case oGroup: add_group(pargs.r.ret_str); break;
3616 case oUnGroup: rm_group(pargs.r.ret_str); break;
3618 while(opt.grouplist)
3620 struct groupitem *iter=opt.grouplist;
3621 free_strlist(iter->values);
3622 opt.grouplist=opt.grouplist->next;
3627 case oMangleDosFilenames: opt.mangle_dos_filenames = 1; break;
3628 case oNoMangleDosFilenames: opt.mangle_dos_filenames = 0; break;
3629 case oEnableProgressFilter: opt.enable_progress_filter = 1; break;
3630 case oMultifile: multifile=1; break;
3632 if(ascii_strcasecmp(pargs.r.ret_str,"short")==0)
3633 opt.keyid_format=KF_SHORT;
3634 else if(ascii_strcasecmp(pargs.r.ret_str,"long")==0)
3635 opt.keyid_format=KF_LONG;
3636 else if(ascii_strcasecmp(pargs.r.ret_str,"0xshort")==0)
3637 opt.keyid_format=KF_0xSHORT;
3638 else if(ascii_strcasecmp(pargs.r.ret_str,"0xlong")==0)
3639 opt.keyid_format=KF_0xLONG;
3640 else if(ascii_strcasecmp(pargs.r.ret_str,"none")==0)
3641 opt.keyid_format = KF_NONE;
3643 log_error("unknown keyid-format '%s'\n",pargs.r.ret_str);
3646 case oExitOnStatusWriteError:
3647 opt.exit_on_status_write_error = 1;
3650 case oLimitCardInsertTries:
3651 opt.limit_card_insert_tries = pargs.r.ret_int;
3654 case oRequireCrossCert: opt.flags.require_cross_cert=1; break;
3655 case oNoRequireCrossCert: opt.flags.require_cross_cert=0; break;
3657 case oAutoKeyLocate:
3660 /* This is the first time --auto-key-locate is seen.
3661 * We need to reset the default akl. */
3665 if(!parse_auto_key_locate(pargs.r.ret_str))
3668 log_error(_("%s:%d: invalid auto-key-locate list\n"),
3669 configname,pargs.lineno);
3671 log_error(_("invalid auto-key-locate list\n"));
3674 case oNoAutoKeyLocate:
3679 if(!parse_key_origin (pargs.r.ret_str))
3680 log_error (_("invalid argument for option \"%.50s\"\n"),
3684 case oEnableLargeRSA:
3685 #if SECMEM_BUFFER_SIZE >= 65536
3686 opt.flags.large_rsa=1;
3689 log_info("%s:%d: WARNING: gpg not built with large secure "
3690 "memory buffer. Ignoring enable-large-rsa\n",
3691 configname,pargs.lineno);
3693 log_info("WARNING: gpg not built with large secure "
3694 "memory buffer. Ignoring --enable-large-rsa\n");
3695 #endif /* SECMEM_BUFFER_SIZE >= 65536 */
3697 case oDisableLargeRSA: opt.flags.large_rsa=0;
3700 case oEnableDSA2: opt.flags.dsa2=1; break;
3701 case oDisableDSA2: opt.flags.dsa2=0; break;
3703 case oAllowWeakDigestAlgos:
3704 opt.flags.allow_weak_digest_algos = 1;
3707 case oAllowWeakKeySignatures:
3708 opt.flags.allow_weak_key_signatures = 1;
3711 case oAllowOldCipherAlgos:
3712 opt.flags.allow_old_cipher_algos = 1;
3715 case oFakedSystemTime:
3717 size_t len = strlen (pargs.r.ret_str);
3721 if (len > 0 && pargs.r.ret_str[len-1] == '!')
3724 pargs.r.ret_str[len-1] = '\0';
3727 faked_time = isotime2epoch (pargs.r.ret_str);
3728 if (faked_time == (time_t)(-1))
3729 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
3730 gnupg_set_time (faked_time, freeze);
3734 case oNoAutostart: opt.autostart = 0; break;
3735 case oNoSymkeyCache: opt.no_symkey_cache = 1; break;
3737 case oDefaultNewKeyAlgo:
3738 opt.def_new_key_algo = pargs.r.ret_str;
3741 case oUseOnlyOpenPGPCard:
3742 opt.flags.use_only_openpgp_card = 1;
3745 case oFullTimestrings:
3746 opt.flags.full_timestrings = 1;
3750 mopt.forbid_gen_key = 1;
3753 case oRequireCompliance:
3754 opt.flags.require_compliance = 1;
3757 case oAddDesigRevoker:
3758 if (!strcmp (pargs.r.ret_str, "clear"))
3759 FREE_STRLIST (opt.desig_revokers);
3761 append_to_strlist (&opt.desig_revokers, pargs.r.ret_str);
3765 add_to_strlist (&opt.assert_signer_list, pargs.r.ret_str);
3768 case oKbxBufferSize:
3769 keybox_set_buffersize (pargs.r.ret_ulong, 0);
3776 pargs.err = ARGPARSE_PRINT_WARNING;
3779 pargs.err = ARGPARSE_PRINT_ERROR;
3780 /* The argparse function calls a plain exit and thus
3781 * we need to print a status here. */
3782 write_status_failure ("option-parser",
3783 gpg_error(GPG_ERR_GENERAL));
3789 gpgrt_argparse (NULL, &pargs, NULL); /* Release internal state. */
3791 if (log_get_errorcount (0))
3793 write_status_failure ("option-parser", gpg_error(GPG_ERR_GENERAL));
3797 /* Process common component options. */
3798 if (parse_comopt (GNUPG_MODULE_NAME_GPG, debug_argparser))
3800 write_status_failure ("option-parser", gpg_error(GPG_ERR_GENERAL));
3804 if (opt.use_keyboxd)
3805 log_info ("Note: Please move option \"%s\" to \"common.conf\"\n",
3807 opt.use_keyboxd = comopt.use_keyboxd; /* Override. */
3809 if (opt.keyboxd_program)
3810 log_info ("Note: Please move option \"%s\" to \"common.conf\"\n",
3812 if (!opt.keyboxd_program && comopt.keyboxd_program)
3814 opt.keyboxd_program = comopt.keyboxd_program;
3815 comopt.keyboxd_program = NULL;
3818 if (comopt.no_autostart)
3821 /* The command --gpgconf-list is pretty simple and may be called
3822 directly after the option parsing. */
3823 if (cmd == aGPGConfList)
3828 xfree (last_configname);
3830 if (print_dane_records)
3831 log_error ("invalid option \"%s\"; use \"%s\" instead\n",
3832 "--print-dane-records",
3833 "--export-options export-dane");
3834 if (log_get_errorcount (0))
3836 write_status_failure ("option-checking", gpg_error(GPG_ERR_GENERAL));
3846 es_fprintf (es_stderr, "%s %s; %s\n",
3847 gpgrt_strusage(11), gpgrt_strusage(13), gpgrt_strusage(14));
3848 es_fprintf (es_stderr, "%s\n", gpgrt_strusage(15) );
3850 #ifdef IS_DEVELOPMENT_VERSION
3855 if((s=gpgrt_strusage(25)))
3857 if((s=gpgrt_strusage(26)))
3859 if((s=gpgrt_strusage(27)))
3864 /* Init threading which is used by some helper functions. */
3866 assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
3867 gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
3871 log_set_file (logfile);
3872 log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
3873 | GPGRT_LOG_WITH_TIME
3874 | GPGRT_LOG_WITH_PID ));
3876 else if (opt_log_time)
3877 log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX|GPGRT_LOG_NO_REGISTRY
3878 |GPGRT_LOG_WITH_TIME));
3880 if (opt.verbose > 2)
3881 log_info ("using character set '%s'\n", get_native_charset ());
3883 if( may_coredump && !opt.quiet )
3884 log_info(_("WARNING: program may create a core file!\n"));
3887 if (opt.set_filename)
3888 log_info(_("WARNING: %s overrides %s\n"),
3889 "--for-your-eyes-only","--set-filename");
3891 opt.set_filename="_CONSOLE";
3894 if (opt.no_literal) {
3895 log_info(_("Note: %s is not for normal use!\n"), "--no-literal");
3897 log_error(_("%s not allowed with %s!\n"),
3898 "--textmode", "--no-literal" );
3899 if (opt.set_filename)
3900 log_error(_("%s makes no sense with %s!\n"),
3901 eyes_only?"--for-your-eyes-only":"--set-filename",
3906 if (opt.set_filesize)
3907 log_info(_("Note: %s is not for normal use!\n"), "--set-filesize");
3911 if (gnupg_faked_time_p ())
3913 gnupg_isotime_t tbuf;
3915 log_info (_("WARNING: running with faked system time: "));
3916 gnupg_get_isotime (tbuf);
3917 dump_isotime (tbuf);
3921 /* Print a warning if an argument looks like an option. */
3922 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
3926 for (i=0; i < argc; i++)
3927 if (argv[i][0] == '-' && argv[i][1] == '-')
3928 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
3932 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
3934 if(require_secmem && !got_secmem)
3936 log_info(_("will not run with insecure memory due to %s\n"),
3937 "--require-secmem");
3938 write_status_failure ("option-checking", gpg_error(GPG_ERR_GENERAL));
3942 set_debug (debug_level);
3943 if (opt.verbose) /* Print the compatibility flags. */
3944 parse_compatibility_flags (NULL, &opt.compat_flags, compatibility_flags);
3945 gnupg_set_compliance_extra_info (opt.min_rsa_length);
3947 log_clock ("start");
3949 /* Do these after the switch(), so they can override settings. */
3952 /* That does not anymore work because we have no more support
3953 for v3 signatures. */
3955 opt.ask_sig_expire=0;
3963 if( def_cipher_string ) {
3964 opt.def_cipher_algo = string_to_cipher_algo (def_cipher_string);
3965 xfree(def_cipher_string); def_cipher_string = NULL;
3966 if ( openpgp_cipher_test_algo (opt.def_cipher_algo) )
3967 log_error(_("selected cipher algorithm is invalid\n"));
3969 if( def_digest_string ) {
3970 opt.def_digest_algo = string_to_digest_algo (def_digest_string);
3971 xfree(def_digest_string); def_digest_string = NULL;
3972 if ( openpgp_md_test_algo (opt.def_digest_algo) )
3973 log_error(_("selected digest algorithm is invalid\n"));
3975 if( compress_algo_string ) {
3976 opt.compress_algo = string_to_compress_algo(compress_algo_string);
3977 xfree(compress_algo_string); compress_algo_string = NULL;
3978 if( check_compress_algo(opt.compress_algo) )
3979 log_error(_("selected compression algorithm is invalid\n"));
3981 if( cert_digest_string ) {
3982 opt.cert_digest_algo = string_to_digest_algo (cert_digest_string);
3983 xfree(cert_digest_string); cert_digest_string = NULL;
3984 if (openpgp_md_test_algo(opt.cert_digest_algo))
3985 log_error(_("selected certification digest algorithm is invalid\n"));
3987 if( s2k_cipher_string ) {
3988 opt.s2k_cipher_algo = string_to_cipher_algo (s2k_cipher_string);
3989 xfree(s2k_cipher_string); s2k_cipher_string = NULL;
3990 if (openpgp_cipher_test_algo (opt.s2k_cipher_algo))
3991 log_error(_("selected cipher algorithm is invalid\n"));
3993 if( s2k_digest_string ) {
3994 opt.s2k_digest_algo = string_to_digest_algo (s2k_digest_string);
3995 xfree(s2k_digest_string); s2k_digest_string = NULL;
3996 if (openpgp_md_test_algo(opt.s2k_digest_algo))
3997 log_error(_("selected digest algorithm is invalid\n"));
3999 if( opt.completes_needed < 1 )
4000 log_error(_("completes-needed must be greater than 0\n"));
4001 if( opt.marginals_needed < 2 )
4002 log_error(_("marginals-needed must be greater than 1\n"));
4003 if( opt.max_cert_depth < 1 || opt.max_cert_depth > 255 )
4004 log_error(_("max-cert-depth must be in the range from 1 to 255\n"));
4005 if(opt.def_cert_level<0 || opt.def_cert_level>3)
4006 log_error(_("invalid default-cert-level; must be 0, 1, 2, or 3\n"));
4007 if( opt.min_cert_level < 1 || opt.min_cert_level > 3 )
4008 log_error(_("invalid min-cert-level; must be 1, 2, or 3\n"));
4009 switch( opt.s2k_mode ) {
4012 log_info(_("Note: simple S2K mode (0) is strongly discouraged\n"));
4014 case 1: case 3: break;
4016 log_error(_("invalid S2K mode; must be 0, 1 or 3\n"));
4019 /* This isn't actually needed, but does serve to error out if the
4020 string is invalid. */
4021 if(opt.def_preference_list &&
4022 keygen_set_std_prefs(opt.def_preference_list,0))
4023 log_error(_("invalid default preferences\n"));
4025 if(pers_cipher_list &&
4026 keygen_set_std_prefs(pers_cipher_list,PREFTYPE_SYM))
4027 log_error(_("invalid personal cipher preferences\n"));
4029 if(pers_digest_list &&
4030 keygen_set_std_prefs(pers_digest_list,PREFTYPE_HASH))
4031 log_error(_("invalid personal digest preferences\n"));
4033 if(pers_compress_list &&
4034 keygen_set_std_prefs(pers_compress_list,PREFTYPE_ZIP))
4035 log_error(_("invalid personal compress preferences\n"));
4037 /* Check chunk size. Please fix also the man page if you change
4038 * the default. The limits are given by the specs. */
4039 if (!opt.chunk_size)
4040 opt.chunk_size = 22; /* Default to the suggested max of 4 MiB. */
4041 else if (opt.chunk_size < 6)
4044 log_info (_("chunk size invalid - using %d\n"), opt.chunk_size);
4046 else if (opt.chunk_size > (allow_large_chunks? 62 : 22))
4048 opt.chunk_size = (allow_large_chunks? 62 : 22);
4049 log_info (_("chunk size invalid - using %d\n"), opt.chunk_size);
4052 /* We don't support all possible commands with multifile yet */
4063 cmdname="--sign --encrypt";
4066 cmdname="--clear-sign";
4069 cmdname="--detach-sign";
4072 cmdname="--symmetric";
4075 cmdname="--symmetric --encrypt";
4086 log_error(_("%s does not yet work with %s\n"),cmdname,"--multifile");
4089 if( log_get_errorcount(0) )
4091 write_status_failure ("option-postprocessing",
4092 gpg_error(GPG_ERR_GENERAL));
4096 if(opt.compress_level==0)
4097 opt.compress_algo=COMPRESS_ALGO_NONE;
4099 /* Check our chosen algorithms against the list of legal
4104 const char *badalg=NULL;
4105 preftype_t badtype=PREFTYPE_NONE;
4107 if(opt.def_cipher_algo
4108 && !algo_available(PREFTYPE_SYM,opt.def_cipher_algo,NULL))
4110 badalg = openpgp_cipher_algo_name (opt.def_cipher_algo);
4111 badtype = PREFTYPE_SYM;
4113 else if(opt.def_digest_algo
4114 && !algo_available(PREFTYPE_HASH,opt.def_digest_algo,NULL))
4116 badalg = gcry_md_algo_name (opt.def_digest_algo);
4117 badtype = PREFTYPE_HASH;
4119 else if(opt.cert_digest_algo
4120 && !algo_available(PREFTYPE_HASH,opt.cert_digest_algo,NULL))
4122 badalg = gcry_md_algo_name (opt.cert_digest_algo);
4123 badtype = PREFTYPE_HASH;
4125 else if(opt.compress_algo!=-1
4126 && !algo_available(PREFTYPE_ZIP,opt.compress_algo,NULL))
4128 badalg = compress_algo_to_string(opt.compress_algo);
4129 badtype = PREFTYPE_ZIP;
4137 log_info (_("cipher algorithm '%s'"
4138 " may not be used in %s mode\n"),
4140 gnupg_compliance_option_string (opt.compliance));
4143 log_info (_("digest algorithm '%s'"
4144 " may not be used in %s mode\n"),
4146 gnupg_compliance_option_string (opt.compliance));
4149 log_info (_("compression algorithm '%s'"
4150 " may not be used in %s mode\n"),
4152 gnupg_compliance_option_string (opt.compliance));
4158 compliance_failure();
4162 /* Check our chosen algorithms against the list of allowed
4163 * algorithms in the current compliance mode, and fail hard if it
4164 * is not. This is us being nice to the user informing her early
4165 * that the chosen algorithms are not available. We also check
4166 * and enforce this right before the actual operation. */
4167 if (opt.def_cipher_algo
4168 && ! gnupg_cipher_is_allowed (opt.compliance,
4174 || cmd == aSignEncrSym,
4175 opt.def_cipher_algo,
4176 GCRY_CIPHER_MODE_NONE))
4177 log_error (_("cipher algorithm '%s' may not be used in %s mode\n"),
4178 openpgp_cipher_algo_name (opt.def_cipher_algo),
4179 gnupg_compliance_option_string (opt.compliance));
4181 if (opt.def_digest_algo
4182 && ! gnupg_digest_is_allowed (opt.compliance,
4185 || cmd == aSignEncrSym
4187 || cmd == aClearsign,
4188 opt.def_digest_algo))
4189 log_error (_("digest algorithm '%s' may not be used in %s mode\n"),
4190 gcry_md_algo_name (opt.def_digest_algo),
4191 gnupg_compliance_option_string (opt.compliance));
4194 if (log_get_errorcount (0))
4196 write_status_failure ("option-checking", gpg_error(GPG_ERR_GENERAL));
4200 /* Set the random seed file. */
4201 if (use_random_seed)
4203 char *p = make_filename (gnupg_homedir (), "random_seed", NULL );
4204 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
4205 if (!gnupg_access (p, F_OK))
4206 register_secured_file (p);
4210 /* If there is no command but the --fingerprint is given, default
4211 to the --list-keys command. */
4212 if (!cmd && fpr_maybe_cmd)
4214 set_cmd (&cmd, aListKeys);
4218 if( opt.verbose > 1 )
4219 set_packet_list_mode(1);
4221 /* Add the keyrings, but not for some special commands. We always
4222 * need to add the keyrings if we are running under SELinux, this
4223 * is so that the rings are added to the list of secured files.
4224 * We do not add any keyring if --no-keyring or --use-keyboxd has
4225 * been used. Note that keydb_add_resource may create a new
4226 * homedir and also tries to write a common.conf to enable the use
4227 * of the keyboxd - in this case a special error code is returned
4228 * and use_keyboxd is then also set. */
4229 if (!opt.use_keyboxd
4230 && default_keyring >= 0
4231 && (ALWAYS_ADD_KEYRINGS
4232 || (cmd != aDeArmor && cmd != aEnArmor && cmd != aGPGConfTest)))
4234 gpg_error_t tmperr = 0;
4236 if (!nrings || default_keyring > 0) /* Add default ring. */
4237 tmperr = keydb_add_resource ("pubring" EXTSEP_S GPGEXT_GPG,
4238 KEYDB_RESOURCE_FLAG_DEFAULT);
4239 if (gpg_err_code (tmperr) == GPG_ERR_TRUE && opt.use_keyboxd)
4240 ; /* The keyboxd has been enabled. */
4243 for (sl = nrings; sl; sl = sl->next )
4244 keydb_add_resource (sl->d, sl->flags);
4247 FREE_STRLIST(nrings);
4249 /* In loopback mode, never ask for the password multiple times. */
4250 if (opt.pinentry_mode == PINENTRY_MODE_LOOPBACK)
4252 opt.passphrase_repeat = 0;
4255 /* If no pinentry is expected shunt
4256 * gnupg_allow_set_foregound_window to avoid useless error
4257 * messages on Windows. */
4258 if (opt.pinentry_mode != PINENTRY_MODE_ASK)
4260 gnupg_inhibit_set_foregound_window (1);
4264 if (cmd == aGPGConfTest)
4268 if (pwfd != -1) /* Read the passphrase now. */
4269 read_passphrase_from_fd (pwfd);
4271 if (ovrseskeyfd != -1 ) /* Read the sessionkey now. */
4272 read_sessionkey_from_fd (ovrseskeyfd);
4274 fname = argc? *argv : NULL;
4276 if(fname && utf8_strings)
4277 opt.flags.utf8_filename=1;
4279 ctrl = xcalloc (1, sizeof *ctrl);
4280 gpg_init_default_ctrl (ctrl);
4282 #ifndef NO_TRUST_MODELS
4292 case aListGcryptConfig:
4295 case aExportOwnerTrust:
4296 rc = setup_trustdb (0, trustdb_name);
4299 rc = setup_trustdb (argc? 1:0, trustdb_name);
4304 rc = setup_trustdb (1, trustdb_name);
4307 /* If we are using TM_ALWAYS, we do not need to create the
4309 rc = setup_trustdb (opt.trust_model != TM_ALWAYS, trustdb_name);
4313 log_error (_("failed to initialize the TrustDB: %s\n"),
4315 #endif /*!NO_TRUST_MODELS*/
4324 if (!opt.quiet && any_explicit_recipient)
4325 log_info (_("WARNING: recipients (-r) given "
4326 "without using public key encryption\n"));
4333 /* Check for certain command whether we need to migrate a
4334 secring.gpg to the gpg-agent. */
4337 case aListSecretKeys:
4348 case aDeleteSecretKeys:
4349 case aDeleteSecretAndPublicKeys:
4355 case aQuickSetPrimaryUid:
4356 case aQuickUpdatePref:
4361 case aExportSecretSub:
4366 migrate_secring (ctrl);
4369 if (opt.with_secret)
4370 migrate_secring (ctrl);
4376 /* The command dispatcher. */
4383 case aStore: /* only store the file */
4385 wrong_args("--store [filename]");
4386 if( (rc = encrypt_store(fname)) )
4388 write_status_failure ("store", rc);
4389 log_error ("storing '%s' failed: %s\n",
4390 print_fname_stdin(fname),gpg_strerror (rc) );
4393 case aSym: /* encrypt the given file only with the symmetric cipher */
4395 wrong_args("--symmetric [filename]");
4396 if( (rc = encrypt_symmetric(fname)) )
4398 write_status_failure ("symencrypt", rc);
4399 log_error (_("symmetric encryption of '%s' failed: %s\n"),
4400 print_fname_stdin(fname),gpg_strerror (rc) );
4404 case aEncr: /* encrypt the given file */
4406 encrypt_crypt_files (ctrl, argc, argv, remusr);
4410 wrong_args("--encrypt [filename]");
4411 if( (rc = encrypt_crypt (ctrl, -1, fname, remusr, 0, NULL, -1)) )
4413 write_status_failure ("encrypt", rc);
4414 log_error("%s: encryption failed: %s\n",
4415 print_fname_stdin(fname), gpg_strerror (rc) );
4421 /* This works with PGP 8 in the sense that it acts just like a
4422 symmetric message. It doesn't work at all with 2 or 6. It
4423 might work with 7, but alas, I don't have a copy to test
4426 wrong_args("--symmetric --encrypt [filename]");
4427 else if(opt.s2k_mode==0)
4428 log_error(_("you cannot use --symmetric --encrypt"
4429 " with --s2k-mode 0\n"));
4431 log_error(_("you cannot use --symmetric --encrypt"
4433 gnupg_compliance_option_string (opt.compliance));
4436 if( (rc = encrypt_crypt (ctrl, -1, fname, remusr, 1, NULL, -1)) )
4438 write_status_failure ("encrypt", rc);
4439 log_error ("%s: encryption failed: %s\n",
4440 print_fname_stdin(fname), gpg_strerror (rc) );
4445 case aSign: /* sign the given file */
4447 if( detached_sig ) { /* sign all files */
4448 for( ; argc; argc--, argv++ )
4449 add_to_strlist( &sl, *argv );
4453 wrong_args("--sign [filename]");
4455 sl = xmalloc_clear( sizeof *sl + strlen(fname));
4456 strcpy(sl->d, fname);
4459 if ((rc = sign_file (ctrl, sl, detached_sig, locusr, 0, NULL, NULL)))
4461 write_status_failure ("sign", rc);
4462 log_error ("signing failed: %s\n", gpg_strerror (rc) );
4467 case aSignEncr: /* sign and encrypt the given file */
4469 wrong_args("--sign --encrypt [filename]");
4471 sl = xmalloc_clear( sizeof *sl + strlen(fname));
4472 strcpy(sl->d, fname);
4476 if ((rc = sign_file (ctrl, sl, detached_sig, locusr, 1, remusr, NULL)))
4478 write_status_failure ("sign-encrypt", rc);
4479 log_error("%s: sign+encrypt failed: %s\n",
4480 print_fname_stdin(fname), gpg_strerror (rc) );
4485 case aSignEncrSym: /* sign and encrypt the given file */
4487 wrong_args("--symmetric --sign --encrypt [filename]");
4488 else if(opt.s2k_mode==0)
4489 log_error(_("you cannot use --symmetric --sign --encrypt"
4490 " with --s2k-mode 0\n"));
4492 log_error(_("you cannot use --symmetric --sign --encrypt"
4494 gnupg_compliance_option_string (opt.compliance));
4499 sl = xmalloc_clear( sizeof *sl + strlen(fname));
4500 strcpy(sl->d, fname);
4504 if ((rc = sign_file (ctrl, sl, detached_sig, locusr,
4507 write_status_failure ("sign-encrypt", rc);
4508 log_error("%s: symmetric+sign+encrypt failed: %s\n",
4509 print_fname_stdin(fname), gpg_strerror (rc) );
4515 case aSignSym: /* sign and conventionally encrypt the given file */
4517 wrong_args("--sign --symmetric [filename]");
4518 rc = sign_symencrypt_file (ctrl, fname, locusr);
4521 write_status_failure ("sign-symencrypt", rc);
4522 log_error("%s: sign+symmetric failed: %s\n",
4523 print_fname_stdin(fname), gpg_strerror (rc) );
4527 case aClearsign: /* make a clearsig */
4529 wrong_args("--clear-sign [filename]");
4530 if( (rc = clearsign_file (ctrl, fname, locusr, NULL)) )
4532 write_status_failure ("sign", rc);
4533 log_error("%s: clear-sign failed: %s\n",
4534 print_fname_stdin(fname), gpg_strerror (rc) );
4541 if ((rc = verify_files (ctrl, argc, argv)))
4542 log_error("verify files failed: %s\n", gpg_strerror (rc) );
4546 if ((rc = verify_signatures (ctrl, argc, argv)))
4547 log_error("verify signatures failed: %s\n", gpg_strerror (rc) );
4550 write_status_failure ("verify", rc);
4555 decrypt_messages (ctrl, argc, argv);
4559 wrong_args("--decrypt [filename]");
4560 if( (rc = decrypt_message (ctrl, fname) ))
4562 write_status_failure ("decrypt", rc);
4563 log_error("decrypt_message failed: %s\n", gpg_strerror (rc) );
4569 case aQuickLSignKey:
4574 wrong_args ("--quick-[l]sign-key fingerprint [userids]");
4575 fpr = *argv++; argc--;
4577 for( ; argc; argc--, argv++)
4578 append_to_strlist2 (&sl, *argv, utf8_strings);
4579 keyedit_quick_sign (ctrl, fpr, sl, locusr, (cmd == aQuickLSignKey));
4586 const char *userid, *siguserid;
4589 wrong_args ("--quick-revoke-sig USER-ID SIG-USER-ID [userids]");
4590 userid = *argv++; argc--;
4591 siguserid = *argv++; argc--;
4593 for( ; argc; argc--, argv++)
4594 append_to_strlist2 (&sl, *argv, utf8_strings);
4595 keyedit_quick_revsig (ctrl, userid, siguserid, sl);
4602 wrong_args("--sign-key user-id");
4606 wrong_args("--lsign-key user-id");
4612 append_to_strlist(&sl,"sign");
4613 else if(cmd==aLSignKey)
4614 append_to_strlist(&sl,"lsign");
4618 append_to_strlist( &sl, "save" );
4619 username = make_username( fname );
4620 keyedit_menu (ctrl, username, locusr, sl, 0, 0 );
4625 case aEditKey: /* Edit a key signature */
4627 wrong_args("--edit-key user-id [commands]");
4628 username = make_username( fname );
4631 for( argc--, argv++ ; argc; argc--, argv++ )
4632 append_to_strlist( &sl, *argv );
4633 keyedit_menu (ctrl, username, locusr, sl, 0, 1 );
4637 keyedit_menu (ctrl, username, locusr, NULL, 0, 1 );
4643 wrong_args("--change-passphrase <user-id>");
4646 username = make_username (fname);
4647 keyedit_passwd (ctrl, username);
4653 case aDeleteSecretKeys:
4654 case aDeleteSecretAndPublicKeys:
4656 /* Print a note if the user did not specify any key. */
4657 if (!argc && !opt.quiet)
4658 log_info (_("Note: %s\n"), gpg_strerror (GPG_ERR_NO_KEY));
4659 /* I'm adding these in reverse order as add_to_strlist2
4660 reverses them again, and it's easier to understand in the
4662 for( ; argc; argc-- )
4663 add_to_strlist2( &sl, argv[argc-1], utf8_strings );
4664 delete_keys (ctrl, sl,
4665 cmd==aDeleteSecretKeys, cmd==aDeleteSecretAndPublicKeys);
4670 opt.check_sigs = 1; /* fall through */
4672 opt.list_sigs = 1; /* fall through */
4675 for( ; argc; argc--, argv++ )
4676 add_to_strlist2( &sl, *argv, utf8_strings );
4677 public_key_list (ctrl, sl, 0, 0);
4680 case aListSecretKeys:
4682 for( ; argc; argc--, argv++ )
4683 add_to_strlist2( &sl, *argv, utf8_strings );
4684 secret_key_list (ctrl, sl);
4688 case aLocateExtKeys:
4690 for (; argc; argc--, argv++)
4691 add_to_strlist2( &sl, *argv, utf8_strings );
4692 if (cmd == aLocateExtKeys && akl_empty_or_only_local ())
4694 /* This is a kludge to let --locate-external-keys even
4695 * work if the config file has --no-auto-key-locate. This
4696 * better matches the expectations of the user. */
4698 parse_auto_key_locate (DEFAULT_AKL_LIST);
4700 public_key_list (ctrl, sl, 1, cmd == aLocateExtKeys);
4708 const char *x_algo, *x_usage, *x_expire;
4710 if (argc < 1 || argc > 4)
4711 wrong_args("--quick-generate-key USER-ID [ALGO [USAGE [EXPIRE]]]");
4712 username = make_username (fname);
4719 x_algo = *argv++; argc--;
4722 x_usage = *argv++; argc--;
4725 x_expire = *argv++; argc--;
4729 if (mopt.forbid_gen_key)
4730 gen_key_forbidden ();
4732 quick_generate_keypair (ctrl, username, x_algo, x_usage, x_expire);
4737 case aKeygen: /* generate a key */
4738 if (mopt.forbid_gen_key)
4739 gen_key_forbidden ();
4740 else if( opt.batch )
4743 wrong_args("--generate-key [parameterfile]");
4744 generate_keypair (ctrl, 0, argc? *argv : NULL, NULL, 0);
4748 if (opt.command_fd != -1 && argc)
4751 wrong_args("--generate-key [parameterfile]");
4754 generate_keypair (ctrl, 0, argc? *argv : NULL, NULL, 0);
4757 wrong_args ("--generate-key");
4759 generate_keypair (ctrl, 0, NULL, NULL, 0);
4763 case aFullKeygen: /* Generate a key with all options. */
4764 if (mopt.forbid_gen_key)
4765 gen_key_forbidden ();
4769 wrong_args ("--full-generate-key [parameterfile]");
4770 generate_keypair (ctrl, 1, argc? *argv : NULL, NULL, 0);
4775 wrong_args("--full-generate-key");
4776 generate_keypair (ctrl, 1, NULL, NULL, 0);
4782 const char *uid, *newuid;
4785 wrong_args ("--quick-add-uid USER-ID NEW-USER-ID");
4786 uid = *argv++; argc--;
4787 newuid = *argv++; argc--;
4788 keyedit_quick_adduid (ctrl, uid, newuid);
4794 const char *x_fpr, *x_algo, *x_usage, *x_expire;
4796 if (argc < 1 || argc > 4)
4797 wrong_args ("--quick-add-key FINGERPRINT [ALGO [USAGE [EXPIRE]]]");
4798 x_fpr = *argv++; argc--;
4804 x_algo = *argv++; argc--;
4807 x_usage = *argv++; argc--;
4810 x_expire = *argv++; argc--;
4814 if (mopt.forbid_gen_key)
4815 gen_key_forbidden ();
4817 keyedit_quick_addkey (ctrl, x_fpr, x_algo, x_usage, x_expire);
4824 wrong_args ("--quick-add-adsk FINGERPRINT ADSK-FINGERPRINT");
4825 if (mopt.forbid_gen_key)
4826 gen_key_forbidden ();
4828 keyedit_quick_addadsk (ctrl, argv[0], argv[1]);
4834 const char *uid, *uidtorev;
4837 wrong_args ("--quick-revoke-uid USER-ID USER-ID-TO-REVOKE");
4838 uid = *argv++; argc--;
4839 uidtorev = *argv++; argc--;
4840 keyedit_quick_revuid (ctrl, uid, uidtorev);
4844 case aQuickSetExpire:
4846 const char *x_fpr, *x_expire;
4849 wrong_args ("--quick-set-exipre FINGERPRINT EXPIRE [SUBKEY-FPRS]");
4850 x_fpr = *argv++; argc--;
4851 x_expire = *argv++; argc--;
4852 keyedit_quick_set_expire (ctrl, x_fpr, x_expire, argv);
4856 case aQuickSetPrimaryUid:
4858 const char *uid, *primaryuid;
4861 wrong_args ("--quick-set-primary-uid USER-ID PRIMARY-USER-ID");
4862 uid = *argv++; argc--;
4863 primaryuid = *argv++; argc--;
4864 keyedit_quick_set_primary (ctrl, uid, primaryuid);
4868 case aQuickUpdatePref:
4871 wrong_args ("--quick-update-pref USER-ID");
4872 keyedit_quick_update_pref (ctrl, *argv);
4877 opt.import_options |= IMPORT_FAST; /* fall through */
4880 import_keys (ctrl, argc? argv:NULL, argc, NULL,
4881 opt.import_options, opt.key_origin, opt.key_origin_url);
4884 /* TODO: There are a number of command that use this same
4885 "make strlist, call function, report error, free strlist"
4886 pattern. Join them together here and avoid all that
4893 for( ; argc; argc--, argv++ )
4894 append_to_strlist2( &sl, *argv, utf8_strings );
4895 if( cmd == aSendKeys )
4896 rc = keyserver_export (ctrl, sl );
4897 else if( cmd == aRecvKeys )
4898 rc = keyserver_import (ctrl, sl );
4901 export_stats_t stats = export_new_stats ();
4902 rc = export_pubkeys (ctrl, sl, opt.export_options, stats);
4903 export_print_stats (stats);
4904 export_release_stats (stats);
4910 write_status_failure ("send-keys", rc);
4911 log_error(_("keyserver send failed: %s\n"),gpg_strerror (rc));
4913 else if(cmd==aRecvKeys)
4915 write_status_failure ("recv-keys", rc);
4916 log_error (_("keyserver receive failed: %s\n"),
4921 write_status_failure ("export", rc);
4922 log_error (_("key export failed: %s\n"), gpg_strerror (rc));
4930 wrong_args ("--export-ssh-key <user-id>");
4931 rc = export_ssh_key (ctrl, argv[0]);
4934 write_status_failure ("export-ssh-key", rc);
4935 log_error (_("export as ssh key failed: %s\n"), gpg_strerror (rc));
4939 case aExportSecretSshKey:
4941 wrong_args ("--export-secret-ssh-key <user-id>");
4942 rc = export_secret_ssh_key (ctrl, argv[0]);
4945 write_status_failure ("export-ssh-key", rc);
4946 log_error (_("export as ssh key failed: %s\n"), gpg_strerror (rc));
4952 for (; argc; argc--, argv++)
4953 append_to_strlist2 (&sl, *argv, utf8_strings);
4954 rc = keyserver_search (ctrl, sl);
4957 write_status_failure ("search-keys", rc);
4958 log_error (_("keyserver search failed: %s\n"), gpg_strerror (rc));
4965 for( ; argc; argc--, argv++ )
4966 append_to_strlist2( &sl, *argv, utf8_strings );
4967 rc = keyserver_refresh (ctrl, sl);
4970 write_status_failure ("refresh-keys", rc);
4971 log_error (_("keyserver refresh failed: %s\n"),gpg_strerror (rc));
4978 for( ; argc; argc--, argv++ )
4979 append_to_strlist2( &sl, *argv, utf8_strings );
4980 rc = keyserver_fetch (ctrl, sl, opt.key_origin);
4984 write_status_failure ("fetch-keys", rc);
4985 log_error ("key fetch failed: %s\n",gpg_strerror (rc));
4986 if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
4987 g10_exit (1); /* In this case return 1 and not 2. */
4993 for( ; argc; argc--, argv++ )
4994 add_to_strlist2( &sl, *argv, utf8_strings );
4996 export_stats_t stats = export_new_stats ();
4997 export_seckeys (ctrl, sl, opt.export_options, stats);
4998 export_print_stats (stats);
4999 export_release_stats (stats);
5004 case aExportSecretSub:
5006 for( ; argc; argc--, argv++ )
5007 add_to_strlist2( &sl, *argv, utf8_strings );
5009 export_stats_t stats = export_new_stats ();
5010 export_secsubkeys (ctrl, sl, opt.export_options, stats);
5011 export_print_stats (stats);
5012 export_release_stats (stats);
5019 wrong_args("--generate-revocation user-id");
5020 username = make_username(*argv);
5021 gen_revoke (ctrl, username );
5027 wrong_args ("--generate-designated-revocation user-id");
5028 username = make_username (*argv);
5029 gen_desig_revoke (ctrl, username, locusr);
5035 wrong_args("--dearmor [file]");
5036 rc = dearmor_file( argc? *argv: NULL );
5039 write_status_failure ("dearmor", rc);
5040 log_error (_("dearmoring failed: %s\n"), gpg_strerror (rc));
5046 wrong_args("--enarmor [file]");
5047 rc = enarmor_file( argc? *argv: NULL );
5050 write_status_failure ("enarmor", rc);
5051 log_error (_("enarmoring failed: %s\n"), gpg_strerror (rc));
5058 { int mode = argc < 2 ? 0 : atoi(*argv);
5060 if( mode == 1 && argc == 2 ) {
5061 mpi_print (es_stdout,
5062 generate_public_prime( atoi(argv[1]) ), 1);
5064 else if( mode == 2 && argc == 3 ) {
5065 mpi_print (es_stdout, generate_elg_prime(
5067 atoi(argv[2]), NULL,NULL ), 1);
5069 else if( mode == 3 && argc == 3 ) {
5071 mpi_print (es_stdout, generate_elg_prime(
5073 atoi(argv[2]), NULL,&factors ), 1);
5074 es_putc ('\n', es_stdout);
5075 mpi_print (es_stdout, factors[0], 1 ); /* print q */
5077 else if( mode == 4 && argc == 3 ) {
5078 MPI g = mpi_alloc(1);
5079 mpi_print (es_stdout, generate_elg_prime(
5081 atoi(argv[2]), g, NULL ), 1);
5082 es_putc ('\n', es_stdout);
5083 mpi_print (es_stdout, g, 1 );
5087 wrong_args("--gen-prime mode bits [qbits] ");
5088 es_putc ('\n', es_stdout);
5091 wrong_args("--gen-prime not yet supported ");
5096 int level = argc ? atoi(*argv):0;
5097 int count = argc > 1 ? atoi(argv[1]): 0;
5098 int endless = !count;
5099 int hexhack = (level == 16);
5104 /* Level 30 uses the same algorithm as our magic wand in
5105 * pinentry/gpg-agent. */
5108 unsigned int nbits = 150;
5109 size_t nbytes = (nbits + 7) / 8;
5113 rand = gcry_random_bytes_secure (nbytes, GCRY_STRONG_RANDOM);
5115 log_fatal ("failed to generate random password\n");
5117 generated = zb32_encode (rand, nbits);
5119 es_fputs (generated, es_stdout);
5120 es_putc ('\n', es_stdout);
5125 if (argc < 1 || argc > 2 || level < 0 || level > 2 || count < 0)
5126 wrong_args ("--gen-random 0|1|2|16|30 [count]");
5128 while (endless || count)
5131 /* We need a multiple of 3, so that in case of armored
5132 * output we get a correct string. No linefolding is
5133 * done, as it is best to leave this to other tools */
5134 size_t n = !endless && count < 99? count : 99;
5137 p = gcry_random_bytes (n, level);
5140 for (nn = 0; nn < n; nn++)
5141 es_fprintf (es_stdout, "%02x", p[nn]);
5145 char *tmp = make_radix64_string (p, n);
5146 es_fputs (tmp, es_stdout);
5149 es_putc ('=', es_stdout);
5151 es_putc ('=', es_stdout);
5155 es_set_binary (es_stdout);
5156 es_fwrite( p, n, 1, es_stdout );
5162 if (opt.armor || hexhack)
5163 es_putc ('\n', es_stdout);
5169 wrong_args("--print-md algo [files]");
5171 int all_algos = (**argv=='*' && !(*argv)[1]);
5172 int algo = all_algos? 0 : gcry_md_map_name (*argv);
5174 if( !algo && !all_algos )
5175 log_error(_("invalid hash algorithm '%s'\n"), *argv );
5179 print_mds(NULL, algo);
5181 for(; argc; argc--, argv++ )
5182 print_mds(*argv, algo);
5188 case aPrintMDs: /* old option */
5192 for(; argc; argc--, argv++ )
5197 #ifndef NO_TRUST_MODELS
5200 list_trustdb (ctrl, es_stdout, NULL);
5202 for( ; argc; argc--, argv++ )
5203 list_trustdb (ctrl, es_stdout, *argv );
5207 case aUpdateTrustDB:
5209 wrong_args("--update-trustdb");
5210 update_trustdb (ctrl);
5214 /* Old versions allowed for arguments - ignore them */
5215 check_trustdb (ctrl);
5219 how_to_fix_the_trustdb ();
5222 case aListTrustPath:
5224 wrong_args("--list-trust-path <user-ids>");
5225 for( ; argc; argc--, argv++ ) {
5226 username = make_username( *argv );
5227 list_trust_path( username );
5232 case aExportOwnerTrust:
5234 wrong_args("--export-ownertrust");
5235 export_ownertrust (ctrl);
5238 case aImportOwnerTrust:
5240 wrong_args("--import-ownertrust [file]");
5241 import_ownertrust (ctrl, argc? *argv:NULL );
5243 #endif /*!NO_TRUST_MODELS*/
5245 case aRebuildKeydbCaches:
5247 wrong_args ("--rebuild-keydb-caches");
5248 keydb_rebuild_caches (ctrl, 1);
5251 #ifdef ENABLE_CARD_SUPPORT
5254 card_status (ctrl, es_stdout, NULL);
5256 card_status (ctrl, es_stdout, *argv);
5258 wrong_args ("--card-status [serialno]");
5264 for (argc--, argv++ ; argc; argc--, argv++)
5265 append_to_strlist (&sl, *argv);
5266 card_edit (ctrl, sl);
5270 card_edit (ctrl, NULL);
5277 change_pin (atoi (*argv),1);
5279 wrong_args ("--change-pin [no]");
5281 #endif /* ENABLE_CARD_SUPPORT*/
5285 char *str=collapse_args(argc,argv);
5291 case aListGcryptConfig:
5292 /* Fixme: It would be nice to integrate that with
5293 --list-config but unfortunately there is no way yet to have
5294 libgcrypt print it to an estream for further parsing. */
5295 gcry_control (GCRYCTL_PRINT_CONFIG, stdout);
5306 wrong_args ("--tofu-policy POLICY KEYID [KEYID...]");
5308 policy = parse_tofu_policy (argv[0]);
5310 hd = keydb_new (ctrl);
5313 write_status_failure ("tofu-driver", gpg_error(GPG_ERR_GENERAL));
5317 tofu_begin_batch_update (ctrl);
5319 for (i = 1; i < argc; i ++)
5321 KEYDB_SEARCH_DESC desc;
5324 rc = classify_user_id (argv[i], &desc, 0);
5327 log_error (_("error parsing key specification '%s': %s\n"),
5328 argv[i], gpg_strerror (rc));
5329 write_status_failure ("tofu-driver", rc);
5333 if (! (desc.mode == KEYDB_SEARCH_MODE_SHORT_KID
5334 || desc.mode == KEYDB_SEARCH_MODE_LONG_KID
5335 || desc.mode == KEYDB_SEARCH_MODE_FPR
5336 || desc.mode == KEYDB_SEARCH_MODE_KEYGRIP))
5338 log_error (_("'%s' does not appear to be a valid"
5339 " key ID, fingerprint or keygrip\n"),
5341 write_status_failure ("tofu-driver",
5342 gpg_error(GPG_ERR_GENERAL));
5346 rc = keydb_search_reset (hd);
5349 /* This should not happen, thus no need to tranalate
5351 log_error ("keydb_search_reset failed: %s\n",
5353 write_status_failure ("tofu-driver", rc);
5357 rc = keydb_search (hd, &desc, 1, NULL);
5360 log_error (_("key \"%s\" not found: %s\n"), argv[i],
5362 write_status_failure ("tofu-driver", rc);
5366 rc = keydb_get_keyblock (hd, &kb);
5369 log_error (_("error reading keyblock: %s\n"),
5371 write_status_failure ("tofu-driver", rc);
5375 merge_keys_and_selfsig (ctrl, kb);
5376 if (tofu_set_policy (ctrl, kb, policy))
5378 write_status_failure ("tofu-driver", rc);
5382 release_kbnode (kb);
5385 tofu_end_batch_update (ctrl);
5394 log_info (_("WARNING: no command supplied."
5395 " Trying to guess what you mean ...\n"));
5399 wrong_args("[filename]");
5400 /* Issue some output for the unix newbie */
5401 if (!fname && !opt.outfile
5402 && gnupg_isatty (fileno (stdin))
5403 && gnupg_isatty (fileno (stdout))
5404 && gnupg_isatty (fileno (stderr)))
5405 log_info(_("Go ahead and type your message ...\n"));
5407 a = iobuf_open(fname);
5408 if (a && is_secured_file (iobuf_get_fd (a)))
5412 gpg_err_set_errno (EPERM);
5415 log_error(_("can't open '%s'\n"), print_fname_stdin(fname));
5418 if( !opt.no_armor ) {
5419 if( use_armor_filter( a ) ) {
5420 afx = new_armor_context ();
5421 push_armor_filter (afx, a);
5424 if( cmd == aListPackets ) {
5426 set_packet_list_mode(1);
5428 rc = proc_packets (ctrl, NULL, a );
5431 write_status_failure ("-", rc);
5432 log_error ("processing message failed: %s\n",
5441 gpg_deinit_default_ctrl (ctrl);
5443 release_armor_context (afx);
5444 FREE_STRLIST(remusr);
5445 FREE_STRLIST(locusr);
5447 return 8; /*NEVER REACHED*/
5451 /* Note: This function is used by signal handlers!. */
5453 emergency_cleanup (void)
5455 gcry_control (GCRYCTL_TERM_SECMEM );
5462 /* If we had an error but not printed an error message, do it now.
5463 * Note that write_status_failure will never print a second failure
5466 write_status_failure ("gpg-exit", gpg_error (GPG_ERR_GENERAL));
5468 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
5472 if ( (opt.debug & DBG_MEMSTAT_VALUE) )
5474 keydb_dump_stats ();
5475 sig_check_dump_stats ();
5476 objcache_dump_stats ();
5477 gcry_control (GCRYCTL_DUMP_MEMORY_STATS);
5478 gcry_control (GCRYCTL_DUMP_RANDOM_STATS);
5481 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
5483 gnupg_block_all_signals ();
5484 emergency_cleanup ();
5488 else if (log_get_errorcount(0))
5490 else if (g10_errors_seen)
5492 else if (opt.assert_signer_list && !assert_signer_true)
5499 /* Pretty-print hex hashes. This assumes at least an 80-character
5500 display, but there are a few other similar assumptions in the
5503 print_hex (gcry_md_hd_t md, int algo, const char *fname)
5505 int i,n,count,indent=0;
5509 indent = es_printf("%s: ",fname);
5517 if (algo==DIGEST_ALGO_RMD160)
5518 indent += es_printf("RMD160 = ");
5520 indent += es_printf("%6s = ", gcry_md_algo_name (algo));
5526 p = gcry_md_read (md, algo);
5527 n = gcry_md_get_algo_dlen (algo);
5529 count += es_printf ("%02X",*p++);
5531 for(i=1;i<n;i++,p++)
5537 es_printf ("\n%*s",indent,indent?" ":"");
5541 count += es_printf(" ");
5544 count += es_printf(" ");
5552 es_printf ("\n%*s",indent,indent?" ":"");
5556 count += es_printf(" ");
5560 count += es_printf(" ");
5568 es_printf ("\n%*s",indent, indent?" ":"");
5572 count += es_printf(" ");
5576 count += es_printf("%02X",*p);
5583 print_hashline( gcry_md_hd_t md, int algo, const char *fname )
5590 for (p = fname; *p; p++ )
5592 if ( *p <= 32 || *p > 127 || *p == ':' || *p == '%' )
5593 es_printf ("%%%02X", *p );
5595 es_putc (*p, es_stdout);
5598 es_putc (':', es_stdout);
5599 es_printf ("%d:", algo);
5600 p = gcry_md_read (md, algo);
5601 n = gcry_md_get_algo_dlen (algo);
5602 for(i=0; i < n ; i++, p++ )
5603 es_printf ("%02X", *p);
5604 es_fputs (":\n", es_stdout);
5609 print_mds( const char *fname, int algo )
5623 fp = es_fopen (fname, "rb" );
5624 if (fp && is_secured_file (es_fileno (fp)))
5628 gpg_err_set_errno (EPERM);
5633 log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
5637 gcry_md_open (&md, 0, 0);
5639 gcry_md_enable (md, algo);
5642 if (!gcry_md_test_algo (GCRY_MD_MD5))
5643 gcry_md_enable (md, GCRY_MD_MD5);
5644 gcry_md_enable (md, GCRY_MD_SHA1);
5645 if (!gcry_md_test_algo (GCRY_MD_RMD160))
5646 gcry_md_enable (md, GCRY_MD_RMD160);
5647 if (!gcry_md_test_algo (GCRY_MD_SHA224))
5648 gcry_md_enable (md, GCRY_MD_SHA224);
5649 if (!gcry_md_test_algo (GCRY_MD_SHA256))
5650 gcry_md_enable (md, GCRY_MD_SHA256);
5651 if (!gcry_md_test_algo (GCRY_MD_SHA384))
5652 gcry_md_enable (md, GCRY_MD_SHA384);
5653 if (!gcry_md_test_algo (GCRY_MD_SHA512))
5654 gcry_md_enable (md, GCRY_MD_SHA512);
5657 while ((n=es_fread (buf, 1, DIM(buf), fp)))
5658 gcry_md_write (md, buf, n);
5661 log_error ("%s: %s\n", fname?fname:"[stdin]", strerror(errno));
5665 if (opt.with_colons)
5668 print_hashline (md, algo, fname);
5671 if (!gcry_md_test_algo (GCRY_MD_MD5))
5672 print_hashline( md, GCRY_MD_MD5, fname );
5673 print_hashline( md, GCRY_MD_SHA1, fname );
5674 if (!gcry_md_test_algo (GCRY_MD_RMD160))
5675 print_hashline( md, GCRY_MD_RMD160, fname );
5676 if (!gcry_md_test_algo (GCRY_MD_SHA224))
5677 print_hashline (md, GCRY_MD_SHA224, fname);
5678 if (!gcry_md_test_algo (GCRY_MD_SHA256))
5679 print_hashline( md, GCRY_MD_SHA256, fname );
5680 if (!gcry_md_test_algo (GCRY_MD_SHA384))
5681 print_hashline ( md, GCRY_MD_SHA384, fname );
5682 if (!gcry_md_test_algo (GCRY_MD_SHA512))
5683 print_hashline ( md, GCRY_MD_SHA512, fname );
5689 print_hex (md, -algo, fname);
5692 if (!gcry_md_test_algo (GCRY_MD_MD5))
5693 print_hex (md, GCRY_MD_MD5, fname);
5694 print_hex (md, GCRY_MD_SHA1, fname );
5695 if (!gcry_md_test_algo (GCRY_MD_RMD160))
5696 print_hex (md, GCRY_MD_RMD160, fname );
5697 if (!gcry_md_test_algo (GCRY_MD_SHA224))
5698 print_hex (md, GCRY_MD_SHA224, fname);
5699 if (!gcry_md_test_algo (GCRY_MD_SHA256))
5700 print_hex (md, GCRY_MD_SHA256, fname );
5701 if (!gcry_md_test_algo (GCRY_MD_SHA384))
5702 print_hex (md, GCRY_MD_SHA384, fname );
5703 if (!gcry_md_test_algo (GCRY_MD_SHA512))
5704 print_hex (md, GCRY_MD_SHA512, fname );
5716 * Check the supplied name,value string and add it to the notation
5717 * data to be used for signatures. which==0 for sig notations, and 1
5718 * for cert notations.
5721 add_notation_data( const char *string, int which )
5723 struct notation *notation;
5725 notation=string_to_notation(string,utf8_strings);
5730 notation->next=opt.cert_notations;
5731 opt.cert_notations=notation;
5735 notation->next=opt.sig_notations;
5736 opt.sig_notations=notation;
5742 add_policy_url( const char *string, int which )
5744 unsigned int i,critical=0;
5753 for(i=0;i<strlen(string);i++)
5754 if( !isascii (string[i]) || iscntrl(string[i]))
5757 if(i==0 || i<strlen(string))
5760 log_error(_("the given certification policy URL is invalid\n"));
5762 log_error(_("the given signature policy URL is invalid\n"));
5766 sl=add_to_strlist( &opt.cert_policy_url, string );
5768 sl=add_to_strlist( &opt.sig_policy_url, string );
5775 add_keyserver_url( const char *string, int which )
5777 unsigned int i,critical=0;
5786 for(i=0;i<strlen(string);i++)
5787 if( !isascii (string[i]) || iscntrl(string[i]))
5790 if(i==0 || i<strlen(string))
5795 log_error(_("the given preferred keyserver URL is invalid\n"));
5801 sl=add_to_strlist( &opt.sig_keyserver_url, string );
5809 read_sessionkey_from_fd (int fd)
5814 if (! gnupg_fd_valid (fd))
5815 log_fatal ("override-session-key-fd is invalid: %s\n", strerror (errno));
5817 for (line = NULL, i = len = 100; ; i++ )
5823 line = xmalloc_secure (len);
5826 memcpy (line, tmp, i);
5832 if (read (fd, line + i, 1) != 1 || line[i] == '\n')
5836 log_debug ("seskey: %s\n", line);
5837 gpgrt_annotate_leaked_object (line);
5838 opt.override_session_key = line;