Page MenuHome GnuPG

No OneTemporary

diff --git a/doc/gpgsm.texi b/doc/gpgsm.texi
index d3d83e4a5..9363ec21d 100644
--- a/doc/gpgsm.texi
+++ b/doc/gpgsm.texi
@@ -1,1669 +1,1667 @@
@c Copyright (C) 2002 Free Software Foundation, Inc.
@c This is part of the GnuPG manual.
@c For copying conditions, see the file gnupg.texi.
@include defs.inc
@node Invoking GPGSM
@chapter Invoking GPGSM
@cindex GPGSM command options
@cindex command options
@cindex options, GPGSM command
@manpage gpgsm.1
@ifset manverb
.B gpgsm
\- CMS encryption and signing tool
@end ifset
@mansect synopsis
@ifset manverb
.B gpgsm
.RB [ \-\-homedir
.IR dir ]
.RB [ \-\-options
.IR file ]
.RI [ options ]
.I command
.RI [ args ]
@end ifset
@mansect description
@command{gpgsm} is a tool similar to @command{gpg} to provide digital
encryption and signing services on X.509 certificates and the CMS
protocol. It is mainly used as a backend for S/MIME mail processing.
@command{gpgsm} includes a full featured certificate management and
complies with all rules defined for the German Sphinx project.
@manpause
@xref{Option Index}, for an index to @command{GPGSM}'s commands and options.
@mancont
@menu
* GPGSM Commands:: List of all commands.
* GPGSM Options:: List of all options.
* GPGSM Configuration:: Configuration files.
* GPGSM Examples:: Some usage examples.
Developer information:
* Unattended Usage:: Using @command{gpgsm} from other programs.
* GPGSM Protocol:: The protocol the server mode uses.
@end menu
@c *******************************************
@c *************** ****************
@c *************** COMMANDS ****************
@c *************** ****************
@c *******************************************
@mansect commands
@node GPGSM Commands
@section Commands
Commands are not distinguished from options except for the fact that
only one command is allowed.
@menu
* General GPGSM Commands:: Commands not specific to the functionality.
* Operational GPGSM Commands:: Commands to select the type of operation.
* Certificate Management:: How to manage certificates.
@end menu
@c *******************************************
@c ********** GENERAL COMMANDS *************
@c *******************************************
@node General GPGSM Commands
@subsection Commands not specific to the function
@table @gnupgtabopt
@item --version
@opindex version
Print the program version and licensing information. Note that you
cannot abbreviate this command.
@item --help, -h
@opindex help
Print a usage message summarizing the most useful command-line options.
Note that you cannot abbreviate this command.
@item --warranty
@opindex warranty
Print warranty information. Note that you cannot abbreviate this
command.
@item --dump-options
@opindex dump-options
Print a list of all available options and commands. Note that you cannot
abbreviate this command.
@end table
@c *******************************************
@c ******** OPERATIONAL COMMANDS ***********
@c *******************************************
@node Operational GPGSM Commands
@subsection Commands to select the type of operation
@table @gnupgtabopt
@item --encrypt
@opindex encrypt
Perform an encryption. The keys the data is encrypted to must be set
using the option @option{--recipient}.
@item --decrypt
@opindex decrypt
Perform a decryption; the type of input is automatically determined. It
may either be in binary form or PEM encoded; automatic determination of
base-64 encoding is not done.
@item --sign
@opindex sign
Create a digital signature. The key used is either the fist one found
in the keybox or those set with the @option{--local-user} option.
@item --verify
@opindex verify
Check a signature file for validity. Depending on the arguments a
detached signature may also be checked.
@item --server
@opindex server
Run in server mode and wait for commands on the @code{stdin}.
@item --call-dirmngr @var{command} [@var{args}]
@opindex call-dirmngr
Behave as a Dirmngr client issuing the request @var{command} with the
optional list of @var{args}. The output of the Dirmngr is printed
stdout. Please note that file names given as arguments should have an
absolute file name (i.e. commencing with @code{/}) because they are
passed verbatim to the Dirmngr and the working directory of the
Dirmngr might not be the same as the one of this client. Currently it
is not possible to pass data via stdin to the Dirmngr. @var{command}
should not contain spaces.
This is command is required for certain maintaining tasks of the dirmngr
where a dirmngr must be able to call back to @command{gpgsm}. See the Dirmngr
manual for details.
@item --call-protect-tool @var{arguments}
@opindex call-protect-tool
Certain maintenance operations are done by an external program call
@command{gpg-protect-tool}; this is usually not installed in a directory
listed in the PATH variable. This command provides a simple wrapper to
access this tool. @var{arguments} are passed verbatim to this command;
use @samp{--help} to get a list of supported operations.
@end table
@c *******************************************
@c ******* CERTIFICATE MANAGEMENT **********
@c *******************************************
@node Certificate Management
@subsection How to manage the certificates and keys
@table @gnupgtabopt
@item --generate-key
@opindex generate-key
@itemx --gen-key
@opindex gen-key
This command allows the creation of a certificate signing request or a
self-signed certificate. It is commonly used along with the
@option{--output} option to save the created CSR or certificate into a
file. If used with the @option{--batch} a parameter file is used to
create the CSR or certificate and it is further possible to create
non-self-signed certificates.
@item --list-keys
@itemx -k
@opindex list-keys
List all available certificates stored in the local key database.
Note that the displayed data might be reformatted for better human
readability and illegal characters are replaced by safe substitutes.
@item --list-secret-keys
@itemx -K
@opindex list-secret-keys
List all available certificates for which a corresponding a secret key
is available.
@item --list-external-keys @var{pattern}
@opindex list-keys
List certificates matching @var{pattern} using an external server. This
utilizes the @code{dirmngr} service.
@item --list-chain
@opindex list-chain
Same as @option{--list-keys} but also prints all keys making up the chain.
@item --dump-cert
@itemx --dump-keys
@opindex dump-cert
@opindex dump-keys
List all available certificates stored in the local key database using a
format useful mainly for debugging.
@item --dump-chain
@opindex dump-chain
Same as @option{--dump-keys} but also prints all keys making up the chain.
@item --dump-secret-keys
@opindex dump-secret-keys
List all available certificates for which a corresponding a secret key
is available using a format useful mainly for debugging.
@item --dump-external-keys @var{pattern}
@opindex dump-external-keys
List certificates matching @var{pattern} using an external server.
This utilizes the @code{dirmngr} service. It uses a format useful
mainly for debugging.
@item --keydb-clear-some-cert-flags
@opindex keydb-clear-some-cert-flags
This is a debugging aid to reset certain flags in the key database
which are used to cache certain certificate stati. It is especially
useful if a bad CRL or a weird running OCSP responder did accidentally
revoke certificate. There is no security issue with this command
because @command{gpgsm} always make sure that the validity of a certificate is
checked right before it is used.
@item --delete-keys @var{pattern}
@opindex delete-keys
Delete the keys matching @var{pattern}. Note that there is no command
to delete the secret part of the key directly. In case you need to do
this, you should run the command @code{gpgsm --dump-secret-keys KEYID}
before you delete the key, copy the string of hex-digits in the
``keygrip'' line and delete the file consisting of these hex-digits
and the suffix @code{.key} from the @file{private-keys-v1.d} directory
below our GnuPG home directory (usually @file{~/.gnupg}).
@item --export [@var{pattern}]
@opindex export
Export all certificates stored in the Keybox or those specified by the
optional @var{pattern}. Those pattern consist of a list of user ids
(@pxref{how-to-specify-a-user-id}). When used along with the
@option{--armor} option a few informational lines are prepended before
each block. There is one limitation: As there is no commonly agreed
upon way to pack more than one certificate into an ASN.1 structure,
the binary export (i.e. without using @option{armor}) works only for
the export of one certificate. Thus it is required to specify a
@var{pattern} which yields exactly one certificate. Ephemeral
certificate are only exported if all @var{pattern} are given as
fingerprints or keygrips.
@item --export-secret-key-p12 @var{key-id}
@opindex export-secret-key-p12
Export the private key and the certificate identified by @var{key-id}
using the PKCS#12 format. When used with the @code{--armor} option a few
informational lines are prepended to the output. Note, that the PKCS#12
format is not very secure and proper transport security should be used
to convey the exported key. (@xref{option --p12-charset}.)
@item --export-secret-key-p8 @var{key-id}
@itemx --export-secret-key-raw @var{key-id}
@opindex export-secret-key-p8
@opindex export-secret-key-raw
Export the private key of the certificate identified by @var{key-id}
with any encryption stripped. The @code{...-raw} command exports in
PKCS#1 format; the @code{...-p8} command exports in PKCS#8 format.
When used with the @code{--armor} option a few informational lines are
prepended to the output. These commands are useful to prepare a key
for use on a TLS server.
@item --import [@var{files}]
@opindex import
Import the certificates from the PEM or binary encoded files as well as
from signed-only messages. This command may also be used to import a
secret key from a PKCS#12 file.
@item --learn-card
@opindex learn-card
Read information about the private keys from the smartcard and import
the certificates from there. This command utilizes the @command{gpg-agent}
and in turn the @command{scdaemon}.
@item --change-passphrase @var{user_id}
@opindex change-passphrase
@itemx --passwd @var{user_id}
@opindex passwd
Change the passphrase of the private key belonging to the certificate
specified as @var{user_id}. Note, that changing the passphrase/PIN of a
smartcard is not yet supported.
@end table
@c *******************************************
@c *************** ****************
@c *************** OPTIONS ****************
@c *************** ****************
@c *******************************************
@mansect options
@node GPGSM Options
@section Option Summary
@command{GPGSM} features a bunch of options to control the exact behaviour
and to change the default configuration.
@menu
* Configuration Options:: How to change the configuration.
* Certificate Options:: Certificate related options.
* Input and Output:: Input and Output.
* CMS Options:: How to change how the CMS is created.
* Esoteric Options:: Doing things one usually do not want to do.
@end menu
@c *******************************************
@c ******** CONFIGURATION OPTIONS **********
@c *******************************************
@node Configuration Options
@subsection How to change the configuration
These options are used to change the configuration and are usually found
in the option file.
@table @gnupgtabopt
@anchor{gpgsm-option --options}
@item --options @var{file}
@opindex options
Reads configuration from @var{file} instead of from the default
per-user configuration file. The default configuration file is named
@file{gpgsm.conf} and expected in the @file{.gnupg} directory directly
below the home directory of the user.
@include opt-homedir.texi
@item -v
@item --verbose
@opindex v
@opindex verbose
Outputs additional information while running.
You can increase the verbosity by giving several
verbose commands to @command{gpgsm}, such as @samp{-vv}.
-@item --ldapserver @var{string}
-@itemx --keyserver @var{string}
-@opindex ldapserver
+@item --keyserver @var{string}
@opindex keyserver
-Add an LDAP server to use for X.509 certificate and CRL lookup. This
-option can be given multiple times to configure more than one LDAP
-server. Note that in general @command{dirmngr} should be configured
-with the list of LDAP servers; if this option is also configured here,
-it is used in addition to those configured in dirmngr. For the syntax
-see the description of dirmngr's ldapserver option.
+This is a deprecated option. It was used to add an LDAP server to use
+for X.509 certificate and CRL lookup. The alias @option{--ldapserver}
+existed from version 2.2.28 to 2.2.33 but is now entirely ignored.
+
+LDAP servers must be given in the configuration for @command{dirmngr}.
+
@item --policy-file @var{filename}
@opindex policy-file
Change the default name of the policy file to @var{filename}.
@item --agent-program @var{file}
@opindex agent-program
Specify an agent program to be used for secret key operations. The
default value is determined by running the command @command{gpgconf}.
Note that the pipe symbol (@code{|}) is used for a regression test
suite hack and may thus not be used in the file name.
@item --dirmngr-program @var{file}
@opindex dirmngr-program
Specify a dirmngr program to be used for @acronym{CRL} checks. The
default value is @file{@value{BINDIR}/dirmngr}.
@item --prefer-system-dirmngr
@opindex prefer-system-dirmngr
This option is obsolete and ignored.
@item --disable-dirmngr
Entirely disable the use of the Dirmngr.
@item --no-autostart
@opindex no-autostart
Do not start the gpg-agent or the dirmngr if it has not yet been
started and its service is required. This option is mostly useful on
machines where the connection to gpg-agent has been redirected to
another machines. If dirmngr is required on the remote machine, it
may be started manually using @command{gpgconf --launch dirmngr}.
@item --no-secmem-warning
@opindex no-secmem-warning
Do not print a warning when the so called "secure memory" cannot be used.
@item --log-file @var{file}
@opindex log-file
When running in server mode, append all logging output to @var{file}.
Use @file{socket://} to log to socket.
@end table
@c *******************************************
@c ******** CERTIFICATE OPTIONS ************
@c *******************************************
@node Certificate Options
@subsection Certificate related options
@table @gnupgtabopt
@item --enable-policy-checks
@itemx --disable-policy-checks
@opindex enable-policy-checks
@opindex disable-policy-checks
By default policy checks are enabled. These options may be used to
change it.
@item --enable-crl-checks
@itemx --disable-crl-checks
@opindex enable-crl-checks
@opindex disable-crl-checks
By default the @acronym{CRL} checks are enabled and the DirMngr is
used to check for revoked certificates. The disable option is most
useful with an off-line network connection to suppress this check and
also to avoid that new certificates introduce a web bug by including a
certificate specific CRL DP. The disable option also disables an
issuer certificate lookup via the authorityInfoAccess property of the
certificate; the @option{--enable-issuer-key-retrieve} can be used
to make use of that property anyway.
@item --enable-trusted-cert-crl-check
@itemx --disable-trusted-cert-crl-check
@opindex enable-trusted-cert-crl-check
@opindex disable-trusted-cert-crl-check
By default the @acronym{CRL} for trusted root certificates are checked
like for any other certificates. This allows a CA to revoke its own
certificates voluntary without the need of putting all ever issued
certificates into a CRL. The disable option may be used to switch this
extra check off. Due to the caching done by the Dirmngr, there will not be
any noticeable performance gain. Note, that this also disables possible
OCSP checks for trusted root certificates. A more specific way of
disabling this check is by adding the ``relax'' keyword to the root CA
line of the @file{trustlist.txt}
@item --force-crl-refresh
@opindex force-crl-refresh
Tell the dirmngr to reload the CRL for each request. For better
performance, the dirmngr will actually optimize this by suppressing
the loading for short time intervals (e.g. 30 minutes). This option
is useful to make sure that a fresh CRL is available for certificates
hold in the keybox. The suggested way of doing this is by using it
along with the option @option{--with-validation} for a key listing
command. This option should not be used in a configuration file.
@item --enable-issuer-based-crl-check
@opindex enable-issuer-based-crl-check
Run a CRL check even for certificates which do not have any CRL
distribution point. This requires that a suitable LDAP server has
been configured in Dirmngr and that the CRL can be found using the
issuer. This option reverts to what GnuPG did up to version 2.2.20.
This option is in general not useful.
@item --enable-ocsp
@itemx --disable-ocsp
@opindex enable-ocsp
@opindex disable-ocsp
By default @acronym{OCSP} checks are disabled. The enable option may
be used to enable OCSP checks via Dirmngr. If @acronym{CRL} checks
are also enabled, CRLs will be used as a fallback if for some reason an
OCSP request will not succeed. Note, that you have to allow OCSP
requests in Dirmngr's configuration too (option
@option{--allow-ocsp}) and configure Dirmngr properly. If you do not do
so you will get the error code @samp{Not supported}.
@item --auto-issuer-key-retrieve
@opindex auto-issuer-key-retrieve
If a required certificate is missing while validating the chain of
certificates, try to load that certificate from an external location.
This usually means that Dirmngr is employed to search for the
certificate. Note that this option makes a "web bug" like behavior
possible. LDAP server operators can see which keys you request, so by
sending you a message signed by a brand new key (which you naturally
will not have on your local keybox), the operator can tell both your IP
address and the time when you verified the signature.
@anchor{gpgsm-option --validation-model}
@item --validation-model @var{name}
@opindex validation-model
This option changes the default validation model. The only possible
values are "shell" (which is the default), "chain" which forces the
use of the chain model and "steed" for a new simplified model. The
chain model is also used if an option in the @file{trustlist.txt} or
an attribute of the certificate requests it. However the standard
model (shell) is in that case always tried first.
@item --ignore-cert-extension @var{oid}
@opindex ignore-cert-extension
Add @var{oid} to the list of ignored certificate extensions. The
@var{oid} is expected to be in dotted decimal form, like
@code{2.5.29.3}. This option may be used more than once. Critical
flagged certificate extensions matching one of the OIDs in the list
are treated as if they are actually handled and thus the certificate
will not be rejected due to an unknown critical extension. Use this
option with care because extensions are usually flagged as critical
for a reason.
@end table
@c *******************************************
@c *********** INPUT AND OUTPUT ************
@c *******************************************
@node Input and Output
@subsection Input and Output
@table @gnupgtabopt
@item --armor
@itemx -a
@opindex armor
Create PEM encoded output. Default is binary output.
@item --base64
@opindex base64
Create Base-64 encoded output; i.e. PEM without the header lines.
@item --assume-armor
@opindex assume-armor
Assume the input data is PEM encoded. Default is to autodetect the
encoding but this is may fail.
@item --assume-base64
@opindex assume-base64
Assume the input data is plain base-64 encoded.
@item --assume-binary
@opindex assume-binary
Assume the input data is binary encoded.
@anchor{option --p12-charset}
@item --p12-charset @var{name}
@opindex p12-charset
@command{gpgsm} uses the UTF-8 encoding when encoding passphrases for
PKCS#12 files. This option may be used to force the passphrase to be
encoded in the specified encoding @var{name}. This is useful if the
application used to import the key uses a different encoding and thus
will not be able to import a file generated by @command{gpgsm}. Commonly
used values for @var{name} are @code{Latin1} and @code{CP850}. Note
that @command{gpgsm} itself automagically imports any file with a
passphrase encoded to the most commonly used encodings.
@item --default-key @var{user_id}
@opindex default-key
Use @var{user_id} as the standard key for signing. This key is used if
no other key has been defined as a signing key. Note, that the first
@option{--local-users} option also sets this key if it has not yet been
set; however @option{--default-key} always overrides this.
@item --local-user @var{user_id}
@item -u @var{user_id}
@opindex local-user
Set the user(s) to be used for signing. The default is the first
secret key found in the database.
@item --recipient @var{name}
@itemx -r
@opindex recipient
Encrypt to the user id @var{name}. There are several ways a user id
may be given (@pxref{how-to-specify-a-user-id}).
@item --output @var{file}
@itemx -o @var{file}
@opindex output
Write output to @var{file}. The default is to write it to stdout.
@anchor{gpgsm-option --with-key-data}
@item --with-key-data
@opindex with-key-data
Displays extra information with the @code{--list-keys} commands. Especially
a line tagged @code{grp} is printed which tells you the keygrip of a
key. This string is for example used as the file name of the
secret key. Implies @code{--with-colons}.
@anchor{gpgsm-option --with-validation}
@item --with-validation
@opindex with-validation
When doing a key listing, do a full validation check for each key and
print the result. This is usually a slow operation because it
requires a CRL lookup and other operations.
When used along with @option{--import}, a validation of the certificate to
import is done and only imported if it succeeds the test. Note that
this does not affect an already available certificate in the DB.
This option is therefore useful to simply verify a certificate.
@item --with-md5-fingerprint
For standard key listings, also print the MD5 fingerprint of the
certificate.
@item --with-keygrip
Include the keygrip in standard key listings. Note that the keygrip is
always listed in @option{--with-colons} mode.
@item --with-secret
@opindex with-secret
Include info about the presence of a secret key in public key listings
done with @code{--with-colons}.
@end table
@c *******************************************
@c ************* CMS OPTIONS ***************
@c *******************************************
@node CMS Options
@subsection How to change how the CMS is created
@table @gnupgtabopt
@item --include-certs @var{n}
@opindex include-certs
Using @var{n} of -2 includes all certificate except for the root cert,
-1 includes all certs, 0 does not include any certs, 1 includes only the
signers cert and all other positive values include up to @var{n}
certificates starting with the signer cert. The default is -2.
@item --cipher-algo @var{oid}
@opindex cipher-algo
Use the cipher algorithm with the ASN.1 object identifier @var{oid} for
encryption. For convenience the strings @code{3DES}, @code{AES} and
@code{AES256} may be used instead of their OIDs. The default is
@code{AES} (2.16.840.1.101.3.4.1.2).
@item --digest-algo @code{name}
Use @code{name} as the message digest algorithm. Usually this
algorithm is deduced from the respective signing certificate. This
option forces the use of the given algorithm and may lead to severe
interoperability problems.
@end table
@c *******************************************
@c ******** ESOTERIC OPTIONS ***************
@c *******************************************
@node Esoteric Options
@subsection Doing things one usually do not want to do
@table @gnupgtabopt
@item --extra-digest-algo @var{name}
@opindex extra-digest-algo
Sometimes signatures are broken in that they announce a different digest
algorithm than actually used. @command{gpgsm} uses a one-pass data
processing model and thus needs to rely on the announced digest
algorithms to properly hash the data. As a workaround this option may
be used to tell @command{gpgsm} to also hash the data using the algorithm
@var{name}; this slows processing down a little bit but allows verification of
such broken signatures. If @command{gpgsm} prints an error like
``digest algo 8 has not been enabled'' you may want to try this option,
with @samp{SHA256} for @var{name}.
@item --compliance @var{string}
@opindex compliance
Set the compliance mode. Valid values are shown when using "help" for
@var{string}.
@item --min-rsa-length @var{n}
@opindex min-rsa-length
This option adjusts the compliance mode "de-vs" for stricter key size
requirements. For example, a value of 3000 turns rsa2048 and dsa2048
keys into non-VS-NfD compliant keys.
@item --faked-system-time @var{epoch}
@opindex faked-system-time
This option is only useful for testing; it sets the system time back or
forth to @var{epoch} which is the number of seconds elapsed since the year
1970. Alternatively @var{epoch} may be given as a full ISO time string
(e.g. "20070924T154812").
@item --with-ephemeral-keys
@opindex with-ephemeral-keys
Include ephemeral flagged keys in the output of key listings. Note
that they are included anyway if the key specification for a listing
is given as fingerprint or keygrip.
@item --debug-level @var{level}
@opindex debug-level
Select the debug level for investigating problems. @var{level} may be
a numeric value or by a keyword:
@table @code
@item none
No debugging at all. A value of less than 1 may be used instead of
the keyword.
@item basic
Some basic debug messages. A value between 1 and 2 may be used
instead of the keyword.
@item advanced
More verbose debug messages. A value between 3 and 5 may be used
instead of the keyword.
@item expert
Even more detailed messages. A value between 6 and 8 may be used
instead of the keyword.
@item guru
All of the debug messages you can get. A value greater than 8 may be
used instead of the keyword. The creation of hash tracing files is
only enabled if the keyword is used.
@end table
How these messages are mapped to the actual debugging flags is not
specified and may change with newer releases of this program. They are
however carefully selected to best aid in debugging.
@item --debug @var{flags}
@opindex debug
This option is only useful for debugging and the behaviour may change
at any time without notice; using @code{--debug-levels} is the
preferred method to select the debug verbosity. FLAGS are bit encoded
and may be given in usual C-Syntax. The currently defined bits are:
@table @code
@item 0 (1)
X.509 or OpenPGP protocol related data
@item 1 (2)
values of big number integers
@item 2 (4)
low level crypto operations
@item 5 (32)
memory allocation
@item 6 (64)
caching
@item 7 (128)
show memory statistics
@item 9 (512)
write hashed data to files named @code{dbgmd-000*}
@item 10 (1024)
trace Assuan protocol
@end table
Note, that all flags set using this option may get overridden by
@code{--debug-level}.
@item --debug-all
@opindex debug-all
Same as @code{--debug=0xffffffff}
@item --debug-allow-core-dump
@opindex debug-allow-core-dump
Usually @command{gpgsm} tries to avoid dumping core by well written code and by
disabling core dumps for security reasons. However, bugs are pretty
durable beasts and to squash them it is sometimes useful to have a core
dump. This option enables core dumps unless the Bad Thing happened
before the option parsing.
@item --debug-no-chain-validation
@opindex debug-no-chain-validation
This is actually not a debugging option but only useful as such. It
lets @command{gpgsm} bypass all certificate chain validation checks.
@item --debug-ignore-expiration
@opindex debug-ignore-expiration
This is actually not a debugging option but only useful as such. It
lets @command{gpgsm} ignore all notAfter dates, this is used by the regression
tests.
@item --passphrase-fd @code{n}
@opindex passphrase-fd
Read the passphrase from file descriptor @code{n}. Only the first line
will be read from file descriptor @code{n}. If you use 0 for @code{n},
the passphrase will be read from STDIN. This can only be used if only
one passphrase is supplied.
Note that this passphrase is only used if the option @option{--batch}
has also been given.
@item --pinentry-mode @code{mode}
@opindex pinentry-mode
Set the pinentry mode to @code{mode}. Allowed values for @code{mode}
are:
@table @asis
@item default
Use the default of the agent, which is @code{ask}.
@item ask
Force the use of the Pinentry.
@item cancel
Emulate use of Pinentry's cancel button.
@item error
Return a Pinentry error (``No Pinentry'').
@item loopback
Redirect Pinentry queries to the caller. Note that in contrast to
Pinentry the user is not prompted again if he enters a bad password.
@end table
@item --request-origin @var{origin}
@opindex request-origin
Tell gpgsm to assume that the operation ultimately originated at
@var{origin}. Depending on the origin certain restrictions are applied
and the Pinentry may include an extra note on the origin. Supported
values for @var{origin} are: @code{local} which is the default,
@code{remote} to indicate a remote origin or @code{browser} for an
operation requested by a web browser.
@item --no-common-certs-import
@opindex no-common-certs-import
Suppress the import of common certificates on keybox creation.
@end table
All the long options may also be given in the configuration file after
stripping off the two leading dashes.
@c *******************************************
@c *************** ****************
@c *************** USER ID ****************
@c *************** ****************
@c *******************************************
@mansect how to specify a user id
@ifset isman
@include specify-user-id.texi
@end ifset
@c *******************************************
@c *************** ****************
@c *************** FILES ****************
@c *************** ****************
@c *******************************************
@mansect files
@node GPGSM Configuration
@section Configuration files
There are a few configuration files to control certain aspects of
@command{gpgsm}'s operation. Unless noted, they are expected in the
current home directory (@pxref{option --homedir}).
@table @file
@item gpgsm.conf
@efindex gpgsm.conf
This is the standard configuration file read by @command{gpgsm} on
startup. It may contain any valid long option; the leading two dashes
may not be entered and the option may not be abbreviated. This default
name may be changed on the command line (@pxref{gpgsm-option --options}).
You should backup this file.
@item policies.txt
@efindex policies.txt
This is a list of allowed CA policies. This file should list the
object identifiers of the policies line by line. Empty lines and
lines starting with a hash mark are ignored. Policies missing in this
file and not marked as critical in the certificate will print only a
warning; certificates with policies marked as critical and not listed
in this file will fail the signature verification. You should backup
this file.
For example, to allow only the policy 2.289.9.9, the file should look
like this:
@c man:.RS
@example
# Allowed policies
2.289.9.9
@end example
@c man:.RE
@item qualified.txt
@efindex qualified.txt
This is the list of root certificates used for qualified certificates.
They are defined as certificates capable of creating legally binding
signatures in the same way as handwritten signatures are. Comments
start with a hash mark and empty lines are ignored. Lines do have a
length limit but this is not a serious limitation as the format of the
entries is fixed and checked by @command{gpgsm}: A non-comment line starts with
optional whitespace, followed by exactly 40 hex characters, white space
and a lowercased 2 letter country code. Additional data delimited with
by a white space is current ignored but might late be used for other
purposes.
Note that even if a certificate is listed in this file, this does not
mean that the certificate is trusted; in general the certificates listed
in this file need to be listed also in @file{trustlist.txt}.
This is a global file an installed in the data directory
(e.g. @file{@value{DATADIR}/qualified.txt}). GnuPG installs a suitable
file with root certificates as used in Germany. As new Root-CA
certificates may be issued over time, these entries may need to be
updated; new distributions of this software should come with an updated
list but it is still the responsibility of the Administrator to check
that this list is correct.
Every time @command{gpgsm} uses a certificate for signing or verification
this file will be consulted to check whether the certificate under
question has ultimately been issued by one of these CAs. If this is the
case the user will be informed that the verified signature represents a
legally binding (``qualified'') signature. When creating a signature
using such a certificate an extra prompt will be issued to let the user
confirm that such a legally binding signature shall really be created.
Because this software has not yet been approved for use with such
certificates, appropriate notices will be shown to indicate this fact.
@item help.txt
@efindex help.txt
This is plain text file with a few help entries used with
@command{pinentry} as well as a large list of help items for
@command{gpg} and @command{gpgsm}. The standard file has English help
texts; to install localized versions use filenames like @file{help.LL.txt}
with LL denoting the locale. GnuPG comes with a set of predefined help
files in the data directory (e.g. @file{@value{DATADIR}/gnupg/help.de.txt})
and allows overriding of any help item by help files stored in the
system configuration directory (e.g. @file{@value{SYSCONFDIR}/help.de.txt}).
For a reference of the help file's syntax, please see the installed
@file{help.txt} file.
@item com-certs.pem
@efindex com-certs.pem
This file is a collection of common certificates used to populated a
newly created @file{pubring.kbx}. An administrator may replace this
file with a custom one. The format is a concatenation of PEM encoded
X.509 certificates. This global file is installed in the data directory
(e.g. @file{@value{DATADIR}/com-certs.pem}).
@end table
@c man:.RE
Note that on larger installations, it is useful to put predefined files
into the directory @file{/etc/skel/.gnupg/} so that newly created users
start up with a working configuration. For existing users a small
helper script is provided to create these files (@pxref{addgnupghome}).
For internal purposes @command{gpgsm} creates and maintains a few other files;
they all live in the current home directory (@pxref{option
--homedir}). Only @command{gpgsm} may modify these files.
@table @file
@item pubring.kbx
@efindex pubring.kbx
This a database file storing the certificates as well as meta
information. For debugging purposes the tool @command{kbxutil} may be
used to show the internal structure of this file. You should backup
this file.
@item random_seed
@efindex random_seed
This content of this file is used to maintain the internal state of the
random number generator across invocations. The same file is used by
other programs of this software too.
@item S.gpg-agent
@efindex S.gpg-agent
If this file exists
@command{gpgsm} will first try to connect to this socket for
accessing @command{gpg-agent} before starting a new @command{gpg-agent}
instance. Under Windows this socket (which in reality be a plain file
describing a regular TCP listening port) is the standard way of
connecting the @command{gpg-agent}.
@end table
@c *******************************************
@c *************** ****************
@c *************** EXAMPLES ****************
@c *************** ****************
@c *******************************************
@mansect examples
@node GPGSM Examples
@section Examples
@example
$ gpgsm -er goo@@bar.net <plaintext >ciphertext
@end example
@c *******************************************
@c *************** **************
@c *************** UNATTENDED **************
@c *************** **************
@c *******************************************
@manpause
@node Unattended Usage
@section Unattended Usage
@command{gpgsm} is often used as a backend engine by other software. To help
with this a machine interface has been defined to have an unambiguous
way to do this. This is most likely used with the @code{--server} command
but may also be used in the standard operation mode by using the
@code{--status-fd} option.
@menu
* Automated signature checking:: Automated signature checking.
* CSR and certificate creation:: CSR and certificate creation.
@end menu
@node Automated signature checking
@subsection Automated signature checking
It is very important to understand the semantics used with signature
verification. Checking a signature is not as simple as it may sound and
so the operation is a bit complicated. In most cases it is required
to look at several status lines. Here is a table of all cases a signed
message may have:
@table @asis
@item The signature is valid
This does mean that the signature has been successfully verified, the
certificates are all sane. However there are two subcases with
important information: One of the certificates may have expired or a
signature of a message itself as expired. It is a sound practise to
consider such a signature still as valid but additional information
should be displayed. Depending on the subcase @command{gpgsm} will issue
these status codes:
@table @asis
@item signature valid and nothing did expire
@code{GOODSIG}, @code{VALIDSIG}, @code{TRUST_FULLY}
@item signature valid but at least one certificate has expired
@code{EXPKEYSIG}, @code{VALIDSIG}, @code{TRUST_FULLY}
@item signature valid but expired
@code{EXPSIG}, @code{VALIDSIG}, @code{TRUST_FULLY}
Note, that this case is currently not implemented.
@end table
@item The signature is invalid
This means that the signature verification failed (this is an indication
of a transfer error, a program error or tampering with the message).
@command{gpgsm} issues one of these status codes sequences:
@table @code
@item @code{BADSIG}
@item @code{GOODSIG}, @code{VALIDSIG} @code{TRUST_NEVER}
@end table
@item Error verifying a signature
For some reason the signature could not be verified, i.e. it cannot be
decided whether the signature is valid or invalid. A common reason for
this is a missing certificate.
@end table
@node CSR and certificate creation
@subsection CSR and certificate creation
The command @option{--generate-key} may be used along with the option
@option{--batch} to either create a certificate signing request (CSR)
or an X.509 certificate. This is controlled by a parameter file; the
format of this file is as follows:
@itemize @bullet
@item Text only, line length is limited to about 1000 characters.
@item UTF-8 encoding must be used to specify non-ASCII characters.
@item Empty lines are ignored.
@item Leading and trailing while space is ignored.
@item A hash sign as the first non white space character indicates
a comment line.
@item Control statements are indicated by a leading percent sign, the
arguments are separated by white space from the keyword.
@item Parameters are specified by a keyword, followed by a colon. Arguments
are separated by white space.
@item The first parameter must be @samp{Key-Type}, control statements
may be placed anywhere.
@item
The order of the parameters does not matter except for @samp{Key-Type}
which must be the first parameter. The parameters are only used for
the generated CSR/certificate; parameters from previous sets are not
used. Some syntactically checks may be performed.
@item
Key generation takes place when either the end of the parameter file
is reached, the next @samp{Key-Type} parameter is encountered or at the
control statement @samp{%commit} is encountered.
@end itemize
@noindent
Control statements:
@table @asis
@item %echo @var{text}
Print @var{text} as diagnostic.
@item %dry-run
Suppress actual key generation (useful for syntax checking).
@item %commit
Perform the key generation. Note that an implicit commit is done at
the next @asis{Key-Type} parameter.
@c %certfile <filename>
@c [Not yet implemented!]
@c Do not write the certificate to the keyDB but to <filename>.
@c This must be given before the first
@c commit to take place, duplicate specification of the same filename
@c is ignored, the last filename before a commit is used.
@c The filename is used until a new filename is used (at commit points)
@c and all keys are written to that file. If a new filename is given,
@c this file is created (and overwrites an existing one).
@c Both control statements must be given.
@end table
@noindent
General Parameters:
@table @asis
@item Key-Type: @var{algo}
Starts a new parameter block by giving the type of the primary
key. The algorithm must be capable of signing. This is a required
parameter. The only supported value for @var{algo} is @samp{rsa}.
@item Key-Length: @var{nbits}
The requested length of a generated key in bits. Defaults to 3072.
@item Key-Grip: @var{hexstring}
This is optional and used to generate a CSR or certificate for an
already existing key. Key-Length will be ignored when given.
@item Key-Usage: @var{usage-list}
Space or comma delimited list of key usage, allowed values are
@samp{encrypt}, @samp{sign} and @samp{cert}. This is used to generate
the keyUsage extension. Please make sure that the algorithm is
capable of this usage. Default is to allow encrypt and sign.
@item Name-DN: @var{subject-name}
This is the Distinguished Name (DN) of the subject in RFC-2253 format.
@item Name-Email: @var{string}
This is an email address for the altSubjectName. This parameter is
optional but may occur several times to add several email addresses to
a certificate.
@item Name-DNS: @var{string}
The is an DNS name for the altSubjectName. This parameter is optional
but may occur several times to add several DNS names to a certificate.
@item Name-URI: @var{string}
This is an URI for the altSubjectName. This parameter is optional but
may occur several times to add several URIs to a certificate.
@end table
@noindent
Additional parameters used to create a certificate (in contrast to a
certificate signing request):
@table @asis
@item Serial: @var{sn}
If this parameter is given an X.509 certificate will be generated.
@var{sn} is expected to be a hex string representing an unsigned
integer of arbitrary length. The special value @samp{random} can be
used to create a 64 bit random serial number.
@item Issuer-DN: @var{issuer-name}
This is the DN name of the issuer in RFC-2253 format. If it is not set
it will default to the subject DN and a special GnuPG extension will
be included in the certificate to mark it as a standalone certificate.
@item Creation-Date: @var{iso-date}
@itemx Not-Before: @var{iso-date}
Set the notBefore date of the certificate. Either a date like
@samp{1986-04-26} or @samp{1986-04-26 12:00} or a standard ISO
timestamp like @samp{19860426T042640} may be used. The time is
considered to be UTC. If it is not given the current date is used.
@item Expire-Date: @var{iso-date}
@itemx Not-After: @var{iso-date}
Set the notAfter date of the certificate. Either a date like
@samp{2063-04-05} or @samp{2063-04-05 17:00} or a standard ISO
timestamp like @samp{20630405T170000} may be used. The time is
considered to be UTC. If it is not given a default value in the not
too far future is used.
@item Signing-Key: @var{keygrip}
This gives the keygrip of the key used to sign the certificate. If it
is not given a self-signed certificate will be created. For
compatibility with future versions, it is suggested to prefix the
keygrip with a @samp{&}.
@item Hash-Algo: @var{hash-algo}
Use @var{hash-algo} for this CSR or certificate. The supported hash
algorithms are: @samp{sha1}, @samp{sha256}, @samp{sha384} and
@samp{sha512}; they may also be specified with uppercase letters. The
default is @samp{sha256}.
@end table
@c *******************************************
@c *************** *****************
@c *************** ASSSUAN *****************
@c *************** *****************
@c *******************************************
@node GPGSM Protocol
@section The Protocol the Server Mode Uses
Description of the protocol used to access @command{GPGSM}.
@command{GPGSM} does implement the Assuan protocol and in addition
provides a regular command line interface which exhibits a full client
to this protocol (but uses internal linking). To start
@command{gpgsm} as a server the command line the option
@code{--server} must be used. Additional options are provided to
select the communication method (i.e. the name of the socket).
We assume that the connection has already been established; see the
Assuan manual for details.
@menu
* GPGSM ENCRYPT:: Encrypting a message.
* GPGSM DECRYPT:: Decrypting a message.
* GPGSM SIGN:: Signing a message.
* GPGSM VERIFY:: Verifying a message.
* GPGSM GENKEY:: Generating a key.
* GPGSM LISTKEYS:: List available keys.
* GPGSM EXPORT:: Export certificates.
* GPGSM IMPORT:: Import certificates.
* GPGSM DELETE:: Delete certificates.
* GPGSM GETAUDITLOG:: Retrieve an audit log.
* GPGSM GETINFO:: Information about the process
* GPGSM OPTION:: Session options.
@end menu
@node GPGSM ENCRYPT
@subsection Encrypting a Message
Before encryption can be done the recipient must be set using the
command:
@example
RECIPIENT @var{userID}
@end example
Set the recipient for the encryption. @var{userID} should be the
internal representation of the key; the server may accept any other way
of specification. If this is a valid and trusted recipient the server
does respond with OK, otherwise the return is an ERR with the reason why
the recipient cannot be used, the encryption will then not be done for
this recipient. If the policy is not to encrypt at all if not all
recipients are valid, the client has to take care of this. All
@code{RECIPIENT} commands are cumulative until a @code{RESET} or an
successful @code{ENCRYPT} command.
@example
INPUT FD[=@var{n}] [--armor|--base64|--binary]
@end example
Set the file descriptor for the message to be encrypted to @var{n}.
Obviously the pipe must be open at that point, the server establishes
its own end. If the server returns an error the client should consider
this session failed. If @var{n} is not given, this commands uses the
last file descriptor passed to the application.
@xref{fun-assuan_sendfd, ,the assuan_sendfd function,assuan,the Libassuan
manual}, on how to do descriptor passing.
The @code{--armor} option may be used to advise the server that the
input data is in @acronym{PEM} format, @code{--base64} advises that a
raw base-64 encoding is used, @code{--binary} advises of raw binary
input (@acronym{BER}). If none of these options is used, the server
tries to figure out the used encoding, but this may not always be
correct.
@example
OUTPUT FD[=@var{n}] [--armor|--base64]
@end example
Set the file descriptor to be used for the output (i.e. the encrypted
message). Obviously the pipe must be open at that point, the server
establishes its own end. If the server returns an error the client
should consider this session failed.
The option @option{--armor} encodes the output in @acronym{PEM} format, the
@option{--base64} option applies just a base-64 encoding. No option
creates binary output (@acronym{BER}).
The actual encryption is done using the command
@example
ENCRYPT
@end example
It takes the plaintext from the @code{INPUT} command, writes to the
ciphertext to the file descriptor set with the @code{OUTPUT} command,
take the recipients from all the recipients set so far. If this command
fails the clients should try to delete all output currently done or
otherwise mark it as invalid. @command{GPGSM} does ensure that there
will not be any
security problem with leftover data on the output in this case.
This command should in general not fail, as all necessary checks have
been done while setting the recipients. The input and output pipes are
closed.
@node GPGSM DECRYPT
@subsection Decrypting a message
Input and output FDs are set the same way as in encryption, but
@code{INPUT} refers to the ciphertext and @code{OUTPUT} to the plaintext. There
is no need to set recipients. @command{GPGSM} automatically strips any
@acronym{S/MIME} headers from the input, so it is valid to pass an
entire MIME part to the INPUT pipe.
The decryption is done by using the command
@example
DECRYPT
@end example
It performs the decrypt operation after doing some check on the internal
state (e.g. that all needed data has been set). Because it utilizes
the GPG-Agent for the session key decryption, there is no need to ask
the client for a protecting passphrase - GpgAgent takes care of this by
requesting this from the user.
@node GPGSM SIGN
@subsection Signing a Message
Signing is usually done with these commands:
@example
INPUT FD[=@var{n}] [--armor|--base64|--binary]
@end example
This tells @command{GPGSM} to read the data to sign from file descriptor @var{n}.
@example
OUTPUT FD[=@var{m}] [--armor|--base64]
@end example
Write the output to file descriptor @var{m}. If a detached signature is
requested, only the signature is written.
@example
SIGN [--detached]
@end example
Sign the data set with the @code{INPUT} command and write it to the sink set by
@code{OUTPUT}. With @code{--detached}, a detached signature is created
(surprise).
The key used for signing is the default one or the one specified in
the configuration file. To get finer control over the keys, it is
possible to use the command
@example
SIGNER @var{userID}
@end example
to set the signer's key. @var{userID} should be the
internal representation of the key; the server may accept any other way
of specification. If this is a valid and trusted recipient the server
does respond with OK, otherwise the return is an ERR with the reason why
the key cannot be used, the signature will then not be created using
this key. If the policy is not to sign at all if not all
keys are valid, the client has to take care of this. All
@code{SIGNER} commands are cumulative until a @code{RESET} is done.
Note that a @code{SIGN} does not reset this list of signers which is in
contrast to the @code{RECIPIENT} command.
@node GPGSM VERIFY
@subsection Verifying a Message
To verify a message the command:
@example
VERIFY
@end example
is used. It does a verify operation on the message send to the input FD.
The result is written out using status lines. If an output FD was
given, the signed text will be written to that. If the signature is a
detached one, the server will inquire about the signed material and the
client must provide it.
@node GPGSM GENKEY
@subsection Generating a Key
This is used to generate a new keypair, store the secret part in the
@acronym{PSE} and the public key in the key database. We will probably
add optional commands to allow the client to select whether a hardware
token is used to store the key. Configuration options to
@command{GPGSM} can be used to restrict the use of this command.
@example
GENKEY
@end example
@command{GPGSM} checks whether this command is allowed and then does an
INQUIRY to get the key parameters, the client should then send the
key parameters in the native format:
@example
S: INQUIRE KEY_PARAM native
C: D foo:fgfgfg
C: D bar
C: END
@end example
Please note that the server may send Status info lines while reading the
data lines from the client. After this the key generation takes place
and the server eventually does send an ERR or OK response. Status lines
may be issued as a progress indicator.
@node GPGSM LISTKEYS
@subsection List available keys
@anchor{gpgsm-cmd listkeys}
To list the keys in the internal database or using an external key
provider, the command:
@example
LISTKEYS @var{pattern}
@end example
is used. To allow multiple patterns (which are ORed during the search)
quoting is required: Spaces are to be translated into "+" or into "%20";
in turn this requires that the usual escape quoting rules are done.
@example
LISTSECRETKEYS @var{pattern}
@end example
Lists only the keys where a secret key is available.
The list commands are affected by the option
@example
OPTION list-mode=@var{mode}
@end example
where mode may be:
@table @code
@item 0
Use default (which is usually the same as 1).
@item 1
List only the internal keys.
@item 2
List only the external keys.
@item 3
List internal and external keys.
@end table
Note that options are valid for the entire session.
@node GPGSM EXPORT
@subsection Export certificates
To export certificate from the internal key database the command:
@example
EXPORT [--data [--armor] [--base64]] [--] @var{pattern}
@end example
is used. To allow multiple patterns (which are ORed) quoting is
required: Spaces are to be translated into "+" or into "%20"; in turn
this requires that the usual escape quoting rules are done.
If the @option{--data} option has not been given, the format of the
output depends on what was set with the @code{OUTPUT} command. When using
@acronym{PEM} encoding a few informational lines are prepended.
If the @option{--data} has been given, a target set via @code{OUTPUT} is
ignored and the data is returned inline using standard
@code{D}-lines. This avoids the need for an extra file descriptor. In
this case the options @option{--armor} and @option{--base64} may be used
in the same way as with the @code{OUTPUT} command.
@node GPGSM IMPORT
@subsection Import certificates
To import certificates into the internal key database, the command
@example
IMPORT [--re-import]
@end example
is used. The data is expected on the file descriptor set with the
@code{INPUT} command. Certain checks are performed on the
certificate. Note that the code will also handle PKCS#12 files and
import private keys; a helper program is used for that.
With the option @option{--re-import} the input data is expected to a be
a linefeed separated list of fingerprints. The command will re-import
the corresponding certificates; that is they are made permanent by
removing their ephemeral flag.
@node GPGSM DELETE
@subsection Delete certificates
To delete a certificate the command
@example
DELKEYS @var{pattern}
@end example
is used. To allow multiple patterns (which are ORed) quoting is
required: Spaces are to be translated into "+" or into "%20"; in turn
this requires that the usual escape quoting rules are done.
The certificates must be specified unambiguously otherwise an error is
returned.
@node GPGSM GETAUDITLOG
@subsection Retrieve an audit log
@anchor{gpgsm-cmd getauditlog}
This command is used to retrieve an audit log.
@example
GETAUDITLOG [--data] [--html]
@end example
If @option{--data} is used, the audit log is send using D-lines
instead of being sent to the file descriptor given by an @code{OUTPUT}
command. If @option{--html} is used, the output is formatted as an
XHTML block. This is designed to be incorporated into a HTML
document.
@node GPGSM GETINFO
@subsection Return information about the process
This is a multipurpose function to return a variety of information.
@example
GETINFO @var{what}
@end example
The value of @var{what} specifies the kind of information returned:
@table @code
@item version
Return the version of the program.
@item pid
Return the process id of the process.
@item agent-check
Return OK if the agent is running.
@item cmd_has_option @var{cmd} @var{opt}
Return OK if the command @var{cmd} implements the option @var{opt}.
The leading two dashes usually used with @var{opt} shall not be given.
@item offline
Return OK if the connection is in offline mode. This may be either
due to a @code{OPTION offline=1} or due to @command{gpgsm} being
started with option @option{--disable-dirmngr}.
@end table
@node GPGSM OPTION
@subsection Session options
The standard Assuan option handler supports these options.
@example
OPTION @var{name}[=@var{value}]
@end example
These @var{name}s are recognized:
@table @code
@item putenv
Change the session's environment to be passed via gpg-agent to
Pinentry. @var{value} is a string of the form
@code{<KEY>[=[<STRING>]]}. If only @code{<KEY>} is given the
environment variable @code{<KEY>} is removed from the session
environment, if @code{<KEY>=} is given that environment variable is
set to the empty string, and if @code{<STRING>} is given it is set to
that string.
@item display
@efindex DISPLAY
Set the session environment variable @code{DISPLAY} is set to @var{value}.
@item ttyname
@efindex GPG_TTY
Set the session environment variable @code{GPG_TTY} is set to @var{value}.
@item ttytype
@efindex TERM
Set the session environment variable @code{TERM} is set to @var{value}.
@item lc-ctype
@efindex LC_CTYPE
Set the session environment variable @code{LC_CTYPE} is set to @var{value}.
@item lc-messages
@efindex LC_MESSAGES
Set the session environment variable @code{LC_MESSAGES} is set to @var{value}.
@item xauthority
@efindex XAUTHORITY
Set the session environment variable @code{XAUTHORITY} is set to @var{value}.
@item pinentry-user-data
@efindex PINENTRY_USER_DATA
Set the session environment variable @code{PINENTRY_USER_DATA} is set
to @var{value}.
@item include-certs
This option overrides the command line option
@option{--include-certs}. A @var{value} of -2 includes all
certificates except for the root certificate, -1 includes all
certificates, 0 does not include any certificates, 1 includes only the
signers certificate and all other positive values include up to
@var{value} certificates starting with the signer cert.
@item list-mode
@xref{gpgsm-cmd listkeys}.
@item list-to-output
If @var{value} is true the output of the list commands
(@pxref{gpgsm-cmd listkeys}) is written to the file descriptor set
with the last @code{OUTPUT} command. If @var{value} is false the output is
written via data lines; this is the default.
@item with-validation
If @var{value} is true for each listed certificate the validation
status is printed. This may result in the download of a CRL or the
user being asked about the trustworthiness of a root certificate. The
default is given by a command line option (@pxref{gpgsm-option
--with-validation}).
@item with-secret
If @var{value} is true certificates with a corresponding private key
are marked by the list commands.
@item validation-model
This option overrides the command line option
@option{validation-model} for the session.
(@xref{gpgsm-option --validation-model}.)
@item with-key-data
This option globally enables the command line option
@option{--with-key-data}. (@xref{gpgsm-option --with-key-data}.)
@item enable-audit-log
If @var{value} is true data to write an audit log is gathered.
(@xref{gpgsm-cmd getauditlog}.)
@item allow-pinentry-notify
If this option is used notifications about the launch of a Pinentry
are passed back to the client.
@item with-ephemeral-keys
If @var{value} is true ephemeral certificates are included in the
output of the list commands.
@item no-encrypt-to
If this option is used all keys set by the command line option
@option{--encrypt-to} are ignored.
@item offline
If @var{value} is true or @var{value} is not given all network access
is disabled for this session. This is the same as the command line
option @option{--disable-dirmngr}.
@end table
@mansect see also
@ifset isman
@command{gpg2}(1),
@command{gpg-agent}(1)
@end ifset
@include see-also-note.texi
diff --git a/sm/gpgsm.c b/sm/gpgsm.c
index b64324706..8ee0e18c1 100644
--- a/sm/gpgsm.c
+++ b/sm/gpgsm.c
@@ -1,2229 +1,2232 @@
/* gpgsm.c - GnuPG for S/MIME
* Copyright (C) 2001-2020 Free Software Foundation, Inc.
* Copyright (C) 2001-2019 Werner Koch
* Copyright (C) 2015-2020 g10 Code GmbH
*
* This file is part of GnuPG.
*
* GnuPG is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GnuPG is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <https://www.gnu.org/licenses/>.
* SPDX-License-Identifier: GPL-3.0-or-later
*/
#include <config.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <fcntl.h>
#define INCLUDED_BY_MAIN_MODULE 1
#include "gpgsm.h"
#include <gcrypt.h>
#include <assuan.h> /* malloc hooks */
#include "passphrase.h"
#include "../common/shareddefs.h"
#include "../kbx/keybox.h" /* malloc hooks */
#include "../common/i18n.h"
#include "keydb.h"
#include "../common/sysutils.h"
#include "../common/gc-opt-flags.h"
#include "../common/asshelp.h"
#include "../common/init.h"
#include "../common/compliance.h"
#include "minip12.h"
#ifndef O_BINARY
#define O_BINARY 0
#endif
enum cmd_and_opt_values {
aNull = 0,
oArmor = 'a',
aDetachedSign = 'b',
aSym = 'c',
aDecrypt = 'd',
aEncr = 'e',
aListKeys = 'k',
aListSecretKeys = 'K',
oDryRun = 'n',
oOutput = 'o',
oQuiet = 'q',
oRecipient = 'r',
aSign = 's',
oUser = 'u',
oVerbose = 'v',
oBatch = 500,
aClearsign,
aKeygen,
aSignEncr,
aDeleteKey,
aImport,
aVerify,
aListExternalKeys,
aListChain,
aSendKeys,
aRecvKeys,
aExport,
aExportSecretKeyP12,
aExportSecretKeyP8,
aExportSecretKeyRaw,
aServer,
aLearnCard,
aCallDirmngr,
aCallProtectTool,
aPasswd,
aGPGConfList,
aGPGConfTest,
aDumpKeys,
aDumpChain,
aDumpSecretKeys,
aDumpExternalKeys,
aKeydbClearSomeCertFlags,
aFingerprint,
oOptions,
oDebug,
oDebugLevel,
oDebugAll,
oDebugNone,
oDebugWait,
oDebugAllowCoreDump,
oDebugNoChainValidation,
oDebugIgnoreExpiration,
oLogFile,
oNoLogFile,
oAuditLog,
oHtmlAuditLog,
oEnableSpecialFilenames,
oAgentProgram,
oDisplay,
oTTYname,
oTTYtype,
oLCctype,
oLCmessages,
oXauthority,
oPreferSystemDirmngr,
oDirmngrProgram,
oDisableDirmngr,
oProtectToolProgram,
oFakedSystemTime,
oPassphraseFD,
oPinentryMode,
oRequestOrigin,
oAssumeArmor,
oAssumeBase64,
oAssumeBinary,
oBase64,
oNoArmor,
oP12Charset,
oCompliance,
oDisableCRLChecks,
oEnableCRLChecks,
oDisableTrustedCertCRLCheck,
oEnableTrustedCertCRLCheck,
oForceCRLRefresh,
oEnableIssuerBasedCRLCheck,
oDisableOCSP,
oEnableOCSP,
oIncludeCerts,
oPolicyFile,
oDisablePolicyChecks,
oEnablePolicyChecks,
oAutoIssuerKeyRetrieve,
oMinRSALength,
oWithFingerprint,
oWithMD5Fingerprint,
oWithKeygrip,
oWithSecret,
oAnswerYes,
oAnswerNo,
oKeyring,
oDefaultKey,
oDefRecipient,
oDefRecipientSelf,
oNoDefRecipient,
oStatusFD,
oCipherAlgo,
oDigestAlgo,
oExtraDigestAlgo,
oNoVerbose,
oNoSecmemWarn,
oNoDefKeyring,
oNoGreeting,
oNoTTY,
oNoOptions,
oNoBatch,
oHomedir,
oWithColons,
oWithKeyData,
oWithValidation,
oWithEphemeralKeys,
oSkipVerify,
oValidationModel,
oKeyServer,
+ oKeyServer_deprecated,
oEncryptTo,
oNoEncryptTo,
oLoggerFD,
oDisableCipherAlgo,
oDisablePubkeyAlgo,
oIgnoreTimeConflict,
oNoRandomSeedFile,
oNoCommonCertsImport,
oIgnoreCertExtension,
oNoAutostart
};
static ARGPARSE_OPTS opts[] = {
ARGPARSE_group (300, N_("@Commands:\n ")),
ARGPARSE_c (aSign, "sign", N_("make a signature")),
/*ARGPARSE_c (aClearsign, "clearsign", N_("make a clear text signature") ),*/
ARGPARSE_c (aDetachedSign, "detach-sign", N_("make a detached signature")),
ARGPARSE_c (aEncr, "encrypt", N_("encrypt data")),
/*ARGPARSE_c (aSym, "symmetric", N_("encryption only with symmetric cipher")),*/
ARGPARSE_c (aDecrypt, "decrypt", N_("decrypt data (default)")),
ARGPARSE_c (aVerify, "verify", N_("verify a signature")),
ARGPARSE_c (aListKeys, "list-keys", N_("list keys")),
ARGPARSE_c (aListExternalKeys, "list-external-keys",
N_("list external keys")),
ARGPARSE_c (aListSecretKeys, "list-secret-keys", N_("list secret keys")),
ARGPARSE_c (aListChain, "list-chain", N_("list certificate chain")),
ARGPARSE_c (aFingerprint, "fingerprint", N_("list keys and fingerprints")),
ARGPARSE_c (aKeygen, "generate-key", N_("generate a new key pair")),
ARGPARSE_c (aKeygen, "gen-key", "@"),
ARGPARSE_c (aDeleteKey, "delete-keys",
N_("remove keys from the public keyring")),
/*ARGPARSE_c (aSendKeys, "send-keys", N_("export keys to a keyserver")),*/
/*ARGPARSE_c (aRecvKeys, "recv-keys", N_("import keys from a keyserver")),*/
ARGPARSE_c (aImport, "import", N_("import certificates")),
ARGPARSE_c (aExport, "export", N_("export certificates")),
/* We use -raw and not -p1 for pkcs#1 secret key export so that it
won't accidentally be used in case -p12 was intended. */
ARGPARSE_c (aExportSecretKeyP12, "export-secret-key-p12", "@"),
ARGPARSE_c (aExportSecretKeyP8, "export-secret-key-p8", "@"),
ARGPARSE_c (aExportSecretKeyRaw, "export-secret-key-raw", "@"),
ARGPARSE_c (aLearnCard, "learn-card", N_("register a smartcard")),
ARGPARSE_c (aServer, "server", N_("run in server mode")),
ARGPARSE_c (aCallDirmngr, "call-dirmngr",
N_("pass a command to the dirmngr")),
ARGPARSE_c (aCallProtectTool, "call-protect-tool",
N_("invoke gpg-protect-tool")),
ARGPARSE_c (aPasswd, "change-passphrase", N_("change a passphrase")),
ARGPARSE_c (aPasswd, "passwd", "@"),
ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
ARGPARSE_c (aDumpKeys, "dump-cert", "@"),
ARGPARSE_c (aDumpKeys, "dump-keys", "@"),
ARGPARSE_c (aDumpChain, "dump-chain", "@"),
ARGPARSE_c (aDumpExternalKeys, "dump-external-keys", "@"),
ARGPARSE_c (aDumpSecretKeys, "dump-secret-keys", "@"),
ARGPARSE_c (aKeydbClearSomeCertFlags, "keydb-clear-some-cert-flags", "@"),
ARGPARSE_header ("Monitor", N_("Options controlling the diagnostic output")),
ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
ARGPARSE_s_n (oNoVerbose, "no-verbose", "@"),
ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
ARGPARSE_s_n (oNoTTY, "no-tty", N_("don't use the terminal at all")),
ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
ARGPARSE_s_s (oDebug, "debug", "@"),
ARGPARSE_s_s (oDebugLevel, "debug-level",
N_("|LEVEL|set the debugging level to LEVEL")),
ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
ARGPARSE_s_n (oDebugNone, "debug-none", "@"),
ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
ARGPARSE_s_n (oDebugAllowCoreDump, "debug-allow-core-dump", "@"),
ARGPARSE_s_n (oDebugNoChainValidation, "debug-no-chain-validation", "@"),
ARGPARSE_s_n (oDebugIgnoreExpiration, "debug-ignore-expiration", "@"),
ARGPARSE_s_s (oLogFile, "log-file",
N_("|FILE|write server mode logs to FILE")),
ARGPARSE_s_n (oNoLogFile, "no-log-file", "@"),
ARGPARSE_s_i (oLoggerFD, "logger-fd", "@"),
ARGPARSE_s_n (oNoSecmemWarn, "no-secmem-warning", "@"),
ARGPARSE_header ("Configuration",
N_("Options controlling the configuration")),
ARGPARSE_s_s (oHomedir, "homedir", "@"),
ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
ARGPARSE_s_n (oPreferSystemDirmngr,"prefer-system-dirmngr", "@"),
ARGPARSE_s_s (oValidationModel, "validation-model", "@"),
ARGPARSE_s_i (oIncludeCerts, "include-certs",
N_("|N|number of certificates to include") ),
ARGPARSE_s_s (oPolicyFile, "policy-file",
N_("|FILE|take policy information from FILE")),
ARGPARSE_s_s (oCompliance, "compliance", "@"),
ARGPARSE_s_n (oNoCommonCertsImport, "no-common-certs-import", "@"),
ARGPARSE_s_s (oIgnoreCertExtension, "ignore-cert-extension", "@"),
ARGPARSE_s_n (oNoAutostart, "no-autostart", "@"),
ARGPARSE_s_s (oAgentProgram, "agent-program", "@"),
ARGPARSE_s_s (oDirmngrProgram, "dirmngr-program", "@"),
ARGPARSE_s_s (oProtectToolProgram, "protect-tool-program", "@"),
ARGPARSE_header ("Input", N_("Options controlling the input")),
ARGPARSE_s_n (oAssumeArmor, "assume-armor",
N_("assume input is in PEM format")),
ARGPARSE_s_n (oAssumeBase64, "assume-base64",
N_("assume input is in base-64 format")),
ARGPARSE_s_n (oAssumeBinary, "assume-binary",
N_("assume input is in binary format")),
ARGPARSE_header ("Output", N_("Options controlling the output")),
ARGPARSE_s_n (oArmor, "armor", N_("create ascii armored output")),
ARGPARSE_s_n (oArmor, "armour", "@"),
ARGPARSE_s_n (oNoArmor, "no-armor", "@"),
ARGPARSE_s_n (oNoArmor, "no-armour", "@"),
ARGPARSE_s_n (oBase64, "base64", N_("create base-64 encoded output")),
ARGPARSE_s_s (oOutput, "output", N_("|FILE|write output to FILE")),
ARGPARSE_header (NULL, N_("Options to specify keys")),
ARGPARSE_s_s (oRecipient, "recipient", N_("|USER-ID|encrypt for USER-ID")),
ARGPARSE_s_s (oUser, "local-user",
N_("|USER-ID|use USER-ID to sign or decrypt")),
ARGPARSE_s_s (oDefaultKey, "default-key",
N_("|USER-ID|use USER-ID as default secret key")),
ARGPARSE_s_s (oEncryptTo, "encrypt-to",
N_("|NAME|encrypt to user ID NAME as well")),
ARGPARSE_s_n (oNoEncryptTo, "no-encrypt-to", "@"),
/* Not yet used: */
/* ARGPARSE_s_s (oDefRecipient, "default-recipient", */
/* N_("|NAME|use NAME as default recipient")), */
/* ARGPARSE_s_n (oDefRecipientSelf, "default-recipient-self", */
/* N_("use the default key as default recipient")), */
/* ARGPARSE_s_n (oNoDefRecipient, "no-default-recipient", "@"), */
ARGPARSE_s_s (oKeyring, "keyring",
N_("|FILE|add keyring to the list of keyrings")),
ARGPARSE_s_n (oNoDefKeyring, "no-default-keyring", "@"),
- ARGPARSE_s_s (oKeyServer, "ldapserver",
- N_("|SPEC|use this keyserver to lookup keys")),
+ ARGPARSE_s_s (oKeyServer_deprecated, "ldapserver", "@"),
ARGPARSE_s_s (oKeyServer, "keyserver", "@"),
-
ARGPARSE_header ("ImportExport",
N_("Options controlling key import and export")),
ARGPARSE_s_n (oDisableDirmngr, "disable-dirmngr",
N_("disable all access to the dirmngr")),
ARGPARSE_s_n (oAutoIssuerKeyRetrieve, "auto-issuer-key-retrieve",
N_("fetch missing issuer certificates")),
ARGPARSE_s_s (oP12Charset, "p12-charset",
N_("|NAME|use encoding NAME for PKCS#12 passphrases")),
ARGPARSE_header ("Keylist", N_("Options controlling key listings")),
ARGPARSE_s_n (oWithColons, "with-colons", "@"),
ARGPARSE_s_n (oWithKeyData,"with-key-data", "@"),
ARGPARSE_s_n (oWithValidation, "with-validation", "@"),
ARGPARSE_s_n (oWithMD5Fingerprint, "with-md5-fingerprint", "@"),
ARGPARSE_s_n (oWithEphemeralKeys, "with-ephemeral-keys", "@"),
ARGPARSE_s_n (oSkipVerify, "skip-verify", "@"),
ARGPARSE_s_n (oWithFingerprint, "with-fingerprint", "@"),
ARGPARSE_s_n (oWithKeygrip, "with-keygrip", "@"),
ARGPARSE_s_n (oWithSecret, "with-secret", "@"),
ARGPARSE_header ("Security", N_("Options controlling the security")),
ARGPARSE_s_n (oDisableCRLChecks, "disable-crl-checks",
N_("never consult a CRL")),
ARGPARSE_s_n (oEnableCRLChecks, "enable-crl-checks", "@"),
ARGPARSE_s_n (oDisableTrustedCertCRLCheck,
"disable-trusted-cert-crl-check",
N_("do not check CRLs for root certificates")),
ARGPARSE_s_n (oEnableTrustedCertCRLCheck,
"enable-trusted-cert-crl-check", "@"),
ARGPARSE_s_n (oDisableOCSP, "disable-ocsp", "@"),
ARGPARSE_s_n (oEnableOCSP, "enable-ocsp", N_("check validity using OCSP")),
ARGPARSE_s_n (oDisablePolicyChecks, "disable-policy-checks",
N_("do not check certificate policies")),
ARGPARSE_s_n (oEnablePolicyChecks, "enable-policy-checks", "@"),
ARGPARSE_s_s (oCipherAlgo, "cipher-algo",
N_("|NAME|use cipher algorithm NAME")),
ARGPARSE_s_s (oDigestAlgo, "digest-algo",
N_("|NAME|use message digest algorithm NAME")),
ARGPARSE_s_s (oExtraDigestAlgo, "extra-digest-algo", "@"),
ARGPARSE_s_s (oDisableCipherAlgo, "disable-cipher-algo", "@"),
ARGPARSE_s_s (oDisablePubkeyAlgo, "disable-pubkey-algo", "@"),
ARGPARSE_s_n (oIgnoreTimeConflict, "ignore-time-conflict", "@"),
ARGPARSE_s_n (oNoRandomSeedFile, "no-random-seed-file", "@"),
ARGPARSE_p_u (oMinRSALength, "min-rsa-length", "@"),
ARGPARSE_header (NULL, N_("Options for unattended use")),
ARGPARSE_s_n (oBatch, "batch", N_("batch mode: never ask")),
ARGPARSE_s_n (oNoBatch, "no-batch", "@"),
ARGPARSE_s_n (oAnswerYes, "yes", N_("assume yes on most questions")),
ARGPARSE_s_n (oAnswerNo, "no", N_("assume no on most questions")),
ARGPARSE_s_i (oStatusFD, "status-fd", N_("|FD|write status info to this FD")),
ARGPARSE_s_n (oEnableSpecialFilenames, "enable-special-filenames", "@"),
ARGPARSE_s_i (oPassphraseFD, "passphrase-fd", "@"),
ARGPARSE_s_s (oPinentryMode, "pinentry-mode", "@"),
ARGPARSE_header (NULL, N_("Other options")),
ARGPARSE_conffile (oOptions, "options", N_("|FILE|read options from FILE")),
ARGPARSE_noconffile (oNoOptions, "no-options", "@"),
ARGPARSE_s_n (oDryRun, "dry-run", N_("do not make any changes")),
ARGPARSE_s_s (oRequestOrigin, "request-origin", "@"),
ARGPARSE_s_n (oForceCRLRefresh, "force-crl-refresh", "@"),
ARGPARSE_s_n (oEnableIssuerBasedCRLCheck, "enable-issuer-based-crl-check",
"@"),
ARGPARSE_s_s (oAuditLog, "audit-log",
N_("|FILE|write an audit log to FILE")),
ARGPARSE_s_s (oHtmlAuditLog, "html-audit-log", "@"),
ARGPARSE_s_s (oDisplay, "display", "@"),
ARGPARSE_s_s (oTTYname, "ttyname", "@"),
ARGPARSE_s_s (oTTYtype, "ttytype", "@"),
ARGPARSE_s_s (oLCctype, "lc-ctype", "@"),
ARGPARSE_s_s (oLCmessages, "lc-messages", "@"),
ARGPARSE_s_s (oXauthority, "xauthority", "@"),
ARGPARSE_header (NULL, ""), /* Stop the header group. */
/* Command aliases. */
ARGPARSE_c (aListKeys, "list-key", "@"),
ARGPARSE_c (aListChain, "list-signatures", "@"),
ARGPARSE_c (aListChain, "list-sigs", "@"),
ARGPARSE_c (aListChain, "check-signatures", "@"),
ARGPARSE_c (aListChain, "check-sigs", "@"),
ARGPARSE_c (aDeleteKey, "delete-key", "@"),
ARGPARSE_group (302, N_(
"@\n(See the man page for a complete listing of all commands and options)\n"
)),
ARGPARSE_end ()
};
/* The list of supported debug flags. */
static struct debug_flags_s debug_flags [] =
{
{ DBG_X509_VALUE , "x509" },
{ DBG_MPI_VALUE , "mpi" },
{ DBG_CRYPTO_VALUE , "crypto" },
{ DBG_MEMORY_VALUE , "memory" },
{ DBG_CACHE_VALUE , "cache" },
{ DBG_MEMSTAT_VALUE, "memstat" },
{ DBG_HASHING_VALUE, "hashing" },
{ DBG_IPC_VALUE , "ipc" },
{ 0, NULL }
};
/* Global variable to keep an error count. */
int gpgsm_errors_seen = 0;
/* It is possible that we are currentlu running under setuid permissions */
static int maybe_setuid = 1;
/* Helper to implement --debug-level and --debug*/
static const char *debug_level;
static unsigned int debug_value;
/* Default value for include-certs. We need an extra macro for
gpgconf-list because the variable will be changed by the command
line option.
It is often cumbersome to locate intermediate certificates, thus by
default we include all certificates in the chain. However we leave
out the root certificate because that would make it too easy for
the recipient to import that root certificate. A root certificate
should be installed only after due checks and thus it won't help to
send it along with each message. */
#define DEFAULT_INCLUDE_CERTS -2 /* Include all certs but root. */
static int default_include_certs = DEFAULT_INCLUDE_CERTS;
/* Whether the chain mode shall be used for validation. */
static int default_validation_model;
/* The default cipher algo. */
#define DEFAULT_CIPHER_ALGO "AES"
static char *build_list (const char *text,
const char *(*mapf)(int), int (*chkf)(int));
static void set_cmd (enum cmd_and_opt_values *ret_cmd,
enum cmd_and_opt_values new_cmd );
static void emergency_cleanup (void);
static int open_read (const char *filename);
static estream_t open_es_fread (const char *filename, const char *mode);
static estream_t open_es_fwrite (const char *filename);
static void run_protect_tool (int argc, char **argv);
static int
our_pk_test_algo (int algo)
{
switch (algo)
{
case GCRY_PK_RSA:
case GCRY_PK_ECDSA:
return gcry_pk_test_algo (algo);
default:
return 1;
}
}
static int
our_cipher_test_algo (int algo)
{
switch (algo)
{
case GCRY_CIPHER_3DES:
case GCRY_CIPHER_AES128:
case GCRY_CIPHER_AES192:
case GCRY_CIPHER_AES256:
case GCRY_CIPHER_SERPENT128:
case GCRY_CIPHER_SERPENT192:
case GCRY_CIPHER_SERPENT256:
case GCRY_CIPHER_SEED:
case GCRY_CIPHER_CAMELLIA128:
case GCRY_CIPHER_CAMELLIA192:
case GCRY_CIPHER_CAMELLIA256:
return gcry_cipher_test_algo (algo);
default:
return 1;
}
}
static int
our_md_test_algo (int algo)
{
switch (algo)
{
case GCRY_MD_MD5:
case GCRY_MD_SHA1:
case GCRY_MD_RMD160:
case GCRY_MD_SHA224:
case GCRY_MD_SHA256:
case GCRY_MD_SHA384:
case GCRY_MD_SHA512:
case GCRY_MD_WHIRLPOOL:
return gcry_md_test_algo (algo);
default:
return 1;
}
}
static char *
make_libversion (const char *libname, const char *(*getfnc)(const char*))
{
const char *s;
char *result;
if (maybe_setuid)
{
gcry_control (GCRYCTL_INIT_SECMEM, 0, 0); /* Drop setuid. */
maybe_setuid = 0;
}
s = getfnc (NULL);
result = xmalloc (strlen (libname) + 1 + strlen (s) + 1);
strcpy (stpcpy (stpcpy (result, libname), " "), s);
return result;
}
static const char *
my_strusage( int level )
{
static char *digests, *pubkeys, *ciphers;
static char *ver_gcry, *ver_ksba;
const char *p;
switch (level)
{
case 9: p = "GPL-3.0-or-later"; break;
case 11: p = "@GPGSM@ (@GNUPG@)";
break;
case 13: p = VERSION; break;
case 14: p = GNUPG_DEF_COPYRIGHT_LINE; break;
case 17: p = PRINTABLE_OS_NAME; break;
case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
case 1:
case 40: p = _("Usage: @GPGSM@ [options] [files] (-h for help)");
break;
case 41:
p = _("Syntax: @GPGSM@ [options] [files]\n"
"Sign, check, encrypt or decrypt using the S/MIME protocol\n"
"Default operation depends on the input data\n");
break;
case 20:
if (!ver_gcry)
ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
p = ver_gcry;
break;
case 21:
if (!ver_ksba)
ver_ksba = make_libversion ("libksba", ksba_check_version);
p = ver_ksba;
break;
case 31: p = "\nHome: "; break;
case 32: p = gnupg_homedir (); break;
case 33: p = _("\nSupported algorithms:\n"); break;
case 34:
if (!ciphers)
ciphers = build_list ("Cipher: ", gnupg_cipher_algo_name,
our_cipher_test_algo );
p = ciphers;
break;
case 35:
if (!pubkeys)
pubkeys = build_list ("Pubkey: ", gcry_pk_algo_name,
our_pk_test_algo );
p = pubkeys;
break;
case 36:
if (!digests)
digests = build_list("Hash: ", gcry_md_algo_name, our_md_test_algo );
p = digests;
break;
default: p = NULL; break;
}
return p;
}
static char *
build_list (const char *text, const char * (*mapf)(int), int (*chkf)(int))
{
int i;
size_t n=strlen(text)+2;
char *list, *p;
if (maybe_setuid) {
gcry_control (GCRYCTL_DROP_PRIVS); /* drop setuid */
}
for (i=1; i < 400; i++ )
if (!chkf(i))
n += strlen(mapf(i)) + 2;
list = xmalloc (21 + n);
*list = 0;
for (p=NULL, i=1; i < 400; i++)
{
if (!chkf(i))
{
if( !p )
p = stpcpy (list, text );
else
p = stpcpy (p, ", ");
p = stpcpy (p, mapf(i) );
}
}
if (p)
strcpy (p, "\n" );
return list;
}
/* Set the file pointer into binary mode if required. */
static void
set_binary (FILE *fp)
{
#ifdef HAVE_DOSISH_SYSTEM
setmode (fileno (fp), O_BINARY);
#else
(void)fp;
#endif
}
static void
wrong_args (const char *text)
{
fprintf (stderr, _("usage: %s [options] %s\n"), GPGSM_NAME, text);
gpgsm_exit (2);
}
static void
set_opt_session_env (const char *name, const char *value)
{
gpg_error_t err;
err = session_env_setenv (opt.session_env, name, value);
if (err)
log_fatal ("error setting session environment: %s\n",
gpg_strerror (err));
}
/* Setup the debugging. With a DEBUG_LEVEL of NULL only the active
debug flags are propagated to the subsystems. With DEBUG_LEVEL
set, a specific set of debug flags is set; and individual debugging
flags will be added on top. */
static void
set_debug (void)
{
int numok = (debug_level && digitp (debug_level));
int numlvl = numok? atoi (debug_level) : 0;
if (!debug_level)
;
else if (!strcmp (debug_level, "none") || (numok && numlvl < 1))
opt.debug = 0;
else if (!strcmp (debug_level, "basic") || (numok && numlvl <= 2))
opt.debug = DBG_IPC_VALUE;
else if (!strcmp (debug_level, "advanced") || (numok && numlvl <= 5))
opt.debug = DBG_IPC_VALUE|DBG_X509_VALUE;
else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE
|DBG_CACHE_VALUE|DBG_CRYPTO_VALUE);
else if (!strcmp (debug_level, "guru") || numok)
{
opt.debug = ~0;
/* Unless the "guru" string has been used we don't want to allow
hashing debugging. The rationale is that people tend to
select the highest debug value and would then clutter their
disk with debug files which may reveal confidential data. */
if (numok)
opt.debug &= ~(DBG_HASHING_VALUE);
}
else
{
log_error (_("invalid debug-level '%s' given\n"), debug_level);
gpgsm_exit (2);
}
opt.debug |= debug_value;
if (opt.debug && !opt.verbose)
opt.verbose = 1;
if (opt.debug)
opt.quiet = 0;
if (opt.debug & DBG_MPI_VALUE)
gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 2);
if (opt.debug & DBG_CRYPTO_VALUE )
gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
if (opt.debug)
parse_debug_flag (NULL, &opt.debug, debug_flags);
/* minip12.c may be used outside of GnuPG, thus we don't have the
* opt structure over there. */
p12_set_verbosity (opt.verbose);
}
static void
set_cmd (enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd)
{
enum cmd_and_opt_values cmd = *ret_cmd;
if (!cmd || cmd == new_cmd)
cmd = new_cmd;
else if ( cmd == aSign && new_cmd == aEncr )
cmd = aSignEncr;
else if ( cmd == aEncr && new_cmd == aSign )
cmd = aSignEncr;
else if ( (cmd == aSign && new_cmd == aClearsign)
|| (cmd == aClearsign && new_cmd == aSign) )
cmd = aClearsign;
else
{
log_error(_("conflicting commands\n"));
gpgsm_exit(2);
}
*ret_cmd = cmd;
}
/* Helper to add recipients to a list. */
static void
do_add_recipient (ctrl_t ctrl, const char *name,
certlist_t *recplist, int is_encrypt_to, int recp_required)
{
int rc = gpgsm_add_to_certlist (ctrl, name, 0, recplist, is_encrypt_to);
if (rc)
{
if (recp_required)
{
log_error ("can't encrypt to '%s': %s\n", name, gpg_strerror (rc));
gpgsm_status2 (ctrl, STATUS_INV_RECP,
get_inv_recpsgnr_code (rc), name, NULL);
}
else
log_info (_("Note: won't be able to encrypt to '%s': %s\n"),
name, gpg_strerror (rc));
}
}
static void
parse_validation_model (const char *model)
{
int i = gpgsm_parse_validation_model (model);
if (i == -1)
log_error (_("unknown validation model '%s'\n"), model);
else
default_validation_model = i;
}
int
main ( int argc, char **argv)
{
ARGPARSE_ARGS pargs;
int orig_argc;
char **orig_argv;
/* char *username;*/
int may_coredump;
strlist_t sl, remusr= NULL, locusr=NULL;
strlist_t nrings=NULL;
int detached_sig = 0;
char *last_configname = NULL;
const char *configname = NULL; /* NULL or points to last_configname.
* NULL also indicates that we are
* processing options from the cmdline. */
int debug_argparser = 0;
int no_more_options = 0;
int default_keyring = 1;
char *logfile = NULL;
char *auditlog = NULL;
char *htmlauditlog = NULL;
int greeting = 0;
int nogreeting = 0;
int debug_wait = 0;
int use_random_seed = 1;
int no_common_certs_import = 0;
int with_fpr = 0;
const char *forced_digest_algo = NULL;
const char *extra_digest_algo = NULL;
enum cmd_and_opt_values cmd = 0;
struct server_control_s ctrl;
certlist_t recplist = NULL;
certlist_t signerlist = NULL;
int do_not_setup_keys = 0;
int recp_required = 0;
estream_t auditfp = NULL;
estream_t htmlauditfp = NULL;
struct assuan_malloc_hooks malloc_hooks;
int pwfd = -1;
static const char *homedirvalue;
early_system_init ();
gnupg_reopen_std (GPGSM_NAME);
/* trap_unaligned ();*/
gnupg_rl_initialize ();
set_strusage (my_strusage);
gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
/* Please note that we may running SUID(ROOT), so be very CAREFUL
when adding any stuff between here and the call to secmem_init()
somewhere after the option parsing */
log_set_prefix (GPGSM_NAME, GPGRT_LOG_WITH_PREFIX);
/* Make sure that our subsystems are ready. */
i18n_init ();
init_common_subsystems (&argc, &argv);
/* Check that the libraries are suitable. Do it here because the
option parse may need services of the library */
if (!ksba_check_version (NEED_KSBA_VERSION) )
log_fatal (_("%s is too old (need %s, have %s)\n"), "libksba",
NEED_KSBA_VERSION, ksba_check_version (NULL) );
gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
may_coredump = disable_core_dumps ();
gnupg_init_signals (0, emergency_cleanup);
dotlock_create (NULL, 0); /* Register lockfile cleanup. */
/* Tell the compliance module who we are. */
gnupg_initialize_compliance (GNUPG_MODULE_NAME_GPGSM);
opt.autostart = 1;
opt.session_env = session_env_new ();
if (!opt.session_env)
log_fatal ("error allocating session environment block: %s\n",
strerror (errno));
/* Note: If you change this default cipher algorithm , please
remember to update the Gpgconflist entry as well. */
opt.def_cipher_algoid = DEFAULT_CIPHER_ALGO;
/* First check whether we have a config file on the commandline */
orig_argc = argc;
orig_argv = argv;
pargs.argc = &argc;
pargs.argv = &argv;
pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
while (gnupg_argparse (NULL, &pargs, opts))
{
switch (pargs.r_opt)
{
case oDebug:
case oDebugAll:
debug_argparser++;
break;
case oNoOptions:
/* Set here here because the homedir would otherwise be
* created before main option parsing starts. */
opt.no_homedir_creation = 1;
break;
case oHomedir:
homedirvalue = pargs.r.ret_str;
break;
case aCallProtectTool:
/* Make sure that --version and --help are passed to the
* protect-tool. */
goto leave_cmdline_parser;
}
}
leave_cmdline_parser:
/* Reset the flags. */
pargs.flags &= ~(ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
/* Initialize the secure memory. */
gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
maybe_setuid = 0;
/*
* Now we are now working under our real uid
*/
ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
malloc_hooks.malloc = gcry_malloc;
malloc_hooks.realloc = gcry_realloc;
malloc_hooks.free = gcry_free;
assuan_set_malloc_hooks (&malloc_hooks);
assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
setup_libassuan_logging (&opt.debug, NULL);
/* Set homedir. */
gnupg_set_homedir (homedirvalue);
/* Setup a default control structure for command line mode */
memset (&ctrl, 0, sizeof ctrl);
gpgsm_init_default_ctrl (&ctrl);
ctrl.no_server = 1;
ctrl.status_fd = -1; /* No status output. */
ctrl.autodetect_encoding = 1;
/* Set the default policy file */
opt.policy_file = make_filename (gnupg_homedir (), "policies.txt", NULL);
/* The configuraton directories for use by gpgrt_argparser. */
gnupg_set_confdir (GNUPG_CONFDIR_SYS, gnupg_sysconfdir ());
gnupg_set_confdir (GNUPG_CONFDIR_USER, gnupg_homedir ());
/* We are re-using the struct, thus the reset flag. We OR the
* flags so that the internal intialized flag won't be cleared. */
argc = orig_argc;
argv = orig_argv;
pargs.argc = &argc;
pargs.argv = &argv;
pargs.flags |= (ARGPARSE_FLAG_RESET
| ARGPARSE_FLAG_KEEP
| ARGPARSE_FLAG_SYS
| ARGPARSE_FLAG_USER);
while (!no_more_options
&& gnupg_argparser (&pargs, opts, GPGSM_NAME EXTSEP_S "conf"))
{
switch (pargs.r_opt)
{
case ARGPARSE_CONFFILE:
if (debug_argparser)
log_info (_("reading options from '%s'\n"),
pargs.r_type? pargs.r.ret_str: "[cmdline]");
if (pargs.r_type)
{
xfree (last_configname);
last_configname = xstrdup (pargs.r.ret_str);
configname = last_configname;
}
else
configname = NULL;
break;
case aGPGConfList:
case aGPGConfTest:
set_cmd (&cmd, pargs.r_opt);
do_not_setup_keys = 1;
default_keyring = 0;
nogreeting = 1;
break;
case aServer:
opt.batch = 1;
set_cmd (&cmd, aServer);
break;
case aCallDirmngr:
opt.batch = 1;
set_cmd (&cmd, aCallDirmngr);
do_not_setup_keys = 1;
break;
case aCallProtectTool:
opt.batch = 1;
set_cmd (&cmd, aCallProtectTool);
no_more_options = 1; /* Stop parsing. */
do_not_setup_keys = 1;
break;
case aDeleteKey:
set_cmd (&cmd, aDeleteKey);
/*greeting=1;*/
do_not_setup_keys = 1;
break;
case aDetachedSign:
detached_sig = 1;
set_cmd (&cmd, aSign );
break;
case aKeygen:
set_cmd (&cmd, aKeygen);
greeting=1;
do_not_setup_keys = 1;
break;
case aImport:
case aSendKeys:
case aRecvKeys:
case aExport:
case aExportSecretKeyP12:
case aExportSecretKeyP8:
case aExportSecretKeyRaw:
case aDumpKeys:
case aDumpChain:
case aDumpExternalKeys:
case aDumpSecretKeys:
case aListKeys:
case aListExternalKeys:
case aListSecretKeys:
case aListChain:
case aLearnCard:
case aPasswd:
case aKeydbClearSomeCertFlags:
do_not_setup_keys = 1;
set_cmd (&cmd, pargs.r_opt);
break;
case aEncr:
recp_required = 1;
set_cmd (&cmd, pargs.r_opt);
break;
case aSym:
case aDecrypt:
case aSign:
case aClearsign:
case aVerify:
set_cmd (&cmd, pargs.r_opt);
break;
/* Output encoding selection. */
case oArmor:
ctrl.create_pem = 1;
break;
case oBase64:
ctrl.create_pem = 0;
ctrl.create_base64 = 1;
break;
case oNoArmor:
ctrl.create_pem = 0;
ctrl.create_base64 = 0;
break;
case oP12Charset:
opt.p12_charset = pargs.r.ret_str;
break;
case oPassphraseFD:
pwfd = translate_sys2libc_fd_int (pargs.r.ret_int, 0);
break;
case oPinentryMode:
opt.pinentry_mode = parse_pinentry_mode (pargs.r.ret_str);
if (opt.pinentry_mode == -1)
log_error (_("invalid pinentry mode '%s'\n"), pargs.r.ret_str);
break;
case oRequestOrigin:
opt.request_origin = parse_request_origin (pargs.r.ret_str);
if (opt.request_origin == -1)
log_error (_("invalid request origin '%s'\n"), pargs.r.ret_str);
break;
/* Input encoding selection. */
case oAssumeArmor:
ctrl.autodetect_encoding = 0;
ctrl.is_pem = 1;
ctrl.is_base64 = 0;
break;
case oAssumeBase64:
ctrl.autodetect_encoding = 0;
ctrl.is_pem = 0;
ctrl.is_base64 = 1;
break;
case oAssumeBinary:
ctrl.autodetect_encoding = 0;
ctrl.is_pem = 0;
ctrl.is_base64 = 0;
break;
case oDisableCRLChecks:
opt.no_crl_check = 1;
break;
case oEnableCRLChecks:
opt.no_crl_check = 0;
break;
case oDisableTrustedCertCRLCheck:
opt.no_trusted_cert_crl_check = 1;
break;
case oEnableTrustedCertCRLCheck:
opt.no_trusted_cert_crl_check = 0;
break;
case oForceCRLRefresh:
opt.force_crl_refresh = 1;
break;
case oEnableIssuerBasedCRLCheck:
opt.enable_issuer_based_crl_check = 1;
break;
case oDisableOCSP:
ctrl.use_ocsp = opt.enable_ocsp = 0;
break;
case oEnableOCSP:
ctrl.use_ocsp = opt.enable_ocsp = 1;
break;
case oIncludeCerts:
ctrl.include_certs = default_include_certs = pargs.r.ret_int;
break;
case oPolicyFile:
xfree (opt.policy_file);
if (*pargs.r.ret_str)
opt.policy_file = xstrdup (pargs.r.ret_str);
else
opt.policy_file = NULL;
break;
case oDisablePolicyChecks:
opt.no_policy_check = 1;
break;
case oEnablePolicyChecks:
opt.no_policy_check = 0;
break;
case oAutoIssuerKeyRetrieve:
opt.auto_issuer_key_retrieve = 1;
break;
case oOutput: opt.outfile = pargs.r.ret_str; break;
case oQuiet: opt.quiet = 1; break;
case oNoTTY: /* fixme:tty_no_terminal(1);*/ break;
case oDryRun: opt.dry_run = 1; break;
case oVerbose:
opt.verbose++;
gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
break;
case oNoVerbose:
opt.verbose = 0;
gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
break;
case oLogFile: logfile = pargs.r.ret_str; break;
case oNoLogFile: logfile = NULL; break;
case oAuditLog: auditlog = pargs.r.ret_str; break;
case oHtmlAuditLog: htmlauditlog = pargs.r.ret_str; break;
case oBatch:
opt.batch = 1;
greeting = 0;
break;
case oNoBatch: opt.batch = 0; break;
case oAnswerYes: opt.answer_yes = 1; break;
case oAnswerNo: opt.answer_no = 1; break;
case oKeyring: append_to_strlist (&nrings, pargs.r.ret_str); break;
case oDebug:
if (parse_debug_flag (pargs.r.ret_str, &debug_value, debug_flags))
{
pargs.r_opt = ARGPARSE_INVALID_ARG;
pargs.err = ARGPARSE_PRINT_ERROR;
}
break;
case oDebugAll: debug_value = ~0; break;
case oDebugNone: debug_value = 0; break;
case oDebugLevel: debug_level = pargs.r.ret_str; break;
case oDebugWait: debug_wait = pargs.r.ret_int; break;
case oDebugAllowCoreDump:
may_coredump = enable_core_dumps ();
break;
case oDebugNoChainValidation: opt.no_chain_validation = 1; break;
case oDebugIgnoreExpiration: opt.ignore_expiration = 1; break;
case oStatusFD:
ctrl.status_fd = translate_sys2libc_fd_int (pargs.r.ret_int, 1);
break;
case oLoggerFD:
log_set_fd (translate_sys2libc_fd_int (pargs.r.ret_int, 1));
break;
case oWithMD5Fingerprint:
opt.with_md5_fingerprint=1; /*fall through*/
case oWithFingerprint:
with_fpr=1; /*fall through*/
case aFingerprint:
opt.fingerprint++;
break;
case oWithKeygrip:
opt.with_keygrip = 1;
break;
case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break;
case oAgentProgram: opt.agent_program = pargs.r.ret_str; break;
case oDisplay:
set_opt_session_env ("DISPLAY", pargs.r.ret_str);
break;
case oTTYname:
set_opt_session_env ("GPG_TTY", pargs.r.ret_str);
break;
case oTTYtype:
set_opt_session_env ("TERM", pargs.r.ret_str);
break;
case oXauthority:
set_opt_session_env ("XAUTHORITY", pargs.r.ret_str);
break;
case oLCctype: opt.lc_ctype = xstrdup (pargs.r.ret_str); break;
case oLCmessages: opt.lc_messages = xstrdup (pargs.r.ret_str); break;
case oDirmngrProgram: opt.dirmngr_program = pargs.r.ret_str; break;
case oDisableDirmngr: opt.disable_dirmngr = 1; break;
case oPreferSystemDirmngr: /* Obsolete */; break;
case oProtectToolProgram:
opt.protect_tool_program = pargs.r.ret_str;
break;
case oFakedSystemTime:
{
time_t faked_time = isotime2epoch (pargs.r.ret_str);
if (faked_time == (time_t)(-1))
faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
gnupg_set_time (faked_time, 0);
}
break;
case oNoDefKeyring: default_keyring = 0; break;
case oNoGreeting: nogreeting = 1; break;
case oDefaultKey:
if (*pargs.r.ret_str)
{
xfree (opt.local_user);
opt.local_user = xstrdup (pargs.r.ret_str);
}
break;
case oDefRecipient:
if (*pargs.r.ret_str)
opt.def_recipient = xstrdup (pargs.r.ret_str);
break;
case oDefRecipientSelf:
xfree (opt.def_recipient);
opt.def_recipient = NULL;
opt.def_recipient_self = 1;
break;
case oNoDefRecipient:
xfree (opt.def_recipient);
opt.def_recipient = NULL;
opt.def_recipient_self = 0;
break;
case oWithKeyData: opt.with_key_data=1; /* fall through */
case oWithColons: ctrl.with_colons = 1; break;
case oWithSecret: ctrl.with_secret = 1; break;
case oWithValidation: ctrl.with_validation=1; break;
case oWithEphemeralKeys: ctrl.with_ephemeral_keys=1; break;
case oSkipVerify: opt.skip_verify=1; break;
case oNoEncryptTo: opt.no_encrypt_to = 1; break;
case oEncryptTo: /* Store the recipient in the second list */
sl = add_to_strlist (&remusr, pargs.r.ret_str);
sl->flags = 1;
break;
case oRecipient: /* store the recipient */
add_to_strlist ( &remusr, pargs.r.ret_str);
break;
case oUser: /* Store the local users, the first one is the default */
if (!opt.local_user)
opt.local_user = xstrdup (pargs.r.ret_str);
add_to_strlist (&locusr, pargs.r.ret_str);
break;
case oNoSecmemWarn:
gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
break;
case oCipherAlgo:
opt.def_cipher_algoid = pargs.r.ret_str;
break;
case oDisableCipherAlgo:
{
int algo = gcry_cipher_map_name (pargs.r.ret_str);
gcry_cipher_ctl (NULL, GCRYCTL_DISABLE_ALGO, &algo, sizeof algo);
}
break;
case oDisablePubkeyAlgo:
{
int algo = gcry_pk_map_name (pargs.r.ret_str);
gcry_pk_ctl (GCRYCTL_DISABLE_ALGO,&algo, sizeof algo );
}
break;
case oDigestAlgo:
forced_digest_algo = pargs.r.ret_str;
break;
case oExtraDigestAlgo:
extra_digest_algo = pargs.r.ret_str;
break;
case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
case oNoRandomSeedFile: use_random_seed = 0; break;
case oNoCommonCertsImport: no_common_certs_import = 1; break;
case oEnableSpecialFilenames:
enable_special_filenames ();
break;
case oValidationModel: parse_validation_model (pargs.r.ret_str); break;
case oKeyServer:
append_to_strlist (&opt.keyserver, pargs.r.ret_str);
break;
+ case oKeyServer_deprecated:
+ obsolete_option (configname, pargs.lineno, "ldapserver");
+ break;
+
case oIgnoreCertExtension:
add_to_strlist (&opt.ignored_cert_extensions, pargs.r.ret_str);
break;
case oNoAutostart: opt.autostart = 0; break;
case oCompliance:
{
struct gnupg_compliance_option compliance_options[] =
{
{ "gnupg", CO_GNUPG },
{ "de-vs", CO_DE_VS }
};
int compliance = gnupg_parse_compliance_option (pargs.r.ret_str,
compliance_options,
DIM (compliance_options),
opt.quiet);
if (compliance < 0)
log_inc_errorcount (); /* Force later termination. */
opt.compliance = compliance;
}
break;
case oMinRSALength: opt.min_rsa_length = pargs.r.ret_ulong; break;
default:
if (configname)
pargs.err = ARGPARSE_PRINT_WARNING;
else
{
pargs.err = ARGPARSE_PRINT_ERROR;
/* The argparse function calls a plain exit and thus we
* need to print a status here. */
gpgsm_status_with_error (&ctrl, STATUS_FAILURE, "option-parser",
gpg_error (GPG_ERR_GENERAL));
}
break;
}
}
gnupg_argparse (NULL, &pargs, NULL); /* Release internal state. */
if (!last_configname)
opt.config_filename = make_filename (gnupg_homedir (),
GPGSM_NAME EXTSEP_S "conf",
NULL);
else
opt.config_filename = last_configname;
if (log_get_errorcount(0))
{
gpgsm_status_with_error (&ctrl, STATUS_FAILURE,
"option-parser", gpg_error (GPG_ERR_GENERAL));
gpgsm_exit(2);
}
if (pwfd != -1) /* Read the passphrase now. */
read_passphrase_from_fd (pwfd);
/* Now that we have the options parsed we need to update the default
control structure. */
gpgsm_init_default_ctrl (&ctrl);
if (nogreeting)
greeting = 0;
if (greeting)
{
es_fprintf (es_stderr, "%s %s; %s\n",
strusage(11), strusage(13), strusage(14) );
es_fprintf (es_stderr, "%s\n", strusage(15) );
}
# ifdef IS_DEVELOPMENT_VERSION
if (!opt.batch)
{
log_info ("NOTE: THIS IS A DEVELOPMENT VERSION!\n");
log_info ("It is only intended for test purposes and should NOT be\n");
log_info ("used in a production environment or with production keys!\n");
}
# endif
if (may_coredump && !opt.quiet)
log_info (_("WARNING: program may create a core file!\n"));
/* if (opt.qualsig_approval && !opt.quiet) */
/* log_info (_("This software has officially been approved to " */
/* "create and verify\n" */
/* "qualified signatures according to German law.\n")); */
if (logfile && cmd == aServer)
{
log_set_file (logfile);
log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
}
if (gnupg_faked_time_p ())
{
gnupg_isotime_t tbuf;
log_info (_("WARNING: running with faked system time: "));
gnupg_get_isotime (tbuf);
dump_isotime (tbuf);
log_printf ("\n");
}
/* Print a warning if an argument looks like an option. */
if (!opt.quiet && !(pargs.flags & ARGPARSE_FLAG_STOP_SEEN))
{
int i;
for (i=0; i < argc; i++)
if (argv[i][0] == '-' && argv[i][1] == '-')
log_info (_("Note: '%s' is not considered an option\n"), argv[i]);
}
/*FIXME if (opt.batch) */
/* tty_batchmode (1); */
gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
set_debug ();
gnupg_set_compliance_extra_info (opt.min_rsa_length);
/* Although we always use gpgsm_exit, we better install a regualr
exit handler so that at least the secure memory gets wiped
out. */
if (atexit (emergency_cleanup))
{
log_error ("atexit failed\n");
gpgsm_exit (2);
}
/* Must do this after dropping setuid, because the mapping functions
may try to load an module and we may have disabled an algorithm.
We remap the commonly used algorithms to the OIDs for
convenience. We need to work with the OIDs because they are used
to check whether the encryption mode is actually available. */
if (!strcmp (opt.def_cipher_algoid, "3DES") )
opt.def_cipher_algoid = "1.2.840.113549.3.7";
else if (!strcmp (opt.def_cipher_algoid, "AES")
|| !strcmp (opt.def_cipher_algoid, "AES128"))
opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.2";
else if (!strcmp (opt.def_cipher_algoid, "AES192") )
opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.22";
else if (!strcmp (opt.def_cipher_algoid, "AES256") )
opt.def_cipher_algoid = "2.16.840.1.101.3.4.1.42";
else if (!strcmp (opt.def_cipher_algoid, "SERPENT")
|| !strcmp (opt.def_cipher_algoid, "SERPENT128") )
opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.2";
else if (!strcmp (opt.def_cipher_algoid, "SERPENT192") )
opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.22";
else if (!strcmp (opt.def_cipher_algoid, "SERPENT256") )
opt.def_cipher_algoid = "1.3.6.1.4.1.11591.13.2.42";
else if (!strcmp (opt.def_cipher_algoid, "SEED") )
opt.def_cipher_algoid = "1.2.410.200004.1.4";
else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA")
|| !strcmp (opt.def_cipher_algoid, "CAMELLIA128") )
opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.2";
else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA192") )
opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.3";
else if (!strcmp (opt.def_cipher_algoid, "CAMELLIA256") )
opt.def_cipher_algoid = "1.2.392.200011.61.1.1.1.4";
if (cmd != aGPGConfList)
{
if ( !gcry_cipher_map_name (opt.def_cipher_algoid)
|| !gcry_cipher_mode_from_oid (opt.def_cipher_algoid))
log_error (_("selected cipher algorithm is invalid\n"));
if (forced_digest_algo)
{
opt.forced_digest_algo = gcry_md_map_name (forced_digest_algo);
if (our_md_test_algo(opt.forced_digest_algo) )
log_error (_("selected digest algorithm is invalid\n"));
}
if (extra_digest_algo)
{
opt.extra_digest_algo = gcry_md_map_name (extra_digest_algo);
if (our_md_test_algo (opt.extra_digest_algo) )
log_error (_("selected digest algorithm is invalid\n"));
}
}
/* Check our chosen algorithms against the list of allowed
* algorithms in the current compliance mode, and fail hard if it is
* not. This is us being nice to the user informing her early that
* the chosen algorithms are not available. We also check and
* enforce this right before the actual operation. */
if (! gnupg_cipher_is_allowed (opt.compliance,
cmd == aEncr || cmd == aSignEncr,
gcry_cipher_map_name (opt.def_cipher_algoid),
GCRY_CIPHER_MODE_NONE)
&& ! gnupg_cipher_is_allowed (opt.compliance,
cmd == aEncr || cmd == aSignEncr,
gcry_cipher_mode_from_oid
(opt.def_cipher_algoid),
GCRY_CIPHER_MODE_NONE))
log_error (_("cipher algorithm '%s' may not be used in %s mode\n"),
opt.def_cipher_algoid,
gnupg_compliance_option_string (opt.compliance));
if (forced_digest_algo
&& ! gnupg_digest_is_allowed (opt.compliance,
cmd == aSign
|| cmd == aSignEncr
|| cmd == aClearsign,
opt.forced_digest_algo))
log_error (_("digest algorithm '%s' may not be used in %s mode\n"),
forced_digest_algo,
gnupg_compliance_option_string (opt.compliance));
if (extra_digest_algo
&& ! gnupg_digest_is_allowed (opt.compliance,
cmd == aSign
|| cmd == aSignEncr
|| cmd == aClearsign,
opt.extra_digest_algo))
log_error (_("digest algorithm '%s' may not be used in %s mode\n"),
extra_digest_algo,
gnupg_compliance_option_string (opt.compliance));
if (log_get_errorcount(0))
{
gpgsm_status_with_error (&ctrl, STATUS_FAILURE, "option-postprocessing",
gpg_error (GPG_ERR_GENERAL));
gpgsm_exit (2);
}
/* Set the random seed file. */
if (use_random_seed)
{
char *p = make_filename (gnupg_homedir (), "random_seed", NULL);
gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
xfree(p);
}
if (!cmd && opt.fingerprint && !with_fpr)
set_cmd (&cmd, aListKeys);
/* Add default keybox. */
if (!nrings && default_keyring)
{
int created;
keydb_add_resource (&ctrl, "pubring.kbx", 0, &created);
if (created && !no_common_certs_import)
{
/* Import the standard certificates for a new default keybox. */
char *filelist[2];
filelist[0] = make_filename (gnupg_datadir (),"com-certs.pem", NULL);
filelist[1] = NULL;
if (!gnupg_access (filelist[0], F_OK))
{
log_info (_("importing common certificates '%s'\n"),
filelist[0]);
gpgsm_import_files (&ctrl, 1, filelist, open_read);
}
xfree (filelist[0]);
}
}
for (sl = nrings; sl; sl = sl->next)
keydb_add_resource (&ctrl, sl->d, 0, NULL);
FREE_STRLIST(nrings);
/* Prepare the audit log feature for certain commands. */
if (auditlog || htmlauditlog)
{
switch (cmd)
{
case aEncr:
case aSign:
case aDecrypt:
case aVerify:
audit_release (ctrl.audit);
ctrl.audit = audit_new ();
if (auditlog)
auditfp = open_es_fwrite (auditlog);
if (htmlauditlog)
htmlauditfp = open_es_fwrite (htmlauditlog);
break;
default:
break;
}
}
if (!do_not_setup_keys)
{
int errcount = log_get_errorcount (0);
for (sl = locusr; sl ; sl = sl->next)
{
int rc = gpgsm_add_to_certlist (&ctrl, sl->d, 1, &signerlist, 0);
if (rc)
{
log_error (_("can't sign using '%s': %s\n"),
sl->d, gpg_strerror (rc));
gpgsm_status2 (&ctrl, STATUS_INV_SGNR,
get_inv_recpsgnr_code (rc), sl->d, NULL);
gpgsm_status2 (&ctrl, STATUS_INV_RECP,
get_inv_recpsgnr_code (rc), sl->d, NULL);
}
}
/* Build the recipient list. We first add the regular ones and then
the encrypt-to ones because the underlying function will silently
ignore duplicates and we can't allow keeping a duplicate which is
flagged as encrypt-to as the actually encrypt function would then
complain about no (regular) recipients. */
for (sl = remusr; sl; sl = sl->next)
if (!(sl->flags & 1))
do_add_recipient (&ctrl, sl->d, &recplist, 0, recp_required);
if (!opt.no_encrypt_to)
{
for (sl = remusr; sl; sl = sl->next)
if ((sl->flags & 1))
do_add_recipient (&ctrl, sl->d, &recplist, 1, recp_required);
}
/* We do not require a recipient for decryption but because
* recipients and signers are always checked and log_error is
* sometimes used (for failed signing keys or due to a failed
* CRL checking) that would have bumbed up the error counter.
* We clear the counter in the decryption case because there is
* no reason to force decryption to fail. */
if (cmd == aDecrypt && !errcount)
log_get_errorcount (1); /* clear counter */
}
if (log_get_errorcount(0))
gpgsm_exit(1); /* Must stop for invalid recipients. */
/* Dispatch command. */
switch (cmd)
{
case aGPGConfList:
{ /* List options and default values in the GPG Conf format. */
es_printf ("debug-level:%lu:\"none:\n", GC_OPT_FLAG_DEFAULT);
es_printf ("include-certs:%lu:%d:\n", GC_OPT_FLAG_DEFAULT,
DEFAULT_INCLUDE_CERTS);
es_printf ("cipher-algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
DEFAULT_CIPHER_ALGO);
es_printf ("p12-charset:%lu:\n", GC_OPT_FLAG_DEFAULT);
es_printf ("default-key:%lu:\n", GC_OPT_FLAG_DEFAULT);
es_printf ("encrypt-to:%lu:\n", GC_OPT_FLAG_DEFAULT);
/* The next one is an info only item and should match what
proc_parameters actually implements. */
es_printf ("default_pubkey_algo:%lu:\"%s:\n", GC_OPT_FLAG_DEFAULT,
"RSA-3072");
}
break;
case aGPGConfTest:
/* This is merely a dummy command to test whether the
configuration file is valid. */
break;
case aServer:
if (debug_wait)
{
log_debug ("waiting for debugger - my pid is %u .....\n",
(unsigned int)getpid());
gnupg_sleep (debug_wait);
log_debug ("... okay\n");
}
gpgsm_server (recplist);
break;
case aCallDirmngr:
if (!argc)
wrong_args ("--call-dirmngr <command> {args}");
else
if (gpgsm_dirmngr_run_command (&ctrl, *argv, argc-1, argv+1))
gpgsm_exit (1);
break;
case aCallProtectTool:
run_protect_tool (argc, argv);
break;
case aEncr: /* Encrypt the given file. */
{
estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
set_binary (stdin);
if (!argc) /* Source is stdin. */
gpgsm_encrypt (&ctrl, recplist, 0, fp);
else if (argc == 1) /* Source is the given file. */
gpgsm_encrypt (&ctrl, recplist, open_read (*argv), fp);
else
wrong_args ("--encrypt [datafile]");
es_fclose (fp);
}
break;
case aSign: /* Sign the given file. */
{
estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
/* Fixme: We should also allow concatenation of multiple files for
signing because that is what gpg does.*/
set_binary (stdin);
if (!argc) /* Create from stdin. */
gpgsm_sign (&ctrl, signerlist, 0, detached_sig, fp);
else if (argc == 1) /* From file. */
gpgsm_sign (&ctrl, signerlist,
open_read (*argv), detached_sig, fp);
else
wrong_args ("--sign [datafile]");
es_fclose (fp);
}
break;
case aSignEncr: /* sign and encrypt the given file */
log_error ("this command has not yet been implemented\n");
break;
case aClearsign: /* make a clearsig */
log_error ("this command has not yet been implemented\n");
break;
case aVerify:
{
estream_t fp = NULL;
set_binary (stdin);
if (argc == 2 && opt.outfile)
log_info ("option --output ignored for a detached signature\n");
else if (opt.outfile)
fp = open_es_fwrite (opt.outfile);
if (!argc)
gpgsm_verify (&ctrl, 0, -1, fp); /* normal signature from stdin */
else if (argc == 1)
gpgsm_verify (&ctrl, open_read (*argv), -1, fp); /* std signature */
else if (argc == 2) /* detached signature (sig, detached) */
gpgsm_verify (&ctrl, open_read (*argv), open_read (argv[1]), NULL);
else
wrong_args ("--verify [signature [detached_data]]");
es_fclose (fp);
}
break;
case aDecrypt:
{
estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
gpg_error_t err;
set_binary (stdin);
if (!argc)
err = gpgsm_decrypt (&ctrl, 0, fp); /* from stdin */
else if (argc == 1)
err = gpgsm_decrypt (&ctrl, open_read (*argv), fp); /* from file */
else
wrong_args ("--decrypt [filename]");
#if GPGRT_VERSION_NUMBER >= 0x012700 /* 1.39 */
if (err)
gpgrt_fcancel (fp);
else
#endif
es_fclose (fp);
}
break;
case aDeleteKey:
for (sl=NULL; argc; argc--, argv++)
add_to_strlist (&sl, *argv);
gpgsm_delete (&ctrl, sl);
free_strlist(sl);
break;
case aListChain:
case aDumpChain:
ctrl.with_chain = 1; /* fall through */
case aListKeys:
case aDumpKeys:
case aListExternalKeys:
case aDumpExternalKeys:
case aListSecretKeys:
case aDumpSecretKeys:
{
unsigned int mode;
estream_t fp;
switch (cmd)
{
case aListChain:
case aListKeys: mode = (0 | 0 | (1<<6)); break;
case aDumpChain:
case aDumpKeys: mode = (256 | 0 | (1<<6)); break;
case aListExternalKeys: mode = (0 | 0 | (1<<7)); break;
case aDumpExternalKeys: mode = (256 | 0 | (1<<7)); break;
case aListSecretKeys: mode = (0 | 2 | (1<<6)); break;
case aDumpSecretKeys: mode = (256 | 2 | (1<<6)); break;
default: BUG();
}
fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
for (sl=NULL; argc; argc--, argv++)
add_to_strlist (&sl, *argv);
gpgsm_list_keys (&ctrl, sl, fp, mode);
free_strlist(sl);
es_fclose (fp);
}
break;
case aKeygen: /* Generate a key; well kind of. */
{
estream_t fpin = NULL;
estream_t fpout;
if (opt.batch)
{
if (!argc) /* Create from stdin. */
fpin = open_es_fread ("-", "r");
else if (argc == 1) /* From file. */
fpin = open_es_fread (*argv, "r");
else
wrong_args ("--generate-key --batch [parmfile]");
}
fpout = open_es_fwrite (opt.outfile?opt.outfile:"-");
if (fpin)
gpgsm_genkey (&ctrl, fpin, fpout);
else
gpgsm_gencertreq_tty (&ctrl, fpout);
es_fclose (fpout);
}
break;
case aImport:
gpgsm_import_files (&ctrl, argc, argv, open_read);
break;
case aExport:
{
estream_t fp;
fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
for (sl=NULL; argc; argc--, argv++)
add_to_strlist (&sl, *argv);
gpgsm_export (&ctrl, sl, fp);
free_strlist(sl);
es_fclose (fp);
}
break;
case aExportSecretKeyP12:
{
estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
if (argc == 1)
gpgsm_p12_export (&ctrl, *argv, fp, 0);
else
wrong_args ("--export-secret-key-p12 KEY-ID");
if (fp != es_stdout)
es_fclose (fp);
}
break;
case aExportSecretKeyP8:
{
estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
if (argc == 1)
gpgsm_p12_export (&ctrl, *argv, fp, 1);
else
wrong_args ("--export-secret-key-p8 KEY-ID");
if (fp != es_stdout)
es_fclose (fp);
}
break;
case aExportSecretKeyRaw:
{
estream_t fp = open_es_fwrite (opt.outfile?opt.outfile:"-");
if (argc == 1)
gpgsm_p12_export (&ctrl, *argv, fp, 2);
else
wrong_args ("--export-secret-key-raw KEY-ID");
if (fp != es_stdout)
es_fclose (fp);
}
break;
case aSendKeys:
case aRecvKeys:
log_error ("this command has not yet been implemented\n");
break;
case aLearnCard:
if (argc)
wrong_args ("--learn-card");
else
{
int rc = gpgsm_agent_learn (&ctrl);
if (rc)
log_error ("error learning card: %s\n", gpg_strerror (rc));
}
break;
case aPasswd:
if (argc != 1)
wrong_args ("--change-passphrase <key-Id>");
else
{
int rc;
ksba_cert_t cert = NULL;
char *grip = NULL;
rc = gpgsm_find_cert (&ctrl, *argv, NULL, &cert, 0);
if (rc)
;
else if (!(grip = gpgsm_get_keygrip_hexstring (cert)))
rc = gpg_error (GPG_ERR_BUG);
else
{
char *desc = gpgsm_format_keydesc (cert);
rc = gpgsm_agent_passwd (&ctrl, grip, desc);
xfree (desc);
}
if (rc)
log_error ("error changing passphrase: %s\n", gpg_strerror (rc));
xfree (grip);
ksba_cert_release (cert);
}
break;
case aKeydbClearSomeCertFlags:
for (sl=NULL; argc; argc--, argv++)
add_to_strlist (&sl, *argv);
keydb_clear_some_cert_flags (&ctrl, sl);
free_strlist(sl);
break;
default:
log_error (_("invalid command (there is no implicit command)\n"));
break;
}
/* Print the audit result if needed. */
if ((auditlog && auditfp) || (htmlauditlog && htmlauditfp))
{
if (auditlog && auditfp)
audit_print_result (ctrl.audit, auditfp, 0);
if (htmlauditlog && htmlauditfp)
audit_print_result (ctrl.audit, htmlauditfp, 1);
audit_release (ctrl.audit);
ctrl.audit = NULL;
es_fclose (auditfp);
es_fclose (htmlauditfp);
}
/* cleanup */
free_strlist (opt.keyserver);
opt.keyserver = NULL;
gpgsm_release_certlist (recplist);
gpgsm_release_certlist (signerlist);
FREE_STRLIST (remusr);
FREE_STRLIST (locusr);
gpgsm_exit(0);
return 8; /*NOTREACHED*/
}
/* Note: This function is used by signal handlers!. */
static void
emergency_cleanup (void)
{
gcry_control (GCRYCTL_TERM_SECMEM );
}
void
gpgsm_exit (int rc)
{
gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
if (opt.debug & DBG_MEMSTAT_VALUE)
{
gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
}
if (opt.debug)
gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
emergency_cleanup ();
rc = rc? rc : log_get_errorcount(0)? 2 : gpgsm_errors_seen? 1 : 0;
exit (rc);
}
void
gpgsm_init_default_ctrl (struct server_control_s *ctrl)
{
ctrl->include_certs = default_include_certs;
ctrl->use_ocsp = opt.enable_ocsp;
ctrl->validation_model = default_validation_model;
ctrl->offline = opt.disable_dirmngr;
}
int
gpgsm_parse_validation_model (const char *model)
{
if (!ascii_strcasecmp (model, "shell") )
return 0;
else if ( !ascii_strcasecmp (model, "chain") )
return 1;
else if ( !ascii_strcasecmp (model, "steed") )
return 2;
else
return -1;
}
/* Open the FILENAME for read and return the file descriptor. Stop
with an error message in case of problems. "-" denotes stdin and
if special filenames are allowed the given fd is opened instead. */
static int
open_read (const char *filename)
{
int fd;
if (filename[0] == '-' && !filename[1])
{
set_binary (stdin);
return 0; /* stdin */
}
fd = check_special_filename (filename, 0, 0);
if (fd != -1)
return fd;
fd = gnupg_open (filename, O_RDONLY | O_BINARY, 0);
if (fd == -1)
{
log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
gpgsm_exit (2);
}
return fd;
}
/* Same as open_read but return an estream_t. */
static estream_t
open_es_fread (const char *filename, const char *mode)
{
int fd;
estream_t fp;
if (filename[0] == '-' && !filename[1])
fd = fileno (stdin);
else
fd = check_special_filename (filename, 0, 0);
if (fd != -1)
{
fp = es_fdopen_nc (fd, mode);
if (!fp)
{
log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
gpgsm_exit (2);
}
return fp;
}
fp = es_fopen (filename, mode);
if (!fp)
{
log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
gpgsm_exit (2);
}
return fp;
}
/* Open FILENAME for fwrite and return an extended stream. Stop with
an error message in case of problems. "-" denotes stdout and if
special filenames are allowed the given fd is opened instead.
Caller must close the returned stream. */
static estream_t
open_es_fwrite (const char *filename)
{
int fd;
estream_t fp;
if (filename[0] == '-' && !filename[1])
{
fflush (stdout);
fp = es_fdopen_nc (fileno(stdout), "wb");
return fp;
}
fd = check_special_filename (filename, 1, 0);
if (fd != -1)
{
fp = es_fdopen_nc (fd, "wb");
if (!fp)
{
log_error ("es_fdopen(%d) failed: %s\n", fd, strerror (errno));
gpgsm_exit (2);
}
return fp;
}
fp = es_fopen (filename, "wb");
if (!fp)
{
log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
gpgsm_exit (2);
}
return fp;
}
static void
run_protect_tool (int argc, char **argv)
{
#ifdef HAVE_W32_SYSTEM
(void)argc;
(void)argv;
#else
const char *pgm;
char **av;
int i;
if (!opt.protect_tool_program || !*opt.protect_tool_program)
pgm = gnupg_module_name (GNUPG_MODULE_NAME_PROTECT_TOOL);
else
pgm = opt.protect_tool_program;
av = xcalloc (argc+2, sizeof *av);
av[0] = strrchr (pgm, '/');
if (!av[0])
av[0] = xstrdup (pgm);
for (i=1; argc; i++, argc--, argv++)
av[i] = *argv;
av[i] = NULL;
execv (pgm, av);
log_error ("error executing '%s': %s\n", pgm, strerror (errno));
#endif /*!HAVE_W32_SYSTEM*/
gpgsm_exit (2);
}
diff --git a/tools/gpgconf-comp.c b/tools/gpgconf-comp.c
index 35ae3e7c0..9b0cc7d1f 100644
--- a/tools/gpgconf-comp.c
+++ b/tools/gpgconf-comp.c
@@ -1,3453 +1,3455 @@
/* gpgconf-comp.c - Configuration utility for GnuPG.
* Copyright (C) 2004, 2007-2011 Free Software Foundation, Inc.
* Copyright (C) 2016 Werner Koch
* Copyright (C) 2020-2022 g10 Code GmbH
*
* This file is part of GnuPG.
*
* GnuPG is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GnuPG is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GnuPG; if not, see <https://www.gnu.org/licenses/>.
*/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <time.h>
#include <stdarg.h>
#ifdef HAVE_SIGNAL_H
# include <signal.h>
#endif
#include <ctype.h>
#ifdef HAVE_W32_SYSTEM
# define WIN32_LEAN_AND_MEAN 1
# include <windows.h>
#else
# include <pwd.h>
# include <grp.h>
#endif
#include "../common/util.h"
#include "../common/i18n.h"
#include "../common/exechelp.h"
#include "../common/sysutils.h"
#include "../common/status.h"
#include "../common/gc-opt-flags.h"
#include "gpgconf.h"
/* There is a problem with gpg 1.4 under Windows: --gpgconf-list
returns a plain filename without escaping. As long as we have not
fixed that we need to use gpg2. */
#if defined(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM)
#define GPGNAME "gpg2"
#else
#define GPGNAME GPG_NAME
#endif
#if (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 5 ))
void gc_error (int status, int errnum, const char *fmt, ...) \
__attribute__ ((format (printf, 3, 4)));
#endif
/* Output a diagnostic message. If ERRNUM is not 0, then the output
is followed by a colon, a white space, and the error string for the
error number ERRNUM. In any case the output is finished by a
newline. The message is prepended by the program name, a colon,
and a whitespace. The output may be further formatted or
redirected by the jnlib logging facility. */
void
gc_error (int status, int errnum, const char *fmt, ...)
{
va_list arg_ptr;
va_start (arg_ptr, fmt);
log_logv (GPGRT_LOG_ERROR, fmt, arg_ptr);
va_end (arg_ptr);
if (errnum)
log_printf (": %s\n", strerror (errnum));
else
log_printf ("\n");
if (status)
{
log_printf (NULL);
log_printf ("fatal error (exit status %i)\n", status);
gpgconf_failure (gpg_error_from_errno (errnum));
}
}
/* Forward declaration. */
static void gpg_agent_runtime_change (int killflag);
static void scdaemon_runtime_change (int killflag);
static void dirmngr_runtime_change (int killflag);
/* STRING_ARRAY is a malloced array with malloced strings. It is used
* a space to store strings so that other objects may point to these
* strings. It shall never be shrinked or any items changes.
* STRING_ARRAY itself may be reallocated to increase the size of the
* table. STRING_ARRAY_USED is the number of items currently used,
* STRING_ARRAY_SIZE is the number of calloced slots. */
static char **string_array;
static size_t string_array_used;
static size_t string_array_size;
/* Option configuration. */
/* An option might take an argument, or not. Argument types can be
basic or complex. Basic types are generic and easy to validate.
Complex types provide more specific information about the intended
use, but can be difficult to validate. If you add to this enum,
don't forget to update GC_ARG_TYPE below. YOU MUST NOT CHANGE THE
NUMBERS OF THE EXISTING ENTRIES, AS THEY ARE PART OF THE EXTERNAL
INTERFACE. */
typedef enum
{
/* Basic argument types. */
/* No argument. */
GC_ARG_TYPE_NONE = 0,
/* A String argument. */
GC_ARG_TYPE_STRING = 1,
/* A signed integer argument. */
GC_ARG_TYPE_INT32 = 2,
/* An unsigned integer argument. */
GC_ARG_TYPE_UINT32 = 3,
/* ADD NEW BASIC TYPE ENTRIES HERE. */
/* Complex argument types. */
/* A complete filename. */
GC_ARG_TYPE_FILENAME = 32,
/* An LDAP server in the format
HOSTNAME:PORT:USERNAME:PASSWORD:BASE_DN. */
GC_ARG_TYPE_LDAP_SERVER = 33,
/* A 40 character fingerprint. */
GC_ARG_TYPE_KEY_FPR = 34,
/* A user ID or key ID or fingerprint for a certificate. */
GC_ARG_TYPE_PUB_KEY = 35,
/* A user ID or key ID or fingerprint for a certificate with a key. */
GC_ARG_TYPE_SEC_KEY = 36,
/* A alias list made up of a key, an equal sign and a space
separated list of values. */
GC_ARG_TYPE_ALIAS_LIST = 37,
/* ADD NEW COMPLEX TYPE ENTRIES HERE. */
/* The number of the above entries. */
GC_ARG_TYPE_NR
} gc_arg_type_t;
/* For every argument, we record some information about it in the
following struct. */
static const struct
{
/* For every argument type exists a basic argument type that can be
used as a fallback for input and validation purposes. */
gc_arg_type_t fallback;
/* Human-readable name of the type. */
const char *name;
} gc_arg_type[GC_ARG_TYPE_NR] =
{
/* The basic argument types have their own types as fallback. */
{ GC_ARG_TYPE_NONE, "none" },
{ GC_ARG_TYPE_STRING, "string" },
{ GC_ARG_TYPE_INT32, "int32" },
{ GC_ARG_TYPE_UINT32, "uint32" },
/* Reserved basic type entries for future extension. */
{ GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
{ GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
{ GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
{ GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
{ GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
{ GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
{ GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
{ GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
{ GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
{ GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
{ GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
{ GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
{ GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
{ GC_ARG_TYPE_NR, NULL }, { GC_ARG_TYPE_NR, NULL },
/* The complex argument types have a basic type as fallback. */
{ GC_ARG_TYPE_STRING, "filename" },
{ GC_ARG_TYPE_STRING, "ldap server" },
{ GC_ARG_TYPE_STRING, "key fpr" },
{ GC_ARG_TYPE_STRING, "pub key" },
{ GC_ARG_TYPE_STRING, "sec key" },
{ GC_ARG_TYPE_STRING, "alias list" },
};
/* Every option has an associated expert level, than can be used to
hide advanced and expert options from beginners. If you add to
this list, don't forget to update GC_LEVEL below. YOU MUST NOT
CHANGE THE NUMBERS OF THE EXISTING ENTRIES, AS THEY ARE PART OF THE
EXTERNAL INTERFACE. */
typedef enum
{
/* The basic options should always be displayed. */
GC_LEVEL_BASIC,
/* The advanced options may be hidden from beginners. */
GC_LEVEL_ADVANCED,
/* The expert options should only be displayed to experts. */
GC_LEVEL_EXPERT,
/* The invisible options should normally never be displayed. */
GC_LEVEL_INVISIBLE,
/* The internal options are never exported, they mark options that
are recorded for internal use only. */
GC_LEVEL_INTERNAL,
/* ADD NEW ENTRIES HERE. */
/* The number of the above entries. */
GC_LEVEL_NR
} gc_expert_level_t;
/* A description for each expert level. */
static const struct
{
const char *name;
} gc_level[] =
{
{ "basic" },
{ "advanced" },
{ "expert" },
{ "invisible" },
{ "internal" }
};
/* Option flags. The flags which are used by the components are defined
by gc-opt-flags.h, included above.
YOU MUST NOT CHANGE THE NUMBERS OF THE EXISTING FLAGS, AS THEY ARE
PART OF THE EXTERNAL INTERFACE. */
/* Some entries in the emitted option list are not options, but mark
the beginning of a new group of options. These entries have the
GROUP flag set. Note that this is internally also known as a
header line. */
#define GC_OPT_FLAG_GROUP (1UL << 0)
/* The ARG_OPT flag for an option indicates that the argument is
optional. This is never set for GC_ARG_TYPE_NONE options. */
#define GC_OPT_FLAG_ARG_OPT (1UL << 1)
/* The LIST flag for an option indicates that the option can occur
several times. A comma separated list of arguments is used as the
argument value. */
#define GC_OPT_FLAG_LIST (1UL << 2)
/* The RUNTIME flag for an option indicates that the option can be
changed at runtime. */
#define GC_OPT_FLAG_RUNTIME (1UL << 3)
/* A human-readable description for each flag. */
static const struct
{
const char *name;
} gc_flag[] =
{
{ "group" },
{ "optional arg" },
{ "list" },
{ "runtime" },
{ "default" },
{ "default desc" },
{ "no arg desc" },
{ "no change" }
};
/* Each option we want to support in gpgconf has the needed
* information in a static list per componenet. This struct describes
* the info for a single option. */
struct known_option_s
{
/* If this is NULL, then this is a terminator in an array of unknown
* length. Otherwise it is the name of the option described by this
* entry. The name must not contain a colon. */
const char *name;
/* The option flags. */
unsigned long flags;
/* The expert level. */
gc_expert_level_t level;
/* The complex type of the option argument; the default of 0 is used
* for a standard type as returned by --dump-option-table. */
gc_arg_type_t arg_type;
};
typedef struct known_option_s known_option_t;
/* The known options of the GC_COMPONENT_GPG_AGENT component. */
static known_option_t known_options_gpg_agent[] =
{
{ "verbose", GC_OPT_FLAG_LIST|GC_OPT_FLAG_RUNTIME, GC_LEVEL_BASIC },
{ "quiet", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME, GC_LEVEL_BASIC },
{ "disable-scdaemon", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
GC_LEVEL_ADVANCED },
{ "enable-ssh-support", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC },
{ "ssh-fingerprint-digest", GC_OPT_FLAG_RUNTIME, GC_LEVEL_EXPERT },
{ "enable-putty-support", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC },
{ "enable-extended-key-format", GC_OPT_FLAG_RUNTIME, GC_LEVEL_INVISIBLE },
{ "debug-level", GC_OPT_FLAG_ARG_OPT|GC_OPT_FLAG_RUNTIME, GC_LEVEL_ADVANCED},
{ "log-file", GC_OPT_FLAG_RUNTIME, GC_LEVEL_ADVANCED,
/**/ GC_ARG_TYPE_FILENAME },
{ "faked-system-time", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE },
{ "default-cache-ttl", GC_OPT_FLAG_RUNTIME, GC_LEVEL_BASIC },
{ "default-cache-ttl-ssh", GC_OPT_FLAG_RUNTIME, GC_LEVEL_ADVANCED },
{ "max-cache-ttl", GC_OPT_FLAG_RUNTIME, GC_LEVEL_EXPERT },
{ "max-cache-ttl-ssh", GC_OPT_FLAG_RUNTIME, GC_LEVEL_EXPERT },
{ "ignore-cache-for-signing", GC_OPT_FLAG_RUNTIME, GC_LEVEL_BASIC },
{ "allow-emacs-pinentry", GC_OPT_FLAG_RUNTIME, GC_LEVEL_ADVANCED },
{ "grab", GC_OPT_FLAG_RUNTIME, GC_LEVEL_EXPERT },
{ "no-allow-external-cache", GC_OPT_FLAG_RUNTIME, GC_LEVEL_BASIC },
{ "no-allow-mark-trusted", GC_OPT_FLAG_RUNTIME, GC_LEVEL_ADVANCED },
{ "no-allow-loopback-pinentry", GC_OPT_FLAG_RUNTIME, GC_LEVEL_EXPERT },
{ "enforce-passphrase-constraints", GC_OPT_FLAG_RUNTIME, GC_LEVEL_EXPERT },
{ "min-passphrase-len", GC_OPT_FLAG_RUNTIME, GC_LEVEL_ADVANCED },
{ "min-passphrase-nonalpha", GC_OPT_FLAG_RUNTIME, GC_LEVEL_EXPERT },
{ "check-passphrase-pattern", GC_OPT_FLAG_RUNTIME, GC_LEVEL_EXPERT,
/**/ GC_ARG_TYPE_FILENAME },
{ "check-sym-passphrase-pattern", GC_OPT_FLAG_RUNTIME, GC_LEVEL_EXPERT,
/**/ GC_ARG_TYPE_FILENAME },
{ "max-passphrase-days", GC_OPT_FLAG_RUNTIME, GC_LEVEL_EXPERT },
{ "enable-passphrase-history", GC_OPT_FLAG_RUNTIME, GC_LEVEL_EXPERT },
{ "pinentry-timeout", GC_OPT_FLAG_RUNTIME, GC_LEVEL_ADVANCED },
{ NULL }
};
/* The known options of the GC_COMPONENT_SCDAEMON component. */
static known_option_t known_options_scdaemon[] =
{
{ "verbose", GC_OPT_FLAG_LIST|GC_OPT_FLAG_RUNTIME, GC_LEVEL_BASIC },
{ "quiet", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC },
{ "no-greeting", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE },
{ "reader-port", GC_OPT_FLAG_RUNTIME, GC_LEVEL_BASIC },
{ "ctapi-driver", GC_OPT_FLAG_RUNTIME, GC_LEVEL_ADVANCED },
{ "pcsc-driver", GC_OPT_FLAG_RUNTIME, GC_LEVEL_ADVANCED },
{ "disable-ccid", GC_OPT_FLAG_RUNTIME, GC_LEVEL_EXPERT },
{ "disable-pinpad", GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME, GC_LEVEL_BASIC },
{ "enable-pinpad-varlen", GC_OPT_FLAG_RUNTIME, GC_LEVEL_BASIC },
{ "card-timeout", GC_OPT_FLAG_RUNTIME, GC_LEVEL_BASIC },
{ "application-priority", GC_OPT_FLAG_RUNTIME, GC_LEVEL_ADVANCED },
{ "debug-level", GC_OPT_FLAG_ARG_OPT|GC_OPT_FLAG_RUNTIME, GC_LEVEL_ADVANCED},
{ "log-file", GC_OPT_FLAG_RUNTIME, GC_LEVEL_ADVANCED,
GC_ARG_TYPE_FILENAME },
{ "deny-admin", GC_OPT_FLAG_RUNTIME, GC_LEVEL_BASIC },
{ NULL }
};
/* The known options of the GC_COMPONENT_GPG component. */
static known_option_t known_options_gpg[] =
{
{ "verbose", GC_OPT_FLAG_LIST, GC_LEVEL_BASIC },
{ "quiet", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC },
{ "no-greeting", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE },
{ "default-key", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC },
{ "encrypt-to", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC },
{ "group", GC_OPT_FLAG_LIST, GC_LEVEL_ADVANCED,
GC_ARG_TYPE_ALIAS_LIST},
{ "compliance", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT },
{ "default-new-key-algo", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE },
{ "trust-model", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE },
{ "debug-level", GC_OPT_FLAG_ARG_OPT, GC_LEVEL_ADVANCED },
{ "log-file", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
GC_ARG_TYPE_FILENAME },
{ "keyserver", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE },
{ "auto-key-locate", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED },
{ "auto-key-retrieve", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT },
{ "no-auto-key-retrieve", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE },
{ "disable-dirmngr", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT },
{ "max-cert-depth", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE },
{ "completes-needed", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE },
{ "marginals-needed", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE },
/* The next is a pseudo option which we read via --gpgconf-list.
* The meta information is taken from the table below. */
{ "default_pubkey_algo", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE },
{ NULL }
};
static const char *known_pseudo_options_gpg[] =
{/* v-- ARGPARSE_TYPE_STRING */
"default_pubkey_algo:0:2:@:",
NULL
};
/* The known options of the GC_COMPONENT_GPGSM component. */
static known_option_t known_options_gpgsm[] =
{
{ "verbose", GC_OPT_FLAG_LIST, GC_LEVEL_BASIC },
{ "quiet", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC },
{ "no-greeting", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE },
{ "default-key", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC },
{ "encrypt-to", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC },
{ "disable-dirmngr", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT },
{ "p12-charset", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED },
- { "keyserver", GC_OPT_FLAG_LIST, GC_LEVEL_BASIC,
+ { "keyserver", GC_OPT_FLAG_LIST, GC_LEVEL_INVISIBLE,
GC_ARG_TYPE_LDAP_SERVER },
{ "compliance", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT },
{ "debug-level", GC_OPT_FLAG_ARG_OPT, GC_LEVEL_ADVANCED },
{ "log-file", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
GC_ARG_TYPE_FILENAME },
{ "faked-system-time", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE },
{ "disable-crl-checks", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC },
{ "enable-crl-checks", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE },
{ "enable-ocsp", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED },
{ "include-certs", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT },
{ "disable-policy-checks", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED },
{ "auto-issuer-key-retrieve", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC },
{ "cipher-algo", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED },
{ "disable-trusted-cert-crl-check", GC_OPT_FLAG_NONE, GC_LEVEL_EXPERT },
/* Pseudo option follows. See also table below. */
{ "default_pubkey_algo", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE },
{ NULL }
};
static const char *known_pseudo_options_gpgsm[] =
{/* v-- ARGPARSE_TYPE_STRING */
"default_pubkey_algo:0:2:@:",
NULL
};
/* The known options of the GC_COMPONENT_DIRMNGR component. */
static known_option_t known_options_dirmngr[] =
{
{ "verbose", GC_OPT_FLAG_LIST, GC_LEVEL_BASIC },
{ "quiet", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC },
{ "no-greeting", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE },
{ "resolver-timeout", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE },
{ "nameserver", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE },
{ "debug-level", GC_OPT_FLAG_ARG_OPT, GC_LEVEL_ADVANCED },
{ "log-file", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED,
GC_ARG_TYPE_FILENAME },
{ "faked-system-time", GC_OPT_FLAG_NONE, GC_LEVEL_INVISIBLE },
{ "batch", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC },
{ "force", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC },
{ "use-tor", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC },
{ "keyserver", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC },
+ { "ldapserver", GC_OPT_FLAG_LIST, GC_LEVEL_BASIC,
+ GC_ARG_TYPE_LDAP_SERVER },
{ "disable-http", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED },
{ "ignore-http-dp", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED },
{ "http-proxy", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED },
{ "honor-http-proxy", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED },
{ "disable-ldap", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED },
{ "ignore-ldap-dp", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED },
{ "ldap-proxy", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC },
{ "only-ldap-proxy", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED },
{ "add-servers", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED },
{ "ldaptimeout", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC },
{ "max-replies", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC },
{ "allow-ocsp", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC },
{ "ocsp-responder", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED },
{ "ocsp-signer", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED },
{ "allow-version-check", GC_OPT_FLAG_NONE, GC_LEVEL_BASIC },
{ "ignore-ocsp-service-url", GC_OPT_FLAG_NONE, GC_LEVEL_ADVANCED },
{ NULL }
};
/* The known options of the GC_COMPONENT_PINENTRY component. */
static known_option_t known_options_pinentry[] =
{
{ NULL }
};
/* Our main option info object. We copy all required information from the
* gpgrt_opt_t items but convert the flags value to bit flags. */
struct gc_option_s
{
const char *name; /* The same as gpgrt_opt_t.long_opt. */
const char *desc; /* The same as gpgrt_opt_t.description. */
unsigned int is_header:1; /* This is a header item. */
unsigned int is_list:1; /* This is a list style option. */
unsigned int opt_arg:1; /* The option's argument is optional. */
unsigned int runtime:1; /* The option is runtime changeable. */
unsigned int gpgconf_list:1; /* Has been announced in gpgconf-list. */
unsigned int has_default:1; /* The option has a default value. */
unsigned int def_in_desc:1; /* The default is in the descrition. */
unsigned int no_arg_desc:1; /* The argument has a default ???. */
unsigned int no_change:1; /* User shall not change the option. */
unsigned int attr_ignore:1; /* The ARGPARSE_ATTR_IGNORE. */
unsigned int attr_force:1; /* The ARGPARSE_ATTR_FORCE. */
/* The expert level - copied from known_options. */
gc_expert_level_t level;
/* The complex type - copied from known_options. */
gc_arg_type_t arg_type;
/* The default value for this option. This is NULL if the option is
not present in the component, the empty string if no default is
available, and otherwise a quoted string. This is currently
malloced.*/
char *default_value;
/* The current value of this option. */
char *value;
/* The new flags for this option. The only defined flag is actually
GC_OPT_FLAG_DEFAULT, and it means that the option should be
deleted. In this case, NEW_VALUE is NULL. */
unsigned long new_flags;
/* The new value of this option. */
char *new_value;
};
typedef struct gc_option_s gc_option_t;
/* The information associated with each component. */
static struct
{
/* The name of the component. Some components don't have an
* associated program, but are implemented directly by GPGConf. In
* this case, PROGRAM is NULL. */
char *program;
/* The displayed name of this component. Must not contain a colon
* (':') character. */
const char *name;
/* The gettext domain for the description DESC. If this is NULL,
then the description is not translated. */
const char *desc_domain;
/* The description of this component. */
const char *desc;
/* The module name (GNUPG_MODULE_NAME_foo) as defined by
* ../common/util.h. This value is used to get the actual installed
* path of the program. 0 is used if no program for the component
* is available. */
char module_name;
/* The name for the configuration filename of this component. */
const char *option_config_filename;
/* The static table of known options for this component. */
known_option_t *known_options;
/* The static table of known pseudo options for this component or NULL. */
const char **known_pseudo_options;
/* The runtime change callback. If KILLFLAG is true the component
is killed and not just reloaded. */
void (*runtime_change) (int killflag);
/* The table of known options as read from the component including
* header lines and such. This is suitable to be passed to
* gpgrt_argparser. Will be filled in by
* retrieve_options_from_program. */
gnupg_opt_t *opt_table;
/* The full table including data from OPT_TABLE. The end of the
* table is marked by NULL entry for NAME. Will be filled in by
* retrieve_options_from_program. */
gc_option_t *options;
} gc_component[GC_COMPONENT_NR] =
{
{ NULL }, /* DUMMY for GC_COMPONENT_ANY */
{ GPG_NAME, GPG_DISP_NAME, "gnupg", N_("OpenPGP"),
GNUPG_MODULE_NAME_GPG, GPG_NAME ".conf",
known_options_gpg, known_pseudo_options_gpg },
{ GPGSM_NAME, GPGSM_DISP_NAME, "gnupg", N_("S/MIME"),
GNUPG_MODULE_NAME_GPGSM, GPGSM_NAME ".conf",
known_options_gpgsm, known_pseudo_options_gpgsm },
{ GPG_AGENT_NAME, GPG_AGENT_DISP_NAME, "gnupg", N_("Private Keys"),
GNUPG_MODULE_NAME_AGENT, GPG_AGENT_NAME ".conf",
known_options_gpg_agent, NULL, gpg_agent_runtime_change },
{ SCDAEMON_NAME, SCDAEMON_DISP_NAME, "gnupg", N_("Smartcards"),
GNUPG_MODULE_NAME_SCDAEMON, SCDAEMON_NAME ".conf",
known_options_scdaemon, NULL, scdaemon_runtime_change},
{ DIRMNGR_NAME, DIRMNGR_DISP_NAME, "gnupg", N_("Network"),
GNUPG_MODULE_NAME_DIRMNGR, DIRMNGR_NAME ".conf",
known_options_dirmngr, NULL, dirmngr_runtime_change },
{ "pinentry", "Pinentry", "gnupg", N_("Passphrase Entry"),
GNUPG_MODULE_NAME_PINENTRY, NULL,
known_options_pinentry }
};
/* Structure used to collect error output of the component programs. */
struct error_line_s;
typedef struct error_line_s *error_line_t;
struct error_line_s
{
error_line_t next; /* Link to next item. */
const char *fname; /* Name of the config file (points into BUFFER). */
unsigned int lineno; /* Line number of the config file. */
const char *errtext; /* Text of the error message (points into BUFFER). */
char buffer[1]; /* Helper buffer. */
};
/* Initialization and finalization. */
static void
gc_option_free (gc_option_t *o)
{
if (o == NULL || o->name == NULL)
return;
xfree (o->value);
gc_option_free (o + 1);
}
static void
gc_components_free (void)
{
int i;
for (i = 0; i < DIM (gc_component); i++)
gc_option_free (gc_component[i].options);
}
void
gc_components_init (void)
{
atexit (gc_components_free);
}
/* Engine specific support. */
static void
gpg_agent_runtime_change (int killflag)
{
gpg_error_t err = 0;
const char *pgmname;
const char *argv[5];
pid_t pid = (pid_t)(-1);
int i = 0;
pgmname = gnupg_module_name (GNUPG_MODULE_NAME_CONNECT_AGENT);
if (!gnupg_default_homedir_p ())
{
argv[i++] = "--homedir";
argv[i++] = gnupg_homedir ();
}
argv[i++] = "--no-autostart";
argv[i++] = killflag? "KILLAGENT" : "RELOADAGENT";
argv[i++] = NULL;
if (!err)
err = gnupg_spawn_process_fd (pgmname, argv, -1, -1, -1, &pid);
if (!err)
err = gnupg_wait_process (pgmname, pid, 1, NULL);
if (err)
gc_error (0, 0, "error running '%s %s': %s",
pgmname, argv[1], gpg_strerror (err));
gnupg_release_process (pid);
}
static void
scdaemon_runtime_change (int killflag)
{
gpg_error_t err = 0;
const char *pgmname;
const char *argv[9];
pid_t pid = (pid_t)(-1);
int i = 0;
(void)killflag; /* For scdaemon kill and reload are synonyms. */
/* We use "GETINFO app_running" to see whether the agent is already
running and kill it only in this case. This avoids an explicit
starting of the agent in case it is not yet running. There is
obviously a race condition but that should not harm too much. */
pgmname = gnupg_module_name (GNUPG_MODULE_NAME_CONNECT_AGENT);
if (!gnupg_default_homedir_p ())
{
argv[i++] = "--homedir";
argv[i++] = gnupg_homedir ();
}
argv[i++] = "-s";
argv[i++] = "--no-autostart";
argv[i++] = "GETINFO scd_running";
argv[i++] = "/if ${! $?}";
argv[i++] = "scd killscd";
argv[i++] = "/end";
argv[i++] = NULL;
if (!err)
err = gnupg_spawn_process_fd (pgmname, argv, -1, -1, -1, &pid);
if (!err)
err = gnupg_wait_process (pgmname, pid, 1, NULL);
if (err)
gc_error (0, 0, "error running '%s %s': %s",
pgmname, argv[4], gpg_strerror (err));
gnupg_release_process (pid);
}
static void
dirmngr_runtime_change (int killflag)
{
gpg_error_t err = 0;
const char *pgmname;
const char *argv[6];
pid_t pid = (pid_t)(-1);
int i = 0;
int cmdidx;
pgmname = gnupg_module_name (GNUPG_MODULE_NAME_CONNECT_AGENT);
if (!gnupg_default_homedir_p ())
{
argv[i++] = "--homedir";
argv[i++] = gnupg_homedir ();
}
argv[i++] = "--no-autostart";
argv[i++] = "--dirmngr";
cmdidx = i;
argv[i++] = killflag? "KILLDIRMNGR" : "RELOADDIRMNGR";
argv[i] = NULL;
log_assert (i < DIM(argv));
if (!err)
err = gnupg_spawn_process_fd (pgmname, argv, -1, -1, -1, &pid);
if (!err)
err = gnupg_wait_process (pgmname, pid, 1, NULL);
if (err)
gc_error (0, 0, "error running '%s %s': %s",
pgmname, argv[cmdidx], gpg_strerror (err));
gnupg_release_process (pid);
}
/* Launch the gpg-agent or the dirmngr if not already running. */
gpg_error_t
gc_component_launch (int component)
{
gpg_error_t err;
const char *pgmname;
const char *argv[6];
int i;
pid_t pid;
if (component < 0)
{
err = gc_component_launch (GC_COMPONENT_GPG_AGENT);
if (!err)
err = gc_component_launch (GC_COMPONENT_DIRMNGR);
return err;
}
if (!(component == GC_COMPONENT_GPG_AGENT
|| component == GC_COMPONENT_DIRMNGR))
{
log_error ("%s\n", _("Component not suitable for launching"));
gpgconf_failure (0);
}
if (gc_component_check_options (component, NULL, NULL))
{
log_error (_("Configuration file of component %s is broken\n"),
gc_component[component].name);
if (!opt.quiet)
log_info (_("Note: Use the command \"%s%s\" to get details.\n"),
gc_component[component].name, " --gpgconf-test");
gpgconf_failure (0);
}
pgmname = gnupg_module_name (GNUPG_MODULE_NAME_CONNECT_AGENT);
i = 0;
if (!gnupg_default_homedir_p ())
{
argv[i++] = "--homedir";
argv[i++] = gnupg_homedir ();
}
if (component == GC_COMPONENT_DIRMNGR)
argv[i++] = "--dirmngr";
argv[i++] = "NOP";
argv[i] = NULL;
log_assert (i < DIM(argv));
err = gnupg_spawn_process_fd (pgmname, argv, -1, -1, -1, &pid);
if (!err)
err = gnupg_wait_process (pgmname, pid, 1, NULL);
if (err)
gc_error (0, 0, "error running '%s%s%s': %s",
pgmname,
component == GC_COMPONENT_DIRMNGR? " --dirmngr":"",
" NOP",
gpg_strerror (err));
gnupg_release_process (pid);
return err;
}
static void
do_runtime_change (int component, int killflag)
{
int runtime[GC_COMPONENT_NR] = { 0 };
if (component < 0)
{
for (component = 0; component < GC_COMPONENT_NR; component++)
runtime [component] = 1;
}
else
{
log_assert (component >= 0 && component < GC_COMPONENT_NR);
runtime [component] = 1;
}
/* Do the restart for the selected components. */
for (component = GC_COMPONENT_NR-1; component >= 0; component--)
{
if (runtime[component] && gc_component[component].runtime_change)
(*gc_component[component].runtime_change) (killflag);
}
}
/* Unconditionally restart COMPONENT. */
void
gc_component_kill (int component)
{
do_runtime_change (component, 1);
}
/* Unconditionally reload COMPONENT or all components if COMPONENT is -1. */
void
gc_component_reload (int component)
{
do_runtime_change (component, 0);
}
/* More or less Robust version of dgettext. It has the side effect of
switching the codeset to utf-8 because this is what we want to
output. In theory it is possible to keep the original code set and
switch back for regular disgnostic output (redefine "_(" for that)
but given the natur of this tool, being something invoked from
other pograms, it does not make much sense. */
static const char *
my_dgettext (const char *domain, const char *msgid)
{
if (!msgid || !*msgid)
return msgid; /* Shortcut form "" which has the PO files meta data. */
#ifdef USE_SIMPLE_GETTEXT
if (domain)
{
static int switched_codeset;
char *text;
if (!switched_codeset)
{
switched_codeset = 1;
gettext_use_utf8 (1);
}
if (!strcmp (domain, "gnupg"))
domain = PACKAGE_GT;
/* FIXME: we have no dgettext, thus we can't switch. */
text = (char*)gettext (msgid);
return text ? text : msgid;
}
else
return msgid;
#elif defined(ENABLE_NLS)
if (domain)
{
static int switched_codeset;
char *text;
if (!switched_codeset)
{
switched_codeset = 1;
bind_textdomain_codeset (PACKAGE_GT, "utf-8");
bindtextdomain (DIRMNGR_NAME, gnupg_localedir ());
bind_textdomain_codeset (DIRMNGR_NAME, "utf-8");
}
/* Note: This is a hack to actually use the gnupg2 domain as
long we are in a transition phase where gnupg 1.x and 1.9 may
coexist. */
if (!strcmp (domain, "gnupg"))
domain = PACKAGE_GT;
text = dgettext (domain, msgid);
return text ? text : msgid;
}
else
return msgid;
#else
(void)domain;
return msgid;
#endif
}
/* Percent-Escape special characters. The string is valid until the
next invocation of the function. */
char *
gc_percent_escape (const char *src)
{
static char *esc_str;
static int esc_str_len;
int new_len = 3 * strlen (src) + 1;
char *dst;
if (esc_str_len < new_len)
{
char *new_esc_str = realloc (esc_str, new_len);
if (!new_esc_str)
gc_error (1, errno, "can not escape string");
esc_str = new_esc_str;
esc_str_len = new_len;
}
dst = esc_str;
while (*src)
{
if (*src == '%')
{
*(dst++) = '%';
*(dst++) = '2';
*(dst++) = '5';
}
else if (*src == ':')
{
/* The colon is used as field separator. */
*(dst++) = '%';
*(dst++) = '3';
*(dst++) = 'a';
}
else if (*src == ',')
{
/* The comma is used as list separator. */
*(dst++) = '%';
*(dst++) = '2';
*(dst++) = 'c';
}
else if (*src == '\n')
{
/* The newline is problematic in a line-based format. */
*(dst++) = '%';
*(dst++) = '0';
*(dst++) = 'a';
}
else
*(dst++) = *(src);
src++;
}
*dst = '\0';
return esc_str;
}
/* Percent-Deescape special characters. The string is valid until the
next invocation of the function. */
static char *
percent_deescape (const char *src)
{
static char *str;
static int str_len;
int new_len = 3 * strlen (src) + 1;
char *dst;
if (str_len < new_len)
{
char *new_str = realloc (str, new_len);
if (!new_str)
gc_error (1, errno, "can not deescape string");
str = new_str;
str_len = new_len;
}
dst = str;
while (*src)
{
if (*src == '%')
{
int val = hextobyte (src + 1);
if (val < 0)
gc_error (1, 0, "malformed end of string %s", src);
*(dst++) = (char) val;
src += 3;
}
else
*(dst++) = *(src++);
}
*dst = '\0';
return str;
}
/* List all components that are available. */
void
gc_component_list_components (estream_t out)
{
gc_component_id_t component;
const char *desc;
const char *pgmname;
for (component = 0; component < GC_COMPONENT_NR; component++)
{
if (!gc_component[component].program)
continue;
if (gc_component[component].module_name)
pgmname = gnupg_module_name (gc_component[component].module_name);
else
pgmname = "";
desc = gc_component[component].desc;
desc = my_dgettext (gc_component[component].desc_domain, desc);
es_fprintf (out, "%s:%s:",
gc_component[component].program, gc_percent_escape (desc));
es_fprintf (out, "%s\n", gc_percent_escape (pgmname));
}
}
static int
all_digits_p (const char *p, size_t len)
{
if (!len)
return 0; /* No. */
for (; len; len--, p++)
if (!isascii (*p) || !isdigit (*p))
return 0; /* No. */
return 1; /* Yes. */
}
/* Collect all error lines from stream FP. Only lines prefixed with
TAG are considered. Returns a list of error line items (which may
be empty). There is no error return. */
static error_line_t
collect_error_output (estream_t fp, const char *tag)
{
char buffer[1024];
char *p, *p2, *p3;
int c, cont_line;
unsigned int pos;
error_line_t eitem, errlines, *errlines_tail;
size_t taglen = strlen (tag);
errlines = NULL;
errlines_tail = &errlines;
pos = 0;
cont_line = 0;
while ((c=es_getc (fp)) != EOF)
{
buffer[pos++] = c;
if (pos >= sizeof buffer - 5 || c == '\n')
{
buffer[pos - (c == '\n')] = 0;
if (cont_line)
; /*Ignore continuations of previous line. */
else if (!strncmp (buffer, tag, taglen) && buffer[taglen] == ':')
{
/* "gpgsm: foo:4: bla" */
/* Yep, we are interested in this line. */
p = buffer + taglen + 1;
while (*p == ' ' || *p == '\t')
p++;
trim_trailing_spaces (p); /* Get rid of extra CRs. */
if (!*p)
; /* Empty lines are ignored. */
else if ( (p2 = strchr (p, ':')) && (p3 = strchr (p2+1, ':'))
&& all_digits_p (p2+1, p3 - (p2+1)))
{
/* Line in standard compiler format. */
p3++;
while (*p3 == ' ' || *p3 == '\t')
p3++;
eitem = xmalloc (sizeof *eitem + strlen (p));
eitem->next = NULL;
strcpy (eitem->buffer, p);
eitem->fname = eitem->buffer;
eitem->buffer[p2-p] = 0;
eitem->errtext = eitem->buffer + (p3 - p);
/* (we already checked that there are only ascii
digits followed by a colon) */
eitem->lineno = 0;
for (p2++; isdigit (*p2); p2++)
eitem->lineno = eitem->lineno*10 + (*p2 - '0');
*errlines_tail = eitem;
errlines_tail = &eitem->next;
}
else
{
/* Other error output. */
eitem = xmalloc (sizeof *eitem + strlen (p));
eitem->next = NULL;
strcpy (eitem->buffer, p);
eitem->fname = NULL;
eitem->errtext = eitem->buffer;
eitem->lineno = 0;
*errlines_tail = eitem;
errlines_tail = &eitem->next;
}
}
pos = 0;
/* If this was not a complete line mark that we are in a
continuation. */
cont_line = (c != '\n');
}
}
/* We ignore error lines not terminated by a LF. */
return errlines;
}
/* Check the options of a single component. If CONF_FILE is NULL the
* standard config file is used. If OUT is not NULL the output is
* written to that stream. Returns 0 if everything is OK. */
int
gc_component_check_options (int component, estream_t out, const char *conf_file)
{
gpg_error_t err;
unsigned int result;
const char *pgmname;
const char *argv[6];
int i;
pid_t pid;
int exitcode;
estream_t errfp;
error_line_t errlines;
log_assert (component >= 0 && component < GC_COMPONENT_NR);
if (!gc_component[component].program)
return 0;
if (!gc_component[component].module_name)
return 0;
pgmname = gnupg_module_name (gc_component[component].module_name);
i = 0;
if (!gnupg_default_homedir_p ()
&& component != GC_COMPONENT_PINENTRY)
{
argv[i++] = "--homedir";
argv[i++] = gnupg_homedir ();
}
if (conf_file)
{
argv[i++] = "--options";
argv[i++] = conf_file;
}
if (component == GC_COMPONENT_PINENTRY)
argv[i++] = "--version";
else
argv[i++] = "--gpgconf-test";
argv[i++] = NULL;
result = 0;
errlines = NULL;
err = gnupg_spawn_process (pgmname, argv, NULL, NULL, 0,
NULL, NULL, &errfp, &pid);
if (err)
result |= 1; /* Program could not be run. */
else
{
errlines = collect_error_output (errfp,
gc_component[component].name);
if (gnupg_wait_process (pgmname, pid, 1, &exitcode))
{
if (exitcode == -1)
result |= 1; /* Program could not be run or it
terminated abnormally. */
result |= 2; /* Program returned an error. */
}
gnupg_release_process (pid);
es_fclose (errfp);
}
/* If the program could not be run, we can't tell whether
the config file is good. */
if (result & 1)
result |= 2;
if (out)
{
const char *desc;
error_line_t errptr;
desc = gc_component[component].desc;
desc = my_dgettext (gc_component[component].desc_domain, desc);
es_fprintf (out, "%s:%s:",
gc_component[component].program, gc_percent_escape (desc));
es_fputs (gc_percent_escape (pgmname), out);
es_fprintf (out, ":%d:%d:", !(result & 1), !(result & 2));
for (errptr = errlines; errptr; errptr = errptr->next)
{
if (errptr != errlines)
es_fputs ("\n:::::", out); /* Continuation line. */
if (errptr->fname)
es_fputs (gc_percent_escape (errptr->fname), out);
es_putc (':', out);
if (errptr->fname)
es_fprintf (out, "%u", errptr->lineno);
es_putc (':', out);
es_fputs (gc_percent_escape (errptr->errtext), out);
es_putc (':', out);
}
es_putc ('\n', out);
}
while (errlines)
{
error_line_t tmp = errlines->next;
xfree (errlines);
errlines = tmp;
}
return result;
}
/* Check all components that are available. */
void
gc_check_programs (estream_t out)
{
gc_component_id_t component;
for (component = 0; component < GC_COMPONENT_NR; component++)
gc_component_check_options (component, out, NULL);
}
/* Find the component with the name NAME. Returns -1 if not
found. */
int
gc_component_find (const char *name)
{
gc_component_id_t idx;
for (idx = 0; idx < GC_COMPONENT_NR; idx++)
{
if (gc_component[idx].program
&& !strcmp (name, gc_component[idx].program))
return idx;
}
return -1;
}
/* List the option OPTION. */
static void
list_one_option (gc_component_id_t component,
const gc_option_t *option, estream_t out)
{
const char *desc = NULL;
char *arg_name = NULL;
unsigned long flags;
const char *desc_domain = gc_component[component].desc_domain;
/* Don't show options with the ignore attribute. */
if (option->attr_ignore && !option->attr_force)
return;
if (option->desc)
{
desc = my_dgettext (desc_domain, option->desc);
if (*desc == '|')
{
const char *arg_tail = strchr (&desc[1], '|');
if (arg_tail)
{
int arg_len = arg_tail - &desc[1];
arg_name = xmalloc (arg_len + 1);
memcpy (arg_name, &desc[1], arg_len);
arg_name[arg_len] = '\0';
desc = arg_tail + 1;
}
}
}
/* YOU MUST NOT REORDER THE FIELDS IN THIS OUTPUT, AS THEIR ORDER IS
PART OF THE EXTERNAL INTERFACE. YOU MUST NOT REMOVE ANY
FIELDS. */
/* The name field. */
es_fprintf (out, "%s", option->name);
/* The flags field. */
flags = 0;
if (option->is_header) flags |= GC_OPT_FLAG_GROUP;
if (option->is_list) flags |= GC_OPT_FLAG_LIST;
if (option->runtime) flags |= GC_OPT_FLAG_RUNTIME;
if (option->has_default) flags |= GC_OPT_FLAG_DEFAULT;
if (option->def_in_desc) flags |= GC_OPT_FLAG_DEF_DESC;
if (option->no_arg_desc) flags |= GC_OPT_FLAG_NO_ARG_DESC;
if (option->no_change) flags |= GC_OPT_FLAG_NO_CHANGE;
if (option->attr_force) flags |= GC_OPT_FLAG_NO_CHANGE;
es_fprintf (out, ":%lu", flags);
if (opt.verbose)
{
es_putc (' ', out);
if (!flags)
es_fprintf (out, "none");
else
{
unsigned long flag = 0;
unsigned long first = 1;
while (flags)
{
if (flags & 1)
{
if (first)
first = 0;
else
es_putc (',', out);
es_fprintf (out, "%s", gc_flag[flag].name);
}
flags >>= 1;
flag++;
}
}
}
/* The level field. */
es_fprintf (out, ":%u", option->level);
if (opt.verbose)
es_fprintf (out, " %s", gc_level[option->level].name);
/* The description field. */
es_fprintf (out, ":%s", desc ? gc_percent_escape (desc) : "");
/* The type field. */
es_fprintf (out, ":%u", option->arg_type);
if (opt.verbose)
es_fprintf (out, " %s", gc_arg_type[option->arg_type].name);
/* The alternate type field. */
es_fprintf (out, ":%u", gc_arg_type[option->arg_type].fallback);
if (opt.verbose)
es_fprintf (out, " %s",
gc_arg_type[gc_arg_type[option->arg_type].fallback].name);
/* The argument name field. */
es_fprintf (out, ":%s", arg_name ? gc_percent_escape (arg_name) : "");
xfree (arg_name);
/* The default value field. */
es_fprintf (out, ":%s", option->default_value ? option->default_value : "");
/* The default argument field. This was never used and is thus empty. */
es_fprintf (out, ":");
/* The value field. */
if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_NONE
&& option->is_list && option->value)
{
/* The special format "1,1,1,1,...,1" is converted to a number
here. */
es_fprintf (out, ":%u", (unsigned int)((strlen (option->value) + 1) / 2));
}
else
es_fprintf (out, ":%s", option->value ? option->value : "");
/* ADD NEW FIELDS HERE. */
es_putc ('\n', out);
}
/* List all options of the component COMPONENT. */
void
gc_component_list_options (int component, estream_t out)
{
const gc_option_t *option = gc_component[component].options;
for ( ; option && option->name; option++)
{
/* Do not output unknown or internal options. */
if (!option->is_header
&& option->level == GC_LEVEL_INTERNAL)
continue;
if (option->is_header)
{
const gc_option_t *group_option = option + 1;
gc_expert_level_t level = GC_LEVEL_NR;
/* The manual states that the group level is always the
minimum of the levels of all contained options. Due to
different active options, and because it is hard to
maintain manually, we calculate it here. The value in
the global static table is ignored. */
for ( ; group_option->name; group_option++)
{
if (group_option->is_header)
break;
if (group_option->level < level)
level = group_option->level;
}
/* Check if group is empty. */
if (level != GC_LEVEL_NR)
{
gc_option_t opt_copy;
/* Fix up the group level. */
opt_copy = *option;
opt_copy.level = level;
list_one_option (component, &opt_copy, out);
}
}
else
list_one_option (component, option, out);
}
}
/* Return true if the option NAME is known and that we want it as
* gpgconf managed option. */
static known_option_t *
is_known_option (gc_component_id_t component, const char *name)
{
known_option_t *option = gc_component[component].known_options;
if (option)
{
for (; option->name; option++)
if (!strcmp (option->name, name))
break;
}
return (option && option->name)? option : NULL;
}
/* Find the option NAME in component COMPONENT. Returns pointer to
* the option descriptor or NULL if not found. */
static gc_option_t *
find_option (gc_component_id_t component, const char *name)
{
gc_option_t *option = gc_component[component].options;
if (option)
{
for (; option->name; option++)
{
if (!option->is_header
&& !strcmp (option->name, name))
return option;
}
}
return NULL;
}
struct read_line_wrapper_parm_s
{
const char *pgmname;
estream_t fp;
char *line;
size_t line_len;
const char **extra_lines;
int extra_lines_idx;
char *extra_line_buffer;
};
/* Helper for retrieve_options_from_program. */
static ssize_t
read_line_wrapper (struct read_line_wrapper_parm_s *parm)
{
ssize_t length;
const char *extra_line;
if (parm->fp)
{
length = es_read_line (parm->fp, &parm->line, &parm->line_len, NULL);
if (length > 0)
return length;
if (length < 0 || es_ferror (parm->fp))
gc_error (1, errno, "error reading from %s", parm->pgmname);
if (es_fclose (parm->fp))
gc_error (1, errno, "error closing %s", parm->pgmname);
/* EOF seen. */
parm->fp = NULL;
}
/* Return the made up lines. */
if (!parm->extra_lines
|| !(extra_line = parm->extra_lines[parm->extra_lines_idx]))
return -1; /* This is really the EOF. */
parm->extra_lines_idx++;
xfree (parm->extra_line_buffer);
parm->extra_line_buffer = xstrdup (extra_line);
return strlen (parm->extra_line_buffer);
}
/* Retrieve the options for the component COMPONENT. With
* ONLY_INSTALLED set components which are not installed are silently
* ignored. */
static void
retrieve_options_from_program (gc_component_id_t component, int only_installed)
{
gpg_error_t err;
const char *pgmname;
const char *argv[4];
estream_t outfp;
int exitcode;
pid_t pid;
known_option_t *known_option;
gc_option_t *option;
char *line = NULL;
size_t line_len;
ssize_t length;
const char *config_name;
gnupg_argparse_t pargs;
int dummy_argc;
char *twopartconfig_name = NULL;
gnupg_opt_t *opt_table = NULL; /* A malloced option table. */
size_t opt_table_used = 0; /* Its current length. */
size_t opt_table_size = 0; /* Its allocated length. */
gc_option_t *opt_info = NULL; /* A malloced options table. */
size_t opt_info_used = 0; /* Its current length. */
size_t opt_info_size = 0; /* Its allocated length. */
int i;
struct read_line_wrapper_parm_s read_line_parm;
int pseudo_count;
pgmname = (gc_component[component].module_name
? gnupg_module_name (gc_component[component].module_name)
: gc_component[component].program );
if (only_installed && gnupg_access (pgmname, X_OK))
{
return; /* The component is not installed. */
}
/* First we need to read the option table from the program. */
argv[0] = "--dump-option-table";
argv[1] = NULL;
err = gnupg_spawn_process (pgmname, argv, NULL, NULL, 0,
NULL, &outfp, NULL, &pid);
if (err)
{
gc_error (1, 0, "could not gather option table from '%s': %s",
pgmname, gpg_strerror (err));
}
read_line_parm.pgmname = pgmname;
read_line_parm.fp = outfp;
read_line_parm.line = line;
read_line_parm.line_len = line_len = 0;
read_line_parm.extra_line_buffer = NULL;
read_line_parm.extra_lines = gc_component[component].known_pseudo_options;
read_line_parm.extra_lines_idx = 0;
pseudo_count = 0;
while ((length = read_line_wrapper (&read_line_parm)) > 0)
{
char *fields[4];
char *optname, *optdesc;
unsigned int optflags;
int short_opt;
gc_arg_type_t arg_type;
int pseudo = 0;
if (read_line_parm.extra_line_buffer)
{
line = read_line_parm.extra_line_buffer;
pseudo = 1;
pseudo_count++;
}
else
line = read_line_parm.line;
/* Strip newline and carriage return, if present. */
while (length > 0
&& (line[length - 1] == '\n' || line[length - 1] == '\r'))
line[--length] = '\0';
if (split_fields_colon (line, fields, DIM (fields)) < 4)
{
gc_error (0,0, "WARNING: invalid line in option table of '%s'\n",
pgmname);
continue;
}
optname = fields[0];
short_opt = atoi (fields[1]);
if (short_opt < 1 && !pseudo)
{
gc_error (0,0, "WARNING: bad short option in option table of '%s'\n",
pgmname);
continue;
}
optflags = strtoul (fields[2], NULL, 10);
if ((optflags & ARGPARSE_OPT_HEADER))
known_option = NULL; /* We want all header-only options. */
else if ((known_option = is_known_option (component, optname)))
; /* Yes we want this one. */
else
continue; /* No need to store this option description. */
/* The +1 here is to make sure that we will have a zero item at
* the end of the table. */
if (opt_table_used + 1 >= opt_table_size)
{
/* Note that this also does the initial allocation. */
opt_table_size += 128;
opt_table = xreallocarray (opt_table,
opt_table_used,
opt_table_size,
sizeof *opt_table);
}
/* The +1 here is to make sure that we will have a zero item at
* the end of the table. */
if (opt_info_used + 1 >= opt_info_size)
{
/* Note that this also does the initial allocation. */
opt_info_size += 128;
opt_info = xreallocarray (opt_info,
opt_info_used,
opt_info_size,
sizeof *opt_info);
}
/* The +1 here accounts for the two items we are going to add to
* the global string table. */
if (string_array_used + 1 >= string_array_size)
{
string_array_size += 256;
string_array = xreallocarray (string_array,
string_array_used,
string_array_size,
sizeof *string_array);
}
string_array[string_array_used++] = optname = xstrdup (fields[0]);
string_array[string_array_used++] = optdesc = xstrdup (fields[3]);
/* Create an option table which can then be supplied to
* gpgrt_parser. Unfortunately there is no private pointer in
* the public option table struct so that we can't add extra
* data we need here. Thus we need to build up another table
* for such info and for ease of use we also copy the tehre the
* data from the option table. It is not possible to use the
* known_option_s for this because that one does not carry
* header lines and it might also be problematic to use such
* static tables for caching options and default values. */
if (!pseudo)
{
opt_table[opt_table_used].long_opt = optname;
opt_table[opt_table_used].short_opt = short_opt;
opt_table[opt_table_used].description = optdesc;
opt_table[opt_table_used].flags = optflags;
opt_table_used++;
}
/* Note that as per argparser specs the opt_table uses "@" to
* specifify an empty description. In the DESC script of
* options (opt_info_t) we want to have a real empty string. */
opt_info[opt_info_used].name = optname;
if (*optdesc == '@' && !optdesc[1])
opt_info[opt_info_used].desc = optdesc+1;
else
opt_info[opt_info_used].desc = optdesc;
/* Unfortunately we need to remap the types. */
switch ((optflags & ARGPARSE_TYPE_MASK))
{
case ARGPARSE_TYPE_INT: arg_type = GC_ARG_TYPE_INT32; break;
case ARGPARSE_TYPE_LONG: arg_type = GC_ARG_TYPE_INT32; break;
case ARGPARSE_TYPE_ULONG: arg_type = GC_ARG_TYPE_UINT32; break;
case ARGPARSE_TYPE_STRING: arg_type = GC_ARG_TYPE_STRING; break;
default: arg_type = GC_ARG_TYPE_NONE; break;
}
opt_info[opt_info_used].arg_type = arg_type;
if (pseudo) /* Pseudo options are always no_change. */
opt_info[opt_info_used].no_change = 1;
if ((optflags & ARGPARSE_OPT_HEADER))
opt_info[opt_info_used].is_header = 1;
if (known_option)
{
if ((known_option->flags & GC_OPT_FLAG_LIST))
opt_info[opt_info_used].is_list = 1;
/* FIXME: The next can also be taken from opt_table->flags.
* We need to check the code whether both specifications match. */
if ((known_option->flags & GC_OPT_FLAG_ARG_OPT))
opt_info[opt_info_used].opt_arg = 1;
/* Same here. */
if ((known_option->flags & GC_OPT_FLAG_RUNTIME))
opt_info[opt_info_used].runtime = 1;
opt_info[opt_info_used].level = known_option->level;
/* Override the received argtype by a complex type. */
if (known_option->arg_type)
opt_info[opt_info_used].arg_type = known_option->arg_type;
}
opt_info_used++;
}
xfree (read_line_parm.extra_line_buffer);
line = read_line_parm.line;
line_len = read_line_parm.line_len;
log_assert (opt_table_used + pseudo_count == opt_info_used);
err = gnupg_wait_process (pgmname, pid, 1, &exitcode);
if (err)
gc_error (1, 0, "running %s failed (exitcode=%d): %s",
pgmname, exitcode, gpg_strerror (err));
gnupg_release_process (pid);
/* Make the gpgrt option table and the internal option table available. */
gc_component[component].opt_table = opt_table;
gc_component[component].options = opt_info;
/* Now read the default options. */
argv[0] = "--gpgconf-list";
argv[1] = NULL;
err = gnupg_spawn_process (pgmname, argv, NULL, NULL, 0,
NULL, &outfp, NULL, &pid);
if (err)
{
gc_error (1, 0, "could not gather active options from '%s': %s",
pgmname, gpg_strerror (err));
}
while ((length = es_read_line (outfp, &line, &line_len, NULL)) > 0)
{
char *linep;
unsigned long flags = 0;
char *default_value = NULL;
/* Strip newline and carriage return, if present. */
while (length > 0
&& (line[length - 1] == '\n' || line[length - 1] == '\r'))
line[--length] = '\0';
linep = strchr (line, ':');
if (linep)
*(linep++) = '\0';
/* Extract additional flags. Default to none. */
if (linep)
{
char *end;
char *tail;
end = strchr (linep, ':');
if (end)
*(end++) = '\0';
gpg_err_set_errno (0);
flags = strtoul (linep, &tail, 0);
if (errno)
gc_error (1, errno, "malformed flags in option %s from %s",
line, pgmname);
if (!(*tail == '\0' || *tail == ':' || *tail == ' '))
gc_error (1, 0, "garbage after flags in option %s from %s",
line, pgmname);
linep = end;
}
/* Extract default value, if present. Default to empty if
not. */
if (linep)
{
char *end;
end = strchr (linep, ':');
if (end)
*(end++) = '\0';
if ((flags & GC_OPT_FLAG_DEFAULT))
default_value = linep;
linep = end;
}
/* Look up the option in the component and install the
configuration data. */
option = find_option (component, line);
if (option)
{
if (option->gpgconf_list)
gc_error (1, errno,
"option %s returned twice from \"%s --gpgconf-list\"",
line, pgmname);
option->gpgconf_list = 1;
if ((flags & GC_OPT_FLAG_DEFAULT))
option->has_default = 1;
if ((flags & GC_OPT_FLAG_DEF_DESC))
option->def_in_desc = 1;
if ((flags & GC_OPT_FLAG_NO_ARG_DESC))
option->no_arg_desc = 1;
if ((flags & GC_OPT_FLAG_NO_CHANGE))
option->no_change = 1;
if (default_value && *default_value)
option->default_value = xstrdup (default_value);
}
}
if (length < 0 || es_ferror (outfp))
gc_error (1, errno, "error reading from %s", pgmname);
if (es_fclose (outfp))
gc_error (1, errno, "error closing %s", pgmname);
err = gnupg_wait_process (pgmname, pid, 1, &exitcode);
if (err)
gc_error (1, 0, "running %s failed (exitcode=%d): %s",
pgmname, exitcode, gpg_strerror (err));
gnupg_release_process (pid);
/* At this point, we can parse the configuration file. */
config_name = gc_component[component].option_config_filename;
if (!config_name)
gc_error (1, 0, "name of config file for %s is not known\n", pgmname);
if (!gnupg_default_homedir_p ())
{
/* This is not the default homedir. We need to take an absolute
* config name for the user config file; gpgrt_argparser
* fortunately supports this. */
char *tmp = make_filename (gnupg_homedir (), config_name, NULL);
twopartconfig_name = xstrconcat (config_name, PATHSEP_S, tmp, NULL);
xfree (tmp);
config_name = twopartconfig_name;
}
memset (&pargs, 0, sizeof pargs);
dummy_argc = 0;
pargs.argc = &dummy_argc;
pargs.flags = (ARGPARSE_FLAG_KEEP
| ARGPARSE_FLAG_SYS
| ARGPARSE_FLAG_USER
| ARGPARSE_FLAG_WITHATTR
| ARGPARSE_FLAG_VERBOSE);
while (gnupg_argparser (&pargs, opt_table, config_name))
{
char *opt_value;
if (pargs.r_opt == ARGPARSE_CONFFILE)
{
/* log_debug ("current conffile='%s'\n", */
/* pargs.r_type? pargs.r.ret_str: "[cmdline]"); */
continue;
}
if ((pargs.r_type & ARGPARSE_OPT_IGNORE))
continue;
/* We only have the short option. Search in the option table
* for the long option name. */
for (i=0; opt_table[i].short_opt; i++)
if (opt_table[i].short_opt == pargs.r_opt)
break;
if (!opt_table[i].short_opt || !opt_table[i].long_opt)
continue; /* No or only a short option - ignore. */
/* Look up the option from the config file in our list of
* supported options. */
option= find_option (component, opt_table[i].long_opt);
if (!option)
continue; /* We don't want to handle this option. */
/* Set the force and ignore attributes. The idea is that there
* is no way to clear them again, thus we set them when first
* encountered. */
if ((pargs.r_type & ARGPARSE_ATTR_FORCE))
option->attr_force = 1;
if ((pargs.r_type & ARGPARSE_ATTR_IGNORE))
option->attr_ignore = 1;
/* If an option has been ignored, there is no need to return
* that option with gpgconf --list-options. */
if (option->attr_ignore)
continue;
switch ((pargs.r_type & ARGPARSE_TYPE_MASK))
{
case ARGPARSE_TYPE_INT:
opt_value = xasprintf ("%d", pargs.r.ret_int);
break;
case ARGPARSE_TYPE_LONG:
opt_value = xasprintf ("%ld", pargs.r.ret_long);
break;
case ARGPARSE_TYPE_ULONG:
opt_value = xasprintf ("%lu", pargs.r.ret_ulong);
break;
case ARGPARSE_TYPE_STRING:
if (!pargs.r.ret_str)
opt_value = xstrdup ("\"(none)"); /* We should not see this. */
else
opt_value = xasprintf ("\"%s", gc_percent_escape (pargs.r.ret_str));
break;
default: /* ARGPARSE_TYPE_NONE or any unknown type. */
opt_value = xstrdup ("1"); /* Make sure we have some value. */
break;
}
/* Now enter the value read from the config file into the table. */
if (!option->is_list)
{
xfree (option->value);
option->value = opt_value;
}
else if (!option->value) /* LIST but first item. */
option->value = opt_value;
else
{
char *old = option->value;
option->value = xstrconcat (old, ",", opt_value, NULL);
xfree (old);
xfree (opt_value);
}
}
xfree (line);
xfree (twopartconfig_name);
}
/* Retrieve the currently active options and their defaults for this
component. Using -1 for component will retrieve all options from
all installed components. */
void
gc_component_retrieve_options (int component)
{
int process_all = 0;
if (component == -1)
{
process_all = 1;
component = 0;
}
do
{
if (component == GC_COMPONENT_PINENTRY)
continue; /* Skip this dummy component. */
if (gc_component[component].program)
retrieve_options_from_program (component, process_all);
}
while (process_all && ++component < GC_COMPONENT_NR);
}
/* Perform a simple validity check based on the type. Return in
* NEW_VALUE_NR the value of the number in NEW_VALUE if OPTION is of
* type GC_ARG_TYPE_NONE. If VERBATIM is set the profile parsing mode
* is used. */
static void
option_check_validity (gc_component_id_t component,
gc_option_t *option, unsigned long flags,
char *new_value, unsigned long *new_value_nr,
int verbatim)
{
char *arg;
(void)component;
if (option->new_flags || option->new_value)
gc_error (1, 0, "option %s already changed", option->name);
if (flags & GC_OPT_FLAG_DEFAULT)
{
if (*new_value)
gc_error (1, 0, "argument %s provided for deleted option %s",
new_value, option->name);
return;
}
/* GC_ARG_TYPE_NONE options have special list treatment. */
if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_NONE)
{
char *tail;
gpg_err_set_errno (0);
*new_value_nr = strtoul (new_value, &tail, 0);
if (errno)
gc_error (1, errno, "invalid argument for option %s",
option->name);
if (*tail)
gc_error (1, 0, "garbage after argument for option %s",
option->name);
if (!option->is_list)
{
if (*new_value_nr != 1)
gc_error (1, 0, "argument for non-list option %s of type 0 "
"(none) must be 1", option->name);
}
else
{
if (*new_value_nr == 0)
gc_error (1, 0, "argument for option %s of type 0 (none) "
"must be positive", option->name);
}
return;
}
arg = new_value;
do
{
if (*arg == '\0' || (*arg == ',' && !verbatim))
{
if (!option->opt_arg)
gc_error (1, 0, "argument required for option %s", option->name);
if (*arg == ',' && !verbatim && !option->is_list)
gc_error (1, 0, "list found for non-list option %s", option->name);
}
else if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_STRING)
{
if (*arg != '"' && !verbatim)
gc_error (1, 0, "string argument for option %s must begin "
"with a quote (\") character", option->name);
/* FIXME: We do not allow empty string arguments for now, as
we do not quote arguments in configuration files, and
thus no argument is indistinguishable from the empty
string. */
if (arg[1] == '\0' || (arg[1] == ',' && !verbatim))
gc_error (1, 0, "empty string argument for option %s is "
"currently not allowed. Please report this!",
option->name);
}
else if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_INT32)
{
long res;
gpg_err_set_errno (0);
res = strtol (arg, &arg, 0);
(void) res;
if (errno)
gc_error (1, errno, "invalid argument for option %s",
option->name);
if (*arg != '\0' && (*arg != ',' || verbatim))
gc_error (1, 0, "garbage after argument for option %s",
option->name);
}
else if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_UINT32)
{
unsigned long res;
gpg_err_set_errno (0);
res = strtoul (arg, &arg, 0);
(void) res;
if (errno)
gc_error (1, errno, "invalid argument for option %s",
option->name);
if (*arg != '\0' && (*arg != ',' || verbatim))
gc_error (1, 0, "garbage after argument for option %s",
option->name);
}
arg = verbatim? strchr (arg, ',') : NULL;
if (arg)
arg++;
}
while (arg && *arg);
}
#ifdef HAVE_W32_SYSTEM
int
copy_file (const char *src_name, const char *dst_name)
{
#define BUF_LEN 4096
char buffer[BUF_LEN];
int len;
gpgrt_stream_t src;
gpgrt_stream_t dst;
src = gpgrt_fopen (src_name, "r");
if (src == NULL)
return -1;
dst = gpgrt_fopen (dst_name, "w");
if (dst == NULL)
{
int saved_err = errno;
gpgrt_fclose (src);
gpg_err_set_errno (saved_err);
return -1;
}
do
{
int written;
len = gpgrt_fread (buffer, 1, BUF_LEN, src);
if (len == 0)
break;
written = gpgrt_fwrite (buffer, 1, len, dst);
if (written != len)
break;
}
while (! gpgrt_feof (src) && ! gpgrt_ferror (src) && ! gpgrt_ferror (dst));
if (gpgrt_ferror (src) || gpgrt_ferror (dst) || ! gpgrt_feof (src))
{
int saved_errno = errno;
gpgrt_fclose (src);
gpgrt_fclose (dst);
unlink (dst_name);
gpg_err_set_errno (saved_errno);
return -1;
}
if (gpgrt_fclose (dst))
gc_error (1, errno, "error closing %s", dst_name);
if (gpgrt_fclose (src))
gc_error (1, errno, "error closing %s", src_name);
return 0;
}
#endif /* HAVE_W32_SYSTEM */
/* Create and verify the new configuration file for the specified
* component. Returns 0 on success and -1 on error. If
* VERBATIM is set the profile mode is used. This function may store
* pointers to malloced strings in SRC_FILENAMEP, DEST_FILENAMEP, and
* ORIG_FILENAMEP. Those must be freed by the caller. The strings
* refer to three versions of the configuration file:
*
* SRC_FILENAME: The updated configuration is written to this file.
* DEST_FILENAME: Name of the configuration file read by the
* component.
* ORIG_FILENAME: A backup of the previous configuration file.
*
* To apply the configuration change, rename SRC_FILENAME to
* DEST_FILENAME. To revert to the previous configuration, rename
* ORIG_FILENAME to DEST_FILENAME. */
static int
change_options_program (gc_component_id_t component,
char **src_filenamep, char **dest_filenamep,
char **orig_filenamep,
int verbatim)
{
static const char marker[] = "###+++--- " GPGCONF_DISP_NAME " ---+++###";
/* True if we are within the marker in the config file. */
int in_marker = 0;
gc_option_t *option;
char *line = NULL;
size_t line_len;
ssize_t length;
int res;
int fd;
gpgrt_stream_t src_file = NULL;
gpgrt_stream_t dest_file = NULL;
char *src_filename;
char *dest_filename;
char *orig_filename;
/* Special hack for gpg, see below. */
int utf8strings_seen = 0;
/* FIXME. Throughout the function, do better error reporting. */
if (!gc_component[component].option_config_filename)
gc_error (1, 0, "name of config file for %s is not known\n",
gc_component[component].name);
dest_filename = make_absfilename
(gnupg_homedir (), gc_component[component].option_config_filename, NULL);
src_filename = xasprintf ("%s.%s.%i.new",
dest_filename, GPGCONF_NAME, (int)getpid ());
orig_filename = xasprintf ("%s.%s.%i.bak",
dest_filename, GPGCONF_NAME, (int)getpid ());
#ifdef HAVE_W32_SYSTEM
res = copy_file (dest_filename, orig_filename);
#else
res = link (dest_filename, orig_filename);
#endif
if (res < 0 && errno != ENOENT)
{
xfree (dest_filename);
xfree (src_filename);
xfree (orig_filename);
return -1;
}
if (res < 0)
{
xfree (orig_filename);
orig_filename = NULL;
}
/* We now initialize the return strings, so the caller can do the
cleanup for us. */
*src_filenamep = src_filename;
*dest_filenamep = dest_filename;
*orig_filenamep = orig_filename;
/* Use open() so that we can use O_EXCL.
* FIXME: gpgrt has an x flag for quite some time now - use that. */
fd = gnupg_open (src_filename, O_CREAT | O_EXCL | O_WRONLY, 0644);
if (fd < 0)
return -1;
src_file = gpgrt_fdopen (fd, "w");
res = errno;
if (!src_file)
{
gpg_err_set_errno (res);
return -1;
}
/* Only if ORIG_FILENAME is not NULL did the configuration file
exist already. In this case, we will copy its content into the
new configuration file, changing it to our liking in the
process. */
if (orig_filename)
{
dest_file = gpgrt_fopen (dest_filename, "r");
if (!dest_file)
goto change_one_err;
while ((length = gpgrt_read_line (dest_file, &line, &line_len, NULL)) > 0)
{
int disable = 0;
char *start;
if (!strncmp (marker, line, sizeof (marker) - 1))
{
if (!in_marker)
in_marker = 1;
else
break;
}
else if (component == GC_COMPONENT_GPG && in_marker
&& ! strcmp ("utf8-strings\n", line))
{
/* Strip duplicated entries. */
if (utf8strings_seen)
disable = 1;
else
utf8strings_seen = 1;
}
start = line;
while (*start == ' ' || *start == '\t')
start++;
if (*start && *start != '\r' && *start != '\n' && *start != '#')
{
char *end;
char saved_end;
end = start;
while (*end && *end != ' ' && *end != '\t'
&& *end != '\r' && *end != '\n' && *end != '#')
end++;
saved_end = *end;
*end = '\0';
option = find_option (component, start);
*end = saved_end;
if (option && ((option->new_flags & GC_OPT_FLAG_DEFAULT)
|| option->new_value))
disable = 1;
}
if (disable)
{
if (!in_marker)
{
gpgrt_fprintf (src_file,
"# %s disabled this option here at %s\n",
GPGCONF_DISP_NAME, asctimestamp (gnupg_get_time ()));
if (gpgrt_ferror (src_file))
goto change_one_err;
gpgrt_fprintf (src_file, "# %s", line);
if (gpgrt_ferror (src_file))
goto change_one_err;
}
}
else
{
gpgrt_fprintf (src_file, "%s", line);
if (gpgrt_ferror (src_file))
goto change_one_err;
}
}
if (length < 0 || gpgrt_ferror (dest_file))
goto change_one_err;
}
if (!in_marker)
{
/* There was no marker. This is the first time we edit the
file. We add our own marker at the end of the file and
proceed. Note that we first write a newline, this guards us
against files which lack the newline at the end of the last
line, while it doesn't hurt us in all other cases. */
gpgrt_fprintf (src_file, "\n%s\n", marker);
if (gpgrt_ferror (src_file))
goto change_one_err;
}
/* At this point, we have copied everything up to the end marker
into the new file, except for the options we are going to change.
Now, dump the changed options (except for those we are going to
revert to their default), and write the end marker, possibly
followed by the rest of the original file. */
/* We have to turn on UTF8 strings for GnuPG. */
if (component == GC_COMPONENT_GPG && ! utf8strings_seen)
gpgrt_fprintf (src_file, "utf8-strings\n");
option = gc_component[component].options;
for ( ; option->name; option++)
{
if (!option->is_header && option->new_value)
{
char *arg = option->new_value;
do
{
if (*arg == '\0' || *arg == ',')
{
gpgrt_fprintf (src_file, "%s\n", option->name);
if (gpgrt_ferror (src_file))
goto change_one_err;
}
else if (gc_arg_type[option->arg_type].fallback
== GC_ARG_TYPE_NONE)
{
log_assert (*arg == '1');
gpgrt_fprintf (src_file, "%s\n", option->name);
if (gpgrt_ferror (src_file))
goto change_one_err;
arg++;
}
else if (gc_arg_type[option->arg_type].fallback
== GC_ARG_TYPE_STRING)
{
char *end;
if (!verbatim)
{
log_assert (*arg == '"');
arg++;
end = strchr (arg, ',');
if (end)
*end = '\0';
}
else
end = NULL;
gpgrt_fprintf (src_file, "%s %s\n", option->name,
verbatim? arg : percent_deescape (arg));
if (gpgrt_ferror (src_file))
goto change_one_err;
if (end)
*end = ',';
arg = end;
}
else
{
char *end;
end = strchr (arg, ',');
if (end)
*end = '\0';
gpgrt_fprintf (src_file, "%s %s\n", option->name, arg);
if (gpgrt_ferror (src_file))
goto change_one_err;
if (end)
*end = ',';
arg = end;
}
log_assert (arg == NULL || *arg == '\0' || *arg == ',');
if (arg && *arg == ',')
arg++;
}
while (arg && *arg);
}
}
gpgrt_fprintf (src_file, "%s %s\n", marker, asctimestamp (gnupg_get_time ()));
if (gpgrt_ferror (src_file))
goto change_one_err;
if (!in_marker)
{
gpgrt_fprintf (src_file, "# %s edited this configuration file.\n",
GPGCONF_DISP_NAME);
if (gpgrt_ferror (src_file))
goto change_one_err;
gpgrt_fprintf (src_file, "# It will disable options before this marked "
"block, but it will\n");
if (gpgrt_ferror (src_file))
goto change_one_err;
gpgrt_fprintf (src_file, "# never change anything below these lines.\n");
if (gpgrt_ferror (src_file))
goto change_one_err;
}
if (dest_file)
{
while ((length = gpgrt_read_line (dest_file, &line, &line_len, NULL)) > 0)
{
gpgrt_fprintf (src_file, "%s", line);
if (gpgrt_ferror (src_file))
goto change_one_err;
}
if (length < 0 || gpgrt_ferror (dest_file))
goto change_one_err;
}
xfree (line);
line = NULL;
res = gpgrt_fclose (src_file);
if (res)
{
res = errno;
close (fd);
if (dest_file)
gpgrt_fclose (dest_file);
gpg_err_set_errno (res);
return -1;
}
close (fd);
if (dest_file)
{
res = gpgrt_fclose (dest_file);
if (res)
return -1;
}
return 0;
change_one_err:
xfree (line);
res = errno;
if (src_file)
{
gpgrt_fclose (src_file);
close (fd);
}
if (dest_file)
gpgrt_fclose (dest_file);
gpg_err_set_errno (res);
return -1;
}
/* Common code for gc_component_change_options and
* gc_process_gpgconf_conf. If VERBATIM is set the profile parsing
* mode is used. */
static void
change_one_value (gc_component_id_t component,
gc_option_t *option, int *r_runtime,
unsigned long flags, char *new_value, int verbatim)
{
unsigned long new_value_nr = 0;
option_check_validity (component, option,
flags, new_value, &new_value_nr, verbatim);
if (option->runtime)
*r_runtime = 1;
option->new_flags = flags;
if (!(flags & GC_OPT_FLAG_DEFAULT))
{
if (gc_arg_type[option->arg_type].fallback == GC_ARG_TYPE_NONE
&& option->is_list)
{
char *str;
/* We convert the number to a list of 1's for convenient
list handling. */
log_assert (new_value_nr > 0);
option->new_value = xmalloc ((2 * (new_value_nr - 1) + 1) + 1);
str = option->new_value;
*(str++) = '1';
while (--new_value_nr > 0)
{
*(str++) = ',';
*(str++) = '1';
}
*(str++) = '\0';
}
else
option->new_value = xstrdup (new_value);
}
}
/* Read the modifications from IN and apply them. If IN is NULL the
modifications are expected to already have been set to the global
table. If VERBATIM is set the profile mode is used. */
void
gc_component_change_options (int component, estream_t in, estream_t out,
int verbatim)
{
int err = 0;
int block = 0;
int runtime = 0;
char *src_filename = NULL;
char *dest_filename = NULL;
char *orig_filename = NULL;
gc_option_t *option;
char *line = NULL;
size_t line_len = 0;
ssize_t length;
if (component == GC_COMPONENT_PINENTRY)
return; /* Dummy component for now. */
if (in)
{
/* Read options from the file IN. */
while ((length = es_read_line (in, &line, &line_len, NULL)) > 0)
{
char *linep;
unsigned long flags = 0;
char *new_value = "";
/* Strip newline and carriage return, if present. */
while (length > 0
&& (line[length - 1] == '\n' || line[length - 1] == '\r'))
line[--length] = '\0';
linep = strchr (line, ':');
if (linep)
*(linep++) = '\0';
/* Extract additional flags. Default to none. */
if (linep)
{
char *end;
char *tail;
end = strchr (linep, ':');
if (end)
*(end++) = '\0';
gpg_err_set_errno (0);
flags = strtoul (linep, &tail, 0);
if (errno)
gc_error (1, errno, "malformed flags in option %s", line);
if (!(*tail == '\0' || *tail == ':' || *tail == ' '))
gc_error (1, 0, "garbage after flags in option %s", line);
linep = end;
}
/* Don't allow setting of the no change flag. */
flags &= ~GC_OPT_FLAG_NO_CHANGE;
/* Extract default value, if present. Default to empty if not. */
if (linep)
{
char *end;
end = strchr (linep, ':');
if (end)
*(end++) = '\0';
new_value = linep;
linep = end;
}
option = find_option (component, line);
if (!option)
gc_error (1, 0, "unknown option %s", line);
if (option->no_change)
{
gc_error (0, 0, "ignoring new value for option %s",
option->name);
continue;
}
change_one_value (component, option, &runtime, flags, new_value, 0);
}
if (length < 0 || gpgrt_ferror (in))
gc_error (1, errno, "error reading stream 'in'");
}
/* Now that we have collected and locally verified the changes,
write them out to new configuration files, verify them
externally, and then commit them. */
option = gc_component[component].options;
while (option && option->name)
{
/* Go on if there is nothing to do. */
if (src_filename || !(option->new_flags || option->new_value))
{
option++;
continue;
}
if (gc_component[component].program)
{
err = change_options_program (component,
&src_filename,
&dest_filename,
&orig_filename,
verbatim);
if (! err)
{
/* External verification. */
err = gc_component_check_options (component, out, src_filename);
if (err)
{
gc_error (0, 0,
_("External verification of component %s failed"),
gc_component[component].name);
gpg_err_set_errno (EINVAL);
}
}
}
if (err)
break;
option++;
}
/* We are trying to atomically commit all changes. Unfortunately,
we cannot rely on gnupg_rename_file to manage the signals for us,
doing so would require us to pass NULL as BLOCK to any subsequent
call to it. Instead, we just manage the signal handling
manually. */
block = 1;
gnupg_block_all_signals ();
if (!err && !opt.dry_run)
{
if (src_filename)
{
/* FIXME: Make a verification here. */
log_assert (dest_filename);
if (orig_filename)
err = gnupg_rename_file (src_filename, dest_filename, NULL);
else
{
#ifdef HAVE_W32_SYSTEM
/* We skip the unlink if we expect the file not to be
* there. */
err = gnupg_rename_file (src_filename, dest_filename, NULL);
#else /* HAVE_W32_SYSTEM */
/* This is a bit safer than rename() because we expect
* DEST_FILENAME not to be there. If it happens to be
* there, this will fail. */
err = link (src_filename, dest_filename);
if (!err)
err = unlink (src_filename);
#endif /* !HAVE_W32_SYSTEM */
}
if (!err)
{
xfree (src_filename);
src_filename = NULL;
}
}
}
if (err || opt.dry_run)
{
int saved_errno = errno;
/* An error occurred or a dry-run is requested. */
if (src_filename)
{
/* The change was not yet committed. */
unlink (src_filename);
if (orig_filename)
unlink (orig_filename);
}
else
{
/* The changes were already committed. FIXME: This is a tad
dangerous, as we don't know if we don't overwrite a
version of the file that is even newer than the one we
just installed. */
if (orig_filename)
gnupg_rename_file (orig_filename, dest_filename, NULL);
else
unlink (dest_filename);
}
if (err)
gc_error (1, saved_errno, "could not commit changes");
/* Fall-through for dry run. */
goto leave;
}
/* If it all worked, notify the daemons of the changes. */
if (opt.runtime)
do_runtime_change (component, 0);
/* Move the per-process backup file into its place. */
if (orig_filename)
{
char *backup_filename;
log_assert (dest_filename);
backup_filename = xasprintf ("%s.%s.bak",
dest_filename, GPGCONF_NAME);
gnupg_rename_file (orig_filename, backup_filename, NULL);
xfree (backup_filename);
}
leave:
if (block)
gnupg_unblock_all_signals ();
xfree (line);
xfree (src_filename);
xfree (dest_filename);
xfree (orig_filename);
}
/* Check whether USER matches the current user of one of its group.
This function may change USER. Returns true is there is a
match. */
static int
key_matches_user_or_group (char *user)
{
char *group;
if (*user == '*' && user[1] == 0)
return 1; /* A single asterisk matches all users. */
group = strchr (user, ':');
if (group)
*group++ = 0;
#ifdef HAVE_W32_SYSTEM
/* Under Windows we don't support groups. */
if (group && *group)
gc_error (0, 0, _("Note that group specifications are ignored\n"));
#ifndef HAVE_W32CE_SYSTEM
if (*user)
{
static char *my_name;
if (!my_name)
{
char tmp[1];
DWORD size = 1;
GetUserNameA (tmp, &size);
my_name = xmalloc (size);
if (!GetUserNameA (my_name, &size))
gc_error (1,0, "error getting current user name: %s",
w32_strerror (-1));
}
if (!strcmp (user, my_name))
return 1; /* Found. */
}
#endif /*HAVE_W32CE_SYSTEM*/
#else /*!HAVE_W32_SYSTEM*/
/* First check whether the user matches. */
if (*user)
{
static char *my_name;
if (!my_name)
{
struct passwd *pw = getpwuid ( getuid () );
if (!pw)
gc_error (1, errno, "getpwuid failed for current user");
my_name = xstrdup (pw->pw_name);
}
if (!strcmp (user, my_name))
return 1; /* Found. */
}
/* If that failed, check whether a group matches. */
if (group && *group)
{
static char *my_group;
static char **my_supgroups;
int n;
if (!my_group)
{
struct group *gr = getgrgid ( getgid () );
if (!gr)
gc_error (1, errno, "getgrgid failed for current user");
my_group = xstrdup (gr->gr_name);
}
if (!strcmp (group, my_group))
return 1; /* Found. */
if (!my_supgroups)
{
int ngids;
gid_t *gids;
ngids = getgroups (0, NULL);
gids = xcalloc (ngids+1, sizeof *gids);
ngids = getgroups (ngids, gids);
if (ngids < 0)
gc_error (1, errno, "getgroups failed for current user");
my_supgroups = xcalloc (ngids+1, sizeof *my_supgroups);
for (n=0; n < ngids; n++)
{
struct group *gr = getgrgid ( gids[n] );
if (!gr)
gc_error (1, errno, "getgrgid failed for supplementary group");
my_supgroups[n] = xstrdup (gr->gr_name);
}
xfree (gids);
}
for (n=0; my_supgroups[n]; n++)
if (!strcmp (group, my_supgroups[n]))
return 1; /* Found. */
}
#endif /*!HAVE_W32_SYSTEM*/
return 0; /* No match. */
}
/* Read and process the global configuration file for gpgconf. This
optional file is used to update our internal tables at runtime and
may also be used to set new default values. If FNAME is NULL the
default name will be used. With UPDATE set to true the internal
tables are actually updated; if not set, only a syntax check is
done. If DEFAULTS is true the global options are written to the
configuration files. If LISTFP is set, no changes are done but the
configuration file is printed to LISTFP in a colon separated format.
Returns 0 on success or if the config file is not present; -1 is
returned on error. */
int
gc_process_gpgconf_conf (const char *fname_arg, int update, int defaults,
estream_t listfp)
{
int result = 0;
char *line = NULL;
size_t line_len = 0;
ssize_t length;
gpgrt_stream_t config;
int lineno = 0;
int in_rule = 0;
int got_match = 0;
int runtime[GC_COMPONENT_NR] = { 0 };
int component_id;
char *fname;
if (fname_arg)
fname = xstrdup (fname_arg);
else
fname = make_filename (gnupg_sysconfdir (), GPGCONF_NAME EXTSEP_S "conf",
NULL);
config = gpgrt_fopen (fname, "r");
if (!config)
{
/* Do not print an error if the file is not available, except
when running in syntax check mode. */
if (errno != ENOENT || !update)
{
gc_error (0, errno, "can not open global config file '%s'", fname);
result = -1;
}
xfree (fname);
return result;
}
while ((length = gpgrt_read_line (config, &line, &line_len, NULL)) > 0)
{
char *key, *compname, *option, *flags, *value;
char *empty;
gc_option_t *option_info = NULL;
char *p;
int is_continuation;
lineno++;
key = line;
while (*key == ' ' || *key == '\t')
key++;
if (!*key || *key == '#' || *key == '\r' || *key == '\n')
continue;
is_continuation = (key != line);
/* Parse the key field. */
if (!is_continuation && got_match)
break; /* Finish after the first match. */
else if (!is_continuation)
{
in_rule = 0;
for (p=key+1; *p && !strchr (" \t\r\n", *p); p++)
;
if (!*p)
{
gc_error (0, 0, "missing rule at '%s', line %d", fname, lineno);
result = -1;
gpgconf_write_status (STATUS_WARNING,
"gpgconf.conf %d file '%s' line %d "
"missing rule",
GPG_ERR_SYNTAX, fname, lineno);
continue;
}
*p++ = 0;
compname = p;
}
else if (!in_rule)
{
gc_error (0, 0, "continuation but no rule at '%s', line %d",
fname, lineno);
result = -1;
continue;
}
else
{
compname = key;
key = NULL;
}
in_rule = 1;
/* Parse the component. */
while (*compname == ' ' || *compname == '\t')
compname++;
for (p=compname; *p && !strchr (" \t\r\n", *p); p++)
;
if (p == compname)
{
gc_error (0, 0, "missing component at '%s', line %d",
fname, lineno);
gpgconf_write_status (STATUS_WARNING,
"gpgconf.conf %d file '%s' line %d "
" missing component",
GPG_ERR_NO_NAME, fname, lineno);
result = -1;
continue;
}
empty = p;
*p++ = 0;
option = p;
component_id = gc_component_find (compname);
if (component_id < 0)
{
gc_error (0, 0, "unknown component at '%s', line %d",
fname, lineno);
gpgconf_write_status (STATUS_WARNING,
"gpgconf.conf %d file '%s' line %d "
"unknown component",
GPG_ERR_UNKNOWN_NAME, fname, lineno);
result = -1;
}
/* Parse the option name. */
while (*option == ' ' || *option == '\t')
option++;
for (p=option; *p && !strchr (" \t\r\n", *p); p++)
;
if (p == option)
{
gc_error (0, 0, "missing option at '%s', line %d",
fname, lineno);
gpgconf_write_status (STATUS_WARNING,
"gpgconf.conf %d file '%s' line %d "
"missing option",
GPG_ERR_INV_NAME, fname, lineno);
result = -1;
continue;
}
*p++ = 0;
flags = p;
if ( component_id != -1)
{
/* We need to make sure that we got the option list for the
* component. */
if (!gc_component[component_id].options)
gc_component_retrieve_options (component_id);
option_info = find_option (component_id, option);
if (!option_info)
{
gc_error (0, 0, "unknown option '%s' at '%s', line %d",
option, fname, lineno);
gpgconf_write_status (STATUS_WARNING,
"gpgconf.conf %d file '%s' line %d "
"unknown option",
GPG_ERR_UNKNOWN_OPTION, fname, lineno);
result = -1;
}
}
/* Parse the optional flags. */
while (*flags == ' ' || *flags == '\t')
flags++;
if (*flags == '[')
{
flags++;
p = strchr (flags, ']');
if (!p)
{
gc_error (0, 0, "syntax error in rule at '%s', line %d",
fname, lineno);
gpgconf_write_status (STATUS_WARNING,
"gpgconf.conf %d file '%s' line %d "
"syntax error in rule",
GPG_ERR_SYNTAX, fname, lineno);
result = -1;
continue;
}
*p++ = 0;
value = p;
}
else /* No flags given. */
{
value = flags;
flags = NULL;
}
/* Parse the optional value. */
while (*value == ' ' || *value == '\t')
value++;
for (p=value; *p && !strchr ("\r\n", *p); p++)
;
if (p == value)
value = empty; /* No value given; let it point to an empty string. */
else
{
/* Strip trailing white space. */
*p = 0;
for (p--; p > value && (*p == ' ' || *p == '\t'); p--)
*p = 0;
}
/* Check flag combinations. */
if (!flags)
;
else if (!strcmp (flags, "default"))
{
if (*value)
{
gc_error (0, 0, "flag \"default\" may not be combined "
"with a value at '%s', line %d",
fname, lineno);
result = -1;
}
}
else if (!strcmp (flags, "change"))
;
else if (!strcmp (flags, "no-change"))
;
else
{
gc_error (0, 0, "unknown flag at '%s', line %d",
fname, lineno);
result = -1;
}
/* In list mode we print out all records. */
if (listfp && !result)
{
/* If this is a new ruleset, print a key record. */
if (!is_continuation)
{
char *group = strchr (key, ':');
if (group)
{
*group++ = 0;
if ((p = strchr (group, ':')))
*p = 0; /* We better strip any extra stuff. */
}
es_fprintf (listfp, "k:%s:", gc_percent_escape (key));
es_fprintf (listfp, "%s\n", group? gc_percent_escape (group):"");
}
/* All other lines are rule records. */
es_fprintf (listfp, "r:::%s:%s:%s:",
gc_component[component_id].name,
option_info->name? option_info->name : "",
flags? flags : "");
if (value != empty)
es_fprintf (listfp, "\"%s", gc_percent_escape (value));
es_putc ('\n', listfp);
}
/* Check whether the key matches but do this only if we are not
running in syntax check mode. */
if ( update
&& !result && !listfp
&& (got_match || (key && key_matches_user_or_group (key))) )
{
int newflags = 0;
got_match = 1;
/* Apply the flags from gpgconf.conf. */
if (!flags)
;
else if (!strcmp (flags, "default"))
newflags |= GC_OPT_FLAG_DEFAULT;
else if (!strcmp (flags, "no-change"))
option_info->no_change = 1;
else if (!strcmp (flags, "change"))
option_info->no_change = 0;
if (defaults)
{
/* Here we explicitly allow updating the value again. */
if (newflags)
{
option_info->new_flags = 0;
}
if (*value)
{
xfree (option_info->new_value);
option_info->new_value = NULL;
}
change_one_value (component_id, option_info,
runtime, newflags, value, 0);
}
}
}
if (length < 0 || gpgrt_ferror (config))
{
gc_error (0, errno, "error reading from '%s'", fname);
result = -1;
}
if (gpgrt_fclose (config))
gc_error (0, errno, "error closing '%s'", fname);
xfree (line);
/* If it all worked, process the options. */
if (!result && update && defaults && !listfp)
{
/* We need to switch off the runtime update, so that we can do
it later all at once. */
int save_opt_runtime = opt.runtime;
opt.runtime = 0;
for (component_id = 0; component_id < GC_COMPONENT_NR; component_id++)
{
gc_component_change_options (component_id, NULL, NULL, 0);
}
opt.runtime = save_opt_runtime;
if (opt.runtime)
{
for (component_id = 0; component_id < GC_COMPONENT_NR; component_id++)
if (runtime[component_id]
&& gc_component[component_id].runtime_change)
(*gc_component[component_id].runtime_change) (0);
}
}
xfree (fname);
return result;
}
/*
* Apply the profile FNAME to all known configure files.
*/
gpg_error_t
gc_apply_profile (const char *fname)
{
gpg_error_t err;
char *fname_buffer = NULL;
char *line = NULL;
size_t line_len = 0;
ssize_t length;
estream_t fp;
int lineno = 0;
int runtime[GC_COMPONENT_NR] = { 0 };
int component_id = -1;
int skip_section = 0;
int error_count = 0;
int newflags;
if (!fname)
fname = "-";
if (!(!strcmp (fname, "-")
|| strchr (fname, '/')
#ifdef HAVE_W32_SYSTEM
|| strchr (fname, '\\')
#endif
|| strchr (fname, '.')))
{
/* FNAME looks like a standard profile name. Check whether one
* is installed and use that instead of the given file name. */
fname_buffer = xstrconcat (gnupg_datadir (), DIRSEP_S,
fname, ".prf", NULL);
if (!gnupg_access (fname_buffer, F_OK))
fname = fname_buffer;
}
fp = !strcmp (fname, "-")? es_stdin : es_fopen (fname, "r");
if (!fp)
{
err = gpg_error_from_syserror ();
log_error ("can't open '%s': %s\n", fname, gpg_strerror (err));
return err;
}
if (opt.verbose)
log_info ("applying profile '%s'\n", fname);
err = 0;
while ((length = es_read_line (fp, &line, &line_len, NULL)) > 0)
{
char *name, *flags, *value;
gc_option_t *option_info = NULL;
char *p;
lineno++;
name = line;
while (*name == ' ' || *name == '\t')
name++;
if (!*name || *name == '#' || *name == '\r' || *name == '\n')
continue;
trim_trailing_spaces (name);
/* Check whether this is a new section. */
if (*name == '[')
{
name++;
skip_section = 0;
/* New section: Get the name of the component. */
p = strchr (name, ']');
if (!p)
{
error_count++;
log_info ("%s:%d:%d: error: syntax error in section tag\n",
fname, lineno, (int)(name - line));
skip_section = 1;
continue;
}
*p++ = 0;
if (*p)
log_info ("%s:%d:%d: warning: garbage after section tag\n",
fname, lineno, (int)(p - line));
trim_spaces (name);
component_id = gc_component_find (name);
if (component_id < 0)
{
log_info ("%s:%d:%d: warning: skipping unknown section '%s'\n",
fname, lineno, (int)(name - line), name );
skip_section = 1;
}
continue;
}
if (skip_section)
continue;
if (component_id < 0)
{
error_count++;
log_info ("%s:%d:%d: error: not in a valid section\n",
fname, lineno, (int)(name - line));
skip_section = 1;
continue;
}
/* Parse the option name. */
for (p = name; *p && !spacep (p); p++)
;
*p++ = 0;
value = p;
option_info = find_option (component_id, name);
if (!option_info)
{
error_count++;
log_info ("%s:%d:%d: error: unknown option '%s' in section '%s'\n",
fname, lineno, (int)(name - line),
name, gc_component[component_id].name);
continue;
}
/* Parse the optional flags. */
trim_spaces (value);
flags = value;
if (*flags == '[')
{
flags++;
p = strchr (flags, ']');
if (!p)
{
log_info ("%s:%d:%d: warning: invalid flag specification\n",
fname, lineno, (int)(p - line));
continue;
}
*p++ = 0;
value = p;
trim_spaces (value);
}
else /* No flags given. */
flags = NULL;
/* Set required defaults. */
if (gc_arg_type[option_info->arg_type].fallback == GC_ARG_TYPE_NONE
&& !*value)
value = "1";
/* Check and save this option. */
newflags = 0;
if (flags && !strcmp (flags, "default"))
newflags |= GC_OPT_FLAG_DEFAULT;
if (newflags)
option_info->new_flags = 0;
if (*value)
{
xfree (option_info->new_value);
option_info->new_value = NULL;
}
change_one_value (component_id, option_info, runtime, newflags, value, 1);
}
if (length < 0 || es_ferror (fp))
{
err = gpg_error_from_syserror ();
error_count++;
log_error (_("%s:%u: read error: %s\n"),
fname, lineno, gpg_strerror (err));
}
if (es_fclose (fp))
log_error (_("error closing '%s'\n"), fname);
if (error_count)
log_error (_("error parsing '%s'\n"), fname);
xfree (line);
/* If it all worked, process the options. */
if (!err)
{
/* We need to switch off the runtime update, so that we can do
it later all at once. */
int save_opt_runtime = opt.runtime;
opt.runtime = 0;
for (component_id = 0; component_id < GC_COMPONENT_NR; component_id++)
{
gc_component_change_options (component_id, NULL, NULL, 1);
}
opt.runtime = save_opt_runtime;
if (opt.runtime)
{
for (component_id = 0; component_id < GC_COMPONENT_NR; component_id++)
if (runtime[component_id]
&& gc_component[component_id].runtime_change)
(*gc_component[component_id].runtime_change) (0);
}
}
xfree (fname_buffer);
return err;
}

File Metadata

Mime Type
text/x-diff
Expires
Mon, Dec 23, 3:19 PM (34 s)
Storage Engine
local-disk
Storage Format
Raw Data
Storage Handle
0e/e8/060b214c68dfd7ebc5ccfc5a8374

Event Timeline