1 /* gpg.c - The GnuPG utility (main for gpg)
2 * Copyright (C) 1998-2011 Free Software Foundation, Inc.
3 * Copyright (C) 1997-2014 Werner Koch
4 * Copyright (C) 2015 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 <http://www.gnu.org/licenses/>.
31 #include <sys/stat.h> /* for stat() */
34 #ifdef HAVE_W32_SYSTEM
35 # ifdef HAVE_WINSOCK2_H
36 # include <winsock2.h>
41 #define INCLUDED_BY_MAIN_MODULE 1
44 #include "../common/iobuf.h"
57 #include "keyserver-internal.h"
59 #include "gc-opt-flags.h"
61 #include "call-dirmngr.h"
62 #include "../common/init.h"
63 #include "../common/shareddefs.h"
65 #if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
66 #define MY_O_BINARY O_BINARY
76 enum cmd_and_opt_values
90 oHiddenRecipient = 'R',
97 aListSecretKeys = 'K',
128 aDeleteSecretAndPublicKeys,
226 oBZ2DecompressLowmem,
254 oSkipHiddenRecipients,
255 oNoSkipHiddenRecipients,
268 oUseEmbeddedFilename,
269 oNoUseEmbeddedFilename,
310 oAllowNonSelfsignedUID,
311 oNoAllowNonSelfsignedUID,
314 oAllowSecretKeyImport,
315 oEnableSpecialFilenames,
336 oNoExpensiveTrustChecks,
343 oPreservePermissions,
344 oDefaultPreferenceList,
345 oDefaultKeyserverURL,
346 oPersonalCipherPreferences,
347 oPersonalDigestPreferences,
348 oPersonalCompressPreferences,
363 oNoMangleDosFilenames,
364 oEnableProgressFilter,
367 oExitOnStatusWriteError,
368 oLimitCardInsertTries,
377 oAllowMultisigVerification,
382 oAllowMultipleMessages,
383 oNoAllowMultipleMessages,
384 oAllowWeakDigestAlgos,
393 static ARGPARSE_OPTS opts[] = {
395 ARGPARSE_group (300, N_("@Commands:\n ")),
397 ARGPARSE_c (aSign, "sign", N_("make a signature")),
398 ARGPARSE_c (aClearsign, "clearsign", N_("make a clear text signature")),
399 ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")),
400 ARGPARSE_c (aEncr, "encrypt", N_("encrypt data")),
401 ARGPARSE_c (aEncrFiles, "encrypt-files", "@"),
402 ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")),
403 ARGPARSE_c (aStore, "store", "@"),
404 ARGPARSE_c (aDecrypt, "decrypt", N_("decrypt data (default)")),
405 ARGPARSE_c (aDecryptFiles, "decrypt-files", "@"),
406 ARGPARSE_c (aVerify, "verify" , N_("verify a signature")),
407 ARGPARSE_c (aVerifyFiles, "verify-files" , "@" ),
408 ARGPARSE_c (aListKeys, "list-keys", N_("list keys")),
409 ARGPARSE_c (aListKeys, "list-public-keys", "@" ),
410 ARGPARSE_c (aListSigs, "list-sigs", N_("list keys and signatures")),
411 ARGPARSE_c (aCheckKeys, "check-sigs",N_("list and check key signatures")),
412 ARGPARSE_c (oFingerprint, "fingerprint", N_("list keys and fingerprints")),
413 ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")),
414 ARGPARSE_c (aKeygen, "gen-key",
415 N_("generate a new key pair")),
416 ARGPARSE_c (aQuickKeygen, "quick-gen-key" ,
417 N_("quickly generate a new key pair")),
418 ARGPARSE_c (aQuickAddUid, "quick-adduid",
419 N_("quickly add a new user-id")),
420 ARGPARSE_c (aFullKeygen, "full-gen-key" ,
421 N_("full featured key pair generation")),
422 ARGPARSE_c (aGenRevoke, "gen-revoke",N_("generate a revocation certificate")),
423 ARGPARSE_c (aDeleteKeys,"delete-keys",
424 N_("remove keys from the public keyring")),
425 ARGPARSE_c (aDeleteSecretKeys, "delete-secret-keys",
426 N_("remove keys from the secret keyring")),
427 ARGPARSE_c (aQuickSignKey, "quick-sign-key" ,
428 N_("quickly sign a key")),
429 ARGPARSE_c (aQuickLSignKey, "quick-lsign-key",
430 N_("quickly sign a key locally")),
431 ARGPARSE_c (aSignKey, "sign-key" ,N_("sign a key")),
432 ARGPARSE_c (aLSignKey, "lsign-key" ,N_("sign a key locally")),
433 ARGPARSE_c (aEditKey, "edit-key" ,N_("sign or edit a key")),
434 ARGPARSE_c (aEditKey, "key-edit" ,"@"),
435 ARGPARSE_c (aPasswd, "passwd", N_("change a passphrase")),
436 ARGPARSE_c (aDesigRevoke, "desig-revoke","@" ),
437 ARGPARSE_c (aExport, "export" , N_("export keys") ),
438 ARGPARSE_c (aSendKeys, "send-keys" , N_("export keys to a key server") ),
439 ARGPARSE_c (aRecvKeys, "recv-keys" , N_("import keys from a key server") ),
440 ARGPARSE_c (aSearchKeys, "search-keys" ,
441 N_("search for keys on a key server") ),
442 ARGPARSE_c (aRefreshKeys, "refresh-keys",
443 N_("update all keys from a keyserver")),
444 ARGPARSE_c (aLocateKeys, "locate-keys", "@"),
445 ARGPARSE_c (aFetchKeys, "fetch-keys" , "@" ),
446 ARGPARSE_c (aExportSecret, "export-secret-keys" , "@" ),
447 ARGPARSE_c (aExportSecretSub, "export-secret-subkeys" , "@" ),
448 ARGPARSE_c (aImport, "import", N_("import/merge keys")),
449 ARGPARSE_c (aFastImport, "fast-import", "@"),
450 #ifdef ENABLE_CARD_SUPPORT
451 ARGPARSE_c (aCardStatus, "card-status", N_("print the card status")),
452 ARGPARSE_c (aCardEdit, "card-edit", N_("change data on a card")),
453 ARGPARSE_c (aChangePIN, "change-pin", N_("change a card's PIN")),
455 ARGPARSE_c (aListConfig, "list-config", "@"),
456 ARGPARSE_c (aListGcryptConfig, "list-gcrypt-config", "@"),
457 ARGPARSE_c (aGPGConfList, "gpgconf-list", "@" ),
458 ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@" ),
459 ARGPARSE_c (aListPackets, "list-packets","@"),
461 #ifndef NO_TRUST_MODELS
462 ARGPARSE_c (aExportOwnerTrust, "export-ownertrust", "@"),
463 ARGPARSE_c (aImportOwnerTrust, "import-ownertrust", "@"),
464 ARGPARSE_c (aUpdateTrustDB,"update-trustdb",
465 N_("update the trust database")),
466 ARGPARSE_c (aCheckTrustDB, "check-trustdb", "@"),
467 ARGPARSE_c (aFixTrustDB, "fix-trustdb", "@"),
470 ARGPARSE_c (aDeArmor, "dearmor", "@"),
471 ARGPARSE_c (aDeArmor, "dearmour", "@"),
472 ARGPARSE_c (aEnArmor, "enarmor", "@"),
473 ARGPARSE_c (aEnArmor, "enarmour", "@"),
474 ARGPARSE_c (aPrintMD, "print-md", N_("print message digests")),
475 ARGPARSE_c (aPrimegen, "gen-prime", "@" ),
476 ARGPARSE_c (aGenRandom,"gen-random", "@" ),
477 ARGPARSE_c (aServer, "server", N_("run in server mode")),
479 ARGPARSE_group (301, N_("@\nOptions:\n ")),
481 ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")),
482 ARGPARSE_s_n (oArmor, "armour", "@"),
484 ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")),
485 ARGPARSE_s_s (oHiddenRecipient, "hidden-recipient", "@"),
486 ARGPARSE_s_s (oRecipient, "remote-user", "@"), /* (old option name) */
487 ARGPARSE_s_s (oDefRecipient, "default-recipient", "@"),
488 ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", "@"),
489 ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"),
491 ARGPARSE_s_s (oTempDir, "temp-directory", "@"),
492 ARGPARSE_s_s (oExecPath, "exec-path", "@"),
493 ARGPARSE_s_s (oEncryptTo, "encrypt-to", "@"),
494 ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"),
495 ARGPARSE_s_s (oHiddenEncryptTo, "hidden-encrypt-to", "@"),
496 ARGPARSE_s_s (oLocalUser, "local-user",
497 N_("|USER-ID|use USER-ID to sign or decrypt")),
499 ARGPARSE_s_s (oTrySecretKey, "try-secret-key", "@"),
501 ARGPARSE_s_i (oCompress, NULL,
502 N_("|N|set compress level to N (0 disables)")),
503 ARGPARSE_s_i (oCompressLevel, "compress-level", "@"),
504 ARGPARSE_s_i (oBZ2CompressLevel, "bzip2-compress-level", "@"),
505 ARGPARSE_s_n (oBZ2DecompressLowmem, "bzip2-decompress-lowmem", "@"),
507 ARGPARSE_s_n (oTextmodeShort, NULL, "@"),
508 ARGPARSE_s_n (oTextmode, "textmode", N_("use canonical text mode")),
509 ARGPARSE_s_n (oNoTextmode, "no-textmode", "@"),
511 ARGPARSE_s_n (oExpert, "expert", "@"),
512 ARGPARSE_s_n (oNoExpert, "no-expert", "@"),
514 ARGPARSE_s_s (oDefSigExpire, "default-sig-expire", "@"),
515 ARGPARSE_s_n (oAskSigExpire, "ask-sig-expire", "@"),
516 ARGPARSE_s_n (oNoAskSigExpire, "no-ask-sig-expire", "@"),
517 ARGPARSE_s_s (oDefCertExpire, "default-cert-expire", "@"),
518 ARGPARSE_s_n (oAskCertExpire, "ask-cert-expire", "@"),
519 ARGPARSE_s_n (oNoAskCertExpire, "no-ask-cert-expire", "@"),
520 ARGPARSE_s_i (oDefCertLevel, "default-cert-level", "@"),
521 ARGPARSE_s_i (oMinCertLevel, "min-cert-level", "@"),
522 ARGPARSE_s_n (oAskCertLevel, "ask-cert-level", "@"),
523 ARGPARSE_s_n (oNoAskCertLevel, "no-ask-cert-level", "@"),
525 ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")),
526 ARGPARSE_p_u (oMaxOutput, "max-output", "@"),
528 ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
529 ARGPARSE_s_n (oQuiet, "quiet", "@"),
530 ARGPARSE_s_n (oNoTTY, "no-tty", "@"),
532 ARGPARSE_s_n (oForceMDC, "force-mdc", "@"),
533 ARGPARSE_s_n (oNoForceMDC, "no-force-mdc", "@"),
534 ARGPARSE_s_n (oDisableMDC, "disable-mdc", "@"),
535 ARGPARSE_s_n (oNoDisableMDC, "no-disable-mdc", "@"),
537 ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")),
538 ARGPARSE_s_n (oInteractive, "interactive", N_("prompt before overwriting")),
540 ARGPARSE_s_n (oBatch, "batch", "@"),
541 ARGPARSE_s_n (oAnswerYes, "yes", "@"),
542 ARGPARSE_s_n (oAnswerNo, "no", "@"),
543 ARGPARSE_s_s (oKeyring, "keyring", "@"),
544 ARGPARSE_s_s (oPrimaryKeyring, "primary-keyring", "@"),
545 ARGPARSE_s_s (oSecretKeyring, "secret-keyring", "@"),
546 ARGPARSE_s_n (oShowKeyring, "show-keyring", "@"),
547 ARGPARSE_s_s (oDefaultKey, "default-key", "@"),
549 ARGPARSE_s_s (oKeyServer, "keyserver", "@"),
550 ARGPARSE_s_s (oKeyServerOptions, "keyserver-options", "@"),
551 ARGPARSE_s_s (oImportOptions, "import-options", "@"),
552 ARGPARSE_s_s (oExportOptions, "export-options", "@"),
553 ARGPARSE_s_s (oListOptions, "list-options", "@"),
554 ARGPARSE_s_s (oVerifyOptions, "verify-options", "@"),
556 ARGPARSE_s_s (oDisplayCharset, "display-charset", "@"),
557 ARGPARSE_s_s (oDisplayCharset, "charset", "@"),
558 ARGPARSE_s_s (oOptions, "options", "@"),
560 ARGPARSE_p_u (oDebug, "debug", "@"),
561 ARGPARSE_s_s (oDebugLevel, "debug-level", "@"),
562 ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
563 ARGPARSE_s_n (oDebugIOLBF, "debug-iolbf", "@"),
564 ARGPARSE_s_i (oStatusFD, "status-fd", "@"),
565 ARGPARSE_s_s (oStatusFile, "status-file", "@"),
566 ARGPARSE_s_i (oAttributeFD, "attribute-fd", "@"),
567 ARGPARSE_s_s (oAttributeFile, "attribute-file", "@"),
569 ARGPARSE_s_i (oCompletesNeeded, "completes-needed", "@"),
570 ARGPARSE_s_i (oMarginalsNeeded, "marginals-needed", "@"),
571 ARGPARSE_s_i (oMaxCertDepth, "max-cert-depth", "@" ),
572 ARGPARSE_s_s (oTrustedKey, "trusted-key", "@"),
574 ARGPARSE_s_s (oLoadExtension, "load-extension", "@"), /* Dummy. */
576 ARGPARSE_s_n (oGnuPG, "gnupg", "@"),
577 ARGPARSE_s_n (oGnuPG, "no-pgp2", "@"),
578 ARGPARSE_s_n (oGnuPG, "no-pgp6", "@"),
579 ARGPARSE_s_n (oGnuPG, "no-pgp7", "@"),
580 ARGPARSE_s_n (oGnuPG, "no-pgp8", "@"),
581 ARGPARSE_s_n (oRFC2440, "rfc2440", "@"),
582 ARGPARSE_s_n (oRFC4880, "rfc4880", "@"),
583 ARGPARSE_s_n (oOpenPGP, "openpgp", N_("use strict OpenPGP behavior")),
584 ARGPARSE_s_n (oPGP6, "pgp6", "@"),
585 ARGPARSE_s_n (oPGP7, "pgp7", "@"),
586 ARGPARSE_s_n (oPGP8, "pgp8", "@"),
588 ARGPARSE_s_n (oRFC2440Text, "rfc2440-text", "@"),
589 ARGPARSE_s_n (oNoRFC2440Text, "no-rfc2440-text", "@"),
590 ARGPARSE_s_i (oS2KMode, "s2k-mode", "@"),
591 ARGPARSE_s_s (oS2KDigest, "s2k-digest-algo", "@"),
592 ARGPARSE_s_s (oS2KCipher, "s2k-cipher-algo", "@"),
593 ARGPARSE_s_i (oS2KCount, "s2k-count", "@"),
594 ARGPARSE_s_s (oCipherAlgo, "cipher-algo", "@"),
595 ARGPARSE_s_s (oDigestAlgo, "digest-algo", "@"),
596 ARGPARSE_s_s (oCertDigestAlgo, "cert-digest-algo", "@"),
597 ARGPARSE_s_s (oCompressAlgo,"compress-algo", "@"),
598 ARGPARSE_s_s (oCompressAlgo, "compression-algo", "@"), /* Alias */
599 ARGPARSE_s_n (oThrowKeyids, "throw-keyids", "@"),
600 ARGPARSE_s_n (oNoThrowKeyids, "no-throw-keyids", "@"),
601 ARGPARSE_s_n (oShowPhotos, "show-photos", "@"),
602 ARGPARSE_s_n (oNoShowPhotos, "no-show-photos", "@"),
603 ARGPARSE_s_s (oPhotoViewer, "photo-viewer", "@"),
604 ARGPARSE_s_s (oSetNotation, "set-notation", "@"),
605 ARGPARSE_s_s (oSigNotation, "sig-notation", "@"),
606 ARGPARSE_s_s (oCertNotation, "cert-notation", "@"),
608 ARGPARSE_group (302, N_(
609 "@\n(See the man page for a complete listing of all commands and options)\n"
612 ARGPARSE_group (303, N_("@\nExamples:\n\n"
613 " -se -r Bob [file] sign and encrypt for user Bob\n"
614 " --clearsign [file] make a clear text signature\n"
615 " --detach-sign [file] make a detached signature\n"
616 " --list-keys [names] show keys\n"
617 " --fingerprint [names] show fingerprints\n")),
619 /* More hidden commands and options. */
620 ARGPARSE_c (aPrintMDs, "print-mds", "@"), /* old */
621 #ifndef NO_TRUST_MODELS
622 ARGPARSE_c (aListTrustDB, "list-trustdb", "@"),
626 ARGPARSE_c (aListTrustPath, "list-trust-path", "@"), */
627 ARGPARSE_c (aDeleteSecretAndPublicKeys,
628 "delete-secret-and-public-keys", "@"),
629 ARGPARSE_c (aRebuildKeydbCaches, "rebuild-keydb-caches", "@"),
631 ARGPARSE_s_s (oPassphrase, "passphrase", "@"),
632 ARGPARSE_s_i (oPassphraseFD, "passphrase-fd", "@"),
633 ARGPARSE_s_s (oPassphraseFile, "passphrase-file", "@"),
634 ARGPARSE_s_i (oPassphraseRepeat,"passphrase-repeat", "@"),
635 ARGPARSE_s_s (oPinentryMode, "pinentry-mode", "@"),
636 ARGPARSE_s_i (oCommandFD, "command-fd", "@"),
637 ARGPARSE_s_s (oCommandFile, "command-file", "@"),
638 ARGPARSE_s_n (oQuickRandom, "debug-quick-random", "@"),
639 ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
641 #ifndef NO_TRUST_MODELS
642 ARGPARSE_s_s (oTrustDBName, "trustdb-name", "@"),
643 ARGPARSE_s_n (oAutoCheckTrustDB, "auto-check-trustdb", "@"),
644 ARGPARSE_s_n (oNoAutoCheckTrustDB, "no-auto-check-trustdb", "@"),
645 ARGPARSE_s_s (oForceOwnertrust, "force-ownertrust", "@"),
648 ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"),
649 ARGPARSE_s_n (oRequireSecmem, "require-secmem", "@"),
650 ARGPARSE_s_n (oNoRequireSecmem, "no-require-secmem", "@"),
651 ARGPARSE_s_n (oNoPermissionWarn, "no-permission-warning", "@"),
652 ARGPARSE_s_n (oNoMDCWarn, "no-mdc-warning", "@"),
653 ARGPARSE_s_n (oNoArmor, "no-armor", "@"),
654 ARGPARSE_s_n (oNoArmor, "no-armour", "@"),
655 ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"),
656 ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
657 ARGPARSE_s_n (oNoOptions, "no-options", "@"),
658 ARGPARSE_s_s (oHomedir, "homedir", "@"),
659 ARGPARSE_s_n (oNoBatch, "no-batch", "@"),
660 ARGPARSE_s_n (oWithColons, "with-colons", "@"),
661 ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"),
662 ARGPARSE_s_n (oWithSigList,"with-sig-list", "@"),
663 ARGPARSE_s_n (oWithSigCheck,"with-sig-check", "@"),
664 ARGPARSE_s_n (aListKeys, "list-key", "@"), /* alias */
665 ARGPARSE_s_n (aListSigs, "list-sig", "@"), /* alias */
666 ARGPARSE_s_n (aCheckKeys, "check-sig", "@"), /* alias */
667 ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"),
668 ARGPARSE_s_n (oSkipHiddenRecipients, "skip-hidden-recipients", "@"),
669 ARGPARSE_s_n (oNoSkipHiddenRecipients, "no-skip-hidden-recipients", "@"),
670 ARGPARSE_s_i (oDefCertLevel, "default-cert-check-level", "@"), /* old */
671 ARGPARSE_s_n (oAlwaysTrust, "always-trust", "@"),
672 ARGPARSE_s_s (oTrustModel, "trust-model", "@"),
673 ARGPARSE_s_s (oSetFilename, "set-filename", "@"),
674 ARGPARSE_s_n (oForYourEyesOnly, "for-your-eyes-only", "@"),
675 ARGPARSE_s_n (oNoForYourEyesOnly, "no-for-your-eyes-only", "@"),
676 ARGPARSE_s_s (oSetPolicyURL, "set-policy-url", "@"),
677 ARGPARSE_s_s (oSigPolicyURL, "sig-policy-url", "@"),
678 ARGPARSE_s_s (oCertPolicyURL, "cert-policy-url", "@"),
679 ARGPARSE_s_n (oShowPolicyURL, "show-policy-url", "@"),
680 ARGPARSE_s_n (oNoShowPolicyURL, "no-show-policy-url", "@"),
681 ARGPARSE_s_s (oSigKeyserverURL, "sig-keyserver-url", "@"),
682 ARGPARSE_s_n (oShowNotation, "show-notation", "@"),
683 ARGPARSE_s_n (oNoShowNotation, "no-show-notation", "@"),
684 ARGPARSE_s_s (oComment, "comment", "@"),
685 ARGPARSE_s_n (oDefaultComment, "default-comment", "@"),
686 ARGPARSE_s_n (oNoComments, "no-comments", "@"),
687 ARGPARSE_s_n (oEmitVersion, "emit-version", "@"),
688 ARGPARSE_s_n (oNoEmitVersion, "no-emit-version", "@"),
689 ARGPARSE_s_n (oNoEmitVersion, "no-version", "@"), /* alias */
690 ARGPARSE_s_n (oNotDashEscaped, "not-dash-escaped", "@"),
691 ARGPARSE_s_n (oEscapeFrom, "escape-from-lines", "@"),
692 ARGPARSE_s_n (oNoEscapeFrom, "no-escape-from-lines", "@"),
693 ARGPARSE_s_n (oLockOnce, "lock-once", "@"),
694 ARGPARSE_s_n (oLockMultiple, "lock-multiple", "@"),
695 ARGPARSE_s_n (oLockNever, "lock-never", "@"),
696 ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"),
697 ARGPARSE_s_s (oLoggerFile, "log-file", "@"),
698 ARGPARSE_s_s (oLoggerFile, "logger-file", "@"), /* 1.4 compatibility. */
699 ARGPARSE_s_n (oUseEmbeddedFilename, "use-embedded-filename", "@"),
700 ARGPARSE_s_n (oNoUseEmbeddedFilename, "no-use-embedded-filename", "@"),
701 ARGPARSE_s_n (oUtf8Strings, "utf8-strings", "@"),
702 ARGPARSE_s_n (oNoUtf8Strings, "no-utf8-strings", "@"),
703 ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"),
704 ARGPARSE_s_n (oWithICAOSpelling, "with-icao-spelling", "@"),
705 ARGPARSE_s_n (oWithKeygrip, "with-keygrip", "@"),
706 ARGPARSE_s_n (oWithSecret, "with-secret", "@"),
707 ARGPARSE_s_s (oDisableCipherAlgo, "disable-cipher-algo", "@"),
708 ARGPARSE_s_s (oDisablePubkeyAlgo, "disable-pubkey-algo", "@"),
709 ARGPARSE_s_n (oAllowNonSelfsignedUID, "allow-non-selfsigned-uid", "@"),
710 ARGPARSE_s_n (oNoAllowNonSelfsignedUID, "no-allow-non-selfsigned-uid", "@"),
711 ARGPARSE_s_n (oAllowFreeformUID, "allow-freeform-uid", "@"),
712 ARGPARSE_s_n (oNoAllowFreeformUID, "no-allow-freeform-uid", "@"),
713 ARGPARSE_s_n (oNoLiteral, "no-literal", "@"),
714 ARGPARSE_p_u (oSetFilesize, "set-filesize", "@"),
715 ARGPARSE_s_n (oFastListMode, "fast-list-mode", "@"),
716 ARGPARSE_s_n (oFixedListMode, "fixed-list-mode", "@"),
717 ARGPARSE_s_n (oLegacyListMode, "legacy-list-mode", "@"),
718 ARGPARSE_s_n (oListOnly, "list-only", "@"),
719 ARGPARSE_s_n (oPrintPKARecords, "print-pka-records", "@"),
720 ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"),
721 ARGPARSE_s_n (oIgnoreValidFrom, "ignore-valid-from", "@"),
722 ARGPARSE_s_n (oIgnoreCrcError, "ignore-crc-error", "@"),
723 ARGPARSE_s_n (oIgnoreMDCError, "ignore-mdc-error", "@"),
724 ARGPARSE_s_n (oShowSessionKey, "show-session-key", "@"),
725 ARGPARSE_s_s (oOverrideSessionKey, "override-session-key", "@"),
726 ARGPARSE_s_n (oNoRandomSeedFile, "no-random-seed-file", "@"),
727 ARGPARSE_s_n (oAutoKeyRetrieve, "auto-key-retrieve", "@"),
728 ARGPARSE_s_n (oNoAutoKeyRetrieve, "no-auto-key-retrieve", "@"),
729 ARGPARSE_s_n (oNoSigCache, "no-sig-cache", "@"),
730 ARGPARSE_s_n (oNoSigCreateCheck, "no-sig-create-check", "@"),
731 ARGPARSE_s_n (oMergeOnly, "merge-only", "@" ),
732 ARGPARSE_s_n (oAllowSecretKeyImport, "allow-secret-key-import", "@"),
733 ARGPARSE_s_n (oTryAllSecrets, "try-all-secrets", "@"),
734 ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"),
735 ARGPARSE_s_n (oNoExpensiveTrustChecks, "no-expensive-trust-checks", "@"),
736 ARGPARSE_s_n (oPreservePermissions, "preserve-permissions", "@"),
737 ARGPARSE_s_s (oDefaultPreferenceList, "default-preference-list", "@"),
738 ARGPARSE_s_s (oDefaultKeyserverURL, "default-keyserver-url", "@"),
739 ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-preferences","@"),
740 ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-preferences","@"),
741 ARGPARSE_s_s (oPersonalCompressPreferences,
742 "personal-compress-preferences", "@"),
743 ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
745 /* Aliases. I constantly mistype these, and assume other people do
747 ARGPARSE_s_s (oPersonalCipherPreferences, "personal-cipher-prefs", "@"),
748 ARGPARSE_s_s (oPersonalDigestPreferences, "personal-digest-prefs", "@"),
749 ARGPARSE_s_s (oPersonalCompressPreferences, "personal-compress-prefs", "@"),
751 ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
752 ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"),
753 ARGPARSE_s_s (oDisplay, "display", "@"),
754 ARGPARSE_s_s (oTTYname, "ttyname", "@"),
755 ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
756 ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
757 ARGPARSE_s_s (oLCmessages, "lc-messages","@"),
758 ARGPARSE_s_s (oXauthority, "xauthority", "@"),
759 ARGPARSE_s_s (oGroup, "group", "@"),
760 ARGPARSE_s_s (oUnGroup, "ungroup", "@"),
761 ARGPARSE_s_n (oNoGroups, "no-groups", "@"),
762 ARGPARSE_s_n (oStrict, "strict", "@"),
763 ARGPARSE_s_n (oNoStrict, "no-strict", "@"),
764 ARGPARSE_s_n (oMangleDosFilenames, "mangle-dos-filenames", "@"),
765 ARGPARSE_s_n (oNoMangleDosFilenames, "no-mangle-dos-filenames", "@"),
766 ARGPARSE_s_n (oEnableProgressFilter, "enable-progress-filter", "@"),
767 ARGPARSE_s_n (oMultifile, "multifile", "@"),
768 ARGPARSE_s_s (oKeyidFormat, "keyid-format", "@"),
769 ARGPARSE_s_n (oExitOnStatusWriteError, "exit-on-status-write-error", "@"),
770 ARGPARSE_s_i (oLimitCardInsertTries, "limit-card-insert-tries", "@"),
772 ARGPARSE_s_n (oAllowMultisigVerification,
773 "allow-multisig-verification", "@"),
774 ARGPARSE_s_n (oEnableLargeRSA, "enable-large-rsa", "@"),
775 ARGPARSE_s_n (oDisableLargeRSA, "disable-large-rsa", "@"),
776 ARGPARSE_s_n (oEnableDSA2, "enable-dsa2", "@"),
777 ARGPARSE_s_n (oDisableDSA2, "disable-dsa2", "@"),
778 ARGPARSE_s_n (oAllowMultipleMessages, "allow-multiple-messages", "@"),
779 ARGPARSE_s_n (oNoAllowMultipleMessages, "no-allow-multiple-messages", "@"),
780 ARGPARSE_s_n (oAllowWeakDigestAlgos, "allow-weak-digest-algos", "@"),
782 /* These two are aliases to help users of the PGP command line
783 product use gpg with minimal pain. Many commands are common
784 already as they seem to have borrowed commands from us. Now I'm
785 returning the favor. */
786 ARGPARSE_s_s (oLocalUser, "sign-with", "@"),
787 ARGPARSE_s_s (oRecipient, "user", "@"),
789 ARGPARSE_s_n (oRequireCrossCert, "require-backsigs", "@"),
790 ARGPARSE_s_n (oRequireCrossCert, "require-cross-certification", "@"),
791 ARGPARSE_s_n (oNoRequireCrossCert, "no-require-backsigs", "@"),
792 ARGPARSE_s_n (oNoRequireCrossCert, "no-require-cross-certification", "@"),
794 /* New options. Fixme: Should go more to the top. */
795 ARGPARSE_s_s (oAutoKeyLocate, "auto-key-locate", "@"),
796 ARGPARSE_s_n (oNoAutoKeyLocate, "no-auto-key-locate", "@"),
797 ARGPARSE_s_n (oNoAutostart, "no-autostart", "@"),
799 /* Dummy options with warnings. */
800 ARGPARSE_s_n (oUseAgent, "use-agent", "@"),
801 ARGPARSE_s_n (oNoUseAgent, "no-use-agent", "@"),
802 ARGPARSE_s_s (oGpgAgentInfo, "gpg-agent-info", "@"),
803 ARGPARSE_s_s (oReaderPort, "reader-port", "@"),
804 ARGPARSE_s_s (octapiDriver, "ctapi-driver", "@"),
805 ARGPARSE_s_s (opcscDriver, "pcsc-driver", "@"),
806 ARGPARSE_s_n (oDisableCCID, "disable-ccid", "@"),
807 ARGPARSE_s_n (oHonorHttpProxy, "honor-http-proxy", "@"),
810 ARGPARSE_s_n (oNoop, "sk-comments", "@"),
811 ARGPARSE_s_n (oNoop, "no-sk-comments", "@"),
812 ARGPARSE_s_n (oNoop, "compress-keys", "@"),
813 ARGPARSE_s_n (oNoop, "compress-sigs", "@"),
814 ARGPARSE_s_n (oNoop, "force-v3-sigs", "@"),
815 ARGPARSE_s_n (oNoop, "no-force-v3-sigs", "@"),
816 ARGPARSE_s_n (oNoop, "force-v4-certs", "@"),
817 ARGPARSE_s_n (oNoop, "no-force-v4-certs", "@"),
823 #ifdef ENABLE_SELINUX_HACKS
824 #define ALWAYS_ADD_KEYRINGS 1
826 #define ALWAYS_ADD_KEYRINGS 0
830 int g10_errors_seen = 0;
832 static int utf8_strings = 0;
833 static int maybe_setuid = 1;
835 static char *build_list( const char *text, char letter,
836 const char *(*mapf)(int), int (*chkf)(int) );
837 static void set_cmd( enum cmd_and_opt_values *ret_cmd,
838 enum cmd_and_opt_values new_cmd );
839 static void print_mds( const char *fname, int algo );
840 static void add_notation_data( const char *string, int which );
841 static void add_policy_url( const char *string, int which );
842 static void add_keyserver_url( const char *string, int which );
843 static void emergency_cleanup (void);
847 make_libversion (const char *libname, const char *(*getfnc)(const char*))
854 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
858 result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
859 strcpy (stpcpy (stpcpy (result, libname), " "), s);
865 build_list_pk_test_algo (int algo)
867 /* Show only one "RSA" string. If RSA_E or RSA_S is available RSA
868 is also available. */
869 if (algo == PUBKEY_ALGO_RSA_E
870 || algo == PUBKEY_ALGO_RSA_S)
871 return GPG_ERR_DIGEST_ALGO;
873 return openpgp_pk_test_algo (algo);
877 build_list_pk_algo_name (int algo)
879 return openpgp_pk_algo_name (algo);
883 build_list_cipher_test_algo (int algo)
885 return openpgp_cipher_test_algo (algo);
889 build_list_cipher_algo_name (int algo)
891 return openpgp_cipher_algo_name (algo);
895 build_list_md_test_algo (int algo)
897 /* By default we do not accept MD5 based signatures. To avoid
898 confusion we do not announce support for it either. */
899 if (algo == DIGEST_ALGO_MD5)
900 return GPG_ERR_DIGEST_ALGO;
902 return openpgp_md_test_algo (algo);
906 build_list_md_algo_name (int algo)
908 return openpgp_md_algo_name (algo);
913 my_strusage( int level )
915 static char *digests, *pubkeys, *ciphers, *zips, *ver_gcry;
919 case 11: p = "@GPG@ (@GNUPG@)";
921 case 13: p = VERSION; break;
922 case 17: p = PRINTABLE_OS_NAME; break;
923 case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
927 ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
931 #ifdef IS_DEVELOPMENT_VERSION
933 p="NOTE: THIS IS A DEVELOPMENT VERSION!";
936 p="It is only intended for test purposes and should NOT be";
939 p="used in a production environment or with production keys!";
945 _("Usage: @GPG@ [options] [files] (-h for help)");
948 _("Syntax: @GPG@ [options] [files]\n"
949 "Sign, check, encrypt or decrypt\n"
950 "Default operation depends on the input data\n");
953 case 31: p = "\nHome: "; break;
955 case 32: p = opt.homedir; break;
956 #else /* __riscos__ */
957 case 32: p = make_filename(opt.homedir, NULL); break;
958 #endif /* __riscos__ */
959 case 33: p = _("\nSupported algorithms:\n"); break;
962 pubkeys = build_list (_("Pubkey: "), 1,
963 build_list_pk_algo_name,
964 build_list_pk_test_algo );
969 ciphers = build_list(_("Cipher: "), 'S',
970 build_list_cipher_algo_name,
971 build_list_cipher_test_algo );
976 digests = build_list(_("Hash: "), 'H',
977 build_list_md_algo_name,
978 build_list_md_test_algo );
983 zips = build_list(_("Compression: "),'Z',
984 compress_algo_to_string,
985 check_compress_algo);
996 build_list (const char *text, char letter,
997 const char * (*mapf)(int), int (*chkf)(int))
1006 gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
1008 indent = utf8_charcount (text);
1010 init_membuf (&mb, 512);
1012 for (i=0; i <= 110; i++ )
1014 if (!chkf (i) && (s = mapf (i)))
1016 if (mb.len - len > 60)
1018 put_membuf_str (&mb, ",\n");
1020 for (j=0; j < indent; j++)
1021 put_membuf_str (&mb, " ");
1024 put_membuf_str (&mb, ", ");
1026 put_membuf_str (&mb, text);
1028 put_membuf_str (&mb, s);
1029 if (opt.verbose && letter)
1033 snprintf (num, sizeof num, " (%d)", i);
1035 snprintf (num, sizeof num, " (%c%d)", letter, i);
1036 put_membuf_str (&mb, num);
1041 put_membuf_str (&mb, "\n");
1042 put_membuf (&mb, "", 1);
1044 string = get_membuf (&mb, NULL);
1045 return xrealloc (string, strlen (string)+1);
1050 wrong_args( const char *text)
1052 es_fprintf (es_stderr, _("usage: %s [options] %s\n"), GPG_NAME, text);
1058 make_username( const char *string )
1062 p = xstrdup(string);
1064 p = native_to_utf8( string );
1070 set_opt_session_env (const char *name, const char *value)
1074 err = session_env_setenv (opt.session_env, name, value);
1076 log_fatal ("error setting session environment: %s\n",
1077 gpg_strerror (err));
1080 /* Setup the debugging. With a LEVEL of NULL only the active debug
1081 flags are propagated to the subsystems. With LEVEL set, a specific
1082 set of debug flags is set; thus overriding all flags already
1085 set_debug (const char *level)
1087 int numok = (level && digitp (level));
1088 int numlvl = numok? atoi (level) : 0;
1092 else if (!strcmp (level, "none") || (numok && numlvl < 1))
1094 else if (!strcmp (level, "basic") || (numok && numlvl <= 2))
1095 opt.debug = DBG_MEMSTAT_VALUE;
1096 else if (!strcmp (level, "advanced") || (numok && numlvl <= 5))
1097 opt.debug = DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE;
1098 else if (!strcmp (level, "expert") || (numok && numlvl <= 8))
1099 opt.debug = (DBG_MEMSTAT_VALUE|DBG_TRUST_VALUE|DBG_EXTPROG_VALUE
1100 |DBG_CACHE_VALUE|DBG_LOOKUP|DBG_FILTER_VALUE|DBG_PACKET_VALUE);
1101 else if (!strcmp (level, "guru") || numok)
1104 /* Unless the "guru" string has been used we don't want to allow
1105 hashing debugging. The rationale is that people tend to
1106 select the highest debug value and would then clutter their
1107 disk with debug files which may reveal confidential data. */
1109 opt.debug &= ~(DBG_HASHING_VALUE);
1113 log_error (_("invalid debug-level '%s' given\n"), level);
1117 if (opt.debug & DBG_MEMORY_VALUE )
1118 memory_debug_mode = 1;
1119 if (opt.debug & DBG_MEMSTAT_VALUE )
1120 memory_stat_debug_mode = 1;
1121 if (opt.debug & DBG_MPI_VALUE)
1122 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
1123 if (opt.debug & DBG_CRYPTO_VALUE )
1124 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
1125 if (opt.debug & DBG_IOBUF_VALUE )
1126 iobuf_debug_mode = 1;
1127 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
1130 log_info ("enabled debug flags:%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n",
1131 (opt.debug & DBG_PACKET_VALUE )? " packet":"",
1132 (opt.debug & DBG_MPI_VALUE )? " mpi":"",
1133 (opt.debug & DBG_CRYPTO_VALUE )? " crypto":"",
1134 (opt.debug & DBG_FILTER_VALUE )? " filter":"",
1135 (opt.debug & DBG_IOBUF_VALUE )? " iobuf":"",
1136 (opt.debug & DBG_MEMORY_VALUE )? " memory":"",
1137 (opt.debug & DBG_CACHE_VALUE )? " cache":"",
1138 (opt.debug & DBG_MEMSTAT_VALUE)? " memstat":"",
1139 (opt.debug & DBG_TRUST_VALUE )? " trust":"",
1140 (opt.debug & DBG_HASHING_VALUE)? " hashing":"",
1141 (opt.debug & DBG_EXTPROG_VALUE)? " extprog":"",
1142 (opt.debug & DBG_CARD_IO_VALUE)? " cardio":"",
1143 (opt.debug & DBG_IPC_VALUE )? " ipc":"",
1144 (opt.debug & DBG_CLOCK_VALUE )? " clock":"",
1145 (opt.debug & DBG_LOOKUP_VALUE )? " lookup":"");
1150 /* We need the home directory also in some other directories, so make
1151 sure that both variables are always in sync. */
1153 set_homedir (const char *dir)
1161 /* We set the screen dimensions for UI purposes. Do not allow screens
1162 smaller than 80x24 for the sake of simplicity. */
1164 set_screen_dimensions(void)
1166 #ifndef HAVE_W32_SYSTEM
1169 str=getenv("COLUMNS");
1171 opt.screen_columns=atoi(str);
1173 str=getenv("LINES");
1175 opt.screen_lines=atoi(str);
1178 if(opt.screen_columns<80 || opt.screen_columns>255)
1179 opt.screen_columns=80;
1181 if(opt.screen_lines<24 || opt.screen_lines>255)
1182 opt.screen_lines=24;
1186 /* Helper to open a file FNAME either for reading or writing to be
1187 used with --status-file etc functions. Not generally useful but it
1188 avoids the riscos specific functions and well some Windows people
1189 might like it too. Prints an error message and returns -1 on
1190 error. On success the file descriptor is returned. */
1192 open_info_file (const char *fname, int for_write, int binary)
1195 return riscos_fdopenfile (fname, for_write);
1196 #elif defined (ENABLE_SELINUX_HACKS)
1197 /* We can't allow these even when testing for a secured filename
1198 because files to be secured might not yet been secured. This is
1199 similar to the option file but in that case it is unlikely that
1200 sensitive information may be retrieved by means of error
1210 binary = MY_O_BINARY;
1212 /* if (is_secured_filename (fname)) */
1215 /* gpg_err_set_errno (EPERM); */
1222 fd = open (fname, O_CREAT | O_TRUNC | O_WRONLY | binary,
1223 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
1225 fd = open (fname, O_RDONLY | binary);
1227 while (fd == -1 && errno == EINTR);
1230 log_error ( for_write? _("can't create '%s': %s\n")
1231 : _("can't open '%s': %s\n"), fname, strerror(errno));
1238 set_cmd( enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd )
1240 enum cmd_and_opt_values cmd = *ret_cmd;
1242 if( !cmd || cmd == new_cmd )
1244 else if( cmd == aSign && new_cmd == aEncr )
1246 else if( cmd == aEncr && new_cmd == aSign )
1248 else if( cmd == aSign && new_cmd == aSym )
1250 else if( cmd == aSym && new_cmd == aSign )
1252 else if( cmd == aSym && new_cmd == aEncr )
1254 else if( cmd == aEncr && new_cmd == aSym )
1256 else if (cmd == aSignEncr && new_cmd == aSym)
1258 else if (cmd == aSignSym && new_cmd == aEncr)
1260 else if (cmd == aEncrSym && new_cmd == aSign)
1262 else if( ( cmd == aSign && new_cmd == aClearsign )
1263 || ( cmd == aClearsign && new_cmd == aSign ) )
1266 log_error(_("conflicting commands\n"));
1275 add_group(char *string)
1278 struct groupitem *item;
1280 /* Break off the group name */
1281 name=strsep(&string,"=");
1284 log_error(_("no = sign found in group definition '%s'\n"),name);
1288 trim_trailing_ws(name,strlen(name));
1290 /* Does this group already exist? */
1291 for(item=opt.grouplist;item;item=item->next)
1292 if(strcasecmp(item->name,name)==0)
1297 item=xmalloc(sizeof(struct groupitem));
1299 item->next=opt.grouplist;
1304 /* Break apart the values */
1305 while ((value= strsep(&string," \t")))
1308 add_to_strlist2(&item->values,value,utf8_strings);
1314 rm_group(char *name)
1316 struct groupitem *item,*last=NULL;
1318 trim_trailing_ws(name,strlen(name));
1320 for(item=opt.grouplist;item;last=item,item=item->next)
1322 if(strcasecmp(item->name,name)==0)
1325 last->next=item->next;
1327 opt.grouplist=item->next;
1329 free_strlist(item->values);
1337 /* We need to check three things.
1339 0) The homedir. It must be x00, a directory, and owned by the
1342 1) The options/gpg.conf file. Okay unless it or its containing
1343 directory is group or other writable or not owned by us. Disable
1346 2) Extensions. Same as #1.
1348 Returns true if the item is unsafe. */
1350 check_permissions (const char *path, int item)
1352 #if defined(HAVE_STAT) && !defined(HAVE_DOSISH_SYSTEM)
1353 static int homedir_cache=-1;
1355 struct stat statbuf,dirbuf;
1356 int homedir=0,ret=0,checkonly=0;
1357 int perm=0,own=0,enc_dir_perm=0,enc_dir_own=0;
1359 if(opt.no_perm_warn)
1362 assert(item==0 || item==1 || item==2);
1364 /* extensions may attach a path */
1365 if(item==2 && path[0]!=DIRSEP_C)
1367 if(strchr(path,DIRSEP_C))
1368 tmppath=make_filename(path,NULL);
1370 tmppath=make_filename(gnupg_libdir (),path,NULL);
1373 tmppath=xstrdup(path);
1375 /* If the item is located in the homedir, but isn't the homedir,
1376 don't continue if we already checked the homedir itself. This is
1377 to avoid user confusion with an extra options file warning which
1378 could be rectified if the homedir itself had proper
1380 if(item!=0 && homedir_cache>-1
1381 && ascii_strncasecmp(opt.homedir,tmppath,strlen(opt.homedir))==0)
1387 /* It's okay if the file or directory doesn't exist */
1388 if(stat(tmppath,&statbuf)!=0)
1394 /* Now check the enclosing directory. Theoretically, we could walk
1395 this test up to the root directory /, but for the sake of sanity,
1396 I'm stopping at one level down. */
1397 dir=make_dirname(tmppath);
1399 if(stat(dir,&dirbuf)!=0 || !S_ISDIR(dirbuf.st_mode))
1408 /* Assume failure */
1413 /* The homedir must be x00, a directory, and owned by the user. */
1415 if(S_ISDIR(statbuf.st_mode))
1417 if(statbuf.st_uid==getuid())
1419 if((statbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1430 else if(item==1 || item==2)
1432 /* The options or extension file. Okay unless it or its
1433 containing directory is group or other writable or not owned
1436 if(S_ISREG(statbuf.st_mode))
1438 if(statbuf.st_uid==getuid() || statbuf.st_uid==0)
1440 if((statbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1442 /* it's not writable, so make sure the enclosing
1443 directory is also not writable */
1444 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1446 if((dirbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
1456 /* it's writable, so the enclosing directory had
1457 better not let people get to it. */
1458 if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
1460 if((dirbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
1463 perm=enc_dir_perm=1; /* unclear which one to fix! */
1481 log_info(_("WARNING: unsafe ownership on"
1482 " homedir '%s'\n"),tmppath);
1484 log_info(_("WARNING: unsafe ownership on"
1485 " configuration file '%s'\n"),tmppath);
1487 log_info(_("WARNING: unsafe ownership on"
1488 " extension '%s'\n"),tmppath);
1493 log_info(_("WARNING: unsafe permissions on"
1494 " homedir '%s'\n"),tmppath);
1496 log_info(_("WARNING: unsafe permissions on"
1497 " configuration file '%s'\n"),tmppath);
1499 log_info(_("WARNING: unsafe permissions on"
1500 " extension '%s'\n"),tmppath);
1505 log_info(_("WARNING: unsafe enclosing directory ownership on"
1506 " homedir '%s'\n"),tmppath);
1508 log_info(_("WARNING: unsafe enclosing directory ownership on"
1509 " configuration file '%s'\n"),tmppath);
1511 log_info(_("WARNING: unsafe enclosing directory ownership on"
1512 " extension '%s'\n"),tmppath);
1517 log_info(_("WARNING: unsafe enclosing directory permissions on"
1518 " homedir '%s'\n"),tmppath);
1520 log_info(_("WARNING: unsafe enclosing directory permissions on"
1521 " configuration file '%s'\n"),tmppath);
1523 log_info(_("WARNING: unsafe enclosing directory permissions on"
1524 " extension '%s'\n"),tmppath);
1536 #else /*!(HAVE_STAT && !HAVE_DOSISH_SYSTEM)*/
1540 #endif /*!(HAVE_STAT && !HAVE_DOSISH_SYSTEM)*/
1544 /* Print the OpenPGP defined algo numbers. */
1546 print_algo_numbers(int (*checker)(int))
1565 print_algo_names(int (*checker)(int),const char *(*mapper)(int))
1577 es_printf ("%s",mapper(i));
1582 /* In the future, we can do all sorts of interesting configuration
1583 output here. For now, just give "group" as the Enigmail folks need
1584 it, and pubkey, cipher, hash, and compress as they may be useful
1587 list_config(char *items)
1589 int show_all = !items;
1592 struct groupitem *giter;
1595 if(!opt.with_colons)
1598 while(show_all || (name=strsep(&items," ")))
1602 if(show_all || ascii_strcasecmp(name,"group")==0)
1604 for (giter = opt.grouplist; giter; giter = giter->next)
1608 es_fprintf (es_stdout, "cfg:group:");
1609 es_write_sanitized (es_stdout, giter->name, strlen(giter->name),
1611 es_putc (':', es_stdout);
1613 for(sl=giter->values; sl; sl=sl->next)
1615 es_write_sanitized (es_stdout, sl->d, strlen (sl->d),
1627 if(show_all || ascii_strcasecmp(name,"version")==0)
1629 es_printf("cfg:version:");
1630 es_write_sanitized (es_stdout, VERSION, strlen(VERSION), ":", NULL);
1635 if(show_all || ascii_strcasecmp(name,"pubkey")==0)
1637 es_printf ("cfg:pubkey:");
1638 print_algo_numbers (build_list_pk_test_algo);
1643 if(show_all || ascii_strcasecmp(name,"pubkeyname")==0)
1645 es_printf ("cfg:pubkeyname:");
1646 print_algo_names (build_list_pk_test_algo,
1647 build_list_pk_algo_name);
1652 if(show_all || ascii_strcasecmp(name,"cipher")==0)
1654 es_printf ("cfg:cipher:");
1655 print_algo_numbers (build_list_cipher_test_algo);
1660 if (show_all || !ascii_strcasecmp (name,"ciphername"))
1662 es_printf ("cfg:ciphername:");
1663 print_algo_names (build_list_cipher_test_algo,
1664 build_list_cipher_algo_name);
1670 || ascii_strcasecmp(name,"digest")==0
1671 || ascii_strcasecmp(name,"hash")==0)
1673 es_printf ("cfg:digest:");
1674 print_algo_numbers (build_list_md_test_algo);
1680 || !ascii_strcasecmp(name,"digestname")
1681 || !ascii_strcasecmp(name,"hashname"))
1683 es_printf ("cfg:digestname:");
1684 print_algo_names (build_list_md_test_algo,
1685 build_list_md_algo_name);
1690 if(show_all || ascii_strcasecmp(name,"compress")==0)
1692 es_printf ("cfg:compress:");
1693 print_algo_numbers(check_compress_algo);
1698 if (show_all || !ascii_strcasecmp(name,"ccid-reader-id"))
1700 /* We ignore this for GnuPG 1.4 backward compatibility. */
1704 if (show_all || !ascii_strcasecmp (name,"curve"))
1706 es_printf ("cfg:curve:");
1707 for (iter=0, first=1; (s = openpgp_enum_curves (&iter)); first=0)
1708 es_printf ("%s%s", first?"":";", s);
1713 /* Curve OIDs are rarely useful and thus only printed if requested. */
1714 if (name && !ascii_strcasecmp (name,"curveoid"))
1716 es_printf ("cfg:curveoid:");
1717 for (iter=0, first=1; (s = openpgp_enum_curves (&iter)); first = 0)
1719 s = openpgp_curve_to_oid (s, NULL);
1720 es_printf ("%s%s", first?"":";", s? s:"[?]");
1730 log_error(_("unknown configuration item '%s'\n"),name);
1735 /* List options and default values in the GPG Conf format. This is a
1736 new tool distributed with gnupg 1.9.x but we also want some limited
1737 support in older gpg versions. The output is the name of the
1738 configuration file and a list of options available for editing by
1741 gpgconf_list (const char *configfile)
1743 char *configfile_esc = percent_escape (configfile, NULL);
1745 es_printf ("%s-%s.conf:%lu:\"%s\n",
1746 GPGCONF_NAME, GPG_NAME,
1747 GC_OPT_FLAG_DEFAULT,
1748 configfile_esc ? configfile_esc : "/dev/null");
1749 es_printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
1750 es_printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
1751 es_printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
1752 es_printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE);
1753 es_printf ("default-key:%lu:\n", GC_OPT_FLAG_NONE);
1754 es_printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_NONE);
1755 es_printf ("try-secret-key:%lu:\n", GC_OPT_FLAG_NONE);
1756 es_printf ("auto-key-locate:%lu:\n", GC_OPT_FLAG_NONE);
1757 es_printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE);
1758 es_printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
1759 es_printf ("group:%lu:\n", GC_OPT_FLAG_NONE);
1761 /* The next one is an info only item and should match the macros at
1762 the top of keygen.c */
1763 es_printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
1766 xfree (configfile_esc);
1771 parse_subpacket_list(char *list)
1774 byte subpackets[128],i;
1779 /* No arguments means all subpackets */
1780 memset(subpackets+1,1,sizeof(subpackets)-1);
1785 memset(subpackets,0,sizeof(subpackets));
1787 /* Merge with earlier copy */
1788 if(opt.show_subpackets)
1792 for(in=opt.show_subpackets;*in;in++)
1794 if(*in>127 || *in<1)
1797 if(!subpackets[*in])
1803 while((tok=strsep(&list," ,")))
1818 xfree(opt.show_subpackets);
1819 opt.show_subpackets=xmalloc(count+1);
1820 opt.show_subpackets[count--]=0;
1822 for(i=1;i<128 && count>=0;i++)
1824 opt.show_subpackets[count--]=i;
1831 parse_list_options(char *str)
1833 char *subpackets=""; /* something that isn't NULL */
1834 struct parse_options lopts[]=
1836 {"show-photos",LIST_SHOW_PHOTOS,NULL,
1837 N_("display photo IDs during key listings")},
1838 {"show-usage",LIST_SHOW_USAGE,NULL,
1839 N_("show key usage information during key listings")},
1840 {"show-policy-urls",LIST_SHOW_POLICY_URLS,NULL,
1841 N_("show policy URLs during signature listings")},
1842 {"show-notations",LIST_SHOW_NOTATIONS,NULL,
1843 N_("show all notations during signature listings")},
1844 {"show-std-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1845 N_("show IETF standard notations during signature listings")},
1846 {"show-standard-notations",LIST_SHOW_STD_NOTATIONS,NULL,
1848 {"show-user-notations",LIST_SHOW_USER_NOTATIONS,NULL,
1849 N_("show user-supplied notations during signature listings")},
1850 {"show-keyserver-urls",LIST_SHOW_KEYSERVER_URLS,NULL,
1851 N_("show preferred keyserver URLs during signature listings")},
1852 {"show-uid-validity",LIST_SHOW_UID_VALIDITY,NULL,
1853 N_("show user ID validity during key listings")},
1854 {"show-unusable-uids",LIST_SHOW_UNUSABLE_UIDS,NULL,
1855 N_("show revoked and expired user IDs in key listings")},
1856 {"show-unusable-subkeys",LIST_SHOW_UNUSABLE_SUBKEYS,NULL,
1857 N_("show revoked and expired subkeys in key listings")},
1858 {"show-keyring",LIST_SHOW_KEYRING,NULL,
1859 N_("show the keyring name in key listings")},
1860 {"show-sig-expire",LIST_SHOW_SIG_EXPIRE,NULL,
1861 N_("show expiration dates during signature listings")},
1862 {"show-sig-subpackets",LIST_SHOW_SIG_SUBPACKETS,NULL,
1867 /* C99 allows for non-constant initializers, but we'd like to
1868 compile everywhere, so fill in the show-sig-subpackets argument
1869 here. Note that if the parse_options array changes, we'll have
1870 to change the subscript here. */
1871 lopts[12].value=&subpackets;
1873 if(parse_options(str,&opt.list_options,lopts,1))
1875 if(opt.list_options&LIST_SHOW_SIG_SUBPACKETS)
1877 /* Unset so users can pass multiple lists in. */
1878 opt.list_options&=~LIST_SHOW_SIG_SUBPACKETS;
1879 if(!parse_subpacket_list(subpackets))
1882 else if(subpackets==NULL && opt.show_subpackets)
1884 /* User did 'no-show-subpackets' */
1885 xfree(opt.show_subpackets);
1886 opt.show_subpackets=NULL;
1896 /* Collapses argc/argv into a single string that must be freed */
1898 collapse_args(int argc,char *argv[])
1901 int i,first=1,len=0;
1905 len+=strlen(argv[i])+2;
1906 str=xrealloc(str,len);
1915 strcat(str,argv[i]);
1922 #ifndef NO_TRUST_MODELS
1924 parse_trust_model(const char *model)
1926 if(ascii_strcasecmp(model,"pgp")==0)
1927 opt.trust_model=TM_PGP;
1928 else if(ascii_strcasecmp(model,"classic")==0)
1929 opt.trust_model=TM_CLASSIC;
1930 else if(ascii_strcasecmp(model,"always")==0)
1931 opt.trust_model=TM_ALWAYS;
1932 else if(ascii_strcasecmp(model,"direct")==0)
1933 opt.trust_model=TM_DIRECT;
1934 else if(ascii_strcasecmp(model,"auto")==0)
1935 opt.trust_model=TM_AUTO;
1937 log_error("unknown trust model '%s'\n",model);
1939 #endif /*NO_TRUST_MODELS*/
1942 /* This fucntion called to initialized a new control object. It is
1943 assumed that this object has been zeroed out before calling this
1946 gpg_init_default_ctrl (ctrl_t ctrl)
1952 /* This function is called to deinitialize a control object. It is
1955 gpg_deinit_default_ctrl (ctrl_t ctrl)
1957 gpg_dirmngr_deinit_session_data (ctrl);
1962 get_default_configname (void)
1964 char *configname = NULL;
1965 char *name = xstrdup (GPG_NAME EXTSEP_S "conf-" SAFE_VERSION);
1966 char *ver = &name[strlen (GPG_NAME EXTSEP_S "conf-")];
1977 if ((tok = strrchr (ver, SAFE_VERSION_DASH)))
1979 else if ((tok = strrchr (ver, SAFE_VERSION_DOT)))
1985 configname = make_filename (opt.homedir, name, NULL);
1987 while (access (configname, R_OK));
1992 configname = make_filename (opt.homedir, GPG_NAME EXTSEP_S "conf", NULL);
1993 if (! access (configname, R_OK))
1995 /* Print a warning when both config files are present. */
1996 char *p = make_filename (opt.homedir, "options", NULL);
1997 if (! access (p, R_OK))
1998 log_info (_("Note: old default options file '%s' ignored\n"), p);
2003 /* Use the old default only if it exists. */
2004 char *p = make_filename (opt.homedir, "options", NULL);
2005 if (!access (p, R_OK))
2019 main (int argc, char **argv)
2021 ARGPARSE_ARGS pargs;
2029 strlist_t sl, remusr= NULL, locusr=NULL;
2030 strlist_t nrings = NULL;
2031 armor_filter_context_t *afx = NULL;
2032 int detached_sig = 0;
2033 FILE *configfp = NULL;
2034 char *configname = NULL;
2035 char *save_configname = NULL;
2036 char *default_configname = NULL;
2037 unsigned configlineno;
2038 int parse_debug = 0;
2039 int default_config = 1;
2040 int default_keyring = 1;
2043 char *logfile = NULL;
2044 int use_random_seed = 1;
2045 enum cmd_and_opt_values cmd = 0;
2046 const char *debug_level = NULL;
2047 #ifndef NO_TRUST_MODELS
2048 const char *trustdb_name = NULL;
2049 #endif /*!NO_TRUST_MODELS*/
2050 char *def_cipher_string = NULL;
2051 char *def_digest_string = NULL;
2052 char *compress_algo_string = NULL;
2053 char *cert_digest_string = NULL;
2054 char *s2k_cipher_string = NULL;
2055 char *s2k_digest_string = NULL;
2056 char *pers_cipher_list = NULL;
2057 char *pers_digest_list = NULL;
2058 char *pers_compress_list = NULL;
2062 int fpr_maybe_cmd = 0; /* --fingerprint maybe a command. */
2063 int any_explicit_recipient = 0;
2064 int require_secmem=0,got_secmem=0;
2065 struct assuan_malloc_hooks malloc_hooks;
2070 #endif /* __riscos__ */
2073 /* Please note that we may running SUID(ROOT), so be very CAREFUL
2074 when adding any stuff between here and the call to
2075 secmem_init() somewhere after the option parsing. */
2076 early_system_init ();
2077 gnupg_reopen_std (GPG_NAME);
2079 gnupg_rl_initialize ();
2080 set_strusage (my_strusage);
2081 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
2082 log_set_prefix (GPG_NAME, 1);
2084 /* Make sure that our subsystems are ready. */
2086 init_common_subsystems (&argc, &argv);
2088 /* Check that the libraries are suitable. Do it right here because the
2089 option parsing may need services of the library. */
2090 if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
2092 log_fatal ( _("libgcrypt is too old (need %s, have %s)\n"),
2093 NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
2096 /* Use our own logging handler for Libcgrypt. */
2097 setup_libgcrypt_logging ();
2099 /* Put random number into secure memory */
2100 gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
2102 may_coredump = disable_core_dumps();
2104 gnupg_init_signals (0, emergency_cleanup);
2106 dotlock_create (NULL, 0); /* Register lock file cleanup. */
2109 opt.session_env = session_env_new ();
2110 if (!opt.session_env)
2111 log_fatal ("error allocating session environment block: %s\n",
2114 opt.command_fd = -1; /* no command fd */
2115 opt.compress_level = -1; /* defaults to standard compress level */
2116 opt.bz2_compress_level = -1; /* defaults to standard compress level */
2117 /* note: if you change these lines, look at oOpenPGP */
2118 opt.def_cipher_algo = 0;
2119 opt.def_digest_algo = 0;
2120 opt.cert_digest_algo = 0;
2121 opt.compress_algo = -1; /* defaults to DEFAULT_COMPRESS_ALGO */
2122 opt.s2k_mode = 3; /* iterated+salted */
2123 opt.s2k_count = 0; /* Auto-calibrate when needed. */
2124 opt.s2k_cipher_algo = DEFAULT_CIPHER_ALGO;
2125 opt.completes_needed = 1;
2126 opt.marginals_needed = 3;
2127 opt.max_cert_depth = 5;
2128 opt.escape_from = 1;
2129 opt.flags.require_cross_cert = 1;
2130 opt.import_options = 0;
2131 opt.export_options = EXPORT_ATTRIBUTES;
2132 opt.keyserver_options.import_options = IMPORT_REPAIR_PKS_SUBKEY_BUG;
2133 opt.keyserver_options.export_options = EXPORT_ATTRIBUTES;
2134 opt.keyserver_options.options = KEYSERVER_HONOR_PKA_RECORD;
2135 opt.verify_options = (LIST_SHOW_UID_VALIDITY
2136 | VERIFY_SHOW_POLICY_URLS
2137 | VERIFY_SHOW_STD_NOTATIONS
2138 | VERIFY_SHOW_KEYSERVER_URLS);
2139 opt.list_options = LIST_SHOW_UID_VALIDITY;
2140 #ifdef NO_TRUST_MODELS
2141 opt.trust_model = TM_ALWAYS;
2143 opt.trust_model = TM_AUTO;
2145 opt.mangle_dos_filenames = 0;
2146 opt.min_cert_level = 2;
2147 set_screen_dimensions ();
2148 opt.keyid_format = KF_SHORT;
2149 opt.def_sig_expire = "0";
2150 opt.def_cert_expire = "0";
2151 set_homedir (default_homedir ());
2152 opt.passphrase_repeat = 1;
2153 opt.emit_version = 1; /* Limit to the major number. */
2155 /* Check whether we have a config file on the command line. */
2160 pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
2161 while( arg_parse( &pargs, opts) ) {
2162 if( pargs.r_opt == oDebug || pargs.r_opt == oDebugAll )
2164 else if (pargs.r_opt == oDebugIOLBF)
2165 es_setvbuf (es_stdout, NULL, _IOLBF, 0);
2166 else if( pargs.r_opt == oOptions ) {
2167 /* yes there is one, so we do not try the default one, but
2168 * read the option file when it is encountered at the commandline
2172 else if( pargs.r_opt == oNoOptions )
2174 default_config = 0; /* --no-options */
2175 opt.no_homedir_creation = 1;
2177 else if( pargs.r_opt == oHomedir )
2178 set_homedir ( pargs.r.ret_str );
2179 else if( pargs.r_opt == oNoPermissionWarn )
2181 else if (pargs.r_opt == oStrict )
2185 else if (pargs.r_opt == oNoStrict )
2191 #ifdef HAVE_DOSISH_SYSTEM
2192 if ( strchr (opt.homedir,'\\') ) {
2193 char *d, *buf = xmalloc (strlen (opt.homedir)+1);
2194 const char *s = opt.homedir;
2195 for (d=buf,s=opt.homedir; *s; s++)
2197 *d++ = *s == '\\'? '/': *s;
2198 #ifdef HAVE_W32_SYSTEM
2199 if (s[1] && IsDBCSLeadByte (*s))
2208 /* Initialize the secure memory. */
2209 if (!gcry_control (GCRYCTL_INIT_SECMEM, SECMEM_BUFFER_SIZE, 0))
2211 #if defined(HAVE_GETUID) && defined(HAVE_GETEUID)
2212 /* There should be no way to get to this spot while still carrying
2213 setuid privs. Just in case, bomb out if we are. */
2214 if ( getuid () != geteuid () )
2219 /* Okay, we are now working under our real uid */
2221 /* malloc hooks go here ... */
2222 malloc_hooks.malloc = gcry_malloc;
2223 malloc_hooks.realloc = gcry_realloc;
2224 malloc_hooks.free = gcry_free;
2225 assuan_set_malloc_hooks (&malloc_hooks);
2226 assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
2227 setup_libassuan_logging (&opt.debug);
2229 /* Try for a version specific config file first */
2230 default_configname = get_default_configname ();
2232 configname = xstrdup (default_configname);
2238 pargs.flags= ARGPARSE_FLAG_KEEP;
2240 /* By this point we have a homedir, and cannot change it. */
2241 check_permissions(opt.homedir,0);
2245 if(check_permissions(configname,1))
2247 /* If any options file is unsafe, then disable any external
2248 programs for keyserver calls or photo IDs. Since the
2249 external program to call is set in the options file, a
2250 unsafe options file can lead to an arbitrary program
2257 configfp = fopen( configname, "r" );
2258 if (configfp && is_secured_file (fileno (configfp)))
2262 gpg_err_set_errno (EPERM);
2265 if( default_config ) {
2267 log_info(_("Note: no default option file '%s'\n"),
2271 log_error(_("option file '%s': %s\n"),
2272 configname, strerror(errno) );
2275 xfree(configname); configname = NULL;
2277 if( parse_debug && configname )
2278 log_info(_("reading options from '%s'\n"), configname );
2282 while( optfile_parse( configfp, configname, &configlineno,
2285 switch( pargs.r_opt )
2289 case aListGcryptConfig:
2301 #ifdef ENABLE_CARD_SUPPORT
2305 #endif /* ENABLE_CARD_SUPPORT*/
2310 case aExportSecretSub:
2321 case aUpdateTrustDB:
2323 case aListTrustPath:
2328 case aQuickLSignKey:
2334 case aExportOwnerTrust:
2335 case aImportOwnerTrust:
2336 case aRebuildKeydbCaches:
2337 set_cmd (&cmd, pargs.r_opt);
2343 case aDeleteSecretKeys:
2344 case aDeleteSecretAndPublicKeys:
2347 set_cmd (&cmd, pargs.r_opt);
2351 case aDetachedSign: detached_sig = 1; set_cmd( &cmd, aSign ); break;
2353 case aDecryptFiles: multifile=1; /* fall through */
2354 case aDecrypt: set_cmd( &cmd, aDecrypt); break;
2356 case aEncrFiles: multifile=1; /* fall through */
2357 case aEncr: set_cmd( &cmd, aEncr); break;
2359 case aVerifyFiles: multifile=1; /* fall through */
2360 case aVerify: set_cmd( &cmd, aVerify); break;
2363 set_cmd (&cmd, pargs.r_opt);
2367 case oArmor: opt.armor = 1; opt.no_armor=0; break;
2368 case oOutput: opt.outfile = pargs.r.ret_str; break;
2369 case oMaxOutput: opt.max_output = pargs.r.ret_ulong; break;
2370 case oQuiet: opt.quiet = 1; break;
2371 case oNoTTY: tty_no_terminal(1); break;
2372 case oDryRun: opt.dry_run = 1; break;
2373 case oInteractive: opt.interactive = 1; break;
2376 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2377 opt.list_options|=LIST_SHOW_UNUSABLE_UIDS;
2378 opt.list_options|=LIST_SHOW_UNUSABLE_SUBKEYS;
2386 case oUseAgent: /* Dummy. */
2390 obsolete_option (configname, configlineno, "no-use-agent");
2393 obsolete_option (configname, configlineno, "gpg-agent-info");
2396 obsolete_scdaemon_option (configname, configlineno, "reader-port");
2399 obsolete_scdaemon_option (configname, configlineno, "ctapi-driver");
2402 obsolete_scdaemon_option (configname, configlineno, "pcsc-driver");
2405 obsolete_scdaemon_option (configname, configlineno, "disable-ccid");
2407 case oHonorHttpProxy:
2408 obsolete_option (configname, configlineno, "honor-http-proxy");
2411 case oAnswerYes: opt.answer_yes = 1; break;
2412 case oAnswerNo: opt.answer_no = 1; break;
2413 case oKeyring: append_to_strlist( &nrings, pargs.r.ret_str); break;
2414 case oPrimaryKeyring:
2415 sl = append_to_strlist (&nrings, pargs.r.ret_str);
2416 sl->flags = KEYDB_RESOURCE_FLAG_PRIMARY;
2419 deprecated_warning(configname,configlineno,"--show-keyring",
2420 "--list-options ","show-keyring");
2421 opt.list_options|=LIST_SHOW_KEYRING;
2424 case oDebug: opt.debug |= pargs.r.ret_ulong; break;
2425 case oDebugAll: opt.debug = ~0; break;
2426 case oDebugLevel: debug_level = pargs.r.ret_str; break;
2428 case oDebugIOLBF: break; /* Already set in pre-parse step. */
2431 set_status_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
2434 set_status_fd ( open_info_file (pargs.r.ret_str, 1, 0) );
2437 set_attrib_fd ( translate_sys2libc_fd_int (pargs.r.ret_int, 1) );
2439 case oAttributeFile:
2440 set_attrib_fd ( open_info_file (pargs.r.ret_str, 1, 1) );
2443 log_set_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1));
2446 logfile = pargs.r.ret_str;
2449 case oWithFingerprint:
2450 opt.with_fingerprint = 1;
2453 case oWithICAOSpelling:
2454 opt.with_icao_spelling = 1;
2462 opt.with_keygrip = 1;
2466 opt.with_secret = 1;
2469 case oSecretKeyring:
2470 /* Ignore this old option. */
2474 /* config files may not be nested (silently ignore them) */
2477 configname = xstrdup(pargs.r.ret_str);
2481 case oNoArmor: opt.no_armor=1; opt.armor=0; break;
2482 case oNoDefKeyring: default_keyring = 0; break;
2483 case oNoGreeting: nogreeting = 1; break;
2486 gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
2490 gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
2492 case oEmitVersion: opt.emit_version++; break;
2493 case oNoEmitVersion: opt.emit_version=0; break;
2494 case oCompletesNeeded: opt.completes_needed = pargs.r.ret_int; break;
2495 case oMarginalsNeeded: opt.marginals_needed = pargs.r.ret_int; break;
2496 case oMaxCertDepth: opt.max_cert_depth = pargs.r.ret_int; break;
2498 #ifndef NO_TRUST_MODELS
2499 case oTrustDBName: trustdb_name = pargs.r.ret_str; break;
2501 #endif /*!NO_TRUST_MODELS*/
2502 case oDefaultKey: opt.def_secret_key = pargs.r.ret_str; break;
2504 if( *pargs.r.ret_str )
2505 opt.def_recipient = make_username(pargs.r.ret_str);
2507 case oDefRecipientSelf:
2508 xfree(opt.def_recipient); opt.def_recipient = NULL;
2509 opt.def_recipient_self = 1;
2511 case oNoDefRecipient:
2512 xfree(opt.def_recipient); opt.def_recipient = NULL;
2513 opt.def_recipient_self = 0;
2515 case oNoOptions: opt.no_homedir_creation = 1; break; /* no-options */
2516 case oHomedir: break;
2517 case oNoBatch: opt.batch = 0; break;
2519 case oWithKeyData: opt.with_key_data=1; /*FALLTHRU*/
2520 case oWithColons: opt.with_colons=':'; break;
2522 case oWithSigCheck: opt.check_sigs = 1; /*FALLTHRU*/
2523 case oWithSigList: opt.list_sigs = 1; break;
2525 case oSkipVerify: opt.skip_verify=1; break;
2527 case oSkipHiddenRecipients: opt.skip_hidden_recipients = 1; break;
2528 case oNoSkipHiddenRecipients: opt.skip_hidden_recipients = 0; break;
2530 case aListSecretKeys: set_cmd( &cmd, aListSecretKeys); break;
2532 #ifndef NO_TRUST_MODELS
2533 /* There are many programs (like mutt) that call gpg with
2534 --always-trust so keep this option around for a long
2536 case oAlwaysTrust: opt.trust_model=TM_ALWAYS; break;
2538 parse_trust_model(pargs.r.ret_str);
2540 #endif /*!NO_TRUST_MODELS*/
2542 case oForceOwnertrust:
2543 log_info(_("Note: %s is not for normal use!\n"),
2544 "--force-ownertrust");
2545 opt.force_ownertrust=string_to_trust_value(pargs.r.ret_str);
2546 if(opt.force_ownertrust==-1)
2548 log_error("invalid ownertrust '%s'\n",pargs.r.ret_str);
2549 opt.force_ownertrust=0;
2552 case oLoadExtension:
2553 /* Dummy so that gpg 1.4 conf files can work. Should
2554 eventually be removed. */
2558 /* This is effectively the same as RFC2440, but with
2559 "--enable-dsa2 --no-rfc2440-text --escape-from-lines
2560 --require-cross-certification". */
2561 opt.compliance = CO_RFC4880;
2563 opt.flags.require_cross_cert = 1;
2564 opt.rfc2440_text = 0;
2565 opt.allow_non_selfsigned_uid = 1;
2566 opt.allow_freeform_uid = 1;
2567 opt.escape_from = 1;
2568 opt.not_dash_escaped = 0;
2569 opt.def_cipher_algo = 0;
2570 opt.def_digest_algo = 0;
2571 opt.cert_digest_algo = 0;
2572 opt.compress_algo = -1;
2573 opt.s2k_mode = 3; /* iterated+salted */
2574 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2575 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2578 opt.compliance = CO_RFC2440;
2580 opt.rfc2440_text = 1;
2581 opt.allow_non_selfsigned_uid = 1;
2582 opt.allow_freeform_uid = 1;
2583 opt.escape_from = 0;
2584 opt.not_dash_escaped = 0;
2585 opt.def_cipher_algo = 0;
2586 opt.def_digest_algo = 0;
2587 opt.cert_digest_algo = 0;
2588 opt.compress_algo = -1;
2589 opt.s2k_mode = 3; /* iterated+salted */
2590 opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
2591 opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
2593 case oPGP6: opt.compliance = CO_PGP6; break;
2594 case oPGP7: opt.compliance = CO_PGP7; break;
2595 case oPGP8: opt.compliance = CO_PGP8; break;
2596 case oGnuPG: opt.compliance = CO_GNUPG; break;
2597 case oRFC2440Text: opt.rfc2440_text=1; break;
2598 case oNoRFC2440Text: opt.rfc2440_text=0; break;
2601 opt.set_filename = pargs.r.ret_str;
2603 opt.set_filename = native_to_utf8(pargs.r.ret_str);
2605 case oForYourEyesOnly: eyes_only = 1; break;
2606 case oNoForYourEyesOnly: eyes_only = 0; break;
2608 add_policy_url(pargs.r.ret_str,0);
2609 add_policy_url(pargs.r.ret_str,1);
2611 case oSigPolicyURL: add_policy_url(pargs.r.ret_str,0); break;
2612 case oCertPolicyURL: add_policy_url(pargs.r.ret_str,1); break;
2613 case oShowPolicyURL:
2614 deprecated_warning(configname,configlineno,"--show-policy-url",
2615 "--list-options ","show-policy-urls");
2616 deprecated_warning(configname,configlineno,"--show-policy-url",
2617 "--verify-options ","show-policy-urls");
2618 opt.list_options|=LIST_SHOW_POLICY_URLS;
2619 opt.verify_options|=VERIFY_SHOW_POLICY_URLS;
2621 case oNoShowPolicyURL:
2622 deprecated_warning(configname,configlineno,"--no-show-policy-url",
2623 "--list-options ","no-show-policy-urls");
2624 deprecated_warning(configname,configlineno,"--no-show-policy-url",
2625 "--verify-options ","no-show-policy-urls");
2626 opt.list_options&=~LIST_SHOW_POLICY_URLS;
2627 opt.verify_options&=~VERIFY_SHOW_POLICY_URLS;
2629 case oSigKeyserverURL: add_keyserver_url(pargs.r.ret_str,0); break;
2630 case oUseEmbeddedFilename:
2631 opt.flags.use_embedded_filename=1;
2633 case oNoUseEmbeddedFilename:
2634 opt.flags.use_embedded_filename=0;
2637 if(pargs.r.ret_str[0])
2638 append_to_strlist(&opt.comments,pargs.r.ret_str);
2640 case oDefaultComment:
2641 deprecated_warning(configname,configlineno,
2642 "--default-comment","--no-comments","");
2645 free_strlist(opt.comments);
2648 case oThrowKeyids: opt.throw_keyids = 1; break;
2649 case oNoThrowKeyids: opt.throw_keyids = 0; break;
2651 deprecated_warning(configname,configlineno,"--show-photos",
2652 "--list-options ","show-photos");
2653 deprecated_warning(configname,configlineno,"--show-photos",
2654 "--verify-options ","show-photos");
2655 opt.list_options|=LIST_SHOW_PHOTOS;
2656 opt.verify_options|=VERIFY_SHOW_PHOTOS;
2659 deprecated_warning(configname,configlineno,"--no-show-photos",
2660 "--list-options ","no-show-photos");
2661 deprecated_warning(configname,configlineno,"--no-show-photos",
2662 "--verify-options ","no-show-photos");
2663 opt.list_options&=~LIST_SHOW_PHOTOS;
2664 opt.verify_options&=~VERIFY_SHOW_PHOTOS;
2666 case oPhotoViewer: opt.photo_viewer = pargs.r.ret_str; break;
2668 case oForceMDC: opt.force_mdc = 1; break;
2669 case oNoForceMDC: opt.force_mdc = 0; break;
2670 case oDisableMDC: opt.disable_mdc = 1; break;
2671 case oNoDisableMDC: opt.disable_mdc = 0; break;
2672 case oS2KMode: opt.s2k_mode = pargs.r.ret_int; break;
2673 case oS2KDigest: s2k_digest_string = xstrdup(pargs.r.ret_str); break;
2674 case oS2KCipher: s2k_cipher_string = xstrdup(pargs.r.ret_str); break;
2676 if (pargs.r.ret_int)
2677 opt.s2k_count = encode_s2k_iterations (pargs.r.ret_int);
2679 opt.s2k_count = 0; /* Auto-calibrate when needed. */
2681 case oNoEncryptTo: opt.no_encrypt_to = 1; break;
2682 case oEncryptTo: /* store the recipient in the second list */
2683 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2686 case oHiddenEncryptTo: /* store the recipient in the second list */
2687 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2690 case oRecipient: /* store the recipient */
2691 add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2692 any_explicit_recipient = 1;
2694 case oHiddenRecipient: /* store the recipient with a flag */
2695 sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
2697 any_explicit_recipient = 1;
2701 add_to_strlist2 (&opt.secret_keys_to_try,
2702 pargs.r.ret_str, utf8_strings);
2705 case oTextmodeShort: opt.textmode = 2; break;
2706 case oTextmode: opt.textmode=1; break;
2707 case oNoTextmode: opt.textmode=0; break;
2708 case oExpert: opt.expert = 1; break;
2709 case oNoExpert: opt.expert = 0; break;
2711 if(*pargs.r.ret_str!='\0')
2713 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
2714 log_error(_("'%s' is not a valid signature expiration\n"),
2717 opt.def_sig_expire=pargs.r.ret_str;
2720 case oAskSigExpire: opt.ask_sig_expire = 1; break;
2721 case oNoAskSigExpire: opt.ask_sig_expire = 0; break;
2722 case oDefCertExpire:
2723 if(*pargs.r.ret_str!='\0')
2725 if(parse_expire_string(pargs.r.ret_str)==(u32)-1)
2726 log_error(_("'%s' is not a valid signature expiration\n"),
2729 opt.def_cert_expire=pargs.r.ret_str;
2732 case oAskCertExpire: opt.ask_cert_expire = 1; break;
2733 case oNoAskCertExpire: opt.ask_cert_expire = 0; break;
2734 case oDefCertLevel: opt.def_cert_level=pargs.r.ret_int; break;
2735 case oMinCertLevel: opt.min_cert_level=pargs.r.ret_int; break;
2736 case oAskCertLevel: opt.ask_cert_level = 1; break;
2737 case oNoAskCertLevel: opt.ask_cert_level = 0; break;
2738 case oLocalUser: /* store the local users */
2739 add_to_strlist2( &locusr, pargs.r.ret_str, utf8_strings );
2742 /* this is the -z command line option */
2743 opt.compress_level = opt.bz2_compress_level = pargs.r.ret_int;
2745 case oCompressLevel: opt.compress_level = pargs.r.ret_int; break;
2746 case oBZ2CompressLevel: opt.bz2_compress_level = pargs.r.ret_int; break;
2747 case oBZ2DecompressLowmem: opt.bz2_decompress_lowmem=1; break;
2749 set_passphrase_from_string(pargs.r.ret_str);
2752 pwfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
2754 case oPassphraseFile:
2755 pwfd = open_info_file (pargs.r.ret_str, 0, 1);
2757 case oPassphraseRepeat:
2758 opt.passphrase_repeat = pargs.r.ret_int;
2762 opt.pinentry_mode = parse_pinentry_mode (pargs.r.ret_str);
2763 if (opt.pinentry_mode == -1)
2764 log_error (_("invalid pinentry mode '%s'\n"), pargs.r.ret_str);
2768 opt.command_fd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
2771 opt.command_fd = open_info_file (pargs.r.ret_str, 0, 1);
2774 def_cipher_string = xstrdup(pargs.r.ret_str);
2777 def_digest_string = xstrdup(pargs.r.ret_str);
2780 /* If it is all digits, stick a Z in front of it for
2781 later. This is for backwards compatibility with
2782 versions that took the compress algorithm number. */
2784 char *pt=pargs.r.ret_str;
2787 if (!isascii (*pt) || !isdigit (*pt))
2795 compress_algo_string=xmalloc(strlen(pargs.r.ret_str)+2);
2796 strcpy(compress_algo_string,"Z");
2797 strcat(compress_algo_string,pargs.r.ret_str);
2800 compress_algo_string = xstrdup(pargs.r.ret_str);
2803 case oCertDigestAlgo:
2804 cert_digest_string = xstrdup(pargs.r.ret_str);
2808 gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
2811 case oRequireSecmem: require_secmem=1; break;
2812 case oNoRequireSecmem: require_secmem=0; break;
2813 case oNoPermissionWarn: opt.no_perm_warn=1; break;
2814 case oNoMDCWarn: opt.no_mdc_warn=1; break;
2815 case oDisplayCharset:
2816 if( set_native_charset( pargs.r.ret_str ) )
2817 log_error(_("'%s' is not a valid character set\n"),
2820 case oNotDashEscaped: opt.not_dash_escaped = 1; break;
2821 case oEscapeFrom: opt.escape_from = 1; break;
2822 case oNoEscapeFrom: opt.escape_from = 0; break;
2823 case oLockOnce: opt.lock_once = 1; break;
2830 #else /* __riscos__ */
2831 riscos_not_implemented("lock-multiple");
2832 #endif /* __riscos__ */
2836 keyserver_spec_t keyserver;
2837 keyserver = parse_keyserver_uri (pargs.r.ret_str, 0);
2839 log_error (_("could not parse keyserver URL\n"));
2842 /* We only support a single keyserver. Later ones
2843 override earlier ones. (Since we parse the
2844 config file first and then the command line
2845 arguments, the command line takes
2848 free_keyserver_spec (opt.keyserver);
2849 opt.keyserver = keyserver;
2853 case oKeyServerOptions:
2854 if(!parse_keyserver_options(pargs.r.ret_str))
2857 log_error(_("%s:%d: invalid keyserver options\n"),
2858 configname,configlineno);
2860 log_error(_("invalid keyserver options\n"));
2863 case oImportOptions:
2864 if(!parse_import_options(pargs.r.ret_str,&opt.import_options,1))
2867 log_error(_("%s:%d: invalid import options\n"),
2868 configname,configlineno);
2870 log_error(_("invalid import options\n"));
2873 case oExportOptions:
2874 if(!parse_export_options(pargs.r.ret_str,&opt.export_options,1))
2877 log_error(_("%s:%d: invalid export options\n"),
2878 configname,configlineno);
2880 log_error(_("invalid export options\n"));
2884 if(!parse_list_options(pargs.r.ret_str))
2887 log_error(_("%s:%d: invalid list options\n"),
2888 configname,configlineno);
2890 log_error(_("invalid list options\n"));
2893 case oVerifyOptions:
2895 struct parse_options vopts[]=
2897 {"show-photos",VERIFY_SHOW_PHOTOS,NULL,
2898 N_("display photo IDs during signature verification")},
2899 {"show-policy-urls",VERIFY_SHOW_POLICY_URLS,NULL,
2900 N_("show policy URLs during signature verification")},
2901 {"show-notations",VERIFY_SHOW_NOTATIONS,NULL,
2902 N_("show all notations during signature verification")},
2903 {"show-std-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
2904 N_("show IETF standard notations during signature verification")},
2905 {"show-standard-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
2907 {"show-user-notations",VERIFY_SHOW_USER_NOTATIONS,NULL,
2908 N_("show user-supplied notations during signature verification")},
2909 {"show-keyserver-urls",VERIFY_SHOW_KEYSERVER_URLS,NULL,
2910 N_("show preferred keyserver URLs during signature verification")},
2911 {"show-uid-validity",VERIFY_SHOW_UID_VALIDITY,NULL,
2912 N_("show user ID validity during signature verification")},
2913 {"show-unusable-uids",VERIFY_SHOW_UNUSABLE_UIDS,NULL,
2914 N_("show revoked and expired user IDs in signature verification")},
2915 {"show-primary-uid-only",VERIFY_SHOW_PRIMARY_UID_ONLY,NULL,
2916 N_("show only the primary user ID in signature verification")},
2917 {"pka-lookups",VERIFY_PKA_LOOKUPS,NULL,
2918 N_("validate signatures with PKA data")},
2919 {"pka-trust-increase",VERIFY_PKA_TRUST_INCREASE,NULL,
2920 N_("elevate the trust of signatures with valid PKA data")},
2924 if(!parse_options(pargs.r.ret_str,&opt.verify_options,vopts,1))
2927 log_error(_("%s:%d: invalid verify options\n"),
2928 configname,configlineno);
2930 log_error(_("invalid verify options\n"));
2934 case oTempDir: opt.temp_dir=pargs.r.ret_str; break;
2936 if(set_exec_path(pargs.r.ret_str))
2937 log_error(_("unable to set exec-path to %s\n"),pargs.r.ret_str);
2939 opt.exec_path_set=1;
2942 add_notation_data( pargs.r.ret_str, 0 );
2943 add_notation_data( pargs.r.ret_str, 1 );
2945 case oSigNotation: add_notation_data( pargs.r.ret_str, 0 ); break;
2946 case oCertNotation: add_notation_data( pargs.r.ret_str, 1 ); break;
2948 deprecated_warning(configname,configlineno,"--show-notation",
2949 "--list-options ","show-notations");
2950 deprecated_warning(configname,configlineno,"--show-notation",
2951 "--verify-options ","show-notations");
2952 opt.list_options|=LIST_SHOW_NOTATIONS;
2953 opt.verify_options|=VERIFY_SHOW_NOTATIONS;
2955 case oNoShowNotation:
2956 deprecated_warning(configname,configlineno,"--no-show-notation",
2957 "--list-options ","no-show-notations");
2958 deprecated_warning(configname,configlineno,"--no-show-notation",
2959 "--verify-options ","no-show-notations");
2960 opt.list_options&=~LIST_SHOW_NOTATIONS;
2961 opt.verify_options&=~VERIFY_SHOW_NOTATIONS;
2963 case oUtf8Strings: utf8_strings = 1; break;
2964 case oNoUtf8Strings: utf8_strings = 0; break;
2965 case oDisableCipherAlgo:
2967 int algo = string_to_cipher_algo (pargs.r.ret_str);
2968 gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
2971 case oDisablePubkeyAlgo:
2973 int algo = gcry_pk_map_name (pargs.r.ret_str);
2974 gcry_pk_ctl (GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
2977 case oNoSigCache: opt.no_sig_cache = 1; break;
2978 case oNoSigCreateCheck: opt.no_sig_create_check = 1; break;
2979 case oAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid = 1; break;
2980 case oNoAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid=0; break;
2981 case oAllowFreeformUID: opt.allow_freeform_uid = 1; break;
2982 case oNoAllowFreeformUID: opt.allow_freeform_uid = 0; break;
2983 case oNoLiteral: opt.no_literal = 1; break;
2984 case oSetFilesize: opt.set_filesize = pargs.r.ret_ulong; break;
2985 case oFastListMode: opt.fast_list_mode = 1; break;
2986 case oFixedListMode: /* Dummy */ break;
2987 case oLegacyListMode: opt.legacy_list_mode = 1; break;
2988 case oPrintPKARecords: opt.print_pka_records = 1; break;
2989 case oListOnly: opt.list_only=1; break;
2990 case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
2991 case oIgnoreValidFrom: opt.ignore_valid_from = 1; break;
2992 case oIgnoreCrcError: opt.ignore_crc_error = 1; break;
2993 case oIgnoreMDCError: opt.ignore_mdc_error = 1; break;
2994 case oNoRandomSeedFile: use_random_seed = 0; break;
2995 case oAutoKeyRetrieve:
2996 case oNoAutoKeyRetrieve:
2997 if(pargs.r_opt==oAutoKeyRetrieve)
2998 opt.keyserver_options.options|=KEYSERVER_AUTO_KEY_RETRIEVE;
3000 opt.keyserver_options.options&=~KEYSERVER_AUTO_KEY_RETRIEVE;
3002 deprecated_warning(configname,configlineno,
3003 pargs.r_opt==oAutoKeyRetrieve?"--auto-key-retrieve":
3004 "--no-auto-key-retrieve","--keyserver-options ",
3005 pargs.r_opt==oAutoKeyRetrieve?"auto-key-retrieve":
3006 "no-auto-key-retrieve");
3008 case oShowSessionKey: opt.show_session_key = 1; break;
3009 case oOverrideSessionKey:
3010 opt.override_session_key = pargs.r.ret_str;
3013 deprecated_warning(configname,configlineno,"--merge-only",
3014 "--import-options ","merge-only");
3015 opt.import_options|=IMPORT_MERGE_ONLY;
3017 case oAllowSecretKeyImport: /* obsolete */ break;
3018 case oTryAllSecrets: opt.try_all_secrets = 1; break;
3019 case oTrustedKey: register_trusted_key( pargs.r.ret_str ); break;
3020 case oEnableSpecialFilenames:
3021 iobuf_enable_special_filenames (1);
3023 case oNoExpensiveTrustChecks: opt.no_expensive_trust_checks=1; break;
3024 case oAutoCheckTrustDB: opt.no_auto_check_trustdb=0; break;
3025 case oNoAutoCheckTrustDB: opt.no_auto_check_trustdb=1; break;
3026 case oPreservePermissions: opt.preserve_permissions=1; break;
3027 case oDefaultPreferenceList:
3028 opt.def_preference_list = pargs.r.ret_str;
3030 case oDefaultKeyserverURL:
3032 keyserver_spec_t keyserver;
3033 keyserver = parse_keyserver_uri (pargs.r.ret_str,1 );
3035 log_error (_("could not parse keyserver URL\n"));
3037 free_keyserver_spec (keyserver);
3039 opt.def_keyserver_url = pargs.r.ret_str;
3042 case oPersonalCipherPreferences:
3043 pers_cipher_list=pargs.r.ret_str;
3045 case oPersonalDigestPreferences:
3046 pers_digest_list=pargs.r.ret_str;
3048 case oPersonalCompressPreferences:
3049 pers_compress_list=pargs.r.ret_str;
3051 case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
3052 case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break;
3055 set_opt_session_env ("DISPLAY", pargs.r.ret_str);
3058 set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
3061 set_opt_session_env ("TERM", pargs.r.ret_str);
3064 set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
3067 case oLCctype: opt.lc_ctype = pargs.r.ret_str; break;
3068 case oLCmessages: opt.lc_messages = pargs.r.ret_str; break;
3070 case oGroup: add_group(pargs.r.ret_str); break;
3071 case oUnGroup: rm_group(pargs.r.ret_str); break;
3073 while(opt.grouplist)
3075 struct groupitem *iter=opt.grouplist;
3076 free_strlist(iter->values);
3077 opt.grouplist=opt.grouplist->next;
3087 case oMangleDosFilenames: opt.mangle_dos_filenames = 1; break;
3088 case oNoMangleDosFilenames: opt.mangle_dos_filenames = 0; break;
3089 case oEnableProgressFilter: opt.enable_progress_filter = 1; break;
3090 case oMultifile: multifile=1; break;
3092 if(ascii_strcasecmp(pargs.r.ret_str,"short")==0)
3093 opt.keyid_format=KF_SHORT;
3094 else if(ascii_strcasecmp(pargs.r.ret_str,"long")==0)
3095 opt.keyid_format=KF_LONG;
3096 else if(ascii_strcasecmp(pargs.r.ret_str,"0xshort")==0)
3097 opt.keyid_format=KF_0xSHORT;
3098 else if(ascii_strcasecmp(pargs.r.ret_str,"0xlong")==0)
3099 opt.keyid_format=KF_0xLONG;
3101 log_error("unknown keyid-format '%s'\n",pargs.r.ret_str);
3104 case oExitOnStatusWriteError:
3105 opt.exit_on_status_write_error = 1;
3108 case oLimitCardInsertTries:
3109 opt.limit_card_insert_tries = pargs.r.ret_int;
3112 case oRequireCrossCert: opt.flags.require_cross_cert=1; break;
3113 case oNoRequireCrossCert: opt.flags.require_cross_cert=0; break;
3115 case oAutoKeyLocate:
3116 if(!parse_auto_key_locate(pargs.r.ret_str))
3119 log_error(_("%s:%d: invalid auto-key-locate list\n"),
3120 configname,configlineno);
3122 log_error(_("invalid auto-key-locate list\n"));
3125 case oNoAutoKeyLocate:
3129 case oEnableLargeRSA:
3130 #if SECMEM_BUFFER_SIZE >= 65536
3131 opt.flags.large_rsa=1;
3134 log_info("%s:%d: WARNING: gpg not built with large secure "
3135 "memory buffer. Ignoring enable-large-rsa\n",
3136 configname,configlineno);
3138 log_info("WARNING: gpg not built with large secure "
3139 "memory buffer. Ignoring --enable-large-rsa\n");
3140 #endif /* SECMEM_BUFFER_SIZE >= 65536 */
3142 case oDisableLargeRSA: opt.flags.large_rsa=0;
3145 case oEnableDSA2: opt.flags.dsa2=1; break;
3146 case oDisableDSA2: opt.flags.dsa2=0; break;
3148 case oAllowMultisigVerification:
3149 case oAllowMultipleMessages:
3150 opt.flags.allow_multiple_messages=1;
3153 case oNoAllowMultipleMessages:
3154 opt.flags.allow_multiple_messages=0;
3157 case oAllowWeakDigestAlgos:
3158 opt.flags.allow_weak_digest_algos = 1;
3161 case oFakedSystemTime:
3163 time_t faked_time = isotime2epoch (pargs.r.ret_str);
3164 if (faked_time == (time_t)(-1))
3165 faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
3166 gnupg_set_time (faked_time, 0);
3170 case oNoAutostart: opt.autostart = 0; break;
3175 pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
3184 /* Remember the first config file name. */
3185 if (!save_configname)
3186 save_configname = configname;
3192 xfree(configname); configname = NULL;
3193 if (log_get_errorcount (0))
3196 /* The command --gpgconf-list is pretty simple and may be called
3197 directly after the option parsing. */
3198 if (cmd == aGPGConfList)
3200 gpgconf_list (save_configname ? save_configname : default_configname);
3203 xfree (save_configname);
3204 xfree (default_configname);
3211 es_fprintf (es_stderr, "%s %s; %s\n",
3212 strusage(11), strusage(13), strusage(14) );
3213 es_fprintf (es_stderr, "%s\n", strusage(15) );
3215 #ifdef IS_DEVELOPMENT_VERSION
3220 if((s=strusage(25)))
3222 if((s=strusage(26)))
3224 if((s=strusage(27)))
3229 /* FIXME: We should use logging to a file only in server mode;
3230 however we have not yet implemetyed that. Thus we try to get
3231 away with --batch as indication for logging to file
3233 if (logfile && opt.batch)
3235 log_set_file (logfile);
3236 log_set_prefix (NULL, 1|2|4);
3239 if (opt.verbose > 2)
3240 log_info ("using character set '%s'\n", get_native_charset ());
3242 if( may_coredump && !opt.quiet )
3243 log_info(_("WARNING: program may create a core file!\n"));
3246 if (opt.set_filename)
3247 log_info(_("WARNING: %s overrides %s\n"),
3248 "--for-your-eyes-only","--set-filename");
3250 opt.set_filename="_CONSOLE";
3253 if (opt.no_literal) {
3254 log_info(_("Note: %s is not for normal use!\n"), "--no-literal");
3256 log_error(_("%s not allowed with %s!\n"),
3257 "--textmode", "--no-literal" );
3258 if (opt.set_filename)
3259 log_error(_("%s makes no sense with %s!\n"),
3260 eyes_only?"--for-your-eyes-only":"--set-filename",
3265 if (opt.set_filesize)
3266 log_info(_("Note: %s is not for normal use!\n"), "--set-filesize");
3270 if (gnupg_faked_time_p ())
3272 gnupg_isotime_t tbuf;
3274 log_info (_("WARNING: running with faked system time: "));
3275 gnupg_get_isotime (tbuf);
3276 dump_isotime (tbuf);
3280 /* Print a warning if an argument looks like an option. */
3281 if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
3285 for (i=0; i < argc; i++)
3286 if (argv[i][0] == '-' && argv[i][1] == '-')
3287 log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
3291 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
3293 if(require_secmem && !got_secmem)
3295 log_info(_("will not run with insecure memory due to %s\n"),
3296 "--require-secmem");
3300 set_debug (debug_level);
3302 log_clock ("start");
3304 /* Do these after the switch(), so they can override settings. */
3307 /* That does not anymore work becuase we have no more support
3308 for v3 signatures. */
3311 opt.ask_sig_expire=0;
3315 /* That does not anymore work because we have no more support
3316 for v3 signatures. */
3318 opt.ask_sig_expire=0;
3326 if( def_cipher_string ) {
3327 opt.def_cipher_algo = string_to_cipher_algo (def_cipher_string);
3328 xfree(def_cipher_string); def_cipher_string = NULL;
3329 if ( openpgp_cipher_test_algo (opt.def_cipher_algo) )
3330 log_error(_("selected cipher algorithm is invalid\n"));
3332 if( def_digest_string ) {
3333 opt.def_digest_algo = string_to_digest_algo (def_digest_string);
3334 xfree(def_digest_string); def_digest_string = NULL;
3335 if ( openpgp_md_test_algo (opt.def_digest_algo) )
3336 log_error(_("selected digest algorithm is invalid\n"));
3338 if( compress_algo_string ) {
3339 opt.compress_algo = string_to_compress_algo(compress_algo_string);
3340 xfree(compress_algo_string); compress_algo_string = NULL;
3341 if( check_compress_algo(opt.compress_algo) )
3342 log_error(_("selected compression algorithm is invalid\n"));
3344 if( cert_digest_string ) {
3345 opt.cert_digest_algo = string_to_digest_algo (cert_digest_string);
3346 xfree(cert_digest_string); cert_digest_string = NULL;
3347 if (openpgp_md_test_algo(opt.cert_digest_algo))
3348 log_error(_("selected certification digest algorithm is invalid\n"));
3350 if( s2k_cipher_string ) {
3351 opt.s2k_cipher_algo = string_to_cipher_algo (s2k_cipher_string);
3352 xfree(s2k_cipher_string); s2k_cipher_string = NULL;
3353 if (openpgp_cipher_test_algo (opt.s2k_cipher_algo))
3354 log_error(_("selected cipher algorithm is invalid\n"));
3356 if( s2k_digest_string ) {
3357 opt.s2k_digest_algo = string_to_digest_algo (s2k_digest_string);
3358 xfree(s2k_digest_string); s2k_digest_string = NULL;
3359 if (openpgp_md_test_algo(opt.s2k_digest_algo))
3360 log_error(_("selected digest algorithm is invalid\n"));
3362 if( opt.completes_needed < 1 )
3363 log_error(_("completes-needed must be greater than 0\n"));
3364 if( opt.marginals_needed < 2 )
3365 log_error(_("marginals-needed must be greater than 1\n"));
3366 if( opt.max_cert_depth < 1 || opt.max_cert_depth > 255 )
3367 log_error(_("max-cert-depth must be in the range from 1 to 255\n"));
3368 if(opt.def_cert_level<0 || opt.def_cert_level>3)
3369 log_error(_("invalid default-cert-level; must be 0, 1, 2, or 3\n"));
3370 if( opt.min_cert_level < 1 || opt.min_cert_level > 3 )
3371 log_error(_("invalid min-cert-level; must be 1, 2, or 3\n"));
3372 switch( opt.s2k_mode ) {
3374 log_info(_("Note: simple S2K mode (0) is strongly discouraged\n"));
3376 case 1: case 3: break;
3378 log_error(_("invalid S2K mode; must be 0, 1 or 3\n"));
3381 /* This isn't actually needed, but does serve to error out if the
3382 string is invalid. */
3383 if(opt.def_preference_list &&
3384 keygen_set_std_prefs(opt.def_preference_list,0))
3385 log_error(_("invalid default preferences\n"));
3387 if(pers_cipher_list &&
3388 keygen_set_std_prefs(pers_cipher_list,PREFTYPE_SYM))
3389 log_error(_("invalid personal cipher preferences\n"));
3391 if(pers_digest_list &&
3392 keygen_set_std_prefs(pers_digest_list,PREFTYPE_HASH))
3393 log_error(_("invalid personal digest preferences\n"));
3395 if(pers_compress_list &&
3396 keygen_set_std_prefs(pers_compress_list,PREFTYPE_ZIP))
3397 log_error(_("invalid personal compress preferences\n"));
3399 /* We don't support all possible commands with multifile yet */
3410 cmdname="--clearsign";
3413 cmdname="--detach-sign";
3416 cmdname="--symmetric";
3419 cmdname="--symmetric --encrypt";
3430 log_error(_("%s does not yet work with %s\n"),cmdname,"--multifile");
3433 if( log_get_errorcount(0) )
3436 if(opt.compress_level==0)
3437 opt.compress_algo=COMPRESS_ALGO_NONE;
3439 /* Check our chosen algorithms against the list of legal
3444 const char *badalg=NULL;
3445 preftype_t badtype=PREFTYPE_NONE;
3447 if(opt.def_cipher_algo
3448 && !algo_available(PREFTYPE_SYM,opt.def_cipher_algo,NULL))
3450 badalg = openpgp_cipher_algo_name (opt.def_cipher_algo);
3451 badtype = PREFTYPE_SYM;
3453 else if(opt.def_digest_algo
3454 && !algo_available(PREFTYPE_HASH,opt.def_digest_algo,NULL))
3456 badalg = gcry_md_algo_name (opt.def_digest_algo);
3457 badtype = PREFTYPE_HASH;
3459 else if(opt.cert_digest_algo
3460 && !algo_available(PREFTYPE_HASH,opt.cert_digest_algo,NULL))
3462 badalg = gcry_md_algo_name (opt.cert_digest_algo);
3463 badtype = PREFTYPE_HASH;
3465 else if(opt.compress_algo!=-1
3466 && !algo_available(PREFTYPE_ZIP,opt.compress_algo,NULL))
3468 badalg = compress_algo_to_string(opt.compress_algo);
3469 badtype = PREFTYPE_ZIP;
3477 log_info(_("you may not use cipher algorithm '%s'"
3478 " while in %s mode\n"),
3479 badalg,compliance_option_string());
3482 log_info(_("you may not use digest algorithm '%s'"
3483 " while in %s mode\n"),
3484 badalg,compliance_option_string());
3487 log_info(_("you may not use compression algorithm '%s'"
3488 " while in %s mode\n"),
3489 badalg,compliance_option_string());
3495 compliance_failure();
3499 /* Set the random seed file. */
3500 if( use_random_seed ) {
3501 char *p = make_filename(opt.homedir, "random_seed", NULL );
3502 gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
3503 if (!access (p, F_OK))
3504 register_secured_file (p);
3508 /* If there is no command but the --fingerprint is given, default
3509 to the --list-keys command. */
3510 if (!cmd && fpr_maybe_cmd)
3512 set_cmd (&cmd, aListKeys);
3516 if( opt.verbose > 1 )
3517 set_packet_list_mode(1);
3519 /* Add the keyrings, but not for some special commands.
3520 We always need to add the keyrings if we are running under
3521 SELinux, this is so that the rings are added to the list of
3523 if( ALWAYS_ADD_KEYRINGS
3524 || (cmd != aDeArmor && cmd != aEnArmor && cmd != aGPGConfTest) )
3526 if (!nrings || default_keyring) /* Add default ring. */
3527 keydb_add_resource ("pubring" EXTSEP_S GPGEXT_GPG,
3528 KEYDB_RESOURCE_FLAG_DEFAULT);
3529 for (sl = nrings; sl; sl = sl->next )
3530 keydb_add_resource (sl->d, sl->flags);
3532 FREE_STRLIST(nrings);
3534 if (cmd == aGPGConfTest)
3538 if( pwfd != -1 ) /* Read the passphrase now. */
3539 read_passphrase_from_fd( pwfd );
3541 fname = argc? *argv : NULL;
3543 if(fname && utf8_strings)
3544 opt.flags.utf8_filename=1;
3546 ctrl = xcalloc (1, sizeof *ctrl);
3547 gpg_init_default_ctrl (ctrl);
3549 #ifndef NO_TRUST_MODELS
3560 case aExportOwnerTrust:
3561 rc = setup_trustdb (0, trustdb_name);
3564 rc = setup_trustdb (argc? 1:0, trustdb_name);
3567 /* If we are using TM_ALWAYS, we do not need to create the
3569 rc = setup_trustdb (opt.trust_model != TM_ALWAYS, trustdb_name);
3573 log_error (_("failed to initialize the TrustDB: %s\n"),
3575 #endif /*!NO_TRUST_MODELS*/
3584 if (!opt.quiet && any_explicit_recipient)
3585 log_info (_("WARNING: recipients (-r) given "
3586 "without using public key encryption\n"));
3593 /* Check for certain command whether we need to migrate a
3594 secring.gpg to the gpg-agent. */
3597 case aListSecretKeys:
3608 case aDeleteSecretKeys:
3609 case aDeleteSecretAndPublicKeys:
3616 case aExportSecretSub:
3621 migrate_secring (ctrl);
3624 if (opt.with_secret)
3625 migrate_secring (ctrl);
3631 /* The command dispatcher. */
3638 case aStore: /* only store the file */
3640 wrong_args(_("--store [filename]"));
3641 if( (rc = encrypt_store(fname)) )
3642 log_error ("storing '%s' failed: %s\n",
3643 print_fname_stdin(fname),gpg_strerror (rc) );
3645 case aSym: /* encrypt the given file only with the symmetric cipher */
3647 wrong_args(_("--symmetric [filename]"));
3648 if( (rc = encrypt_symmetric(fname)) )
3649 log_error (_("symmetric encryption of '%s' failed: %s\n"),
3650 print_fname_stdin(fname),gpg_strerror (rc) );
3653 case aEncr: /* encrypt the given file */
3655 encrypt_crypt_files (ctrl, argc, argv, remusr);
3659 wrong_args(_("--encrypt [filename]"));
3660 if( (rc = encrypt_crypt (ctrl, -1, fname, remusr, 0, NULL, -1)) )
3661 log_error("%s: encryption failed: %s\n",
3662 print_fname_stdin(fname), gpg_strerror (rc) );
3667 /* This works with PGP 8 in the sense that it acts just like a
3668 symmetric message. It doesn't work at all with 2 or 6. It
3669 might work with 7, but alas, I don't have a copy to test
3672 wrong_args(_("--symmetric --encrypt [filename]"));
3673 else if(opt.s2k_mode==0)
3674 log_error(_("you cannot use --symmetric --encrypt"
3675 " with --s2k-mode 0\n"));
3676 else if(PGP6 || PGP7)
3677 log_error(_("you cannot use --symmetric --encrypt"
3678 " while in %s mode\n"),compliance_option_string());
3681 if( (rc = encrypt_crypt (ctrl, -1, fname, remusr, 1, NULL, -1)) )
3682 log_error("%s: encryption failed: %s\n",
3683 print_fname_stdin(fname), gpg_strerror (rc) );
3687 case aSign: /* sign the given file */
3689 if( detached_sig ) { /* sign all files */
3690 for( ; argc; argc--, argv++ )
3691 add_to_strlist( &sl, *argv );
3695 wrong_args(_("--sign [filename]"));
3697 sl = xmalloc_clear( sizeof *sl + strlen(fname));
3698 strcpy(sl->d, fname);
3701 if( (rc = sign_file (ctrl, sl, detached_sig, locusr, 0, NULL, NULL)) )
3702 log_error("signing failed: %s\n", gpg_strerror (rc) );
3706 case aSignEncr: /* sign and encrypt the given file */
3708 wrong_args(_("--sign --encrypt [filename]"));
3710 sl = xmalloc_clear( sizeof *sl + strlen(fname));
3711 strcpy(sl->d, fname);
3715 if ((rc = sign_file (ctrl, sl, detached_sig, locusr, 1, remusr, NULL)))
3716 log_error("%s: sign+encrypt failed: %s\n",
3717 print_fname_stdin(fname), gpg_strerror (rc) );
3721 case aSignEncrSym: /* sign and encrypt the given file */
3723 wrong_args(_("--symmetric --sign --encrypt [filename]"));
3724 else if(opt.s2k_mode==0)
3725 log_error(_("you cannot use --symmetric --sign --encrypt"
3726 " with --s2k-mode 0\n"));
3727 else if(PGP6 || PGP7)
3728 log_error(_("you cannot use --symmetric --sign --encrypt"
3729 " while in %s mode\n"),compliance_option_string());
3734 sl = xmalloc_clear( sizeof *sl + strlen(fname));
3735 strcpy(sl->d, fname);
3739 if ((rc = sign_file (ctrl, sl, detached_sig, locusr,
3741 log_error("%s: symmetric+sign+encrypt failed: %s\n",
3742 print_fname_stdin(fname), gpg_strerror (rc) );
3747 case aSignSym: /* sign and conventionally encrypt the given file */
3749 wrong_args(_("--sign --symmetric [filename]"));
3750 rc = sign_symencrypt_file (fname, locusr);
3752 log_error("%s: sign+symmetric failed: %s\n",
3753 print_fname_stdin(fname), gpg_strerror (rc) );
3756 case aClearsign: /* make a clearsig */
3758 wrong_args(_("--clearsign [filename]"));
3759 if( (rc = clearsign_file(fname, locusr, NULL)) )
3760 log_error("%s: clearsign failed: %s\n",
3761 print_fname_stdin(fname), gpg_strerror (rc) );
3767 if ((rc = verify_files (ctrl, argc, argv)))
3768 log_error("verify files failed: %s\n", gpg_strerror (rc) );
3772 if ((rc = verify_signatures (ctrl, argc, argv)))
3773 log_error("verify signatures failed: %s\n", gpg_strerror (rc) );
3779 decrypt_messages (ctrl, argc, argv);
3783 wrong_args(_("--decrypt [filename]"));
3784 if( (rc = decrypt_message (ctrl, fname) ))
3785 log_error("decrypt_message failed: %s\n", gpg_strerror (rc) );
3790 case aQuickLSignKey:
3795 wrong_args ("--quick-[l]sign-key fingerprint [userids]");
3796 fpr = *argv++; argc--;
3798 for( ; argc; argc--, argv++)
3799 append_to_strlist2 (&sl, *argv, utf8_strings);
3800 keyedit_quick_sign (ctrl, fpr, sl, locusr, (cmd == aQuickLSignKey));
3807 wrong_args(_("--sign-key user-id"));
3811 wrong_args(_("--lsign-key user-id"));
3817 append_to_strlist(&sl,"sign");
3818 else if(cmd==aLSignKey)
3819 append_to_strlist(&sl,"lsign");
3823 append_to_strlist( &sl, "save" );
3824 username = make_username( fname );
3825 keyedit_menu (ctrl, username, locusr, sl, 0, 0 );
3830 case aEditKey: /* Edit a key signature */
3832 wrong_args(_("--edit-key user-id [commands]"));
3833 username = make_username( fname );
3836 for( argc--, argv++ ; argc; argc--, argv++ )
3837 append_to_strlist( &sl, *argv );
3838 keyedit_menu (ctrl, username, locusr, sl, 0, 1 );
3842 keyedit_menu (ctrl, username, locusr, NULL, 0, 1 );
3848 wrong_args (_("--passwd <user-id>"));
3851 username = make_username (fname);
3852 keyedit_passwd (ctrl, username);
3858 case aDeleteSecretKeys:
3859 case aDeleteSecretAndPublicKeys:
3861 /* I'm adding these in reverse order as add_to_strlist2
3862 reverses them again, and it's easier to understand in the
3864 for( ; argc; argc-- )
3865 add_to_strlist2( &sl, argv[argc-1], utf8_strings );
3866 delete_keys(sl,cmd==aDeleteSecretKeys,cmd==aDeleteSecretAndPublicKeys);
3876 for( ; argc; argc--, argv++ )
3877 add_to_strlist2( &sl, *argv, utf8_strings );
3878 public_key_list (ctrl, sl, 0);
3881 case aListSecretKeys:
3883 for( ; argc; argc--, argv++ )
3884 add_to_strlist2( &sl, *argv, utf8_strings );
3885 secret_key_list (ctrl, sl);
3890 for (; argc; argc--, argv++)
3891 add_to_strlist2( &sl, *argv, utf8_strings );
3892 public_key_list (ctrl, sl, 1);
3898 wrong_args("--gen-key user-id");
3899 username = make_username (fname);
3900 quick_generate_keypair (username);
3904 case aKeygen: /* generate a key */
3907 wrong_args("--gen-key [parameterfile]");
3908 generate_keypair (ctrl, 0, argc? *argv : NULL, NULL, 0);
3912 wrong_args("--gen-key");
3913 generate_keypair (ctrl, 0, NULL, NULL, 0);
3917 case aFullKeygen: /* Generate a key with all options. */
3921 wrong_args ("--full-gen-key [parameterfile]");
3922 generate_keypair (ctrl, 1, argc? *argv : NULL, NULL, 0);
3927 wrong_args("--full-gen-key");
3928 generate_keypair (ctrl, 1, NULL, NULL, 0);
3934 const char *uid, *newuid;
3937 wrong_args ("--quick-adduid USER-ID NEW-USER-ID");
3938 uid = *argv++; argc--;
3939 newuid = *argv++; argc--;
3940 keyedit_quick_adduid (ctrl, uid, newuid);
3945 opt.import_options |= IMPORT_FAST;
3947 import_keys (ctrl, argc? argv:NULL, argc, NULL, opt.import_options);
3950 /* TODO: There are a number of command that use this same
3951 "make strlist, call function, report error, free strlist"
3952 pattern. Join them together here and avoid all that
3959 for( ; argc; argc--, argv++ )
3960 append_to_strlist2( &sl, *argv, utf8_strings );
3961 if( cmd == aSendKeys )
3962 rc = keyserver_export (ctrl, sl );
3963 else if( cmd == aRecvKeys )
3964 rc = keyserver_import (ctrl, sl );
3966 rc = export_pubkeys (ctrl, sl, opt.export_options);
3970 log_error(_("keyserver send failed: %s\n"),gpg_strerror (rc));
3971 else if(cmd==aRecvKeys)
3972 log_error(_("keyserver receive failed: %s\n"),gpg_strerror (rc));
3974 log_error(_("key export failed: %s\n"),gpg_strerror (rc));
3981 for (; argc; argc--, argv++)
3982 append_to_strlist2 (&sl, *argv, utf8_strings);
3983 rc = keyserver_search (ctrl, sl);
3985 log_error (_("keyserver search failed: %s\n"), gpg_strerror (rc));
3991 for( ; argc; argc--, argv++ )
3992 append_to_strlist2( &sl, *argv, utf8_strings );
3993 rc = keyserver_refresh (ctrl, sl);
3995 log_error(_("keyserver refresh failed: %s\n"),gpg_strerror (rc));
4001 for( ; argc; argc--, argv++ )
4002 append_to_strlist2( &sl, *argv, utf8_strings );
4003 rc = keyserver_fetch (ctrl, sl);
4005 log_error("key fetch failed: %s\n",gpg_strerror (rc));
4011 for( ; argc; argc--, argv++ )
4012 add_to_strlist2( &sl, *argv, utf8_strings );
4013 export_seckeys (ctrl, sl);
4017 case aExportSecretSub:
4019 for( ; argc; argc--, argv++ )
4020 add_to_strlist2( &sl, *argv, utf8_strings );
4021 export_secsubkeys (ctrl, sl);
4027 wrong_args("--gen-revoke user-id");
4028 username = make_username(*argv);
4029 gen_revoke( username );
4035 wrong_args("--desig-revoke user-id");
4036 username = make_username(*argv);
4037 gen_desig_revoke( username, locusr );
4043 wrong_args("--dearmor [file]");
4044 rc = dearmor_file( argc? *argv: NULL );
4046 log_error(_("dearmoring failed: %s\n"), gpg_strerror (rc));
4051 wrong_args("--enarmor [file]");
4052 rc = enarmor_file( argc? *argv: NULL );
4054 log_error(_("enarmoring failed: %s\n"), gpg_strerror (rc));
4060 { int mode = argc < 2 ? 0 : atoi(*argv);
4062 if( mode == 1 && argc == 2 ) {
4063 mpi_print (es_stdout,
4064 generate_public_prime( atoi(argv[1]) ), 1);
4066 else if( mode == 2 && argc == 3 ) {
4067 mpi_print (es_stdout, generate_elg_prime(
4069 atoi(argv[2]), NULL,NULL ), 1);
4071 else if( mode == 3 && argc == 3 ) {
4073 mpi_print (es_stdout, generate_elg_prime(
4075 atoi(argv[2]), NULL,&factors ), 1);
4076 es_putc ('\n', es_stdout);
4077 mpi_print (es_stdout, factors[0], 1 ); /* print q */
4079 else if( mode == 4 && argc == 3 ) {
4080 MPI g = mpi_alloc(1);
4081 mpi_print (es_stdout, generate_elg_prime(
4083 atoi(argv[2]), g, NULL ), 1);
4084 es_putc ('\n', es_stdout);
4085 mpi_print (es_stdout, g, 1 );
4089 wrong_args("--gen-prime mode bits [qbits] ");
4090 es_putc ('\n', es_stdout);
4093 wrong_args("--gen-prime not yet supported ");
4098 int level = argc ? atoi(*argv):0;
4099 int count = argc > 1 ? atoi(argv[1]): 0;
4100 int endless = !count;
4102 if( argc < 1 || argc > 2 || level < 0 || level > 2 || count < 0 )
4103 wrong_args("--gen-random 0|1|2 [count]");
4105 while( endless || count ) {
4107 /* Wee need a multiple of 3, so that in case of
4108 armored output we get a correct string. No
4109 linefolding is done, as it is best to levae this to
4111 size_t n = !endless && count < 99? count : 99;
4113 p = gcry_random_bytes (n, level);
4114 #ifdef HAVE_DOSISH_SYSTEM
4115 setmode ( fileno(stdout), O_BINARY );
4118 char *tmp = make_radix64_string (p, n);
4119 es_fputs (tmp, es_stdout);
4122 es_putc ('=', es_stdout);
4124 es_putc ('=', es_stdout);
4126 es_fwrite( p, n, 1, es_stdout );
4133 es_putc ('\n', es_stdout);
4139 wrong_args("--print-md algo [files]");
4141 int all_algos = (**argv=='*' && !(*argv)[1]);
4142 int algo = all_algos? 0 : gcry_md_map_name (*argv);
4144 if( !algo && !all_algos )
4145 log_error(_("invalid hash algorithm '%s'\n"), *argv );
4149 print_mds(NULL, algo);
4151 for(; argc; argc--, argv++ )
4152 print_mds(*argv, algo);
4158 case aPrintMDs: /* old option */
4162 for(; argc; argc--, argv++ )
4167 #ifndef NO_TRUST_MODELS
4172 for( ; argc; argc--, argv++ )
4173 list_trustdb( *argv );
4177 case aUpdateTrustDB:
4179 wrong_args("--update-trustdb");
4184 /* Old versions allowed for arguments - ignore them */
4189 how_to_fix_the_trustdb ();
4192 case aListTrustPath:
4194 wrong_args("--list-trust-path <user-ids>");
4195 for( ; argc; argc--, argv++ ) {
4196 username = make_username( *argv );
4197 list_trust_path( username );
4202 case aExportOwnerTrust:
4204 wrong_args("--export-ownertrust");
4205 export_ownertrust();
4208 case aImportOwnerTrust:
4210 wrong_args("--import-ownertrust [file]");
4211 import_ownertrust( argc? *argv:NULL );
4213 #endif /*!NO_TRUST_MODELS*/
4215 case aRebuildKeydbCaches:
4217 wrong_args ("--rebuild-keydb-caches");
4218 keydb_rebuild_caches (1);
4221 #ifdef ENABLE_CARD_SUPPORT
4224 wrong_args ("--card-status");
4225 card_status (es_stdout, NULL, 0);
4231 for (argc--, argv++ ; argc; argc--, argv++)
4232 append_to_strlist (&sl, *argv);
4233 card_edit (ctrl, sl);
4237 card_edit (ctrl, NULL);
4244 change_pin (atoi (*argv),1);
4246 wrong_args ("--change-pin [no]");
4248 #endif /* ENABLE_CARD_SUPPORT*/
4252 char *str=collapse_args(argc,argv);
4258 case aListGcryptConfig:
4259 /* Fixme: It would be nice to integrate that with
4260 --list-config but unfortunately there is no way yet to have
4261 libgcrypt print it to an estream for further parsing. */
4262 gcry_control (GCRYCTL_PRINT_CONFIG, stdout);
4269 wrong_args(_("[filename]"));
4270 /* Issue some output for the unix newbie */
4271 if (!fname && !opt.outfile
4272 && gnupg_isatty (fileno (stdin))
4273 && gnupg_isatty (fileno (stdout))
4274 && gnupg_isatty (fileno (stderr)))
4275 log_info(_("Go ahead and type your message ...\n"));
4277 a = iobuf_open(fname);
4278 if (a && is_secured_file (iobuf_get_fd (a)))
4282 gpg_err_set_errno (EPERM);
4285 log_error(_("can't open '%s'\n"), print_fname_stdin(fname));
4288 if( !opt.no_armor ) {
4289 if( use_armor_filter( a ) ) {
4290 afx = new_armor_context ();
4291 push_armor_filter (afx, a);
4294 if( cmd == aListPackets ) {
4295 set_packet_list_mode(1);
4298 rc = proc_packets (ctrl, NULL, a );
4300 log_error("processing message failed: %s\n", gpg_strerror (rc));
4307 gpg_deinit_default_ctrl (ctrl);
4309 release_armor_context (afx);
4310 FREE_STRLIST(remusr);
4311 FREE_STRLIST(locusr);
4313 return 8; /*NEVER REACHED*/
4317 /* Note: This function is used by signal handlers!. */
4319 emergency_cleanup (void)
4321 gcry_control (GCRYCTL_TERM_SECMEM );
4328 gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
4331 if ( (opt.debug & DBG_MEMSTAT_VALUE) )
4333 gcry_control (GCRYCTL_DUMP_MEMORY_STATS);
4334 gcry_control (GCRYCTL_DUMP_RANDOM_STATS);
4337 gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
4339 emergency_cleanup ();
4341 rc = rc? rc : log_get_errorcount(0)? 2 : g10_errors_seen? 1 : 0;
4346 /* Pretty-print hex hashes. This assumes at least an 80-character
4347 display, but there are a few other similar assumptions in the
4350 print_hex (gcry_md_hd_t md, int algo, const char *fname)
4352 int i,n,count,indent=0;
4356 indent = es_printf("%s: ",fname);
4364 if (algo==DIGEST_ALGO_RMD160)
4365 indent += es_printf("RMD160 = ");
4367 indent += es_printf("%6s = ", gcry_md_algo_name (algo));
4373 p = gcry_md_read (md, algo);
4374 n = gcry_md_get_algo_dlen (algo);
4376 count += es_printf ("%02X",*p++);
4378 for(i=1;i<n;i++,p++)
4384 es_printf ("\n%*s",indent," ");
4388 count += es_printf(" ");
4391 count += es_printf(" ");
4399 es_printf ("\n%*s",indent," ");
4403 count += es_printf(" ");
4407 count += es_printf(" ");
4415 es_printf ("\n%*s",indent," ");
4419 count += es_printf(" ");
4423 count += es_printf("%02X",*p);
4430 print_hashline( gcry_md_hd_t md, int algo, const char *fname )
4437 for (p = fname; *p; p++ )
4439 if ( *p <= 32 || *p > 127 || *p == ':' || *p == '%' )
4440 es_printf ("%%%02X", *p );
4442 es_putc (*p, es_stdout);
4445 es_putc (':', es_stdout);
4446 es_printf ("%d:", algo);
4447 p = gcry_md_read (md, algo);
4448 n = gcry_md_get_algo_dlen (algo);
4449 for(i=0; i < n ; i++, p++ )
4450 es_printf ("%02X", *p);
4451 es_fputs (":\n", es_stdout);
4456 print_mds( const char *fname, int algo )
4470 fp = es_fopen (fname, "rb" );
4471 if (fp && is_secured_file (es_fileno (fp)))
4475 gpg_err_set_errno (EPERM);
4480 log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
4484 gcry_md_open (&md, 0, 0);
4486 gcry_md_enable (md, algo);
4489 if (!gcry_md_test_algo (GCRY_MD_MD5))
4490 gcry_md_enable (md, GCRY_MD_MD5);
4491 gcry_md_enable (md, GCRY_MD_SHA1);
4492 if (!gcry_md_test_algo (GCRY_MD_RMD160))
4493 gcry_md_enable (md, GCRY_MD_RMD160);
4494 if (!gcry_md_test_algo (GCRY_MD_SHA224))
4495 gcry_md_enable (md, GCRY_MD_SHA224);
4496 if (!gcry_md_test_algo (GCRY_MD_SHA256))
4497 gcry_md_enable (md, GCRY_MD_SHA256);
4498 if (!gcry_md_test_algo (GCRY_MD_SHA384))
4499 gcry_md_enable (md, GCRY_MD_SHA384);
4500 if (!gcry_md_test_algo (GCRY_MD_SHA512))
4501 gcry_md_enable (md, GCRY_MD_SHA512);
4504 while ((n=es_fread (buf, 1, DIM(buf), fp)))
4505 gcry_md_write (md, buf, n);
4508 log_error ("%s: %s\n", fname?fname:"[stdin]", strerror(errno));
4512 if (opt.with_colons)
4515 print_hashline (md, algo, fname);
4518 if (!gcry_md_test_algo (GCRY_MD_MD5))
4519 print_hashline( md, GCRY_MD_MD5, fname );
4520 print_hashline( md, GCRY_MD_SHA1, fname );
4521 if (!gcry_md_test_algo (GCRY_MD_RMD160))
4522 print_hashline( md, GCRY_MD_RMD160, fname );
4523 if (!gcry_md_test_algo (GCRY_MD_SHA224))
4524 print_hashline (md, GCRY_MD_SHA224, fname);
4525 if (!gcry_md_test_algo (GCRY_MD_SHA256))
4526 print_hashline( md, GCRY_MD_SHA256, fname );
4527 if (!gcry_md_test_algo (GCRY_MD_SHA384))
4528 print_hashline ( md, GCRY_MD_SHA384, fname );
4529 if (!gcry_md_test_algo (GCRY_MD_SHA512))
4530 print_hashline ( md, GCRY_MD_SHA512, fname );
4536 print_hex (md, -algo, fname);
4539 if (!gcry_md_test_algo (GCRY_MD_MD5))
4540 print_hex (md, GCRY_MD_MD5, fname);
4541 print_hex (md, GCRY_MD_SHA1, fname );
4542 if (!gcry_md_test_algo (GCRY_MD_RMD160))
4543 print_hex (md, GCRY_MD_RMD160, fname );
4544 if (!gcry_md_test_algo (GCRY_MD_SHA224))
4545 print_hex (md, GCRY_MD_SHA224, fname);
4546 if (!gcry_md_test_algo (GCRY_MD_SHA256))
4547 print_hex (md, GCRY_MD_SHA256, fname );
4548 if (!gcry_md_test_algo (GCRY_MD_SHA384))
4549 print_hex (md, GCRY_MD_SHA384, fname );
4550 if (!gcry_md_test_algo (GCRY_MD_SHA512))
4551 print_hex (md, GCRY_MD_SHA512, fname );
4563 * Check the supplied name,value string and add it to the notation
4564 * data to be used for signatures. which==0 for sig notations, and 1
4565 * for cert notations.
4568 add_notation_data( const char *string, int which )
4570 struct notation *notation;
4572 notation=string_to_notation(string,utf8_strings);
4577 notation->next=opt.cert_notations;
4578 opt.cert_notations=notation;
4582 notation->next=opt.sig_notations;
4583 opt.sig_notations=notation;
4589 add_policy_url( const char *string, int which )
4591 unsigned int i,critical=0;
4600 for(i=0;i<strlen(string);i++)
4601 if( !isascii (string[i]) || iscntrl(string[i]))
4604 if(i==0 || i<strlen(string))
4607 log_error(_("the given certification policy URL is invalid\n"));
4609 log_error(_("the given signature policy URL is invalid\n"));
4613 sl=add_to_strlist( &opt.cert_policy_url, string );
4615 sl=add_to_strlist( &opt.sig_policy_url, string );
4622 add_keyserver_url( const char *string, int which )
4624 unsigned int i,critical=0;
4633 for(i=0;i<strlen(string);i++)
4634 if( !isascii (string[i]) || iscntrl(string[i]))
4637 if(i==0 || i<strlen(string))
4642 log_error(_("the given preferred keyserver URL is invalid\n"));
4648 sl=add_to_strlist( &opt.sig_keyserver_url, string );