1 /* gpg.c - The GnuPG utility (main for gpg)
2 * Copyright (C) 1998-2019 Free Software Foundation, Inc.
3 * Copyright (C) 1997-2019 Werner Koch
4 * Copyright (C) 2015-2019 g10 Code GmbH
6 * This file is part of GnuPG.
8 * GnuPG is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * GnuPG is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, see <https://www.gnu.org/licenses/>.
30 #include <sys/stat.h> /* for stat() */
33 #ifdef HAVE_W32_SYSTEM
34 # ifdef HAVE_WINSOCK2_H
35 # include <winsock2.h>
40 #define INCLUDED_BY_MAIN_MODULE 1
43 #include "../common/iobuf.h"
44 #include "../common/util.h"
46 #include "../common/membuf.h"
52 #include "../common/ttyio.h"
53 #include "../common/i18n.h"
54 #include "../common/sysutils.h"
55 #include "../common/status.h"
56 #include "keyserver-internal.h"
58 #include "../common/gc-opt-flags.h"
59 #include "../common/asshelp.h"
60 #include "call-dirmngr.h"
62 #include "../common/init.h"
63 #include "../common/mbox-util.h"
64 #include "../common/shareddefs.h"
65 #include "../common/compliance.h"
67 #if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
68 #define MY_O_BINARY O_BINARY
81 enum cmd_and_opt_values
90 oHiddenRecipientFile = 'F',
97 oHiddenRecipient = 'R',
104 aListSecretKeys = 'K',
141 aDeleteSecretAndPublicKeys,
199 oWithSubkeyFingerprint,
254 oBZ2DecompressLowmem,
278 oSkipHiddenRecipients,
279 oNoSkipHiddenRecipients,
292 oUseEmbeddedFilename,
293 oNoUseEmbeddedFilename,
326 oEncryptToDefaultKey,
333 oAllowNonSelfsignedUID,
334 oNoAllowNonSelfsignedUID,
337 oAllowSecretKeyImport,
338 oEnableSpecialFilenames,
350 oOverrideSessionKeyFD,
360 oNoExpensiveTrustChecks,
366 oPreservePermissions,
367 oDefaultPreferenceList,
368 oDefaultKeyserverURL,
369 oPersonalCipherPreferences,
370 oPersonalDigestPreferences,
371 oPersonalCompressPreferences,
387 oNoMangleDosFilenames,
388 oEnableProgressFilter,
391 oExitOnStatusWriteError,
392 oLimitCardInsertTries,
401 oAllowMultisigVerification,
406 oAllowMultipleMessages,
407 oNoAllowMultipleMessages,
408 oAllowWeakDigestAlgos,
429 static ARGPARSE_OPTS opts[] = {
431 ARGPARSE_group (300, N_("@Commands:\n ")),
433 ARGPARSE_c (aSign, "sign", N_("make a signature")),
434 ARGPARSE_c (aClearsign, "clear-sign", N_("make a clear text signature")),
435 ARGPARSE_c (aClearsign, "clearsign", "@"),
436 ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")),
437 ARGPARSE_c (aEncr, "encrypt", N_("encrypt data")),
438 ARGPARSE_c (aEncrFiles, "encrypt-files", "@"),
439 ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")),
440 ARGPARSE_c (aStore, "store", "@"),
441 ARGPARSE_c (aDecrypt, "decrypt", N_("decrypt data (default)")),
442 ARGPARSE_c (aDecryptFiles, "decrypt-files", "@"),
443 ARGPARSE_c (aVerify, "verify" , N_("verify a signature")),
444 ARGPARSE_c (aVerifyFiles, "verify-files" , "@" ),
445 ARGPARSE_c (aListKeys, "list-keys", N_("list keys")),
446 ARGPARSE_c (aListKeys, "list-public-keys", "@" ),
447 ARGPARSE_c (aListSigs, "list-signatures", N_("list keys and signatures")),
448 ARGPARSE_c (aListSigs, "list-sigs", "@"),
449 ARGPARSE_c (aCheckKeys, "check-signatures",
450 N_("list and check key signatures")),
451 ARGPARSE_c (aCheckKeys, "check-sigs", "@"),
452 ARGPARSE_c (oFingerprint, "fingerprint", N_("list keys and fingerprints")),
453 ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")),
454 ARGPARSE_c (aKeygen, "generate-key",
455 N_("generate a new key pair")),
456 ARGPARSE_c (aKeygen, "gen-key", "@"),
457 ARGPARSE_c (aQuickKeygen, "quick-generate-key" ,
458 N_("quickly generate a new key pair")),
459 ARGPARSE_c (aQuickKeygen, "quick-gen-key", "@"),
460 ARGPARSE_c (aQuickAddUid, "quick-add-uid",
461 N_("quickly add a new user-id")),
462 ARGPARSE_c (aQuickAddUid, "quick-adduid", "@"),
463 ARGPARSE_c (aQuickAddKey, "quick-add-key", "@"),
464 ARGPARSE_c (aQuickAddKey, "quick-addkey", "@"),
465 ARGPARSE_c (aQuickRevUid, "quick-revoke-uid",
466 N_("quickly revoke a user-id")),
467 ARGPARSE_c (aQuickRevUid, "quick-revuid", "@"),
468 ARGPARSE_c (aQuickSetExpire, "quick-set-expire",
469 N_("quickly set a new expiration date")),
470 ARGPARSE_c (aQuickSetPrimaryUid, "quick-set-primary-uid", "@"),
471 ARGPARSE_c (aFullKeygen, "full-generate-key" ,
472 N_("full featured key pair generation")),
473 ARGPARSE_c (aFullKeygen, "full-gen-key", "@"),
474 ARGPARSE_c (aGenRevoke, "generate-revocation",
475 N_("generate a revocation certificate")),
476 ARGPARSE_c (aGenRevoke, "gen-revoke", "@"),
477 ARGPARSE_c (aDeleteKeys,"delete-keys",
478 N_("remove keys from the public keyring")),
479 ARGPARSE_c (aDeleteSecretKeys, "delete-secret-keys",
480 N_("remove keys from the secret keyring")),
481 ARGPARSE_c (aQuickSignKey, "quick-sign-key" ,
482 N_("quickly sign a key")),
483 ARGPARSE_c (aQuickLSignKey, "quick-lsign-key",
484 N_("quickly sign a key locally")),
485 ARGPARSE_c (aSignKey, "sign-key" ,N_("sign a key")),
486 ARGPARSE_c (aLSignKey, "lsign-key" ,N_("sign a key locally")),
487 ARGPARSE_c (aEditKey, "edit-key" ,N_("sign or edit a key")),
488 ARGPARSE_c (aEditKey, "key-edit" ,"@"),
489 ARGPARSE_c (aPasswd, "change-passphrase", N_("change a passphrase")),
490 ARGPARSE_c (aPasswd, "passwd", "@"),
491 ARGPARSE_c (aDesigRevoke, "generate-designated-revocation", "@"),
492 ARGPARSE_c (aDesigRevoke, "desig-revoke","@" ),
493 ARGPARSE_c (aExport, "export" , N_("export keys") ),
494 ARGPARSE_c (aSendKeys, "send-keys" , N_("export keys to a keyserver") ),
495 ARGPARSE_c (aRecvKeys, "receive-keys" , N_("import keys from a keyserver") ),
496 ARGPARSE_c (aRecvKeys, "recv-keys" , "@"),
497 ARGPARSE_c (aSearchKeys, "search-keys" ,
498 N_("search for keys on a keyserver") ),
499 ARGPARSE_c (aRefreshKeys, "refresh-keys",
500 N_("update all keys from a keyserver")),
501 ARGPARSE_c (aLocateKeys, "locate-keys", "@"),
502 ARGPARSE_c (aFetchKeys, "fetch-keys" , "@" ),
503 ARGPARSE_c (aShowKeys, "show-keys" , "@" ),
504 ARGPARSE_c (aExportSecret, "export-secret-keys" , "@" ),
505 ARGPARSE_c (aExportSecretSub, "export-secret-subkeys" , "@" ),
506 ARGPARSE_c (aExportSshKey, "export-ssh-key", "@" ),
507 ARGPARSE_c (aImport, "import", N_("import/merge keys")),
508 ARGPARSE_c (aFastImport, "fast-import", "@"),
509 #ifdef ENABLE_CARD_SUPPORT
510 ARGPARSE_c (aCardStatus, "card-status", N_("print the card status")),
511 ARGPARSE_c (aCardEdit, "edit-card", N_("change data on a card")),
512 ARGPARSE_c (aCardEdit, "card-edit", "@"),
513 ARGPARSE_c (aChangePIN, "change-pin", N_("change a card's PIN")),
515 ARGPARSE_c (aListConfig, "list-config", "@"),
516 ARGPARSE_c (aListGcryptConfig, "list-gcrypt-config", "@"),
517 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@" ),
518 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@" ),
519 ARGPARSE_c (aListPackets, "list-packets","@"),
521 #ifndef NO_TRUST_MODELS
522 ARGPARSE_c (aExportOwnerTrust, "export-ownertrust", "@"),
523 ARGPARSE_c (aImportOwnerTrust, "import-ownertrust", "@"),
524 ARGPARSE_c (aUpdateTrustDB,"update-trustdb",
525 N_("update the trust database")),
526 ARGPARSE_c (aCheckTrustDB, "check-trustdb", "@"),
527 ARGPARSE_c (aFixTrustDB, "fix-trustdb", "@"),
530 ARGPARSE_c (aDeArmor, "dearmor", "@"),
531 ARGPARSE_c (aDeArmor, "dearmour", "@"),
532 ARGPARSE_c (aEnArmor, "enarmor", "@"),
533 ARGPARSE_c (aEnArmor, "enarmour", "@"),
534 ARGPARSE_c (aPrintMD, "print-md", N_("print message digests")),
535 ARGPARSE_c (aPrimegen, "gen-prime", "@" ),
536 ARGPARSE_c (aGenRandom,"gen-random", "@" ),
537 ARGPARSE_c (aServer, "server", N_("run in server mode")),
538 ARGPARSE_c (aTOFUPolicy, "tofu-policy",
539 N_("|VALUE|set the TOFU policy for a key")),
541 ARGPARSE_group (301, N_("@\nOptions:\n ")),
543 ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")),
544 ARGPARSE_s_n (oArmor, "armour", "@"),
546 ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")),
547 ARGPARSE_s_s (oHiddenRecipient, "hidden-recipient", "@"),
548 ARGPARSE_s_s (oRecipientFile, "recipient-file", "@"),
549 ARGPARSE_s_s (oHiddenRecipientFile, "hidden-recipient-file", "@"),
550 ARGPARSE_s_s (oRecipient, "remote-user", "@"), /* (old option name) */
551 ARGPARSE_s_s (oDefRecipient, "default-recipient", "@"),
552 ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", "@"),
553 ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"),
555 ARGPARSE_s_s (oTempDir, "temp-directory", "@"),
556 ARGPARSE_s_s (oExecPath, "exec-path", "@"),
557 ARGPARSE_s_s (oEncryptTo, "encrypt-to", "@"),
558 ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"),
559 ARGPARSE_s_s (oHiddenEncryptTo, "hidden-encrypt-to", "@"),
560 ARGPARSE_s_n (oEncryptToDefaultKey, "encrypt-to-default-key", "@"),
561 ARGPARSE_s_s (oLocalUser, "local-user",
562 N_("|USER-ID|use USER-ID to sign or decrypt")),
563 ARGPARSE_s_s (oSender, "sender", "@"),
565 ARGPARSE_s_s (oTrySecretKey, "try-secret-key", "@"),
567 ARGPARSE_s_i (oCompress, NULL,
568 N_("|N|set compress level to N (0 disables)")),
569 ARGPARSE_s_i (oCompressLevel, "compress-level", "@"),
570 ARGPARSE_s_i (oBZ2CompressLevel, "bzip2-compress-level", "@"),
571 ARGPARSE_s_n (oBZ2DecompressLowmem, "bzip2-decompress-lowmem", "@"),
573 ARGPARSE_s_n (oMimemode, "mimemode", "@"),
574 ARGPARSE_s_n (oTextmodeShort, NULL, "@"),
575 ARGPARSE_s_n (oTextmode, "textmode", N_("use canonical text mode")),
576 ARGPARSE_s_n (oNoTextmode, "no-textmode", "@"),
578 ARGPARSE_s_n (oExpert, "expert", "@"),
579 ARGPARSE_s_n (oNoExpert, "no-expert", "@"),
581 ARGPARSE_s_s (oDefSigExpire, "default-sig-expire", "@"),
582 ARGPARSE_s_n (oAskSigExpire, "ask-sig-expire", "@"),
583 ARGPARSE_s_n (oNoAskSigExpire, "no-ask-sig-expire", "@"),
584 ARGPARSE_s_s (oDefCertExpire, "default-cert-expire", "@"),
585 ARGPARSE_s_n (oAskCertExpire, "ask-cert-expire", "@"),
586 ARGPARSE_s_n (oNoAskCertExpire, "no-ask-cert-expire", "@"),
587 ARGPARSE_s_i (oDefCertLevel, "default-cert-level", "@"),
588 ARGPARSE_s_i (oMinCertLevel, "min-cert-level", "@"),
589 ARGPARSE_s_n (oAskCertLevel, "ask-cert-level", "@"),
590 ARGPARSE_s_n (oNoAskCertLevel, "no-ask-cert-level", "@"),
592 ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")),
593 ARGPARSE_p_u (oMaxOutput, "max-output", "@"),
594 ARGPARSE_s_s (oInputSizeHint, "input-size-hint", "@"),
596 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
597 ARGPARSE_s_n (oQuiet, "quiet", "@"),
598 ARGPARSE_s_n (oNoTTY, "no-tty", "@"),
600 ARGPARSE_s_n (oDisableSignerUID, "disable-signer-uid", "@"),
602 ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")),
603 ARGPARSE_s_n (oInteractive, "interactive", N_("prompt before overwriting")),
605 ARGPARSE_s_n (oBatch, "batch", "@"),
606 ARGPARSE_s_n (oAnswerYes, "yes", "@"),
607 ARGPARSE_s_n (oAnswerNo, "no", "@"),
608 ARGPARSE_s_s (oKeyring, "keyring", "@"),
609 ARGPARSE_s_s (oPrimaryKeyring, "primary-keyring", "@"),
610 ARGPARSE_s_s (oSecretKeyring, "secret-keyring", "@"),
611 ARGPARSE_s_n (oShowKeyring, "show-keyring", "@"),
612 ARGPARSE_s_s (oDefaultKey, "default-key", "@"),
614 ARGPARSE_s_s (oKeyServer, "keyserver", "@"),
615 ARGPARSE_s_s (oKeyServerOptions, "keyserver-options", "@"),
616 ARGPARSE_s_s (oKeyOrigin, "key-origin", "@"),
617 ARGPARSE_s_s (oImportOptions, "import-options", "@"),
618 ARGPARSE_s_s (oImportFilter, "import-filter", "@"),
619 ARGPARSE_s_s (oExportOptions, "export-options", "@"),
620 ARGPARSE_s_s (oExportFilter, "export-filter", "@"),
621 ARGPARSE_s_s (oListOptions, "list-options", "@"),
622 ARGPARSE_s_s (oVerifyOptions, "verify-options", "@"),
624 ARGPARSE_s_s (oDisplayCharset, "display-charset", "@"),
625 ARGPARSE_s_s (oDisplayCharset, "charset", "@"),
626 ARGPARSE_s_s (oOptions, "options", "@"),
628 ARGPARSE_s_s (oDebug, "debug", "@"),
629 ARGPARSE_s_s (oDebugLevel, "debug-level", "@"),
630 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
631 ARGPARSE_s_n (oDebugIOLBF, "debug-iolbf", "@"),
632 ARGPARSE_s_i (oStatusFD, "status-fd", "@"),
633 ARGPARSE_s_s (oStatusFile, "status-file", "@"),
634 ARGPARSE_s_i (oAttributeFD, "attribute-fd", "@"),
635 ARGPARSE_s_s (oAttributeFile, "attribute-file", "@"),
637 ARGPARSE_s_i (oCompletesNeeded, "completes-needed", "@"),
638 ARGPARSE_s_i (oMarginalsNeeded, "marginals-needed", "@"),
639 ARGPARSE_s_i (oMaxCertDepth, "max-cert-depth", "@" ),
640 ARGPARSE_s_s (oTrustedKey, "trusted-key", "@"),
642 ARGPARSE_s_s (oLoadExtension, "load-extension", "@"), /* Dummy. */
644 ARGPARSE_s_s (oCompliance, "compliance", "@"),
645 ARGPARSE_s_n (oGnuPG, "gnupg", "@"),
646 ARGPARSE_s_n (oGnuPG, "no-pgp2", "@"),
647 ARGPARSE_s_n (oGnuPG, "no-pgp6", "@"),
648 ARGPARSE_s_n (oGnuPG, "no-pgp7", "@"),
649 ARGPARSE_s_n (oGnuPG, "no-pgp8", "@"),
650 ARGPARSE_s_n (oRFC2440, "rfc2440", "@"),
651 ARGPARSE_s_n (oRFC4880, "rfc4880", "@"),
652 ARGPARSE_s_n (oRFC4880bis, "rfc4880bis", "@"),
653 ARGPARSE_s_n (oOpenPGP, "openpgp", N_("use strict OpenPGP behavior")),
654 ARGPARSE_s_n (oPGP6, "pgp6", "@"),
655 ARGPARSE_s_n (oPGP7, "pgp7", "@"),
656 ARGPARSE_s_n (oPGP8, "pgp8", "@"),
658 ARGPARSE_s_n (oRFC2440Text, "rfc2440-text", "@"),
659 ARGPARSE_s_n (oNoRFC2440Text, "no-rfc2440-text", "@"),
660 ARGPARSE_s_i (oS2KMode, "s2k-mode", "@"),
661 ARGPARSE_s_s (oS2KDigest, "s2k-digest-algo", "@"),
662 ARGPARSE_s_s (oS2KCipher, "s2k-cipher-algo", "@"),
663 ARGPARSE_s_i (oS2KCount, "s2k-count", "@"),
664 ARGPARSE_s_s (oCipherAlgo, "cipher-algo", "@"),
665 ARGPARSE_s_s (oDigestAlgo, "digest-algo", "@"),
666 ARGPARSE_s_s (oCertDigestAlgo, "cert-digest-algo", "@"),
667 ARGPARSE_s_s (oCompressAlgo,"compress-algo", "@"),
668 ARGPARSE_s_s (oCompressAlgo, "compression-algo", "@"), /* Alias */
669 ARGPARSE_s_n (oThrowKeyids, "throw-keyids", "@"),
670 ARGPARSE_s_n (oNoThrowKeyids, "no-throw-keyids", "@"),
671 ARGPARSE_s_n (oShowPhotos, "show-photos", "@"),
672 ARGPARSE_s_n (oNoShowPhotos, "no-show-photos", "@"),
673 ARGPARSE_s_s (oPhotoViewer, "photo-viewer", "@"),
674 ARGPARSE_s_s (oSetNotation, "set-notation", "@"),
675 ARGPARSE_s_s (oSigNotation, "sig-notation", "@"),
676 ARGPARSE_s_s (oCertNotation, "cert-notation", "@"),
677 ARGPARSE_s_s (oKnownNotation, "known-notation", "@"),
679 ARGPARSE_group (302, N_(
680 "@\n(See the man page for a complete listing of all commands and options)\n"
683 ARGPARSE_group (303, N_("@\nExamples:\n\n"
684 " -se -r Bob [file] sign and encrypt for user Bob\n"
685 " --clear-sign [file] make a clear text signature\n"
686 " --detach-sign [file] make a detached signature\n"
687 " --list-keys [names] show keys\n"
688 " --fingerprint [names] show fingerprints\n")),
690 /* More hidden commands and options. */
691 ARGPARSE_c (aPrintMDs, "print-mds", "@"), /* old */
692 #ifndef NO_TRUST_MODELS
693 ARGPARSE_c (aListTrustDB, "list-trustdb", "@"),
697 ARGPARSE_c (aListTrustPath, "list-trust-path", "@"), */
698 ARGPARSE_c (aDeleteSecretAndPublicKeys,
699 "delete-secret-and-public-keys", "@"),
700 ARGPARSE_c (aRebuildKeydbCaches, "rebuild-keydb-caches", "@"),
702 ARGPARSE_s_s (oPassphrase, "passphrase", "@"),
703 ARGPARSE_s_i (oPassphraseFD, "passphrase-fd", "@"),
704 ARGPARSE_s_s (oPassphraseFile, "passphrase-file", "@"),
705 ARGPARSE_s_i (oPassphraseRepeat,"passphrase-repeat", "@"),
706 ARGPARSE_s_s (oPinentryMode, "pinentry-mode", "@"),
707 ARGPARSE_s_s (oRequestOrigin, "request-origin", "@"),
708 ARGPARSE_s_i (oCommandFD, "command-fd", "@"),
709 ARGPARSE_s_s (oCommandFile, "command-file", "@"),
710 ARGPARSE_s_n (oQuickRandom, "debug-quick-random", "@"),
711 ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
713 #ifndef NO_TRUST_MODELS
714 ARGPARSE_s_s (oTrustDBName, "trustdb-name", "@"),
715 ARGPARSE_s_n (oAutoCheckTrustDB, "auto-check-trustdb", "@"),
716 ARGPARSE_s_n (oNoAutoCheckTrustDB, "no-auto-check-trustdb", "@"),
717 ARGPARSE_s_s (oForceOwnertrust, "force-ownertrust", "@"),
720 ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"),
721 ARGPARSE_s_n (oRequireSecmem, "require-secmem", "@"),
722 ARGPARSE_s_n (oNoRequireSecmem, "no-require-secmem", "@"),
723 ARGPARSE_s_n (oNoPermissionWarn, "no-permission-warning", "@"),
724 ARGPARSE_s_n (oNoArmor, "no-armor", "@"),
725 ARGPARSE_s_n (oNoArmor, "no-armour", "@"),
726 ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"),
727 ARGPARSE_s_n (oNoKeyring, "no-keyring", "@"),
728 ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
729 ARGPARSE_s_n (oNoOptions, "no-options", "@"),
730 ARGPARSE_s_s (oHomedir, "homedir", "@"),
731 ARGPARSE_s_n (oNoBatch, "no-batch", "@"),
732 ARGPARSE_s_n (oWithColons, "with-colons", "@"),
733 ARGPARSE_s_n (oWithTofuInfo,"with-tofu-info", "@"),
734 ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"),
735 ARGPARSE_s_n (oWithSigList,"with-sig-list", "@"),
736 ARGPARSE_s_n (oWithSigCheck,"with-sig-check", "@"),
737 ARGPARSE_c (aListKeys, "list-key", "@"), /* alias */
738 ARGPARSE_c (aListSigs, "list-sig", "@"), /* alias */
739 ARGPARSE_c (aCheckKeys, "check-sig", "@"), /* alias */
740 ARGPARSE_c (aShowKeys, "show-key", "@"), /* alias */
741 ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"),
742 ARGPARSE_s_n (oSkipHiddenRecipients, "skip-hidden-recipients", "@"),
743 ARGPARSE_s_n (oNoSkipHiddenRecipients, "no-skip-hidden-recipients", "@"),
744 ARGPARSE_s_i (oDefCertLevel, "default-cert-check-level", "@"), /* old */
745 #ifndef NO_TRUST_MODELS
746 ARGPARSE_s_n (oAlwaysTrust, "always-trust", "@"),
748 ARGPARSE_s_s (oTrustModel, "trust-model", "@"),
749 ARGPARSE_s_s (oTOFUDefaultPolicy, "tofu-default-policy", "@"),
750 ARGPARSE_s_s (oSetFilename, "set-filename", "@"),
751 ARGPARSE_s_n (oForYourEyesOnly, "for-your-eyes-only", "@"),
752 ARGPARSE_s_n (oNoForYourEyesOnly, "no-for-your-eyes-only", "@"),
753 ARGPARSE_s_s (oSetPolicyURL, "set-policy-url", "@"),
754 ARGPARSE_s_s (oSigPolicyURL, "sig-policy-url", "@"),
755 ARGPARSE_s_s (oCertPolicyURL, "cert-policy-url", "@"),
756 ARGPARSE_s_n (oShowPolicyURL, "show-policy-url", "@"),
757 ARGPARSE_s_n (oNoShowPolicyURL, "no-show-policy-url", "@"),
758 ARGPARSE_s_s (oSigKeyserverURL, "sig-keyserver-url", "@"),
759 ARGPARSE_s_n (oShowNotation, "show-notation", "@"),
760 ARGPARSE_s_n (oNoShowNotation, "no-show-notation", "@"),
761 ARGPARSE_s_s (oComment, "comment", "@"),
762 ARGPARSE_s_n (oDefaultComment, "default-comment", "@"),
763 ARGPARSE_s_n (oNoComments, "no-comments", "@"),
764 ARGPARSE_s_n (oEmitVersion, "emit-version", "@"),
765 ARGPARSE_s_n (oNoEmitVersion, "no-emit-version", "@"),
766 ARGPARSE_s_n (oNoEmitVersion, "no-version", "@"), /* alias */
767 ARGPARSE_s_n (oNotDashEscaped, "not-dash-escaped", "@"),
768 ARGPARSE_s_n (oEscapeFrom, "escape-from-lines", "@"),
769 ARGPARSE_s_n (oNoEscapeFrom, "no-escape-from-lines", "@"),
770 ARGPARSE_s_n (oLockOnce, "lock-once", "@"),
771 ARGPARSE_s_n (oLockMultiple, "lock-multiple", "@"),
772 ARGPARSE_s_n (oLockNever, "lock-never", "@"),
773 ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"),
774 ARGPARSE_s_s (oLoggerFile, "log-file", "@"),
775 ARGPARSE_s_s (oLoggerFile, "logger-file", "@"), /* 1.4 compatibility. */
776 ARGPARSE_s_n (oUseEmbeddedFilename, "use-embedded-filename", "@"),
777 ARGPARSE_s_n (oNoUseEmbeddedFilename, "no-use-embedded-filename", "@"),
778 ARGPARSE_s_n (oUtf8Strings, "utf8-strings", "@"),
779 ARGPARSE_s_n (oNoUtf8Strings, "no-utf8-strings", "@"),
780 ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"),
781 ARGPARSE_s_n (oWithSubkeyFingerprint, "with-subkey-fingerprint", "@"),
782 ARGPARSE_s_n (oWithSubkeyFingerprint, "with-subkey-fingerprints", "@"),
783 ARGPARSE_s_n (oWithICAOSpelling, "with-icao-spelling", "@"),
784 ARGPARSE_s_n (oWithKeygrip, "with-keygrip", "@"),
785 ARGPARSE_s_n (oWithSecret, "with-secret", "@"),
786 ARGPARSE_s_n (oWithWKDHash, "with-wkd-hash", "@"),
787 ARGPARSE_s_n (oWithKeyOrigin, "with-key-origin", "@"),
788 ARGPARSE_s_s (oDisableCipherAlgo, "disable-cipher-algo", "@"),
789 ARGPARSE_s_s (oDisablePubkeyAlgo, "disable-pubkey-algo", "@"),
790 ARGPARSE_s_n (oAllowNonSelfsignedUID, "allow-non-selfsigned-uid", "@"),
791 ARGPARSE_s_n (oNoAllowNonSelfsignedUID, "no-allow-non-selfsigned-uid", "@"),
792 ARGPARSE_s_n (oAllowFreeformUID, "allow-freeform-uid", "@"),
793 ARGPARSE_s_n (oNoAllowFreeformUID, "no-allow-freeform-uid", "@"),
794 ARGPARSE_s_n (oNoLiteral, "no-literal", "@"),
795 ARGPARSE_p_u (oSetFilesize, "set-filesize", "@"),
796 ARGPARSE_s_n (oFastListMode, "fast-list-mode", "@"),
797 ARGPARSE_s_n (oFixedListMode, "fixed-list-mode", "@"),
798 ARGPARSE_s_n (oLegacyListMode, "legacy-list-mode", "@"),
799 ARGPARSE_s_n (oListOnly, "list-only", "@"),
800 ARGPARSE_s_n (oPrintPKARecords, "print-pka-records", "@"),
801 ARGPARSE_s_n (oPrintDANERecords, "print-dane-records", "@"),
802 ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"),
803 ARGPARSE_s_n (oIgnoreValidFrom, "ignore-valid-from", "@"),
804 ARGPARSE_s_n (oIgnoreCrcError, "ignore-crc-error", "@"),
805 ARGPARSE_s_n (oIgnoreMDCError, "ignore-mdc-error", "@"),
806 ARGPARSE_s_n (oShowSessionKey, "show-session-key", "@"),
807 ARGPARSE_s_s (oOverrideSessionKey, "override-session-key", "@"),
808 ARGPARSE_s_i (oOverrideSessionKeyFD, "override-session-key-fd", "@"),
809 ARGPARSE_s_n (oNoRandomSeedFile, "no-random-seed-file", "@"),
810 ARGPARSE_s_n (oAutoKeyRetrieve, "auto-key-retrieve", "@"),
811 ARGPARSE_s_n (oNoAutoKeyRetrieve, "no-auto-key-retrieve", "@"),
812 ARGPARSE_s_n (oNoSigCache, "no-sig-cache", "@"),
813 ARGPARSE_s_n (oMergeOnly, "merge-only", "@" ),
814 ARGPARSE_s_n (oAllowSecretKeyImport, "allow-secret-key-import", "@"),
815 ARGPARSE_s_n (oTryAllSecrets, "try-all-secrets", "@"),
816 ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"),
817 ARGPARSE_s_n (oNoExpensiveTrustChecks, "no-expensive-trust-checks", "@"),
818 ARGPARSE_s_n (oPreservePermissions, "preserve-permissions", "@"),
819 ARGPARSE_s_s (oDefaultPreferenceList, "default-preference-list", "@"),
820 ARGPARSE_s_s (oDefaultKeyserverURL, "default-keyserver-url", "@"),
821 ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-preferences","@"),
822 ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-preferences","@"),
823 ARGPARSE_s_s (oPersonalCompressPreferences,
824 "personal-compress-preferences", "@"),
825 ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
826 ARGPARSE_s_s (oWeakDigest, "weak-digest","@"),
827 ARGPARSE_s_n (oUnwrap, "unwrap", "@"),
828 ARGPARSE_s_n (oOnlySignTextIDs, "only-sign-text-ids", "@"),
830 /* Aliases. I constantly mistype these, and assume other people do
832 ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-prefs", "@"),
833 ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-prefs", "@"),
834 ARGPARSE_s_s (oPersonalCompressPreferences, "personal-compress-prefs", "@"),
836 ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
837 ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"),
838 ARGPARSE_s_n (oDisableDirmngr, "disable-dirmngr", "@"),
839 ARGPARSE_s_s (oDisplay, "display", "@"),
840 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
841 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
842 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
843 ARGPARSE_s_s (oLCmessages, "lc-messages","@"),
844 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
845 ARGPARSE_s_s (oGroup, "group", "@"),
846 ARGPARSE_s_s (oUnGroup, "ungroup", "@"),
847 ARGPARSE_s_n (oNoGroups, "no-groups", "@"),
848 ARGPARSE_s_n (oStrict, "strict", "@"),
849 ARGPARSE_s_n (oNoStrict, "no-strict", "@"),
850 ARGPARSE_s_n (oMangleDosFilenames, "mangle-dos-filenames", "@"),
851 ARGPARSE_s_n (oNoMangleDosFilenames, "no-mangle-dos-filenames", "@"),
852 ARGPARSE_s_n (oEnableProgressFilter, "enable-progress-filter", "@"),
853 ARGPARSE_s_n (oMultifile, "multifile", "@"),
854 ARGPARSE_s_s (oKeyidFormat, "keyid-format", "@"),
855 ARGPARSE_s_n (oExitOnStatusWriteError, "exit-on-status-write-error", "@"),
856 ARGPARSE_s_i (oLimitCardInsertTries, "limit-card-insert-tries", "@"),
858 ARGPARSE_s_n (oAllowMultisigVerification,
859 "allow-multisig-verification", "@"),
860 ARGPARSE_s_n (oEnableLargeRSA, "enable-large-rsa", "@"),
861 ARGPARSE_s_n (oDisableLargeRSA, "disable-large-rsa", "@"),
862 ARGPARSE_s_n (oEnableDSA2, "enable-dsa2", "@"),
863 ARGPARSE_s_n (oDisableDSA2, "disable-dsa2", "@"),
864 ARGPARSE_s_n (oAllowMultipleMessages, "allow-multiple-messages", "@"),
865 ARGPARSE_s_n (oNoAllowMultipleMessages, "no-allow-multiple-messages", "@"),
866 ARGPARSE_s_n (oAllowWeakDigestAlgos, "allow-weak-digest-algos", "@"),
868 ARGPARSE_s_s (oDefaultNewKeyAlgo, "default-new-key-algo", "@"),
870 /* These two are aliases to help users of the PGP command line
871 product use gpg with minimal pain. Many commands are common
872 already as they seem to have borrowed commands from us. Now I'm
873 returning the favor. */
874 ARGPARSE_s_s (oLocalUser, "sign-with", "@"),
875 ARGPARSE_s_s (oRecipient, "user", "@"),
877 ARGPARSE_s_n (oRequireCrossCert, "require-backsigs", "@"),
878 ARGPARSE_s_n (oRequireCrossCert, "require-cross-certification", "@"),
879 ARGPARSE_s_n (oNoRequireCrossCert, "no-require-backsigs", "@"),
880 ARGPARSE_s_n (oNoRequireCrossCert, "no-require-cross-certification", "@"),
882 /* New options. Fixme: Should go more to the top. */
883 ARGPARSE_s_s (oAutoKeyLocate, "auto-key-locate", "@"),
884 ARGPARSE_s_n (oNoAutoKeyLocate, "no-auto-key-locate", "@"),
885 ARGPARSE_s_n (oNoAutostart, "no-autostart", "@"),
886 ARGPARSE_s_n (oNoSymkeyCache, "no-symkey-cache", "@"),
888 /* Dummy options with warnings. */
889 ARGPARSE_s_n (oUseAgent, "use-agent", "@"),
890 ARGPARSE_s_n (oNoUseAgent, "no-use-agent", "@"),
891 ARGPARSE_s_s (oGpgAgentInfo, "gpg-agent-info", "@"),
892 ARGPARSE_s_s (oReaderPort, "reader-port", "@"),
893 ARGPARSE_s_s (octapiDriver, "ctapi-driver", "@"),
894 ARGPARSE_s_s (opcscDriver, "pcsc-driver", "@"),
895 ARGPARSE_s_n (oDisableCCID, "disable-ccid", "@"),
896 ARGPARSE_s_n (oHonorHttpProxy, "honor-http-proxy", "@"),
897 ARGPARSE_s_s (oTOFUDBFormat, "tofu-db-format", "@"),
900 ARGPARSE_s_n (oNoop, "sk-comments", "@"),
901 ARGPARSE_s_n (oNoop, "no-sk-comments", "@"),
902 ARGPARSE_s_n (oNoop, "compress-keys", "@"),
903 ARGPARSE_s_n (oNoop, "compress-sigs", "@"),
904 ARGPARSE_s_n (oNoop, "force-v3-sigs", "@"),
905 ARGPARSE_s_n (oNoop, "no-force-v3-sigs", "@"),
906 ARGPARSE_s_n (oNoop, "force-v4-certs", "@"),
907 ARGPARSE_s_n (oNoop, "no-force-v4-certs", "@"),
908 ARGPARSE_s_n (oNoop, "no-mdc-warning", "@"),
909 ARGPARSE_s_n (oNoop, "force-mdc", "@"),
910 ARGPARSE_s_n (oNoop, "no-force-mdc", "@"),
911 ARGPARSE_s_n (oNoop, "disable-mdc", "@"),
912 ARGPARSE_s_n (oNoop, "no-disable-mdc", "@"),
919 /* The list of supported debug flags. */
920 static struct debug_flags_s debug_flags [] =
922 { DBG_PACKET_VALUE , "packet" },
923 { DBG_MPI_VALUE , "mpi" },
924 { DBG_CRYPTO_VALUE , "crypto" },
925 { DBG_FILTER_VALUE , "filter" },
926 { DBG_IOBUF_VALUE , "iobuf" },
927 { DBG_MEMORY_VALUE , "memory" },
928 { DBG_CACHE_VALUE , "cache" },
929 { DBG_MEMSTAT_VALUE, "memstat" },
930 { DBG_TRUST_VALUE , "trust" },
931 { DBG_HASHING_VALUE, "hashing" },
932 { DBG_IPC_VALUE , "ipc" },
933 { DBG_CLOCK_VALUE , "clock" },
934 { DBG_LOOKUP_VALUE , "lookup" },
935 { DBG_EXTPROG_VALUE, "extprog" },
940 #ifdef ENABLE_SELINUX_HACKS
941 #define ALWAYS_ADD_KEYRINGS 1
943 #define ALWAYS_ADD_KEYRINGS 0
947 int g10_errors_seen = 0;
949 static int utf8_strings = 0;
950 static int maybe_setuid = 1;
952 static char *build_list( const char *text, char letter,
953 const char *(*mapf)(int), int (*chkf)(int) );
954 static void set_cmd( enum cmd_and_opt_values *ret_cmd,
955 enum cmd_and_opt_values new_cmd );
956 static void print_mds( const char *fname, int algo );
957 static void add_notation_data( const char *string, int which );
958 static void add_policy_url( const char *string, int which );
959 static void add_keyserver_url( const char *string, int which );
960 static void emergency_cleanup (void);
961 static void read_sessionkey_from_fd (int fd);
965 make_libversion (const char *libname, const char *(*getfnc)(const char*))
972 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
976 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
977 strcpy (stpcpy (stpcpy (result, libname), " "), s);
983 build_list_pk_test_algo (int algo)
985 /* Show only one "RSA" string. If RSA_E or RSA_S is available RSA
986 is also available. */
987 if (algo == PUBKEY_ALGO_RSA_E
988 || algo == PUBKEY_ALGO_RSA_S)
989 return GPG_ERR_DIGEST_ALGO;
991 return openpgp_pk_test_algo (algo);
995 build_list_pk_algo_name (int algo)
997 return openpgp_pk_algo_name (algo);
1001 build_list_cipher_test_algo (int algo)
1003 return openpgp_cipher_test_algo (algo);
1007 build_list_cipher_algo_name (int algo)
1009 return openpgp_cipher_algo_name (algo);
1013 build_list_md_test_algo (int algo)
1015 /* By default we do not accept MD5 based signatures. To avoid
1016 confusion we do not announce support for it either. */
1017 if (algo == DIGEST_ALGO_MD5)
1018 return GPG_ERR_DIGEST_ALGO;
1020 return openpgp_md_test_algo (algo);
1024 build_list_md_algo_name (int algo)
1026 return openpgp_md_algo_name (algo);
1031 my_strusage( int level )
1033 static char *digests, *pubkeys, *ciphers, *zips, *ver_gcry;
1037 case 11: p = "@GPG@ (@GNUPG@)";
1039 case 13: p = VERSION; break;
1040 case 17: p = PRINTABLE_OS_NAME; break;
1041 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
1045 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
1049 #ifdef IS_DEVELOPMENT_VERSION
1051 p="NOTE: THIS IS A DEVELOPMENT VERSION!";
1054 p="It is only intended for test purposes and should NOT be";
1057 p="used in a production environment or with production keys!";
1063 _("Usage: @GPG@ [options] [files] (-h for help)");
1066 _("Syntax: @GPG@ [options] [files]\n"
1067 "Sign, check, encrypt or decrypt\n"
1068 "Default operation depends on the input data\n");
1071 case 31: p = "\nHome: "; break;
1073 case 32: p = gnupg_homedir (); break;
1074 #else /* __riscos__ */
1075 case 32: p = make_filename(gnupg_homedir (), NULL); break;
1076 #endif /* __riscos__ */
1077 case 33: p = _("\nSupported algorithms:\n"); break;
1080 pubkeys = build_list (_("Pubkey: "), 1,
1081 build_list_pk_algo_name,
1082 build_list_pk_test_algo );
1087 ciphers = build_list(_("Cipher: "), 'S',
1088 build_list_cipher_algo_name,
1089 build_list_cipher_test_algo );
1094 digests = build_list(_("Hash: "), 'H',
1095 build_list_md_algo_name,
1096 build_list_md_test_algo );
1101 zips = build_list(_("Compression: "),'Z',
1102 compress_algo_to_string,
1103 check_compress_algo);
1114 build_list (const char *text, char letter,
1115 const char * (*mapf)(int), int (*chkf)(int))
1124 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
1126 indent = utf8_charcount (text, -1);
1128 init_membuf (&mb, 512);
1130 for (i=0; i <= 110; i++ )
1132 if (!chkf (i) && (s = mapf (i)))
1134 if (mb.len - len > 60)
1136 put_membuf_str (&mb, ",\n");
1138 for (j=0; j < indent; j++)
1139 put_membuf_str (&mb, " ");
1142 put_membuf_str (&mb, ", ");
1144 put_membuf_str (&mb, text);
1146 put_membuf_str (&mb, s);
1147 if (opt.verbose && letter)
1151 snprintf (num, sizeof num, " (%d)", i);
1153 snprintf (num, sizeof num, " (%c%d)", letter, i);
1154 put_membuf_str (&mb, num);
1159 put_membuf_str (&mb, "\n");
1160 put_membuf (&mb, "", 1);
1162 string = get_membuf (&mb, NULL);
1163 return xrealloc (string, strlen (string)+1);
1168 wrong_args( const char *text)
1170 es_fprintf (es_stderr, _("usage: %s [options] %s\n"), GPG_NAME, text);
1171 log_inc_errorcount ();
1177 make_username( const char *string )
1181 p = xstrdup(string);
1183 p = native_to_utf8( string );
1189 set_opt_session_env (const char *name, const char *value)
1193 err = session_env_setenv (opt.session_env, name, value);
1195 log_fatal ("error setting session environment: %s\n",
1196 gpg_strerror (err));
1200 /* Setup the debugging. With a LEVEL of NULL only the active debug
1201 flags are propagated to the subsystems. With LEVEL set, a specific
1202 set of debug flags is set; thus overriding all flags already
1205 set_debug (const char *level)
1207 int numok = (level && digitp (level));
1208 int numlvl = numok? atoi (level) : 0;
1212 else if (!strcmp (level, "none") || (numok && numlvl < 1))
1214 else if (!strcmp (level, "basic") || (numok && numlvl <= 2))
1215 opt.debug = DBG_MEMSTAT_VALUE;
1216 else if (!strcmp (level, "advanced") || (numok && numlvl <= 5))
1217 opt.debug = DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE;
1218 else if (!strcmp (level, "expert") || (numok && numlvl <= 8))
1219 opt.debug = (DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE
1220 |DBG_CACHE_VALUE|DBG_LOOKUP|DBG_FILTER_VALUE|DBG_PACKET_VALUE);
1221 else if (!strcmp (level, "guru") || numok)
1224 /* Unless the "guru" string has been used we don't want to allow
1225 hashing debugging. The rationale is that people tend to
1226 select the highest debug value and would then clutter their
1227 disk with debug files which may reveal confidential data. */
1229 opt.debug &= ~(DBG_HASHING_VALUE);
1233 log_error (_("invalid debug-level '%s' given\n"), level);
1237 if ((opt.debug & DBG_MEMORY_VALUE))
1238 memory_debug_mode = 1;
1239 if ((opt.debug & DBG_MEMSTAT_VALUE))
1240 memory_stat_debug_mode = 1;
1242 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
1244 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
1245 if ((opt.debug & DBG_IOBUF_VALUE))
1246 iobuf_debug_mode = 1;
1247 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1250 parse_debug_flag (NULL, &opt.debug, debug_flags);
1254 /* We set the screen dimensions for UI purposes. Do not allow screens
1255 smaller than 80x24 for the sake of simplicity. */
1257 set_screen_dimensions(void)
1259 #ifndef HAVE_W32_SYSTEM
1262 str=getenv("COLUMNS");
1264 opt.screen_columns=atoi(str);
1266 str=getenv("LINES");
1268 opt.screen_lines=atoi(str);
1271 if(opt.screen_columns<80 || opt.screen_columns>255)
1272 opt.screen_columns=80;
1274 if(opt.screen_lines<24 || opt.screen_lines>255)
1275 opt.screen_lines=24;
1279 /* Helper to open a file FNAME either for reading or writing to be
1280 used with --status-file etc functions. Not generally useful but it
1281 avoids the riscos specific functions and well some Windows people
1282 might like it too. Prints an error message and returns -1 on
1283 error. On success the file descriptor is returned. */
1285 open_info_file (const char *fname, int for_write, int binary)
1288 return riscos_fdopenfile (fname, for_write);
1289 #elif defined (ENABLE_SELINUX_HACKS)
1290 /* We can't allow these even when testing for a secured filename
1291 because files to be secured might not yet been secured. This is
1292 similar to the option file but in that case it is unlikely that
1293 sensitive information may be retrieved by means of error
1303 binary = MY_O_BINARY;
1305 /* if (is_secured_filename (fname)) */
1308 /* gpg_err_set_errno (EPERM); */
1315 fd = open (fname, O_CREAT | O_TRUNC | O_WRONLY | binary,
1316 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
1318 fd = open (fname, O_RDONLY | binary);
1320 while (fd == -1 && errno == EINTR);
1323 log_error ( for_write? _("can't create '%s': %s\n")
1324 : _("can't open '%s': %s\n"), fname, strerror(errno));
1331 set_cmd( enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd )
1333 enum cmd_and_opt_values cmd = *ret_cmd;
1335 if( !cmd || cmd == new_cmd )
1337 else if( cmd == aSign && new_cmd == aEncr )
1339 else if( cmd == aEncr && new_cmd == aSign )
1341 else if( cmd == aSign && new_cmd == aSym )
1343 else if( cmd == aSym && new_cmd == aSign )
1345 else if( cmd == aSym && new_cmd == aEncr )
1347 else if( cmd == aEncr && new_cmd == aSym )
1349 else if (cmd == aSignEncr && new_cmd == aSym)
1351 else if (cmd == aSignSym && new_cmd == aEncr)
1353 else if (cmd == aEncrSym && new_cmd == aSign)
1355 else if( ( cmd == aSign && new_cmd == aClearsign )
1356 || ( cmd == aClearsign && new_cmd == aSign ) )
1359 log_error(_("conflicting commands\n"));
1368 add_group(char *string)
1371 struct groupitem *item;
1373 /* Break off the group name */
1374 name=strsep(&string,"=");
1377 log_error(_("no = sign found in group definition '%s'\n"),name);
1381 trim_trailing_ws(name,strlen(name));
1383 /* Does this group already exist? */
1384 for(item=opt.grouplist;item;item=item->next)
1385 if(strcasecmp(item->name,name)==0)
1390 item=xmalloc(sizeof(struct groupitem));
1392 item->next=opt.grouplist;
1397 /* Break apart the values */
1398 while ((value= strsep(&string," \t")))
1401 add_to_strlist2(&item->values,value,utf8_strings);
1407 rm_group(char *name)
1409 struct groupitem *item,*last=NULL;
1411 trim_trailing_ws(name,strlen(name));
1413 for(item=opt.grouplist;item;last=item,item=item->next)
1415 if(strcasecmp(item->name,name)==0)
1418 last->next=item->next;
1420 opt.grouplist=item->next;
1422 free_strlist(item->values);
1430 /* We need to check three things.
1432 0) The homedir. It must be x00, a directory, and owned by the
1435 1) The options/gpg.conf file. Okay unless it or its containing
1436 directory is group or other writable or not owned by us. Disable
1439 2) Extensions. Same as #1.
1441 Returns true if the item is unsafe. */
1443 check_permissions (const char *path, int item)
1445 #if defined(HAVE_STAT) && !defined(HAVE_DOSISH_SYSTEM)
1446 static int homedir_cache=-1;
1448 struct stat statbuf,dirbuf;
1449 int homedir=0,ret=0,checkonly=0;
1450 int perm=0,own=0,enc_dir_perm=0,enc_dir_own=0;
1452 if(opt.no_perm_warn)
1455 log_assert(item==0 || item==1 || item==2);
1457 /* extensions may attach a path */
1458 if(item==2 && path[0]!=DIRSEP_C)
1460 if(strchr(path,DIRSEP_C))
1461 tmppath=make_filename(path,NULL);
1463 tmppath=make_filename(gnupg_libdir (),path,NULL);
1466 tmppath=xstrdup(path);
1468 /* If the item is located in the homedir, but isn't the homedir,
1469 don't continue if we already checked the homedir itself. This is
1470 to avoid user confusion with an extra options file warning which
1471 could be rectified if the homedir itself had proper
1473 if(item!=0 && homedir_cache>-1
1474 && !ascii_strncasecmp (gnupg_homedir (), tmppath,
1475 strlen (gnupg_homedir ())))
1481 /* It's okay if the file or directory doesn't exist */
1482 if(stat(tmppath,&statbuf)!=0)
1488 /* Now check the enclosing directory. Theoretically, we could walk
1489 this test up to the root directory /, but for the sake of sanity,
1490 I'm stopping at one level down. */
1491 dir=make_dirname(tmppath);
1493 if(stat(dir,&dirbuf)!=0 || !S_ISDIR(dirbuf.st_mode))
1502 /* Assume failure */
1507 /* The homedir must be x00, a directory, and owned by the user. */
1509 if(S_ISDIR(statbuf.st_mode))
1511 if(statbuf.st_uid==getuid())
1513 if((statbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1524 else if(item==1 || item==2)
1526 /* The options or extension file. Okay unless it or its
1527 containing directory is group or other writable or not owned
1530 if(S_ISREG(statbuf.st_mode))
1532 if(statbuf.st_uid==getuid() || statbuf.st_uid==0)
1534 if((statbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1536 /* it's not writable, so make sure the enclosing
1537 directory is also not writable */
1538 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1540 if((dirbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1550 /* it's writable, so the enclosing directory had
1551 better not let people get to it. */
1552 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1554 if((dirbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1557 perm=enc_dir_perm=1; /* unclear which one to fix! */
1575 log_info(_("WARNING: unsafe ownership on"
1576 " homedir '%s'\n"),tmppath);
1578 log_info(_("WARNING: unsafe ownership on"
1579 " configuration file '%s'\n"),tmppath);
1581 log_info(_("WARNING: unsafe ownership on"
1582 " extension '%s'\n"),tmppath);
1587 log_info(_("WARNING: unsafe permissions on"
1588 " homedir '%s'\n"),tmppath);
1590 log_info(_("WARNING: unsafe permissions on"
1591 " configuration file '%s'\n"),tmppath);
1593 log_info(_("WARNING: unsafe permissions on"
1594 " extension '%s'\n"),tmppath);
1599 log_info(_("WARNING: unsafe enclosing directory ownership on"
1600 " homedir '%s'\n"),tmppath);
1602 log_info(_("WARNING: unsafe enclosing directory ownership on"
1603 " configuration file '%s'\n"),tmppath);
1605 log_info(_("WARNING: unsafe enclosing directory ownership on"
1606 " extension '%s'\n"),tmppath);
1611 log_info(_("WARNING: unsafe enclosing directory permissions on"
1612 " homedir '%s'\n"),tmppath);
1614 log_info(_("WARNING: unsafe enclosing directory permissions on"
1615 " configuration file '%s'\n"),tmppath);
1617 log_info(_("WARNING: unsafe enclosing directory permissions on"
1618 " extension '%s'\n"),tmppath);
1630 #else /*!(HAVE_STAT && !HAVE_DOSISH_SYSTEM)*/
1634 #endif /*!(HAVE_STAT && !HAVE_DOSISH_SYSTEM)*/
1638 /* Print the OpenPGP defined algo numbers. */
1640 print_algo_numbers(int (*checker)(int))
1659 print_algo_names(int (*checker)(int),const char *(*mapper)(int))
1671 es_printf ("%s",mapper(i));
1676 /* In the future, we can do all sorts of interesting configuration
1677 output here. For now, just give "group" as the Enigmail folks need
1678 it, and pubkey, cipher, hash, and compress as they may be useful
1681 list_config(char *items)
1683 int show_all = !items;
1686 struct groupitem *giter;
1689 if(!opt.with_colons)
1692 while(show_all || (name=strsep(&items," ")))
1696 if(show_all || ascii_strcasecmp(name,"group")==0)
1698 for (giter = opt.grouplist; giter; giter = giter->next)
1702 es_fprintf (es_stdout, "cfg:group:");
1703 es_write_sanitized (es_stdout, giter->name, strlen(giter->name),
1705 es_putc (':', es_stdout);
1707 for(sl=giter->values; sl; sl=sl->next)
1709 es_write_sanitized (es_stdout, sl->d, strlen (sl->d),
1721 if(show_all || ascii_strcasecmp(name,"version")==0)
1723 es_printf("cfg:version:");
1724 es_write_sanitized (es_stdout, VERSION, strlen(VERSION), ":", NULL);
1729 if(show_all || ascii_strcasecmp(name,"pubkey")==0)
1731 es_printf ("cfg:pubkey:");
1732 print_algo_numbers (build_list_pk_test_algo);
1737 if(show_all || ascii_strcasecmp(name,"pubkeyname")==0)
1739 es_printf ("cfg:pubkeyname:");
1740 print_algo_names (build_list_pk_test_algo,
1741 build_list_pk_algo_name);
1746 if(show_all || ascii_strcasecmp(name,"cipher")==0)
1748 es_printf ("cfg:cipher:");
1749 print_algo_numbers (build_list_cipher_test_algo);
1754 if (show_all || !ascii_strcasecmp (name,"ciphername"))
1756 es_printf ("cfg:ciphername:");
1757 print_algo_names (build_list_cipher_test_algo,
1758 build_list_cipher_algo_name);
1764 || ascii_strcasecmp(name,"digest")==0
1765 || ascii_strcasecmp(name,"hash")==0)
1767 es_printf ("cfg:digest:");
1768 print_algo_numbers (build_list_md_test_algo);
1774 || !ascii_strcasecmp(name,"digestname")
1775 || !ascii_strcasecmp(name,"hashname"))
1777 es_printf ("cfg:digestname:");
1778 print_algo_names (build_list_md_test_algo,
1779 build_list_md_algo_name);
1784 if(show_all || ascii_strcasecmp(name,"compress")==0)
1786 es_printf ("cfg:compress:");
1787 print_algo_numbers(check_compress_algo);
1792 if(show_all || ascii_strcasecmp (name, "compressname") == 0)
1794 es_printf ("cfg:compressname:");
1795 print_algo_names (check_compress_algo,
1796 compress_algo_to_string);
1801 if (show_all || !ascii_strcasecmp(name,"ccid-reader-id"))
1803 /* We ignore this for GnuPG 1.4 backward compatibility. */
1807 if (show_all || !ascii_strcasecmp (name,"curve"))
1809 es_printf ("cfg:curve:");
1810 for (iter=0, first=1; (s = openpgp_enum_curves (&iter)); first=0)
1811 es_printf ("%s%s", first?"":";", s);
1816 /* Curve OIDs are rarely useful and thus only printed if requested. */
1817 if (name && !ascii_strcasecmp (name,"curveoid"))
1819 es_printf ("cfg:curveoid:");
1820 for (iter=0, first=1; (s = openpgp_enum_curves (&iter)); first = 0)
1822 s = openpgp_curve_to_oid (s, NULL);
1823 es_printf ("%s%s", first?"":";", s? s:"[?]");
1833 log_error(_("unknown configuration item '%s'\n"),name);
1838 /* List options and default values in the GPG Conf format. This is a
1839 new tool distributed with gnupg 1.9.x but we also want some limited
1840 support in older gpg versions. The output is the name of the
1841 configuration file and a list of options available for editing by
1844 gpgconf_list (const char *configfile)
1846 char *configfile_esc = percent_escape (configfile, NULL);
1848 es_printf ("%s-%s.conf:%lu:\"%s\n",
1849 GPGCONF_NAME, GPG_NAME,
1850 GC_OPT_FLAG_DEFAULT,
1851 configfile_esc ? configfile_esc : "/dev/null");
1852 es_printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
1853 es_printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
1854 es_printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
1855 es_printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE);
1856 es_printf ("default-key:%lu:\n", GC_OPT_FLAG_NONE);
1857 es_printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_NONE);
1858 es_printf ("try-secret-key:%lu:\n", GC_OPT_FLAG_NONE);
1859 es_printf ("auto-key-locate:%lu:\n", GC_OPT_FLAG_NONE);
1860 es_printf ("auto-key-retrieve:%lu:\n", GC_OPT_FLAG_NONE);
1861 es_printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE);
1862 es_printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
1863 es_printf ("group:%lu:\n", GC_OPT_FLAG_NONE);
1864 es_printf ("compliance:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT, "gnupg");
1865 es_printf ("default-new-key-algo:%lu:\n", GC_OPT_FLAG_NONE);
1866 es_printf ("trust-model:%lu:\n", GC_OPT_FLAG_NONE);
1867 es_printf ("disable-dirmngr:%lu:\n", GC_OPT_FLAG_NONE);
1868 es_printf ("max-cert-depth:%lu:\n", GC_OPT_FLAG_NONE);
1869 es_printf ("completes-needed:%lu:\n", GC_OPT_FLAG_NONE);
1870 es_printf ("marginals-needed:%lu:\n", GC_OPT_FLAG_NONE);
1872 /* The next one is an info only item and should match the macros at
1873 the top of keygen.c */
1874 es_printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1875 get_default_pubkey_algo ());
1877 xfree (configfile_esc);
1882 parse_subpacket_list(char *list)
1885 byte subpackets[128],i;
1890 /* No arguments means all subpackets */
1891 memset(subpackets+1,1,sizeof(subpackets)-1);
1896 memset(subpackets,0,sizeof(subpackets));
1898 /* Merge with earlier copy */
1899 if(opt.show_subpackets)
1903 for(in=opt.show_subpackets;*in;in++)
1905 if(*in>127 || *in<1)
1908 if(!subpackets[*in])
1914 while((tok=strsep(&list," ,")))
1929 xfree(opt.show_subpackets);
1930 opt.show_subpackets=xmalloc(count+1);
1931 opt.show_subpackets[count--]=0;
1933 for(i=1;i<128 && count>=0;i++)
1935 opt.show_subpackets[count--]=i;
1942 parse_list_options(char *str)
1944 char *subpackets=""; /* something that isn't NULL */
1945 struct parse_options lopts[]=
1947 {"show-photos",LIST_SHOW_PHOTOS,NULL,
1948 N_("display photo IDs during key listings")},
1949 {"show-usage",LIST_SHOW_USAGE,NULL,
1950 N_("show key usage information during key listings")},
1951 {"show-policy-urls",LIST_SHOW_POLICY_URLS,NULL,
1952 N_("show policy URLs during signature listings")},
1953 {"show-notations",LIST_SHOW_NOTATIONS,NULL,
1954 N_("show all notations during signature listings")},
1955 {"show-std-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1956 N_("show IETF standard notations during signature listings")},
1957 {"show-standard-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1959 {"show-user-notations",LIST_SHOW_USER_NOTATIONS,NULL,
1960 N_("show user-supplied notations during signature listings")},
1961 {"show-keyserver-urls",LIST_SHOW_KEYSERVER_URLS,NULL,
1962 N_("show preferred keyserver URLs during signature listings")},
1963 {"show-uid-validity",LIST_SHOW_UID_VALIDITY,NULL,
1964 N_("show user ID validity during key listings")},
1965 {"show-unusable-uids",LIST_SHOW_UNUSABLE_UIDS,NULL,
1966 N_("show revoked and expired user IDs in key listings")},
1967 {"show-unusable-subkeys",LIST_SHOW_UNUSABLE_SUBKEYS,NULL,
1968 N_("show revoked and expired subkeys in key listings")},
1969 {"show-keyring",LIST_SHOW_KEYRING,NULL,
1970 N_("show the keyring name in key listings")},
1971 {"show-sig-expire",LIST_SHOW_SIG_EXPIRE,NULL,
1972 N_("show expiration dates during signature listings")},
1973 {"show-sig-subpackets",LIST_SHOW_SIG_SUBPACKETS,NULL,
1975 {"show-only-fpr-mbox",LIST_SHOW_ONLY_FPR_MBOX, NULL,
1980 /* C99 allows for non-constant initializers, but we'd like to
1981 compile everywhere, so fill in the show-sig-subpackets argument
1982 here. Note that if the parse_options array changes, we'll have
1983 to change the subscript here. */
1984 lopts[13].value=&subpackets;
1986 if(parse_options(str,&opt.list_options,lopts,1))
1988 if(opt.list_options&LIST_SHOW_SIG_SUBPACKETS)
1990 /* Unset so users can pass multiple lists in. */
1991 opt.list_options&=~LIST_SHOW_SIG_SUBPACKETS;
1992 if(!parse_subpacket_list(subpackets))
1995 else if(subpackets==NULL && opt.show_subpackets)
1997 /* User did 'no-show-subpackets' */
1998 xfree(opt.show_subpackets);
1999 opt.show_subpackets=NULL;
2009 /* Collapses argc/argv into a single string that must be freed */
2011 collapse_args(int argc,char *argv[])
2014 int i,first=1,len=0;
2018 len+=strlen(argv[i])+2;
2019 str=xrealloc(str,len);
2028 strcat(str,argv[i]);
2035 #ifndef NO_TRUST_MODELS
2037 parse_trust_model(const char *model)
2039 if(ascii_strcasecmp(model,"pgp")==0)
2040 opt.trust_model=TM_PGP;
2041 else if(ascii_strcasecmp(model,"classic")==0)
2042 opt.trust_model=TM_CLASSIC;
2043 else if(ascii_strcasecmp(model,"always")==0)
2044 opt.trust_model=TM_ALWAYS;
2045 else if(ascii_strcasecmp(model,"direct")==0)
2046 opt.trust_model=TM_DIRECT;
2048 else if(ascii_strcasecmp(model,"tofu")==0)
2049 opt.trust_model=TM_TOFU;
2050 else if(ascii_strcasecmp(model,"tofu+pgp")==0)
2051 opt.trust_model=TM_TOFU_PGP;
2053 else if(ascii_strcasecmp(model,"auto")==0)
2054 opt.trust_model=TM_AUTO;
2056 log_error("unknown trust model '%s'\n",model);
2058 #endif /*NO_TRUST_MODELS*/
2062 parse_tofu_policy (const char *policystr)
2065 struct { const char *keyword; int policy; } list[] = {
2066 { "auto", TOFU_POLICY_AUTO },
2067 { "good", TOFU_POLICY_GOOD },
2068 { "unknown", TOFU_POLICY_UNKNOWN },
2069 { "bad", TOFU_POLICY_BAD },
2070 { "ask", TOFU_POLICY_ASK }
2074 if (!ascii_strcasecmp (policystr, "help"))
2076 log_info (_("valid values for option '%s':\n"), "--tofu-policy");
2077 for (i=0; i < DIM (list); i++)
2078 log_info (" %s\n", list[i].keyword);
2082 for (i=0; i < DIM (list); i++)
2083 if (!ascii_strcasecmp (policystr, list[i].keyword))
2084 return list[i].policy;
2087 log_error (_("unknown TOFU policy '%s'\n"), policystr);
2089 log_info (_("(use \"help\" to list choices)\n"));
2094 static struct gnupg_compliance_option compliance_options[] =
2096 { "gnupg", oGnuPG },
2097 { "openpgp", oOpenPGP },
2098 { "rfc4880bis", oRFC4880bis },
2099 { "rfc4880", oRFC4880 },
2100 { "rfc2440", oRFC2440 },
2108 /* Helper to set compliance related options. This is a separate
2109 * function so that it can also be used by the --compliance option
2112 set_compliance_option (enum cmd_and_opt_values option)
2117 opt.flags.rfc4880bis = 1;
2121 /* This is effectively the same as RFC2440, but with
2122 "--enable-dsa2 --no-rfc2440-text --escape-from-lines
2123 --require-cross-certification". */
2124 opt.compliance = CO_RFC4880;
2126 opt.flags.require_cross_cert = 1;
2127 opt.rfc2440_text = 0;
2128 opt.allow_non_selfsigned_uid = 1;
2129 opt.allow_freeform_uid = 1;
2130 opt.escape_from = 1;
2131 opt.not_dash_escaped = 0;
2132 opt.def_cipher_algo = 0;
2133 opt.def_digest_algo = 0;
2134 opt.cert_digest_algo = 0;
2135 opt.compress_algo = -1;
2136 opt.s2k_mode = 3; /* iterated+salted */
2137 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2138 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2141 opt.compliance = CO_RFC2440;
2143 opt.rfc2440_text = 1;
2144 opt.allow_non_selfsigned_uid = 1;
2145 opt.allow_freeform_uid = 1;
2146 opt.escape_from = 0;
2147 opt.not_dash_escaped = 0;
2148 opt.def_cipher_algo = 0;
2149 opt.def_digest_algo = 0;
2150 opt.cert_digest_algo = 0;
2151 opt.compress_algo = -1;
2152 opt.s2k_mode = 3; /* iterated+salted */
2153 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2154 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2156 case oPGP6: opt.compliance = CO_PGP6; break;
2157 case oPGP7: opt.compliance = CO_PGP7; break;
2158 case oPGP8: opt.compliance = CO_PGP8; break;
2159 case oGnuPG: opt.compliance = CO_GNUPG; break;
2162 set_compliance_option (oOpenPGP);
2163 opt.compliance = CO_DE_VS;
2164 /* Fixme: Change other options. */
2177 /* This function called to initialized a new control object. It is
2178 assumed that this object has been zeroed out before calling this
2181 gpg_init_default_ctrl (ctrl_t ctrl)
2183 ctrl->magic = SERVER_CONTROL_MAGIC;
2187 /* This function is called to deinitialize a control object. It is
2190 gpg_deinit_default_ctrl (ctrl_t ctrl)
2193 tofu_closedbs (ctrl);
2195 gpg_dirmngr_deinit_session_data (ctrl);
2197 keydb_release (ctrl->cached_getkey_kdb);
2202 get_default_configname (void)
2204 char *configname = NULL;
2205 char *name = xstrdup (GPG_NAME EXTSEP_S "conf-" SAFE_VERSION);
2206 char *ver = &name[strlen (GPG_NAME EXTSEP_S "conf-")];
2217 if ((tok = strrchr (ver, SAFE_VERSION_DASH)))
2219 else if ((tok = strrchr (ver, SAFE_VERSION_DOT)))
2225 configname = make_filename (gnupg_homedir (), name, NULL);
2227 while (access (configname, R_OK));
2232 configname = make_filename (gnupg_homedir (),
2233 GPG_NAME EXTSEP_S "conf", NULL);
2234 if (! access (configname, R_OK))
2236 /* Print a warning when both config files are present. */
2237 char *p = make_filename (gnupg_homedir (), "options", NULL);
2238 if (! access (p, R_OK))
2239 log_info (_("Note: old default options file '%s' ignored\n"), p);
2244 /* Use the old default only if it exists. */
2245 char *p = make_filename (gnupg_homedir (), "options", NULL);
2246 if (!access (p, R_OK))
2259 main (int argc, char **argv)
2261 ARGPARSE_ARGS pargs;
2270 strlist_t remusr = NULL;
2271 strlist_t locusr = NULL;
2272 strlist_t nrings = NULL;
2273 armor_filter_context_t *afx = NULL;
2274 int detached_sig = 0;
2275 FILE *configfp = NULL;
2276 char *configname = NULL;
2277 char *save_configname = NULL;
2278 char *default_configname = NULL;
2279 unsigned configlineno;
2280 int parse_debug = 0;
2281 int default_config = 1;
2282 int default_keyring = 1;
2285 char *logfile = NULL;
2286 int use_random_seed = 1;
2287 enum cmd_and_opt_values cmd = 0;
2288 const char *debug_level = NULL;
2289 #ifndef NO_TRUST_MODELS
2290 const char *trustdb_name = NULL;
2291 #endif /*!NO_TRUST_MODELS*/
2292 char *def_cipher_string = NULL;
2293 char *def_digest_string = NULL;
2294 char *compress_algo_string = NULL;
2295 char *cert_digest_string = NULL;
2296 char *s2k_cipher_string = NULL;
2297 char *s2k_digest_string = NULL;
2298 char *pers_cipher_list = NULL;
2299 char *pers_digest_list = NULL;
2300 char *pers_compress_list = NULL;
2304 int ovrseskeyfd = -1;
2305 int fpr_maybe_cmd = 0; /* --fingerprint maybe a command. */
2306 int any_explicit_recipient = 0;
2307 int default_akl = 1;
2308 int require_secmem = 0;
2310 struct assuan_malloc_hooks malloc_hooks;
2313 static int print_dane_records;
2314 static int print_pka_records;
2319 #endif /* __riscos__ */
2321 /* Please note that we may running SUID(ROOT), so be very CAREFUL
2322 when adding any stuff between here and the call to
2323 secmem_init() somewhere after the option parsing. */
2324 early_system_init ();
2325 gnupg_reopen_std (GPG_NAME);
2327 gnupg_rl_initialize ();
2328 set_strusage (my_strusage);
2329 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
2330 log_set_prefix (GPG_NAME, GPGRT_LOG_WITH_PREFIX);
2332 /* Make sure that our subsystems are ready. */
2334 init_common_subsystems (&argc, &argv);
2336 /* Use our own logging handler for Libcgrypt. */
2337 setup_libgcrypt_logging ();
2339 /* Put random number into secure memory */
2340 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
2342 may_coredump = disable_core_dumps();
2344 gnupg_init_signals (0, emergency_cleanup);
2346 dotlock_create (NULL, 0); /* Register lock file cleanup. */
2348 /* Tell the compliance module who we are. */
2349 gnupg_initialize_compliance (GNUPG_MODULE_NAME_GPG);
2352 opt.session_env = session_env_new ();
2353 if (!opt.session_env)
2354 log_fatal ("error allocating session environment block: %s\n",
2357 opt.command_fd = -1; /* no command fd */
2358 opt.compress_level = -1; /* defaults to standard compress level */
2359 opt.bz2_compress_level = -1; /* defaults to standard compress level */
2360 /* note: if you change these lines, look at oOpenPGP */
2361 opt.def_cipher_algo = 0;
2362 opt.def_digest_algo = 0;
2363 opt.cert_digest_algo = 0;
2364 opt.compress_algo = -1; /* defaults to DEFAULT_COMPRESS_ALGO */
2365 opt.s2k_mode = 3; /* iterated+salted */
2366 opt.s2k_count = 0; /* Auto-calibrate when needed. */
2367 opt.s2k_cipher_algo = DEFAULT_CIPHER_ALGO;
2368 opt.completes_needed = 1;
2369 opt.marginals_needed = 3;
2370 opt.max_cert_depth = 5;
2371 opt.escape_from = 1;
2372 opt.flags.require_cross_cert = 1;
2373 opt.import_options = IMPORT_REPAIR_KEYS;
2374 opt.export_options = EXPORT_ATTRIBUTES;
2375 opt.keyserver_options.import_options = (IMPORT_REPAIR_KEYS
2376 | IMPORT_REPAIR_PKS_SUBKEY_BUG);
2377 opt.keyserver_options.export_options = EXPORT_ATTRIBUTES;
2378 opt.keyserver_options.options = KEYSERVER_HONOR_PKA_RECORD;
2379 opt.verify_options = (LIST_SHOW_UID_VALIDITY
2380 | VERIFY_SHOW_POLICY_URLS
2381 | VERIFY_SHOW_STD_NOTATIONS
2382 | VERIFY_SHOW_KEYSERVER_URLS);
2383 opt.list_options = (LIST_SHOW_UID_VALIDITY
2385 #ifdef NO_TRUST_MODELS
2386 opt.trust_model = TM_ALWAYS;
2388 opt.trust_model = TM_AUTO;
2390 opt.tofu_default_policy = TOFU_POLICY_AUTO;
2391 opt.mangle_dos_filenames = 0;
2392 opt.min_cert_level = 2;
2393 set_screen_dimensions ();
2394 opt.keyid_format = KF_NONE;
2395 opt.def_sig_expire = "0";
2396 opt.def_cert_expire = "0";
2397 gnupg_set_homedir (NULL);
2398 opt.passphrase_repeat = 1;
2399 opt.emit_version = 0;
2400 opt.weak_digests = NULL;
2402 /* Check whether we have a config file on the command line. */
2407 pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
2408 while( arg_parse( &pargs, opts) ) {
2409 if( pargs.r_opt == oDebug || pargs.r_opt == oDebugAll )
2411 else if (pargs.r_opt == oDebugIOLBF)
2412 es_setvbuf (es_stdout, NULL, _IOLBF, 0);
2413 else if( pargs.r_opt == oOptions ) {
2414 /* yes there is one, so we do not try the default one, but
2415 * read the option file when it is encountered at the commandline
2419 else if( pargs.r_opt == oNoOptions )
2421 default_config = 0; /* --no-options */
2422 opt.no_homedir_creation = 1;
2424 else if( pargs.r_opt == oHomedir )
2425 gnupg_set_homedir (pargs.r.ret_str);
2426 else if( pargs.r_opt == oNoPermissionWarn )
2428 else if (pargs.r_opt == oStrict )
2432 else if (pargs.r_opt == oNoStrict )
2438 #ifdef HAVE_DOSISH_SYSTEM
2439 if ( strchr (gnupg_homedir (), '\\') ) {
2440 char *d, *buf = xmalloc (strlen (gnupg_homedir ())+1);
2442 for (d=buf, s = gnupg_homedir (); *s; s++)
2444 *d++ = *s == '\\'? '/': *s;
2445 #ifdef HAVE_W32_SYSTEM
2446 if (s[1] && IsDBCSLeadByte (*s))
2451 gnupg_set_homedir (buf);
2455 /* Initialize the secure memory. */
2456 if (!gcry_control (GCRYCTL_INIT_SECMEM, SECMEM_BUFFER_SIZE, 0))
2458 #if defined(HAVE_GETUID) && defined(HAVE_GETEUID)
2459 /* There should be no way to get to this spot while still carrying
2460 setuid privs. Just in case, bomb out if we are. */
2461 if ( getuid () != geteuid () )
2466 /* Okay, we are now working under our real uid */
2468 /* malloc hooks go here ... */
2469 malloc_hooks.malloc = gcry_malloc;
2470 malloc_hooks.realloc = gcry_realloc;
2471 malloc_hooks.free = gcry_free;
2472 assuan_set_malloc_hooks (&malloc_hooks);
2473 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
2474 setup_libassuan_logging (&opt.debug, NULL);
2476 /* Set default options which require that malloc stuff is ready. */
2477 additional_weak_digest ("MD5");
2478 parse_auto_key_locate ("local,wkd");
2480 /* Try for a version specific config file first */
2481 default_configname = get_default_configname ();
2483 configname = xstrdup (default_configname);
2489 pargs.flags= ARGPARSE_FLAG_KEEP;
2491 /* By this point we have a homedir, and cannot change it. */
2492 check_permissions (gnupg_homedir (), 0);
2496 if(check_permissions(configname,1))
2498 /* If any options file is unsafe, then disable any external
2499 programs for keyserver calls or photo IDs. Since the
2500 external program to call is set in the options file, a
2501 unsafe options file can lead to an arbitrary program
2508 configfp = fopen( configname, "r" );
2509 if (configfp && is_secured_file (fileno (configfp)))
2513 gpg_err_set_errno (EPERM);
2516 if( default_config ) {
2518 log_info(_("Note: no default option file '%s'\n"),
2522 log_error(_("option file '%s': %s\n"),
2523 configname, strerror(errno) );
2526 xfree(configname); configname = NULL;
2528 if( parse_debug && configname )
2529 log_info(_("reading options from '%s'\n"), configname );
2533 while( optfile_parse( configfp, configname, &configlineno,
2536 switch( pargs.r_opt )
2539 case aListGcryptConfig:
2542 set_cmd (&cmd, pargs.r_opt);
2543 /* Do not register a keyring for these commands. */
2544 default_keyring = -1;
2557 #ifdef ENABLE_CARD_SUPPORT
2561 #endif /* ENABLE_CARD_SUPPORT*/
2566 case aExportSecretSub:
2578 case aUpdateTrustDB:
2580 case aListTrustPath:
2585 case aQuickLSignKey:
2593 case aQuickSetExpire:
2594 case aQuickSetPrimaryUid:
2595 case aExportOwnerTrust:
2596 case aImportOwnerTrust:
2597 case aRebuildKeydbCaches:
2598 set_cmd (&cmd, pargs.r_opt);
2604 case aDeleteSecretKeys:
2605 case aDeleteSecretAndPublicKeys:
2608 set_cmd (&cmd, pargs.r_opt);
2613 set_cmd (&cmd, pargs.r_opt);
2614 opt.import_options |= IMPORT_SHOW;
2615 opt.import_options |= IMPORT_DRY_RUN;
2616 opt.import_options &= ~IMPORT_REPAIR_KEYS;
2617 opt.list_options |= LIST_SHOW_UNUSABLE_UIDS;
2618 opt.list_options |= LIST_SHOW_UNUSABLE_SUBKEYS;
2619 opt.list_options |= LIST_SHOW_NOTATIONS;
2620 opt.list_options |= LIST_SHOW_POLICY_URLS;
2623 case aDetachedSign: detached_sig = 1; set_cmd( &cmd, aSign ); break;
2625 case aDecryptFiles: multifile=1; /* fall through */
2626 case aDecrypt: set_cmd( &cmd, aDecrypt); break;
2628 case aEncrFiles: multifile=1; /* fall through */
2629 case aEncr: set_cmd( &cmd, aEncr); break;
2631 case aVerifyFiles: multifile=1; /* fall through */
2632 case aVerify: set_cmd( &cmd, aVerify); break;
2635 set_cmd (&cmd, pargs.r_opt);
2640 set_cmd (&cmd, pargs.r_opt);
2643 case oArmor: opt.armor = 1; opt.no_armor=0; break;
2644 case oOutput: opt.outfile = pargs.r.ret_str; break;
2646 case oMaxOutput: opt.max_output = pargs.r.ret_ulong; break;
2648 case oInputSizeHint:
2649 opt.input_size_hint = string_to_u64 (pargs.r.ret_str);
2652 case oQuiet: opt.quiet = 1; break;
2653 case oNoTTY: tty_no_terminal(1); break;
2654 case oDryRun: opt.dry_run = 1; break;
2655 case oInteractive: opt.interactive = 1; break;
2658 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2659 opt.list_options|=LIST_SHOW_UNUSABLE_UIDS;
2660 opt.list_options|=LIST_SHOW_UNUSABLE_SUBKEYS;
2668 case oUseAgent: /* Dummy. */
2672 obsolete_option (configname, configlineno, "no-use-agent");
2675 obsolete_option (configname, configlineno, "gpg-agent-info");
2678 obsolete_scdaemon_option (configname, configlineno, "reader-port");
2681 obsolete_scdaemon_option (configname, configlineno, "ctapi-driver");
2684 obsolete_scdaemon_option (configname, configlineno, "pcsc-driver");
2687 obsolete_scdaemon_option (configname, configlineno, "disable-ccid");
2689 case oHonorHttpProxy:
2690 obsolete_option (configname, configlineno, "honor-http-proxy");
2693 case oAnswerYes: opt.answer_yes = 1; break;
2694 case oAnswerNo: opt.answer_no = 1; break;
2695 case oKeyring: append_to_strlist( &nrings, pargs.r.ret_str); break;
2696 case oPrimaryKeyring:
2697 sl = append_to_strlist (&nrings, pargs.r.ret_str);
2698 sl->flags = KEYDB_RESOURCE_FLAG_PRIMARY;
2701 deprecated_warning(configname,configlineno,"--show-keyring",
2702 "--list-options ","show-keyring");
2703 opt.list_options|=LIST_SHOW_KEYRING;
2707 if (parse_debug_flag (pargs.r.ret_str, &opt.debug, debug_flags))
2709 pargs.r_opt = ARGPARSE_INVALID_ARG;
2710 pargs.err = ARGPARSE_PRINT_ERROR;
2714 case oDebugAll: opt.debug = ~0; break;
2715 case oDebugLevel: debug_level = pargs.r.ret_str; break;
2717 case oDebugIOLBF: break; /* Already set in pre-parse step. */
2720 set_status_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
2723 set_status_fd ( open_info_file (pargs.r.ret_str, 1, 0) );
2726 set_attrib_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
2728 case oAttributeFile:
2729 set_attrib_fd ( open_info_file (pargs.r.ret_str, 1, 1) );
2732 log_set_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1));
2735 logfile = pargs.r.ret_str;
2738 case oWithFingerprint:
2739 opt.with_fingerprint = 1;
2742 case oWithSubkeyFingerprint:
2743 opt.with_subkey_fingerprint = 1;
2745 case oWithICAOSpelling:
2746 opt.with_icao_spelling = 1;
2754 opt.with_keygrip = 1;
2758 opt.with_secret = 1;
2762 opt.with_wkd_hash = 1;
2765 case oWithKeyOrigin:
2766 opt.with_key_origin = 1;
2769 case oSecretKeyring:
2770 /* Ignore this old option. */
2774 /* config files may not be nested (silently ignore them) */
2777 configname = xstrdup(pargs.r.ret_str);
2781 case oNoArmor: opt.no_armor=1; opt.armor=0; break;
2784 if (default_keyring > 0)
2785 default_keyring = 0;
2788 default_keyring = -1;
2791 case oNoGreeting: nogreeting = 1; break;
2794 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2798 gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
2800 case oEmitVersion: opt.emit_version++; break;
2801 case oNoEmitVersion: opt.emit_version=0; break;
2802 case oCompletesNeeded: opt.completes_needed = pargs.r.ret_int; break;
2803 case oMarginalsNeeded: opt.marginals_needed = pargs.r.ret_int; break;
2804 case oMaxCertDepth: opt.max_cert_depth = pargs.r.ret_int; break;
2806 #ifndef NO_TRUST_MODELS
2807 case oTrustDBName: trustdb_name = pargs.r.ret_str; break;
2809 #endif /*!NO_TRUST_MODELS*/
2811 sl = add_to_strlist (&opt.def_secret_key, pargs.r.ret_str);
2812 sl->flags = (pargs.r_opt << PK_LIST_SHIFT);
2814 sl->flags |= PK_LIST_CONFIG;
2817 if( *pargs.r.ret_str )
2819 xfree (opt.def_recipient);
2820 opt.def_recipient = make_username(pargs.r.ret_str);
2823 case oDefRecipientSelf:
2824 xfree(opt.def_recipient); opt.def_recipient = NULL;
2825 opt.def_recipient_self = 1;
2827 case oNoDefRecipient:
2828 xfree(opt.def_recipient); opt.def_recipient = NULL;
2829 opt.def_recipient_self = 0;
2831 case oNoOptions: opt.no_homedir_creation = 1; break; /* no-options */
2832 case oHomedir: break;
2833 case oNoBatch: opt.batch = 0; break;
2835 case oWithTofuInfo: opt.with_tofu_info = 1; break;
2837 case oWithKeyData: opt.with_key_data=1; /*FALLTHRU*/
2838 case oWithColons: opt.with_colons=':'; break;
2840 case oWithSigCheck: opt.check_sigs = 1; /*FALLTHRU*/
2841 case oWithSigList: opt.list_sigs = 1; break;
2843 case oSkipVerify: opt.skip_verify=1; break;
2845 case oSkipHiddenRecipients: opt.skip_hidden_recipients = 1; break;
2846 case oNoSkipHiddenRecipients: opt.skip_hidden_recipients = 0; break;
2848 case aListSecretKeys: set_cmd( &cmd, aListSecretKeys); break;
2850 #ifndef NO_TRUST_MODELS
2851 /* There are many programs (like mutt) that call gpg with
2852 --always-trust so keep this option around for a long
2854 case oAlwaysTrust: opt.trust_model=TM_ALWAYS; break;
2856 parse_trust_model(pargs.r.ret_str);
2858 #endif /*!NO_TRUST_MODELS*/
2859 case oTOFUDefaultPolicy:
2860 opt.tofu_default_policy = parse_tofu_policy (pargs.r.ret_str);
2863 obsolete_option (configname, configlineno, "tofu-db-format");
2866 case oForceOwnertrust:
2867 log_info(_("Note: %s is not for normal use!\n"),
2868 "--force-ownertrust");
2869 opt.force_ownertrust=string_to_trust_value(pargs.r.ret_str);
2870 if(opt.force_ownertrust==-1)
2872 log_error("invalid ownertrust '%s'\n",pargs.r.ret_str);
2873 opt.force_ownertrust=0;
2876 case oLoadExtension:
2877 /* Dummy so that gpg 1.4 conf files can work. Should
2878 eventually be removed. */
2883 int compliance = gnupg_parse_compliance_option
2885 compliance_options, DIM (compliance_options),
2889 set_compliance_option (compliance);
2900 set_compliance_option (pargs.r_opt);
2903 case oRFC2440Text: opt.rfc2440_text=1; break;
2904 case oNoRFC2440Text: opt.rfc2440_text=0; break;
2908 opt.set_filename = pargs.r.ret_str;
2910 opt.set_filename = native_to_utf8(pargs.r.ret_str);
2912 case oForYourEyesOnly: eyes_only = 1; break;
2913 case oNoForYourEyesOnly: eyes_only = 0; break;
2915 add_policy_url(pargs.r.ret_str,0);
2916 add_policy_url(pargs.r.ret_str,1);
2918 case oSigPolicyURL: add_policy_url(pargs.r.ret_str,0); break;
2919 case oCertPolicyURL: add_policy_url(pargs.r.ret_str,1); break;
2920 case oShowPolicyURL:
2921 deprecated_warning(configname,configlineno,"--show-policy-url",
2922 "--list-options ","show-policy-urls");
2923 deprecated_warning(configname,configlineno,"--show-policy-url",
2924 "--verify-options ","show-policy-urls");
2925 opt.list_options|=LIST_SHOW_POLICY_URLS;
2926 opt.verify_options|=VERIFY_SHOW_POLICY_URLS;
2928 case oNoShowPolicyURL:
2929 deprecated_warning(configname,configlineno,"--no-show-policy-url",
2930 "--list-options ","no-show-policy-urls");
2931 deprecated_warning(configname,configlineno,"--no-show-policy-url",
2932 "--verify-options ","no-show-policy-urls");
2933 opt.list_options&=~LIST_SHOW_POLICY_URLS;
2934 opt.verify_options&=~VERIFY_SHOW_POLICY_URLS;
2936 case oSigKeyserverURL: add_keyserver_url(pargs.r.ret_str,0); break;
2937 case oUseEmbeddedFilename:
2938 opt.flags.use_embedded_filename=1;
2940 case oNoUseEmbeddedFilename:
2941 opt.flags.use_embedded_filename=0;
2944 if(pargs.r.ret_str[0])
2945 append_to_strlist(&opt.comments,pargs.r.ret_str);
2947 case oDefaultComment:
2948 deprecated_warning(configname,configlineno,
2949 "--default-comment","--no-comments","");
2952 free_strlist(opt.comments);
2955 case oThrowKeyids: opt.throw_keyids = 1; break;
2956 case oNoThrowKeyids: opt.throw_keyids = 0; break;
2958 deprecated_warning(configname,configlineno,"--show-photos",
2959 "--list-options ","show-photos");
2960 deprecated_warning(configname,configlineno,"--show-photos",
2961 "--verify-options ","show-photos");
2962 opt.list_options|=LIST_SHOW_PHOTOS;
2963 opt.verify_options|=VERIFY_SHOW_PHOTOS;
2966 deprecated_warning(configname,configlineno,"--no-show-photos",
2967 "--list-options ","no-show-photos");
2968 deprecated_warning(configname,configlineno,"--no-show-photos",
2969 "--verify-options ","no-show-photos");
2970 opt.list_options&=~LIST_SHOW_PHOTOS;
2971 opt.verify_options&=~VERIFY_SHOW_PHOTOS;
2973 case oPhotoViewer: opt.photo_viewer = pargs.r.ret_str; break;
2975 case oDisableSignerUID: opt.flags.disable_signer_uid = 1; break;
2977 case oS2KMode: opt.s2k_mode = pargs.r.ret_int; break;
2978 case oS2KDigest: s2k_digest_string = xstrdup(pargs.r.ret_str); break;
2979 case oS2KCipher: s2k_cipher_string = xstrdup(pargs.r.ret_str); break;
2981 if (pargs.r.ret_int)
2982 opt.s2k_count = encode_s2k_iterations (pargs.r.ret_int);
2984 opt.s2k_count = 0; /* Auto-calibrate when needed. */
2988 case oHiddenRecipient:
2989 case oRecipientFile:
2990 case oHiddenRecipientFile:
2991 /* Store the recipient. Note that we also store the
2992 * option as private data in the flags. This is achieved
2993 * by shifting the option value to the left so to keep
2994 * enough space for the flags. */
2995 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2996 sl->flags = (pargs.r_opt << PK_LIST_SHIFT);
2998 sl->flags |= PK_LIST_CONFIG;
2999 if (pargs.r_opt == oHiddenRecipient
3000 || pargs.r_opt == oHiddenRecipientFile)
3001 sl->flags |= PK_LIST_HIDDEN;
3002 if (pargs.r_opt == oRecipientFile
3003 || pargs.r_opt == oHiddenRecipientFile)
3004 sl->flags |= PK_LIST_FROM_FILE;
3005 any_explicit_recipient = 1;
3009 case oHiddenEncryptTo:
3010 /* Store an additional recipient. */
3011 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
3012 sl->flags = ((pargs.r_opt << PK_LIST_SHIFT) | PK_LIST_ENCRYPT_TO);
3014 sl->flags |= PK_LIST_CONFIG;
3015 if (pargs.r_opt == oHiddenEncryptTo)
3016 sl->flags |= PK_LIST_HIDDEN;
3020 opt.no_encrypt_to = 1;
3022 case oEncryptToDefaultKey:
3023 opt.encrypt_to_default_key = configfp ? 2 : 1;
3027 add_to_strlist2 (&opt.secret_keys_to_try,
3028 pargs.r.ret_str, utf8_strings);
3031 case oMimemode: opt.mimemode = opt.textmode = 1; break;
3032 case oTextmodeShort: opt.textmode = 2; break;
3033 case oTextmode: opt.textmode=1; break;
3034 case oNoTextmode: opt.textmode=opt.mimemode=0; break;
3036 case oExpert: opt.expert = 1; break;
3037 case oNoExpert: opt.expert = 0; break;
3039 if(*pargs.r.ret_str!='\0')
3041 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
3042 log_error(_("'%s' is not a valid signature expiration\n"),
3045 opt.def_sig_expire=pargs.r.ret_str;
3048 case oAskSigExpire: opt.ask_sig_expire = 1; break;
3049 case oNoAskSigExpire: opt.ask_sig_expire = 0; break;
3050 case oDefCertExpire:
3051 if(*pargs.r.ret_str!='\0')
3053 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
3054 log_error(_("'%s' is not a valid signature expiration\n"),
3057 opt.def_cert_expire=pargs.r.ret_str;
3060 case oAskCertExpire: opt.ask_cert_expire = 1; break;
3061 case oNoAskCertExpire: opt.ask_cert_expire = 0; break;
3062 case oDefCertLevel: opt.def_cert_level=pargs.r.ret_int; break;
3063 case oMinCertLevel: opt.min_cert_level=pargs.r.ret_int; break;
3064 case oAskCertLevel: opt.ask_cert_level = 1; break;
3065 case oNoAskCertLevel: opt.ask_cert_level = 0; break;
3066 case oLocalUser: /* store the local users */
3067 sl = add_to_strlist2( &locusr, pargs.r.ret_str, utf8_strings );
3068 sl->flags = (pargs.r_opt << PK_LIST_SHIFT);
3070 sl->flags |= PK_LIST_CONFIG;
3074 char *mbox = mailbox_from_userid (pargs.r.ret_str);
3076 log_error (_("\"%s\" is not a proper mail address\n"),
3080 add_to_strlist (&opt.sender_list, mbox);
3086 /* this is the -z command line option */
3087 opt.compress_level = opt.bz2_compress_level = pargs.r.ret_int;
3089 case oCompressLevel: opt.compress_level = pargs.r.ret_int; break;
3090 case oBZ2CompressLevel: opt.bz2_compress_level = pargs.r.ret_int; break;
3091 case oBZ2DecompressLowmem: opt.bz2_decompress_lowmem=1; break;
3093 set_passphrase_from_string(pargs.r.ret_str);
3096 pwfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
3098 case oPassphraseFile:
3099 pwfd = open_info_file (pargs.r.ret_str, 0, 1);
3101 case oPassphraseRepeat:
3102 opt.passphrase_repeat = pargs.r.ret_int;
3106 opt.pinentry_mode = parse_pinentry_mode (pargs.r.ret_str);
3107 if (opt.pinentry_mode == -1)
3108 log_error (_("invalid pinentry mode '%s'\n"), pargs.r.ret_str);
3111 case oRequestOrigin:
3112 opt.request_origin = parse_request_origin (pargs.r.ret_str);
3113 if (opt.request_origin == -1)
3114 log_error (_("invalid request origin '%s'\n"), pargs.r.ret_str);
3118 opt.command_fd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
3119 if (! gnupg_fd_valid (opt.command_fd))
3120 log_error ("command-fd is invalid: %s\n", strerror (errno));
3123 opt.command_fd = open_info_file (pargs.r.ret_str, 0, 1);
3126 def_cipher_string = xstrdup(pargs.r.ret_str);
3129 def_digest_string = xstrdup(pargs.r.ret_str);
3132 /* If it is all digits, stick a Z in front of it for
3133 later. This is for backwards compatibility with
3134 versions that took the compress algorithm number. */
3136 char *pt=pargs.r.ret_str;
3139 if (!isascii (*pt) || !isdigit (*pt))
3147 compress_algo_string=xmalloc(strlen(pargs.r.ret_str)+2);
3148 strcpy(compress_algo_string,"Z");
3149 strcat(compress_algo_string,pargs.r.ret_str);
3152 compress_algo_string = xstrdup(pargs.r.ret_str);
3155 case oCertDigestAlgo:
3156 cert_digest_string = xstrdup(pargs.r.ret_str);
3160 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
3163 case oRequireSecmem: require_secmem=1; break;
3164 case oNoRequireSecmem: require_secmem=0; break;
3165 case oNoPermissionWarn: opt.no_perm_warn=1; break;
3166 case oDisplayCharset:
3167 if( set_native_charset( pargs.r.ret_str ) )
3168 log_error(_("'%s' is not a valid character set\n"),
3171 case oNotDashEscaped: opt.not_dash_escaped = 1; break;
3172 case oEscapeFrom: opt.escape_from = 1; break;
3173 case oNoEscapeFrom: opt.escape_from = 0; break;
3174 case oLockOnce: opt.lock_once = 1; break;
3181 #else /* __riscos__ */
3182 riscos_not_implemented("lock-multiple");
3183 #endif /* __riscos__ */
3187 keyserver_spec_t keyserver;
3188 keyserver = parse_keyserver_uri (pargs.r.ret_str, 0);
3190 log_error (_("could not parse keyserver URL\n"));
3193 /* We only support a single keyserver. Later ones
3194 override earlier ones. (Since we parse the
3195 config file first and then the command line
3196 arguments, the command line takes
3199 free_keyserver_spec (opt.keyserver);
3200 opt.keyserver = keyserver;
3204 case oKeyServerOptions:
3205 if(!parse_keyserver_options(pargs.r.ret_str))
3208 log_error(_("%s:%d: invalid keyserver options\n"),
3209 configname,configlineno);
3211 log_error(_("invalid keyserver options\n"));
3214 case oImportOptions:
3215 if(!parse_import_options(pargs.r.ret_str,&opt.import_options,1))
3218 log_error(_("%s:%d: invalid import options\n"),
3219 configname,configlineno);
3221 log_error(_("invalid import options\n"));
3225 rc = parse_and_set_import_filter (pargs.r.ret_str);
3227 log_error (_("invalid filter option: %s\n"), gpg_strerror (rc));
3229 case oExportOptions:
3230 if(!parse_export_options(pargs.r.ret_str,&opt.export_options,1))
3233 log_error(_("%s:%d: invalid export options\n"),
3234 configname,configlineno);
3236 log_error(_("invalid export options\n"));
3240 rc = parse_and_set_export_filter (pargs.r.ret_str);
3242 log_error (_("invalid filter option: %s\n"), gpg_strerror (rc));
3245 if(!parse_list_options(pargs.r.ret_str))
3248 log_error(_("%s:%d: invalid list options\n"),
3249 configname,configlineno);
3251 log_error(_("invalid list options\n"));
3254 case oVerifyOptions:
3256 struct parse_options vopts[]=
3258 {"show-photos",VERIFY_SHOW_PHOTOS,NULL,
3259 N_("display photo IDs during signature verification")},
3260 {"show-policy-urls",VERIFY_SHOW_POLICY_URLS,NULL,
3261 N_("show policy URLs during signature verification")},
3262 {"show-notations",VERIFY_SHOW_NOTATIONS,NULL,
3263 N_("show all notations during signature verification")},
3264 {"show-std-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
3265 N_("show IETF standard notations during signature verification")},
3266 {"show-standard-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
3268 {"show-user-notations",VERIFY_SHOW_USER_NOTATIONS,NULL,
3269 N_("show user-supplied notations during signature verification")},
3270 {"show-keyserver-urls",VERIFY_SHOW_KEYSERVER_URLS,NULL,
3271 N_("show preferred keyserver URLs during signature verification")},
3272 {"show-uid-validity",VERIFY_SHOW_UID_VALIDITY,NULL,
3273 N_("show user ID validity during signature verification")},
3274 {"show-unusable-uids",VERIFY_SHOW_UNUSABLE_UIDS,NULL,
3275 N_("show revoked and expired user IDs in signature verification")},
3276 {"show-primary-uid-only",VERIFY_SHOW_PRIMARY_UID_ONLY,NULL,
3277 N_("show only the primary user ID in signature verification")},
3278 {"pka-lookups",VERIFY_PKA_LOOKUPS,NULL,
3279 N_("validate signatures with PKA data")},
3280 {"pka-trust-increase",VERIFY_PKA_TRUST_INCREASE,NULL,
3281 N_("elevate the trust of signatures with valid PKA data")},
3285 if(!parse_options(pargs.r.ret_str,&opt.verify_options,vopts,1))
3288 log_error(_("%s:%d: invalid verify options\n"),
3289 configname,configlineno);
3291 log_error(_("invalid verify options\n"));
3295 case oTempDir: opt.temp_dir=pargs.r.ret_str; break;
3297 if(set_exec_path(pargs.r.ret_str))
3298 log_error(_("unable to set exec-path to %s\n"),pargs.r.ret_str);
3300 opt.exec_path_set=1;
3303 add_notation_data( pargs.r.ret_str, 0 );
3304 add_notation_data( pargs.r.ret_str, 1 );
3306 case oSigNotation: add_notation_data( pargs.r.ret_str, 0 ); break;
3307 case oCertNotation: add_notation_data( pargs.r.ret_str, 1 ); break;
3308 case oKnownNotation: register_known_notation (pargs.r.ret_str); break;
3310 deprecated_warning(configname,configlineno,"--show-notation",
3311 "--list-options ","show-notations");
3312 deprecated_warning(configname,configlineno,"--show-notation",
3313 "--verify-options ","show-notations");
3314 opt.list_options|=LIST_SHOW_NOTATIONS;
3315 opt.verify_options|=VERIFY_SHOW_NOTATIONS;
3317 case oNoShowNotation:
3318 deprecated_warning(configname,configlineno,"--no-show-notation",
3319 "--list-options ","no-show-notations");
3320 deprecated_warning(configname,configlineno,"--no-show-notation",
3321 "--verify-options ","no-show-notations");
3322 opt.list_options&=~LIST_SHOW_NOTATIONS;
3323 opt.verify_options&=~VERIFY_SHOW_NOTATIONS;
3325 case oUtf8Strings: utf8_strings = 1; break;
3326 case oNoUtf8Strings: utf8_strings = 0; break;
3327 case oDisableCipherAlgo:
3329 int algo = string_to_cipher_algo (pargs.r.ret_str);
3330 gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
3333 case oDisablePubkeyAlgo:
3335 int algo = gcry_pk_map_name (pargs.r.ret_str);
3336 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
3339 case oNoSigCache: opt.no_sig_cache = 1; break;
3340 case oAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid = 1; break;
3341 case oNoAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid=0; break;
3342 case oAllowFreeformUID: opt.allow_freeform_uid = 1; break;
3343 case oNoAllowFreeformUID: opt.allow_freeform_uid = 0; break;
3344 case oNoLiteral: opt.no_literal = 1; break;
3345 case oSetFilesize: opt.set_filesize = pargs.r.ret_ulong; break;
3346 case oFastListMode: opt.fast_list_mode = 1; break;
3347 case oFixedListMode: /* Dummy */ break;
3348 case oLegacyListMode: opt.legacy_list_mode = 1; break;
3349 case oPrintPKARecords: print_pka_records = 1; break;
3350 case oPrintDANERecords: print_dane_records = 1; break;
3351 case oListOnly: opt.list_only=1; break;
3352 case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
3353 case oIgnoreValidFrom: opt.ignore_valid_from = 1; break;
3354 case oIgnoreCrcError: opt.ignore_crc_error = 1; break;
3355 case oIgnoreMDCError: opt.ignore_mdc_error = 1; break;
3356 case oNoRandomSeedFile: use_random_seed = 0; break;
3358 case oAutoKeyRetrieve:
3359 opt.keyserver_options.options |= KEYSERVER_AUTO_KEY_RETRIEVE;
3361 case oNoAutoKeyRetrieve:
3362 opt.keyserver_options.options &= ~KEYSERVER_AUTO_KEY_RETRIEVE;
3365 case oShowSessionKey: opt.show_session_key = 1; break;
3366 case oOverrideSessionKey:
3367 opt.override_session_key = pargs.r.ret_str;
3369 case oOverrideSessionKeyFD:
3370 ovrseskeyfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
3373 deprecated_warning(configname,configlineno,"--merge-only",
3374 "--import-options ","merge-only");
3375 opt.import_options|=IMPORT_MERGE_ONLY;
3377 case oAllowSecretKeyImport: /* obsolete */ break;
3378 case oTryAllSecrets: opt.try_all_secrets = 1; break;
3379 case oTrustedKey: register_trusted_key( pargs.r.ret_str ); break;
3381 case oEnableSpecialFilenames:
3382 enable_special_filenames ();
3385 case oNoExpensiveTrustChecks: opt.no_expensive_trust_checks=1; break;
3386 case oAutoCheckTrustDB: opt.no_auto_check_trustdb=0; break;
3387 case oNoAutoCheckTrustDB: opt.no_auto_check_trustdb=1; break;
3388 case oPreservePermissions: opt.preserve_permissions=1; break;
3389 case oDefaultPreferenceList:
3390 opt.def_preference_list = pargs.r.ret_str;
3392 case oDefaultKeyserverURL:
3394 keyserver_spec_t keyserver;
3395 keyserver = parse_keyserver_uri (pargs.r.ret_str,1 );
3397 log_error (_("could not parse keyserver URL\n"));
3399 free_keyserver_spec (keyserver);
3401 opt.def_keyserver_url = pargs.r.ret_str;
3404 case oPersonalCipherPreferences:
3405 pers_cipher_list=pargs.r.ret_str;
3407 case oPersonalDigestPreferences:
3408 pers_digest_list=pargs.r.ret_str;
3410 case oPersonalCompressPreferences:
3411 pers_compress_list=pargs.r.ret_str;
3413 case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
3414 case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break;
3415 case oDisableDirmngr: opt.disable_dirmngr = 1; break;
3417 additional_weak_digest(pargs.r.ret_str);
3420 opt.unwrap_encryption = 1;
3422 case oOnlySignTextIDs:
3423 opt.only_sign_text_ids = 1;
3427 set_opt_session_env ("DISPLAY", pargs.r.ret_str);
3430 set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
3433 set_opt_session_env ("TERM", pargs.r.ret_str);
3436 set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
3439 case oLCctype: opt.lc_ctype = pargs.r.ret_str; break;
3440 case oLCmessages: opt.lc_messages = pargs.r.ret_str; break;
3442 case oGroup: add_group(pargs.r.ret_str); break;
3443 case oUnGroup: rm_group(pargs.r.ret_str); break;
3445 while(opt.grouplist)
3447 struct groupitem *iter=opt.grouplist;
3448 free_strlist(iter->values);
3449 opt.grouplist=opt.grouplist->next;
3459 case oMangleDosFilenames: opt.mangle_dos_filenames = 1; break;
3460 case oNoMangleDosFilenames: opt.mangle_dos_filenames = 0; break;
3461 case oEnableProgressFilter: opt.enable_progress_filter = 1; break;
3462 case oMultifile: multifile=1; break;
3464 if(ascii_strcasecmp(pargs.r.ret_str,"short")==0)
3465 opt.keyid_format=KF_SHORT;
3466 else if(ascii_strcasecmp(pargs.r.ret_str,"long")==0)
3467 opt.keyid_format=KF_LONG;
3468 else if(ascii_strcasecmp(pargs.r.ret_str,"0xshort")==0)
3469 opt.keyid_format=KF_0xSHORT;
3470 else if(ascii_strcasecmp(pargs.r.ret_str,"0xlong")==0)
3471 opt.keyid_format=KF_0xLONG;
3472 else if(ascii_strcasecmp(pargs.r.ret_str,"none")==0)
3473 opt.keyid_format = KF_NONE;
3475 log_error("unknown keyid-format '%s'\n",pargs.r.ret_str);
3478 case oExitOnStatusWriteError:
3479 opt.exit_on_status_write_error = 1;
3482 case oLimitCardInsertTries:
3483 opt.limit_card_insert_tries = pargs.r.ret_int;
3486 case oRequireCrossCert: opt.flags.require_cross_cert=1; break;
3487 case oNoRequireCrossCert: opt.flags.require_cross_cert=0; break;
3489 case oAutoKeyLocate:
3492 /* This is the first time --auto-key-locate is seen.
3493 * We need to reset the default akl. */
3497 if(!parse_auto_key_locate(pargs.r.ret_str))
3500 log_error(_("%s:%d: invalid auto-key-locate list\n"),
3501 configname,configlineno);
3503 log_error(_("invalid auto-key-locate list\n"));
3506 case oNoAutoKeyLocate:
3511 if(!parse_key_origin (pargs.r.ret_str))
3512 log_error (_("invalid argument for option \"%.50s\"\n"),
3516 case oEnableLargeRSA:
3517 #if SECMEM_BUFFER_SIZE >= 65536
3518 opt.flags.large_rsa=1;
3521 log_info("%s:%d: WARNING: gpg not built with large secure "
3522 "memory buffer. Ignoring enable-large-rsa\n",
3523 configname,configlineno);
3525 log_info("WARNING: gpg not built with large secure "
3526 "memory buffer. Ignoring --enable-large-rsa\n");
3527 #endif /* SECMEM_BUFFER_SIZE >= 65536 */
3529 case oDisableLargeRSA: opt.flags.large_rsa=0;
3532 case oEnableDSA2: opt.flags.dsa2=1; break;
3533 case oDisableDSA2: opt.flags.dsa2=0; break;
3535 case oAllowMultisigVerification:
3536 case oAllowMultipleMessages:
3537 opt.flags.allow_multiple_messages=1;
3540 case oNoAllowMultipleMessages:
3541 opt.flags.allow_multiple_messages=0;
3544 case oAllowWeakDigestAlgos:
3545 opt.flags.allow_weak_digest_algos = 1;
3548 case oFakedSystemTime:
3550 size_t len = strlen (pargs.r.ret_str);
3554 if (len > 0 && pargs.r.ret_str[len-1] == '!')
3557 pargs.r.ret_str[len-1] = '\0';
3560 faked_time = isotime2epoch (pargs.r.ret_str);
3561 if (faked_time == (time_t)(-1))
3562 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
3563 gnupg_set_time (faked_time, freeze);
3567 case oNoAutostart: opt.autostart = 0; break;
3568 case oNoSymkeyCache: opt.no_symkey_cache = 1; break;
3570 case oDefaultNewKeyAlgo:
3571 opt.def_new_key_algo = pargs.r.ret_str;
3578 pargs.err = ARGPARSE_PRINT_WARNING;
3581 pargs.err = ARGPARSE_PRINT_ERROR;
3582 /* The argparse fucntion calls a plain exit and thus
3583 * we need to print a status here. */
3584 write_status_failure ("option-parser",
3585 gpg_error(GPG_ERR_GENERAL));
3595 /* Remember the first config file name. */
3596 if (!save_configname)
3597 save_configname = configname;
3603 xfree(configname); configname = NULL;
3604 if (log_get_errorcount (0))
3606 write_status_failure ("option-parser", gpg_error(GPG_ERR_GENERAL));
3610 /* The command --gpgconf-list is pretty simple and may be called
3611 directly after the option parsing. */
3612 if (cmd == aGPGConfList)
3614 gpgconf_list (save_configname ? save_configname : default_configname);
3617 xfree (save_configname);
3618 xfree (default_configname);
3620 if (print_dane_records)
3621 log_error ("invalid option \"%s\"; use \"%s\" instead\n",
3622 "--print-dane-records",
3623 "--export-options export-dane");
3624 if (print_pka_records)
3625 log_error ("invalid option \"%s\"; use \"%s\" instead\n",
3626 "--print-pks-records",
3627 "--export-options export-pka");
3628 if (log_get_errorcount (0))
3630 write_status_failure ("option-checking", gpg_error(GPG_ERR_GENERAL));
3640 es_fprintf (es_stderr, "%s %s; %s\n",
3641 strusage(11), strusage(13), strusage(14) );
3642 es_fprintf (es_stderr, "%s\n", strusage(15) );
3644 #ifdef IS_DEVELOPMENT_VERSION
3649 if((s=strusage(25)))
3651 if((s=strusage(26)))
3653 if((s=strusage(27)))
3658 /* FIXME: We should use logging to a file only in server mode;
3659 however we have not yet implemetyed that. Thus we try to get
3660 away with --batch as indication for logging to file
3662 if (logfile && opt.batch)
3664 log_set_file (logfile);
3665 log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
3668 if (opt.verbose > 2)
3669 log_info ("using character set '%s'\n", get_native_charset ());
3671 if( may_coredump && !opt.quiet )
3672 log_info(_("WARNING: program may create a core file!\n"));
3674 if (opt.flags.rfc4880bis)
3675 log_info ("WARNING: using experimental features from RFC4880bis!\n");
3678 opt.mimemode = 0; /* This will use text mode instead. */
3682 if (opt.set_filename)
3683 log_info(_("WARNING: %s overrides %s\n"),
3684 "--for-your-eyes-only","--set-filename");
3686 opt.set_filename="_CONSOLE";
3689 if (opt.no_literal) {
3690 log_info(_("Note: %s is not for normal use!\n"), "--no-literal");
3692 log_error(_("%s not allowed with %s!\n"),
3693 "--textmode", "--no-literal" );
3694 if (opt.set_filename)
3695 log_error(_("%s makes no sense with %s!\n"),
3696 eyes_only?"--for-your-eyes-only":"--set-filename",
3701 if (opt.set_filesize)
3702 log_info(_("Note: %s is not for normal use!\n"), "--set-filesize");
3706 if (gnupg_faked_time_p ())
3708 gnupg_isotime_t tbuf;
3710 log_info (_("WARNING: running with faked system time: "));
3711 gnupg_get_isotime (tbuf);
3712 dump_isotime (tbuf);
3716 /* Print a warning if an argument looks like an option. */
3717 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
3721 for (i=0; i < argc; i++)
3722 if (argv[i][0] == '-' && argv[i][1] == '-')
3723 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
3727 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
3729 if(require_secmem && !got_secmem)
3731 log_info(_("will not run with insecure memory due to %s\n"),
3732 "--require-secmem");
3733 write_status_failure ("option-checking", gpg_error(GPG_ERR_GENERAL));
3737 set_debug (debug_level);
3739 log_clock ("start");
3741 /* Do these after the switch(), so they can override settings. */
3744 /* That does not anymore work because we have no more support
3745 for v3 signatures. */
3747 opt.ask_sig_expire=0;
3751 /* That does not anymore work because we have no more support
3752 for v3 signatures. */
3754 opt.ask_sig_expire=0;
3762 if( def_cipher_string ) {
3763 opt.def_cipher_algo = string_to_cipher_algo (def_cipher_string);
3764 xfree(def_cipher_string); def_cipher_string = NULL;
3765 if ( openpgp_cipher_test_algo (opt.def_cipher_algo) )
3766 log_error(_("selected cipher algorithm is invalid\n"));
3768 if( def_digest_string ) {
3769 opt.def_digest_algo = string_to_digest_algo (def_digest_string);
3770 xfree(def_digest_string); def_digest_string = NULL;
3771 if ( openpgp_md_test_algo (opt.def_digest_algo) )
3772 log_error(_("selected digest algorithm is invalid\n"));
3774 if( compress_algo_string ) {
3775 opt.compress_algo = string_to_compress_algo(compress_algo_string);
3776 xfree(compress_algo_string); compress_algo_string = NULL;
3777 if( check_compress_algo(opt.compress_algo) )
3778 log_error(_("selected compression algorithm is invalid\n"));
3780 if( cert_digest_string ) {
3781 opt.cert_digest_algo = string_to_digest_algo (cert_digest_string);
3782 xfree(cert_digest_string); cert_digest_string = NULL;
3783 if (openpgp_md_test_algo(opt.cert_digest_algo))
3784 log_error(_("selected certification digest algorithm is invalid\n"));
3786 if( s2k_cipher_string ) {
3787 opt.s2k_cipher_algo = string_to_cipher_algo (s2k_cipher_string);
3788 xfree(s2k_cipher_string); s2k_cipher_string = NULL;
3789 if (openpgp_cipher_test_algo (opt.s2k_cipher_algo))
3790 log_error(_("selected cipher algorithm is invalid\n"));
3792 if( s2k_digest_string ) {
3793 opt.s2k_digest_algo = string_to_digest_algo (s2k_digest_string);
3794 xfree(s2k_digest_string); s2k_digest_string = NULL;
3795 if (openpgp_md_test_algo(opt.s2k_digest_algo))
3796 log_error(_("selected digest algorithm is invalid\n"));
3798 if( opt.completes_needed < 1 )
3799 log_error(_("completes-needed must be greater than 0\n"));
3800 if( opt.marginals_needed < 2 )
3801 log_error(_("marginals-needed must be greater than 1\n"));
3802 if( opt.max_cert_depth < 1 || opt.max_cert_depth > 255 )
3803 log_error(_("max-cert-depth must be in the range from 1 to 255\n"));
3804 if(opt.def_cert_level<0 || opt.def_cert_level>3)
3805 log_error(_("invalid default-cert-level; must be 0, 1, 2, or 3\n"));
3806 if( opt.min_cert_level < 1 || opt.min_cert_level > 3 )
3807 log_error(_("invalid min-cert-level; must be 1, 2, or 3\n"));
3808 switch( opt.s2k_mode ) {
3810 log_info(_("Note: simple S2K mode (0) is strongly discouraged\n"));
3812 case 1: case 3: break;
3814 log_error(_("invalid S2K mode; must be 0, 1 or 3\n"));
3817 /* This isn't actually needed, but does serve to error out if the
3818 string is invalid. */
3819 if(opt.def_preference_list &&
3820 keygen_set_std_prefs(opt.def_preference_list,0))
3821 log_error(_("invalid default preferences\n"));
3823 if(pers_cipher_list &&
3824 keygen_set_std_prefs(pers_cipher_list,PREFTYPE_SYM))
3825 log_error(_("invalid personal cipher preferences\n"));
3827 if(pers_digest_list &&
3828 keygen_set_std_prefs(pers_digest_list,PREFTYPE_HASH))
3829 log_error(_("invalid personal digest preferences\n"));
3831 if(pers_compress_list &&
3832 keygen_set_std_prefs(pers_compress_list,PREFTYPE_ZIP))
3833 log_error(_("invalid personal compress preferences\n"));
3835 /* We don't support all possible commands with multifile yet */
3846 cmdname="--sign --encrypt";
3849 cmdname="--clear-sign";
3852 cmdname="--detach-sign";
3855 cmdname="--symmetric";
3858 cmdname="--symmetric --encrypt";
3869 log_error(_("%s does not yet work with %s\n"),cmdname,"--multifile");
3872 if( log_get_errorcount(0) )
3874 write_status_failure ("option-postprocessing",
3875 gpg_error(GPG_ERR_GENERAL));
3879 if(opt.compress_level==0)
3880 opt.compress_algo=COMPRESS_ALGO_NONE;
3882 /* Check our chosen algorithms against the list of legal
3887 const char *badalg=NULL;
3888 preftype_t badtype=PREFTYPE_NONE;
3890 if(opt.def_cipher_algo
3891 && !algo_available(PREFTYPE_SYM,opt.def_cipher_algo,NULL))
3893 badalg = openpgp_cipher_algo_name (opt.def_cipher_algo);
3894 badtype = PREFTYPE_SYM;
3896 else if(opt.def_digest_algo
3897 && !algo_available(PREFTYPE_HASH,opt.def_digest_algo,NULL))
3899 badalg = gcry_md_algo_name (opt.def_digest_algo);
3900 badtype = PREFTYPE_HASH;
3902 else if(opt.cert_digest_algo
3903 && !algo_available(PREFTYPE_HASH,opt.cert_digest_algo,NULL))
3905 badalg = gcry_md_algo_name (opt.cert_digest_algo);
3906 badtype = PREFTYPE_HASH;
3908 else if(opt.compress_algo!=-1
3909 && !algo_available(PREFTYPE_ZIP,opt.compress_algo,NULL))
3911 badalg = compress_algo_to_string(opt.compress_algo);
3912 badtype = PREFTYPE_ZIP;
3920 log_info (_("cipher algorithm '%s'"
3921 " may not be used in %s mode\n"),
3923 gnupg_compliance_option_string (opt.compliance));
3926 log_info (_("digest algorithm '%s'"
3927 " may not be used in %s mode\n"),
3929 gnupg_compliance_option_string (opt.compliance));
3932 log_info (_("compression algorithm '%s'"
3933 " may not be used in %s mode\n"),
3935 gnupg_compliance_option_string (opt.compliance));
3941 compliance_failure();
3945 /* Check our chosen algorithms against the list of allowed
3946 * algorithms in the current compliance mode, and fail hard if it
3947 * is not. This is us being nice to the user informing her early
3948 * that the chosen algorithms are not available. We also check
3949 * and enforce this right before the actual operation. */
3950 if (opt.def_cipher_algo
3951 && ! gnupg_cipher_is_allowed (opt.compliance,
3957 || cmd == aSignEncrSym,
3958 opt.def_cipher_algo,
3959 GCRY_CIPHER_MODE_NONE))
3960 log_error (_("cipher algorithm '%s' may not be used in %s mode\n"),
3961 openpgp_cipher_algo_name (opt.def_cipher_algo),
3962 gnupg_compliance_option_string (opt.compliance));
3964 if (opt.def_digest_algo
3965 && ! gnupg_digest_is_allowed (opt.compliance,
3968 || cmd == aSignEncrSym
3970 || cmd == aClearsign,
3971 opt.def_digest_algo))
3972 log_error (_("digest algorithm '%s' may not be used in %s mode\n"),
3973 gcry_md_algo_name (opt.def_digest_algo),
3974 gnupg_compliance_option_string (opt.compliance));
3977 if (log_get_errorcount (0))
3979 write_status_failure ("option-checking", gpg_error(GPG_ERR_GENERAL));
3983 /* Set the random seed file. */
3984 if( use_random_seed ) {
3985 char *p = make_filename (gnupg_homedir (), "random_seed", NULL );
3986 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
3987 if (!access (p, F_OK))
3988 register_secured_file (p);
3992 /* If there is no command but the --fingerprint is given, default
3993 to the --list-keys command. */
3994 if (!cmd && fpr_maybe_cmd)
3996 set_cmd (&cmd, aListKeys);
4000 if( opt.verbose > 1 )
4001 set_packet_list_mode(1);
4003 /* Add the keyrings, but not for some special commands. We always
4004 * need to add the keyrings if we are running under SELinux, this
4005 * is so that the rings are added to the list of secured files.
4006 * We do not add any keyring if --no-keyring has been used. */
4007 if (default_keyring >= 0
4008 && (ALWAYS_ADD_KEYRINGS
4009 || (cmd != aDeArmor && cmd != aEnArmor && cmd != aGPGConfTest)))
4011 if (!nrings || default_keyring > 0) /* Add default ring. */
4012 keydb_add_resource ("pubring" EXTSEP_S GPGEXT_GPG,
4013 KEYDB_RESOURCE_FLAG_DEFAULT);
4014 for (sl = nrings; sl; sl = sl->next )
4015 keydb_add_resource (sl->d, sl->flags);
4017 FREE_STRLIST(nrings);
4019 if (opt.pinentry_mode == PINENTRY_MODE_LOOPBACK)
4020 /* In loopback mode, never ask for the password multiple
4023 opt.passphrase_repeat = 0;
4026 if (cmd == aGPGConfTest)
4030 if (pwfd != -1) /* Read the passphrase now. */
4031 read_passphrase_from_fd (pwfd);
4033 if (ovrseskeyfd != -1 ) /* Read the sessionkey now. */
4034 read_sessionkey_from_fd (ovrseskeyfd);
4036 fname = argc? *argv : NULL;
4038 if(fname && utf8_strings)
4039 opt.flags.utf8_filename=1;
4041 ctrl = xcalloc (1, sizeof *ctrl);
4042 gpg_init_default_ctrl (ctrl);
4044 #ifndef NO_TRUST_MODELS
4054 case aListGcryptConfig:
4057 case aExportOwnerTrust:
4058 rc = setup_trustdb (0, trustdb_name);
4061 rc = setup_trustdb (argc? 1:0, trustdb_name);
4066 rc = setup_trustdb (1, trustdb_name);
4069 /* If we are using TM_ALWAYS, we do not need to create the
4071 rc = setup_trustdb (opt.trust_model != TM_ALWAYS, trustdb_name);
4075 log_error (_("failed to initialize the TrustDB: %s\n"),
4077 #endif /*!NO_TRUST_MODELS*/
4086 if (!opt.quiet && any_explicit_recipient)
4087 log_info (_("WARNING: recipients (-r) given "
4088 "without using public key encryption\n"));
4095 /* Check for certain command whether we need to migrate a
4096 secring.gpg to the gpg-agent. */
4099 case aListSecretKeys:
4110 case aDeleteSecretKeys:
4111 case aDeleteSecretAndPublicKeys:
4116 case aQuickSetPrimaryUid:
4121 case aExportSecretSub:
4126 migrate_secring (ctrl);
4129 if (opt.with_secret)
4130 migrate_secring (ctrl);
4136 /* The command dispatcher. */
4143 case aStore: /* only store the file */
4145 wrong_args("--store [filename]");
4146 if( (rc = encrypt_store(fname)) )
4148 write_status_failure ("store", rc);
4149 log_error ("storing '%s' failed: %s\n",
4150 print_fname_stdin(fname),gpg_strerror (rc) );
4153 case aSym: /* encrypt the given file only with the symmetric cipher */
4155 wrong_args("--symmetric [filename]");
4156 if( (rc = encrypt_symmetric(fname)) )
4158 write_status_failure ("symencrypt", rc);
4159 log_error (_("symmetric encryption of '%s' failed: %s\n"),
4160 print_fname_stdin(fname),gpg_strerror (rc) );
4164 case aEncr: /* encrypt the given file */
4166 encrypt_crypt_files (ctrl, argc, argv, remusr);
4170 wrong_args("--encrypt [filename]");
4171 if( (rc = encrypt_crypt (ctrl, -1, fname, remusr, 0, NULL, -1)) )
4173 write_status_failure ("encrypt", rc);
4174 log_error("%s: encryption failed: %s\n",
4175 print_fname_stdin(fname), gpg_strerror (rc) );
4181 /* This works with PGP 8 in the sense that it acts just like a
4182 symmetric message. It doesn't work at all with 2 or 6. It
4183 might work with 7, but alas, I don't have a copy to test
4186 wrong_args("--symmetric --encrypt [filename]");
4187 else if(opt.s2k_mode==0)
4188 log_error(_("you cannot use --symmetric --encrypt"
4189 " with --s2k-mode 0\n"));
4190 else if(PGP6 || PGP7)
4191 log_error(_("you cannot use --symmetric --encrypt"
4193 gnupg_compliance_option_string (opt.compliance));
4196 if( (rc = encrypt_crypt (ctrl, -1, fname, remusr, 1, NULL, -1)) )
4198 write_status_failure ("encrypt", rc);
4199 log_error ("%s: encryption failed: %s\n",
4200 print_fname_stdin(fname), gpg_strerror (rc) );
4205 case aSign: /* sign the given file */
4207 if( detached_sig ) { /* sign all files */
4208 for( ; argc; argc--, argv++ )
4209 add_to_strlist( &sl, *argv );
4213 wrong_args("--sign [filename]");
4215 sl = xmalloc_clear( sizeof *sl + strlen(fname));
4216 strcpy(sl->d, fname);
4219 if ((rc = sign_file (ctrl, sl, detached_sig, locusr, 0, NULL, NULL)))
4221 write_status_failure ("sign", rc);
4222 log_error ("signing failed: %s\n", gpg_strerror (rc) );
4227 case aSignEncr: /* sign and encrypt the given file */
4229 wrong_args("--sign --encrypt [filename]");
4231 sl = xmalloc_clear( sizeof *sl + strlen(fname));
4232 strcpy(sl->d, fname);
4236 if ((rc = sign_file (ctrl, sl, detached_sig, locusr, 1, remusr, NULL)))
4238 write_status_failure ("sign-encrypt", rc);
4239 log_error("%s: sign+encrypt failed: %s\n",
4240 print_fname_stdin(fname), gpg_strerror (rc) );
4245 case aSignEncrSym: /* sign and encrypt the given file */
4247 wrong_args("--symmetric --sign --encrypt [filename]");
4248 else if(opt.s2k_mode==0)
4249 log_error(_("you cannot use --symmetric --sign --encrypt"
4250 " with --s2k-mode 0\n"));
4251 else if(PGP6 || PGP7)
4252 log_error(_("you cannot use --symmetric --sign --encrypt"
4254 gnupg_compliance_option_string (opt.compliance));
4259 sl = xmalloc_clear( sizeof *sl + strlen(fname));
4260 strcpy(sl->d, fname);
4264 if ((rc = sign_file (ctrl, sl, detached_sig, locusr,
4267 write_status_failure ("sign-encrypt", rc);
4268 log_error("%s: symmetric+sign+encrypt failed: %s\n",
4269 print_fname_stdin(fname), gpg_strerror (rc) );
4275 case aSignSym: /* sign and conventionally encrypt the given file */
4277 wrong_args("--sign --symmetric [filename]");
4278 rc = sign_symencrypt_file (ctrl, fname, locusr);
4281 write_status_failure ("sign-symencrypt", rc);
4282 log_error("%s: sign+symmetric failed: %s\n",
4283 print_fname_stdin(fname), gpg_strerror (rc) );
4287 case aClearsign: /* make a clearsig */
4289 wrong_args("--clear-sign [filename]");
4290 if( (rc = clearsign_file (ctrl, fname, locusr, NULL)) )
4292 write_status_failure ("sign", rc);
4293 log_error("%s: clear-sign failed: %s\n",
4294 print_fname_stdin(fname), gpg_strerror (rc) );
4301 if ((rc = verify_files (ctrl, argc, argv)))
4302 log_error("verify files failed: %s\n", gpg_strerror (rc) );
4306 if ((rc = verify_signatures (ctrl, argc, argv)))
4307 log_error("verify signatures failed: %s\n", gpg_strerror (rc) );
4310 write_status_failure ("verify", rc);
4315 decrypt_messages (ctrl, argc, argv);
4319 wrong_args("--decrypt [filename]");
4320 if( (rc = decrypt_message (ctrl, fname) ))
4322 write_status_failure ("decrypt", rc);
4323 log_error("decrypt_message failed: %s\n", gpg_strerror (rc) );
4329 case aQuickLSignKey:
4334 wrong_args ("--quick-[l]sign-key fingerprint [userids]");
4335 fpr = *argv++; argc--;
4337 for( ; argc; argc--, argv++)
4338 append_to_strlist2 (&sl, *argv, utf8_strings);
4339 keyedit_quick_sign (ctrl, fpr, sl, locusr, (cmd == aQuickLSignKey));
4346 wrong_args("--sign-key user-id");
4350 wrong_args("--lsign-key user-id");
4356 append_to_strlist(&sl,"sign");
4357 else if(cmd==aLSignKey)
4358 append_to_strlist(&sl,"lsign");
4362 append_to_strlist( &sl, "save" );
4363 username = make_username( fname );
4364 keyedit_menu (ctrl, username, locusr, sl, 0, 0 );
4369 case aEditKey: /* Edit a key signature */
4371 wrong_args("--edit-key user-id [commands]");
4372 username = make_username( fname );
4375 for( argc--, argv++ ; argc; argc--, argv++ )
4376 append_to_strlist( &sl, *argv );
4377 keyedit_menu (ctrl, username, locusr, sl, 0, 1 );
4381 keyedit_menu (ctrl, username, locusr, NULL, 0, 1 );
4387 wrong_args("--change-passphrase <user-id>");
4390 username = make_username (fname);
4391 keyedit_passwd (ctrl, username);
4397 case aDeleteSecretKeys:
4398 case aDeleteSecretAndPublicKeys:
4400 /* I'm adding these in reverse order as add_to_strlist2
4401 reverses them again, and it's easier to understand in the
4403 for( ; argc; argc-- )
4404 add_to_strlist2( &sl, argv[argc-1], utf8_strings );
4405 delete_keys (ctrl, sl,
4406 cmd==aDeleteSecretKeys, cmd==aDeleteSecretAndPublicKeys);
4411 opt.check_sigs = 1; /* fall through */
4413 opt.list_sigs = 1; /* fall through */
4416 for( ; argc; argc--, argv++ )
4417 add_to_strlist2( &sl, *argv, utf8_strings );
4418 public_key_list (ctrl, sl, 0);
4421 case aListSecretKeys:
4423 for( ; argc; argc--, argv++ )
4424 add_to_strlist2( &sl, *argv, utf8_strings );
4425 secret_key_list (ctrl, sl);
4430 for (; argc; argc--, argv++)
4431 add_to_strlist2( &sl, *argv, utf8_strings );
4432 public_key_list (ctrl, sl, 1);
4438 const char *x_algo, *x_usage, *x_expire;
4440 if (argc < 1 || argc > 4)
4441 wrong_args("--quick-generate-key USER-ID [ALGO [USAGE [EXPIRE]]]");
4442 username = make_username (fname);
4449 x_algo = *argv++; argc--;
4452 x_usage = *argv++; argc--;
4455 x_expire = *argv++; argc--;
4459 quick_generate_keypair (ctrl, username, x_algo, x_usage, x_expire);
4464 case aKeygen: /* generate a key */
4467 wrong_args("--generate-key [parameterfile]");
4468 generate_keypair (ctrl, 0, argc? *argv : NULL, NULL, 0);
4471 if (opt.command_fd != -1 && argc)
4474 wrong_args("--generate-key [parameterfile]");
4477 generate_keypair (ctrl, 0, argc? *argv : NULL, NULL, 0);
4480 wrong_args ("--generate-key");
4482 generate_keypair (ctrl, 0, NULL, NULL, 0);
4486 case aFullKeygen: /* Generate a key with all options. */
4490 wrong_args ("--full-generate-key [parameterfile]");
4491 generate_keypair (ctrl, 1, argc? *argv : NULL, NULL, 0);
4496 wrong_args("--full-generate-key");
4497 generate_keypair (ctrl, 1, NULL, NULL, 0);
4503 const char *uid, *newuid;
4506 wrong_args ("--quick-add-uid USER-ID NEW-USER-ID");
4507 uid = *argv++; argc--;
4508 newuid = *argv++; argc--;
4509 keyedit_quick_adduid (ctrl, uid, newuid);
4515 const char *x_fpr, *x_algo, *x_usage, *x_expire;
4517 if (argc < 1 || argc > 4)
4518 wrong_args ("--quick-add-key FINGERPRINT [ALGO [USAGE [EXPIRE]]]");
4519 x_fpr = *argv++; argc--;
4525 x_algo = *argv++; argc--;
4528 x_usage = *argv++; argc--;
4531 x_expire = *argv++; argc--;
4535 keyedit_quick_addkey (ctrl, x_fpr, x_algo, x_usage, x_expire);
4541 const char *uid, *uidtorev;
4544 wrong_args ("--quick-revoke-uid USER-ID USER-ID-TO-REVOKE");
4545 uid = *argv++; argc--;
4546 uidtorev = *argv++; argc--;
4547 keyedit_quick_revuid (ctrl, uid, uidtorev);
4551 case aQuickSetExpire:
4553 const char *x_fpr, *x_expire;
4556 wrong_args ("--quick-set-exipre FINGERPRINT EXPIRE [SUBKEY-FPRS]");
4557 x_fpr = *argv++; argc--;
4558 x_expire = *argv++; argc--;
4559 keyedit_quick_set_expire (ctrl, x_fpr, x_expire, argv);
4563 case aQuickSetPrimaryUid:
4565 const char *uid, *primaryuid;
4568 wrong_args ("--quick-set-primary-uid USER-ID PRIMARY-USER-ID");
4569 uid = *argv++; argc--;
4570 primaryuid = *argv++; argc--;
4571 keyedit_quick_set_primary (ctrl, uid, primaryuid);
4576 opt.import_options |= IMPORT_FAST; /* fall through */
4579 import_keys (ctrl, argc? argv:NULL, argc, NULL,
4580 opt.import_options, opt.key_origin, opt.key_origin_url);
4583 /* TODO: There are a number of command that use this same
4584 "make strlist, call function, report error, free strlist"
4585 pattern. Join them together here and avoid all that
4592 for( ; argc; argc--, argv++ )
4593 append_to_strlist2( &sl, *argv, utf8_strings );
4594 if( cmd == aSendKeys )
4595 rc = keyserver_export (ctrl, sl );
4596 else if( cmd == aRecvKeys )
4597 rc = keyserver_import (ctrl, sl );
4600 export_stats_t stats = export_new_stats ();
4601 rc = export_pubkeys (ctrl, sl, opt.export_options, stats);
4602 export_print_stats (stats);
4603 export_release_stats (stats);
4609 write_status_failure ("send-keys", rc);
4610 log_error(_("keyserver send failed: %s\n"),gpg_strerror (rc));
4612 else if(cmd==aRecvKeys)
4614 write_status_failure ("recv-keys", rc);
4615 log_error (_("keyserver receive failed: %s\n"),
4620 write_status_failure ("export", rc);
4621 log_error (_("key export failed: %s\n"), gpg_strerror (rc));
4629 wrong_args ("--export-ssh-key <user-id>");
4630 rc = export_ssh_key (ctrl, argv[0]);
4633 write_status_failure ("export-ssh-key", rc);
4634 log_error (_("export as ssh key failed: %s\n"), gpg_strerror (rc));
4640 for (; argc; argc--, argv++)
4641 append_to_strlist2 (&sl, *argv, utf8_strings);
4642 rc = keyserver_search (ctrl, sl);
4645 write_status_failure ("search-keys", rc);
4646 log_error (_("keyserver search failed: %s\n"), gpg_strerror (rc));
4653 for( ; argc; argc--, argv++ )
4654 append_to_strlist2( &sl, *argv, utf8_strings );
4655 rc = keyserver_refresh (ctrl, sl);
4658 write_status_failure ("refresh-keys", rc);
4659 log_error (_("keyserver refresh failed: %s\n"),gpg_strerror (rc));
4666 for( ; argc; argc--, argv++ )
4667 append_to_strlist2( &sl, *argv, utf8_strings );
4668 rc = keyserver_fetch (ctrl, sl, opt.key_origin);
4671 write_status_failure ("fetch-keys", rc);
4672 log_error ("key fetch failed: %s\n",gpg_strerror (rc));
4679 for( ; argc; argc--, argv++ )
4680 add_to_strlist2( &sl, *argv, utf8_strings );
4682 export_stats_t stats = export_new_stats ();
4683 export_seckeys (ctrl, sl, opt.export_options, stats);
4684 export_print_stats (stats);
4685 export_release_stats (stats);
4690 case aExportSecretSub:
4692 for( ; argc; argc--, argv++ )
4693 add_to_strlist2( &sl, *argv, utf8_strings );
4695 export_stats_t stats = export_new_stats ();
4696 export_secsubkeys (ctrl, sl, opt.export_options, stats);
4697 export_print_stats (stats);
4698 export_release_stats (stats);
4705 wrong_args("--generate-revocation user-id");
4706 username = make_username(*argv);
4707 gen_revoke (ctrl, username );
4713 wrong_args ("--generate-designated-revocation user-id");
4714 username = make_username (*argv);
4715 gen_desig_revoke (ctrl, username, locusr);
4721 wrong_args("--dearmor [file]");
4722 rc = dearmor_file( argc? *argv: NULL );
4725 write_status_failure ("dearmor", rc);
4726 log_error (_("dearmoring failed: %s\n"), gpg_strerror (rc));
4732 wrong_args("--enarmor [file]");
4733 rc = enarmor_file( argc? *argv: NULL );
4736 write_status_failure ("enarmor", rc);
4737 log_error (_("enarmoring failed: %s\n"), gpg_strerror (rc));
4744 { int mode = argc < 2 ? 0 : atoi(*argv);
4746 if( mode == 1 && argc == 2 ) {
4747 mpi_print (es_stdout,
4748 generate_public_prime( atoi(argv[1]) ), 1);
4750 else if( mode == 2 && argc == 3 ) {
4751 mpi_print (es_stdout, generate_elg_prime(
4753 atoi(argv[2]), NULL,NULL ), 1);
4755 else if( mode == 3 && argc == 3 ) {
4757 mpi_print (es_stdout, generate_elg_prime(
4759 atoi(argv[2]), NULL,&factors ), 1);
4760 es_putc ('\n', es_stdout);
4761 mpi_print (es_stdout, factors[0], 1 ); /* print q */
4763 else if( mode == 4 && argc == 3 ) {
4764 MPI g = mpi_alloc(1);
4765 mpi_print (es_stdout, generate_elg_prime(
4767 atoi(argv[2]), g, NULL ), 1);
4768 es_putc ('\n', es_stdout);
4769 mpi_print (es_stdout, g, 1 );
4773 wrong_args("--gen-prime mode bits [qbits] ");
4774 es_putc ('\n', es_stdout);
4777 wrong_args("--gen-prime not yet supported ");
4782 int level = argc ? atoi(*argv):0;
4783 int count = argc > 1 ? atoi(argv[1]): 0;
4784 int endless = !count;
4786 if( argc < 1 || argc > 2 || level < 0 || level > 2 || count < 0 )
4787 wrong_args("--gen-random 0|1|2 [count]");
4789 while( endless || count ) {
4791 /* Wee need a multiple of 3, so that in case of
4792 armored output we get a correct string. No
4793 linefolding is done, as it is best to levae this to
4795 size_t n = !endless && count < 99? count : 99;
4797 p = gcry_random_bytes (n, level);
4798 #ifdef HAVE_DOSISH_SYSTEM
4799 setmode ( fileno(stdout), O_BINARY );
4802 char *tmp = make_radix64_string (p, n);
4803 es_fputs (tmp, es_stdout);
4806 es_putc ('=', es_stdout);
4808 es_putc ('=', es_stdout);
4810 es_fwrite( p, n, 1, es_stdout );
4817 es_putc ('\n', es_stdout);
4823 wrong_args("--print-md algo [files]");
4825 int all_algos = (**argv=='*' && !(*argv)[1]);
4826 int algo = all_algos? 0 : gcry_md_map_name (*argv);
4828 if( !algo && !all_algos )
4829 log_error(_("invalid hash algorithm '%s'\n"), *argv );
4833 print_mds(NULL, algo);
4835 for(; argc; argc--, argv++ )
4836 print_mds(*argv, algo);
4842 case aPrintMDs: /* old option */
4846 for(; argc; argc--, argv++ )
4851 #ifndef NO_TRUST_MODELS
4854 list_trustdb (ctrl, es_stdout, NULL);
4856 for( ; argc; argc--, argv++ )
4857 list_trustdb (ctrl, es_stdout, *argv );
4861 case aUpdateTrustDB:
4863 wrong_args("--update-trustdb");
4864 update_trustdb (ctrl);
4868 /* Old versions allowed for arguments - ignore them */
4869 check_trustdb (ctrl);
4873 how_to_fix_the_trustdb ();
4876 case aListTrustPath:
4878 wrong_args("--list-trust-path <user-ids>");
4879 for( ; argc; argc--, argv++ ) {
4880 username = make_username( *argv );
4881 list_trust_path( username );
4886 case aExportOwnerTrust:
4888 wrong_args("--export-ownertrust");
4889 export_ownertrust (ctrl);
4892 case aImportOwnerTrust:
4894 wrong_args("--import-ownertrust [file]");
4895 import_ownertrust (ctrl, argc? *argv:NULL );
4897 #endif /*!NO_TRUST_MODELS*/
4899 case aRebuildKeydbCaches:
4901 wrong_args ("--rebuild-keydb-caches");
4902 keydb_rebuild_caches (ctrl, 1);
4905 #ifdef ENABLE_CARD_SUPPORT
4908 card_status (ctrl, es_stdout, NULL);
4910 card_status (ctrl, es_stdout, *argv);
4912 wrong_args ("--card-status [serialno]");
4918 for (argc--, argv++ ; argc; argc--, argv++)
4919 append_to_strlist (&sl, *argv);
4920 card_edit (ctrl, sl);
4924 card_edit (ctrl, NULL);
4931 change_pin (atoi (*argv),1);
4933 wrong_args ("--change-pin [no]");
4935 #endif /* ENABLE_CARD_SUPPORT*/
4939 char *str=collapse_args(argc,argv);
4945 case aListGcryptConfig:
4946 /* Fixme: It would be nice to integrate that with
4947 --list-config but unfortunately there is no way yet to have
4948 libgcrypt print it to an estream for further parsing. */
4949 gcry_control (GCRYCTL_PRINT_CONFIG, stdout);
4960 wrong_args ("--tofu-policy POLICY KEYID [KEYID...]");
4962 policy = parse_tofu_policy (argv[0]);
4967 write_status_failure ("tofu-driver", gpg_error(GPG_ERR_GENERAL));
4971 tofu_begin_batch_update (ctrl);
4973 for (i = 1; i < argc; i ++)
4975 KEYDB_SEARCH_DESC desc;
4978 rc = classify_user_id (argv[i], &desc, 0);
4981 log_error (_("error parsing key specification '%s': %s\n"),
4982 argv[i], gpg_strerror (rc));
4983 write_status_failure ("tofu-driver", rc);
4987 if (! (desc.mode == KEYDB_SEARCH_MODE_SHORT_KID
4988 || desc.mode == KEYDB_SEARCH_MODE_LONG_KID
4989 || desc.mode == KEYDB_SEARCH_MODE_FPR16
4990 || desc.mode == KEYDB_SEARCH_MODE_FPR20
4991 || desc.mode == KEYDB_SEARCH_MODE_FPR
4992 || desc.mode == KEYDB_SEARCH_MODE_KEYGRIP))
4994 log_error (_("'%s' does not appear to be a valid"
4995 " key ID, fingerprint or keygrip\n"),
4997 write_status_failure ("tofu-driver",
4998 gpg_error(GPG_ERR_GENERAL));
5002 rc = keydb_search_reset (hd);
5005 /* This should not happen, thus no need to tranalate
5007 log_error ("keydb_search_reset failed: %s\n",
5009 write_status_failure ("tofu-driver", rc);
5013 rc = keydb_search (hd, &desc, 1, NULL);
5016 log_error (_("key \"%s\" not found: %s\n"), argv[i],
5018 write_status_failure ("tofu-driver", rc);
5022 rc = keydb_get_keyblock (hd, &kb);
5025 log_error (_("error reading keyblock: %s\n"),
5027 write_status_failure ("tofu-driver", rc);
5031 merge_keys_and_selfsig (ctrl, kb);
5032 if (tofu_set_policy (ctrl, kb, policy))
5034 write_status_failure ("tofu-driver", rc);
5038 release_kbnode (kb);
5041 tofu_end_batch_update (ctrl);
5050 log_info (_("WARNING: no command supplied."
5051 " Trying to guess what you mean ...\n"));
5055 wrong_args("[filename]");
5056 /* Issue some output for the unix newbie */
5057 if (!fname && !opt.outfile
5058 && gnupg_isatty (fileno (stdin))
5059 && gnupg_isatty (fileno (stdout))
5060 && gnupg_isatty (fileno (stderr)))
5061 log_info(_("Go ahead and type your message ...\n"));
5063 a = iobuf_open(fname);
5064 if (a && is_secured_file (iobuf_get_fd (a)))
5068 gpg_err_set_errno (EPERM);
5071 log_error(_("can't open '%s'\n"), print_fname_stdin(fname));
5074 if( !opt.no_armor ) {
5075 if( use_armor_filter( a ) ) {
5076 afx = new_armor_context ();
5077 push_armor_filter (afx, a);
5080 if( cmd == aListPackets ) {
5082 set_packet_list_mode(1);
5084 rc = proc_packets (ctrl, NULL, a );
5087 write_status_failure ("-", rc);
5088 log_error ("processing message failed: %s\n",
5097 gpg_deinit_default_ctrl (ctrl);
5099 release_armor_context (afx);
5100 FREE_STRLIST(remusr);
5101 FREE_STRLIST(locusr);
5103 return 8; /*NEVER REACHED*/
5107 /* Note: This function is used by signal handlers!. */
5109 emergency_cleanup (void)
5111 gcry_control (GCRYCTL_TERM_SECMEM );
5118 /* If we had an error but not printed an error message, do it now.
5119 * Note that write_status_failure will never print a second failure
5122 write_status_failure ("gpg-exit", gpg_error (GPG_ERR_GENERAL));
5124 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
5128 if ( (opt.debug & DBG_MEMSTAT_VALUE) )
5130 keydb_dump_stats ();
5131 sig_check_dump_stats ();
5132 gcry_control (GCRYCTL_DUMP_MEMORY_STATS);
5133 gcry_control (GCRYCTL_DUMP_RANDOM_STATS);
5136 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
5138 emergency_cleanup ();
5140 rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0;
5145 /* Pretty-print hex hashes. This assumes at least an 80-character
5146 display, but there are a few other similar assumptions in the
5149 print_hex (gcry_md_hd_t md, int algo, const char *fname)
5151 int i,n,count,indent=0;
5155 indent = es_printf("%s: ",fname);
5163 if (algo==DIGEST_ALGO_RMD160)
5164 indent += es_printf("RMD160 = ");
5166 indent += es_printf("%6s = ", gcry_md_algo_name (algo));
5172 p = gcry_md_read (md, algo);
5173 n = gcry_md_get_algo_dlen (algo);
5175 count += es_printf ("%02X",*p++);
5177 for(i=1;i<n;i++,p++)
5183 es_printf ("\n%*s",indent," ");
5187 count += es_printf(" ");
5190 count += es_printf(" ");
5198 es_printf ("\n%*s",indent," ");
5202 count += es_printf(" ");
5206 count += es_printf(" ");
5214 es_printf ("\n%*s",indent," ");
5218 count += es_printf(" ");
5222 count += es_printf("%02X",*p);
5229 print_hashline( gcry_md_hd_t md, int algo, const char *fname )
5236 for (p = fname; *p; p++ )
5238 if ( *p <= 32 || *p > 127 || *p == ':' || *p == '%' )
5239 es_printf ("%%%02X", *p );
5241 es_putc (*p, es_stdout);
5244 es_putc (':', es_stdout);
5245 es_printf ("%d:", algo);
5246 p = gcry_md_read (md, algo);
5247 n = gcry_md_get_algo_dlen (algo);
5248 for(i=0; i < n ; i++, p++ )
5249 es_printf ("%02X", *p);
5250 es_fputs (":\n", es_stdout);
5255 print_mds( const char *fname, int algo )
5269 fp = es_fopen (fname, "rb" );
5270 if (fp && is_secured_file (es_fileno (fp)))
5274 gpg_err_set_errno (EPERM);
5279 log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
5283 gcry_md_open (&md, 0, 0);
5285 gcry_md_enable (md, algo);
5288 if (!gcry_md_test_algo (GCRY_MD_MD5))
5289 gcry_md_enable (md, GCRY_MD_MD5);
5290 gcry_md_enable (md, GCRY_MD_SHA1);
5291 if (!gcry_md_test_algo (GCRY_MD_RMD160))
5292 gcry_md_enable (md, GCRY_MD_RMD160);
5293 if (!gcry_md_test_algo (GCRY_MD_SHA224))
5294 gcry_md_enable (md, GCRY_MD_SHA224);
5295 if (!gcry_md_test_algo (GCRY_MD_SHA256))
5296 gcry_md_enable (md, GCRY_MD_SHA256);
5297 if (!gcry_md_test_algo (GCRY_MD_SHA384))
5298 gcry_md_enable (md, GCRY_MD_SHA384);
5299 if (!gcry_md_test_algo (GCRY_MD_SHA512))
5300 gcry_md_enable (md, GCRY_MD_SHA512);
5303 while ((n=es_fread (buf, 1, DIM(buf), fp)))
5304 gcry_md_write (md, buf, n);
5307 log_error ("%s: %s\n", fname?fname:"[stdin]", strerror(errno));
5311 if (opt.with_colons)
5314 print_hashline (md, algo, fname);
5317 if (!gcry_md_test_algo (GCRY_MD_MD5))
5318 print_hashline( md, GCRY_MD_MD5, fname );
5319 print_hashline( md, GCRY_MD_SHA1, fname );
5320 if (!gcry_md_test_algo (GCRY_MD_RMD160))
5321 print_hashline( md, GCRY_MD_RMD160, fname );
5322 if (!gcry_md_test_algo (GCRY_MD_SHA224))
5323 print_hashline (md, GCRY_MD_SHA224, fname);
5324 if (!gcry_md_test_algo (GCRY_MD_SHA256))
5325 print_hashline( md, GCRY_MD_SHA256, fname );
5326 if (!gcry_md_test_algo (GCRY_MD_SHA384))
5327 print_hashline ( md, GCRY_MD_SHA384, fname );
5328 if (!gcry_md_test_algo (GCRY_MD_SHA512))
5329 print_hashline ( md, GCRY_MD_SHA512, fname );
5335 print_hex (md, -algo, fname);
5338 if (!gcry_md_test_algo (GCRY_MD_MD5))
5339 print_hex (md, GCRY_MD_MD5, fname);
5340 print_hex (md, GCRY_MD_SHA1, fname );
5341 if (!gcry_md_test_algo (GCRY_MD_RMD160))
5342 print_hex (md, GCRY_MD_RMD160, fname );
5343 if (!gcry_md_test_algo (GCRY_MD_SHA224))
5344 print_hex (md, GCRY_MD_SHA224, fname);
5345 if (!gcry_md_test_algo (GCRY_MD_SHA256))
5346 print_hex (md, GCRY_MD_SHA256, fname );
5347 if (!gcry_md_test_algo (GCRY_MD_SHA384))
5348 print_hex (md, GCRY_MD_SHA384, fname );
5349 if (!gcry_md_test_algo (GCRY_MD_SHA512))
5350 print_hex (md, GCRY_MD_SHA512, fname );
5362 * Check the supplied name,value string and add it to the notation
5363 * data to be used for signatures. which==0 for sig notations, and 1
5364 * for cert notations.
5367 add_notation_data( const char *string, int which )
5369 struct notation *notation;
5371 notation=string_to_notation(string,utf8_strings);
5376 notation->next=opt.cert_notations;
5377 opt.cert_notations=notation;
5381 notation->next=opt.sig_notations;
5382 opt.sig_notations=notation;
5388 add_policy_url( const char *string, int which )
5390 unsigned int i,critical=0;
5399 for(i=0;i<strlen(string);i++)
5400 if( !isascii (string[i]) || iscntrl(string[i]))
5403 if(i==0 || i<strlen(string))
5406 log_error(_("the given certification policy URL is invalid\n"));
5408 log_error(_("the given signature policy URL is invalid\n"));
5412 sl=add_to_strlist( &opt.cert_policy_url, string );
5414 sl=add_to_strlist( &opt.sig_policy_url, string );
5421 add_keyserver_url( const char *string, int which )
5423 unsigned int i,critical=0;
5432 for(i=0;i<strlen(string);i++)
5433 if( !isascii (string[i]) || iscntrl(string[i]))
5436 if(i==0 || i<strlen(string))
5441 log_error(_("the given preferred keyserver URL is invalid\n"));
5447 sl=add_to_strlist( &opt.sig_keyserver_url, string );
5455 read_sessionkey_from_fd (int fd)
5460 if (! gnupg_fd_valid (fd))
5461 log_fatal ("override-session-key-fd is invalid: %s\n", strerror (errno));
5463 for (line = NULL, i = len = 100; ; i++ )
5469 line = xmalloc_secure (len);
5472 memcpy (line, tmp, i);
5478 if (read (fd, line + i, 1) != 1 || line[i] == '\n')
5482 log_debug ("seskey: %s\n", line);
5483 gpgrt_annotate_leaked_object (line);
5484 opt.override_session_key = line;