LCOV - code coverage report
Current view: top level - sm - gpgsm.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 213 935 22.8 %
Date: 2016-09-12 12:29:17 Functions: 9 25 36.0 %

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

Generated by: LCOV version 1.11