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-2021 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/shareddefs.h"
68 #include "../common/compliance.h"
69 #include "../common/comopt.h"
71 #if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
72 #define MY_O_BINARY O_BINARY
81 enum cmd_and_opt_values
90 oHiddenRecipientFile = 'F',
97 oHiddenRecipient = 'R',
104 aListSecretKeys = 'K',
143 aDeleteSecretAndPublicKeys,
202 oWithSubkeyFingerprint,
231 oDebugAllowLargeChunks,
260 oBZ2DecompressLowmem,
284 oSkipHiddenRecipients,
285 oNoSkipHiddenRecipients,
299 oUseEmbeddedFilename,
300 oNoUseEmbeddedFilename,
334 oEncryptToDefaultKey,
341 oAllowNonSelfsignedUID,
342 oNoAllowNonSelfsignedUID,
345 oAllowSecretKeyImport,
346 oAllowOldCipherAlgos,
347 oEnableSpecialFilenames,
359 oOverrideSessionKeyFD,
372 oNoExpensiveTrustChecks,
378 oPreservePermissions,
379 oDefaultPreferenceList,
380 oDefaultKeyserverURL,
381 oPersonalCipherPreferences,
382 oPersonalAEADPreferences,
383 oPersonalDigestPreferences,
384 oPersonalCompressPreferences,
401 oNoMangleDosFilenames,
402 oEnableProgressFilter,
405 oExitOnStatusWriteError,
406 oLimitCardInsertTries,
419 oAllowWeakDigestAlgos,
420 oAllowWeakKeySignatures,
446 static gpgrt_opt_t opts[] = {
448 ARGPARSE_group (300, N_("@Commands:\n ")),
450 ARGPARSE_c (aSign, "sign", N_("make a signature")),
451 ARGPARSE_c (aClearsign, "clear-sign", N_("make a clear text signature")),
452 ARGPARSE_c (aClearsign, "clearsign", "@"),
453 ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")),
454 ARGPARSE_c (aEncr, "encrypt", N_("encrypt data")),
455 ARGPARSE_c (aEncrFiles, "encrypt-files", "@"),
456 ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")),
457 ARGPARSE_c (aStore, "store", "@"),
458 ARGPARSE_c (aDecrypt, "decrypt", N_("decrypt data (default)")),
459 ARGPARSE_c (aDecryptFiles, "decrypt-files", "@"),
460 ARGPARSE_c (aVerify, "verify" , N_("verify a signature")),
461 ARGPARSE_c (aVerifyFiles, "verify-files" , "@" ),
462 ARGPARSE_c (aListKeys, "list-keys", N_("list keys")),
463 ARGPARSE_c (aListKeys, "list-public-keys", "@" ),
464 ARGPARSE_c (aListSigs, "list-signatures", N_("list keys and signatures")),
465 ARGPARSE_c (aListSigs, "list-sigs", "@"),
466 ARGPARSE_c (aCheckKeys, "check-signatures",
467 N_("list and check key signatures")),
468 ARGPARSE_c (aCheckKeys, "check-sigs", "@"),
469 ARGPARSE_c (oFingerprint, "fingerprint", N_("list keys and fingerprints")),
470 ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")),
471 ARGPARSE_c (aKeygen, "generate-key",
472 N_("generate a new key pair")),
473 ARGPARSE_c (aKeygen, "gen-key", "@"),
474 ARGPARSE_c (aQuickKeygen, "quick-generate-key" ,
475 N_("quickly generate a new key pair")),
476 ARGPARSE_c (aQuickKeygen, "quick-gen-key", "@"),
477 ARGPARSE_c (aQuickAddUid, "quick-add-uid",
478 N_("quickly add a new user-id")),
479 ARGPARSE_c (aQuickAddUid, "quick-adduid", "@"),
480 ARGPARSE_c (aQuickAddKey, "quick-add-key", "@"),
481 ARGPARSE_c (aQuickAddKey, "quick-addkey", "@"),
482 ARGPARSE_c (aQuickRevUid, "quick-revoke-uid",
483 N_("quickly revoke a user-id")),
484 ARGPARSE_c (aQuickRevUid, "quick-revuid", "@"),
485 ARGPARSE_c (aQuickSetExpire, "quick-set-expire",
486 N_("quickly set a new expiration date")),
487 ARGPARSE_c (aQuickSetPrimaryUid, "quick-set-primary-uid", "@"),
488 ARGPARSE_c (aFullKeygen, "full-generate-key" ,
489 N_("full featured key pair generation")),
490 ARGPARSE_c (aFullKeygen, "full-gen-key", "@"),
491 ARGPARSE_c (aGenRevoke, "generate-revocation",
492 N_("generate a revocation certificate")),
493 ARGPARSE_c (aGenRevoke, "gen-revoke", "@"),
494 ARGPARSE_c (aDeleteKeys,"delete-keys",
495 N_("remove keys from the public keyring")),
496 ARGPARSE_c (aDeleteSecretKeys, "delete-secret-keys",
497 N_("remove keys from the secret keyring")),
498 ARGPARSE_c (aQuickSignKey, "quick-sign-key" ,
499 N_("quickly sign a key")),
500 ARGPARSE_c (aQuickLSignKey, "quick-lsign-key",
501 N_("quickly sign a key locally")),
502 ARGPARSE_c (aQuickRevSig, "quick-revoke-sig" ,
503 N_("quickly revoke a key signature")),
504 ARGPARSE_c (aSignKey, "sign-key" ,N_("sign a key")),
505 ARGPARSE_c (aLSignKey, "lsign-key" ,N_("sign a key locally")),
506 ARGPARSE_c (aEditKey, "edit-key" ,N_("sign or edit a key")),
507 ARGPARSE_c (aEditKey, "key-edit" ,"@"),
508 ARGPARSE_c (aPasswd, "change-passphrase", N_("change a passphrase")),
509 ARGPARSE_c (aPasswd, "passwd", "@"),
510 ARGPARSE_c (aDesigRevoke, "generate-designated-revocation", "@"),
511 ARGPARSE_c (aDesigRevoke, "desig-revoke","@" ),
512 ARGPARSE_c (aExport, "export" , N_("export keys") ),
513 ARGPARSE_c (aSendKeys, "send-keys" , N_("export keys to a keyserver") ),
514 ARGPARSE_c (aRecvKeys, "receive-keys" , N_("import keys from a keyserver") ),
515 ARGPARSE_c (aRecvKeys, "recv-keys" , "@"),
516 ARGPARSE_c (aSearchKeys, "search-keys" ,
517 N_("search for keys on a keyserver") ),
518 ARGPARSE_c (aRefreshKeys, "refresh-keys",
519 N_("update all keys from a keyserver")),
520 ARGPARSE_c (aLocateKeys, "locate-keys", "@"),
521 ARGPARSE_c (aLocateExtKeys, "locate-external-keys", "@"),
522 ARGPARSE_c (aFetchKeys, "fetch-keys" , "@" ),
523 ARGPARSE_c (aShowKeys, "show-keys" , "@" ),
524 ARGPARSE_c (aExportSecret, "export-secret-keys" , "@" ),
525 ARGPARSE_c (aExportSecretSub, "export-secret-subkeys" , "@" ),
526 ARGPARSE_c (aExportSshKey, "export-ssh-key", "@" ),
527 ARGPARSE_c (aImport, "import", N_("import/merge keys")),
528 ARGPARSE_c (aFastImport, "fast-import", "@"),
529 #ifdef ENABLE_CARD_SUPPORT
530 ARGPARSE_c (aCardStatus, "card-status", N_("print the card status")),
531 ARGPARSE_c (aCardEdit, "edit-card", N_("change data on a card")),
532 ARGPARSE_c (aCardEdit, "card-edit", "@"),
533 ARGPARSE_c (aChangePIN, "change-pin", N_("change a card's PIN")),
535 ARGPARSE_c (aListConfig, "list-config", "@"),
536 ARGPARSE_c (aListGcryptConfig, "list-gcrypt-config", "@"),
537 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@" ),
538 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@" ),
539 ARGPARSE_c (aListPackets, "list-packets","@"),
541 #ifndef NO_TRUST_MODELS
542 ARGPARSE_c (aExportOwnerTrust, "export-ownertrust", "@"),
543 ARGPARSE_c (aImportOwnerTrust, "import-ownertrust", "@"),
544 ARGPARSE_c (aUpdateTrustDB,"update-trustdb",
545 N_("update the trust database")),
546 ARGPARSE_c (aCheckTrustDB, "check-trustdb", "@"),
547 ARGPARSE_c (aFixTrustDB, "fix-trustdb", "@"),
548 ARGPARSE_c (aListTrustDB, "list-trustdb", "@"),
551 ARGPARSE_c (aDeArmor, "dearmor", "@"),
552 ARGPARSE_c (aDeArmor, "dearmour", "@"),
553 ARGPARSE_c (aEnArmor, "enarmor", "@"),
554 ARGPARSE_c (aEnArmor, "enarmour", "@"),
555 ARGPARSE_c (aPrintMD, "print-md", N_("print message digests")),
556 ARGPARSE_c (aPrintMDs, "print-mds", "@"), /* old */
557 ARGPARSE_c (aPrimegen, "gen-prime", "@" ),
558 ARGPARSE_c (aGenRandom,"gen-random", "@" ),
559 ARGPARSE_c (aServer, "server", N_("run in server mode")),
560 ARGPARSE_c (aTOFUPolicy, "tofu-policy",
561 N_("|VALUE|set the TOFU policy for a key")),
563 ARGPARSE_c (aListTrustPath, "list-trust-path", "@"), */
564 ARGPARSE_c (aDeleteSecretAndPublicKeys,
565 "delete-secret-and-public-keys", "@"),
566 ARGPARSE_c (aRebuildKeydbCaches, "rebuild-keydb-caches", "@"),
567 ARGPARSE_c (aListKeys, "list-key", "@"), /* alias */
568 ARGPARSE_c (aListSigs, "list-sig", "@"), /* alias */
569 ARGPARSE_c (aCheckKeys, "check-sig", "@"), /* alias */
570 ARGPARSE_c (aShowKeys, "show-key", "@"), /* alias */
574 ARGPARSE_header ("Monitor", N_("Options controlling the diagnostic output")),
576 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
577 ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
578 ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
579 ARGPARSE_s_n (oNoTTY, "no-tty", "@"),
580 ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
581 ARGPARSE_s_s (oDebug, "debug", "@"),
582 ARGPARSE_s_s (oDebugLevel, "debug-level", "@"),
583 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
584 ARGPARSE_s_n (oDebugIOLBF, "debug-iolbf", "@"),
585 ARGPARSE_s_u (oDebugSetIobufSize, "debug-set-iobuf-size", "@"),
586 ARGPARSE_s_u (oDebugAllowLargeChunks, "debug-allow-large-chunks", "@"),
587 ARGPARSE_s_s (oDisplayCharset, "display-charset", "@"),
588 ARGPARSE_s_s (oDisplayCharset, "charset", "@"),
589 ARGPARSE_conffile (oOptions, "options", N_("|FILE|read options from FILE")),
590 ARGPARSE_noconffile (oNoOptions, "no-options", "@"),
591 ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"),
592 ARGPARSE_s_s (oLoggerFile, "log-file",
593 N_("|FILE|write server mode logs to FILE")),
594 ARGPARSE_s_s (oLoggerFile, "logger-file", "@"), /* 1.4 compatibility. */
595 ARGPARSE_s_n (oQuickRandom, "debug-quick-random", "@"),
598 ARGPARSE_header ("Configuration",
599 N_("Options controlling the configuration")),
601 ARGPARSE_s_s (oHomedir, "homedir", "@"),
602 ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
603 ARGPARSE_s_s (oDefaultKey, "default-key",
604 N_("|NAME|use NAME as default secret key")),
605 ARGPARSE_s_s (oEncryptTo, "encrypt-to",
606 N_("|NAME|encrypt to user ID NAME as well")),
607 ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"),
608 ARGPARSE_s_s (oHiddenEncryptTo, "hidden-encrypt-to", "@"),
609 ARGPARSE_s_n (oEncryptToDefaultKey, "encrypt-to-default-key", "@"),
610 ARGPARSE_s_s (oDefRecipient, "default-recipient", "@"),
611 ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", "@"),
612 ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"),
613 ARGPARSE_s_s (oGroup, "group",
614 N_("|SPEC|set up email aliases")),
615 ARGPARSE_s_s (oUnGroup, "ungroup", "@"),
616 ARGPARSE_s_n (oNoGroups, "no-groups", "@"),
617 ARGPARSE_s_s (oCompliance, "compliance", "@"),
618 ARGPARSE_s_n (oGnuPG, "gnupg", "@"),
619 ARGPARSE_s_n (oGnuPG, "no-pgp2", "@"),
620 ARGPARSE_s_n (oGnuPG, "no-pgp6", "@"),
621 ARGPARSE_s_n (oGnuPG, "no-pgp7", "@"),
622 ARGPARSE_s_n (oGnuPG, "no-pgp8", "@"),
623 ARGPARSE_s_n (oRFC2440, "rfc2440", "@"),
624 ARGPARSE_s_n (oRFC4880, "rfc4880", "@"),
625 ARGPARSE_s_n (oRFC4880bis, "rfc4880bis", "@"),
626 ARGPARSE_s_n (oOpenPGP, "openpgp", N_("use strict OpenPGP behavior")),
627 ARGPARSE_s_n (oPGP7, "pgp6", "@"),
628 ARGPARSE_s_n (oPGP7, "pgp7", "@"),
629 ARGPARSE_s_n (oPGP8, "pgp8", "@"),
630 ARGPARSE_s_s (oDefaultNewKeyAlgo, "default-new-key-algo", "@"),
631 #ifndef NO_TRUST_MODELS
632 ARGPARSE_s_n (oAlwaysTrust, "always-trust", "@"),
634 ARGPARSE_s_s (oTrustModel, "trust-model", "@"),
635 ARGPARSE_s_s (oPhotoViewer, "photo-viewer", "@"),
636 ARGPARSE_s_s (oKnownNotation, "known-notation", "@"),
637 ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
638 ARGPARSE_s_s (oKeyboxdProgram, "keyboxd-program", "@"),
639 ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"),
640 ARGPARSE_s_n (oExitOnStatusWriteError, "exit-on-status-write-error", "@"),
641 ARGPARSE_s_i (oLimitCardInsertTries, "limit-card-insert-tries", "@"),
642 ARGPARSE_s_n (oEnableProgressFilter, "enable-progress-filter", "@"),
643 ARGPARSE_s_s (oTempDir, "temp-directory", "@"),
644 ARGPARSE_s_s (oExecPath, "exec-path", "@"),
645 ARGPARSE_s_n (oExpert, "expert", "@"),
646 ARGPARSE_s_n (oNoExpert, "no-expert", "@"),
647 ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"),
648 ARGPARSE_s_n (oRequireSecmem, "require-secmem", "@"),
649 ARGPARSE_s_n (oNoRequireSecmem, "no-require-secmem", "@"),
650 ARGPARSE_s_n (oNoPermissionWarn, "no-permission-warning", "@"),
651 ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")),
652 ARGPARSE_s_n (oInteractive, "interactive", N_("prompt before overwriting")),
653 ARGPARSE_s_s (oDefSigExpire, "default-sig-expire", "@"),
654 ARGPARSE_s_n (oAskSigExpire, "ask-sig-expire", "@"),
655 ARGPARSE_s_n (oNoAskSigExpire, "no-ask-sig-expire", "@"),
656 ARGPARSE_s_s (oDefCertExpire, "default-cert-expire", "@"),
657 ARGPARSE_s_n (oAskCertExpire, "ask-cert-expire", "@"),
658 ARGPARSE_s_n (oNoAskCertExpire, "no-ask-cert-expire", "@"),
659 ARGPARSE_s_i (oDefCertLevel, "default-cert-level", "@"),
660 ARGPARSE_s_i (oMinCertLevel, "min-cert-level", "@"),
661 ARGPARSE_s_n (oAskCertLevel, "ask-cert-level", "@"),
662 ARGPARSE_s_n (oNoAskCertLevel, "no-ask-cert-level", "@"),
663 ARGPARSE_s_n (oOnlySignTextIDs, "only-sign-text-ids", "@"),
664 ARGPARSE_s_n (oEnableLargeRSA, "enable-large-rsa", "@"),
665 ARGPARSE_s_n (oDisableLargeRSA, "disable-large-rsa", "@"),
666 ARGPARSE_s_n (oEnableDSA2, "enable-dsa2", "@"),
667 ARGPARSE_s_n (oDisableDSA2, "disable-dsa2", "@"),
668 ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-preferences","@"),
669 ARGPARSE_s_s (oPersonalAEADPreferences, "personal-aead-preferences","@"),
670 ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-preferences","@"),
671 ARGPARSE_s_s (oPersonalCompressPreferences,
672 "personal-compress-preferences", "@"),
673 ARGPARSE_s_s (oDefaultPreferenceList, "default-preference-list", "@"),
674 ARGPARSE_s_s (oDefaultKeyserverURL, "default-keyserver-url", "@"),
675 ARGPARSE_s_n (oNoExpensiveTrustChecks, "no-expensive-trust-checks", "@"),
676 ARGPARSE_s_n (oAllowNonSelfsignedUID, "allow-non-selfsigned-uid", "@"),
677 ARGPARSE_s_n (oNoAllowNonSelfsignedUID, "no-allow-non-selfsigned-uid", "@"),
678 ARGPARSE_s_n (oAllowFreeformUID, "allow-freeform-uid", "@"),
679 ARGPARSE_s_n (oNoAllowFreeformUID, "no-allow-freeform-uid", "@"),
680 ARGPARSE_s_n (oPreservePermissions, "preserve-permissions", "@"),
681 ARGPARSE_s_i (oDefCertLevel, "default-cert-check-level", "@"), /* old */
682 ARGPARSE_s_s (oTOFUDefaultPolicy, "tofu-default-policy", "@"),
683 ARGPARSE_s_n (oLockOnce, "lock-once", "@"),
684 ARGPARSE_s_n (oLockMultiple, "lock-multiple", "@"),
685 ARGPARSE_s_n (oLockNever, "lock-never", "@"),
686 ARGPARSE_s_s (oCompressAlgo,"compress-algo", "@"),
687 ARGPARSE_s_s (oCompressAlgo, "compression-algo", "@"), /* Alias */
688 ARGPARSE_s_n (oBZ2DecompressLowmem, "bzip2-decompress-lowmem", "@"),
689 ARGPARSE_s_i (oCompletesNeeded, "completes-needed", "@"),
690 ARGPARSE_s_i (oMarginalsNeeded, "marginals-needed", "@"),
691 ARGPARSE_s_i (oMaxCertDepth, "max-cert-depth", "@" ),
692 #ifndef NO_TRUST_MODELS
693 ARGPARSE_s_s (oTrustDBName, "trustdb-name", "@"),
694 ARGPARSE_s_n (oAutoCheckTrustDB, "auto-check-trustdb", "@"),
695 ARGPARSE_s_n (oNoAutoCheckTrustDB, "no-auto-check-trustdb", "@"),
696 ARGPARSE_s_s (oForceOwnertrust, "force-ownertrust", "@"),
697 ARGPARSE_s_n (oNoAutoTrustNewKey, "no-auto-trust-new-key", "@"),
701 ARGPARSE_header ("Input", N_("Options controlling the input")),
703 ARGPARSE_s_n (oMultifile, "multifile", "@"),
704 ARGPARSE_s_s (oInputSizeHint, "input-size-hint", "@"),
705 ARGPARSE_s_n (oUtf8Strings, "utf8-strings", "@"),
706 ARGPARSE_s_n (oNoUtf8Strings, "no-utf8-strings", "@"),
707 ARGPARSE_p_u (oSetFilesize, "set-filesize", "@"),
708 ARGPARSE_s_n (oNoLiteral, "no-literal", "@"),
709 ARGPARSE_s_s (oSetNotation, "set-notation", "@"),
710 ARGPARSE_s_s (oSigNotation, "sig-notation", "@"),
711 ARGPARSE_s_s (oCertNotation, "cert-notation", "@"),
712 ARGPARSE_s_s (oSetPolicyURL, "set-policy-url", "@"),
713 ARGPARSE_s_s (oSigPolicyURL, "sig-policy-url", "@"),
714 ARGPARSE_s_s (oCertPolicyURL, "cert-policy-url", "@"),
715 ARGPARSE_s_s (oSigKeyserverURL, "sig-keyserver-url", "@"),
719 ARGPARSE_header ("Output", N_("Options controlling the output")),
721 ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")),
722 ARGPARSE_s_n (oArmor, "armour", "@"),
723 ARGPARSE_s_n (oNoArmor, "no-armor", "@"),
724 ARGPARSE_s_n (oNoArmor, "no-armour", "@"),
725 ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")),
726 ARGPARSE_p_u (oMaxOutput, "max-output", "@"),
727 ARGPARSE_s_s (oComment, "comment", "@"),
728 ARGPARSE_s_n (oDefaultComment, "default-comment", "@"),
729 ARGPARSE_s_n (oNoComments, "no-comments", "@"),
730 ARGPARSE_s_n (oEmitVersion, "emit-version", "@"),
731 ARGPARSE_s_n (oNoEmitVersion, "no-emit-version", "@"),
732 ARGPARSE_s_n (oNoEmitVersion, "no-version", "@"), /* alias */
733 ARGPARSE_s_n (oNotDashEscaped, "not-dash-escaped", "@"),
734 ARGPARSE_s_n (oEscapeFrom, "escape-from-lines", "@"),
735 ARGPARSE_s_n (oNoEscapeFrom, "no-escape-from-lines", "@"),
736 ARGPARSE_s_n (oMimemode, "mimemode", "@"),
737 ARGPARSE_s_n (oTextmodeShort, NULL, "@"),
738 ARGPARSE_s_n (oTextmode, "textmode", N_("use canonical text mode")),
739 ARGPARSE_s_n (oNoTextmode, "no-textmode", "@"),
740 ARGPARSE_s_s (oSetFilename, "set-filename", "@"),
741 ARGPARSE_s_n (oForYourEyesOnly, "for-your-eyes-only", "@"),
742 ARGPARSE_s_n (oNoForYourEyesOnly, "no-for-your-eyes-only", "@"),
743 ARGPARSE_s_n (oShowNotation, "show-notation", "@"),
744 ARGPARSE_s_n (oNoShowNotation, "no-show-notation", "@"),
745 ARGPARSE_s_n (oShowSessionKey, "show-session-key", "@"),
746 ARGPARSE_s_n (oUseEmbeddedFilename, "use-embedded-filename", "@"),
747 ARGPARSE_s_n (oNoUseEmbeddedFilename, "no-use-embedded-filename", "@"),
748 ARGPARSE_s_n (oUnwrap, "unwrap", "@"),
749 ARGPARSE_s_n (oMangleDosFilenames, "mangle-dos-filenames", "@"),
750 ARGPARSE_s_n (oNoMangleDosFilenames, "no-mangle-dos-filenames", "@"),
751 ARGPARSE_s_i (oChunkSize, "chunk-size", "@"),
752 ARGPARSE_s_n (oNoSymkeyCache, "no-symkey-cache", "@"),
753 ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"),
754 ARGPARSE_s_n (oListOnly, "list-only", "@"),
755 ARGPARSE_s_i (oCompress, NULL,
756 N_("|N|set compress level to N (0 disables)")),
757 ARGPARSE_s_i (oCompressLevel, "compress-level", "@"),
758 ARGPARSE_s_i (oBZ2CompressLevel, "bzip2-compress-level", "@"),
759 ARGPARSE_s_n (oDisableSignerUID, "disable-signer-uid", "@"),
761 ARGPARSE_header ("ImportExport",
762 N_("Options controlling key import and export")),
764 ARGPARSE_s_s (oAutoKeyLocate, "auto-key-locate",
765 N_("|MECHANISMS|use MECHANISMS to locate keys by mail address")),
766 ARGPARSE_s_n (oNoAutoKeyLocate, "no-auto-key-locate", "@"),
767 ARGPARSE_s_n (oAutoKeyImport, "auto-key-import",
768 N_("import missing key from a signature")),
769 ARGPARSE_s_n (oNoAutoKeyImport, "no-auto-key-import", "@"),
770 ARGPARSE_s_n (oAutoKeyRetrieve, "auto-key-retrieve", "@"),
771 ARGPARSE_s_n (oNoAutoKeyRetrieve, "no-auto-key-retrieve", "@"),
772 ARGPARSE_s_n (oIncludeKeyBlock, "include-key-block",
773 N_("include the public key in signatures")),
774 ARGPARSE_s_n (oNoIncludeKeyBlock, "no-include-key-block", "@"),
775 ARGPARSE_s_n (oDisableDirmngr, "disable-dirmngr",
776 N_("disable all access to the dirmngr")),
777 ARGPARSE_s_s (oKeyServer, "keyserver", "@"), /* Deprecated. */
778 ARGPARSE_s_s (oKeyServerOptions, "keyserver-options", "@"),
779 ARGPARSE_s_s (oKeyOrigin, "key-origin", "@"),
780 ARGPARSE_s_s (oImportOptions, "import-options", "@"),
781 ARGPARSE_s_s (oImportFilter, "import-filter", "@"),
782 ARGPARSE_s_s (oExportOptions, "export-options", "@"),
783 ARGPARSE_s_s (oExportFilter, "export-filter", "@"),
784 ARGPARSE_s_n (oMergeOnly, "merge-only", "@" ),
785 ARGPARSE_s_n (oAllowSecretKeyImport, "allow-secret-key-import", "@"),
788 ARGPARSE_header ("Keylist", N_("Options controlling key listings")),
790 ARGPARSE_s_s (oListOptions, "list-options", "@"),
791 ARGPARSE_s_n (oFullTimestrings, "full-timestrings", "@"),
792 ARGPARSE_s_n (oShowPhotos, "show-photos", "@"),
793 ARGPARSE_s_n (oNoShowPhotos, "no-show-photos", "@"),
794 ARGPARSE_s_n (oShowPolicyURL, "show-policy-url", "@"),
795 ARGPARSE_s_n (oNoShowPolicyURL, "no-show-policy-url", "@"),
796 ARGPARSE_s_n (oWithColons, "with-colons", "@"),
797 ARGPARSE_s_n (oWithTofuInfo,"with-tofu-info", "@"),
798 ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"),
799 ARGPARSE_s_n (oWithSigList,"with-sig-list", "@"),
800 ARGPARSE_s_n (oWithSigCheck,"with-sig-check", "@"),
801 ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"),
802 ARGPARSE_s_n (oWithSubkeyFingerprint, "with-subkey-fingerprint", "@"),
803 ARGPARSE_s_n (oWithSubkeyFingerprint, "with-subkey-fingerprints", "@"),
804 ARGPARSE_s_n (oWithICAOSpelling, "with-icao-spelling", "@"),
805 ARGPARSE_s_n (oWithKeygrip, "with-keygrip", "@"),
806 ARGPARSE_s_n (oWithKeyScreening,"with-key-screening", "@"),
807 ARGPARSE_s_n (oWithSecret, "with-secret", "@"),
808 ARGPARSE_s_n (oWithWKDHash, "with-wkd-hash", "@"),
809 ARGPARSE_s_n (oWithKeyOrigin, "with-key-origin", "@"),
810 ARGPARSE_s_n (oFastListMode, "fast-list-mode", "@"),
811 ARGPARSE_s_n (oFixedListMode, "fixed-list-mode", "@"),
812 ARGPARSE_s_n (oLegacyListMode, "legacy-list-mode", "@"),
813 ARGPARSE_s_n (oPrintDANERecords, "print-dane-records", "@"),
814 ARGPARSE_s_s (oKeyidFormat, "keyid-format", "@"),
815 ARGPARSE_s_n (oShowKeyring, "show-keyring", "@"),
818 ARGPARSE_header (NULL, N_("Options to specify keys")),
820 ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")),
821 ARGPARSE_s_s (oHiddenRecipient, "hidden-recipient", "@"),
822 ARGPARSE_s_s (oRecipientFile, "recipient-file", "@"),
823 ARGPARSE_s_s (oHiddenRecipientFile, "hidden-recipient-file", "@"),
824 ARGPARSE_s_s (oRecipient, "remote-user", "@"), /* (old option name) */
825 ARGPARSE_s_n (oThrowKeyids, "throw-keyids", "@"),
826 ARGPARSE_s_n (oNoThrowKeyids, "no-throw-keyids", "@"),
827 ARGPARSE_s_s (oLocalUser, "local-user",
828 N_("|USER-ID|use USER-ID to sign or decrypt")),
829 ARGPARSE_s_s (oTrustedKey, "trusted-key", "@"),
830 ARGPARSE_s_s (oSender, "sender", "@"),
831 ARGPARSE_s_s (oTrySecretKey, "try-secret-key", "@"),
832 ARGPARSE_s_n (oTryAllSecrets, "try-all-secrets", "@"),
833 ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"),
834 ARGPARSE_s_n (oNoKeyring, "no-keyring", "@"),
835 ARGPARSE_s_s (oKeyring, "keyring", "@"),
836 ARGPARSE_s_s (oPrimaryKeyring, "primary-keyring", "@"),
837 ARGPARSE_s_s (oSecretKeyring, "secret-keyring", "@"),
838 ARGPARSE_s_n (oSkipHiddenRecipients, "skip-hidden-recipients", "@"),
839 ARGPARSE_s_n (oNoSkipHiddenRecipients, "no-skip-hidden-recipients", "@"),
840 ARGPARSE_s_s (oOverrideSessionKey, "override-session-key", "@"),
841 ARGPARSE_s_i (oOverrideSessionKeyFD, "override-session-key-fd", "@"),
844 ARGPARSE_header ("Security", N_("Options controlling the security")),
846 ARGPARSE_s_i (oS2KMode, "s2k-mode", "@"),
847 ARGPARSE_s_s (oS2KDigest, "s2k-digest-algo", "@"),
848 ARGPARSE_s_s (oS2KCipher, "s2k-cipher-algo", "@"),
849 ARGPARSE_s_i (oS2KCount, "s2k-count", "@"),
850 ARGPARSE_s_n (oForceAEAD, "force-aead", "@"),
851 ARGPARSE_s_n (oRequireCrossCert, "require-backsigs", "@"),
852 ARGPARSE_s_n (oRequireCrossCert, "require-cross-certification", "@"),
853 ARGPARSE_s_n (oNoRequireCrossCert, "no-require-backsigs", "@"),
854 ARGPARSE_s_n (oNoRequireCrossCert, "no-require-cross-certification", "@"),
855 /* Options to override new security defaults. */
856 ARGPARSE_s_n (oAllowWeakKeySignatures, "allow-weak-key-signatures", "@"),
857 ARGPARSE_s_n (oAllowWeakDigestAlgos, "allow-weak-digest-algos", "@"),
858 ARGPARSE_s_n (oAllowOldCipherAlgos, "allow-old-cipher-algos", "@"),
859 ARGPARSE_s_s (oWeakDigest, "weak-digest","@"),
860 ARGPARSE_s_s (oVerifyOptions, "verify-options", "@"),
861 ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"),
862 ARGPARSE_s_n (oNoRandomSeedFile, "no-random-seed-file", "@"),
863 ARGPARSE_s_n (oNoSigCache, "no-sig-cache", "@"),
864 ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"),
865 ARGPARSE_s_n (oIgnoreValidFrom, "ignore-valid-from", "@"),
866 ARGPARSE_s_n (oIgnoreCrcError, "ignore-crc-error", "@"),
867 ARGPARSE_s_n (oIgnoreMDCError, "ignore-mdc-error", "@"),
868 ARGPARSE_s_s (oDisableCipherAlgo, "disable-cipher-algo", "@"),
869 ARGPARSE_s_s (oDisablePubkeyAlgo, "disable-pubkey-algo", "@"),
870 ARGPARSE_s_s (oCipherAlgo, "cipher-algo", "@"),
871 ARGPARSE_s_s (oAEADAlgo, "aead-algo", "@"),
872 ARGPARSE_s_s (oDigestAlgo, "digest-algo", "@"),
873 ARGPARSE_s_s (oCertDigestAlgo, "cert-digest-algo", "@"),
876 ARGPARSE_header (NULL, N_("Options for unattended use")),
878 ARGPARSE_s_n (oBatch, "batch", "@"),
879 ARGPARSE_s_n (oNoBatch, "no-batch", "@"),
880 ARGPARSE_s_n (oAnswerYes, "yes", "@"),
881 ARGPARSE_s_n (oAnswerNo, "no", "@"),
882 ARGPARSE_s_i (oStatusFD, "status-fd", "@"),
883 ARGPARSE_s_s (oStatusFile, "status-file", "@"),
884 ARGPARSE_s_i (oAttributeFD, "attribute-fd", "@"),
885 ARGPARSE_s_s (oAttributeFile, "attribute-file", "@"),
886 ARGPARSE_s_i (oCommandFD, "command-fd", "@"),
887 ARGPARSE_s_s (oCommandFile, "command-file", "@"),
888 ARGPARSE_o_s (oPassphrase, "passphrase", "@"),
889 ARGPARSE_s_i (oPassphraseFD, "passphrase-fd", "@"),
890 ARGPARSE_s_s (oPassphraseFile, "passphrase-file", "@"),
891 ARGPARSE_s_i (oPassphraseRepeat,"passphrase-repeat", "@"),
892 ARGPARSE_s_s (oPinentryMode, "pinentry-mode", "@"),
893 ARGPARSE_s_n (oForceSignKey, "force-sign-key", "@"),
895 ARGPARSE_header (NULL, N_("Other options")),
897 ARGPARSE_s_s (oRequestOrigin, "request-origin", "@"),
898 ARGPARSE_s_s (oDisplay, "display", "@"),
899 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
900 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
901 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
902 ARGPARSE_s_s (oLCmessages, "lc-messages","@"),
903 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
904 ARGPARSE_s_s (oChUid, "chuid", "@"),
905 ARGPARSE_s_n (oNoAutostart, "no-autostart", "@"),
906 ARGPARSE_s_n (oUseKeyboxd, "use-keyboxd", "@"),
907 /* Options which can be used in special circumstances. They are not
908 * published and we hope they are never required. */
909 ARGPARSE_s_n (oUseOnlyOpenPGPCard, "use-only-openpgp-card", "@"),
910 /* Esoteric compatibility options. */
911 ARGPARSE_s_n (oRFC2440Text, "rfc2440-text", "@"),
912 ARGPARSE_s_n (oNoRFC2440Text, "no-rfc2440-text", "@"),
914 ARGPARSE_header (NULL, ""), /* Stop the header group. */
916 /* Aliases. I constantly mistype these, and assume other people do
918 ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-prefs", "@"),
919 ARGPARSE_s_s (oPersonalAEADPreferences, "personal-aead-prefs", "@"),
920 ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-prefs", "@"),
921 ARGPARSE_s_s (oPersonalCompressPreferences, "personal-compress-prefs", "@"),
923 /* These two are aliases to help users of the PGP command line
924 product use gpg with minimal pain. Many commands are common
925 already as they seem to have borrowed commands from us. Now I'm
926 returning the favor. */
927 ARGPARSE_s_s (oLocalUser, "sign-with", "@"),
928 ARGPARSE_s_s (oRecipient, "user", "@"),
931 /* Dummy options with warnings. */
932 ARGPARSE_s_n (oUseAgent, "use-agent", "@"),
933 ARGPARSE_s_n (oNoUseAgent, "no-use-agent", "@"),
934 ARGPARSE_s_s (oGpgAgentInfo, "gpg-agent-info", "@"),
935 ARGPARSE_s_s (oReaderPort, "reader-port", "@"),
936 ARGPARSE_s_s (octapiDriver, "ctapi-driver", "@"),
937 ARGPARSE_s_s (opcscDriver, "pcsc-driver", "@"),
938 ARGPARSE_s_n (oDisableCCID, "disable-ccid", "@"),
939 ARGPARSE_s_n (oHonorHttpProxy, "honor-http-proxy", "@"),
940 ARGPARSE_s_s (oTOFUDBFormat, "tofu-db-format", "@"),
943 ARGPARSE_ignore (oStrict, "strict"),
944 ARGPARSE_ignore (oNoStrict, "no-strict"),
945 ARGPARSE_ignore (oLoadExtension, "load-extension"), /* from 1.4. */
947 ARGPARSE_s_n (oNoop, "sk-comments", "@"),
948 ARGPARSE_s_n (oNoop, "no-sk-comments", "@"),
949 ARGPARSE_s_n (oNoop, "compress-keys", "@"),
950 ARGPARSE_s_n (oNoop, "compress-sigs", "@"),
951 ARGPARSE_s_n (oNoop, "force-v3-sigs", "@"),
952 ARGPARSE_s_n (oNoop, "no-force-v3-sigs", "@"),
953 ARGPARSE_s_n (oNoop, "force-v4-certs", "@"),
954 ARGPARSE_s_n (oNoop, "no-force-v4-certs", "@"),
955 ARGPARSE_s_n (oNoop, "no-mdc-warning", "@"),
956 ARGPARSE_s_n (oNoop, "force-mdc", "@"),
957 ARGPARSE_s_n (oNoop, "no-force-mdc", "@"),
958 ARGPARSE_s_n (oNoop, "disable-mdc", "@"),
959 ARGPARSE_s_n (oNoop, "no-disable-mdc", "@"),
960 ARGPARSE_s_n (oNoop, "allow-multisig-verification", "@"),
961 ARGPARSE_s_n (oNoop, "allow-multiple-messages", "@"),
962 ARGPARSE_s_n (oNoop, "no-allow-multiple-messages", "@"),
965 ARGPARSE_group (302, N_(
966 "@\n(See the man page for a complete listing of all commands and options)\n"
969 ARGPARSE_group (303, N_("@\nExamples:\n\n"
970 " -se -r Bob [file] sign and encrypt for user Bob\n"
971 " --clear-sign [file] make a clear text signature\n"
972 " --detach-sign [file] make a detached signature\n"
973 " --list-keys [names] show keys\n"
974 " --fingerprint [names] show fingerprints\n")),
981 /* The list of supported debug flags. */
982 static struct debug_flags_s debug_flags [] =
984 { DBG_PACKET_VALUE , "packet" },
985 { DBG_MPI_VALUE , "mpi" },
986 { DBG_CRYPTO_VALUE , "crypto" },
987 { DBG_FILTER_VALUE , "filter" },
988 { DBG_IOBUF_VALUE , "iobuf" },
989 { DBG_MEMORY_VALUE , "memory" },
990 { DBG_CACHE_VALUE , "cache" },
991 { DBG_MEMSTAT_VALUE, "memstat" },
992 { DBG_TRUST_VALUE , "trust" },
993 { DBG_HASHING_VALUE, "hashing" },
994 { DBG_IPC_VALUE , "ipc" },
995 { DBG_CLOCK_VALUE , "clock" },
996 { DBG_LOOKUP_VALUE , "lookup" },
997 { DBG_EXTPROG_VALUE, "extprog" },
1002 #ifdef ENABLE_SELINUX_HACKS
1003 #define ALWAYS_ADD_KEYRINGS 1
1005 #define ALWAYS_ADD_KEYRINGS 0
1008 /* The list of the default AKL methods. */
1009 #define DEFAULT_AKL_LIST "local,wkd"
1012 int g10_errors_seen = 0;
1014 static int utf8_strings =
1015 #ifdef HAVE_W32_SYSTEM
1021 static int maybe_setuid = 1;
1022 static unsigned int opt_set_iobuf_size;
1023 static unsigned int opt_set_iobuf_size_used;
1025 static char *build_list( const char *text, char letter,
1026 const char *(*mapf)(int), int (*chkf)(int) );
1027 static void set_cmd( enum cmd_and_opt_values *ret_cmd,
1028 enum cmd_and_opt_values new_cmd );
1029 static void print_mds( const char *fname, int algo );
1030 static void add_notation_data( const char *string, int which );
1031 static void add_policy_url( const char *string, int which );
1032 static void add_keyserver_url( const char *string, int which );
1033 static void emergency_cleanup (void);
1034 static void read_sessionkey_from_fd (int fd);
1036 /* NPth wrapper function definitions. */
1037 ASSUAN_SYSTEM_NPTH_IMPL;
1041 make_libversion (const char *libname, const char *(*getfnc)(const char*))
1048 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
1052 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
1053 strcpy (stpcpy (stpcpy (result, libname), " "), s);
1059 build_list_pk_test_algo (int algo)
1061 /* Show only one "RSA" string. If RSA_E or RSA_S is available RSA
1062 is also available. */
1063 if (algo == PUBKEY_ALGO_RSA_E
1064 || algo == PUBKEY_ALGO_RSA_S)
1065 return GPG_ERR_DIGEST_ALGO;
1067 return openpgp_pk_test_algo (algo);
1071 build_list_pk_algo_name (int algo)
1073 return openpgp_pk_algo_name (algo);
1077 build_list_cipher_test_algo (int algo)
1079 return openpgp_cipher_test_algo (algo);
1083 build_list_cipher_algo_name (int algo)
1085 return openpgp_cipher_algo_name (algo);
1089 build_list_aead_test_algo (int algo)
1091 return openpgp_aead_test_algo (algo);
1095 build_list_aead_algo_name (int algo)
1097 return openpgp_aead_algo_name (algo);
1101 build_list_md_test_algo (int algo)
1103 /* By default we do not accept MD5 based signatures. To avoid
1104 confusion we do not announce support for it either. */
1105 if (algo == DIGEST_ALGO_MD5)
1106 return GPG_ERR_DIGEST_ALGO;
1108 return openpgp_md_test_algo (algo);
1112 build_list_md_algo_name (int algo)
1114 return openpgp_md_algo_name (algo);
1119 my_strusage( int level )
1121 static char *digests, *pubkeys, *ciphers, *zips, *aeads, *ver_gcry;
1125 case 9: p = "GPL-3.0-or-later"; break;
1126 case 11: p = "@GPG@ (@GNUPG@)";
1128 case 13: p = VERSION; break;
1129 case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break;
1131 case 17: p = PRINTABLE_OS_NAME; break;
1132 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
1136 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
1140 #ifdef IS_DEVELOPMENT_VERSION
1142 p="NOTE: THIS IS A DEVELOPMENT VERSION!";
1145 p="It is only intended for test purposes and should NOT be";
1148 p="used in a production environment or with production keys!";
1154 _("Usage: @GPG@ [options] [files] (-h for help)");
1157 _("Syntax: @GPG@ [options] [files]\n"
1158 "Sign, check, encrypt or decrypt\n"
1159 "Default operation depends on the input data\n");
1162 case 31: p = "\nHome: "; break;
1164 case 32: p = gnupg_homedir (); break;
1165 #else /* __riscos__ */
1166 case 32: p = make_filename(gnupg_homedir (), NULL); break;
1167 #endif /* __riscos__ */
1168 case 33: p = _("\nSupported algorithms:\n"); break;
1171 pubkeys = build_list (_("Pubkey: "), 1,
1172 build_list_pk_algo_name,
1173 build_list_pk_test_algo );
1178 ciphers = build_list(_("Cipher: "), 'S',
1179 build_list_cipher_algo_name,
1180 build_list_cipher_test_algo );
1185 aeads = build_list ("AEAD: ", 'A',
1186 build_list_aead_algo_name,
1187 build_list_aead_test_algo);
1192 digests = build_list(_("Hash: "), 'H',
1193 build_list_md_algo_name,
1194 build_list_md_test_algo );
1199 zips = build_list(_("Compression: "),'Z',
1200 compress_algo_to_string,
1201 check_compress_algo);
1206 p = "1"; /* <-- Enable globbing under Windows (see init.c) */
1216 build_list (const char *text, char letter,
1217 const char * (*mapf)(int), int (*chkf)(int))
1227 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
1229 indent = utf8_charcount (text, -1);
1231 init_membuf (&mb, 512);
1233 limit = (letter == 'A')? 4 : 110;
1234 for (i=0; i <= limit; i++ )
1236 if (!chkf (i) && (s = mapf (i)))
1238 if (mb.len - len > 60)
1240 put_membuf_str (&mb, ",\n");
1242 for (j=0; j < indent; j++)
1243 put_membuf_str (&mb, " ");
1246 put_membuf_str (&mb, ", ");
1248 put_membuf_str (&mb, text);
1250 put_membuf_str (&mb, s);
1251 if (opt.verbose && letter)
1255 snprintf (num, sizeof num, " (%d)", i);
1257 snprintf (num, sizeof num, " (%c%d)", letter, i);
1258 put_membuf_str (&mb, num);
1263 put_membuf_str (&mb, "\n");
1264 put_membuf (&mb, "", 1);
1266 string = get_membuf (&mb, NULL);
1267 return xrealloc (string, strlen (string)+1);
1272 wrong_args( const char *text)
1274 es_fprintf (es_stderr, _("usage: %s [options] %s\n"), GPG_NAME, text);
1275 log_inc_errorcount ();
1281 make_username( const char *string )
1285 p = xstrdup(string);
1287 p = native_to_utf8( string );
1293 set_opt_session_env (const char *name, const char *value)
1297 err = session_env_setenv (opt.session_env, name, value);
1299 log_fatal ("error setting session environment: %s\n",
1300 gpg_strerror (err));
1304 /* Setup the debugging. With a LEVEL of NULL only the active debug
1305 flags are propagated to the subsystems. With LEVEL set, a specific
1306 set of debug flags is set; thus overriding all flags already
1309 set_debug (const char *level)
1311 int numok = (level && digitp (level));
1312 int numlvl = numok? atoi (level) : 0;
1316 else if (!strcmp (level, "none") || (numok && numlvl < 1))
1318 else if (!strcmp (level, "basic") || (numok && numlvl <= 2))
1319 opt.debug = DBG_MEMSTAT_VALUE;
1320 else if (!strcmp (level, "advanced") || (numok && numlvl <= 5))
1321 opt.debug = DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE;
1322 else if (!strcmp (level, "expert") || (numok && numlvl <= 8))
1323 opt.debug = (DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE
1324 |DBG_CACHE_VALUE|DBG_LOOKUP|DBG_FILTER_VALUE|DBG_PACKET_VALUE);
1325 else if (!strcmp (level, "guru") || numok)
1328 /* Unless the "guru" string has been used we don't want to allow
1329 hashing debugging. The rationale is that people tend to
1330 select the highest debug value and would then clutter their
1331 disk with debug files which may reveal confidential data. */
1333 opt.debug &= ~(DBG_HASHING_VALUE);
1337 log_error (_("invalid debug-level '%s' given\n"), level);
1341 if ((opt.debug & DBG_MEMORY_VALUE))
1342 memory_debug_mode = 1;
1343 if ((opt.debug & DBG_MEMSTAT_VALUE))
1344 memory_stat_debug_mode = 1;
1346 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
1348 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
1349 if ((opt.debug & DBG_IOBUF_VALUE))
1350 iobuf_debug_mode = 1;
1351 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1354 parse_debug_flag (NULL, &opt.debug, debug_flags);
1356 if (opt_set_iobuf_size || opt_set_iobuf_size_used)
1357 log_debug ("iobuf buffer size is %uk\n",
1358 iobuf_set_buffer_size (opt_set_iobuf_size));
1362 /* We set the screen dimensions for UI purposes. Do not allow screens
1363 smaller than 80x24 for the sake of simplicity. */
1365 set_screen_dimensions(void)
1367 #ifndef HAVE_W32_SYSTEM
1370 str=getenv("COLUMNS");
1372 opt.screen_columns=atoi(str);
1374 str=getenv("LINES");
1376 opt.screen_lines=atoi(str);
1379 if(opt.screen_columns<80 || opt.screen_columns>255)
1380 opt.screen_columns=80;
1382 if(opt.screen_lines<24 || opt.screen_lines>255)
1383 opt.screen_lines=24;
1387 /* Helper to open a file FNAME either for reading or writing to be
1388 used with --status-file etc functions. Not generally useful but it
1389 avoids the riscos specific functions and well some Windows people
1390 might like it too. Prints an error message and returns -1 on
1391 error. On success the file descriptor is returned. */
1393 open_info_file (const char *fname, int for_write, int binary)
1396 return riscos_fdopenfile (fname, for_write);
1397 #elif defined (ENABLE_SELINUX_HACKS)
1398 /* We can't allow these even when testing for a secured filename
1399 because files to be secured might not yet been secured. This is
1400 similar to the option file but in that case it is unlikely that
1401 sensitive information may be retrieved by means of error
1411 binary = MY_O_BINARY;
1413 /* if (is_secured_filename (fname)) */
1416 /* gpg_err_set_errno (EPERM); */
1423 fd = gnupg_open (fname, O_CREAT | O_TRUNC | O_WRONLY | binary,
1424 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
1426 fd = gnupg_open (fname, O_RDONLY | binary, 0);
1428 while (fd == -1 && errno == EINTR);
1431 log_error ( for_write? _("can't create '%s': %s\n")
1432 : _("can't open '%s': %s\n"), fname, strerror(errno));
1439 set_cmd( enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd )
1441 enum cmd_and_opt_values cmd = *ret_cmd;
1443 if( !cmd || cmd == new_cmd )
1445 else if( cmd == aSign && new_cmd == aEncr )
1447 else if( cmd == aEncr && new_cmd == aSign )
1449 else if( cmd == aSign && new_cmd == aSym )
1451 else if( cmd == aSym && new_cmd == aSign )
1453 else if( cmd == aSym && new_cmd == aEncr )
1455 else if( cmd == aEncr && new_cmd == aSym )
1457 else if (cmd == aSignEncr && new_cmd == aSym)
1459 else if (cmd == aSignSym && new_cmd == aEncr)
1461 else if (cmd == aEncrSym && new_cmd == aSign)
1463 else if( ( cmd == aSign && new_cmd == aClearsign )
1464 || ( cmd == aClearsign && new_cmd == aSign ) )
1467 log_error(_("conflicting commands\n"));
1476 add_group(char *string)
1479 struct groupitem *item;
1481 /* Break off the group name */
1482 name=strsep(&string,"=");
1485 log_error(_("no = sign found in group definition '%s'\n"),name);
1489 trim_trailing_ws(name,strlen(name));
1491 /* Does this group already exist? */
1492 for(item=opt.grouplist;item;item=item->next)
1493 if(strcasecmp(item->name,name)==0)
1498 item=xmalloc(sizeof(struct groupitem));
1500 item->next=opt.grouplist;
1505 /* Break apart the values */
1506 while ((value= strsep(&string," \t")))
1509 add_to_strlist2(&item->values,value,utf8_strings);
1515 rm_group(char *name)
1517 struct groupitem *item,*last=NULL;
1519 trim_trailing_ws(name,strlen(name));
1521 for(item=opt.grouplist;item;last=item,item=item->next)
1523 if(strcasecmp(item->name,name)==0)
1526 last->next=item->next;
1528 opt.grouplist=item->next;
1530 free_strlist(item->values);
1538 /* We need to check three things.
1540 0) The homedir. It must be x00, a directory, and owned by the
1543 1) The options/gpg.conf file. Okay unless it or its containing
1544 directory is group or other writable or not owned by us. Disable
1547 2) Extensions. Same as #1.
1549 Returns true if the item is unsafe. */
1551 check_permissions (const char *path, int item)
1553 #if defined(HAVE_STAT) && !defined(HAVE_DOSISH_SYSTEM)
1554 static int homedir_cache=-1;
1556 struct stat statbuf,dirbuf;
1557 int homedir=0,ret=0,checkonly=0;
1558 int perm=0,own=0,enc_dir_perm=0,enc_dir_own=0;
1560 if(opt.no_perm_warn)
1563 log_assert(item==0 || item==1 || item==2);
1565 /* extensions may attach a path */
1566 if(item==2 && path[0]!=DIRSEP_C)
1568 if(strchr(path,DIRSEP_C))
1569 tmppath=make_filename(path,NULL);
1571 tmppath=make_filename(gnupg_libdir (),path,NULL);
1574 tmppath=xstrdup(path);
1576 /* If the item is located in the homedir, but isn't the homedir,
1577 don't continue if we already checked the homedir itself. This is
1578 to avoid user confusion with an extra options file warning which
1579 could be rectified if the homedir itself had proper
1581 if(item!=0 && homedir_cache>-1
1582 && !ascii_strncasecmp (gnupg_homedir (), tmppath,
1583 strlen (gnupg_homedir ())))
1589 /* It's okay if the file or directory doesn't exist */
1590 if (gnupg_stat (tmppath,&statbuf))
1596 /* Now check the enclosing directory. Theoretically, we could walk
1597 this test up to the root directory /, but for the sake of sanity,
1598 I'm stopping at one level down. */
1599 dir=make_dirname(tmppath);
1601 if (gnupg_stat (dir,&dirbuf) || !S_ISDIR (dirbuf.st_mode))
1611 /* Assume failure */
1616 /* The homedir must be x00, a directory, and owned by the user. */
1618 if(S_ISDIR(statbuf.st_mode))
1620 if(statbuf.st_uid==getuid())
1622 if((statbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1633 else if(item==1 || item==2)
1635 /* The options or extension file. Okay unless it or its
1636 containing directory is group or other writable or not owned
1639 if(S_ISREG(statbuf.st_mode))
1641 if(statbuf.st_uid==getuid() || statbuf.st_uid==0)
1643 if((statbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1645 /* it's not writable, so make sure the enclosing
1646 directory is also not writable */
1647 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1649 if((dirbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1659 /* it's writable, so the enclosing directory had
1660 better not let people get to it. */
1661 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1663 if((dirbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1666 perm=enc_dir_perm=1; /* unclear which one to fix! */
1684 log_info(_("WARNING: unsafe ownership on"
1685 " homedir '%s'\n"),tmppath);
1687 log_info(_("WARNING: unsafe ownership on"
1688 " configuration file '%s'\n"),tmppath);
1690 log_info(_("WARNING: unsafe ownership on"
1691 " extension '%s'\n"),tmppath);
1696 log_info(_("WARNING: unsafe permissions on"
1697 " homedir '%s'\n"),tmppath);
1699 log_info(_("WARNING: unsafe permissions on"
1700 " configuration file '%s'\n"),tmppath);
1702 log_info(_("WARNING: unsafe permissions on"
1703 " extension '%s'\n"),tmppath);
1708 log_info(_("WARNING: unsafe enclosing directory ownership on"
1709 " homedir '%s'\n"),tmppath);
1711 log_info(_("WARNING: unsafe enclosing directory ownership on"
1712 " configuration file '%s'\n"),tmppath);
1714 log_info(_("WARNING: unsafe enclosing directory ownership on"
1715 " extension '%s'\n"),tmppath);
1720 log_info(_("WARNING: unsafe enclosing directory permissions on"
1721 " homedir '%s'\n"),tmppath);
1723 log_info(_("WARNING: unsafe enclosing directory permissions on"
1724 " configuration file '%s'\n"),tmppath);
1726 log_info(_("WARNING: unsafe enclosing directory permissions on"
1727 " extension '%s'\n"),tmppath);
1739 #else /*!(HAVE_STAT && !HAVE_DOSISH_SYSTEM)*/
1743 #endif /*!(HAVE_STAT && !HAVE_DOSISH_SYSTEM)*/
1747 /* Print the OpenPGP defined algo numbers. */
1749 print_algo_numbers(int (*checker)(int))
1768 print_algo_names(int (*checker)(int),const char *(*mapper)(int))
1780 es_printf ("%s",mapper(i));
1785 /* In the future, we can do all sorts of interesting configuration
1786 output here. For now, just give "group" as the Enigmail folks need
1787 it, and pubkey, cipher, hash, and compress as they may be useful
1790 list_config(char *items)
1792 int show_all = !items;
1795 struct groupitem *giter;
1798 if(!opt.with_colons)
1801 while(show_all || (name=strsep(&items," ")))
1805 if(show_all || ascii_strcasecmp(name,"group")==0)
1807 for (giter = opt.grouplist; giter; giter = giter->next)
1811 es_fprintf (es_stdout, "cfg:group:");
1812 es_write_sanitized (es_stdout, giter->name, strlen(giter->name),
1814 es_putc (':', es_stdout);
1816 for(sl=giter->values; sl; sl=sl->next)
1818 es_write_sanitized (es_stdout, sl->d, strlen (sl->d),
1830 if(show_all || ascii_strcasecmp(name,"version")==0)
1832 es_printf("cfg:version:");
1833 es_write_sanitized (es_stdout, VERSION, strlen(VERSION), ":", NULL);
1838 if(show_all || ascii_strcasecmp(name,"pubkey")==0)
1840 es_printf ("cfg:pubkey:");
1841 print_algo_numbers (build_list_pk_test_algo);
1846 if(show_all || ascii_strcasecmp(name,"pubkeyname")==0)
1848 es_printf ("cfg:pubkeyname:");
1849 print_algo_names (build_list_pk_test_algo,
1850 build_list_pk_algo_name);
1855 if(show_all || ascii_strcasecmp(name,"cipher")==0)
1857 es_printf ("cfg:cipher:");
1858 print_algo_numbers (build_list_cipher_test_algo);
1863 if (show_all || !ascii_strcasecmp (name,"ciphername"))
1865 es_printf ("cfg:ciphername:");
1866 print_algo_names (build_list_cipher_test_algo,
1867 build_list_cipher_algo_name);
1873 || ascii_strcasecmp(name,"digest")==0
1874 || ascii_strcasecmp(name,"hash")==0)
1876 es_printf ("cfg:digest:");
1877 print_algo_numbers (build_list_md_test_algo);
1883 || !ascii_strcasecmp(name,"digestname")
1884 || !ascii_strcasecmp(name,"hashname"))
1886 es_printf ("cfg:digestname:");
1887 print_algo_names (build_list_md_test_algo,
1888 build_list_md_algo_name);
1893 if(show_all || ascii_strcasecmp(name,"compress")==0)
1895 es_printf ("cfg:compress:");
1896 print_algo_numbers(check_compress_algo);
1901 if(show_all || ascii_strcasecmp (name, "compressname") == 0)
1903 es_printf ("cfg:compressname:");
1904 print_algo_names (check_compress_algo,
1905 compress_algo_to_string);
1910 if (show_all || !ascii_strcasecmp(name,"ccid-reader-id"))
1912 /* We ignore this for GnuPG 1.4 backward compatibility. */
1916 if (show_all || !ascii_strcasecmp (name,"curve"))
1918 es_printf ("cfg:curve:");
1919 for (iter=0, first=1; (s = openpgp_enum_curves (&iter)); first=0)
1920 es_printf ("%s%s", first?"":";", s);
1925 /* Curve OIDs are rarely useful and thus only printed if requested. */
1926 if (name && !ascii_strcasecmp (name,"curveoid"))
1928 es_printf ("cfg:curveoid:");
1929 for (iter=0, first=1; (s = openpgp_enum_curves (&iter)); first = 0)
1931 s = openpgp_curve_to_oid (s, NULL, NULL);
1932 es_printf ("%s%s", first?"":";", s? s:"[?]");
1942 log_error(_("unknown configuration item '%s'\n"),name);
1947 /* List default values for use by gpgconf. */
1951 es_printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
1952 es_printf ("compliance:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT, "gnupg");
1954 /* The next one is an info only item and should match the macros at
1955 the top of keygen.c */
1956 es_printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1957 get_default_pubkey_algo ());
1958 /* This info only mode tells whether the we are running in de-vs
1959 * compliance mode. This does not test all parameters but the basic
1960 * conditions like a proper RNG and Libgcrypt. AS of now we always
1961 * return 0 because this version of gnupg has not yet received an
1963 es_printf ("compliance_de_vs:%lu:%d:\n", GC_OPT_FLAG_DEFAULT,
1964 0 /*gnupg_rng_is_compliant (CO_DE_VS)*/);
1966 es_printf ("use_keyboxd:%lu:%d:\n", GC_OPT_FLAG_DEFAULT, opt.use_keyboxd);
1972 parse_subpacket_list(char *list)
1975 byte subpackets[128],i;
1980 /* No arguments means all subpackets */
1981 memset(subpackets+1,1,sizeof(subpackets)-1);
1986 memset(subpackets,0,sizeof(subpackets));
1988 /* Merge with earlier copy */
1989 if(opt.show_subpackets)
1993 for(in=opt.show_subpackets;*in;in++)
1995 if(*in>127 || *in<1)
1998 if(!subpackets[*in])
2004 while((tok=strsep(&list," ,")))
2019 xfree(opt.show_subpackets);
2020 opt.show_subpackets=xmalloc(count+1);
2021 opt.show_subpackets[count--]=0;
2023 for(i=1;i<128 && count>=0;i++)
2025 opt.show_subpackets[count--]=i;
2032 parse_list_options(char *str)
2034 char *subpackets=""; /* something that isn't NULL */
2035 struct parse_options lopts[]=
2037 {"show-photos",LIST_SHOW_PHOTOS,NULL,
2038 N_("display photo IDs during key listings")},
2039 {"show-usage",LIST_SHOW_USAGE,NULL,
2040 N_("show key usage information during key listings")},
2041 {"show-policy-urls",LIST_SHOW_POLICY_URLS,NULL,
2042 N_("show policy URLs during signature listings")},
2043 {"show-notations",LIST_SHOW_NOTATIONS,NULL,
2044 N_("show all notations during signature listings")},
2045 {"show-std-notations",LIST_SHOW_STD_NOTATIONS,NULL,
2046 N_("show IETF standard notations during signature listings")},
2047 {"show-standard-notations",LIST_SHOW_STD_NOTATIONS,NULL,
2049 {"show-user-notations",LIST_SHOW_USER_NOTATIONS,NULL,
2050 N_("show user-supplied notations during signature listings")},
2051 {"show-keyserver-urls",LIST_SHOW_KEYSERVER_URLS,NULL,
2052 N_("show preferred keyserver URLs during signature listings")},
2053 {"show-uid-validity",LIST_SHOW_UID_VALIDITY,NULL,
2054 N_("show user ID validity during key listings")},
2055 {"show-unusable-uids",LIST_SHOW_UNUSABLE_UIDS,NULL,
2056 N_("show revoked and expired user IDs in key listings")},
2057 {"show-unusable-subkeys",LIST_SHOW_UNUSABLE_SUBKEYS,NULL,
2058 N_("show revoked and expired subkeys in key listings")},
2059 {"show-keyring",LIST_SHOW_KEYRING,NULL,
2060 N_("show the keyring name in key listings")},
2061 {"show-sig-expire",LIST_SHOW_SIG_EXPIRE,NULL,
2062 N_("show expiration dates during signature listings")},
2063 {"show-sig-subpackets",LIST_SHOW_SIG_SUBPACKETS,NULL,
2065 {"show-only-fpr-mbox",LIST_SHOW_ONLY_FPR_MBOX, NULL,
2067 {"sort-sigs", LIST_SORT_SIGS, NULL,
2072 /* C99 allows for non-constant initializers, but we'd like to
2073 compile everywhere, so fill in the show-sig-subpackets argument
2074 here. Note that if the parse_options array changes, we'll have
2075 to change the subscript here. */
2076 lopts[13].value=&subpackets;
2078 if(parse_options(str,&opt.list_options,lopts,1))
2080 if(opt.list_options&LIST_SHOW_SIG_SUBPACKETS)
2082 /* Unset so users can pass multiple lists in. */
2083 opt.list_options&=~LIST_SHOW_SIG_SUBPACKETS;
2084 if(!parse_subpacket_list(subpackets))
2087 else if(subpackets==NULL && opt.show_subpackets)
2089 /* User did 'no-show-subpackets' */
2090 xfree(opt.show_subpackets);
2091 opt.show_subpackets=NULL;
2101 /* Collapses argc/argv into a single string that must be freed */
2103 collapse_args(int argc,char *argv[])
2106 int i,first=1,len=0;
2110 len+=strlen(argv[i])+2;
2111 str=xrealloc(str,len);
2120 strcat(str,argv[i]);
2127 #ifndef NO_TRUST_MODELS
2129 parse_trust_model(const char *model)
2131 if(ascii_strcasecmp(model,"pgp")==0)
2132 opt.trust_model=TM_PGP;
2133 else if(ascii_strcasecmp(model,"classic")==0)
2134 opt.trust_model=TM_CLASSIC;
2135 else if(ascii_strcasecmp(model,"always")==0)
2136 opt.trust_model=TM_ALWAYS;
2137 else if(ascii_strcasecmp(model,"direct")==0)
2138 opt.trust_model=TM_DIRECT;
2140 else if(ascii_strcasecmp(model,"tofu")==0)
2141 opt.trust_model=TM_TOFU;
2142 else if(ascii_strcasecmp(model,"tofu+pgp")==0)
2143 opt.trust_model=TM_TOFU_PGP;
2145 else if(ascii_strcasecmp(model,"auto")==0)
2146 opt.trust_model=TM_AUTO;
2148 log_error("unknown trust model '%s'\n",model);
2150 #endif /*NO_TRUST_MODELS*/
2154 parse_tofu_policy (const char *policystr)
2157 struct { const char *keyword; int policy; } list[] = {
2158 { "auto", TOFU_POLICY_AUTO },
2159 { "good", TOFU_POLICY_GOOD },
2160 { "unknown", TOFU_POLICY_UNKNOWN },
2161 { "bad", TOFU_POLICY_BAD },
2162 { "ask", TOFU_POLICY_ASK }
2166 if (!ascii_strcasecmp (policystr, "help"))
2168 log_info (_("valid values for option '%s':\n"), "--tofu-policy");
2169 for (i=0; i < DIM (list); i++)
2170 log_info (" %s\n", list[i].keyword);
2174 for (i=0; i < DIM (list); i++)
2175 if (!ascii_strcasecmp (policystr, list[i].keyword))
2176 return list[i].policy;
2179 log_error (_("unknown TOFU policy '%s'\n"), policystr);
2181 log_info (_("(use \"help\" to list choices)\n"));
2186 static struct gnupg_compliance_option compliance_options[] =
2188 { "gnupg", oGnuPG },
2189 { "openpgp", oOpenPGP },
2190 { "rfc4880bis", oRFC4880bis },
2191 { "rfc4880", oRFC4880 },
2192 { "rfc2440", oRFC2440 },
2200 /* Helper to set compliance related options. This is a separate
2201 * function so that it can also be used by the --compliance option
2204 set_compliance_option (enum cmd_and_opt_values option)
2206 opt.flags.rfc4880bis = 0; /* Clear because it is initially set. */
2211 opt.flags.rfc4880bis = 1;
2212 opt.compliance = CO_RFC4880;
2214 opt.flags.require_cross_cert = 1;
2215 opt.rfc2440_text = 0;
2216 opt.allow_non_selfsigned_uid = 1;
2217 opt.allow_freeform_uid = 1;
2218 opt.escape_from = 1;
2219 opt.not_dash_escaped = 0;
2220 opt.def_cipher_algo = 0;
2221 opt.def_aead_algo = 0;
2222 opt.def_digest_algo = 0;
2223 opt.cert_digest_algo = 0;
2224 opt.compress_algo = -1;
2225 opt.s2k_mode = 3; /* iterated+salted */
2226 opt.s2k_digest_algo = DIGEST_ALGO_SHA256;
2227 opt.s2k_cipher_algo = CIPHER_ALGO_AES256;
2231 /* This is effectively the same as RFC2440, but with
2232 "--enable-dsa2 --no-rfc2440-text --escape-from-lines
2233 --require-cross-certification". */
2234 opt.compliance = CO_RFC4880;
2236 opt.flags.require_cross_cert = 1;
2237 opt.rfc2440_text = 0;
2238 opt.allow_non_selfsigned_uid = 1;
2239 opt.allow_freeform_uid = 1;
2240 opt.escape_from = 1;
2241 opt.not_dash_escaped = 0;
2242 opt.def_cipher_algo = 0;
2243 opt.def_aead_algo = 0;
2244 opt.def_digest_algo = 0;
2245 opt.cert_digest_algo = 0;
2246 opt.compress_algo = -1;
2247 opt.s2k_mode = 3; /* iterated+salted */
2248 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2249 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2250 opt.flags.allow_old_cipher_algos = 1;
2253 opt.compliance = CO_RFC2440;
2255 opt.rfc2440_text = 1;
2256 opt.allow_non_selfsigned_uid = 1;
2257 opt.allow_freeform_uid = 1;
2258 opt.escape_from = 0;
2259 opt.not_dash_escaped = 0;
2260 opt.def_cipher_algo = 0;
2261 opt.def_aead_algo = 0;
2262 opt.def_digest_algo = 0;
2263 opt.cert_digest_algo = 0;
2264 opt.compress_algo = -1;
2265 opt.s2k_mode = 3; /* iterated+salted */
2266 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2267 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2268 opt.flags.allow_old_cipher_algos = 1;
2270 case oPGP7: opt.compliance = CO_PGP7; break;
2271 case oPGP8: opt.compliance = CO_PGP8; break;
2273 opt.compliance = CO_GNUPG;
2274 opt.flags.rfc4880bis = 1;
2278 set_compliance_option (oOpenPGP);
2279 opt.compliance = CO_DE_VS;
2280 opt.def_aead_algo = 0;
2281 /* We divert here from the backward compatible rfc4880 algos. */
2282 opt.s2k_digest_algo = DIGEST_ALGO_SHA256;
2283 opt.s2k_cipher_algo = CIPHER_ALGO_AES256;
2296 /* This function called to initialized a new control object. It is
2297 assumed that this object has been zeroed out before calling this
2300 gpg_init_default_ctrl (ctrl_t ctrl)
2302 ctrl->magic = SERVER_CONTROL_MAGIC;
2306 /* This function is called to deinitialize a control object. It is
2309 gpg_deinit_default_ctrl (ctrl_t ctrl)
2312 tofu_closedbs (ctrl);
2314 gpg_dirmngr_deinit_session_data (ctrl);
2316 keydb_release (ctrl->cached_getkey_kdb);
2317 gpg_keyboxd_deinit_session_data (ctrl);
2318 xfree (ctrl->secret_keygrips);
2319 ctrl->secret_keygrips = NULL;
2324 main (int argc, char **argv)
2326 gpgrt_argparse_t pargs;
2335 strlist_t remusr = NULL;
2336 strlist_t locusr = NULL;
2337 strlist_t nrings = NULL;
2338 armor_filter_context_t *afx = NULL;
2339 int detached_sig = 0;
2340 char *last_configname = NULL;
2341 const char *configname = NULL; /* NULL or points to last_configname.
2342 * NULL also indicates that we are
2343 * processing options from the cmdline. */
2344 int debug_argparser = 0;
2345 int default_keyring = 1;
2348 char *logfile = NULL;
2349 int use_random_seed = 1;
2350 enum cmd_and_opt_values cmd = 0;
2351 const char *debug_level = NULL;
2352 #ifndef NO_TRUST_MODELS
2353 const char *trustdb_name = NULL;
2354 #endif /*!NO_TRUST_MODELS*/
2355 char *def_cipher_string = NULL;
2356 char *def_aead_string = NULL;
2357 char *def_digest_string = NULL;
2358 char *compress_algo_string = NULL;
2359 char *cert_digest_string = NULL;
2360 char *s2k_cipher_string = NULL;
2361 char *s2k_digest_string = NULL;
2362 char *pers_cipher_list = NULL;
2363 char *pers_aead_list = NULL;
2364 char *pers_digest_list = NULL;
2365 char *pers_compress_list = NULL;
2369 int ovrseskeyfd = -1;
2370 int fpr_maybe_cmd = 0; /* --fingerprint maybe a command. */
2371 int any_explicit_recipient = 0;
2372 int default_akl = 1;
2373 int require_secmem = 0;
2375 struct assuan_malloc_hooks malloc_hooks;
2378 static int print_dane_records;
2379 static int allow_large_chunks;
2380 static const char *homedirvalue;
2381 static const char *changeuser;
2386 #endif /* __riscos__ */
2388 /* Please note that we may running SUID(ROOT), so be very CAREFUL
2389 when adding any stuff between here and the call to
2390 secmem_init() somewhere after the option parsing. */
2391 early_system_init ();
2392 gnupg_reopen_std (GPG_NAME);
2394 gnupg_rl_initialize ();
2395 gpgrt_set_strusage (my_strusage);
2396 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
2397 log_set_prefix (GPG_NAME, GPGRT_LOG_WITH_PREFIX);
2399 /* Make sure that our subsystems are ready. */
2401 init_common_subsystems (&argc, &argv);
2403 /* Use our own logging handler for Libcgrypt. */
2404 setup_libgcrypt_logging ();
2406 /* Put random number into secure memory */
2407 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
2409 may_coredump = disable_core_dumps();
2411 gnupg_init_signals (0, emergency_cleanup);
2413 dotlock_create (NULL, 0); /* Register lock file cleanup. */
2415 /* Tell the compliance module who we are. */
2416 gnupg_initialize_compliance (GNUPG_MODULE_NAME_GPG);
2419 opt.session_env = session_env_new ();
2420 if (!opt.session_env)
2421 log_fatal ("error allocating session environment block: %s\n",
2424 opt.command_fd = -1; /* no command fd */
2425 opt.compress_level = -1; /* defaults to standard compress level */
2426 opt.bz2_compress_level = -1; /* defaults to standard compress level */
2427 /* note: if you change these lines, look at oOpenPGP */
2428 opt.def_cipher_algo = 0;
2429 opt.def_aead_algo = 0;
2430 opt.def_digest_algo = 0;
2431 opt.cert_digest_algo = 0;
2432 opt.compress_algo = -1; /* defaults to DEFAULT_COMPRESS_ALGO */
2433 opt.s2k_mode = 3; /* iterated+salted */
2434 opt.s2k_count = 0; /* Auto-calibrate when needed. */
2435 opt.s2k_cipher_algo = DEFAULT_CIPHER_ALGO;
2436 opt.completes_needed = 1;
2437 opt.marginals_needed = 3;
2438 opt.max_cert_depth = 5;
2439 opt.escape_from = 1;
2440 opt.flags.require_cross_cert = 1;
2441 opt.import_options = (IMPORT_REPAIR_KEYS
2442 | IMPORT_COLLAPSE_UIDS
2443 | IMPORT_COLLAPSE_SUBKEYS);
2444 opt.export_options = EXPORT_ATTRIBUTES;
2445 opt.keyserver_options.import_options = (IMPORT_REPAIR_KEYS
2446 | IMPORT_REPAIR_PKS_SUBKEY_BUG
2447 | IMPORT_SELF_SIGS_ONLY
2448 | IMPORT_COLLAPSE_UIDS
2449 | IMPORT_COLLAPSE_SUBKEYS
2451 opt.keyserver_options.export_options = EXPORT_ATTRIBUTES;
2452 opt.keyserver_options.options = 0;
2453 opt.verify_options = (LIST_SHOW_UID_VALIDITY
2454 | VERIFY_SHOW_POLICY_URLS
2455 | VERIFY_SHOW_STD_NOTATIONS
2456 | VERIFY_SHOW_KEYSERVER_URLS);
2457 opt.list_options = (LIST_SHOW_UID_VALIDITY
2460 #ifdef NO_TRUST_MODELS
2461 opt.trust_model = TM_ALWAYS;
2463 opt.trust_model = TM_AUTO;
2465 opt.tofu_default_policy = TOFU_POLICY_AUTO;
2466 opt.mangle_dos_filenames = 0;
2467 opt.min_cert_level = 2;
2468 set_screen_dimensions ();
2469 opt.keyid_format = KF_NONE;
2470 opt.def_sig_expire = "0";
2471 opt.def_cert_expire = "0";
2472 opt.passphrase_repeat = 1;
2473 opt.emit_version = 0;
2474 opt.weak_digests = NULL;
2475 opt.compliance = CO_GNUPG;
2476 opt.flags.rfc4880bis = 1;
2478 /* Check special options given on the command line. */
2483 pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
2484 while (gpgrt_argparse (NULL, &pargs, opts))
2486 switch (pargs.r_opt)
2494 es_setvbuf (es_stdout, NULL, _IOLBF, 0);
2498 /* Set here here because the homedir would otherwise be
2499 * created before main option parsing starts. */
2500 opt.no_homedir_creation = 1;
2504 homedirvalue = pargs.r.ret_str;
2508 changeuser = pargs.r.ret_str;
2511 case oNoPermissionWarn:
2512 opt.no_perm_warn = 1;
2516 /* Reset the flags. */
2517 pargs.flags &= ~(ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
2519 #ifdef HAVE_DOSISH_SYSTEM
2520 /* FIXME: Do we still need this? No: gnupg_homedir calls
2521 * make_filename which changes the slashed anyway. IsDBCSLeadByte still
2522 * needed? See bug #561. */
2523 if ( strchr (gnupg_homedir (), '\\') ) {
2524 char *d, *buf = xmalloc (strlen (gnupg_homedir ())+1);
2526 for (d=buf, s = gnupg_homedir (); *s; s++)
2528 *d++ = *s == '\\'? '/': *s;
2529 #ifdef HAVE_W32_SYSTEM
2530 if (s[1] && IsDBCSLeadByte (*s))
2535 gnupg_set_homedir (buf);
2539 /* Initialize the secure memory. */
2540 if (!gcry_control (GCRYCTL_INIT_SECMEM, SECMEM_BUFFER_SIZE, 0))
2542 #if defined(HAVE_GETUID) && defined(HAVE_GETEUID)
2543 /* There should be no way to get to this spot while still carrying
2544 setuid privs. Just in case, bomb out if we are. */
2545 if ( getuid () != geteuid () )
2550 /* Okay, we are now working under our real uid */
2552 /* malloc hooks go here ... */
2553 malloc_hooks.malloc = gcry_malloc;
2554 malloc_hooks.realloc = gcry_realloc;
2555 malloc_hooks.free = gcry_free;
2556 assuan_set_malloc_hooks (&malloc_hooks);
2557 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
2558 setup_libassuan_logging (&opt.debug, NULL);
2560 /* Change UID and then set the homedir. */
2561 if (changeuser && gnupg_chuid (changeuser, 0))
2562 log_inc_errorcount (); /* Force later termination. */
2563 gnupg_set_homedir (homedirvalue);
2565 /* Set default options which require that malloc stuff is ready. */
2566 additional_weak_digest ("MD5");
2567 parse_auto_key_locate (DEFAULT_AKL_LIST);
2573 /* We are re-using the struct, thus the reset flag. We OR the
2574 * flags so that the internal intialized flag won't be cleared. */
2575 pargs.flags |= (ARGPARSE_FLAG_RESET
2576 | ARGPARSE_FLAG_KEEP
2578 | ARGPARSE_FLAG_USER
2579 | ARGPARSE_FLAG_USERVERS);
2581 /* By this point we have a homedir, and cannot change it. */
2582 check_permissions (gnupg_homedir (), 0);
2584 /* The configuraton directories for use by gpgrt_argparser. */
2585 gpgrt_set_confdir (GPGRT_CONFDIR_SYS, gnupg_sysconfdir ());
2586 gpgrt_set_confdir (GPGRT_CONFDIR_USER, gnupg_homedir ());
2588 while (gpgrt_argparser (&pargs, opts, GPG_NAME EXTSEP_S "conf" ))
2590 switch (pargs.r_opt)
2592 case ARGPARSE_CONFFILE:
2593 if (debug_argparser)
2594 log_info (_("reading options from '%s'\n"),
2595 pargs.r_type? pargs.r.ret_str: "[cmdline]");
2598 xfree (last_configname);
2599 last_configname = xstrdup (pargs.r.ret_str);
2600 configname = last_configname;
2601 if (is_secured_filename (configname))
2603 pargs.r_opt = ARGPARSE_PERMISSION_ERROR;
2604 pargs.err = ARGPARSE_PRINT_ERROR;
2606 else if (strncmp (configname, gnupg_sysconfdir (),
2607 strlen (gnupg_sysconfdir ())))
2609 /* This is not the global config file and thus we
2610 * need to check the permissions: If the file is
2611 * unsafe, then disable any external programs for
2612 * keyserver calls or photo IDs. Since the
2613 * external program to call is set in the options
2614 * file, a unsafe options file can lead to an
2615 * arbitrary program being run. */
2616 if (check_permissions (configname, 1))
2624 /* case oOptions: */
2625 /* case oNoOptions: */
2626 /* We will never see these options here because
2627 * gpgrt_argparse handles them for us. */
2631 case aListGcryptConfig:
2634 set_cmd (&cmd, pargs.r_opt);
2635 /* Do not register a keyring for these commands. */
2636 default_keyring = -1;
2649 #ifdef ENABLE_CARD_SUPPORT
2653 #endif /* ENABLE_CARD_SUPPORT*/
2656 case aLocateExtKeys:
2659 case aExportSecretSub:
2671 case aUpdateTrustDB:
2673 case aListTrustPath:
2678 case aQuickLSignKey:
2687 case aQuickSetExpire:
2688 case aQuickSetPrimaryUid:
2689 case aExportOwnerTrust:
2690 case aImportOwnerTrust:
2691 case aRebuildKeydbCaches:
2692 set_cmd (&cmd, pargs.r_opt);
2698 case aDeleteSecretKeys:
2699 case aDeleteSecretAndPublicKeys:
2702 set_cmd (&cmd, pargs.r_opt);
2707 set_cmd (&cmd, pargs.r_opt);
2708 opt.import_options |= IMPORT_SHOW;
2709 opt.import_options |= IMPORT_DRY_RUN;
2710 opt.import_options &= ~IMPORT_REPAIR_KEYS;
2711 opt.list_options |= LIST_SHOW_UNUSABLE_UIDS;
2712 opt.list_options |= LIST_SHOW_UNUSABLE_SUBKEYS;
2713 opt.list_options |= LIST_SHOW_NOTATIONS;
2714 opt.list_options |= LIST_SHOW_POLICY_URLS;
2717 case aDetachedSign: detached_sig = 1; set_cmd( &cmd, aSign ); break;
2719 case aDecryptFiles: multifile=1; /* fall through */
2720 case aDecrypt: set_cmd( &cmd, aDecrypt); break;
2722 case aEncrFiles: multifile=1; /* fall through */
2723 case aEncr: set_cmd( &cmd, aEncr); break;
2725 case aVerifyFiles: multifile=1; /* fall through */
2726 case aVerify: set_cmd( &cmd, aVerify); break;
2729 set_cmd (&cmd, pargs.r_opt);
2734 set_cmd (&cmd, pargs.r_opt);
2737 case oArmor: opt.armor = 1; opt.no_armor=0; break;
2738 case oOutput: opt.outfile = pargs.r.ret_str; break;
2740 case oMaxOutput: opt.max_output = pargs.r.ret_ulong; break;
2742 case oInputSizeHint:
2743 opt.input_size_hint = string_to_u64 (pargs.r.ret_str);
2747 opt.chunk_size = pargs.r.ret_int;
2750 case oQuiet: opt.quiet = 1; break;
2751 case oNoTTY: tty_no_terminal(1); break;
2752 case oDryRun: opt.dry_run = 1; break;
2753 case oInteractive: opt.interactive = 1; break;
2756 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2757 opt.list_options|=LIST_SHOW_UNUSABLE_UIDS;
2758 opt.list_options|=LIST_SHOW_UNUSABLE_SUBKEYS;
2766 case oUseAgent: /* Dummy. */
2770 obsolete_option (configname, pargs.lineno, "no-use-agent");
2773 obsolete_option (configname, pargs.lineno, "gpg-agent-info");
2777 opt.use_keyboxd = 1;
2781 obsolete_scdaemon_option (configname, pargs.lineno, "reader-port");
2784 obsolete_scdaemon_option (configname, pargs.lineno, "ctapi-driver");
2787 obsolete_scdaemon_option (configname, pargs.lineno, "pcsc-driver");
2790 obsolete_scdaemon_option (configname, pargs.lineno, "disable-ccid");
2792 case oHonorHttpProxy:
2793 obsolete_option (configname, pargs.lineno, "honor-http-proxy");
2796 case oAnswerYes: opt.answer_yes = 1; break;
2797 case oAnswerNo: opt.answer_no = 1; break;
2799 case oForceSignKey: opt.flags.force_sign_key = 1; break;
2801 case oKeyring: append_to_strlist( &nrings, pargs.r.ret_str); break;
2802 case oPrimaryKeyring:
2803 sl = append_to_strlist (&nrings, pargs.r.ret_str);
2804 sl->flags = KEYDB_RESOURCE_FLAG_PRIMARY;
2807 deprecated_warning(configname,pargs.lineno,"--show-keyring",
2808 "--list-options ","show-keyring");
2809 opt.list_options|=LIST_SHOW_KEYRING;
2813 if (parse_debug_flag (pargs.r.ret_str, &opt.debug, debug_flags))
2815 pargs.r_opt = ARGPARSE_INVALID_ARG;
2816 pargs.err = ARGPARSE_PRINT_ERROR;
2820 case oDebugAll: opt.debug = ~0; break;
2821 case oDebugLevel: debug_level = pargs.r.ret_str; break;
2823 case oDebugIOLBF: break; /* Already set in pre-parse step. */
2825 case oDebugSetIobufSize:
2826 opt_set_iobuf_size = pargs.r.ret_ulong;
2827 opt_set_iobuf_size_used = 1;
2830 case oDebugAllowLargeChunks:
2831 allow_large_chunks = 1;
2835 set_status_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
2838 set_status_fd ( open_info_file (pargs.r.ret_str, 1, 0) );
2841 set_attrib_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
2843 case oAttributeFile:
2844 set_attrib_fd ( open_info_file (pargs.r.ret_str, 1, 1) );
2847 log_set_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1));
2850 logfile = pargs.r.ret_str;
2853 case oWithFingerprint:
2854 opt.with_fingerprint = 1;
2857 case oWithSubkeyFingerprint:
2858 opt.with_subkey_fingerprint = 1;
2860 case oWithICAOSpelling:
2861 opt.with_icao_spelling = 1;
2869 opt.with_keygrip = 1;
2872 case oWithKeyScreening:
2873 opt.with_key_screening = 1;
2877 opt.with_secret = 1;
2881 opt.with_wkd_hash = 1;
2884 case oWithKeyOrigin:
2885 opt.with_key_origin = 1;
2888 case oSecretKeyring:
2889 obsolete_option (configname, pargs.lineno, "secret-keyring");
2892 case oNoArmor: opt.no_armor=1; opt.armor=0; break;
2895 if (default_keyring > 0)
2896 default_keyring = 0;
2899 default_keyring = -1;
2902 case oNoGreeting: nogreeting = 1; break;
2905 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2909 gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
2911 case oEmitVersion: opt.emit_version++; break;
2912 case oNoEmitVersion: opt.emit_version=0; break;
2913 case oCompletesNeeded: opt.completes_needed = pargs.r.ret_int; break;
2914 case oMarginalsNeeded: opt.marginals_needed = pargs.r.ret_int; break;
2915 case oMaxCertDepth: opt.max_cert_depth = pargs.r.ret_int; break;
2917 #ifndef NO_TRUST_MODELS
2918 case oTrustDBName: trustdb_name = pargs.r.ret_str; break;
2920 #endif /*!NO_TRUST_MODELS*/
2922 sl = add_to_strlist (&opt.def_secret_key, pargs.r.ret_str);
2923 sl->flags = (pargs.r_opt << PK_LIST_SHIFT);
2925 sl->flags |= PK_LIST_CONFIG;
2928 if( *pargs.r.ret_str )
2930 xfree (opt.def_recipient);
2931 opt.def_recipient = make_username(pargs.r.ret_str);
2934 case oDefRecipientSelf:
2935 xfree(opt.def_recipient); opt.def_recipient = NULL;
2936 opt.def_recipient_self = 1;
2938 case oNoDefRecipient:
2939 xfree(opt.def_recipient); opt.def_recipient = NULL;
2940 opt.def_recipient_self = 0;
2942 case oHomedir: break;
2943 case oChUid: break; /* Command line only (see above). */
2944 case oNoBatch: opt.batch = 0; break;
2946 case oWithTofuInfo: opt.with_tofu_info = 1; break;
2948 case oWithKeyData: opt.with_key_data=1; /*FALLTHRU*/
2949 case oWithColons: opt.with_colons=':'; break;
2951 case oWithSigCheck: opt.check_sigs = 1; /*FALLTHRU*/
2952 case oWithSigList: opt.list_sigs = 1; break;
2954 case oSkipVerify: opt.skip_verify=1; break;
2956 case oSkipHiddenRecipients: opt.skip_hidden_recipients = 1; break;
2957 case oNoSkipHiddenRecipients: opt.skip_hidden_recipients = 0; break;
2959 case aListSecretKeys: set_cmd( &cmd, aListSecretKeys); break;
2961 #ifndef NO_TRUST_MODELS
2962 /* There are many programs (like mutt) that call gpg with
2963 --always-trust so keep this option around for a long
2965 case oAlwaysTrust: opt.trust_model=TM_ALWAYS; break;
2967 parse_trust_model(pargs.r.ret_str);
2969 #endif /*!NO_TRUST_MODELS*/
2970 case oTOFUDefaultPolicy:
2971 opt.tofu_default_policy = parse_tofu_policy (pargs.r.ret_str);
2974 obsolete_option (configname, pargs.lineno, "tofu-db-format");
2977 case oForceOwnertrust:
2978 log_info(_("Note: %s is not for normal use!\n"),
2979 "--force-ownertrust");
2980 opt.force_ownertrust=string_to_trust_value(pargs.r.ret_str);
2981 if(opt.force_ownertrust==-1)
2983 log_error("invalid ownertrust '%s'\n",pargs.r.ret_str);
2984 opt.force_ownertrust=0;
2988 case oNoAutoTrustNewKey: opt.flags.no_auto_trust_new_key = 1; break;
2992 int compliance = gnupg_parse_compliance_option
2994 compliance_options, DIM (compliance_options),
2998 set_compliance_option (compliance);
3008 set_compliance_option (pargs.r_opt);
3011 case oRFC2440Text: opt.rfc2440_text=1; break;
3012 case oNoRFC2440Text: opt.rfc2440_text=0; break;
3016 opt.set_filename = pargs.r.ret_str;
3018 opt.set_filename = native_to_utf8(pargs.r.ret_str);
3020 case oForYourEyesOnly: eyes_only = 1; break;
3021 case oNoForYourEyesOnly: eyes_only = 0; break;
3023 add_policy_url(pargs.r.ret_str,0);
3024 add_policy_url(pargs.r.ret_str,1);
3026 case oSigPolicyURL: add_policy_url(pargs.r.ret_str,0); break;
3027 case oCertPolicyURL: add_policy_url(pargs.r.ret_str,1); break;
3028 case oShowPolicyURL:
3029 deprecated_warning(configname,pargs.lineno,"--show-policy-url",
3030 "--list-options ","show-policy-urls");
3031 deprecated_warning(configname,pargs.lineno,"--show-policy-url",
3032 "--verify-options ","show-policy-urls");
3033 opt.list_options|=LIST_SHOW_POLICY_URLS;
3034 opt.verify_options|=VERIFY_SHOW_POLICY_URLS;
3036 case oNoShowPolicyURL:
3037 deprecated_warning(configname,pargs.lineno,"--no-show-policy-url",
3038 "--list-options ","no-show-policy-urls");
3039 deprecated_warning(configname,pargs.lineno,"--no-show-policy-url",
3040 "--verify-options ","no-show-policy-urls");
3041 opt.list_options&=~LIST_SHOW_POLICY_URLS;
3042 opt.verify_options&=~VERIFY_SHOW_POLICY_URLS;
3044 case oSigKeyserverURL: add_keyserver_url(pargs.r.ret_str,0); break;
3045 case oUseEmbeddedFilename:
3046 opt.flags.use_embedded_filename=1;
3048 case oNoUseEmbeddedFilename:
3049 opt.flags.use_embedded_filename=0;
3052 if(pargs.r.ret_str[0])
3053 append_to_strlist(&opt.comments,pargs.r.ret_str);
3055 case oDefaultComment:
3056 deprecated_warning(configname,pargs.lineno,
3057 "--default-comment","--no-comments","");
3060 free_strlist(opt.comments);
3063 case oThrowKeyids: opt.throw_keyids = 1; break;
3064 case oNoThrowKeyids: opt.throw_keyids = 0; break;
3066 deprecated_warning(configname,pargs.lineno,"--show-photos",
3067 "--list-options ","show-photos");
3068 deprecated_warning(configname,pargs.lineno,"--show-photos",
3069 "--verify-options ","show-photos");
3070 opt.list_options|=LIST_SHOW_PHOTOS;
3071 opt.verify_options|=VERIFY_SHOW_PHOTOS;
3074 deprecated_warning(configname,pargs.lineno,"--no-show-photos",
3075 "--list-options ","no-show-photos");
3076 deprecated_warning(configname,pargs.lineno,"--no-show-photos",
3077 "--verify-options ","no-show-photos");
3078 opt.list_options&=~LIST_SHOW_PHOTOS;
3079 opt.verify_options&=~VERIFY_SHOW_PHOTOS;
3081 case oPhotoViewer: opt.photo_viewer = pargs.r.ret_str; break;
3083 case oForceAEAD: opt.force_aead = 1; break;
3085 case oDisableSignerUID: opt.flags.disable_signer_uid = 1; break;
3086 case oIncludeKeyBlock: opt.flags.include_key_block = 1; break;
3087 case oNoIncludeKeyBlock: opt.flags.include_key_block = 0; break;
3089 case oS2KMode: opt.s2k_mode = pargs.r.ret_int; break;
3090 case oS2KDigest: s2k_digest_string = xstrdup(pargs.r.ret_str); break;
3091 case oS2KCipher: s2k_cipher_string = xstrdup(pargs.r.ret_str); break;
3093 if (pargs.r.ret_int)
3094 opt.s2k_count = encode_s2k_iterations (pargs.r.ret_int);
3096 opt.s2k_count = 0; /* Auto-calibrate when needed. */
3100 case oHiddenRecipient:
3101 case oRecipientFile:
3102 case oHiddenRecipientFile:
3103 /* Store the recipient. Note that we also store the
3104 * option as private data in the flags. This is achieved
3105 * by shifting the option value to the left so to keep
3106 * enough space for the flags. */
3107 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
3108 sl->flags = (pargs.r_opt << PK_LIST_SHIFT);
3110 sl->flags |= PK_LIST_CONFIG;
3111 if (pargs.r_opt == oHiddenRecipient
3112 || pargs.r_opt == oHiddenRecipientFile)
3113 sl->flags |= PK_LIST_HIDDEN;
3114 if (pargs.r_opt == oRecipientFile
3115 || pargs.r_opt == oHiddenRecipientFile)
3116 sl->flags |= PK_LIST_FROM_FILE;
3117 any_explicit_recipient = 1;
3121 case oHiddenEncryptTo:
3122 /* Store an additional recipient. */
3123 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
3124 sl->flags = ((pargs.r_opt << PK_LIST_SHIFT) | PK_LIST_ENCRYPT_TO);
3126 sl->flags |= PK_LIST_CONFIG;
3127 if (pargs.r_opt == oHiddenEncryptTo)
3128 sl->flags |= PK_LIST_HIDDEN;
3132 opt.no_encrypt_to = 1;
3134 case oEncryptToDefaultKey:
3135 opt.encrypt_to_default_key = configname ? 2 : 1;
3139 add_to_strlist2 (&opt.secret_keys_to_try,
3140 pargs.r.ret_str, utf8_strings);
3143 case oMimemode: opt.mimemode = opt.textmode = 1; break;
3144 case oTextmodeShort: opt.textmode = 2; break;
3145 case oTextmode: opt.textmode=1; break;
3146 case oNoTextmode: opt.textmode=opt.mimemode=0; break;
3148 case oExpert: opt.expert = 1; break;
3149 case oNoExpert: opt.expert = 0; break;
3151 if(*pargs.r.ret_str!='\0')
3153 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
3154 log_error(_("'%s' is not a valid signature expiration\n"),
3157 opt.def_sig_expire=pargs.r.ret_str;
3160 case oAskSigExpire: opt.ask_sig_expire = 1; break;
3161 case oNoAskSigExpire: opt.ask_sig_expire = 0; break;
3162 case oDefCertExpire:
3163 if(*pargs.r.ret_str!='\0')
3165 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
3166 log_error(_("'%s' is not a valid signature expiration\n"),
3169 opt.def_cert_expire=pargs.r.ret_str;
3172 case oAskCertExpire: opt.ask_cert_expire = 1; break;
3173 case oNoAskCertExpire: opt.ask_cert_expire = 0; break;
3174 case oDefCertLevel: opt.def_cert_level=pargs.r.ret_int; break;
3175 case oMinCertLevel: opt.min_cert_level=pargs.r.ret_int; break;
3176 case oAskCertLevel: opt.ask_cert_level = 1; break;
3177 case oNoAskCertLevel: opt.ask_cert_level = 0; break;
3178 case oLocalUser: /* store the local users */
3179 sl = add_to_strlist2( &locusr, pargs.r.ret_str, utf8_strings );
3180 sl->flags = (pargs.r_opt << PK_LIST_SHIFT);
3182 sl->flags |= PK_LIST_CONFIG;
3186 char *mbox = mailbox_from_userid (pargs.r.ret_str, 0);
3188 log_error (_("\"%s\" is not a proper mail address\n"),
3192 add_to_strlist (&opt.sender_list, mbox);
3198 /* this is the -z command line option */
3199 opt.compress_level = opt.bz2_compress_level = pargs.r.ret_int;
3201 case oCompressLevel: opt.compress_level = pargs.r.ret_int; break;
3202 case oBZ2CompressLevel: opt.bz2_compress_level = pargs.r.ret_int; break;
3203 case oBZ2DecompressLowmem: opt.bz2_decompress_lowmem=1; break;
3205 set_passphrase_from_string (pargs.r_type ? pargs.r.ret_str : "");
3208 pwfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
3210 case oPassphraseFile:
3211 pwfd = open_info_file (pargs.r.ret_str, 0, 1);
3213 case oPassphraseRepeat:
3214 opt.passphrase_repeat = pargs.r.ret_int;
3218 opt.pinentry_mode = parse_pinentry_mode (pargs.r.ret_str);
3219 if (opt.pinentry_mode == -1)
3220 log_error (_("invalid pinentry mode '%s'\n"), pargs.r.ret_str);
3223 case oRequestOrigin:
3224 opt.request_origin = parse_request_origin (pargs.r.ret_str);
3225 if (opt.request_origin == -1)
3226 log_error (_("invalid request origin '%s'\n"), pargs.r.ret_str);
3230 opt.command_fd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
3231 if (! gnupg_fd_valid (opt.command_fd))
3232 log_error ("command-fd is invalid: %s\n", strerror (errno));
3235 opt.command_fd = open_info_file (pargs.r.ret_str, 0, 1);
3238 def_cipher_string = xstrdup(pargs.r.ret_str);
3241 def_aead_string = xstrdup (pargs.r.ret_str);
3244 def_digest_string = xstrdup(pargs.r.ret_str);
3247 /* If it is all digits, stick a Z in front of it for
3248 later. This is for backwards compatibility with
3249 versions that took the compress algorithm number. */
3251 char *pt=pargs.r.ret_str;
3254 if (!isascii (*pt) || !isdigit (*pt))
3262 compress_algo_string=xmalloc(strlen(pargs.r.ret_str)+2);
3263 strcpy(compress_algo_string,"Z");
3264 strcat(compress_algo_string,pargs.r.ret_str);
3267 compress_algo_string = xstrdup(pargs.r.ret_str);
3270 case oCertDigestAlgo:
3271 cert_digest_string = xstrdup(pargs.r.ret_str);
3275 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
3278 case oRequireSecmem: require_secmem=1; break;
3279 case oNoRequireSecmem: require_secmem=0; break;
3280 case oNoPermissionWarn: opt.no_perm_warn=1; break;
3281 case oDisplayCharset:
3282 if( set_native_charset( pargs.r.ret_str ) )
3283 log_error(_("'%s' is not a valid character set\n"),
3286 case oNotDashEscaped: opt.not_dash_escaped = 1; break;
3287 case oEscapeFrom: opt.escape_from = 1; break;
3288 case oNoEscapeFrom: opt.escape_from = 0; break;
3289 case oLockOnce: opt.lock_once = 1; break;
3296 #else /* __riscos__ */
3297 riscos_not_implemented("lock-multiple");
3298 #endif /* __riscos__ */
3302 keyserver_spec_t keyserver;
3303 keyserver = parse_keyserver_uri (pargs.r.ret_str, 0);
3305 log_error (_("could not parse keyserver URL\n"));
3308 /* We only support a single keyserver. Later ones
3309 override earlier ones. (Since we parse the
3310 config file first and then the command line
3311 arguments, the command line takes
3314 free_keyserver_spec (opt.keyserver);
3315 opt.keyserver = keyserver;
3319 case oKeyServerOptions:
3320 if(!parse_keyserver_options(pargs.r.ret_str))
3323 log_error(_("%s:%d: invalid keyserver options\n"),
3324 configname,pargs.lineno);
3326 log_error(_("invalid keyserver options\n"));
3329 case oImportOptions:
3330 if(!parse_import_options(pargs.r.ret_str,&opt.import_options,1))
3333 log_error(_("%s:%d: invalid import options\n"),
3334 configname,pargs.lineno);
3336 log_error(_("invalid import options\n"));
3340 rc = parse_and_set_import_filter (pargs.r.ret_str);
3342 log_error (_("invalid filter option: %s\n"), gpg_strerror (rc));
3344 case oExportOptions:
3345 if(!parse_export_options(pargs.r.ret_str,&opt.export_options,1))
3348 log_error(_("%s:%d: invalid export options\n"),
3349 configname,pargs.lineno);
3351 log_error(_("invalid export options\n"));
3355 rc = parse_and_set_export_filter (pargs.r.ret_str);
3357 log_error (_("invalid filter option: %s\n"), gpg_strerror (rc));
3360 if(!parse_list_options(pargs.r.ret_str))
3363 log_error(_("%s:%d: invalid list options\n"),
3364 configname,pargs.lineno);
3366 log_error(_("invalid list options\n"));
3369 case oVerifyOptions:
3371 struct parse_options vopts[]=
3373 {"show-photos",VERIFY_SHOW_PHOTOS,NULL,
3374 N_("display photo IDs during signature verification")},
3375 {"show-policy-urls",VERIFY_SHOW_POLICY_URLS,NULL,
3376 N_("show policy URLs during signature verification")},
3377 {"show-notations",VERIFY_SHOW_NOTATIONS,NULL,
3378 N_("show all notations during signature verification")},
3379 {"show-std-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
3380 N_("show IETF standard notations during signature verification")},
3381 {"show-standard-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
3383 {"show-user-notations",VERIFY_SHOW_USER_NOTATIONS,NULL,
3384 N_("show user-supplied notations during signature verification")},
3385 {"show-keyserver-urls",VERIFY_SHOW_KEYSERVER_URLS,NULL,
3386 N_("show preferred keyserver URLs during signature verification")},
3387 {"show-uid-validity",VERIFY_SHOW_UID_VALIDITY,NULL,
3388 N_("show user ID validity during signature verification")},
3389 {"show-unusable-uids",VERIFY_SHOW_UNUSABLE_UIDS,NULL,
3390 N_("show revoked and expired user IDs in signature verification")},
3391 {"show-primary-uid-only",VERIFY_SHOW_PRIMARY_UID_ONLY,NULL,
3392 N_("show only the primary user ID in signature verification")},
3396 if(!parse_options(pargs.r.ret_str,&opt.verify_options,vopts,1))
3399 log_error(_("%s:%d: invalid verify options\n"),
3400 configname,pargs.lineno);
3402 log_error(_("invalid verify options\n"));
3406 case oTempDir: opt.temp_dir=pargs.r.ret_str; break;
3408 if(set_exec_path(pargs.r.ret_str))
3409 log_error(_("unable to set exec-path to %s\n"),pargs.r.ret_str);
3411 opt.exec_path_set=1;
3414 add_notation_data( pargs.r.ret_str, 0 );
3415 add_notation_data( pargs.r.ret_str, 1 );
3417 case oSigNotation: add_notation_data( pargs.r.ret_str, 0 ); break;
3418 case oCertNotation: add_notation_data( pargs.r.ret_str, 1 ); break;
3419 case oKnownNotation: register_known_notation (pargs.r.ret_str); break;
3421 deprecated_warning(configname,pargs.lineno,"--show-notation",
3422 "--list-options ","show-notations");
3423 deprecated_warning(configname,pargs.lineno,"--show-notation",
3424 "--verify-options ","show-notations");
3425 opt.list_options|=LIST_SHOW_NOTATIONS;
3426 opt.verify_options|=VERIFY_SHOW_NOTATIONS;
3428 case oNoShowNotation:
3429 deprecated_warning(configname,pargs.lineno,"--no-show-notation",
3430 "--list-options ","no-show-notations");
3431 deprecated_warning(configname,pargs.lineno,"--no-show-notation",
3432 "--verify-options ","no-show-notations");
3433 opt.list_options&=~LIST_SHOW_NOTATIONS;
3434 opt.verify_options&=~VERIFY_SHOW_NOTATIONS;
3436 case oUtf8Strings: utf8_strings = 1; break;
3437 case oNoUtf8Strings:
3438 #ifdef HAVE_W32_SYSTEM
3442 case oDisableCipherAlgo:
3444 int algo = string_to_cipher_algo (pargs.r.ret_str);
3445 gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
3448 case oDisablePubkeyAlgo:
3450 int algo = gcry_pk_map_name (pargs.r.ret_str);
3451 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
3454 case oNoSigCache: opt.no_sig_cache = 1; break;
3455 case oAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid = 1; break;
3456 case oNoAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid=0; break;
3457 case oAllowFreeformUID: opt.allow_freeform_uid = 1; break;
3458 case oNoAllowFreeformUID: opt.allow_freeform_uid = 0; break;
3459 case oNoLiteral: opt.no_literal = 1; break;
3460 case oSetFilesize: opt.set_filesize = pargs.r.ret_ulong; break;
3461 case oFastListMode: opt.fast_list_mode = 1; break;
3462 case oFixedListMode: /* Dummy */ break;
3463 case oLegacyListMode: opt.legacy_list_mode = 1; break;
3464 case oPrintDANERecords: print_dane_records = 1; break;
3465 case oListOnly: opt.list_only=1; break;
3466 case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
3467 case oIgnoreValidFrom: opt.ignore_valid_from = 1; break;
3468 case oIgnoreCrcError: opt.ignore_crc_error = 1; break;
3469 case oIgnoreMDCError: opt.ignore_mdc_error = 1; break;
3470 case oNoRandomSeedFile: use_random_seed = 0; break;
3472 case oAutoKeyImport: opt.flags.auto_key_import = 1; break;
3473 case oNoAutoKeyImport: opt.flags.auto_key_import = 0; break;
3475 case oAutoKeyRetrieve:
3476 opt.keyserver_options.options |= KEYSERVER_AUTO_KEY_RETRIEVE;
3478 case oNoAutoKeyRetrieve:
3479 opt.keyserver_options.options &= ~KEYSERVER_AUTO_KEY_RETRIEVE;
3482 case oShowSessionKey: opt.show_session_key = 1; break;
3483 case oOverrideSessionKey:
3484 opt.override_session_key = pargs.r.ret_str;
3486 case oOverrideSessionKeyFD:
3487 ovrseskeyfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
3490 deprecated_warning(configname,pargs.lineno,"--merge-only",
3491 "--import-options ","merge-only");
3492 opt.import_options|=IMPORT_MERGE_ONLY;
3494 case oAllowSecretKeyImport: /* obsolete */ break;
3495 case oTryAllSecrets: opt.try_all_secrets = 1; break;
3496 case oTrustedKey: register_trusted_key( pargs.r.ret_str ); break;
3498 case oEnableSpecialFilenames:
3499 enable_special_filenames ();
3502 case oNoExpensiveTrustChecks: opt.no_expensive_trust_checks=1; break;
3503 case oAutoCheckTrustDB: opt.no_auto_check_trustdb=0; break;
3504 case oNoAutoCheckTrustDB: opt.no_auto_check_trustdb=1; break;
3505 case oPreservePermissions: opt.preserve_permissions=1; break;
3506 case oDefaultPreferenceList:
3507 opt.def_preference_list = pargs.r.ret_str;
3509 case oDefaultKeyserverURL:
3511 keyserver_spec_t keyserver;
3512 keyserver = parse_keyserver_uri (pargs.r.ret_str,1 );
3514 log_error (_("could not parse keyserver URL\n"));
3516 free_keyserver_spec (keyserver);
3518 opt.def_keyserver_url = pargs.r.ret_str;
3521 case oPersonalCipherPreferences:
3522 pers_cipher_list=pargs.r.ret_str;
3524 case oPersonalAEADPreferences:
3525 pers_aead_list = pargs.r.ret_str;
3527 case oPersonalDigestPreferences:
3528 pers_digest_list=pargs.r.ret_str;
3530 case oPersonalCompressPreferences:
3531 pers_compress_list=pargs.r.ret_str;
3533 case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
3534 case oKeyboxdProgram: opt.keyboxd_program = pargs.r.ret_str; break;
3535 case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break;
3536 case oDisableDirmngr: opt.disable_dirmngr = 1; break;
3538 additional_weak_digest(pargs.r.ret_str);
3541 opt.unwrap_encryption = 1;
3543 case oOnlySignTextIDs:
3544 opt.only_sign_text_ids = 1;
3548 set_opt_session_env ("DISPLAY", pargs.r.ret_str);
3551 set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
3554 set_opt_session_env ("TERM", pargs.r.ret_str);
3557 set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
3560 case oLCctype: opt.lc_ctype = pargs.r.ret_str; break;
3561 case oLCmessages: opt.lc_messages = pargs.r.ret_str; break;
3563 case oGroup: add_group(pargs.r.ret_str); break;
3564 case oUnGroup: rm_group(pargs.r.ret_str); break;
3566 while(opt.grouplist)
3568 struct groupitem *iter=opt.grouplist;
3569 free_strlist(iter->values);
3570 opt.grouplist=opt.grouplist->next;
3575 case oMangleDosFilenames: opt.mangle_dos_filenames = 1; break;
3576 case oNoMangleDosFilenames: opt.mangle_dos_filenames = 0; break;
3577 case oEnableProgressFilter: opt.enable_progress_filter = 1; break;
3578 case oMultifile: multifile=1; break;
3580 if(ascii_strcasecmp(pargs.r.ret_str,"short")==0)
3581 opt.keyid_format=KF_SHORT;
3582 else if(ascii_strcasecmp(pargs.r.ret_str,"long")==0)
3583 opt.keyid_format=KF_LONG;
3584 else if(ascii_strcasecmp(pargs.r.ret_str,"0xshort")==0)
3585 opt.keyid_format=KF_0xSHORT;
3586 else if(ascii_strcasecmp(pargs.r.ret_str,"0xlong")==0)
3587 opt.keyid_format=KF_0xLONG;
3588 else if(ascii_strcasecmp(pargs.r.ret_str,"none")==0)
3589 opt.keyid_format = KF_NONE;
3591 log_error("unknown keyid-format '%s'\n",pargs.r.ret_str);
3594 case oExitOnStatusWriteError:
3595 opt.exit_on_status_write_error = 1;
3598 case oLimitCardInsertTries:
3599 opt.limit_card_insert_tries = pargs.r.ret_int;
3602 case oRequireCrossCert: opt.flags.require_cross_cert=1; break;
3603 case oNoRequireCrossCert: opt.flags.require_cross_cert=0; break;
3605 case oAutoKeyLocate:
3608 /* This is the first time --auto-key-locate is seen.
3609 * We need to reset the default akl. */
3613 if(!parse_auto_key_locate(pargs.r.ret_str))
3616 log_error(_("%s:%d: invalid auto-key-locate list\n"),
3617 configname,pargs.lineno);
3619 log_error(_("invalid auto-key-locate list\n"));
3622 case oNoAutoKeyLocate:
3627 if(!parse_key_origin (pargs.r.ret_str))
3628 log_error (_("invalid argument for option \"%.50s\"\n"),
3632 case oEnableLargeRSA:
3633 #if SECMEM_BUFFER_SIZE >= 65536
3634 opt.flags.large_rsa=1;
3637 log_info("%s:%d: WARNING: gpg not built with large secure "
3638 "memory buffer. Ignoring enable-large-rsa\n",
3639 configname,pargs.lineno);
3641 log_info("WARNING: gpg not built with large secure "
3642 "memory buffer. Ignoring --enable-large-rsa\n");
3643 #endif /* SECMEM_BUFFER_SIZE >= 65536 */
3645 case oDisableLargeRSA: opt.flags.large_rsa=0;
3648 case oEnableDSA2: opt.flags.dsa2=1; break;
3649 case oDisableDSA2: opt.flags.dsa2=0; break;
3651 case oAllowWeakDigestAlgos:
3652 opt.flags.allow_weak_digest_algos = 1;
3655 case oAllowWeakKeySignatures:
3656 opt.flags.allow_weak_key_signatures = 1;
3659 case oAllowOldCipherAlgos:
3660 opt.flags.allow_old_cipher_algos = 1;
3663 case oFakedSystemTime:
3665 size_t len = strlen (pargs.r.ret_str);
3669 if (len > 0 && pargs.r.ret_str[len-1] == '!')
3672 pargs.r.ret_str[len-1] = '\0';
3675 faked_time = isotime2epoch (pargs.r.ret_str);
3676 if (faked_time == (time_t)(-1))
3677 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
3678 gnupg_set_time (faked_time, freeze);
3682 case oNoAutostart: opt.autostart = 0; break;
3683 case oNoSymkeyCache: opt.no_symkey_cache = 1; break;
3685 case oDefaultNewKeyAlgo:
3686 opt.def_new_key_algo = pargs.r.ret_str;
3689 case oUseOnlyOpenPGPCard:
3690 opt.flags.use_only_openpgp_card = 1;
3693 case oFullTimestrings:
3694 opt.flags.full_timestrings = 1;
3701 pargs.err = ARGPARSE_PRINT_WARNING;
3704 pargs.err = ARGPARSE_PRINT_ERROR;
3705 /* The argparse function calls a plain exit and thus
3706 * we need to print a status here. */
3707 write_status_failure ("option-parser",
3708 gpg_error(GPG_ERR_GENERAL));
3714 gpgrt_argparse (NULL, &pargs, NULL); /* Release internal state. */
3716 if (log_get_errorcount (0))
3718 write_status_failure ("option-parser", gpg_error(GPG_ERR_GENERAL));
3722 /* Process common component options. */
3723 if (parse_comopt (GNUPG_MODULE_NAME_GPG, debug_argparser))
3725 write_status_failure ("option-parser", gpg_error(GPG_ERR_GENERAL));
3729 if (opt.use_keyboxd)
3730 log_info ("Note: Please move option \"%s\" to \"common.conf\"\n",
3732 opt.use_keyboxd = comopt.use_keyboxd; /* Override. */
3734 if (opt.keyboxd_program)
3735 log_info ("Note: Please move option \"%s\" to \"common.conf\"\n",
3737 if (!opt.keyboxd_program && comopt.keyboxd_program)
3739 opt.keyboxd_program = comopt.keyboxd_program;
3740 comopt.keyboxd_program = NULL;
3744 /* The command --gpgconf-list is pretty simple and may be called
3745 directly after the option parsing. */
3746 if (cmd == aGPGConfList)
3751 xfree (last_configname);
3753 if (print_dane_records)
3754 log_error ("invalid option \"%s\"; use \"%s\" instead\n",
3755 "--print-dane-records",
3756 "--export-options export-dane");
3757 if (log_get_errorcount (0))
3759 write_status_failure ("option-checking", gpg_error(GPG_ERR_GENERAL));
3769 es_fprintf (es_stderr, "%s %s; %s\n",
3770 gpgrt_strusage(11), gpgrt_strusage(13), gpgrt_strusage(14));
3771 es_fprintf (es_stderr, "%s\n", gpgrt_strusage(15) );
3773 #ifdef IS_DEVELOPMENT_VERSION
3778 if((s=gpgrt_strusage(25)))
3780 if((s=gpgrt_strusage(26)))
3782 if((s=gpgrt_strusage(27)))
3787 /* Init threading which is used by some helper functions. */
3789 assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
3790 gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
3794 log_set_file (logfile);
3795 log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
3796 | GPGRT_LOG_WITH_TIME
3797 | GPGRT_LOG_WITH_PID ));
3800 if (opt.verbose > 2)
3801 log_info ("using character set '%s'\n", get_native_charset ());
3803 if( may_coredump && !opt.quiet )
3804 log_info(_("WARNING: program may create a core file!\n"));
3806 if (opt.flags.rfc4880bis)
3809 log_info ("Note: RFC4880bis features are enabled.\n");
3813 opt.mimemode = 0; /* This will use text mode instead. */
3817 if (opt.set_filename)
3818 log_info(_("WARNING: %s overrides %s\n"),
3819 "--for-your-eyes-only","--set-filename");
3821 opt.set_filename="_CONSOLE";
3824 if (opt.no_literal) {
3825 log_info(_("Note: %s is not for normal use!\n"), "--no-literal");
3827 log_error(_("%s not allowed with %s!\n"),
3828 "--textmode", "--no-literal" );
3829 if (opt.set_filename)
3830 log_error(_("%s makes no sense with %s!\n"),
3831 eyes_only?"--for-your-eyes-only":"--set-filename",
3836 if (opt.set_filesize)
3837 log_info(_("Note: %s is not for normal use!\n"), "--set-filesize");
3841 if (gnupg_faked_time_p ())
3843 gnupg_isotime_t tbuf;
3845 log_info (_("WARNING: running with faked system time: "));
3846 gnupg_get_isotime (tbuf);
3847 dump_isotime (tbuf);
3851 /* Print a warning if an argument looks like an option. */
3852 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
3856 for (i=0; i < argc; i++)
3857 if (argv[i][0] == '-' && argv[i][1] == '-')
3858 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
3862 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
3864 if(require_secmem && !got_secmem)
3866 log_info(_("will not run with insecure memory due to %s\n"),
3867 "--require-secmem");
3868 write_status_failure ("option-checking", gpg_error(GPG_ERR_GENERAL));
3872 set_debug (debug_level);
3874 log_clock ("start");
3876 /* Do these after the switch(), so they can override settings. */
3879 /* That does not anymore work because we have no more support
3880 for v3 signatures. */
3882 opt.ask_sig_expire=0;
3890 if( def_cipher_string ) {
3891 opt.def_cipher_algo = string_to_cipher_algo (def_cipher_string);
3892 xfree(def_cipher_string); def_cipher_string = NULL;
3893 if ( openpgp_cipher_test_algo (opt.def_cipher_algo) )
3894 log_error(_("selected cipher algorithm is invalid\n"));
3896 if (def_aead_string)
3898 opt.def_aead_algo = string_to_aead_algo (def_aead_string);
3899 xfree (def_aead_string); def_aead_string = NULL;
3900 if (openpgp_aead_test_algo (opt.def_aead_algo))
3901 log_error(_("selected AEAD algorithm is invalid\n"));
3903 if( def_digest_string ) {
3904 opt.def_digest_algo = string_to_digest_algo (def_digest_string);
3905 xfree(def_digest_string); def_digest_string = NULL;
3906 if ( openpgp_md_test_algo (opt.def_digest_algo) )
3907 log_error(_("selected digest algorithm is invalid\n"));
3909 if( compress_algo_string ) {
3910 opt.compress_algo = string_to_compress_algo(compress_algo_string);
3911 xfree(compress_algo_string); compress_algo_string = NULL;
3912 if( check_compress_algo(opt.compress_algo) )
3913 log_error(_("selected compression algorithm is invalid\n"));
3915 if( cert_digest_string ) {
3916 opt.cert_digest_algo = string_to_digest_algo (cert_digest_string);
3917 xfree(cert_digest_string); cert_digest_string = NULL;
3918 if (openpgp_md_test_algo(opt.cert_digest_algo))
3919 log_error(_("selected certification digest algorithm is invalid\n"));
3921 if( s2k_cipher_string ) {
3922 opt.s2k_cipher_algo = string_to_cipher_algo (s2k_cipher_string);
3923 xfree(s2k_cipher_string); s2k_cipher_string = NULL;
3924 if (openpgp_cipher_test_algo (opt.s2k_cipher_algo))
3925 log_error(_("selected cipher algorithm is invalid\n"));
3927 if( s2k_digest_string ) {
3928 opt.s2k_digest_algo = string_to_digest_algo (s2k_digest_string);
3929 xfree(s2k_digest_string); s2k_digest_string = NULL;
3930 if (openpgp_md_test_algo(opt.s2k_digest_algo))
3931 log_error(_("selected digest algorithm is invalid\n"));
3933 if( opt.completes_needed < 1 )
3934 log_error(_("completes-needed must be greater than 0\n"));
3935 if( opt.marginals_needed < 2 )
3936 log_error(_("marginals-needed must be greater than 1\n"));
3937 if( opt.max_cert_depth < 1 || opt.max_cert_depth > 255 )
3938 log_error(_("max-cert-depth must be in the range from 1 to 255\n"));
3939 if(opt.def_cert_level<0 || opt.def_cert_level>3)
3940 log_error(_("invalid default-cert-level; must be 0, 1, 2, or 3\n"));
3941 if( opt.min_cert_level < 1 || opt.min_cert_level > 3 )
3942 log_error(_("invalid min-cert-level; must be 1, 2, or 3\n"));
3943 switch( opt.s2k_mode ) {
3946 log_info(_("Note: simple S2K mode (0) is strongly discouraged\n"));
3948 case 1: case 3: break;
3950 log_error(_("invalid S2K mode; must be 0, 1 or 3\n"));
3953 /* This isn't actually needed, but does serve to error out if the
3954 string is invalid. */
3955 if(opt.def_preference_list &&
3956 keygen_set_std_prefs(opt.def_preference_list,0))
3957 log_error(_("invalid default preferences\n"));
3959 if(pers_cipher_list &&
3960 keygen_set_std_prefs(pers_cipher_list,PREFTYPE_SYM))
3961 log_error(_("invalid personal cipher preferences\n"));
3963 if (pers_aead_list && keygen_set_std_prefs (pers_aead_list, PREFTYPE_AEAD))
3964 log_error(_("invalid personal AEAD preferences\n"));
3966 if(pers_digest_list &&
3967 keygen_set_std_prefs(pers_digest_list,PREFTYPE_HASH))
3968 log_error(_("invalid personal digest preferences\n"));
3970 if(pers_compress_list &&
3971 keygen_set_std_prefs(pers_compress_list,PREFTYPE_ZIP))
3972 log_error(_("invalid personal compress preferences\n"));
3974 /* Check chunk size. Please fix also the man page if you change
3975 * the default. The limits are given by the specs. */
3976 if (!opt.chunk_size)
3977 opt.chunk_size = 22; /* Default to the suggested max of 4 MiB. */
3978 else if (opt.chunk_size < 6)
3981 log_info (_("chunk size invalid - using %d\n"), opt.chunk_size);
3983 else if (opt.chunk_size > (allow_large_chunks? 62 : 22))
3985 opt.chunk_size = (allow_large_chunks? 62 : 22);
3986 log_info (_("chunk size invalid - using %d\n"), opt.chunk_size);
3989 /* We don't support all possible commands with multifile yet */
4000 cmdname="--sign --encrypt";
4003 cmdname="--clear-sign";
4006 cmdname="--detach-sign";
4009 cmdname="--symmetric";
4012 cmdname="--symmetric --encrypt";
4023 log_error(_("%s does not yet work with %s\n"),cmdname,"--multifile");
4026 if( log_get_errorcount(0) )
4028 write_status_failure ("option-postprocessing",
4029 gpg_error(GPG_ERR_GENERAL));
4033 if(opt.compress_level==0)
4034 opt.compress_algo=COMPRESS_ALGO_NONE;
4036 /* Check our chosen algorithms against the list of legal
4039 if(!GNUPG && !opt.flags.rfc4880bis)
4041 const char *badalg=NULL;
4042 preftype_t badtype=PREFTYPE_NONE;
4044 if(opt.def_cipher_algo
4045 && !algo_available(PREFTYPE_SYM,opt.def_cipher_algo,NULL))
4047 badalg = openpgp_cipher_algo_name (opt.def_cipher_algo);
4048 badtype = PREFTYPE_SYM;
4050 else if(opt.def_aead_algo
4051 && !algo_available(PREFTYPE_AEAD, opt.def_aead_algo, NULL))
4053 badalg = openpgp_aead_algo_name (opt.def_aead_algo);
4054 badtype = PREFTYPE_AEAD;
4056 else if(opt.def_digest_algo
4057 && !algo_available(PREFTYPE_HASH,opt.def_digest_algo,NULL))
4059 badalg = gcry_md_algo_name (opt.def_digest_algo);
4060 badtype = PREFTYPE_HASH;
4062 else if(opt.cert_digest_algo
4063 && !algo_available(PREFTYPE_HASH,opt.cert_digest_algo,NULL))
4065 badalg = gcry_md_algo_name (opt.cert_digest_algo);
4066 badtype = PREFTYPE_HASH;
4068 else if(opt.compress_algo!=-1
4069 && !algo_available(PREFTYPE_ZIP,opt.compress_algo,NULL))
4071 badalg = compress_algo_to_string(opt.compress_algo);
4072 badtype = PREFTYPE_ZIP;
4080 log_info (_("cipher algorithm '%s'"
4081 " may not be used in %s mode\n"),
4083 gnupg_compliance_option_string (opt.compliance));
4086 log_info (_("AEAD algorithm '%s'"
4087 " may not be used in %s mode\n"),
4089 gnupg_compliance_option_string (opt.compliance));
4092 log_info (_("digest algorithm '%s'"
4093 " may not be used in %s mode\n"),
4095 gnupg_compliance_option_string (opt.compliance));
4098 log_info (_("compression algorithm '%s'"
4099 " may not be used in %s mode\n"),
4101 gnupg_compliance_option_string (opt.compliance));
4107 compliance_failure();
4111 /* Check our chosen algorithms against the list of allowed
4112 * algorithms in the current compliance mode, and fail hard if it
4113 * is not. This is us being nice to the user informing her early
4114 * that the chosen algorithms are not available. We also check
4115 * and enforce this right before the actual operation. */
4116 /* FIXME: We also need to check the AEAD algo. */
4117 if (opt.def_cipher_algo
4118 && ! gnupg_cipher_is_allowed (opt.compliance,
4124 || cmd == aSignEncrSym,
4125 opt.def_cipher_algo,
4126 GCRY_CIPHER_MODE_NONE))
4127 log_error (_("cipher algorithm '%s' may not be used in %s mode\n"),
4128 openpgp_cipher_algo_name (opt.def_cipher_algo),
4129 gnupg_compliance_option_string (opt.compliance));
4131 if (opt.def_digest_algo
4132 && ! gnupg_digest_is_allowed (opt.compliance,
4135 || cmd == aSignEncrSym
4137 || cmd == aClearsign,
4138 opt.def_digest_algo))
4139 log_error (_("digest algorithm '%s' may not be used in %s mode\n"),
4140 gcry_md_algo_name (opt.def_digest_algo),
4141 gnupg_compliance_option_string (opt.compliance));
4144 if (log_get_errorcount (0))
4146 write_status_failure ("option-checking", gpg_error(GPG_ERR_GENERAL));
4150 /* Set the random seed file. */
4151 if (use_random_seed)
4153 char *p = make_filename (gnupg_homedir (), "random_seed", NULL );
4154 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
4155 if (!gnupg_access (p, F_OK))
4156 register_secured_file (p);
4160 /* If there is no command but the --fingerprint is given, default
4161 to the --list-keys command. */
4162 if (!cmd && fpr_maybe_cmd)
4164 set_cmd (&cmd, aListKeys);
4168 if( opt.verbose > 1 )
4169 set_packet_list_mode(1);
4171 /* Add the keyrings, but not for some special commands. We always
4172 * need to add the keyrings if we are running under SELinux, this
4173 * is so that the rings are added to the list of secured files.
4174 * We do not add any keyring if --no-keyring or --use-keyboxd has
4176 if (!opt.use_keyboxd
4177 && default_keyring >= 0
4178 && (ALWAYS_ADD_KEYRINGS
4179 || (cmd != aDeArmor && cmd != aEnArmor && cmd != aGPGConfTest)))
4181 if (!nrings || default_keyring > 0) /* Add default ring. */
4182 keydb_add_resource ("pubring" EXTSEP_S GPGEXT_GPG,
4183 KEYDB_RESOURCE_FLAG_DEFAULT);
4184 for (sl = nrings; sl; sl = sl->next )
4185 keydb_add_resource (sl->d, sl->flags);
4187 FREE_STRLIST(nrings);
4189 /* In loopback mode, never ask for the password multiple times. */
4190 if (opt.pinentry_mode == PINENTRY_MODE_LOOPBACK)
4192 opt.passphrase_repeat = 0;
4195 /* If no pinentry is expected shunt
4196 * gnupg_allow_set_foregound_window to avoid useless error
4197 * messages on Windows. */
4198 if (opt.pinentry_mode != PINENTRY_MODE_ASK)
4200 gnupg_inhibit_set_foregound_window (1);
4204 if (cmd == aGPGConfTest)
4208 if (pwfd != -1) /* Read the passphrase now. */
4209 read_passphrase_from_fd (pwfd);
4211 if (ovrseskeyfd != -1 ) /* Read the sessionkey now. */
4212 read_sessionkey_from_fd (ovrseskeyfd);
4214 fname = argc? *argv : NULL;
4216 if(fname && utf8_strings)
4217 opt.flags.utf8_filename=1;
4219 ctrl = xcalloc (1, sizeof *ctrl);
4220 gpg_init_default_ctrl (ctrl);
4222 #ifndef NO_TRUST_MODELS
4232 case aListGcryptConfig:
4235 case aExportOwnerTrust:
4236 rc = setup_trustdb (0, trustdb_name);
4239 rc = setup_trustdb (argc? 1:0, trustdb_name);
4244 rc = setup_trustdb (1, trustdb_name);
4247 /* If we are using TM_ALWAYS, we do not need to create the
4249 rc = setup_trustdb (opt.trust_model != TM_ALWAYS, trustdb_name);
4253 log_error (_("failed to initialize the TrustDB: %s\n"),
4255 #endif /*!NO_TRUST_MODELS*/
4264 if (!opt.quiet && any_explicit_recipient)
4265 log_info (_("WARNING: recipients (-r) given "
4266 "without using public key encryption\n"));
4273 /* Check for certain command whether we need to migrate a
4274 secring.gpg to the gpg-agent. */
4277 case aListSecretKeys:
4288 case aDeleteSecretKeys:
4289 case aDeleteSecretAndPublicKeys:
4294 case aQuickSetPrimaryUid:
4299 case aExportSecretSub:
4304 migrate_secring (ctrl);
4307 if (opt.with_secret)
4308 migrate_secring (ctrl);
4314 /* The command dispatcher. */
4321 case aStore: /* only store the file */
4323 wrong_args("--store [filename]");
4324 if( (rc = encrypt_store(fname)) )
4326 write_status_failure ("store", rc);
4327 log_error ("storing '%s' failed: %s\n",
4328 print_fname_stdin(fname),gpg_strerror (rc) );
4331 case aSym: /* encrypt the given file only with the symmetric cipher */
4333 wrong_args("--symmetric [filename]");
4334 if( (rc = encrypt_symmetric(fname)) )
4336 write_status_failure ("symencrypt", rc);
4337 log_error (_("symmetric encryption of '%s' failed: %s\n"),
4338 print_fname_stdin(fname),gpg_strerror (rc) );
4342 case aEncr: /* encrypt the given file */
4344 encrypt_crypt_files (ctrl, argc, argv, remusr);
4348 wrong_args("--encrypt [filename]");
4349 if( (rc = encrypt_crypt (ctrl, -1, fname, remusr, 0, NULL, -1)) )
4351 write_status_failure ("encrypt", rc);
4352 log_error("%s: encryption failed: %s\n",
4353 print_fname_stdin(fname), gpg_strerror (rc) );
4359 /* This works with PGP 8 in the sense that it acts just like a
4360 symmetric message. It doesn't work at all with 2 or 6. It
4361 might work with 7, but alas, I don't have a copy to test
4364 wrong_args("--symmetric --encrypt [filename]");
4365 else if(opt.s2k_mode==0)
4366 log_error(_("you cannot use --symmetric --encrypt"
4367 " with --s2k-mode 0\n"));
4369 log_error(_("you cannot use --symmetric --encrypt"
4371 gnupg_compliance_option_string (opt.compliance));
4374 if( (rc = encrypt_crypt (ctrl, -1, fname, remusr, 1, NULL, -1)) )
4376 write_status_failure ("encrypt", rc);
4377 log_error ("%s: encryption failed: %s\n",
4378 print_fname_stdin(fname), gpg_strerror (rc) );
4383 case aSign: /* sign the given file */
4385 if( detached_sig ) { /* sign all files */
4386 for( ; argc; argc--, argv++ )
4387 add_to_strlist( &sl, *argv );
4391 wrong_args("--sign [filename]");
4393 sl = xmalloc_clear( sizeof *sl + strlen(fname));
4394 strcpy(sl->d, fname);
4397 if ((rc = sign_file (ctrl, sl, detached_sig, locusr, 0, NULL, NULL)))
4399 write_status_failure ("sign", rc);
4400 log_error ("signing failed: %s\n", gpg_strerror (rc) );
4405 case aSignEncr: /* sign and encrypt the given file */
4407 wrong_args("--sign --encrypt [filename]");
4409 sl = xmalloc_clear( sizeof *sl + strlen(fname));
4410 strcpy(sl->d, fname);
4414 if ((rc = sign_file (ctrl, sl, detached_sig, locusr, 1, remusr, NULL)))
4416 write_status_failure ("sign-encrypt", rc);
4417 log_error("%s: sign+encrypt failed: %s\n",
4418 print_fname_stdin(fname), gpg_strerror (rc) );
4423 case aSignEncrSym: /* sign and encrypt the given file */
4425 wrong_args("--symmetric --sign --encrypt [filename]");
4426 else if(opt.s2k_mode==0)
4427 log_error(_("you cannot use --symmetric --sign --encrypt"
4428 " with --s2k-mode 0\n"));
4430 log_error(_("you cannot use --symmetric --sign --encrypt"
4432 gnupg_compliance_option_string (opt.compliance));
4437 sl = xmalloc_clear( sizeof *sl + strlen(fname));
4438 strcpy(sl->d, fname);
4442 if ((rc = sign_file (ctrl, sl, detached_sig, locusr,
4445 write_status_failure ("sign-encrypt", rc);
4446 log_error("%s: symmetric+sign+encrypt failed: %s\n",
4447 print_fname_stdin(fname), gpg_strerror (rc) );
4453 case aSignSym: /* sign and conventionally encrypt the given file */
4455 wrong_args("--sign --symmetric [filename]");
4456 rc = sign_symencrypt_file (ctrl, fname, locusr);
4459 write_status_failure ("sign-symencrypt", rc);
4460 log_error("%s: sign+symmetric failed: %s\n",
4461 print_fname_stdin(fname), gpg_strerror (rc) );
4465 case aClearsign: /* make a clearsig */
4467 wrong_args("--clear-sign [filename]");
4468 if( (rc = clearsign_file (ctrl, fname, locusr, NULL)) )
4470 write_status_failure ("sign", rc);
4471 log_error("%s: clear-sign failed: %s\n",
4472 print_fname_stdin(fname), gpg_strerror (rc) );
4479 if ((rc = verify_files (ctrl, argc, argv)))
4480 log_error("verify files failed: %s\n", gpg_strerror (rc) );
4484 if ((rc = verify_signatures (ctrl, argc, argv)))
4485 log_error("verify signatures failed: %s\n", gpg_strerror (rc) );
4488 write_status_failure ("verify", rc);
4493 decrypt_messages (ctrl, argc, argv);
4497 wrong_args("--decrypt [filename]");
4498 if( (rc = decrypt_message (ctrl, fname) ))
4500 write_status_failure ("decrypt", rc);
4501 log_error("decrypt_message failed: %s\n", gpg_strerror (rc) );
4507 case aQuickLSignKey:
4512 wrong_args ("--quick-[l]sign-key fingerprint [userids]");
4513 fpr = *argv++; argc--;
4515 for( ; argc; argc--, argv++)
4516 append_to_strlist2 (&sl, *argv, utf8_strings);
4517 keyedit_quick_sign (ctrl, fpr, sl, locusr, (cmd == aQuickLSignKey));
4524 const char *userid, *siguserid;
4527 wrong_args ("--quick-revoke-sig USER-ID SIG-USER-ID [userids]");
4528 userid = *argv++; argc--;
4529 siguserid = *argv++; argc--;
4531 for( ; argc; argc--, argv++)
4532 append_to_strlist2 (&sl, *argv, utf8_strings);
4533 keyedit_quick_revsig (ctrl, userid, siguserid, sl);
4540 wrong_args("--sign-key user-id");
4544 wrong_args("--lsign-key user-id");
4550 append_to_strlist(&sl,"sign");
4551 else if(cmd==aLSignKey)
4552 append_to_strlist(&sl,"lsign");
4556 append_to_strlist( &sl, "save" );
4557 username = make_username( fname );
4558 keyedit_menu (ctrl, username, locusr, sl, 0, 0 );
4563 case aEditKey: /* Edit a key signature */
4565 wrong_args("--edit-key user-id [commands]");
4566 username = make_username( fname );
4569 for( argc--, argv++ ; argc; argc--, argv++ )
4570 append_to_strlist( &sl, *argv );
4571 keyedit_menu (ctrl, username, locusr, sl, 0, 1 );
4575 keyedit_menu (ctrl, username, locusr, NULL, 0, 1 );
4581 wrong_args("--change-passphrase <user-id>");
4584 username = make_username (fname);
4585 keyedit_passwd (ctrl, username);
4591 case aDeleteSecretKeys:
4592 case aDeleteSecretAndPublicKeys:
4594 /* Print a note if the user did not specify any key. */
4595 if (!argc && !opt.quiet)
4596 log_info (_("Note: %s\n"), gpg_strerror (GPG_ERR_NO_KEY));
4597 /* I'm adding these in reverse order as add_to_strlist2
4598 reverses them again, and it's easier to understand in the
4600 for( ; argc; argc-- )
4601 add_to_strlist2( &sl, argv[argc-1], utf8_strings );
4602 delete_keys (ctrl, sl,
4603 cmd==aDeleteSecretKeys, cmd==aDeleteSecretAndPublicKeys);
4608 opt.check_sigs = 1; /* fall through */
4610 opt.list_sigs = 1; /* fall through */
4613 for( ; argc; argc--, argv++ )
4614 add_to_strlist2( &sl, *argv, utf8_strings );
4615 public_key_list (ctrl, sl, 0, 0);
4618 case aListSecretKeys:
4620 for( ; argc; argc--, argv++ )
4621 add_to_strlist2( &sl, *argv, utf8_strings );
4622 secret_key_list (ctrl, sl);
4626 case aLocateExtKeys:
4628 for (; argc; argc--, argv++)
4629 add_to_strlist2( &sl, *argv, utf8_strings );
4630 if (cmd == aLocateExtKeys && akl_empty_or_only_local ())
4632 /* This is a kludge to let --locate-external-keys even
4633 * work if the config file has --no-auto-key-locate. This
4634 * better matches the expectations of the user. */
4636 parse_auto_key_locate (DEFAULT_AKL_LIST);
4638 public_key_list (ctrl, sl, 1, cmd == aLocateExtKeys);
4646 const char *x_algo, *x_usage, *x_expire;
4648 if (argc < 1 || argc > 4)
4649 wrong_args("--quick-generate-key USER-ID [ALGO [USAGE [EXPIRE]]]");
4650 username = make_username (fname);
4657 x_algo = *argv++; argc--;
4660 x_usage = *argv++; argc--;
4663 x_expire = *argv++; argc--;
4667 quick_generate_keypair (ctrl, username, x_algo, x_usage, x_expire);
4672 case aKeygen: /* generate a key */
4675 wrong_args("--generate-key [parameterfile]");
4676 generate_keypair (ctrl, 0, argc? *argv : NULL, NULL, 0);
4679 if (opt.command_fd != -1 && argc)
4682 wrong_args("--generate-key [parameterfile]");
4685 generate_keypair (ctrl, 0, argc? *argv : NULL, NULL, 0);
4688 wrong_args ("--generate-key");
4690 generate_keypair (ctrl, 0, NULL, NULL, 0);
4694 case aFullKeygen: /* Generate a key with all options. */
4698 wrong_args ("--full-generate-key [parameterfile]");
4699 generate_keypair (ctrl, 1, argc? *argv : NULL, NULL, 0);
4704 wrong_args("--full-generate-key");
4705 generate_keypair (ctrl, 1, NULL, NULL, 0);
4711 const char *uid, *newuid;
4714 wrong_args ("--quick-add-uid USER-ID NEW-USER-ID");
4715 uid = *argv++; argc--;
4716 newuid = *argv++; argc--;
4717 keyedit_quick_adduid (ctrl, uid, newuid);
4723 const char *x_fpr, *x_algo, *x_usage, *x_expire;
4725 if (argc < 1 || argc > 4)
4726 wrong_args ("--quick-add-key FINGERPRINT [ALGO [USAGE [EXPIRE]]]");
4727 x_fpr = *argv++; argc--;
4733 x_algo = *argv++; argc--;
4736 x_usage = *argv++; argc--;
4739 x_expire = *argv++; argc--;
4743 keyedit_quick_addkey (ctrl, x_fpr, x_algo, x_usage, x_expire);
4749 const char *uid, *uidtorev;
4752 wrong_args ("--quick-revoke-uid USER-ID USER-ID-TO-REVOKE");
4753 uid = *argv++; argc--;
4754 uidtorev = *argv++; argc--;
4755 keyedit_quick_revuid (ctrl, uid, uidtorev);
4759 case aQuickSetExpire:
4761 const char *x_fpr, *x_expire;
4764 wrong_args ("--quick-set-exipre FINGERPRINT EXPIRE [SUBKEY-FPRS]");
4765 x_fpr = *argv++; argc--;
4766 x_expire = *argv++; argc--;
4767 keyedit_quick_set_expire (ctrl, x_fpr, x_expire, argv);
4771 case aQuickSetPrimaryUid:
4773 const char *uid, *primaryuid;
4776 wrong_args ("--quick-set-primary-uid USER-ID PRIMARY-USER-ID");
4777 uid = *argv++; argc--;
4778 primaryuid = *argv++; argc--;
4779 keyedit_quick_set_primary (ctrl, uid, primaryuid);
4784 opt.import_options |= IMPORT_FAST; /* fall through */
4787 import_keys (ctrl, argc? argv:NULL, argc, NULL,
4788 opt.import_options, opt.key_origin, opt.key_origin_url);
4791 /* TODO: There are a number of command that use this same
4792 "make strlist, call function, report error, free strlist"
4793 pattern. Join them together here and avoid all that
4800 for( ; argc; argc--, argv++ )
4801 append_to_strlist2( &sl, *argv, utf8_strings );
4802 if( cmd == aSendKeys )
4803 rc = keyserver_export (ctrl, sl );
4804 else if( cmd == aRecvKeys )
4805 rc = keyserver_import (ctrl, sl );
4808 export_stats_t stats = export_new_stats ();
4809 rc = export_pubkeys (ctrl, sl, opt.export_options, stats);
4810 export_print_stats (stats);
4811 export_release_stats (stats);
4817 write_status_failure ("send-keys", rc);
4818 log_error(_("keyserver send failed: %s\n"),gpg_strerror (rc));
4820 else if(cmd==aRecvKeys)
4822 write_status_failure ("recv-keys", rc);
4823 log_error (_("keyserver receive failed: %s\n"),
4828 write_status_failure ("export", rc);
4829 log_error (_("key export failed: %s\n"), gpg_strerror (rc));
4837 wrong_args ("--export-ssh-key <user-id>");
4838 rc = export_ssh_key (ctrl, argv[0]);
4841 write_status_failure ("export-ssh-key", rc);
4842 log_error (_("export as ssh key failed: %s\n"), gpg_strerror (rc));
4848 for (; argc; argc--, argv++)
4849 append_to_strlist2 (&sl, *argv, utf8_strings);
4850 rc = keyserver_search (ctrl, sl);
4853 write_status_failure ("search-keys", rc);
4854 log_error (_("keyserver search failed: %s\n"), gpg_strerror (rc));
4861 for( ; argc; argc--, argv++ )
4862 append_to_strlist2( &sl, *argv, utf8_strings );
4863 rc = keyserver_refresh (ctrl, sl);
4866 write_status_failure ("refresh-keys", rc);
4867 log_error (_("keyserver refresh failed: %s\n"),gpg_strerror (rc));
4874 for( ; argc; argc--, argv++ )
4875 append_to_strlist2( &sl, *argv, utf8_strings );
4876 rc = keyserver_fetch (ctrl, sl, opt.key_origin);
4880 write_status_failure ("fetch-keys", rc);
4881 log_error ("key fetch failed: %s\n",gpg_strerror (rc));
4882 if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
4883 g10_exit (1); /* In this case return 1 and not 2. */
4889 for( ; argc; argc--, argv++ )
4890 add_to_strlist2( &sl, *argv, utf8_strings );
4892 export_stats_t stats = export_new_stats ();
4893 export_seckeys (ctrl, sl, opt.export_options, stats);
4894 export_print_stats (stats);
4895 export_release_stats (stats);
4900 case aExportSecretSub:
4902 for( ; argc; argc--, argv++ )
4903 add_to_strlist2( &sl, *argv, utf8_strings );
4905 export_stats_t stats = export_new_stats ();
4906 export_secsubkeys (ctrl, sl, opt.export_options, stats);
4907 export_print_stats (stats);
4908 export_release_stats (stats);
4915 wrong_args("--generate-revocation user-id");
4916 username = make_username(*argv);
4917 gen_revoke (ctrl, username );
4923 wrong_args ("--generate-designated-revocation user-id");
4924 username = make_username (*argv);
4925 gen_desig_revoke (ctrl, username, locusr);
4931 wrong_args("--dearmor [file]");
4932 rc = dearmor_file( argc? *argv: NULL );
4935 write_status_failure ("dearmor", rc);
4936 log_error (_("dearmoring failed: %s\n"), gpg_strerror (rc));
4942 wrong_args("--enarmor [file]");
4943 rc = enarmor_file( argc? *argv: NULL );
4946 write_status_failure ("enarmor", rc);
4947 log_error (_("enarmoring failed: %s\n"), gpg_strerror (rc));
4954 { int mode = argc < 2 ? 0 : atoi(*argv);
4956 if( mode == 1 && argc == 2 ) {
4957 mpi_print (es_stdout,
4958 generate_public_prime( atoi(argv[1]) ), 1);
4960 else if( mode == 2 && argc == 3 ) {
4961 mpi_print (es_stdout, generate_elg_prime(
4963 atoi(argv[2]), NULL,NULL ), 1);
4965 else if( mode == 3 && argc == 3 ) {
4967 mpi_print (es_stdout, generate_elg_prime(
4969 atoi(argv[2]), NULL,&factors ), 1);
4970 es_putc ('\n', es_stdout);
4971 mpi_print (es_stdout, factors[0], 1 ); /* print q */
4973 else if( mode == 4 && argc == 3 ) {
4974 MPI g = mpi_alloc(1);
4975 mpi_print (es_stdout, generate_elg_prime(
4977 atoi(argv[2]), g, NULL ), 1);
4978 es_putc ('\n', es_stdout);
4979 mpi_print (es_stdout, g, 1 );
4983 wrong_args("--gen-prime mode bits [qbits] ");
4984 es_putc ('\n', es_stdout);
4987 wrong_args("--gen-prime not yet supported ");
4992 int level = argc ? atoi(*argv):0;
4993 int count = argc > 1 ? atoi(argv[1]): 0;
4994 int endless = !count;
4995 int hexhack = (level == 16);
5000 if (argc < 1 || argc > 2 || level < 0 || level > 2 || count < 0)
5001 wrong_args ("--gen-random 0|1|2 [count]");
5003 while (endless || count)
5006 /* We need a multiple of 3, so that in case of armored
5007 * output we get a correct string. No linefolding is
5008 * done, as it is best to leave this to other tools */
5009 size_t n = !endless && count < 99? count : 99;
5012 p = gcry_random_bytes (n, level);
5013 #ifdef HAVE_DOSISH_SYSTEM
5014 setmode ( fileno(stdout), O_BINARY );
5018 for (nn = 0; nn < n; nn++)
5019 es_fprintf (es_stdout, "%02x", p[nn]);
5023 char *tmp = make_radix64_string (p, n);
5024 es_fputs (tmp, es_stdout);
5027 es_putc ('=', es_stdout);
5029 es_putc ('=', es_stdout);
5033 es_fwrite( p, n, 1, es_stdout );
5039 if (opt.armor || hexhack)
5040 es_putc ('\n', es_stdout);
5046 wrong_args("--print-md algo [files]");
5048 int all_algos = (**argv=='*' && !(*argv)[1]);
5049 int algo = all_algos? 0 : gcry_md_map_name (*argv);
5051 if( !algo && !all_algos )
5052 log_error(_("invalid hash algorithm '%s'\n"), *argv );
5056 print_mds(NULL, algo);
5058 for(; argc; argc--, argv++ )
5059 print_mds(*argv, algo);
5065 case aPrintMDs: /* old option */
5069 for(; argc; argc--, argv++ )
5074 #ifndef NO_TRUST_MODELS
5077 list_trustdb (ctrl, es_stdout, NULL);
5079 for( ; argc; argc--, argv++ )
5080 list_trustdb (ctrl, es_stdout, *argv );
5084 case aUpdateTrustDB:
5086 wrong_args("--update-trustdb");
5087 update_trustdb (ctrl);
5091 /* Old versions allowed for arguments - ignore them */
5092 check_trustdb (ctrl);
5096 how_to_fix_the_trustdb ();
5099 case aListTrustPath:
5101 wrong_args("--list-trust-path <user-ids>");
5102 for( ; argc; argc--, argv++ ) {
5103 username = make_username( *argv );
5104 list_trust_path( username );
5109 case aExportOwnerTrust:
5111 wrong_args("--export-ownertrust");
5112 export_ownertrust (ctrl);
5115 case aImportOwnerTrust:
5117 wrong_args("--import-ownertrust [file]");
5118 import_ownertrust (ctrl, argc? *argv:NULL );
5120 #endif /*!NO_TRUST_MODELS*/
5122 case aRebuildKeydbCaches:
5124 wrong_args ("--rebuild-keydb-caches");
5125 keydb_rebuild_caches (ctrl, 1);
5128 #ifdef ENABLE_CARD_SUPPORT
5131 card_status (ctrl, es_stdout, NULL);
5133 card_status (ctrl, es_stdout, *argv);
5135 wrong_args ("--card-status [serialno]");
5141 for (argc--, argv++ ; argc; argc--, argv++)
5142 append_to_strlist (&sl, *argv);
5143 card_edit (ctrl, sl);
5147 card_edit (ctrl, NULL);
5154 change_pin (atoi (*argv),1);
5156 wrong_args ("--change-pin [no]");
5158 #endif /* ENABLE_CARD_SUPPORT*/
5162 char *str=collapse_args(argc,argv);
5168 case aListGcryptConfig:
5169 /* Fixme: It would be nice to integrate that with
5170 --list-config but unfortunately there is no way yet to have
5171 libgcrypt print it to an estream for further parsing. */
5172 gcry_control (GCRYCTL_PRINT_CONFIG, stdout);
5183 wrong_args ("--tofu-policy POLICY KEYID [KEYID...]");
5185 policy = parse_tofu_policy (argv[0]);
5187 hd = keydb_new (ctrl);
5190 write_status_failure ("tofu-driver", gpg_error(GPG_ERR_GENERAL));
5194 tofu_begin_batch_update (ctrl);
5196 for (i = 1; i < argc; i ++)
5198 KEYDB_SEARCH_DESC desc;
5201 rc = classify_user_id (argv[i], &desc, 0);
5204 log_error (_("error parsing key specification '%s': %s\n"),
5205 argv[i], gpg_strerror (rc));
5206 write_status_failure ("tofu-driver", rc);
5210 if (! (desc.mode == KEYDB_SEARCH_MODE_SHORT_KID
5211 || desc.mode == KEYDB_SEARCH_MODE_LONG_KID
5212 || desc.mode == KEYDB_SEARCH_MODE_FPR
5213 || desc.mode == KEYDB_SEARCH_MODE_KEYGRIP))
5215 log_error (_("'%s' does not appear to be a valid"
5216 " key ID, fingerprint or keygrip\n"),
5218 write_status_failure ("tofu-driver",
5219 gpg_error(GPG_ERR_GENERAL));
5223 rc = keydb_search_reset (hd);
5226 /* This should not happen, thus no need to tranalate
5228 log_error ("keydb_search_reset failed: %s\n",
5230 write_status_failure ("tofu-driver", rc);
5234 rc = keydb_search (hd, &desc, 1, NULL);
5237 log_error (_("key \"%s\" not found: %s\n"), argv[i],
5239 write_status_failure ("tofu-driver", rc);
5243 rc = keydb_get_keyblock (hd, &kb);
5246 log_error (_("error reading keyblock: %s\n"),
5248 write_status_failure ("tofu-driver", rc);
5252 merge_keys_and_selfsig (ctrl, kb);
5253 if (tofu_set_policy (ctrl, kb, policy))
5255 write_status_failure ("tofu-driver", rc);
5259 release_kbnode (kb);
5262 tofu_end_batch_update (ctrl);
5271 log_info (_("WARNING: no command supplied."
5272 " Trying to guess what you mean ...\n"));
5276 wrong_args("[filename]");
5277 /* Issue some output for the unix newbie */
5278 if (!fname && !opt.outfile
5279 && gnupg_isatty (fileno (stdin))
5280 && gnupg_isatty (fileno (stdout))
5281 && gnupg_isatty (fileno (stderr)))
5282 log_info(_("Go ahead and type your message ...\n"));
5284 a = iobuf_open(fname);
5285 if (a && is_secured_file (iobuf_get_fd (a)))
5289 gpg_err_set_errno (EPERM);
5292 log_error(_("can't open '%s'\n"), print_fname_stdin(fname));
5295 if( !opt.no_armor ) {
5296 if( use_armor_filter( a ) ) {
5297 afx = new_armor_context ();
5298 push_armor_filter (afx, a);
5301 if( cmd == aListPackets ) {
5303 set_packet_list_mode(1);
5305 rc = proc_packets (ctrl, NULL, a );
5308 write_status_failure ("-", rc);
5309 log_error ("processing message failed: %s\n",
5318 gpg_deinit_default_ctrl (ctrl);
5320 release_armor_context (afx);
5321 FREE_STRLIST(remusr);
5322 FREE_STRLIST(locusr);
5324 return 8; /*NEVER REACHED*/
5328 /* Note: This function is used by signal handlers!. */
5330 emergency_cleanup (void)
5332 gcry_control (GCRYCTL_TERM_SECMEM );
5339 /* If we had an error but not printed an error message, do it now.
5340 * Note that write_status_failure will never print a second failure
5343 write_status_failure ("gpg-exit", gpg_error (GPG_ERR_GENERAL));
5345 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
5349 if ( (opt.debug & DBG_MEMSTAT_VALUE) )
5351 keydb_dump_stats ();
5352 sig_check_dump_stats ();
5353 objcache_dump_stats ();
5354 gcry_control (GCRYCTL_DUMP_MEMORY_STATS);
5355 gcry_control (GCRYCTL_DUMP_RANDOM_STATS);
5358 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
5360 gnupg_block_all_signals ();
5361 emergency_cleanup ();
5363 rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0;
5368 /* Pretty-print hex hashes. This assumes at least an 80-character
5369 display, but there are a few other similar assumptions in the
5372 print_hex (gcry_md_hd_t md, int algo, const char *fname)
5374 int i,n,count,indent=0;
5378 indent = es_printf("%s: ",fname);
5386 if (algo==DIGEST_ALGO_RMD160)
5387 indent += es_printf("RMD160 = ");
5389 indent += es_printf("%6s = ", gcry_md_algo_name (algo));
5395 p = gcry_md_read (md, algo);
5396 n = gcry_md_get_algo_dlen (algo);
5398 count += es_printf ("%02X",*p++);
5400 for(i=1;i<n;i++,p++)
5406 es_printf ("\n%*s",indent," ");
5410 count += es_printf(" ");
5413 count += es_printf(" ");
5421 es_printf ("\n%*s",indent," ");
5425 count += es_printf(" ");
5429 count += es_printf(" ");
5437 es_printf ("\n%*s",indent," ");
5441 count += es_printf(" ");
5445 count += es_printf("%02X",*p);
5452 print_hashline( gcry_md_hd_t md, int algo, const char *fname )
5459 for (p = fname; *p; p++ )
5461 if ( *p <= 32 || *p > 127 || *p == ':' || *p == '%' )
5462 es_printf ("%%%02X", *p );
5464 es_putc (*p, es_stdout);
5467 es_putc (':', es_stdout);
5468 es_printf ("%d:", algo);
5469 p = gcry_md_read (md, algo);
5470 n = gcry_md_get_algo_dlen (algo);
5471 for(i=0; i < n ; i++, p++ )
5472 es_printf ("%02X", *p);
5473 es_fputs (":\n", es_stdout);
5478 print_mds( const char *fname, int algo )
5492 fp = es_fopen (fname, "rb" );
5493 if (fp && is_secured_file (es_fileno (fp)))
5497 gpg_err_set_errno (EPERM);
5502 log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
5506 gcry_md_open (&md, 0, 0);
5508 gcry_md_enable (md, algo);
5511 if (!gcry_md_test_algo (GCRY_MD_MD5))
5512 gcry_md_enable (md, GCRY_MD_MD5);
5513 gcry_md_enable (md, GCRY_MD_SHA1);
5514 if (!gcry_md_test_algo (GCRY_MD_RMD160))
5515 gcry_md_enable (md, GCRY_MD_RMD160);
5516 if (!gcry_md_test_algo (GCRY_MD_SHA224))
5517 gcry_md_enable (md, GCRY_MD_SHA224);
5518 if (!gcry_md_test_algo (GCRY_MD_SHA256))
5519 gcry_md_enable (md, GCRY_MD_SHA256);
5520 if (!gcry_md_test_algo (GCRY_MD_SHA384))
5521 gcry_md_enable (md, GCRY_MD_SHA384);
5522 if (!gcry_md_test_algo (GCRY_MD_SHA512))
5523 gcry_md_enable (md, GCRY_MD_SHA512);
5526 while ((n=es_fread (buf, 1, DIM(buf), fp)))
5527 gcry_md_write (md, buf, n);
5530 log_error ("%s: %s\n", fname?fname:"[stdin]", strerror(errno));
5534 if (opt.with_colons)
5537 print_hashline (md, algo, fname);
5540 if (!gcry_md_test_algo (GCRY_MD_MD5))
5541 print_hashline( md, GCRY_MD_MD5, fname );
5542 print_hashline( md, GCRY_MD_SHA1, fname );
5543 if (!gcry_md_test_algo (GCRY_MD_RMD160))
5544 print_hashline( md, GCRY_MD_RMD160, fname );
5545 if (!gcry_md_test_algo (GCRY_MD_SHA224))
5546 print_hashline (md, GCRY_MD_SHA224, fname);
5547 if (!gcry_md_test_algo (GCRY_MD_SHA256))
5548 print_hashline( md, GCRY_MD_SHA256, fname );
5549 if (!gcry_md_test_algo (GCRY_MD_SHA384))
5550 print_hashline ( md, GCRY_MD_SHA384, fname );
5551 if (!gcry_md_test_algo (GCRY_MD_SHA512))
5552 print_hashline ( md, GCRY_MD_SHA512, fname );
5558 print_hex (md, -algo, fname);
5561 if (!gcry_md_test_algo (GCRY_MD_MD5))
5562 print_hex (md, GCRY_MD_MD5, fname);
5563 print_hex (md, GCRY_MD_SHA1, fname );
5564 if (!gcry_md_test_algo (GCRY_MD_RMD160))
5565 print_hex (md, GCRY_MD_RMD160, fname );
5566 if (!gcry_md_test_algo (GCRY_MD_SHA224))
5567 print_hex (md, GCRY_MD_SHA224, fname);
5568 if (!gcry_md_test_algo (GCRY_MD_SHA256))
5569 print_hex (md, GCRY_MD_SHA256, fname );
5570 if (!gcry_md_test_algo (GCRY_MD_SHA384))
5571 print_hex (md, GCRY_MD_SHA384, fname );
5572 if (!gcry_md_test_algo (GCRY_MD_SHA512))
5573 print_hex (md, GCRY_MD_SHA512, fname );
5585 * Check the supplied name,value string and add it to the notation
5586 * data to be used for signatures. which==0 for sig notations, and 1
5587 * for cert notations.
5590 add_notation_data( const char *string, int which )
5592 struct notation *notation;
5594 notation=string_to_notation(string,utf8_strings);
5599 notation->next=opt.cert_notations;
5600 opt.cert_notations=notation;
5604 notation->next=opt.sig_notations;
5605 opt.sig_notations=notation;
5611 add_policy_url( const char *string, int which )
5613 unsigned int i,critical=0;
5622 for(i=0;i<strlen(string);i++)
5623 if( !isascii (string[i]) || iscntrl(string[i]))
5626 if(i==0 || i<strlen(string))
5629 log_error(_("the given certification policy URL is invalid\n"));
5631 log_error(_("the given signature policy URL is invalid\n"));
5635 sl=add_to_strlist( &opt.cert_policy_url, string );
5637 sl=add_to_strlist( &opt.sig_policy_url, string );
5644 add_keyserver_url( const char *string, int which )
5646 unsigned int i,critical=0;
5655 for(i=0;i<strlen(string);i++)
5656 if( !isascii (string[i]) || iscntrl(string[i]))
5659 if(i==0 || i<strlen(string))
5664 log_error(_("the given preferred keyserver URL is invalid\n"));
5670 sl=add_to_strlist( &opt.sig_keyserver_url, string );
5678 read_sessionkey_from_fd (int fd)
5683 if (! gnupg_fd_valid (fd))
5684 log_fatal ("override-session-key-fd is invalid: %s\n", strerror (errno));
5686 for (line = NULL, i = len = 100; ; i++ )
5692 line = xmalloc_secure (len);
5695 memcpy (line, tmp, i);
5701 if (read (fd, line + i, 1) != 1 || line[i] == '\n')
5705 log_debug ("seskey: %s\n", line);
5706 gpgrt_annotate_leaked_object (line);
5707 opt.override_session_key = line;