LCOV - code coverage report
Current view: top level - sm - gpgsm.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 210 929 22.6 %
Date: 2016-12-01 18:37:21 Functions: 8 24 33.3 %

          Line data    Source code
       1             : /* gpgsm.c - GnuPG for S/MIME
       2             :  * Copyright (C) 2001-2008, 2010  Free Software Foundation, Inc.
       3             :  * Copyright (C) 2001-2008, 2010  Werner Koch
       4             :  *
       5             :  * This file is part of GnuPG.
       6             :  *
       7             :  * GnuPG is free software; you can redistribute it and/or modify
       8             :  * it under the terms of the GNU General Public License as published by
       9             :  * the Free Software Foundation; either version 3 of the License, or
      10             :  * (at your option) any later version.
      11             :  *
      12             :  * GnuPG is distributed in the hope that it will be useful,
      13             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      14             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      15             :  * GNU General Public License for more details.
      16             :  *
      17             :  * You should have received a copy of the GNU General Public License
      18             :  * along with this program; if not, see <https://www.gnu.org/licenses/>.
      19             :  */
      20             : 
      21             : #include <config.h>
      22             : #include <errno.h>
      23             : #include <stdio.h>
      24             : #include <stdlib.h>
      25             : #include <string.h>
      26             : #include <ctype.h>
      27             : #include <unistd.h>
      28             : #include <fcntl.h>
      29             : /*#include <mcheck.h>*/
      30             : 
      31             : #include "gpgsm.h"
      32             : #include <gcrypt.h>
      33             : #include <assuan.h> /* malloc hooks */
      34             : 
      35             : #include "passphrase.h"
      36             : #include "../common/shareddefs.h"
      37             : #include "../kbx/keybox.h" /* malloc hooks */
      38             : #include "i18n.h"
      39             : #include "keydb.h"
      40             : #include "sysutils.h"
      41             : #include "gc-opt-flags.h"
      42             : #include "asshelp.h"
      43             : #include "../common/init.h"
      44             : 
      45             : 
      46             : #ifndef O_BINARY
      47             : #define O_BINARY 0
      48             : #endif
      49             : 
      50             : enum cmd_and_opt_values {
      51             :   aNull = 0,
      52             :   oArmor        = 'a',
      53             :   aDetachedSign = 'b',
      54             :   aSym          = 'c',
      55             :   aDecrypt      = 'd',
      56             :   aEncr         = 'e',
      57             :   aListKeys     = 'k',
      58             :   aListSecretKeys = 'K',
      59             :   oDryRun       = 'n',
      60             :   oOutput       = 'o',
      61             :   oQuiet        = 'q',
      62             :   oRecipient    = 'r',
      63             :   aSign         = 's',
      64             :   oUser         = 'u',
      65             :   oVerbose      = 'v',
      66             :   oBatch        = 500,
      67             :   aClearsign,
      68             :   aKeygen,
      69             :   aSignEncr,
      70             :   aDeleteKey,
      71             :   aImport,
      72             :   aVerify,
      73             :   aListExternalKeys,
      74             :   aListChain,
      75             :   aSendKeys,
      76             :   aRecvKeys,
      77             :   aExport,
      78             :   aExportSecretKeyP12,
      79             :   aExportSecretKeyP8,
      80             :   aExportSecretKeyRaw,
      81             :   aServer,
      82             :   aLearnCard,
      83             :   aCallDirmngr,
      84             :   aCallProtectTool,
      85             :   aPasswd,
      86             :   aGPGConfList,
      87             :   aGPGConfTest,
      88             :   aDumpKeys,
      89             :   aDumpChain,
      90             :   aDumpSecretKeys,
      91             :   aDumpExternalKeys,
      92             :   aKeydbClearSomeCertFlags,
      93             :   aFingerprint,
      94             : 
      95             :   oOptions,
      96             :   oDebug,
      97             :   oDebugLevel,
      98             :   oDebugAll,
      99             :   oDebugNone,
     100             :   oDebugWait,
     101             :   oDebugAllowCoreDump,
     102             :   oDebugNoChainValidation,
     103             :   oDebugIgnoreExpiration,
     104             :   oLogFile,
     105             :   oNoLogFile,
     106             :   oAuditLog,
     107             :   oHtmlAuditLog,
     108             : 
     109             :   oEnableSpecialFilenames,
     110             : 
     111             :   oAgentProgram,
     112             :   oDisplay,
     113             :   oTTYname,
     114             :   oTTYtype,
     115             :   oLCctype,
     116             :   oLCmessages,
     117             :   oXauthority,
     118             : 
     119             :   oPreferSystemDirmngr,
     120             :   oDirmngrProgram,
     121             :   oDisableDirmngr,
     122             :   oProtectToolProgram,
     123             :   oFakedSystemTime,
     124             : 
     125             :   oPassphraseFD,
     126             :   oPinentryMode,
     127             : 
     128             :   oAssumeArmor,
     129             :   oAssumeBase64,
     130             :   oAssumeBinary,
     131             : 
     132             :   oBase64,
     133             :   oNoArmor,
     134             :   oP12Charset,
     135             : 
     136             :   oCompliance,
     137             : 
     138             :   oDisableCRLChecks,
     139             :   oEnableCRLChecks,
     140             :   oDisableTrustedCertCRLCheck,
     141             :   oEnableTrustedCertCRLCheck,
     142             :   oForceCRLRefresh,
     143             : 
     144             :   oDisableOCSP,
     145             :   oEnableOCSP,
     146             : 
     147             :   oIncludeCerts,
     148             :   oPolicyFile,
     149             :   oDisablePolicyChecks,
     150             :   oEnablePolicyChecks,
     151             :   oAutoIssuerKeyRetrieve,
     152             : 
     153             :   oWithFingerprint,
     154             :   oWithMD5Fingerprint,
     155             :   oWithKeygrip,
     156             :   oWithSecret,
     157             :   oAnswerYes,
     158             :   oAnswerNo,
     159             :   oKeyring,
     160             :   oDefaultKey,
     161             :   oDefRecipient,
     162             :   oDefRecipientSelf,
     163             :   oNoDefRecipient,
     164             :   oStatusFD,
     165             :   oCipherAlgo,
     166             :   oDigestAlgo,
     167             :   oExtraDigestAlgo,
     168             :   oNoVerbose,
     169             :   oNoSecmemWarn,
     170             :   oNoDefKeyring,
     171             :   oNoGreeting,
     172             :   oNoTTY,
     173             :   oNoOptions,
     174             :   oNoBatch,
     175             :   oHomedir,
     176             :   oWithColons,
     177             :   oWithKeyData,
     178             :   oWithValidation,
     179             :   oWithEphemeralKeys,
     180             :   oSkipVerify,
     181             :   oValidationModel,
     182             :   oKeyServer,
     183             :   oEncryptTo,
     184             :   oNoEncryptTo,
     185             :   oLoggerFD,
     186             :   oDisableCipherAlgo,
     187             :   oDisablePubkeyAlgo,
     188             :   oIgnoreTimeConflict,
     189             :   oNoRandomSeedFile,
     190             :   oNoCommonCertsImport,
     191             :   oIgnoreCertExtension,
     192             :   oNoAutostart
     193             :  };
     194             : 
     195             : 
     196             : static ARGPARSE_OPTS opts[] = {
     197             : 
     198             :   ARGPARSE_group (300, N_("@Commands:\n ")),
     199             : 
     200             :   ARGPARSE_c (aSign, "sign", N_("make a signature")),
     201             : /*ARGPARSE_c (aClearsign, "clearsign", N_("make a clear text signature") ),*/
     202             :   ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")),
     203             :   ARGPARSE_c (aEncr, "encrypt", N_("encrypt data")),
     204             : /*ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")),*/
     205             :   ARGPARSE_c (aDecrypt, "decrypt", N_("decrypt data (default)")),
     206             :   ARGPARSE_c (aVerify, "verify",  N_("verify a signature")),
     207             :   ARGPARSE_c (aListKeys, "list-keys", N_("list keys")),
     208             :   ARGPARSE_c (aListExternalKeys, "list-external-keys",
     209             :               N_("list external keys")),
     210             :   ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")),
     211             :   ARGPARSE_c (aListChain,   "list-chain",  N_("list certificate chain")),
     212             :   ARGPARSE_c (aFingerprint, "fingerprint", N_("list keys and fingerprints")),
     213             :   ARGPARSE_c (aKeygen, "gen-key", N_("generate a new key pair")),
     214             :   ARGPARSE_c (aDeleteKey, "delete-keys",
     215             :               N_("remove keys from the public keyring")),
     216             : /*ARGPARSE_c (aSendKeys, "send-keys", N_("export keys to a keyserver")),*/
     217             : /*ARGPARSE_c (aRecvKeys, "recv-keys", N_("import keys from a keyserver")),*/
     218             :   ARGPARSE_c (aImport, "import", N_("import certificates")),
     219             :   ARGPARSE_c (aExport, "export", N_("export certificates")),
     220             : 
     221             :   /* We use -raw and not -p1 for pkcs#1 secret key export so that it
     222             :      won't accidentally be used in case -p12 was intended.  */
     223             :   ARGPARSE_c (aExportSecretKeyP12, "export-secret-key-p12", "@"),
     224             :   ARGPARSE_c (aExportSecretKeyP8,  "export-secret-key-p8", "@"),
     225             :   ARGPARSE_c (aExportSecretKeyRaw, "export-secret-key-raw", "@"),
     226             : 
     227             :   ARGPARSE_c (aLearnCard, "learn-card", N_("register a smartcard")),
     228             :   ARGPARSE_c (aServer, "server", N_("run in server mode")),
     229             :   ARGPARSE_c (aCallDirmngr, "call-dirmngr",
     230             :               N_("pass a command to the dirmngr")),
     231             :   ARGPARSE_c (aCallProtectTool, "call-protect-tool",
     232             :               N_("invoke gpg-protect-tool")),
     233             :   ARGPARSE_c (aPasswd, "passwd", N_("change a passphrase")),
     234             :   ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
     235             :   ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
     236             : 
     237             :   ARGPARSE_c (aDumpKeys, "dump-cert", "@"),
     238             :   ARGPARSE_c (aDumpKeys, "dump-keys", "@"),
     239             :   ARGPARSE_c (aDumpChain, "dump-chain", "@"),
     240             :   ARGPARSE_c (aDumpExternalKeys, "dump-external-keys", "@"),
     241             :   ARGPARSE_c (aDumpSecretKeys, "dump-secret-keys", "@"),
     242             :   ARGPARSE_c (aKeydbClearSomeCertFlags, "keydb-clear-some-cert-flags", "@"),
     243             : 
     244             :   ARGPARSE_group (301, N_("@\nOptions:\n ")),
     245             : 
     246             :   ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")),
     247             :   ARGPARSE_s_n (oArmor, "armour", "@"),
     248             :   ARGPARSE_s_n (oBase64, "base64", N_("create base-64 encoded output")),
     249             : 
     250             :   ARGPARSE_s_s (oP12Charset, "p12-charset", "@"),
     251             : 
     252             :   ARGPARSE_s_i (oPassphraseFD,    "passphrase-fd", "@"),
     253             :   ARGPARSE_s_s (oPinentryMode,    "pinentry-mode", "@"),
     254             : 
     255             :   ARGPARSE_s_n (oAssumeArmor, "assume-armor",
     256             :                 N_("assume input is in PEM format")),
     257             :   ARGPARSE_s_n (oAssumeBase64, "assume-base64",
     258             :                 N_("assume input is in base-64 format")),
     259             :   ARGPARSE_s_n (oAssumeBinary, "assume-binary",
     260             :                 N_("assume input is in binary format")),
     261             : 
     262             :   ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")),
     263             : 
     264             :   ARGPARSE_s_n (oPreferSystemDirmngr,"prefer-system-dirmngr", "@"),
     265             : 
     266             :   ARGPARSE_s_n (oDisableCRLChecks, "disable-crl-checks",
     267             :                 N_("never consult a CRL")),
     268             :   ARGPARSE_s_n (oEnableCRLChecks, "enable-crl-checks", "@"),
     269             :   ARGPARSE_s_n (oDisableTrustedCertCRLCheck,
     270             :                 "disable-trusted-cert-crl-check", "@"),
     271             :   ARGPARSE_s_n (oEnableTrustedCertCRLCheck,
     272             :                 "enable-trusted-cert-crl-check", "@"),
     273             : 
     274             :   ARGPARSE_s_n (oForceCRLRefresh, "force-crl-refresh", "@"),
     275             : 
     276             :   ARGPARSE_s_n (oDisableOCSP, "disable-ocsp", "@"),
     277             :   ARGPARSE_s_n (oEnableOCSP,  "enable-ocsp", N_("check validity using OCSP")),
     278             : 
     279             :   ARGPARSE_s_s (oValidationModel, "validation-model", "@"),
     280             : 
     281             :   ARGPARSE_s_i (oIncludeCerts, "include-certs",
     282             :                 N_("|N|number of certificates to include") ),
     283             : 
     284             :   ARGPARSE_s_s (oPolicyFile, "policy-file",
     285             :                 N_("|FILE|take policy information from FILE")),
     286             : 
     287             :   ARGPARSE_s_n (oDisablePolicyChecks, "disable-policy-checks",
     288             :                 N_("do not check certificate policies")),
     289             :   ARGPARSE_s_n (oEnablePolicyChecks, "enable-policy-checks", "@"),
     290             : 
     291             :   ARGPARSE_s_n (oAutoIssuerKeyRetrieve, "auto-issuer-key-retrieve",
     292             :                 N_("fetch missing issuer certificates")),
     293             : 
     294             :   ARGPARSE_s_s (oEncryptTo, "encrypt-to", "@"),
     295             :   ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"),
     296             : 
     297             :   ARGPARSE_s_s (oUser, "local-user",
     298             :                 N_("|USER-ID|use USER-ID to sign or decrypt")),
     299             : 
     300             :   ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")),
     301             :   ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
     302             :   ARGPARSE_s_n (oQuiet, "quiet",  N_("be somewhat more quiet")),
     303             :   ARGPARSE_s_n (oNoTTY, "no-tty", N_("don't use the terminal at all")),
     304             :   ARGPARSE_s_s (oLogFile, "log-file",
     305             :                 N_("|FILE|write a server mode log to FILE")),
     306             :   ARGPARSE_s_n (oNoLogFile, "no-log-file", "@"),
     307             :   ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"),
     308             : 
     309             :   ARGPARSE_s_s (oAuditLog, "audit-log",
     310             :                 N_("|FILE|write an audit log to FILE")),
     311             :   ARGPARSE_s_s (oHtmlAuditLog, "html-audit-log", "@"),
     312             :   ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")),
     313             :   ARGPARSE_s_n (oBatch, "batch", N_("batch mode: never ask")),
     314             :   ARGPARSE_s_n (oAnswerYes, "yes", N_("assume yes on most questions")),
     315             :   ARGPARSE_s_n (oAnswerNo,  "no",  N_("assume no on most questions")),
     316             : 
     317             :   ARGPARSE_s_s (oKeyring, "keyring",
     318             :                 N_("|FILE|add keyring to the list of keyrings")),
     319             : 
     320             :   ARGPARSE_s_s (oDefaultKey, "default-key",
     321             :                 N_("|USER-ID|use USER-ID as default secret key")),
     322             : 
     323             :   /* Not yet used: */
     324             :   /*   ARGPARSE_s_s (oDefRecipient, "default-recipient", */
     325             :   /*                  N_("|NAME|use NAME as default recipient")), */
     326             :   /*   ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", */
     327             :   /*                  N_("use the default key as default recipient")), */
     328             :   /*   ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"), */
     329             : 
     330             :   ARGPARSE_s_s (oKeyServer, "keyserver",
     331             :                 N_("|SPEC|use this keyserver to lookup keys")),
     332             :   ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
     333             : 
     334             :   ARGPARSE_s_s (oDebug, "debug", "@"),
     335             :   ARGPARSE_s_s (oDebugLevel, "debug-level",
     336             :                 N_("|LEVEL|set the debugging level to LEVEL")),
     337             :   ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
     338             :   ARGPARSE_s_n (oDebugNone, "debug-none", "@"),
     339             :   ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
     340             :   ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"),
     341             :   ARGPARSE_s_n (oDebugNoChainValidation, "debug-no-chain-validation", "@"),
     342             :   ARGPARSE_s_n (oDebugIgnoreExpiration,  "debug-ignore-expiration", "@"),
     343             : 
     344             :   ARGPARSE_s_i (oStatusFD, "status-fd",
     345             :                 N_("|FD|write status info to this FD")),
     346             : 
     347             :   ARGPARSE_s_s (oCipherAlgo, "cipher-algo",
     348             :                 N_("|NAME|use cipher algorithm NAME")),
     349             :   ARGPARSE_s_s (oDigestAlgo, "digest-algo",
     350             :                 N_("|NAME|use message digest algorithm NAME")),
     351             :   ARGPARSE_s_s (oExtraDigestAlgo, "extra-digest-algo", "@"),
     352             : 
     353             : 
     354             :   ARGPARSE_group (302, N_(
     355             :   "@\n(See the man page for a complete listing of all commands and options)\n"
     356             :   )),
     357             : 
     358             :   ARGPARSE_group (303, N_("@\nExamples:\n\n"
     359             :     " -se -r Bob [file]          sign and encrypt for user Bob\n"
     360             :     " --clearsign [file]         make a clear text signature\n"
     361             :     " --detach-sign [file]       make a detached signature\n"
     362             :     " --list-keys [names]        show keys\n"
     363             :     " --fingerprint [names]      show fingerprints\n"  )),
     364             : 
     365             :   /* Hidden options. */
     366             :   ARGPARSE_s_s (oCompliance, "compliance",   "@"),
     367             :   ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
     368             :   ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"),
     369             :   ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"),
     370             :   ARGPARSE_s_n (oNoArmor, "no-armor", "@"),
     371             :   ARGPARSE_s_n (oNoArmor, "no-armour", "@"),
     372             :   ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"),
     373             :   ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
     374             :   ARGPARSE_s_n (oNoOptions, "no-options", "@"),
     375             :   ARGPARSE_s_s (oHomedir, "homedir", "@"),
     376             :   ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
     377             :   ARGPARSE_s_s (oDisplay,    "display", "@"),
     378             :   ARGPARSE_s_s (oTTYname,    "ttyname", "@"),
     379             :   ARGPARSE_s_s (oTTYtype,    "ttytype", "@"),
     380             :   ARGPARSE_s_s (oLCctype,    "lc-ctype", "@"),
     381             :   ARGPARSE_s_s (oLCmessages, "lc-messages", "@"),
     382             :   ARGPARSE_s_s (oXauthority, "xauthority", "@"),
     383             :   ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"),
     384             :   ARGPARSE_s_n (oDisableDirmngr, "disable-dirmngr", "@"),
     385             :   ARGPARSE_s_s (oProtectToolProgram, "protect-tool-program", "@"),
     386             :   ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
     387             :   ARGPARSE_s_n (oNoBatch, "no-batch", "@"),
     388             :   ARGPARSE_s_n (oWithColons, "with-colons", "@"),
     389             :   ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"),
     390             :   ARGPARSE_s_n (oWithValidation, "with-validation", "@"),
     391             :   ARGPARSE_s_n (oWithMD5Fingerprint, "with-md5-fingerprint", "@"),
     392             :   ARGPARSE_s_n (oWithEphemeralKeys,  "with-ephemeral-keys", "@"),
     393             :   ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"),
     394             :   ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"),
     395             :   ARGPARSE_s_n (oWithKeygrip,     "with-keygrip", "@"),
     396             :   ARGPARSE_s_n (oWithSecret,      "with-secret", "@"),
     397             :   ARGPARSE_s_s (oDisableCipherAlgo,  "disable-cipher-algo", "@"),
     398             :   ARGPARSE_s_s (oDisablePubkeyAlgo,  "disable-pubkey-algo", "@"),
     399             :   ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"),
     400             :   ARGPARSE_s_n (oNoRandomSeedFile,  "no-random-seed-file", "@"),
     401             :   ARGPARSE_s_n (oNoCommonCertsImport, "no-common-certs-import", "@"),
     402             :   ARGPARSE_s_s (oIgnoreCertExtension, "ignore-cert-extension", "@"),
     403             :   ARGPARSE_s_n (oNoAutostart, "no-autostart", "@"),
     404             : 
     405             :   /* Command aliases.  */
     406             :   ARGPARSE_c (aListKeys, "list-key", "@"),
     407             :   ARGPARSE_c (aListChain, "list-sig", "@"),
     408             :   ARGPARSE_c (aListChain, "list-sigs", "@"),
     409             :   ARGPARSE_c (aListChain, "check-sig", "@"),
     410             :   ARGPARSE_c (aListChain, "check-sigs", "@"),
     411             :   ARGPARSE_c (aDeleteKey, "delete-key", "@"),
     412             : 
     413             :   ARGPARSE_end ()
     414             : };
     415             : 
     416             : 
     417             : /* The list of supported debug flags.  */
     418             : static struct debug_flags_s debug_flags [] =
     419             :   {
     420             :     { DBG_X509_VALUE   , "x509"    },
     421             :     { DBG_MPI_VALUE    , "mpi"     },
     422             :     { DBG_CRYPTO_VALUE , "crypto"  },
     423             :     { DBG_MEMORY_VALUE , "memory"  },
     424             :     { DBG_CACHE_VALUE  , "cache"   },
     425             :     { DBG_MEMSTAT_VALUE, "memstat" },
     426             :     { DBG_HASHING_VALUE, "hashing" },
     427             :     { DBG_IPC_VALUE    , "ipc"     },
     428             :     { 0, NULL }
     429             :   };
     430             : 
     431             : 
     432             : /* Global variable to keep an error count. */
     433             : int gpgsm_errors_seen = 0;
     434             : 
     435             : /* It is possible that we are currentlu running under setuid permissions */
     436             : static int maybe_setuid = 1;
     437             : 
     438             : /* Helper to implement --debug-level and --debug*/
     439             : static const char *debug_level;
     440             : static unsigned int debug_value;
     441             : 
     442             : /* Default value for include-certs.  We need an extra macro for
     443             :    gpgconf-list because the variable will be changed by the command
     444             :    line option.
     445             : 
     446             :    It is often cumbersome to locate intermediate certificates, thus by
     447             :    default we include all certificates in the chain.  However we leave
     448             :    out the root certificate because that would make it too easy for
     449             :    the recipient to import that root certificate.  A root certificate
     450             :    should be installed only after due checks and thus it won't help to
     451             :    send it along with each message.  */
     452             : #define DEFAULT_INCLUDE_CERTS -2 /* Include all certs but root. */
     453             : static int default_include_certs = DEFAULT_INCLUDE_CERTS;
     454             : 
     455             : /* Whether the chain mode shall be used for validation.  */
     456             : static int default_validation_model;
     457             : 
     458             : /* The default cipher algo.  */
     459             : #define DEFAULT_CIPHER_ALGO "AES"
     460             : 
     461             : 
     462             : static char *build_list (const char *text,
     463             :                          const char *(*mapf)(int), int (*chkf)(int));
     464             : static void set_cmd (enum cmd_and_opt_values *ret_cmd,
     465             :                      enum cmd_and_opt_values new_cmd );
     466             : 
     467             : static void emergency_cleanup (void);
     468             : static int open_read (const char *filename);
     469             : static estream_t open_es_fread (const char *filename, const char *mode);
     470             : static estream_t open_es_fwrite (const char *filename);
     471             : static void run_protect_tool (int argc, char **argv);
     472             : 
     473             : static int
     474           0 : our_pk_test_algo (int algo)
     475             : {
     476           0 :   switch (algo)
     477             :     {
     478             :     case GCRY_PK_RSA:
     479             :     case GCRY_PK_ECDSA:
     480           0 :       return gcry_pk_test_algo (algo);
     481             :     default:
     482           0 :       return 1;
     483             :     }
     484             : }
     485             : 
     486             : static int
     487           0 : our_cipher_test_algo (int algo)
     488             : {
     489           0 :   switch (algo)
     490             :     {
     491             :     case GCRY_CIPHER_3DES:
     492             :     case GCRY_CIPHER_AES128:
     493             :     case GCRY_CIPHER_AES192:
     494             :     case GCRY_CIPHER_AES256:
     495             :     case GCRY_CIPHER_SERPENT128:
     496             :     case GCRY_CIPHER_SERPENT192:
     497             :     case GCRY_CIPHER_SERPENT256:
     498             :     case GCRY_CIPHER_SEED:
     499             :     case GCRY_CIPHER_CAMELLIA128:
     500             :     case GCRY_CIPHER_CAMELLIA192:
     501             :     case GCRY_CIPHER_CAMELLIA256:
     502           0 :       return gcry_cipher_test_algo (algo);
     503             :     default:
     504           0 :       return 1;
     505             :     }
     506             : }
     507             : 
     508             : 
     509             : static int
     510           0 : our_md_test_algo (int algo)
     511             : {
     512           0 :   switch (algo)
     513             :     {
     514             :     case GCRY_MD_MD5:
     515             :     case GCRY_MD_SHA1:
     516             :     case GCRY_MD_RMD160:
     517             :     case GCRY_MD_SHA224:
     518             :     case GCRY_MD_SHA256:
     519             :     case GCRY_MD_SHA384:
     520             :     case GCRY_MD_SHA512:
     521             :     case GCRY_MD_WHIRLPOOL:
     522           0 :       return gcry_md_test_algo (algo);
     523             :     default:
     524           0 :       return 1;
     525             :     }
     526             : }
     527             : 
     528             : 
     529             : static char *
     530           0 : make_libversion (const char *libname, const char *(*getfnc)(const char*))
     531             : {
     532             :   const char *s;
     533             :   char *result;
     534             : 
     535           0 :   if (maybe_setuid)
     536             :     {
     537           0 :       gcry_control (GCRYCTL_INIT_SECMEM, 0, 0);  /* Drop setuid. */
     538           0 :       maybe_setuid = 0;
     539             :     }
     540           0 :   s = getfnc (NULL);
     541           0 :   result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
     542           0 :   strcpy (stpcpy (stpcpy (result, libname), " "), s);
     543           0 :   return result;
     544             : }
     545             : 
     546             : 
     547             : static const char *
     548           0 : my_strusage( int level )
     549             : {
     550             :   static char *digests, *pubkeys, *ciphers;
     551             :   static char *ver_gcry, *ver_ksba;
     552             :   const char *p;
     553             : 
     554           0 :   switch (level)
     555             :     {
     556           0 :     case 11: p = "@GPGSM@ (@GNUPG@)";
     557           0 :       break;
     558           0 :     case 13: p = VERSION; break;
     559           0 :     case 17: p = PRINTABLE_OS_NAME; break;
     560           0 :     case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
     561             : 
     562             :     case 1:
     563           0 :     case 40: p = _("Usage: @GPGSM@ [options] [files] (-h for help)");
     564           0 :       break;
     565             :     case 41:
     566           0 :       p = _("Syntax: @GPGSM@ [options] [files]\n"
     567             :             "Sign, check, encrypt or decrypt using the S/MIME protocol\n"
     568             :             "Default operation depends on the input data\n");
     569           0 :       break;
     570             : 
     571             :     case 20:
     572           0 :       if (!ver_gcry)
     573           0 :         ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
     574           0 :       p = ver_gcry;
     575           0 :       break;
     576             :     case 21:
     577           0 :       if (!ver_ksba)
     578           0 :         ver_ksba = make_libversion ("libksba", ksba_check_version);
     579           0 :       p = ver_ksba;
     580           0 :       break;
     581             : 
     582           0 :     case 31: p = "\nHome: "; break;
     583           0 :     case 32: p = gnupg_homedir (); break;
     584           0 :     case 33: p = _("\nSupported algorithms:\n"); break;
     585             :     case 34:
     586           0 :       if (!ciphers)
     587           0 :         ciphers = build_list ("Cipher: ", gnupg_cipher_algo_name,
     588             :                               our_cipher_test_algo );
     589           0 :       p = ciphers;
     590           0 :       break;
     591             :     case 35:
     592           0 :       if (!pubkeys)
     593           0 :         pubkeys = build_list ("Pubkey: ", gcry_pk_algo_name,
     594             :                               our_pk_test_algo );
     595           0 :       p = pubkeys;
     596           0 :       break;
     597             :     case 36:
     598           0 :       if (!digests)
     599           0 :         digests = build_list("Hash: ", gcry_md_algo_name, our_md_test_algo );
     600           0 :       p = digests;
     601           0 :       break;
     602             : 
     603           0 :     default: p = NULL; break;
     604             :     }
     605           0 :   return p;
     606             : }
     607             : 
     608             : 
     609             : static char *
     610           0 : build_list (const char *text, const char * (*mapf)(int), int (*chkf)(int))
     611             : {
     612             :   int i;
     613           0 :   size_t n=strlen(text)+2;
     614             :   char *list, *p;
     615             : 
     616           0 :   if (maybe_setuid) {
     617           0 :     gcry_control (GCRYCTL_DROP_PRIVS); /* drop setuid */
     618             :   }
     619             : 
     620           0 :   for (i=1; i < 400; i++ )
     621           0 :     if (!chkf(i))
     622           0 :       n += strlen(mapf(i)) + 2;
     623           0 :   list = xmalloc (21 + n);
     624           0 :   *list = 0;
     625           0 :   for (p=NULL, i=1; i < 400; i++)
     626             :     {
     627           0 :       if (!chkf(i))
     628             :         {
     629           0 :           if( !p )
     630           0 :             p = stpcpy (list, text );
     631             :           else
     632           0 :             p = stpcpy (p, ", ");
     633           0 :           p = stpcpy (p, mapf(i) );
     634             :         }
     635             :     }
     636           0 :   if (p)
     637           0 :     strcpy (p, "\n" );
     638           0 :   return list;
     639             : }
     640             : 
     641             : 
     642             : /* Set the file pointer into binary mode if required.  */
     643             : static void
     644           0 : set_binary (FILE *fp)
     645             : {
     646             : #ifdef HAVE_DOSISH_SYSTEM
     647             :   setmode (fileno (fp), O_BINARY);
     648             : #else
     649             :   (void)fp;
     650             : #endif
     651           0 : }
     652             : 
     653             : 
     654             : 
     655             : static void
     656           0 : wrong_args (const char *text)
     657             : {
     658           0 :   fprintf (stderr, _("usage: %s [options] %s\n"), GPGSM_NAME, text);
     659           0 :   gpgsm_exit (2);
     660           0 : }
     661             : 
     662             : 
     663             : static void
     664           0 : set_opt_session_env (const char *name, const char *value)
     665             : {
     666             :   gpg_error_t err;
     667             : 
     668           0 :   err = session_env_setenv (opt.session_env, name, value);
     669           0 :   if (err)
     670           0 :     log_fatal ("error setting session environment: %s\n",
     671             :                gpg_strerror (err));
     672           0 : }
     673             : 
     674             : 
     675             : /* Setup the debugging.  With a DEBUG_LEVEL of NULL only the active
     676             :    debug flags are propagated to the subsystems.  With DEBUG_LEVEL
     677             :    set, a specific set of debug flags is set; and individual debugging
     678             :    flags will be added on top.  */
     679             : static void
     680           3 : set_debug (void)
     681             : {
     682           3 :   int numok = (debug_level && digitp (debug_level));
     683           3 :   int numlvl = numok? atoi (debug_level) : 0;
     684             : 
     685           3 :   if (!debug_level)
     686             :     ;
     687           0 :   else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
     688           0 :     opt.debug = 0;
     689           0 :   else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
     690           0 :     opt.debug = DBG_IPC_VALUE;
     691           0 :   else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
     692           0 :     opt.debug = DBG_IPC_VALUE|DBG_X509_VALUE;
     693           0 :   else if (!strcmp (debug_level, "expert")  || (numok && numlvl <= 8))
     694           0 :     opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE
     695             :                  |DBG_CACHE_VALUE|DBG_CRYPTO_VALUE);
     696           0 :   else if (!strcmp (debug_level, "guru") || numok)
     697             :     {
     698           0 :       opt.debug = ~0;
     699             :       /* Unless the "guru" string has been used we don't want to allow
     700             :          hashing debugging.  The rationale is that people tend to
     701             :          select the highest debug value and would then clutter their
     702             :          disk with debug files which may reveal confidential data.  */
     703           0 :       if (numok)
     704           0 :         opt.debug &= ~(DBG_HASHING_VALUE);
     705             :     }
     706             :   else
     707             :     {
     708           0 :       log_error (_("invalid debug-level '%s' given\n"), debug_level);
     709           0 :       gpgsm_exit (2);
     710             :     }
     711             : 
     712           3 :   opt.debug |= debug_value;
     713             : 
     714           3 :   if (opt.debug && !opt.verbose)
     715           0 :     opt.verbose = 1;
     716           3 :   if (opt.debug)
     717           0 :     opt.quiet = 0;
     718             : 
     719           3 :   if (opt.debug & DBG_MPI_VALUE)
     720           0 :     gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
     721           3 :   if (opt.debug & DBG_CRYPTO_VALUE )
     722           0 :     gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
     723           3 :   gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
     724             : 
     725           3 :   if (opt.debug)
     726           0 :     parse_debug_flag (NULL, &opt.debug, debug_flags);
     727           3 : }
     728             : 
     729             : 
     730             : 
     731             : static void
     732           3 : set_cmd (enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd)
     733             : {
     734           3 :   enum cmd_and_opt_values cmd = *ret_cmd;
     735             : 
     736           3 :   if (!cmd || cmd == new_cmd)
     737           3 :     cmd = new_cmd;
     738           0 :   else if ( cmd == aSign && new_cmd == aEncr )
     739           0 :     cmd = aSignEncr;
     740           0 :   else if ( cmd == aEncr && new_cmd == aSign )
     741           0 :     cmd = aSignEncr;
     742           0 :   else if ( (cmd == aSign && new_cmd == aClearsign)
     743           0 :             || (cmd == aClearsign && new_cmd == aSign) )
     744           0 :     cmd = aClearsign;
     745             :   else
     746             :     {
     747           0 :       log_error(_("conflicting commands\n"));
     748           0 :       gpgsm_exit(2);
     749             :     }
     750             : 
     751           3 :   *ret_cmd = cmd;
     752           3 : }
     753             : 
     754             : 
     755             : /* Helper to add recipients to a list. */
     756             : static void
     757           0 : do_add_recipient (ctrl_t ctrl, const char *name,
     758             :                   certlist_t *recplist, int is_encrypt_to, int recp_required)
     759             : {
     760           0 :   int rc = gpgsm_add_to_certlist (ctrl, name, 0, recplist, is_encrypt_to);
     761           0 :   if (rc)
     762             :     {
     763           0 :       if (recp_required)
     764             :         {
     765           0 :           log_error ("can't encrypt to '%s': %s\n", name, gpg_strerror (rc));
     766           0 :           gpgsm_status2 (ctrl, STATUS_INV_RECP,
     767             :                          get_inv_recpsgnr_code (rc), name, NULL);
     768             :         }
     769             :       else
     770           0 :         log_info (_("Note: won't be able to encrypt to '%s': %s\n"),
     771             :                   name, gpg_strerror (rc));
     772             :     }
     773           0 : }
     774             : 
     775             : 
     776             : static void
     777           0 : parse_validation_model (const char *model)
     778             : {
     779           0 :   int i = gpgsm_parse_validation_model (model);
     780           0 :   if (i == -1)
     781           0 :     log_error (_("unknown validation model '%s'\n"), model);
     782             :   else
     783           0 :     default_validation_model = i;
     784           0 : }
     785             : 
     786             : 
     787             : /* Release the list of SERVERS.  As usual it is okay to call this
     788             :    function with SERVERS passed as NULL.  */
     789             : void
     790           3 : keyserver_list_free (struct keyserver_spec *servers)
     791             : {
     792           6 :   while (servers)
     793             :     {
     794           0 :       struct keyserver_spec *tmp = servers->next;
     795           0 :       xfree (servers->host);
     796           0 :       xfree (servers->user);
     797           0 :       if (servers->pass)
     798           0 :         memset (servers->pass, 0, strlen (servers->pass));
     799           0 :       xfree (servers->pass);
     800           0 :       xfree (servers->base);
     801           0 :       xfree (servers);
     802           0 :       servers = tmp;
     803             :     }
     804           3 : }
     805             : 
     806             : /* See also dirmngr ldapserver_parse_one().  */
     807             : struct keyserver_spec *
     808           0 : parse_keyserver_line (char *line,
     809             :                       const char *filename, unsigned int lineno)
     810             : {
     811             :   char *p;
     812             :   char *endp;
     813             :   struct keyserver_spec *server;
     814             :   int fieldno;
     815           0 :   int fail = 0;
     816             : 
     817             :   /* Parse the colon separated fields.  */
     818           0 :   server = xcalloc (1, sizeof *server);
     819           0 :   for (fieldno = 1, p = line; p; p = endp, fieldno++ )
     820             :     {
     821           0 :       endp = strchr (p, ':');
     822           0 :       if (endp)
     823           0 :         *endp++ = '\0';
     824           0 :       trim_spaces (p);
     825           0 :       switch (fieldno)
     826             :         {
     827             :         case 1:
     828           0 :           if (*p)
     829           0 :             server->host = xstrdup (p);
     830             :           else
     831             :             {
     832           0 :               log_error (_("%s:%u: no hostname given\n"),
     833             :                          filename, lineno);
     834           0 :               fail = 1;
     835             :             }
     836           0 :           break;
     837             : 
     838             :         case 2:
     839           0 :           if (*p)
     840           0 :             server->port = atoi (p);
     841           0 :           break;
     842             : 
     843             :         case 3:
     844           0 :           if (*p)
     845           0 :             server->user = xstrdup (p);
     846           0 :           break;
     847             : 
     848             :         case 4:
     849           0 :           if (*p && !server->user)
     850             :             {
     851           0 :               log_error (_("%s:%u: password given without user\n"),
     852             :                          filename, lineno);
     853           0 :               fail = 1;
     854             :             }
     855           0 :           else if (*p)
     856           0 :             server->pass = xstrdup (p);
     857           0 :           break;
     858             : 
     859             :         case 5:
     860           0 :           if (*p)
     861           0 :             server->base = xstrdup (p);
     862           0 :           break;
     863             : 
     864             :         default:
     865             :           /* (We silently ignore extra fields.) */
     866           0 :           break;
     867             :         }
     868             :     }
     869             : 
     870           0 :   if (fail)
     871             :     {
     872           0 :       log_info (_("%s:%u: skipping this line\n"), filename, lineno);
     873           0 :       keyserver_list_free (server);
     874           0 :       server = NULL;
     875             :     }
     876             : 
     877           0 :   return server;
     878             : }
     879             : 
     880             : 
     881             : int
     882           3 : main ( int argc, char **argv)
     883             : {
     884             :   ARGPARSE_ARGS pargs;
     885             :   int orig_argc;
     886             :   char **orig_argv;
     887             :   /*  char *username;*/
     888             :   int may_coredump;
     889           3 :   strlist_t sl, remusr= NULL, locusr=NULL;
     890           3 :   strlist_t nrings=NULL;
     891           3 :   int detached_sig = 0;
     892           3 :   FILE *configfp = NULL;
     893           3 :   char *configname = NULL;
     894             :   unsigned configlineno;
     895           3 :   int parse_debug = 0;
     896           3 :   int no_more_options = 0;
     897           3 :   int default_config =1;
     898           3 :   int default_keyring = 1;
     899           3 :   char *logfile = NULL;
     900           3 :   char *auditlog = NULL;
     901           3 :   char *htmlauditlog = NULL;
     902           3 :   int greeting = 0;
     903           3 :   int nogreeting = 0;
     904           3 :   int debug_wait = 0;
     905           3 :   int use_random_seed = 1;
     906           3 :   int no_common_certs_import = 0;
     907           3 :   int with_fpr = 0;
     908           3 :   const char *forced_digest_algo = NULL;
     909           3 :   const char *extra_digest_algo = NULL;
     910           3 :   enum cmd_and_opt_values cmd = 0;
     911             :   struct server_control_s ctrl;
     912           3 :   certlist_t recplist = NULL;
     913           3 :   certlist_t signerlist = NULL;
     914           3 :   int do_not_setup_keys = 0;
     915           3 :   int recp_required = 0;
     916           3 :   estream_t auditfp = NULL;
     917           3 :   estream_t htmlauditfp = NULL;
     918             :   struct assuan_malloc_hooks malloc_hooks;
     919           3 :   int pwfd = -1;
     920             :   /*mtrace();*/
     921             : 
     922           3 :   early_system_init ();
     923           3 :   gnupg_reopen_std (GPGSM_NAME);
     924             :   /* trap_unaligned ();*/
     925           3 :   gnupg_rl_initialize ();
     926           3 :   set_strusage (my_strusage);
     927           3 :   gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
     928             : 
     929             :   /* Please note that we may running SUID(ROOT), so be very CAREFUL
     930             :      when adding any stuff between here and the call to secmem_init()
     931             :      somewhere after the option parsing */
     932           3 :   log_set_prefix (GPGSM_NAME, GPGRT_LOG_WITH_PREFIX);
     933             : 
     934             :   /* Make sure that our subsystems are ready.  */
     935           3 :   i18n_init ();
     936           3 :   init_common_subsystems (&argc, &argv);
     937             : 
     938             :   /* Check that the libraries are suitable.  Do it here because the
     939             :      option parse may need services of the library */
     940           3 :   if (!ksba_check_version (NEED_KSBA_VERSION) )
     941           0 :     log_fatal (_("%s is too old (need %s, have %s)\n"), "libksba",
     942             :                NEED_KSBA_VERSION, ksba_check_version (NULL) );
     943             : 
     944             : 
     945           3 :   gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
     946             : 
     947           3 :   may_coredump = disable_core_dumps ();
     948             : 
     949           3 :   gnupg_init_signals (0, emergency_cleanup);
     950             : 
     951           3 :   dotlock_create (NULL, 0); /* Register lockfile cleanup.  */
     952             : 
     953           3 :   opt.autostart = 1;
     954           3 :   opt.session_env = session_env_new ();
     955           3 :   if (!opt.session_env)
     956           0 :     log_fatal ("error allocating session environment block: %s\n",
     957           0 :                strerror (errno));
     958             : 
     959             :   /* Note: If you change this default cipher algorithm , please
     960             :      remember to update the Gpgconflist entry as well.  */
     961           3 :   opt.def_cipher_algoid = DEFAULT_CIPHER_ALGO;
     962             : 
     963             : 
     964             :   /* First check whether we have a config file on the commandline */
     965           3 :   orig_argc = argc;
     966           3 :   orig_argv = argv;
     967           3 :   pargs.argc = &argc;
     968           3 :   pargs.argv = &argv;
     969           3 :   pargs.flags= 1|(1<<6);  /* do not remove the args, ignore version */
     970           9 :   while (arg_parse( &pargs, opts))
     971             :     {
     972           3 :       if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
     973           0 :         parse_debug++;
     974           3 :       else if (pargs.r_opt == oOptions)
     975             :         { /* yes there is one, so we do not try the default one but
     976             :              read the config file when it is encountered at the
     977             :              commandline */
     978           0 :           default_config = 0;
     979             :         }
     980           3 :       else if (pargs.r_opt == oNoOptions)
     981             :         {
     982           0 :           default_config = 0; /* --no-options */
     983           0 :           opt.no_homedir_creation = 1;
     984             :         }
     985           3 :       else if (pargs.r_opt == oHomedir)
     986           0 :         gnupg_set_homedir (pargs.r.ret_str);
     987           3 :       else if (pargs.r_opt == aCallProtectTool)
     988           0 :         break; /* This break makes sure that --version and --help are
     989             :                   passed to the protect-tool. */
     990             :     }
     991             : 
     992             : 
     993             :   /* Initialize the secure memory. */
     994           3 :   gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
     995           3 :   maybe_setuid = 0;
     996             : 
     997             :   /*
     998             :      Now we are now working under our real uid
     999             :   */
    1000             : 
    1001           3 :   ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
    1002             : 
    1003           3 :   malloc_hooks.malloc = gcry_malloc;
    1004           3 :   malloc_hooks.realloc = gcry_realloc;
    1005           3 :   malloc_hooks.free = gcry_free;
    1006           3 :   assuan_set_malloc_hooks (&malloc_hooks);
    1007           3 :   assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
    1008           3 :   setup_libassuan_logging (&opt.debug, NULL);
    1009             : 
    1010           3 :   keybox_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
    1011             : 
    1012             :   /* Setup a default control structure for command line mode */
    1013           3 :   memset (&ctrl, 0, sizeof ctrl);
    1014           3 :   gpgsm_init_default_ctrl (&ctrl);
    1015           3 :   ctrl.no_server = 1;
    1016           3 :   ctrl.status_fd = -1; /* No status output. */
    1017           3 :   ctrl.autodetect_encoding = 1;
    1018             : 
    1019             :   /* Set the default option file */
    1020           3 :   if (default_config )
    1021           3 :     configname = make_filename (gnupg_homedir (),
    1022             :                                 GPGSM_NAME EXTSEP_S "conf", NULL);
    1023             :   /* Set the default policy file */
    1024           3 :   opt.policy_file = make_filename (gnupg_homedir (), "policies.txt", NULL);
    1025             : 
    1026           3 :   argc        = orig_argc;
    1027           3 :   argv        = orig_argv;
    1028           3 :   pargs.argc  = &argc;
    1029           3 :   pargs.argv  = &argv;
    1030           3 :   pargs.flags =  1;  /* do not remove the args */
    1031             : 
    1032             :  next_pass:
    1033           6 :   if (configname) {
    1034           3 :     configlineno = 0;
    1035           3 :     configfp = fopen (configname, "r");
    1036           3 :     if (!configfp)
    1037             :       {
    1038           0 :         if (default_config)
    1039             :           {
    1040           0 :             if (parse_debug)
    1041           0 :               log_info (_("Note: no default option file '%s'\n"), configname);
    1042             :           }
    1043             :         else
    1044             :           {
    1045           0 :             log_error (_("option file '%s': %s\n"), configname, strerror(errno));
    1046           0 :             gpgsm_exit(2);
    1047             :           }
    1048           0 :         xfree(configname);
    1049           0 :         configname = NULL;
    1050             :       }
    1051           3 :     if (parse_debug && configname)
    1052           0 :       log_info (_("reading options from '%s'\n"), configname);
    1053           3 :     default_config = 0;
    1054             :   }
    1055             : 
    1056          27 :   while (!no_more_options
    1057          21 :          && optfile_parse (configfp, configname, &configlineno, &pargs, opts))
    1058             :     {
    1059          15 :       switch (pargs.r_opt)
    1060             :         {
    1061             :         case aGPGConfList:
    1062             :         case aGPGConfTest:
    1063           0 :           set_cmd (&cmd, pargs.r_opt);
    1064           0 :           do_not_setup_keys = 1;
    1065           0 :           nogreeting = 1;
    1066           0 :           break;
    1067             : 
    1068             :         case aServer:
    1069           0 :           opt.batch = 1;
    1070           0 :           set_cmd (&cmd, aServer);
    1071           0 :           break;
    1072             : 
    1073             :         case aCallDirmngr:
    1074           0 :           opt.batch = 1;
    1075           0 :           set_cmd (&cmd, aCallDirmngr);
    1076           0 :           do_not_setup_keys = 1;
    1077           0 :           break;
    1078             : 
    1079             :         case aCallProtectTool:
    1080           0 :           opt.batch = 1;
    1081           0 :           set_cmd (&cmd, aCallProtectTool);
    1082           0 :           no_more_options = 1; /* Stop parsing. */
    1083           0 :           do_not_setup_keys = 1;
    1084           0 :           break;
    1085             : 
    1086             :         case aDeleteKey:
    1087           0 :           set_cmd (&cmd, aDeleteKey);
    1088             :           /*greeting=1;*/
    1089           0 :           do_not_setup_keys = 1;
    1090           0 :           break;
    1091             : 
    1092             :         case aDetachedSign:
    1093           0 :           detached_sig = 1;
    1094           0 :           set_cmd (&cmd, aSign );
    1095           0 :           break;
    1096             : 
    1097             :         case aKeygen:
    1098           0 :           set_cmd (&cmd, aKeygen);
    1099           0 :           greeting=1;
    1100           0 :           do_not_setup_keys = 1;
    1101           0 :           break;
    1102             : 
    1103             :         case aImport:
    1104             :         case aSendKeys:
    1105             :         case aRecvKeys:
    1106             :         case aExport:
    1107             :         case aExportSecretKeyP12:
    1108             :         case aExportSecretKeyP8:
    1109             :         case aExportSecretKeyRaw:
    1110             :         case aDumpKeys:
    1111             :         case aDumpChain:
    1112             :         case aDumpExternalKeys:
    1113             :         case aDumpSecretKeys:
    1114             :         case aListKeys:
    1115             :         case aListExternalKeys:
    1116             :         case aListSecretKeys:
    1117             :         case aListChain:
    1118             :         case aLearnCard:
    1119             :         case aPasswd:
    1120             :         case aKeydbClearSomeCertFlags:
    1121           3 :           do_not_setup_keys = 1;
    1122           3 :           set_cmd (&cmd, pargs.r_opt);
    1123           3 :           break;
    1124             : 
    1125             :         case aEncr:
    1126           0 :           recp_required = 1;
    1127           0 :           set_cmd (&cmd, pargs.r_opt);
    1128           0 :           break;
    1129             : 
    1130             :         case aSym:
    1131             :         case aDecrypt:
    1132             :         case aSign:
    1133             :         case aClearsign:
    1134             :         case aVerify:
    1135           0 :           set_cmd (&cmd, pargs.r_opt);
    1136           0 :           break;
    1137             : 
    1138             :           /* Output encoding selection.  */
    1139             :         case oArmor:
    1140           0 :           ctrl.create_pem = 1;
    1141           0 :           break;
    1142             :         case oBase64:
    1143           0 :           ctrl.create_pem = 0;
    1144           0 :           ctrl.create_base64 = 1;
    1145           0 :           break;
    1146             :         case oNoArmor:
    1147           0 :           ctrl.create_pem = 0;
    1148           0 :           ctrl.create_base64 = 0;
    1149           0 :           break;
    1150             : 
    1151             :         case oP12Charset:
    1152           0 :           opt.p12_charset = pargs.r.ret_str;
    1153           0 :           break;
    1154             : 
    1155             :         case oPassphraseFD:
    1156           0 :           pwfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
    1157           0 :           break;
    1158             : 
    1159             :         case oPinentryMode:
    1160           0 :           opt.pinentry_mode = parse_pinentry_mode (pargs.r.ret_str);
    1161           0 :           if (opt.pinentry_mode == -1)
    1162           0 :             log_error (_("invalid pinentry mode '%s'\n"), pargs.r.ret_str);
    1163           0 :           break;
    1164             : 
    1165             :           /* Input encoding selection.  */
    1166             :         case oAssumeArmor:
    1167           0 :           ctrl.autodetect_encoding = 0;
    1168           0 :           ctrl.is_pem = 1;
    1169           0 :           ctrl.is_base64 = 0;
    1170           0 :           break;
    1171             :         case oAssumeBase64:
    1172           0 :           ctrl.autodetect_encoding = 0;
    1173           0 :           ctrl.is_pem = 0;
    1174           0 :           ctrl.is_base64 = 1;
    1175           0 :           break;
    1176             :         case oAssumeBinary:
    1177           0 :           ctrl.autodetect_encoding = 0;
    1178           0 :           ctrl.is_pem = 0;
    1179           0 :           ctrl.is_base64 = 0;
    1180           0 :           break;
    1181             : 
    1182             :         case oDisableCRLChecks:
    1183           3 :           opt.no_crl_check = 1;
    1184           3 :           break;
    1185             :         case oEnableCRLChecks:
    1186           0 :           opt.no_crl_check = 0;
    1187           0 :           break;
    1188             :         case oDisableTrustedCertCRLCheck:
    1189           0 :           opt.no_trusted_cert_crl_check = 1;
    1190           0 :           break;
    1191             :         case oEnableTrustedCertCRLCheck:
    1192           0 :           opt.no_trusted_cert_crl_check = 0;
    1193           0 :           break;
    1194             :         case oForceCRLRefresh:
    1195           0 :           opt.force_crl_refresh = 1;
    1196           0 :           break;
    1197             : 
    1198             :         case oDisableOCSP:
    1199           0 :           ctrl.use_ocsp = opt.enable_ocsp = 0;
    1200           0 :           break;
    1201             :         case oEnableOCSP:
    1202           0 :           ctrl.use_ocsp = opt.enable_ocsp = 1;
    1203           0 :           break;
    1204             : 
    1205             :         case oIncludeCerts:
    1206           0 :           ctrl.include_certs = default_include_certs = pargs.r.ret_int;
    1207           0 :           break;
    1208             : 
    1209             :         case oPolicyFile:
    1210           0 :           xfree (opt.policy_file);
    1211           0 :           if (*pargs.r.ret_str)
    1212           0 :             opt.policy_file = xstrdup (pargs.r.ret_str);
    1213             :           else
    1214           0 :             opt.policy_file = NULL;
    1215           0 :           break;
    1216             : 
    1217             :         case oDisablePolicyChecks:
    1218           0 :           opt.no_policy_check = 1;
    1219           0 :           break;
    1220             :         case oEnablePolicyChecks:
    1221           0 :           opt.no_policy_check = 0;
    1222           0 :           break;
    1223             : 
    1224             :         case oAutoIssuerKeyRetrieve:
    1225           0 :           opt.auto_issuer_key_retrieve = 1;
    1226           0 :           break;
    1227             : 
    1228           0 :         case oOutput: opt.outfile = pargs.r.ret_str; break;
    1229             : 
    1230             : 
    1231           0 :         case oQuiet: opt.quiet = 1; break;
    1232           0 :         case oNoTTY: /* fixme:tty_no_terminal(1);*/ break;
    1233           0 :         case oDryRun: opt.dry_run = 1; break;
    1234             : 
    1235             :         case oVerbose:
    1236           0 :           opt.verbose++;
    1237           0 :           gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
    1238           0 :           break;
    1239             :         case oNoVerbose:
    1240           0 :           opt.verbose = 0;
    1241           0 :           gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
    1242           0 :           break;
    1243             : 
    1244           0 :         case oLogFile: logfile = pargs.r.ret_str; break;
    1245           0 :         case oNoLogFile: logfile = NULL; break;
    1246             : 
    1247           0 :         case oAuditLog: auditlog = pargs.r.ret_str; break;
    1248           0 :         case oHtmlAuditLog: htmlauditlog = pargs.r.ret_str; break;
    1249             : 
    1250             :         case oBatch:
    1251           0 :           opt.batch = 1;
    1252           0 :           greeting = 0;
    1253           0 :           break;
    1254           0 :         case oNoBatch: opt.batch = 0; break;
    1255             : 
    1256           0 :         case oAnswerYes: opt.answer_yes = 1; break;
    1257           0 :         case oAnswerNo: opt.answer_no = 1; break;
    1258             : 
    1259           0 :         case oKeyring: append_to_strlist (&nrings, pargs.r.ret_str); break;
    1260             : 
    1261             :         case oDebug:
    1262           0 :           if (parse_debug_flag (pargs.r.ret_str, &debug_value, debug_flags))
    1263             :             {
    1264           0 :               pargs.r_opt = ARGPARSE_INVALID_ARG;
    1265           0 :               pargs.err = ARGPARSE_PRINT_ERROR;
    1266             :             }
    1267           0 :           break;
    1268           0 :         case oDebugAll: debug_value = ~0; break;
    1269           0 :         case oDebugNone: debug_value = 0; break;
    1270           0 :         case oDebugLevel: debug_level = pargs.r.ret_str; break;
    1271           0 :         case oDebugWait: debug_wait = pargs.r.ret_int; break;
    1272             :         case oDebugAllowCoreDump:
    1273           0 :           may_coredump = enable_core_dumps ();
    1274           0 :           break;
    1275           0 :         case oDebugNoChainValidation: opt.no_chain_validation = 1; break;
    1276           0 :         case oDebugIgnoreExpiration: opt.ignore_expiration = 1; break;
    1277             : 
    1278           0 :         case oStatusFD: ctrl.status_fd = pargs.r.ret_int; break;
    1279           0 :         case oLoggerFD: log_set_fd (pargs.r.ret_int ); break;
    1280             :         case oWithMD5Fingerprint:
    1281           0 :           opt.with_md5_fingerprint=1; /*fall through*/
    1282             :         case oWithFingerprint:
    1283           0 :           with_fpr=1; /*fall through*/
    1284             :         case aFingerprint:
    1285           0 :           opt.fingerprint++;
    1286           0 :           break;
    1287             : 
    1288             :         case oWithKeygrip:
    1289           0 :           opt.with_keygrip = 1;
    1290           0 :           break;
    1291             : 
    1292             :         case oOptions:
    1293             :           /* config files may not be nested (silently ignore them) */
    1294           0 :           if (!configfp)
    1295             :             {
    1296           0 :               xfree(configname);
    1297           0 :               configname = xstrdup (pargs.r.ret_str);
    1298           0 :               goto next_pass;
    1299             :             }
    1300           0 :           break;
    1301           0 :         case oNoOptions: opt.no_homedir_creation = 1; break; /* no-options */
    1302           0 :         case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break;
    1303           3 :         case oAgentProgram: opt.agent_program = pargs.r.ret_str;  break;
    1304             : 
    1305             :         case oDisplay:
    1306           0 :           set_opt_session_env ("DISPLAY", pargs.r.ret_str);
    1307           0 :           break;
    1308             :         case oTTYname:
    1309           0 :           set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
    1310           0 :           break;
    1311             :         case oTTYtype:
    1312           0 :           set_opt_session_env ("TERM", pargs.r.ret_str);
    1313           0 :           break;
    1314             :         case oXauthority:
    1315           0 :           set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
    1316           0 :           break;
    1317             : 
    1318           0 :         case oLCctype: opt.lc_ctype = xstrdup (pargs.r.ret_str); break;
    1319           0 :         case oLCmessages: opt.lc_messages = xstrdup (pargs.r.ret_str); break;
    1320             : 
    1321           0 :         case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str;  break;
    1322           0 :         case oDisableDirmngr: opt.disable_dirmngr = 1;  break;
    1323           0 :         case oPreferSystemDirmngr: /* Obsolete */; break;
    1324             :         case oProtectToolProgram:
    1325           0 :           opt.protect_tool_program = pargs.r.ret_str;
    1326           0 :           break;
    1327             : 
    1328             :         case oFakedSystemTime:
    1329             :           {
    1330           3 :             time_t faked_time = isotime2epoch (pargs.r.ret_str);
    1331           3 :             if (faked_time == (time_t)(-1))
    1332           3 :               faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
    1333           3 :             gnupg_set_time (faked_time, 0);
    1334             :           }
    1335           3 :           break;
    1336             : 
    1337           0 :         case oNoDefKeyring: default_keyring = 0; break;
    1338           0 :         case oNoGreeting: nogreeting = 1; break;
    1339             : 
    1340             :         case oDefaultKey:
    1341           0 :           if (*pargs.r.ret_str)
    1342             :             {
    1343           0 :               xfree (opt.local_user);
    1344           0 :               opt.local_user = xstrdup (pargs.r.ret_str);
    1345             :             }
    1346           0 :           break;
    1347             :         case oDefRecipient:
    1348           0 :           if (*pargs.r.ret_str)
    1349           0 :             opt.def_recipient = xstrdup (pargs.r.ret_str);
    1350           0 :           break;
    1351             :         case oDefRecipientSelf:
    1352           0 :           xfree (opt.def_recipient);
    1353           0 :           opt.def_recipient = NULL;
    1354           0 :           opt.def_recipient_self = 1;
    1355           0 :           break;
    1356             :         case oNoDefRecipient:
    1357           0 :           xfree (opt.def_recipient);
    1358           0 :           opt.def_recipient = NULL;
    1359           0 :           opt.def_recipient_self = 0;
    1360           0 :           break;
    1361             : 
    1362           0 :         case oWithKeyData: opt.with_key_data=1; /* fall through */
    1363           0 :         case oWithColons: ctrl.with_colons = 1; break;
    1364           0 :         case oWithSecret: ctrl.with_secret = 1; break;
    1365           0 :         case oWithValidation: ctrl.with_validation=1; break;
    1366           0 :         case oWithEphemeralKeys: ctrl.with_ephemeral_keys=1; break;
    1367             : 
    1368           0 :         case oSkipVerify: opt.skip_verify=1; break;
    1369             : 
    1370           0 :         case oNoEncryptTo: opt.no_encrypt_to = 1; break;
    1371             :         case oEncryptTo: /* Store the recipient in the second list */
    1372           0 :           sl = add_to_strlist (&remusr, pargs.r.ret_str);
    1373           0 :           sl->flags = 1;
    1374           0 :           break;
    1375             : 
    1376             :         case oRecipient: /* store the recipient */
    1377           0 :           add_to_strlist ( &remusr, pargs.r.ret_str);
    1378           0 :           break;
    1379             : 
    1380             :         case oUser: /* Store the local users, the first one is the default */
    1381           0 :           if (!opt.local_user)
    1382           0 :             opt.local_user = xstrdup (pargs.r.ret_str);
    1383           0 :           add_to_strlist (&locusr, pargs.r.ret_str);
    1384           0 :           break;
    1385             : 
    1386             :         case oNoSecmemWarn:
    1387           3 :           gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
    1388           3 :           break;
    1389             : 
    1390             :         case oCipherAlgo:
    1391           0 :           opt.def_cipher_algoid = pargs.r.ret_str;
    1392           0 :           break;
    1393             : 
    1394             :         case oDisableCipherAlgo:
    1395             :           {
    1396           0 :             int algo = gcry_cipher_map_name (pargs.r.ret_str);
    1397           0 :             gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
    1398             :           }
    1399           0 :           break;
    1400             :         case oDisablePubkeyAlgo:
    1401             :           {
    1402           0 :             int algo = gcry_pk_map_name (pargs.r.ret_str);
    1403           0 :             gcry_pk_ctl (GCRYCTL_DISABLE_ALGO,&algo, sizeof algo );
    1404             :           }
    1405           0 :           break;
    1406             : 
    1407             :         case oDigestAlgo:
    1408           0 :           forced_digest_algo = pargs.r.ret_str;
    1409           0 :           break;
    1410             : 
    1411             :         case oExtraDigestAlgo:
    1412           0 :           extra_digest_algo = pargs.r.ret_str;
    1413           0 :           break;
    1414             : 
    1415           0 :         case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
    1416           0 :         case oNoRandomSeedFile: use_random_seed = 0; break;
    1417           0 :         case oNoCommonCertsImport: no_common_certs_import = 1; break;
    1418             : 
    1419             :         case oEnableSpecialFilenames:
    1420           0 :           enable_special_filenames ();
    1421           0 :           break;
    1422             : 
    1423           0 :         case oValidationModel: parse_validation_model (pargs.r.ret_str); break;
    1424             : 
    1425             :         case oKeyServer:
    1426             :           {
    1427             :             struct keyserver_spec *keyserver;
    1428           0 :             keyserver = parse_keyserver_line (pargs.r.ret_str,
    1429             :                                               configname, configlineno);
    1430           0 :             if (! keyserver)
    1431           0 :               log_error (_("could not parse keyserver\n"));
    1432             :             else
    1433             :               {
    1434             :                 /* FIXME: Keep last next pointer.  */
    1435           0 :                 struct keyserver_spec **next_p = &opt.keyserver;
    1436           0 :                 while (*next_p)
    1437           0 :                   next_p = &(*next_p)->next;
    1438           0 :                 *next_p = keyserver;
    1439             :               }
    1440             :           }
    1441           0 :           break;
    1442             : 
    1443             :         case oIgnoreCertExtension:
    1444           0 :           add_to_strlist (&opt.ignored_cert_extensions, pargs.r.ret_str);
    1445           0 :           break;
    1446             : 
    1447           0 :         case oNoAutostart: opt.autostart = 0; break;
    1448             : 
    1449             :         case oCompliance:
    1450             :           /* Dummy option for now.  */
    1451           0 :           break;
    1452             : 
    1453             :         default:
    1454           0 :           pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
    1455           0 :           break;
    1456             :         }
    1457             :     }
    1458             : 
    1459           6 :   if (configfp)
    1460             :     {
    1461           3 :       fclose (configfp);
    1462           3 :       configfp = NULL;
    1463             :       /* Keep a copy of the config filename. */
    1464           3 :       opt.config_filename = configname;
    1465           3 :       configname = NULL;
    1466           3 :       goto next_pass;
    1467             :     }
    1468           3 :   xfree (configname);
    1469           3 :   configname = NULL;
    1470             : 
    1471           3 :   if (!opt.config_filename)
    1472           0 :     opt.config_filename = make_filename (gnupg_homedir (),
    1473             :                                          GPGSM_NAME EXTSEP_S "conf",
    1474             :                                          NULL);
    1475             : 
    1476           3 :   if (log_get_errorcount(0))
    1477           0 :     gpgsm_exit(2);
    1478             : 
    1479           3 :   if (pwfd != -1)       /* Read the passphrase now.  */
    1480           0 :     read_passphrase_from_fd (pwfd);
    1481             : 
    1482             :   /* Now that we have the options parsed we need to update the default
    1483             :      control structure.  */
    1484           3 :   gpgsm_init_default_ctrl (&ctrl);
    1485             : 
    1486           3 :   if (nogreeting)
    1487           0 :     greeting = 0;
    1488             : 
    1489           3 :   if (greeting)
    1490             :     {
    1491           0 :       es_fprintf (es_stderr, "%s %s; %s\n",
    1492             :                   strusage(11), strusage(13), strusage(14) );
    1493           0 :       es_fprintf (es_stderr, "%s\n", strusage(15) );
    1494             :     }
    1495             : #  ifdef IS_DEVELOPMENT_VERSION
    1496             :   if (!opt.batch)
    1497             :     {
    1498             :       log_info ("NOTE: THIS IS A DEVELOPMENT VERSION!\n");
    1499             :       log_info ("It is only intended for test purposes and should NOT be\n");
    1500             :       log_info ("used in a production environment or with production keys!\n");
    1501             :     }
    1502             : #  endif
    1503             : 
    1504           3 :   if (may_coredump && !opt.quiet)
    1505           0 :     log_info (_("WARNING: program may create a core file!\n"));
    1506             : 
    1507             : /*   if (opt.qualsig_approval && !opt.quiet) */
    1508             : /*     log_info (_("This software has officially been approved to " */
    1509             : /*                 "create and verify\n" */
    1510             : /*                 "qualified signatures according to German law.\n")); */
    1511             : 
    1512           3 :   if (logfile && cmd == aServer)
    1513             :     {
    1514           0 :       log_set_file (logfile);
    1515           0 :       log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
    1516             :     }
    1517             : 
    1518           3 :   if (gnupg_faked_time_p ())
    1519             :     {
    1520             :       gnupg_isotime_t tbuf;
    1521             : 
    1522           3 :       log_info (_("WARNING: running with faked system time: "));
    1523           3 :       gnupg_get_isotime (tbuf);
    1524           3 :       dump_isotime (tbuf);
    1525           3 :       log_printf ("\n");
    1526             :     }
    1527             : 
    1528             :   /* Print a warning if an argument looks like an option.  */
    1529           3 :   if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
    1530             :     {
    1531             :       int i;
    1532             : 
    1533           6 :       for (i=0; i < argc; i++)
    1534           3 :         if (argv[i][0] == '-' && argv[i][1] == '-')
    1535           0 :           log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
    1536             :     }
    1537             : 
    1538             : /*FIXME    if (opt.batch) */
    1539             : /*      tty_batchmode (1); */
    1540             : 
    1541           3 :   gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
    1542             : 
    1543           3 :   set_debug ();
    1544             : 
    1545             :   /* Although we always use gpgsm_exit, we better install a regualr
    1546             :      exit handler so that at least the secure memory gets wiped
    1547             :      out. */
    1548           3 :   if (atexit (emergency_cleanup))
    1549             :     {
    1550           0 :       log_error ("atexit failed\n");
    1551           0 :       gpgsm_exit (2);
    1552             :     }
    1553             : 
    1554             :   /* Must do this after dropping setuid, because the mapping functions
    1555             :      may try to load an module and we may have disabled an algorithm.
    1556             :      We remap the commonly used algorithms to the OIDs for
    1557             :      convenience.  We need to work with the OIDs because they are used
    1558             :      to check whether the encryption mode is actually available. */
    1559           3 :   if (!strcmp (opt.def_cipher_algoid, "3DES") )
    1560           0 :     opt.def_cipher_algoid = "1.2.840.113549.3.7";
    1561           3 :   else if (!strcmp (opt.def_cipher_algoid, "AES")
    1562           0 :            || !strcmp (opt.def_cipher_algoid, "AES128"))
    1563           3 :     opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.2";
    1564           0 :   else if (!strcmp (opt.def_cipher_algoid, "AES192") )
    1565           0 :     opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.22";
    1566           0 :   else if (!strcmp (opt.def_cipher_algoid, "AES256") )
    1567           0 :     opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.42";
    1568           0 :   else if (!strcmp (opt.def_cipher_algoid, "SERPENT")
    1569           0 :            || !strcmp (opt.def_cipher_algoid, "SERPENT128") )
    1570           0 :     opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.2";
    1571           0 :   else if (!strcmp (opt.def_cipher_algoid, "SERPENT192") )
    1572           0 :     opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.22";
    1573           0 :   else if (!strcmp (opt.def_cipher_algoid, "SERPENT256") )
    1574           0 :     opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.42";
    1575           0 :   else if (!strcmp (opt.def_cipher_algoid, "SEED") )
    1576           0 :     opt.def_cipher_algoid = "1.2.410.200004.1.4";
    1577           0 :   else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA")
    1578           0 :            || !strcmp (opt.def_cipher_algoid, "CAMELLIA128") )
    1579           0 :     opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.2";
    1580           0 :   else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA192") )
    1581           0 :     opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.3";
    1582           0 :   else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA256") )
    1583           0 :     opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.4";
    1584             : 
    1585           3 :   if (cmd != aGPGConfList)
    1586             :     {
    1587           3 :       if ( !gcry_cipher_map_name (opt.def_cipher_algoid)
    1588           3 :            || !gcry_cipher_mode_from_oid (opt.def_cipher_algoid))
    1589           0 :         log_error (_("selected cipher algorithm is invalid\n"));
    1590             : 
    1591           3 :       if (forced_digest_algo)
    1592             :         {
    1593           0 :           opt.forced_digest_algo = gcry_md_map_name (forced_digest_algo);
    1594           0 :           if (our_md_test_algo(opt.forced_digest_algo) )
    1595           0 :             log_error (_("selected digest algorithm is invalid\n"));
    1596             :         }
    1597           3 :       if (extra_digest_algo)
    1598             :         {
    1599           0 :           opt.extra_digest_algo = gcry_md_map_name (extra_digest_algo);
    1600           0 :           if (our_md_test_algo (opt.extra_digest_algo) )
    1601           0 :             log_error (_("selected digest algorithm is invalid\n"));
    1602             :         }
    1603             :     }
    1604             : 
    1605           3 :   if (log_get_errorcount(0))
    1606           0 :     gpgsm_exit(2);
    1607             : 
    1608             :   /* Set the random seed file. */
    1609           3 :   if (use_random_seed)
    1610             :     {
    1611           3 :       char *p = make_filename (gnupg_homedir (), "random_seed", NULL);
    1612           3 :       gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
    1613           3 :       xfree(p);
    1614             :     }
    1615             : 
    1616           3 :   if (!cmd && opt.fingerprint && !with_fpr)
    1617           0 :     set_cmd (&cmd, aListKeys);
    1618             : 
    1619             :   /* Add default keybox. */
    1620           3 :   if (!nrings && default_keyring)
    1621             :     {
    1622             :       int created;
    1623             : 
    1624           3 :       keydb_add_resource (&ctrl, "pubring.kbx", 0, &created);
    1625           3 :       if (created && !no_common_certs_import)
    1626             :         {
    1627             :           /* Import the standard certificates for a new default keybox. */
    1628             :           char *filelist[2];
    1629             : 
    1630           1 :           filelist[0] = make_filename (gnupg_datadir (),"com-certs.pem", NULL);
    1631           1 :           filelist[1] = NULL;
    1632           1 :           if (!access (filelist[0], F_OK))
    1633             :             {
    1634           0 :               log_info (_("importing common certificates '%s'\n"),
    1635             :                         filelist[0]);
    1636           0 :               gpgsm_import_files (&ctrl, 1, filelist, open_read);
    1637             :             }
    1638           1 :           xfree (filelist[0]);
    1639             :         }
    1640             :     }
    1641           3 :   for (sl = nrings; sl; sl = sl->next)
    1642           0 :     keydb_add_resource (&ctrl, sl->d, 0, NULL);
    1643           3 :   FREE_STRLIST(nrings);
    1644             : 
    1645             : 
    1646             :   /* Prepare the audit log feature for certain commands.  */
    1647           3 :   if (auditlog || htmlauditlog)
    1648             :     {
    1649           0 :       switch (cmd)
    1650             :         {
    1651             :         case aEncr:
    1652             :         case aSign:
    1653             :         case aDecrypt:
    1654             :         case aVerify:
    1655           0 :           audit_release (ctrl.audit);
    1656           0 :           ctrl.audit = audit_new ();
    1657           0 :           if (auditlog)
    1658           0 :             auditfp = open_es_fwrite (auditlog);
    1659           0 :           if (htmlauditlog)
    1660           0 :             htmlauditfp = open_es_fwrite (htmlauditlog);
    1661           0 :           break;
    1662             :         default:
    1663           0 :           break;
    1664             :         }
    1665             :     }
    1666             : 
    1667             : 
    1668           3 :   if (!do_not_setup_keys)
    1669             :     {
    1670           0 :       for (sl = locusr; sl ; sl = sl->next)
    1671             :         {
    1672           0 :           int rc = gpgsm_add_to_certlist (&ctrl, sl->d, 1, &signerlist, 0);
    1673           0 :           if (rc)
    1674             :             {
    1675           0 :               log_error (_("can't sign using '%s': %s\n"),
    1676           0 :                          sl->d, gpg_strerror (rc));
    1677           0 :               gpgsm_status2 (&ctrl, STATUS_INV_SGNR,
    1678           0 :                              get_inv_recpsgnr_code (rc), sl->d, NULL);
    1679           0 :               gpgsm_status2 (&ctrl, STATUS_INV_RECP,
    1680           0 :                              get_inv_recpsgnr_code (rc), sl->d, NULL);
    1681             :             }
    1682             :         }
    1683             : 
    1684             :       /* Build the recipient list.  We first add the regular ones and then
    1685             :          the encrypt-to ones because the underlying function will silently
    1686             :          ignore duplicates and we can't allow keeping a duplicate which is
    1687             :          flagged as encrypt-to as the actually encrypt function would then
    1688             :          complain about no (regular) recipients. */
    1689           0 :       for (sl = remusr; sl; sl = sl->next)
    1690           0 :         if (!(sl->flags & 1))
    1691           0 :           do_add_recipient (&ctrl, sl->d, &recplist, 0, recp_required);
    1692           0 :       if (!opt.no_encrypt_to)
    1693             :         {
    1694           0 :           for (sl = remusr; sl; sl = sl->next)
    1695           0 :             if ((sl->flags & 1))
    1696           0 :               do_add_recipient (&ctrl, sl->d, &recplist, 1, recp_required);
    1697             :         }
    1698             :     }
    1699             : 
    1700           3 :   if (log_get_errorcount(0))
    1701           0 :     gpgsm_exit(1); /* Must stop for invalid recipients. */
    1702             : 
    1703             :   /* Dispatch command.  */
    1704           3 :   switch (cmd)
    1705             :     {
    1706             :     case aGPGConfList:
    1707             :       { /* List options and default values in the GPG Conf format.  */
    1708           0 :         char *config_filename_esc = percent_escape (opt.config_filename, NULL);
    1709             : 
    1710           0 :         es_printf ("%s-%s.conf:%lu:\"%s\n",
    1711             :                    GPGCONF_NAME, GPGSM_NAME,
    1712             :                    GC_OPT_FLAG_DEFAULT, config_filename_esc);
    1713           0 :         xfree (config_filename_esc);
    1714             : 
    1715           0 :         es_printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
    1716           0 :         es_printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
    1717           0 :         es_printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
    1718           0 :         es_printf ("log-file:%lu:\n", GC_OPT_FLAG_NONE);
    1719           0 :         es_printf ("disable-crl-checks:%lu:\n", GC_OPT_FLAG_NONE);
    1720           0 :         es_printf ("disable-trusted-cert-crl-check:%lu:\n", GC_OPT_FLAG_NONE);
    1721           0 :         es_printf ("enable-ocsp:%lu:\n", GC_OPT_FLAG_NONE);
    1722           0 :         es_printf ("include-certs:%lu:%d:\n", GC_OPT_FLAG_DEFAULT,
    1723             :                    DEFAULT_INCLUDE_CERTS);
    1724           0 :         es_printf ("disable-policy-checks:%lu:\n", GC_OPT_FLAG_NONE);
    1725           0 :         es_printf ("auto-issuer-key-retrieve:%lu:\n", GC_OPT_FLAG_NONE);
    1726           0 :         es_printf ("disable-dirmngr:%lu:\n", GC_OPT_FLAG_NONE);
    1727           0 :         es_printf ("cipher-algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
    1728             :                    DEFAULT_CIPHER_ALGO);
    1729           0 :         es_printf ("p12-charset:%lu:\n", GC_OPT_FLAG_DEFAULT);
    1730           0 :         es_printf ("default-key:%lu:\n", GC_OPT_FLAG_DEFAULT);
    1731           0 :         es_printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_DEFAULT);
    1732           0 :         es_printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
    1733             : 
    1734             :         /* The next one is an info only item and should match what
    1735             :            proc_parameters actually implements.  */
    1736           0 :         es_printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
    1737             :                    "RSA-2048");
    1738             : 
    1739             :       }
    1740           0 :       break;
    1741             :     case aGPGConfTest:
    1742             :       /* This is merely a dummy command to test whether the
    1743             :          configuration file is valid.  */
    1744           0 :       break;
    1745             : 
    1746             :     case aServer:
    1747           0 :       if (debug_wait)
    1748             :         {
    1749           0 :           log_debug ("waiting for debugger - my pid is %u .....\n",
    1750           0 :                      (unsigned int)getpid());
    1751           0 :           gnupg_sleep (debug_wait);
    1752           0 :           log_debug ("... okay\n");
    1753             :          }
    1754           0 :       gpgsm_server (recplist);
    1755           0 :       break;
    1756             : 
    1757             :     case aCallDirmngr:
    1758           0 :       if (!argc)
    1759           0 :         wrong_args ("--call-dirmngr <command> {args}");
    1760             :       else
    1761           0 :         if (gpgsm_dirmngr_run_command (&ctrl, *argv, argc-1, argv+1))
    1762           0 :           gpgsm_exit (1);
    1763           0 :       break;
    1764             : 
    1765             :     case aCallProtectTool:
    1766           0 :       run_protect_tool (argc, argv);
    1767           0 :       break;
    1768             : 
    1769             :     case aEncr: /* Encrypt the given file. */
    1770             :       {
    1771           0 :         estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
    1772             : 
    1773           0 :         set_binary (stdin);
    1774             : 
    1775           0 :         if (!argc) /* Source is stdin. */
    1776           0 :           gpgsm_encrypt (&ctrl, recplist, 0, fp);
    1777           0 :         else if (argc == 1)  /* Source is the given file. */
    1778           0 :           gpgsm_encrypt (&ctrl, recplist, open_read (*argv), fp);
    1779             :         else
    1780           0 :           wrong_args ("--encrypt [datafile]");
    1781             : 
    1782           0 :         es_fclose (fp);
    1783             :       }
    1784           0 :       break;
    1785             : 
    1786             :     case aSign: /* Sign the given file. */
    1787             :       {
    1788           0 :         estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
    1789             : 
    1790             :         /* Fixme: We should also allow concatenation of multiple files for
    1791             :            signing because that is what gpg does.*/
    1792           0 :         set_binary (stdin);
    1793           0 :         if (!argc) /* Create from stdin. */
    1794           0 :           gpgsm_sign (&ctrl, signerlist, 0, detached_sig, fp);
    1795           0 :         else if (argc == 1) /* From file. */
    1796           0 :           gpgsm_sign (&ctrl, signerlist,
    1797             :                       open_read (*argv), detached_sig, fp);
    1798             :         else
    1799           0 :           wrong_args ("--sign [datafile]");
    1800             : 
    1801           0 :         es_fclose (fp);
    1802             :       }
    1803           0 :       break;
    1804             : 
    1805             :     case aSignEncr: /* sign and encrypt the given file */
    1806           0 :       log_error ("this command has not yet been implemented\n");
    1807           0 :       break;
    1808             : 
    1809             :     case aClearsign: /* make a clearsig */
    1810           0 :       log_error ("this command has not yet been implemented\n");
    1811           0 :       break;
    1812             : 
    1813             :     case aVerify:
    1814             :       {
    1815           0 :         estream_t fp = NULL;
    1816             : 
    1817           0 :         set_binary (stdin);
    1818           0 :         if (argc == 2 && opt.outfile)
    1819           0 :           log_info ("option --output ignored for a detached signature\n");
    1820           0 :         else if (opt.outfile)
    1821           0 :           fp = open_es_fwrite (opt.outfile);
    1822             : 
    1823           0 :         if (!argc)
    1824           0 :           gpgsm_verify (&ctrl, 0, -1, fp); /* normal signature from stdin */
    1825           0 :         else if (argc == 1)
    1826           0 :           gpgsm_verify (&ctrl, open_read (*argv), -1, fp); /* std signature */
    1827           0 :         else if (argc == 2) /* detached signature (sig, detached) */
    1828           0 :           gpgsm_verify (&ctrl, open_read (*argv), open_read (argv[1]), NULL);
    1829             :         else
    1830           0 :           wrong_args ("--verify [signature [detached_data]]");
    1831             : 
    1832           0 :         es_fclose (fp);
    1833             :       }
    1834           0 :       break;
    1835             : 
    1836             :     case aDecrypt:
    1837             :       {
    1838           0 :         estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
    1839             : 
    1840           0 :         set_binary (stdin);
    1841           0 :         if (!argc)
    1842           0 :           gpgsm_decrypt (&ctrl, 0, fp); /* from stdin */
    1843           0 :         else if (argc == 1)
    1844           0 :           gpgsm_decrypt (&ctrl, open_read (*argv), fp); /* from file */
    1845             :         else
    1846           0 :           wrong_args ("--decrypt [filename]");
    1847             : 
    1848           0 :         es_fclose (fp);
    1849             :       }
    1850           0 :       break;
    1851             : 
    1852             :     case aDeleteKey:
    1853           0 :       for (sl=NULL; argc; argc--, argv++)
    1854           0 :         add_to_strlist (&sl, *argv);
    1855           0 :       gpgsm_delete (&ctrl, sl);
    1856           0 :       free_strlist(sl);
    1857           0 :       break;
    1858             : 
    1859             :     case aListChain:
    1860             :     case aDumpChain:
    1861           0 :        ctrl.with_chain = 1;
    1862             :     case aListKeys:
    1863             :     case aDumpKeys:
    1864             :     case aListExternalKeys:
    1865             :     case aDumpExternalKeys:
    1866             :     case aListSecretKeys:
    1867             :     case aDumpSecretKeys:
    1868             :       {
    1869             :         unsigned int mode;
    1870             :         estream_t fp;
    1871             : 
    1872           0 :         switch (cmd)
    1873             :           {
    1874             :           case aListChain:
    1875           0 :           case aListKeys:         mode = (0   | 0 | (1<<6)); break;
    1876             :           case aDumpChain:
    1877           0 :           case aDumpKeys:         mode = (256 | 0 | (1<<6)); break;
    1878           0 :           case aListExternalKeys: mode = (0   | 0 | (1<<7)); break;
    1879           0 :           case aDumpExternalKeys: mode = (256 | 0 | (1<<7)); break;
    1880           0 :           case aListSecretKeys:   mode = (0   | 2 | (1<<6)); break;
    1881           0 :           case aDumpSecretKeys:   mode = (256 | 2 | (1<<6)); break;
    1882           0 :           default: BUG();
    1883             :           }
    1884             : 
    1885           0 :         fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
    1886           0 :         for (sl=NULL; argc; argc--, argv++)
    1887           0 :           add_to_strlist (&sl, *argv);
    1888           0 :         gpgsm_list_keys (&ctrl, sl, fp, mode);
    1889           0 :         free_strlist(sl);
    1890           0 :         es_fclose (fp);
    1891             :       }
    1892           0 :       break;
    1893             : 
    1894             : 
    1895             :     case aKeygen: /* Generate a key; well kind of. */
    1896             :       {
    1897           0 :         estream_t fpin = NULL;
    1898             :         estream_t fpout;
    1899             : 
    1900           0 :         if (opt.batch)
    1901             :           {
    1902           0 :             if (!argc) /* Create from stdin. */
    1903           0 :               fpin = open_es_fread ("-", "r");
    1904           0 :             else if (argc == 1) /* From file. */
    1905           0 :               fpin = open_es_fread (*argv, "r");
    1906             :             else
    1907           0 :               wrong_args ("--gen-key --batch [parmfile]");
    1908             :           }
    1909             : 
    1910           0 :         fpout = open_es_fwrite (opt.outfile?opt.outfile:"-");
    1911             : 
    1912           0 :         if (fpin)
    1913           0 :           gpgsm_genkey (&ctrl, fpin, fpout);
    1914             :         else
    1915           0 :           gpgsm_gencertreq_tty (&ctrl, fpout);
    1916             : 
    1917           0 :         es_fclose (fpout);
    1918             :       }
    1919           0 :       break;
    1920             : 
    1921             : 
    1922             :     case aImport:
    1923           3 :       gpgsm_import_files (&ctrl, argc, argv, open_read);
    1924           3 :       break;
    1925             : 
    1926             :     case aExport:
    1927             :       {
    1928             :         estream_t fp;
    1929             : 
    1930           0 :         fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
    1931           0 :         for (sl=NULL; argc; argc--, argv++)
    1932           0 :           add_to_strlist (&sl, *argv);
    1933           0 :         gpgsm_export (&ctrl, sl, fp);
    1934           0 :         free_strlist(sl);
    1935           0 :         es_fclose (fp);
    1936             :       }
    1937           0 :       break;
    1938             : 
    1939             :     case aExportSecretKeyP12:
    1940             :       {
    1941           0 :         estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
    1942             : 
    1943           0 :         if (argc == 1)
    1944           0 :           gpgsm_p12_export (&ctrl, *argv, fp, 0);
    1945             :         else
    1946           0 :           wrong_args ("--export-secret-key-p12 KEY-ID");
    1947           0 :         if (fp != es_stdout)
    1948           0 :           es_fclose (fp);
    1949             :       }
    1950           0 :       break;
    1951             : 
    1952             :     case aExportSecretKeyP8:
    1953             :       {
    1954           0 :         estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
    1955             : 
    1956           0 :         if (argc == 1)
    1957           0 :           gpgsm_p12_export (&ctrl, *argv, fp, 1);
    1958             :         else
    1959           0 :           wrong_args ("--export-secret-key-p8 KEY-ID");
    1960           0 :         if (fp != es_stdout)
    1961           0 :           es_fclose (fp);
    1962             :       }
    1963           0 :       break;
    1964             : 
    1965             :     case aExportSecretKeyRaw:
    1966             :       {
    1967           0 :         estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
    1968             : 
    1969           0 :         if (argc == 1)
    1970           0 :           gpgsm_p12_export (&ctrl, *argv, fp, 2);
    1971             :         else
    1972           0 :           wrong_args ("--export-secret-key-raw KEY-ID");
    1973           0 :         if (fp != es_stdout)
    1974           0 :           es_fclose (fp);
    1975             :       }
    1976           0 :       break;
    1977             : 
    1978             :     case aSendKeys:
    1979             :     case aRecvKeys:
    1980           0 :       log_error ("this command has not yet been implemented\n");
    1981           0 :       break;
    1982             : 
    1983             : 
    1984             :     case aLearnCard:
    1985           0 :       if (argc)
    1986           0 :         wrong_args ("--learn-card");
    1987             :       else
    1988             :         {
    1989           0 :           int rc = gpgsm_agent_learn (&ctrl);
    1990           0 :           if (rc)
    1991           0 :             log_error ("error learning card: %s\n", gpg_strerror (rc));
    1992             :         }
    1993           0 :       break;
    1994             : 
    1995             :     case aPasswd:
    1996           0 :       if (argc != 1)
    1997           0 :         wrong_args ("--passwd <key-Id>");
    1998             :       else
    1999             :         {
    2000             :           int rc;
    2001           0 :           ksba_cert_t cert = NULL;
    2002           0 :           char *grip = NULL;
    2003             : 
    2004           0 :           rc = gpgsm_find_cert (&ctrl, *argv, NULL, &cert);
    2005           0 :           if (rc)
    2006             :             ;
    2007           0 :           else if (!(grip = gpgsm_get_keygrip_hexstring (cert)))
    2008           0 :             rc = gpg_error (GPG_ERR_BUG);
    2009             :           else
    2010             :             {
    2011           0 :               char *desc = gpgsm_format_keydesc (cert);
    2012           0 :               rc = gpgsm_agent_passwd (&ctrl, grip, desc);
    2013           0 :               xfree (desc);
    2014             :             }
    2015           0 :           if (rc)
    2016           0 :             log_error ("error changing passphrase: %s\n", gpg_strerror (rc));
    2017           0 :           xfree (grip);
    2018           0 :           ksba_cert_release (cert);
    2019             :         }
    2020           0 :       break;
    2021             : 
    2022             :     case aKeydbClearSomeCertFlags:
    2023           0 :       for (sl=NULL; argc; argc--, argv++)
    2024           0 :         add_to_strlist (&sl, *argv);
    2025           0 :       keydb_clear_some_cert_flags (&ctrl, sl);
    2026           0 :       free_strlist(sl);
    2027           0 :       break;
    2028             : 
    2029             : 
    2030             :     default:
    2031           0 :         log_error (_("invalid command (there is no implicit command)\n"));
    2032           0 :         break;
    2033             :     }
    2034             : 
    2035             :   /* Print the audit result if needed.  */
    2036           3 :   if ((auditlog && auditfp) || (htmlauditlog && htmlauditfp))
    2037             :     {
    2038           0 :       if (auditlog && auditfp)
    2039           0 :         audit_print_result (ctrl.audit, auditfp, 0);
    2040           0 :       if (htmlauditlog && htmlauditfp)
    2041           0 :         audit_print_result (ctrl.audit, htmlauditfp, 1);
    2042           0 :       audit_release (ctrl.audit);
    2043           0 :       ctrl.audit = NULL;
    2044           0 :       es_fclose (auditfp);
    2045           0 :       es_fclose (htmlauditfp);
    2046             :     }
    2047             : 
    2048             :   /* cleanup */
    2049           3 :   keyserver_list_free (opt.keyserver);
    2050           3 :   opt.keyserver = NULL;
    2051           3 :   gpgsm_release_certlist (recplist);
    2052           3 :   gpgsm_release_certlist (signerlist);
    2053           3 :   FREE_STRLIST (remusr);
    2054           3 :   FREE_STRLIST (locusr);
    2055           3 :   gpgsm_exit(0);
    2056           0 :   return 8; /*NOTREACHED*/
    2057             : }
    2058             : 
    2059             : /* Note: This function is used by signal handlers!. */
    2060             : static void
    2061           6 : emergency_cleanup (void)
    2062             : {
    2063           6 :   gcry_control (GCRYCTL_TERM_SECMEM );
    2064           6 : }
    2065             : 
    2066             : 
    2067             : void
    2068           3 : gpgsm_exit (int rc)
    2069             : {
    2070           3 :   gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
    2071           3 :   if (opt.debug & DBG_MEMSTAT_VALUE)
    2072             :     {
    2073           0 :       gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
    2074           0 :       gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
    2075             :     }
    2076           3 :   if (opt.debug)
    2077           0 :     gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
    2078           3 :   emergency_cleanup ();
    2079           3 :   rc = rc? rc : log_get_errorcount(0)? 2 : gpgsm_errors_seen? 1 : 0;
    2080           3 :   exit (rc);
    2081             : }
    2082             : 
    2083             : 
    2084             : void
    2085           6 : gpgsm_init_default_ctrl (struct server_control_s *ctrl)
    2086             : {
    2087           6 :   ctrl->include_certs = default_include_certs;
    2088           6 :   ctrl->use_ocsp = opt.enable_ocsp;
    2089           6 :   ctrl->validation_model = default_validation_model;
    2090           6 :   ctrl->offline = opt.disable_dirmngr;
    2091           6 : }
    2092             : 
    2093             : 
    2094             : int
    2095           0 : gpgsm_parse_validation_model (const char *model)
    2096             : {
    2097           0 :   if (!ascii_strcasecmp (model, "shell") )
    2098           0 :     return 0;
    2099           0 :   else if ( !ascii_strcasecmp (model, "chain") )
    2100           0 :     return 1;
    2101           0 :   else if ( !ascii_strcasecmp (model, "steed") )
    2102           0 :     return 2;
    2103             :   else
    2104           0 :     return -1;
    2105             : }
    2106             : 
    2107             : 
    2108             : 
    2109             : /* Open the FILENAME for read and return the file descriptor.  Stop
    2110             :    with an error message in case of problems.  "-" denotes stdin and
    2111             :    if special filenames are allowed the given fd is opened instead.  */
    2112             : static int
    2113           3 : open_read (const char *filename)
    2114             : {
    2115             :   int fd;
    2116             : 
    2117           3 :   if (filename[0] == '-' && !filename[1])
    2118             :     {
    2119           0 :       set_binary (stdin);
    2120           0 :       return 0; /* stdin */
    2121             :     }
    2122           3 :   fd = check_special_filename (filename, 0, 0);
    2123           3 :   if (fd != -1)
    2124           0 :     return fd;
    2125           3 :   fd = open (filename, O_RDONLY | O_BINARY);
    2126           3 :   if (fd == -1)
    2127             :     {
    2128           0 :       log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
    2129           0 :       gpgsm_exit (2);
    2130             :     }
    2131           3 :   return fd;
    2132             : }
    2133             : 
    2134             : /* Same as open_read but return an estream_t.  */
    2135             : static estream_t
    2136           0 : open_es_fread (const char *filename, const char *mode)
    2137             : {
    2138             :   int fd;
    2139             :   estream_t fp;
    2140             : 
    2141           0 :   if (filename[0] == '-' && !filename[1])
    2142           0 :     fd = fileno (stdin);
    2143             :   else
    2144           0 :     fd = check_special_filename (filename, 0, 0);
    2145           0 :   if (fd != -1)
    2146             :     {
    2147           0 :       fp = es_fdopen_nc (fd, mode);
    2148           0 :       if (!fp)
    2149             :         {
    2150           0 :           log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
    2151           0 :           gpgsm_exit (2);
    2152             :         }
    2153           0 :       return fp;
    2154             :     }
    2155           0 :   fp = es_fopen (filename, mode);
    2156           0 :   if (!fp)
    2157             :     {
    2158           0 :       log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
    2159           0 :       gpgsm_exit (2);
    2160             :     }
    2161           0 :   return fp;
    2162             : }
    2163             : 
    2164             : 
    2165             : /* Open FILENAME for fwrite and return an extended stream.  Stop with
    2166             :    an error message in case of problems.  "-" denotes stdout and if
    2167             :    special filenames are allowed the given fd is opened instead.
    2168             :    Caller must close the returned stream. */
    2169             : static estream_t
    2170           0 : open_es_fwrite (const char *filename)
    2171             : {
    2172             :   int fd;
    2173             :   estream_t fp;
    2174             : 
    2175           0 :   if (filename[0] == '-' && !filename[1])
    2176             :     {
    2177           0 :       fflush (stdout);
    2178           0 :       fp = es_fdopen_nc (fileno(stdout), "wb");
    2179           0 :       return fp;
    2180             :     }
    2181             : 
    2182           0 :   fd = check_special_filename (filename, 1, 0);
    2183           0 :   if (fd != -1)
    2184             :     {
    2185           0 :       fp = es_fdopen_nc (fd, "wb");
    2186           0 :       if (!fp)
    2187             :         {
    2188           0 :           log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
    2189           0 :           gpgsm_exit (2);
    2190             :         }
    2191           0 :       return fp;
    2192             :     }
    2193           0 :   fp = es_fopen (filename, "wb");
    2194           0 :   if (!fp)
    2195             :     {
    2196           0 :       log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
    2197           0 :       gpgsm_exit (2);
    2198             :     }
    2199           0 :   return fp;
    2200             : }
    2201             : 
    2202             : 
    2203             : static void
    2204           0 : run_protect_tool (int argc, char **argv)
    2205             : {
    2206             : #ifdef HAVE_W32_SYSTEM
    2207             :   (void)argc;
    2208             :   (void)argv;
    2209             : #else
    2210             :   const char *pgm;
    2211             :   char **av;
    2212             :   int i;
    2213             : 
    2214           0 :   if (!opt.protect_tool_program || !*opt.protect_tool_program)
    2215           0 :     pgm = gnupg_module_name (GNUPG_MODULE_NAME_PROTECT_TOOL);
    2216             :   else
    2217           0 :     pgm = opt.protect_tool_program;
    2218             : 
    2219           0 :   av = xcalloc (argc+2, sizeof *av);
    2220           0 :   av[0] = strrchr (pgm, '/');
    2221           0 :   if (!av[0])
    2222           0 :     av[0] = xstrdup (pgm);
    2223           0 :   for (i=1; argc; i++, argc--, argv++)
    2224           0 :     av[i] = *argv;
    2225           0 :   av[i] = NULL;
    2226           0 :   execv (pgm, av);
    2227           0 :   log_error ("error executing '%s': %s\n", pgm, strerror (errno));
    2228             : #endif /*!HAVE_W32_SYSTEM*/
    2229           0 :   gpgsm_exit (2);
    2230           0 : }

Generated by: LCOV version 1.11