1 /* gpg.c - The GnuPG utility (main for gpg)
2 * Copyright (C) 1998-2011 Free Software Foundation, Inc.
3 * Copyright (C) 1997-2017 Werner Koch
4 * Copyright (C) 2015-2017 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',
140 aDeleteSecretAndPublicKeys,
197 oWithSubkeyFingerprint,
252 oBZ2DecompressLowmem,
277 oSkipHiddenRecipients,
278 oNoSkipHiddenRecipients,
291 oUseEmbeddedFilename,
292 oNoUseEmbeddedFilename,
329 oEncryptToDefaultKey,
336 oAllowNonSelfsignedUID,
337 oNoAllowNonSelfsignedUID,
340 oAllowSecretKeyImport,
341 oEnableSpecialFilenames,
353 oOverrideSessionKeyFD,
363 oNoExpensiveTrustChecks,
369 oPreservePermissions,
370 oDefaultPreferenceList,
371 oDefaultKeyserverURL,
372 oPersonalCipherPreferences,
373 oPersonalDigestPreferences,
374 oPersonalCompressPreferences,
390 oNoMangleDosFilenames,
391 oEnableProgressFilter,
394 oExitOnStatusWriteError,
395 oLimitCardInsertTries,
404 oAllowMultisigVerification,
409 oAllowMultipleMessages,
410 oNoAllowMultipleMessages,
411 oAllowWeakDigestAlgos,
431 static ARGPARSE_OPTS opts[] = {
433 ARGPARSE_group (300, N_("@Commands:\n ")),
435 ARGPARSE_c (aSign, "sign", N_("make a signature")),
436 ARGPARSE_c (aClearsign, "clear-sign", N_("make a clear text signature")),
437 ARGPARSE_c (aClearsign, "clearsign", "@"),
438 ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")),
439 ARGPARSE_c (aEncr, "encrypt", N_("encrypt data")),
440 ARGPARSE_c (aEncrFiles, "encrypt-files", "@"),
441 ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")),
442 ARGPARSE_c (aStore, "store", "@"),
443 ARGPARSE_c (aDecrypt, "decrypt", N_("decrypt data (default)")),
444 ARGPARSE_c (aDecryptFiles, "decrypt-files", "@"),
445 ARGPARSE_c (aVerify, "verify" , N_("verify a signature")),
446 ARGPARSE_c (aVerifyFiles, "verify-files" , "@" ),
447 ARGPARSE_c (aListKeys, "list-keys", N_("list keys")),
448 ARGPARSE_c (aListKeys, "list-public-keys", "@" ),
449 ARGPARSE_c (aListSigs, "list-signatures", N_("list keys and signatures")),
450 ARGPARSE_c (aListSigs, "list-sigs", "@"),
451 ARGPARSE_c (aCheckKeys, "check-signatures",
452 N_("list and check key signatures")),
453 ARGPARSE_c (aCheckKeys, "check-sigs", "@"),
454 ARGPARSE_c (oFingerprint, "fingerprint", N_("list keys and fingerprints")),
455 ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")),
456 ARGPARSE_c (aKeygen, "generate-key",
457 N_("generate a new key pair")),
458 ARGPARSE_c (aKeygen, "gen-key", "@"),
459 ARGPARSE_c (aQuickKeygen, "quick-generate-key" ,
460 N_("quickly generate a new key pair")),
461 ARGPARSE_c (aQuickKeygen, "quick-gen-key", "@"),
462 ARGPARSE_c (aQuickAddUid, "quick-add-uid",
463 N_("quickly add a new user-id")),
464 ARGPARSE_c (aQuickAddUid, "quick-adduid", "@"),
465 ARGPARSE_c (aQuickAddKey, "quick-add-key", "@"),
466 ARGPARSE_c (aQuickAddKey, "quick-addkey", "@"),
467 ARGPARSE_c (aQuickRevUid, "quick-revoke-uid",
468 N_("quickly revoke a user-id")),
469 ARGPARSE_c (aQuickRevUid, "quick-revuid", "@"),
470 ARGPARSE_c (aQuickSetExpire, "quick-set-expire",
471 N_("quickly set a new expiration date")),
472 ARGPARSE_c (aQuickSetPrimaryUid, "quick-set-primary-uid", "@"),
473 ARGPARSE_c (aFullKeygen, "full-generate-key" ,
474 N_("full featured key pair generation")),
475 ARGPARSE_c (aFullKeygen, "full-gen-key", "@"),
476 ARGPARSE_c (aGenRevoke, "generate-revocation",
477 N_("generate a revocation certificate")),
478 ARGPARSE_c (aGenRevoke, "gen-revoke", "@"),
479 ARGPARSE_c (aDeleteKeys,"delete-keys",
480 N_("remove keys from the public keyring")),
481 ARGPARSE_c (aDeleteSecretKeys, "delete-secret-keys",
482 N_("remove keys from the secret keyring")),
483 ARGPARSE_c (aQuickSignKey, "quick-sign-key" ,
484 N_("quickly sign a key")),
485 ARGPARSE_c (aQuickLSignKey, "quick-lsign-key",
486 N_("quickly sign a key locally")),
487 ARGPARSE_c (aSignKey, "sign-key" ,N_("sign a key")),
488 ARGPARSE_c (aLSignKey, "lsign-key" ,N_("sign a key locally")),
489 ARGPARSE_c (aEditKey, "edit-key" ,N_("sign or edit a key")),
490 ARGPARSE_c (aEditKey, "key-edit" ,"@"),
491 ARGPARSE_c (aPasswd, "change-passphrase", N_("change a passphrase")),
492 ARGPARSE_c (aPasswd, "passwd", "@"),
493 ARGPARSE_c (aDesigRevoke, "generate-designated-revocation", "@"),
494 ARGPARSE_c (aDesigRevoke, "desig-revoke","@" ),
495 ARGPARSE_c (aExport, "export" , N_("export keys") ),
496 ARGPARSE_c (aSendKeys, "send-keys" , N_("export keys to a keyserver") ),
497 ARGPARSE_c (aRecvKeys, "receive-keys" , N_("import keys from a keyserver") ),
498 ARGPARSE_c (aRecvKeys, "recv-keys" , "@"),
499 ARGPARSE_c (aSearchKeys, "search-keys" ,
500 N_("search for keys on a keyserver") ),
501 ARGPARSE_c (aRefreshKeys, "refresh-keys",
502 N_("update all keys from a keyserver")),
503 ARGPARSE_c (aLocateKeys, "locate-keys", "@"),
504 ARGPARSE_c (aFetchKeys, "fetch-keys" , "@" ),
505 ARGPARSE_c (aExportSecret, "export-secret-keys" , "@" ),
506 ARGPARSE_c (aExportSecretSub, "export-secret-subkeys" , "@" ),
507 ARGPARSE_c (aExportSshKey, "export-ssh-key", "@" ),
508 ARGPARSE_c (aImport, "import", N_("import/merge keys")),
509 ARGPARSE_c (aFastImport, "fast-import", "@"),
510 #ifdef ENABLE_CARD_SUPPORT
511 ARGPARSE_c (aCardStatus, "card-status", N_("print the card status")),
512 ARGPARSE_c (aCardEdit, "edit-card", N_("change data on a card")),
513 ARGPARSE_c (aCardEdit, "card-edit", "@"),
514 ARGPARSE_c (aChangePIN, "change-pin", N_("change a card's PIN")),
516 ARGPARSE_c (aListConfig, "list-config", "@"),
517 ARGPARSE_c (aListGcryptConfig, "list-gcrypt-config", "@"),
518 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@" ),
519 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@" ),
520 ARGPARSE_c (aListPackets, "list-packets","@"),
522 #ifndef NO_TRUST_MODELS
523 ARGPARSE_c (aExportOwnerTrust, "export-ownertrust", "@"),
524 ARGPARSE_c (aImportOwnerTrust, "import-ownertrust", "@"),
525 ARGPARSE_c (aUpdateTrustDB,"update-trustdb",
526 N_("update the trust database")),
527 ARGPARSE_c (aCheckTrustDB, "check-trustdb", "@"),
528 ARGPARSE_c (aFixTrustDB, "fix-trustdb", "@"),
531 ARGPARSE_c (aDeArmor, "dearmor", "@"),
532 ARGPARSE_c (aDeArmor, "dearmour", "@"),
533 ARGPARSE_c (aEnArmor, "enarmor", "@"),
534 ARGPARSE_c (aEnArmor, "enarmour", "@"),
535 ARGPARSE_c (aPrintMD, "print-md", N_("print message digests")),
536 ARGPARSE_c (aPrimegen, "gen-prime", "@" ),
537 ARGPARSE_c (aGenRandom,"gen-random", "@" ),
538 ARGPARSE_c (aServer, "server", N_("run in server mode")),
539 ARGPARSE_c (aTOFUPolicy, "tofu-policy",
540 N_("|VALUE|set the TOFU policy for a key")),
542 ARGPARSE_group (301, N_("@\nOptions:\n ")),
544 ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")),
545 ARGPARSE_s_n (oArmor, "armour", "@"),
547 ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")),
548 ARGPARSE_s_s (oHiddenRecipient, "hidden-recipient", "@"),
549 ARGPARSE_s_s (oRecipientFile, "recipient-file", "@"),
550 ARGPARSE_s_s (oHiddenRecipientFile, "hidden-recipient-file", "@"),
551 ARGPARSE_s_s (oRecipient, "remote-user", "@"), /* (old option name) */
552 ARGPARSE_s_s (oDefRecipient, "default-recipient", "@"),
553 ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", "@"),
554 ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"),
556 ARGPARSE_s_s (oTempDir, "temp-directory", "@"),
557 ARGPARSE_s_s (oExecPath, "exec-path", "@"),
558 ARGPARSE_s_s (oEncryptTo, "encrypt-to", "@"),
559 ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"),
560 ARGPARSE_s_s (oHiddenEncryptTo, "hidden-encrypt-to", "@"),
561 ARGPARSE_s_n (oEncryptToDefaultKey, "encrypt-to-default-key", "@"),
562 ARGPARSE_s_s (oLocalUser, "local-user",
563 N_("|USER-ID|use USER-ID to sign or decrypt")),
564 ARGPARSE_s_s (oSender, "sender", "@"),
566 ARGPARSE_s_s (oTrySecretKey, "try-secret-key", "@"),
568 ARGPARSE_s_i (oCompress, NULL,
569 N_("|N|set compress level to N (0 disables)")),
570 ARGPARSE_s_i (oCompressLevel, "compress-level", "@"),
571 ARGPARSE_s_i (oBZ2CompressLevel, "bzip2-compress-level", "@"),
572 ARGPARSE_s_n (oBZ2DecompressLowmem, "bzip2-decompress-lowmem", "@"),
574 ARGPARSE_s_n (oMimemode, "mimemode", "@"),
575 ARGPARSE_s_n (oTextmodeShort, NULL, "@"),
576 ARGPARSE_s_n (oTextmode, "textmode", N_("use canonical text mode")),
577 ARGPARSE_s_n (oNoTextmode, "no-textmode", "@"),
579 ARGPARSE_s_n (oExpert, "expert", "@"),
580 ARGPARSE_s_n (oNoExpert, "no-expert", "@"),
582 ARGPARSE_s_s (oDefSigExpire, "default-sig-expire", "@"),
583 ARGPARSE_s_n (oAskSigExpire, "ask-sig-expire", "@"),
584 ARGPARSE_s_n (oNoAskSigExpire, "no-ask-sig-expire", "@"),
585 ARGPARSE_s_s (oDefCertExpire, "default-cert-expire", "@"),
586 ARGPARSE_s_n (oAskCertExpire, "ask-cert-expire", "@"),
587 ARGPARSE_s_n (oNoAskCertExpire, "no-ask-cert-expire", "@"),
588 ARGPARSE_s_i (oDefCertLevel, "default-cert-level", "@"),
589 ARGPARSE_s_i (oMinCertLevel, "min-cert-level", "@"),
590 ARGPARSE_s_n (oAskCertLevel, "ask-cert-level", "@"),
591 ARGPARSE_s_n (oNoAskCertLevel, "no-ask-cert-level", "@"),
593 ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")),
594 ARGPARSE_p_u (oMaxOutput, "max-output", "@"),
595 ARGPARSE_s_s (oInputSizeHint, "input-size-hint", "@"),
597 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
598 ARGPARSE_s_n (oQuiet, "quiet", "@"),
599 ARGPARSE_s_n (oNoTTY, "no-tty", "@"),
601 ARGPARSE_s_n (oForceMDC, "force-mdc", "@"),
602 ARGPARSE_s_n (oNoForceMDC, "no-force-mdc", "@"),
603 ARGPARSE_s_n (oDisableMDC, "disable-mdc", "@"),
604 ARGPARSE_s_n (oNoDisableMDC, "no-disable-mdc", "@"),
606 ARGPARSE_s_n (oDisableSignerUID, "disable-signer-uid", "@"),
608 ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")),
609 ARGPARSE_s_n (oInteractive, "interactive", N_("prompt before overwriting")),
611 ARGPARSE_s_n (oBatch, "batch", "@"),
612 ARGPARSE_s_n (oAnswerYes, "yes", "@"),
613 ARGPARSE_s_n (oAnswerNo, "no", "@"),
614 ARGPARSE_s_s (oKeyring, "keyring", "@"),
615 ARGPARSE_s_s (oPrimaryKeyring, "primary-keyring", "@"),
616 ARGPARSE_s_s (oSecretKeyring, "secret-keyring", "@"),
617 ARGPARSE_s_n (oShowKeyring, "show-keyring", "@"),
618 ARGPARSE_s_s (oDefaultKey, "default-key", "@"),
620 ARGPARSE_s_s (oKeyServer, "keyserver", "@"),
621 ARGPARSE_s_s (oKeyServerOptions, "keyserver-options", "@"),
622 ARGPARSE_s_s (oKeyOrigin, "key-origin", "@"),
623 ARGPARSE_s_s (oImportOptions, "import-options", "@"),
624 ARGPARSE_s_s (oImportFilter, "import-filter", "@"),
625 ARGPARSE_s_s (oExportOptions, "export-options", "@"),
626 ARGPARSE_s_s (oExportFilter, "export-filter", "@"),
627 ARGPARSE_s_s (oListOptions, "list-options", "@"),
628 ARGPARSE_s_s (oVerifyOptions, "verify-options", "@"),
630 ARGPARSE_s_s (oDisplayCharset, "display-charset", "@"),
631 ARGPARSE_s_s (oDisplayCharset, "charset", "@"),
632 ARGPARSE_s_s (oOptions, "options", "@"),
634 ARGPARSE_s_s (oDebug, "debug", "@"),
635 ARGPARSE_s_s (oDebugLevel, "debug-level", "@"),
636 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
637 ARGPARSE_s_n (oDebugIOLBF, "debug-iolbf", "@"),
638 ARGPARSE_s_i (oStatusFD, "status-fd", "@"),
639 ARGPARSE_s_s (oStatusFile, "status-file", "@"),
640 ARGPARSE_s_i (oAttributeFD, "attribute-fd", "@"),
641 ARGPARSE_s_s (oAttributeFile, "attribute-file", "@"),
643 ARGPARSE_s_i (oCompletesNeeded, "completes-needed", "@"),
644 ARGPARSE_s_i (oMarginalsNeeded, "marginals-needed", "@"),
645 ARGPARSE_s_i (oMaxCertDepth, "max-cert-depth", "@" ),
646 ARGPARSE_s_s (oTrustedKey, "trusted-key", "@"),
648 ARGPARSE_s_s (oLoadExtension, "load-extension", "@"), /* Dummy. */
650 ARGPARSE_s_s (oCompliance, "compliance", "@"),
651 ARGPARSE_s_n (oGnuPG, "gnupg", "@"),
652 ARGPARSE_s_n (oGnuPG, "no-pgp2", "@"),
653 ARGPARSE_s_n (oGnuPG, "no-pgp6", "@"),
654 ARGPARSE_s_n (oGnuPG, "no-pgp7", "@"),
655 ARGPARSE_s_n (oGnuPG, "no-pgp8", "@"),
656 ARGPARSE_s_n (oRFC2440, "rfc2440", "@"),
657 ARGPARSE_s_n (oRFC4880, "rfc4880", "@"),
658 ARGPARSE_s_n (oRFC4880bis, "rfc4880bis", "@"),
659 ARGPARSE_s_n (oOpenPGP, "openpgp", N_("use strict OpenPGP behavior")),
660 ARGPARSE_s_n (oPGP6, "pgp6", "@"),
661 ARGPARSE_s_n (oPGP7, "pgp7", "@"),
662 ARGPARSE_s_n (oPGP8, "pgp8", "@"),
664 ARGPARSE_s_n (oRFC2440Text, "rfc2440-text", "@"),
665 ARGPARSE_s_n (oNoRFC2440Text, "no-rfc2440-text", "@"),
666 ARGPARSE_s_i (oS2KMode, "s2k-mode", "@"),
667 ARGPARSE_s_s (oS2KDigest, "s2k-digest-algo", "@"),
668 ARGPARSE_s_s (oS2KCipher, "s2k-cipher-algo", "@"),
669 ARGPARSE_s_i (oS2KCount, "s2k-count", "@"),
670 ARGPARSE_s_s (oCipherAlgo, "cipher-algo", "@"),
671 ARGPARSE_s_s (oDigestAlgo, "digest-algo", "@"),
672 ARGPARSE_s_s (oCertDigestAlgo, "cert-digest-algo", "@"),
673 ARGPARSE_s_s (oCompressAlgo,"compress-algo", "@"),
674 ARGPARSE_s_s (oCompressAlgo, "compression-algo", "@"), /* Alias */
675 ARGPARSE_s_n (oThrowKeyids, "throw-keyids", "@"),
676 ARGPARSE_s_n (oNoThrowKeyids, "no-throw-keyids", "@"),
677 ARGPARSE_s_n (oShowPhotos, "show-photos", "@"),
678 ARGPARSE_s_n (oNoShowPhotos, "no-show-photos", "@"),
679 ARGPARSE_s_s (oPhotoViewer, "photo-viewer", "@"),
680 ARGPARSE_s_s (oSetNotation, "set-notation", "@"),
681 ARGPARSE_s_s (oSigNotation, "sig-notation", "@"),
682 ARGPARSE_s_s (oCertNotation, "cert-notation", "@"),
684 ARGPARSE_group (302, N_(
685 "@\n(See the man page for a complete listing of all commands and options)\n"
688 ARGPARSE_group (303, N_("@\nExamples:\n\n"
689 " -se -r Bob [file] sign and encrypt for user Bob\n"
690 " --clear-sign [file] make a clear text signature\n"
691 " --detach-sign [file] make a detached signature\n"
692 " --list-keys [names] show keys\n"
693 " --fingerprint [names] show fingerprints\n")),
695 /* More hidden commands and options. */
696 ARGPARSE_c (aPrintMDs, "print-mds", "@"), /* old */
697 #ifndef NO_TRUST_MODELS
698 ARGPARSE_c (aListTrustDB, "list-trustdb", "@"),
702 ARGPARSE_c (aListTrustPath, "list-trust-path", "@"), */
703 ARGPARSE_c (aDeleteSecretAndPublicKeys,
704 "delete-secret-and-public-keys", "@"),
705 ARGPARSE_c (aRebuildKeydbCaches, "rebuild-keydb-caches", "@"),
707 ARGPARSE_s_s (oPassphrase, "passphrase", "@"),
708 ARGPARSE_s_i (oPassphraseFD, "passphrase-fd", "@"),
709 ARGPARSE_s_s (oPassphraseFile, "passphrase-file", "@"),
710 ARGPARSE_s_i (oPassphraseRepeat,"passphrase-repeat", "@"),
711 ARGPARSE_s_s (oPinentryMode, "pinentry-mode", "@"),
712 ARGPARSE_s_s (oRequestOrigin, "request-origin", "@"),
713 ARGPARSE_s_i (oCommandFD, "command-fd", "@"),
714 ARGPARSE_s_s (oCommandFile, "command-file", "@"),
715 ARGPARSE_s_n (oQuickRandom, "debug-quick-random", "@"),
716 ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
718 #ifndef NO_TRUST_MODELS
719 ARGPARSE_s_s (oTrustDBName, "trustdb-name", "@"),
720 ARGPARSE_s_n (oAutoCheckTrustDB, "auto-check-trustdb", "@"),
721 ARGPARSE_s_n (oNoAutoCheckTrustDB, "no-auto-check-trustdb", "@"),
722 ARGPARSE_s_s (oForceOwnertrust, "force-ownertrust", "@"),
725 ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"),
726 ARGPARSE_s_n (oRequireSecmem, "require-secmem", "@"),
727 ARGPARSE_s_n (oNoRequireSecmem, "no-require-secmem", "@"),
728 ARGPARSE_s_n (oNoPermissionWarn, "no-permission-warning", "@"),
729 ARGPARSE_s_n (oNoMDCWarn, "no-mdc-warning", "@"),
730 ARGPARSE_s_n (oNoArmor, "no-armor", "@"),
731 ARGPARSE_s_n (oNoArmor, "no-armour", "@"),
732 ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"),
733 ARGPARSE_s_n (oNoKeyring, "no-keyring", "@"),
734 ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
735 ARGPARSE_s_n (oNoOptions, "no-options", "@"),
736 ARGPARSE_s_s (oHomedir, "homedir", "@"),
737 ARGPARSE_s_n (oNoBatch, "no-batch", "@"),
738 ARGPARSE_s_n (oWithColons, "with-colons", "@"),
739 ARGPARSE_s_n (oWithTofuInfo,"with-tofu-info", "@"),
740 ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"),
741 ARGPARSE_s_n (oWithSigList,"with-sig-list", "@"),
742 ARGPARSE_s_n (oWithSigCheck,"with-sig-check", "@"),
743 ARGPARSE_c (aListKeys, "list-key", "@"), /* alias */
744 ARGPARSE_c (aListSigs, "list-sig", "@"), /* alias */
745 ARGPARSE_c (aCheckKeys, "check-sig", "@"), /* alias */
746 ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"),
747 ARGPARSE_s_n (oSkipHiddenRecipients, "skip-hidden-recipients", "@"),
748 ARGPARSE_s_n (oNoSkipHiddenRecipients, "no-skip-hidden-recipients", "@"),
749 ARGPARSE_s_i (oDefCertLevel, "default-cert-check-level", "@"), /* old */
750 #ifndef NO_TRUST_MODELS
751 ARGPARSE_s_n (oAlwaysTrust, "always-trust", "@"),
753 ARGPARSE_s_s (oTrustModel, "trust-model", "@"),
754 ARGPARSE_s_s (oTOFUDefaultPolicy, "tofu-default-policy", "@"),
755 ARGPARSE_s_s (oSetFilename, "set-filename", "@"),
756 ARGPARSE_s_n (oForYourEyesOnly, "for-your-eyes-only", "@"),
757 ARGPARSE_s_n (oNoForYourEyesOnly, "no-for-your-eyes-only", "@"),
758 ARGPARSE_s_s (oSetPolicyURL, "set-policy-url", "@"),
759 ARGPARSE_s_s (oSigPolicyURL, "sig-policy-url", "@"),
760 ARGPARSE_s_s (oCertPolicyURL, "cert-policy-url", "@"),
761 ARGPARSE_s_n (oShowPolicyURL, "show-policy-url", "@"),
762 ARGPARSE_s_n (oNoShowPolicyURL, "no-show-policy-url", "@"),
763 ARGPARSE_s_s (oSigKeyserverURL, "sig-keyserver-url", "@"),
764 ARGPARSE_s_n (oShowNotation, "show-notation", "@"),
765 ARGPARSE_s_n (oNoShowNotation, "no-show-notation", "@"),
766 ARGPARSE_s_s (oComment, "comment", "@"),
767 ARGPARSE_s_n (oDefaultComment, "default-comment", "@"),
768 ARGPARSE_s_n (oNoComments, "no-comments", "@"),
769 ARGPARSE_s_n (oEmitVersion, "emit-version", "@"),
770 ARGPARSE_s_n (oNoEmitVersion, "no-emit-version", "@"),
771 ARGPARSE_s_n (oNoEmitVersion, "no-version", "@"), /* alias */
772 ARGPARSE_s_n (oNotDashEscaped, "not-dash-escaped", "@"),
773 ARGPARSE_s_n (oEscapeFrom, "escape-from-lines", "@"),
774 ARGPARSE_s_n (oNoEscapeFrom, "no-escape-from-lines", "@"),
775 ARGPARSE_s_n (oLockOnce, "lock-once", "@"),
776 ARGPARSE_s_n (oLockMultiple, "lock-multiple", "@"),
777 ARGPARSE_s_n (oLockNever, "lock-never", "@"),
778 ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"),
779 ARGPARSE_s_s (oLoggerFile, "log-file", "@"),
780 ARGPARSE_s_s (oLoggerFile, "logger-file", "@"), /* 1.4 compatibility. */
781 ARGPARSE_s_n (oUseEmbeddedFilename, "use-embedded-filename", "@"),
782 ARGPARSE_s_n (oNoUseEmbeddedFilename, "no-use-embedded-filename", "@"),
783 ARGPARSE_s_n (oUtf8Strings, "utf8-strings", "@"),
784 ARGPARSE_s_n (oNoUtf8Strings, "no-utf8-strings", "@"),
785 ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"),
786 ARGPARSE_s_n (oWithSubkeyFingerprint, "with-subkey-fingerprint", "@"),
787 ARGPARSE_s_n (oWithSubkeyFingerprint, "with-subkey-fingerprints", "@"),
788 ARGPARSE_s_n (oWithICAOSpelling, "with-icao-spelling", "@"),
789 ARGPARSE_s_n (oWithKeygrip, "with-keygrip", "@"),
790 ARGPARSE_s_n (oWithSecret, "with-secret", "@"),
791 ARGPARSE_s_n (oWithWKDHash, "with-wkd-hash", "@"),
792 ARGPARSE_s_n (oWithKeyOrigin, "with-key-origin", "@"),
793 ARGPARSE_s_s (oDisableCipherAlgo, "disable-cipher-algo", "@"),
794 ARGPARSE_s_s (oDisablePubkeyAlgo, "disable-pubkey-algo", "@"),
795 ARGPARSE_s_n (oAllowNonSelfsignedUID, "allow-non-selfsigned-uid", "@"),
796 ARGPARSE_s_n (oNoAllowNonSelfsignedUID, "no-allow-non-selfsigned-uid", "@"),
797 ARGPARSE_s_n (oAllowFreeformUID, "allow-freeform-uid", "@"),
798 ARGPARSE_s_n (oNoAllowFreeformUID, "no-allow-freeform-uid", "@"),
799 ARGPARSE_s_n (oNoLiteral, "no-literal", "@"),
800 ARGPARSE_p_u (oSetFilesize, "set-filesize", "@"),
801 ARGPARSE_s_n (oFastListMode, "fast-list-mode", "@"),
802 ARGPARSE_s_n (oFixedListMode, "fixed-list-mode", "@"),
803 ARGPARSE_s_n (oLegacyListMode, "legacy-list-mode", "@"),
804 ARGPARSE_s_n (oListOnly, "list-only", "@"),
805 ARGPARSE_s_n (oPrintPKARecords, "print-pka-records", "@"),
806 ARGPARSE_s_n (oPrintDANERecords, "print-dane-records", "@"),
807 ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"),
808 ARGPARSE_s_n (oIgnoreValidFrom, "ignore-valid-from", "@"),
809 ARGPARSE_s_n (oIgnoreCrcError, "ignore-crc-error", "@"),
810 ARGPARSE_s_n (oIgnoreMDCError, "ignore-mdc-error", "@"),
811 ARGPARSE_s_n (oShowSessionKey, "show-session-key", "@"),
812 ARGPARSE_s_s (oOverrideSessionKey, "override-session-key", "@"),
813 ARGPARSE_s_i (oOverrideSessionKeyFD, "override-session-key-fd", "@"),
814 ARGPARSE_s_n (oNoRandomSeedFile, "no-random-seed-file", "@"),
815 ARGPARSE_s_n (oAutoKeyRetrieve, "auto-key-retrieve", "@"),
816 ARGPARSE_s_n (oNoAutoKeyRetrieve, "no-auto-key-retrieve", "@"),
817 ARGPARSE_s_n (oNoSigCache, "no-sig-cache", "@"),
818 ARGPARSE_s_n (oMergeOnly, "merge-only", "@" ),
819 ARGPARSE_s_n (oAllowSecretKeyImport, "allow-secret-key-import", "@"),
820 ARGPARSE_s_n (oTryAllSecrets, "try-all-secrets", "@"),
821 ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"),
822 ARGPARSE_s_n (oNoExpensiveTrustChecks, "no-expensive-trust-checks", "@"),
823 ARGPARSE_s_n (oPreservePermissions, "preserve-permissions", "@"),
824 ARGPARSE_s_s (oDefaultPreferenceList, "default-preference-list", "@"),
825 ARGPARSE_s_s (oDefaultKeyserverURL, "default-keyserver-url", "@"),
826 ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-preferences","@"),
827 ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-preferences","@"),
828 ARGPARSE_s_s (oPersonalCompressPreferences,
829 "personal-compress-preferences", "@"),
830 ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
831 ARGPARSE_s_s (oWeakDigest, "weak-digest","@"),
832 ARGPARSE_s_n (oUnwrap, "unwrap", "@"),
833 ARGPARSE_s_n (oOnlySignTextIDs, "only-sign-text-ids", "@"),
835 /* Aliases. I constantly mistype these, and assume other people do
837 ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-prefs", "@"),
838 ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-prefs", "@"),
839 ARGPARSE_s_s (oPersonalCompressPreferences, "personal-compress-prefs", "@"),
841 ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
842 ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"),
843 ARGPARSE_s_n (oDisableDirmngr, "disable-dirmngr", "@"),
844 ARGPARSE_s_s (oDisplay, "display", "@"),
845 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
846 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
847 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
848 ARGPARSE_s_s (oLCmessages, "lc-messages","@"),
849 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
850 ARGPARSE_s_s (oGroup, "group", "@"),
851 ARGPARSE_s_s (oUnGroup, "ungroup", "@"),
852 ARGPARSE_s_n (oNoGroups, "no-groups", "@"),
853 ARGPARSE_s_n (oStrict, "strict", "@"),
854 ARGPARSE_s_n (oNoStrict, "no-strict", "@"),
855 ARGPARSE_s_n (oMangleDosFilenames, "mangle-dos-filenames", "@"),
856 ARGPARSE_s_n (oNoMangleDosFilenames, "no-mangle-dos-filenames", "@"),
857 ARGPARSE_s_n (oEnableProgressFilter, "enable-progress-filter", "@"),
858 ARGPARSE_s_n (oMultifile, "multifile", "@"),
859 ARGPARSE_s_s (oKeyidFormat, "keyid-format", "@"),
860 ARGPARSE_s_n (oExitOnStatusWriteError, "exit-on-status-write-error", "@"),
861 ARGPARSE_s_i (oLimitCardInsertTries, "limit-card-insert-tries", "@"),
863 ARGPARSE_s_n (oAllowMultisigVerification,
864 "allow-multisig-verification", "@"),
865 ARGPARSE_s_n (oEnableLargeRSA, "enable-large-rsa", "@"),
866 ARGPARSE_s_n (oDisableLargeRSA, "disable-large-rsa", "@"),
867 ARGPARSE_s_n (oEnableDSA2, "enable-dsa2", "@"),
868 ARGPARSE_s_n (oDisableDSA2, "disable-dsa2", "@"),
869 ARGPARSE_s_n (oAllowMultipleMessages, "allow-multiple-messages", "@"),
870 ARGPARSE_s_n (oNoAllowMultipleMessages, "no-allow-multiple-messages", "@"),
871 ARGPARSE_s_n (oAllowWeakDigestAlgos, "allow-weak-digest-algos", "@"),
873 ARGPARSE_s_s (oDefaultNewKeyAlgo, "default-new-key-algo", "@"),
875 /* These two are aliases to help users of the PGP command line
876 product use gpg with minimal pain. Many commands are common
877 already as they seem to have borrowed commands from us. Now I'm
878 returning the favor. */
879 ARGPARSE_s_s (oLocalUser, "sign-with", "@"),
880 ARGPARSE_s_s (oRecipient, "user", "@"),
882 ARGPARSE_s_n (oRequireCrossCert, "require-backsigs", "@"),
883 ARGPARSE_s_n (oRequireCrossCert, "require-cross-certification", "@"),
884 ARGPARSE_s_n (oNoRequireCrossCert, "no-require-backsigs", "@"),
885 ARGPARSE_s_n (oNoRequireCrossCert, "no-require-cross-certification", "@"),
887 /* New options. Fixme: Should go more to the top. */
888 ARGPARSE_s_s (oAutoKeyLocate, "auto-key-locate", "@"),
889 ARGPARSE_s_n (oNoAutoKeyLocate, "no-auto-key-locate", "@"),
890 ARGPARSE_s_n (oNoAutostart, "no-autostart", "@"),
892 /* Dummy options with warnings. */
893 ARGPARSE_s_n (oUseAgent, "use-agent", "@"),
894 ARGPARSE_s_n (oNoUseAgent, "no-use-agent", "@"),
895 ARGPARSE_s_s (oGpgAgentInfo, "gpg-agent-info", "@"),
896 ARGPARSE_s_s (oReaderPort, "reader-port", "@"),
897 ARGPARSE_s_s (octapiDriver, "ctapi-driver", "@"),
898 ARGPARSE_s_s (opcscDriver, "pcsc-driver", "@"),
899 ARGPARSE_s_n (oDisableCCID, "disable-ccid", "@"),
900 ARGPARSE_s_n (oHonorHttpProxy, "honor-http-proxy", "@"),
901 ARGPARSE_s_s (oTOFUDBFormat, "tofu-db-format", "@"),
904 ARGPARSE_s_n (oNoop, "sk-comments", "@"),
905 ARGPARSE_s_n (oNoop, "no-sk-comments", "@"),
906 ARGPARSE_s_n (oNoop, "compress-keys", "@"),
907 ARGPARSE_s_n (oNoop, "compress-sigs", "@"),
908 ARGPARSE_s_n (oNoop, "force-v3-sigs", "@"),
909 ARGPARSE_s_n (oNoop, "no-force-v3-sigs", "@"),
910 ARGPARSE_s_n (oNoop, "force-v4-certs", "@"),
911 ARGPARSE_s_n (oNoop, "no-force-v4-certs", "@"),
917 /* The list of supported debug flags. */
918 static struct debug_flags_s debug_flags [] =
920 { DBG_PACKET_VALUE , "packet" },
921 { DBG_MPI_VALUE , "mpi" },
922 { DBG_CRYPTO_VALUE , "crypto" },
923 { DBG_FILTER_VALUE , "filter" },
924 { DBG_IOBUF_VALUE , "iobuf" },
925 { DBG_MEMORY_VALUE , "memory" },
926 { DBG_CACHE_VALUE , "cache" },
927 { DBG_MEMSTAT_VALUE, "memstat" },
928 { DBG_TRUST_VALUE , "trust" },
929 { DBG_HASHING_VALUE, "hashing" },
930 { DBG_IPC_VALUE , "ipc" },
931 { DBG_CLOCK_VALUE , "clock" },
932 { DBG_LOOKUP_VALUE , "lookup" },
933 { DBG_EXTPROG_VALUE, "extprog" },
938 #ifdef ENABLE_SELINUX_HACKS
939 #define ALWAYS_ADD_KEYRINGS 1
941 #define ALWAYS_ADD_KEYRINGS 0
945 int g10_errors_seen = 0;
947 static int utf8_strings = 0;
948 static int maybe_setuid = 1;
950 static char *build_list( const char *text, char letter,
951 const char *(*mapf)(int), int (*chkf)(int) );
952 static void set_cmd( enum cmd_and_opt_values *ret_cmd,
953 enum cmd_and_opt_values new_cmd );
954 static void print_mds( const char *fname, int algo );
955 static void add_notation_data( const char *string, int which );
956 static void add_policy_url( const char *string, int which );
957 static void add_keyserver_url( const char *string, int which );
958 static void emergency_cleanup (void);
959 static void read_sessionkey_from_fd (int fd);
963 make_libversion (const char *libname, const char *(*getfnc)(const char*))
970 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
974 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
975 strcpy (stpcpy (stpcpy (result, libname), " "), s);
981 build_list_pk_test_algo (int algo)
983 /* Show only one "RSA" string. If RSA_E or RSA_S is available RSA
984 is also available. */
985 if (algo == PUBKEY_ALGO_RSA_E
986 || algo == PUBKEY_ALGO_RSA_S)
987 return GPG_ERR_DIGEST_ALGO;
989 return openpgp_pk_test_algo (algo);
993 build_list_pk_algo_name (int algo)
995 return openpgp_pk_algo_name (algo);
999 build_list_cipher_test_algo (int algo)
1001 return openpgp_cipher_test_algo (algo);
1005 build_list_cipher_algo_name (int algo)
1007 return openpgp_cipher_algo_name (algo);
1011 build_list_md_test_algo (int algo)
1013 /* By default we do not accept MD5 based signatures. To avoid
1014 confusion we do not announce support for it either. */
1015 if (algo == DIGEST_ALGO_MD5)
1016 return GPG_ERR_DIGEST_ALGO;
1018 return openpgp_md_test_algo (algo);
1022 build_list_md_algo_name (int algo)
1024 return openpgp_md_algo_name (algo);
1029 my_strusage( int level )
1031 static char *digests, *pubkeys, *ciphers, *zips, *ver_gcry;
1035 case 11: p = "@GPG@ (@GNUPG@)";
1037 case 13: p = VERSION; break;
1038 case 17: p = PRINTABLE_OS_NAME; break;
1039 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
1043 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
1047 #ifdef IS_DEVELOPMENT_VERSION
1049 p="NOTE: THIS IS A DEVELOPMENT VERSION!";
1052 p="It is only intended for test purposes and should NOT be";
1055 p="used in a production environment or with production keys!";
1061 _("Usage: @GPG@ [options] [files] (-h for help)");
1064 _("Syntax: @GPG@ [options] [files]\n"
1065 "Sign, check, encrypt or decrypt\n"
1066 "Default operation depends on the input data\n");
1069 case 31: p = "\nHome: "; break;
1071 case 32: p = gnupg_homedir (); break;
1072 #else /* __riscos__ */
1073 case 32: p = make_filename(gnupg_homedir (), NULL); break;
1074 #endif /* __riscos__ */
1075 case 33: p = _("\nSupported algorithms:\n"); break;
1078 pubkeys = build_list (_("Pubkey: "), 1,
1079 build_list_pk_algo_name,
1080 build_list_pk_test_algo );
1085 ciphers = build_list(_("Cipher: "), 'S',
1086 build_list_cipher_algo_name,
1087 build_list_cipher_test_algo );
1092 digests = build_list(_("Hash: "), 'H',
1093 build_list_md_algo_name,
1094 build_list_md_test_algo );
1099 zips = build_list(_("Compression: "),'Z',
1100 compress_algo_to_string,
1101 check_compress_algo);
1112 build_list (const char *text, char letter,
1113 const char * (*mapf)(int), int (*chkf)(int))
1122 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
1124 indent = utf8_charcount (text, -1);
1126 init_membuf (&mb, 512);
1128 for (i=0; i <= 110; i++ )
1130 if (!chkf (i) && (s = mapf (i)))
1132 if (mb.len - len > 60)
1134 put_membuf_str (&mb, ",\n");
1136 for (j=0; j < indent; j++)
1137 put_membuf_str (&mb, " ");
1140 put_membuf_str (&mb, ", ");
1142 put_membuf_str (&mb, text);
1144 put_membuf_str (&mb, s);
1145 if (opt.verbose && letter)
1149 snprintf (num, sizeof num, " (%d)", i);
1151 snprintf (num, sizeof num, " (%c%d)", letter, i);
1152 put_membuf_str (&mb, num);
1157 put_membuf_str (&mb, "\n");
1158 put_membuf (&mb, "", 1);
1160 string = get_membuf (&mb, NULL);
1161 return xrealloc (string, strlen (string)+1);
1166 wrong_args( const char *text)
1168 es_fprintf (es_stderr, _("usage: %s [options] %s\n"), GPG_NAME, text);
1169 log_inc_errorcount ();
1175 make_username( const char *string )
1179 p = xstrdup(string);
1181 p = native_to_utf8( string );
1187 set_opt_session_env (const char *name, const char *value)
1191 err = session_env_setenv (opt.session_env, name, value);
1193 log_fatal ("error setting session environment: %s\n",
1194 gpg_strerror (err));
1198 /* Setup the debugging. With a LEVEL of NULL only the active debug
1199 flags are propagated to the subsystems. With LEVEL set, a specific
1200 set of debug flags is set; thus overriding all flags already
1203 set_debug (const char *level)
1205 int numok = (level && digitp (level));
1206 int numlvl = numok? atoi (level) : 0;
1210 else if (!strcmp (level, "none") || (numok && numlvl < 1))
1212 else if (!strcmp (level, "basic") || (numok && numlvl <= 2))
1213 opt.debug = DBG_MEMSTAT_VALUE;
1214 else if (!strcmp (level, "advanced") || (numok && numlvl <= 5))
1215 opt.debug = DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE;
1216 else if (!strcmp (level, "expert") || (numok && numlvl <= 8))
1217 opt.debug = (DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE
1218 |DBG_CACHE_VALUE|DBG_LOOKUP|DBG_FILTER_VALUE|DBG_PACKET_VALUE);
1219 else if (!strcmp (level, "guru") || numok)
1222 /* Unless the "guru" string has been used we don't want to allow
1223 hashing debugging. The rationale is that people tend to
1224 select the highest debug value and would then clutter their
1225 disk with debug files which may reveal confidential data. */
1227 opt.debug &= ~(DBG_HASHING_VALUE);
1231 log_error (_("invalid debug-level '%s' given\n"), level);
1235 if ((opt.debug & DBG_MEMORY_VALUE))
1236 memory_debug_mode = 1;
1237 if ((opt.debug & DBG_MEMSTAT_VALUE))
1238 memory_stat_debug_mode = 1;
1240 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
1242 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
1243 if ((opt.debug & DBG_IOBUF_VALUE))
1244 iobuf_debug_mode = 1;
1245 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1248 parse_debug_flag (NULL, &opt.debug, debug_flags);
1252 /* We set the screen dimensions for UI purposes. Do not allow screens
1253 smaller than 80x24 for the sake of simplicity. */
1255 set_screen_dimensions(void)
1257 #ifndef HAVE_W32_SYSTEM
1260 str=getenv("COLUMNS");
1262 opt.screen_columns=atoi(str);
1264 str=getenv("LINES");
1266 opt.screen_lines=atoi(str);
1269 if(opt.screen_columns<80 || opt.screen_columns>255)
1270 opt.screen_columns=80;
1272 if(opt.screen_lines<24 || opt.screen_lines>255)
1273 opt.screen_lines=24;
1277 /* Helper to open a file FNAME either for reading or writing to be
1278 used with --status-file etc functions. Not generally useful but it
1279 avoids the riscos specific functions and well some Windows people
1280 might like it too. Prints an error message and returns -1 on
1281 error. On success the file descriptor is returned. */
1283 open_info_file (const char *fname, int for_write, int binary)
1286 return riscos_fdopenfile (fname, for_write);
1287 #elif defined (ENABLE_SELINUX_HACKS)
1288 /* We can't allow these even when testing for a secured filename
1289 because files to be secured might not yet been secured. This is
1290 similar to the option file but in that case it is unlikely that
1291 sensitive information may be retrieved by means of error
1301 binary = MY_O_BINARY;
1303 /* if (is_secured_filename (fname)) */
1306 /* gpg_err_set_errno (EPERM); */
1313 fd = open (fname, O_CREAT | O_TRUNC | O_WRONLY | binary,
1314 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
1316 fd = open (fname, O_RDONLY | binary);
1318 while (fd == -1 && errno == EINTR);
1321 log_error ( for_write? _("can't create '%s': %s\n")
1322 : _("can't open '%s': %s\n"), fname, strerror(errno));
1329 set_cmd( enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd )
1331 enum cmd_and_opt_values cmd = *ret_cmd;
1333 if( !cmd || cmd == new_cmd )
1335 else if( cmd == aSign && new_cmd == aEncr )
1337 else if( cmd == aEncr && new_cmd == aSign )
1339 else if( cmd == aSign && new_cmd == aSym )
1341 else if( cmd == aSym && new_cmd == aSign )
1343 else if( cmd == aSym && new_cmd == aEncr )
1345 else if( cmd == aEncr && new_cmd == aSym )
1347 else if (cmd == aSignEncr && new_cmd == aSym)
1349 else if (cmd == aSignSym && new_cmd == aEncr)
1351 else if (cmd == aEncrSym && new_cmd == aSign)
1353 else if( ( cmd == aSign && new_cmd == aClearsign )
1354 || ( cmd == aClearsign && new_cmd == aSign ) )
1357 log_error(_("conflicting commands\n"));
1366 add_group(char *string)
1369 struct groupitem *item;
1371 /* Break off the group name */
1372 name=strsep(&string,"=");
1375 log_error(_("no = sign found in group definition '%s'\n"),name);
1379 trim_trailing_ws(name,strlen(name));
1381 /* Does this group already exist? */
1382 for(item=opt.grouplist;item;item=item->next)
1383 if(strcasecmp(item->name,name)==0)
1388 item=xmalloc(sizeof(struct groupitem));
1390 item->next=opt.grouplist;
1395 /* Break apart the values */
1396 while ((value= strsep(&string," \t")))
1399 add_to_strlist2(&item->values,value,utf8_strings);
1405 rm_group(char *name)
1407 struct groupitem *item,*last=NULL;
1409 trim_trailing_ws(name,strlen(name));
1411 for(item=opt.grouplist;item;last=item,item=item->next)
1413 if(strcasecmp(item->name,name)==0)
1416 last->next=item->next;
1418 opt.grouplist=item->next;
1420 free_strlist(item->values);
1428 /* We need to check three things.
1430 0) The homedir. It must be x00, a directory, and owned by the
1433 1) The options/gpg.conf file. Okay unless it or its containing
1434 directory is group or other writable or not owned by us. Disable
1437 2) Extensions. Same as #1.
1439 Returns true if the item is unsafe. */
1441 check_permissions (const char *path, int item)
1443 #if defined(HAVE_STAT) && !defined(HAVE_DOSISH_SYSTEM)
1444 static int homedir_cache=-1;
1446 struct stat statbuf,dirbuf;
1447 int homedir=0,ret=0,checkonly=0;
1448 int perm=0,own=0,enc_dir_perm=0,enc_dir_own=0;
1450 if(opt.no_perm_warn)
1453 log_assert(item==0 || item==1 || item==2);
1455 /* extensions may attach a path */
1456 if(item==2 && path[0]!=DIRSEP_C)
1458 if(strchr(path,DIRSEP_C))
1459 tmppath=make_filename(path,NULL);
1461 tmppath=make_filename(gnupg_libdir (),path,NULL);
1464 tmppath=xstrdup(path);
1466 /* If the item is located in the homedir, but isn't the homedir,
1467 don't continue if we already checked the homedir itself. This is
1468 to avoid user confusion with an extra options file warning which
1469 could be rectified if the homedir itself had proper
1471 if(item!=0 && homedir_cache>-1
1472 && !ascii_strncasecmp (gnupg_homedir (), tmppath,
1473 strlen (gnupg_homedir ())))
1479 /* It's okay if the file or directory doesn't exist */
1480 if(stat(tmppath,&statbuf)!=0)
1486 /* Now check the enclosing directory. Theoretically, we could walk
1487 this test up to the root directory /, but for the sake of sanity,
1488 I'm stopping at one level down. */
1489 dir=make_dirname(tmppath);
1491 if(stat(dir,&dirbuf)!=0 || !S_ISDIR(dirbuf.st_mode))
1500 /* Assume failure */
1505 /* The homedir must be x00, a directory, and owned by the user. */
1507 if(S_ISDIR(statbuf.st_mode))
1509 if(statbuf.st_uid==getuid())
1511 if((statbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1522 else if(item==1 || item==2)
1524 /* The options or extension file. Okay unless it or its
1525 containing directory is group or other writable or not owned
1528 if(S_ISREG(statbuf.st_mode))
1530 if(statbuf.st_uid==getuid() || statbuf.st_uid==0)
1532 if((statbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1534 /* it's not writable, so make sure the enclosing
1535 directory is also not writable */
1536 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1538 if((dirbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1548 /* it's writable, so the enclosing directory had
1549 better not let people get to it. */
1550 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1552 if((dirbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1555 perm=enc_dir_perm=1; /* unclear which one to fix! */
1573 log_info(_("WARNING: unsafe ownership on"
1574 " homedir '%s'\n"),tmppath);
1576 log_info(_("WARNING: unsafe ownership on"
1577 " configuration file '%s'\n"),tmppath);
1579 log_info(_("WARNING: unsafe ownership on"
1580 " extension '%s'\n"),tmppath);
1585 log_info(_("WARNING: unsafe permissions on"
1586 " homedir '%s'\n"),tmppath);
1588 log_info(_("WARNING: unsafe permissions on"
1589 " configuration file '%s'\n"),tmppath);
1591 log_info(_("WARNING: unsafe permissions on"
1592 " extension '%s'\n"),tmppath);
1597 log_info(_("WARNING: unsafe enclosing directory ownership on"
1598 " homedir '%s'\n"),tmppath);
1600 log_info(_("WARNING: unsafe enclosing directory ownership on"
1601 " configuration file '%s'\n"),tmppath);
1603 log_info(_("WARNING: unsafe enclosing directory ownership on"
1604 " extension '%s'\n"),tmppath);
1609 log_info(_("WARNING: unsafe enclosing directory permissions on"
1610 " homedir '%s'\n"),tmppath);
1612 log_info(_("WARNING: unsafe enclosing directory permissions on"
1613 " configuration file '%s'\n"),tmppath);
1615 log_info(_("WARNING: unsafe enclosing directory permissions on"
1616 " extension '%s'\n"),tmppath);
1628 #else /*!(HAVE_STAT && !HAVE_DOSISH_SYSTEM)*/
1632 #endif /*!(HAVE_STAT && !HAVE_DOSISH_SYSTEM)*/
1636 /* Print the OpenPGP defined algo numbers. */
1638 print_algo_numbers(int (*checker)(int))
1657 print_algo_names(int (*checker)(int),const char *(*mapper)(int))
1669 es_printf ("%s",mapper(i));
1674 /* In the future, we can do all sorts of interesting configuration
1675 output here. For now, just give "group" as the Enigmail folks need
1676 it, and pubkey, cipher, hash, and compress as they may be useful
1679 list_config(char *items)
1681 int show_all = !items;
1684 struct groupitem *giter;
1687 if(!opt.with_colons)
1690 while(show_all || (name=strsep(&items," ")))
1694 if(show_all || ascii_strcasecmp(name,"group")==0)
1696 for (giter = opt.grouplist; giter; giter = giter->next)
1700 es_fprintf (es_stdout, "cfg:group:");
1701 es_write_sanitized (es_stdout, giter->name, strlen(giter->name),
1703 es_putc (':', es_stdout);
1705 for(sl=giter->values; sl; sl=sl->next)
1707 es_write_sanitized (es_stdout, sl->d, strlen (sl->d),
1719 if(show_all || ascii_strcasecmp(name,"version")==0)
1721 es_printf("cfg:version:");
1722 es_write_sanitized (es_stdout, VERSION, strlen(VERSION), ":", NULL);
1727 if(show_all || ascii_strcasecmp(name,"pubkey")==0)
1729 es_printf ("cfg:pubkey:");
1730 print_algo_numbers (build_list_pk_test_algo);
1735 if(show_all || ascii_strcasecmp(name,"pubkeyname")==0)
1737 es_printf ("cfg:pubkeyname:");
1738 print_algo_names (build_list_pk_test_algo,
1739 build_list_pk_algo_name);
1744 if(show_all || ascii_strcasecmp(name,"cipher")==0)
1746 es_printf ("cfg:cipher:");
1747 print_algo_numbers (build_list_cipher_test_algo);
1752 if (show_all || !ascii_strcasecmp (name,"ciphername"))
1754 es_printf ("cfg:ciphername:");
1755 print_algo_names (build_list_cipher_test_algo,
1756 build_list_cipher_algo_name);
1762 || ascii_strcasecmp(name,"digest")==0
1763 || ascii_strcasecmp(name,"hash")==0)
1765 es_printf ("cfg:digest:");
1766 print_algo_numbers (build_list_md_test_algo);
1772 || !ascii_strcasecmp(name,"digestname")
1773 || !ascii_strcasecmp(name,"hashname"))
1775 es_printf ("cfg:digestname:");
1776 print_algo_names (build_list_md_test_algo,
1777 build_list_md_algo_name);
1782 if(show_all || ascii_strcasecmp(name,"compress")==0)
1784 es_printf ("cfg:compress:");
1785 print_algo_numbers(check_compress_algo);
1790 if(show_all || ascii_strcasecmp (name, "compressname") == 0)
1792 es_printf ("cfg:compressname:");
1793 print_algo_names (check_compress_algo,
1794 compress_algo_to_string);
1799 if (show_all || !ascii_strcasecmp(name,"ccid-reader-id"))
1801 /* We ignore this for GnuPG 1.4 backward compatibility. */
1805 if (show_all || !ascii_strcasecmp (name,"curve"))
1807 es_printf ("cfg:curve:");
1808 for (iter=0, first=1; (s = openpgp_enum_curves (&iter)); first=0)
1809 es_printf ("%s%s", first?"":";", s);
1814 /* Curve OIDs are rarely useful and thus only printed if requested. */
1815 if (name && !ascii_strcasecmp (name,"curveoid"))
1817 es_printf ("cfg:curveoid:");
1818 for (iter=0, first=1; (s = openpgp_enum_curves (&iter)); first = 0)
1820 s = openpgp_curve_to_oid (s, NULL);
1821 es_printf ("%s%s", first?"":";", s? s:"[?]");
1831 log_error(_("unknown configuration item '%s'\n"),name);
1836 /* List options and default values in the GPG Conf format. This is a
1837 new tool distributed with gnupg 1.9.x but we also want some limited
1838 support in older gpg versions. The output is the name of the
1839 configuration file and a list of options available for editing by
1842 gpgconf_list (const char *configfile)
1844 char *configfile_esc = percent_escape (configfile, NULL);
1846 es_printf ("%s-%s.conf:%lu:\"%s\n",
1847 GPGCONF_NAME, GPG_NAME,
1848 GC_OPT_FLAG_DEFAULT,
1849 configfile_esc ? configfile_esc : "/dev/null");
1850 es_printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
1851 es_printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
1852 es_printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
1853 es_printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE);
1854 es_printf ("default-key:%lu:\n", GC_OPT_FLAG_NONE);
1855 es_printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_NONE);
1856 es_printf ("try-secret-key:%lu:\n", GC_OPT_FLAG_NONE);
1857 es_printf ("auto-key-locate:%lu:\n", GC_OPT_FLAG_NONE);
1858 es_printf ("auto-key-retrieve:%lu:\n", GC_OPT_FLAG_NONE);
1859 es_printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE);
1860 es_printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
1861 es_printf ("group:%lu:\n", GC_OPT_FLAG_NONE);
1862 es_printf ("compliance:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT, "gnupg");
1863 es_printf ("default-new-key-algo:%lu:\n", GC_OPT_FLAG_NONE);
1864 es_printf ("trust-model:%lu:\n", GC_OPT_FLAG_NONE);
1865 es_printf ("disable-dirmngr:%lu:\n", GC_OPT_FLAG_NONE);
1866 es_printf ("max-cert-depth:%lu:\n", GC_OPT_FLAG_NONE);
1867 es_printf ("completes-needed:%lu:\n", GC_OPT_FLAG_NONE);
1868 es_printf ("marginals-needed:%lu:\n", GC_OPT_FLAG_NONE);
1870 /* The next one is an info only item and should match the macros at
1871 the top of keygen.c */
1872 es_printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1873 get_default_pubkey_algo ());
1875 xfree (configfile_esc);
1880 parse_subpacket_list(char *list)
1883 byte subpackets[128],i;
1888 /* No arguments means all subpackets */
1889 memset(subpackets+1,1,sizeof(subpackets)-1);
1894 memset(subpackets,0,sizeof(subpackets));
1896 /* Merge with earlier copy */
1897 if(opt.show_subpackets)
1901 for(in=opt.show_subpackets;*in;in++)
1903 if(*in>127 || *in<1)
1906 if(!subpackets[*in])
1912 while((tok=strsep(&list," ,")))
1927 xfree(opt.show_subpackets);
1928 opt.show_subpackets=xmalloc(count+1);
1929 opt.show_subpackets[count--]=0;
1931 for(i=1;i<128 && count>=0;i++)
1933 opt.show_subpackets[count--]=i;
1940 parse_list_options(char *str)
1942 char *subpackets=""; /* something that isn't NULL */
1943 struct parse_options lopts[]=
1945 {"show-photos",LIST_SHOW_PHOTOS,NULL,
1946 N_("display photo IDs during key listings")},
1947 {"show-usage",LIST_SHOW_USAGE,NULL,
1948 N_("show key usage information during key listings")},
1949 {"show-policy-urls",LIST_SHOW_POLICY_URLS,NULL,
1950 N_("show policy URLs during signature listings")},
1951 {"show-notations",LIST_SHOW_NOTATIONS,NULL,
1952 N_("show all notations during signature listings")},
1953 {"show-std-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1954 N_("show IETF standard notations during signature listings")},
1955 {"show-standard-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1957 {"show-user-notations",LIST_SHOW_USER_NOTATIONS,NULL,
1958 N_("show user-supplied notations during signature listings")},
1959 {"show-keyserver-urls",LIST_SHOW_KEYSERVER_URLS,NULL,
1960 N_("show preferred keyserver URLs during signature listings")},
1961 {"show-uid-validity",LIST_SHOW_UID_VALIDITY,NULL,
1962 N_("show user ID validity during key listings")},
1963 {"show-unusable-uids",LIST_SHOW_UNUSABLE_UIDS,NULL,
1964 N_("show revoked and expired user IDs in key listings")},
1965 {"show-unusable-subkeys",LIST_SHOW_UNUSABLE_SUBKEYS,NULL,
1966 N_("show revoked and expired subkeys in key listings")},
1967 {"show-keyring",LIST_SHOW_KEYRING,NULL,
1968 N_("show the keyring name in key listings")},
1969 {"show-sig-expire",LIST_SHOW_SIG_EXPIRE,NULL,
1970 N_("show expiration dates during signature listings")},
1971 {"show-sig-subpackets",LIST_SHOW_SIG_SUBPACKETS,NULL,
1976 /* C99 allows for non-constant initializers, but we'd like to
1977 compile everywhere, so fill in the show-sig-subpackets argument
1978 here. Note that if the parse_options array changes, we'll have
1979 to change the subscript here. */
1980 lopts[13].value=&subpackets;
1982 if(parse_options(str,&opt.list_options,lopts,1))
1984 if(opt.list_options&LIST_SHOW_SIG_SUBPACKETS)
1986 /* Unset so users can pass multiple lists in. */
1987 opt.list_options&=~LIST_SHOW_SIG_SUBPACKETS;
1988 if(!parse_subpacket_list(subpackets))
1991 else if(subpackets==NULL && opt.show_subpackets)
1993 /* User did 'no-show-subpackets' */
1994 xfree(opt.show_subpackets);
1995 opt.show_subpackets=NULL;
2005 /* Collapses argc/argv into a single string that must be freed */
2007 collapse_args(int argc,char *argv[])
2010 int i,first=1,len=0;
2014 len+=strlen(argv[i])+2;
2015 str=xrealloc(str,len);
2024 strcat(str,argv[i]);
2031 #ifndef NO_TRUST_MODELS
2033 parse_trust_model(const char *model)
2035 if(ascii_strcasecmp(model,"pgp")==0)
2036 opt.trust_model=TM_PGP;
2037 else if(ascii_strcasecmp(model,"classic")==0)
2038 opt.trust_model=TM_CLASSIC;
2039 else if(ascii_strcasecmp(model,"always")==0)
2040 opt.trust_model=TM_ALWAYS;
2041 else if(ascii_strcasecmp(model,"direct")==0)
2042 opt.trust_model=TM_DIRECT;
2044 else if(ascii_strcasecmp(model,"tofu")==0)
2045 opt.trust_model=TM_TOFU;
2046 else if(ascii_strcasecmp(model,"tofu+pgp")==0)
2047 opt.trust_model=TM_TOFU_PGP;
2049 else if(ascii_strcasecmp(model,"auto")==0)
2050 opt.trust_model=TM_AUTO;
2052 log_error("unknown trust model '%s'\n",model);
2054 #endif /*NO_TRUST_MODELS*/
2058 parse_tofu_policy (const char *policystr)
2061 struct { const char *keyword; int policy; } list[] = {
2062 { "auto", TOFU_POLICY_AUTO },
2063 { "good", TOFU_POLICY_GOOD },
2064 { "unknown", TOFU_POLICY_UNKNOWN },
2065 { "bad", TOFU_POLICY_BAD },
2066 { "ask", TOFU_POLICY_ASK }
2070 if (!ascii_strcasecmp (policystr, "help"))
2072 log_info (_("valid values for option '%s':\n"), "--tofu-policy");
2073 for (i=0; i < DIM (list); i++)
2074 log_info (" %s\n", list[i].keyword);
2078 for (i=0; i < DIM (list); i++)
2079 if (!ascii_strcasecmp (policystr, list[i].keyword))
2080 return list[i].policy;
2083 log_error (_("unknown TOFU policy '%s'\n"), policystr);
2085 log_info (_("(use \"help\" to list choices)\n"));
2090 static struct gnupg_compliance_option compliance_options[] =
2092 { "gnupg", oGnuPG },
2093 { "openpgp", oOpenPGP },
2094 { "rfc4880bis", oRFC4880bis },
2095 { "rfc4880", oRFC4880 },
2096 { "rfc2440", oRFC2440 },
2104 /* Helper to set compliance related options. This is a separate
2105 * function so that it can also be used by the --compliance option
2108 set_compliance_option (enum cmd_and_opt_values option)
2113 opt.flags.rfc4880bis = 1;
2117 /* This is effectively the same as RFC2440, but with
2118 "--enable-dsa2 --no-rfc2440-text --escape-from-lines
2119 --require-cross-certification". */
2120 opt.compliance = CO_RFC4880;
2122 opt.flags.require_cross_cert = 1;
2123 opt.rfc2440_text = 0;
2124 opt.allow_non_selfsigned_uid = 1;
2125 opt.allow_freeform_uid = 1;
2126 opt.escape_from = 1;
2127 opt.not_dash_escaped = 0;
2128 opt.def_cipher_algo = 0;
2129 opt.def_digest_algo = 0;
2130 opt.cert_digest_algo = 0;
2131 opt.compress_algo = -1;
2132 opt.s2k_mode = 3; /* iterated+salted */
2133 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2134 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2137 opt.compliance = CO_RFC2440;
2139 opt.rfc2440_text = 1;
2140 opt.allow_non_selfsigned_uid = 1;
2141 opt.allow_freeform_uid = 1;
2142 opt.escape_from = 0;
2143 opt.not_dash_escaped = 0;
2144 opt.def_cipher_algo = 0;
2145 opt.def_digest_algo = 0;
2146 opt.cert_digest_algo = 0;
2147 opt.compress_algo = -1;
2148 opt.s2k_mode = 3; /* iterated+salted */
2149 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2150 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2152 case oPGP6: opt.compliance = CO_PGP6; break;
2153 case oPGP7: opt.compliance = CO_PGP7; break;
2154 case oPGP8: opt.compliance = CO_PGP8; break;
2155 case oGnuPG: opt.compliance = CO_GNUPG; break;
2158 set_compliance_option (oOpenPGP);
2159 opt.compliance = CO_DE_VS;
2161 /* Fixme: Change other options. */
2174 /* This function called to initialized a new control object. It is
2175 assumed that this object has been zeroed out before calling this
2178 gpg_init_default_ctrl (ctrl_t ctrl)
2180 ctrl->magic = SERVER_CONTROL_MAGIC;
2184 /* This function is called to deinitialize a control object. It is
2187 gpg_deinit_default_ctrl (ctrl_t ctrl)
2190 tofu_closedbs (ctrl);
2192 gpg_dirmngr_deinit_session_data (ctrl);
2194 keydb_release (ctrl->cached_getkey_kdb);
2199 get_default_configname (void)
2201 char *configname = NULL;
2202 char *name = xstrdup (GPG_NAME EXTSEP_S "conf-" SAFE_VERSION);
2203 char *ver = &name[strlen (GPG_NAME EXTSEP_S "conf-")];
2214 if ((tok = strrchr (ver, SAFE_VERSION_DASH)))
2216 else if ((tok = strrchr (ver, SAFE_VERSION_DOT)))
2222 configname = make_filename (gnupg_homedir (), name, NULL);
2224 while (access (configname, R_OK));
2229 configname = make_filename (gnupg_homedir (),
2230 GPG_NAME EXTSEP_S "conf", NULL);
2231 if (! access (configname, R_OK))
2233 /* Print a warning when both config files are present. */
2234 char *p = make_filename (gnupg_homedir (), "options", NULL);
2235 if (! access (p, R_OK))
2236 log_info (_("Note: old default options file '%s' ignored\n"), p);
2241 /* Use the old default only if it exists. */
2242 char *p = make_filename (gnupg_homedir (), "options", NULL);
2243 if (!access (p, R_OK))
2256 main (int argc, char **argv)
2258 ARGPARSE_ARGS pargs;
2267 strlist_t remusr = NULL;
2268 strlist_t locusr = NULL;
2269 strlist_t nrings = NULL;
2270 armor_filter_context_t *afx = NULL;
2271 int detached_sig = 0;
2272 FILE *configfp = NULL;
2273 char *configname = NULL;
2274 char *save_configname = NULL;
2275 char *default_configname = NULL;
2276 unsigned configlineno;
2277 int parse_debug = 0;
2278 int default_config = 1;
2279 int default_keyring = 1;
2282 char *logfile = NULL;
2283 int use_random_seed = 1;
2284 enum cmd_and_opt_values cmd = 0;
2285 const char *debug_level = NULL;
2286 #ifndef NO_TRUST_MODELS
2287 const char *trustdb_name = NULL;
2288 #endif /*!NO_TRUST_MODELS*/
2289 char *def_cipher_string = NULL;
2290 char *def_digest_string = NULL;
2291 char *compress_algo_string = NULL;
2292 char *cert_digest_string = NULL;
2293 char *s2k_cipher_string = NULL;
2294 char *s2k_digest_string = NULL;
2295 char *pers_cipher_list = NULL;
2296 char *pers_digest_list = NULL;
2297 char *pers_compress_list = NULL;
2301 int ovrseskeyfd = -1;
2302 int fpr_maybe_cmd = 0; /* --fingerprint maybe a command. */
2303 int any_explicit_recipient = 0;
2304 int default_akl = 1;
2305 int require_secmem = 0;
2307 struct assuan_malloc_hooks malloc_hooks;
2310 static int print_dane_records;
2311 static int print_pka_records;
2316 #endif /* __riscos__ */
2318 /* Please note that we may running SUID(ROOT), so be very CAREFUL
2319 when adding any stuff between here and the call to
2320 secmem_init() somewhere after the option parsing. */
2321 early_system_init ();
2322 gnupg_reopen_std (GPG_NAME);
2324 gnupg_rl_initialize ();
2325 set_strusage (my_strusage);
2326 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
2327 log_set_prefix (GPG_NAME, GPGRT_LOG_WITH_PREFIX);
2329 /* Make sure that our subsystems are ready. */
2331 init_common_subsystems (&argc, &argv);
2333 /* Use our own logging handler for Libcgrypt. */
2334 setup_libgcrypt_logging ();
2336 /* Put random number into secure memory */
2337 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
2339 may_coredump = disable_core_dumps();
2341 gnupg_init_signals (0, emergency_cleanup);
2343 dotlock_create (NULL, 0); /* Register lock file cleanup. */
2345 /* Tell the compliance module who we are. */
2346 gnupg_initialize_compliance (GNUPG_MODULE_NAME_GPG);
2349 opt.session_env = session_env_new ();
2350 if (!opt.session_env)
2351 log_fatal ("error allocating session environment block: %s\n",
2354 opt.command_fd = -1; /* no command fd */
2355 opt.compress_level = -1; /* defaults to standard compress level */
2356 opt.bz2_compress_level = -1; /* defaults to standard compress level */
2357 /* note: if you change these lines, look at oOpenPGP */
2358 opt.def_cipher_algo = 0;
2359 opt.def_digest_algo = 0;
2360 opt.cert_digest_algo = 0;
2361 opt.compress_algo = -1; /* defaults to DEFAULT_COMPRESS_ALGO */
2362 opt.s2k_mode = 3; /* iterated+salted */
2363 opt.s2k_count = 0; /* Auto-calibrate when needed. */
2364 opt.s2k_cipher_algo = DEFAULT_CIPHER_ALGO;
2365 opt.completes_needed = 1;
2366 opt.marginals_needed = 3;
2367 opt.max_cert_depth = 5;
2368 opt.escape_from = 1;
2369 opt.flags.require_cross_cert = 1;
2370 opt.import_options = IMPORT_REPAIR_KEYS;
2371 opt.export_options = EXPORT_ATTRIBUTES;
2372 opt.keyserver_options.import_options = (IMPORT_REPAIR_KEYS
2373 | IMPORT_REPAIR_PKS_SUBKEY_BUG);
2374 opt.keyserver_options.export_options = EXPORT_ATTRIBUTES;
2375 opt.keyserver_options.options = KEYSERVER_HONOR_PKA_RECORD;
2376 opt.verify_options = (LIST_SHOW_UID_VALIDITY
2377 | VERIFY_SHOW_POLICY_URLS
2378 | VERIFY_SHOW_STD_NOTATIONS
2379 | VERIFY_SHOW_KEYSERVER_URLS);
2380 opt.list_options = (LIST_SHOW_UID_VALIDITY
2382 #ifdef NO_TRUST_MODELS
2383 opt.trust_model = TM_ALWAYS;
2385 opt.trust_model = TM_AUTO;
2387 opt.tofu_default_policy = TOFU_POLICY_AUTO;
2388 opt.mangle_dos_filenames = 0;
2389 opt.min_cert_level = 2;
2390 set_screen_dimensions ();
2391 opt.keyid_format = KF_NONE;
2392 opt.def_sig_expire = "0";
2393 opt.def_cert_expire = "0";
2394 gnupg_set_homedir (NULL);
2395 opt.passphrase_repeat = 1;
2396 opt.emit_version = 0;
2397 opt.weak_digests = NULL;
2399 /* Check whether we have a config file on the command line. */
2404 pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
2405 while( arg_parse( &pargs, opts) ) {
2406 if( pargs.r_opt == oDebug || pargs.r_opt == oDebugAll )
2408 else if (pargs.r_opt == oDebugIOLBF)
2409 es_setvbuf (es_stdout, NULL, _IOLBF, 0);
2410 else if( pargs.r_opt == oOptions ) {
2411 /* yes there is one, so we do not try the default one, but
2412 * read the option file when it is encountered at the commandline
2416 else if( pargs.r_opt == oNoOptions )
2418 default_config = 0; /* --no-options */
2419 opt.no_homedir_creation = 1;
2421 else if( pargs.r_opt == oHomedir )
2422 gnupg_set_homedir (pargs.r.ret_str);
2423 else if( pargs.r_opt == oNoPermissionWarn )
2425 else if (pargs.r_opt == oStrict )
2429 else if (pargs.r_opt == oNoStrict )
2435 #ifdef HAVE_DOSISH_SYSTEM
2436 if ( strchr (gnupg_homedir (), '\\') ) {
2437 char *d, *buf = xmalloc (strlen (gnupg_homedir ())+1);
2439 for (d=buf, s = gnupg_homedir (); *s; s++)
2441 *d++ = *s == '\\'? '/': *s;
2442 #ifdef HAVE_W32_SYSTEM
2443 if (s[1] && IsDBCSLeadByte (*s))
2448 gnupg_set_homedir (buf);
2452 /* Initialize the secure memory. */
2453 if (!gcry_control (GCRYCTL_INIT_SECMEM, SECMEM_BUFFER_SIZE, 0))
2455 #if defined(HAVE_GETUID) && defined(HAVE_GETEUID)
2456 /* There should be no way to get to this spot while still carrying
2457 setuid privs. Just in case, bomb out if we are. */
2458 if ( getuid () != geteuid () )
2463 /* Okay, we are now working under our real uid */
2465 /* malloc hooks go here ... */
2466 malloc_hooks.malloc = gcry_malloc;
2467 malloc_hooks.realloc = gcry_realloc;
2468 malloc_hooks.free = gcry_free;
2469 assuan_set_malloc_hooks (&malloc_hooks);
2470 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
2471 setup_libassuan_logging (&opt.debug, NULL);
2473 /* Set default options which require that malloc stuff is ready. */
2474 additional_weak_digest ("MD5");
2475 parse_auto_key_locate ("local,wkd");
2477 /* Try for a version specific config file first */
2478 default_configname = get_default_configname ();
2480 configname = xstrdup (default_configname);
2486 pargs.flags= ARGPARSE_FLAG_KEEP;
2488 /* By this point we have a homedir, and cannot change it. */
2489 check_permissions (gnupg_homedir (), 0);
2493 if(check_permissions(configname,1))
2495 /* If any options file is unsafe, then disable any external
2496 programs for keyserver calls or photo IDs. Since the
2497 external program to call is set in the options file, a
2498 unsafe options file can lead to an arbitrary program
2505 configfp = fopen( configname, "r" );
2506 if (configfp && is_secured_file (fileno (configfp)))
2510 gpg_err_set_errno (EPERM);
2513 if( default_config ) {
2515 log_info(_("Note: no default option file '%s'\n"),
2519 log_error(_("option file '%s': %s\n"),
2520 configname, strerror(errno) );
2523 xfree(configname); configname = NULL;
2525 if( parse_debug && configname )
2526 log_info(_("reading options from '%s'\n"), configname );
2530 while( optfile_parse( configfp, configname, &configlineno,
2533 switch( pargs.r_opt )
2536 case aListGcryptConfig:
2539 set_cmd (&cmd, pargs.r_opt);
2540 /* Do not register a keyring for these commands. */
2541 default_keyring = -1;
2554 #ifdef ENABLE_CARD_SUPPORT
2558 #endif /* ENABLE_CARD_SUPPORT*/
2563 case aExportSecretSub:
2575 case aUpdateTrustDB:
2577 case aListTrustPath:
2582 case aQuickLSignKey:
2590 case aQuickSetExpire:
2591 case aQuickSetPrimaryUid:
2592 case aExportOwnerTrust:
2593 case aImportOwnerTrust:
2594 case aRebuildKeydbCaches:
2595 set_cmd (&cmd, pargs.r_opt);
2601 case aDeleteSecretKeys:
2602 case aDeleteSecretAndPublicKeys:
2605 set_cmd (&cmd, pargs.r_opt);
2609 case aDetachedSign: detached_sig = 1; set_cmd( &cmd, aSign ); break;
2611 case aDecryptFiles: multifile=1; /* fall through */
2612 case aDecrypt: set_cmd( &cmd, aDecrypt); break;
2614 case aEncrFiles: multifile=1; /* fall through */
2615 case aEncr: set_cmd( &cmd, aEncr); break;
2617 case aVerifyFiles: multifile=1; /* fall through */
2618 case aVerify: set_cmd( &cmd, aVerify); break;
2621 set_cmd (&cmd, pargs.r_opt);
2626 set_cmd (&cmd, pargs.r_opt);
2629 case oArmor: opt.armor = 1; opt.no_armor=0; break;
2630 case oOutput: opt.outfile = pargs.r.ret_str; break;
2632 case oMaxOutput: opt.max_output = pargs.r.ret_ulong; break;
2634 case oInputSizeHint:
2635 opt.input_size_hint = string_to_u64 (pargs.r.ret_str);
2638 case oQuiet: opt.quiet = 1; break;
2639 case oNoTTY: tty_no_terminal(1); break;
2640 case oDryRun: opt.dry_run = 1; break;
2641 case oInteractive: opt.interactive = 1; break;
2644 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2645 opt.list_options|=LIST_SHOW_UNUSABLE_UIDS;
2646 opt.list_options|=LIST_SHOW_UNUSABLE_SUBKEYS;
2654 case oUseAgent: /* Dummy. */
2658 obsolete_option (configname, configlineno, "no-use-agent");
2661 obsolete_option (configname, configlineno, "gpg-agent-info");
2664 obsolete_scdaemon_option (configname, configlineno, "reader-port");
2667 obsolete_scdaemon_option (configname, configlineno, "ctapi-driver");
2670 obsolete_scdaemon_option (configname, configlineno, "pcsc-driver");
2673 obsolete_scdaemon_option (configname, configlineno, "disable-ccid");
2675 case oHonorHttpProxy:
2676 obsolete_option (configname, configlineno, "honor-http-proxy");
2679 case oAnswerYes: opt.answer_yes = 1; break;
2680 case oAnswerNo: opt.answer_no = 1; break;
2681 case oKeyring: append_to_strlist( &nrings, pargs.r.ret_str); break;
2682 case oPrimaryKeyring:
2683 sl = append_to_strlist (&nrings, pargs.r.ret_str);
2684 sl->flags = KEYDB_RESOURCE_FLAG_PRIMARY;
2687 deprecated_warning(configname,configlineno,"--show-keyring",
2688 "--list-options ","show-keyring");
2689 opt.list_options|=LIST_SHOW_KEYRING;
2693 if (parse_debug_flag (pargs.r.ret_str, &opt.debug, debug_flags))
2695 pargs.r_opt = ARGPARSE_INVALID_ARG;
2696 pargs.err = ARGPARSE_PRINT_ERROR;
2700 case oDebugAll: opt.debug = ~0; break;
2701 case oDebugLevel: debug_level = pargs.r.ret_str; break;
2703 case oDebugIOLBF: break; /* Already set in pre-parse step. */
2706 set_status_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
2709 set_status_fd ( open_info_file (pargs.r.ret_str, 1, 0) );
2712 set_attrib_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
2714 case oAttributeFile:
2715 set_attrib_fd ( open_info_file (pargs.r.ret_str, 1, 1) );
2718 log_set_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1));
2721 logfile = pargs.r.ret_str;
2724 case oWithFingerprint:
2725 opt.with_fingerprint = 1;
2728 case oWithSubkeyFingerprint:
2729 opt.with_subkey_fingerprint = 1;
2731 case oWithICAOSpelling:
2732 opt.with_icao_spelling = 1;
2740 opt.with_keygrip = 1;
2744 opt.with_secret = 1;
2748 opt.with_wkd_hash = 1;
2751 case oWithKeyOrigin:
2752 opt.with_key_origin = 1;
2755 case oSecretKeyring:
2756 /* Ignore this old option. */
2760 /* config files may not be nested (silently ignore them) */
2763 configname = xstrdup(pargs.r.ret_str);
2767 case oNoArmor: opt.no_armor=1; opt.armor=0; break;
2770 if (default_keyring > 0)
2771 default_keyring = 0;
2774 default_keyring = -1;
2777 case oNoGreeting: nogreeting = 1; break;
2780 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2784 gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
2786 case oEmitVersion: opt.emit_version++; break;
2787 case oNoEmitVersion: opt.emit_version=0; break;
2788 case oCompletesNeeded: opt.completes_needed = pargs.r.ret_int; break;
2789 case oMarginalsNeeded: opt.marginals_needed = pargs.r.ret_int; break;
2790 case oMaxCertDepth: opt.max_cert_depth = pargs.r.ret_int; break;
2792 #ifndef NO_TRUST_MODELS
2793 case oTrustDBName: trustdb_name = pargs.r.ret_str; break;
2795 #endif /*!NO_TRUST_MODELS*/
2797 sl = add_to_strlist (&opt.def_secret_key, pargs.r.ret_str);
2798 sl->flags = (pargs.r_opt << PK_LIST_SHIFT);
2800 sl->flags |= PK_LIST_CONFIG;
2803 if( *pargs.r.ret_str )
2805 xfree (opt.def_recipient);
2806 opt.def_recipient = make_username(pargs.r.ret_str);
2809 case oDefRecipientSelf:
2810 xfree(opt.def_recipient); opt.def_recipient = NULL;
2811 opt.def_recipient_self = 1;
2813 case oNoDefRecipient:
2814 xfree(opt.def_recipient); opt.def_recipient = NULL;
2815 opt.def_recipient_self = 0;
2817 case oNoOptions: opt.no_homedir_creation = 1; break; /* no-options */
2818 case oHomedir: break;
2819 case oNoBatch: opt.batch = 0; break;
2821 case oWithTofuInfo: opt.with_tofu_info = 1; break;
2823 case oWithKeyData: opt.with_key_data=1; /*FALLTHRU*/
2824 case oWithColons: opt.with_colons=':'; break;
2826 case oWithSigCheck: opt.check_sigs = 1; /*FALLTHRU*/
2827 case oWithSigList: opt.list_sigs = 1; break;
2829 case oSkipVerify: opt.skip_verify=1; break;
2831 case oSkipHiddenRecipients: opt.skip_hidden_recipients = 1; break;
2832 case oNoSkipHiddenRecipients: opt.skip_hidden_recipients = 0; break;
2834 case aListSecretKeys: set_cmd( &cmd, aListSecretKeys); break;
2836 #ifndef NO_TRUST_MODELS
2837 /* There are many programs (like mutt) that call gpg with
2838 --always-trust so keep this option around for a long
2840 case oAlwaysTrust: opt.trust_model=TM_ALWAYS; break;
2842 parse_trust_model(pargs.r.ret_str);
2844 #endif /*!NO_TRUST_MODELS*/
2845 case oTOFUDefaultPolicy:
2846 opt.tofu_default_policy = parse_tofu_policy (pargs.r.ret_str);
2849 obsolete_option (configname, configlineno, "tofu-db-format");
2852 case oForceOwnertrust:
2853 log_info(_("Note: %s is not for normal use!\n"),
2854 "--force-ownertrust");
2855 opt.force_ownertrust=string_to_trust_value(pargs.r.ret_str);
2856 if(opt.force_ownertrust==-1)
2858 log_error("invalid ownertrust '%s'\n",pargs.r.ret_str);
2859 opt.force_ownertrust=0;
2862 case oLoadExtension:
2863 /* Dummy so that gpg 1.4 conf files can work. Should
2864 eventually be removed. */
2869 int compliance = gnupg_parse_compliance_option
2871 compliance_options, DIM (compliance_options),
2875 set_compliance_option (compliance);
2886 set_compliance_option (pargs.r_opt);
2889 case oRFC2440Text: opt.rfc2440_text=1; break;
2890 case oNoRFC2440Text: opt.rfc2440_text=0; break;
2894 opt.set_filename = pargs.r.ret_str;
2896 opt.set_filename = native_to_utf8(pargs.r.ret_str);
2898 case oForYourEyesOnly: eyes_only = 1; break;
2899 case oNoForYourEyesOnly: eyes_only = 0; break;
2901 add_policy_url(pargs.r.ret_str,0);
2902 add_policy_url(pargs.r.ret_str,1);
2904 case oSigPolicyURL: add_policy_url(pargs.r.ret_str,0); break;
2905 case oCertPolicyURL: add_policy_url(pargs.r.ret_str,1); break;
2906 case oShowPolicyURL:
2907 deprecated_warning(configname,configlineno,"--show-policy-url",
2908 "--list-options ","show-policy-urls");
2909 deprecated_warning(configname,configlineno,"--show-policy-url",
2910 "--verify-options ","show-policy-urls");
2911 opt.list_options|=LIST_SHOW_POLICY_URLS;
2912 opt.verify_options|=VERIFY_SHOW_POLICY_URLS;
2914 case oNoShowPolicyURL:
2915 deprecated_warning(configname,configlineno,"--no-show-policy-url",
2916 "--list-options ","no-show-policy-urls");
2917 deprecated_warning(configname,configlineno,"--no-show-policy-url",
2918 "--verify-options ","no-show-policy-urls");
2919 opt.list_options&=~LIST_SHOW_POLICY_URLS;
2920 opt.verify_options&=~VERIFY_SHOW_POLICY_URLS;
2922 case oSigKeyserverURL: add_keyserver_url(pargs.r.ret_str,0); break;
2923 case oUseEmbeddedFilename:
2924 opt.flags.use_embedded_filename=1;
2926 case oNoUseEmbeddedFilename:
2927 opt.flags.use_embedded_filename=0;
2930 if(pargs.r.ret_str[0])
2931 append_to_strlist(&opt.comments,pargs.r.ret_str);
2933 case oDefaultComment:
2934 deprecated_warning(configname,configlineno,
2935 "--default-comment","--no-comments","");
2938 free_strlist(opt.comments);
2941 case oThrowKeyids: opt.throw_keyids = 1; break;
2942 case oNoThrowKeyids: opt.throw_keyids = 0; break;
2944 deprecated_warning(configname,configlineno,"--show-photos",
2945 "--list-options ","show-photos");
2946 deprecated_warning(configname,configlineno,"--show-photos",
2947 "--verify-options ","show-photos");
2948 opt.list_options|=LIST_SHOW_PHOTOS;
2949 opt.verify_options|=VERIFY_SHOW_PHOTOS;
2952 deprecated_warning(configname,configlineno,"--no-show-photos",
2953 "--list-options ","no-show-photos");
2954 deprecated_warning(configname,configlineno,"--no-show-photos",
2955 "--verify-options ","no-show-photos");
2956 opt.list_options&=~LIST_SHOW_PHOTOS;
2957 opt.verify_options&=~VERIFY_SHOW_PHOTOS;
2959 case oPhotoViewer: opt.photo_viewer = pargs.r.ret_str; break;
2961 case oForceMDC: opt.force_mdc = 1; break;
2962 case oNoForceMDC: opt.force_mdc = 0; break;
2963 case oDisableMDC: opt.disable_mdc = 1; break;
2964 case oNoDisableMDC: opt.disable_mdc = 0; break;
2966 case oDisableSignerUID: opt.flags.disable_signer_uid = 1; break;
2968 case oS2KMode: opt.s2k_mode = pargs.r.ret_int; break;
2969 case oS2KDigest: s2k_digest_string = xstrdup(pargs.r.ret_str); break;
2970 case oS2KCipher: s2k_cipher_string = xstrdup(pargs.r.ret_str); break;
2972 if (pargs.r.ret_int)
2973 opt.s2k_count = encode_s2k_iterations (pargs.r.ret_int);
2975 opt.s2k_count = 0; /* Auto-calibrate when needed. */
2979 case oHiddenRecipient:
2980 case oRecipientFile:
2981 case oHiddenRecipientFile:
2982 /* Store the recipient. Note that we also store the
2983 * option as private data in the flags. This is achieved
2984 * by shifting the option value to the left so to keep
2985 * enough space for the flags. */
2986 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2987 sl->flags = (pargs.r_opt << PK_LIST_SHIFT);
2989 sl->flags |= PK_LIST_CONFIG;
2990 if (pargs.r_opt == oHiddenRecipient
2991 || pargs.r_opt == oHiddenRecipientFile)
2992 sl->flags |= PK_LIST_HIDDEN;
2993 if (pargs.r_opt == oRecipientFile
2994 || pargs.r_opt == oHiddenRecipientFile)
2995 sl->flags |= PK_LIST_FROM_FILE;
2996 any_explicit_recipient = 1;
3000 case oHiddenEncryptTo:
3001 /* Store an additional recipient. */
3002 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
3003 sl->flags = ((pargs.r_opt << PK_LIST_SHIFT) | PK_LIST_ENCRYPT_TO);
3005 sl->flags |= PK_LIST_CONFIG;
3006 if (pargs.r_opt == oHiddenEncryptTo)
3007 sl->flags |= PK_LIST_HIDDEN;
3011 opt.no_encrypt_to = 1;
3013 case oEncryptToDefaultKey:
3014 opt.encrypt_to_default_key = configfp ? 2 : 1;
3018 add_to_strlist2 (&opt.secret_keys_to_try,
3019 pargs.r.ret_str, utf8_strings);
3022 case oMimemode: opt.mimemode = opt.textmode = 1; break;
3023 case oTextmodeShort: opt.textmode = 2; break;
3024 case oTextmode: opt.textmode=1; break;
3025 case oNoTextmode: opt.textmode=opt.mimemode=0; break;
3027 case oExpert: opt.expert = 1; break;
3028 case oNoExpert: opt.expert = 0; break;
3030 if(*pargs.r.ret_str!='\0')
3032 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
3033 log_error(_("'%s' is not a valid signature expiration\n"),
3036 opt.def_sig_expire=pargs.r.ret_str;
3039 case oAskSigExpire: opt.ask_sig_expire = 1; break;
3040 case oNoAskSigExpire: opt.ask_sig_expire = 0; break;
3041 case oDefCertExpire:
3042 if(*pargs.r.ret_str!='\0')
3044 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
3045 log_error(_("'%s' is not a valid signature expiration\n"),
3048 opt.def_cert_expire=pargs.r.ret_str;
3051 case oAskCertExpire: opt.ask_cert_expire = 1; break;
3052 case oNoAskCertExpire: opt.ask_cert_expire = 0; break;
3053 case oDefCertLevel: opt.def_cert_level=pargs.r.ret_int; break;
3054 case oMinCertLevel: opt.min_cert_level=pargs.r.ret_int; break;
3055 case oAskCertLevel: opt.ask_cert_level = 1; break;
3056 case oNoAskCertLevel: opt.ask_cert_level = 0; break;
3057 case oLocalUser: /* store the local users */
3058 sl = add_to_strlist2( &locusr, pargs.r.ret_str, utf8_strings );
3059 sl->flags = (pargs.r_opt << PK_LIST_SHIFT);
3061 sl->flags |= PK_LIST_CONFIG;
3065 char *mbox = mailbox_from_userid (pargs.r.ret_str);
3067 log_error (_("\"%s\" is not a proper mail address\n"),
3071 add_to_strlist (&opt.sender_list, mbox);
3077 /* this is the -z command line option */
3078 opt.compress_level = opt.bz2_compress_level = pargs.r.ret_int;
3080 case oCompressLevel: opt.compress_level = pargs.r.ret_int; break;
3081 case oBZ2CompressLevel: opt.bz2_compress_level = pargs.r.ret_int; break;
3082 case oBZ2DecompressLowmem: opt.bz2_decompress_lowmem=1; break;
3084 set_passphrase_from_string(pargs.r.ret_str);
3087 pwfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
3089 case oPassphraseFile:
3090 pwfd = open_info_file (pargs.r.ret_str, 0, 1);
3092 case oPassphraseRepeat:
3093 opt.passphrase_repeat = pargs.r.ret_int;
3097 opt.pinentry_mode = parse_pinentry_mode (pargs.r.ret_str);
3098 if (opt.pinentry_mode == -1)
3099 log_error (_("invalid pinentry mode '%s'\n"), pargs.r.ret_str);
3102 case oRequestOrigin:
3103 opt.request_origin = parse_request_origin (pargs.r.ret_str);
3104 if (opt.request_origin == -1)
3105 log_error (_("invalid request origin '%s'\n"), pargs.r.ret_str);
3109 opt.command_fd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
3110 if (! gnupg_fd_valid (opt.command_fd))
3111 log_error ("command-fd is invalid: %s\n", strerror (errno));
3114 opt.command_fd = open_info_file (pargs.r.ret_str, 0, 1);
3117 def_cipher_string = xstrdup(pargs.r.ret_str);
3120 def_digest_string = xstrdup(pargs.r.ret_str);
3123 /* If it is all digits, stick a Z in front of it for
3124 later. This is for backwards compatibility with
3125 versions that took the compress algorithm number. */
3127 char *pt=pargs.r.ret_str;
3130 if (!isascii (*pt) || !isdigit (*pt))
3138 compress_algo_string=xmalloc(strlen(pargs.r.ret_str)+2);
3139 strcpy(compress_algo_string,"Z");
3140 strcat(compress_algo_string,pargs.r.ret_str);
3143 compress_algo_string = xstrdup(pargs.r.ret_str);
3146 case oCertDigestAlgo:
3147 cert_digest_string = xstrdup(pargs.r.ret_str);
3151 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
3154 case oRequireSecmem: require_secmem=1; break;
3155 case oNoRequireSecmem: require_secmem=0; break;
3156 case oNoPermissionWarn: opt.no_perm_warn=1; break;
3157 case oNoMDCWarn: opt.no_mdc_warn=1; break;
3158 case oDisplayCharset:
3159 if( set_native_charset( pargs.r.ret_str ) )
3160 log_error(_("'%s' is not a valid character set\n"),
3163 case oNotDashEscaped: opt.not_dash_escaped = 1; break;
3164 case oEscapeFrom: opt.escape_from = 1; break;
3165 case oNoEscapeFrom: opt.escape_from = 0; break;
3166 case oLockOnce: opt.lock_once = 1; break;
3173 #else /* __riscos__ */
3174 riscos_not_implemented("lock-multiple");
3175 #endif /* __riscos__ */
3179 keyserver_spec_t keyserver;
3180 keyserver = parse_keyserver_uri (pargs.r.ret_str, 0);
3182 log_error (_("could not parse keyserver URL\n"));
3185 /* We only support a single keyserver. Later ones
3186 override earlier ones. (Since we parse the
3187 config file first and then the command line
3188 arguments, the command line takes
3191 free_keyserver_spec (opt.keyserver);
3192 opt.keyserver = keyserver;
3196 case oKeyServerOptions:
3197 if(!parse_keyserver_options(pargs.r.ret_str))
3200 log_error(_("%s:%d: invalid keyserver options\n"),
3201 configname,configlineno);
3203 log_error(_("invalid keyserver options\n"));
3206 case oImportOptions:
3207 if(!parse_import_options(pargs.r.ret_str,&opt.import_options,1))
3210 log_error(_("%s:%d: invalid import options\n"),
3211 configname,configlineno);
3213 log_error(_("invalid import options\n"));
3217 rc = parse_and_set_import_filter (pargs.r.ret_str);
3219 log_error (_("invalid filter option: %s\n"), gpg_strerror (rc));
3221 case oExportOptions:
3222 if(!parse_export_options(pargs.r.ret_str,&opt.export_options,1))
3225 log_error(_("%s:%d: invalid export options\n"),
3226 configname,configlineno);
3228 log_error(_("invalid export options\n"));
3232 rc = parse_and_set_export_filter (pargs.r.ret_str);
3234 log_error (_("invalid filter option: %s\n"), gpg_strerror (rc));
3237 if(!parse_list_options(pargs.r.ret_str))
3240 log_error(_("%s:%d: invalid list options\n"),
3241 configname,configlineno);
3243 log_error(_("invalid list options\n"));
3246 case oVerifyOptions:
3248 struct parse_options vopts[]=
3250 {"show-photos",VERIFY_SHOW_PHOTOS,NULL,
3251 N_("display photo IDs during signature verification")},
3252 {"show-policy-urls",VERIFY_SHOW_POLICY_URLS,NULL,
3253 N_("show policy URLs during signature verification")},
3254 {"show-notations",VERIFY_SHOW_NOTATIONS,NULL,
3255 N_("show all notations during signature verification")},
3256 {"show-std-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
3257 N_("show IETF standard notations during signature verification")},
3258 {"show-standard-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
3260 {"show-user-notations",VERIFY_SHOW_USER_NOTATIONS,NULL,
3261 N_("show user-supplied notations during signature verification")},
3262 {"show-keyserver-urls",VERIFY_SHOW_KEYSERVER_URLS,NULL,
3263 N_("show preferred keyserver URLs during signature verification")},
3264 {"show-uid-validity",VERIFY_SHOW_UID_VALIDITY,NULL,
3265 N_("show user ID validity during signature verification")},
3266 {"show-unusable-uids",VERIFY_SHOW_UNUSABLE_UIDS,NULL,
3267 N_("show revoked and expired user IDs in signature verification")},
3268 {"show-primary-uid-only",VERIFY_SHOW_PRIMARY_UID_ONLY,NULL,
3269 N_("show only the primary user ID in signature verification")},
3270 {"pka-lookups",VERIFY_PKA_LOOKUPS,NULL,
3271 N_("validate signatures with PKA data")},
3272 {"pka-trust-increase",VERIFY_PKA_TRUST_INCREASE,NULL,
3273 N_("elevate the trust of signatures with valid PKA data")},
3277 if(!parse_options(pargs.r.ret_str,&opt.verify_options,vopts,1))
3280 log_error(_("%s:%d: invalid verify options\n"),
3281 configname,configlineno);
3283 log_error(_("invalid verify options\n"));
3287 case oTempDir: opt.temp_dir=pargs.r.ret_str; break;
3289 if(set_exec_path(pargs.r.ret_str))
3290 log_error(_("unable to set exec-path to %s\n"),pargs.r.ret_str);
3292 opt.exec_path_set=1;
3295 add_notation_data( pargs.r.ret_str, 0 );
3296 add_notation_data( pargs.r.ret_str, 1 );
3298 case oSigNotation: add_notation_data( pargs.r.ret_str, 0 ); break;
3299 case oCertNotation: add_notation_data( pargs.r.ret_str, 1 ); break;
3301 deprecated_warning(configname,configlineno,"--show-notation",
3302 "--list-options ","show-notations");
3303 deprecated_warning(configname,configlineno,"--show-notation",
3304 "--verify-options ","show-notations");
3305 opt.list_options|=LIST_SHOW_NOTATIONS;
3306 opt.verify_options|=VERIFY_SHOW_NOTATIONS;
3308 case oNoShowNotation:
3309 deprecated_warning(configname,configlineno,"--no-show-notation",
3310 "--list-options ","no-show-notations");
3311 deprecated_warning(configname,configlineno,"--no-show-notation",
3312 "--verify-options ","no-show-notations");
3313 opt.list_options&=~LIST_SHOW_NOTATIONS;
3314 opt.verify_options&=~VERIFY_SHOW_NOTATIONS;
3316 case oUtf8Strings: utf8_strings = 1; break;
3317 case oNoUtf8Strings: utf8_strings = 0; break;
3318 case oDisableCipherAlgo:
3320 int algo = string_to_cipher_algo (pargs.r.ret_str);
3321 gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
3324 case oDisablePubkeyAlgo:
3326 int algo = gcry_pk_map_name (pargs.r.ret_str);
3327 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
3330 case oNoSigCache: opt.no_sig_cache = 1; break;
3331 case oAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid = 1; break;
3332 case oNoAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid=0; break;
3333 case oAllowFreeformUID: opt.allow_freeform_uid = 1; break;
3334 case oNoAllowFreeformUID: opt.allow_freeform_uid = 0; break;
3335 case oNoLiteral: opt.no_literal = 1; break;
3336 case oSetFilesize: opt.set_filesize = pargs.r.ret_ulong; break;
3337 case oFastListMode: opt.fast_list_mode = 1; break;
3338 case oFixedListMode: /* Dummy */ break;
3339 case oLegacyListMode: opt.legacy_list_mode = 1; break;
3340 case oPrintPKARecords: print_pka_records = 1; break;
3341 case oPrintDANERecords: print_dane_records = 1; break;
3342 case oListOnly: opt.list_only=1; break;
3343 case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
3344 case oIgnoreValidFrom: opt.ignore_valid_from = 1; break;
3345 case oIgnoreCrcError: opt.ignore_crc_error = 1; break;
3346 case oIgnoreMDCError: opt.ignore_mdc_error = 1; break;
3347 case oNoRandomSeedFile: use_random_seed = 0; break;
3349 case oAutoKeyRetrieve:
3350 opt.keyserver_options.options |= KEYSERVER_AUTO_KEY_RETRIEVE;
3352 case oNoAutoKeyRetrieve:
3353 opt.keyserver_options.options &= ~KEYSERVER_AUTO_KEY_RETRIEVE;
3356 case oShowSessionKey: opt.show_session_key = 1; break;
3357 case oOverrideSessionKey:
3358 opt.override_session_key = pargs.r.ret_str;
3360 case oOverrideSessionKeyFD:
3361 ovrseskeyfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
3364 deprecated_warning(configname,configlineno,"--merge-only",
3365 "--import-options ","merge-only");
3366 opt.import_options|=IMPORT_MERGE_ONLY;
3368 case oAllowSecretKeyImport: /* obsolete */ break;
3369 case oTryAllSecrets: opt.try_all_secrets = 1; break;
3370 case oTrustedKey: register_trusted_key( pargs.r.ret_str ); break;
3372 case oEnableSpecialFilenames:
3373 enable_special_filenames ();
3376 case oNoExpensiveTrustChecks: opt.no_expensive_trust_checks=1; break;
3377 case oAutoCheckTrustDB: opt.no_auto_check_trustdb=0; break;
3378 case oNoAutoCheckTrustDB: opt.no_auto_check_trustdb=1; break;
3379 case oPreservePermissions: opt.preserve_permissions=1; break;
3380 case oDefaultPreferenceList:
3381 opt.def_preference_list = pargs.r.ret_str;
3383 case oDefaultKeyserverURL:
3385 keyserver_spec_t keyserver;
3386 keyserver = parse_keyserver_uri (pargs.r.ret_str,1 );
3388 log_error (_("could not parse keyserver URL\n"));
3390 free_keyserver_spec (keyserver);
3392 opt.def_keyserver_url = pargs.r.ret_str;
3395 case oPersonalCipherPreferences:
3396 pers_cipher_list=pargs.r.ret_str;
3398 case oPersonalDigestPreferences:
3399 pers_digest_list=pargs.r.ret_str;
3401 case oPersonalCompressPreferences:
3402 pers_compress_list=pargs.r.ret_str;
3404 case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
3405 case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break;
3406 case oDisableDirmngr: opt.disable_dirmngr = 1; break;
3408 additional_weak_digest(pargs.r.ret_str);
3411 opt.unwrap_encryption = 1;
3413 case oOnlySignTextIDs:
3414 opt.only_sign_text_ids = 1;
3418 set_opt_session_env ("DISPLAY", pargs.r.ret_str);
3421 set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
3424 set_opt_session_env ("TERM", pargs.r.ret_str);
3427 set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
3430 case oLCctype: opt.lc_ctype = pargs.r.ret_str; break;
3431 case oLCmessages: opt.lc_messages = pargs.r.ret_str; break;
3433 case oGroup: add_group(pargs.r.ret_str); break;
3434 case oUnGroup: rm_group(pargs.r.ret_str); break;
3436 while(opt.grouplist)
3438 struct groupitem *iter=opt.grouplist;
3439 free_strlist(iter->values);
3440 opt.grouplist=opt.grouplist->next;
3450 case oMangleDosFilenames: opt.mangle_dos_filenames = 1; break;
3451 case oNoMangleDosFilenames: opt.mangle_dos_filenames = 0; break;
3452 case oEnableProgressFilter: opt.enable_progress_filter = 1; break;
3453 case oMultifile: multifile=1; break;
3455 if(ascii_strcasecmp(pargs.r.ret_str,"short")==0)
3456 opt.keyid_format=KF_SHORT;
3457 else if(ascii_strcasecmp(pargs.r.ret_str,"long")==0)
3458 opt.keyid_format=KF_LONG;
3459 else if(ascii_strcasecmp(pargs.r.ret_str,"0xshort")==0)
3460 opt.keyid_format=KF_0xSHORT;
3461 else if(ascii_strcasecmp(pargs.r.ret_str,"0xlong")==0)
3462 opt.keyid_format=KF_0xLONG;
3463 else if(ascii_strcasecmp(pargs.r.ret_str,"none")==0)
3464 opt.keyid_format = KF_NONE;
3466 log_error("unknown keyid-format '%s'\n",pargs.r.ret_str);
3469 case oExitOnStatusWriteError:
3470 opt.exit_on_status_write_error = 1;
3473 case oLimitCardInsertTries:
3474 opt.limit_card_insert_tries = pargs.r.ret_int;
3477 case oRequireCrossCert: opt.flags.require_cross_cert=1; break;
3478 case oNoRequireCrossCert: opt.flags.require_cross_cert=0; break;
3480 case oAutoKeyLocate:
3483 /* This is the first time --aito-key-locate is seen.
3484 * We need to reset the default akl. */
3488 if(!parse_auto_key_locate(pargs.r.ret_str))
3491 log_error(_("%s:%d: invalid auto-key-locate list\n"),
3492 configname,configlineno);
3494 log_error(_("invalid auto-key-locate list\n"));
3497 case oNoAutoKeyLocate:
3502 if(!parse_key_origin (pargs.r.ret_str))
3503 log_error (_("invalid argument for option \"%.50s\"\n"),
3507 case oEnableLargeRSA:
3508 #if SECMEM_BUFFER_SIZE >= 65536
3509 opt.flags.large_rsa=1;
3512 log_info("%s:%d: WARNING: gpg not built with large secure "
3513 "memory buffer. Ignoring enable-large-rsa\n",
3514 configname,configlineno);
3516 log_info("WARNING: gpg not built with large secure "
3517 "memory buffer. Ignoring --enable-large-rsa\n");
3518 #endif /* SECMEM_BUFFER_SIZE >= 65536 */
3520 case oDisableLargeRSA: opt.flags.large_rsa=0;
3523 case oEnableDSA2: opt.flags.dsa2=1; break;
3524 case oDisableDSA2: opt.flags.dsa2=0; break;
3526 case oAllowMultisigVerification:
3527 case oAllowMultipleMessages:
3528 opt.flags.allow_multiple_messages=1;
3531 case oNoAllowMultipleMessages:
3532 opt.flags.allow_multiple_messages=0;
3535 case oAllowWeakDigestAlgos:
3536 opt.flags.allow_weak_digest_algos = 1;
3539 case oFakedSystemTime:
3541 size_t len = strlen (pargs.r.ret_str);
3545 if (len > 0 && pargs.r.ret_str[len-1] == '!')
3548 pargs.r.ret_str[len-1] = '\0';
3551 faked_time = isotime2epoch (pargs.r.ret_str);
3552 if (faked_time == (time_t)(-1))
3553 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
3554 gnupg_set_time (faked_time, freeze);
3558 case oNoAutostart: opt.autostart = 0; break;
3560 case oDefaultNewKeyAlgo:
3561 opt.def_new_key_algo = pargs.r.ret_str;
3568 pargs.err = ARGPARSE_PRINT_WARNING;
3571 pargs.err = ARGPARSE_PRINT_ERROR;
3572 /* The argparse fucntion calls a plain exit and thus
3573 * we need to print a status here. */
3574 write_status_failure ("option-parser",
3575 gpg_error(GPG_ERR_GENERAL));
3585 /* Remember the first config file name. */
3586 if (!save_configname)
3587 save_configname = configname;
3593 xfree(configname); configname = NULL;
3594 if (log_get_errorcount (0))
3596 write_status_failure ("option-parser", gpg_error(GPG_ERR_GENERAL));
3600 /* The command --gpgconf-list is pretty simple and may be called
3601 directly after the option parsing. */
3602 if (cmd == aGPGConfList)
3604 gpgconf_list (save_configname ? save_configname : default_configname);
3607 xfree (save_configname);
3608 xfree (default_configname);
3610 if (print_dane_records)
3611 log_error ("invalid option \"%s\"; use \"%s\" instead\n",
3612 "--print-dane-records",
3613 "--export-options export-dane");
3614 if (print_pka_records)
3615 log_error ("invalid option \"%s\"; use \"%s\" instead\n",
3616 "--print-pks-records",
3617 "--export-options export-pka");
3618 if (log_get_errorcount (0))
3620 write_status_failure ("option-checking", gpg_error(GPG_ERR_GENERAL));
3630 es_fprintf (es_stderr, "%s %s; %s\n",
3631 strusage(11), strusage(13), strusage(14) );
3632 es_fprintf (es_stderr, "%s\n", strusage(15) );
3634 #ifdef IS_DEVELOPMENT_VERSION
3639 if((s=strusage(25)))
3641 if((s=strusage(26)))
3643 if((s=strusage(27)))
3648 /* FIXME: We should use logging to a file only in server mode;
3649 however we have not yet implemetyed that. Thus we try to get
3650 away with --batch as indication for logging to file
3652 if (logfile && opt.batch)
3654 log_set_file (logfile);
3655 log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
3658 if (opt.verbose > 2)
3659 log_info ("using character set '%s'\n", get_native_charset ());
3661 if( may_coredump && !opt.quiet )
3662 log_info(_("WARNING: program may create a core file!\n"));
3664 if (opt.flags.rfc4880bis)
3665 log_info ("WARNING: using experimental features from RFC4880bis!\n");
3668 opt.mimemode = 0; /* This will use text mode instead. */
3672 if (opt.set_filename)
3673 log_info(_("WARNING: %s overrides %s\n"),
3674 "--for-your-eyes-only","--set-filename");
3676 opt.set_filename="_CONSOLE";
3679 if (opt.no_literal) {
3680 log_info(_("Note: %s is not for normal use!\n"), "--no-literal");
3682 log_error(_("%s not allowed with %s!\n"),
3683 "--textmode", "--no-literal" );
3684 if (opt.set_filename)
3685 log_error(_("%s makes no sense with %s!\n"),
3686 eyes_only?"--for-your-eyes-only":"--set-filename",
3691 if (opt.set_filesize)
3692 log_info(_("Note: %s is not for normal use!\n"), "--set-filesize");
3696 if (gnupg_faked_time_p ())
3698 gnupg_isotime_t tbuf;
3700 log_info (_("WARNING: running with faked system time: "));
3701 gnupg_get_isotime (tbuf);
3702 dump_isotime (tbuf);
3706 /* Print a warning if an argument looks like an option. */
3707 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
3711 for (i=0; i < argc; i++)
3712 if (argv[i][0] == '-' && argv[i][1] == '-')
3713 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
3717 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
3719 if(require_secmem && !got_secmem)
3721 log_info(_("will not run with insecure memory due to %s\n"),
3722 "--require-secmem");
3723 write_status_failure ("option-checking", gpg_error(GPG_ERR_GENERAL));
3727 set_debug (debug_level);
3729 log_clock ("start");
3731 /* Do these after the switch(), so they can override settings. */
3734 /* That does not anymore work because we have no more support
3735 for v3 signatures. */
3738 opt.ask_sig_expire=0;
3742 /* That does not anymore work because we have no more support
3743 for v3 signatures. */
3745 opt.ask_sig_expire=0;
3753 if( def_cipher_string ) {
3754 opt.def_cipher_algo = string_to_cipher_algo (def_cipher_string);
3755 xfree(def_cipher_string); def_cipher_string = NULL;
3756 if ( openpgp_cipher_test_algo (opt.def_cipher_algo) )
3757 log_error(_("selected cipher algorithm is invalid\n"));
3759 if( def_digest_string ) {
3760 opt.def_digest_algo = string_to_digest_algo (def_digest_string);
3761 xfree(def_digest_string); def_digest_string = NULL;
3762 if ( openpgp_md_test_algo (opt.def_digest_algo) )
3763 log_error(_("selected digest algorithm is invalid\n"));
3765 if( compress_algo_string ) {
3766 opt.compress_algo = string_to_compress_algo(compress_algo_string);
3767 xfree(compress_algo_string); compress_algo_string = NULL;
3768 if( check_compress_algo(opt.compress_algo) )
3769 log_error(_("selected compression algorithm is invalid\n"));
3771 if( cert_digest_string ) {
3772 opt.cert_digest_algo = string_to_digest_algo (cert_digest_string);
3773 xfree(cert_digest_string); cert_digest_string = NULL;
3774 if (openpgp_md_test_algo(opt.cert_digest_algo))
3775 log_error(_("selected certification digest algorithm is invalid\n"));
3777 if( s2k_cipher_string ) {
3778 opt.s2k_cipher_algo = string_to_cipher_algo (s2k_cipher_string);
3779 xfree(s2k_cipher_string); s2k_cipher_string = NULL;
3780 if (openpgp_cipher_test_algo (opt.s2k_cipher_algo))
3781 log_error(_("selected cipher algorithm is invalid\n"));
3783 if( s2k_digest_string ) {
3784 opt.s2k_digest_algo = string_to_digest_algo (s2k_digest_string);
3785 xfree(s2k_digest_string); s2k_digest_string = NULL;
3786 if (openpgp_md_test_algo(opt.s2k_digest_algo))
3787 log_error(_("selected digest algorithm is invalid\n"));
3789 if( opt.completes_needed < 1 )
3790 log_error(_("completes-needed must be greater than 0\n"));
3791 if( opt.marginals_needed < 2 )
3792 log_error(_("marginals-needed must be greater than 1\n"));
3793 if( opt.max_cert_depth < 1 || opt.max_cert_depth > 255 )
3794 log_error(_("max-cert-depth must be in the range from 1 to 255\n"));
3795 if(opt.def_cert_level<0 || opt.def_cert_level>3)
3796 log_error(_("invalid default-cert-level; must be 0, 1, 2, or 3\n"));
3797 if( opt.min_cert_level < 1 || opt.min_cert_level > 3 )
3798 log_error(_("invalid min-cert-level; must be 1, 2, or 3\n"));
3799 switch( opt.s2k_mode ) {
3801 log_info(_("Note: simple S2K mode (0) is strongly discouraged\n"));
3803 case 1: case 3: break;
3805 log_error(_("invalid S2K mode; must be 0, 1 or 3\n"));
3808 /* This isn't actually needed, but does serve to error out if the
3809 string is invalid. */
3810 if(opt.def_preference_list &&
3811 keygen_set_std_prefs(opt.def_preference_list,0))
3812 log_error(_("invalid default preferences\n"));
3814 if(pers_cipher_list &&
3815 keygen_set_std_prefs(pers_cipher_list,PREFTYPE_SYM))
3816 log_error(_("invalid personal cipher preferences\n"));
3818 if(pers_digest_list &&
3819 keygen_set_std_prefs(pers_digest_list,PREFTYPE_HASH))
3820 log_error(_("invalid personal digest preferences\n"));
3822 if(pers_compress_list &&
3823 keygen_set_std_prefs(pers_compress_list,PREFTYPE_ZIP))
3824 log_error(_("invalid personal compress preferences\n"));
3826 /* We don't support all possible commands with multifile yet */
3837 cmdname="--sign --encrypt";
3840 cmdname="--clear-sign";
3843 cmdname="--detach-sign";
3846 cmdname="--symmetric";
3849 cmdname="--symmetric --encrypt";
3860 log_error(_("%s does not yet work with %s\n"),cmdname,"--multifile");
3863 if( log_get_errorcount(0) )
3865 write_status_failure ("option-postprocessing",
3866 gpg_error(GPG_ERR_GENERAL));
3870 if(opt.compress_level==0)
3871 opt.compress_algo=COMPRESS_ALGO_NONE;
3873 /* Check our chosen algorithms against the list of legal
3878 const char *badalg=NULL;
3879 preftype_t badtype=PREFTYPE_NONE;
3881 if(opt.def_cipher_algo
3882 && !algo_available(PREFTYPE_SYM,opt.def_cipher_algo,NULL))
3884 badalg = openpgp_cipher_algo_name (opt.def_cipher_algo);
3885 badtype = PREFTYPE_SYM;
3887 else if(opt.def_digest_algo
3888 && !algo_available(PREFTYPE_HASH,opt.def_digest_algo,NULL))
3890 badalg = gcry_md_algo_name (opt.def_digest_algo);
3891 badtype = PREFTYPE_HASH;
3893 else if(opt.cert_digest_algo
3894 && !algo_available(PREFTYPE_HASH,opt.cert_digest_algo,NULL))
3896 badalg = gcry_md_algo_name (opt.cert_digest_algo);
3897 badtype = PREFTYPE_HASH;
3899 else if(opt.compress_algo!=-1
3900 && !algo_available(PREFTYPE_ZIP,opt.compress_algo,NULL))
3902 badalg = compress_algo_to_string(opt.compress_algo);
3903 badtype = PREFTYPE_ZIP;
3911 log_info (_("cipher algorithm '%s'"
3912 " may not be used in %s mode\n"),
3914 gnupg_compliance_option_string (opt.compliance));
3917 log_info (_("digest algorithm '%s'"
3918 " may not be used in %s mode\n"),
3920 gnupg_compliance_option_string (opt.compliance));
3923 log_info (_("compression algorithm '%s'"
3924 " may not be used in %s mode\n"),
3926 gnupg_compliance_option_string (opt.compliance));
3932 compliance_failure();
3936 /* Check our chosen algorithms against the list of allowed
3937 * algorithms in the current compliance mode, and fail hard if it
3938 * is not. This is us being nice to the user informing her early
3939 * that the chosen algorithms are not available. We also check
3940 * and enforce this right before the actual operation. */
3941 if (opt.def_cipher_algo
3942 && ! gnupg_cipher_is_allowed (opt.compliance,
3948 || cmd == aSignEncrSym,
3949 opt.def_cipher_algo,
3950 GCRY_CIPHER_MODE_NONE))
3951 log_error (_("cipher algorithm '%s' may not be used in %s mode\n"),
3952 openpgp_cipher_algo_name (opt.def_cipher_algo),
3953 gnupg_compliance_option_string (opt.compliance));
3955 if (opt.def_digest_algo
3956 && ! gnupg_digest_is_allowed (opt.compliance,
3959 || cmd == aSignEncrSym
3961 || cmd == aClearsign,
3962 opt.def_digest_algo))
3963 log_error (_("digest algorithm '%s' may not be used in %s mode\n"),
3964 gcry_md_algo_name (opt.def_digest_algo),
3965 gnupg_compliance_option_string (opt.compliance));
3968 if (log_get_errorcount (0))
3970 write_status_failure ("option-checking", gpg_error(GPG_ERR_GENERAL));
3974 /* Set the random seed file. */
3975 if( use_random_seed ) {
3976 char *p = make_filename (gnupg_homedir (), "random_seed", NULL );
3977 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
3978 if (!access (p, F_OK))
3979 register_secured_file (p);
3983 /* If there is no command but the --fingerprint is given, default
3984 to the --list-keys command. */
3985 if (!cmd && fpr_maybe_cmd)
3987 set_cmd (&cmd, aListKeys);
3991 if( opt.verbose > 1 )
3992 set_packet_list_mode(1);
3994 /* Add the keyrings, but not for some special commands. We always
3995 * need to add the keyrings if we are running under SELinux, this
3996 * is so that the rings are added to the list of secured files.
3997 * We do not add any keyring if --no-keyring has been used. */
3998 if (default_keyring >= 0
3999 && (ALWAYS_ADD_KEYRINGS
4000 || (cmd != aDeArmor && cmd != aEnArmor && cmd != aGPGConfTest)))
4002 if (!nrings || default_keyring > 0) /* Add default ring. */
4003 keydb_add_resource ("pubring" EXTSEP_S GPGEXT_GPG,
4004 KEYDB_RESOURCE_FLAG_DEFAULT);
4005 for (sl = nrings; sl; sl = sl->next )
4006 keydb_add_resource (sl->d, sl->flags);
4008 FREE_STRLIST(nrings);
4010 if (opt.pinentry_mode == PINENTRY_MODE_LOOPBACK)
4011 /* In loopback mode, never ask for the password multiple
4014 opt.passphrase_repeat = 0;
4017 if (cmd == aGPGConfTest)
4021 if (pwfd != -1) /* Read the passphrase now. */
4022 read_passphrase_from_fd (pwfd);
4024 if (ovrseskeyfd != -1 ) /* Read the sessionkey now. */
4025 read_sessionkey_from_fd (ovrseskeyfd);
4027 fname = argc? *argv : NULL;
4029 if(fname && utf8_strings)
4030 opt.flags.utf8_filename=1;
4032 ctrl = xcalloc (1, sizeof *ctrl);
4033 gpg_init_default_ctrl (ctrl);
4035 #ifndef NO_TRUST_MODELS
4045 case aListGcryptConfig:
4048 case aExportOwnerTrust:
4049 rc = setup_trustdb (0, trustdb_name);
4052 rc = setup_trustdb (argc? 1:0, trustdb_name);
4057 rc = setup_trustdb (1, trustdb_name);
4060 /* If we are using TM_ALWAYS, we do not need to create the
4062 rc = setup_trustdb (opt.trust_model != TM_ALWAYS, trustdb_name);
4066 log_error (_("failed to initialize the TrustDB: %s\n"),
4068 #endif /*!NO_TRUST_MODELS*/
4077 if (!opt.quiet && any_explicit_recipient)
4078 log_info (_("WARNING: recipients (-r) given "
4079 "without using public key encryption\n"));
4086 /* Check for certain command whether we need to migrate a
4087 secring.gpg to the gpg-agent. */
4090 case aListSecretKeys:
4101 case aDeleteSecretKeys:
4102 case aDeleteSecretAndPublicKeys:
4107 case aQuickSetPrimaryUid:
4112 case aExportSecretSub:
4117 migrate_secring (ctrl);
4120 if (opt.with_secret)
4121 migrate_secring (ctrl);
4127 /* The command dispatcher. */
4134 case aStore: /* only store the file */
4136 wrong_args("--store [filename]");
4137 if( (rc = encrypt_store(fname)) )
4139 write_status_failure ("store", rc);
4140 log_error ("storing '%s' failed: %s\n",
4141 print_fname_stdin(fname),gpg_strerror (rc) );
4144 case aSym: /* encrypt the given file only with the symmetric cipher */
4146 wrong_args("--symmetric [filename]");
4147 if( (rc = encrypt_symmetric(fname)) )
4149 write_status_failure ("symencrypt", rc);
4150 log_error (_("symmetric encryption of '%s' failed: %s\n"),
4151 print_fname_stdin(fname),gpg_strerror (rc) );
4155 case aEncr: /* encrypt the given file */
4157 encrypt_crypt_files (ctrl, argc, argv, remusr);
4161 wrong_args("--encrypt [filename]");
4162 if( (rc = encrypt_crypt (ctrl, -1, fname, remusr, 0, NULL, -1)) )
4164 write_status_failure ("encrypt", rc);
4165 log_error("%s: encryption failed: %s\n",
4166 print_fname_stdin(fname), gpg_strerror (rc) );
4172 /* This works with PGP 8 in the sense that it acts just like a
4173 symmetric message. It doesn't work at all with 2 or 6. It
4174 might work with 7, but alas, I don't have a copy to test
4177 wrong_args("--symmetric --encrypt [filename]");
4178 else if(opt.s2k_mode==0)
4179 log_error(_("you cannot use --symmetric --encrypt"
4180 " with --s2k-mode 0\n"));
4181 else if(PGP6 || PGP7)
4182 log_error(_("you cannot use --symmetric --encrypt"
4184 gnupg_compliance_option_string (opt.compliance));
4187 if( (rc = encrypt_crypt (ctrl, -1, fname, remusr, 1, NULL, -1)) )
4189 write_status_failure ("encrypt", rc);
4190 log_error ("%s: encryption failed: %s\n",
4191 print_fname_stdin(fname), gpg_strerror (rc) );
4196 case aSign: /* sign the given file */
4198 if( detached_sig ) { /* sign all files */
4199 for( ; argc; argc--, argv++ )
4200 add_to_strlist( &sl, *argv );
4204 wrong_args("--sign [filename]");
4206 sl = xmalloc_clear( sizeof *sl + strlen(fname));
4207 strcpy(sl->d, fname);
4210 if ((rc = sign_file (ctrl, sl, detached_sig, locusr, 0, NULL, NULL)))
4212 write_status_failure ("sign", rc);
4213 log_error ("signing failed: %s\n", gpg_strerror (rc) );
4218 case aSignEncr: /* sign and encrypt the given file */
4220 wrong_args("--sign --encrypt [filename]");
4222 sl = xmalloc_clear( sizeof *sl + strlen(fname));
4223 strcpy(sl->d, fname);
4227 if ((rc = sign_file (ctrl, sl, detached_sig, locusr, 1, remusr, NULL)))
4229 write_status_failure ("sign-encrypt", rc);
4230 log_error("%s: sign+encrypt failed: %s\n",
4231 print_fname_stdin(fname), gpg_strerror (rc) );
4236 case aSignEncrSym: /* sign and encrypt the given file */
4238 wrong_args("--symmetric --sign --encrypt [filename]");
4239 else if(opt.s2k_mode==0)
4240 log_error(_("you cannot use --symmetric --sign --encrypt"
4241 " with --s2k-mode 0\n"));
4242 else if(PGP6 || PGP7)
4243 log_error(_("you cannot use --symmetric --sign --encrypt"
4245 gnupg_compliance_option_string (opt.compliance));
4250 sl = xmalloc_clear( sizeof *sl + strlen(fname));
4251 strcpy(sl->d, fname);
4255 if ((rc = sign_file (ctrl, sl, detached_sig, locusr,
4258 write_status_failure ("sign-encrypt", rc);
4259 log_error("%s: symmetric+sign+encrypt failed: %s\n",
4260 print_fname_stdin(fname), gpg_strerror (rc) );
4266 case aSignSym: /* sign and conventionally encrypt the given file */
4268 wrong_args("--sign --symmetric [filename]");
4269 rc = sign_symencrypt_file (ctrl, fname, locusr);
4272 write_status_failure ("sign-symencrypt", rc);
4273 log_error("%s: sign+symmetric failed: %s\n",
4274 print_fname_stdin(fname), gpg_strerror (rc) );
4278 case aClearsign: /* make a clearsig */
4280 wrong_args("--clear-sign [filename]");
4281 if( (rc = clearsign_file (ctrl, fname, locusr, NULL)) )
4283 write_status_failure ("sign", rc);
4284 log_error("%s: clear-sign failed: %s\n",
4285 print_fname_stdin(fname), gpg_strerror (rc) );
4292 if ((rc = verify_files (ctrl, argc, argv)))
4293 log_error("verify files failed: %s\n", gpg_strerror (rc) );
4297 if ((rc = verify_signatures (ctrl, argc, argv)))
4298 log_error("verify signatures failed: %s\n", gpg_strerror (rc) );
4301 write_status_failure ("verify", rc);
4306 decrypt_messages (ctrl, argc, argv);
4310 wrong_args("--decrypt [filename]");
4311 if( (rc = decrypt_message (ctrl, fname) ))
4313 write_status_failure ("decrypt", rc);
4314 log_error("decrypt_message failed: %s\n", gpg_strerror (rc) );
4320 case aQuickLSignKey:
4325 wrong_args ("--quick-[l]sign-key fingerprint [userids]");
4326 fpr = *argv++; argc--;
4328 for( ; argc; argc--, argv++)
4329 append_to_strlist2 (&sl, *argv, utf8_strings);
4330 keyedit_quick_sign (ctrl, fpr, sl, locusr, (cmd == aQuickLSignKey));
4337 wrong_args("--sign-key user-id");
4341 wrong_args("--lsign-key user-id");
4347 append_to_strlist(&sl,"sign");
4348 else if(cmd==aLSignKey)
4349 append_to_strlist(&sl,"lsign");
4353 append_to_strlist( &sl, "save" );
4354 username = make_username( fname );
4355 keyedit_menu (ctrl, username, locusr, sl, 0, 0 );
4360 case aEditKey: /* Edit a key signature */
4362 wrong_args("--edit-key user-id [commands]");
4363 username = make_username( fname );
4366 for( argc--, argv++ ; argc; argc--, argv++ )
4367 append_to_strlist( &sl, *argv );
4368 keyedit_menu (ctrl, username, locusr, sl, 0, 1 );
4372 keyedit_menu (ctrl, username, locusr, NULL, 0, 1 );
4378 wrong_args("--change-passphrase <user-id>");
4381 username = make_username (fname);
4382 keyedit_passwd (ctrl, username);
4388 case aDeleteSecretKeys:
4389 case aDeleteSecretAndPublicKeys:
4391 /* I'm adding these in reverse order as add_to_strlist2
4392 reverses them again, and it's easier to understand in the
4394 for( ; argc; argc-- )
4395 add_to_strlist2( &sl, argv[argc-1], utf8_strings );
4396 delete_keys (ctrl, sl,
4397 cmd==aDeleteSecretKeys, cmd==aDeleteSecretAndPublicKeys);
4402 opt.check_sigs = 1; /* fall through */
4404 opt.list_sigs = 1; /* fall through */
4407 for( ; argc; argc--, argv++ )
4408 add_to_strlist2( &sl, *argv, utf8_strings );
4409 public_key_list (ctrl, sl, 0);
4412 case aListSecretKeys:
4414 for( ; argc; argc--, argv++ )
4415 add_to_strlist2( &sl, *argv, utf8_strings );
4416 secret_key_list (ctrl, sl);
4421 for (; argc; argc--, argv++)
4422 add_to_strlist2( &sl, *argv, utf8_strings );
4423 public_key_list (ctrl, sl, 1);
4429 const char *x_algo, *x_usage, *x_expire;
4431 if (argc < 1 || argc > 4)
4432 wrong_args("--quick-generate-key USER-ID [ALGO [USAGE [EXPIRE]]]");
4433 username = make_username (fname);
4440 x_algo = *argv++; argc--;
4443 x_usage = *argv++; argc--;
4446 x_expire = *argv++; argc--;
4450 quick_generate_keypair (ctrl, username, x_algo, x_usage, x_expire);
4455 case aKeygen: /* generate a key */
4458 wrong_args("--generate-key [parameterfile]");
4459 generate_keypair (ctrl, 0, argc? *argv : NULL, NULL, 0);
4462 if (opt.command_fd != -1 && argc)
4465 wrong_args("--generate-key [parameterfile]");
4468 generate_keypair (ctrl, 0, argc? *argv : NULL, NULL, 0);
4471 wrong_args ("--generate-key");
4473 generate_keypair (ctrl, 0, NULL, NULL, 0);
4477 case aFullKeygen: /* Generate a key with all options. */
4481 wrong_args ("--full-generate-key [parameterfile]");
4482 generate_keypair (ctrl, 1, argc? *argv : NULL, NULL, 0);
4487 wrong_args("--full-generate-key");
4488 generate_keypair (ctrl, 1, NULL, NULL, 0);
4494 const char *uid, *newuid;
4497 wrong_args ("--quick-add-uid USER-ID NEW-USER-ID");
4498 uid = *argv++; argc--;
4499 newuid = *argv++; argc--;
4500 keyedit_quick_adduid (ctrl, uid, newuid);
4506 const char *x_fpr, *x_algo, *x_usage, *x_expire;
4508 if (argc < 1 || argc > 4)
4509 wrong_args ("--quick-add-key FINGERPRINT [ALGO [USAGE [EXPIRE]]]");
4510 x_fpr = *argv++; argc--;
4516 x_algo = *argv++; argc--;
4519 x_usage = *argv++; argc--;
4522 x_expire = *argv++; argc--;
4526 keyedit_quick_addkey (ctrl, x_fpr, x_algo, x_usage, x_expire);
4532 const char *uid, *uidtorev;
4535 wrong_args ("--quick-revoke-uid USER-ID USER-ID-TO-REVOKE");
4536 uid = *argv++; argc--;
4537 uidtorev = *argv++; argc--;
4538 keyedit_quick_revuid (ctrl, uid, uidtorev);
4542 case aQuickSetExpire:
4544 const char *x_fpr, *x_expire;
4547 wrong_args ("--quick-set-exipre FINGERPRINT EXPIRE [SUBKEY-FPRS]");
4548 x_fpr = *argv++; argc--;
4549 x_expire = *argv++; argc--;
4550 keyedit_quick_set_expire (ctrl, x_fpr, x_expire, argv);
4554 case aQuickSetPrimaryUid:
4556 const char *uid, *primaryuid;
4559 wrong_args ("--quick-set-primary-uid USER-ID PRIMARY-USER-ID");
4560 uid = *argv++; argc--;
4561 primaryuid = *argv++; argc--;
4562 keyedit_quick_set_primary (ctrl, uid, primaryuid);
4567 opt.import_options |= IMPORT_FAST; /* fall through */
4569 import_keys (ctrl, argc? argv:NULL, argc, NULL,
4570 opt.import_options, opt.key_origin, opt.key_origin_url);
4573 /* TODO: There are a number of command that use this same
4574 "make strlist, call function, report error, free strlist"
4575 pattern. Join them together here and avoid all that
4582 for( ; argc; argc--, argv++ )
4583 append_to_strlist2( &sl, *argv, utf8_strings );
4584 if( cmd == aSendKeys )
4585 rc = keyserver_export (ctrl, sl );
4586 else if( cmd == aRecvKeys )
4587 rc = keyserver_import (ctrl, sl );
4590 export_stats_t stats = export_new_stats ();
4591 rc = export_pubkeys (ctrl, sl, opt.export_options, stats);
4592 export_print_stats (stats);
4593 export_release_stats (stats);
4599 write_status_failure ("send-keys", rc);
4600 log_error(_("keyserver send failed: %s\n"),gpg_strerror (rc));
4602 else if(cmd==aRecvKeys)
4604 write_status_failure ("recv-keys", rc);
4605 log_error (_("keyserver receive failed: %s\n"),
4610 write_status_failure ("export", rc);
4611 log_error (_("key export failed: %s\n"), gpg_strerror (rc));
4619 wrong_args ("--export-ssh-key <user-id>");
4620 rc = export_ssh_key (ctrl, argv[0]);
4623 write_status_failure ("export-ssh-key", rc);
4624 log_error (_("export as ssh key failed: %s\n"), gpg_strerror (rc));
4630 for (; argc; argc--, argv++)
4631 append_to_strlist2 (&sl, *argv, utf8_strings);
4632 rc = keyserver_search (ctrl, sl);
4635 write_status_failure ("search-keys", rc);
4636 log_error (_("keyserver search failed: %s\n"), gpg_strerror (rc));
4643 for( ; argc; argc--, argv++ )
4644 append_to_strlist2( &sl, *argv, utf8_strings );
4645 rc = keyserver_refresh (ctrl, sl);
4648 write_status_failure ("refresh-keys", rc);
4649 log_error (_("keyserver refresh failed: %s\n"),gpg_strerror (rc));
4656 for( ; argc; argc--, argv++ )
4657 append_to_strlist2( &sl, *argv, utf8_strings );
4658 rc = keyserver_fetch (ctrl, sl, opt.key_origin);
4661 write_status_failure ("fetch-keys", rc);
4662 log_error ("key fetch failed: %s\n",gpg_strerror (rc));
4669 for( ; argc; argc--, argv++ )
4670 add_to_strlist2( &sl, *argv, utf8_strings );
4672 export_stats_t stats = export_new_stats ();
4673 export_seckeys (ctrl, sl, opt.export_options, stats);
4674 export_print_stats (stats);
4675 export_release_stats (stats);
4680 case aExportSecretSub:
4682 for( ; argc; argc--, argv++ )
4683 add_to_strlist2( &sl, *argv, utf8_strings );
4685 export_stats_t stats = export_new_stats ();
4686 export_secsubkeys (ctrl, sl, opt.export_options, stats);
4687 export_print_stats (stats);
4688 export_release_stats (stats);
4695 wrong_args("--generate-revocation user-id");
4696 username = make_username(*argv);
4697 gen_revoke (ctrl, username );
4703 wrong_args ("--generate-designated-revocation user-id");
4704 username = make_username (*argv);
4705 gen_desig_revoke (ctrl, username, locusr);
4711 wrong_args("--dearmor [file]");
4712 rc = dearmor_file( argc? *argv: NULL );
4715 write_status_failure ("dearmor", rc);
4716 log_error (_("dearmoring failed: %s\n"), gpg_strerror (rc));
4722 wrong_args("--enarmor [file]");
4723 rc = enarmor_file( argc? *argv: NULL );
4726 write_status_failure ("enarmor", rc);
4727 log_error (_("enarmoring failed: %s\n"), gpg_strerror (rc));
4734 { int mode = argc < 2 ? 0 : atoi(*argv);
4736 if( mode == 1 && argc == 2 ) {
4737 mpi_print (es_stdout,
4738 generate_public_prime( atoi(argv[1]) ), 1);
4740 else if( mode == 2 && argc == 3 ) {
4741 mpi_print (es_stdout, generate_elg_prime(
4743 atoi(argv[2]), NULL,NULL ), 1);
4745 else if( mode == 3 && argc == 3 ) {
4747 mpi_print (es_stdout, generate_elg_prime(
4749 atoi(argv[2]), NULL,&factors ), 1);
4750 es_putc ('\n', es_stdout);
4751 mpi_print (es_stdout, factors[0], 1 ); /* print q */
4753 else if( mode == 4 && argc == 3 ) {
4754 MPI g = mpi_alloc(1);
4755 mpi_print (es_stdout, generate_elg_prime(
4757 atoi(argv[2]), g, NULL ), 1);
4758 es_putc ('\n', es_stdout);
4759 mpi_print (es_stdout, g, 1 );
4763 wrong_args("--gen-prime mode bits [qbits] ");
4764 es_putc ('\n', es_stdout);
4767 wrong_args("--gen-prime not yet supported ");
4772 int level = argc ? atoi(*argv):0;
4773 int count = argc > 1 ? atoi(argv[1]): 0;
4774 int endless = !count;
4776 if( argc < 1 || argc > 2 || level < 0 || level > 2 || count < 0 )
4777 wrong_args("--gen-random 0|1|2 [count]");
4779 while( endless || count ) {
4781 /* Wee need a multiple of 3, so that in case of
4782 armored output we get a correct string. No
4783 linefolding is done, as it is best to levae this to
4785 size_t n = !endless && count < 99? count : 99;
4787 p = gcry_random_bytes (n, level);
4788 #ifdef HAVE_DOSISH_SYSTEM
4789 setmode ( fileno(stdout), O_BINARY );
4792 char *tmp = make_radix64_string (p, n);
4793 es_fputs (tmp, es_stdout);
4796 es_putc ('=', es_stdout);
4798 es_putc ('=', es_stdout);
4800 es_fwrite( p, n, 1, es_stdout );
4807 es_putc ('\n', es_stdout);
4813 wrong_args("--print-md algo [files]");
4815 int all_algos = (**argv=='*' && !(*argv)[1]);
4816 int algo = all_algos? 0 : gcry_md_map_name (*argv);
4818 if( !algo && !all_algos )
4819 log_error(_("invalid hash algorithm '%s'\n"), *argv );
4823 print_mds(NULL, algo);
4825 for(; argc; argc--, argv++ )
4826 print_mds(*argv, algo);
4832 case aPrintMDs: /* old option */
4836 for(; argc; argc--, argv++ )
4841 #ifndef NO_TRUST_MODELS
4844 list_trustdb (ctrl, es_stdout, NULL);
4846 for( ; argc; argc--, argv++ )
4847 list_trustdb (ctrl, es_stdout, *argv );
4851 case aUpdateTrustDB:
4853 wrong_args("--update-trustdb");
4854 update_trustdb (ctrl);
4858 /* Old versions allowed for arguments - ignore them */
4859 check_trustdb (ctrl);
4863 how_to_fix_the_trustdb ();
4866 case aListTrustPath:
4868 wrong_args("--list-trust-path <user-ids>");
4869 for( ; argc; argc--, argv++ ) {
4870 username = make_username( *argv );
4871 list_trust_path( username );
4876 case aExportOwnerTrust:
4878 wrong_args("--export-ownertrust");
4879 export_ownertrust (ctrl);
4882 case aImportOwnerTrust:
4884 wrong_args("--import-ownertrust [file]");
4885 import_ownertrust (ctrl, argc? *argv:NULL );
4887 #endif /*!NO_TRUST_MODELS*/
4889 case aRebuildKeydbCaches:
4891 wrong_args ("--rebuild-keydb-caches");
4892 keydb_rebuild_caches (ctrl, 1);
4895 #ifdef ENABLE_CARD_SUPPORT
4898 card_status (ctrl, es_stdout, NULL);
4900 card_status (ctrl, es_stdout, *argv);
4902 wrong_args ("--card-status [serialno]");
4908 for (argc--, argv++ ; argc; argc--, argv++)
4909 append_to_strlist (&sl, *argv);
4910 card_edit (ctrl, sl);
4914 card_edit (ctrl, NULL);
4921 change_pin (atoi (*argv),1);
4923 wrong_args ("--change-pin [no]");
4925 #endif /* ENABLE_CARD_SUPPORT*/
4929 char *str=collapse_args(argc,argv);
4935 case aListGcryptConfig:
4936 /* Fixme: It would be nice to integrate that with
4937 --list-config but unfortunately there is no way yet to have
4938 libgcrypt print it to an estream for further parsing. */
4939 gcry_control (GCRYCTL_PRINT_CONFIG, stdout);
4950 wrong_args ("--tofu-policy POLICY KEYID [KEYID...]");
4952 policy = parse_tofu_policy (argv[0]);
4957 write_status_failure ("tofu-driver", gpg_error(GPG_ERR_GENERAL));
4961 tofu_begin_batch_update (ctrl);
4963 for (i = 1; i < argc; i ++)
4965 KEYDB_SEARCH_DESC desc;
4968 rc = classify_user_id (argv[i], &desc, 0);
4971 log_error (_("error parsing key specification '%s': %s\n"),
4972 argv[i], gpg_strerror (rc));
4973 write_status_failure ("tofu-driver", rc);
4977 if (! (desc.mode == KEYDB_SEARCH_MODE_SHORT_KID
4978 || desc.mode == KEYDB_SEARCH_MODE_LONG_KID
4979 || desc.mode == KEYDB_SEARCH_MODE_FPR16
4980 || desc.mode == KEYDB_SEARCH_MODE_FPR20
4981 || desc.mode == KEYDB_SEARCH_MODE_FPR
4982 || desc.mode == KEYDB_SEARCH_MODE_KEYGRIP))
4984 log_error (_("'%s' does not appear to be a valid"
4985 " key ID, fingerprint or keygrip\n"),
4987 write_status_failure ("tofu-driver",
4988 gpg_error(GPG_ERR_GENERAL));
4992 rc = keydb_search_reset (hd);
4995 /* This should not happen, thus no need to tranalate
4997 log_error ("keydb_search_reset failed: %s\n",
4999 write_status_failure ("tofu-driver", rc);
5003 rc = keydb_search (hd, &desc, 1, NULL);
5006 log_error (_("key \"%s\" not found: %s\n"), argv[i],
5008 write_status_failure ("tofu-driver", rc);
5012 rc = keydb_get_keyblock (hd, &kb);
5015 log_error (_("error reading keyblock: %s\n"),
5017 write_status_failure ("tofu-driver", rc);
5021 merge_keys_and_selfsig (ctrl, kb);
5022 if (tofu_set_policy (ctrl, kb, policy))
5024 write_status_failure ("tofu-driver", rc);
5028 release_kbnode (kb);
5031 tofu_end_batch_update (ctrl);
5040 log_info (_("WARNING: no command supplied."
5041 " Trying to guess what you mean ...\n"));
5045 wrong_args("[filename]");
5046 /* Issue some output for the unix newbie */
5047 if (!fname && !opt.outfile
5048 && gnupg_isatty (fileno (stdin))
5049 && gnupg_isatty (fileno (stdout))
5050 && gnupg_isatty (fileno (stderr)))
5051 log_info(_("Go ahead and type your message ...\n"));
5053 a = iobuf_open(fname);
5054 if (a && is_secured_file (iobuf_get_fd (a)))
5058 gpg_err_set_errno (EPERM);
5061 log_error(_("can't open '%s'\n"), print_fname_stdin(fname));
5064 if( !opt.no_armor ) {
5065 if( use_armor_filter( a ) ) {
5066 afx = new_armor_context ();
5067 push_armor_filter (afx, a);
5070 if( cmd == aListPackets ) {
5072 set_packet_list_mode(1);
5074 rc = proc_packets (ctrl, NULL, a );
5077 write_status_failure ("-", rc);
5078 log_error ("processing message failed: %s\n",
5087 gpg_deinit_default_ctrl (ctrl);
5089 release_armor_context (afx);
5090 FREE_STRLIST(remusr);
5091 FREE_STRLIST(locusr);
5093 return 8; /*NEVER REACHED*/
5097 /* Note: This function is used by signal handlers!. */
5099 emergency_cleanup (void)
5101 gcry_control (GCRYCTL_TERM_SECMEM );
5108 /* If we had an error but not printed an error message, do it now.
5109 * Note that write_status_failure will never print a second failure
5111 if (log_get_errorcount (0))
5112 write_status_failure ("gpg-exit", gpg_error (GPG_ERR_GENERAL));
5114 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
5118 if ( (opt.debug & DBG_MEMSTAT_VALUE) )
5120 keydb_dump_stats ();
5121 sig_check_dump_stats ();
5122 gcry_control (GCRYCTL_DUMP_MEMORY_STATS);
5123 gcry_control (GCRYCTL_DUMP_RANDOM_STATS);
5126 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
5128 emergency_cleanup ();
5130 rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0;
5135 /* Pretty-print hex hashes. This assumes at least an 80-character
5136 display, but there are a few other similar assumptions in the
5139 print_hex (gcry_md_hd_t md, int algo, const char *fname)
5141 int i,n,count,indent=0;
5145 indent = es_printf("%s: ",fname);
5153 if (algo==DIGEST_ALGO_RMD160)
5154 indent += es_printf("RMD160 = ");
5156 indent += es_printf("%6s = ", gcry_md_algo_name (algo));
5162 p = gcry_md_read (md, algo);
5163 n = gcry_md_get_algo_dlen (algo);
5165 count += es_printf ("%02X",*p++);
5167 for(i=1;i<n;i++,p++)
5173 es_printf ("\n%*s",indent," ");
5177 count += es_printf(" ");
5180 count += es_printf(" ");
5188 es_printf ("\n%*s",indent," ");
5192 count += es_printf(" ");
5196 count += es_printf(" ");
5204 es_printf ("\n%*s",indent," ");
5208 count += es_printf(" ");
5212 count += es_printf("%02X",*p);
5219 print_hashline( gcry_md_hd_t md, int algo, const char *fname )
5226 for (p = fname; *p; p++ )
5228 if ( *p <= 32 || *p > 127 || *p == ':' || *p == '%' )
5229 es_printf ("%%%02X", *p );
5231 es_putc (*p, es_stdout);
5234 es_putc (':', es_stdout);
5235 es_printf ("%d:", algo);
5236 p = gcry_md_read (md, algo);
5237 n = gcry_md_get_algo_dlen (algo);
5238 for(i=0; i < n ; i++, p++ )
5239 es_printf ("%02X", *p);
5240 es_fputs (":\n", es_stdout);
5245 print_mds( const char *fname, int algo )
5259 fp = es_fopen (fname, "rb" );
5260 if (fp && is_secured_file (es_fileno (fp)))
5264 gpg_err_set_errno (EPERM);
5269 log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
5273 gcry_md_open (&md, 0, 0);
5275 gcry_md_enable (md, algo);
5278 if (!gcry_md_test_algo (GCRY_MD_MD5))
5279 gcry_md_enable (md, GCRY_MD_MD5);
5280 gcry_md_enable (md, GCRY_MD_SHA1);
5281 if (!gcry_md_test_algo (GCRY_MD_RMD160))
5282 gcry_md_enable (md, GCRY_MD_RMD160);
5283 if (!gcry_md_test_algo (GCRY_MD_SHA224))
5284 gcry_md_enable (md, GCRY_MD_SHA224);
5285 if (!gcry_md_test_algo (GCRY_MD_SHA256))
5286 gcry_md_enable (md, GCRY_MD_SHA256);
5287 if (!gcry_md_test_algo (GCRY_MD_SHA384))
5288 gcry_md_enable (md, GCRY_MD_SHA384);
5289 if (!gcry_md_test_algo (GCRY_MD_SHA512))
5290 gcry_md_enable (md, GCRY_MD_SHA512);
5293 while ((n=es_fread (buf, 1, DIM(buf), fp)))
5294 gcry_md_write (md, buf, n);
5297 log_error ("%s: %s\n", fname?fname:"[stdin]", strerror(errno));
5301 if (opt.with_colons)
5304 print_hashline (md, algo, fname);
5307 if (!gcry_md_test_algo (GCRY_MD_MD5))
5308 print_hashline( md, GCRY_MD_MD5, fname );
5309 print_hashline( md, GCRY_MD_SHA1, fname );
5310 if (!gcry_md_test_algo (GCRY_MD_RMD160))
5311 print_hashline( md, GCRY_MD_RMD160, fname );
5312 if (!gcry_md_test_algo (GCRY_MD_SHA224))
5313 print_hashline (md, GCRY_MD_SHA224, fname);
5314 if (!gcry_md_test_algo (GCRY_MD_SHA256))
5315 print_hashline( md, GCRY_MD_SHA256, fname );
5316 if (!gcry_md_test_algo (GCRY_MD_SHA384))
5317 print_hashline ( md, GCRY_MD_SHA384, fname );
5318 if (!gcry_md_test_algo (GCRY_MD_SHA512))
5319 print_hashline ( md, GCRY_MD_SHA512, fname );
5325 print_hex (md, -algo, fname);
5328 if (!gcry_md_test_algo (GCRY_MD_MD5))
5329 print_hex (md, GCRY_MD_MD5, fname);
5330 print_hex (md, GCRY_MD_SHA1, fname );
5331 if (!gcry_md_test_algo (GCRY_MD_RMD160))
5332 print_hex (md, GCRY_MD_RMD160, fname );
5333 if (!gcry_md_test_algo (GCRY_MD_SHA224))
5334 print_hex (md, GCRY_MD_SHA224, fname);
5335 if (!gcry_md_test_algo (GCRY_MD_SHA256))
5336 print_hex (md, GCRY_MD_SHA256, fname );
5337 if (!gcry_md_test_algo (GCRY_MD_SHA384))
5338 print_hex (md, GCRY_MD_SHA384, fname );
5339 if (!gcry_md_test_algo (GCRY_MD_SHA512))
5340 print_hex (md, GCRY_MD_SHA512, fname );
5352 * Check the supplied name,value string and add it to the notation
5353 * data to be used for signatures. which==0 for sig notations, and 1
5354 * for cert notations.
5357 add_notation_data( const char *string, int which )
5359 struct notation *notation;
5361 notation=string_to_notation(string,utf8_strings);
5366 notation->next=opt.cert_notations;
5367 opt.cert_notations=notation;
5371 notation->next=opt.sig_notations;
5372 opt.sig_notations=notation;
5378 add_policy_url( const char *string, int which )
5380 unsigned int i,critical=0;
5389 for(i=0;i<strlen(string);i++)
5390 if( !isascii (string[i]) || iscntrl(string[i]))
5393 if(i==0 || i<strlen(string))
5396 log_error(_("the given certification policy URL is invalid\n"));
5398 log_error(_("the given signature policy URL is invalid\n"));
5402 sl=add_to_strlist( &opt.cert_policy_url, string );
5404 sl=add_to_strlist( &opt.sig_policy_url, string );
5411 add_keyserver_url( const char *string, int which )
5413 unsigned int i,critical=0;
5422 for(i=0;i<strlen(string);i++)
5423 if( !isascii (string[i]) || iscntrl(string[i]))
5426 if(i==0 || i<strlen(string))
5431 log_error(_("the given preferred keyserver URL is invalid\n"));
5437 sl=add_to_strlist( &opt.sig_keyserver_url, string );
5445 read_sessionkey_from_fd (int fd)
5450 if (! gnupg_fd_valid (fd))
5451 log_fatal ("override-session-key-fd is invalid: %s\n", strerror (errno));
5453 for (line = NULL, i = len = 100; ; i++ )
5459 line = xmalloc_secure (len);
5462 memcpy (line, tmp, i);
5468 if (read (fd, line + i, 1) != 1 || line[i] == '\n')
5472 log_debug ("seskey: %s\n", line);
5473 gpgrt_annotate_leaked_object (line);
5474 opt.override_session_key = line;