diff --git a/agent/command-ssh.c b/agent/command-ssh.c
index 86fd092ff..8a4150539 100644
--- a/agent/command-ssh.c
+++ b/agent/command-ssh.c
@@ -1,3902 +1,3902 @@
/* command-ssh.c - gpg-agent's implementation of the ssh-agent protocol.
* Copyright (C) 2004-2006, 2009, 2012 Free Software Foundation, Inc.
* Copyright (C) 2004-2006, 2009, 2012-2014 Werner Koch
*
* 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 .
*/
/* Only v2 of the ssh-agent protocol is implemented. Relevant RFCs
are:
RFC-4250 - Protocol Assigned Numbers
RFC-4251 - Protocol Architecture
RFC-4252 - Authentication Protocol
RFC-4253 - Transport Layer Protocol
RFC-5656 - ECC support
The protocol for the agent is defined in:
https://tools.ietf.org/html/draft-miller-ssh-agent
*/
#include
#include
#include
#include
#include
#include
#include
#include
#ifndef HAVE_W32_SYSTEM
#include
#include
#endif /*!HAVE_W32_SYSTEM*/
#ifdef HAVE_SYS_UCRED_H
#include
#endif
#ifdef HAVE_UCRED_H
#include
#endif
#include "agent.h"
#include "../common/i18n.h"
#include "../common/util.h"
#include "../common/ssh-utils.h"
/* Request types. */
#define SSH_REQUEST_REQUEST_IDENTITIES 11
#define SSH_REQUEST_SIGN_REQUEST 13
#define SSH_REQUEST_ADD_IDENTITY 17
#define SSH_REQUEST_REMOVE_IDENTITY 18
#define SSH_REQUEST_REMOVE_ALL_IDENTITIES 19
#define SSH_REQUEST_LOCK 22
#define SSH_REQUEST_UNLOCK 23
#define SSH_REQUEST_ADD_ID_CONSTRAINED 25
/* Options. */
#define SSH_OPT_CONSTRAIN_LIFETIME 1
#define SSH_OPT_CONSTRAIN_CONFIRM 2
/* Response types. */
#define SSH_RESPONSE_SUCCESS 6
#define SSH_RESPONSE_FAILURE 5
#define SSH_RESPONSE_IDENTITIES_ANSWER 12
#define SSH_RESPONSE_SIGN_RESPONSE 14
/* Other constants. */
#define SSH_DSA_SIGNATURE_PADDING 20
#define SSH_DSA_SIGNATURE_ELEMS 2
#define SSH_AGENT_RSA_SHA2_256 0x02
#define SSH_AGENT_RSA_SHA2_512 0x04
#define SPEC_FLAG_USE_PKCS1V2 (1 << 0)
#define SPEC_FLAG_IS_ECDSA (1 << 1)
#define SPEC_FLAG_IS_EdDSA (1 << 2) /*(lowercase 'd' on purpose.)*/
#define SPEC_FLAG_WITH_CERT (1 << 7)
/* The name of the control file. */
#define SSH_CONTROL_FILE_NAME "sshcontrol"
/* The blurb we put into the header of a newly created control file. */
static const char sshcontrolblurb[] =
"# List of allowed ssh keys. Only keys present in this file are used\n"
"# in the SSH protocol. The ssh-add tool may add new entries to this\n"
"# file to enable them; you may also add them manually. Comment\n"
"# lines, like this one, as well as empty lines are ignored. Lines do\n"
"# have a certain length limit but this is not serious limitation as\n"
"# the format of the entries is fixed and checked by gpg-agent. A\n"
"# non-comment line starts with optional white spaces, followed by the\n"
"# keygrip of the key given as 40 hex digits, optionally followed by a\n"
"# caching TTL in seconds, and another optional field for arbitrary\n"
"# flags. Prepend the keygrip with an '!' mark to disable it.\n"
"\n";
/* Macros. */
/* Return a new uint32 with b0 being the most significant byte and b3
being the least significant byte. */
#define uint32_construct(b0, b1, b2, b3) \
((b0 << 24) | (b1 << 16) | (b2 << 8) | b3)
/*
* Basic types.
*/
/* Type for a request handler. */
typedef gpg_error_t (*ssh_request_handler_t) (ctrl_t ctrl,
estream_t request,
estream_t response);
struct ssh_key_type_spec;
typedef struct ssh_key_type_spec ssh_key_type_spec_t;
/* Type, which is used for associating request handlers with the
appropriate request IDs. */
typedef struct ssh_request_spec
{
unsigned char type;
ssh_request_handler_t handler;
const char *identifier;
unsigned int secret_input;
} ssh_request_spec_t;
/* Type for "key modifier functions", which are necessary since
OpenSSH and GnuPG treat key material slightly different. A key
modifier is called right after a new key identity has been received
in order to "sanitize" the material. */
typedef gpg_error_t (*ssh_key_modifier_t) (const char *elems,
gcry_mpi_t *mpis);
/* The encoding of a generated signature is dependent on the
algorithm; therefore algorithm specific signature encoding
functions are necessary. */
typedef gpg_error_t (*ssh_signature_encoder_t) (ssh_key_type_spec_t *spec,
estream_t signature_blob,
gcry_sexp_t sig);
/* Type, which is used for boundling all the algorithm specific
information together in a single object. */
struct ssh_key_type_spec
{
/* Algorithm identifier as used by OpenSSH. */
const char *ssh_identifier;
/* Human readable name of the algorithm. */
const char *name;
/* Algorithm identifier as used by GnuPG. */
int algo;
/* List of MPI names for secret keys; order matches the one of the
agent protocol. */
const char *elems_key_secret;
/* List of MPI names for public keys; order matches the one of the
agent protocol. */
const char *elems_key_public;
/* List of MPI names for signature data. */
const char *elems_signature;
/* List of MPI names for secret keys; order matches the one, which
is required by gpg-agent's key access layer. */
const char *elems_sexp_order;
/* Key modifier function. Key modifier functions are necessary in
order to fix any inconsistencies between the representation of
keys on the SSH and on the GnuPG side. */
ssh_key_modifier_t key_modifier;
/* Signature encoder function. Signature encoder functions are
necessary since the encoding of signatures depends on the used
algorithm. */
ssh_signature_encoder_t signature_encoder;
/* The name of the ECC curve or NULL. */
const char *curve_name;
/* The hash algorithm to be used with this key. 0 for using the
default. */
int hash_algo;
/* Misc flags. */
unsigned int flags;
};
/* Definition of an object to access the sshcontrol file. */
struct ssh_control_file_s
{
char *fname; /* Name of the file. */
FILE *fp; /* This is never NULL. */
int lnr; /* The current line number. */
struct {
int valid; /* True if the data of this structure is valid. */
int disabled; /* The item is disabled. */
int ttl; /* The TTL of the item. */
int confirm; /* The confirm flag is set. */
char hexgrip[40+1]; /* The hexgrip of the item (uppercase). */
} item;
};
/* Prototypes. */
static gpg_error_t ssh_handler_request_identities (ctrl_t ctrl,
estream_t request,
estream_t response);
static gpg_error_t ssh_handler_sign_request (ctrl_t ctrl,
estream_t request,
estream_t response);
static gpg_error_t ssh_handler_add_identity (ctrl_t ctrl,
estream_t request,
estream_t response);
static gpg_error_t ssh_handler_remove_identity (ctrl_t ctrl,
estream_t request,
estream_t response);
static gpg_error_t ssh_handler_remove_all_identities (ctrl_t ctrl,
estream_t request,
estream_t response);
static gpg_error_t ssh_handler_lock (ctrl_t ctrl,
estream_t request,
estream_t response);
static gpg_error_t ssh_handler_unlock (ctrl_t ctrl,
estream_t request,
estream_t response);
static gpg_error_t ssh_key_modifier_rsa (const char *elems, gcry_mpi_t *mpis);
static gpg_error_t ssh_signature_encoder_rsa (ssh_key_type_spec_t *spec,
estream_t signature_blob,
gcry_sexp_t signature);
static gpg_error_t ssh_signature_encoder_dsa (ssh_key_type_spec_t *spec,
estream_t signature_blob,
gcry_sexp_t signature);
static gpg_error_t ssh_signature_encoder_ecdsa (ssh_key_type_spec_t *spec,
estream_t signature_blob,
gcry_sexp_t signature);
static gpg_error_t ssh_signature_encoder_eddsa (ssh_key_type_spec_t *spec,
estream_t signature_blob,
gcry_sexp_t signature);
static gpg_error_t ssh_key_extract_comment (gcry_sexp_t key, char **comment);
struct peer_info_s
{
unsigned long pid;
int uid;
};
/* Global variables. */
/* Associating request types with the corresponding request
handlers. */
static const ssh_request_spec_t request_specs[] =
{
#define REQUEST_SPEC_DEFINE(id, name, secret_input) \
{ SSH_REQUEST_##id, ssh_handler_##name, #name, secret_input }
REQUEST_SPEC_DEFINE (REQUEST_IDENTITIES, request_identities, 1),
REQUEST_SPEC_DEFINE (SIGN_REQUEST, sign_request, 0),
REQUEST_SPEC_DEFINE (ADD_IDENTITY, add_identity, 1),
REQUEST_SPEC_DEFINE (ADD_ID_CONSTRAINED, add_identity, 1),
REQUEST_SPEC_DEFINE (REMOVE_IDENTITY, remove_identity, 0),
REQUEST_SPEC_DEFINE (REMOVE_ALL_IDENTITIES, remove_all_identities, 0),
REQUEST_SPEC_DEFINE (LOCK, lock, 0),
REQUEST_SPEC_DEFINE (UNLOCK, unlock, 0)
#undef REQUEST_SPEC_DEFINE
};
/* Table holding key type specifications. */
static const ssh_key_type_spec_t ssh_key_types[] =
{
{
"ssh-ed25519", "Ed25519", GCRY_PK_EDDSA, "qd", "q", "rs", "qd",
NULL, ssh_signature_encoder_eddsa,
"Ed25519", 0, SPEC_FLAG_IS_EdDSA
},
{
"ssh-rsa", "RSA", GCRY_PK_RSA, "nedupq", "en", "s", "nedpqu",
ssh_key_modifier_rsa, ssh_signature_encoder_rsa,
NULL, 0, SPEC_FLAG_USE_PKCS1V2
},
{
"ssh-dss", "DSA", GCRY_PK_DSA, "pqgyx", "pqgy", "rs", "pqgyx",
NULL, ssh_signature_encoder_dsa,
NULL, 0, 0
},
{
"ecdsa-sha2-nistp256", "ECDSA", GCRY_PK_ECC, "qd", "q", "rs", "qd",
NULL, ssh_signature_encoder_ecdsa,
"nistp256", GCRY_MD_SHA256, SPEC_FLAG_IS_ECDSA
},
{
"ecdsa-sha2-nistp384", "ECDSA", GCRY_PK_ECC, "qd", "q", "rs", "qd",
NULL, ssh_signature_encoder_ecdsa,
"nistp384", GCRY_MD_SHA384, SPEC_FLAG_IS_ECDSA
},
{
"ecdsa-sha2-nistp521", "ECDSA", GCRY_PK_ECC, "qd", "q", "rs", "qd",
NULL, ssh_signature_encoder_ecdsa,
"nistp521", GCRY_MD_SHA512, SPEC_FLAG_IS_ECDSA
},
{
"ssh-ed25519-cert-v01@openssh.com", "Ed25519",
GCRY_PK_EDDSA, "qd", "q", "rs", "qd",
NULL, ssh_signature_encoder_eddsa,
"Ed25519", 0, SPEC_FLAG_IS_EdDSA | SPEC_FLAG_WITH_CERT
},
{
"ssh-rsa-cert-v01@openssh.com", "RSA",
GCRY_PK_RSA, "nedupq", "en", "s", "nedpqu",
ssh_key_modifier_rsa, ssh_signature_encoder_rsa,
NULL, 0, SPEC_FLAG_USE_PKCS1V2 | SPEC_FLAG_WITH_CERT
},
{
"ssh-dss-cert-v01@openssh.com", "DSA",
GCRY_PK_DSA, "pqgyx", "pqgy", "rs", "pqgyx",
NULL, ssh_signature_encoder_dsa,
NULL, 0, SPEC_FLAG_WITH_CERT | SPEC_FLAG_WITH_CERT
},
{
"ecdsa-sha2-nistp256-cert-v01@openssh.com", "ECDSA",
GCRY_PK_ECC, "qd", "q", "rs", "qd",
NULL, ssh_signature_encoder_ecdsa,
"nistp256", GCRY_MD_SHA256, SPEC_FLAG_IS_ECDSA | SPEC_FLAG_WITH_CERT
},
{
"ecdsa-sha2-nistp384-cert-v01@openssh.com", "ECDSA",
GCRY_PK_ECC, "qd", "q", "rs", "qd",
NULL, ssh_signature_encoder_ecdsa,
"nistp384", GCRY_MD_SHA384, SPEC_FLAG_IS_ECDSA | SPEC_FLAG_WITH_CERT
},
{
"ecdsa-sha2-nistp521-cert-v01@openssh.com", "ECDSA",
GCRY_PK_ECC, "qd", "q", "rs", "qd",
NULL, ssh_signature_encoder_ecdsa,
"nistp521", GCRY_MD_SHA512, SPEC_FLAG_IS_ECDSA | SPEC_FLAG_WITH_CERT
}
};
/*
General utility functions.
*/
/* A secure realloc, i.e. it makes sure to allocate secure memory if A
is NULL. This is required because the standard gcry_realloc does
not know whether to allocate secure or normal if NULL is passed as
existing buffer. */
static void *
realloc_secure (void *a, size_t n)
{
void *p;
if (a)
p = gcry_realloc (a, n);
else
p = gcry_malloc_secure (n);
return p;
}
/* Lookup the ssh-identifier for the ECC curve CURVE_NAME. Returns
NULL if not found. */
static const char *
ssh_identifier_from_curve_name (const char *curve_name)
{
int i;
for (i = 0; i < DIM (ssh_key_types); i++)
if (ssh_key_types[i].curve_name
&& !strcmp (ssh_key_types[i].curve_name, curve_name))
return ssh_key_types[i].ssh_identifier;
return NULL;
}
/*
Primitive I/O functions.
*/
/* Read a byte from STREAM, store it in B. */
static gpg_error_t
stream_read_byte (estream_t stream, unsigned char *b)
{
gpg_error_t err;
int ret;
ret = es_fgetc (stream);
if (ret == EOF)
{
if (es_ferror (stream))
err = gpg_error_from_syserror ();
else
err = gpg_error (GPG_ERR_EOF);
*b = 0;
}
else
{
*b = ret & 0xFF;
err = 0;
}
return err;
}
/* Write the byte contained in B to STREAM. */
static gpg_error_t
stream_write_byte (estream_t stream, unsigned char b)
{
gpg_error_t err;
int ret;
ret = es_fputc (b, stream);
if (ret == EOF)
err = gpg_error_from_syserror ();
else
err = 0;
return err;
}
/* Read a uint32 from STREAM, store it in UINT32. */
static gpg_error_t
stream_read_uint32 (estream_t stream, u32 *uint32)
{
unsigned char buffer[4];
size_t bytes_read;
gpg_error_t err;
int ret;
ret = es_read (stream, buffer, sizeof (buffer), &bytes_read);
if (ret)
err = gpg_error_from_syserror ();
else
{
if (bytes_read != sizeof (buffer))
err = gpg_error (GPG_ERR_EOF);
else
{
u32 n;
n = uint32_construct (buffer[0], buffer[1], buffer[2], buffer[3]);
*uint32 = n;
err = 0;
}
}
return err;
}
/* Write the uint32 contained in UINT32 to STREAM. */
static gpg_error_t
stream_write_uint32 (estream_t stream, u32 uint32)
{
unsigned char buffer[4];
gpg_error_t err;
int ret;
buffer[0] = uint32 >> 24;
buffer[1] = uint32 >> 16;
buffer[2] = uint32 >> 8;
buffer[3] = uint32 >> 0;
ret = es_write (stream, buffer, sizeof (buffer), NULL);
if (ret)
err = gpg_error_from_syserror ();
else
err = 0;
return err;
}
/* Read SIZE bytes from STREAM into BUFFER. */
static gpg_error_t
stream_read_data (estream_t stream, unsigned char *buffer, size_t size)
{
gpg_error_t err;
size_t bytes_read;
int ret;
ret = es_read (stream, buffer, size, &bytes_read);
if (ret)
err = gpg_error_from_syserror ();
else
{
if (bytes_read != size)
err = gpg_error (GPG_ERR_EOF);
else
err = 0;
}
return err;
}
/* Skip over SIZE bytes from STREAM. */
static gpg_error_t
stream_read_skip (estream_t stream, size_t size)
{
char buffer[128];
size_t bytes_to_read, bytes_read;
int ret;
do
{
bytes_to_read = size;
if (bytes_to_read > sizeof buffer)
bytes_to_read = sizeof buffer;
ret = es_read (stream, buffer, bytes_to_read, &bytes_read);
if (ret)
return gpg_error_from_syserror ();
else if (bytes_read != bytes_to_read)
return gpg_error (GPG_ERR_EOF);
else
size -= bytes_to_read;
}
while (size);
return 0;
}
/* Write SIZE bytes from BUFFER to STREAM. */
static gpg_error_t
stream_write_data (estream_t stream, const unsigned char *buffer, size_t size)
{
gpg_error_t err;
int ret;
ret = es_write (stream, buffer, size, NULL);
if (ret)
err = gpg_error_from_syserror ();
else
err = 0;
return err;
}
/* Read a binary string from STREAM into STRING, store size of string
in STRING_SIZE. Append a hidden nul so that the result may
directly be used as a C string. Depending on SECURE use secure
memory for STRING. If STRING is NULL do only a dummy read. */
static gpg_error_t
stream_read_string (estream_t stream, unsigned int secure,
unsigned char **string, u32 *string_size)
{
gpg_error_t err;
unsigned char *buffer = NULL;
u32 length = 0;
if (string_size)
*string_size = 0;
/* Read string length. */
err = stream_read_uint32 (stream, &length);
if (err)
goto out;
if (string)
{
/* Allocate space. */
if (secure)
buffer = xtrymalloc_secure (length + 1);
else
buffer = xtrymalloc (length + 1);
if (! buffer)
{
err = gpg_error_from_syserror ();
goto out;
}
/* Read data. */
err = stream_read_data (stream, buffer, length);
if (err)
goto out;
/* Finalize string object. */
buffer[length] = 0;
*string = buffer;
}
else /* Dummy read requested. */
{
err = stream_read_skip (stream, length);
if (err)
goto out;
}
if (string_size)
*string_size = length;
out:
if (err)
xfree (buffer);
return err;
}
/* Read a binary string from STREAM and store it as an opaque MPI at
R_MPI, adding 0x40 (this is the prefix for EdDSA key in OpenPGP).
Depending on SECURE use secure memory. If the string is too large
for key material return an error. */
static gpg_error_t
stream_read_blob (estream_t stream, unsigned int secure, gcry_mpi_t *r_mpi)
{
gpg_error_t err;
unsigned char *buffer = NULL;
u32 length = 0;
*r_mpi = NULL;
/* Read string length. */
err = stream_read_uint32 (stream, &length);
if (err)
goto leave;
/* To avoid excessive use of secure memory we check that an MPI is
not too large. */
if (length > (4096/8) + 8)
{
log_error (_("ssh keys greater than %d bits are not supported\n"), 4096);
err = GPG_ERR_TOO_LARGE;
goto leave;
}
/* Allocate space. */
if (secure)
buffer = xtrymalloc_secure (length+1);
else
buffer = xtrymalloc (length+1);
if (!buffer)
{
err = gpg_error_from_syserror ();
goto leave;
}
/* Read data. */
err = stream_read_data (stream, buffer + 1, length);
if (err)
goto leave;
buffer[0] = 0x40;
*r_mpi = gcry_mpi_set_opaque (NULL, buffer, 8*(length+1));
buffer = NULL;
leave:
xfree (buffer);
return err;
}
/* Read a C-string from STREAM, store copy in STRING. */
static gpg_error_t
stream_read_cstring (estream_t stream, char **string)
{
return stream_read_string (stream, 0, (unsigned char **)string, NULL);
}
/* Write a binary string from STRING of size STRING_N to STREAM. */
static gpg_error_t
stream_write_string (estream_t stream,
const unsigned char *string, u32 string_n)
{
gpg_error_t err;
err = stream_write_uint32 (stream, string_n);
if (err)
goto out;
err = stream_write_data (stream, string, string_n);
out:
return err;
}
/* Write a C-string from STRING to STREAM. */
static gpg_error_t
stream_write_cstring (estream_t stream, const char *string)
{
gpg_error_t err;
err = stream_write_string (stream,
(const unsigned char *) string, strlen (string));
return err;
}
/* Read an MPI from STREAM, store it in MPINT. Depending on SECURE
use secure memory. */
static gpg_error_t
stream_read_mpi (estream_t stream, unsigned int secure, gcry_mpi_t *mpint)
{
unsigned char *mpi_data;
u32 mpi_data_size;
gpg_error_t err;
gcry_mpi_t mpi;
mpi_data = NULL;
err = stream_read_string (stream, secure, &mpi_data, &mpi_data_size);
if (err)
goto out;
/* To avoid excessive use of secure memory we check that an MPI is
not too large. */
if (mpi_data_size > 520)
{
log_error (_("ssh keys greater than %d bits are not supported\n"), 4096);
err = GPG_ERR_TOO_LARGE;
goto out;
}
err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_STD, mpi_data, mpi_data_size, NULL);
if (err)
goto out;
*mpint = mpi;
out:
xfree (mpi_data);
return err;
}
/* Write the MPI contained in MPINT to STREAM. */
static gpg_error_t
stream_write_mpi (estream_t stream, gcry_mpi_t mpint)
{
unsigned char *mpi_buffer;
size_t mpi_buffer_n;
gpg_error_t err;
mpi_buffer = NULL;
err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &mpi_buffer, &mpi_buffer_n, mpint);
if (err)
goto out;
err = stream_write_string (stream, mpi_buffer, mpi_buffer_n);
out:
xfree (mpi_buffer);
return err;
}
/* Copy data from SRC to DST until EOF is reached. */
static gpg_error_t
stream_copy (estream_t dst, estream_t src)
{
char buffer[BUFSIZ];
size_t bytes_read;
gpg_error_t err;
int ret;
err = 0;
while (1)
{
ret = es_read (src, buffer, sizeof (buffer), &bytes_read);
if (ret || (! bytes_read))
{
if (ret)
err = gpg_error_from_syserror ();
break;
}
ret = es_write (dst, buffer, bytes_read, NULL);
if (ret)
{
err = gpg_error_from_syserror ();
break;
}
}
return err;
}
/* Open the ssh control file and create it if not available. With
APPEND passed as true the file will be opened in append mode,
otherwise in read only mode. On success 0 is returned and a new
control file object stored at R_CF. On error an error code is
returned and NULL is stored at R_CF. */
static gpg_error_t
open_control_file (ssh_control_file_t *r_cf, int append)
{
gpg_error_t err;
ssh_control_file_t cf;
cf = xtrycalloc (1, sizeof *cf);
if (!cf)
{
err = gpg_error_from_syserror ();
goto leave;
}
/* Note: As soon as we start to use non blocking functions here
(i.e. where Pth might switch threads) we need to employ a
mutex. */
cf->fname = make_filename_try (gnupg_homedir (), SSH_CONTROL_FILE_NAME, NULL);
if (!cf->fname)
{
err = gpg_error_from_syserror ();
goto leave;
}
/* FIXME: With "a+" we are not able to check whether this will
be created and thus the blurb needs to be written first. */
cf->fp = fopen (cf->fname, append? "a+":"r");
if (!cf->fp && errno == ENOENT)
{
estream_t stream = es_fopen (cf->fname, "wx,mode=-rw-r");
if (!stream)
{
err = gpg_error_from_syserror ();
log_error (_("can't create '%s': %s\n"),
cf->fname, gpg_strerror (err));
goto leave;
}
es_fputs (sshcontrolblurb, stream);
es_fclose (stream);
cf->fp = fopen (cf->fname, append? "a+":"r");
}
if (!cf->fp)
{
err = gpg_error_from_syserror ();
log_error (_("can't open '%s': %s\n"),
cf->fname, gpg_strerror (err));
goto leave;
}
err = 0;
leave:
if (err && cf)
{
if (cf->fp)
fclose (cf->fp);
xfree (cf->fname);
xfree (cf);
}
else
*r_cf = cf;
return err;
}
static void
rewind_control_file (ssh_control_file_t cf)
{
fseek (cf->fp, 0, SEEK_SET);
cf->lnr = 0;
clearerr (cf->fp);
}
static void
close_control_file (ssh_control_file_t cf)
{
if (!cf)
return;
fclose (cf->fp);
xfree (cf->fname);
xfree (cf);
}
/* Read the next line from the control file and store the data in CF.
Returns 0 on success, GPG_ERR_EOF on EOF, or other error codes. */
static gpg_error_t
read_control_file_item (ssh_control_file_t cf)
{
int c, i, n;
char *p, *pend, line[256];
long ttl = 0;
cf->item.valid = 0;
clearerr (cf->fp);
do
{
if (!fgets (line, DIM(line)-1, cf->fp) )
{
if (feof (cf->fp))
return gpg_error (GPG_ERR_EOF);
return gpg_error_from_syserror ();
}
cf->lnr++;
if (!*line || line[strlen(line)-1] != '\n')
{
/* Eat until end of line */
while ( (c=getc (cf->fp)) != EOF && c != '\n')
;
return gpg_error (*line? GPG_ERR_LINE_TOO_LONG
: GPG_ERR_INCOMPLETE_LINE);
}
/* Allow for empty lines and spaces */
for (p=line; spacep (p); p++)
;
}
while (!*p || *p == '\n' || *p == '#');
cf->item.disabled = 0;
if (*p == '!')
{
cf->item.disabled = 1;
for (p++; spacep (p); p++)
;
}
for (i=0; hexdigitp (p) && i < 40; p++, i++)
cf->item.hexgrip[i] = (*p >= 'a'? (*p & 0xdf): *p);
cf->item.hexgrip[i] = 0;
if (i != 40 || !(spacep (p) || *p == '\n'))
{
log_error ("%s:%d: invalid formatted line\n", cf->fname, cf->lnr);
return gpg_error (GPG_ERR_BAD_DATA);
}
ttl = strtol (p, &pend, 10);
p = pend;
if (!(spacep (p) || *p == '\n') || (int)ttl < -1)
{
log_error ("%s:%d: invalid TTL value; assuming 0\n", cf->fname, cf->lnr);
cf->item.ttl = 0;
}
cf->item.ttl = ttl;
/* Now check for key-value pairs of the form NAME[=VALUE]. */
cf->item.confirm = 0;
while (*p)
{
for (; spacep (p) && *p != '\n'; p++)
;
if (!*p || *p == '\n')
break;
n = strcspn (p, "= \t\n");
if (p[n] == '=')
{
log_error ("%s:%d: assigning a value to a flag is not yet supported; "
"flag ignored\n", cf->fname, cf->lnr);
p++;
}
else if (n == 7 && !memcmp (p, "confirm", 7))
{
cf->item.confirm = 1;
}
else
log_error ("%s:%d: invalid flag '%.*s'; ignored\n",
cf->fname, cf->lnr, n, p);
p += n;
}
/* log_debug ("%s:%d: grip=%s ttl=%d%s%s\n", */
/* cf->fname, cf->lnr, */
/* cf->item.hexgrip, cf->item.ttl, */
/* cf->item.disabled? " disabled":"", */
/* cf->item.confirm? " confirm":""); */
cf->item.valid = 1;
return 0; /* Okay: valid entry found. */
}
/* Search the control file CF from the beginning until a matching
HEXGRIP is found; return success in this case and store true at
DISABLED if the found key has been disabled. If R_TTL is not NULL
a specified TTL for that key is stored there. If R_CONFIRM is not
NULL it is set to 1 if the key has the confirm flag set. */
static gpg_error_t
search_control_file (ssh_control_file_t cf, const char *hexgrip,
int *r_disabled, int *r_ttl, int *r_confirm)
{
gpg_error_t err;
assert (strlen (hexgrip) == 40 );
if (r_disabled)
*r_disabled = 0;
if (r_ttl)
*r_ttl = 0;
if (r_confirm)
*r_confirm = 0;
rewind_control_file (cf);
while (!(err=read_control_file_item (cf)))
{
if (!cf->item.valid)
continue; /* Should not happen. */
if (!strcmp (hexgrip, cf->item.hexgrip))
break;
}
if (!err)
{
if (r_disabled)
*r_disabled = cf->item.disabled;
if (r_ttl)
*r_ttl = cf->item.ttl;
if (r_confirm)
*r_confirm = cf->item.confirm;
}
return err;
}
/* Add an entry to the control file to mark the key with the keygrip
HEXGRIP as usable for SSH; i.e. it will be returned when ssh asks
for it. FMTFPR is the fingerprint string. This function is in
general used to add a key received through the ssh-add function.
We can assume that the user wants to allow ssh using this key. */
static gpg_error_t
add_control_entry (ctrl_t ctrl, ssh_key_type_spec_t *spec,
const char *hexgrip, gcry_sexp_t key,
int ttl, int confirm)
{
gpg_error_t err;
ssh_control_file_t cf;
int disabled;
char *fpr_md5 = NULL;
char *fpr_sha256 = NULL;
(void)ctrl;
err = open_control_file (&cf, 1);
if (err)
return err;
err = search_control_file (cf, hexgrip, &disabled, NULL, NULL);
if (err && gpg_err_code(err) == GPG_ERR_EOF)
{
struct tm *tp;
time_t atime = time (NULL);
err = ssh_get_fingerprint_string (key, GCRY_MD_MD5, &fpr_md5);
if (err)
goto out;
err = ssh_get_fingerprint_string (key, GCRY_MD_SHA256, &fpr_sha256);
if (err)
goto out;
/* Not yet in the file - add it. Because the file has been
opened in append mode, we simply need to write to it. */
tp = localtime (&atime);
fprintf (cf->fp,
("# %s key added on: %04d-%02d-%02d %02d:%02d:%02d\n"
"# Fingerprints: %s\n"
"# %s\n"
"%s %d%s\n"),
spec->name,
1900+tp->tm_year, tp->tm_mon+1, tp->tm_mday,
tp->tm_hour, tp->tm_min, tp->tm_sec,
fpr_md5, fpr_sha256, hexgrip, ttl, confirm? " confirm":"");
}
out:
xfree (fpr_md5);
xfree (fpr_sha256);
close_control_file (cf);
return 0;
}
/* Scan the sshcontrol file and return the TTL. */
static int
ttl_from_sshcontrol (const char *hexgrip)
{
ssh_control_file_t cf;
int disabled, ttl;
if (!hexgrip || strlen (hexgrip) != 40)
return 0; /* Wrong input: Use global default. */
if (open_control_file (&cf, 0))
return 0; /* Error: Use the global default TTL. */
if (search_control_file (cf, hexgrip, &disabled, &ttl, NULL)
|| disabled)
ttl = 0; /* Use the global default if not found or disabled. */
close_control_file (cf);
return ttl;
}
/* Scan the sshcontrol file and return the confirm flag. */
static int
confirm_flag_from_sshcontrol (const char *hexgrip)
{
ssh_control_file_t cf;
int disabled, confirm;
if (!hexgrip || strlen (hexgrip) != 40)
return 1; /* Wrong input: Better ask for confirmation. */
if (open_control_file (&cf, 0))
return 1; /* Error: Better ask for confirmation. */
if (search_control_file (cf, hexgrip, &disabled, NULL, &confirm)
|| disabled)
confirm = 0; /* If not found or disabled, there is no reason to
ask for confirmation. */
close_control_file (cf);
return confirm;
}
/* Open the ssh control file for reading. This is a public version of
open_control_file. The caller must use ssh_close_control_file to
release the returned handle. */
ssh_control_file_t
ssh_open_control_file (void)
{
ssh_control_file_t cf;
/* Then look at all the registered and non-disabled keys. */
if (open_control_file (&cf, 0))
return NULL;
return cf;
}
/* Close an ssh control file handle. This is the public version of
close_control_file. CF may be NULL. */
void
ssh_close_control_file (ssh_control_file_t cf)
{
close_control_file (cf);
}
/* Read the next item from the ssh control file. The function returns
0 if a item was read, GPG_ERR_EOF on eof or another error value.
R_HEXGRIP shall either be null or a BUFFER of at least 41 byte.
R_DISABLED, R_TTLm and R_CONFIRM return flags from the control
file; they are only set on success. */
gpg_error_t
ssh_read_control_file (ssh_control_file_t cf,
char *r_hexgrip,
int *r_disabled, int *r_ttl, int *r_confirm)
{
gpg_error_t err;
do
err = read_control_file_item (cf);
while (!err && !cf->item.valid);
if (!err)
{
if (r_hexgrip)
strcpy (r_hexgrip, cf->item.hexgrip);
if (r_disabled)
*r_disabled = cf->item.disabled;
if (r_ttl)
*r_ttl = cf->item.ttl;
if (r_confirm)
*r_confirm = cf->item.confirm;
}
return err;
}
/* Search for a key with HEXGRIP in sshcontrol and return all
info. */
gpg_error_t
ssh_search_control_file (ssh_control_file_t cf,
const char *hexgrip,
int *r_disabled, int *r_ttl, int *r_confirm)
{
gpg_error_t err;
int i;
const char *s;
char uphexgrip[41];
/* We need to make sure that HEXGRIP is all uppercase. The easiest
way to do this and also check its length is by copying to a
second buffer. */
for (i=0, s=hexgrip; i < 40 && *s; s++, i++)
uphexgrip[i] = *s >= 'a'? (*s & 0xdf): *s;
uphexgrip[i] = 0;
if (i != 40)
err = gpg_error (GPG_ERR_INV_LENGTH);
else
err = search_control_file (cf, uphexgrip, r_disabled, r_ttl, r_confirm);
if (gpg_err_code (err) == GPG_ERR_EOF)
err = gpg_error (GPG_ERR_NOT_FOUND);
return err;
}
/*
MPI lists.
*/
/* Free the list of MPIs MPI_LIST. */
static void
mpint_list_free (gcry_mpi_t *mpi_list)
{
if (mpi_list)
{
unsigned int i;
for (i = 0; mpi_list[i]; i++)
gcry_mpi_release (mpi_list[i]);
xfree (mpi_list);
}
}
/* Receive key material MPIs from STREAM according to KEY_SPEC;
depending on SECRET expect a public key or secret key. CERT is the
certificate blob used if KEY_SPEC indicates the certificate format;
it needs to be positioned to the end of the nonce. The newly
allocated list of MPIs is stored in MPI_LIST. Returns usual error
code. */
static gpg_error_t
ssh_receive_mpint_list (estream_t stream, int secret,
ssh_key_type_spec_t *spec, estream_t cert,
gcry_mpi_t **mpi_list)
{
const char *elems_public;
unsigned int elems_n;
const char *elems;
int elem_is_secret;
gcry_mpi_t *mpis = NULL;
gpg_error_t err = 0;
unsigned int i;
if (secret)
elems = spec->elems_key_secret;
else
elems = spec->elems_key_public;
elems_n = strlen (elems);
elems_public = spec->elems_key_public;
/* Check that either both, CERT and the WITH_CERT flag, are given or
none of them. */
if (!(!!(spec->flags & SPEC_FLAG_WITH_CERT) ^ !cert))
{
err = gpg_error (GPG_ERR_INV_CERT_OBJ);
goto out;
}
mpis = xtrycalloc (elems_n + 1, sizeof *mpis );
if (!mpis)
{
err = gpg_error_from_syserror ();
goto out;
}
elem_is_secret = 0;
for (i = 0; i < elems_n; i++)
{
if (secret)
elem_is_secret = !strchr (elems_public, elems[i]);
if (cert && !elem_is_secret)
err = stream_read_mpi (cert, elem_is_secret, &mpis[i]);
else
err = stream_read_mpi (stream, elem_is_secret, &mpis[i]);
if (err)
goto out;
}
*mpi_list = mpis;
mpis = NULL;
out:
if (err)
mpint_list_free (mpis);
return err;
}
/* Key modifier function for RSA. */
static gpg_error_t
ssh_key_modifier_rsa (const char *elems, gcry_mpi_t *mpis)
{
gcry_mpi_t p;
gcry_mpi_t q;
gcry_mpi_t u;
if (strcmp (elems, "nedupq"))
/* Modifying only necessary for secret keys. */
goto out;
u = mpis[3];
p = mpis[4];
q = mpis[5];
if (gcry_mpi_cmp (p, q) > 0)
{
/* P shall be smaller then Q! Swap primes. iqmp becomes u. */
gcry_mpi_t tmp;
tmp = mpis[4];
mpis[4] = mpis[5];
mpis[5] = tmp;
}
else
/* U needs to be recomputed. */
gcry_mpi_invm (u, p, q);
out:
return 0;
}
/* Signature encoder function for RSA. */
static gpg_error_t
ssh_signature_encoder_rsa (ssh_key_type_spec_t *spec,
estream_t signature_blob,
gcry_sexp_t s_signature)
{
gpg_error_t err = 0;
gcry_sexp_t valuelist = NULL;
gcry_sexp_t sublist = NULL;
gcry_mpi_t sig_value = NULL;
gcry_mpi_t *mpis = NULL;
const char *elems;
size_t elems_n;
int i;
unsigned char *data;
size_t data_n;
gcry_mpi_t s;
valuelist = gcry_sexp_nth (s_signature, 1);
if (!valuelist)
{
err = gpg_error (GPG_ERR_INV_SEXP);
goto out;
}
elems = spec->elems_signature;
elems_n = strlen (elems);
mpis = xtrycalloc (elems_n + 1, sizeof *mpis);
if (!mpis)
{
err = gpg_error_from_syserror ();
goto out;
}
for (i = 0; i < elems_n; i++)
{
sublist = gcry_sexp_find_token (valuelist, spec->elems_signature + i, 1);
if (!sublist)
{
err = gpg_error (GPG_ERR_INV_SEXP);
break;
}
sig_value = gcry_sexp_nth_mpi (sublist, 1, GCRYMPI_FMT_USG);
if (!sig_value)
{
err = gpg_error (GPG_ERR_INTERNAL); /* FIXME? */
break;
}
gcry_sexp_release (sublist);
sublist = NULL;
mpis[i] = sig_value;
}
if (err)
goto out;
/* RSA specific */
s = mpis[0];
err = gcry_mpi_aprint (GCRYMPI_FMT_USG, &data, &data_n, s);
if (err)
goto out;
err = stream_write_string (signature_blob, data, data_n);
xfree (data);
out:
gcry_sexp_release (valuelist);
gcry_sexp_release (sublist);
mpint_list_free (mpis);
return err;
}
/* Signature encoder function for DSA. */
static gpg_error_t
ssh_signature_encoder_dsa (ssh_key_type_spec_t *spec,
estream_t signature_blob,
gcry_sexp_t s_signature)
{
gpg_error_t err = 0;
gcry_sexp_t valuelist = NULL;
gcry_sexp_t sublist = NULL;
gcry_mpi_t sig_value = NULL;
gcry_mpi_t *mpis = NULL;
const char *elems;
size_t elems_n;
int i;
unsigned char buffer[SSH_DSA_SIGNATURE_PADDING * SSH_DSA_SIGNATURE_ELEMS];
unsigned char *data = NULL;
size_t data_n;
valuelist = gcry_sexp_nth (s_signature, 1);
if (!valuelist)
{
err = gpg_error (GPG_ERR_INV_SEXP);
goto out;
}
elems = spec->elems_signature;
elems_n = strlen (elems);
mpis = xtrycalloc (elems_n + 1, sizeof *mpis);
if (!mpis)
{
err = gpg_error_from_syserror ();
goto out;
}
for (i = 0; i < elems_n; i++)
{
sublist = gcry_sexp_find_token (valuelist, spec->elems_signature + i, 1);
if (!sublist)
{
err = gpg_error (GPG_ERR_INV_SEXP);
break;
}
sig_value = gcry_sexp_nth_mpi (sublist, 1, GCRYMPI_FMT_USG);
if (!sig_value)
{
err = gpg_error (GPG_ERR_INTERNAL); /* FIXME? */
break;
}
gcry_sexp_release (sublist);
sublist = NULL;
mpis[i] = sig_value;
}
if (err)
goto out;
/* DSA specific code. */
/* FIXME: Why this complicated code? Why collecting boths mpis in a
buffer instead of writing them out one after the other? */
for (i = 0; i < 2; i++)
{
err = gcry_mpi_aprint (GCRYMPI_FMT_USG, &data, &data_n, mpis[i]);
if (err)
break;
if (data_n > SSH_DSA_SIGNATURE_PADDING)
{
err = gpg_error (GPG_ERR_INTERNAL); /* FIXME? */
break;
}
memset (buffer + (i * SSH_DSA_SIGNATURE_PADDING), 0,
SSH_DSA_SIGNATURE_PADDING - data_n);
memcpy (buffer + (i * SSH_DSA_SIGNATURE_PADDING)
+ (SSH_DSA_SIGNATURE_PADDING - data_n), data, data_n);
xfree (data);
data = NULL;
}
if (err)
goto out;
err = stream_write_string (signature_blob, buffer, sizeof (buffer));
out:
xfree (data);
gcry_sexp_release (valuelist);
gcry_sexp_release (sublist);
mpint_list_free (mpis);
return err;
}
/* Signature encoder function for ECDSA. */
static gpg_error_t
ssh_signature_encoder_ecdsa (ssh_key_type_spec_t *spec,
estream_t stream, gcry_sexp_t s_signature)
{
gpg_error_t err = 0;
gcry_sexp_t valuelist = NULL;
gcry_sexp_t sublist = NULL;
gcry_mpi_t sig_value = NULL;
gcry_mpi_t *mpis = NULL;
const char *elems;
size_t elems_n;
int i;
unsigned char *data[2] = {NULL, NULL};
size_t data_n[2];
size_t innerlen;
valuelist = gcry_sexp_nth (s_signature, 1);
if (!valuelist)
{
err = gpg_error (GPG_ERR_INV_SEXP);
goto out;
}
elems = spec->elems_signature;
elems_n = strlen (elems);
mpis = xtrycalloc (elems_n + 1, sizeof *mpis);
if (!mpis)
{
err = gpg_error_from_syserror ();
goto out;
}
for (i = 0; i < elems_n; i++)
{
sublist = gcry_sexp_find_token (valuelist, spec->elems_signature + i, 1);
if (!sublist)
{
err = gpg_error (GPG_ERR_INV_SEXP);
break;
}
sig_value = gcry_sexp_nth_mpi (sublist, 1, GCRYMPI_FMT_USG);
if (!sig_value)
{
err = gpg_error (GPG_ERR_INTERNAL); /* FIXME? */
break;
}
gcry_sexp_release (sublist);
sublist = NULL;
mpis[i] = sig_value;
}
if (err)
goto out;
/* ECDSA specific */
innerlen = 0;
for (i = 0; i < DIM(data); i++)
{
err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &data[i], &data_n[i], mpis[i]);
if (err)
goto out;
innerlen += 4 + data_n[i];
}
err = stream_write_uint32 (stream, innerlen);
if (err)
goto out;
for (i = 0; i < DIM(data); i++)
{
err = stream_write_string (stream, data[i], data_n[i]);
if (err)
goto out;
}
out:
for (i = 0; i < DIM(data); i++)
xfree (data[i]);
gcry_sexp_release (valuelist);
gcry_sexp_release (sublist);
mpint_list_free (mpis);
return err;
}
/* Signature encoder function for EdDSA. */
static gpg_error_t
ssh_signature_encoder_eddsa (ssh_key_type_spec_t *spec,
estream_t stream, gcry_sexp_t s_signature)
{
gpg_error_t err = 0;
gcry_sexp_t valuelist = NULL;
gcry_sexp_t sublist = NULL;
const char *elems;
size_t elems_n;
int i;
unsigned char *data[2] = {NULL, NULL};
size_t data_n[2];
size_t totallen = 0;
valuelist = gcry_sexp_nth (s_signature, 1);
if (!valuelist)
{
err = gpg_error (GPG_ERR_INV_SEXP);
goto out;
}
elems = spec->elems_signature;
elems_n = strlen (elems);
if (elems_n != DIM(data))
{
err = gpg_error (GPG_ERR_INV_SEXP);
goto out;
}
for (i = 0; i < DIM(data); i++)
{
sublist = gcry_sexp_find_token (valuelist, spec->elems_signature + i, 1);
if (!sublist)
{
err = gpg_error (GPG_ERR_INV_SEXP);
break;
}
data[i] = gcry_sexp_nth_buffer (sublist, 1, &data_n[i]);
if (!data[i])
{
err = gpg_error (GPG_ERR_INTERNAL); /* FIXME? */
break;
}
totallen += data_n[i];
gcry_sexp_release (sublist);
sublist = NULL;
}
if (err)
goto out;
err = stream_write_uint32 (stream, totallen);
if (err)
goto out;
for (i = 0; i < DIM(data); i++)
{
err = stream_write_data (stream, data[i], data_n[i]);
if (err)
goto out;
}
out:
for (i = 0; i < DIM(data); i++)
xfree (data[i]);
gcry_sexp_release (valuelist);
gcry_sexp_release (sublist);
return err;
}
/*
S-Expressions.
*/
/* This function constructs a new S-Expression for the key identified
by the KEY_SPEC, SECRET, CURVE_NAME, MPIS, and COMMENT, which is to
be stored at R_SEXP. Returns an error code. */
static gpg_error_t
sexp_key_construct (gcry_sexp_t *r_sexp,
ssh_key_type_spec_t key_spec, int secret,
const char *curve_name, gcry_mpi_t *mpis,
const char *comment)
{
gpg_error_t err;
gcry_sexp_t sexp_new = NULL;
void *formatbuf = NULL;
void **arg_list = NULL;
estream_t format = NULL;
char *algo_name = NULL;
if ((key_spec.flags & SPEC_FLAG_IS_EdDSA))
{
/* It is much easier and more readable to use a separate code
path for EdDSA. */
if (!curve_name)
err = gpg_error (GPG_ERR_INV_CURVE);
else if (!mpis[0] || !gcry_mpi_get_flag (mpis[0], GCRYMPI_FLAG_OPAQUE))
err = gpg_error (GPG_ERR_BAD_PUBKEY);
else if (secret
&& (!mpis[1]
|| !gcry_mpi_get_flag (mpis[1], GCRYMPI_FLAG_OPAQUE)))
err = gpg_error (GPG_ERR_BAD_SECKEY);
else if (secret)
err = gcry_sexp_build (&sexp_new, NULL,
"(private-key(ecc(curve %s)"
"(flags eddsa)(q %m)(d %m))"
"(comment%s))",
curve_name,
mpis[0], mpis[1],
comment? comment:"");
else
err = gcry_sexp_build (&sexp_new, NULL,
"(public-key(ecc(curve %s)"
"(flags eddsa)(q %m))"
"(comment%s))",
curve_name,
mpis[0],
comment? comment:"");
}
else
{
const char *key_identifier[] = { "public-key", "private-key" };
int arg_idx;
const char *elems;
size_t elems_n;
unsigned int i, j;
if (secret)
elems = key_spec.elems_sexp_order;
else
elems = key_spec.elems_key_public;
elems_n = strlen (elems);
format = es_fopenmem (0, "a+b");
if (!format)
{
err = gpg_error_from_syserror ();
goto out;
}
/* Key identifier, algorithm identifier, mpis, comment, and a NULL
as a safeguard. */
arg_list = xtrymalloc (sizeof (*arg_list) * (2 + 1 + elems_n + 1 + 1));
if (!arg_list)
{
err = gpg_error_from_syserror ();
goto out;
}
arg_idx = 0;
es_fputs ("(%s(%s", format);
arg_list[arg_idx++] = &key_identifier[secret];
algo_name = xtrystrdup (gcry_pk_algo_name (key_spec.algo));
if (!algo_name)
{
err = gpg_error_from_syserror ();
goto out;
}
strlwr (algo_name);
arg_list[arg_idx++] = &algo_name;
if (curve_name)
{
es_fputs ("(curve%s)", format);
arg_list[arg_idx++] = &curve_name;
}
for (i = 0; i < elems_n; i++)
{
es_fprintf (format, "(%c%%m)", elems[i]);
if (secret)
{
for (j = 0; j < elems_n; j++)
if (key_spec.elems_key_secret[j] == elems[i])
break;
}
else
j = i;
arg_list[arg_idx++] = &mpis[j];
}
es_fputs (")(comment%s))", format);
arg_list[arg_idx++] = &comment;
arg_list[arg_idx] = NULL;
es_putc (0, format);
if (es_ferror (format))
{
err = gpg_error_from_syserror ();
goto out;
}
if (es_fclose_snatch (format, &formatbuf, NULL))
{
err = gpg_error_from_syserror ();
goto out;
}
format = NULL;
err = gcry_sexp_build_array (&sexp_new, NULL, formatbuf, arg_list);
}
if (!err)
*r_sexp = sexp_new;
out:
es_fclose (format);
xfree (arg_list);
xfree (formatbuf);
xfree (algo_name);
return err;
}
/* This function extracts the key from the s-expression SEXP according
to KEY_SPEC and stores it in ssh format at (R_BLOB, R_BLOBLEN). If
WITH_SECRET is true, the secret key parts are also extracted if
possible. Returns 0 on success or an error code. Note that data
stored at R_BLOB must be freed using es_free! */
static gpg_error_t
ssh_key_to_blob (gcry_sexp_t sexp, int with_secret,
ssh_key_type_spec_t key_spec,
void **r_blob, size_t *r_blob_size)
{
gpg_error_t err = 0;
gcry_sexp_t value_list = NULL;
gcry_sexp_t value_pair = NULL;
char *curve_name = NULL;
estream_t stream = NULL;
void *blob = NULL;
size_t blob_size;
const char *elems, *p_elems;
const char *data;
size_t datalen;
*r_blob = NULL;
*r_blob_size = 0;
stream = es_fopenmem (0, "r+b");
if (!stream)
{
err = gpg_error_from_syserror ();
goto out;
}
/* Get the type of the key extpression. */
data = gcry_sexp_nth_data (sexp, 0, &datalen);
if (!data)
{
err = gpg_error (GPG_ERR_INV_SEXP);
goto out;
}
if ((datalen == 10 && !strncmp (data, "public-key", 10))
|| (datalen == 21 && !strncmp (data, "protected-private-key", 21))
|| (datalen == 20 && !strncmp (data, "shadowed-private-key", 20)))
elems = key_spec.elems_key_public;
else if (datalen == 11 && !strncmp (data, "private-key", 11))
elems = with_secret? key_spec.elems_key_secret : key_spec.elems_key_public;
else
{
err = gpg_error (GPG_ERR_INV_SEXP);
goto out;
}
/* Get key value list. */
value_list = gcry_sexp_cadr (sexp);
if (!value_list)
{
err = gpg_error (GPG_ERR_INV_SEXP);
goto out;
}
/* Write the ssh algorithm identifier. */
if ((key_spec.flags & SPEC_FLAG_IS_ECDSA))
{
/* Parse the "curve" parameter. We currently expect the curve
name for ECC and not the parameters of the curve. This can
easily be changed but then we need to find the curve name
from the parameters using gcry_pk_get_curve. */
const char *mapped;
const char *sshname;
gcry_sexp_release (value_pair);
value_pair = gcry_sexp_find_token (value_list, "curve", 5);
if (!value_pair)
{
err = gpg_error (GPG_ERR_INV_CURVE);
goto out;
}
curve_name = gcry_sexp_nth_string (value_pair, 1);
if (!curve_name)
{
err = gpg_error (GPG_ERR_INV_CURVE); /* (Or out of core.) */
goto out;
}
/* Fixme: The mapping should be done by using gcry_pk_get_curve
et al to iterate over all name aliases. */
if (!strcmp (curve_name, "NIST P-256"))
mapped = "nistp256";
else if (!strcmp (curve_name, "NIST P-384"))
mapped = "nistp384";
else if (!strcmp (curve_name, "NIST P-521"))
mapped = "nistp521";
else
mapped = NULL;
if (mapped)
{
xfree (curve_name);
curve_name = xtrystrdup (mapped);
if (!curve_name)
{
err = gpg_error_from_syserror ();
goto out;
}
}
sshname = ssh_identifier_from_curve_name (curve_name);
if (!sshname)
{
err = gpg_error (GPG_ERR_UNKNOWN_CURVE);
goto out;
}
err = stream_write_cstring (stream, sshname);
if (err)
goto out;
err = stream_write_cstring (stream, curve_name);
if (err)
goto out;
}
else
{
/* Note: This is also used for EdDSA. */
err = stream_write_cstring (stream, key_spec.ssh_identifier);
if (err)
goto out;
}
/* Write the parameters. */
for (p_elems = elems; *p_elems; p_elems++)
{
gcry_sexp_release (value_pair);
value_pair = gcry_sexp_find_token (value_list, p_elems, 1);
if (!value_pair)
{
err = gpg_error (GPG_ERR_INV_SEXP);
goto out;
}
if ((key_spec.flags & SPEC_FLAG_IS_EdDSA))
{
data = gcry_sexp_nth_data (value_pair, 1, &datalen);
if (!data)
{
err = gpg_error (GPG_ERR_INV_SEXP);
goto out;
}
if (*p_elems == 'q' && datalen)
{ /* Remove the prefix 0x40. */
data++;
datalen--;
}
err = stream_write_string (stream, data, datalen);
if (err)
goto out;
}
else
{
gcry_mpi_t mpi;
/* Note that we need to use STD format; i.e. prepend a 0x00
to indicate a positive number if the high bit is set. */
mpi = gcry_sexp_nth_mpi (value_pair, 1, GCRYMPI_FMT_STD);
if (!mpi)
{
err = gpg_error (GPG_ERR_INV_SEXP);
goto out;
}
err = stream_write_mpi (stream, mpi);
gcry_mpi_release (mpi);
if (err)
goto out;
}
}
if (es_fclose_snatch (stream, &blob, &blob_size))
{
err = gpg_error_from_syserror ();
goto out;
}
stream = NULL;
*r_blob = blob;
blob = NULL;
*r_blob_size = blob_size;
out:
gcry_sexp_release (value_list);
gcry_sexp_release (value_pair);
xfree (curve_name);
es_fclose (stream);
es_free (blob);
return err;
}
/*
Key I/O.
*/
/* Search for a key specification entry. If SSH_NAME is not NULL,
search for an entry whose "ssh_name" is equal to SSH_NAME;
otherwise, search for an entry whose algorithm is equal to ALGO.
Store found entry in SPEC on success, return error otherwise. */
static gpg_error_t
ssh_key_type_lookup (const char *ssh_name, int algo,
ssh_key_type_spec_t *spec)
{
gpg_error_t err;
unsigned int i;
for (i = 0; i < DIM (ssh_key_types); i++)
if ((ssh_name && (! strcmp (ssh_name, ssh_key_types[i].ssh_identifier)))
|| algo == ssh_key_types[i].algo)
break;
if (i == DIM (ssh_key_types))
err = gpg_error (GPG_ERR_NOT_FOUND);
else
{
*spec = ssh_key_types[i];
err = 0;
}
return err;
}
/* Receive a key from STREAM, according to the key specification given
as KEY_SPEC. Depending on SECRET, receive a secret or a public
key. If READ_COMMENT is true, receive a comment string as well.
Constructs a new S-Expression from received data and stores it in
KEY_NEW. Returns zero on success or an error code. */
static gpg_error_t
ssh_receive_key (estream_t stream, gcry_sexp_t *key_new, int secret,
int read_comment, ssh_key_type_spec_t *key_spec)
{
gpg_error_t err;
char *key_type = NULL;
char *comment = NULL;
estream_t cert = NULL;
gcry_sexp_t key = NULL;
ssh_key_type_spec_t spec;
gcry_mpi_t *mpi_list = NULL;
const char *elems;
char *curve_name = NULL;
err = stream_read_cstring (stream, &key_type);
if (err)
goto out;
err = ssh_key_type_lookup (key_type, 0, &spec);
if (err)
goto out;
if ((spec.flags & SPEC_FLAG_WITH_CERT))
{
/* This is an OpenSSH certificate+private key. The certificate
is an SSH string and which we store in an estream object. */
unsigned char *buffer;
u32 buflen;
char *cert_key_type;
err = stream_read_string (stream, 0, &buffer, &buflen);
if (err)
goto out;
cert = es_fopenmem_init (0, "rb", buffer, buflen);
xfree (buffer);
if (!cert)
{
err = gpg_error_from_syserror ();
goto out;
}
/* Check that the key type matches. */
err = stream_read_cstring (cert, &cert_key_type);
if (err)
goto out;
if (strcmp (cert_key_type, key_type) )
{
xfree (cert_key_type);
log_error ("key types in received ssh certificate do not match\n");
err = gpg_error (GPG_ERR_INV_CERT_OBJ);
goto out;
}
xfree (cert_key_type);
/* Skip the nonce. */
err = stream_read_string (cert, 0, NULL, NULL);
if (err)
goto out;
}
if ((spec.flags & SPEC_FLAG_IS_EdDSA))
{
/* The format of an EdDSA key is:
* string key_type ("ssh-ed25519")
* string public_key
* string private_key
*
* Note that the private key is the concatenation of the private
* key with the public key. Thus there's are 64 bytes; however
* we only want the real 32 byte private key - Libgcrypt expects
* this.
*/
mpi_list = xtrycalloc (3, sizeof *mpi_list);
if (!mpi_list)
{
err = gpg_error_from_syserror ();
goto out;
}
err = stream_read_blob (cert? cert : stream, 0, &mpi_list[0]);
if (err)
goto out;
if (secret)
{
u32 len = 0;
unsigned char *buffer;
/* Read string length. */
err = stream_read_uint32 (stream, &len);
if (err)
goto out;
if (len != 32 && len != 64)
{
err = gpg_error (GPG_ERR_BAD_SECKEY);
goto out;
}
buffer = xtrymalloc_secure (32);
if (!buffer)
{
err = gpg_error_from_syserror ();
goto out;
}
err = stream_read_data (stream, buffer, 32);
if (err)
{
xfree (buffer);
goto out;
}
mpi_list[1] = gcry_mpi_set_opaque (NULL, buffer, 8*32);
buffer = NULL;
if (len == 64)
{
err = stream_read_skip (stream, 32);
if (err)
goto out;
}
}
}
else if ((spec.flags & SPEC_FLAG_IS_ECDSA))
{
/* The format of an ECDSA key is:
* string key_type ("ecdsa-sha2-nistp256" |
* "ecdsa-sha2-nistp384" |
* "ecdsa-sha2-nistp521" )
* string ecdsa_curve_name
* string ecdsa_public_key
* mpint ecdsa_private
*
* Note that we use the mpint reader instead of the string
* reader for ecsa_public_key. For the certificate variante
* ecdsa_curve_name+ecdsa_public_key are replaced by the
* certificate.
*/
unsigned char *buffer;
const char *mapped;
err = stream_read_string (cert? cert : stream, 0, &buffer, NULL);
if (err)
goto out;
curve_name = buffer;
/* Fixme: Check that curve_name matches the keytype. */
/* Because Libgcrypt < 1.6 has no support for the "nistpNNN"
curve names, we need to translate them here to Libgcrypt's
native names. */
if (!strcmp (curve_name, "nistp256"))
mapped = "NIST P-256";
else if (!strcmp (curve_name, "nistp384"))
mapped = "NIST P-384";
else if (!strcmp (curve_name, "nistp521"))
mapped = "NIST P-521";
else
mapped = NULL;
if (mapped)
{
xfree (curve_name);
curve_name = xtrystrdup (mapped);
if (!curve_name)
{
err = gpg_error_from_syserror ();
goto out;
}
}
err = ssh_receive_mpint_list (stream, secret, &spec, cert, &mpi_list);
if (err)
goto out;
}
else
{
err = ssh_receive_mpint_list (stream, secret, &spec, cert, &mpi_list);
if (err)
goto out;
}
if (read_comment)
{
err = stream_read_cstring (stream, &comment);
if (err)
goto out;
}
if (secret)
elems = spec.elems_key_secret;
else
elems = spec.elems_key_public;
if (spec.key_modifier)
{
err = (*spec.key_modifier) (elems, mpi_list);
if (err)
goto out;
}
if ((spec.flags & SPEC_FLAG_IS_EdDSA))
{
if (secret)
{
err = gcry_sexp_build (&key, NULL,
"(private-key(ecc(curve \"Ed25519\")"
"(flags eddsa)(q %m)(d %m))"
"(comment%s))",
mpi_list[0], mpi_list[1],
comment? comment:"");
}
else
{
err = gcry_sexp_build (&key, NULL,
"(public-key(ecc(curve \"Ed25519\")"
"(flags eddsa)(q %m))"
"(comment%s))",
mpi_list[0],
comment? comment:"");
}
}
else
{
err = sexp_key_construct (&key, spec, secret, curve_name, mpi_list,
comment? comment:"");
if (err)
goto out;
}
if (key_spec)
*key_spec = spec;
*key_new = key;
out:
es_fclose (cert);
mpint_list_free (mpi_list);
xfree (curve_name);
xfree (key_type);
xfree (comment);
return err;
}
/* Write the public key from KEY to STREAM in SSH key format. If
OVERRIDE_COMMENT is not NULL, it will be used instead of the
comment stored in the key. */
static gpg_error_t
ssh_send_key_public (estream_t stream, gcry_sexp_t key,
const char *override_comment)
{
ssh_key_type_spec_t spec;
int algo;
char *comment = NULL;
void *blob = NULL;
size_t bloblen;
gpg_error_t err = 0;
algo = get_pk_algo_from_key (key);
if (algo == 0)
goto out;
err = ssh_key_type_lookup (NULL, algo, &spec);
if (err)
goto out;
err = ssh_key_to_blob (key, 0, spec, &blob, &bloblen);
if (err)
goto out;
err = stream_write_string (stream, blob, bloblen);
if (err)
goto out;
if (override_comment)
err = stream_write_cstring (stream, override_comment);
else
{
err = ssh_key_extract_comment (key, &comment);
if (err)
err = stream_write_cstring (stream, "(none)");
else
err = stream_write_cstring (stream, comment);
}
if (err)
goto out;
out:
xfree (comment);
es_free (blob);
return err;
}
/* Read a public key out of BLOB/BLOB_SIZE according to the key
specification given as KEY_SPEC, storing the new key in KEY_PUBLIC.
Returns zero on success or an error code. */
static gpg_error_t
ssh_read_key_public_from_blob (unsigned char *blob, size_t blob_size,
gcry_sexp_t *key_public,
ssh_key_type_spec_t *key_spec)
{
gpg_error_t err;
estream_t blob_stream;
blob_stream = es_fopenmem (0, "r+b");
if (!blob_stream)
{
err = gpg_error_from_syserror ();
goto out;
}
err = stream_write_data (blob_stream, blob, blob_size);
if (err)
goto out;
err = es_fseek (blob_stream, 0, SEEK_SET);
if (err)
goto out;
err = ssh_receive_key (blob_stream, key_public, 0, 0, key_spec);
out:
es_fclose (blob_stream);
return err;
}
/* This function calculates the key grip for the key contained in the
S-Expression KEY and writes it to BUFFER, which must be large
enough to hold it. Returns usual error code. */
static gpg_error_t
ssh_key_grip (gcry_sexp_t key, unsigned char *buffer)
{
if (!gcry_pk_get_keygrip (key, buffer))
{
gpg_error_t err = gcry_pk_testkey (key);
return err? err : gpg_error (GPG_ERR_INTERNAL);
}
return 0;
}
static gpg_error_t
card_key_list (ctrl_t ctrl, char **r_serialno, strlist_t *result)
{
gpg_error_t err;
*r_serialno = NULL;
*result = NULL;
err = agent_card_serialno (ctrl, r_serialno, NULL);
if (err)
{
if (gpg_err_code (err) != GPG_ERR_ENODEV && opt.verbose)
log_info (_("error getting serial number of card: %s\n"),
gpg_strerror (err));
/* Nothing available. */
return 0;
}
err = agent_card_cardlist (ctrl, result);
if (err)
{
xfree (*r_serialno);
*r_serialno = NULL;
}
return err;
}
/* Check whether a smartcard is available and whether it has a usable
key. Store a copy of that key at R_PK and return 0. If no key is
available store NULL at R_PK and return an error code. If CARDSN
is not NULL, a string with the serial number of the card will be
a malloced and stored there. */
static gpg_error_t
card_key_available (ctrl_t ctrl, gcry_sexp_t *r_pk, char **cardsn)
{
gpg_error_t err;
char *authkeyid;
char *serialno = NULL;
unsigned char *pkbuf;
size_t pkbuflen;
gcry_sexp_t s_pk;
unsigned char grip[20];
*r_pk = NULL;
if (cardsn)
*cardsn = NULL;
/* First see whether a card is available and whether the application
is supported. */
err = agent_card_getattr (ctrl, "$AUTHKEYID", &authkeyid);
if ( gpg_err_code (err) == GPG_ERR_CARD_REMOVED )
{
/* Ask for the serial number to reset the card. */
err = agent_card_serialno (ctrl, &serialno, NULL);
if (err)
{
if (opt.verbose)
log_info (_("error getting serial number of card: %s\n"),
gpg_strerror (err));
return err;
}
log_info (_("detected card with S/N: %s\n"), serialno);
err = agent_card_getattr (ctrl, "$AUTHKEYID", &authkeyid);
}
if (err)
{
log_error (_("no authentication key for ssh on card: %s\n"),
gpg_strerror (err));
xfree (serialno);
return err;
}
/* Get the S/N if we don't have it yet. Use the fast getattr method. */
if (!serialno && (err = agent_card_getattr (ctrl, "SERIALNO", &serialno)) )
{
log_error (_("error getting serial number of card: %s\n"),
gpg_strerror (err));
xfree (authkeyid);
return err;
}
/* Read the public key. */
err = agent_card_readkey (ctrl, authkeyid, &pkbuf);
if (err)
{
if (opt.verbose)
log_info (_("no suitable card key found: %s\n"), gpg_strerror (err));
xfree (serialno);
xfree (authkeyid);
return err;
}
pkbuflen = gcry_sexp_canon_len (pkbuf, 0, NULL, NULL);
err = gcry_sexp_sscan (&s_pk, NULL, (char*)pkbuf, pkbuflen);
if (err)
{
log_error ("failed to build S-Exp from received card key: %s\n",
gpg_strerror (err));
xfree (pkbuf);
xfree (serialno);
xfree (authkeyid);
return err;
}
err = ssh_key_grip (s_pk, grip);
if (err)
{
log_debug ("error computing keygrip from received card key: %s\n",
gcry_strerror (err));
xfree (pkbuf);
gcry_sexp_release (s_pk);
xfree (serialno);
xfree (authkeyid);
return err;
}
if ( agent_key_available (grip) )
{
/* (Shadow)-key is not available in our key storage. */
err = agent_write_shadow_key (grip, serialno, authkeyid, pkbuf, 0);
if (err)
{
xfree (pkbuf);
gcry_sexp_release (s_pk);
xfree (serialno);
xfree (authkeyid);
return err;
}
}
if (cardsn)
{
char *dispsn;
/* If the card handler is able to return a short serialnumber,
use that one, else use the complete serialno. */
if (!agent_card_getattr (ctrl, "$DISPSERIALNO", &dispsn))
{
*cardsn = xtryasprintf ("cardno:%s", dispsn);
xfree (dispsn);
}
else
*cardsn = xtryasprintf ("cardno:%s", serialno);
if (!*cardsn)
{
err = gpg_error_from_syserror ();
xfree (pkbuf);
gcry_sexp_release (s_pk);
xfree (serialno);
xfree (authkeyid);
return err;
}
}
xfree (pkbuf);
xfree (serialno);
xfree (authkeyid);
*r_pk = s_pk;
return 0;
}
/*
Request handler. Each handler is provided with a CTRL context, a
REQUEST object and a RESPONSE object. The actual request is to be
read from REQUEST, the response needs to be written to RESPONSE.
*/
/* Handler for the "request_identities" command. */
static gpg_error_t
ssh_handler_request_identities (ctrl_t ctrl,
estream_t request, estream_t response)
{
u32 key_counter;
estream_t key_blobs;
gcry_sexp_t key_public;
gpg_error_t err;
int ret;
ssh_control_file_t cf = NULL;
gpg_error_t ret_err;
(void)request;
/* Prepare buffer stream. */
key_public = NULL;
key_counter = 0;
key_blobs = es_fopenmem (0, "r+b");
if (! key_blobs)
{
err = gpg_error_from_syserror ();
goto out;
}
/* First check whether a key is currently available in the card
reader - this should be allowed even without being listed in
sshcontrol. */
if (!opt.disable_scdaemon)
{
char *serialno;
strlist_t card_list, sl;
err = card_key_list (ctrl, &serialno, &card_list);
if (err)
{
if (opt.verbose)
log_info (_("error getting list of cards: %s\n"),
gpg_strerror (err));
goto scd_out;
}
for (sl = card_list; sl; sl = sl->next)
{
char *serialno0;
char *cardsn;
err = agent_card_serialno (ctrl, &serialno0, sl->d);
if (err)
{
if (opt.verbose)
log_info (_("error getting serial number of card: %s\n"),
gpg_strerror (err));
continue;
}
xfree (serialno0);
if (card_key_available (ctrl, &key_public, &cardsn))
continue;
err = ssh_send_key_public (key_blobs, key_public, cardsn);
gcry_sexp_release (key_public);
key_public = NULL;
xfree (cardsn);
if (err)
{
xfree (serialno);
free_strlist (card_list);
goto out;
}
key_counter++;
}
xfree (serialno);
free_strlist (card_list);
}
scd_out:
/* Then look at all the registered and non-disabled keys. */
err = open_control_file (&cf, 0);
if (err)
goto out;
while (!read_control_file_item (cf))
{
unsigned char grip[20];
if (!cf->item.valid)
continue; /* Should not happen. */
if (cf->item.disabled)
continue;
assert (strlen (cf->item.hexgrip) == 40);
hex2bin (cf->item.hexgrip, grip, sizeof (grip));
err = agent_public_key_from_file (ctrl, grip, &key_public);
if (err)
{
log_error ("%s:%d: key '%s' skipped: %s\n",
cf->fname, cf->lnr, cf->item.hexgrip,
gpg_strerror (err));
continue;
}
err = ssh_send_key_public (key_blobs, key_public, NULL);
if (err)
goto out;
gcry_sexp_release (key_public);
key_public = NULL;
key_counter++;
}
err = 0;
ret = es_fseek (key_blobs, 0, SEEK_SET);
if (ret)
{
err = gpg_error_from_syserror ();
goto out;
}
out:
/* Send response. */
gcry_sexp_release (key_public);
if (!err)
{
ret_err = stream_write_byte (response, SSH_RESPONSE_IDENTITIES_ANSWER);
if (!ret_err)
ret_err = stream_write_uint32 (response, key_counter);
if (!ret_err)
ret_err = stream_copy (response, key_blobs);
}
else
{
ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE);
}
es_fclose (key_blobs);
close_control_file (cf);
return ret_err;
}
/* This function hashes the data contained in DATA of size DATA_N
according to the message digest algorithm specified by MD_ALGORITHM
and writes the message digest to HASH, which needs to large enough
for the digest. */
static gpg_error_t
data_hash (unsigned char *data, size_t data_n,
int md_algorithm, unsigned char *hash)
{
gcry_md_hash_buffer (md_algorithm, hash, data, data_n);
return 0;
}
/* This function signs the data described by CTRL. If HASH is not
NULL, (HASH,HASHLEN) overrides the hash stored in CTRL. This is to
allow the use of signature algorithms that implement the hashing
internally (e.g. Ed25519). On success the created signature is
stored in ssh format at R_SIG and it's size at R_SIGLEN; the caller
- must use es_free to releaase this memory. */
+ must use es_free to release this memory. */
static gpg_error_t
data_sign (ctrl_t ctrl, ssh_key_type_spec_t *spec,
const void *hash, size_t hashlen,
unsigned char **r_sig, size_t *r_siglen)
{
gpg_error_t err;
gcry_sexp_t signature_sexp = NULL;
estream_t stream = NULL;
void *blob = NULL;
size_t bloblen;
char hexgrip[40+1];
*r_sig = NULL;
*r_siglen = 0;
/* Quick check to see whether we have a valid keygrip and convert it
to hex. */
if (!ctrl->have_keygrip)
{
err = gpg_error (GPG_ERR_NO_SECKEY);
goto out;
}
bin2hex (ctrl->keygrip, 20, hexgrip);
/* Ask for confirmation if needed. */
if (confirm_flag_from_sshcontrol (hexgrip))
{
gcry_sexp_t key;
char *fpr, *prompt;
char *comment = NULL;
err = agent_raw_key_from_file (ctrl, ctrl->keygrip, &key);
if (err)
goto out;
err = ssh_get_fingerprint_string (key, opt.ssh_fingerprint_digest, &fpr);
if (!err)
{
gcry_sexp_t tmpsxp = gcry_sexp_find_token (key, "comment", 0);
if (tmpsxp)
comment = gcry_sexp_nth_string (tmpsxp, 1);
gcry_sexp_release (tmpsxp);
}
gcry_sexp_release (key);
if (err)
goto out;
prompt = xtryasprintf (L_("An ssh process requested the use of key%%0A"
" %s%%0A"
" (%s)%%0A"
"Do you want to allow this?"),
fpr, comment? comment:"");
xfree (fpr);
gcry_free (comment);
err = agent_get_confirmation (ctrl, prompt, L_("Allow"), L_("Deny"), 0);
xfree (prompt);
if (err)
goto out;
}
/* Create signature. */
ctrl->use_auth_call = 1;
err = agent_pksign_do (ctrl, NULL,
L_("Please enter the passphrase "
"for the ssh key%%0A %F%%0A (%c)"),
&signature_sexp,
CACHE_MODE_SSH, ttl_from_sshcontrol,
hash, hashlen);
ctrl->use_auth_call = 0;
if (err)
goto out;
stream = es_fopenmem (0, "r+b");
if (!stream)
{
err = gpg_error_from_syserror ();
goto out;
}
err = stream_write_cstring (stream, spec->ssh_identifier);
if (err)
goto out;
err = spec->signature_encoder (spec, stream, signature_sexp);
if (err)
goto out;
err = es_fclose_snatch (stream, &blob, &bloblen);
if (err)
goto out;
stream = NULL;
*r_sig = blob; blob = NULL;
*r_siglen = bloblen;
out:
xfree (blob);
es_fclose (stream);
gcry_sexp_release (signature_sexp);
return err;
}
/* Handler for the "sign_request" command. */
static gpg_error_t
ssh_handler_sign_request (ctrl_t ctrl, estream_t request, estream_t response)
{
gcry_sexp_t key = NULL;
ssh_key_type_spec_t spec;
unsigned char hash[MAX_DIGEST_LEN];
unsigned int hash_n;
unsigned char key_grip[20];
unsigned char *key_blob = NULL;
u32 key_blob_size;
unsigned char *data = NULL;
unsigned char *sig = NULL;
size_t sig_n;
u32 data_size;
gpg_error_t err;
gpg_error_t ret_err;
int hash_algo;
/* Receive key. */
err = stream_read_string (request, 0, &key_blob, &key_blob_size);
if (err)
goto out;
err = ssh_read_key_public_from_blob (key_blob, key_blob_size, &key, &spec);
if (err)
goto out;
/* Receive data to sign. */
err = stream_read_string (request, 0, &data, &data_size);
if (err)
goto out;
/* Flag processing. */
{
u32 flags;
err = stream_read_uint32 (request, &flags);
if (err)
goto out;
if (spec.algo == GCRY_PK_RSA)
{
if ((flags & SSH_AGENT_RSA_SHA2_512))
{
flags &= ~SSH_AGENT_RSA_SHA2_512;
spec.ssh_identifier = "rsa-sha2-512";
spec.hash_algo = GCRY_MD_SHA512;
}
if ((flags & SSH_AGENT_RSA_SHA2_256))
{
/* Note: We prefer SHA256 over SHA512. */
flags &= ~SSH_AGENT_RSA_SHA2_256;
spec.ssh_identifier = "rsa-sha2-256";
spec.hash_algo = GCRY_MD_SHA256;
}
}
/* Some flag is present that we do not know about. Note that
* processed or known flags have been cleared at this point. */
if (flags)
{
err = gpg_error (GPG_ERR_UNKNOWN_OPTION);
goto out;
}
}
hash_algo = spec.hash_algo;
if (!hash_algo)
hash_algo = GCRY_MD_SHA1; /* Use the default. */
ctrl->digest.algo = hash_algo;
if ((spec.flags & SPEC_FLAG_USE_PKCS1V2))
ctrl->digest.raw_value = 0;
else
ctrl->digest.raw_value = 1;
/* Calculate key grip. */
err = ssh_key_grip (key, key_grip);
if (err)
goto out;
ctrl->have_keygrip = 1;
memcpy (ctrl->keygrip, key_grip, 20);
/* Hash data unless we use EdDSA. */
if ((spec.flags & SPEC_FLAG_IS_EdDSA))
{
ctrl->digest.valuelen = 0;
}
else
{
hash_n = gcry_md_get_algo_dlen (hash_algo);
if (!hash_n)
{
err = gpg_error (GPG_ERR_INTERNAL);
goto out;
}
err = data_hash (data, data_size, hash_algo, hash);
if (err)
goto out;
memcpy (ctrl->digest.value, hash, hash_n);
ctrl->digest.valuelen = hash_n;
}
/* Sign data. */
if ((spec.flags & SPEC_FLAG_IS_EdDSA))
err = data_sign (ctrl, &spec, data, data_size, &sig, &sig_n);
else
err = data_sign (ctrl, &spec, NULL, 0, &sig, &sig_n);
out:
/* Done. */
if (!err)
{
ret_err = stream_write_byte (response, SSH_RESPONSE_SIGN_RESPONSE);
if (ret_err)
goto leave;
ret_err = stream_write_string (response, sig, sig_n);
if (ret_err)
goto leave;
}
else
{
log_error ("ssh sign request failed: %s <%s>\n",
gpg_strerror (err), gpg_strsource (err));
ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE);
if (ret_err)
goto leave;
}
leave:
gcry_sexp_release (key);
xfree (key_blob);
xfree (data);
es_free (sig);
return ret_err;
}
/* This function extracts the comment contained in the key
s-expression KEY and stores a copy in COMMENT. Returns usual error
code. */
static gpg_error_t
ssh_key_extract_comment (gcry_sexp_t key, char **r_comment)
{
gcry_sexp_t comment_list;
*r_comment = NULL;
comment_list = gcry_sexp_find_token (key, "comment", 0);
if (!comment_list)
return gpg_error (GPG_ERR_INV_SEXP);
*r_comment = gcry_sexp_nth_string (comment_list, 1);
gcry_sexp_release (comment_list);
if (!*r_comment)
return gpg_error (GPG_ERR_INV_SEXP);
return 0;
}
/* This function converts the key contained in the S-Expression KEY
into a buffer, which is protected by the passphrase PASSPHRASE.
If PASSPHRASE is the empty passphrase, the key is not protected.
Returns usual error code. */
static gpg_error_t
ssh_key_to_protected_buffer (gcry_sexp_t key, const char *passphrase,
unsigned char **buffer, size_t *buffer_n)
{
unsigned char *buffer_new;
unsigned int buffer_new_n;
gpg_error_t err;
buffer_new_n = gcry_sexp_sprint (key, GCRYSEXP_FMT_CANON, NULL, 0);
buffer_new = xtrymalloc_secure (buffer_new_n);
if (! buffer_new)
{
err = gpg_error_from_syserror ();
goto out;
}
gcry_sexp_sprint (key, GCRYSEXP_FMT_CANON, buffer_new, buffer_new_n);
/* FIXME: guarantee? */
if (*passphrase)
err = agent_protect (buffer_new, passphrase, buffer, buffer_n, 0, -1);
else
{
/* The key derivation function does not support zero length
* strings. Store key unprotected if the user wishes so. */
*buffer = buffer_new;
*buffer_n = buffer_new_n;
buffer_new = NULL;
err = 0;
}
out:
xfree (buffer_new);
return err;
}
/* Callback function to compare the first entered PIN with the one
currently being entered. */
static gpg_error_t
reenter_compare_cb (struct pin_entry_info_s *pi)
{
const char *pin1 = pi->check_cb_arg;
if (!strcmp (pin1, pi->pin))
return 0; /* okay */
return gpg_error (GPG_ERR_BAD_PASSPHRASE);
}
/* Store the ssh KEY into our local key storage and protect it after
asking for a passphrase. Cache that passphrase. TTL is the
maximum caching time for that key. If the key already exists in
our key storage, don't do anything. When entering a key also add
an entry to the sshcontrol file. */
static gpg_error_t
ssh_identity_register (ctrl_t ctrl, ssh_key_type_spec_t *spec,
gcry_sexp_t key, int ttl, int confirm)
{
gpg_error_t err;
unsigned char key_grip_raw[20];
char key_grip[41];
unsigned char *buffer = NULL;
size_t buffer_n;
char *description = NULL;
const char *description2 = L_("Please re-enter this passphrase");
char *comment = NULL;
char *key_fpr = NULL;
const char *initial_errtext = NULL;
struct pin_entry_info_s *pi = NULL;
struct pin_entry_info_s *pi2 = NULL;
err = ssh_key_grip (key, key_grip_raw);
if (err)
goto out;
bin2hex (key_grip_raw, 20, key_grip);
err = ssh_get_fingerprint_string (key, opt.ssh_fingerprint_digest, &key_fpr);
if (err)
goto out;
/* Check whether the key is already in our key storage. Don't do
anything then besides (re-)adding it to sshcontrol. */
if ( !agent_key_available (key_grip_raw) )
goto key_exists; /* Yes, key is available. */
err = ssh_key_extract_comment (key, &comment);
if (err)
goto out;
if ( asprintf (&description,
L_("Please enter a passphrase to protect"
" the received secret key%%0A"
" %s%%0A"
" %s%%0A"
"within gpg-agent's key storage"),
key_fpr, comment ? comment : "") < 0)
{
err = gpg_error_from_syserror ();
goto out;
}
pi = gcry_calloc_secure (1, sizeof (*pi) + MAX_PASSPHRASE_LEN + 1);
if (!pi)
{
err = gpg_error_from_syserror ();
goto out;
}
pi2 = gcry_calloc_secure (1, sizeof (*pi2) + MAX_PASSPHRASE_LEN + 1);
if (!pi2)
{
err = gpg_error_from_syserror ();
goto out;
}
pi->max_length = MAX_PASSPHRASE_LEN + 1;
pi->max_tries = 1;
pi->with_repeat = 1;
pi2->max_length = MAX_PASSPHRASE_LEN + 1;
pi2->max_tries = 1;
pi2->check_cb = reenter_compare_cb;
pi2->check_cb_arg = pi->pin;
next_try:
err = agent_askpin (ctrl, description, NULL, initial_errtext, pi, NULL, 0);
initial_errtext = NULL;
if (err)
goto out;
/* Unless the passphrase is empty or the pinentry told us that
it already did the repetition check, ask to confirm it. */
if (*pi->pin && !pi->repeat_okay)
{
err = agent_askpin (ctrl, description2, NULL, NULL, pi2, NULL, 0);
if (gpg_err_code (err) == GPG_ERR_BAD_PASSPHRASE)
{ /* The re-entered one did not match and the user did not
hit cancel. */
initial_errtext = L_("does not match - try again");
goto next_try;
}
}
err = ssh_key_to_protected_buffer (key, pi->pin, &buffer, &buffer_n);
if (err)
goto out;
/* Store this key to our key storage. */
err = agent_write_private_key (key_grip_raw, buffer, buffer_n, 0);
if (err)
goto out;
/* Cache this passphrase. */
err = agent_put_cache (ctrl, key_grip, CACHE_MODE_SSH, pi->pin, ttl);
if (err)
goto out;
key_exists:
/* And add an entry to the sshcontrol file. */
err = add_control_entry (ctrl, spec, key_grip, key, ttl, confirm);
out:
if (pi2 && pi2->max_length)
wipememory (pi2->pin, pi2->max_length);
xfree (pi2);
if (pi && pi->max_length)
wipememory (pi->pin, pi->max_length);
xfree (pi);
xfree (buffer);
xfree (comment);
xfree (key_fpr);
xfree (description);
return err;
}
/* This function removes the key contained in the S-Expression KEY
from the local key storage, in case it exists there. Returns usual
error code. FIXME: this function is a stub. */
static gpg_error_t
ssh_identity_drop (gcry_sexp_t key)
{
unsigned char key_grip[21] = { 0 };
gpg_error_t err;
err = ssh_key_grip (key, key_grip);
if (err)
goto out;
key_grip[sizeof (key_grip) - 1] = 0;
/* FIXME: What to do here - forgetting the passphrase or deleting
the key from key cache? */
out:
return err;
}
/* Handler for the "add_identity" command. */
static gpg_error_t
ssh_handler_add_identity (ctrl_t ctrl, estream_t request, estream_t response)
{
gpg_error_t ret_err;
ssh_key_type_spec_t spec;
gpg_error_t err;
gcry_sexp_t key;
unsigned char b;
int confirm;
int ttl;
confirm = 0;
key = NULL;
ttl = 0;
/* FIXME? */
err = ssh_receive_key (request, &key, 1, 1, &spec);
if (err)
goto out;
while (1)
{
err = stream_read_byte (request, &b);
if (err)
{
if (gpg_err_code (err) == GPG_ERR_EOF)
err = 0;
break;
}
switch (b)
{
case SSH_OPT_CONSTRAIN_LIFETIME:
{
u32 n = 0;
err = stream_read_uint32 (request, &n);
if (! err)
ttl = n;
break;
}
case SSH_OPT_CONSTRAIN_CONFIRM:
{
confirm = 1;
break;
}
default:
/* FIXME: log/bad? */
break;
}
}
if (err)
goto out;
err = ssh_identity_register (ctrl, &spec, key, ttl, confirm);
out:
gcry_sexp_release (key);
if (! err)
ret_err = stream_write_byte (response, SSH_RESPONSE_SUCCESS);
else
ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE);
return ret_err;
}
/* Handler for the "remove_identity" command. */
static gpg_error_t
ssh_handler_remove_identity (ctrl_t ctrl,
estream_t request, estream_t response)
{
unsigned char *key_blob;
u32 key_blob_size;
gcry_sexp_t key;
gpg_error_t ret_err;
gpg_error_t err;
(void)ctrl;
/* Receive key. */
key_blob = NULL;
key = NULL;
err = stream_read_string (request, 0, &key_blob, &key_blob_size);
if (err)
goto out;
err = ssh_read_key_public_from_blob (key_blob, key_blob_size, &key, NULL);
if (err)
goto out;
err = ssh_identity_drop (key);
out:
xfree (key_blob);
gcry_sexp_release (key);
if (! err)
ret_err = stream_write_byte (response, SSH_RESPONSE_SUCCESS);
else
ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE);
return ret_err;
}
/* FIXME: stub function. Actually useful? */
static gpg_error_t
ssh_identities_remove_all (void)
{
gpg_error_t err;
err = 0;
/* FIXME: shall we remove _all_ cache entries or only those
registered through the ssh-agent protocol? */
return err;
}
/* Handler for the "remove_all_identities" command. */
static gpg_error_t
ssh_handler_remove_all_identities (ctrl_t ctrl,
estream_t request, estream_t response)
{
gpg_error_t ret_err;
gpg_error_t err;
(void)ctrl;
(void)request;
err = ssh_identities_remove_all ();
if (! err)
ret_err = stream_write_byte (response, SSH_RESPONSE_SUCCESS);
else
ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE);
return ret_err;
}
/* Lock agent? FIXME: stub function. */
static gpg_error_t
ssh_lock (void)
{
gpg_error_t err;
/* FIXME */
log_error ("ssh-agent's lock command is not implemented\n");
err = 0;
return err;
}
/* Unock agent? FIXME: stub function. */
static gpg_error_t
ssh_unlock (void)
{
gpg_error_t err;
log_error ("ssh-agent's unlock command is not implemented\n");
err = 0;
return err;
}
/* Handler for the "lock" command. */
static gpg_error_t
ssh_handler_lock (ctrl_t ctrl, estream_t request, estream_t response)
{
gpg_error_t ret_err;
gpg_error_t err;
(void)ctrl;
(void)request;
err = ssh_lock ();
if (! err)
ret_err = stream_write_byte (response, SSH_RESPONSE_SUCCESS);
else
ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE);
return ret_err;
}
/* Handler for the "unlock" command. */
static gpg_error_t
ssh_handler_unlock (ctrl_t ctrl, estream_t request, estream_t response)
{
gpg_error_t ret_err;
gpg_error_t err;
(void)ctrl;
(void)request;
err = ssh_unlock ();
if (! err)
ret_err = stream_write_byte (response, SSH_RESPONSE_SUCCESS);
else
ret_err = stream_write_byte (response, SSH_RESPONSE_FAILURE);
return ret_err;
}
/* Return the request specification for the request identified by TYPE
or NULL in case the requested request specification could not be
found. */
static const ssh_request_spec_t *
request_spec_lookup (int type)
{
const ssh_request_spec_t *spec;
unsigned int i;
for (i = 0; i < DIM (request_specs); i++)
if (request_specs[i].type == type)
break;
if (i == DIM (request_specs))
{
if (opt.verbose)
log_info ("ssh request %u is not supported\n", type);
spec = NULL;
}
else
spec = request_specs + i;
return spec;
}
/* Process a single request. The request is read from and the
response is written to STREAM_SOCK. Uses CTRL as context. Returns
zero in case of success, non zero in case of failure. */
static int
ssh_request_process (ctrl_t ctrl, estream_t stream_sock)
{
const ssh_request_spec_t *spec;
estream_t response = NULL;
estream_t request = NULL;
unsigned char request_type;
gpg_error_t err;
int send_err = 0;
int ret;
unsigned char *request_data = NULL;
u32 request_data_size;
u32 response_size;
/* Create memory streams for request/response data. The entire
request will be stored in secure memory, since it might contain
secret key material. The response does not have to be stored in
secure memory, since we never give out secret keys.
Note: we only have little secure memory, but there is NO
possibility of DoS here; only trusted clients are allowed to
connect to the agent. What could happen is that the agent
returns out-of-secure-memory errors on requests in case the
agent's owner floods his own agent with many large messages.
-moritz */
/* Retrieve request. */
err = stream_read_string (stream_sock, 1, &request_data, &request_data_size);
if (err)
goto out;
if (opt.verbose > 1)
log_info ("received ssh request of length %u\n",
(unsigned int)request_data_size);
if (! request_data_size)
{
send_err = 1;
goto out;
/* Broken request; FIXME. */
}
request_type = request_data[0];
spec = request_spec_lookup (request_type);
if (! spec)
{
send_err = 1;
goto out;
/* Unknown request; FIXME. */
}
if (spec->secret_input)
request = es_mopen (NULL, 0, 0, 1, realloc_secure, gcry_free, "r+b");
else
request = es_mopen (NULL, 0, 0, 1, gcry_realloc, gcry_free, "r+b");
if (! request)
{
err = gpg_error_from_syserror ();
goto out;
}
ret = es_setvbuf (request, NULL, _IONBF, 0);
if (ret)
{
err = gpg_error_from_syserror ();
goto out;
}
err = stream_write_data (request, request_data + 1, request_data_size - 1);
if (err)
goto out;
es_rewind (request);
response = es_fopenmem (0, "r+b");
if (! response)
{
err = gpg_error_from_syserror ();
goto out;
}
if (opt.verbose)
log_info ("ssh request handler for %s (%u) started\n",
spec->identifier, spec->type);
err = (*spec->handler) (ctrl, request, response);
if (opt.verbose)
{
if (err)
log_info ("ssh request handler for %s (%u) failed: %s\n",
spec->identifier, spec->type, gpg_strerror (err));
else
log_info ("ssh request handler for %s (%u) ready\n",
spec->identifier, spec->type);
}
if (err)
{
send_err = 1;
goto out;
}
response_size = es_ftell (response);
if (opt.verbose > 1)
log_info ("sending ssh response of length %u\n",
(unsigned int)response_size);
err = es_fseek (response, 0, SEEK_SET);
if (err)
{
send_err = 1;
goto out;
}
err = stream_write_uint32 (stream_sock, response_size);
if (err)
{
send_err = 1;
goto out;
}
err = stream_copy (stream_sock, response);
if (err)
goto out;
err = es_fflush (stream_sock);
if (err)
goto out;
out:
if (err && es_feof (stream_sock))
log_error ("error occurred while processing request: %s\n",
gpg_strerror (err));
if (send_err)
{
if (opt.verbose > 1)
log_info ("sending ssh error response\n");
err = stream_write_uint32 (stream_sock, 1);
if (err)
goto leave;
err = stream_write_byte (stream_sock, SSH_RESPONSE_FAILURE);
if (err)
goto leave;
}
leave:
es_fclose (request);
es_fclose (response);
xfree (request_data);
return !!err;
}
/* Return the peer's pid. */
static void
get_client_info (int fd, struct peer_info_s *out)
{
pid_t client_pid = (pid_t)(-1);
int client_uid = -1;
#ifdef SO_PEERCRED
{
#ifdef HAVE_STRUCT_SOCKPEERCRED_PID
struct sockpeercred cr;
#else
struct ucred cr;
#endif
socklen_t cl = sizeof cr;
if (!getsockopt (fd, SOL_SOCKET, SO_PEERCRED, &cr, &cl))
{
#if defined (HAVE_STRUCT_SOCKPEERCRED_PID) || defined (HAVE_STRUCT_UCRED_PID)
client_pid = cr.pid;
client_uid = (int)cr.uid;
#elif defined (HAVE_STRUCT_UCRED_CR_PID)
client_pid = cr.cr_pid;
client_uid = (int)cr.cr_uid;
#else
#error "Unknown SO_PEERCRED struct"
#endif
}
}
#elif defined (LOCAL_PEERPID)
{
socklen_t len = sizeof (pid_t);
getsockopt (fd, SOL_LOCAL, LOCAL_PEERPID, &client_pid, &len);
#if defined (LOCAL_PEERCRED)
{
struct xucred cr;
len = sizeof (struct xucred);
if (!getsockopt (fd, SOL_LOCAL, LOCAL_PEERCRED, &cr, &len))
client_uid = (int)cr.cr_uid;
}
#endif
}
#elif defined (LOCAL_PEEREID)
{
struct unpcbid unp;
socklen_t unpl = sizeof unp;
if (getsockopt (fd, 0, LOCAL_PEEREID, &unp, &unpl) != -1)
{
client_pid = unp.unp_pid;
client_uid = (int)unp.unp_euid;
}
}
#elif defined (HAVE_GETPEERUCRED)
{
ucred_t *ucred = NULL;
if (getpeerucred (fd, &ucred) != -1)
{
client_pid = ucred_getpid (ucred);
client_uid = (int)ucred_geteuid (ucred);
ucred_free (ucred);
}
}
#else
(void)fd;
#endif
out->pid = (client_pid == (pid_t)(-1)? 0 : (unsigned long)client_pid);
out->uid = client_uid;
}
/* Start serving client on SOCK_CLIENT. */
void
start_command_handler_ssh (ctrl_t ctrl, gnupg_fd_t sock_client)
{
estream_t stream_sock = NULL;
gpg_error_t err;
int ret;
struct peer_info_s peer_info;
err = agent_copy_startup_env (ctrl);
if (err)
goto out;
get_client_info (FD2INT(sock_client), &peer_info);
ctrl->client_pid = peer_info.pid;
ctrl->client_uid = peer_info.uid;
/* Create stream from socket. */
stream_sock = es_fdopen (FD2INT(sock_client), "r+");
if (!stream_sock)
{
err = gpg_error_from_syserror ();
log_error (_("failed to create stream from socket: %s\n"),
gpg_strerror (err));
goto out;
}
/* We have to disable the estream buffering, because the estream
core doesn't know about secure memory. */
ret = es_setvbuf (stream_sock, NULL, _IONBF, 0);
if (ret)
{
err = gpg_error_from_syserror ();
log_error ("failed to disable buffering "
"on socket stream: %s\n", gpg_strerror (err));
goto out;
}
/* Main processing loop. */
while ( !ssh_request_process (ctrl, stream_sock) )
{
/* Check whether we have reached EOF before trying to read
another request. */
int c;
c = es_fgetc (stream_sock);
if (c == EOF)
break;
es_ungetc (c, stream_sock);
}
/* Reset the SCD in case it has been used. */
agent_reset_scd (ctrl);
out:
if (stream_sock)
es_fclose (stream_sock);
}
#ifdef HAVE_W32_SYSTEM
/* Serve one ssh-agent request. This is used for the Putty support.
REQUEST is the mmapped memory which may be accessed up to a
length of MAXREQLEN. Returns 0 on success which also indicates
that a valid SSH response message is now in REQUEST. */
int
serve_mmapped_ssh_request (ctrl_t ctrl,
unsigned char *request, size_t maxreqlen)
{
gpg_error_t err;
int send_err = 0;
int valid_response = 0;
const ssh_request_spec_t *spec;
u32 msglen;
estream_t request_stream, response_stream;
if (agent_copy_startup_env (ctrl))
goto leave; /* Error setting up the environment. */
if (maxreqlen < 5)
goto leave; /* Caller error. */
msglen = uint32_construct (request[0], request[1], request[2], request[3]);
if (msglen < 1 || msglen > maxreqlen - 4)
{
log_error ("ssh message len (%u) out of range", (unsigned int)msglen);
goto leave;
}
spec = request_spec_lookup (request[4]);
if (!spec)
{
send_err = 1; /* Unknown request type. */
goto leave;
}
/* Create a stream object with the data part of the request. */
if (spec->secret_input)
request_stream = es_mopen (NULL, 0, 0, 1, realloc_secure, gcry_free, "r+");
else
request_stream = es_mopen (NULL, 0, 0, 1, gcry_realloc, gcry_free, "r+");
if (!request_stream)
{
err = gpg_error_from_syserror ();
goto leave;
}
/* We have to disable the estream buffering, because the estream
core doesn't know about secure memory. */
if (es_setvbuf (request_stream, NULL, _IONBF, 0))
{
err = gpg_error_from_syserror ();
goto leave;
}
/* Copy the request to the stream but omit the request type. */
err = stream_write_data (request_stream, request + 5, msglen - 1);
if (err)
goto leave;
es_rewind (request_stream);
response_stream = es_fopenmem (0, "r+b");
if (!response_stream)
{
err = gpg_error_from_syserror ();
goto leave;
}
if (opt.verbose)
log_info ("ssh request handler for %s (%u) started\n",
spec->identifier, spec->type);
err = (*spec->handler) (ctrl, request_stream, response_stream);
if (opt.verbose)
{
if (err)
log_info ("ssh request handler for %s (%u) failed: %s\n",
spec->identifier, spec->type, gpg_strerror (err));
else
log_info ("ssh request handler for %s (%u) ready\n",
spec->identifier, spec->type);
}
es_fclose (request_stream);
request_stream = NULL;
if (err)
{
send_err = 1;
goto leave;
}
/* Put the response back into the mmapped buffer. */
{
void *response_data;
size_t response_size;
/* NB: In contrast to the request-stream, the response stream
includes the message type byte. */
if (es_fclose_snatch (response_stream, &response_data, &response_size))
{
log_error ("snatching ssh response failed: %s",
gpg_strerror (gpg_error_from_syserror ()));
send_err = 1; /* Ooops. */
goto leave;
}
if (opt.verbose > 1)
log_info ("sending ssh response of length %u\n",
(unsigned int)response_size);
if (response_size > maxreqlen - 4)
{
log_error ("invalid length of the ssh response: %s",
gpg_strerror (GPG_ERR_INTERNAL));
es_free (response_data);
send_err = 1;
goto leave;
}
request[0] = response_size >> 24;
request[1] = response_size >> 16;
request[2] = response_size >> 8;
request[3] = response_size >> 0;
memcpy (request+4, response_data, response_size);
es_free (response_data);
valid_response = 1;
}
leave:
if (send_err)
{
request[0] = 0;
request[1] = 0;
request[2] = 0;
request[3] = 1;
request[4] = SSH_RESPONSE_FAILURE;
valid_response = 1;
}
/* Reset the SCD in case it has been used. */
agent_reset_scd (ctrl);
return valid_response? 0 : -1;
}
#endif /*HAVE_W32_SYSTEM*/
diff --git a/agent/divert-scd.c b/agent/divert-scd.c
index baa1cc3eb..b9781547d 100644
--- a/agent/divert-scd.c
+++ b/agent/divert-scd.c
@@ -1,597 +1,597 @@
/* divert-scd.c - divert operations to the scdaemon
* Copyright (C) 2002, 2003, 2009 Free Software Foundation, Inc.
*
* 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 .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "agent.h"
#include "../common/i18n.h"
#include "../common/sexp-parse.h"
static int
ask_for_card (ctrl_t ctrl, const unsigned char *shadow_info, char **r_kid)
{
int rc, i;
char *serialno;
int no_card = 0;
char *desc;
char *want_sn, *want_kid, *want_sn_disp;
int len;
*r_kid = NULL;
rc = parse_shadow_info (shadow_info, &want_sn, &want_kid, NULL);
if (rc)
return rc;
want_sn_disp = xtrystrdup (want_sn);
if (!want_sn_disp)
{
rc = gpg_error_from_syserror ();
xfree (want_sn);
xfree (want_kid);
return rc;
}
len = strlen (want_sn_disp);
if (len == 32 && !strncmp (want_sn_disp, "D27600012401", 12))
{
/* This is an OpenPGP card - reformat */
memmove (want_sn_disp, want_sn_disp+16, 4);
want_sn_disp[4] = ' ';
memmove (want_sn_disp+5, want_sn_disp+20, 8);
want_sn_disp[13] = 0;
}
else if (len == 20 && want_sn_disp[19] == '0')
{
/* We assume that a 20 byte serial number is a standard one
* which has the property to have a zero in the last nibble (Due
* to BCD representation). We don't display this '0' because it
* may confuse the user. */
want_sn_disp[19] = 0;
}
for (;;)
{
rc = agent_card_serialno (ctrl, &serialno, want_sn);
if (!rc)
{
log_debug ("detected card with S/N %s\n", serialno);
i = strcmp (serialno, want_sn);
xfree (serialno);
serialno = NULL;
if (!i)
{
xfree (want_sn_disp);
xfree (want_sn);
*r_kid = want_kid;
return 0; /* yes, we have the correct card */
}
}
else if (gpg_err_code (rc) == GPG_ERR_ENODEV)
{
log_debug ("no device present\n");
rc = 0;
no_card = 1;
}
else if (gpg_err_code (rc) == GPG_ERR_CARD_NOT_PRESENT)
{
log_debug ("no card present\n");
rc = 0;
no_card = 2;
}
else
{
log_error ("error accessing card: %s\n", gpg_strerror (rc));
}
if (!rc)
{
if (asprintf (&desc,
"%s:%%0A%%0A"
" %s",
no_card
? L_("Please insert the card with serial number")
: L_("Please remove the current card and "
"insert the one with serial number"),
want_sn_disp) < 0)
{
rc = out_of_core ();
}
else
{
rc = agent_get_confirmation (ctrl, desc, NULL, NULL, 0);
if (ctrl->pinentry_mode == PINENTRY_MODE_LOOPBACK &&
gpg_err_code (rc) == GPG_ERR_NO_PIN_ENTRY)
rc = gpg_error (GPG_ERR_CARD_NOT_PRESENT);
xfree (desc);
}
}
if (rc)
{
xfree (want_sn_disp);
xfree (want_sn);
xfree (want_kid);
return rc;
}
}
}
/* Put the DIGEST into an DER encoded container and return it in R_VAL. */
static int
encode_md_for_card (const unsigned char *digest, size_t digestlen, int algo,
unsigned char **r_val, size_t *r_len)
{
unsigned char *frame;
unsigned char asn[100];
size_t asnlen;
*r_val = NULL;
*r_len = 0;
asnlen = DIM(asn);
if (!algo || gcry_md_test_algo (algo))
return gpg_error (GPG_ERR_DIGEST_ALGO);
if (gcry_md_algo_info (algo, GCRYCTL_GET_ASNOID, asn, &asnlen))
{
log_error ("no object identifier for algo %d\n", algo);
return gpg_error (GPG_ERR_INTERNAL);
}
frame = xtrymalloc (asnlen + digestlen);
if (!frame)
return out_of_core ();
memcpy (frame, asn, asnlen);
memcpy (frame+asnlen, digest, digestlen);
if (DBG_CRYPTO)
log_printhex (frame, asnlen+digestlen, "encoded hash:");
*r_val = frame;
*r_len = asnlen+digestlen;
return 0;
}
/* Return true if STRING ends in "%0A". */
static int
has_percent0A_suffix (const char *string)
{
size_t n;
return (string
&& (n = strlen (string)) >= 3
&& !strcmp (string + n - 3, "%0A"));
}
/* Callback used to ask for the PIN which should be set into BUF. The
buf has been allocated by the caller and is of size MAXBUF which
includes the terminating null. The function should return an UTF-8
string with the passphrase, the buffer may optionally be padded
with arbitrary characters.
- If DESC_TEXT is not NULL it can be used as further informtion shown
+ If DESC_TEXT is not NULL it can be used as further information shown
atop of the INFO message.
INFO gets displayed as part of a generic string. However if the
first character of INFO is a vertical bar all up to the next
verical bar are considered flags and only everything after the
second vertical bar gets displayed as the full prompt.
Flags:
'N' = New PIN, this requests a second prompt to repeat the
PIN. If the PIN is not correctly repeated it starts from
all over.
'A' = The PIN is an Admin PIN, SO-PIN or alike.
'P' = The PIN is a PUK (Personal Unblocking Key).
'R' = The PIN is a Reset Code.
Example:
"|AN|Please enter the new security officer's PIN"
The text "Please ..." will get displayed and the flags 'A' and 'N'
are considered.
*/
static int
getpin_cb (void *opaque, const char *desc_text, const char *info,
char *buf, size_t maxbuf)
{
struct pin_entry_info_s *pi;
int rc;
ctrl_t ctrl = opaque;
const char *ends, *s;
int any_flags = 0;
int newpin = 0;
int resetcode = 0;
int is_puk = 0;
const char *again_text = NULL;
const char *prompt = "PIN";
if (buf && maxbuf < 2)
return gpg_error (GPG_ERR_INV_VALUE);
/* Parse the flags. */
if (info && *info =='|' && (ends=strchr (info+1, '|')))
{
for (s=info+1; s < ends; s++)
{
if (*s == 'A')
prompt = L_("Admin PIN");
else if (*s == 'P')
{
/* TRANSLATORS: A PUK is the Personal Unblocking Code
used to unblock a PIN. */
prompt = L_("PUK");
is_puk = 1;
}
else if (*s == 'N')
newpin = 1;
else if (*s == 'R')
{
prompt = L_("Reset Code");
resetcode = 1;
}
}
info = ends+1;
any_flags = 1;
}
else if (info && *info == '|')
log_debug ("pin_cb called without proper PIN info hack\n");
/* If BUF has been passed as NULL, we are in pinpad mode: The
callback opens the popup and immediately returns. */
if (!buf)
{
if (maxbuf == 0) /* Close the pinentry. */
{
agent_popup_message_stop (ctrl);
rc = 0;
}
else if (maxbuf == 1) /* Open the pinentry. */
{
if (info)
{
char *desc;
const char *desc2;
if (!strcmp (info, "--ack"))
{
desc2 = L_("Push ACK button on card/token.");
if (desc_text)
{
desc = strconcat (desc_text,
has_percent0A_suffix (desc_text)
? "%0A" : "%0A%0A",
desc2, NULL);
desc2 = NULL;
}
else
desc = NULL;
}
else
{
desc2 = NULL;
if (desc_text)
desc = strconcat (desc_text,
has_percent0A_suffix (desc_text)
? "%0A" : "%0A%0A",
info, "%0A%0A",
L_("Use the reader's pinpad for input."),
NULL);
else
desc = strconcat (info, "%0A%0A",
L_("Use the reader's pinpad for input."),
NULL);
}
if (!desc2 && !desc)
rc = gpg_error_from_syserror ();
else
{
rc = agent_popup_message_start (ctrl,
desc2? desc2:desc, NULL);
xfree (desc);
}
}
else
rc = agent_popup_message_start (ctrl, desc_text, NULL);
}
else
rc = gpg_error (GPG_ERR_INV_VALUE);
return rc;
}
/* FIXME: keep PI and TRIES in OPAQUE. Frankly this is a whole
mess because we should call the card's verify function from the
pinentry check pin CB. */
again:
pi = gcry_calloc_secure (1, sizeof (*pi) + maxbuf + 10);
if (!pi)
return gpg_error_from_syserror ();
pi->max_length = maxbuf-1;
pi->min_digits = 0; /* we want a real passphrase */
pi->max_digits = 16;
pi->max_tries = 3;
if (any_flags)
{
{
char *desc2;
if (desc_text)
desc2 = strconcat (desc_text,
has_percent0A_suffix (desc_text)
? "%0A" : "%0A%0A",
info, NULL);
else
desc2 = NULL;
rc = agent_askpin (ctrl, desc2? desc2 : info,
prompt, again_text, pi, NULL, 0);
xfree (desc2);
}
again_text = NULL;
if (!rc && newpin)
{
struct pin_entry_info_s *pi2;
pi2 = gcry_calloc_secure (1, sizeof (*pi) + maxbuf + 10);
if (!pi2)
{
rc = gpg_error_from_syserror ();
xfree (pi);
return rc;
}
pi2->max_length = maxbuf-1;
pi2->min_digits = 0;
pi2->max_digits = 16;
pi2->max_tries = 1;
rc = agent_askpin (ctrl,
(resetcode?
L_("Repeat this Reset Code"):
is_puk?
L_("Repeat this PUK"):
L_("Repeat this PIN")),
prompt, NULL, pi2, NULL, 0);
if (!rc && strcmp (pi->pin, pi2->pin))
{
again_text = (resetcode?
L_("Reset Code not correctly repeated; try again"):
is_puk?
L_("PUK not correctly repeated; try again"):
L_("PIN not correctly repeated; try again"));
xfree (pi2);
xfree (pi);
goto again;
}
xfree (pi2);
}
}
else
{
char *desc, *desc2;
if ( asprintf (&desc,
L_("Please enter the PIN%s%s%s to unlock the card"),
info? " (":"",
info? info:"",
info? ")":"") < 0)
desc = NULL;
if (desc_text)
desc2 = strconcat (desc_text,
has_percent0A_suffix (desc_text)
? "%0A" : "%0A%0A",
desc, NULL);
else
desc2 = NULL;
rc = agent_askpin (ctrl, desc2? desc2 : desc? desc : info,
prompt, NULL, pi, NULL, 0);
xfree (desc2);
xfree (desc);
}
if (!rc)
{
strncpy (buf, pi->pin, maxbuf-1);
buf[maxbuf-1] = 0;
}
xfree (pi);
return rc;
}
/* This function is used when a sign operation has been diverted to a
* smartcard. DESC_TEXT is the original text for a prompt has send by
* gpg to gpg-agent.
*
* FIXME: Explain the other args. */
int
divert_pksign (ctrl_t ctrl, const char *desc_text,
const unsigned char *digest, size_t digestlen, int algo,
const unsigned char *shadow_info, unsigned char **r_sig,
size_t *r_siglen)
{
int rc;
char *kid;
size_t siglen;
unsigned char *sigval = NULL;
(void)desc_text;
rc = ask_for_card (ctrl, shadow_info, &kid);
if (rc)
return rc;
if (algo == MD_USER_TLS_MD5SHA1)
{
int save = ctrl->use_auth_call;
ctrl->use_auth_call = 1;
rc = agent_card_pksign (ctrl, kid, getpin_cb, ctrl, NULL,
algo, digest, digestlen, &sigval, &siglen);
ctrl->use_auth_call = save;
}
else
{
unsigned char *data;
size_t ndata;
rc = encode_md_for_card (digest, digestlen, algo, &data, &ndata);
if (!rc)
{
rc = agent_card_pksign (ctrl, kid, getpin_cb, ctrl, NULL,
algo, data, ndata, &sigval, &siglen);
xfree (data);
}
}
if (!rc)
{
*r_sig = sigval;
*r_siglen = siglen;
}
xfree (kid);
return rc;
}
/* Decrypt the value given asn an S-expression in CIPHER using the
key identified by SHADOW_INFO and return the plaintext in an
allocated buffer in R_BUF. The padding information is stored at
R_PADDING with -1 for not known. */
int
divert_pkdecrypt (ctrl_t ctrl, const char *desc_text,
const unsigned char *cipher,
const unsigned char *shadow_info,
char **r_buf, size_t *r_len, int *r_padding)
{
int rc;
char *kid;
const unsigned char *s;
size_t n;
const unsigned char *ciphertext;
size_t ciphertextlen;
char *plaintext;
size_t plaintextlen;
(void)desc_text;
*r_padding = -1;
s = cipher;
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (!smatch (&s, n, "enc-val"))
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
if (*s != '(')
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (smatch (&s, n, "rsa"))
{
if (*s != '(')
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (!smatch (&s, n, "a"))
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
n = snext (&s);
}
else if (smatch (&s, n, "ecdh"))
{
if (*s != '(')
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (smatch (&s, n, "s"))
{
n = snext (&s);
s += n;
if (*s++ != ')')
return gpg_error (GPG_ERR_INV_SEXP);
if (*s++ != '(')
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
}
if (!smatch (&s, n, "e"))
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
n = snext (&s);
}
else
return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
if (!n)
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
ciphertext = s;
ciphertextlen = n;
rc = ask_for_card (ctrl, shadow_info, &kid);
if (rc)
return rc;
rc = agent_card_pkdecrypt (ctrl, kid, getpin_cb, ctrl, NULL,
ciphertext, ciphertextlen,
&plaintext, &plaintextlen, r_padding);
if (!rc)
{
*r_buf = plaintext;
*r_len = plaintextlen;
}
xfree (kid);
return rc;
}
int
divert_writekey (ctrl_t ctrl, int force, const char *serialno,
const char *id, const char *keydata, size_t keydatalen)
{
return agent_card_writekey (ctrl, force, serialno, id, keydata, keydatalen,
getpin_cb, ctrl);
}
int
divert_generic_cmd (ctrl_t ctrl, const char *cmdline, void *assuan_context)
{
return agent_card_scd (ctrl, cmdline, getpin_cb, ctrl, assuan_context);
}
diff --git a/agent/gpg-agent.c b/agent/gpg-agent.c
index 1fdc94d0f..911064cdc 100644
--- a/agent/gpg-agent.c
+++ b/agent/gpg-agent.c
@@ -1,3258 +1,3258 @@
/* gpg-agent.c - The GnuPG Agent
* Copyright (C) 2000-2007, 2009-2010 Free Software Foundation, Inc.
* Copyright (C) 2000-2016 Werner Koch
*
* 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 .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#ifdef HAVE_W32_SYSTEM
# ifndef WINVER
# define WINVER 0x0500 /* Same as in common/sysutils.c */
# endif
# ifdef HAVE_WINSOCK2_H
# include
# endif
# include
# include
#else /*!HAVE_W32_SYSTEM*/
# include
# include
#endif /*!HAVE_W32_SYSTEM*/
#include
#ifdef HAVE_SIGNAL_H
# include
#endif
#include
#define GNUPG_COMMON_NEED_AFLOCAL
#include "agent.h"
#include /* Malloc hooks and socket wrappers. */
#include "../common/i18n.h"
#include "../common/sysutils.h"
#include "../common/gc-opt-flags.h"
#include "../common/exechelp.h"
#include "../common/asshelp.h"
#include "../common/init.h"
enum cmd_and_opt_values
{ aNull = 0,
oCsh = 'c',
oQuiet = 'q',
oSh = 's',
oVerbose = 'v',
oNoVerbose = 500,
aGPGConfList,
aGPGConfTest,
aUseStandardSocketP,
oOptions,
oDebug,
oDebugAll,
oDebugLevel,
oDebugWait,
oDebugQuickRandom,
oDebugPinentry,
oNoGreeting,
oNoOptions,
oHomedir,
oNoDetach,
oGrab,
oNoGrab,
oLogFile,
oServer,
oDaemon,
oSupervised,
oBatch,
oPinentryProgram,
oPinentryTouchFile,
oPinentryInvisibleChar,
oPinentryTimeout,
oDisplay,
oTTYname,
oTTYtype,
oLCctype,
oLCmessages,
oXauthority,
oScdaemonProgram,
oDefCacheTTL,
oDefCacheTTLSSH,
oMaxCacheTTL,
oMaxCacheTTLSSH,
oEnforcePassphraseConstraints,
oMinPassphraseLen,
oMinPassphraseNonalpha,
oCheckPassphrasePattern,
oMaxPassphraseDays,
oEnablePassphraseHistory,
oEnableExtendedKeyFormat,
oUseStandardSocket,
oNoUseStandardSocket,
oExtraSocket,
oBrowserSocket,
oFakedSystemTime,
oIgnoreCacheForSigning,
oAllowMarkTrusted,
oNoAllowMarkTrusted,
oAllowPresetPassphrase,
oAllowLoopbackPinentry,
oNoAllowLoopbackPinentry,
oNoAllowExternalCache,
oAllowEmacsPinentry,
oKeepTTY,
oKeepDISPLAY,
oSSHSupport,
oSSHFingerprintDigest,
oPuttySupport,
oDisableScdaemon,
oDisableCheckOwnSocket,
oS2KCount,
oAutoExpandSecmem,
oListenBacklog,
oWriteEnvFile
};
#ifndef ENAMETOOLONG
# define ENAMETOOLONG EINVAL
#endif
static ARGPARSE_OPTS opts[] = {
ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
ARGPARSE_c (aUseStandardSocketP, "use-standard-socket-p", "@"),
ARGPARSE_group (301, N_("@Options:\n ")),
ARGPARSE_s_n (oDaemon, "daemon", N_("run in daemon mode (background)")),
ARGPARSE_s_n (oServer, "server", N_("run in server mode (foreground)")),
#ifndef HAVE_W32_SYSTEM
ARGPARSE_s_n (oSupervised, "supervised", N_("run in supervised mode")),
#endif
ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")),
ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")),
ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
ARGPARSE_s_s (oDebug, "debug", "@"),
ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
ARGPARSE_s_s (oDebugLevel, "debug-level", "@"),
ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
ARGPARSE_s_n (oDebugQuickRandom, "debug-quick-random", "@"),
ARGPARSE_s_n (oDebugPinentry, "debug-pinentry", "@"),
ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
ARGPARSE_s_n (oGrab, "grab", "@"),
/* FIXME: Add the below string for 2.3 */
/* N_("let PIN-Entry grab keyboard and mouse")), */
ARGPARSE_s_n (oNoGrab, "no-grab", "@"),
ARGPARSE_s_s (oLogFile, "log-file", N_("use a log file for the server")),
ARGPARSE_s_s (oPinentryProgram, "pinentry-program",
/* */ N_("|PGM|use PGM as the PIN-Entry program")),
ARGPARSE_s_s (oPinentryTouchFile, "pinentry-touch-file", "@"),
ARGPARSE_s_s (oPinentryInvisibleChar, "pinentry-invisible-char", "@"),
ARGPARSE_s_u (oPinentryTimeout, "pinentry-timeout", "@"),
ARGPARSE_s_s (oScdaemonProgram, "scdaemon-program",
/* */ N_("|PGM|use PGM as the SCdaemon program") ),
ARGPARSE_s_n (oDisableScdaemon, "disable-scdaemon",
/* */ N_("do not use the SCdaemon") ),
ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"),
ARGPARSE_s_s (oExtraSocket, "extra-socket",
/* */ N_("|NAME|accept some commands via NAME")),
ARGPARSE_s_s (oBrowserSocket, "browser-socket", "@"),
ARGPARSE_s_s (oFakedSystemTime, "faked-system-time", "@"),
ARGPARSE_s_n (oBatch, "batch", "@"),
ARGPARSE_s_s (oHomedir, "homedir", "@"),
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_s_n (oKeepTTY, "keep-tty",
/* */ N_("ignore requests to change the TTY")),
ARGPARSE_s_n (oKeepDISPLAY, "keep-display",
/* */ N_("ignore requests to change the X display")),
ARGPARSE_s_u (oDefCacheTTL, "default-cache-ttl",
N_("|N|expire cached PINs after N seconds")),
ARGPARSE_s_u (oDefCacheTTLSSH, "default-cache-ttl-ssh", "@" ),
ARGPARSE_s_u (oMaxCacheTTL, "max-cache-ttl", "@" ),
ARGPARSE_s_u (oMaxCacheTTLSSH, "max-cache-ttl-ssh", "@" ),
ARGPARSE_s_n (oEnforcePassphraseConstraints, "enforce-passphrase-constraints",
/* */ "@"),
ARGPARSE_s_u (oMinPassphraseLen, "min-passphrase-len", "@"),
ARGPARSE_s_u (oMinPassphraseNonalpha, "min-passphrase-nonalpha", "@"),
ARGPARSE_s_s (oCheckPassphrasePattern, "check-passphrase-pattern", "@"),
ARGPARSE_s_u (oMaxPassphraseDays, "max-passphrase-days", "@"),
ARGPARSE_s_n (oEnablePassphraseHistory, "enable-passphrase-history", "@"),
ARGPARSE_s_n (oIgnoreCacheForSigning, "ignore-cache-for-signing",
/* */ N_("do not use the PIN cache when signing")),
ARGPARSE_s_n (oNoAllowExternalCache, "no-allow-external-cache",
/* */ N_("disallow the use of an external password cache")),
ARGPARSE_s_n (oNoAllowMarkTrusted, "no-allow-mark-trusted",
/* */ N_("disallow clients to mark keys as \"trusted\"")),
ARGPARSE_s_n (oAllowMarkTrusted, "allow-mark-trusted", "@"),
ARGPARSE_s_n (oAllowPresetPassphrase, "allow-preset-passphrase",
/* */ N_("allow presetting passphrase")),
ARGPARSE_s_n (oNoAllowLoopbackPinentry, "no-allow-loopback-pinentry",
N_("disallow caller to override the pinentry")),
ARGPARSE_s_n (oAllowLoopbackPinentry, "allow-loopback-pinentry", "@"),
ARGPARSE_s_n (oAllowEmacsPinentry, "allow-emacs-pinentry",
/* */ N_("allow passphrase to be prompted through Emacs")),
ARGPARSE_s_n (oSSHSupport, "enable-ssh-support", N_("enable ssh support")),
ARGPARSE_s_s (oSSHFingerprintDigest, "ssh-fingerprint-digest",
N_("|ALGO|use ALGO to show ssh fingerprints")),
ARGPARSE_s_n (oPuttySupport, "enable-putty-support",
#ifdef HAVE_W32_SYSTEM
/* */ N_("enable putty support")
#else
/* */ "@"
#endif
),
ARGPARSE_s_n (oEnableExtendedKeyFormat, "enable-extended-key-format", "@"),
ARGPARSE_s_u (oS2KCount, "s2k-count", "@"),
ARGPARSE_op_u (oAutoExpandSecmem, "auto-expand-secmem", "@"),
ARGPARSE_s_i (oListenBacklog, "listen-backlog", "@"),
/* Dummy options for backward compatibility. */
ARGPARSE_o_s (oWriteEnvFile, "write-env-file", "@"),
ARGPARSE_s_n (oUseStandardSocket, "use-standard-socket", "@"),
ARGPARSE_s_n (oNoUseStandardSocket, "no-use-standard-socket", "@"),
ARGPARSE_end () /* End of list */
};
/* The list of supported debug flags. */
static struct debug_flags_s debug_flags [] =
{
{ 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" },
{ 77, NULL } /* 77 := Do not exit on "help" or "?". */
};
#define DEFAULT_CACHE_TTL (10*60) /* 10 minutes */
#define DEFAULT_CACHE_TTL_SSH (30*60) /* 30 minutes */
#define MAX_CACHE_TTL (120*60) /* 2 hours */
#define MAX_CACHE_TTL_SSH (120*60) /* 2 hours */
#define MIN_PASSPHRASE_LEN (8)
#define MIN_PASSPHRASE_NONALPHA (1)
#define MAX_PASSPHRASE_DAYS (0)
/* The timer tick used for housekeeping stuff. Note that on Windows
* we use a SetWaitableTimer seems to signal earlier than about 2
* seconds. Thus we use 4 seconds on all platforms except for
* Windowsce. CHECK_OWN_SOCKET_INTERVAL defines how often we check
* our own socket in standard socket mode. If that value is 0 we
* don't check at all. All values are in seconds. */
#if defined(HAVE_W32CE_SYSTEM)
# define TIMERTICK_INTERVAL (60)
# define CHECK_OWN_SOCKET_INTERVAL (0) /* Never */
#else
# define TIMERTICK_INTERVAL (4)
# define CHECK_OWN_SOCKET_INTERVAL (60)
#endif
/* Flag indicating that the ssh-agent subsystem has been enabled. */
static int ssh_support;
#ifdef HAVE_W32_SYSTEM
/* Flag indicating that support for Putty has been enabled. */
static int putty_support;
/* A magic value used with WM_COPYDATA. */
#define PUTTY_IPC_MAGIC 0x804e50ba
/* To avoid surprises we limit the size of the mapped IPC file to this
value. Putty currently (0.62) uses 8k, thus 16k should be enough
for the foreseeable future. */
#define PUTTY_IPC_MAXLEN 16384
#endif /*HAVE_W32_SYSTEM*/
/* The list of open file descriptors at startup. Note that this list
* has been allocated using the standard malloc. */
#ifndef HAVE_W32_SYSTEM
static int *startup_fd_list;
#endif
/* The signal mask at startup and a flag telling whether it is valid. */
#ifdef HAVE_SIGPROCMASK
static sigset_t startup_signal_mask;
static int startup_signal_mask_valid;
#endif
/* Flag to indicate that a shutdown was requested. */
static int shutdown_pending;
/* Counter for the currently running own socket checks. */
static int check_own_socket_running;
/* Flags to indicate that check_own_socket shall not be called. */
static int disable_check_own_socket;
/* Flag indicating that we are in supervised mode. */
static int is_supervised;
/* Flag to inhibit socket removal in cleanup. */
static int inhibit_socket_removal;
/* It is possible that we are currently running under setuid permissions */
static int maybe_setuid = 1;
/* Name of the communication socket used for native gpg-agent
requests. The second variable is either NULL or a malloced string
with the real socket name in case it has been redirected. */
static char *socket_name;
static char *redir_socket_name;
/* Name of the optional extra socket used for native gpg-agent requests. */
static char *socket_name_extra;
static char *redir_socket_name_extra;
/* Name of the optional browser socket used for native gpg-agent requests. */
static char *socket_name_browser;
static char *redir_socket_name_browser;
/* Name of the communication socket used for ssh-agent protocol. */
static char *socket_name_ssh;
static char *redir_socket_name_ssh;
/* We need to keep track of the server's nonces (these are dummies for
POSIX systems). */
static assuan_sock_nonce_t socket_nonce;
static assuan_sock_nonce_t socket_nonce_extra;
static assuan_sock_nonce_t socket_nonce_browser;
static assuan_sock_nonce_t socket_nonce_ssh;
/* Value for the listen() backlog argument. We use the same value for
* all sockets - 64 is on current Linux half of the default maximum.
* Let's try this as default. Change at runtime with --listen-backlog. */
static int listen_backlog = 64;
/* Default values for options passed to the pinentry. */
static char *default_display;
static char *default_ttyname;
static char *default_ttytype;
static char *default_lc_ctype;
static char *default_lc_messages;
static char *default_xauthority;
/* Name of a config file, which will be reread on a HUP if it is not NULL. */
static char *config_filename;
/* Helper to implement --debug-level */
static const char *debug_level;
/* Keep track of the current log file so that we can avoid updating
the log file after a SIGHUP if it didn't changed. Malloced. */
static char *current_logfile;
/* The handle_tick() function may test whether a parent is still
* running. We record the PID of the parent here or -1 if it should
* be watched. */
static pid_t parent_pid = (pid_t)(-1);
/* This flag is true if the inotify mechanism for detecting the
* removal of the homedir is active. This flag is used to disable the
* alternative but portable stat based check. */
static int have_homedir_inotify;
/* Depending on how gpg-agent was started, the homedir inotify watch
* may not be reliable. This flag is set if we assume that inotify
* works reliable. */
static int reliable_homedir_inotify;
/* Number of active connections. */
static int active_connections;
/* This object is used to dispatch progress messages from Libgcrypt to
* the right thread. Given that we will have at max only a few dozen
* connections at a time, using a linked list is the easiest way to
* handle this. */
struct progress_dispatch_s
{
struct progress_dispatch_s *next;
/* The control object of the connection. If this is NULL no
* connection is associated with this item and it is free for reuse
* by new connections. */
ctrl_t ctrl;
/* The thread id of (npth_self) of the connection. */
npth_t tid;
/* The callback set by the connection. This is similar to the
* Libgcrypt callback but with the control object passed as the
* first argument. */
void (*cb)(ctrl_t ctrl,
const char *what, int printchar,
int current, int total);
};
struct progress_dispatch_s *progress_dispatch_list;
/*
Local prototypes.
*/
static char *create_socket_name (char *standard_name, int with_homedir);
static gnupg_fd_t create_server_socket (char *name, int primary, int cygwin,
char **r_redir_name,
assuan_sock_nonce_t *nonce);
static void create_directories (void);
static void agent_libgcrypt_progress_cb (void *data, const char *what,
int printchar,
int current, int total);
static void agent_init_default_ctrl (ctrl_t ctrl);
static void agent_deinit_default_ctrl (ctrl_t ctrl);
static void handle_connections (gnupg_fd_t listen_fd,
gnupg_fd_t listen_fd_extra,
gnupg_fd_t listen_fd_browser,
gnupg_fd_t listen_fd_ssh);
static void check_own_socket (void);
static int check_for_running_agent (int silent);
/* Pth wrapper function definitions. */
ASSUAN_SYSTEM_NPTH_IMPL;
/*
Functions.
*/
/* Allocate a string describing a library version by calling a GETFNC.
This function is expected to be called only once. GETFNC is
expected to have a semantic like gcry_check_version (). */
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;
}
/* Return strings describing this program. The case values are
described in common/argparse.c:strusage. The values here override
the default values given by strusage. */
static const char *
my_strusage (int level)
{
static char *ver_gcry;
const char *p;
switch (level)
{
case 11: p = "@GPG_AGENT@ (@GNUPG@)";
break;
case 13: p = VERSION; break;
case 17: p = PRINTABLE_OS_NAME; break;
/* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
reporting address. This is so that we can change the
reporting address without breaking the translations. */
case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
case 20:
if (!ver_gcry)
ver_gcry = make_libversion ("libgcrypt", gcry_check_version);
p = ver_gcry;
break;
case 1:
case 40: p = _("Usage: @GPG_AGENT@ [options] (-h for help)");
break;
case 41: p = _("Syntax: @GPG_AGENT@ [options] [command [args]]\n"
"Secret key management for @GNUPG@\n");
break;
default: p = NULL;
}
return p;
}
/* Setup the debugging. With the global variable DEBUG_LEVEL set to NULL
only the active debug flags are propagated to the subsystems. With
DEBUG_LEVEL set, a specific set of debug flags is set; thus overriding
all flags already set. Note that we don't fail here, because it is
important to keep gpg-agent running even after re-reading the
options due to a SIGHUP. */
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;
else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
opt.debug = (DBG_IPC_VALUE | DBG_CACHE_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);
opt.debug = 0; /* Reset debugging, so that prior debug
statements won't have an undesired effect. */
}
if (opt.debug && !opt.verbose)
opt.verbose = 1;
if (opt.debug && opt.quiet)
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);
}
/* Helper for cleanup to remove one socket with NAME. REDIR_NAME is
the corresponding real name if the socket has been redirected. */
static void
remove_socket (char *name, char *redir_name)
{
if (name && *name)
{
if (redir_name)
name = redir_name;
gnupg_remove (name);
*name = 0;
}
}
/* Discover which inherited file descriptors correspond to which
* services/sockets offered by gpg-agent, using the LISTEN_FDS and
* LISTEN_FDNAMES convention. The understood labels are "ssh",
* "extra", and "browser". "std" or other labels will be interpreted
* as the standard socket.
*
* This function is designed to log errors when the expected file
* descriptors don't make sense, but to do its best to continue to
* work even in the face of minor misconfigurations.
*
* For more information on the LISTEN_FDS convention, see
* sd_listen_fds(3) on certain Linux distributions.
*/
#ifndef HAVE_W32_SYSTEM
static void
map_supervised_sockets (gnupg_fd_t *r_fd,
gnupg_fd_t *r_fd_extra,
gnupg_fd_t *r_fd_browser,
gnupg_fd_t *r_fd_ssh)
{
struct {
const char *label;
int **fdaddr;
char **nameaddr;
} tbl[] = {
{ "ssh", &r_fd_ssh, &socket_name_ssh },
{ "browser", &r_fd_browser, &socket_name_browser },
{ "extra", &r_fd_extra, &socket_name_extra },
{ "std", &r_fd, &socket_name } /* (Must be the last item.) */
};
const char *envvar;
char **fdnames;
int nfdnames;
int fd_count;
*r_fd = *r_fd_extra = *r_fd_browser = *r_fd_ssh = -1;
/* Print a warning if LISTEN_PID does not match outr pid. */
envvar = getenv ("LISTEN_PID");
if (!envvar)
log_error ("no LISTEN_PID environment variable found in "
"--supervised mode (ignoring)\n");
else if (strtoul (envvar, NULL, 10) != (unsigned long)getpid ())
log_error ("environment variable LISTEN_PID (%lu) does not match"
" our pid (%lu) in --supervised mode (ignoring)\n",
(unsigned long)strtoul (envvar, NULL, 10),
(unsigned long)getpid ());
/* Parse LISTEN_FDNAMES into the array FDNAMES. */
envvar = getenv ("LISTEN_FDNAMES");
if (envvar)
{
fdnames = strtokenize (envvar, ":");
if (!fdnames)
{
log_error ("strtokenize failed: %s\n",
gpg_strerror (gpg_error_from_syserror ()));
agent_exit (1);
}
for (nfdnames=0; fdnames[nfdnames]; nfdnames++)
;
}
else
{
fdnames = NULL;
nfdnames = 0;
}
/* Parse LISTEN_FDS into fd_count or provide a replacement. */
envvar = getenv ("LISTEN_FDS");
if (envvar)
fd_count = atoi (envvar);
else if (fdnames)
{
log_error ("no LISTEN_FDS environment variable found in --supervised"
" mode (relying on LISTEN_FDNAMES instead)\n");
fd_count = nfdnames;
}
else
{
log_error ("no LISTEN_FDS or LISTEN_FDNAMES environment variables "
"found in --supervised mode"
" (assuming 1 active descriptor)\n");
fd_count = 1;
}
if (fd_count < 1)
{
log_error ("--supervised mode expects at least one file descriptor"
" (was told %d, carrying on as though it were 1)\n",
fd_count);
fd_count = 1;
}
/* Assign the descriptors to the return values. */
if (!fdnames)
{
struct stat statbuf;
if (fd_count != 1)
log_error ("no LISTEN_FDNAMES and LISTEN_FDS (%d) != 1"
" in --supervised mode."
" (ignoring all sockets but the first one)\n",
fd_count);
if (fstat (3, &statbuf) == -1 && errno ==EBADF)
log_fatal ("file descriptor 3 must be valid in --supervised mode"
" if LISTEN_FDNAMES is not set\n");
*r_fd = 3;
socket_name = gnupg_get_socket_name (3);
}
else if (fd_count != nfdnames)
{
log_fatal ("number of items in LISTEN_FDNAMES (%d) does not match "
"LISTEN_FDS (%d) in --supervised mode\n",
nfdnames, fd_count);
}
else
{
int i, j, fd;
char *name;
for (i = 0; i < nfdnames; i++)
{
for (j = 0; j < DIM (tbl); j++)
{
if (!strcmp (fdnames[i], tbl[j].label) || j == DIM(tbl)-1)
{
fd = 3 + i;
if (**tbl[j].fdaddr == -1)
{
name = gnupg_get_socket_name (fd);
if (name)
{
**tbl[j].fdaddr = fd;
*tbl[j].nameaddr = name;
log_info ("using fd %d for %s socket (%s)\n",
fd, tbl[j].label, name);
}
else
{
log_error ("cannot listen on fd %d for %s socket\n",
fd, tbl[j].label);
close (fd);
}
}
else
{
log_error ("cannot listen on more than one %s socket\n",
tbl[j].label);
close (fd);
}
break;
}
}
}
}
xfree (fdnames);
}
#endif /*!HAVE_W32_SYSTEM*/
/* Cleanup code for this program. This is either called has an atexit
handler or directly. */
static void
cleanup (void)
{
static int done;
if (done)
return;
done = 1;
deinitialize_module_cache ();
if (!is_supervised && !inhibit_socket_removal)
{
remove_socket (socket_name, redir_socket_name);
if (opt.extra_socket > 1)
remove_socket (socket_name_extra, redir_socket_name_extra);
if (opt.browser_socket > 1)
remove_socket (socket_name_browser, redir_socket_name_browser);
remove_socket (socket_name_ssh, redir_socket_name_ssh);
}
}
/* Handle options which are allowed to be reset after program start.
Return true when the current option in PARGS could be handled and
false if not. As a special feature, passing a value of NULL for
PARGS, resets the options to the default. REREAD should be set
true if it is not the initial option parsing. */
static int
parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
{
int i;
if (!pargs)
{ /* reset mode */
opt.quiet = 0;
opt.verbose = 0;
opt.debug = 0;
opt.no_grab = 1;
opt.debug_pinentry = 0;
opt.pinentry_program = NULL;
opt.pinentry_touch_file = NULL;
xfree (opt.pinentry_invisible_char);
opt.pinentry_invisible_char = NULL;
opt.pinentry_timeout = 0;
opt.scdaemon_program = NULL;
opt.def_cache_ttl = DEFAULT_CACHE_TTL;
opt.def_cache_ttl_ssh = DEFAULT_CACHE_TTL_SSH;
opt.max_cache_ttl = MAX_CACHE_TTL;
opt.max_cache_ttl_ssh = MAX_CACHE_TTL_SSH;
opt.enforce_passphrase_constraints = 0;
opt.min_passphrase_len = MIN_PASSPHRASE_LEN;
opt.min_passphrase_nonalpha = MIN_PASSPHRASE_NONALPHA;
opt.check_passphrase_pattern = NULL;
opt.max_passphrase_days = MAX_PASSPHRASE_DAYS;
opt.enable_passphrase_history = 0;
opt.enable_extended_key_format = 0;
opt.ignore_cache_for_signing = 0;
opt.allow_mark_trusted = 1;
opt.allow_external_cache = 1;
opt.allow_loopback_pinentry = 1;
opt.allow_emacs_pinentry = 0;
opt.disable_scdaemon = 0;
disable_check_own_socket = 0;
/* Note: When changing the next line, change also gpgconf_list. */
opt.ssh_fingerprint_digest = GCRY_MD_MD5;
opt.s2k_count = 0;
return 1;
}
switch (pargs->r_opt)
{
case oQuiet: opt.quiet = 1; break;
case oVerbose: opt.verbose++; break;
case oDebug:
parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags);
break;
case oDebugAll: opt.debug = ~0; break;
case oDebugLevel: debug_level = pargs->r.ret_str; break;
case oDebugPinentry: opt.debug_pinentry = 1; break;
case oLogFile:
if (!reread)
- return 0; /* not handeld */
+ return 0; /* not handled */
if (!current_logfile || !pargs->r.ret_str
|| strcmp (current_logfile, pargs->r.ret_str))
{
log_set_file (pargs->r.ret_str);
xfree (current_logfile);
current_logfile = xtrystrdup (pargs->r.ret_str);
}
break;
case oNoGrab: opt.no_grab |= 1; break;
case oGrab: opt.no_grab |= 2; break;
case oPinentryProgram: opt.pinentry_program = pargs->r.ret_str; break;
case oPinentryTouchFile: opt.pinentry_touch_file = pargs->r.ret_str; break;
case oPinentryInvisibleChar:
xfree (opt.pinentry_invisible_char);
opt.pinentry_invisible_char = xtrystrdup (pargs->r.ret_str); break;
break;
case oPinentryTimeout: opt.pinentry_timeout = pargs->r.ret_ulong; break;
case oScdaemonProgram: opt.scdaemon_program = pargs->r.ret_str; break;
case oDisableScdaemon: opt.disable_scdaemon = 1; break;
case oDisableCheckOwnSocket: disable_check_own_socket = 1; break;
case oDefCacheTTL: opt.def_cache_ttl = pargs->r.ret_ulong; break;
case oDefCacheTTLSSH: opt.def_cache_ttl_ssh = pargs->r.ret_ulong; break;
case oMaxCacheTTL: opt.max_cache_ttl = pargs->r.ret_ulong; break;
case oMaxCacheTTLSSH: opt.max_cache_ttl_ssh = pargs->r.ret_ulong; break;
case oEnforcePassphraseConstraints:
opt.enforce_passphrase_constraints=1;
break;
case oMinPassphraseLen: opt.min_passphrase_len = pargs->r.ret_ulong; break;
case oMinPassphraseNonalpha:
opt.min_passphrase_nonalpha = pargs->r.ret_ulong;
break;
case oCheckPassphrasePattern:
opt.check_passphrase_pattern = pargs->r.ret_str;
break;
case oMaxPassphraseDays:
opt.max_passphrase_days = pargs->r.ret_ulong;
break;
case oEnablePassphraseHistory:
opt.enable_passphrase_history = 1;
break;
case oEnableExtendedKeyFormat:
opt.enable_extended_key_format = 1;
break;
case oIgnoreCacheForSigning: opt.ignore_cache_for_signing = 1; break;
case oAllowMarkTrusted: opt.allow_mark_trusted = 1; break;
case oNoAllowMarkTrusted: opt.allow_mark_trusted = 0; break;
case oAllowPresetPassphrase: opt.allow_preset_passphrase = 1; break;
case oAllowLoopbackPinentry: opt.allow_loopback_pinentry = 1; break;
case oNoAllowLoopbackPinentry: opt.allow_loopback_pinentry = 0; break;
case oNoAllowExternalCache: opt.allow_external_cache = 0;
break;
case oAllowEmacsPinentry: opt.allow_emacs_pinentry = 1;
break;
case oSSHFingerprintDigest:
i = gcry_md_map_name (pargs->r.ret_str);
if (!i)
log_error (_("selected digest algorithm is invalid\n"));
else
opt.ssh_fingerprint_digest = i;
break;
case oS2KCount:
opt.s2k_count = pargs->r.ret_ulong;
break;
default:
return 0; /* not handled */
}
return 1; /* handled */
}
/* Fixup some options after all have been processed. */
static void
finalize_rereadable_options (void)
{
/* Hack to allow --grab to override --no-grab. */
if ((opt.no_grab & 2))
opt.no_grab = 0;
}
static void
thread_init_once (void)
{
static int npth_initialized = 0;
if (!npth_initialized)
{
npth_initialized++;
npth_init ();
}
gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
/* Now that we have set the syscall clamp we need to tell Libgcrypt
* that it should get them from libgpg-error. Note that Libgcrypt
* has already been initialized but at that point nPth was not
* initialized and thus Libgcrypt could not set its system call
* clamp. */
#if GCRYPT_VERSION_NUMBER >= 0x010800 /* 1.8.0 */
gcry_control (GCRYCTL_REINIT_SYSCALL_CLAMP, 0, 0);
#endif
}
static void
initialize_modules (void)
{
thread_init_once ();
assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
initialize_module_cache ();
initialize_module_call_pinentry ();
initialize_module_call_scd ();
initialize_module_trustlist ();
}
/* The main entry point. */
int
main (int argc, char **argv )
{
ARGPARSE_ARGS pargs;
int orig_argc;
char **orig_argv;
FILE *configfp = NULL;
char *configname = NULL;
const char *shell;
unsigned configlineno;
int parse_debug = 0;
int default_config =1;
int pipe_server = 0;
int is_daemon = 0;
int nodetach = 0;
int csh_style = 0;
char *logfile = NULL;
int debug_wait = 0;
int gpgconf_list = 0;
gpg_error_t err;
struct assuan_malloc_hooks malloc_hooks;
early_system_init ();
/* Before we do anything else we save the list of currently open
file descriptors and the signal mask. This info is required to
do the exec call properly. We don't need it on Windows. */
#ifndef HAVE_W32_SYSTEM
startup_fd_list = get_all_open_fds ();
#endif /*!HAVE_W32_SYSTEM*/
#ifdef HAVE_SIGPROCMASK
if (!sigprocmask (SIG_UNBLOCK, NULL, &startup_signal_mask))
startup_signal_mask_valid = 1;
#endif /*HAVE_SIGPROCMASK*/
/* Set program name etc. */
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 INIT_SECMEM()
somewhere after the option parsing */
log_set_prefix (GPG_AGENT_NAME, GPGRT_LOG_WITH_PREFIX|GPGRT_LOG_WITH_PID);
/* Make sure that our subsystems are ready. */
i18n_init ();
init_common_subsystems (&argc, &argv);
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);
assuan_sock_init ();
assuan_sock_set_system_hooks (ASSUAN_SYSTEM_NPTH);
setup_libassuan_logging (&opt.debug, NULL);
setup_libgcrypt_logging ();
gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
gcry_set_progress_handler (agent_libgcrypt_progress_cb, NULL);
disable_core_dumps ();
/* Set default options. */
parse_rereadable_options (NULL, 0); /* Reset them to default values. */
shell = getenv ("SHELL");
if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
csh_style = 1;
/* Record some of the original environment strings. */
{
const char *s;
int idx;
static const char *names[] =
{ "DISPLAY", "TERM", "XAUTHORITY", "PINENTRY_USER_DATA", NULL };
err = 0;
opt.startup_env = session_env_new ();
if (!opt.startup_env)
err = gpg_error_from_syserror ();
for (idx=0; !err && names[idx]; idx++)
{
s = getenv (names[idx]);
if (s)
err = session_env_setenv (opt.startup_env, names[idx], s);
}
if (!err)
{
s = gnupg_ttyname (0);
if (s)
err = session_env_setenv (opt.startup_env, "GPG_TTY", s);
}
if (err)
log_fatal ("error recording startup environment: %s\n",
gpg_strerror (err));
/* Fixme: Better use the locale function here. */
opt.startup_lc_ctype = getenv ("LC_CTYPE");
if (opt.startup_lc_ctype)
opt.startup_lc_ctype = xstrdup (opt.startup_lc_ctype);
opt.startup_lc_messages = getenv ("LC_MESSAGES");
if (opt.startup_lc_messages)
opt.startup_lc_messages = xstrdup (opt.startup_lc_messages);
}
/* Check whether we have a config file on the commandline */
orig_argc = argc;
orig_argv = argv;
pargs.argc = &argc;
pargs.argv = &argv;
pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
while (arg_parse( &pargs, opts))
{
if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
parse_debug++;
else if (pargs.r_opt == oOptions)
{ /* yes there is one, so we do not try the default one, but
read the option file when it is encountered at the
commandline */
default_config = 0;
}
else if (pargs.r_opt == oNoOptions)
default_config = 0; /* --no-options */
else if (pargs.r_opt == oHomedir)
gnupg_set_homedir (pargs.r.ret_str);
else if (pargs.r_opt == oDebugQuickRandom)
{
gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
}
}
/* Initialize the secure memory. */
gcry_control (GCRYCTL_INIT_SECMEM, SECMEM_BUFFER_SIZE, 0);
maybe_setuid = 0;
/*
Now we are now working under our real uid
*/
if (default_config)
configname = make_filename (gnupg_homedir (),
GPG_AGENT_NAME EXTSEP_S "conf", NULL);
argc = orig_argc;
argv = orig_argv;
pargs.argc = &argc;
pargs.argv = &argv;
pargs.flags= 1; /* do not remove the args */
next_pass:
if (configname)
{
configlineno = 0;
configfp = fopen (configname, "r");
if (!configfp)
{
if (default_config)
{
if( parse_debug )
log_info (_("Note: no default option file '%s'\n"),
configname );
/* Save the default conf file name so that
reread_configuration is able to test whether the
config file has been created in the meantime. */
xfree (config_filename);
config_filename = configname;
configname = NULL;
}
else
{
log_error (_("option file '%s': %s\n"),
configname, strerror(errno) );
exit(2);
}
xfree (configname);
configname = NULL;
}
if (parse_debug && configname )
log_info (_("reading options from '%s'\n"), configname );
default_config = 0;
}
while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
{
if (parse_rereadable_options (&pargs, 0))
continue; /* Already handled */
switch (pargs.r_opt)
{
case aGPGConfList: gpgconf_list = 1; break;
case aGPGConfTest: gpgconf_list = 2; break;
case aUseStandardSocketP: gpgconf_list = 3; break;
case oBatch: opt.batch=1; break;
case oDebugWait: debug_wait = pargs.r.ret_int; break;
case oOptions:
/* config files may not be nested (silently ignore them) */
if (!configfp)
{
xfree(configname);
configname = xstrdup(pargs.r.ret_str);
goto next_pass;
}
break;
case oNoGreeting: /* Dummy option. */ break;
case oNoVerbose: opt.verbose = 0; break;
case oNoOptions: break; /* no-options */
case oHomedir: gnupg_set_homedir (pargs.r.ret_str); break;
case oNoDetach: nodetach = 1; break;
case oLogFile: logfile = pargs.r.ret_str; break;
case oCsh: csh_style = 1; break;
case oSh: csh_style = 0; break;
case oServer: pipe_server = 1; break;
case oDaemon: is_daemon = 1; break;
case oSupervised: is_supervised = 1; break;
case oDisplay: default_display = xstrdup (pargs.r.ret_str); break;
case oTTYname: default_ttyname = xstrdup (pargs.r.ret_str); break;
case oTTYtype: default_ttytype = xstrdup (pargs.r.ret_str); break;
case oLCctype: default_lc_ctype = xstrdup (pargs.r.ret_str); break;
case oLCmessages: default_lc_messages = xstrdup (pargs.r.ret_str);
break;
case oXauthority: default_xauthority = xstrdup (pargs.r.ret_str);
break;
case oUseStandardSocket:
case oNoUseStandardSocket:
obsolete_option (configname, configlineno, "use-standard-socket");
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 oKeepTTY: opt.keep_tty = 1; break;
case oKeepDISPLAY: opt.keep_display = 1; break;
case oSSHSupport:
ssh_support = 1;
break;
case oPuttySupport:
# ifdef HAVE_W32_SYSTEM
putty_support = 1;
# endif
break;
case oExtraSocket:
opt.extra_socket = 1; /* (1 = points into argv) */
socket_name_extra = pargs.r.ret_str;
break;
case oBrowserSocket:
opt.browser_socket = 1; /* (1 = points into argv) */
socket_name_browser = pargs.r.ret_str;
break;
case oAutoExpandSecmem:
/* Try to enable this option. It will officially only be
* supported by Libgcrypt 1.9 but 1.8.2 already supports it
* on the quiet and thus we use the numeric value value. */
gcry_control (78 /*GCRYCTL_AUTO_EXPAND_SECMEM*/,
(unsigned int)pargs.r.ret_ulong, 0);
break;
case oListenBacklog:
listen_backlog = pargs.r.ret_int;
break;
case oDebugQuickRandom:
/* Only used by the first stage command line parser. */
break;
case oWriteEnvFile:
obsolete_option (configname, configlineno, "write-env-file");
break;
default : pargs.err = configfp? 1:2; break;
}
}
if (configfp)
{
fclose( configfp );
configfp = NULL;
/* Keep a copy of the name so that it can be read on SIGHUP. */
if (config_filename != configname)
{
xfree (config_filename);
config_filename = configname;
}
configname = NULL;
goto next_pass;
}
xfree (configname);
configname = NULL;
if (log_get_errorcount(0))
exit(2);
finalize_rereadable_options ();
/* 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]);
}
#ifdef ENABLE_NLS
/* gpg-agent usually does not output any messages because it runs in
the background. For log files it is acceptable to have messages
always encoded in utf-8. We switch here to utf-8, so that
commands like --help still give native messages. It is far
easier to switch only once instead of for every message and it
actually helps when more then one thread is active (avoids an
extra copy step). */
bind_textdomain_codeset (PACKAGE_GT, "UTF-8");
#endif
if (!pipe_server && !is_daemon && !gpgconf_list && !is_supervised)
{
/* We have been called without any command and thus we merely
check whether an agent is already running. We do this right
here so that we don't clobber a logfile with this check but
print the status directly to stderr. */
opt.debug = 0;
set_debug ();
check_for_running_agent (0);
agent_exit (0);
}
if (is_supervised)
;
else if (!opt.extra_socket)
opt.extra_socket = 1;
else if (socket_name_extra
&& (!strcmp (socket_name_extra, "none")
|| !strcmp (socket_name_extra, "/dev/null")))
{
/* User requested not to create this socket. */
opt.extra_socket = 0;
socket_name_extra = NULL;
}
if (is_supervised)
;
else if (!opt.browser_socket)
opt.browser_socket = 1;
else if (socket_name_browser
&& (!strcmp (socket_name_browser, "none")
|| !strcmp (socket_name_browser, "/dev/null")))
{
/* User requested not to create this socket. */
opt.browser_socket = 0;
socket_name_browser = NULL;
}
set_debug ();
if (atexit (cleanup))
{
log_error ("atexit failed\n");
cleanup ();
exit (1);
}
/* Try to create missing directories. */
create_directories ();
if (debug_wait && pipe_server)
{
thread_init_once ();
log_debug ("waiting for debugger - my pid is %u .....\n",
(unsigned int)getpid());
gnupg_sleep (debug_wait);
log_debug ("... okay\n");
}
if (gpgconf_list == 3)
{
/* We now use the standard socket always - return true for
backward compatibility. */
agent_exit (0);
}
else if (gpgconf_list == 2)
agent_exit (0);
else if (gpgconf_list)
{
char *filename;
char *filename_esc;
/* List options and default values in the GPG Conf format. */
filename = make_filename (gnupg_homedir (),
GPG_AGENT_NAME EXTSEP_S "conf", NULL);
filename_esc = percent_escape (filename, NULL);
es_printf ("%s-%s.conf:%lu:\"%s\n",
GPGCONF_NAME, GPG_AGENT_NAME,
GC_OPT_FLAG_DEFAULT, filename_esc);
xfree (filename);
xfree (filename_esc);
es_printf ("verbose:%lu:\n"
"quiet:%lu:\n"
"debug-level:%lu:\"none:\n"
"log-file:%lu:\n",
GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME,
GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME );
es_printf ("default-cache-ttl:%lu:%d:\n",
GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL );
es_printf ("default-cache-ttl-ssh:%lu:%d:\n",
GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, DEFAULT_CACHE_TTL_SSH );
es_printf ("max-cache-ttl:%lu:%d:\n",
GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL );
es_printf ("max-cache-ttl-ssh:%lu:%d:\n",
GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MAX_CACHE_TTL_SSH );
es_printf ("enforce-passphrase-constraints:%lu:\n",
GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
es_printf ("min-passphrase-len:%lu:%d:\n",
GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, MIN_PASSPHRASE_LEN );
es_printf ("min-passphrase-nonalpha:%lu:%d:\n",
GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
MIN_PASSPHRASE_NONALPHA);
es_printf ("check-passphrase-pattern:%lu:\n",
GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
es_printf ("max-passphrase-days:%lu:%d:\n",
GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME,
MAX_PASSPHRASE_DAYS);
es_printf ("enable-passphrase-history:%lu:\n",
GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
es_printf ("no-grab:%lu:\n",
GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
es_printf ("ignore-cache-for-signing:%lu:\n",
GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
es_printf ("no-allow-external-cache:%lu:\n",
GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
es_printf ("no-allow-mark-trusted:%lu:\n",
GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
es_printf ("disable-scdaemon:%lu:\n",
GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
es_printf ("enable-ssh-support:%lu:\n", GC_OPT_FLAG_NONE);
es_printf ("ssh-fingerprint-digest:%lu:\"%s:\n",
GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME, "md5");
#ifdef HAVE_W32_SYSTEM
es_printf ("enable-putty-support:%lu:\n", GC_OPT_FLAG_NONE);
#endif
es_printf ("no-allow-loopback-pinentry:%lu:\n",
GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
es_printf ("allow-emacs-pinentry:%lu:\n",
GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
es_printf ("pinentry-timeout:%lu:0:\n",
GC_OPT_FLAG_DEFAULT|GC_OPT_FLAG_RUNTIME);
es_printf ("enable-extended-key-format:%lu:\n",
GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
es_printf ("grab:%lu:\n",
GC_OPT_FLAG_NONE|GC_OPT_FLAG_RUNTIME);
agent_exit (0);
}
/* Now start with logging to a file if this is desired. */
if (logfile)
{
log_set_file (logfile);
log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
| GPGRT_LOG_WITH_TIME
| GPGRT_LOG_WITH_PID));
current_logfile = xstrdup (logfile);
}
/* Make sure that we have a default ttyname. */
if (!default_ttyname && gnupg_ttyname (1))
default_ttyname = xstrdup (gnupg_ttyname (1));
if (!default_ttytype && getenv ("TERM"))
default_ttytype = xstrdup (getenv ("TERM"));
if (pipe_server)
{
/* This is the simple pipe based server */
ctrl_t ctrl;
initialize_modules ();
ctrl = xtrycalloc (1, sizeof *ctrl);
if (!ctrl)
{
log_error ("error allocating connection control data: %s\n",
strerror (errno) );
agent_exit (1);
}
ctrl->session_env = session_env_new ();
if (!ctrl->session_env)
{
log_error ("error allocating session environment block: %s\n",
strerror (errno) );
xfree (ctrl);
agent_exit (1);
}
agent_init_default_ctrl (ctrl);
start_command_handler (ctrl, GNUPG_INVALID_FD, GNUPG_INVALID_FD);
agent_deinit_default_ctrl (ctrl);
xfree (ctrl);
}
else if (is_supervised)
{
#ifndef HAVE_W32_SYSTEM
gnupg_fd_t fd, fd_extra, fd_browser, fd_ssh;
initialize_modules ();
/* when supervised and sending logs to stderr, the process
supervisor should handle log entry metadata (pid, name,
timestamp) */
if (!logfile)
log_set_prefix (NULL, 0);
log_info ("%s %s starting in supervised mode.\n",
strusage(11), strusage(13) );
/* See below in "regular server mode" on why we remove certain
* envvars. */
if (!opt.keep_display)
gnupg_unsetenv ("DISPLAY");
gnupg_unsetenv ("INSIDE_EMACS");
/* Virtually create the sockets. Note that we use -1 here
* because the whole thing works only on Unix. */
map_supervised_sockets (&fd, &fd_extra, &fd_browser, &fd_ssh);
if (fd == -1)
log_fatal ("no standard socket provided\n");
#ifdef HAVE_SIGPROCMASK
if (startup_signal_mask_valid)
{
if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
log_error ("error restoring signal mask: %s\n",
strerror (errno));
}
else
log_info ("no saved signal mask\n");
#endif /*HAVE_SIGPROCMASK*/
log_info ("listening on: std=%d extra=%d browser=%d ssh=%d\n",
fd, fd_extra, fd_browser, fd_ssh);
handle_connections (fd, fd_extra, fd_browser, fd_ssh);
#endif /*!HAVE_W32_SYSTEM*/
}
else if (!is_daemon)
; /* NOTREACHED */
else
{ /* Regular server mode */
gnupg_fd_t fd;
gnupg_fd_t fd_extra = GNUPG_INVALID_FD;
gnupg_fd_t fd_browser = GNUPG_INVALID_FD;
gnupg_fd_t fd_ssh = GNUPG_INVALID_FD;
#ifndef HAVE_W32_SYSTEM
pid_t pid;
#endif
/* Remove the DISPLAY variable so that a pinentry does not
default to a specific display. There is still a default
display when gpg-agent was started using --display or a
client requested this using an OPTION command. Note, that we
don't do this when running in reverse daemon mode (i.e. when
exec the program given as arguments). */
#ifndef HAVE_W32_SYSTEM
if (!opt.keep_display && !argc)
gnupg_unsetenv ("DISPLAY");
#endif
/* Remove the INSIDE_EMACS variable so that a pinentry does not
always try to interact with Emacs. The variable is set when
a client requested this using an OPTION command. */
gnupg_unsetenv ("INSIDE_EMACS");
/* Create the sockets. */
socket_name = create_socket_name (GPG_AGENT_SOCK_NAME, 1);
fd = create_server_socket (socket_name, 1, 0,
&redir_socket_name, &socket_nonce);
if (opt.extra_socket)
{
if (socket_name_extra)
socket_name_extra = create_socket_name (socket_name_extra, 0);
else
socket_name_extra = create_socket_name
/**/ (GPG_AGENT_EXTRA_SOCK_NAME, 1);
opt.extra_socket = 2; /* Indicate that it has been malloced. */
fd_extra = create_server_socket (socket_name_extra, 0, 0,
&redir_socket_name_extra,
&socket_nonce_extra);
}
if (opt.browser_socket)
{
if (socket_name_browser)
socket_name_browser = create_socket_name (socket_name_browser, 0);
else
socket_name_browser= create_socket_name
/**/ (GPG_AGENT_BROWSER_SOCK_NAME, 1);
opt.browser_socket = 2; /* Indicate that it has been malloced. */
fd_browser = create_server_socket (socket_name_browser, 0, 0,
&redir_socket_name_browser,
&socket_nonce_browser);
}
socket_name_ssh = create_socket_name (GPG_AGENT_SSH_SOCK_NAME, 1);
fd_ssh = create_server_socket (socket_name_ssh, 0, 1,
&redir_socket_name_ssh,
&socket_nonce_ssh);
/* If we are going to exec a program in the parent, we record
the PID, so that the child may check whether the program is
still alive. */
if (argc)
parent_pid = getpid ();
fflush (NULL);
#ifdef HAVE_W32_SYSTEM
(void)csh_style;
(void)nodetach;
initialize_modules ();
#else /*!HAVE_W32_SYSTEM*/
pid = fork ();
if (pid == (pid_t)-1)
{
log_fatal ("fork failed: %s\n", strerror (errno) );
exit (1);
}
else if (pid)
{ /* We are the parent */
char *infostr_ssh_sock, *infostr_ssh_valid;
/* Close the socket FD. */
close (fd);
/* The signal mask might not be correct right now and thus
we restore it. That is not strictly necessary but some
programs falsely assume a cleared signal mask. */
#ifdef HAVE_SIGPROCMASK
if (startup_signal_mask_valid)
{
if (sigprocmask (SIG_SETMASK, &startup_signal_mask, NULL))
log_error ("error restoring signal mask: %s\n",
strerror (errno));
}
else
log_info ("no saved signal mask\n");
#endif /*HAVE_SIGPROCMASK*/
/* Create the SSH info string if enabled. */
if (ssh_support)
{
if (asprintf (&infostr_ssh_sock, "SSH_AUTH_SOCK=%s",
socket_name_ssh) < 0)
{
log_error ("out of core\n");
kill (pid, SIGTERM);
exit (1);
}
if (asprintf (&infostr_ssh_valid, "gnupg_SSH_AUTH_SOCK_by=%lu",
(unsigned long)getpid()) < 0)
{
log_error ("out of core\n");
kill (pid, SIGTERM);
exit (1);
}
}
*socket_name = 0; /* Don't let cleanup() remove the socket -
the child should do this from now on */
if (opt.extra_socket)
*socket_name_extra = 0;
if (opt.browser_socket)
*socket_name_browser = 0;
*socket_name_ssh = 0;
if (argc)
{ /* Run the program given on the commandline. */
if (ssh_support && (putenv (infostr_ssh_sock)
|| putenv (infostr_ssh_valid)))
{
log_error ("failed to set environment: %s\n",
strerror (errno) );
kill (pid, SIGTERM );
exit (1);
}
/* Close all the file descriptors except the standard
ones and those open at startup. We explicitly don't
close 0,1,2 in case something went wrong collecting
them at startup. */
close_all_fds (3, startup_fd_list);
/* Run the command. */
execvp (argv[0], argv);
log_error ("failed to run the command: %s\n", strerror (errno));
kill (pid, SIGTERM);
exit (1);
}
else
{
/* Print the environment string, so that the caller can use
shell's eval to set it */
if (csh_style)
{
if (ssh_support)
{
*strchr (infostr_ssh_sock, '=') = ' ';
es_printf ("setenv %s;\n", infostr_ssh_sock);
}
}
else
{
if (ssh_support)
{
es_printf ("%s; export SSH_AUTH_SOCK;\n",
infostr_ssh_sock);
}
}
if (ssh_support)
{
xfree (infostr_ssh_sock);
xfree (infostr_ssh_valid);
}
exit (0);
}
/*NOTREACHED*/
} /* End parent */
/*
This is the child
*/
initialize_modules ();
/* Detach from tty and put process into a new session */
if (!nodetach )
{
int i;
unsigned int oldflags;
/* Close stdin, stdout and stderr unless it is the log stream */
for (i=0; i <= 2; i++)
{
if (!log_test_fd (i) && i != fd )
{
if ( ! close (i)
&& open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
{
log_error ("failed to open '%s': %s\n",
"/dev/null", strerror (errno));
cleanup ();
exit (1);
}
}
}
if (setsid() == -1)
{
log_error ("setsid() failed: %s\n", strerror(errno) );
cleanup ();
exit (1);
}
log_get_prefix (&oldflags);
log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED);
opt.running_detached = 1;
/* Unless we are running with a program given on the command
* line we can assume that the inotify things works and thus
- * we can avoid tye regular stat calls. */
+ * we can avoid the regular stat calls. */
if (!argc)
reliable_homedir_inotify = 1;
}
{
struct sigaction sa;
sa.sa_handler = SIG_IGN;
sigemptyset (&sa.sa_mask);
sa.sa_flags = 0;
sigaction (SIGPIPE, &sa, NULL);
}
#endif /*!HAVE_W32_SYSTEM*/
if (gnupg_chdir (gnupg_daemon_rootdir ()))
{
log_error ("chdir to '%s' failed: %s\n",
gnupg_daemon_rootdir (), strerror (errno));
exit (1);
}
log_info ("%s %s started\n", strusage(11), strusage(13) );
handle_connections (fd, fd_extra, fd_browser, fd_ssh);
assuan_sock_close (fd);
}
return 0;
}
/* Exit entry point. This function should be called instead of a
plain exit. */
void
agent_exit (int rc)
{
/*FIXME: update_random_seed_file();*/
/* We run our cleanup handler because that may close cipher contexts
stored in secure memory and thus this needs to be done before we
explicitly terminate secure memory. */
cleanup ();
#if 1
/* at this time a bit annoying */
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 );
#endif
gcry_control (GCRYCTL_TERM_SECMEM );
rc = rc? rc : log_get_errorcount(0)? 2 : 0;
exit (rc);
}
/* This is our callback function for gcrypt progress messages. It is
set once at startup and dispatches progress messages to the
corresponding threads of the agent. */
static void
agent_libgcrypt_progress_cb (void *data, const char *what, int printchar,
int current, int total)
{
struct progress_dispatch_s *dispatch;
npth_t mytid = npth_self ();
(void)data;
for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
if (dispatch->ctrl && dispatch->tid == mytid)
break;
if (dispatch && dispatch->cb)
dispatch->cb (dispatch->ctrl, what, printchar, current, total);
/* Libgcrypt < 1.8 does not know about nPth and thus when it reads
* from /dev/random this will block the process. To mitigate this
* problem we yield the thread when Libgcrypt tells us that it needs
* more entropy. This way other threads have chance to run. */
#if GCRYPT_VERSION_NUMBER < 0x010800 /* 1.8.0 */
if (what && !strcmp (what, "need_entropy"))
{
#if GPGRT_VERSION_NUMBER < 0x011900 /* 1.25 */
/* In older gpg-error versions gpgrt_yield is buggy for use with
* nPth and thus we need to resort to a sleep call. */
npth_usleep (1000); /* 1ms */
#else
gpgrt_yield ();
#endif
}
#endif
}
/* If a progress dispatcher callback has been associated with the
* current connection unregister it. */
static void
unregister_progress_cb (void)
{
struct progress_dispatch_s *dispatch;
npth_t mytid = npth_self ();
for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
if (dispatch->ctrl && dispatch->tid == mytid)
break;
if (dispatch)
{
dispatch->ctrl = NULL;
dispatch->cb = NULL;
}
}
/* Setup a progress callback CB for the current connection. Using a
* CB of NULL disables the callback. */
void
agent_set_progress_cb (void (*cb)(ctrl_t ctrl, const char *what,
int printchar, int current, int total),
ctrl_t ctrl)
{
struct progress_dispatch_s *dispatch, *firstfree;
npth_t mytid = npth_self ();
firstfree = NULL;
for (dispatch = progress_dispatch_list; dispatch; dispatch = dispatch->next)
{
if (dispatch->ctrl && dispatch->tid == mytid)
break;
if (!dispatch->ctrl && !firstfree)
firstfree = dispatch;
}
if (!dispatch) /* None allocated: Reuse or allocate a new one. */
{
if (firstfree)
{
dispatch = firstfree;
}
else if ((dispatch = xtrycalloc (1, sizeof *dispatch)))
{
dispatch->next = progress_dispatch_list;
progress_dispatch_list = dispatch;
}
else
{
log_error ("error allocating new progress dispatcher slot: %s\n",
gpg_strerror (gpg_error_from_syserror ()));
return;
}
dispatch->ctrl = ctrl;
dispatch->tid = mytid;
}
dispatch->cb = cb;
}
/* Each thread has its own local variables conveyed by a control
structure usually identified by an argument named CTRL. This
function is called immediately after allocating the control
structure. Its purpose is to setup the default values for that
structure. Note that some values may have already been set. */
static void
agent_init_default_ctrl (ctrl_t ctrl)
{
assert (ctrl->session_env);
/* Note we ignore malloc errors because we can't do much about it
and the request will fail anyway shortly after this
initialization. */
session_env_setenv (ctrl->session_env, "DISPLAY", default_display);
session_env_setenv (ctrl->session_env, "GPG_TTY", default_ttyname);
session_env_setenv (ctrl->session_env, "TERM", default_ttytype);
session_env_setenv (ctrl->session_env, "XAUTHORITY", default_xauthority);
session_env_setenv (ctrl->session_env, "PINENTRY_USER_DATA", NULL);
if (ctrl->lc_ctype)
xfree (ctrl->lc_ctype);
ctrl->lc_ctype = default_lc_ctype? xtrystrdup (default_lc_ctype) : NULL;
if (ctrl->lc_messages)
xfree (ctrl->lc_messages);
ctrl->lc_messages = default_lc_messages? xtrystrdup (default_lc_messages)
/**/ : NULL;
ctrl->cache_ttl_opt_preset = CACHE_TTL_OPT_PRESET;
}
/* Release all resources allocated by default in the control
structure. This is the counterpart to agent_init_default_ctrl. */
static void
agent_deinit_default_ctrl (ctrl_t ctrl)
{
unregister_progress_cb ();
session_env_release (ctrl->session_env);
if (ctrl->lc_ctype)
xfree (ctrl->lc_ctype);
if (ctrl->lc_messages)
xfree (ctrl->lc_messages);
}
/* Because the ssh protocol does not send us information about the
current TTY setting, we use this function to use those from startup
or those explicitly set. This is also used for the restricted mode
where we ignore requests to change the environment. */
gpg_error_t
agent_copy_startup_env (ctrl_t ctrl)
{
gpg_error_t err = 0;
int iterator = 0;
const char *name, *value;
while (!err && (name = session_env_list_stdenvnames (&iterator, NULL)))
{
if ((value = session_env_getenv (opt.startup_env, name)))
err = session_env_setenv (ctrl->session_env, name, value);
}
if (!err && !ctrl->lc_ctype && opt.startup_lc_ctype)
if (!(ctrl->lc_ctype = xtrystrdup (opt.startup_lc_ctype)))
err = gpg_error_from_syserror ();
if (!err && !ctrl->lc_messages && opt.startup_lc_messages)
if (!(ctrl->lc_messages = xtrystrdup (opt.startup_lc_messages)))
err = gpg_error_from_syserror ();
if (err)
log_error ("error setting default session environment: %s\n",
gpg_strerror (err));
return err;
}
/* Reread parts of the configuration. Note, that this function is
obviously not thread-safe and should only be called from the PTH
signal handler.
Fixme: Due to the way the argument parsing works, we create a
memory leak here for all string type arguments. There is currently
no clean way to tell whether the memory for the argument has been
allocated or points into the process' original arguments. Unless
we have a mechanism to tell this, we need to live on with this. */
static void
reread_configuration (void)
{
ARGPARSE_ARGS pargs;
FILE *fp;
unsigned int configlineno = 0;
int dummy;
if (!config_filename)
return; /* No config file. */
fp = fopen (config_filename, "r");
if (!fp)
{
log_info (_("option file '%s': %s\n"),
config_filename, strerror(errno) );
return;
}
parse_rereadable_options (NULL, 1); /* Start from the default values. */
memset (&pargs, 0, sizeof pargs);
dummy = 0;
pargs.argc = &dummy;
pargs.flags = 1; /* do not remove the args */
while (optfile_parse (fp, config_filename, &configlineno, &pargs, opts) )
{
if (pargs.r_opt < -1)
pargs.err = 1; /* Print a warning. */
else /* Try to parse this option - ignore unchangeable ones. */
parse_rereadable_options (&pargs, 1);
}
fclose (fp);
finalize_rereadable_options ();
set_debug ();
}
/* Return the file name of the socket we are using for native
requests. */
const char *
get_agent_socket_name (void)
{
const char *s = socket_name;
return (s && *s)? s : NULL;
}
/* Return the file name of the socket we are using for SSH
requests. */
const char *
get_agent_ssh_socket_name (void)
{
const char *s = socket_name_ssh;
return (s && *s)? s : NULL;
}
/* Return the number of active connections. */
int
get_agent_active_connection_count (void)
{
return active_connections;
}
/* Under W32, this function returns the handle of the scdaemon
notification event. Calling it the first time creates that
event. */
#if defined(HAVE_W32_SYSTEM) && !defined(HAVE_W32CE_SYSTEM)
void *
get_agent_scd_notify_event (void)
{
static HANDLE the_event = INVALID_HANDLE_VALUE;
if (the_event == INVALID_HANDLE_VALUE)
{
HANDLE h, h2;
SECURITY_ATTRIBUTES sa = { sizeof (SECURITY_ATTRIBUTES), NULL, TRUE};
/* We need to use a manual reset event object due to the way our
w32-pth wait function works: If we would use an automatic
reset event we are not able to figure out which handle has
been signaled because at the time we single out the signaled
handles using WFSO the event has already been reset due to
the WFMO. */
h = CreateEvent (&sa, TRUE, FALSE, NULL);
if (!h)
log_error ("can't create scd notify event: %s\n", w32_strerror (-1) );
else if (!DuplicateHandle (GetCurrentProcess(), h,
GetCurrentProcess(), &h2,
EVENT_MODIFY_STATE|SYNCHRONIZE, TRUE, 0))
{
- log_error ("setting syncronize for scd notify event failed: %s\n",
+ log_error ("setting synchronize for scd notify event failed: %s\n",
w32_strerror (-1) );
CloseHandle (h);
}
else
{
CloseHandle (h);
the_event = h2;
}
}
return the_event;
}
#endif /*HAVE_W32_SYSTEM && !HAVE_W32CE_SYSTEM*/
/* Create a name for the socket in the home directory as using
STANDARD_NAME. We also check for valid characters as well as
against a maximum allowed length for a unix domain socket is done.
The function terminates the process in case of an error. Returns:
Pointer to an allocated string with the absolute name of the socket
used. */
static char *
create_socket_name (char *standard_name, int with_homedir)
{
char *name;
if (with_homedir)
name = make_filename (gnupg_socketdir (), standard_name, NULL);
else
name = make_filename (standard_name, NULL);
if (strchr (name, PATHSEP_C))
{
log_error (("'%s' are not allowed in the socket name\n"), PATHSEP_S);
agent_exit (2);
}
return name;
}
/* Create a Unix domain socket with NAME. Returns the file descriptor
or terminates the process in case of an error. Note that this
function needs to be used for the regular socket first (indicated
by PRIMARY) and only then for the extra and the ssh sockets. If
the socket has been redirected the name of the real socket is
stored as a malloced string at R_REDIR_NAME. If CYGWIN is set a
Cygwin compatible socket is created (Windows only). */
static gnupg_fd_t
create_server_socket (char *name, int primary, int cygwin,
char **r_redir_name, assuan_sock_nonce_t *nonce)
{
struct sockaddr *addr;
struct sockaddr_un *unaddr;
socklen_t len;
gnupg_fd_t fd;
int rc;
xfree (*r_redir_name);
*r_redir_name = NULL;
fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
if (fd == ASSUAN_INVALID_FD)
{
log_error (_("can't create socket: %s\n"), strerror (errno));
*name = 0; /* Inhibit removal of the socket by cleanup(). */
agent_exit (2);
}
if (cygwin)
assuan_sock_set_flag (fd, "cygwin", 1);
unaddr = xmalloc (sizeof *unaddr);
addr = (struct sockaddr*)unaddr;
{
int redirected;
if (assuan_sock_set_sockaddr_un (name, addr, &redirected))
{
if (errno == ENAMETOOLONG)
log_error (_("socket name '%s' is too long\n"), name);
else
log_error ("error preparing socket '%s': %s\n",
name, gpg_strerror (gpg_error_from_syserror ()));
*name = 0; /* Inhibit removal of the socket by cleanup(). */
xfree (unaddr);
agent_exit (2);
}
if (redirected)
{
*r_redir_name = xstrdup (unaddr->sun_path);
if (opt.verbose)
log_info ("redirecting socket '%s' to '%s'\n", name, *r_redir_name);
}
}
len = SUN_LEN (unaddr);
rc = assuan_sock_bind (fd, addr, len);
/* Our error code mapping on W32CE returns EEXIST thus we also test
for this. */
if (rc == -1
&& (errno == EADDRINUSE
#ifdef HAVE_W32_SYSTEM
|| errno == EEXIST
#endif
))
{
/* Check whether a gpg-agent is already running. We do this
test only if this is the primary socket. For secondary
sockets we assume that a test for gpg-agent has already been
done and reuse the requested socket. Testing the ssh-socket
is not possible because at this point, though we know the new
Assuan socket, the Assuan server and thus the ssh-agent
server is not yet operational; this would lead to a hang. */
if (primary && !check_for_running_agent (1))
{
log_set_prefix (NULL, GPGRT_LOG_WITH_PREFIX);
log_set_file (NULL);
log_error (_("a gpg-agent is already running - "
"not starting a new one\n"));
*name = 0; /* Inhibit removal of the socket by cleanup(). */
assuan_sock_close (fd);
xfree (unaddr);
agent_exit (2);
}
gnupg_remove (unaddr->sun_path);
rc = assuan_sock_bind (fd, addr, len);
}
if (rc != -1 && (rc=assuan_sock_get_nonce (addr, len, nonce)))
log_error (_("error getting nonce for the socket\n"));
if (rc == -1)
{
/* We use gpg_strerror here because it allows us to get strings
for some W32 socket error codes. */
log_error (_("error binding socket to '%s': %s\n"),
unaddr->sun_path,
gpg_strerror (gpg_error_from_syserror ()));
assuan_sock_close (fd);
*name = 0; /* Inhibit removal of the socket by cleanup(). */
xfree (unaddr);
agent_exit (2);
}
if (gnupg_chmod (unaddr->sun_path, "-rwx"))
log_error (_("can't set permissions of '%s': %s\n"),
unaddr->sun_path, strerror (errno));
if (listen (FD2INT(fd), listen_backlog ) == -1)
{
log_error ("listen(fd,%d) failed: %s\n",
listen_backlog, strerror (errno));
*name = 0; /* Inhibit removal of the socket by cleanup(). */
assuan_sock_close (fd);
xfree (unaddr);
agent_exit (2);
}
if (opt.verbose)
log_info (_("listening on socket '%s'\n"), unaddr->sun_path);
xfree (unaddr);
return fd;
}
/* Check that the directory for storing the private keys exists and
create it if not. This function won't fail as it is only a
convenience function and not strictly necessary. */
static void
create_private_keys_directory (const char *home)
{
char *fname;
struct stat statbuf;
fname = make_filename (home, GNUPG_PRIVATE_KEYS_DIR, NULL);
if (stat (fname, &statbuf) && errno == ENOENT)
{
if (gnupg_mkdir (fname, "-rwx"))
log_error (_("can't create directory '%s': %s\n"),
fname, strerror (errno) );
else if (!opt.quiet)
log_info (_("directory '%s' created\n"), fname);
}
if (gnupg_chmod (fname, "-rwx"))
log_error (_("can't set permissions of '%s': %s\n"),
fname, strerror (errno));
xfree (fname);
}
/* Create the directory only if the supplied directory name is the
same as the default one. This way we avoid to create arbitrary
directories when a non-default home directory is used. To cope
with HOME, we compare only the suffix if we see that the default
homedir does start with a tilde. We don't stop here in case of
problems because other functions will throw an error anyway.*/
static void
create_directories (void)
{
struct stat statbuf;
const char *defhome = standard_homedir ();
char *home;
home = make_filename (gnupg_homedir (), NULL);
if ( stat (home, &statbuf) )
{
if (errno == ENOENT)
{
if (
#ifdef HAVE_W32_SYSTEM
( !compare_filenames (home, defhome) )
#else
(*defhome == '~'
&& (strlen (home) >= strlen (defhome+1)
&& !strcmp (home + strlen(home)
- strlen (defhome+1), defhome+1)))
|| (*defhome != '~' && !strcmp (home, defhome) )
#endif
)
{
if (gnupg_mkdir (home, "-rwx"))
log_error (_("can't create directory '%s': %s\n"),
home, strerror (errno) );
else
{
if (!opt.quiet)
log_info (_("directory '%s' created\n"), home);
create_private_keys_directory (home);
}
}
}
else
log_error (_("stat() failed for '%s': %s\n"), home, strerror (errno));
}
else if ( !S_ISDIR(statbuf.st_mode))
{
log_error (_("can't use '%s' as home directory\n"), home);
}
else /* exists and is a directory. */
{
create_private_keys_directory (home);
}
xfree (home);
}
/* This is the worker for the ticker. It is called every few seconds
and may only do fast operations. */
static void
handle_tick (void)
{
static time_t last_minute;
struct stat statbuf;
if (!last_minute)
last_minute = time (NULL);
/* Check whether the scdaemon has died and cleanup in this case. */
agent_scd_check_aliveness ();
/* If we are running as a child of another process, check whether
the parent is still alive and shutdown if not. */
#ifndef HAVE_W32_SYSTEM
if (parent_pid != (pid_t)(-1))
{
if (kill (parent_pid, 0))
{
shutdown_pending = 2;
log_info ("parent process died - shutting down\n");
log_info ("%s %s stopped\n", strusage(11), strusage(13) );
cleanup ();
agent_exit (0);
}
}
#endif /*HAVE_W32_SYSTEM*/
/* Code to be run from time to time. */
#if CHECK_OWN_SOCKET_INTERVAL > 0
if (last_minute + CHECK_OWN_SOCKET_INTERVAL <= time (NULL))
{
check_own_socket ();
last_minute = time (NULL);
}
#endif
/* Need to check for expired cache entries. */
agent_cache_housekeeping ();
/* Check whether the homedir is still available. */
if (!shutdown_pending
&& (!have_homedir_inotify || !reliable_homedir_inotify)
&& stat (gnupg_homedir (), &statbuf) && errno == ENOENT)
{
shutdown_pending = 1;
log_info ("homedir has been removed - shutting down\n");
}
}
/* A global function which allows us to call the reload stuff from
other places too. This is only used when build for W32. */
void
agent_sighup_action (void)
{
log_info ("SIGHUP received - "
"re-reading configuration and flushing cache\n");
agent_flush_cache ();
reread_configuration ();
agent_reload_trustlist ();
/* We flush the module name cache so that after installing a
"pinentry" binary that one can be used in case the
"pinentry-basic" fallback was in use. */
gnupg_module_name_flush_some ();
}
/* A helper function to handle SIGUSR2. */
static void
agent_sigusr2_action (void)
{
if (opt.verbose)
log_info ("SIGUSR2 received - updating card event counter\n");
/* Nothing to check right now. We only increment a counter. */
bump_card_eventcounter ();
}
#ifndef HAVE_W32_SYSTEM
/* The signal handler for this program. It is expected to be run in
its own thread and not in the context of a signal handler. */
static void
handle_signal (int signo)
{
switch (signo)
{
#ifndef HAVE_W32_SYSTEM
case SIGHUP:
agent_sighup_action ();
break;
case SIGUSR1:
log_info ("SIGUSR1 received - printing internal information:\n");
/* Fixme: We need to see how to integrate pth dumping into our
logging system. */
/* pth_ctrl (PTH_CTRL_DUMPSTATE, log_get_stream ()); */
agent_query_dump_state ();
agent_scd_dump_state ();
break;
case SIGUSR2:
agent_sigusr2_action ();
break;
case SIGTERM:
if (!shutdown_pending)
log_info ("SIGTERM received - shutting down ...\n");
else
log_info ("SIGTERM received - still %i open connections\n",
active_connections);
shutdown_pending++;
if (shutdown_pending > 2)
{
log_info ("shutdown forced\n");
log_info ("%s %s stopped\n", strusage(11), strusage(13) );
cleanup ();
agent_exit (0);
}
break;
case SIGINT:
log_info ("SIGINT received - immediate shutdown\n");
log_info( "%s %s stopped\n", strusage(11), strusage(13));
cleanup ();
agent_exit (0);
break;
#endif
default:
log_info ("signal %d received - no action defined\n", signo);
}
}
#endif
/* Check the nonce on a new connection. This is a NOP unless we
are using our Unix domain socket emulation under Windows. */
static int
check_nonce (ctrl_t ctrl, assuan_sock_nonce_t *nonce)
{
if (assuan_sock_check_nonce (ctrl->thread_startup.fd, nonce))
{
log_info (_("error reading nonce on fd %d: %s\n"),
FD2INT(ctrl->thread_startup.fd), strerror (errno));
assuan_sock_close (ctrl->thread_startup.fd);
xfree (ctrl);
return -1;
}
else
return 0;
}
#ifdef HAVE_W32_SYSTEM
/* The window message processing function for Putty. Warning: This
code runs as a native Windows thread. Use of our own functions
needs to be bracket with pth_leave/pth_enter. */
static LRESULT CALLBACK
putty_message_proc (HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
int ret = 0;
int w32rc;
COPYDATASTRUCT *cds;
const char *mapfile;
HANDLE maphd;
PSID mysid = NULL;
PSID mapsid = NULL;
void *data = NULL;
PSECURITY_DESCRIPTOR psd = NULL;
ctrl_t ctrl = NULL;
if (msg != WM_COPYDATA)
{
return DefWindowProc (hwnd, msg, wparam, lparam);
}
cds = (COPYDATASTRUCT*)lparam;
if (cds->dwData != PUTTY_IPC_MAGIC)
return 0; /* Ignore data with the wrong magic. */
mapfile = cds->lpData;
if (!cds->cbData || mapfile[cds->cbData - 1])
return 0; /* Ignore empty and non-properly terminated strings. */
if (DBG_IPC)
{
npth_protect ();
log_debug ("ssh map file '%s'", mapfile);
npth_unprotect ();
}
maphd = OpenFileMapping (FILE_MAP_ALL_ACCESS, FALSE, mapfile);
if (DBG_IPC)
{
npth_protect ();
log_debug ("ssh map handle %p\n", maphd);
npth_unprotect ();
}
if (!maphd || maphd == INVALID_HANDLE_VALUE)
return 0;
npth_protect ();
mysid = w32_get_user_sid ();
if (!mysid)
{
log_error ("error getting my sid\n");
goto leave;
}
w32rc = GetSecurityInfo (maphd, SE_KERNEL_OBJECT,
OWNER_SECURITY_INFORMATION,
&mapsid, NULL, NULL, NULL,
&psd);
if (w32rc)
{
log_error ("error getting sid of ssh map file: rc=%d", w32rc);
goto leave;
}
if (DBG_IPC)
{
char *sidstr;
if (!ConvertSidToStringSid (mysid, &sidstr))
sidstr = NULL;
log_debug (" my sid: '%s'", sidstr? sidstr: "[error]");
LocalFree (sidstr);
if (!ConvertSidToStringSid (mapsid, &sidstr))
sidstr = NULL;
log_debug ("ssh map file sid: '%s'", sidstr? sidstr: "[error]");
LocalFree (sidstr);
}
if (!EqualSid (mysid, mapsid))
{
log_error ("ssh map file has a non-matching sid\n");
goto leave;
}
data = MapViewOfFile (maphd, FILE_MAP_ALL_ACCESS, 0, 0, 0);
if (DBG_IPC)
log_debug ("ssh IPC buffer at %p\n", data);
if (!data)
goto leave;
/* log_printhex ("request:", data, 20); */
ctrl = xtrycalloc (1, sizeof *ctrl);
if (!ctrl)
{
log_error ("error allocating connection control data: %s\n",
strerror (errno) );
goto leave;
}
ctrl->session_env = session_env_new ();
if (!ctrl->session_env)
{
log_error ("error allocating session environment block: %s\n",
strerror (errno) );
goto leave;
}
agent_init_default_ctrl (ctrl);
if (!serve_mmapped_ssh_request (ctrl, data, PUTTY_IPC_MAXLEN))
ret = 1; /* Valid ssh message has been constructed. */
agent_deinit_default_ctrl (ctrl);
/* log_printhex (" reply:", data, 20); */
leave:
xfree (ctrl);
if (data)
UnmapViewOfFile (data);
xfree (mapsid);
if (psd)
LocalFree (psd);
xfree (mysid);
CloseHandle (maphd);
npth_unprotect ();
return ret;
}
#endif /*HAVE_W32_SYSTEM*/
#ifdef HAVE_W32_SYSTEM
/* The thread handling Putty's IPC requests. */
static void *
putty_message_thread (void *arg)
{
WNDCLASS wndwclass = {0, putty_message_proc, 0, 0,
NULL, NULL, NULL, NULL, NULL, "Pageant"};
HWND hwnd;
MSG msg;
(void)arg;
if (opt.verbose)
log_info ("putty message loop thread started\n");
/* The message loop runs as thread independent from our nPth system.
This also means that we need to make sure that we switch back to
our system before calling any no-windows function. */
npth_unprotect ();
/* First create a window to make sure that a message queue exists
for this thread. */
if (!RegisterClass (&wndwclass))
{
npth_protect ();
log_error ("error registering Pageant window class");
return NULL;
}
hwnd = CreateWindowEx (0, "Pageant", "Pageant", 0,
0, 0, 0, 0,
HWND_MESSAGE, /* hWndParent */
NULL, /* hWndMenu */
NULL, /* hInstance */
NULL); /* lpParm */
if (!hwnd)
{
npth_protect ();
log_error ("error creating Pageant window");
return NULL;
}
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
/* Back to nPth. */
npth_protect ();
if (opt.verbose)
log_info ("putty message loop thread stopped\n");
return NULL;
}
#endif /*HAVE_W32_SYSTEM*/
static void *
do_start_connection_thread (ctrl_t ctrl)
{
active_connections++;
agent_init_default_ctrl (ctrl);
if (opt.verbose && !DBG_IPC)
log_info (_("handler 0x%lx for fd %d started\n"),
(unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
start_command_handler (ctrl, GNUPG_INVALID_FD, ctrl->thread_startup.fd);
if (opt.verbose && !DBG_IPC)
log_info (_("handler 0x%lx for fd %d terminated\n"),
(unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
agent_deinit_default_ctrl (ctrl);
xfree (ctrl);
active_connections--;
return NULL;
}
/* This is the standard connection thread's main function. */
static void *
start_connection_thread_std (void *arg)
{
ctrl_t ctrl = arg;
if (check_nonce (ctrl, &socket_nonce))
{
log_error ("handler 0x%lx nonce check FAILED\n",
(unsigned long) npth_self());
return NULL;
}
return do_start_connection_thread (ctrl);
}
/* This is the extra socket connection thread's main function. */
static void *
start_connection_thread_extra (void *arg)
{
ctrl_t ctrl = arg;
if (check_nonce (ctrl, &socket_nonce_extra))
{
log_error ("handler 0x%lx nonce check FAILED\n",
(unsigned long) npth_self());
return NULL;
}
ctrl->restricted = 1;
return do_start_connection_thread (ctrl);
}
/* This is the browser socket connection thread's main function. */
static void *
start_connection_thread_browser (void *arg)
{
ctrl_t ctrl = arg;
if (check_nonce (ctrl, &socket_nonce_browser))
{
log_error ("handler 0x%lx nonce check FAILED\n",
(unsigned long) npth_self());
return NULL;
}
ctrl->restricted = 2;
return do_start_connection_thread (ctrl);
}
/* This is the ssh connection thread's main function. */
static void *
start_connection_thread_ssh (void *arg)
{
ctrl_t ctrl = arg;
if (check_nonce (ctrl, &socket_nonce_ssh))
return NULL;
active_connections++;
agent_init_default_ctrl (ctrl);
if (opt.verbose)
log_info (_("ssh handler 0x%lx for fd %d started\n"),
(unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
start_command_handler_ssh (ctrl, ctrl->thread_startup.fd);
if (opt.verbose)
log_info (_("ssh handler 0x%lx for fd %d terminated\n"),
(unsigned long) npth_self(), FD2INT(ctrl->thread_startup.fd));
agent_deinit_default_ctrl (ctrl);
xfree (ctrl);
active_connections--;
return NULL;
}
/* Connection handler loop. Wait for connection requests and spawn a
thread after accepting a connection. */
static void
handle_connections (gnupg_fd_t listen_fd,
gnupg_fd_t listen_fd_extra,
gnupg_fd_t listen_fd_browser,
gnupg_fd_t listen_fd_ssh)
{
gpg_error_t err;
npth_attr_t tattr;
struct sockaddr_un paddr;
socklen_t plen;
fd_set fdset, read_fdset;
int ret;
gnupg_fd_t fd;
int nfd;
int saved_errno;
struct timespec abstime;
struct timespec curtime;
struct timespec timeout;
#ifdef HAVE_W32_SYSTEM
HANDLE events[2];
unsigned int events_set;
#endif
int sock_inotify_fd = -1;
int home_inotify_fd = -1;
struct {
const char *name;
void *(*func) (void *arg);
gnupg_fd_t l_fd;
} listentbl[] = {
{ "std", start_connection_thread_std },
{ "extra", start_connection_thread_extra },
{ "browser", start_connection_thread_browser },
{ "ssh", start_connection_thread_ssh }
};
ret = npth_attr_init(&tattr);
if (ret)
log_fatal ("error allocating thread attributes: %s\n",
strerror (ret));
npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
#ifndef HAVE_W32_SYSTEM
npth_sigev_init ();
npth_sigev_add (SIGHUP);
npth_sigev_add (SIGUSR1);
npth_sigev_add (SIGUSR2);
npth_sigev_add (SIGINT);
npth_sigev_add (SIGTERM);
npth_sigev_fini ();
#else
# ifdef HAVE_W32CE_SYSTEM
/* Use a dummy event. */
sigs = 0;
ev = pth_event (PTH_EVENT_SIGS, &sigs, &signo);
# else
events[0] = get_agent_scd_notify_event ();
events[1] = INVALID_HANDLE_VALUE;
# endif
#endif
if (disable_check_own_socket)
sock_inotify_fd = -1;
else if ((err = gnupg_inotify_watch_socket (&sock_inotify_fd, socket_name)))
{
if (gpg_err_code (err) != GPG_ERR_NOT_SUPPORTED)
log_info ("error enabling daemon termination by socket removal: %s\n",
gpg_strerror (err));
}
if (disable_check_own_socket)
home_inotify_fd = -1;
else if ((err = gnupg_inotify_watch_delete_self (&home_inotify_fd,
gnupg_homedir ())))
{
if (gpg_err_code (err) != GPG_ERR_NOT_SUPPORTED)
log_info ("error enabling daemon termination by homedir removal: %s\n",
gpg_strerror (err));
}
else
have_homedir_inotify = 1;
/* On Windows we need to fire up a separate thread to listen for
requests from Putty (an SSH client), so we can replace Putty's
Pageant (its ssh-agent implementation). */
#ifdef HAVE_W32_SYSTEM
if (putty_support)
{
npth_t thread;
ret = npth_create (&thread, &tattr, putty_message_thread, NULL);
if (ret)
{
log_error ("error spawning putty message loop: %s\n", strerror (ret));
}
}
#endif /*HAVE_W32_SYSTEM*/
/* Set a flag to tell call-scd.c that it may enable event
notifications. */
opt.sigusr2_enabled = 1;
FD_ZERO (&fdset);
FD_SET (FD2INT (listen_fd), &fdset);
nfd = FD2INT (listen_fd);
if (listen_fd_extra != GNUPG_INVALID_FD)
{
FD_SET ( FD2INT(listen_fd_extra), &fdset);
if (FD2INT (listen_fd_extra) > nfd)
nfd = FD2INT (listen_fd_extra);
}
if (listen_fd_browser != GNUPG_INVALID_FD)
{
FD_SET ( FD2INT(listen_fd_browser), &fdset);
if (FD2INT (listen_fd_browser) > nfd)
nfd = FD2INT (listen_fd_browser);
}
if (listen_fd_ssh != GNUPG_INVALID_FD)
{
FD_SET ( FD2INT(listen_fd_ssh), &fdset);
if (FD2INT (listen_fd_ssh) > nfd)
nfd = FD2INT (listen_fd_ssh);
}
if (sock_inotify_fd != -1)
{
FD_SET (sock_inotify_fd, &fdset);
if (sock_inotify_fd > nfd)
nfd = sock_inotify_fd;
}
if (home_inotify_fd != -1)
{
FD_SET (home_inotify_fd, &fdset);
if (home_inotify_fd > nfd)
nfd = home_inotify_fd;
}
listentbl[0].l_fd = listen_fd;
listentbl[1].l_fd = listen_fd_extra;
listentbl[2].l_fd = listen_fd_browser;
listentbl[3].l_fd = listen_fd_ssh;
npth_clock_gettime (&abstime);
abstime.tv_sec += TIMERTICK_INTERVAL;
for (;;)
{
/* Shutdown test. */
if (shutdown_pending)
{
if (active_connections == 0)
break; /* ready */
/* Do not accept new connections but keep on running the
* loop to cope with the timer events.
*
* Note that we do not close the listening socket because a
* client trying to connect to that socket would instead
* restart a new dirmngr instance - which is unlikely the
* intention of a shutdown. */
FD_ZERO (&fdset);
nfd = -1;
if (sock_inotify_fd != -1)
{
FD_SET (sock_inotify_fd, &fdset);
nfd = sock_inotify_fd;
}
if (home_inotify_fd != -1)
{
FD_SET (home_inotify_fd, &fdset);
if (home_inotify_fd > nfd)
nfd = home_inotify_fd;
}
}
/* POSIX says that fd_set should be implemented as a structure,
thus a simple assignment is fine to copy the entire set. */
read_fdset = fdset;
npth_clock_gettime (&curtime);
if (!(npth_timercmp (&curtime, &abstime, <)))
{
/* Timeout. */
handle_tick ();
npth_clock_gettime (&abstime);
abstime.tv_sec += TIMERTICK_INTERVAL;
}
npth_timersub (&abstime, &curtime, &timeout);
#ifndef HAVE_W32_SYSTEM
ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
npth_sigev_sigmask ());
saved_errno = errno;
{
int signo;
while (npth_sigev_get_pending (&signo))
handle_signal (signo);
}
#else
ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
events, &events_set);
saved_errno = errno;
/* This is valid even if npth_eselect returns an error. */
if (events_set & 1)
agent_sigusr2_action ();
#endif
if (ret == -1 && saved_errno != EINTR)
{
log_error (_("npth_pselect failed: %s - waiting 1s\n"),
strerror (saved_errno));
npth_sleep (1);
continue;
}
if (ret <= 0)
/* Interrupt or timeout. Will be handled when calculating the
next timeout. */
continue;
/* The inotify fds are set even when a shutdown is pending (see
* above). So we must handle them in any case. To avoid that
* they trigger a second time we close them immediately. */
if (sock_inotify_fd != -1
&& FD_ISSET (sock_inotify_fd, &read_fdset)
&& gnupg_inotify_has_name (sock_inotify_fd, GPG_AGENT_SOCK_NAME))
{
shutdown_pending = 1;
close (sock_inotify_fd);
sock_inotify_fd = -1;
log_info ("socket file has been removed - shutting down\n");
}
if (home_inotify_fd != -1
&& FD_ISSET (home_inotify_fd, &read_fdset))
{
shutdown_pending = 1;
close (home_inotify_fd);
home_inotify_fd = -1;
log_info ("homedir has been removed - shutting down\n");
}
if (!shutdown_pending)
{
int idx;
ctrl_t ctrl;
npth_t thread;
for (idx=0; idx < DIM(listentbl); idx++)
{
if (listentbl[idx].l_fd == GNUPG_INVALID_FD)
continue;
if (!FD_ISSET (FD2INT (listentbl[idx].l_fd), &read_fdset))
continue;
plen = sizeof paddr;
fd = INT2FD (npth_accept (FD2INT(listentbl[idx].l_fd),
(struct sockaddr *)&paddr, &plen));
if (fd == GNUPG_INVALID_FD)
{
log_error ("accept failed for %s: %s\n",
listentbl[idx].name, strerror (errno));
}
else if ( !(ctrl = xtrycalloc (1, sizeof *ctrl)))
{
log_error ("error allocating connection data for %s: %s\n",
listentbl[idx].name, strerror (errno) );
assuan_sock_close (fd);
}
else if ( !(ctrl->session_env = session_env_new ()))
{
log_error ("error allocating session env block for %s: %s\n",
listentbl[idx].name, strerror (errno) );
xfree (ctrl);
assuan_sock_close (fd);
}
else
{
ctrl->thread_startup.fd = fd;
ret = npth_create (&thread, &tattr,
listentbl[idx].func, ctrl);
if (ret)
{
log_error ("error spawning connection handler for %s:"
" %s\n", listentbl[idx].name, strerror (ret));
assuan_sock_close (fd);
xfree (ctrl);
}
}
}
}
}
if (sock_inotify_fd != -1)
close (sock_inotify_fd);
if (home_inotify_fd != -1)
close (home_inotify_fd);
cleanup ();
log_info (_("%s %s stopped\n"), strusage(11), strusage(13));
npth_attr_destroy (&tattr);
}
/* Helper for check_own_socket. */
static gpg_error_t
check_own_socket_pid_cb (void *opaque, const void *buffer, size_t length)
{
membuf_t *mb = opaque;
put_membuf (mb, buffer, length);
return 0;
}
/* The thread running the actual check. We need to run this in a
separate thread so that check_own_thread can be called from the
timer tick. */
static void *
check_own_socket_thread (void *arg)
{
int rc;
char *sockname = arg;
assuan_context_t ctx = NULL;
membuf_t mb;
char *buffer;
check_own_socket_running++;
rc = assuan_new (&ctx);
if (rc)
{
log_error ("can't allocate assuan context: %s\n", gpg_strerror (rc));
goto leave;
}
assuan_set_flag (ctx, ASSUAN_NO_LOGGING, 1);
rc = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
if (rc)
{
log_error ("can't connect my own socket: %s\n", gpg_strerror (rc));
goto leave;
}
init_membuf (&mb, 100);
rc = assuan_transact (ctx, "GETINFO pid", check_own_socket_pid_cb, &mb,
NULL, NULL, NULL, NULL);
put_membuf (&mb, "", 1);
buffer = get_membuf (&mb, NULL);
if (rc || !buffer)
{
log_error ("sending command \"%s\" to my own socket failed: %s\n",
"GETINFO pid", gpg_strerror (rc));
rc = 1;
}
else if ( (pid_t)strtoul (buffer, NULL, 10) != getpid ())
{
log_error ("socket is now serviced by another server\n");
rc = 1;
}
else if (opt.verbose > 1)
log_error ("socket is still served by this server\n");
xfree (buffer);
leave:
xfree (sockname);
if (ctx)
assuan_release (ctx);
if (rc)
{
/* We may not remove the socket as it is now in use by another
server. */
inhibit_socket_removal = 1;
shutdown_pending = 2;
log_info ("this process is useless - shutting down\n");
}
check_own_socket_running--;
return NULL;
}
/* Check whether we are still listening on our own socket. In case
another gpg-agent process started after us has taken ownership of
our socket, we would linger around without any real task. Thus we
better check once in a while whether we are really needed. */
static void
check_own_socket (void)
{
char *sockname;
npth_t thread;
npth_attr_t tattr;
int err;
if (disable_check_own_socket)
return;
if (check_own_socket_running || shutdown_pending)
return; /* Still running or already shutting down. */
sockname = make_filename_try (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL);
if (!sockname)
return; /* Out of memory. */
err = npth_attr_init (&tattr);
if (err)
return;
npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
err = npth_create (&thread, &tattr, check_own_socket_thread, sockname);
if (err)
log_error ("error spawning check_own_socket_thread: %s\n", strerror (err));
npth_attr_destroy (&tattr);
}
/* Figure out whether an agent is available and running. Prints an
error if not. If SILENT is true, no messages are printed.
Returns 0 if the agent is running. */
static int
check_for_running_agent (int silent)
{
gpg_error_t err;
char *sockname;
assuan_context_t ctx = NULL;
sockname = make_filename_try (gnupg_socketdir (), GPG_AGENT_SOCK_NAME, NULL);
if (!sockname)
return gpg_error_from_syserror ();
err = assuan_new (&ctx);
if (!err)
err = assuan_socket_connect (ctx, sockname, (pid_t)(-1), 0);
xfree (sockname);
if (err)
{
if (!silent)
log_error (_("no gpg-agent running in this session\n"));
if (ctx)
assuan_release (ctx);
return -1;
}
if (!opt.quiet && !silent)
log_info ("gpg-agent running and available\n");
assuan_release (ctx);
return 0;
}
diff --git a/agent/learncard.c b/agent/learncard.c
index abe1dd0bf..f3219ed8f 100644
--- a/agent/learncard.c
+++ b/agent/learncard.c
@@ -1,445 +1,445 @@
/* learncard.c - Handle the LEARN command
* Copyright (C) 2002, 2003, 2004, 2009 Free Software Foundation, Inc.
*
* 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 .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "agent.h"
#include
/* Structures used by the callback mechanism to convey information
pertaining to key pairs. */
struct keypair_info_s
{
struct keypair_info_s *next;
int no_cert;
char *id; /* points into grip */
char hexgrip[1]; /* The keygrip (i.e. a hash over the public key
parameters) formatted as a hex string.
Allocated somewhat large to also act as
- memeory for the above ID field. */
+ memory for the above ID field. */
};
typedef struct keypair_info_s *KEYPAIR_INFO;
struct kpinfo_cb_parm_s
{
ctrl_t ctrl;
int error;
KEYPAIR_INFO info;
};
/* Structures used by the callback mechanism to convey information
pertaining to certificates. */
struct certinfo_s {
struct certinfo_s *next;
int type;
int done;
char id[1];
};
typedef struct certinfo_s *CERTINFO;
struct certinfo_cb_parm_s
{
ctrl_t ctrl;
int error;
CERTINFO info;
};
/* Structures used by the callback mechanism to convey assuan status
lines. */
struct sinfo_s {
struct sinfo_s *next;
char *data; /* Points into keyword. */
char keyword[1];
};
typedef struct sinfo_s *SINFO;
struct sinfo_cb_parm_s {
int error;
SINFO info;
};
/* Destructor for key information objects. */
static void
release_keypair_info (KEYPAIR_INFO info)
{
while (info)
{
KEYPAIR_INFO tmp = info->next;
xfree (info);
info = tmp;
}
}
/* Destructor for certificate information objects. */
static void
release_certinfo (CERTINFO info)
{
while (info)
{
CERTINFO tmp = info->next;
xfree (info);
info = tmp;
}
}
/* Destructor for status information objects. */
static void
release_sinfo (SINFO info)
{
while (info)
{
SINFO tmp = info->next;
xfree (info);
info = tmp;
}
}
/* This callback is used by agent_card_learn and passed the content of
all KEYPAIRINFO lines. It merely stores this data away */
static void
kpinfo_cb (void *opaque, const char *line)
{
struct kpinfo_cb_parm_s *parm = opaque;
KEYPAIR_INFO item;
char *p;
if (parm->error)
return; /* no need to gather data after an error occurred */
if ((parm->error = agent_write_status (parm->ctrl, "PROGRESS",
"learncard", "k", "0", "0", NULL)))
return;
item = xtrycalloc (1, sizeof *item + strlen (line));
if (!item)
{
parm->error = out_of_core ();
return;
}
strcpy (item->hexgrip, line);
for (p = item->hexgrip; hexdigitp (p); p++)
;
if (p == item->hexgrip && *p == 'X' && spacep (p+1))
{
item->no_cert = 1;
p++;
}
else if ((p - item->hexgrip) != 40 || !spacep (p))
{ /* not a 20 byte hex keygrip or not followed by a space */
parm->error = gpg_error (GPG_ERR_INV_RESPONSE);
xfree (item);
return;
}
*p++ = 0;
while (spacep (p))
p++;
item->id = p;
while (*p && !spacep (p))
p++;
if (p == item->id)
{ /* invalid ID string */
parm->error = gpg_error (GPG_ERR_INV_RESPONSE);
xfree (item);
return;
}
*p = 0; /* ignore trailing stuff */
/* store it */
item->next = parm->info;
parm->info = item;
}
/* This callback is used by agent_card_learn and passed the content of
all CERTINFO lines. It merely stores this data away */
static void
certinfo_cb (void *opaque, const char *line)
{
struct certinfo_cb_parm_s *parm = opaque;
CERTINFO item;
int type;
char *p, *pend;
if (parm->error)
return; /* no need to gather data after an error occurred */
if ((parm->error = agent_write_status (parm->ctrl, "PROGRESS",
"learncard", "c", "0", "0", NULL)))
return;
type = strtol (line, &p, 10);
while (spacep (p))
p++;
for (pend = p; *pend && !spacep (pend); pend++)
;
if (p == pend || !*p)
{
parm->error = gpg_error (GPG_ERR_INV_RESPONSE);
return;
}
*pend = 0; /* ignore trailing stuff */
item = xtrycalloc (1, sizeof *item + strlen (p));
if (!item)
{
parm->error = out_of_core ();
return;
}
item->type = type;
strcpy (item->id, p);
/* store it */
item->next = parm->info;
parm->info = item;
}
/* This callback is used by agent_card_learn and passed the content of
all SINFO lines. It merely stores this data away */
static void
sinfo_cb (void *opaque, const char *keyword, size_t keywordlen,
const char *data)
{
struct sinfo_cb_parm_s *sparm = opaque;
SINFO item;
if (sparm->error)
return; /* no need to gather data after an error occurred */
item = xtrycalloc (1, sizeof *item + keywordlen + 1 + strlen (data));
if (!item)
{
sparm->error = out_of_core ();
return;
}
memcpy (item->keyword, keyword, keywordlen);
item->data = item->keyword + keywordlen;
*item->data = 0;
item->data++;
strcpy (item->data, data);
/* store it */
item->next = sparm->info;
sparm->info = item;
}
static int
send_cert_back (ctrl_t ctrl, const char *id, void *assuan_context)
{
int rc;
char *derbuf;
size_t derbuflen;
rc = agent_card_readcert (ctrl, id, &derbuf, &derbuflen);
if (rc)
{
const char *action;
switch (gpg_err_code (rc))
{
case GPG_ERR_INV_ID:
case GPG_ERR_NOT_FOUND:
action = " - ignored";
break;
default:
action = "";
break;
}
if (opt.verbose || !*action)
log_info ("error reading certificate '%s': %s%s\n",
id? id:"?", gpg_strerror (rc), action);
return *action? 0 : rc;
}
rc = assuan_send_data (assuan_context, derbuf, derbuflen);
xfree (derbuf);
if (!rc)
rc = assuan_send_data (assuan_context, NULL, 0);
if (!rc)
rc = assuan_write_line (assuan_context, "END");
if (rc)
{
log_error ("sending certificate failed: %s\n",
gpg_strerror (rc));
return rc;
}
return 0;
}
/* Perform the learn operation. If ASSUAN_CONTEXT is not NULL and
SEND is true all new certificates are send back via Assuan. */
int
agent_handle_learn (ctrl_t ctrl, int send, void *assuan_context, int force)
{
int rc;
struct kpinfo_cb_parm_s parm;
struct certinfo_cb_parm_s cparm;
struct sinfo_cb_parm_s sparm;
const char *serialno = NULL;
KEYPAIR_INFO item;
SINFO sitem;
unsigned char grip[20];
char *p;
int i;
static int certtype_list[] = {
111, /* Root CA */
101, /* trusted */
102, /* useful */
100, /* regular */
/* We don't include 110 here because gpgsm can't handle that
special root CA format. */
-1 /* end of list */
};
memset (&parm, 0, sizeof parm);
memset (&cparm, 0, sizeof cparm);
memset (&sparm, 0, sizeof sparm);
parm.ctrl = ctrl;
cparm.ctrl = ctrl;
/* Now gather all the available info. */
rc = agent_card_learn (ctrl, kpinfo_cb, &parm, certinfo_cb, &cparm,
sinfo_cb, &sparm);
if (!rc && (parm.error || cparm.error || sparm.error))
rc = parm.error? parm.error : cparm.error? cparm.error : sparm.error;
if (rc)
{
log_debug ("agent_card_learn failed: %s\n", gpg_strerror (rc));
goto leave;
}
/* Pass on all the collected status information. */
for (sitem = sparm.info; sitem; sitem = sitem->next)
{
if (!strcmp (sitem->keyword, "SERIALNO"))
serialno = sitem->data;
if (assuan_context)
assuan_write_status (assuan_context, sitem->keyword, sitem->data);
}
if (!serialno)
{
rc = GPG_ERR_NOT_FOUND;
goto leave;
}
log_info ("card has S/N: %s\n", serialno);
/* Write out the certificates in a standard order. */
for (i=0; certtype_list[i] != -1; i++)
{
CERTINFO citem;
for (citem = cparm.info; citem; citem = citem->next)
{
if (certtype_list[i] != citem->type)
continue;
if (opt.verbose)
log_info (" id: %s (type=%d)\n",
citem->id, citem->type);
if (assuan_context && send)
{
rc = send_cert_back (ctrl, citem->id, assuan_context);
if (rc)
goto leave;
citem->done = 1;
}
}
}
for (item = parm.info; item; item = item->next)
{
unsigned char *pubkey;
if (opt.verbose)
log_info (" id: %s (grip=%s)\n", item->id, item->hexgrip);
if (item->no_cert)
continue; /* No public key yet available. */
if (assuan_context)
{
agent_write_status (ctrl, "KEYPAIRINFO",
item->hexgrip, item->id, NULL);
}
for (p=item->hexgrip, i=0; i < 20; p += 2, i++)
grip[i] = xtoi_2 (p);
if (!force && !agent_key_available (grip))
continue; /* The key is already available. */
/* Unknown key - store it. */
rc = agent_card_readkey (ctrl, item->id, &pubkey);
if (rc)
{
log_debug ("agent_card_readkey failed: %s\n", gpg_strerror (rc));
goto leave;
}
rc = agent_write_shadow_key (grip, serialno, item->id, pubkey, force);
xfree (pubkey);
if (rc)
goto leave;
if (opt.verbose)
log_info (" id: %s - shadow key created\n", item->id);
if (assuan_context && send)
{
CERTINFO citem;
/* only send the certificate if we have not done so before */
for (citem = cparm.info; citem; citem = citem->next)
{
if (!strcmp (citem->id, item->id))
break;
}
if (!citem)
{
rc = send_cert_back (ctrl, item->id, assuan_context);
if (rc)
goto leave;
}
}
}
leave:
release_keypair_info (parm.info);
release_certinfo (cparm.info);
release_sinfo (sparm.info);
return rc;
}
diff --git a/agent/protect.c b/agent/protect.c
index 16ae715e1..c7bd30b68 100644
--- a/agent/protect.c
+++ b/agent/protect.c
@@ -1,1741 +1,1741 @@
/* protect.c - Un/Protect a secret key
* Copyright (C) 1998-2003, 2007, 2009, 2011 Free Software Foundation, Inc.
* Copyright (C) 1998-2003, 2007, 2009, 2011, 2013-2015 Werner Koch
*
* 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 .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#ifdef HAVE_W32_SYSTEM
# ifdef HAVE_WINSOCK2_H
# include
# endif
# include
#else
# include
#endif
#include "agent.h"
#include "cvt-openpgp.h"
#include "../common/sexp-parse.h"
/* The protection mode for encryption. The supported modes for
decryption are listed in agent_unprotect(). */
#define PROT_CIPHER GCRY_CIPHER_AES128
#define PROT_CIPHER_STRING "aes"
#define PROT_CIPHER_KEYLEN (128/8)
/* Decode an rfc4880 encoded S2K count. */
#define S2K_DECODE_COUNT(_val) ((16ul + ((_val) & 15)) << (((_val) >> 4) + 6))
/* A table containing the information needed to create a protected
private key. */
static const struct {
const char *algo;
const char *parmlist;
int prot_from, prot_to;
int ecc_hack;
} protect_info[] = {
{ "rsa", "nedpqu", 2, 5 },
{ "dsa", "pqgyx", 4, 4 },
{ "elg", "pgyx", 3, 3 },
{ "ecdsa","pabgnqd", 6, 6, 1 },
{ "ecdh", "pabgnqd", 6, 6, 1 },
{ "ecc", "pabgnqd", 6, 6, 1 },
{ NULL }
};
/* A helper object for time measurement. */
struct calibrate_time_s
{
#ifdef HAVE_W32_SYSTEM
FILETIME creation_time, exit_time, kernel_time, user_time;
#else
clock_t ticks;
#endif
};
static int
hash_passphrase (const char *passphrase, int hashalgo,
int s2kmode,
const unsigned char *s2ksalt, unsigned long s2kcount,
unsigned char *key, size_t keylen);
/* Get the process time and store it in DATA. */
static void
calibrate_get_time (struct calibrate_time_s *data)
{
#ifdef HAVE_W32_SYSTEM
# ifdef HAVE_W32CE_SYSTEM
GetThreadTimes (GetCurrentThread (),
&data->creation_time, &data->exit_time,
&data->kernel_time, &data->user_time);
# else
GetProcessTimes (GetCurrentProcess (),
&data->creation_time, &data->exit_time,
&data->kernel_time, &data->user_time);
# endif
#elif defined (CLOCK_THREAD_CPUTIME_ID)
struct timespec tmp;
clock_gettime (CLOCK_THREAD_CPUTIME_ID, &tmp);
data->ticks = (clock_t)(((unsigned long long)tmp.tv_sec * 1000000000 +
tmp.tv_nsec) * CLOCKS_PER_SEC / 1000000000);
#else
data->ticks = clock ();
#endif
}
static unsigned long
calibrate_elapsed_time (struct calibrate_time_s *starttime)
{
struct calibrate_time_s stoptime;
calibrate_get_time (&stoptime);
#ifdef HAVE_W32_SYSTEM
{
unsigned long long t1, t2;
t1 = (((unsigned long long)starttime->kernel_time.dwHighDateTime << 32)
+ starttime->kernel_time.dwLowDateTime);
t1 += (((unsigned long long)starttime->user_time.dwHighDateTime << 32)
+ starttime->user_time.dwLowDateTime);
t2 = (((unsigned long long)stoptime.kernel_time.dwHighDateTime << 32)
+ stoptime.kernel_time.dwLowDateTime);
t2 += (((unsigned long long)stoptime.user_time.dwHighDateTime << 32)
+ stoptime.user_time.dwLowDateTime);
return (unsigned long)((t2 - t1)/10000);
}
#else
return (unsigned long)((((double) (stoptime.ticks - starttime->ticks))
/CLOCKS_PER_SEC)*1000);
#endif
}
/* Run a test hashing for COUNT and return the time required in
milliseconds. */
static unsigned long
calibrate_s2k_count_one (unsigned long count)
{
int rc;
char keybuf[PROT_CIPHER_KEYLEN];
struct calibrate_time_s starttime;
calibrate_get_time (&starttime);
rc = hash_passphrase ("123456789abcdef0", GCRY_MD_SHA1,
3, "saltsalt", count, keybuf, sizeof keybuf);
if (rc)
BUG ();
return calibrate_elapsed_time (&starttime);
}
/* Measure the time we need to do the hash operations and deduce an
S2K count which requires roughly some targeted amount of time. */
static unsigned long
calibrate_s2k_count (void)
{
unsigned long count;
unsigned long ms;
for (count = 65536; count; count *= 2)
{
ms = calibrate_s2k_count_one (count);
if (opt.verbose > 1)
log_info ("S2K calibration: %lu -> %lums\n", count, ms);
if (ms > AGENT_S2K_CALIBRATION)
break;
}
count = (unsigned long)(((double)count / ms) * AGENT_S2K_CALIBRATION);
count /= 1024;
count *= 1024;
if (count < 65536)
count = 65536;
if (opt.verbose)
{
ms = calibrate_s2k_count_one (count);
log_info ("S2K calibration: %lu -> %lums\n", count, ms);
}
return count;
}
/* Return the calibrated S2K count. This is only public for the use
* of the Assuan getinfo s2k_count_cal command. */
unsigned long
get_calibrated_s2k_count (void)
{
static unsigned long count;
if (!count)
count = calibrate_s2k_count ();
/* Enforce a lower limit. */
return count < 65536 ? 65536 : count;
}
/* Return the standard S2K count. */
unsigned long
get_standard_s2k_count (void)
{
if (opt.s2k_count)
return opt.s2k_count < 65536 ? 65536 : opt.s2k_count;
return get_calibrated_s2k_count ();
}
/* Return the milliseconds required for the standard S2K
* operation. */
unsigned long
get_standard_s2k_time (void)
{
return calibrate_s2k_count_one (get_standard_s2k_count ());
}
/* Same as get_standard_s2k_count but return the count in the encoding
as described by rfc4880. */
unsigned char
get_standard_s2k_count_rfc4880 (void)
{
unsigned long iterations;
unsigned int count;
unsigned char result;
unsigned char c=0;
iterations = get_standard_s2k_count ();
if (iterations >= 65011712)
return 255;
/* Need count to be in the range 16-31 */
for (count=iterations>>6; count>=32; count>>=1)
c++;
result = (c<<4)|(count-16);
if (S2K_DECODE_COUNT(result) < iterations)
result++;
return result;
}
/* Calculate the MIC for a private key or shared secret S-expression.
SHA1HASH should point to a 20 byte buffer. This function is
suitable for all algorithms. */
static gpg_error_t
calculate_mic (const unsigned char *plainkey, unsigned char *sha1hash)
{
const unsigned char *hash_begin, *hash_end;
const unsigned char *s;
size_t n;
int is_shared_secret;
s = plainkey;
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (smatch (&s, n, "private-key"))
is_shared_secret = 0;
else if (smatch (&s, n, "shared-secret"))
is_shared_secret = 1;
else
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
if (*s != '(')
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
hash_begin = s;
if (!is_shared_secret)
{
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
s += n; /* Skip the algorithm name. */
}
while (*s == '(')
{
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
s += n;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
s += n;
if ( *s != ')' )
return gpg_error (GPG_ERR_INV_SEXP);
s++;
}
if (*s != ')')
return gpg_error (GPG_ERR_INV_SEXP);
s++;
hash_end = s;
gcry_md_hash_buffer (GCRY_MD_SHA1, sha1hash,
hash_begin, hash_end - hash_begin);
return 0;
}
/* Encrypt the parameter block starting at PROTBEGIN with length
PROTLEN using the utf8 encoded key PASSPHRASE and return the entire
encrypted block in RESULT or return with an error code. SHA1HASH
is the 20 byte SHA-1 hash required for the integrity code.
The parameter block is expected to be an incomplete canonical
encoded S-Expression of the form (example in advanced format):
(d #046129F..[some bytes not shown]..81#)
(p #00e861b..[some bytes not shown]..f1#)
(q #00f7a7c..[some bytes not shown]..61#)
(u #304559a..[some bytes not shown]..9b#)
the returned block is the S-Expression:
(protected mode (parms) encrypted_octet_string)
*/
static int
do_encryption (const unsigned char *hashbegin, size_t hashlen,
const unsigned char *protbegin, size_t protlen,
const char *passphrase,
const char *timestamp_exp, size_t timestamp_exp_len,
unsigned char **result, size_t *resultlen,
unsigned long s2k_count, int use_ocb)
{
gcry_cipher_hd_t hd;
const char *modestr;
unsigned char hashvalue[20];
int blklen, enclen, outlen;
unsigned char *iv = NULL;
unsigned int ivsize; /* Size of the buffer allocated for IV. */
const unsigned char *s2ksalt; /* Points into IV. */
int rc;
char *outbuf = NULL;
char *p;
int saltpos, ivpos, encpos;
s2ksalt = iv; /* Silence compiler warning. */
*resultlen = 0;
*result = NULL;
modestr = (use_ocb? "openpgp-s2k3-ocb-aes"
/* */: "openpgp-s2k3-sha1-" PROT_CIPHER_STRING "-cbc");
rc = gcry_cipher_open (&hd, PROT_CIPHER,
use_ocb? GCRY_CIPHER_MODE_OCB :
GCRY_CIPHER_MODE_CBC,
GCRY_CIPHER_SECURE);
if (rc)
return rc;
/* We need to work on a copy of the data because this makes it
* easier to add the trailer and the padding and more important we
* have to prefix the text with 2 parenthesis. In CBC mode we
* have to allocate enough space for:
*
* (()(4:hash4:sha120:)) + padding
*
* we always append a full block of random bytes as padding but
* encrypt only what is needed for a full blocksize. In OCB mode we
* have to allocate enough space for just:
*
* (())
*/
blklen = gcry_cipher_get_algo_blklen (PROT_CIPHER);
if (use_ocb)
{
/* (( )) */
outlen = 2 + protlen + 2 ;
enclen = outlen + 16 /* taglen */;
outbuf = gcry_malloc_secure (enclen);
}
else
{
/* (( )( 4:hash 4:sha1 20: )) */
outlen = 2 + protlen + 2 + 6 + 6 + 23 + 2 + blklen;
enclen = outlen/blklen * blklen;
outbuf = gcry_malloc_secure (outlen);
}
if (!outbuf)
{
rc = out_of_core ();
goto leave;
}
/* Allocate a buffer for the nonce and the salt. */
if (!rc)
{
/* Allocate random bytes to be used as IV, padding and s2k salt
* or in OCB mode for a nonce and the s2k salt. The IV/nonce is
* set later because for OCB we need to set the key first. */
ivsize = (use_ocb? 12 : (blklen*2)) + 8;
iv = xtrymalloc (ivsize);
if (!iv)
rc = gpg_error_from_syserror ();
else
{
gcry_create_nonce (iv, ivsize);
s2ksalt = iv + ivsize - 8;
}
}
/* Hash the passphrase and set the key. */
if (!rc)
{
unsigned char *key;
size_t keylen = PROT_CIPHER_KEYLEN;
key = gcry_malloc_secure (keylen);
if (!key)
rc = out_of_core ();
else
{
rc = hash_passphrase (passphrase, GCRY_MD_SHA1,
3, s2ksalt,
s2k_count? s2k_count:get_standard_s2k_count(),
key, keylen);
if (!rc)
rc = gcry_cipher_setkey (hd, key, keylen);
xfree (key);
}
}
if (rc)
goto leave;
/* Set the IV/nonce. */
rc = gcry_cipher_setiv (hd, iv, use_ocb? 12 : blklen);
if (rc)
goto leave;
if (use_ocb)
{
/* In OCB Mode we use only the public key parameters as AAD. */
rc = gcry_cipher_authenticate (hd, hashbegin, protbegin - hashbegin);
if (!rc)
rc = gcry_cipher_authenticate (hd, timestamp_exp, timestamp_exp_len);
if (!rc)
rc = gcry_cipher_authenticate
(hd, protbegin+protlen, hashlen - (protbegin+protlen - hashbegin));
}
else
{
/* Hash the entire expression for CBC mode. Because
* TIMESTAMP_EXP won't get protected, we can't simply hash a
* continuous buffer but need to call md_write several times. */
gcry_md_hd_t md;
rc = gcry_md_open (&md, GCRY_MD_SHA1, 0 );
if (!rc)
{
gcry_md_write (md, hashbegin, protbegin - hashbegin);
gcry_md_write (md, protbegin, protlen);
gcry_md_write (md, timestamp_exp, timestamp_exp_len);
gcry_md_write (md, protbegin+protlen,
hashlen - (protbegin+protlen - hashbegin));
memcpy (hashvalue, gcry_md_read (md, GCRY_MD_SHA1), 20);
gcry_md_close (md);
}
}
/* Encrypt. */
if (!rc)
{
p = outbuf;
*p++ = '(';
*p++ = '(';
memcpy (p, protbegin, protlen);
p += protlen;
if (use_ocb)
{
*p++ = ')';
*p++ = ')';
}
else
{
memcpy (p, ")(4:hash4:sha120:", 17);
p += 17;
memcpy (p, hashvalue, 20);
p += 20;
*p++ = ')';
*p++ = ')';
memcpy (p, iv+blklen, blklen); /* Add padding. */
p += blklen;
}
assert ( p - outbuf == outlen);
if (use_ocb)
{
gcry_cipher_final (hd);
rc = gcry_cipher_encrypt (hd, outbuf, outlen, NULL, 0);
if (!rc)
{
log_assert (outlen + 16 == enclen);
rc = gcry_cipher_gettag (hd, outbuf + outlen, 16);
}
}
else
{
rc = gcry_cipher_encrypt (hd, outbuf, enclen, NULL, 0);
}
}
if (rc)
goto leave;
/* Release cipher handle and check for errors. */
gcry_cipher_close (hd);
/* Now allocate the buffer we want to return. This is
(protected openpgp-s2k3-sha1-aes-cbc
((sha1 salt no_of_iterations) 16byte_iv)
encrypted_octet_string)
in canoncical format of course. We use asprintf and %n modifier
and dummy values as placeholders. */
{
char countbuf[35];
snprintf (countbuf, sizeof countbuf, "%lu",
s2k_count ? s2k_count : get_standard_s2k_count ());
p = xtryasprintf
("(9:protected%d:%s((4:sha18:%n_8bytes_%u:%s)%d:%n%*s)%d:%n%*s)",
(int)strlen (modestr), modestr,
&saltpos,
(unsigned int)strlen (countbuf), countbuf,
use_ocb? 12 : blklen, &ivpos, use_ocb? 12 : blklen, "",
enclen, &encpos, enclen, "");
if (!p)
{
gpg_error_t tmperr = out_of_core ();
xfree (iv);
xfree (outbuf);
return tmperr;
}
}
*resultlen = strlen (p);
*result = (unsigned char*)p;
memcpy (p+saltpos, s2ksalt, 8);
memcpy (p+ivpos, iv, use_ocb? 12 : blklen);
memcpy (p+encpos, outbuf, enclen);
xfree (iv);
xfree (outbuf);
return 0;
leave:
gcry_cipher_close (hd);
xfree (iv);
xfree (outbuf);
return rc;
}
/* Protect the key encoded in canonical format in PLAINKEY. We assume
a valid S-Exp here. With USE_UCB set to -1 the default scheme is
used (ie. either CBC or OCB), set to 0 the old CBC mode is used,
and set to 1 OCB is used. */
int
agent_protect (const unsigned char *plainkey, const char *passphrase,
unsigned char **result, size_t *resultlen,
unsigned long s2k_count, int use_ocb)
{
int rc;
const char *parmlist;
int prot_from_idx, prot_to_idx;
const unsigned char *s;
const unsigned char *hash_begin, *hash_end;
const unsigned char *prot_begin, *prot_end, *real_end;
size_t n;
int c, infidx, i;
char timestamp_exp[35];
unsigned char *protected;
size_t protectedlen;
int depth = 0;
unsigned char *p;
int have_curve = 0;
if (use_ocb == -1)
use_ocb = opt.enable_extended_key_format;
/* Create an S-expression with the protected-at timestamp. */
memcpy (timestamp_exp, "(12:protected-at15:", 19);
gnupg_get_isotime (timestamp_exp+19);
timestamp_exp[19+15] = ')';
/* Parse original key. */
s = plainkey;
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
depth++;
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (!smatch (&s, n, "private-key"))
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
if (*s != '(')
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
depth++;
hash_begin = s;
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
for (infidx=0; protect_info[infidx].algo
&& !smatch (&s, n, protect_info[infidx].algo); infidx++)
;
if (!protect_info[infidx].algo)
return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
/* The parser below is a complete mess: To make it robust for ECC
use we should reorder the s-expression to include only what we
really need and thus guarantee the right order for saving stuff.
This should be done before calling this function and maybe with
the help of the new gcry_sexp_extract_param. */
parmlist = protect_info[infidx].parmlist;
prot_from_idx = protect_info[infidx].prot_from;
prot_to_idx = protect_info[infidx].prot_to;
prot_begin = prot_end = NULL;
for (i=0; (c=parmlist[i]); i++)
{
if (i == prot_from_idx)
prot_begin = s;
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
depth++;
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (n != 1 || c != *s)
{
if (n == 5 && !memcmp (s, "curve", 5)
&& !i && protect_info[infidx].ecc_hack)
{
/* This is a private ECC key but the first parameter is
the name of the curve. We change the parameter list
here to the one we expect in this case. */
have_curve = 1;
parmlist = "?qd";
prot_from_idx = 2;
prot_to_idx = 2;
}
else if (n == 5 && !memcmp (s, "flags", 5)
&& i == 1 && have_curve)
{
/* "curve" followed by "flags": Change again. */
parmlist = "??qd";
prot_from_idx = 3;
prot_to_idx = 3;
}
else
return gpg_error (GPG_ERR_INV_SEXP);
}
s += n;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
s +=n; /* skip value */
if (*s != ')')
return gpg_error (GPG_ERR_INV_SEXP);
depth--;
if (i == prot_to_idx)
prot_end = s;
s++;
}
if (*s != ')' || !prot_begin || !prot_end )
return gpg_error (GPG_ERR_INV_SEXP);
depth--;
hash_end = s;
s++;
/* Skip to the end of the S-expression. */
assert (depth == 1);
rc = sskip (&s, &depth);
if (rc)
return rc;
assert (!depth);
real_end = s-1;
rc = do_encryption (hash_begin, hash_end - hash_begin + 1,
prot_begin, prot_end - prot_begin + 1,
passphrase, timestamp_exp, sizeof (timestamp_exp),
&protected, &protectedlen, s2k_count, use_ocb);
if (rc)
return rc;
/* Now create the protected version of the key. Note that the 10
extra bytes are for the inserted "protected-" string (the
beginning of the plaintext reads: "((11:private-key(" ). The 35
term is the space for (12:protected-at15:). */
*resultlen = (10
+ (prot_begin-plainkey)
+ protectedlen
+ 35
+ (real_end-prot_end));
*result = p = xtrymalloc (*resultlen);
if (!p)
{
gpg_error_t tmperr = out_of_core ();
xfree (protected);
return tmperr;
}
memcpy (p, "(21:protected-", 14);
p += 14;
memcpy (p, plainkey+4, prot_begin - plainkey - 4);
p += prot_begin - plainkey - 4;
memcpy (p, protected, protectedlen);
p += protectedlen;
memcpy (p, timestamp_exp, 35);
p += 35;
memcpy (p, prot_end+1, real_end - prot_end);
p += real_end - prot_end;
assert ( p - *result == *resultlen);
xfree (protected);
return 0;
}
/* Do the actual decryption and check the return list for consistency. */
static gpg_error_t
do_decryption (const unsigned char *aad_begin, size_t aad_len,
const unsigned char *aadhole_begin, size_t aadhole_len,
const unsigned char *protected, size_t protectedlen,
const char *passphrase,
const unsigned char *s2ksalt, unsigned long s2kcount,
const unsigned char *iv, size_t ivlen,
int prot_cipher, int prot_cipher_keylen, int is_ocb,
unsigned char **result)
{
int rc;
int blklen;
gcry_cipher_hd_t hd;
unsigned char *outbuf;
size_t reallen;
blklen = gcry_cipher_get_algo_blklen (prot_cipher);
if (is_ocb)
{
/* OCB does not require a multiple of the block length but we
* check that it is long enough for the 128 bit tag and that we
* have the 96 bit nonce. */
if (protectedlen < (4 + 16) || ivlen != 12)
return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
}
else
{
if (protectedlen < 4 || (protectedlen%blklen))
return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
}
rc = gcry_cipher_open (&hd, prot_cipher,
is_ocb? GCRY_CIPHER_MODE_OCB :
GCRY_CIPHER_MODE_CBC,
GCRY_CIPHER_SECURE);
if (rc)
return rc;
outbuf = gcry_malloc_secure (protectedlen);
if (!outbuf)
rc = out_of_core ();
/* Hash the passphrase and set the key. */
if (!rc)
{
unsigned char *key;
key = gcry_malloc_secure (prot_cipher_keylen);
if (!key)
rc = out_of_core ();
else
{
rc = hash_passphrase (passphrase, GCRY_MD_SHA1,
3, s2ksalt, s2kcount, key, prot_cipher_keylen);
if (!rc)
rc = gcry_cipher_setkey (hd, key, prot_cipher_keylen);
xfree (key);
}
}
/* Set the IV/nonce. */
if (!rc)
{
rc = gcry_cipher_setiv (hd, iv, ivlen);
}
/* Decrypt. */
if (!rc)
{
if (is_ocb)
{
rc = gcry_cipher_authenticate (hd, aad_begin,
aadhole_begin - aad_begin);
if (!rc)
rc = gcry_cipher_authenticate
(hd, aadhole_begin + aadhole_len,
aad_len - (aadhole_begin+aadhole_len - aad_begin));
if (!rc)
{
gcry_cipher_final (hd);
rc = gcry_cipher_decrypt (hd, outbuf, protectedlen - 16,
protected, protectedlen - 16);
}
if (!rc)
{
rc = gcry_cipher_checktag (hd, protected + protectedlen - 16, 16);
if (gpg_err_code (rc) == GPG_ERR_CHECKSUM)
{
/* Return Bad Passphrase instead of checksum error */
rc = gpg_error (GPG_ERR_BAD_PASSPHRASE);
}
}
}
else
{
rc = gcry_cipher_decrypt (hd, outbuf, protectedlen,
protected, protectedlen);
}
}
/* Release cipher handle and check for errors. */
gcry_cipher_close (hd);
if (rc)
{
xfree (outbuf);
return rc;
}
/* Do a quick check on the data structure. */
if (*outbuf != '(' && outbuf[1] != '(')
{
xfree (outbuf);
return gpg_error (GPG_ERR_BAD_PASSPHRASE);
}
/* Check that we have a consistent S-Exp. */
reallen = gcry_sexp_canon_len (outbuf, protectedlen, NULL, NULL);
if (!reallen || (reallen + blklen < protectedlen) )
{
xfree (outbuf);
return gpg_error (GPG_ERR_BAD_PASSPHRASE);
}
*result = outbuf;
return 0;
}
/* Merge the parameter list contained in CLEARTEXT with the original
* protect lists PROTECTEDKEY by replacing the list at REPLACEPOS.
* Return the new list in RESULT and the MIC value in the 20 byte
* buffer SHA1HASH; if SHA1HASH is NULL no MIC will be computed.
* CUTOFF and CUTLEN will receive the offset and the length of the
* resulting list which should go into the MIC calculation but then be
* removed. */
static gpg_error_t
merge_lists (const unsigned char *protectedkey,
size_t replacepos,
const unsigned char *cleartext,
unsigned char *sha1hash,
unsigned char **result, size_t *resultlen,
size_t *cutoff, size_t *cutlen)
{
size_t n, newlistlen;
unsigned char *newlist, *p;
const unsigned char *s;
const unsigned char *startpos, *endpos;
int i, rc;
*result = NULL;
*resultlen = 0;
*cutoff = 0;
*cutlen = 0;
if (replacepos < 26)
return gpg_error (GPG_ERR_BUG);
/* Estimate the required size of the resulting list. We have a large
safety margin of >20 bytes (FIXME: MIC hash from CLEARTEXT and the
removed "protected-" */
newlistlen = gcry_sexp_canon_len (protectedkey, 0, NULL, NULL);
if (!newlistlen)
return gpg_error (GPG_ERR_BUG);
n = gcry_sexp_canon_len (cleartext, 0, NULL, NULL);
if (!n)
return gpg_error (GPG_ERR_BUG);
newlistlen += n;
newlist = gcry_malloc_secure (newlistlen);
if (!newlist)
return out_of_core ();
/* Copy the initial segment */
strcpy ((char*)newlist, "(11:private-key");
p = newlist + 15;
memcpy (p, protectedkey+15+10, replacepos-15-10);
p += replacepos-15-10;
/* Copy the cleartext. */
s = cleartext;
if (*s != '(' && s[1] != '(')
return gpg_error (GPG_ERR_BUG); /*we already checked this */
s += 2;
startpos = s;
while ( *s == '(' )
{
s++;
n = snext (&s);
if (!n)
goto invalid_sexp;
s += n;
n = snext (&s);
if (!n)
goto invalid_sexp;
s += n;
if ( *s != ')' )
goto invalid_sexp;
s++;
}
if ( *s != ')' )
goto invalid_sexp;
endpos = s;
s++;
/* Intermezzo: Get the MIC if requested. */
if (sha1hash)
{
if (*s != '(')
goto invalid_sexp;
s++;
n = snext (&s);
if (!smatch (&s, n, "hash"))
goto invalid_sexp;
n = snext (&s);
if (!smatch (&s, n, "sha1"))
goto invalid_sexp;
n = snext (&s);
if (n != 20)
goto invalid_sexp;
memcpy (sha1hash, s, 20);
s += n;
if (*s != ')')
goto invalid_sexp;
}
/* Append the parameter list. */
memcpy (p, startpos, endpos - startpos);
p += endpos - startpos;
/* Skip over the protected list element in the original list. */
s = protectedkey + replacepos;
assert (*s == '(');
s++;
i = 1;
rc = sskip (&s, &i);
if (rc)
goto failure;
/* Record the position of the optional protected-at expression. */
if (*s == '(')
{
const unsigned char *save_s = s;
s++;
n = snext (&s);
if (smatch (&s, n, "protected-at"))
{
i = 1;
rc = sskip (&s, &i);
if (rc)
goto failure;
*cutlen = s - save_s;
}
s = save_s;
}
startpos = s;
i = 2; /* we are inside this level */
rc = sskip (&s, &i);
if (rc)
goto failure;
assert (s[-1] == ')');
endpos = s; /* one behind the end of the list */
/* Append the rest. */
if (*cutlen)
*cutoff = p - newlist;
memcpy (p, startpos, endpos - startpos);
p += endpos - startpos;
/* ready */
*result = newlist;
*resultlen = newlistlen;
return 0;
failure:
wipememory (newlist, newlistlen);
xfree (newlist);
return rc;
invalid_sexp:
wipememory (newlist, newlistlen);
xfree (newlist);
return gpg_error (GPG_ERR_INV_SEXP);
}
/* Unprotect the key encoded in canonical format. We assume a valid
S-Exp here. If a protected-at item is available, its value will
be stored at protected_at unless this is NULL. */
gpg_error_t
agent_unprotect (ctrl_t ctrl,
const unsigned char *protectedkey, const char *passphrase,
gnupg_isotime_t protected_at,
unsigned char **result, size_t *resultlen)
{
static const struct {
const char *name; /* Name of the protection method. */
int algo; /* (A zero indicates the "openpgp-native" hack.) */
int keylen; /* Used key length in bytes. */
unsigned int is_ocb:1;
} algotable[] = {
{ "openpgp-s2k3-sha1-aes-cbc", GCRY_CIPHER_AES128, (128/8)},
{ "openpgp-s2k3-sha1-aes256-cbc", GCRY_CIPHER_AES256, (256/8)},
{ "openpgp-s2k3-ocb-aes", GCRY_CIPHER_AES128, (128/8), 1},
{ "openpgp-native", 0, 0 }
};
int rc;
const unsigned char *s;
const unsigned char *protect_list;
size_t n;
int infidx, i;
unsigned char sha1hash[20], sha1hash2[20];
const unsigned char *s2ksalt;
unsigned long s2kcount;
const unsigned char *iv;
int prot_cipher, prot_cipher_keylen;
int is_ocb;
const unsigned char *aad_begin, *aad_end, *aadhole_begin, *aadhole_end;
const unsigned char *prot_begin;
unsigned char *cleartext;
unsigned char *final;
size_t finallen;
size_t cutoff, cutlen;
if (protected_at)
*protected_at = 0;
s = protectedkey;
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (!smatch (&s, n, "protected-private-key"))
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
if (*s != '(')
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
{
aad_begin = aad_end = s;
aad_end++;
i = 1;
rc = sskip (&aad_end, &i);
if (rc)
return rc;
}
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
for (infidx=0; protect_info[infidx].algo
&& !smatch (&s, n, protect_info[infidx].algo); infidx++)
;
if (!protect_info[infidx].algo)
return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
- /* See wether we have a protected-at timestamp. */
+ /* See whether we have a protected-at timestamp. */
protect_list = s; /* Save for later. */
if (protected_at)
{
while (*s == '(')
{
prot_begin = s;
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (smatch (&s, n, "protected-at"))
{
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (n != 15)
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
memcpy (protected_at, s, 15);
protected_at[15] = 0;
break;
}
s += n;
i = 1;
rc = sskip (&s, &i);
if (rc)
return rc;
}
}
/* Now find the list with the protected information. Here is an
example for such a list:
(protected openpgp-s2k3-sha1-aes-cbc
((sha1 ) )
)
*/
s = protect_list;
for (;;)
{
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
prot_begin = s;
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (smatch (&s, n, "protected"))
break;
s += n;
i = 1;
rc = sskip (&s, &i);
if (rc)
return rc;
}
/* found */
{
aadhole_begin = aadhole_end = prot_begin;
aadhole_end++;
i = 1;
rc = sskip (&aadhole_end, &i);
if (rc)
return rc;
}
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
/* Lookup the protection algo. */
prot_cipher = 0; /* (avoid gcc warning) */
prot_cipher_keylen = 0; /* (avoid gcc warning) */
is_ocb = 0;
for (i=0; i < DIM (algotable); i++)
if (smatch (&s, n, algotable[i].name))
{
prot_cipher = algotable[i].algo;
prot_cipher_keylen = algotable[i].keylen;
is_ocb = algotable[i].is_ocb;
break;
}
if (i == DIM (algotable))
return gpg_error (GPG_ERR_UNSUPPORTED_PROTECTION);
if (!prot_cipher) /* This is "openpgp-native". */
{
gcry_sexp_t s_prot_begin;
rc = gcry_sexp_sscan (&s_prot_begin, NULL,
prot_begin,
gcry_sexp_canon_len (prot_begin, 0,NULL,NULL));
if (rc)
return rc;
rc = convert_from_openpgp_native (ctrl, s_prot_begin, passphrase, &final);
gcry_sexp_release (s_prot_begin);
if (!rc)
{
*result = final;
*resultlen = gcry_sexp_canon_len (final, 0, NULL, NULL);
}
return rc;
}
if (*s != '(' || s[1] != '(')
return gpg_error (GPG_ERR_INV_SEXP);
s += 2;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (!smatch (&s, n, "sha1"))
return gpg_error (GPG_ERR_UNSUPPORTED_PROTECTION);
n = snext (&s);
if (n != 8)
return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
s2ksalt = s;
s += n;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
/* We expect a list close as next, so we can simply use strtoul()
here. We might want to check that we only have digits - but this
is nothing we should worry about */
if (s[n] != ')' )
return gpg_error (GPG_ERR_INV_SEXP);
/* Old versions of gpg-agent used the funny floating point number in
a byte encoding as specified by OpenPGP. However this is not
needed and thus we now store it as a plain unsigned integer. We
can easily distinguish the old format by looking at its value:
Less than 256 is an old-style encoded number; other values are
plain integers. In any case we check that they are at least
65536 because we never used a lower value in the past and we
should have a lower limit. */
s2kcount = strtoul ((const char*)s, NULL, 10);
if (!s2kcount)
return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
if (s2kcount < 256)
s2kcount = (16ul + (s2kcount & 15)) << ((s2kcount >> 4) + 6);
if (s2kcount < 65536)
return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
s += n;
s++; /* skip list end */
n = snext (&s);
if (is_ocb)
{
if (n != 12) /* Wrong size of the nonce. */
return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
}
else
{
if (n != 16) /* Wrong blocksize for IV (we support only 128 bit). */
return gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
}
iv = s;
s += n;
if (*s != ')' )
return gpg_error (GPG_ERR_INV_SEXP);
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
cleartext = NULL; /* Avoid cc warning. */
rc = do_decryption (aad_begin, aad_end - aad_begin,
aadhole_begin, aadhole_end - aadhole_begin,
s, n,
passphrase, s2ksalt, s2kcount,
iv, is_ocb? 12:16,
prot_cipher, prot_cipher_keylen, is_ocb,
&cleartext);
if (rc)
return rc;
rc = merge_lists (protectedkey, prot_begin-protectedkey, cleartext,
is_ocb? NULL : sha1hash,
&final, &finallen, &cutoff, &cutlen);
/* Albeit cleartext has been allocated in secure memory and thus
xfree will wipe it out, we do an extra wipe just in case
somethings goes badly wrong. */
wipememory (cleartext, n);
xfree (cleartext);
if (rc)
return rc;
if (!is_ocb)
{
rc = calculate_mic (final, sha1hash2);
if (!rc && memcmp (sha1hash, sha1hash2, 20))
rc = gpg_error (GPG_ERR_CORRUPTED_PROTECTION);
if (rc)
{
wipememory (final, finallen);
xfree (final);
return rc;
}
}
/* Now remove the part which is included in the MIC but should not
go into the final thing. */
if (cutlen)
{
memmove (final+cutoff, final+cutoff+cutlen, finallen-cutoff-cutlen);
finallen -= cutlen;
}
*result = final;
*resultlen = gcry_sexp_canon_len (final, 0, NULL, NULL);
return 0;
}
/* Check the type of the private key, this is one of the constants:
PRIVATE_KEY_UNKNOWN if we can't figure out the type (this is the
value 0), PRIVATE_KEY_CLEAR for an unprotected private key.
PRIVATE_KEY_PROTECTED for an protected private key or
PRIVATE_KEY_SHADOWED for a sub key where the secret parts are
stored elsewhere. Finally PRIVATE_KEY_OPENPGP_NONE may be returned
is the key is still in the openpgp-native format but without
protection. */
int
agent_private_key_type (const unsigned char *privatekey)
{
const unsigned char *s;
size_t n;
int i;
s = privatekey;
if (*s != '(')
return PRIVATE_KEY_UNKNOWN;
s++;
n = snext (&s);
if (!n)
return PRIVATE_KEY_UNKNOWN;
if (smatch (&s, n, "protected-private-key"))
{
/* We need to check whether this is openpgp-native protected
with the protection method "none". In that case we return a
different key type so that the caller knows that there is no
need to ask for a passphrase. */
if (*s != '(')
return PRIVATE_KEY_PROTECTED; /* Unknown sexp - assume protected. */
s++;
n = snext (&s);
if (!n)
return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
s += n; /* Skip over the algo */
/* Find the (protected ...) list. */
for (;;)
{
if (*s != '(')
return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
s++;
n = snext (&s);
if (!n)
return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
if (smatch (&s, n, "protected"))
break;
s += n;
i = 1;
if (sskip (&s, &i))
return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
}
/* Found - Is this openpgp-native? */
n = snext (&s);
if (!n)
return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
if (smatch (&s, n, "openpgp-native")) /* Yes. */
{
if (*s != '(')
return PRIVATE_KEY_UNKNOWN; /* Unknown sexp. */
s++;
n = snext (&s);
if (!n)
return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
s += n; /* Skip over "openpgp-private-key". */
/* Find the (protection ...) list. */
for (;;)
{
if (*s != '(')
return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
s++;
n = snext (&s);
if (!n)
return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
if (smatch (&s, n, "protection"))
break;
s += n;
i = 1;
if (sskip (&s, &i))
return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
}
/* Found - Is the mode "none"? */
n = snext (&s);
if (!n)
return PRIVATE_KEY_UNKNOWN; /* Invalid sexp. */
if (smatch (&s, n, "none"))
return PRIVATE_KEY_OPENPGP_NONE; /* Yes. */
}
return PRIVATE_KEY_PROTECTED;
}
if (smatch (&s, n, "shadowed-private-key"))
return PRIVATE_KEY_SHADOWED;
if (smatch (&s, n, "private-key"))
return PRIVATE_KEY_CLEAR;
return PRIVATE_KEY_UNKNOWN;
}
/* Transform a passphrase into a suitable key of length KEYLEN and
store this key in the caller provided buffer KEY. The caller must
provide an HASHALGO, a valid S2KMODE (see rfc-2440) and depending on
that mode an S2KSALT of 8 random bytes and an S2KCOUNT.
Returns an error code on failure. */
static int
hash_passphrase (const char *passphrase, int hashalgo,
int s2kmode,
const unsigned char *s2ksalt,
unsigned long s2kcount,
unsigned char *key, size_t keylen)
{
/* The key derive function does not support a zero length string for
the passphrase in the S2K modes. Return a better suited error
code than GPG_ERR_INV_DATA. */
if (!passphrase || !*passphrase)
return gpg_error (GPG_ERR_NO_PASSPHRASE);
return gcry_kdf_derive (passphrase, strlen (passphrase),
s2kmode == 3? GCRY_KDF_ITERSALTED_S2K :
s2kmode == 1? GCRY_KDF_SALTED_S2K :
s2kmode == 0? GCRY_KDF_SIMPLE_S2K : GCRY_KDF_NONE,
hashalgo, s2ksalt, 8, s2kcount,
keylen, key);
}
gpg_error_t
s2k_hash_passphrase (const char *passphrase, int hashalgo,
int s2kmode,
const unsigned char *s2ksalt,
unsigned int s2kcount,
unsigned char *key, size_t keylen)
{
return hash_passphrase (passphrase, hashalgo, s2kmode, s2ksalt,
S2K_DECODE_COUNT (s2kcount),
key, keylen);
}
/* Create an canonical encoded S-expression with the shadow info from
a card's SERIALNO and the IDSTRING. */
unsigned char *
make_shadow_info (const char *serialno, const char *idstring)
{
const char *s;
char *info, *p;
char numbuf[20];
size_t n;
for (s=serialno, n=0; *s && s[1]; s += 2)
n++;
info = p = xtrymalloc (1 + sizeof numbuf + n
+ sizeof numbuf + strlen (idstring) + 1 + 1);
if (!info)
return NULL;
*p++ = '(';
p = stpcpy (p, smklen (numbuf, sizeof numbuf, n, NULL));
for (s=serialno; *s && s[1]; s += 2)
*(unsigned char *)p++ = xtoi_2 (s);
p = stpcpy (p, smklen (numbuf, sizeof numbuf, strlen (idstring), NULL));
p = stpcpy (p, idstring);
*p++ = ')';
*p = 0;
return (unsigned char *)info;
}
/* Create a shadow key from a public key. We use the shadow protocol
"t1-v1" and insert the S-expressionn SHADOW_INFO. The resulting
S-expression is returned in an allocated buffer RESULT will point
to. The input parameters are expected to be valid canonicalized
S-expressions */
int
agent_shadow_key (const unsigned char *pubkey,
const unsigned char *shadow_info,
unsigned char **result)
{
const unsigned char *s;
const unsigned char *point;
size_t n;
int depth = 0;
char *p;
size_t pubkey_len = gcry_sexp_canon_len (pubkey, 0, NULL,NULL);
size_t shadow_info_len = gcry_sexp_canon_len (shadow_info, 0, NULL,NULL);
if (!pubkey_len || !shadow_info_len)
return gpg_error (GPG_ERR_INV_VALUE);
s = pubkey;
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
depth++;
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (!smatch (&s, n, "public-key"))
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
if (*s != '(')
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
depth++;
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
s += n; /* skip over the algorithm name */
while (*s != ')')
{
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
depth++;
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
s += n;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
s +=n; /* skip value */
if (*s != ')')
return gpg_error (GPG_ERR_INV_SEXP);
depth--;
s++;
}
point = s; /* insert right before the point */
depth--;
s++;
assert (depth == 1);
/* Calculate required length by taking in account: the "shadowed-"
prefix, the "shadowed", "t1-v1" as well as some parenthesis */
n = 12 + pubkey_len + 1 + 3+8 + 2+5 + shadow_info_len + 1;
*result = xtrymalloc (n);
p = (char*)*result;
if (!p)
return out_of_core ();
p = stpcpy (p, "(20:shadowed-private-key");
/* (10:public-key ...)*/
memcpy (p, pubkey+14, point - (pubkey+14));
p += point - (pubkey+14);
p = stpcpy (p, "(8:shadowed5:t1-v1");
memcpy (p, shadow_info, shadow_info_len);
p += shadow_info_len;
*p++ = ')';
memcpy (p, point, pubkey_len - (point - pubkey));
p += pubkey_len - (point - pubkey);
return 0;
}
/* Parse a canonical encoded shadowed key and return a pointer to the
inner list with the shadow_info */
gpg_error_t
agent_get_shadow_info (const unsigned char *shadowkey,
unsigned char const **shadow_info)
{
const unsigned char *s;
size_t n;
int depth = 0;
s = shadowkey;
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
depth++;
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (!smatch (&s, n, "shadowed-private-key"))
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
if (*s != '(')
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
depth++;
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
s += n; /* skip over the algorithm name */
for (;;)
{
if (*s == ')')
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
depth++;
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (smatch (&s, n, "shadowed"))
break;
s += n;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
s +=n; /* skip value */
if (*s != ')')
return gpg_error (GPG_ERR_INV_SEXP);
depth--;
s++;
}
/* Found the shadowed list, S points to the protocol */
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (smatch (&s, n, "t1-v1"))
{
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
*shadow_info = s;
}
else
return gpg_error (GPG_ERR_UNSUPPORTED_PROTOCOL);
return 0;
}
/* Parse the canonical encoded SHADOW_INFO S-expression. On success
the hex encoded serial number is returned as a malloced strings at
R_HEXSN and the Id string as a malloced string at R_IDSTR. On
error an error code is returned and NULL is stored at the result
parameters addresses. If the serial number or the ID string is not
required, NULL may be passed for them. */
gpg_error_t
parse_shadow_info (const unsigned char *shadow_info,
char **r_hexsn, char **r_idstr, int *r_pinlen)
{
const unsigned char *s;
size_t n;
if (r_hexsn)
*r_hexsn = NULL;
if (r_idstr)
*r_idstr = NULL;
if (r_pinlen)
*r_pinlen = 0;
s = shadow_info;
if (*s != '(')
return gpg_error (GPG_ERR_INV_SEXP);
s++;
n = snext (&s);
if (!n)
return gpg_error (GPG_ERR_INV_SEXP);
if (r_hexsn)
{
*r_hexsn = bin2hex (s, n, NULL);
if (!*r_hexsn)
return gpg_error_from_syserror ();
}
s += n;
n = snext (&s);
if (!n)
{
if (r_hexsn)
{
xfree (*r_hexsn);
*r_hexsn = NULL;
}
return gpg_error (GPG_ERR_INV_SEXP);
}
if (r_idstr)
{
*r_idstr = xtrymalloc (n+1);
if (!*r_idstr)
{
if (r_hexsn)
{
xfree (*r_hexsn);
*r_hexsn = NULL;
}
return gpg_error_from_syserror ();
}
memcpy (*r_idstr, s, n);
(*r_idstr)[n] = 0;
}
/* Parse the optional PINLEN. */
n = snext (&s);
if (!n)
return 0;
if (r_pinlen)
{
char *tmpstr = xtrymalloc (n+1);
if (!tmpstr)
{
if (r_hexsn)
{
xfree (*r_hexsn);
*r_hexsn = NULL;
}
if (r_idstr)
{
xfree (*r_idstr);
*r_idstr = NULL;
}
return gpg_error_from_syserror ();
}
memcpy (tmpstr, s, n);
tmpstr[n] = 0;
*r_pinlen = (int)strtol (tmpstr, NULL, 10);
xfree (tmpstr);
}
return 0;
}
diff --git a/common/argparse.c b/common/argparse.c
index 331998bb2..db0b7e079 100644
--- a/common/argparse.c
+++ b/common/argparse.c
@@ -1,1660 +1,1660 @@
/* argparse.c - Argument Parser for option handling
* Copyright (C) 1997-2001, 2006-2008, 2013-2017 Werner Koch
* Copyright (C) 1998-2001, 2006-2008, 2012 Free Software Foundation, Inc.
* Copyright (C) 2015-2017 g10 Code GmbH
*
* This file is part of GnuPG.
*
* This file is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This file 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 Lesser General Public License
* along with this program; if not, see .
* SPDX-License-Identifier: LGPL-2.1+
*/
/* This file may be used as part of GnuPG or standalone. A GnuPG
build is detected by the presence of the macro GNUPG_MAJOR_VERSION.
Some feature are only availalbe in the GnuPG build mode.
*/
#ifdef HAVE_CONFIG_H
#include
#endif
#include
#include
#include
#include
#include
#include
#include
#ifdef GNUPG_MAJOR_VERSION
# include "util.h"
# include "common-defs.h"
# include "i18n.h"
# include "mischelp.h"
# include "stringhelp.h"
# include "logging.h"
# include "utf8conv.h"
#endif /*GNUPG_MAJOR_VERSION*/
#include "argparse.h"
/* GnuPG uses GPLv3+ but a standalone version of this defaults to
GPLv2+ because that is the license of this file. Change this if
you include it in a program which uses GPLv3. If you don't want to
set a copyright string for your usage() you may also hardcode it
here. */
#ifndef GNUPG_MAJOR_VERSION
# define ARGPARSE_GPL_VERSION 2
# define ARGPARSE_CRIGHT_STR "Copyright (C) YEAR NAME"
#else /* Used by GnuPG */
# define ARGPARSE_GPL_VERSION 3
# define ARGPARSE_CRIGHT_STR "Copyright (C) 2018 Free Software Foundation, Inc."
#endif /*GNUPG_MAJOR_VERSION*/
/* Replacements for standalone builds. */
#ifndef GNUPG_MAJOR_VERSION
# ifndef _
# define _(a) (a)
# endif
# ifndef DIM
# define DIM(v) (sizeof(v)/sizeof((v)[0]))
# endif
# define xtrymalloc(a) malloc ((a))
# define xtryrealloc(a,b) realloc ((a), (b))
# define xtrystrdup(a) strdup ((a))
# define xfree(a) free ((a))
# define log_error my_log_error
# define log_bug my_log_bug
# define trim_spaces(a) my_trim_spaces ((a))
# define map_static_macro_string(a) (a)
#endif /*!GNUPG_MAJOR_VERSION*/
#define ARGPARSE_STR(v) #v
#define ARGPARSE_STR2(v) ARGPARSE_STR(v)
/* Replacements for standalone builds. */
#ifndef GNUPG_MAJOR_VERSION
static void
my_log_error (const char *fmt, ...)
{
va_list arg_ptr ;
va_start (arg_ptr, fmt);
fprintf (stderr, "%s: ", strusage (11));
vfprintf (stderr, fmt, arg_ptr);
va_end (arg_ptr);
}
static void
my_log_bug (const char *fmt, ...)
{
va_list arg_ptr ;
va_start (arg_ptr, fmt);
fprintf (stderr, "%s: Ohhhh jeeee: ", strusage (11));
vfprintf (stderr, fmt, arg_ptr);
va_end (arg_ptr);
abort ();
}
/* Return true if the native charset is utf-8. */
static int
is_native_utf8 (void)
{
return 1;
}
static char *
my_trim_spaces (char *str)
{
char *string, *p, *mark;
string = str;
/* Find first non space character. */
for (p=string; *p && isspace (*(unsigned char*)p) ; p++)
;
/* Move characters. */
for ((mark = NULL); (*string = *p); string++, p++)
if (isspace (*(unsigned char*)p))
{
if (!mark)
mark = string;
}
else
mark = NULL;
if (mark)
*mark = '\0' ; /* Remove trailing spaces. */
return str ;
}
#endif /*!GNUPG_MAJOR_VERSION*/
/*********************************
* @Summary arg_parse
* #include "argparse.h"
*
* typedef struct {
* char *argc; pointer to argc (value subject to change)
* char ***argv; pointer to argv (value subject to change)
* unsigned flags; Global flags (DO NOT CHANGE)
* int err; print error about last option
* 1 = warning, 2 = abort
* int r_opt; return option
* int r_type; type of return value (0 = no argument found)
* union {
* int ret_int;
* long ret_long
* ulong ret_ulong;
* char *ret_str;
* } r; Return values
* struct {
* int idx;
* const char *last;
* void *aliases;
* } internal; DO NOT CHANGE
* } ARGPARSE_ARGS;
*
* typedef struct {
* int short_opt;
* const char *long_opt;
* unsigned flags;
* } ARGPARSE_OPTS;
*
* int arg_parse( ARGPARSE_ARGS *arg, ARGPARSE_OPTS *opts );
*
* @Description
* This is my replacement for getopt(). See the example for a typical usage.
* Global flags are:
* Bit 0 : Do not remove options form argv
* Bit 1 : Do not stop at last option but return other args
* with r_opt set to -1.
* Bit 2 : Assume options and real args are mixed.
* Bit 3 : Do not use -- to stop option processing.
* Bit 4 : Do not skip the first arg.
* Bit 5 : allow usage of long option with only one dash
* Bit 6 : ignore --version
* all other bits must be set to zero, this value is modified by the
* function, so assume this is write only.
* Local flags (for each option):
* Bit 2-0 : 0 = does not take an argument
* 1 = takes int argument
* 2 = takes string argument
* 3 = takes long argument
* 4 = takes ulong argument
* Bit 3 : argument is optional (r_type will the be set to 0)
* Bit 4 : allow 0x etc. prefixed values.
* Bit 6 : Ignore this option
* Bit 7 : This is a command and not an option
* You stop the option processing by setting opts to NULL, the function will
* then return 0.
* @Return Value
* Returns the args.r_opt or 0 if ready
* r_opt may be -2/-7 to indicate an unknown option/command.
* @See Also
* ArgExpand
* @Notes
* You do not need to process the options 'h', '--help' or '--version'
* because this function includes standard help processing; but if you
* specify '-h', '--help' or '--version' you have to do it yourself.
* The option '--' stops argument processing; if bit 1 is set the function
* continues to return normal arguments.
* To process float args or unsigned args you must use a string args and do
* the conversion yourself.
* @Example
*
* ARGPARSE_OPTS opts[] = {
* { 'v', "verbose", 0 },
* { 'd', "debug", 0 },
* { 'o', "output", 2 },
* { 'c', "cross-ref", 2|8 },
* { 'm', "my-option", 1|8 },
* { 300, "ignored-long-option, ARGPARSE_OP_IGNORE},
* { 500, "have-no-short-option-for-this-long-option", 0 },
* {0} };
* ARGPARSE_ARGS pargs = { &argc, &argv, 0 }
*
* while( ArgParse( &pargs, &opts) ) {
* switch( pargs.r_opt ) {
* case 'v': opt.verbose++; break;
* case 'd': opt.debug++; break;
* case 'o': opt.outfile = pargs.r.ret_str; break;
* case 'c': opt.crf = pargs.r_type? pargs.r.ret_str:"a.crf"; break;
* case 'm': opt.myopt = pargs.r_type? pargs.r.ret_int : 1; break;
* case 500: opt.a_long_one++; break
* default : pargs.err = 1; break; -- force warning output --
* }
* }
* if( argc > 1 )
* log_fatal( "Too many args");
*
*/
typedef struct alias_def_s *ALIAS_DEF;
struct alias_def_s {
ALIAS_DEF next;
char *name; /* malloced buffer with name, \0, value */
const char *value; /* ptr into name */
};
/* Object to store the names for the --ignore-invalid-option option.
This is a simple linked list. */
typedef struct iio_item_def_s *IIO_ITEM_DEF;
struct iio_item_def_s
{
IIO_ITEM_DEF next;
char name[1]; /* String with the long option name. */
};
static const char *(*strusage_handler)( int ) = NULL;
static int (*custom_outfnc) (int, const char *);
static int set_opt_arg(ARGPARSE_ARGS *arg, unsigned flags, char *s);
static void show_help(ARGPARSE_OPTS *opts, unsigned flags);
static void show_version(void);
static int writestrings (int is_error, const char *string, ...)
#if __GNUC__ >= 4
__attribute__ ((sentinel(0)))
#endif
;
void
argparse_register_outfnc (int (*fnc)(int, const char *))
{
custom_outfnc = fnc;
}
/* Write STRING and all following const char * arguments either to
stdout or, if IS_ERROR is set, to stderr. The list of strings must
be terminated by a NULL. */
static int
writestrings (int is_error, const char *string, ...)
{
va_list arg_ptr;
const char *s;
int count = 0;
if (string)
{
s = string;
va_start (arg_ptr, string);
do
{
if (custom_outfnc)
custom_outfnc (is_error? 2:1, s);
else
fputs (s, is_error? stderr : stdout);
count += strlen (s);
}
while ((s = va_arg (arg_ptr, const char *)));
va_end (arg_ptr);
}
return count;
}
static void
flushstrings (int is_error)
{
if (custom_outfnc)
custom_outfnc (is_error? 2:1, NULL);
else
fflush (is_error? stderr : stdout);
}
static void
initialize( ARGPARSE_ARGS *arg, const char *filename, unsigned *lineno )
{
if( !(arg->flags & (1<<15)) )
{
/* Initialize this instance. */
arg->internal.idx = 0;
arg->internal.last = NULL;
arg->internal.inarg = 0;
arg->internal.stopped = 0;
arg->internal.aliases = NULL;
arg->internal.cur_alias = NULL;
arg->internal.iio_list = NULL;
arg->err = 0;
arg->flags |= 1<<15; /* Mark as initialized. */
if ( *arg->argc < 0 )
log_bug ("invalid argument for arg_parse\n");
}
if (arg->err)
{
/* Last option was erroneous. */
const char *s;
if (filename)
{
if ( arg->r_opt == ARGPARSE_UNEXPECTED_ARG )
s = _("argument not expected");
else if ( arg->r_opt == ARGPARSE_READ_ERROR )
s = _("read error");
else if ( arg->r_opt == ARGPARSE_KEYWORD_TOO_LONG )
s = _("keyword too long");
else if ( arg->r_opt == ARGPARSE_MISSING_ARG )
s = _("missing argument");
else if ( arg->r_opt == ARGPARSE_INVALID_ARG )
s = _("invalid argument");
else if ( arg->r_opt == ARGPARSE_INVALID_COMMAND )
s = _("invalid command");
else if ( arg->r_opt == ARGPARSE_INVALID_ALIAS )
s = _("invalid alias definition");
else if ( arg->r_opt == ARGPARSE_OUT_OF_CORE )
s = _("out of core");
else
s = _("invalid option");
log_error ("%s:%u: %s\n", filename, *lineno, s);
}
else
{
s = arg->internal.last? arg->internal.last:"[??]";
if ( arg->r_opt == ARGPARSE_MISSING_ARG )
log_error (_("missing argument for option \"%.50s\"\n"), s);
else if ( arg->r_opt == ARGPARSE_INVALID_ARG )
log_error (_("invalid argument for option \"%.50s\"\n"), s);
else if ( arg->r_opt == ARGPARSE_UNEXPECTED_ARG )
log_error (_("option \"%.50s\" does not expect an argument\n"), s);
else if ( arg->r_opt == ARGPARSE_INVALID_COMMAND )
log_error (_("invalid command \"%.50s\"\n"), s);
else if ( arg->r_opt == ARGPARSE_AMBIGUOUS_OPTION )
log_error (_("option \"%.50s\" is ambiguous\n"), s);
else if ( arg->r_opt == ARGPARSE_AMBIGUOUS_COMMAND )
log_error (_("command \"%.50s\" is ambiguous\n"),s );
else if ( arg->r_opt == ARGPARSE_OUT_OF_CORE )
log_error ("%s\n", _("out of core\n"));
else
log_error (_("invalid option \"%.50s\"\n"), s);
}
if (arg->err != ARGPARSE_PRINT_WARNING)
exit (2);
arg->err = 0;
}
/* Zero out the return value union. */
arg->r.ret_str = NULL;
arg->r.ret_long = 0;
}
static void
store_alias( ARGPARSE_ARGS *arg, char *name, char *value )
{
/* TODO: replace this dummy function with a rea one
- * and fix the probelms IRIX has with (ALIAS_DEV)arg..
+ * and fix the problems IRIX has with (ALIAS_DEV)arg..
* used as lvalue
*/
(void)arg;
(void)name;
(void)value;
#if 0
ALIAS_DEF a = xmalloc( sizeof *a );
a->name = name;
a->value = value;
a->next = (ALIAS_DEF)arg->internal.aliases;
(ALIAS_DEF)arg->internal.aliases = a;
#endif
}
/* Return true if KEYWORD is in the ignore-invalid-option list. */
static int
ignore_invalid_option_p (ARGPARSE_ARGS *arg, const char *keyword)
{
IIO_ITEM_DEF item = arg->internal.iio_list;
for (; item; item = item->next)
if (!strcmp (item->name, keyword))
return 1;
return 0;
}
/* Add the keywords up to the next LF to the list of to be ignored
options. After returning FP will either be at EOF or the next
- character read wll be the first of a new line. The function
+ character read will be the first of a new line. The function
returns 0 on success or true on malloc failure. */
static int
ignore_invalid_option_add (ARGPARSE_ARGS *arg, FILE *fp)
{
IIO_ITEM_DEF item;
int c;
char name[100];
int namelen = 0;
int ready = 0;
enum { skipWS, collectNAME, skipNAME, addNAME} state = skipWS;
while (!ready)
{
c = getc (fp);
if (c == '\n')
ready = 1;
else if (c == EOF)
{
c = '\n';
ready = 1;
}
again:
switch (state)
{
case skipWS:
if (!isascii (c) || !isspace(c))
{
namelen = 0;
state = collectNAME;
goto again;
}
break;
case collectNAME:
if (isspace (c))
{
state = addNAME;
goto again;
}
else if (namelen < DIM(name)-1)
name[namelen++] = c;
else /* Too long. */
state = skipNAME;
break;
case skipNAME:
if (isspace (c))
{
state = skipWS;
goto again;
}
break;
case addNAME:
name[namelen] = 0;
if (!ignore_invalid_option_p (arg, name))
{
item = xtrymalloc (sizeof *item + namelen);
if (!item)
return 1;
strcpy (item->name, name);
item->next = (IIO_ITEM_DEF)arg->internal.iio_list;
arg->internal.iio_list = item;
}
state = skipWS;
goto again;
}
}
return 0;
}
/* Clear the entire ignore-invalid-option list. */
static void
ignore_invalid_option_clear (ARGPARSE_ARGS *arg)
{
IIO_ITEM_DEF item, tmpitem;
for (item = arg->internal.iio_list; item; item = tmpitem)
{
tmpitem = item->next;
xfree (item);
}
arg->internal.iio_list = NULL;
}
/****************
* Get options from a file.
* Lines starting with '#' are comment lines.
* Syntax is simply a keyword and the argument.
* Valid keywords are all keywords from the long_opt list without
* the leading dashes. The special keywords "help", "warranty" and "version"
* are not valid here.
* The special keyword "alias" may be used to store alias definitions,
* which are later expanded like long options.
* The option
* ignore-invalid-option OPTIONNAMEs
* is recognized and updates a list of option which should be ignored if they
* are not defined.
* Caller must free returned strings.
* If called with FP set to NULL command line args are parse instead.
*
* Q: Should we allow the syntax
* keyword = value
* and accept for boolean options a value of 1/0, yes/no or true/false?
* Note: Abbreviation of options is here not allowed.
*/
int
optfile_parse (FILE *fp, const char *filename, unsigned *lineno,
ARGPARSE_ARGS *arg, ARGPARSE_OPTS *opts)
{
int state, i, c;
int idx=0;
char keyword[100];
char *buffer = NULL;
size_t buflen = 0;
int in_alias=0;
int unread_buf[3]; /* We use an int so that we can store EOF. */
int unread_buf_count = 0;
if (!fp) /* Divert to arg_parse() in this case. */
return arg_parse (arg, opts);
initialize (arg, filename, lineno);
/* If the LINENO is zero we assume that we are at the start of a
* file and we skip over a possible Byte Order Mark. */
if (!*lineno)
{
unread_buf[0] = getc (fp);
unread_buf[1] = getc (fp);
unread_buf[2] = getc (fp);
if (unread_buf[0] != 0xef
|| unread_buf[1] != 0xbb
|| unread_buf[2] != 0xbf)
unread_buf_count = 3;
}
/* Find the next keyword. */
state = i = 0;
for (;;)
{
if (unread_buf_count)
c = unread_buf[3 - unread_buf_count--];
else
c = getc (fp);
if (c == '\n' || c== EOF )
{
if ( c != EOF )
++*lineno;
if (state == -1)
break;
else if (state == 2)
{
keyword[i] = 0;
for (i=0; opts[i].short_opt; i++ )
{
if (opts[i].long_opt && !strcmp (opts[i].long_opt, keyword))
break;
}
idx = i;
arg->r_opt = opts[idx].short_opt;
if ((opts[idx].flags & ARGPARSE_OPT_IGNORE))
{
state = i = 0;
continue;
}
else if (!opts[idx].short_opt )
{
if (!strcmp (keyword, "ignore-invalid-option"))
{
/* No argument - ignore this meta option. */
state = i = 0;
continue;
}
else if (ignore_invalid_option_p (arg, keyword))
{
/* This invalid option is in the iio list. */
state = i = 0;
continue;
}
arg->r_opt = ((opts[idx].flags & ARGPARSE_OPT_COMMAND)
? ARGPARSE_INVALID_COMMAND
: ARGPARSE_INVALID_OPTION);
}
else if (!(opts[idx].flags & ARGPARSE_TYPE_MASK))
arg->r_type = 0; /* Does not take an arg. */
else if ((opts[idx].flags & ARGPARSE_OPT_OPTIONAL) )
arg->r_type = 0; /* Arg is optional. */
else
arg->r_opt = ARGPARSE_MISSING_ARG;
break;
}
else if (state == 3)
{
/* No argument found. */
if (in_alias)
arg->r_opt = ARGPARSE_MISSING_ARG;
else if (!(opts[idx].flags & ARGPARSE_TYPE_MASK))
arg->r_type = 0; /* Does not take an arg. */
else if ((opts[idx].flags & ARGPARSE_OPT_OPTIONAL))
arg->r_type = 0; /* No optional argument. */
else
arg->r_opt = ARGPARSE_MISSING_ARG;
break;
}
else if (state == 4)
{
/* Has an argument. */
if (in_alias)
{
if (!buffer)
arg->r_opt = ARGPARSE_UNEXPECTED_ARG;
else
{
char *p;
buffer[i] = 0;
p = strpbrk (buffer, " \t");
if (p)
{
*p++ = 0;
trim_spaces (p);
}
if (!p || !*p)
{
xfree (buffer);
arg->r_opt = ARGPARSE_INVALID_ALIAS;
}
else
{
store_alias (arg, buffer, p);
}
}
}
else if (!(opts[idx].flags & ARGPARSE_TYPE_MASK))
arg->r_opt = ARGPARSE_UNEXPECTED_ARG;
else
{
char *p;
if (!buffer)
{
keyword[i] = 0;
buffer = xtrystrdup (keyword);
if (!buffer)
arg->r_opt = ARGPARSE_OUT_OF_CORE;
}
else
buffer[i] = 0;
if (buffer)
{
trim_spaces (buffer);
p = buffer;
if (*p == '"')
{
/* Remove quotes. */
p++;
if (*p && p[strlen(p)-1] == '\"' )
p[strlen(p)-1] = 0;
}
if (!set_opt_arg (arg, opts[idx].flags, p))
xfree (buffer);
else
gpgrt_annotate_leaked_object (buffer);
}
}
break;
}
else if (c == EOF)
{
ignore_invalid_option_clear (arg);
if (ferror (fp))
arg->r_opt = ARGPARSE_READ_ERROR;
else
arg->r_opt = 0; /* EOF. */
break;
}
state = 0;
i = 0;
}
else if (state == -1)
; /* Skip. */
else if (state == 0 && isascii (c) && isspace(c))
; /* Skip leading white space. */
else if (state == 0 && c == '#' )
state = 1; /* Start of a comment. */
else if (state == 1)
; /* Skip comments. */
else if (state == 2 && isascii (c) && isspace(c))
{
/* Check keyword. */
keyword[i] = 0;
for (i=0; opts[i].short_opt; i++ )
if (opts[i].long_opt && !strcmp (opts[i].long_opt, keyword))
break;
idx = i;
arg->r_opt = opts[idx].short_opt;
if ((opts[idx].flags & ARGPARSE_OPT_IGNORE))
{
state = 1; /* Process like a comment. */
}
else if (!opts[idx].short_opt)
{
if (!strcmp (keyword, "alias"))
{
in_alias = 1;
state = 3;
}
else if (!strcmp (keyword, "ignore-invalid-option"))
{
if (ignore_invalid_option_add (arg, fp))
{
arg->r_opt = ARGPARSE_OUT_OF_CORE;
break;
}
state = i = 0;
++*lineno;
}
else if (ignore_invalid_option_p (arg, keyword))
state = 1; /* Process like a comment. */
else
{
arg->r_opt = ((opts[idx].flags & ARGPARSE_OPT_COMMAND)
? ARGPARSE_INVALID_COMMAND
: ARGPARSE_INVALID_OPTION);
state = -1; /* Skip rest of line and leave. */
}
}
else
state = 3;
}
else if (state == 3)
{
/* Skip leading spaces of the argument. */
if (!isascii (c) || !isspace(c))
{
i = 0;
keyword[i++] = c;
state = 4;
}
}
else if (state == 4)
{
/* Collect the argument. */
if (buffer)
{
if (i < buflen-1)
buffer[i++] = c;
else
{
char *tmp;
size_t tmplen = buflen + 50;
tmp = xtryrealloc (buffer, tmplen);
if (tmp)
{
buflen = tmplen;
buffer = tmp;
buffer[i++] = c;
}
else
{
xfree (buffer);
arg->r_opt = ARGPARSE_OUT_OF_CORE;
break;
}
}
}
else if (i < DIM(keyword)-1)
keyword[i++] = c;
else
{
size_t tmplen = DIM(keyword) + 50;
buffer = xtrymalloc (tmplen);
if (buffer)
{
buflen = tmplen;
memcpy(buffer, keyword, i);
buffer[i++] = c;
}
else
{
arg->r_opt = ARGPARSE_OUT_OF_CORE;
break;
}
}
}
else if (i >= DIM(keyword)-1)
{
arg->r_opt = ARGPARSE_KEYWORD_TOO_LONG;
state = -1; /* Skip rest of line and leave. */
}
else
{
keyword[i++] = c;
state = 2;
}
}
return arg->r_opt;
}
static int
find_long_option( ARGPARSE_ARGS *arg,
ARGPARSE_OPTS *opts, const char *keyword )
{
int i;
size_t n;
(void)arg;
/* Would be better if we can do a binary search, but it is not
possible to reorder our option table because we would mess
up our help strings - What we can do is: Build a nice option
lookup table when this function is first invoked */
if( !*keyword )
return -1;
for(i=0; opts[i].short_opt; i++ )
if( opts[i].long_opt && !strcmp( opts[i].long_opt, keyword) )
return i;
#if 0
{
ALIAS_DEF a;
/* see whether it is an alias */
for( a = args->internal.aliases; a; a = a->next ) {
if( !strcmp( a->name, keyword) ) {
/* todo: must parse the alias here */
args->internal.cur_alias = a;
return -3; /* alias available */
}
}
}
#endif
/* not found, see whether it is an abbreviation */
/* aliases may not be abbreviated */
n = strlen( keyword );
for(i=0; opts[i].short_opt; i++ ) {
if( opts[i].long_opt && !strncmp( opts[i].long_opt, keyword, n ) ) {
int j;
for(j=i+1; opts[j].short_opt; j++ ) {
if( opts[j].long_opt
&& !strncmp( opts[j].long_opt, keyword, n )
&& !(opts[j].short_opt == opts[i].short_opt
&& opts[j].flags == opts[i].flags ) )
return -2; /* abbreviation is ambiguous */
}
return i;
}
}
return -1; /* Not found. */
}
int
arg_parse( ARGPARSE_ARGS *arg, ARGPARSE_OPTS *opts)
{
int idx;
int argc;
char **argv;
char *s, *s2;
int i;
/* Fill in missing standard options: help, version, warranty and
* dump-options. */
ARGPARSE_OPTS help_opt
= ARGPARSE_s_n (ARGPARSE_SHORTOPT_HELP, "help", "@");
ARGPARSE_OPTS version_opt
= ARGPARSE_s_n (ARGPARSE_SHORTOPT_VERSION, "version", "@");
ARGPARSE_OPTS warranty_opt
= ARGPARSE_s_n (ARGPARSE_SHORTOPT_WARRANTY, "warranty", "@");
ARGPARSE_OPTS dump_options_opt
= ARGPARSE_s_n(ARGPARSE_SHORTOPT_DUMP_OPTIONS, "dump-options", "@");
int seen_help = 0;
int seen_version = 0;
int seen_warranty = 0;
int seen_dump_options = 0;
i = 0;
while (opts[i].short_opt)
{
if (opts[i].long_opt)
{
if (!strcmp(opts[i].long_opt, help_opt.long_opt))
seen_help = 1;
else if (!strcmp(opts[i].long_opt, version_opt.long_opt))
seen_version = 1;
else if (!strcmp(opts[i].long_opt, warranty_opt.long_opt))
seen_warranty = 1;
else if (!strcmp(opts[i].long_opt, dump_options_opt.long_opt))
seen_dump_options = 1;
}
i++;
}
if (! seen_help)
opts[i++] = help_opt;
if (! seen_version)
opts[i++] = version_opt;
if (! seen_warranty)
opts[i++] = warranty_opt;
if (! seen_dump_options)
opts[i++] = dump_options_opt;
initialize( arg, NULL, NULL );
argc = *arg->argc;
argv = *arg->argv;
idx = arg->internal.idx;
if (!idx && argc && !(arg->flags & ARGPARSE_FLAG_ARG0))
{
/* Skip the first argument. */
argc--; argv++; idx++;
}
next_one:
if (!argc)
{
/* No more args. */
arg->r_opt = 0;
goto leave; /* Ready. */
}
s = *argv;
arg->internal.last = s;
if (arg->internal.stopped && (arg->flags & ARGPARSE_FLAG_ALL))
{
arg->r_opt = ARGPARSE_IS_ARG; /* Not an option but an argument. */
arg->r_type = 2;
arg->r.ret_str = s;
argc--; argv++; idx++; /* set to next one */
}
else if( arg->internal.stopped )
{
arg->r_opt = 0;
goto leave; /* Ready. */
}
else if ( *s == '-' && s[1] == '-' )
{
/* Long option. */
char *argpos;
arg->internal.inarg = 0;
if (!s[2] && !(arg->flags & ARGPARSE_FLAG_NOSTOP))
{
/* Stop option processing. */
arg->internal.stopped = 1;
arg->flags |= ARGPARSE_FLAG_STOP_SEEN;
argc--; argv++; idx++;
goto next_one;
}
argpos = strchr( s+2, '=' );
if ( argpos )
*argpos = 0;
i = find_long_option ( arg, opts, s+2 );
if ( argpos )
*argpos = '=';
if (i > 0 && opts[i].short_opt == ARGPARSE_SHORTOPT_HELP)
show_help (opts, arg->flags);
else if (i > 0 && opts[i].short_opt == ARGPARSE_SHORTOPT_VERSION)
{
if (!(arg->flags & ARGPARSE_FLAG_NOVERSION))
{
show_version ();
exit(0);
}
}
else if (i > 0 && opts[i].short_opt == ARGPARSE_SHORTOPT_WARRANTY)
{
writestrings (0, strusage (16), "\n", NULL);
exit (0);
}
else if (i > 0 && opts[i].short_opt == ARGPARSE_SHORTOPT_DUMP_OPTIONS)
{
for (i=0; opts[i].short_opt; i++ )
{
if (opts[i].long_opt && !(opts[i].flags & ARGPARSE_OPT_IGNORE))
writestrings (0, "--", opts[i].long_opt, "\n", NULL);
}
exit (0);
}
if ( i == -2 )
arg->r_opt = ARGPARSE_AMBIGUOUS_OPTION;
else if ( i == -1 )
{
arg->r_opt = ARGPARSE_INVALID_OPTION;
arg->r.ret_str = s+2;
}
else
arg->r_opt = opts[i].short_opt;
if ( i < 0 )
;
else if ( (opts[i].flags & ARGPARSE_TYPE_MASK) )
{
if ( argpos )
{
s2 = argpos+1;
if ( !*s2 )
s2 = NULL;
}
else
s2 = argv[1];
if ( !s2 && (opts[i].flags & ARGPARSE_OPT_OPTIONAL) )
{
arg->r_type = ARGPARSE_TYPE_NONE; /* Argument is optional. */
}
else if ( !s2 )
{
arg->r_opt = ARGPARSE_MISSING_ARG;
}
else if ( !argpos && *s2 == '-'
&& (opts[i].flags & ARGPARSE_OPT_OPTIONAL) )
{
/* The argument is optional and the next seems to be an
option. We do not check this possible option but
assume no argument */
arg->r_type = ARGPARSE_TYPE_NONE;
}
else
{
set_opt_arg (arg, opts[i].flags, s2);
if ( !argpos )
{
argc--; argv++; idx++; /* Skip one. */
}
}
}
else
{
/* Does not take an argument. */
if ( argpos )
arg->r_type = ARGPARSE_UNEXPECTED_ARG;
else
arg->r_type = 0;
}
argc--; argv++; idx++; /* Set to next one. */
}
else if ( (*s == '-' && s[1]) || arg->internal.inarg )
{
/* Short option. */
int dash_kludge = 0;
i = 0;
if ( !arg->internal.inarg )
{
arg->internal.inarg++;
if ( (arg->flags & ARGPARSE_FLAG_ONEDASH) )
{
for (i=0; opts[i].short_opt; i++ )
if ( opts[i].long_opt && !strcmp (opts[i].long_opt, s+1))
{
dash_kludge = 1;
break;
}
}
}
s += arg->internal.inarg;
if (!dash_kludge )
{
for (i=0; opts[i].short_opt; i++ )
if ( opts[i].short_opt == *s )
break;
}
if ( !opts[i].short_opt && ( *s == 'h' || *s == '?' ) )
show_help (opts, arg->flags);
arg->r_opt = opts[i].short_opt;
if (!opts[i].short_opt )
{
arg->r_opt = (opts[i].flags & ARGPARSE_OPT_COMMAND)?
ARGPARSE_INVALID_COMMAND:ARGPARSE_INVALID_OPTION;
arg->internal.inarg++; /* Point to the next arg. */
arg->r.ret_str = s;
}
else if ( (opts[i].flags & ARGPARSE_TYPE_MASK) )
{
if ( s[1] && !dash_kludge )
{
s2 = s+1;
set_opt_arg (arg, opts[i].flags, s2);
}
else
{
s2 = argv[1];
if ( !s2 && (opts[i].flags & ARGPARSE_OPT_OPTIONAL) )
{
arg->r_type = ARGPARSE_TYPE_NONE;
}
else if ( !s2 )
{
arg->r_opt = ARGPARSE_MISSING_ARG;
}
else if ( *s2 == '-' && s2[1]
&& (opts[i].flags & ARGPARSE_OPT_OPTIONAL) )
{
/* The argument is optional and the next seems to
be an option. We do not check this possible
option but assume no argument. */
arg->r_type = ARGPARSE_TYPE_NONE;
}
else
{
set_opt_arg (arg, opts[i].flags, s2);
argc--; argv++; idx++; /* Skip one. */
}
}
s = "x"; /* This is so that !s[1] yields false. */
}
else
{
/* Does not take an argument. */
arg->r_type = ARGPARSE_TYPE_NONE;
arg->internal.inarg++; /* Point to the next arg. */
}
if ( !s[1] || dash_kludge )
{
/* No more concatenated short options. */
arg->internal.inarg = 0;
argc--; argv++; idx++;
}
}
else if ( arg->flags & ARGPARSE_FLAG_MIXED )
{
arg->r_opt = ARGPARSE_IS_ARG;
arg->r_type = 2;
arg->r.ret_str = s;
argc--; argv++; idx++; /* Set to next one. */
}
else
{
arg->internal.stopped = 1; /* Stop option processing. */
goto next_one;
}
leave:
*arg->argc = argc;
*arg->argv = argv;
arg->internal.idx = idx;
return arg->r_opt;
}
/* Returns: -1 on error, 0 for an integer type and 1 for a non integer
type argument. */
static int
set_opt_arg (ARGPARSE_ARGS *arg, unsigned flags, char *s)
{
int base = (flags & ARGPARSE_OPT_PREFIX)? 0 : 10;
long l;
switch ( (arg->r_type = (flags & ARGPARSE_TYPE_MASK)) )
{
case ARGPARSE_TYPE_LONG:
case ARGPARSE_TYPE_INT:
errno = 0;
l = strtol (s, NULL, base);
if ((l == LONG_MIN || l == LONG_MAX) && errno == ERANGE)
{
arg->r_opt = ARGPARSE_INVALID_ARG;
return -1;
}
if (arg->r_type == ARGPARSE_TYPE_LONG)
arg->r.ret_long = l;
else if ( (l < 0 && l < INT_MIN) || l > INT_MAX )
{
arg->r_opt = ARGPARSE_INVALID_ARG;
return -1;
}
else
arg->r.ret_int = (int)l;
return 0;
case ARGPARSE_TYPE_ULONG:
while (isascii (*s) && isspace(*s))
s++;
if (*s == '-')
{
arg->r.ret_ulong = 0;
arg->r_opt = ARGPARSE_INVALID_ARG;
return -1;
}
errno = 0;
arg->r.ret_ulong = strtoul (s, NULL, base);
if (arg->r.ret_ulong == ULONG_MAX && errno == ERANGE)
{
arg->r_opt = ARGPARSE_INVALID_ARG;
return -1;
}
return 0;
case ARGPARSE_TYPE_STRING:
default:
arg->r.ret_str = s;
return 1;
}
}
static size_t
long_opt_strlen( ARGPARSE_OPTS *o )
{
size_t n = strlen (o->long_opt);
if ( o->description && *o->description == '|' )
{
const char *s;
int is_utf8 = is_native_utf8 ();
s=o->description+1;
if ( *s != '=' )
n++;
/* For a (mostly) correct length calculation we exclude
continuation bytes (10xxxxxx) if we are on a native utf8
terminal. */
for (; *s && *s != '|'; s++ )
if ( is_utf8 && (*s&0xc0) != 0x80 )
n++;
}
return n;
}
/****************
* Print formatted help. The description string has some special
* meanings:
* - A description string which is "@" suppresses help output for
* this option
* - a description,ine which starts with a '@' and is followed by
* any other characters is printed as is; this may be used for examples
- * ans such.
+ * and such.
* - A description which starts with a '|' outputs the string between this
* bar and the next one as arguments of the long option.
*/
static void
show_help (ARGPARSE_OPTS *opts, unsigned int flags)
{
const char *s;
char tmp[2];
show_version ();
writestrings (0, "\n", NULL);
s = strusage (42);
if (s && *s == '1')
{
s = strusage (40);
writestrings (1, s, NULL);
if (*s && s[strlen(s)] != '\n')
writestrings (1, "\n", NULL);
}
s = strusage(41);
writestrings (0, s, "\n", NULL);
if ( opts[0].description )
{
/* Auto format the option description. */
int i,j, indent;
/* Get max. length of long options. */
for (i=indent=0; opts[i].short_opt; i++ )
{
if ( opts[i].long_opt )
if ( !opts[i].description || *opts[i].description != '@' )
if ( (j=long_opt_strlen(opts+i)) > indent && j < 35 )
indent = j;
}
/* Example: " -v, --verbose Viele Sachen ausgeben" */
indent += 10;
if ( *opts[0].description != '@' )
writestrings (0, "Options:", "\n", NULL);
for (i=0; opts[i].short_opt; i++ )
{
s = map_static_macro_string (_( opts[i].description ));
if ( s && *s== '@' && !s[1] ) /* Hide this line. */
continue;
if ( s && *s == '@' ) /* Unindented comment only line. */
{
for (s++; *s; s++ )
{
if ( *s == '\n' )
{
if( s[1] )
writestrings (0, "\n", NULL);
}
else
{
tmp[0] = *s;
tmp[1] = 0;
writestrings (0, tmp, NULL);
}
}
writestrings (0, "\n", NULL);
continue;
}
j = 3;
if ( opts[i].short_opt < 256 )
{
tmp[0] = opts[i].short_opt;
tmp[1] = 0;
writestrings (0, " -", tmp, NULL );
if ( !opts[i].long_opt )
{
if (s && *s == '|' )
{
writestrings (0, " ", NULL); j++;
for (s++ ; *s && *s != '|'; s++, j++ )
{
tmp[0] = *s;
tmp[1] = 0;
writestrings (0, tmp, NULL);
}
if ( *s )
s++;
}
}
}
else
writestrings (0, " ", NULL);
if ( opts[i].long_opt )
{
tmp[0] = opts[i].short_opt < 256?',':' ';
tmp[1] = 0;
j += writestrings (0, tmp, " --", opts[i].long_opt, NULL);
if (s && *s == '|' )
{
if ( *++s != '=' )
{
writestrings (0, " ", NULL);
j++;
}
for ( ; *s && *s != '|'; s++, j++ )
{
tmp[0] = *s;
tmp[1] = 0;
writestrings (0, tmp, NULL);
}
if ( *s )
s++;
}
writestrings (0, " ", NULL);
j += 3;
}
for (;j < indent; j++ )
writestrings (0, " ", NULL);
if ( s )
{
if ( *s && j > indent )
{
writestrings (0, "\n", NULL);
for (j=0;j < indent; j++ )
writestrings (0, " ", NULL);
}
for (; *s; s++ )
{
if ( *s == '\n' )
{
if ( s[1] )
{
writestrings (0, "\n", NULL);
for (j=0; j < indent; j++ )
writestrings (0, " ", NULL);
}
}
else
{
tmp[0] = *s;
tmp[1] = 0;
writestrings (0, tmp, NULL);
}
}
}
writestrings (0, "\n", NULL);
}
if ( (flags & ARGPARSE_FLAG_ONEDASH) )
writestrings (0, "\n(A single dash may be used "
"instead of the double ones)\n", NULL);
}
if ( (s=strusage(19)) )
{
writestrings (0, "\n", NULL);
writestrings (0, s, NULL);
}
flushstrings (0);
exit(0);
}
static void
show_version ()
{
const char *s;
int i;
/* Version line. */
writestrings (0, strusage (11), NULL);
if ((s=strusage (12)))
writestrings (0, " (", s, ")", NULL);
writestrings (0, " ", strusage (13), "\n", NULL);
/* Additional version lines. */
for (i=20; i < 30; i++)
if ((s=strusage (i)))
writestrings (0, s, "\n", NULL);
/* Copyright string. */
if ((s=strusage (14)))
writestrings (0, s, "\n", NULL);
/* Licence string. */
if( (s=strusage (10)) )
writestrings (0, s, "\n", NULL);
/* Copying conditions. */
if ( (s=strusage(15)) )
writestrings (0, s, NULL);
/* Thanks. */
if ((s=strusage(18)))
writestrings (0, s, NULL);
/* Additional program info. */
for (i=30; i < 40; i++ )
if ( (s=strusage (i)) )
writestrings (0, s, NULL);
flushstrings (0);
}
void
usage (int level)
{
const char *p;
if (!level)
{
writestrings (1, strusage(11), " ", strusage(13), "; ",
strusage (14), "\n", NULL);
flushstrings (1);
}
else if (level == 1)
{
p = strusage (40);
writestrings (1, p, NULL);
if (*p && p[strlen(p)] != '\n')
writestrings (1, "\n", NULL);
exit (2);
}
else if (level == 2)
{
p = strusage (42);
if (p && *p == '1')
{
p = strusage (40);
writestrings (1, p, NULL);
if (*p && p[strlen(p)] != '\n')
writestrings (1, "\n", NULL);
}
writestrings (0, strusage(41), "\n", NULL);
exit (0);
}
}
/* Level
* 0: Print copyright string to stderr
* 1: Print a short usage hint to stderr and terminate
* 2: Print a long usage hint to stdout and terminate
* 10: Return license info string
* 11: Return the name of the program
* 12: Return optional name of package which includes this program.
* 13: version string
* 14: copyright string
* 15: Short copying conditions (with LFs)
* 16: Long copying conditions (with LFs)
* 17: Optional printable OS name
* 18: Optional thanks list (with LFs)
* 19: Bug report info
*20..29: Additional lib version strings.
*30..39: Additional program info (with LFs)
* 40: short usage note (with LF)
* 41: long usage note (with LF)
* 42: Flag string:
* First char is '1':
* The short usage notes needs to be printed
* before the long usage note.
*/
const char *
strusage( int level )
{
const char *p = strusage_handler? strusage_handler(level) : NULL;
if ( p )
return map_static_macro_string (p);
switch ( level )
{
case 10:
#if ARGPARSE_GPL_VERSION == 3
p = ("License GPLv3+: GNU GPL version 3 or later "
"");
#else
p = ("License GPLv2+: GNU GPL version 2 or later "
"");
#endif
break;
case 11: p = "foo"; break;
case 13: p = "0.0"; break;
case 14: p = ARGPARSE_CRIGHT_STR; break;
case 15: p =
"This is free software: you are free to change and redistribute it.\n"
"There is NO WARRANTY, to the extent permitted by law.\n";
break;
case 16: p =
"This is free software; you can redistribute it and/or modify\n"
"it under the terms of the GNU General Public License as published by\n"
"the Free Software Foundation; either version "
ARGPARSE_STR2(ARGPARSE_GPL_VERSION)
" of the License, or\n"
"(at your option) any later version.\n\n"
"It is distributed in the hope that it will be useful,\n"
"but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
"GNU General Public License for more details.\n\n"
"You should have received a copy of the GNU General Public License\n"
"along with this software. If not, see .\n";
break;
case 40: /* short and long usage */
case 41: p = ""; break;
}
return p;
}
/* Set the usage handler. This function is basically a constructor. */
void
set_strusage ( const char *(*f)( int ) )
{
strusage_handler = f;
}
#ifdef TEST
static struct {
int verbose;
int debug;
char *outfile;
char *crf;
int myopt;
int echo;
int a_long_one;
} opt;
int
main(int argc, char **argv)
{
ARGPARSE_OPTS opts[] = {
ARGPARSE_x('v', "verbose", NONE, 0, "Laut sein"),
ARGPARSE_s_n('e', "echo" , ("Zeile ausgeben, damit wir sehen, "
"was wir eingegeben haben")),
ARGPARSE_s_n('d', "debug", "Debug\nfalls mal etwas\nschief geht"),
ARGPARSE_s_s('o', "output", 0 ),
ARGPARSE_o_s('c', "cross-ref", "cross-reference erzeugen\n" ),
/* Note that on a non-utf8 terminal the ß might garble the output. */
ARGPARSE_s_n('s', "street","|Straße|set the name of the street to Straße"),
ARGPARSE_o_i('m', "my-option", 0),
ARGPARSE_s_n(500, "a-long-option", 0 ),
ARGPARSE_end()
};
ARGPARSE_ARGS pargs = { &argc, &argv, (ARGPARSE_FLAG_ALL
| ARGPARSE_FLAG_MIXED
| ARGPARSE_FLAG_ONEDASH) };
int i;
while (arg_parse (&pargs, opts))
{
switch (pargs.r_opt)
{
case ARGPARSE_IS_ARG :
printf ("arg='%s'\n", pargs.r.ret_str);
break;
case 'v': opt.verbose++; break;
case 'e': opt.echo++; break;
case 'd': opt.debug++; break;
case 'o': opt.outfile = pargs.r.ret_str; break;
case 'c': opt.crf = pargs.r_type? pargs.r.ret_str:"a.crf"; break;
case 'm': opt.myopt = pargs.r_type? pargs.r.ret_int : 1; break;
case 500: opt.a_long_one++; break;
default : pargs.err = ARGPARSE_PRINT_WARNING; break;
}
}
for (i=0; i < argc; i++ )
printf ("%3d -> (%s)\n", i, argv[i] );
puts ("Options:");
if (opt.verbose)
printf (" verbose=%d\n", opt.verbose );
if (opt.debug)
printf (" debug=%d\n", opt.debug );
if (opt.outfile)
printf (" outfile='%s'\n", opt.outfile );
if (opt.crf)
printf (" crffile='%s'\n", opt.crf );
if (opt.myopt)
printf (" myopt=%d\n", opt.myopt );
if (opt.a_long_one)
printf (" a-long-one=%d\n", opt.a_long_one );
if (opt.echo)
printf (" echo=%d\n", opt.echo );
return 0;
}
#endif /*TEST*/
/**** bottom of file ****/
diff --git a/common/convert.c b/common/convert.c
index 6d03adc3d..40fb4eecf 100644
--- a/common/convert.c
+++ b/common/convert.c
@@ -1,266 +1,266 @@
/* convert.c - Hex conversion functions.
* Copyright (C) 2006, 2008 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* This file is free software; you can redistribute it and/or modify
* it under the terms of either
*
* - the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* or
*
* - the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* or both in parallel, as here.
*
* This file 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 .
*/
#include
#include
#include
#include
#include "util.h"
#define tohex(n) ((n) < 10 ? ((n) + '0') : (((n) - 10) + 'A'))
/* Convert STRING consisting of hex characters into its binary
representation and store that at BUFFER. BUFFER needs to be of
LENGTH bytes. The function checks that the STRING will convert
exactly to LENGTH bytes. The string is delimited by either end of
string or a white space character. The function returns -1 on
error or the length of the parsed string. */
int
hex2bin (const char *string, void *buffer, size_t length)
{
int i;
const char *s = string;
for (i=0; i < length; )
{
if (!hexdigitp (s) || !hexdigitp (s+1))
return -1; /* Invalid hex digits. */
((unsigned char*)buffer)[i++] = xtoi_2 (s);
s += 2;
}
if (*s && (!isascii (*s) || !isspace (*s)) )
return -1; /* Not followed by Nul or white space. */
if (i != length)
return -1; /* Not of expected length. */
if (*s)
s++; /* Skip the delimiter. */
return s - string;
}
/* Convert STRING consisting of hex characters into its binary representation
and store that at BUFFER. BUFFER needs to be of LENGTH bytes. The
function check that the STRING will convert exactly to LENGTH
bytes. Colons between the hex digits are allowed, if one colon
has been given a colon is expected very 2 characters. The string
is delimited by either end of string or a white space character.
The function returns -1 on error or the length of the parsed
string. */
int
hexcolon2bin (const char *string, void *buffer, size_t length)
{
int i;
const char *s = string;
int need_colon = 0;
for (i=0; i < length; )
{
if (i==1 && *s == ':') /* Skip colons between hex digits. */
{
need_colon = 1;
s++;
}
else if (need_colon && *s == ':')
s++;
else if (need_colon)
return -1; /* Colon expected. */
if (!hexdigitp (s) || !hexdigitp (s+1))
return -1; /* Invalid hex digits. */
((unsigned char*)buffer)[i++] = xtoi_2 (s);
s += 2;
}
if (*s == ':')
return -1; /* Trailing colons are not allowed. */
if (*s && (!isascii (*s) || !isspace (*s)) )
return -1; /* Not followed by Nul or white space. */
if (i != length)
return -1; /* Not of expected length. */
if (*s)
s++; /* Skip the delimiter. */
return s - string;
}
static char *
do_bin2hex (const void *buffer, size_t length, char *stringbuf, int with_colon)
{
const unsigned char *s;
char *p;
if (!stringbuf)
{
/* Not really correct for with_colon but we don't care about the
one wasted byte. */
size_t n = with_colon? 3:2;
size_t nbytes = n * length + 1;
if (length && (nbytes-1) / n != length)
{
gpg_err_set_errno (ENOMEM);
return NULL;
}
stringbuf = xtrymalloc (nbytes);
if (!stringbuf)
return NULL;
}
for (s = buffer, p = stringbuf; length; length--, s++)
{
if (with_colon && s != buffer)
*p++ = ':';
*p++ = tohex ((*s>>4)&15);
*p++ = tohex (*s&15);
}
*p = 0;
return stringbuf;
}
/* Convert LENGTH bytes of data in BUFFER into hex encoding and store
that at the provided STRINGBUF. STRINGBUF must be allocated of at
least (2*LENGTH+1) bytes or be NULL so that the function mallocs an
appropriate buffer. Returns STRINGBUF or NULL on error (which may
only occur if STRINGBUF has been NULL and the internal malloc
failed). */
char *
bin2hex (const void *buffer, size_t length, char *stringbuf)
{
return do_bin2hex (buffer, length, stringbuf, 0);
}
/* Convert LENGTH bytes of data in BUFFER into hex encoding and store
that at the provided STRINGBUF. STRINGBUF must be allocated of at
least (3*LENGTH+1) bytes or be NULL so that the function mallocs an
appropriate buffer. Returns STRINGBUF or NULL on error (which may
only occur if STRINGBUF has been NULL and the internal malloc
failed). */
char *
bin2hexcolon (const void *buffer, size_t length, char *stringbuf)
{
return do_bin2hex (buffer, length, stringbuf, 1);
}
/* Convert HEXSTRING consisting of hex characters into string and
store that at BUFFER. HEXSTRING is either delimited by end of
string or a white space character. The function makes sure that
the resulting string in BUFFER is terminated by a Nul byte. Note
that the returned string may include embedded Nul bytes; the extra
- Nul byte at the end is used to make sure tha the result can always
+ Nul byte at the end is used to make sure that the result can always
be used as a C-string.
BUFSIZE is the available length of BUFFER; if the converted result
plus a possible required extra Nul character does not fit into this
buffer, the function returns NULL and won't change the existing
content of BUFFER. In-place conversion is possible as long as
BUFFER points to HEXSTRING.
If BUFFER is NULL and BUFSIZE is 0 the function scans HEXSTRING but
does not store anything. This may be used to find the end of
HEXSTRING.
On success the function returns a pointer to the next character
after HEXSTRING (which is either end-of-string or a the next white
space). If BUFLEN is not NULL the number of valid vytes in BUFFER
is stored there (an extra Nul byte is not counted); this will even
be done if BUFFER has been passed as NULL. */
const char *
hex2str (const char *hexstring, char *buffer, size_t bufsize, size_t *buflen)
{
const char *s = hexstring;
int idx, count;
int need_nul = 0;
if (buflen)
*buflen = 0;
for (s=hexstring, count=0; hexdigitp (s) && hexdigitp (s+1); s += 2, count++)
;
if (*s && (!isascii (*s) || !isspace (*s)) )
{
gpg_err_set_errno (EINVAL);
return NULL; /* Not followed by Nul or white space. */
}
/* We need to append a nul character. However we don't want that if
the hexstring already ends with "00". */
need_nul = ((s == hexstring) || !(s[-2] == '0' && s[-1] == '0'));
if (need_nul)
count++;
if (buffer)
{
if (count > bufsize)
{
gpg_err_set_errno (EINVAL);
return NULL; /* Too long. */
}
for (s=hexstring, idx=0; hexdigitp (s) && hexdigitp (s+1); s += 2)
((unsigned char*)buffer)[idx++] = xtoi_2 (s);
if (need_nul)
buffer[idx] = 0;
}
if (buflen)
*buflen = count - need_nul;
return s;
}
/* Same as hex2str but this function allocated a new string. Returns
NULL on error. If R_COUNT is not NULL, the number of scanned bytes
will be stored there. ERRNO is set on error. */
char *
hex2str_alloc (const char *hexstring, size_t *r_count)
{
const char *tail;
size_t nbytes;
char *result;
tail = hex2str (hexstring, NULL, 0, &nbytes);
if (!tail)
{
if (r_count)
*r_count = 0;
return NULL;
}
if (r_count)
*r_count = tail - hexstring;
result = xtrymalloc (nbytes+1);
if (!result)
return NULL;
if (!hex2str (hexstring, result, nbytes+1, NULL))
BUG ();
return result;
}
diff --git a/common/dotlock.c b/common/dotlock.c
index 5227bb64e..1bc31d8a6 100644
--- a/common/dotlock.c
+++ b/common/dotlock.c
@@ -1,1379 +1,1379 @@
/* dotlock.c - dotfile locking
* Copyright (C) 1998, 2000, 2001, 2003, 2004,
* 2005, 2006, 2008, 2010, 2011 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG is free software; you can redistribute and/or modify this
* part of GnuPG under the terms of either
*
* - the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* or
*
* - the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* or both in parallel, as here.
*
* 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 copies of the GNU General Public License
* and the GNU Lesser General Public License along with this program;
* if not, see .
*
* ALTERNATIVELY, this file may be distributed under the terms of the
* following license, in which case the provisions of this license are
* required INSTEAD OF the GNU Lesser General License or the GNU
* General Public License. If you wish to allow use of your version of
* this file only under the terms of the GNU Lesser General License or
* the GNU General Public License, and not to allow others to use your
* version of this file under the terms of the following license,
* indicate your decision by deleting this paragraph and the license
* below.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, and the entire permission notice in its entirety,
* including the disclaimer of warranties.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
Overview:
=========
This module implements advisory file locking in a portable way.
Due to the problems with POSIX fcntl locking a separate lock file
is used. It would be possible to use fcntl locking on this lock
file and thus avoid the weird auto unlock bug of POSIX while still
having an unproved better performance of fcntl locking. However
there are still problems left, thus we resort to use a hardlink
which has the well defined property that a link call will fail if
the target file already exists.
Given that hardlinks are also available on NTFS file systems since
Windows XP; it will be possible to enhance this module to use
hardlinks even on Windows and thus allow Windows and Posix clients
to use locking on the same directory. This is not yet implemented;
instead we use a lockfile on Windows along with W32 style file
locking.
On FAT file systems hardlinks are not supported. Thus this method
does not work. Our solution is to use a O_EXCL locking instead.
Querying the type of the file system is not easy to do in a
portable way (e.g. Linux has a statfs, BSDs have a the same call
but using different structures and constants). What we do instead
is to check at runtime whether link(2) works for a specific lock
file.
How to use:
===========
At program initialization time, the module should be explicitly
initialized:
dotlock_create (NULL, 0);
This installs an atexit handler and may also initialize mutex etc.
It is optional for non-threaded applications. Only the first call
has an effect. This needs to be done before any extra threads are
started.
To create a lock file (which prepares it but does not take the
lock) you do:
dotlock_t h
h = dotlock_create (fname, 0);
if (!h)
error ("error creating lock file: %s\n", strerror (errno));
It is important to handle the error. For example on a read-only
file system a lock can't be created (but is usually not needed).
FNAME is the file you want to lock; the actual lockfile is that
name with the suffix ".lock" appended. On success a handle to be
used with the other functions is returned or NULL on error. Note
that the handle shall only be used by one thread at a time. This
function creates a unique file temporary file (".#lk*") in the same
directory as FNAME and returns a handle for further operations.
The module keeps track of theses unique files so that they will be
unlinked using the atexit handler. If you don't need the lock file
anymore, you may also explicitly remove it with a call to:
dotlock_destroy (h);
To actually lock the file, you use:
if (dotlock_take (h, -1))
error ("error taking lock: %s\n", strerror (errno));
This function will wait until the lock is acquired. If an
unexpected error occurs if will return non-zero and set ERRNO. If
you pass (0) instead of (-1) the function does not wait in case the
file is already locked but returns -1 and sets ERRNO to EACCES.
Any other positive value for the second parameter is considered a
- timeout valuie in milliseconds.
+ timeout value in milliseconds.
To release the lock you call:
if (dotlock_release (h))
error ("error releasing lock: %s\n", strerror (errno));
or, if the lock file is not anymore needed, you may just call
dotlock_destroy. However dotlock_release does some extra checks
before releasing the lock and prints diagnostics to help detecting
bugs.
If you want to explicitly destroy all lock files you may call
dotlock_remove_lockfiles ();
which is the core of the installed atexit handler. In case your
application wants to disable locking completely it may call
disable_locking ()
before any locks are created.
There are two convenience functions to store an integer (e.g. a
file descriptor) value with the handle:
void dotlock_set_fd (dotlock_t h, int fd);
int dotlock_get_fd (dotlock_t h);
If nothing has been stored dotlock_get_fd returns -1.
How to build:
=============
This module was originally developed for GnuPG but later changed to
allow its use without any GnuPG dependency. If you want to use it
with you application you may simply use it and it should figure out
most things automagically.
You may use the common config.h file to pass macros, but take care
to pass -DHAVE_CONFIG_H to the compiler. Macros used by this
module are:
DOTLOCK_USE_PTHREAD - Define if POSIX threads are in use.
DOTLOCK_GLIB_LOGGING - Define this to use Glib logging functions.
DOTLOCK_EXT_SYM_PREFIX - Prefix all external symbols with the
string to which this macro evaluates.
GNUPG_MAJOR_VERSION - Defined when used by GnuPG.
HAVE_DOSISH_SYSTEM - Defined for Windows etc. Will be
automatically defined if a the target is
Windows.
HAVE_POSIX_SYSTEM - Internally defined to !HAVE_DOSISH_SYSTEM.
HAVE_SIGNAL_H - Should be defined on Posix systems. If config.h
is not used defaults to defined.
DIRSEP_C - Separation character for file name parts.
Usually not redefined.
EXTSEP_S - Separation string for file name suffixes.
Usually not redefined.
HAVE_W32CE_SYSTEM - Currently only used by GnuPG.
Note that there is a test program t-dotlock which has compile
instructions at its end. At least for SMBFS and CIFS it is
important that 64 bit versions of stat are used; most programming
environments do this these days, just in case you want to compile
it on the command line, remember to pass -D_FILE_OFFSET_BITS=64
Bugs:
=====
On Windows this module is not yet thread-safe.
Miscellaneous notes:
====================
On hardlinks:
- Hardlinks are supported under Windows with NTFS since XP/Server2003.
- In Linux 2.6.33 both SMBFS and CIFS seem to support hardlinks.
- NFS supports hard links. But there are solvable problems.
- FAT does not support links
On the file locking API:
- CIFS on Linux 2.6.33 supports several locking methods.
SMBFS seems not to support locking. No closer checks done.
- NFS supports Posix locks. flock is emulated in the server.
However there are a couple of problems; see below.
- FAT does not support locks.
- An advantage of fcntl locking is that R/W locks can be
implemented which is not easy with a straight lock file.
On O_EXCL:
- Does not work reliable on NFS
- Should work on CIFS and SMBFS but how can we delete lockfiles?
On NFS problems:
- Locks vanish if the server crashes and reboots.
- Client crashes keep the lock in the server until the client
re-connects.
- Communication problems may return unreliable error codes. The
MUA Postfix's workaround is to compare the link count after
seeing an error for link. However that gives a race. If using a
unique file to link to a lockfile and using stat to check the
link count instead of looking at the error return of link(2) is
the best solution.
- O_EXCL seems to have a race and may re-create a file anyway.
*/
#ifdef HAVE_CONFIG_H
# include
#endif
/* Some quick replacements for stuff we usually expect to be defined
in config.h. Define HAVE_POSIX_SYSTEM for better readability. */
#if !defined (HAVE_DOSISH_SYSTEM) && defined(_WIN32)
# define HAVE_DOSISH_SYSTEM 1
#endif
#if !defined (HAVE_DOSISH_SYSTEM) && !defined (HAVE_POSIX_SYSTEM)
# define HAVE_POSIX_SYSTEM 1
#endif
/* With no config.h assume that we have sitgnal.h. */
#if !defined (HAVE_CONFIG_H) && defined (HAVE_POSIX_SYSTEM)
# define HAVE_SIGNAL_H 1
#endif
/* Standard headers. */
#include
#include
#include
#include
#include
#include
#include
#ifdef HAVE_DOSISH_SYSTEM
# define WIN32_LEAN_AND_MEAN /* We only need the OS core stuff. */
# include
#else
# include
# include
# include
#endif
#include
#include
#include
#include
#ifdef HAVE_SIGNAL_H
# include
#endif
#ifdef DOTLOCK_USE_PTHREAD
# include
#endif
#ifdef DOTLOCK_GLIB_LOGGING
# include
#endif
#ifdef GNUPG_MAJOR_VERSION
# include "util.h"
# include "common-defs.h"
# include "stringhelp.h" /* For stpcpy and w32_strerror. */
#endif
#ifdef HAVE_W32CE_SYSTEM
# include "utf8conv.h" /* WindowsCE requires filename conversion. */
#endif
#include "dotlock.h"
/* Define constants for file name construction. */
#if !defined(DIRSEP_C) && !defined(EXTSEP_S)
# ifdef HAVE_DOSISH_SYSTEM
# define DIRSEP_C '\\'
# define EXTSEP_S "."
#else
# define DIRSEP_C '/'
# define EXTSEP_S "."
# endif
#endif
/* In GnuPG we use wrappers around the malloc functions. If they are
not defined we assume that this code is used outside of GnuPG and
fall back to the regular malloc functions. */
#ifndef xtrymalloc
# define xtrymalloc(a) malloc ((a))
# define xtrycalloc(a,b) calloc ((a), (b))
# define xfree(a) free ((a))
#endif
/* Wrapper to set ERRNO (required for W32CE). */
#ifdef GPG_ERROR_VERSION
# define my_set_errno(e) gpg_err_set_errno ((e))
#else
# define my_set_errno(e) do { errno = (e); } while (0)
#endif
/* Gettext macro replacement. */
#ifndef _
# define _(a) (a)
#endif
#ifdef GNUPG_MAJOR_VERSION
# define my_info_0(a) log_info ((a))
# define my_info_1(a,b) log_info ((a), (b))
# define my_info_2(a,b,c) log_info ((a), (b), (c))
# define my_info_3(a,b,c,d) log_info ((a), (b), (c), (d))
# define my_error_0(a) log_error ((a))
# define my_error_1(a,b) log_error ((a), (b))
# define my_error_2(a,b,c) log_error ((a), (b), (c))
# define my_debug_1(a,b) log_debug ((a), (b))
# define my_fatal_0(a) log_fatal ((a))
#elif defined (DOTLOCK_GLIB_LOGGING)
# define my_info_0(a) g_message ((a))
# define my_info_1(a,b) g_message ((a), (b))
# define my_info_2(a,b,c) g_message ((a), (b), (c))
# define my_info_3(a,b,c,d) g_message ((a), (b), (c), (d))
# define my_error_0(a) g_warning ((a))
# define my_error_1(a,b) g_warning ((a), (b))
# define my_error_2(a,b,c) g_warning ((a), (b), (c))
# define my_debug_1(a,b) g_debug ((a), (b))
# define my_fatal_0(a) g_error ((a))
#else
# define my_info_0(a) fprintf (stderr, (a))
# define my_info_1(a,b) fprintf (stderr, (a), (b))
# define my_info_2(a,b,c) fprintf (stderr, (a), (b), (c))
# define my_info_3(a,b,c,d) fprintf (stderr, (a), (b), (c), (d))
# define my_error_0(a) fprintf (stderr, (a))
# define my_error_1(a,b) fprintf (stderr, (a), (b))
# define my_error_2(a,b,c) fprintf (stderr, (a), (b), (c))
# define my_debug_1(a,b) fprintf (stderr, (a), (b))
# define my_fatal_0(a) do { fprintf (stderr,(a)); fflush (stderr); \
abort (); } while (0)
#endif
/* The object describing a lock. */
struct dotlock_handle
{
struct dotlock_handle *next;
char *lockname; /* Name of the actual lockfile. */
unsigned int locked:1; /* Lock status. */
unsigned int disable:1; /* If true, locking is disabled. */
unsigned int use_o_excl:1; /* Use open (O_EXCL) for locking. */
int extra_fd; /* A place for the caller to store an FD. */
#ifdef HAVE_DOSISH_SYSTEM
HANDLE lockhd; /* The W32 handle of the lock file. */
#else /*!HAVE_DOSISH_SYSTEM */
char *tname; /* Name of the lockfile template. */
size_t nodename_off; /* Offset in TNAME of the nodename part. */
size_t nodename_len; /* Length of the nodename part. */
#endif /*!HAVE_DOSISH_SYSTEM */
};
/* A list of all lock handles. The volatile attribute might help
if used in an atexit handler. Note that [UN]LOCK_all_lockfiles
must not change ERRNO. */
static volatile dotlock_t all_lockfiles;
#ifdef DOTLOCK_USE_PTHREAD
static pthread_mutex_t all_lockfiles_mutex = PTHREAD_MUTEX_INITIALIZER;
# define LOCK_all_lockfiles() do { \
if (pthread_mutex_lock (&all_lockfiles_mutex)) \
my_fatal_0 ("locking all_lockfiles_mutex failed\n"); \
} while (0)
# define UNLOCK_all_lockfiles() do { \
if (pthread_mutex_unlock (&all_lockfiles_mutex)) \
my_fatal_0 ("unlocking all_lockfiles_mutex failed\n"); \
} while (0)
#else /*!DOTLOCK_USE_PTHREAD*/
# define LOCK_all_lockfiles() do { } while (0)
# define UNLOCK_all_lockfiles() do { } while (0)
#endif /*!DOTLOCK_USE_PTHREAD*/
/* If this has the value true all locking is disabled. */
static int never_lock;
#ifdef HAVE_DOSISH_SYSTEM
static int
map_w32_to_errno (DWORD w32_err)
{
switch (w32_err)
{
case 0:
return 0;
case ERROR_FILE_NOT_FOUND:
return ENOENT;
case ERROR_PATH_NOT_FOUND:
return ENOENT;
case ERROR_ACCESS_DENIED:
return EPERM;
case ERROR_INVALID_HANDLE:
case ERROR_INVALID_BLOCK:
return EINVAL;
case ERROR_NOT_ENOUGH_MEMORY:
return ENOMEM;
case ERROR_NO_DATA:
case ERROR_BROKEN_PIPE:
return EPIPE;
default:
return EIO;
}
}
#endif /*HAVE_DOSISH_SYSTEM*/
/* Entirely disable all locking. This function should be called
before any locking is done. It may be called right at startup of
the process as it only sets a global value. */
void
dotlock_disable (void)
{
never_lock = 1;
}
#ifdef HAVE_POSIX_SYSTEM
static int
maybe_deadlock (dotlock_t h)
{
dotlock_t r;
int res = 0;
LOCK_all_lockfiles ();
for (r=all_lockfiles; r; r = r->next)
{
if ( r != h && r->locked )
{
res = 1;
break;
}
}
UNLOCK_all_lockfiles ();
return res;
}
#endif /*HAVE_POSIX_SYSTEM*/
/* Read the lock file and return the pid, returns -1 on error. True
will be stored in the integer at address SAME_NODE if the lock file
has been created on the same node. */
#ifdef HAVE_POSIX_SYSTEM
static int
read_lockfile (dotlock_t h, int *same_node )
{
char buffer_space[10+1+70+1]; /* 70 is just an estimated value; node
names are usually shorter. */
int fd;
int pid = -1;
char *buffer, *p;
size_t expected_len;
int res, nread;
*same_node = 0;
expected_len = 10 + 1 + h->nodename_len + 1;
if ( expected_len >= sizeof buffer_space)
{
buffer = xtrymalloc (expected_len);
if (!buffer)
return -1;
}
else
buffer = buffer_space;
if ( (fd = open (h->lockname, O_RDONLY)) == -1 )
{
int e = errno;
my_info_2 ("error opening lockfile '%s': %s\n",
h->lockname, strerror(errno) );
if (buffer != buffer_space)
xfree (buffer);
my_set_errno (e); /* Need to return ERRNO here. */
return -1;
}
p = buffer;
nread = 0;
do
{
res = read (fd, p, expected_len - nread);
if (res == -1 && errno == EINTR)
continue;
if (res < 0)
{
int e = errno;
my_info_1 ("error reading lockfile '%s'\n", h->lockname );
close (fd);
if (buffer != buffer_space)
xfree (buffer);
my_set_errno (e);
return -1;
}
p += res;
nread += res;
}
while (res && nread != expected_len);
close(fd);
if (nread < 11)
{
my_info_1 ("invalid size of lockfile '%s'\n", h->lockname);
if (buffer != buffer_space)
xfree (buffer);
my_set_errno (EINVAL);
return -1;
}
if (buffer[10] != '\n'
|| (buffer[10] = 0, pid = atoi (buffer)) == -1
|| !pid )
{
my_error_2 ("invalid pid %d in lockfile '%s'\n", pid, h->lockname);
if (buffer != buffer_space)
xfree (buffer);
my_set_errno (EINVAL);
return -1;
}
if (nread == expected_len
&& !memcmp (h->tname+h->nodename_off, buffer+11, h->nodename_len)
&& buffer[11+h->nodename_len] == '\n')
*same_node = 1;
if (buffer != buffer_space)
xfree (buffer);
return pid;
}
#endif /*HAVE_POSIX_SYSTEM */
/* Check whether the file system which stores TNAME supports
hardlinks. Instead of using the non-portable statsfs call which
differs between various Unix versions, we do a runtime test.
Returns: 0 supports hardlinks; 1 no hardlink support, -1 unknown
(test error). */
#ifdef HAVE_POSIX_SYSTEM
static int
use_hardlinks_p (const char *tname)
{
char *lname;
struct stat sb;
unsigned int nlink;
int res;
if (stat (tname, &sb))
return -1;
nlink = (unsigned int)sb.st_nlink;
lname = xtrymalloc (strlen (tname) + 1 + 1);
if (!lname)
return -1;
strcpy (lname, tname);
strcat (lname, "x");
/* We ignore the return value of link() because it is unreliable. */
(void) link (tname, lname);
if (stat (tname, &sb))
res = -1; /* Ooops. */
else if (sb.st_nlink == nlink + 1)
res = 0; /* Yeah, hardlinks are supported. */
else
res = 1; /* No hardlink support. */
unlink (lname);
xfree (lname);
return res;
}
#endif /*HAVE_POSIX_SYSTEM */
#ifdef HAVE_POSIX_SYSTEM
/* Locking core for Unix. It used a temporary file and the link
system call to make locking an atomic operation. */
static dotlock_t
dotlock_create_unix (dotlock_t h, const char *file_to_lock)
{
int fd = -1;
char pidstr[16];
const char *nodename;
const char *dirpart;
int dirpartlen;
struct utsname utsbuf;
size_t tnamelen;
snprintf (pidstr, sizeof pidstr, "%10d\n", (int)getpid() );
/* Create a temporary file. */
if ( uname ( &utsbuf ) )
nodename = "unknown";
else
nodename = utsbuf.nodename;
if ( !(dirpart = strrchr (file_to_lock, DIRSEP_C)) )
{
dirpart = EXTSEP_S;
dirpartlen = 1;
}
else
{
dirpartlen = dirpart - file_to_lock;
dirpart = file_to_lock;
}
LOCK_all_lockfiles ();
h->next = all_lockfiles;
all_lockfiles = h;
tnamelen = dirpartlen + 6 + 30 + strlen(nodename) + 10 + 1;
h->tname = xtrymalloc (tnamelen + 1);
if (!h->tname)
{
all_lockfiles = h->next;
UNLOCK_all_lockfiles ();
xfree (h);
return NULL;
}
h->nodename_len = strlen (nodename);
snprintf (h->tname, tnamelen, "%.*s/.#lk%p.", dirpartlen, dirpart, h );
h->nodename_off = strlen (h->tname);
snprintf (h->tname+h->nodename_off, tnamelen - h->nodename_off,
"%s.%d", nodename, (int)getpid ());
do
{
my_set_errno (0);
fd = open (h->tname, O_WRONLY|O_CREAT|O_EXCL,
S_IRUSR|S_IRGRP|S_IROTH|S_IWUSR );
}
while (fd == -1 && errno == EINTR);
if ( fd == -1 )
{
int saveerrno = errno;
all_lockfiles = h->next;
UNLOCK_all_lockfiles ();
my_error_2 (_("failed to create temporary file '%s': %s\n"),
h->tname, strerror (errno));
xfree (h->tname);
xfree (h);
my_set_errno (saveerrno);
return NULL;
}
if ( write (fd, pidstr, 11 ) != 11 )
goto write_failed;
if ( write (fd, nodename, strlen (nodename) ) != strlen (nodename) )
goto write_failed;
if ( write (fd, "\n", 1 ) != 1 )
goto write_failed;
if ( close (fd) )
{
if ( errno == EINTR )
fd = -1;
goto write_failed;
}
fd = -1;
/* Check whether we support hard links. */
switch (use_hardlinks_p (h->tname))
{
case 0: /* Yes. */
break;
case 1: /* No. */
unlink (h->tname);
h->use_o_excl = 1;
break;
default:
{
int saveerrno = errno;
my_error_2 ("can't check whether hardlinks are supported for '%s': %s\n"
, h->tname, strerror (saveerrno));
my_set_errno (saveerrno);
}
goto write_failed;
}
h->lockname = xtrymalloc (strlen (file_to_lock) + 6 );
if (!h->lockname)
{
int saveerrno = errno;
all_lockfiles = h->next;
UNLOCK_all_lockfiles ();
unlink (h->tname);
xfree (h->tname);
xfree (h);
my_set_errno (saveerrno);
return NULL;
}
strcpy (stpcpy (h->lockname, file_to_lock), EXTSEP_S "lock");
UNLOCK_all_lockfiles ();
if (h->use_o_excl)
my_debug_1 ("locking for '%s' done via O_EXCL\n", h->lockname);
return h;
write_failed:
{
int saveerrno = errno;
all_lockfiles = h->next;
UNLOCK_all_lockfiles ();
my_error_2 (_("error writing to '%s': %s\n"), h->tname, strerror (errno));
if ( fd != -1 )
close (fd);
unlink (h->tname);
xfree (h->tname);
xfree (h);
my_set_errno (saveerrno);
}
return NULL;
}
#endif /*HAVE_POSIX_SYSTEM*/
#ifdef HAVE_DOSISH_SYSTEM
/* Locking core for Windows. This version does not need a temporary
file but uses the plain lock file along with record locking. We
create this file here so that we later only need to do the file
locking. For error reporting it is useful to keep the name of the
file in the handle. */
static dotlock_t
dotlock_create_w32 (dotlock_t h, const char *file_to_lock)
{
LOCK_all_lockfiles ();
h->next = all_lockfiles;
all_lockfiles = h;
h->lockname = xtrymalloc ( strlen (file_to_lock) + 6 );
if (!h->lockname)
{
all_lockfiles = h->next;
UNLOCK_all_lockfiles ();
xfree (h);
return NULL;
}
strcpy (stpcpy(h->lockname, file_to_lock), EXTSEP_S "lock");
/* If would be nice if we would use the FILE_FLAG_DELETE_ON_CLOSE
along with FILE_SHARE_DELETE but that does not work due to a race
condition: Despite the OPEN_ALWAYS flag CreateFile may return an
error and we can't reliable create/open the lock file unless we
would wait here until it works - however there are other valid
reasons why a lock file can't be created and thus the process
would not stop as expected but spin until Windows crashes. Our
solution is to keep the lock file open; that does not harm. */
{
#ifdef HAVE_W32CE_SYSTEM
wchar_t *wname = utf8_to_wchar (h->lockname);
if (wname)
h->lockhd = CreateFile (wname,
GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL, OPEN_ALWAYS, 0, NULL);
else
h->lockhd = INVALID_HANDLE_VALUE;
xfree (wname);
#else
h->lockhd = CreateFile (h->lockname,
GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL, OPEN_ALWAYS, 0, NULL);
#endif
}
if (h->lockhd == INVALID_HANDLE_VALUE)
{
int saveerrno = map_w32_to_errno (GetLastError ());
all_lockfiles = h->next;
UNLOCK_all_lockfiles ();
my_error_2 (_("can't create '%s': %s\n"), h->lockname, w32_strerror (-1));
xfree (h->lockname);
xfree (h);
my_set_errno (saveerrno);
return NULL;
}
return h;
}
#endif /*HAVE_DOSISH_SYSTEM*/
/* Create a lockfile for a file name FILE_TO_LOCK and returns an
object of type dotlock_t which may be used later to actually acquire
the lock. A cleanup routine gets installed to cleanup left over
locks or other files used internally by the lock mechanism.
Calling this function with NULL does only install the atexit
handler and may thus be used to assure that the cleanup is called
after all other atexit handlers.
This function creates a lock file in the same directory as
FILE_TO_LOCK using that name and a suffix of ".lock". Note that on
POSIX systems a temporary file ".#lk..pid[.threadid] is
used.
FLAGS must be 0.
The function returns an new handle which needs to be released using
destroy_dotlock but gets also released at the termination of the
process. On error NULL is returned.
*/
dotlock_t
dotlock_create (const char *file_to_lock, unsigned int flags)
{
static int initialized;
dotlock_t h;
if ( !initialized )
{
atexit (dotlock_remove_lockfiles);
initialized = 1;
}
if ( !file_to_lock )
return NULL; /* Only initialization was requested. */
if (flags)
{
my_set_errno (EINVAL);
return NULL;
}
h = xtrycalloc (1, sizeof *h);
if (!h)
return NULL;
h->extra_fd = -1;
if (never_lock)
{
h->disable = 1;
LOCK_all_lockfiles ();
h->next = all_lockfiles;
all_lockfiles = h;
UNLOCK_all_lockfiles ();
return h;
}
#ifdef HAVE_DOSISH_SYSTEM
return dotlock_create_w32 (h, file_to_lock);
#else /*!HAVE_DOSISH_SYSTEM */
return dotlock_create_unix (h, file_to_lock);
#endif /*!HAVE_DOSISH_SYSTEM*/
}
/* Convenience function to store a file descriptor (or any other
integer value) in the context of handle H. */
void
dotlock_set_fd (dotlock_t h, int fd)
{
h->extra_fd = fd;
}
/* Convenience function to retrieve a file descriptor (or any other
integer value) stored in the context of handle H. */
int
dotlock_get_fd (dotlock_t h)
{
return h->extra_fd;
}
#ifdef HAVE_POSIX_SYSTEM
/* Unix specific code of destroy_dotlock. */
static void
dotlock_destroy_unix (dotlock_t h)
{
if (h->locked && h->lockname)
unlink (h->lockname);
if (h->tname && !h->use_o_excl)
unlink (h->tname);
xfree (h->tname);
}
#endif /*HAVE_POSIX_SYSTEM*/
#ifdef HAVE_DOSISH_SYSTEM
/* Windows specific code of destroy_dotlock. */
static void
dotlock_destroy_w32 (dotlock_t h)
{
if (h->locked)
{
OVERLAPPED ovl;
memset (&ovl, 0, sizeof ovl);
UnlockFileEx (h->lockhd, 0, 1, 0, &ovl);
}
CloseHandle (h->lockhd);
}
#endif /*HAVE_DOSISH_SYSTEM*/
/* Destroy the lock handle H and release the lock. */
void
dotlock_destroy (dotlock_t h)
{
dotlock_t hprev, htmp;
if ( !h )
return;
/* First remove the handle from our global list of all locks. */
LOCK_all_lockfiles ();
for (hprev=NULL, htmp=all_lockfiles; htmp; hprev=htmp, htmp=htmp->next)
if (htmp == h)
{
if (hprev)
hprev->next = htmp->next;
else
all_lockfiles = htmp->next;
h->next = NULL;
break;
}
UNLOCK_all_lockfiles ();
/* Then destroy the lock. */
if (!h->disable)
{
#ifdef HAVE_DOSISH_SYSTEM
dotlock_destroy_w32 (h);
#else /* !HAVE_DOSISH_SYSTEM */
dotlock_destroy_unix (h);
#endif /* HAVE_DOSISH_SYSTEM */
xfree (h->lockname);
}
xfree(h);
}
#ifdef HAVE_POSIX_SYSTEM
/* Unix specific code of make_dotlock. Returns 0 on success and -1 on
error. */
static int
dotlock_take_unix (dotlock_t h, long timeout)
{
int wtime = 0;
int sumtime = 0;
int pid;
int lastpid = -1;
int ownerchanged;
const char *maybe_dead="";
int same_node;
int saveerrno;
again:
if (h->use_o_excl)
{
/* No hardlink support - use open(O_EXCL). */
int fd;
do
{
my_set_errno (0);
fd = open (h->lockname, O_WRONLY|O_CREAT|O_EXCL,
S_IRUSR|S_IRGRP|S_IROTH|S_IWUSR );
}
while (fd == -1 && errno == EINTR);
if (fd == -1 && errno == EEXIST)
; /* Lock held by another process. */
else if (fd == -1)
{
saveerrno = errno;
my_error_2 ("lock not made: open(O_EXCL) of '%s' failed: %s\n",
h->lockname, strerror (saveerrno));
my_set_errno (saveerrno);
return -1;
}
else
{
char pidstr[16];
snprintf (pidstr, sizeof pidstr, "%10d\n", (int)getpid());
if (write (fd, pidstr, 11 ) == 11
&& write (fd, h->tname + h->nodename_off,h->nodename_len)
== h->nodename_len
&& write (fd, "\n", 1) == 1
&& !close (fd))
{
h->locked = 1;
return 0;
}
/* Write error. */
saveerrno = errno;
my_error_2 ("lock not made: writing to '%s' failed: %s\n",
h->lockname, strerror (errno));
close (fd);
unlink (h->lockname);
my_set_errno (saveerrno);
return -1;
}
}
else /* Standard method: Use hardlinks. */
{
struct stat sb;
/* We ignore the return value of link() because it is unreliable. */
(void) link (h->tname, h->lockname);
if (stat (h->tname, &sb))
{
saveerrno = errno;
my_error_1 ("lock not made: Oops: stat of tmp file failed: %s\n",
strerror (errno));
/* In theory this might be a severe error: It is possible
that link succeeded but stat failed due to changed
permissions. We can't do anything about it, though. */
my_set_errno (saveerrno);
return -1;
}
if (sb.st_nlink == 2)
{
h->locked = 1;
return 0; /* Okay. */
}
}
/* Check for stale lock files. */
if ( (pid = read_lockfile (h, &same_node)) == -1 )
{
if ( errno != ENOENT )
{
saveerrno = errno;
my_info_0 ("cannot read lockfile\n");
my_set_errno (saveerrno);
return -1;
}
my_info_0 ("lockfile disappeared\n");
goto again;
}
else if ( pid == getpid() && same_node )
{
my_info_0 ("Oops: lock already held by us\n");
h->locked = 1;
return 0; /* okay */
}
else if ( same_node && kill (pid, 0) && errno == ESRCH )
{
/* Note: It is unlikley that we get a race here unless a pid is
reused too fast or a new process with the same pid as the one
of the stale file tries to lock right at the same time as we. */
my_info_1 (_("removing stale lockfile (created by %d)\n"), pid);
unlink (h->lockname);
goto again;
}
if (lastpid == -1)
lastpid = pid;
ownerchanged = (pid != lastpid);
if (timeout)
{
struct timeval tv;
/* Wait until lock has been released. We use increasing retry
intervals of 50ms, 100ms, 200ms, 400ms, 800ms, 2s, 4s and 8s
but reset it if the lock owner meanwhile changed. */
if (!wtime || ownerchanged)
wtime = 50;
else if (wtime < 800)
wtime *= 2;
else if (wtime == 800)
wtime = 2000;
else if (wtime < 8000)
wtime *= 2;
if (timeout > 0)
{
if (wtime > timeout)
wtime = timeout;
timeout -= wtime;
}
sumtime += wtime;
if (sumtime >= 1500)
{
sumtime = 0;
my_info_3 (_("waiting for lock (held by %d%s) %s...\n"),
pid, maybe_dead, maybe_deadlock(h)? _("(deadlock?) "):"");
}
tv.tv_sec = wtime / 1000;
tv.tv_usec = (wtime % 1000) * 1000;
select (0, NULL, NULL, NULL, &tv);
goto again;
}
my_set_errno (EACCES);
return -1;
}
#endif /*HAVE_POSIX_SYSTEM*/
#ifdef HAVE_DOSISH_SYSTEM
/* Windows specific code of make_dotlock. Returns 0 on success and -1 on
error. */
static int
dotlock_take_w32 (dotlock_t h, long timeout)
{
int wtime = 0;
int w32err;
OVERLAPPED ovl;
again:
/* Lock one byte at offset 0. The offset is given by OVL. */
memset (&ovl, 0, sizeof ovl);
if (LockFileEx (h->lockhd, (LOCKFILE_EXCLUSIVE_LOCK
| LOCKFILE_FAIL_IMMEDIATELY), 0, 1, 0, &ovl))
{
h->locked = 1;
return 0; /* okay */
}
w32err = GetLastError ();
if (w32err != ERROR_LOCK_VIOLATION)
{
my_error_2 (_("lock '%s' not made: %s\n"),
h->lockname, w32_strerror (w32err));
my_set_errno (map_w32_to_errno (w32err));
return -1;
}
if (timeout)
{
/* Wait until lock has been released. We use retry intervals of
50ms, 100ms, 200ms, 400ms, 800ms, 2s, 4s and 8s. */
if (!wtime)
wtime = 50;
else if (wtime < 800)
wtime *= 2;
else if (wtime == 800)
wtime = 2000;
else if (wtime < 8000)
wtime *= 2;
if (timeout > 0)
{
if (wtime > timeout)
wtime = timeout;
timeout -= wtime;
}
if (wtime >= 800)
my_info_1 (_("waiting for lock %s...\n"), h->lockname);
Sleep (wtime);
goto again;
}
my_set_errno (EACCES);
return -1;
}
#endif /*HAVE_DOSISH_SYSTEM*/
/* Take a lock on H. A value of 0 for TIMEOUT returns immediately if
the lock can't be taked, -1 waits forever (hopefully not), other
values wait for TIMEOUT milliseconds. Returns: 0 on success */
int
dotlock_take (dotlock_t h, long timeout)
{
int ret;
if ( h->disable )
return 0; /* Locks are completely disabled. Return success. */
if ( h->locked )
{
my_debug_1 ("Oops, '%s' is already locked\n", h->lockname);
return 0;
}
#ifdef HAVE_DOSISH_SYSTEM
ret = dotlock_take_w32 (h, timeout);
#else /*!HAVE_DOSISH_SYSTEM*/
ret = dotlock_take_unix (h, timeout);
#endif /*!HAVE_DOSISH_SYSTEM*/
return ret;
}
#ifdef HAVE_POSIX_SYSTEM
/* Unix specific code of release_dotlock. */
static int
dotlock_release_unix (dotlock_t h)
{
int pid, same_node;
int saveerrno;
pid = read_lockfile (h, &same_node);
if ( pid == -1 )
{
saveerrno = errno;
my_error_0 ("release_dotlock: lockfile error\n");
my_set_errno (saveerrno);
return -1;
}
if ( pid != getpid() || !same_node )
{
my_error_1 ("release_dotlock: not our lock (pid=%d)\n", pid);
my_set_errno (EACCES);
return -1;
}
if ( unlink( h->lockname ) )
{
saveerrno = errno;
my_error_1 ("release_dotlock: error removing lockfile '%s'\n",
h->lockname);
my_set_errno (saveerrno);
return -1;
}
/* Fixme: As an extra check we could check whether the link count is
now really at 1. */
return 0;
}
#endif /*HAVE_POSIX_SYSTEM */
#ifdef HAVE_DOSISH_SYSTEM
/* Windows specific code of release_dotlock. */
static int
dotlock_release_w32 (dotlock_t h)
{
OVERLAPPED ovl;
memset (&ovl, 0, sizeof ovl);
if (!UnlockFileEx (h->lockhd, 0, 1, 0, &ovl))
{
int saveerrno = map_w32_to_errno (GetLastError ());
my_error_2 ("release_dotlock: error removing lockfile '%s': %s\n",
h->lockname, w32_strerror (-1));
my_set_errno (saveerrno);
return -1;
}
return 0;
}
#endif /*HAVE_DOSISH_SYSTEM */
/* Release a lock. Returns 0 on success. */
int
dotlock_release (dotlock_t h)
{
int ret;
/* To avoid atexit race conditions we first check whether there are
any locks left. It might happen that another atexit handler
tries to release the lock while the atexit handler of this module
already ran and thus H is undefined. */
LOCK_all_lockfiles ();
ret = !all_lockfiles;
UNLOCK_all_lockfiles ();
if (ret)
return 0;
if ( h->disable )
return 0;
if ( !h->locked )
{
my_debug_1 ("Oops, '%s' is not locked\n", h->lockname);
return 0;
}
#ifdef HAVE_DOSISH_SYSTEM
ret = dotlock_release_w32 (h);
#else
ret = dotlock_release_unix (h);
#endif
if (!ret)
h->locked = 0;
return ret;
}
/* Remove all lockfiles. This is called by the atexit handler
installed by this module but may also be called by other
termination handlers. */
void
dotlock_remove_lockfiles (void)
{
dotlock_t h, h2;
/* First set the lockfiles list to NULL so that for example
dotlock_release is aware that this function is currently
running. */
LOCK_all_lockfiles ();
h = all_lockfiles;
all_lockfiles = NULL;
UNLOCK_all_lockfiles ();
while ( h )
{
h2 = h->next;
dotlock_destroy (h);
h = h2;
}
}
diff --git a/common/iobuf.c b/common/iobuf.c
index 8f52f7f5c..18a458e0a 100644
--- a/common/iobuf.c
+++ b/common/iobuf.c
@@ -1,2744 +1,2744 @@
/* iobuf.c - File Handling for OpenPGP.
* Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2006, 2007, 2008,
* 2009, 2010, 2011 Free Software Foundation, Inc.
* Copyright (C) 2015 g10 Code GmbH
*
* This file is part of GnuPG.
*
* This file is free software; you can redistribute it and/or modify
* it under the terms of either
*
* - the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* or
*
* - the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* or both in parallel, as here.
*
* This file 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 .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#ifdef HAVE_W32_SYSTEM
# ifdef HAVE_WINSOCK2_H
# include
# endif
# include
#endif
#ifdef __riscos__
# include
# include
#endif /* __riscos__ */
#include
#include "util.h"
#include "sysutils.h"
#include "iobuf.h"
/*-- Begin configurable part. --*/
/* The standard size of the internal buffers. */
#define DEFAULT_IOBUF_BUFFER_SIZE (64*1024)
/* To avoid a potential DoS with compression packets we better limit
the number of filters in a chain. */
#define MAX_NESTING_FILTER 64
/*-- End configurable part. --*/
-/* The size of the iobuffers. This can be chnages using the
- * iobuf_set_buffer_size fucntion. */
+/* The size of the iobuffers. This can be changed using the
+ * iobuf_set_buffer_size function. */
static unsigned int iobuf_buffer_size = DEFAULT_IOBUF_BUFFER_SIZE;
#ifdef HAVE_W32_SYSTEM
# ifdef HAVE_W32CE_SYSTEM
# define FD_FOR_STDIN (es_fileno (es_stdin))
# define FD_FOR_STDOUT (es_fileno (es_stdout))
# else
# define FD_FOR_STDIN (GetStdHandle (STD_INPUT_HANDLE))
# define FD_FOR_STDOUT (GetStdHandle (STD_OUTPUT_HANDLE))
# endif
#else /*!HAVE_W32_SYSTEM*/
# define FD_FOR_STDIN (0)
# define FD_FOR_STDOUT (1)
#endif /*!HAVE_W32_SYSTEM*/
/* The context used by the file filter. */
typedef struct
{
gnupg_fd_t fp; /* Open file pointer or handle. */
int keep_open;
int no_cache;
int eof_seen;
int delayed_rc;
int print_only_name; /* Flags indicating that fname is not a real file. */
char fname[1]; /* Name of the file. */
} file_filter_ctx_t;
/* The context used by the estream filter. */
typedef struct
{
estream_t fp; /* Open estream handle. */
int keep_open;
int no_cache;
int eof_seen;
int print_only_name; /* Flags indicating that fname is not a real file. */
char fname[1]; /* Name of the file. */
} file_es_filter_ctx_t;
/* Object to control the "close cache". */
struct close_cache_s
{
struct close_cache_s *next;
gnupg_fd_t fp;
char fname[1];
};
typedef struct close_cache_s *close_cache_t;
static close_cache_t close_cache;
#ifdef HAVE_W32_SYSTEM
typedef struct
{
int sock;
int keep_open;
int no_cache;
int eof_seen;
int print_only_name; /* Flag indicating that fname is not a real file. */
char fname[1]; /* Name of the file */
} sock_filter_ctx_t;
#endif /*HAVE_W32_SYSTEM*/
/* The first partial length header block must be of size 512 to make
* it easier (and more efficient) we use a min. block size of 512 for
* all chunks (but the last one) */
#define OP_MIN_PARTIAL_CHUNK 512
#define OP_MIN_PARTIAL_CHUNK_2POW 9
/* The context we use for the block filter (used to handle OpenPGP
length information header). */
typedef struct
{
int use;
size_t size;
size_t count;
int partial; /* 1 = partial header, 2 in last partial packet. */
char *buffer; /* Used for partial header. */
size_t buflen; /* Used size of buffer. */
int first_c; /* First character of a partial header (which is > 0). */
int eof;
}
block_filter_ctx_t;
/* Local prototypes. */
static int underflow (iobuf_t a, int clear_pending_eof);
static int underflow_target (iobuf_t a, int clear_pending_eof, size_t target);
static int translate_file_handle (int fd, int for_write);
/* Sends any pending data to the filter's FILTER function. Note: this
works on the filter and not on the whole pipeline. That is,
iobuf_flush doesn't necessarily cause data to be written to any
underlying file; it just causes any data buffered at the filter A
to be sent to A's filter function.
If A is a IOBUF_OUTPUT_TEMP filter, then this also enlarges the
buffer by iobuf_buffer_size.
May only be called on an IOBUF_OUTPUT or IOBUF_OUTPUT_TEMP filters. */
static int filter_flush (iobuf_t a);
/* This is a replacement for strcmp. Under W32 it does not
distinguish between backslash and slash. */
static int
fd_cache_strcmp (const char *a, const char *b)
{
#ifdef HAVE_DOSISH_SYSTEM
for (; *a && *b; a++, b++)
{
if (*a != *b && !((*a == '/' && *b == '\\')
|| (*a == '\\' && *b == '/')) )
break;
}
return *(const unsigned char *)a - *(const unsigned char *)b;
#else
return strcmp (a, b);
#endif
}
/*
* Invalidate (i.e. close) a cached iobuf
*/
static int
fd_cache_invalidate (const char *fname)
{
close_cache_t cc;
int rc = 0;
assert (fname);
if (DBG_IOBUF)
log_debug ("fd_cache_invalidate (%s)\n", fname);
for (cc = close_cache; cc; cc = cc->next)
{
if (cc->fp != GNUPG_INVALID_FD && !fd_cache_strcmp (cc->fname, fname))
{
if (DBG_IOBUF)
log_debug (" did (%s)\n", cc->fname);
#ifdef HAVE_W32_SYSTEM
if (!CloseHandle (cc->fp))
rc = -1;
#else
rc = close (cc->fp);
#endif
cc->fp = GNUPG_INVALID_FD;
}
}
return rc;
}
/* Try to sync changes to the disk. This is to avoid data loss during
a system crash in write/close/rename cycle on some file
systems. */
static int
fd_cache_synchronize (const char *fname)
{
int err = 0;
#ifdef HAVE_FSYNC
close_cache_t cc;
if (DBG_IOBUF)
log_debug ("fd_cache_synchronize (%s)\n", fname);
for (cc=close_cache; cc; cc = cc->next )
{
if (cc->fp != GNUPG_INVALID_FD && !fd_cache_strcmp (cc->fname, fname))
{
if (DBG_IOBUF)
log_debug (" did (%s)\n", cc->fname);
err = fsync (cc->fp);
}
}
#else
(void)fname;
#endif /*HAVE_FSYNC*/
return err;
}
static gnupg_fd_t
direct_open (const char *fname, const char *mode, int mode700)
{
#ifdef HAVE_W32_SYSTEM
unsigned long da, cd, sm;
HANDLE hfile;
(void)mode700;
/* Note, that we do not handle all mode combinations */
/* According to the ReactOS source it seems that open() of the
* standard MSW32 crt does open the file in shared mode which is
* something new for MS applications ;-)
*/
if (strchr (mode, '+'))
{
if (fd_cache_invalidate (fname))
return GNUPG_INVALID_FD;
da = GENERIC_READ | GENERIC_WRITE;
cd = OPEN_EXISTING;
sm = FILE_SHARE_READ | FILE_SHARE_WRITE;
}
else if (strchr (mode, 'w'))
{
if (fd_cache_invalidate (fname))
return GNUPG_INVALID_FD;
da = GENERIC_WRITE;
cd = CREATE_ALWAYS;
sm = FILE_SHARE_WRITE;
}
else
{
da = GENERIC_READ;
cd = OPEN_EXISTING;
sm = FILE_SHARE_READ;
}
#ifdef HAVE_W32CE_SYSTEM
{
wchar_t *wfname = utf8_to_wchar (fname);
if (wfname)
{
hfile = CreateFile (wfname, da, sm, NULL, cd,
FILE_ATTRIBUTE_NORMAL, NULL);
xfree (wfname);
}
else
hfile = INVALID_HANDLE_VALUE;
}
#else
hfile = CreateFile (fname, da, sm, NULL, cd, FILE_ATTRIBUTE_NORMAL, NULL);
#endif
return hfile;
#else /*!HAVE_W32_SYSTEM*/
int oflag;
int cflag = S_IRUSR | S_IWUSR;
if (!mode700)
cflag |= S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
/* Note, that we do not handle all mode combinations */
if (strchr (mode, '+'))
{
if (fd_cache_invalidate (fname))
return GNUPG_INVALID_FD;
oflag = O_RDWR;
}
else if (strchr (mode, 'w'))
{
if (fd_cache_invalidate (fname))
return GNUPG_INVALID_FD;
oflag = O_WRONLY | O_CREAT | O_TRUNC;
}
else
{
oflag = O_RDONLY;
}
#ifdef O_BINARY
if (strchr (mode, 'b'))
oflag |= O_BINARY;
#endif
#ifdef __riscos__
{
struct stat buf;
/* Don't allow iobufs on directories */
if (!stat (fname, &buf) && S_ISDIR (buf.st_mode) && !S_ISREG (buf.st_mode))
return __set_errno (EISDIR);
}
#endif
return open (fname, oflag, cflag);
#endif /*!HAVE_W32_SYSTEM*/
}
/*
* Instead of closing an FD we keep it open and cache it for later reuse
* Note that this caching strategy only works if the process does not chdir.
*/
static void
fd_cache_close (const char *fname, gnupg_fd_t fp)
{
close_cache_t cc;
assert (fp);
if (!fname || !*fname)
{
#ifdef HAVE_W32_SYSTEM
CloseHandle (fp);
#else
close (fp);
#endif
if (DBG_IOBUF)
log_debug ("fd_cache_close (%d) real\n", (int)fp);
return;
}
/* try to reuse a slot */
for (cc = close_cache; cc; cc = cc->next)
{
if (cc->fp == GNUPG_INVALID_FD && !fd_cache_strcmp (cc->fname, fname))
{
cc->fp = fp;
if (DBG_IOBUF)
log_debug ("fd_cache_close (%s) used existing slot\n", fname);
return;
}
}
/* add a new one */
if (DBG_IOBUF)
log_debug ("fd_cache_close (%s) new slot created\n", fname);
cc = xcalloc (1, sizeof *cc + strlen (fname));
strcpy (cc->fname, fname);
cc->fp = fp;
cc->next = close_cache;
close_cache = cc;
}
/*
* Do a direct_open on FNAME but first try to reuse one from the fd_cache
*/
static gnupg_fd_t
fd_cache_open (const char *fname, const char *mode)
{
close_cache_t cc;
assert (fname);
for (cc = close_cache; cc; cc = cc->next)
{
if (cc->fp != GNUPG_INVALID_FD && !fd_cache_strcmp (cc->fname, fname))
{
gnupg_fd_t fp = cc->fp;
cc->fp = GNUPG_INVALID_FD;
if (DBG_IOBUF)
log_debug ("fd_cache_open (%s) using cached fp\n", fname);
#ifdef HAVE_W32_SYSTEM
if (SetFilePointer (fp, 0, NULL, FILE_BEGIN) == 0xffffffff)
{
log_error ("rewind file failed on handle %p: ec=%d\n",
fp, (int) GetLastError ());
fp = GNUPG_INVALID_FD;
}
#else
if (lseek (fp, 0, SEEK_SET) == (off_t) - 1)
{
log_error ("can't rewind fd %d: %s\n", fp, strerror (errno));
fp = GNUPG_INVALID_FD;
}
#endif
return fp;
}
}
if (DBG_IOBUF)
log_debug ("fd_cache_open (%s) not cached\n", fname);
return direct_open (fname, mode, 0);
}
static int
file_filter (void *opaque, int control, iobuf_t chain, byte * buf,
size_t * ret_len)
{
file_filter_ctx_t *a = opaque;
gnupg_fd_t f = a->fp;
size_t size = *ret_len;
size_t nbytes = 0;
int rc = 0;
(void)chain; /* Not used. */
if (control == IOBUFCTRL_UNDERFLOW)
{
log_assert (size); /* We need a buffer. */
if (a->eof_seen)
{
rc = -1;
*ret_len = 0;
}
else if (a->delayed_rc)
{
rc = a->delayed_rc;
a->delayed_rc = 0;
if (rc == -1)
a->eof_seen = -1;
*ret_len = 0;
}
else
{
#ifdef HAVE_W32_SYSTEM
unsigned long nread;
nbytes = 0;
if (!ReadFile (f, buf, size, &nread, NULL))
{
int ec = (int) GetLastError ();
if (ec != ERROR_BROKEN_PIPE)
{
rc = gpg_error_from_errno (ec);
log_error ("%s: read error: ec=%d\n", a->fname, ec);
}
}
else if (!nread)
{
a->eof_seen = 1;
rc = -1;
}
else
{
nbytes = nread;
}
#else
int n;
nbytes = 0;
read_more:
do
{
n = read (f, buf + nbytes, size - nbytes);
}
while (n == -1 && errno == EINTR);
if (n > 0)
{
nbytes += n;
if (nbytes < size)
goto read_more;
}
else if (!n) /* eof */
{
if (nbytes)
a->delayed_rc = -1;
else
{
a->eof_seen = 1;
rc = -1;
}
}
else /* error */
{
rc = gpg_error_from_syserror ();
if (gpg_err_code (rc) != GPG_ERR_EPIPE)
log_error ("%s: read error: %s\n", a->fname, gpg_strerror (rc));
if (nbytes)
{
a->delayed_rc = rc;
rc = 0;
}
}
#endif
*ret_len = nbytes;
}
}
else if (control == IOBUFCTRL_FLUSH)
{
if (size)
{
#ifdef HAVE_W32_SYSTEM
byte *p = buf;
unsigned long n;
nbytes = size;
do
{
if (size && !WriteFile (f, p, nbytes, &n, NULL))
{
int ec = (int) GetLastError ();
rc = gpg_error_from_errno (ec);
log_error ("%s: write error: ec=%d\n", a->fname, ec);
break;
}
p += n;
nbytes -= n;
}
while (nbytes);
nbytes = p - buf;
#else
byte *p = buf;
int n;
nbytes = size;
do
{
do
{
n = write (f, p, nbytes);
}
while (n == -1 && errno == EINTR);
if (n > 0)
{
p += n;
nbytes -= n;
}
}
while (n != -1 && nbytes);
if (n == -1)
{
rc = gpg_error_from_syserror ();
log_error ("%s: write error: %s\n", a->fname, strerror (errno));
}
nbytes = p - buf;
#endif
}
*ret_len = nbytes;
}
else if (control == IOBUFCTRL_INIT)
{
a->eof_seen = 0;
a->delayed_rc = 0;
a->keep_open = 0;
a->no_cache = 0;
}
else if (control == IOBUFCTRL_DESC)
{
mem2str (buf, "file_filter(fd)", *ret_len);
}
else if (control == IOBUFCTRL_FREE)
{
if (f != FD_FOR_STDIN && f != FD_FOR_STDOUT)
{
if (DBG_IOBUF)
log_debug ("%s: close fd/handle %d\n", a->fname, FD2INT (f));
if (!a->keep_open)
fd_cache_close (a->no_cache ? NULL : a->fname, f);
}
xfree (a); /* We can free our context now. */
}
return rc;
}
/* Similar to file_filter but using the estream system. */
static int
file_es_filter (void *opaque, int control, iobuf_t chain, byte * buf,
size_t * ret_len)
{
file_es_filter_ctx_t *a = opaque;
estream_t f = a->fp;
size_t size = *ret_len;
size_t nbytes = 0;
int rc = 0;
(void)chain; /* Not used. */
if (control == IOBUFCTRL_UNDERFLOW)
{
assert (size); /* We need a buffer. */
if (a->eof_seen)
{
rc = -1;
*ret_len = 0;
}
else
{
nbytes = 0;
rc = es_read (f, buf, size, &nbytes);
if (rc == -1)
{ /* error */
rc = gpg_error_from_syserror ();
log_error ("%s: read error: %s\n", a->fname, strerror (errno));
}
else if (!nbytes)
{ /* eof */
a->eof_seen = 1;
rc = -1;
}
*ret_len = nbytes;
}
}
else if (control == IOBUFCTRL_FLUSH)
{
if (size)
{
byte *p = buf;
size_t nwritten;
nbytes = size;
do
{
nwritten = 0;
if (es_write (f, p, nbytes, &nwritten))
{
rc = gpg_error_from_syserror ();
log_error ("%s: write error: %s\n",
a->fname, strerror (errno));
break;
}
p += nwritten;
nbytes -= nwritten;
}
while (nbytes);
nbytes = p - buf;
}
*ret_len = nbytes;
}
else if (control == IOBUFCTRL_INIT)
{
a->eof_seen = 0;
a->no_cache = 0;
}
else if (control == IOBUFCTRL_DESC)
{
mem2str (buf, "estream_filter", *ret_len);
}
else if (control == IOBUFCTRL_FREE)
{
if (f != es_stdin && f != es_stdout)
{
if (DBG_IOBUF)
log_debug ("%s: es_fclose %p\n", a->fname, f);
if (!a->keep_open)
es_fclose (f);
}
f = NULL;
xfree (a); /* We can free our context now. */
}
return rc;
}
#ifdef HAVE_W32_SYSTEM
/* Because network sockets are special objects under Lose32 we have to
use a dedicated filter for them. */
static int
sock_filter (void *opaque, int control, iobuf_t chain, byte * buf,
size_t * ret_len)
{
sock_filter_ctx_t *a = opaque;
size_t size = *ret_len;
size_t nbytes = 0;
int rc = 0;
(void)chain;
if (control == IOBUFCTRL_UNDERFLOW)
{
assert (size); /* need a buffer */
if (a->eof_seen)
{
rc = -1;
*ret_len = 0;
}
else
{
int nread;
nread = recv (a->sock, buf, size, 0);
if (nread == SOCKET_ERROR)
{
int ec = (int) WSAGetLastError ();
rc = gpg_error_from_errno (ec);
log_error ("socket read error: ec=%d\n", ec);
}
else if (!nread)
{
a->eof_seen = 1;
rc = -1;
}
else
{
nbytes = nread;
}
*ret_len = nbytes;
}
}
else if (control == IOBUFCTRL_FLUSH)
{
if (size)
{
byte *p = buf;
int n;
nbytes = size;
do
{
n = send (a->sock, p, nbytes, 0);
if (n == SOCKET_ERROR)
{
int ec = (int) WSAGetLastError ();
rc = gpg_error_from_errno (ec);
log_error ("socket write error: ec=%d\n", ec);
break;
}
p += n;
nbytes -= n;
}
while (nbytes);
nbytes = p - buf;
}
*ret_len = nbytes;
}
else if (control == IOBUFCTRL_INIT)
{
a->eof_seen = 0;
a->keep_open = 0;
a->no_cache = 0;
}
else if (control == IOBUFCTRL_DESC)
{
mem2str (buf, "sock_filter", *ret_len);
}
else if (control == IOBUFCTRL_FREE)
{
if (!a->keep_open)
closesocket (a->sock);
xfree (a); /* we can free our context now */
}
return rc;
}
#endif /*HAVE_W32_SYSTEM*/
/****************
* This is used to implement the block write mode.
* Block reading is done on a byte by byte basis in readbyte(),
* without a filter
*/
static int
block_filter (void *opaque, int control, iobuf_t chain, byte * buffer,
size_t * ret_len)
{
block_filter_ctx_t *a = opaque;
char *buf = (char *)buffer;
size_t size = *ret_len;
int c, needed, rc = 0;
char *p;
if (control == IOBUFCTRL_UNDERFLOW)
{
size_t n = 0;
p = buf;
assert (size); /* need a buffer */
if (a->eof) /* don't read any further */
rc = -1;
while (!rc && size)
{
if (!a->size)
{ /* get the length bytes */
if (a->partial == 2)
{
a->eof = 1;
if (!n)
rc = -1;
break;
}
else if (a->partial)
{
/* These OpenPGP introduced huffman like encoded length
* bytes are really a mess :-( */
if (a->first_c)
{
c = a->first_c;
a->first_c = 0;
}
else if ((c = iobuf_get (chain)) == -1)
{
log_error ("block_filter: 1st length byte missing\n");
rc = GPG_ERR_BAD_DATA;
break;
}
if (c < 192)
{
a->size = c;
a->partial = 2;
if (!a->size)
{
a->eof = 1;
if (!n)
rc = -1;
break;
}
}
else if (c < 224)
{
a->size = (c - 192) * 256;
if ((c = iobuf_get (chain)) == -1)
{
log_error
("block_filter: 2nd length byte missing\n");
rc = GPG_ERR_BAD_DATA;
break;
}
a->size += c + 192;
a->partial = 2;
if (!a->size)
{
a->eof = 1;
if (!n)
rc = -1;
break;
}
}
else if (c == 255)
{
a->size = iobuf_get_noeof (chain) << 24;
a->size |= iobuf_get_noeof (chain) << 16;
a->size |= iobuf_get_noeof (chain) << 8;
if ((c = iobuf_get (chain)) == -1)
{
log_error ("block_filter: invalid 4 byte length\n");
rc = GPG_ERR_BAD_DATA;
break;
}
a->size |= c;
a->partial = 2;
if (!a->size)
{
a->eof = 1;
if (!n)
rc = -1;
break;
}
}
else
{ /* Next partial body length. */
a->size = 1 << (c & 0x1f);
}
/* log_debug("partial: ctx=%p c=%02x size=%u\n", a, c, a->size); */
}
else
BUG ();
}
while (!rc && size && a->size)
{
needed = size < a->size ? size : a->size;
c = iobuf_read (chain, p, needed);
if (c < needed)
{
if (c == -1)
c = 0;
log_error
("block_filter %p: read error (size=%lu,a->size=%lu)\n",
a, (ulong) size + c, (ulong) a->size + c);
rc = GPG_ERR_BAD_DATA;
}
else
{
size -= c;
a->size -= c;
p += c;
n += c;
}
}
}
*ret_len = n;
}
else if (control == IOBUFCTRL_FLUSH)
{
if (a->partial)
{ /* the complicated openpgp scheme */
size_t blen, n, nbytes = size + a->buflen;
assert (a->buflen <= OP_MIN_PARTIAL_CHUNK);
if (nbytes < OP_MIN_PARTIAL_CHUNK)
{
/* not enough to write a partial block out; so we store it */
if (!a->buffer)
a->buffer = xmalloc (OP_MIN_PARTIAL_CHUNK);
memcpy (a->buffer + a->buflen, buf, size);
a->buflen += size;
}
else
{ /* okay, we can write out something */
/* do this in a loop to use the most efficient block lengths */
p = buf;
do
{
/* find the best matching block length - this is limited
* by the size of the internal buffering */
for (blen = OP_MIN_PARTIAL_CHUNK * 2,
c = OP_MIN_PARTIAL_CHUNK_2POW + 1; blen <= nbytes;
blen *= 2, c++)
;
blen /= 2;
c--;
/* write the partial length header */
assert (c <= 0x1f); /*;-) */
c |= 0xe0;
iobuf_put (chain, c);
if ((n = a->buflen))
{ /* write stuff from the buffer */
assert (n == OP_MIN_PARTIAL_CHUNK);
if (iobuf_write (chain, a->buffer, n))
rc = gpg_error_from_syserror ();
a->buflen = 0;
nbytes -= n;
}
if ((n = nbytes) > blen)
n = blen;
if (n && iobuf_write (chain, p, n))
rc = gpg_error_from_syserror ();
p += n;
nbytes -= n;
}
while (!rc && nbytes >= OP_MIN_PARTIAL_CHUNK);
/* store the rest in the buffer */
if (!rc && nbytes)
{
assert (!a->buflen);
assert (nbytes < OP_MIN_PARTIAL_CHUNK);
if (!a->buffer)
a->buffer = xmalloc (OP_MIN_PARTIAL_CHUNK);
memcpy (a->buffer, p, nbytes);
a->buflen = nbytes;
}
}
}
else
BUG ();
}
else if (control == IOBUFCTRL_INIT)
{
if (DBG_IOBUF)
log_debug ("init block_filter %p\n", a);
if (a->partial)
a->count = 0;
else if (a->use == IOBUF_INPUT)
a->count = a->size = 0;
else
a->count = a->size; /* force first length bytes */
a->eof = 0;
a->buffer = NULL;
a->buflen = 0;
}
else if (control == IOBUFCTRL_DESC)
{
mem2str (buf, "block_filter", *ret_len);
}
else if (control == IOBUFCTRL_FREE)
{
if (a->use == IOBUF_OUTPUT)
{ /* write the end markers */
if (a->partial)
{
u32 len;
/* write out the remaining bytes without a partial header
* the length of this header may be 0 - but if it is
* the first block we are not allowed to use a partial header
* and frankly we can't do so, because this length must be
* a power of 2. This is _really_ complicated because we
* have to check the possible length of a packet prior
* to it's creation: a chain of filters becomes complicated
* and we need a lot of code to handle compressed packets etc.
* :-(((((((
*/
/* construct header */
len = a->buflen;
/*log_debug("partial: remaining length=%u\n", len ); */
if (len < 192)
rc = iobuf_put (chain, len);
else if (len < 8384)
{
if (!(rc = iobuf_put (chain, ((len - 192) / 256) + 192)))
rc = iobuf_put (chain, ((len - 192) % 256));
}
else
{ /* use a 4 byte header */
if (!(rc = iobuf_put (chain, 0xff)))
if (!(rc = iobuf_put (chain, (len >> 24) & 0xff)))
if (!(rc = iobuf_put (chain, (len >> 16) & 0xff)))
if (!(rc = iobuf_put (chain, (len >> 8) & 0xff)))
rc = iobuf_put (chain, len & 0xff);
}
if (!rc && len)
rc = iobuf_write (chain, a->buffer, len);
if (rc)
{
log_error ("block_filter: write error: %s\n",
strerror (errno));
rc = gpg_error_from_syserror ();
}
xfree (a->buffer);
a->buffer = NULL;
a->buflen = 0;
}
else
BUG ();
}
else if (a->size)
{
log_error ("block_filter: pending bytes!\n");
}
if (DBG_IOBUF)
log_debug ("free block_filter %p\n", a);
xfree (a); /* we can free our context now */
}
return rc;
}
/* Change the default size for all IOBUFs to KILOBYTE. This needs to
* be called before any iobufs are used and can only be used once.
* Returns the current value. Using 0 has no effect except for
* returning the current value. */
unsigned int
iobuf_set_buffer_size (unsigned int kilobyte)
{
static int used;
if (!used && kilobyte)
{
if (kilobyte < 4)
kilobyte = 4;
else if (kilobyte > 16*1024)
kilobyte = 16*1024;
iobuf_buffer_size = kilobyte * 1024;
used = 1;
}
return iobuf_buffer_size / 1024;
}
#define MAX_IOBUF_DESC 32
/*
* Fill the buffer by the description of iobuf A.
* The buffer size should be MAX_IOBUF_DESC (or larger).
* Returns BUF as (const char *).
*/
static const char *
iobuf_desc (iobuf_t a, byte *buf)
{
size_t len = MAX_IOBUF_DESC;
if (! a || ! a->filter)
memcpy (buf, "?", 2);
else
a->filter (a->filter_ov, IOBUFCTRL_DESC, NULL, buf, &len);
return buf;
}
static void
print_chain (iobuf_t a)
{
if (!DBG_IOBUF)
return;
for (; a; a = a->chain)
{
byte desc[MAX_IOBUF_DESC];
log_debug ("iobuf chain: %d.%d '%s' filter_eof=%d start=%d len=%d\n",
a->no, a->subno, iobuf_desc (a, desc), a->filter_eof,
(int) a->d.start, (int) a->d.len);
}
}
int
iobuf_print_chain (iobuf_t a)
{
print_chain (a);
return 0;
}
iobuf_t
iobuf_alloc (int use, size_t bufsize)
{
iobuf_t a;
static int number = 0;
assert (use == IOBUF_INPUT || use == IOBUF_INPUT_TEMP
|| use == IOBUF_OUTPUT || use == IOBUF_OUTPUT_TEMP);
if (bufsize == 0)
{
log_bug ("iobuf_alloc() passed a bufsize of 0!\n");
bufsize = iobuf_buffer_size;
}
a = xcalloc (1, sizeof *a);
a->use = use;
a->d.buf = xmalloc (bufsize);
a->d.size = bufsize;
a->no = ++number;
a->subno = 0;
a->real_fname = NULL;
return a;
}
int
iobuf_close (iobuf_t a)
{
iobuf_t a_chain;
size_t dummy_len = 0;
int rc = 0;
for (; a; a = a_chain)
{
byte desc[MAX_IOBUF_DESC];
int rc2 = 0;
a_chain = a->chain;
if (a->use == IOBUF_OUTPUT && (rc = filter_flush (a)))
log_error ("filter_flush failed on close: %s\n", gpg_strerror (rc));
if (DBG_IOBUF)
log_debug ("iobuf-%d.%d: close '%s'\n",
a->no, a->subno, iobuf_desc (a, desc));
if (a->filter && (rc2 = a->filter (a->filter_ov, IOBUFCTRL_FREE,
a->chain, NULL, &dummy_len)))
log_error ("IOBUFCTRL_FREE failed on close: %s\n", gpg_strerror (rc));
if (! rc && rc2)
/* Whoops! An error occurred. Save it in RC if we haven't
already recorded an error. */
rc = rc2;
xfree (a->real_fname);
if (a->d.buf)
{
memset (a->d.buf, 0, a->d.size); /* erase the buffer */
xfree (a->d.buf);
}
xfree (a);
}
return rc;
}
int
iobuf_cancel (iobuf_t a)
{
const char *s;
iobuf_t a2;
int rc;
#if defined(HAVE_W32_SYSTEM) || defined(__riscos__)
char *remove_name = NULL;
#endif
if (a && a->use == IOBUF_OUTPUT)
{
s = iobuf_get_real_fname (a);
if (s && *s)
{
#if defined(HAVE_W32_SYSTEM) || defined(__riscos__)
remove_name = xstrdup (s);
#else
remove (s);
#endif
}
}
/* send a cancel message to all filters */
for (a2 = a; a2; a2 = a2->chain)
{
size_t dummy;
if (a2->filter)
a2->filter (a2->filter_ov, IOBUFCTRL_CANCEL, a2->chain, NULL, &dummy);
}
rc = iobuf_close (a);
#if defined(HAVE_W32_SYSTEM) || defined(__riscos__)
if (remove_name)
{
/* Argg, MSDOS does not allow removing open files. So
* we have to do it here */
#ifdef HAVE_W32CE_SYSTEM
wchar_t *wtmp = utf8_to_wchar (remove_name);
if (wtmp)
DeleteFile (wtmp);
xfree (wtmp);
#else
remove (remove_name);
#endif
xfree (remove_name);
}
#endif
return rc;
}
iobuf_t
iobuf_temp (void)
{
return iobuf_alloc (IOBUF_OUTPUT_TEMP, iobuf_buffer_size);
}
iobuf_t
iobuf_temp_with_content (const char *buffer, size_t length)
{
iobuf_t a;
int i;
a = iobuf_alloc (IOBUF_INPUT_TEMP, length);
assert (length == a->d.size);
/* memcpy (a->d.buf, buffer, length); */
for (i=0; i < length; i++)
a->d.buf[i] = buffer[i];
a->d.len = length;
return a;
}
int
iobuf_is_pipe_filename (const char *fname)
{
if (!fname || (*fname=='-' && !fname[1]) )
return 1;
return check_special_filename (fname, 0, 1) != -1;
}
static iobuf_t
do_open (const char *fname, int special_filenames,
int use, const char *opentype, int mode700)
{
iobuf_t a;
gnupg_fd_t fp;
file_filter_ctx_t *fcx;
size_t len = 0;
int print_only = 0;
int fd;
byte desc[MAX_IOBUF_DESC];
assert (use == IOBUF_INPUT || use == IOBUF_OUTPUT);
if (special_filenames
/* NULL or '-'. */
&& (!fname || (*fname == '-' && !fname[1])))
{
if (use == IOBUF_INPUT)
{
fp = FD_FOR_STDIN;
fname = "[stdin]";
}
else
{
fp = FD_FOR_STDOUT;
fname = "[stdout]";
}
print_only = 1;
}
else if (!fname)
return NULL;
else if (special_filenames
&& (fd = check_special_filename (fname, 0, 1)) != -1)
return iobuf_fdopen (translate_file_handle (fd, use == IOBUF_INPUT ? 0 : 1),
opentype);
else
{
if (use == IOBUF_INPUT)
fp = fd_cache_open (fname, opentype);
else
fp = direct_open (fname, opentype, mode700);
if (fp == GNUPG_INVALID_FD)
return NULL;
}
a = iobuf_alloc (use, iobuf_buffer_size);
fcx = xmalloc (sizeof *fcx + strlen (fname));
fcx->fp = fp;
fcx->print_only_name = print_only;
strcpy (fcx->fname, fname);
if (!print_only)
a->real_fname = xstrdup (fname);
a->filter = file_filter;
a->filter_ov = fcx;
file_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len);
if (DBG_IOBUF)
log_debug ("iobuf-%d.%d: open '%s' desc=%s fd=%d\n",
a->no, a->subno, fname, iobuf_desc (a, desc), FD2INT (fcx->fp));
return a;
}
iobuf_t
iobuf_open (const char *fname)
{
return do_open (fname, 1, IOBUF_INPUT, "rb", 0);
}
iobuf_t
iobuf_create (const char *fname, int mode700)
{
return do_open (fname, 1, IOBUF_OUTPUT, "wb", mode700);
}
iobuf_t
iobuf_openrw (const char *fname)
{
return do_open (fname, 0, IOBUF_OUTPUT, "r+b", 0);
}
static iobuf_t
do_iobuf_fdopen (int fd, const char *mode, int keep_open)
{
iobuf_t a;
gnupg_fd_t fp;
file_filter_ctx_t *fcx;
size_t len;
fp = INT2FD (fd);
a = iobuf_alloc (strchr (mode, 'w') ? IOBUF_OUTPUT : IOBUF_INPUT,
iobuf_buffer_size);
fcx = xmalloc (sizeof *fcx + 20);
fcx->fp = fp;
fcx->print_only_name = 1;
fcx->keep_open = keep_open;
sprintf (fcx->fname, "[fd %d]", fd);
a->filter = file_filter;
a->filter_ov = fcx;
file_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len);
if (DBG_IOBUF)
log_debug ("iobuf-%d.%d: fdopen%s '%s'\n",
a->no, a->subno, keep_open? "_nc":"", fcx->fname);
iobuf_ioctl (a, IOBUF_IOCTL_NO_CACHE, 1, NULL);
return a;
}
iobuf_t
iobuf_fdopen (int fd, const char *mode)
{
return do_iobuf_fdopen (fd, mode, 0);
}
iobuf_t
iobuf_fdopen_nc (int fd, const char *mode)
{
return do_iobuf_fdopen (fd, mode, 1);
}
iobuf_t
iobuf_esopen (estream_t estream, const char *mode, int keep_open)
{
iobuf_t a;
file_es_filter_ctx_t *fcx;
size_t len = 0;
a = iobuf_alloc (strchr (mode, 'w') ? IOBUF_OUTPUT : IOBUF_INPUT,
iobuf_buffer_size);
fcx = xtrymalloc (sizeof *fcx + 30);
fcx->fp = estream;
fcx->print_only_name = 1;
fcx->keep_open = keep_open;
sprintf (fcx->fname, "[fd %p]", estream);
a->filter = file_es_filter;
a->filter_ov = fcx;
file_es_filter (fcx, IOBUFCTRL_INIT, NULL, NULL, &len);
if (DBG_IOBUF)
log_debug ("iobuf-%d.%d: esopen%s '%s'\n",
a->no, a->subno, keep_open? "_nc":"", fcx->fname);
return a;
}
iobuf_t
iobuf_sockopen (int fd, const char *mode)
{
iobuf_t a;
#ifdef HAVE_W32_SYSTEM
sock_filter_ctx_t *scx;
size_t len;
a = iobuf_alloc (strchr (mode, 'w') ? IOBUF_OUTPUT : IOBUF_INPUT,
iobuf_buffer_size);
scx = xmalloc (sizeof *scx + 25);
scx->sock = fd;
scx->print_only_name = 1;
sprintf (scx->fname, "[sock %d]", fd);
a->filter = sock_filter;
a->filter_ov = scx;
sock_filter (scx, IOBUFCTRL_INIT, NULL, NULL, &len);
if (DBG_IOBUF)
log_debug ("iobuf-%d.%d: sockopen '%s'\n", a->no, a->subno, scx->fname);
iobuf_ioctl (a, IOBUF_IOCTL_NO_CACHE, 1, NULL);
#else
a = iobuf_fdopen (fd, mode);
#endif
return a;
}
int
iobuf_ioctl (iobuf_t a, iobuf_ioctl_t cmd, int intval, void *ptrval)
{
byte desc[MAX_IOBUF_DESC];
if (cmd == IOBUF_IOCTL_KEEP_OPEN)
{
/* Keep system filepointer/descriptor open. This was used in
the past by http.c; this ioctl is not directly used
anymore. */
if (DBG_IOBUF)
log_debug ("iobuf-%d.%d: ioctl '%s' keep_open=%d\n",
a ? a->no : -1, a ? a->subno : -1, iobuf_desc (a, desc),
intval);
for (; a; a = a->chain)
if (!a->chain && a->filter == file_filter)
{
file_filter_ctx_t *b = a->filter_ov;
b->keep_open = intval;
return 0;
}
#ifdef HAVE_W32_SYSTEM
else if (!a->chain && a->filter == sock_filter)
{
sock_filter_ctx_t *b = a->filter_ov;
b->keep_open = intval;
return 0;
}
#endif
}
else if (cmd == IOBUF_IOCTL_INVALIDATE_CACHE)
{
if (DBG_IOBUF)
log_debug ("iobuf-*.*: ioctl '%s' invalidate\n",
ptrval ? (char *) ptrval : "?");
if (!a && !intval && ptrval)
{
if (fd_cache_invalidate (ptrval))
return -1;
return 0;
}
}
else if (cmd == IOBUF_IOCTL_NO_CACHE)
{
if (DBG_IOBUF)
log_debug ("iobuf-%d.%d: ioctl '%s' no_cache=%d\n",
a ? a->no : -1, a ? a->subno : -1, iobuf_desc (a, desc),
intval);
for (; a; a = a->chain)
if (!a->chain && a->filter == file_filter)
{
file_filter_ctx_t *b = a->filter_ov;
b->no_cache = intval;
return 0;
}
#ifdef HAVE_W32_SYSTEM
else if (!a->chain && a->filter == sock_filter)
{
sock_filter_ctx_t *b = a->filter_ov;
b->no_cache = intval;
return 0;
}
#endif
}
else if (cmd == IOBUF_IOCTL_FSYNC)
{
/* Do a fsync on the open fd and return any errors to the caller
of iobuf_ioctl. Note that we work on a file name here. */
if (DBG_IOBUF)
log_debug ("iobuf-*.*: ioctl '%s' fsync\n",
ptrval? (const char*)ptrval:"");
if (!a && !intval && ptrval)
{
return fd_cache_synchronize (ptrval);
}
}
return -1;
}
/****************
* Register an i/o filter.
*/
int
iobuf_push_filter (iobuf_t a,
int (*f) (void *opaque, int control,
iobuf_t chain, byte * buf, size_t * len),
void *ov)
{
return iobuf_push_filter2 (a, f, ov, 0);
}
int
iobuf_push_filter2 (iobuf_t a,
int (*f) (void *opaque, int control,
iobuf_t chain, byte * buf, size_t * len),
void *ov, int rel_ov)
{
iobuf_t b;
size_t dummy_len = 0;
int rc = 0;
if (a->use == IOBUF_OUTPUT && (rc = filter_flush (a)))
return rc;
if (a->subno >= MAX_NESTING_FILTER)
{
log_error ("i/o filter too deeply nested - corrupted data?\n");
return GPG_ERR_BAD_DATA;
}
/* We want to create a new filter and put it in front of A. A
simple implementation would do:
b = iobuf_alloc (...);
b->chain = a;
return a;
This is a bit problematic: A is the head of the pipeline and
there are potentially many pointers to it. Requiring the caller
to update all of these pointers is a burden.
An alternative implementation would add a level of indirection.
For instance, we could use a pipeline object, which contains a
pointer to the first filter in the pipeline. This is not what we
do either.
Instead, we allocate a new buffer (B) and copy the first filter's
state into that and use the initial buffer (A) for the new
filter. One limitation of this approach is that it is not
practical to maintain a pointer to a specific filter's state.
Before:
A
|
v 0x100 0x200
+----------+ +----------+
| filter x |--------->| filter y |---->....
+----------+ +----------+
After: B
|
v 0x300
+----------+
A | filter x |
| +----------+
v 0x100 ^ v 0x200
+----------+ +----------+
| filter w | | filter y |---->....
+----------+ +----------+
Note: filter x's address changed from 0x100 to 0x300, but A still
points to the head of the pipeline.
*/
b = xmalloc (sizeof *b);
memcpy (b, a, sizeof *b);
/* fixme: it is stupid to keep a copy of the name at every level
* but we need the name somewhere because the name known by file_filter
* may have been released when we need the name of the file */
b->real_fname = a->real_fname ? xstrdup (a->real_fname) : NULL;
/* remove the filter stuff from the new stream */
a->filter = NULL;
a->filter_ov = NULL;
a->filter_ov_owner = 0;
a->filter_eof = 0;
if (a->use == IOBUF_OUTPUT_TEMP)
/* A TEMP filter buffers any data sent to it; it does not forward
any data down the pipeline. If we add a new filter to the
pipeline, it shouldn't also buffer data. It should send it
downstream to be buffered. Thus, the correct type for a filter
added in front of an IOBUF_OUTPUT_TEMP filter is IOBUF_OUPUT, not
IOBUF_OUTPUT_TEMP. */
{
a->use = IOBUF_OUTPUT;
/* When pipeline is written to, the temp buffer's size is
increased accordingly. We don't need to allocate a 10 MB
buffer for a non-terminal filter. Just use the default
size. */
a->d.size = iobuf_buffer_size;
}
else if (a->use == IOBUF_INPUT_TEMP)
/* Same idea as above. */
{
a->use = IOBUF_INPUT;
a->d.size = iobuf_buffer_size;
}
/* The new filter (A) gets a new buffer.
If the pipeline is an output or temp pipeline, then giving the
buffer to the new filter means that data that was written before
the filter was pushed gets sent to the filter. That's clearly
wrong.
If the pipeline is an input pipeline, then giving the buffer to
the new filter (A) means that data that has read from (B), but
not yet read from the pipeline won't be processed by the new
filter (A)! That's certainly not what we want. */
a->d.buf = xmalloc (a->d.size);
a->d.len = 0;
a->d.start = 0;
/* disable nlimit for the new stream */
a->ntotal = b->ntotal + b->nbytes;
a->nlimit = a->nbytes = 0;
a->nofast = 0;
/* make a link from the new stream to the original stream */
a->chain = b;
/* setup the function on the new stream */
a->filter = f;
a->filter_ov = ov;
a->filter_ov_owner = rel_ov;
a->subno = b->subno + 1;
if (DBG_IOBUF)
{
byte desc[MAX_IOBUF_DESC];
log_debug ("iobuf-%d.%d: push '%s'\n",
a->no, a->subno, iobuf_desc (a, desc));
print_chain (a);
}
/* now we can initialize the new function if we have one */
if (a->filter && (rc = a->filter (a->filter_ov, IOBUFCTRL_INIT, a->chain,
NULL, &dummy_len)))
log_error ("IOBUFCTRL_INIT failed: %s\n", gpg_strerror (rc));
return rc;
}
/****************
* Remove an i/o filter.
*/
int
iobuf_pop_filter (iobuf_t a, int (*f) (void *opaque, int control,
iobuf_t chain, byte * buf, size_t * len),
void *ov)
{
iobuf_t b;
size_t dummy_len = 0;
int rc = 0;
byte desc[MAX_IOBUF_DESC];
if (DBG_IOBUF)
log_debug ("iobuf-%d.%d: pop '%s'\n",
a->no, a->subno, iobuf_desc (a, desc));
if (a->use == IOBUF_INPUT_TEMP || a->use == IOBUF_OUTPUT_TEMP)
{
/* This should be the last filter in the pipeline. */
assert (! a->chain);
return 0;
}
if (!a->filter)
{ /* this is simple */
b = a->chain;
assert (b);
xfree (a->d.buf);
xfree (a->real_fname);
memcpy (a, b, sizeof *a);
xfree (b);
return 0;
}
for (b = a; b; b = b->chain)
if (b->filter == f && (!ov || b->filter_ov == ov))
break;
if (!b)
log_bug ("iobuf_pop_filter(): filter function not found\n");
/* flush this stream if it is an output stream */
if (a->use == IOBUF_OUTPUT && (rc = filter_flush (b)))
{
log_error ("filter_flush failed in iobuf_pop_filter: %s\n",
gpg_strerror (rc));
return rc;
}
/* and tell the filter to free it self */
if (b->filter && (rc = b->filter (b->filter_ov, IOBUFCTRL_FREE, b->chain,
NULL, &dummy_len)))
{
log_error ("IOBUFCTRL_FREE failed: %s\n", gpg_strerror (rc));
return rc;
}
if (b->filter_ov && b->filter_ov_owner)
{
xfree (b->filter_ov);
b->filter_ov = NULL;
}
/* and see how to remove it */
if (a == b && !b->chain)
log_bug ("can't remove the last filter from the chain\n");
else if (a == b)
{ /* remove the first iobuf from the chain */
/* everything from b is copied to a. This is save because
* a flush has been done on the to be removed entry
*/
b = a->chain;
xfree (a->d.buf);
xfree (a->real_fname);
memcpy (a, b, sizeof *a);
xfree (b);
if (DBG_IOBUF)
log_debug ("iobuf-%d.%d: popped filter\n", a->no, a->subno);
}
else if (!b->chain)
{ /* remove the last iobuf from the chain */
log_bug ("Ohh jeee, trying to remove a head filter\n");
}
else
{ /* remove an intermediate iobuf from the chain */
log_bug ("Ohh jeee, trying to remove an intermediate filter\n");
}
return rc;
}
/****************
* read underflow: read at least one byte into the buffer and return
* the first byte or -1 on EOF.
*/
static int
underflow (iobuf_t a, int clear_pending_eof)
{
return underflow_target (a, clear_pending_eof, 1);
}
/****************
* read underflow: read TARGET bytes into the buffer and return
* the first byte or -1 on EOF.
*/
static int
underflow_target (iobuf_t a, int clear_pending_eof, size_t target)
{
size_t len;
int rc;
if (DBG_IOBUF)
log_debug ("iobuf-%d.%d: underflow: buffer size: %d; still buffered: %d => space for %d bytes\n",
a->no, a->subno,
(int) a->d.size, (int) (a->d.len - a->d.start),
(int) (a->d.size - (a->d.len - a->d.start)));
if (a->use == IOBUF_INPUT_TEMP)
/* By definition, there isn't more data to read into the
buffer. */
return -1;
assert (a->use == IOBUF_INPUT);
/* If there is still some buffered data, then move it to the start
of the buffer and try to fill the end of the buffer. (This is
useful if we are called from iobuf_peek().) */
assert (a->d.start <= a->d.len);
a->d.len -= a->d.start;
memmove (a->d.buf, &a->d.buf[a->d.start], a->d.len);
a->d.start = 0;
if (a->d.len < target && a->filter_eof)
/* The last time we tried to read from this filter, we got an EOF.
We couldn't return the EOF, because there was buffered data.
Since there is no longer any buffered data, return the
error. */
{
if (DBG_IOBUF)
log_debug ("iobuf-%d.%d: underflow: eof (pending eof)\n",
a->no, a->subno);
if (! clear_pending_eof)
return -1;
if (a->chain)
/* A filter follows this one. Free this filter. */
{
iobuf_t b = a->chain;
if (DBG_IOBUF)
log_debug ("iobuf-%d.%d: filter popped (pending EOF returned)\n",
a->no, a->subno);
xfree (a->d.buf);
xfree (a->real_fname);
memcpy (a, b, sizeof *a);
xfree (b);
print_chain (a);
}
else
a->filter_eof = 0; /* for the top level filter */
return -1; /* return one(!) EOF */
}
if (a->d.len == 0 && a->error)
/* The last time we tried to read from this filter, we got an
error. We couldn't return the error, because there was
buffered data. Since there is no longer any buffered data,
return the error. */
{
if (DBG_IOBUF)
log_debug ("iobuf-%d.%d: pending error (%s) returned\n",
a->no, a->subno, gpg_strerror (a->error));
return -1;
}
if (a->filter && ! a->filter_eof && ! a->error)
/* We have a filter function and the last time we tried to read we
didn't get an EOF or an error. Try to fill the buffer. */
{
/* Be careful to account for any buffered data. */
len = a->d.size - a->d.len;
if (DBG_IOBUF)
log_debug ("iobuf-%d.%d: underflow: A->FILTER (%lu bytes)\n",
a->no, a->subno, (ulong) len);
if (len == 0)
/* There is no space for more data. Don't bother calling
A->FILTER. */
rc = 0;
else
rc = a->filter (a->filter_ov, IOBUFCTRL_UNDERFLOW, a->chain,
&a->d.buf[a->d.len], &len);
a->d.len += len;
if (DBG_IOBUF)
log_debug ("iobuf-%d.%d: A->FILTER() returned rc=%d (%s), read %lu bytes\n",
a->no, a->subno,
rc, rc == 0 ? "ok" : rc == -1 ? "EOF" : gpg_strerror (rc),
(ulong) len);
/* if( a->no == 1 ) */
/* log_hexdump (" data:", a->d.buf, len); */
if (rc == -1)
/* EOF. */
{
size_t dummy_len = 0;
/* Tell the filter to free itself */
if ((rc = a->filter (a->filter_ov, IOBUFCTRL_FREE, a->chain,
NULL, &dummy_len)))
log_error ("IOBUFCTRL_FREE failed: %s\n", gpg_strerror (rc));
/* Free everything except for the internal buffer. */
if (a->filter_ov && a->filter_ov_owner)
xfree (a->filter_ov);
a->filter_ov = NULL;
a->filter = NULL;
a->filter_eof = 1;
if (clear_pending_eof && a->d.len == 0 && a->chain)
/* We don't need to keep this filter around at all:
- we got an EOF
- we have no buffered data
- a filter follows this one.
Unlink this filter. */
{
iobuf_t b = a->chain;
if (DBG_IOBUF)
log_debug ("iobuf-%d.%d: pop in underflow (nothing buffered, got EOF)\n",
a->no, a->subno);
xfree (a->d.buf);
xfree (a->real_fname);
memcpy (a, b, sizeof *a);
xfree (b);
print_chain (a);
return -1;
}
else if (a->d.len == 0)
/* We can't unlink this filter (it is the only one in the
pipeline), but we can immediately return EOF. */
return -1;
}
else if (rc)
/* Record the error. */
{
a->error = rc;
if (a->d.len == 0)
/* There is no buffered data. Immediately return EOF. */
return -1;
}
}
assert (a->d.start <= a->d.len);
if (a->d.start < a->d.len)
return a->d.buf[a->d.start++];
/* EOF. */
return -1;
}
static int
filter_flush (iobuf_t a)
{
size_t len;
int rc;
if (a->use == IOBUF_OUTPUT_TEMP)
{ /* increase the temp buffer */
size_t newsize = a->d.size + iobuf_buffer_size;
if (DBG_IOBUF)
log_debug ("increasing temp iobuf from %lu to %lu\n",
(ulong) a->d.size, (ulong) newsize);
a->d.buf = xrealloc (a->d.buf, newsize);
a->d.size = newsize;
return 0;
}
else if (a->use != IOBUF_OUTPUT)
log_bug ("flush on non-output iobuf\n");
else if (!a->filter)
log_bug ("filter_flush: no filter\n");
len = a->d.len;
rc = a->filter (a->filter_ov, IOBUFCTRL_FLUSH, a->chain, a->d.buf, &len);
if (!rc && len != a->d.len)
{
log_info ("filter_flush did not write all!\n");
rc = GPG_ERR_INTERNAL;
}
else if (rc)
a->error = rc;
a->d.len = 0;
return rc;
}
int
iobuf_readbyte (iobuf_t a)
{
int c;
if (a->use == IOBUF_OUTPUT || a->use == IOBUF_OUTPUT_TEMP)
{
log_bug ("iobuf_readbyte called on a non-INPUT pipeline!\n");
return -1;
}
assert (a->d.start <= a->d.len);
if (a->nlimit && a->nbytes >= a->nlimit)
return -1; /* forced EOF */
if (a->d.start < a->d.len)
{
c = a->d.buf[a->d.start++];
}
else if ((c = underflow (a, 1)) == -1)
return -1; /* EOF */
assert (a->d.start <= a->d.len);
/* Note: if underflow doesn't return EOF, then it returns the first
byte that was read and advances a->d.start appropriately. */
a->nbytes++;
return c;
}
int
iobuf_read (iobuf_t a, void *buffer, unsigned int buflen)
{
unsigned char *buf = (unsigned char *)buffer;
int c, n;
if (a->use == IOBUF_OUTPUT || a->use == IOBUF_OUTPUT_TEMP)
{
log_bug ("iobuf_read called on a non-INPUT pipeline!\n");
return -1;
}
if (a->nlimit)
{
/* Handle special cases. */
for (n = 0; n < buflen; n++)
{
if ((c = iobuf_readbyte (a)) == -1)
{
if (!n)
return -1; /* eof */
break;
}
if (buf)
{
*buf = c;
buf++;
}
}
return n;
}
n = 0;
do
{
if (n < buflen && a->d.start < a->d.len)
/* Drain the buffer. */
{
unsigned size = a->d.len - a->d.start;
if (size > buflen - n)
size = buflen - n;
if (buf)
memcpy (buf, a->d.buf + a->d.start, size);
n += size;
a->d.start += size;
if (buf)
buf += size;
}
if (n < buflen)
/* Draining the internal buffer didn't fill BUFFER. Call
underflow to read more data into the filter's internal
buffer. */
{
if ((c = underflow (a, 1)) == -1)
/* EOF. If we managed to read something, don't return EOF
now. */
{
a->nbytes += n;
return n ? n : -1 /*EOF*/;
}
if (buf)
*buf++ = c;
n++;
}
}
while (n < buflen);
a->nbytes += n;
return n;
}
int
iobuf_peek (iobuf_t a, byte * buf, unsigned buflen)
{
int n = 0;
assert (buflen > 0);
assert (a->use == IOBUF_INPUT || a->use == IOBUF_INPUT_TEMP);
if (buflen > a->d.size)
/* We can't peek more than we can buffer. */
buflen = a->d.size;
/* Try to fill the internal buffer with enough data to satisfy the
request. */
while (buflen > a->d.len - a->d.start)
{
if (underflow_target (a, 0, buflen) == -1)
/* EOF. We can't read any more. */
break;
/* Underflow consumes the first character (it's the return
value). unget() it by resetting the "file position". */
assert (a->d.start == 1);
a->d.start = 0;
}
n = a->d.len - a->d.start;
if (n > buflen)
n = buflen;
if (n == 0)
/* EOF. */
return -1;
memcpy (buf, &a->d.buf[a->d.start], n);
return n;
}
int
iobuf_writebyte (iobuf_t a, unsigned int c)
{
int rc;
if (a->use == IOBUF_INPUT || a->use == IOBUF_INPUT_TEMP)
{
log_bug ("iobuf_writebyte called on an input pipeline!\n");
return -1;
}
if (a->d.len == a->d.size)
if ((rc=filter_flush (a)))
return rc;
assert (a->d.len < a->d.size);
a->d.buf[a->d.len++] = c;
return 0;
}
int
iobuf_write (iobuf_t a, const void *buffer, unsigned int buflen)
{
const unsigned char *buf = (const unsigned char *)buffer;
int rc;
if (a->use == IOBUF_INPUT || a->use == IOBUF_INPUT_TEMP)
{
log_bug ("iobuf_write called on an input pipeline!\n");
return -1;
}
do
{
if (buflen && a->d.len < a->d.size)
{
unsigned size = a->d.size - a->d.len;
if (size > buflen)
size = buflen;
memcpy (a->d.buf + a->d.len, buf, size);
buflen -= size;
buf += size;
a->d.len += size;
}
if (buflen)
{
rc = filter_flush (a);
if (rc)
return rc;
}
}
while (buflen);
return 0;
}
int
iobuf_writestr (iobuf_t a, const char *buf)
{
if (a->use == IOBUF_INPUT || a->use == IOBUF_INPUT_TEMP)
{
log_bug ("iobuf_writestr called on an input pipeline!\n");
return -1;
}
return iobuf_write (a, buf, strlen (buf));
}
int
iobuf_write_temp (iobuf_t dest, iobuf_t source)
{
assert (source->use == IOBUF_OUTPUT || source->use == IOBUF_OUTPUT_TEMP);
assert (dest->use == IOBUF_OUTPUT || dest->use == IOBUF_OUTPUT_TEMP);
iobuf_flush_temp (source);
return iobuf_write (dest, source->d.buf, source->d.len);
}
size_t
iobuf_temp_to_buffer (iobuf_t a, byte * buffer, size_t buflen)
{
byte desc[MAX_IOBUF_DESC];
size_t n;
while (1)
{
int rc = filter_flush (a);
if (rc)
log_bug ("Flushing iobuf %d.%d (%s) from iobuf_temp_to_buffer failed. Ignoring.\n",
a->no, a->subno, iobuf_desc (a, desc));
if (! a->chain)
break;
a = a->chain;
}
n = a->d.len;
if (n > buflen)
n = buflen;
memcpy (buffer, a->d.buf, n);
return n;
}
/* Copies the data from the input iobuf SOURCE to the output iobuf
DEST until either an error is encountered or EOF is reached.
Returns the number of bytes copies. */
size_t
iobuf_copy (iobuf_t dest, iobuf_t source)
{
char *temp;
/* Use a 32 KB buffer. */
const size_t temp_size = 32 * 1024;
size_t nread;
size_t nwrote = 0;
int err;
assert (source->use == IOBUF_INPUT || source->use == IOBUF_INPUT_TEMP);
assert (dest->use == IOBUF_OUTPUT || source->use == IOBUF_OUTPUT_TEMP);
if (iobuf_error (dest))
return -1;
temp = xmalloc (temp_size);
while (1)
{
nread = iobuf_read (source, temp, temp_size);
if (nread == -1)
/* EOF. */
break;
err = iobuf_write (dest, temp, nread);
if (err)
break;
nwrote += nread;
}
/* Burn the buffer. */
wipememory (temp, sizeof (temp));
xfree (temp);
return nwrote;
}
void
iobuf_flush_temp (iobuf_t temp)
{
if (temp->use == IOBUF_INPUT || temp->use == IOBUF_INPUT_TEMP)
log_bug ("iobuf_flush_temp called on an input pipeline!\n");
while (temp->chain)
iobuf_pop_filter (temp, temp->filter, NULL);
}
void
iobuf_set_limit (iobuf_t a, off_t nlimit)
{
if (nlimit)
a->nofast = 1;
else
a->nofast = 0;
a->nlimit = nlimit;
a->ntotal += a->nbytes;
a->nbytes = 0;
}
off_t
iobuf_get_filelength (iobuf_t a, int *overflow)
{
if (overflow)
*overflow = 0;
/* Hmmm: file_filter may have already been removed */
for ( ; a->chain; a = a->chain )
;
if (a->filter != file_filter)
return 0;
{
file_filter_ctx_t *b = a->filter_ov;
gnupg_fd_t fp = b->fp;
#if defined(HAVE_W32_SYSTEM)
ulong size;
static int (* __stdcall get_file_size_ex) (void *handle,
LARGE_INTEGER *r_size);
static int get_file_size_ex_initialized;
if (!get_file_size_ex_initialized)
{
void *handle;
handle = dlopen ("kernel32.dll", RTLD_LAZY);
if (handle)
{
get_file_size_ex = dlsym (handle, "GetFileSizeEx");
if (!get_file_size_ex)
dlclose (handle);
}
get_file_size_ex_initialized = 1;
}
if (get_file_size_ex)
{
/* This is a newer system with GetFileSizeEx; we use this
then because it seem that GetFileSize won't return a
proper error in case a file is larger than 4GB. */
LARGE_INTEGER exsize;
if (get_file_size_ex (fp, &exsize))
{
if (!exsize.u.HighPart)
return exsize.u.LowPart;
if (overflow)
*overflow = 1;
return 0;
}
}
else
{
if ((size=GetFileSize (fp, NULL)) != 0xffffffff)
return size;
}
log_error ("GetFileSize for handle %p failed: %s\n",
fp, w32_strerror (0));
#else /*!HAVE_W32_SYSTEM*/
{
struct stat st;
if ( !fstat (FD2INT (fp), &st) )
return st.st_size;
log_error("fstat() failed: %s\n", strerror(errno) );
}
#endif /*!HAVE_W32_SYSTEM*/
}
return 0;
}
int
iobuf_get_fd (iobuf_t a)
{
for (; a->chain; a = a->chain)
;
if (a->filter != file_filter)
return -1;
{
file_filter_ctx_t *b = a->filter_ov;
gnupg_fd_t fp = b->fp;
return FD2INT (fp);
}
}
off_t
iobuf_tell (iobuf_t a)
{
return a->ntotal + a->nbytes;
}
#if !defined(HAVE_FSEEKO) && !defined(fseeko)
#ifdef HAVE_LIMITS_H
# include
#endif
#ifndef LONG_MAX
# define LONG_MAX ((long) ((unsigned long) -1 >> 1))
#endif
#ifndef LONG_MIN
# define LONG_MIN (-1 - LONG_MAX)
#endif
/****************
* A substitute for fseeko, for hosts that don't have it.
*/
static int
fseeko (FILE * stream, off_t newpos, int whence)
{
while (newpos != (long) newpos)
{
long pos = newpos < 0 ? LONG_MIN : LONG_MAX;
if (fseek (stream, pos, whence) != 0)
return -1;
newpos -= pos;
whence = SEEK_CUR;
}
return fseek (stream, (long) newpos, whence);
}
#endif
int
iobuf_seek (iobuf_t a, off_t newpos)
{
file_filter_ctx_t *b = NULL;
if (a->use == IOBUF_OUTPUT || a->use == IOBUF_INPUT)
{
/* Find the last filter in the pipeline. */
for (; a->chain; a = a->chain)
;
if (a->filter != file_filter)
return -1;
b = a->filter_ov;
#ifdef HAVE_W32_SYSTEM
if (SetFilePointer (b->fp, newpos, NULL, FILE_BEGIN) == 0xffffffff)
{
log_error ("SetFilePointer failed on handle %p: ec=%d\n",
b->fp, (int) GetLastError ());
return -1;
}
#else
if (lseek (b->fp, newpos, SEEK_SET) == (off_t) - 1)
{
log_error ("can't lseek: %s\n", strerror (errno));
return -1;
}
#endif
/* Discard the buffer it is not a temp stream. */
a->d.len = 0;
}
a->d.start = 0;
a->nbytes = 0;
a->nlimit = 0;
a->nofast = 0;
a->ntotal = newpos;
a->error = 0;
/* It is impossible for A->CHAIN to be non-NULL. If A is an INPUT
or OUTPUT buffer, then we find the last filter, which is defined
as A->CHAIN being NULL. If A is a TEMP filter, then A must be
the only filter in the pipe: when iobuf_push_filter adds a filter
to the front of a pipeline, it sets the new filter to be an
OUTPUT filter if the pipeline is an OUTPUT or TEMP pipeline and
to be an INPUT filter if the pipeline is an INPUT pipeline.
Thus, only the last filter in a TEMP pipeline can be a */
/* remove filters, but the last */
if (a->chain)
log_debug ("iobuf_pop_filter called in iobuf_seek - please report\n");
while (a->chain)
iobuf_pop_filter (a, a->filter, NULL);
return 0;
}
const char *
iobuf_get_real_fname (iobuf_t a)
{
if (a->real_fname)
return a->real_fname;
/* the old solution */
for (; a; a = a->chain)
if (!a->chain && a->filter == file_filter)
{
file_filter_ctx_t *b = a->filter_ov;
return b->print_only_name ? NULL : b->fname;
}
return NULL;
}
const char *
iobuf_get_fname (iobuf_t a)
{
for (; a; a = a->chain)
if (!a->chain && a->filter == file_filter)
{
file_filter_ctx_t *b = a->filter_ov;
return b->fname;
}
return NULL;
}
const char *
iobuf_get_fname_nonnull (iobuf_t a)
{
const char *fname;
fname = iobuf_get_fname (a);
return fname? fname : "[?]";
}
/****************
* Enable or disable partial body length mode (RFC 4880 4.2.2.4).
*
* If LEN is 0, this disables partial block mode by popping the
* partial body length filter, which must be the most recently
* added filter.
*
* If LEN is non-zero, it pushes a partial body length filter. If
* this is a read filter, LEN must be the length byte from the first
* chunk and A should be position just after this first partial body
* length header.
*/
void
iobuf_set_partial_body_length_mode (iobuf_t a, size_t len)
{
if (!len)
/* Disable partial body length mode. */
{
if (a->use == IOBUF_INPUT)
log_debug ("iobuf_pop_filter called in set_partial_block_mode"
" - please report\n");
log_assert (a->filter == block_filter);
iobuf_pop_filter (a, block_filter, NULL);
}
else
/* Enabled partial body length mode. */
{
block_filter_ctx_t *ctx = xcalloc (1, sizeof *ctx);
ctx->use = a->use;
ctx->partial = 1;
ctx->size = 0;
ctx->first_c = len;
iobuf_push_filter (a, block_filter, ctx);
}
}
unsigned int
iobuf_read_line (iobuf_t a, byte ** addr_of_buffer,
unsigned *length_of_buffer, unsigned *max_length)
{
int c;
char *buffer = (char *)*addr_of_buffer;
unsigned length = *length_of_buffer;
unsigned nbytes = 0;
unsigned maxlen = *max_length;
char *p;
/* The code assumes that we have space for at least a newline and a
NUL character in the buffer. This requires at least 2 bytes. We
don't complicate the code by handling the stupid corner case, but
simply assert that it can't happen. */
assert (!buffer || length >= 2 || maxlen >= 2);
if (!buffer || length <= 1)
/* must allocate a new buffer */
{
length = 256 <= maxlen ? 256 : maxlen;
buffer = xrealloc (buffer, length);
*addr_of_buffer = (unsigned char *)buffer;
*length_of_buffer = length;
}
p = buffer;
while ((c = iobuf_get (a)) != -1)
{
*p++ = c;
nbytes++;
if (c == '\n')
break;
if (nbytes == length - 1)
/* We don't have enough space to add a \n and a \0. Increase
the buffer size. */
{
if (length == maxlen)
/* We reached the buffer's size limit! */
{
/* Skip the rest of the line. */
while (c != '\n' && (c = iobuf_get (a)) != -1)
;
/* p is pointing at the last byte in the buffer. We
always terminate the line with "\n\0" so overwrite
the previous byte with a \n. */
assert (p > buffer);
p[-1] = '\n';
/* Indicate truncation. */
*max_length = 0;
break;
}
length += length < 1024 ? 256 : 1024;
if (length > maxlen)
length = maxlen;
buffer = xrealloc (buffer, length);
*addr_of_buffer = (unsigned char *)buffer;
*length_of_buffer = length;
p = buffer + nbytes;
}
}
/* Add the terminating NUL. */
*p = 0;
/* Return the number of characters written to the buffer including
the newline, but not including the terminating NUL. */
return nbytes;
}
static int
translate_file_handle (int fd, int for_write)
{
#if defined(HAVE_W32CE_SYSTEM)
/* This is called only with one of the special filenames. Under
W32CE the FD here is not a file descriptor but a rendezvous id,
thus we need to finish the pipe first. */
fd = _assuan_w32ce_finish_pipe (fd, for_write);
#elif defined(HAVE_W32_SYSTEM)
{
int x;
(void)for_write;
if (fd == 0)
x = (int) GetStdHandle (STD_INPUT_HANDLE);
else if (fd == 1)
x = (int) GetStdHandle (STD_OUTPUT_HANDLE);
else if (fd == 2)
x = (int) GetStdHandle (STD_ERROR_HANDLE);
else
x = fd;
if (x == -1)
log_debug ("GetStdHandle(%d) failed: ec=%d\n",
fd, (int) GetLastError ());
fd = x;
}
#else
(void)for_write;
#endif
return fd;
}
void
iobuf_skip_rest (iobuf_t a, unsigned long n, int partial)
{
if ( partial )
{
for (;;)
{
if (a->nofast || a->d.start >= a->d.len)
{
if (iobuf_readbyte (a) == -1)
{
break;
}
}
else
{
unsigned long count = a->d.len - a->d.start;
a->nbytes += count;
a->d.start = a->d.len;
}
}
}
else
{
unsigned long remaining = n;
while (remaining > 0)
{
if (a->nofast || a->d.start >= a->d.len)
{
if (iobuf_readbyte (a) == -1)
{
break;
}
--remaining;
}
else
{
unsigned long count = a->d.len - a->d.start;
if (count > remaining)
{
count = remaining;
}
a->nbytes += count;
a->d.start += count;
remaining -= count;
}
}
}
}
diff --git a/common/openpgp-oid.c b/common/openpgp-oid.c
index d800e7d57..86885e0aa 100644
--- a/common/openpgp-oid.c
+++ b/common/openpgp-oid.c
@@ -1,443 +1,443 @@
/* openpgp-oids.c - OID helper for OpenPGP
* Copyright (C) 2011 Free Software Foundation, Inc.
* Copyright (C) 2013 Werner Koch
*
* This file is part of GnuPG.
*
* This file is free software; you can redistribute it and/or modify
* it under the terms of either
*
* - the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* or
*
* - the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* or both in parallel, as here.
*
* This file 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 .
*/
#include
#include
#include
#include
#include
#include "util.h"
#include "openpgpdefs.h"
/* A table with all our supported OpenPGP curves. */
static struct {
const char *name; /* Standard name. */
const char *oidstr; /* IETF formatted OID. */
unsigned int nbits; /* Nominal bit length of the curve. */
const char *alias; /* NULL or alternative name of the curve. */
int pubkey_algo; /* Required OpenPGP algo or 0 for ECDSA/ECDH. */
} oidtable[] = {
{ "Curve25519", "1.3.6.1.4.1.3029.1.5.1", 255, "cv25519", PUBKEY_ALGO_ECDH },
{ "Ed25519", "1.3.6.1.4.1.11591.15.1", 255, "ed25519", PUBKEY_ALGO_EDDSA },
{ "NIST P-256", "1.2.840.10045.3.1.7", 256, "nistp256" },
{ "NIST P-384", "1.3.132.0.34", 384, "nistp384" },
{ "NIST P-521", "1.3.132.0.35", 521, "nistp521" },
{ "brainpoolP256r1", "1.3.36.3.3.2.8.1.1.7", 256 },
{ "brainpoolP384r1", "1.3.36.3.3.2.8.1.1.11", 384 },
{ "brainpoolP512r1", "1.3.36.3.3.2.8.1.1.13", 512 },
{ "secp256k1", "1.3.132.0.10", 256 },
{ NULL, NULL, 0}
};
/* The OID for Curve Ed25519 in OpenPGP format. */
static const char oid_ed25519[] =
{ 0x09, 0x2b, 0x06, 0x01, 0x04, 0x01, 0xda, 0x47, 0x0f, 0x01 };
/* The OID for Curve25519 in OpenPGP format. */
static const char oid_cv25519[] =
{ 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01 };
/* Helper for openpgp_oid_from_str. */
static size_t
make_flagged_int (unsigned long value, char *buf, size_t buflen)
{
int more = 0;
int shift;
/* fixme: figure out the number of bits in an ulong and start with
that value as shift (after making it a multiple of 7) a more
straigtforward implementation is to do it in reverse order using
a temporary buffer - saves a lot of compares */
for (more=0, shift=28; shift > 0; shift -= 7)
{
if (more || value >= (1<> shift);
value -= (value >> shift) << shift;
more = 1;
}
}
buf[buflen++] = value;
return buflen;
}
/* Convert the OID given in dotted decimal form in STRING to an DER
* encoding and store it as an opaque value at R_MPI. The format of
* the DER encoded is not a regular ASN.1 object but the modified
* format as used by OpenPGP for the ECC curve description. On error
* the function returns and error code an NULL is stored at R_BUG.
* Note that scanning STRING stops at the first white space
* character. */
gpg_error_t
openpgp_oid_from_str (const char *string, gcry_mpi_t *r_mpi)
{
unsigned char *buf;
size_t buflen;
unsigned long val1, val;
const char *endp;
int arcno;
*r_mpi = NULL;
if (!string || !*string)
return gpg_error (GPG_ERR_INV_VALUE);
/* We can safely assume that the encoded OID is shorter than the string. */
buf = xtrymalloc (1 + strlen (string) + 2);
if (!buf)
return gpg_error_from_syserror ();
/* Save the first byte for the length. */
buflen = 1;
val1 = 0; /* Avoid compiler warning. */
arcno = 0;
do {
arcno++;
val = strtoul (string, (char**)&endp, 10);
if (!digitp (string) || !(*endp == '.' || !*endp))
{
xfree (buf);
return gpg_error (GPG_ERR_INV_OID_STRING);
}
if (*endp == '.')
string = endp+1;
if (arcno == 1)
{
if (val > 2)
break; /* Not allowed, error caught below. */
val1 = val;
}
else if (arcno == 2)
{ /* Need to combine the first two arcs in one octet. */
if (val1 < 2)
{
if (val > 39)
{
xfree (buf);
return gpg_error (GPG_ERR_INV_OID_STRING);
}
buf[buflen++] = val1*40 + val;
}
else
{
val += 80;
buflen = make_flagged_int (val, buf, buflen);
}
}
else
{
buflen = make_flagged_int (val, buf, buflen);
}
} while (*endp == '.');
if (arcno == 1 || buflen < 2 || buflen > 254 )
{ /* It is not possible to encode only the first arc. */
xfree (buf);
return gpg_error (GPG_ERR_INV_OID_STRING);
}
*buf = buflen - 1;
*r_mpi = gcry_mpi_set_opaque (NULL, buf, buflen * 8);
if (!*r_mpi)
{
xfree (buf);
return gpg_error_from_syserror ();
}
return 0;
}
-/* Return a malloced string represenation of the OID in the opaque MPI
+/* Return a malloced string representation of the OID in the opaque MPI
A. In case of an error NULL is returned and ERRNO is set. */
char *
openpgp_oid_to_str (gcry_mpi_t a)
{
const unsigned char *buf;
size_t length;
unsigned int lengthi;
char *string, *p;
int n = 0;
unsigned long val, valmask;
valmask = (unsigned long)0xfe << (8 * (sizeof (valmask) - 1));
if (!a
|| !gcry_mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE)
|| !(buf = gcry_mpi_get_opaque (a, &lengthi)))
{
gpg_err_set_errno (EINVAL);
return NULL;
}
buf = gcry_mpi_get_opaque (a, &lengthi);
length = (lengthi+7)/8;
/* The first bytes gives the length; check consistency. */
if (!length || buf[0] != length -1)
{
gpg_err_set_errno (EINVAL);
return NULL;
}
/* Skip length byte. */
length--;
buf++;
/* To calculate the length of the string we can safely assume an
upper limit of 3 decimal characters per byte. Two extra bytes
- account for the special first octect */
+ account for the special first octet */
string = p = xtrymalloc (length*(1+3)+2+1);
if (!string)
return NULL;
if (!length)
{
*p = 0;
return string;
}
if (buf[0] < 40)
p += sprintf (p, "0.%d", buf[n]);
else if (buf[0] < 80)
p += sprintf (p, "1.%d", buf[n]-40);
else {
val = buf[n] & 0x7f;
while ( (buf[n]&0x80) && ++n < length )
{
if ( (val & valmask) )
goto badoid; /* Overflow. */
val <<= 7;
val |= buf[n] & 0x7f;
}
if (val < 80)
goto badoid;
val -= 80;
sprintf (p, "2.%lu", val);
p += strlen (p);
}
for (n++; n < length; n++)
{
val = buf[n] & 0x7f;
while ( (buf[n]&0x80) && ++n < length )
{
if ( (val & valmask) )
goto badoid; /* Overflow. */
val <<= 7;
val |= buf[n] & 0x7f;
}
sprintf (p, ".%lu", val);
p += strlen (p);
}
*p = 0;
return string;
badoid:
/* Return a special OID (gnu.gnupg.badoid) to indicate the error
case. The OID is broken and thus we return one which can't do
any harm. Formally this does not need to be a bad OID but an OID
with an arc that can't be represented in a 32 bit word is more
than likely corrupt. */
xfree (string);
return xtrystrdup ("1.3.6.1.4.1.11591.2.12242973");
}
/* Return true if A represents the OID for Ed25519. */
int
openpgp_oid_is_ed25519 (gcry_mpi_t a)
{
const unsigned char *buf;
unsigned int nbits;
size_t n;
if (!a || !gcry_mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE))
return 0;
buf = gcry_mpi_get_opaque (a, &nbits);
n = (nbits+7)/8;
return (n == DIM (oid_ed25519)
&& !memcmp (buf, oid_ed25519, DIM (oid_ed25519)));
}
int
openpgp_oid_is_cv25519 (gcry_mpi_t a)
{
const unsigned char *buf;
unsigned int nbits;
size_t n;
if (!a || !gcry_mpi_get_flag (a, GCRYMPI_FLAG_OPAQUE))
return 0;
buf = gcry_mpi_get_opaque (a, &nbits);
n = (nbits+7)/8;
return (n == DIM (oid_cv25519)
&& !memcmp (buf, oid_cv25519, DIM (oid_cv25519)));
}
/* Map the Libgcrypt ECC curve NAME to an OID. If R_NBITS is not NULL
store the bit size of the curve there. Returns NULL for unknown
curve names. */
const char *
openpgp_curve_to_oid (const char *name, unsigned int *r_nbits)
{
int i;
unsigned int nbits = 0;
const char *oidstr = NULL;
if (name)
{
for (i=0; oidtable[i].name; i++)
if (!strcmp (oidtable[i].name, name)
|| (oidtable[i].alias && !strcmp (oidtable[i].alias, name)))
{
oidstr = oidtable[i].oidstr;
nbits = oidtable[i].nbits;
break;
}
if (!oidtable[i].name)
{
/* If not found assume the input is already an OID and check
whether we support it. */
for (i=0; oidtable[i].name; i++)
if (!strcmp (name, oidtable[i].oidstr))
{
oidstr = oidtable[i].oidstr;
nbits = oidtable[i].nbits;
break;
}
}
}
if (r_nbits)
*r_nbits = nbits;
return oidstr;
}
/* Map an OpenPGP OID to the Libgcrypt curve NAME. Returns NULL for
unknown curve names. Unless CANON is set we prefer an alias name
here which is more suitable for printing. */
const char *
openpgp_oid_to_curve (const char *oidstr, int canon)
{
int i;
if (!oidstr)
return NULL;
for (i=0; oidtable[i].name; i++)
if (!strcmp (oidtable[i].oidstr, oidstr))
return !canon && oidtable[i].alias? oidtable[i].alias : oidtable[i].name;
return NULL;
}
/* Return true if the curve with NAME is supported. */
static int
curve_supported_p (const char *name)
{
int result = 0;
gcry_sexp_t keyparms;
if (!gcry_sexp_build (&keyparms, NULL, "(public-key(ecc(curve %s)))", name))
{
result = !!gcry_pk_get_curve (keyparms, 0, NULL);
gcry_sexp_release (keyparms);
}
return result;
}
/* Enumerate available and supported OpenPGP curves. The caller needs
to set the integer variable at ITERP to zero and keep on calling
this function until NULL is returned. */
const char *
openpgp_enum_curves (int *iterp)
{
int idx = *iterp;
while (idx >= 0 && idx < DIM (oidtable) && oidtable[idx].name)
{
if (curve_supported_p (oidtable[idx].name))
{
*iterp = idx + 1;
return oidtable[idx].alias? oidtable[idx].alias : oidtable[idx].name;
}
idx++;
}
*iterp = idx;
return NULL;
}
/* Return the Libgcrypt name for the gpg curve NAME if supported. If
* R_ALGO is not NULL the required OpenPGP public key algo or 0 is
* stored at that address. If R_NBITS is not NULL the nominal bitsize
* of the curves is stored there. NULL is returned if the curve is
* not supported. */
const char *
openpgp_is_curve_supported (const char *name, int *r_algo,
unsigned int *r_nbits)
{
int idx;
if (r_algo)
*r_algo = 0;
if (r_nbits)
*r_nbits = 0;
for (idx = 0; idx < DIM (oidtable) && oidtable[idx].name; idx++)
{
if ((!strcmp (name, oidtable[idx].name)
|| (oidtable[idx].alias && !strcmp (name, (oidtable[idx].alias))))
&& curve_supported_p (oidtable[idx].name))
{
if (r_algo)
*r_algo = oidtable[idx].pubkey_algo;
if (r_nbits)
*r_nbits = oidtable[idx].nbits;
return oidtable[idx].name;
}
}
return NULL;
}
diff --git a/common/percent.c b/common/percent.c
index eeb026fbe..7b817684d 100644
--- a/common/percent.c
+++ b/common/percent.c
@@ -1,282 +1,282 @@
/* percent.c - Percent escaping
* Copyright (C) 2008, 2009 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* This file is free software; you can redistribute it and/or modify
* it under the terms of either
*
* - the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* or
*
* - the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* or both in parallel, as here.
*
* This file 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 .
*/
#include
#include
#include
#include
#include
#include "util.h"
/* Create a newly alloced string from STRING with all spaces and
control characters converted to plus signs or %xx sequences. The
function returns the new string or NULL in case of a malloc
failure.
Note that we also escape the quote character to work around a bug
- in the mingw32 runtime which does not correcty handle command line
+ in the mingw32 runtime which does not correctly handle command line
quoting. We correctly double the quote mark when calling a program
(i.e. gpg-protect-tool), but the pre-main code does not notice the
double quote as an escaped quote. We do this also on POSIX systems
for consistency. */
char *
percent_plus_escape (const char *string)
{
char *buffer, *p;
const char *s;
size_t length;
for (length=1, s=string; *s; s++)
{
if (*s == '+' || *s == '\"' || *s == '%'
|| *(const unsigned char *)s < 0x20)
length += 3;
else
length++;
}
buffer = p = xtrymalloc (length);
if (!buffer)
return NULL;
for (s=string; *s; s++)
{
if (*s == '+' || *s == '\"' || *s == '%'
|| *(const unsigned char *)s < 0x20)
{
snprintf (p, 4, "%%%02X", *(unsigned char *)s);
p += 3;
}
else if (*s == ' ')
*p++ = '+';
else
*p++ = *s;
}
*p = 0;
return buffer;
}
/* Create a newly alloced string from (DATA,DATALEN) with embedded
* Nuls quoted as %00. The standard percent unescaping can be
* used to reverse this encoding. */
char *
percent_data_escape (const void *data, size_t datalen)
{
char *buffer, *p;
const char *s;
size_t n, length;
for (length=1, s=data, n=datalen; n; s++, n--)
{
if (!*s || *s == '%')
length += 3;
else
length++;
}
buffer = p = xtrymalloc (length);
if (!buffer)
return NULL;
for (s=data, n=datalen; n; s++, n--)
{
if (!*s)
{
memcpy (p, "%00", 3);
p += 3;
}
else if (*s == '%')
{
memcpy (p, "%25", 3);
p += 3;
}
else
*p++ = *s;
}
*p = 0;
return buffer;
}
/* Do the percent and plus/space unescaping from STRING to BUFFER and
return the length of the valid buffer. Plus unescaping is only
done if WITHPLUS is true. An escaped Nul character will be
replaced by NULREPL. */
static size_t
do_unescape (unsigned char *buffer, const unsigned char *string,
int withplus, int nulrepl)
{
unsigned char *p = buffer;
while (*string)
{
if (*string == '%' && string[1] && string[2])
{
string++;
*p = xtoi_2 (string);
if (!*p)
*p = nulrepl;
string++;
}
else if (*string == '+' && withplus)
*p = ' ';
else
*p = *string;
p++;
string++;
}
return (p - buffer);
}
/* Count space required after unescaping STRING. Note that this will
never be larger than strlen (STRING). */
static size_t
count_unescape (const unsigned char *string)
{
size_t n = 0;
while (*string)
{
if (*string == '%' && string[1] && string[2])
{
string++;
string++;
}
string++;
n++;
}
return n;
}
/* Helper. */
static char *
do_plus_or_plain_unescape (const char *string, int withplus, int nulrepl)
{
size_t nbytes, n;
char *newstring;
nbytes = count_unescape (string);
newstring = xtrymalloc (nbytes+1);
if (newstring)
{
n = do_unescape (newstring, string, withplus, nulrepl);
assert (n == nbytes);
newstring[n] = 0;
}
return newstring;
}
/* Create a new allocated string from STRING with all "%xx" sequences
decoded and all plus signs replaced by a space. Embedded Nul
characters are replaced by the value of NULREPL. The function
returns the new string or NULL in case of a malloc failure. */
char *
percent_plus_unescape (const char *string, int nulrepl)
{
return do_plus_or_plain_unescape (string, 1, nulrepl);
}
/* Create a new allocated string from STRING with all "%xx" sequences
decoded. Embedded Nul characters are replaced by the value of
NULREPL. The function returns the new string or NULL in case of a
malloc failure. */
char *
percent_unescape (const char *string, int nulrepl)
{
return do_plus_or_plain_unescape (string, 0, nulrepl);
}
static size_t
do_unescape_inplace (char *string, int withplus, int nulrepl)
{
unsigned char *p, *p0;
p = p0 = string;
while (*string)
{
if (*string == '%' && string[1] && string[2])
{
string++;
*p = xtoi_2 (string);
if (!*p)
*p = nulrepl;
string++;
}
else if (*string == '+' && withplus)
*p = ' ';
else
*p = *string;
p++;
string++;
}
return (p - p0);
}
/* Perform percent and plus unescaping in STRING and return the new
valid length of the string. Embedded Nul characters are replaced
by the value of NULREPL. A terminating Nul character is not
inserted; the caller might want to call this function this way:
foo[percent_plus_unescape_inplace (foo, 0)] = 0;
*/
size_t
percent_plus_unescape_inplace (char *string, int nulrepl)
{
return do_unescape_inplace (string, 1, nulrepl);
}
/* Perform percent unescaping in STRING and return the new valid
length of the string. Embedded Nul characters are replaced by the
value of NULREPL. A terminating Nul character is not inserted; the
caller might want to call this function this way:
foo[percent_unescape_inplace (foo, 0)] = 0;
*/
size_t
percent_unescape_inplace (char *string, int nulrepl)
{
return do_unescape_inplace (string, 0, nulrepl);
}
diff --git a/common/sexputil.c b/common/sexputil.c
index f30790aa1..02e52d0ed 100644
--- a/common/sexputil.c
+++ b/common/sexputil.c
@@ -1,579 +1,579 @@
/* sexputil.c - Utility functions for S-expressions.
* Copyright (C) 2005, 2007, 2009 Free Software Foundation, Inc.
* Copyright (C) 2013 Werner Koch
*
* This file is part of GnuPG.
*
* This file is free software; you can redistribute it and/or modify
* it under the terms of either
*
* - the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* or
*
* - the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* or both in parallel, as here.
*
* This file 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 .
*/
/* This file implements a few utility functions useful when working
with canonical encrypted S-expressions (i.e. not the S-exprssion
objects from libgcrypt). */
#include
#include
#include
#include
#include
#include
#ifdef HAVE_LOCALE_H
#include
#endif
#include "util.h"
#include "tlv.h"
#include "sexp-parse.h"
#include "openpgpdefs.h" /* for pubkey_algo_t */
/* Return a malloced string with the S-expression CANON in advanced
format. Returns NULL on error. */
static char *
sexp_to_string (gcry_sexp_t sexp)
{
size_t n;
char *result;
if (!sexp)
return NULL;
n = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_ADVANCED, NULL, 0);
if (!n)
return NULL;
result = xtrymalloc (n);
if (!result)
return NULL;
n = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_ADVANCED, result, n);
if (!n)
BUG ();
return result;
}
/* Return a malloced string with the S-expression CANON in advanced
format. Returns NULL on error. */
char *
canon_sexp_to_string (const unsigned char *canon, size_t canonlen)
{
size_t n;
gcry_sexp_t sexp;
char *result;
n = gcry_sexp_canon_len (canon, canonlen, NULL, NULL);
if (!n)
return NULL;
if (gcry_sexp_sscan (&sexp, NULL, canon, n))
return NULL;
result = sexp_to_string (sexp);
gcry_sexp_release (sexp);
return result;
}
/* Print the canonical encoded S-expression in SEXP in advanced
format. SEXPLEN may be passed as 0 is SEXP is known to be valid.
With TEXT of NULL print just the raw S-expression, with TEXT just
an empty string, print a trailing linefeed, otherwise print an
entire debug line. */
void
log_printcanon (const char *text, const unsigned char *sexp, size_t sexplen)
{
if (text && *text)
log_debug ("%s ", text);
if (sexp)
{
char *buf = canon_sexp_to_string (sexp, sexplen);
log_printf ("%s", buf? buf : "[invalid S-expression]");
xfree (buf);
}
if (text)
log_printf ("\n");
}
/* Print the gcryp S-expression in SEXP in advanced format. With TEXT
of NULL print just the raw S-expression, with TEXT just an empty
string, print a trailing linefeed, otherwise print an entire debug
line. */
void
log_printsexp (const char *text, gcry_sexp_t sexp)
{
if (text && *text)
log_debug ("%s ", text);
if (sexp)
{
char *buf = sexp_to_string (sexp);
log_printf ("%s", buf? buf : "[invalid S-expression]");
xfree (buf);
}
if (text)
log_printf ("\n");
}
/* Helper function to create a canonical encoded S-expression from a
Libgcrypt S-expression object. The function returns 0 on success
and the malloced canonical S-expression is stored at R_BUFFER and
the allocated length at R_BUFLEN. On error an error code is
returned and (NULL, 0) stored at R_BUFFER and R_BUFLEN. If the
allocated buffer length is not required, NULL by be used for
R_BUFLEN. */
gpg_error_t
make_canon_sexp (gcry_sexp_t sexp, unsigned char **r_buffer, size_t *r_buflen)
{
size_t len;
unsigned char *buf;
*r_buffer = NULL;
if (r_buflen)
*r_buflen = 0;;
len = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_CANON, NULL, 0);
if (!len)
return gpg_error (GPG_ERR_BUG);
buf = xtrymalloc (len);
if (!buf)
return gpg_error_from_syserror ();
len = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_CANON, buf, len);
if (!len)
return gpg_error (GPG_ERR_BUG);
*r_buffer = buf;
if (r_buflen)
*r_buflen = len;
return 0;
}
/* Same as make_canon_sexp but pad the buffer to multiple of 64
bits. If SECURE is set, secure memory will be allocated. */
gpg_error_t
make_canon_sexp_pad (gcry_sexp_t sexp, int secure,
unsigned char **r_buffer, size_t *r_buflen)
{
size_t len;
unsigned char *buf;
*r_buffer = NULL;
if (r_buflen)
*r_buflen = 0;;
len = gcry_sexp_sprint (sexp, GCRYSEXP_FMT_CANON, NULL, 0);
if (!len)
return gpg_error (GPG_ERR_BUG);
len += (8 - len % 8) % 8;
buf = secure? xtrycalloc_secure (1, len) : xtrycalloc (1, len);
if (!buf)
return gpg_error_from_syserror ();
if (!gcry_sexp_sprint (sexp, GCRYSEXP_FMT_CANON, buf, len))
return gpg_error (GPG_ERR_BUG);
*r_buffer = buf;
if (r_buflen)
*r_buflen = len;
return 0;
}
/* Return the so called "keygrip" which is the SHA-1 hash of the
public key parameters expressed in a way depended on the algorithm.
KEY is expected to be an canonical encoded S-expression with a
public or private key. KEYLEN is the length of that buffer.
GRIP must be at least 20 bytes long. On success 0 is returned, on
error an error code. */
gpg_error_t
keygrip_from_canon_sexp (const unsigned char *key, size_t keylen,
unsigned char *grip)
{
gpg_error_t err;
gcry_sexp_t sexp;
if (!grip)
return gpg_error (GPG_ERR_INV_VALUE);
err = gcry_sexp_sscan (&sexp, NULL, (const char *)key, keylen);
if (err)
return err;
if (!gcry_pk_get_keygrip (sexp, grip))
err = gpg_error (GPG_ERR_INTERNAL);
gcry_sexp_release (sexp);
return err;
}
/* Compare two simple S-expressions like "(3:foo)". Returns 0 if they
are identical or !0 if they are not. Note that this function can't
be used for sorting. */
int
cmp_simple_canon_sexp (const unsigned char *a_orig,
const unsigned char *b_orig)
{
const char *a = (const char *)a_orig;
const char *b = (const char *)b_orig;
unsigned long n1, n2;
char *endp;
if (!a && !b)
return 0; /* Both are NULL, they are identical. */
if (!a || !b)
return 1; /* One is NULL, they are not identical. */
if (*a != '(' || *b != '(')
log_bug ("invalid S-exp in cmp_simple_canon_sexp\n");
a++;
n1 = strtoul (a, &endp, 10);
a = endp;
b++;
n2 = strtoul (b, &endp, 10);
b = endp;
if (*a != ':' || *b != ':' )
log_bug ("invalid S-exp in cmp_simple_canon_sexp\n");
if (n1 != n2)
return 1; /* Not the same. */
for (a++, b++; n1; n1--, a++, b++)
if (*a != *b)
return 1; /* Not the same. */
return 0;
}
/* Create a simple S-expression from the hex string at LINE. Returns
a newly allocated buffer with that canonical encoded S-expression
or NULL in case of an error. On return the number of characters
scanned in LINE will be stored at NSCANNED. This functions stops
converting at the first character not representing a hexdigit. Odd
numbers of hex digits are allowed; a leading zero is then
assumed. If no characters have been found, NULL is returned.*/
unsigned char *
make_simple_sexp_from_hexstr (const char *line, size_t *nscanned)
{
size_t n, len;
const char *s;
unsigned char *buf;
unsigned char *p;
char numbuf[50], *numbufp;
size_t numbuflen;
for (n=0, s=line; hexdigitp (s); s++, n++)
;
if (nscanned)
*nscanned = n;
if (!n)
return NULL;
len = ((n+1) & ~0x01)/2;
numbufp = smklen (numbuf, sizeof numbuf, len, &numbuflen);
buf = xtrymalloc (1 + numbuflen + len + 1 + 1);
if (!buf)
return NULL;
buf[0] = '(';
p = (unsigned char *)stpcpy ((char *)buf+1, numbufp);
s = line;
if ((n&1))
{
*p++ = xtoi_1 (s);
s++;
n--;
}
for (; n > 1; n -=2, s += 2)
*p++ = xtoi_2 (s);
*p++ = ')';
- *p = 0; /* (Not really neaded.) */
+ *p = 0; /* (Not really needed.) */
return buf;
}
/* Return the hash algorithm from a KSBA sig-val. SIGVAL is a
canonical encoded S-expression. Return 0 if the hash algorithm is
not encoded in SIG-VAL or it is not supported by libgcrypt. */
int
hash_algo_from_sigval (const unsigned char *sigval)
{
const unsigned char *s = sigval;
size_t n;
int depth;
char buffer[50];
if (!s || *s != '(')
return 0; /* Invalid S-expression. */
s++;
n = snext (&s);
if (!n)
return 0; /* Invalid S-expression. */
if (!smatch (&s, n, "sig-val"))
return 0; /* Not a sig-val. */
if (*s != '(')
return 0; /* Invalid S-expression. */
s++;
/* Skip over the algo+parameter list. */
depth = 1;
if (sskip (&s, &depth) || depth)
return 0; /* Invalid S-expression. */
if (*s != '(')
return 0; /* No further list. */
/* Check whether this is (hash ALGO). */
s++;
n = snext (&s);
if (!n)
return 0; /* Invalid S-expression. */
if (!smatch (&s, n, "hash"))
return 0; /* Not a "hash" keyword. */
n = snext (&s);
if (!n || n+1 >= sizeof (buffer))
return 0; /* Algorithm string is missing or too long. */
memcpy (buffer, s, n);
buffer[n] = 0;
return gcry_md_map_name (buffer);
}
/* Create a public key S-expression for an RSA public key from the
modulus M with length MLEN and the public exponent E with length
ELEN. Returns a newly allocated buffer of NULL in case of a memory
allocation problem. If R_LEN is not NULL, the length of the
canonical S-expression is stored there. */
unsigned char *
make_canon_sexp_from_rsa_pk (const void *m_arg, size_t mlen,
const void *e_arg, size_t elen,
size_t *r_len)
{
const unsigned char *m = m_arg;
const unsigned char *e = e_arg;
int m_extra = 0;
int e_extra = 0;
char mlen_str[35];
char elen_str[35];
unsigned char *keybuf, *p;
const char part1[] = "(10:public-key(3:rsa(1:n";
const char part2[] = ")(1:e";
const char part3[] = ")))";
/* Remove leading zeroes. */
for (; mlen && !*m; mlen--, m++)
;
for (; elen && !*e; elen--, e++)
;
/* Insert a leading zero if the number would be zero or interpreted
as negative. */
if (!mlen || (m[0] & 0x80))
m_extra = 1;
if (!elen || (e[0] & 0x80))
e_extra = 1;
/* Build the S-expression. */
snprintf (mlen_str, sizeof mlen_str, "%u:", (unsigned int)mlen+m_extra);
snprintf (elen_str, sizeof elen_str, "%u:", (unsigned int)elen+e_extra);
keybuf = xtrymalloc (strlen (part1) + strlen (mlen_str) + mlen + m_extra
+ strlen (part2) + strlen (elen_str) + elen + e_extra
+ strlen (part3) + 1);
if (!keybuf)
return NULL;
p = stpcpy (keybuf, part1);
p = stpcpy (p, mlen_str);
if (m_extra)
*p++ = 0;
memcpy (p, m, mlen);
p += mlen;
p = stpcpy (p, part2);
p = stpcpy (p, elen_str);
if (e_extra)
*p++ = 0;
memcpy (p, e, elen);
p += elen;
p = stpcpy (p, part3);
if (r_len)
*r_len = p - keybuf;
return keybuf;
}
/* Return the parameters of a public RSA key expressed as an
canonical encoded S-expression. */
gpg_error_t
get_rsa_pk_from_canon_sexp (const unsigned char *keydata, size_t keydatalen,
unsigned char const **r_n, size_t *r_nlen,
unsigned char const **r_e, size_t *r_elen)
{
gpg_error_t err;
const unsigned char *buf, *tok;
size_t buflen, toklen;
int depth, last_depth1, last_depth2;
const unsigned char *rsa_n = NULL;
const unsigned char *rsa_e = NULL;
size_t rsa_n_len, rsa_e_len;
*r_n = NULL;
*r_nlen = 0;
*r_e = NULL;
*r_elen = 0;
buf = keydata;
buflen = keydatalen;
depth = 0;
if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
return err;
if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
return err;
if (!tok || toklen != 10 || memcmp ("public-key", tok, toklen))
return gpg_error (GPG_ERR_BAD_PUBKEY);
if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
return err;
if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
return err;
if (!tok || toklen != 3 || memcmp ("rsa", tok, toklen))
return gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
last_depth1 = depth;
while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
&& depth && depth >= last_depth1)
{
if (tok)
return gpg_error (GPG_ERR_UNKNOWN_SEXP);
if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
return err;
if (tok && toklen == 1)
{
const unsigned char **mpi;
size_t *mpi_len;
switch (*tok)
{
case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break;
case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break;
default: mpi = NULL; mpi_len = NULL; break;
}
if (mpi && *mpi)
return gpg_error (GPG_ERR_DUP_VALUE);
if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
return err;
if (tok && mpi)
{
/* Strip off leading zero bytes and save. */
for (;toklen && !*tok; toklen--, tok++)
;
*mpi = tok;
*mpi_len = toklen;
}
}
/* Skip to the end of the list. */
last_depth2 = depth;
while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
&& depth && depth >= last_depth2)
;
if (err)
return err;
}
if (err)
return err;
if (!rsa_n || !rsa_n_len || !rsa_e || !rsa_e_len)
return gpg_error (GPG_ERR_BAD_PUBKEY);
*r_n = rsa_n;
*r_nlen = rsa_n_len;
*r_e = rsa_e;
*r_elen = rsa_e_len;
return 0;
}
/* Return the algo of a public KEY of SEXP. */
int
get_pk_algo_from_key (gcry_sexp_t key)
{
gcry_sexp_t list;
const char *s;
size_t n;
char algoname[6];
int algo = 0;
list = gcry_sexp_nth (key, 1);
if (!list)
goto out;
s = gcry_sexp_nth_data (list, 0, &n);
if (!s)
goto out;
if (n >= sizeof (algoname))
goto out;
memcpy (algoname, s, n);
algoname[n] = 0;
algo = gcry_pk_map_name (algoname);
if (algo == GCRY_PK_ECC)
{
gcry_sexp_t l1 = gcry_sexp_find_token (list, "flags", 0);
int i;
for (i = l1 ? gcry_sexp_length (l1)-1 : 0; i > 0; i--)
{
s = gcry_sexp_nth_data (l1, i, &n);
if (!s)
continue; /* Not a data element. */
if (n == 5 && !memcmp (s, "eddsa", 5))
{
algo = GCRY_PK_EDDSA;
break;
}
}
gcry_sexp_release (l1);
}
out:
gcry_sexp_release (list);
return algo;
}
/* This is a variant of get_pk_algo_from_key but takes an canonical
* encoded S-expression as input. Returns a GCRYPT public key
* identiier or 0 on error. */
int
get_pk_algo_from_canon_sexp (const unsigned char *keydata, size_t keydatalen)
{
gcry_sexp_t sexp;
int algo;
if (gcry_sexp_sscan (&sexp, NULL, keydata, keydatalen))
return 0;
algo = get_pk_algo_from_key (sexp);
gcry_sexp_release (sexp);
return algo;
}
diff --git a/common/simple-pwquery.c b/common/simple-pwquery.c
index b8ada4214..7688c846d 100644
--- a/common/simple-pwquery.c
+++ b/common/simple-pwquery.c
@@ -1,495 +1,495 @@
/* simple-pwquery.c - A simple password query client for gpg-agent
* Copyright (C) 2002, 2004, 2007 Free Software Foundation, Inc.
*
* 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 .
*/
/* This module is intended as a simple client implementation to
gpg-agent's GET_PASSPHRASE command. It can only cope with an
already running gpg-agent. Some stuff is configurable in the
header file. */
#ifdef HAVE_CONFIG_H
#include
#endif
#include
#include
#include
#include
#include
#include
#ifdef HAVE_W32_SYSTEM
#include
#else
#include
#include
#endif
#ifdef HAVE_LOCALE_H
#include
#endif
#define GNUPG_COMMON_NEED_AFLOCAL
#include "../common/mischelp.h"
#include "sysutils.h"
#include "membuf.h"
#define SIMPLE_PWQUERY_IMPLEMENTATION 1
#include "simple-pwquery.h"
#define SPWQ_OUT_OF_CORE gpg_error_from_errno (ENOMEM)
#define SPWQ_IO_ERROR gpg_error_from_errno (EIO)
#define SPWQ_PROTOCOL_ERROR gpg_error (GPG_ERR_PROTOCOL_VIOLATION)
#define SPWQ_ERR_RESPONSE gpg_error (GPG_ERR_INV_RESPONSE)
#define SPWQ_NO_AGENT gpg_error (GPG_ERR_NO_AGENT)
#define SPWQ_SYS_ERROR gpg_error_from_syserror ()
#define SPWQ_GENERAL_ERROR gpg_error (GPG_ERR_GENERAL)
#define SPWQ_NO_PIN_ENTRY gpg_error (GPG_ERR_NO_PIN_ENTRY)
#ifndef _
#define _(a) (a)
#endif
#if !defined (hexdigitp) && !defined (xtoi_2)
#define digitp(p) (*(p) >= '0' && *(p) <= '9')
#define hexdigitp(a) (digitp (a) \
|| (*(a) >= 'A' && *(a) <= 'F') \
|| (*(a) >= 'a' && *(a) <= 'f'))
#define xtoi_1(p) (*(p) <= '9'? (*(p)- '0'): \
*(p) <= 'F'? (*(p)-'A'+10):(*(p)-'a'+10))
#define xtoi_2(p) ((xtoi_1(p) * 16) + xtoi_1((p)+1))
#endif
/* Name of the socket to be used. This is a kludge to keep on using
- the existsing code despite that we only support a standard socket. */
+ the existing code despite that we only support a standard socket. */
static char *default_gpg_agent_info;
#ifndef HAVE_STPCPY
static char *
my_stpcpy(char *a,const char *b)
{
while( *b )
*a++ = *b++;
*a = 0;
return (char*)a;
}
#define stpcpy(a,b) my_stpcpy((a), (b))
#endif
/* Send an option to the agent */
static int
agent_send_option (assuan_context_t ctx, const char *name, const char *value)
{
int err;
char *line;
line = spwq_malloc (7 + strlen (name) + 1 + strlen (value) + 2);
if (!line)
return SPWQ_OUT_OF_CORE;
strcpy (stpcpy (stpcpy (stpcpy (
stpcpy (line, "OPTION "), name), "="), value), "\n");
err = assuan_transact (ctx, line, NULL, NULL, NULL, NULL, NULL, NULL);
spwq_free (line);
return err;
}
/* Send all available options to the agent. */
static int
agent_send_all_options (assuan_context_t ctx)
{
char *dft_display = NULL;
char *dft_ttyname = NULL;
char *dft_ttytype = NULL;
char *dft_xauthority = NULL;
char *dft_pinentry_user_data = NULL;
int rc = 0;
dft_display = getenv ("DISPLAY");
if (dft_display)
{
if ((rc = agent_send_option (ctx, "display", dft_display)))
return rc;
}
dft_ttyname = getenv ("GPG_TTY");
#if !defined(HAVE_W32_SYSTEM) && !defined(HAVE_BROKEN_TTYNAME)
if ((!dft_ttyname || !*dft_ttyname) && ttyname (0))
dft_ttyname = ttyname (0);
#endif
if (dft_ttyname && *dft_ttyname)
{
if ((rc=agent_send_option (ctx, "ttyname", dft_ttyname)))
return rc;
}
dft_ttytype = getenv ("TERM");
if (dft_ttyname && dft_ttytype)
{
if ((rc = agent_send_option (ctx, "ttytype", dft_ttytype)))
return rc;
}
#if defined(HAVE_SETLOCALE)
{
char *old_lc = NULL;
char *dft_lc = NULL;
#if defined(LC_CTYPE)
old_lc = setlocale (LC_CTYPE, NULL);
if (old_lc)
{
char *p = spwq_malloc (strlen (old_lc)+1);
if (!p)
return SPWQ_OUT_OF_CORE;
strcpy (p, old_lc);
old_lc = p;
}
dft_lc = setlocale (LC_CTYPE, "");
if (dft_ttyname && dft_lc)
rc = agent_send_option (ctx, "lc-ctype", dft_lc);
if (old_lc)
{
setlocale (LC_CTYPE, old_lc);
spwq_free (old_lc);
}
if (rc)
return rc;
#endif
#if defined(LC_MESSAGES)
old_lc = setlocale (LC_MESSAGES, NULL);
if (old_lc)
{
char *p = spwq_malloc (strlen (old_lc)+1);
if (!p)
return SPWQ_OUT_OF_CORE;
strcpy (p, old_lc);
old_lc = p;
}
dft_lc = setlocale (LC_MESSAGES, "");
if (dft_ttyname && dft_lc)
rc = agent_send_option (ctx, "lc-messages", dft_lc);
if (old_lc)
{
setlocale (LC_MESSAGES, old_lc);
spwq_free (old_lc);
}
if (rc)
return rc;
#endif
}
#endif /*HAVE_SETLOCALE*/
/* Send the XAUTHORITY variable. */
dft_xauthority = getenv ("XAUTHORITY");
if (dft_xauthority)
{
/* We ignore errors here because older gpg-agents don't support
this option. */
agent_send_option (ctx, "xauthority", dft_xauthority);
}
/* Send the PINENTRY_USER_DATA variable. */
dft_pinentry_user_data = getenv ("PINENTRY_USER_DATA");
if (dft_pinentry_user_data)
{
/* We ignore errors here because older gpg-agents don't support
this option. */
agent_send_option (ctx, "pinentry-user-data", dft_pinentry_user_data);
}
/* Tell the agent that we support Pinentry notifications. No
error checking so that it will work with older agents. */
assuan_transact (ctx, "OPTION allow-pinentry-notify",
NULL, NULL, NULL, NULL, NULL, NULL);
return 0;
}
/* Try to open a connection to the agent, send all options and return
the file descriptor for the connection. Return -1 in case of
error. */
static int
agent_open (assuan_context_t *ctx)
{
int rc;
char *infostr;
infostr = default_gpg_agent_info;
if ( !infostr || !*infostr )
{
#ifdef SPWQ_USE_LOGGING
log_error (_("no gpg-agent running in this session\n"));
#endif
*ctx = NULL;
return SPWQ_NO_AGENT;
}
rc = assuan_new (ctx);
if (rc)
return rc;
rc = assuan_socket_connect (*ctx, infostr, 0, 0);
if (rc)
{
#ifdef SPWQ_USE_LOGGING
log_error (_("can't connect to '%s': %s\n"),
infostr, gpg_strerror (rc));
#endif
goto errout;
}
rc = agent_send_all_options (*ctx);
if (rc)
{
#ifdef SPWQ_USE_LOGGING
log_error (_("problem setting the gpg-agent options\n"));
#endif
goto errout;
}
return 0;
errout:
assuan_release (*ctx);
*ctx = NULL;
return rc;
}
/* Copy text to BUFFER and escape as required. Return a pointer to
the end of the new buffer. Note that BUFFER must be large enough
to keep the entire text; allocataing it 3 times the size of TEXT
is sufficient. */
static char *
copy_and_escape (char *buffer, const char *text)
{
int i;
const unsigned char *s = (unsigned char *)text;
char *p = buffer;
for (i=0; s[i]; i++)
{
if (s[i] < ' ' || s[i] == '+')
{
sprintf (p, "%%%02X", s[i]);
p += 3;
}
else if (s[i] == ' ')
*p++ = '+';
else
*p++ = s[i];
}
return p;
}
/* Set the name of the default socket to NAME. */
int
simple_pw_set_socket (const char *name)
{
spwq_free (default_gpg_agent_info);
default_gpg_agent_info = NULL;
if (name)
{
default_gpg_agent_info = spwq_malloc (strlen (name) + 1);
if (!default_gpg_agent_info)
return SPWQ_OUT_OF_CORE;
strcpy (default_gpg_agent_info, name);
}
return 0;
}
/* This is the default inquiry callback. It merely handles the
Pinentry notification. */
static gpg_error_t
default_inq_cb (void *opaque, const char *line)
{
(void)opaque;
if (!strncmp (line, "PINENTRY_LAUNCHED", 17) && (line[17]==' '||!line[17]))
{
gnupg_allow_set_foregound_window ((pid_t)strtoul (line+17, NULL, 10));
/* We do not return errors to avoid breaking other code. */
}
else
{
#ifdef SPWQ_USE_LOGGING
log_debug ("ignoring gpg-agent inquiry '%s'\n", line);
#endif
}
return 0;
}
/* Ask the gpg-agent for a passphrase and present the user with a
DESCRIPTION, a PROMPT and optionally with a TRYAGAIN extra text.
If a CACHEID is not NULL it is used to locate the passphrase in
the cache and store it under this ID. If OPT_CHECK is true
gpg-agent is asked to apply some checks on the passphrase security.
If ERRORCODE is not NULL it should point a variable receiving an
errorcode; this error code might be 0 if the user canceled the
operation. The function returns NULL to indicate an error. */
char *
simple_pwquery (const char *cacheid,
const char *tryagain,
const char *prompt,
const char *description,
int opt_check,
int *errorcode)
{
int rc;
assuan_context_t ctx;
membuf_t data;
char *result = NULL;
char *pw = NULL;
char *p;
size_t n;
rc = agent_open (&ctx);
if (rc)
goto leave;
if (!cacheid)
cacheid = "X";
if (!tryagain)
tryagain = "X";
if (!prompt)
prompt = "X";
if (!description)
description = "X";
{
char *line;
/* We allocate 3 times the needed space so that there is enough
space for escaping. */
line = spwq_malloc (15 + 10
+ 3*strlen (cacheid) + 1
+ 3*strlen (tryagain) + 1
+ 3*strlen (prompt) + 1
+ 3*strlen (description) + 1
+ 2);
if (!line)
{
rc = SPWQ_OUT_OF_CORE;
goto leave;
}
strcpy (line, "GET_PASSPHRASE ");
p = line+15;
if (opt_check)
p = stpcpy (p, "--check ");
p = copy_and_escape (p, cacheid);
*p++ = ' ';
p = copy_and_escape (p, tryagain);
*p++ = ' ';
p = copy_and_escape (p, prompt);
*p++ = ' ';
p = copy_and_escape (p, description);
*p++ = '\n';
init_membuf_secure (&data, 64);
rc = assuan_transact (ctx, line, put_membuf_cb, &data,
default_inq_cb, NULL, NULL, NULL);
spwq_free (line);
/* Older Pinentries return the old assuan error code for canceled
which gets translated by libassuan to GPG_ERR_ASS_CANCELED and
not to the code for a user cancel. Fix this here. */
if (rc && gpg_err_source (rc)
&& gpg_err_code (rc) == GPG_ERR_ASS_CANCELED)
rc = gpg_err_make (gpg_err_source (rc), GPG_ERR_CANCELED);
if (rc)
{
p = get_membuf (&data, &n);
if (p)
wipememory (p, n);
spwq_free (p);
}
else
{
put_membuf (&data, "", 1);
result = get_membuf (&data, NULL);
if (pw == NULL)
rc = gpg_error_from_syserror ();
}
}
leave:
if (errorcode)
*errorcode = rc;
assuan_release (ctx);
return result;
}
/* Ask the gpg-agent to clear the passphrase for the cache ID CACHEID. */
int
simple_pwclear (const char *cacheid)
{
char line[500];
char *p;
/* We need not more than 50 characters for the command and the
terminating nul. */
if (strlen (cacheid) * 3 > sizeof (line) - 50)
return SPWQ_PROTOCOL_ERROR;
strcpy (line, "CLEAR_PASSPHRASE ");
p = line + 17;
p = copy_and_escape (p, cacheid);
*p++ = '\n';
*p++ = '\0';
return simple_query (line);
}
/* Perform the simple query QUERY (which must be new-line and 0
terminated) and return the error code. */
int
simple_query (const char *query)
{
assuan_context_t ctx;
int rc;
rc = agent_open (&ctx);
if (rc)
return rc;
rc = assuan_transact (ctx, query, NULL, NULL, NULL, NULL, NULL, NULL);
assuan_release (ctx);
return rc;
}
diff --git a/common/stringhelp.c b/common/stringhelp.c
index 0abac8ae5..751e5711f 100644
--- a/common/stringhelp.c
+++ b/common/stringhelp.c
@@ -1,1614 +1,1614 @@
/* stringhelp.c - standard string helper functions
* Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, 2007,
* 2008, 2009, 2010 Free Software Foundation, Inc.
* Copyright (C) 2014 Werner Koch
* Copyright (C) 2015 g10 Code GmbH
*
* This file is part of GnuPG.
*
* GnuPG is free software; you can redistribute and/or modify this
* part of GnuPG under the terms of either
*
* - the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* or
*
* - the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* or both in parallel, as here.
*
* 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 copies of the GNU General Public License
* and the GNU Lesser General Public License along with this program;
* if not, see .
*/
#include
#include
#include
#include
#include
#include
#ifdef HAVE_PWD_H
# include
#endif
#include
#include
#ifdef HAVE_W32_SYSTEM
# ifdef HAVE_WINSOCK2_H
# include
# endif
# include
#endif
#include
#include
#include "util.h"
#include "common-defs.h"
#include "utf8conv.h"
#include "sysutils.h"
#include "stringhelp.h"
#define tohex_lower(n) ((n) < 10 ? ((n) + '0') : (((n) - 10) + 'a'))
/* Sometimes we want to avoid mixing slashes and backslashes on W32
and prefer backslashes. There is usual no problem with mixing
them, however a very few W32 API calls can't grok plain slashes.
Printing filenames with mixed slashes also looks a bit strange.
This function has no effext on POSIX. */
static inline char *
change_slashes (char *name)
{
#ifdef HAVE_DOSISH_SYSTEM
char *p;
if (strchr (name, '\\'))
{
for (p=name; *p; p++)
if (*p == '/')
*p = '\\';
}
#endif /*HAVE_DOSISH_SYSTEM*/
return name;
}
/*
* Check whether STRING starts with KEYWORD. The keyword is
* delimited by end of string, a space or a tab. Returns NULL if not
* found or a pointer into STRING to the next non-space character
* after the KEYWORD (which may be end of string).
*/
char *
has_leading_keyword (const char *string, const char *keyword)
{
size_t n = strlen (keyword);
if (!strncmp (string, keyword, n)
&& (!string[n] || string[n] == ' ' || string[n] == '\t'))
{
string += n;
while (*string == ' ' || *string == '\t')
string++;
return (char*)string;
}
return NULL;
}
/*
* Look for the substring SUB in buffer and return a pointer to that
* substring in BUFFER or NULL if not found.
* Comparison is case-insensitive.
*/
const char *
memistr (const void *buffer, size_t buflen, const char *sub)
{
const unsigned char *buf = buffer;
const unsigned char *t = (const unsigned char *)buffer;
const unsigned char *s = (const unsigned char *)sub;
size_t n = buflen;
for ( ; n ; t++, n-- )
{
if ( toupper (*t) == toupper (*s) )
{
for ( buf=t++, buflen = n--, s++;
n && toupper (*t) == toupper (*s); t++, s++, n-- )
;
if (!*s)
return (const char*)buf;
t = buf;
s = (const unsigned char *)sub ;
n = buflen;
}
}
return NULL;
}
const char *
ascii_memistr ( const void *buffer, size_t buflen, const char *sub )
{
const unsigned char *buf = buffer;
const unsigned char *t = (const unsigned char *)buf;
const unsigned char *s = (const unsigned char *)sub;
size_t n = buflen;
for ( ; n ; t++, n-- )
{
if (ascii_toupper (*t) == ascii_toupper (*s) )
{
for ( buf=t++, buflen = n--, s++;
n && ascii_toupper (*t) == ascii_toupper (*s); t++, s++, n-- )
;
if (!*s)
return (const char*)buf;
t = (const unsigned char *)buf;
s = (const unsigned char *)sub ;
n = buflen;
}
}
return NULL;
}
/* This function is similar to strncpy(). However it won't copy more
than N - 1 characters and makes sure that a '\0' is appended. With
N given as 0, nothing will happen. With DEST given as NULL, memory
will be allocated using xmalloc (i.e. if it runs out of core
the function terminates). Returns DES or a pointer to the
allocated memory.
*/
char *
mem2str( char *dest , const void *src , size_t n )
{
char *d;
const char *s;
if( n ) {
if( !dest )
dest = xmalloc( n ) ;
d = dest;
s = src ;
for(n--; n && *s; n-- )
*d++ = *s++;
*d = '\0' ;
}
return dest ;
}
/****************
* remove leading and trailing white spaces
*/
char *
trim_spaces( char *str )
{
char *string, *p, *mark;
string = str;
/* find first non space character */
for( p=string; *p && isspace( *(byte*)p ) ; p++ )
;
/* move characters */
for( (mark = NULL); (*string = *p); string++, p++ )
if( isspace( *(byte*)p ) ) {
if( !mark )
mark = string ;
}
else
mark = NULL ;
if( mark )
*mark = '\0' ; /* remove trailing spaces */
return str ;
}
/****************
* remove trailing white spaces
*/
char *
trim_trailing_spaces( char *string )
{
char *p, *mark;
for( mark = NULL, p = string; *p; p++ ) {
if( isspace( *(byte*)p ) ) {
if( !mark )
mark = p;
}
else
mark = NULL;
}
if( mark )
*mark = '\0' ;
return string ;
}
unsigned
trim_trailing_chars( byte *line, unsigned len, const char *trimchars )
{
byte *p, *mark;
unsigned n;
for(mark=NULL, p=line, n=0; n < len; n++, p++ ) {
if( strchr(trimchars, *p ) ) {
if( !mark )
mark = p;
}
else
mark = NULL;
}
if( mark ) {
*mark = 0;
return mark - line;
}
return len;
}
/****************
* remove trailing white spaces and return the length of the buffer
*/
unsigned
trim_trailing_ws( byte *line, unsigned len )
{
return trim_trailing_chars( line, len, " \t\r\n" );
}
size_t
length_sans_trailing_chars (const unsigned char *line, size_t len,
const char *trimchars )
{
const unsigned char *p, *mark;
size_t n;
for( mark=NULL, p=line, n=0; n < len; n++, p++ )
{
if (strchr (trimchars, *p ))
{
if( !mark )
mark = p;
}
else
mark = NULL;
}
if (mark)
return mark - line;
return len;
}
/*
* Return the length of line ignoring trailing white-space.
*/
size_t
length_sans_trailing_ws (const unsigned char *line, size_t len)
{
return length_sans_trailing_chars (line, len, " \t\r\n");
}
/*
* Extract from a given path the filename component. This function
* terminates the process on memory shortage.
*/
char *
make_basename(const char *filepath, const char *inputpath)
{
#ifdef __riscos__
return riscos_make_basename(filepath, inputpath);
#else
char *p;
(void)inputpath; /* Only required for riscos. */
if ( !(p=strrchr(filepath, '/')) )
#ifdef HAVE_DOSISH_SYSTEM
if ( !(p=strrchr(filepath, '\\')) )
#endif
#ifdef HAVE_DRIVE_LETTERS
if ( !(p=strrchr(filepath, ':')) )
#endif
{
return xstrdup(filepath);
}
return xstrdup(p+1);
#endif
}
/*
* Extract from a given filename the path prepended to it. If there
* isn't a path prepended to the filename, a dot is returned ('.').
* This function terminates the process on memory shortage.
*/
char *
make_dirname(const char *filepath)
{
char *dirname;
int dirname_length;
char *p;
if ( !(p=strrchr(filepath, '/')) )
#ifdef HAVE_DOSISH_SYSTEM
if ( !(p=strrchr(filepath, '\\')) )
#endif
#ifdef HAVE_DRIVE_LETTERS
if ( !(p=strrchr(filepath, ':')) )
#endif
{
return xstrdup(".");
}
dirname_length = p-filepath;
dirname = xmalloc(dirname_length+1);
strncpy(dirname, filepath, dirname_length);
dirname[dirname_length] = 0;
return dirname;
}
static char *
get_pwdir (int xmode, const char *name)
{
char *result = NULL;
#ifdef HAVE_PWD_H
struct passwd *pwd = NULL;
if (name)
{
#ifdef HAVE_GETPWNAM
/* Fixme: We should use getpwnam_r if available. */
pwd = getpwnam (name);
#endif
}
else
{
#ifdef HAVE_GETPWUID
/* Fixme: We should use getpwuid_r if available. */
pwd = getpwuid (getuid());
#endif
}
if (pwd)
{
if (xmode)
result = xstrdup (pwd->pw_dir);
else
result = xtrystrdup (pwd->pw_dir);
}
#else /*!HAVE_PWD_H*/
/* No support at all. */
(void)xmode;
(void)name;
#endif /*HAVE_PWD_H*/
return result;
}
/* xmode 0 := Return NULL on error
1 := Terminate on error
2 := Make sure that name is absolute; return NULL on error
3 := Make sure that name is absolute; terminate on error
*/
static char *
do_make_filename (int xmode, const char *first_part, va_list arg_ptr)
{
const char *argv[32];
int argc;
size_t n;
int skip = 1;
char *home_buffer = NULL;
char *name, *home, *p;
int want_abs;
want_abs = !!(xmode & 2);
xmode &= 1;
n = strlen (first_part) + 1;
argc = 0;
while ( (argv[argc] = va_arg (arg_ptr, const char *)) )
{
n += strlen (argv[argc]) + 1;
if (argc >= DIM (argv)-1)
{
if (xmode)
BUG ();
gpg_err_set_errno (EINVAL);
return NULL;
}
argc++;
}
n++;
home = NULL;
if (*first_part == '~')
{
if (first_part[1] == '/' || !first_part[1])
{
/* This is the "~/" or "~" case. */
home = getenv("HOME");
if (!home)
home = home_buffer = get_pwdir (xmode, NULL);
if (home && *home)
n += strlen (home);
}
else
{
/* This is the "~username/" or "~username" case. */
char *user;
if (xmode)
user = xstrdup (first_part+1);
else
{
user = xtrystrdup (first_part+1);
if (!user)
return NULL;
}
p = strchr (user, '/');
if (p)
*p = 0;
skip = 1 + strlen (user);
home = home_buffer = get_pwdir (xmode, user);
xfree (user);
if (home)
n += strlen (home);
else
skip = 1;
}
}
if (xmode)
name = xmalloc (n);
else
{
name = xtrymalloc (n);
if (!name)
{
xfree (home_buffer);
return NULL;
}
}
if (home)
p = stpcpy (stpcpy (name, home), first_part + skip);
else
p = stpcpy (name, first_part);
xfree (home_buffer);
for (argc=0; argv[argc]; argc++)
{
/* Avoid a leading double slash if the first part was "/". */
if (!argc && name[0] == '/' && !name[1])
p = stpcpy (p, argv[argc]);
else
p = stpcpy (stpcpy (p, "/"), argv[argc]);
}
if (want_abs)
{
#ifdef HAVE_DRIVE_LETTERS
p = strchr (name, ':');
if (p)
p++;
else
p = name;
#else
p = name;
#endif
if (*p != '/'
#ifdef HAVE_DRIVE_LETTERS
&& *p != '\\'
#endif
)
{
home = gnupg_getcwd ();
if (!home)
{
if (xmode)
{
fprintf (stderr, "\nfatal: getcwd failed: %s\n",
strerror (errno));
exit(2);
}
xfree (name);
return NULL;
}
n = strlen (home) + 1 + strlen (name) + 1;
if (xmode)
home_buffer = xmalloc (n);
else
{
home_buffer = xtrymalloc (n);
if (!home_buffer)
{
xfree (home);
xfree (name);
return NULL;
}
}
if (p == name)
p = home_buffer;
else /* Windows case. */
{
memcpy (home_buffer, p, p - name + 1);
p = home_buffer + (p - name + 1);
}
/* Avoid a leading double slash if the cwd is "/". */
if (home[0] == '/' && !home[1])
strcpy (stpcpy (p, "/"), name);
else
strcpy (stpcpy (stpcpy (p, home), "/"), name);
xfree (home);
xfree (name);
name = home_buffer;
/* Let's do a simple compression to catch the most common
case of using "." for gpg's --homedir option. */
n = strlen (name);
if (n > 2 && name[n-2] == '/' && name[n-1] == '.')
name[n-2] = 0;
}
}
return change_slashes (name);
}
/* Construct a filename from the NULL terminated list of parts. Tilde
expansion is done for the first argument. This function terminates
the process on memory shortage. */
char *
make_filename (const char *first_part, ... )
{
va_list arg_ptr;
char *result;
va_start (arg_ptr, first_part);
result = do_make_filename (1, first_part, arg_ptr);
va_end (arg_ptr);
return result;
}
/* Construct a filename from the NULL terminated list of parts. Tilde
expansion is done for the first argument. This function may return
NULL on error. */
char *
make_filename_try (const char *first_part, ... )
{
va_list arg_ptr;
char *result;
va_start (arg_ptr, first_part);
result = do_make_filename (0, first_part, arg_ptr);
va_end (arg_ptr);
return result;
}
/* Construct an absolute filename from the NULL terminated list of
parts. Tilde expansion is done for the first argument. This
function terminates the process on memory shortage. */
char *
make_absfilename (const char *first_part, ... )
{
va_list arg_ptr;
char *result;
va_start (arg_ptr, first_part);
result = do_make_filename (3, first_part, arg_ptr);
va_end (arg_ptr);
return result;
}
/* Construct an absolute filename from the NULL terminated list of
parts. Tilde expansion is done for the first argument. This
function may return NULL on error. */
char *
make_absfilename_try (const char *first_part, ... )
{
va_list arg_ptr;
char *result;
va_start (arg_ptr, first_part);
result = do_make_filename (2, first_part, arg_ptr);
va_end (arg_ptr);
return result;
}
/* Compare whether the filenames are identical. This is a
special version of strcmp() taking the semantics of filenames in
account. Note that this function works only on the supplied names
without considering any context like the current directory. See
also same_file_p(). */
int
compare_filenames (const char *a, const char *b)
{
#ifdef HAVE_DOSISH_SYSTEM
for ( ; *a && *b; a++, b++ )
{
if (*a != *b
&& (toupper (*(const unsigned char*)a)
!= toupper (*(const unsigned char*)b) )
&& !((*a == '/' && *b == '\\') || (*a == '\\' && *b == '/')))
break;
}
if ((*a == '/' && *b == '\\') || (*a == '\\' && *b == '/'))
return 0;
else
return (toupper (*(const unsigned char*)a)
- toupper (*(const unsigned char*)b));
#else
return strcmp(a,b);
#endif
}
/* Convert a base-10 number in STRING into a 64 bit unsigned int
* value. Leading white spaces are skipped but no error checking is
* done. Thus it is similar to atoi(). */
uint64_t
string_to_u64 (const char *string)
{
uint64_t val = 0;
while (spacep (string))
string++;
for (; digitp (string); string++)
{
val *= 10;
val += *string - '0';
}
return val;
}
/* Convert 2 hex characters at S to a byte value. Return this value
or -1 if there is an error. */
int
hextobyte (const char *s)
{
int c;
if ( *s >= '0' && *s <= '9' )
c = 16 * (*s - '0');
else if ( *s >= 'A' && *s <= 'F' )
c = 16 * (10 + *s - 'A');
else if ( *s >= 'a' && *s <= 'f' )
c = 16 * (10 + *s - 'a');
else
return -1;
s++;
if ( *s >= '0' && *s <= '9' )
c += *s - '0';
else if ( *s >= 'A' && *s <= 'F' )
c += 10 + *s - 'A';
else if ( *s >= 'a' && *s <= 'f' )
c += 10 + *s - 'a';
else
return -1;
return c;
}
/* Given a string containing an UTF-8 encoded text, return the number
of characters in this string. It differs from strlen in that it
only counts complete UTF-8 characters. SIZE is the maximum length
of the string in bytes. If SIZE is -1, then a NUL character is
taken to be the end of the string. Note, that this function does
not take combined characters into account. */
size_t
utf8_charcount (const char *s, int len)
{
size_t n;
if (len == 0)
return 0;
for (n=0; *s; s++)
{
if ( (*s&0xc0) != 0x80 ) /* Exclude continuation bytes: 10xxxxxx */
n++;
if (len != -1)
{
len --;
if (len == 0)
break;
}
}
return n;
}
/****************************************************
********** W32 specific functions ****************
****************************************************/
#ifdef HAVE_W32_SYSTEM
const char *
w32_strerror (int ec)
{
static char strerr[256];
if (ec == -1)
ec = (int)GetLastError ();
#ifdef HAVE_W32CE_SYSTEM
/* There is only a wchar_t FormatMessage. It does not make much
sense to play the conversion game; we print only the code. */
snprintf (strerr, sizeof strerr, "ec=%d", (int)GetLastError ());
#else
FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL, ec,
MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
strerr, DIM (strerr)-1, NULL);
#endif
return strerr;
}
#endif /*HAVE_W32_SYSTEM*/
/****************************************************
******** Locale insensitive ctype functions ********
****************************************************/
/* FIXME: replace them by a table lookup and macros */
int
ascii_isupper (int c)
{
return c >= 'A' && c <= 'Z';
}
int
ascii_islower (int c)
{
return c >= 'a' && c <= 'z';
}
int
ascii_toupper (int c)
{
if (c >= 'a' && c <= 'z')
c &= ~0x20;
return c;
}
int
ascii_tolower (int c)
{
if (c >= 'A' && c <= 'Z')
c |= 0x20;
return c;
}
/* Lowercase all ASCII characters in S. */
char *
ascii_strlwr (char *s)
{
char *p = s;
for (p=s; *p; p++ )
if (isascii (*p) && *p >= 'A' && *p <= 'Z')
*p |= 0x20;
return s;
}
int
ascii_strcasecmp( const char *a, const char *b )
{
if (a == b)
return 0;
for (; *a && *b; a++, b++) {
if (*a != *b && ascii_toupper(*a) != ascii_toupper(*b))
break;
}
return *a == *b? 0 : (ascii_toupper (*a) - ascii_toupper (*b));
}
int
ascii_strncasecmp (const char *a, const char *b, size_t n)
{
const unsigned char *p1 = (const unsigned char *)a;
const unsigned char *p2 = (const unsigned char *)b;
unsigned char c1, c2;
if (p1 == p2 || !n )
return 0;
do
{
c1 = ascii_tolower (*p1);
c2 = ascii_tolower (*p2);
if ( !--n || c1 == '\0')
break;
++p1;
++p2;
}
while (c1 == c2);
return c1 - c2;
}
int
ascii_memcasecmp (const void *a_arg, const void *b_arg, size_t n )
{
const char *a = a_arg;
const char *b = b_arg;
if (a == b)
return 0;
for ( ; n; n--, a++, b++ )
{
if( *a != *b && ascii_toupper (*a) != ascii_toupper (*b) )
return *a == *b? 0 : (ascii_toupper (*a) - ascii_toupper (*b));
}
return 0;
}
int
ascii_strcmp( const char *a, const char *b )
{
if (a == b)
return 0;
for (; *a && *b; a++, b++) {
if (*a != *b )
break;
}
return *a == *b? 0 : (*(signed char *)a - *(signed char *)b);
}
void *
ascii_memcasemem (const void *haystack, size_t nhaystack,
const void *needle, size_t nneedle)
{
if (!nneedle)
return (void*)haystack; /* finding an empty needle is really easy */
if (nneedle <= nhaystack)
{
const char *a = haystack;
const char *b = a + nhaystack - nneedle;
for (; a <= b; a++)
{
if ( !ascii_memcasecmp (a, needle, nneedle) )
return (void *)a;
}
}
return NULL;
}
/*********************************************
********** missing string functions *********
*********************************************/
#ifndef HAVE_STPCPY
char *
stpcpy(char *a,const char *b)
{
while( *b )
*a++ = *b++;
*a = 0;
return (char*)a;
}
#endif
#ifndef HAVE_STRPBRK
/* Find the first occurrence in S of any character in ACCEPT.
Code taken from glibc-2.6/string/strpbrk.c (LGPLv2.1+) and modified. */
char *
strpbrk (const char *s, const char *accept)
{
while (*s != '\0')
{
const char *a = accept;
while (*a != '\0')
if (*a++ == *s)
return (char *) s;
++s;
}
return NULL;
}
#endif /*!HAVE_STRPBRK*/
#ifndef HAVE_STRSEP
/* Code taken from glibc-2.2.1/sysdeps/generic/strsep.c. */
char *
strsep (char **stringp, const char *delim)
{
char *begin, *end;
begin = *stringp;
if (begin == NULL)
return NULL;
/* A frequent case is when the delimiter string contains only one
character. Here we don't need to call the expensive 'strpbrk'
function and instead work using 'strchr'. */
if (delim[0] == '\0' || delim[1] == '\0')
{
char ch = delim[0];
if (ch == '\0')
end = NULL;
else
{
if (*begin == ch)
end = begin;
else if (*begin == '\0')
end = NULL;
else
end = strchr (begin + 1, ch);
}
}
else
/* Find the end of the token. */
end = strpbrk (begin, delim);
if (end)
{
/* Terminate the token and set *STRINGP past NUL character. */
*end++ = '\0';
*stringp = end;
}
else
/* No more delimiters; this is the last token. */
*stringp = NULL;
return begin;
}
#endif /*HAVE_STRSEP*/
#ifndef HAVE_STRLWR
char *
strlwr(char *s)
{
char *p;
for(p=s; *p; p++ )
*p = tolower(*p);
return s;
}
#endif
#ifndef HAVE_STRCASECMP
int
strcasecmp( const char *a, const char *b )
{
for( ; *a && *b; a++, b++ ) {
if( *a != *b && toupper(*a) != toupper(*b) )
break;
}
return *(const byte*)a - *(const byte*)b;
}
#endif
/****************
* mingw32/cpd has a memicmp()
*/
#ifndef HAVE_MEMICMP
int
memicmp( const char *a, const char *b, size_t n )
{
for( ; n; n--, a++, b++ )
if( *a != *b && toupper(*(const byte*)a) != toupper(*(const byte*)b) )
return *(const byte *)a - *(const byte*)b;
return 0;
}
#endif
#ifndef HAVE_MEMRCHR
void *
memrchr (const void *buffer, int c, size_t n)
{
const unsigned char *p = buffer;
for (p += n; n ; n--)
if (*--p == c)
return (void *)p;
return NULL;
}
#endif /*HAVE_MEMRCHR*/
/* Percent-escape the string STR by replacing colons with '%3a'. If
EXTRA is not NULL all characters in EXTRA are also escaped. */
static char *
do_percent_escape (const char *str, const char *extra, int die)
{
int i, j;
char *ptr;
if (!str)
return NULL;
for (i=j=0; str[i]; i++)
if (str[i] == ':' || str[i] == '%' || str[i] == '\n'
|| (extra && strchr (extra, str[i])))
j++;
if (die)
ptr = xmalloc (i + 2 * j + 1);
else
{
ptr = xtrymalloc (i + 2 * j + 1);
if (!ptr)
return NULL;
}
i = 0;
while (*str)
{
if (*str == ':')
{
ptr[i++] = '%';
ptr[i++] = '3';
ptr[i++] = 'a';
}
else if (*str == '%')
{
ptr[i++] = '%';
ptr[i++] = '2';
ptr[i++] = '5';
}
else if (*str == '\n')
{
/* The newline is problematic in a line-based format. */
ptr[i++] = '%';
ptr[i++] = '0';
ptr[i++] = 'a';
}
else if (extra && strchr (extra, *str))
{
ptr[i++] = '%';
ptr[i++] = tohex_lower ((*str>>4)&15);
ptr[i++] = tohex_lower (*str&15);
}
else
ptr[i++] = *str;
str++;
}
ptr[i] = '\0';
return ptr;
}
/* Percent-escape the string STR by replacing colons with '%3a'. If
EXTRA is not NULL all characters in EXTRA are also escaped. This
function terminates the process on memory shortage. */
char *
percent_escape (const char *str, const char *extra)
{
return do_percent_escape (str, extra, 1);
}
/* Same as percent_escape but return NULL instead of exiting on memory
error. */
char *
try_percent_escape (const char *str, const char *extra)
{
return do_percent_escape (str, extra, 0);
}
static char *
do_strconcat (const char *s1, va_list arg_ptr)
{
const char *argv[48];
size_t argc;
size_t needed;
char *buffer, *p;
argc = 0;
argv[argc++] = s1;
needed = strlen (s1);
while (((argv[argc] = va_arg (arg_ptr, const char *))))
{
needed += strlen (argv[argc]);
if (argc >= DIM (argv)-1)
{
gpg_err_set_errno (EINVAL);
return NULL;
}
argc++;
}
needed++;
buffer = xtrymalloc (needed);
if (buffer)
{
for (p = buffer, argc=0; argv[argc]; argc++)
p = stpcpy (p, argv[argc]);
}
return buffer;
}
/* Concatenate the string S1 with all the following strings up to a
NULL. Returns a malloced buffer with the new string or NULL on a
malloc error or if too many arguments are given. */
char *
strconcat (const char *s1, ...)
{
va_list arg_ptr;
char *result;
if (!s1)
result = xtrystrdup ("");
else
{
va_start (arg_ptr, s1);
result = do_strconcat (s1, arg_ptr);
va_end (arg_ptr);
}
return result;
}
/* Same as strconcat but terminate the process with an error message
if something goes wrong. */
char *
xstrconcat (const char *s1, ...)
{
va_list arg_ptr;
char *result;
if (!s1)
result = xstrdup ("");
else
{
va_start (arg_ptr, s1);
result = do_strconcat (s1, arg_ptr);
va_end (arg_ptr);
}
if (!result)
{
if (errno == EINVAL)
fputs ("\nfatal: too many args for xstrconcat\n", stderr);
else
fputs ("\nfatal: out of memory\n", stderr);
exit (2);
}
return result;
}
/* Split a string into fields at DELIM. REPLACEMENT is the character
to replace the delimiter with (normally: '\0' so that each field is
NUL terminated). The caller is responsible for freeing the result.
Note: this function modifies STRING! If you need the original
value, then you should pass a copy to this function.
If malloc fails, this function returns NULL. */
char **
strsplit (char *string, char delim, char replacement, int *count)
{
int fields = 1;
char *t;
char **result;
/* First, count the number of fields. */
for (t = strchr (string, delim); t; t = strchr (t + 1, delim))
fields ++;
result = xtrycalloc ((fields + 1), sizeof (*result));
if (! result)
return NULL;
result[0] = string;
fields = 1;
for (t = strchr (string, delim); t; t = strchr (t + 1, delim))
{
result[fields ++] = t + 1;
*t = replacement;
}
if (count)
*count = fields;
return result;
}
/* Tokenize STRING using the set of delimiters in DELIM. Leading
* spaces and tabs are removed from all tokens. The caller must xfree
* the result.
*
* Returns: A malloced and NULL delimited array with the tokens. On
* memory error NULL is returned and ERRNO is set.
*/
char **
strtokenize (const char *string, const char *delim)
{
const char *s;
size_t fields;
size_t bytes, n;
char *buffer;
char *p, *px, *pend;
char **result;
/* Count the number of fields. */
for (fields = 1, s = strpbrk (string, delim); s; s = strpbrk (s + 1, delim))
fields++;
fields++; /* Add one for the terminating NULL. */
/* Allocate an array for all fields, a terminating NULL, and space
for a copy of the string. */
bytes = fields * sizeof *result;
if (bytes / sizeof *result != fields)
{
gpg_err_set_errno (ENOMEM);
return NULL;
}
n = strlen (string) + 1;
bytes += n;
if (bytes < n)
{
gpg_err_set_errno (ENOMEM);
return NULL;
}
result = xtrymalloc (bytes);
if (!result)
return NULL;
buffer = (char*)(result + fields);
/* Copy and parse the string. */
strcpy (buffer, string);
for (n = 0, p = buffer; (pend = strpbrk (p, delim)); p = pend + 1)
{
*pend = 0;
while (spacep (p))
p++;
for (px = pend - 1; px >= p && spacep (px); px--)
*px = 0;
result[n++] = p;
}
while (spacep (p))
p++;
for (px = p + strlen (p) - 1; px >= p && spacep (px); px--)
*px = 0;
result[n++] = p;
result[n] = NULL;
assert ((char*)(result + n + 1) == buffer);
return result;
}
/* Split a string into space delimited fields and remove leading and
* trailing spaces from each field. A pointer to each field is stored
* in ARRAY. Stop splitting at ARRAYSIZE fields. The function
* modifies STRING. The number of parsed fields is returned.
* Example:
*
* char *fields[2];
* if (split_fields (string, fields, DIM (fields)) < 2)
* return // Not enough args.
* foo (fields[0]);
* foo (fields[1]);
*/
int
split_fields (char *string, char **array, int arraysize)
{
int n = 0;
char *p, *pend;
for (p = string; *p == ' '; p++)
;
do
{
if (n == arraysize)
break;
array[n++] = p;
pend = strchr (p, ' ');
if (!pend)
break;
*pend++ = 0;
for (p = pend; *p == ' '; p++)
;
}
while (*p);
return n;
}
/* Split a string into colon delimited fields A pointer to each field
* is stored in ARRAY. Stop splitting at ARRAYSIZE fields. The
* function modifies STRING. The number of parsed fields is returned.
* Note that leading and trailing spaces are not removed from the fields.
* Example:
*
* char *fields[2];
* if (split_fields (string, fields, DIM (fields)) < 2)
* return // Not enough args.
* foo (fields[0]);
* foo (fields[1]);
*/
int
split_fields_colon (char *string, char **array, int arraysize)
{
int n = 0;
char *p, *pend;
p = string;
do
{
if (n == arraysize)
break;
array[n++] = p;
pend = strchr (p, ':');
if (!pend)
break;
*pend++ = 0;
p = pend;
}
while (*p);
return n;
}
/* Version number parsing. */
/* This function parses the first portion of the version number S and
stores it in *NUMBER. On success, this function returns a pointer
into S starting with the first character, which is not part of the
initial number portion; on failure, NULL is returned. */
static const char*
parse_version_number (const char *s, int *number)
{
int val = 0;
if (*s == '0' && digitp (s+1))
return NULL; /* Leading zeros are not allowed. */
for (; digitp (s); s++)
{
val *= 10;
val += *s - '0';
}
*number = val;
return val < 0 ? NULL : s;
}
/* This function breaks up the complete string-representation of the
- version number S, which is of the following struture: .[.]. The major,
minor, and micro number components will be stored in *MAJOR, *MINOR
and *MICRO. If MICRO is not given 0 is used instead.
On success, the last component, the patch level, will be returned;
in failure, NULL will be returned. */
static const char *
parse_version_string (const char *s, int *major, int *minor, int *micro)
{
s = parse_version_number (s, major);
if (!s || *s != '.')
return NULL;
s++;
s = parse_version_number (s, minor);
if (!s)
return NULL;
if (*s == '.')
{
s++;
s = parse_version_number (s, micro);
if (!s)
return NULL;
}
else
*micro = 0;
return s; /* Patchlevel. */
}
/* Compare the version string MY_VERSION to the version string
* REQ_VERSION. Returns -1, 0, or 1 if MY_VERSION is found,
* respectively, to be less than, to match, or be greater than
* REQ_VERSION. This function works for three and two part version
* strings; for a two part version string the micro part is assumed to
* be 0. Patch levels are compared as strings. If a version number
* is invalid INT_MIN is returned. If REQ_VERSION is given as NULL
* the function returns 0 if MY_VERSION is parsable version string. */
int
compare_version_strings (const char *my_version, const char *req_version)
{
int my_major, my_minor, my_micro;
int rq_major, rq_minor, rq_micro;
const char *my_patch, *rq_patch;
int result;
if (!my_version)
return INT_MIN;
my_patch = parse_version_string (my_version, &my_major, &my_minor, &my_micro);
if (!my_patch)
return INT_MIN;
if (!req_version)
return 0; /* MY_VERSION can be parsed. */
rq_patch = parse_version_string (req_version, &rq_major, &rq_minor,&rq_micro);
if (!rq_patch)
return INT_MIN;
if (my_major == rq_major)
{
if (my_minor == rq_minor)
{
if (my_micro == rq_micro)
result = strcmp (my_patch, rq_patch);
else
result = my_micro - rq_micro;
}
else
result = my_minor - rq_minor;
}
else
result = my_major - rq_major;
return !result? 0 : result < 0 ? -1 : 1;
}
/* Format a string so that it fits within about TARGET_COLS columns.
* TEXT_IN is copied to a new buffer, which is returned. Normally,
* target_cols will be 72 and max_cols is 80. On error NULL is
* returned and ERRNO is set. */
char *
format_text (const char *text_in, int target_cols, int max_cols)
{
/* const int do_debug = 0; */
/* The character under consideration. */
char *p;
/* The start of the current line. */
char *line;
/* The last space that we saw. */
char *last_space = NULL;
int last_space_cols = 0;
int copied_last_space = 0;
char *text;
text = xtrystrdup (text_in);
if (!text)
return NULL;
p = line = text;
while (1)
{
/* The number of columns including any trailing space. */
int cols;
p = p + strcspn (p, "\n ");
if (! p)
/* P now points to the NUL character. */
p = &text[strlen (text)];
if (*p == '\n')
/* Pass through any newlines. */
{
p ++;
line = p;
last_space = NULL;
last_space_cols = 0;
copied_last_space = 1;
continue;
}
/* Have a space or a NUL. Note: we don't count the trailing
space. */
cols = utf8_charcount (line, (uintptr_t) p - (uintptr_t) line);
if (cols < target_cols)
{
if (! *p)
/* Nothing left to break. */
break;
last_space = p;
last_space_cols = cols;
p ++;
/* Skip any immediately following spaces. If we break:
"... foo bar ..." between "foo" and "bar" then we want:
"... foo\nbar ...", which means that the left space has
to be the first space after foo, not the last space
before bar. */
while (*p == ' ')
p ++;
}
else
{
int cols_with_left_space;
int cols_with_right_space;
int left_penalty;
int right_penalty;
cols_with_left_space = last_space_cols;
cols_with_right_space = cols;
/* if (do_debug) */
/* log_debug ("Breaking: '%.*s'\n", */
/* (int) ((uintptr_t) p - (uintptr_t) line), line); */
/* The number of columns away from TARGET_COLS. We prefer
to underflow than to overflow. */
left_penalty = target_cols - cols_with_left_space;
right_penalty = 2 * (cols_with_right_space - target_cols);
if (cols_with_right_space > max_cols)
/* Add a large penalty for each column that exceeds
max_cols. */
right_penalty += 4 * (cols_with_right_space - max_cols);
/* if (do_debug) */
/* log_debug ("Left space => %d cols (penalty: %d); " */
/* "right space => %d cols (penalty: %d)\n", */
/* cols_with_left_space, left_penalty, */
/* cols_with_right_space, right_penalty); */
if (last_space_cols && left_penalty <= right_penalty)
{
/* Prefer the left space. */
/* if (do_debug) */
/* log_debug ("Breaking at left space.\n"); */
p = last_space;
}
else
{
/* if (do_debug) */
/* log_debug ("Breaking at right space.\n"); */
}
if (! *p)
break;
*p = '\n';
p ++;
if (*p == ' ')
{
int spaces;
for (spaces = 1; p[spaces] == ' '; spaces ++)
;
memmove (p, &p[spaces], strlen (&p[spaces]) + 1);
}
line = p;
last_space = NULL;
last_space_cols = 0;
copied_last_space = 0;
}
}
/* Chop off any trailing space. */
trim_trailing_chars (text, strlen (text), " ");
/* If we inserted the trailing newline, then remove it. */
if (! copied_last_space && *text && text[strlen (text) - 1] == '\n')
text[strlen (text) - 1] = '\0';
return text;
}
diff --git a/common/t-exechelp.c b/common/t-exechelp.c
index cf967fcc7..3bf082bbb 100644
--- a/common/t-exechelp.c
+++ b/common/t-exechelp.c
@@ -1,188 +1,188 @@
/* t-exechelp.c - Module test for exechelp.c
* Copyright (C) 2009 Free Software Foundation, Inc.
*
* 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 .
*/
#include
#include
#include
#include
#include
#include
#include "util.h"
#include "exechelp.h"
static int verbose;
static void
print_open_fds (int *array)
{
int n;
if (!verbose)
return;
for (n=0; array[n] != -1; n++)
;
printf ("open file descriptors: %d", n);
putchar (' ');
putchar (' ');
putchar ('(');
for (n=0; array[n] != -1; n++)
printf ("%d%s", array[n], array[n+1] == -1?"":" ");
putchar (')');
putchar ('\n');
}
static int *
xget_all_open_fds (void)
{
int *array;
array = get_all_open_fds ();
if (!array)
{
fprintf (stderr, "%s:%d: get_all_open_fds failed: %s\n",
__FILE__, __LINE__, strerror (errno));
exit (1);
}
return array;
}
/* That is a very crude test. To do a proper test we would need to
fork a test process and best return information by some other means
than file descriptors. */
static void
test_close_all_fds (void)
{
int max_fd = get_max_fds ();
int *array;
int fd;
int initial_count, count, n;
#if 0
char buffer[100];
snprintf (buffer, sizeof buffer, "/bin/ls -l /proc/%d/fd", (int)getpid ());
system (buffer);
#endif
if (verbose)
printf ("max. file descriptors: %d\n", max_fd);
array = xget_all_open_fds ();
print_open_fds (array);
for (initial_count=n=0; array[n] != -1; n++)
initial_count++;
free (array);
/* Some dups to get more file descriptors and close one. */
dup (1);
dup (1);
fd = dup (1);
dup (1);
close (fd);
array = xget_all_open_fds ();
if (verbose)
print_open_fds (array);
for (count=n=0; array[n] != -1; n++)
count++;
if (count != initial_count+3)
{
fprintf (stderr, "%s:%d: dup or close failed\n",
__FILE__, __LINE__);
exit (1);
}
free (array);
/* Close the non standard ones. */
close_all_fds (3, NULL);
/* Get a list to check whether they are all closed. */
array = xget_all_open_fds ();
if (verbose)
print_open_fds (array);
for (count=n=0; array[n] != -1; n++)
count++;
if (count > initial_count)
{
fprintf (stderr, "%s:%d: not all files were closed\n",
__FILE__, __LINE__);
exit (1);
}
initial_count = count;
free (array);
/* Now let's check the realloc we use. We do this and the next
- tests only if we are allowed to open enought descriptors. */
+ tests only if we are allowed to open enough descriptors. */
if (get_max_fds () > 32)
{
int except[] = { 20, 23, 24, -1 };
for (n=initial_count; n < 31; n++)
dup (1);
array = xget_all_open_fds ();
if (verbose)
print_open_fds (array);
free (array);
for (n=0; n < 5; n++)
{
dup (1);
array = xget_all_open_fds ();
if (verbose)
print_open_fds (array);
free (array);
}
/* Check whether the except list works. */
close_all_fds (3, except);
array = xget_all_open_fds ();
if (verbose)
print_open_fds (array);
for (count=n=0; array[n] != -1; n++)
count++;
free (array);
if (count != initial_count + DIM(except)-1)
{
fprintf (stderr, "%s:%d: close_all_fds failed\n",
__FILE__, __LINE__);
exit (1);
}
}
}
int
main (int argc, char **argv)
{
if (argc)
{ argc--; argv++; }
if (argc && !strcmp (argv[0], "--verbose"))
{
verbose = 1;
argc--; argv++;
}
test_close_all_fds ();
return 0;
}
diff --git a/dirmngr/cdblib.c b/dirmngr/cdblib.c
index 827399f7e..c40126396 100644
--- a/dirmngr/cdblib.c
+++ b/dirmngr/cdblib.c
@@ -1,928 +1,928 @@
/* cdblib.c - all CDB library functions.
*
* This file is a part of tinycdb package by Michael Tokarev, mjt@corpit.ru.
* Public domain.
*
* Taken from tinycdb-0.73 and merged into one file for easier
* inclusion into Dirmngr. By Werner Koch 2003-12-12.
*/
/* A cdb database is a single file used to map 'keys' to 'values',
having records of (key,value) pairs. File consists of 3 parts: toc
(table of contents), data and index (hash tables).
Toc has fixed length of 2048 bytes, containing 256 pointers to hash
tables inside index sections. Every pointer consists of position
of a hash table in bytes from the beginning of a file, and a size
of a hash table in entries, both are 4-bytes (32 bits) unsigned
integers in little-endian form. Hash table length may have zero
length, meaning that corresponding hash table is empty.
Right after toc section, data section follows without any
- alingment. It consists of series of records, each is a key length,
+ alignment. It consists of series of records, each is a key length,
value (data) length, key and value. Again, key and value length
are 4-byte unsigned integers. Each next record follows previous
without any special alignment.
After data section, index (hash tables) section follows. It should
be looked to in conjunction with toc section, where each of max 256
hash tables are defined. Index section consists of series of hash
tables, with starting position and length defined in toc section.
Every hash table is a sequence of records each holds two numbers:
key's hash value and record position inside data section (bytes
from the beginning of a file to first byte of key length starting
data record). If record position is zero, then this is an empty
hash table slot, pointed to nowhere.
CDB hash function is
hv = ((hv << 5) + hv) ^ c
for every single c byte of a key, starting with hv = 5381.
Toc section indexed by (hv % 256), i.e. hash value modulo 256
(number of entries in toc section).
In order to find a record, one should: first, compute the hash
value (hv) of a key. Second, look to hash table number hv modulo
256. If it is empty, then there is no such key exists. If it is
not empty, then third, loop by slots inside that hash table,
starting from slot with number hv divided by 256 modulo length of
that table, or ((hv / 256) % htlen), searching for this hv in hash
table. Stop search on empty slot (if record position is zero) or
when all slots was probed (note cyclic search, jumping from end to
beginning of a table). When hash value in question is found in
hash table, look to key of corresponding record, comparing it with
key in question. If them of the same length and equals to each
- other, then record is found, overwise, repeat with next hash table
+ other, then record is found, otherwise, repeat with next hash table
slot. Note that there may be several records with the same key.
*/
#ifdef HAVE_CONFIG_H
#include
#endif
#include
#include
#include
#include
#include
#ifdef _WIN32
# include
#else
# include
# ifndef MAP_FAILED
# define MAP_FAILED ((void*)-1)
# endif
#endif
#include
#include "dirmngr-err.h"
#include "cdb.h"
#ifndef EPROTO
# define EPROTO EINVAL
#endif
#ifndef SEEK_SET
# define SEEK_SET 0
#endif
struct cdb_rec {
cdbi_t hval;
cdbi_t rpos;
};
struct cdb_rl {
struct cdb_rl *next;
cdbi_t cnt;
struct cdb_rec rec[254];
};
static int make_find(struct cdb_make *cdbmp,
const void *key, cdbi_t klen, cdbi_t hval,
struct cdb_rl **rlp);
static int make_write(struct cdb_make *cdbmp,
const char *ptr, cdbi_t len);
/* Initializes structure given by CDBP pointer and associates it with
the open file descriptor FD. Allocate memory for the structure
itself if needed and file open operation should be done by
application. File FD should be opened at least read-only, and
should be seekable. Routine returns 0 on success or negative value
on error. */
int
cdb_init(struct cdb *cdbp, int fd)
{
struct stat st;
unsigned char *mem;
#ifdef _WIN32
HANDLE hFile, hMapping;
#else
unsigned int fsize;
#endif
/* get file size */
if (fstat(fd, &st) < 0)
return -1;
/* trivial sanity check: at least toc should be here */
if (st.st_size < 2048) {
gpg_err_set_errno (EPROTO);
return -1;
}
/* memory-map file */
#ifdef _WIN32
# ifdef __MINGW32CE__
hFile = fd;
# else
hFile = (HANDLE) _get_osfhandle(fd);
# endif
if (hFile == (HANDLE) -1)
return -1;
hMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
if (!hMapping)
return -1;
mem = (unsigned char *)MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
if (!mem)
return -1;
cdbp->cdb_mapping = hMapping;
#else /*!_WIN32*/
fsize = (unsigned int)(st.st_size & 0xffffffffu);
mem = (unsigned char*)mmap(NULL, fsize, PROT_READ, MAP_SHARED, fd, 0);
if (mem == MAP_FAILED)
return -1;
#endif /*!_WIN32*/
cdbp->cdb_fd = fd;
cdbp->cdb_fsize = st.st_size;
cdbp->cdb_mem = mem;
#if 0
/* XXX don't know well about madvise syscall -- is it legal
to set different options for parts of one mmap() region?
There is also posix_madvise() exist, with POSIX_MADV_RANDOM etc...
*/
#ifdef MADV_RANDOM
/* set madvise() parameters. Ignore errors for now if system
doesn't support it */
madvise(mem, 2048, MADV_WILLNEED);
madvise(mem + 2048, cdbp->cdb_fsize - 2048, MADV_RANDOM);
#endif
#endif
cdbp->cdb_vpos = cdbp->cdb_vlen = 0;
return 0;
}
/* Frees the internal resources held by structure. Note that this
routine does not close the file. */
void
cdb_free(struct cdb *cdbp)
{
if (cdbp->cdb_mem) {
#ifdef _WIN32
UnmapViewOfFile ((void*) cdbp->cdb_mem);
CloseHandle (cdbp->cdb_mapping);
cdbp->cdb_mapping = NULL;
#else
munmap((void*)cdbp->cdb_mem, cdbp->cdb_fsize);
#endif /* _WIN32 */
cdbp->cdb_mem = NULL;
}
cdbp->cdb_fsize = 0;
}
/* Read data from cdb file, starting at position pos of length len,
placing result to buf. This routine may be used to get actual
value found by cdb_find() or other routines that returns position
and length of a data. Returns 0 on success or negative value on
error. */
int
cdb_read(const struct cdb *cdbp, void *buf, unsigned len, cdbi_t pos)
{
if (pos > cdbp->cdb_fsize || cdbp->cdb_fsize - pos < len) {
gpg_err_set_errno (EPROTO);
return -1;
}
memcpy(buf, cdbp->cdb_mem + pos, len);
return 0;
}
/* Attempts to find a key given by (key,klen) parameters. If key
exists in database, routine returns 1 and places position and
length of value associated with this key to internal fields inside
cdbp structure, to be accessible by cdb_datapos() and
cdb_datalen(). If key is not in database, routines returns 0. On
error, negative value is returned. Note that using cdb_find() it
is possible to lookup only first record with a given key. */
int
cdb_find(struct cdb *cdbp, const void *key, cdbi_t klen)
{
const unsigned char *htp; /* hash table pointer */
const unsigned char *htab; /* hash table */
const unsigned char *htend; /* end of hash table */
cdbi_t httodo; /* ht bytes left to look */
cdbi_t pos, n;
cdbi_t hval;
if (klen > cdbp->cdb_fsize) /* if key size is larger than file */
return 0;
hval = cdb_hash(key, klen);
/* find (pos,n) hash table to use */
/* first 2048 bytes (toc) are always available */
/* (hval % 256) * 8 */
htp = cdbp->cdb_mem + ((hval << 3) & 2047); /* index in toc (256x8) */
n = cdb_unpack(htp + 4); /* table size */
if (!n) /* empty table */
return 0; /* not found */
httodo = n << 3; /* bytes of htab to lookup */
pos = cdb_unpack(htp); /* htab position */
if (n > (cdbp->cdb_fsize >> 3) /* overflow of httodo ? */
|| pos > cdbp->cdb_fsize /* htab start within file ? */
- || httodo > cdbp->cdb_fsize - pos) /* entrie htab within file ? */
+ || httodo > cdbp->cdb_fsize - pos) /* htab entry within file ? */
{
gpg_err_set_errno (EPROTO);
return -1;
}
htab = cdbp->cdb_mem + pos; /* htab pointer */
htend = htab + httodo; /* after end of htab */
/* htab starting position: rest of hval modulo htsize, 8bytes per elt */
htp = htab + (((hval >> 8) % n) << 3);
for(;;) {
pos = cdb_unpack(htp + 4); /* record position */
if (!pos)
return 0;
if (cdb_unpack(htp) == hval) {
if (pos > cdbp->cdb_fsize - 8) { /* key+val lengths */
gpg_err_set_errno (EPROTO);
return -1;
}
if (cdb_unpack(cdbp->cdb_mem + pos) == klen) {
if (cdbp->cdb_fsize - klen < pos + 8) {
gpg_err_set_errno (EPROTO);
return -1;
}
if (memcmp(key, cdbp->cdb_mem + pos + 8, klen) == 0) {
n = cdb_unpack(cdbp->cdb_mem + pos + 4);
pos += 8 + klen;
if (cdbp->cdb_fsize < n || cdbp->cdb_fsize - n < pos) {
gpg_err_set_errno (EPROTO);
return -1;
}
cdbp->cdb_vpos = pos;
cdbp->cdb_vlen = n;
return 1;
}
}
}
httodo -= 8;
if (!httodo)
return 0;
if ((htp += 8) >= htend)
htp = htab;
}
}
/* Sequential-find routines that used separate structure. It is
possible to have many than one record with the same key in a
database, and these routines allow enumeration of all of them.
cdb_findinit() initializes search structure pointed to by cdbfp.
It will return negative value on error or 0 on success.
cdb_findnext() attempts to find next matching key, setting value
position and length in cdbfp structure. It will return positive
value if given key was found, 0 if there is no more such key(s), or
negative value on error. To access value position and length after
successeful call to cdb_findnext() (when it returned positive
result), use cdb_datapos() and cdb_datalen() macros with cdbp
pointer. It is error to use cdb_findnext() after it returned 0 or
error condition. These routines is a bit slower than cdb_find().
Setting KEY to NULL will start a sequential search through the
entire DB.
*/
int
cdb_findinit(struct cdb_find *cdbfp, struct cdb *cdbp,
const void *key, cdbi_t klen)
{
cdbi_t n, pos;
cdbfp->cdb_cdbp = cdbp;
cdbfp->cdb_key = key;
cdbfp->cdb_klen = klen;
cdbfp->cdb_hval = key? cdb_hash(key, klen) : 0;
if (key)
{
cdbfp->cdb_htp = cdbp->cdb_mem + ((cdbfp->cdb_hval << 3) & 2047);
n = cdb_unpack(cdbfp->cdb_htp + 4);
cdbfp->cdb_httodo = n << 3; /* Set to size of hash table. */
if (!n)
return 0; /* The hash table is empry. */
pos = cdb_unpack(cdbfp->cdb_htp);
if (n > (cdbp->cdb_fsize >> 3)
|| pos > cdbp->cdb_fsize
|| cdbfp->cdb_httodo > cdbp->cdb_fsize - pos)
{
gpg_err_set_errno (EPROTO);
return -1;
}
cdbfp->cdb_htab = cdbp->cdb_mem + pos;
cdbfp->cdb_htend = cdbfp->cdb_htab + cdbfp->cdb_httodo;
cdbfp->cdb_htp = cdbfp->cdb_htab + (((cdbfp->cdb_hval >> 8) % n) << 3);
}
else /* Walk over all entries. */
{
cdbfp->cdb_hval = 0;
/* Force stepping in findnext. */
cdbfp->cdb_htp = cdbfp->cdb_htend = cdbp->cdb_mem;
}
return 0;
}
/* See cdb_findinit. */
int
cdb_findnext(struct cdb_find *cdbfp)
{
cdbi_t pos, n;
struct cdb *cdbp = cdbfp->cdb_cdbp;
if (cdbfp->cdb_key)
{
while(cdbfp->cdb_httodo) {
pos = cdb_unpack(cdbfp->cdb_htp + 4);
if (!pos)
return 0;
n = cdb_unpack(cdbfp->cdb_htp) == cdbfp->cdb_hval;
if ((cdbfp->cdb_htp += 8) >= cdbfp->cdb_htend)
cdbfp->cdb_htp = cdbfp->cdb_htab;
cdbfp->cdb_httodo -= 8;
if (n) {
if (pos > cdbp->cdb_fsize - 8) {
gpg_err_set_errno (EPROTO);
return -1;
}
if (cdb_unpack(cdbp->cdb_mem + pos) == cdbfp->cdb_klen) {
if (cdbp->cdb_fsize - cdbfp->cdb_klen < pos + 8) {
gpg_err_set_errno (EPROTO);
return -1;
}
if (memcmp(cdbfp->cdb_key,
cdbp->cdb_mem + pos + 8, cdbfp->cdb_klen) == 0) {
n = cdb_unpack(cdbp->cdb_mem + pos + 4);
pos += 8 + cdbfp->cdb_klen;
if (cdbp->cdb_fsize < n || cdbp->cdb_fsize - n < pos) {
gpg_err_set_errno (EPROTO);
return -1;
}
cdbp->cdb_vpos = pos;
cdbp->cdb_vlen = n;
return 1;
}
}
}
}
}
else /* Walk over all entries. */
{
do
{
while (cdbfp->cdb_htp >= cdbfp->cdb_htend)
{
if (cdbfp->cdb_hval > 255)
return 0; /* No more items. */
cdbfp->cdb_htp = cdbp->cdb_mem + cdbfp->cdb_hval * 8;
cdbfp->cdb_hval++; /* Advance for next round. */
pos = cdb_unpack (cdbfp->cdb_htp); /* Offset of table. */
n = cdb_unpack (cdbfp->cdb_htp + 4); /* Number of entries. */
cdbfp->cdb_httodo = n * 8; /* Size of table. */
if (n > (cdbp->cdb_fsize / 8)
|| pos > cdbp->cdb_fsize
|| cdbfp->cdb_httodo > cdbp->cdb_fsize - pos)
{
gpg_err_set_errno (EPROTO);
return -1;
}
cdbfp->cdb_htab = cdbp->cdb_mem + pos;
cdbfp->cdb_htend = cdbfp->cdb_htab + cdbfp->cdb_httodo;
cdbfp->cdb_htp = cdbfp->cdb_htab;
}
pos = cdb_unpack (cdbfp->cdb_htp + 4); /* Offset of record. */
cdbfp->cdb_htp += 8;
}
while (!pos);
if (pos > cdbp->cdb_fsize - 8)
{
gpg_err_set_errno (EPROTO);
return -1;
}
cdbp->cdb_kpos = pos + 8;
cdbp->cdb_klen = cdb_unpack(cdbp->cdb_mem + pos);
cdbp->cdb_vpos = pos + 8 + cdbp->cdb_klen;
cdbp->cdb_vlen = cdb_unpack(cdbp->cdb_mem + pos + 4);
n = 8 + cdbp->cdb_klen + cdbp->cdb_vlen;
if ( pos > cdbp->cdb_fsize || pos > cdbp->cdb_fsize - n)
{
gpg_err_set_errno (EPROTO);
return -1;
}
return 1; /* Found. */
}
return 0;
}
/* Read a chunk from file, ignoring interrupts (EINTR) */
int
cdb_bread(int fd, void *buf, int len)
{
int l;
while(len > 0) {
do l = read(fd, buf, len);
while(l < 0 && errno == EINTR);
if (l <= 0) {
if (!l)
gpg_err_set_errno (EIO);
return -1;
}
buf = (char*)buf + l;
len -= l;
}
return 0;
}
/* Find a given key in cdb file, seek a file pointer to it's value and
place data length to *dlenp. */
int
cdb_seek(int fd, const void *key, unsigned klen, cdbi_t *dlenp)
{
cdbi_t htstart; /* hash table start position */
cdbi_t htsize; /* number of elements in a hash table */
cdbi_t httodo; /* hash table elements left to look */
cdbi_t hti; /* hash table index */
cdbi_t pos; /* position in a file */
cdbi_t hval; /* key's hash value */
unsigned char rbuf[64]; /* read buffer */
int needseek = 1; /* if we should seek to a hash slot */
hval = cdb_hash(key, klen);
pos = (hval & 0xff) << 3; /* position in TOC */
/* read the hash table parameters */
if (lseek(fd, pos, SEEK_SET) < 0 || cdb_bread(fd, rbuf, 8) < 0)
return -1;
if ((htsize = cdb_unpack(rbuf + 4)) == 0)
return 0;
hti = (hval >> 8) % htsize; /* start position in hash table */
httodo = htsize;
htstart = cdb_unpack(rbuf);
for(;;) {
if (needseek && lseek(fd, htstart + (hti << 3), SEEK_SET) < 0)
return -1;
if (cdb_bread(fd, rbuf, 8) < 0)
return -1;
if ((pos = cdb_unpack(rbuf + 4)) == 0) /* not found */
return 0;
if (cdb_unpack(rbuf) != hval) /* hash value not matched */
needseek = 0;
else { /* hash value matched */
if (lseek(fd, pos, SEEK_SET) < 0 || cdb_bread(fd, rbuf, 8) < 0)
return -1;
if (cdb_unpack(rbuf) == klen) { /* key length matches */
/* read the key from file and compare with wanted */
cdbi_t l = klen, c;
const char *k = (const char*)key;
if (*dlenp)
*dlenp = cdb_unpack(rbuf + 4); /* save value length */
for(;;) {
if (!l) /* the whole key read and matches, return */
return 1;
c = l > sizeof(rbuf) ? sizeof(rbuf) : l;
if (cdb_bread(fd, rbuf, c) < 0)
return -1;
if (memcmp(rbuf, k, c) != 0) /* no, it differs, stop here */
break;
k += c; l -= c;
}
}
needseek = 1; /* we're looked to other place, should seek back */
}
if (!--httodo)
return 0;
if (++hti == htsize) {
hti = htstart;
needseek = 1;
}
}
}
cdbi_t
cdb_unpack(const unsigned char buf[4])
{
cdbi_t n = buf[3];
n <<= 8; n |= buf[2];
n <<= 8; n |= buf[1];
n <<= 8; n |= buf[0];
return n;
}
/* Add record with key (KEY,KLEN) and value (VAL,VLEN) to a database.
Returns 0 on success or negative value on error. Note that this
routine does not checks if given key already exists, but cdb_find()
will not see second record with the same key. It is not possible
to continue building a database if cdb_make_add() returned an error
indicator. */
int
cdb_make_add(struct cdb_make *cdbmp,
const void *key, cdbi_t klen,
const void *val, cdbi_t vlen)
{
unsigned char rlen[8];
cdbi_t hval;
struct cdb_rl *rl;
if (klen > 0xffffffff - (cdbmp->cdb_dpos + 8) ||
vlen > 0xffffffff - (cdbmp->cdb_dpos + klen + 8)) {
gpg_err_set_errno (ENOMEM);
return -1;
}
hval = cdb_hash(key, klen);
rl = cdbmp->cdb_rec[hval&255];
if (!rl || rl->cnt >= sizeof(rl->rec)/sizeof(rl->rec[0])) {
rl = (struct cdb_rl*)malloc(sizeof(struct cdb_rl));
if (!rl) {
gpg_err_set_errno (ENOMEM);
return -1;
}
rl->cnt = 0;
rl->next = cdbmp->cdb_rec[hval&255];
cdbmp->cdb_rec[hval&255] = rl;
}
rl->rec[rl->cnt].hval = hval;
rl->rec[rl->cnt].rpos = cdbmp->cdb_dpos;
++rl->cnt;
++cdbmp->cdb_rcnt;
cdb_pack(klen, rlen);
cdb_pack(vlen, rlen + 4);
if (make_write(cdbmp, rlen, 8) < 0 ||
make_write(cdbmp, key, klen) < 0 ||
make_write(cdbmp, val, vlen) < 0)
return -1;
return 0;
}
int
cdb_make_put(struct cdb_make *cdbmp,
const void *key, cdbi_t klen,
const void *val, cdbi_t vlen,
int flags)
{
unsigned char rlen[8];
cdbi_t hval = cdb_hash(key, klen);
struct cdb_rl *rl;
int c, r;
switch(flags) {
case CDB_PUT_REPLACE:
case CDB_PUT_INSERT:
case CDB_PUT_WARN:
c = make_find(cdbmp, key, klen, hval, &rl);
if (c < 0)
return -1;
if (c) {
if (flags == CDB_PUT_INSERT) {
gpg_err_set_errno (EEXIST);
return 1;
}
else if (flags == CDB_PUT_REPLACE) {
--c;
r = 1;
break;
}
else
r = 1;
}
/* fall through */
case CDB_PUT_ADD:
rl = cdbmp->cdb_rec[hval&255];
if (!rl || rl->cnt >= sizeof(rl->rec)/sizeof(rl->rec[0])) {
rl = (struct cdb_rl*)malloc(sizeof(struct cdb_rl));
if (!rl) {
gpg_err_set_errno (ENOMEM);
return -1;
}
rl->cnt = 0;
rl->next = cdbmp->cdb_rec[hval&255];
cdbmp->cdb_rec[hval&255] = rl;
}
c = rl->cnt;
r = 0;
break;
default:
gpg_err_set_errno (EINVAL);
return -1;
}
if (klen > 0xffffffff - (cdbmp->cdb_dpos + 8) ||
vlen > 0xffffffff - (cdbmp->cdb_dpos + klen + 8)) {
gpg_err_set_errno (ENOMEM);
return -1;
}
rl->rec[c].hval = hval;
rl->rec[c].rpos = cdbmp->cdb_dpos;
if (c == rl->cnt) {
++rl->cnt;
++cdbmp->cdb_rcnt;
}
cdb_pack(klen, rlen);
cdb_pack(vlen, rlen + 4);
if (make_write(cdbmp, rlen, 8) < 0 ||
make_write(cdbmp, key, klen) < 0 ||
make_write(cdbmp, val, vlen) < 0)
return -1;
return r;
}
static int
match(int fd, cdbi_t pos, const char *key, cdbi_t klen)
{
unsigned char buf[64]; /*XXX cdb_buf may be used here instead */
if (lseek(fd, pos, SEEK_SET) < 0 || read(fd, buf, 8) != 8)
return -1;
if (cdb_unpack(buf) != klen)
return 0;
while(klen > sizeof(buf)) {
if (read(fd, buf, sizeof(buf)) != sizeof(buf))
return -1;
if (memcmp(buf, key, sizeof(buf)) != 0)
return 0;
key += sizeof(buf);
klen -= sizeof(buf);
}
if (klen) {
if (read(fd, buf, klen) != klen)
return -1;
if (memcmp(buf, key, klen) != 0)
return 0;
}
return 1;
}
static int
make_find (struct cdb_make *cdbmp,
const void *key, cdbi_t klen, cdbi_t hval,
struct cdb_rl **rlp)
{
struct cdb_rl *rl = cdbmp->cdb_rec[hval&255];
int r, i;
int sought = 0;
while(rl) {
for(i = rl->cnt - 1; i >= 0; --i) { /* search backward */
if (rl->rec[i].hval != hval)
continue;
/*XXX this explicit flush may be unnecessary having
* smarter match() that looks to cdb_buf too, but
* most of a time here spent in finding hash values
* (above), not keys */
if (cdbmp->cdb_bpos != cdbmp->cdb_buf) {
if (write(cdbmp->cdb_fd, cdbmp->cdb_buf,
cdbmp->cdb_bpos - cdbmp->cdb_buf) < 0)
return -1;
cdbmp->cdb_bpos = cdbmp->cdb_buf;
}
sought = 1;
r = match(cdbmp->cdb_fd, rl->rec[i].rpos, key, klen);
if (!r)
continue;
if (r < 0)
return -1;
if (lseek(cdbmp->cdb_fd, cdbmp->cdb_dpos, SEEK_SET) < 0)
return -1;
if (rlp)
*rlp = rl;
return i + 1;
}
rl = rl->next;
}
if (sought && lseek(cdbmp->cdb_fd, cdbmp->cdb_dpos, SEEK_SET) < 0)
return -1;
return 0;
}
int
cdb_make_exists(struct cdb_make *cdbmp,
const void *key, cdbi_t klen)
{
return make_find(cdbmp, key, klen, cdb_hash(key, klen), NULL);
}
void
cdb_pack(cdbi_t num, unsigned char buf[4])
{
buf[0] = num & 255; num >>= 8;
buf[1] = num & 255; num >>= 8;
buf[2] = num & 255;
buf[3] = num >> 8;
}
/* Initializes structure to create a database. File FD should be
opened read-write and should be seekable. Returns 0 on success or
negative value on error. */
int
cdb_make_start(struct cdb_make *cdbmp, int fd)
{
memset (cdbmp, 0, sizeof *cdbmp);
cdbmp->cdb_fd = fd;
cdbmp->cdb_dpos = 2048;
cdbmp->cdb_bpos = cdbmp->cdb_buf + 2048;
return 0;
}
static int
ewrite(int fd, const char *buf, int len)
{
while(len) {
int l = write(fd, buf, len);
if (l < 0 && errno != EINTR)
return -1;
if (l > 0)
{
len -= l;
buf += l;
}
}
return 0;
}
static int
make_write(struct cdb_make *cdbmp, const char *ptr, cdbi_t len)
{
cdbi_t l = sizeof(cdbmp->cdb_buf) - (cdbmp->cdb_bpos - cdbmp->cdb_buf);
cdbmp->cdb_dpos += len;
if (len > l) {
memcpy(cdbmp->cdb_bpos, ptr, l);
if (ewrite(cdbmp->cdb_fd, cdbmp->cdb_buf, sizeof(cdbmp->cdb_buf)) < 0)
return -1;
ptr += l; len -= l;
l = len / sizeof(cdbmp->cdb_buf);
if (l) {
l *= sizeof(cdbmp->cdb_buf);
if (ewrite(cdbmp->cdb_fd, ptr, l) < 0)
return -1;
ptr += l; len -= l;
}
cdbmp->cdb_bpos = cdbmp->cdb_buf;
}
if (len) {
memcpy(cdbmp->cdb_bpos, ptr, len);
cdbmp->cdb_bpos += len;
}
return 0;
}
static int
cdb_make_finish_internal(struct cdb_make *cdbmp)
{
cdbi_t hcnt[256]; /* hash table counts */
cdbi_t hpos[256]; /* hash table positions */
struct cdb_rec *htab;
unsigned char *p;
struct cdb_rl *rl;
cdbi_t hsize;
unsigned t, i;
if (((0xffffffff - cdbmp->cdb_dpos) >> 3) < cdbmp->cdb_rcnt) {
gpg_err_set_errno (ENOMEM);
return -1;
}
/* count htab sizes and reorder reclists */
hsize = 0;
for (t = 0; t < 256; ++t) {
struct cdb_rl *rlt = NULL;
i = 0;
rl = cdbmp->cdb_rec[t];
while(rl) {
struct cdb_rl *rln = rl->next;
rl->next = rlt;
rlt = rl;
i += rl->cnt;
rl = rln;
}
cdbmp->cdb_rec[t] = rlt;
if (hsize < (hcnt[t] = i << 1))
hsize = hcnt[t];
}
/* allocate memory to hold max htable */
htab = (struct cdb_rec*)malloc((hsize + 2) * sizeof(struct cdb_rec));
if (!htab) {
gpg_err_set_errno (ENOENT);
return -1;
}
p = (unsigned char *)htab;
htab += 2;
/* build hash tables */
for (t = 0; t < 256; ++t) {
cdbi_t len, hi;
hpos[t] = cdbmp->cdb_dpos;
if ((len = hcnt[t]) == 0)
continue;
for (i = 0; i < len; ++i)
htab[i].hval = htab[i].rpos = 0;
for (rl = cdbmp->cdb_rec[t]; rl; rl = rl->next)
for (i = 0; i < rl->cnt; ++i) {
hi = (rl->rec[i].hval >> 8) % len;
while(htab[hi].rpos)
if (++hi == len)
hi = 0;
htab[hi] = rl->rec[i];
}
for (i = 0; i < len; ++i) {
cdb_pack(htab[i].hval, p + (i << 3));
cdb_pack(htab[i].rpos, p + (i << 3) + 4);
}
if (make_write(cdbmp, p, len << 3) < 0) {
free(p);
return -1;
}
}
free(p);
if (cdbmp->cdb_bpos != cdbmp->cdb_buf &&
ewrite(cdbmp->cdb_fd, cdbmp->cdb_buf,
cdbmp->cdb_bpos - cdbmp->cdb_buf) != 0)
return -1;
p = cdbmp->cdb_buf;
for (t = 0; t < 256; ++t) {
cdb_pack(hpos[t], p + (t << 3));
cdb_pack(hcnt[t], p + (t << 3) + 4);
}
if (lseek(cdbmp->cdb_fd, 0, 0) != 0 ||
ewrite(cdbmp->cdb_fd, p, 2048) != 0)
return -1;
return 0;
}
static void
cdb_make_free(struct cdb_make *cdbmp)
{
unsigned t;
for(t = 0; t < 256; ++t) {
struct cdb_rl *rl = cdbmp->cdb_rec[t];
while(rl) {
struct cdb_rl *tm = rl;
rl = rl->next;
free(tm);
}
}
}
/* Finalizes database file, constructing all needed indexes, and frees
memory structures. It does not close the file descriptor. Returns
0 on success or a negative value on error. */
int
cdb_make_finish(struct cdb_make *cdbmp)
{
int r = cdb_make_finish_internal(cdbmp);
cdb_make_free(cdbmp);
return r;
}
cdbi_t
cdb_hash(const void *buf, cdbi_t len)
{
register const unsigned char *p = (const unsigned char *)buf;
register const unsigned char *end = p + len;
register cdbi_t hash = 5381; /* start value */
while (p < end)
hash = (hash + (hash << 5)) ^ *p++;
return hash;
}
diff --git a/dirmngr/crlcache.c b/dirmngr/crlcache.c
index fbe3beea1..a2867be54 100644
--- a/dirmngr/crlcache.c
+++ b/dirmngr/crlcache.c
@@ -1,2589 +1,2589 @@
/* crlcache.c - LDAP access
* Copyright (C) 2002 Klarälvdalens Datakonsult AB
* Copyright (C) 2003, 2004, 2005, 2008 g10 Code GmbH
*
* This file is part of DirMngr.
*
* DirMngr 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 2 of the License, or
* (at your option) any later version.
*
* DirMngr 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 .
*/
/*
1. To keep track of the CRLs actually cached and to store the meta
information of the CRLs a simple record oriented text file is
used. Fields in the file are colon (':') separated and values
containing colons or linefeeds are percent escaped (e.g. a colon
itself is represented as "%3A").
The first field is a record type identifier, so that the file is
useful to keep track of other meta data too.
The name of the file is "DIR.txt".
1.1. Comment record
Field 1: Constant beginning with "#".
Other fields are not defined and such a record is simply
skipped during processing.
1.2. Version record
Field 1: Constant "v"
Field 2: Version number of this file. Must be 1.
This record must be the first non-comment record and
there shall only exist one record of this type.
1.3. CRL cache record
Field 1: Constant "c", "u" or "i".
A "c" or "u" indicate a valid cache entry, however
"u" requires that a user root certificate check needs
to be done.
An "i" indicates an invalid cache entry which should
not be used but still exists so that it can be
updated at NEXT_UPDATE.
Field 2: Hexadecimal encoded SHA-1 hash of the issuer DN using
uppercase letters.
Field 3: Issuer DN in RFC-2253 notation.
Field 4: URL used to retrieve the corresponding CRL.
Field 5: 15 character ISO timestamp with THIS_UPDATE.
Field 6: 15 character ISO timestamp with NEXT_UPDATE.
Field 7: Hexadecimal encoded MD-5 hash of the DB file to detect
accidental modified (i.e. deleted and created) cache files.
Field 8: optional CRL number as a hex string.
Field 9: AuthorityKeyID.issuer, each Name separated by 0x01
Field 10: AuthorityKeyID.serial
Field 11: Hex fingerprint of trust anchor if field 1 is 'u'.
2. Layout of the standard CRL Cache DB file:
We use records of variable length with this structure
n bytes Serialnumber (binary) used as key
thus there is no need to store the length explicitly with DB2.
1 byte Reason for revocation
(currently the KSBA reason flags are used)
15 bytes ISO date of revocation (e.g. 19980815T142000)
Note that there is no terminating 0 stored.
The filename used is the hexadecimal (using uppercase letters)
SHA-1 hash value of the issuer DN prefixed with a "crl-" and
suffixed with a ".db". Thus the length of the filename is 47.
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#ifndef HAVE_W32_SYSTEM
#include
#endif
#ifdef MKDIR_TAKES_ONE_ARG
#undef mkdir
#define mkdir(a,b) mkdir(a)
#endif
#include "dirmngr.h"
#include "validate.h"
#include "certcache.h"
#include "crlcache.h"
#include "crlfetch.h"
#include "misc.h"
#include "cdb.h"
/* Change this whenever the format changes */
#define DBDIR_D "crls.d"
#define DBDIRFILE "DIR.txt"
#define DBDIRVERSION 1
/* The number of DB files we may have open at one time. We need to
limit this because there is no guarantee that the number of issuers
has a upper limit. We are currently using mmap, so it is a good
idea anyway to limit the number of opened cache files. */
#define MAX_OPEN_DB_FILES 5
#ifndef O_BINARY
# define O_BINARY 0
#endif
static const char oidstr_crlNumber[] = "2.5.29.20";
/* static const char oidstr_issuingDistributionPoint[] = "2.5.29.28"; */
static const char oidstr_authorityKeyIdentifier[] = "2.5.29.35";
/* Definition of one cached item. */
struct crl_cache_entry_s
{
struct crl_cache_entry_s *next;
int deleted; /* True if marked for deletion. */
int mark; /* Internally used by update_dir. */
unsigned int lineno;/* A 0 indicates a new entry. */
char *release_ptr; /* The actual allocated memory. */
char *url; /* Points into RELEASE_PTR. */
char *issuer; /* Ditto. */
char *issuer_hash; /* Ditto. */
char *dbfile_hash; /* MD5 sum of the cache file, points into RELEASE_PTR.*/
int invalid; /* Can't use this CRL. */
int user_trust_req; /* User supplied root certificate required. */
char *check_trust_anchor; /* Malloced fingerprint. */
ksba_isotime_t this_update;
ksba_isotime_t next_update;
ksba_isotime_t last_refresh; /* Use for the force_crl_refresh feature. */
char *crl_number;
char *authority_issuer;
char *authority_serialno;
struct cdb *cdb; /* The cache file handle or NULL if not open. */
unsigned int cdb_use_count; /* Current use count. */
unsigned int cdb_lru_count; /* Used for LRU purposes. */
int dbfile_checked; /* Set to true if the dbfile_hash value has
been checked one. */
};
/* Definition of the entire cache object. */
struct crl_cache_s
{
crl_cache_entry_t entries;
};
typedef struct crl_cache_s *crl_cache_t;
/* Prototypes. */
static crl_cache_entry_t find_entry (crl_cache_entry_t first,
const char *issuer_hash);
/* The currently loaded cache object. This is usually initialized
right at startup. */
static crl_cache_t current_cache;
/* Return the current cache object or bail out if it is has not yet
been initialized. */
static crl_cache_t
get_current_cache (void)
{
if (!current_cache)
log_fatal ("CRL cache has not yet been initialized\n");
return current_cache;
}
/*
Create ae directory if it does not yet exists. Returns on
success, or -1 on error.
*/
static int
create_directory_if_needed (const char *name)
{
DIR *dir;
char *fname;
fname = make_filename (opt.homedir_cache, name, NULL);
dir = opendir (fname);
if (!dir)
{
log_info (_("creating directory '%s'\n"), fname);
if (mkdir (fname, S_IRUSR|S_IWUSR|S_IXUSR) )
{
int save_errno = errno;
log_error (_("error creating directory '%s': %s\n"),
fname, strerror (errno));
xfree (fname);
gpg_err_set_errno (save_errno);
return -1;
}
}
else
closedir (dir);
xfree (fname);
return 0;
}
/* Remove all files from the cache directory. If FORCE is not true,
some sanity checks on the filenames are done. Return 0 if
everything went fine. */
static int
cleanup_cache_dir (int force)
{
char *dname = make_filename (opt.homedir_cache, DBDIR_D, NULL);
DIR *dir;
struct dirent *de;
int problem = 0;
if (!force)
{ /* Very minor sanity checks. */
if (!strcmp (dname, "~/") || !strcmp (dname, "/" ))
{
log_error (_("ignoring database dir '%s'\n"), dname);
xfree (dname);
return -1;
}
}
dir = opendir (dname);
if (!dir)
{
log_error (_("error reading directory '%s': %s\n"),
dname, strerror (errno));
xfree (dname);
return -1;
}
while ((de = readdir (dir)))
{
if (strcmp (de->d_name, "." ) && strcmp (de->d_name, ".."))
{
char *cdbname = make_filename (dname, de->d_name, NULL);
int okay;
struct stat sbuf;
if (force)
okay = 1;
else
okay = (!stat (cdbname, &sbuf) && S_ISREG (sbuf.st_mode));
if (okay)
{
log_info (_("removing cache file '%s'\n"), cdbname);
if (gnupg_remove (cdbname))
{
log_error ("failed to remove '%s': %s\n",
cdbname, strerror (errno));
problem = -1;
}
}
else
log_info (_("not removing file '%s'\n"), cdbname);
xfree (cdbname);
}
}
xfree (dname);
closedir (dir);
return problem;
}
/* Read the next line from the file FP and return the line in an
malloced buffer. Return NULL on error or EOF. There is no
limitation os the line length. The trailing linefeed has been
removed, the function will read the last line of a file, even if
that is not terminated by a LF. */
static char *
next_line_from_file (estream_t fp, gpg_error_t *r_err)
{
char buf[300];
char *largebuf = NULL;
size_t buflen;
size_t len = 0;
unsigned char *p;
int c;
char *tmpbuf;
*r_err = 0;
p = buf;
buflen = sizeof buf - 1;
while ((c=es_getc (fp)) != EOF && c != '\n')
{
if (len >= buflen)
{
if (!largebuf)
{
buflen += 1024;
largebuf = xtrymalloc ( buflen + 1 );
if (!largebuf)
{
*r_err = gpg_error_from_syserror ();
return NULL;
}
memcpy (largebuf, buf, len);
}
else
{
buflen += 1024;
tmpbuf = xtryrealloc (largebuf, buflen + 1);
if (!tmpbuf)
{
*r_err = gpg_error_from_syserror ();
xfree (largebuf);
return NULL;
}
largebuf = tmpbuf;
}
p = largebuf;
}
p[len++] = c;
}
if (c == EOF && !len)
return NULL;
p[len] = 0;
if (largebuf)
tmpbuf = xtryrealloc (largebuf, len+1);
else
tmpbuf = xtrystrdup (buf);
if (!tmpbuf)
{
*r_err = gpg_error_from_syserror ();
xfree (largebuf);
}
return tmpbuf;
}
/* Release one cache entry. */
static void
release_one_cache_entry (crl_cache_entry_t entry)
{
if (entry)
{
if (entry->cdb)
{
int fd = cdb_fileno (entry->cdb);
cdb_free (entry->cdb);
xfree (entry->cdb);
if (close (fd))
log_error (_("error closing cache file: %s\n"), strerror(errno));
}
xfree (entry->release_ptr);
xfree (entry->check_trust_anchor);
xfree (entry);
}
}
/* Release the CACHE object. */
static void
release_cache (crl_cache_t cache)
{
crl_cache_entry_t entry, entry2;
if (!cache)
return;
for (entry = cache->entries; entry; entry = entry2)
{
entry2 = entry->next;
release_one_cache_entry (entry);
}
cache->entries = NULL;
xfree (cache);
}
/* Open the dir file FNAME or create a new one if it does not yet
exist. */
static estream_t
open_dir_file (const char *fname)
{
estream_t fp;
fp = es_fopen (fname, "r");
if (!fp)
{
log_error (_("failed to open cache dir file '%s': %s\n"),
fname, strerror (errno));
/* Make sure that the directory exists, try to create if otherwise. */
if (create_directory_if_needed (NULL)
|| create_directory_if_needed (DBDIR_D))
return NULL;
fp = es_fopen (fname, "w");
if (!fp)
{
log_error (_("error creating new cache dir file '%s': %s\n"),
fname, strerror (errno));
return NULL;
}
es_fprintf (fp, "v:%d:\n", DBDIRVERSION);
if (es_ferror (fp))
{
log_error (_("error writing new cache dir file '%s': %s\n"),
fname, strerror (errno));
es_fclose (fp);
return NULL;
}
if (es_fclose (fp))
{
log_error (_("error closing new cache dir file '%s': %s\n"),
fname, strerror (errno));
return NULL;
}
log_info (_("new cache dir file '%s' created\n"), fname);
fp = es_fopen (fname, "r");
if (!fp)
{
log_error (_("failed to re-open cache dir file '%s': %s\n"),
fname, strerror (errno));
return NULL;
}
}
return fp;
}
/* Helper for open_dir. */
static gpg_error_t
check_dir_version (estream_t *fpadr, const char *fname,
unsigned int *lineno,
int cleanup_on_mismatch)
{
char *line;
gpg_error_t lineerr = 0;
estream_t fp = *fpadr;
int created = 0;
retry:
while ((line = next_line_from_file (fp, &lineerr)))
{
++*lineno;
if (*line == 'v' && line[1] == ':')
break;
else if (*line != '#')
{
log_error (_("first record of '%s' is not the version\n"), fname);
xfree (line);
return gpg_error (GPG_ERR_CONFIGURATION);
}
xfree (line);
}
if (lineerr)
return lineerr;
/* The !line catches the case of an empty DIR file. We handle this
the same as a non-matching version. */
if (!line || strtol (line+2, NULL, 10) != DBDIRVERSION)
{
if (!created && cleanup_on_mismatch)
{
log_error (_("old version of cache directory - cleaning up\n"));
es_fclose (fp);
*fpadr = NULL;
if (!cleanup_cache_dir (1))
{
*lineno = 0;
fp = *fpadr = open_dir_file (fname);
if (!fp)
{
xfree (line);
return gpg_error (GPG_ERR_CONFIGURATION);
}
created = 1;
goto retry;
}
}
log_error (_("old version of cache directory - giving up\n"));
xfree (line);
return gpg_error (GPG_ERR_CONFIGURATION);
}
xfree (line);
return 0;
}
/* Open the dir file and read in all available information. Store
that in a newly allocated cache object and return that if
everything worked out fine. Create the cache directory and the dir
if it does not yet exist. Remove all files in that directory if
the version does not match. */
static gpg_error_t
open_dir (crl_cache_t *r_cache)
{
crl_cache_t cache;
char *fname;
char *line = NULL;
gpg_error_t lineerr = 0;
estream_t fp;
crl_cache_entry_t entry, *entrytail;
unsigned int lineno;
gpg_error_t err = 0;
int anyerr = 0;
cache = xtrycalloc (1, sizeof *cache);
if (!cache)
return gpg_error_from_syserror ();
fname = make_filename (opt.homedir_cache, DBDIR_D, DBDIRFILE, NULL);
lineno = 0;
fp = open_dir_file (fname);
if (!fp)
{
err = gpg_error (GPG_ERR_CONFIGURATION);
goto leave;
}
err = check_dir_version (&fp, fname, &lineno, 1);
if (err)
goto leave;
/* Read in all supported entries from the dir file. */
cache->entries = NULL;
entrytail = &cache->entries;
xfree (line);
while ((line = next_line_from_file (fp, &lineerr)))
{
int fieldno;
char *p, *endp;
lineno++;
if ( *line == 'c' || *line == 'u' || *line == 'i' )
{
entry = xtrycalloc (1, sizeof *entry);
if (!entry)
{
err = gpg_error_from_syserror ();
goto leave;
}
entry->lineno = lineno;
entry->release_ptr = line;
if (*line == 'i')
{
entry->invalid = atoi (line+1);
if (entry->invalid < 1)
entry->invalid = 1;
}
else if (*line == 'u')
entry->user_trust_req = 1;
for (fieldno=1, p = line; p; p = endp, fieldno++)
{
endp = strchr (p, ':');
if (endp)
*endp++ = '\0';
switch (fieldno)
{
case 1: /* record type */ break;
case 2: entry->issuer_hash = p; break;
case 3: entry->issuer = unpercent_string (p); break;
case 4: entry->url = unpercent_string (p); break;
case 5:
strncpy (entry->this_update, p, 15);
entry->this_update[15] = 0;
break;
case 6:
strncpy (entry->next_update, p, 15);
entry->next_update[15] = 0;
break;
case 7: entry->dbfile_hash = p; break;
case 8: if (*p) entry->crl_number = p; break;
case 9:
if (*p)
entry->authority_issuer = unpercent_string (p);
break;
case 10:
if (*p)
entry->authority_serialno = unpercent_string (p);
break;
case 11:
if (*p)
entry->check_trust_anchor = xtrystrdup (p);
break;
default:
if (*p)
log_info (_("extra field detected in crl record of "
"'%s' line %u\n"), fname, lineno);
break;
}
}
if (!entry->issuer_hash)
{
log_info (_("invalid line detected in '%s' line %u\n"),
fname, lineno);
xfree (entry);
entry = NULL;
}
else if (find_entry (cache->entries, entry->issuer_hash))
{
/* Fixme: The duplicate checking used is not very
effective for large numbers of issuers. */
log_info (_("duplicate entry detected in '%s' line %u\n"),
fname, lineno);
xfree (entry);
entry = NULL;
}
else
{
line = NULL;
*entrytail = entry;
entrytail = &entry->next;
}
}
else if (*line == '#')
;
else
log_info (_("unsupported record type in '%s' line %u skipped\n"),
fname, lineno);
if (line)
xfree (line);
}
if (lineerr)
{
err = lineerr;
log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (err));
goto leave;
}
if (es_ferror (fp))
{
log_error (_("error reading '%s': %s\n"), fname, strerror (errno));
err = gpg_error (GPG_ERR_CONFIGURATION);
goto leave;
}
/* Now do some basic checks on the data. */
for (entry = cache->entries; entry; entry = entry->next)
{
assert (entry->lineno);
if (strlen (entry->issuer_hash) != 40)
{
anyerr++;
log_error (_("invalid issuer hash in '%s' line %u\n"),
fname, entry->lineno);
}
else if ( !*entry->issuer )
{
anyerr++;
log_error (_("no issuer DN in '%s' line %u\n"),
fname, entry->lineno);
}
else if ( check_isotime (entry->this_update)
|| check_isotime (entry->next_update))
{
anyerr++;
log_error (_("invalid timestamp in '%s' line %u\n"),
fname, entry->lineno);
}
/* Checks not leading to an immediate fail. */
if (strlen (entry->dbfile_hash) != 32)
log_info (_("WARNING: invalid cache file hash in '%s' line %u\n"),
fname, entry->lineno);
}
if (anyerr)
{
log_error (_("detected errors in cache dir file\n"));
log_info (_("please check the reason and manually delete that file\n"));
err = gpg_error (GPG_ERR_CONFIGURATION);
}
leave:
es_fclose (fp);
xfree (line);
xfree (fname);
if (err)
{
release_cache (cache);
cache = NULL;
}
*r_cache = cache;
return err;
}
static void
write_percented_string (const char *s, estream_t fp)
{
for (; *s; s++)
if (*s == ':')
es_fputs ("%3A", fp);
else if (*s == '\n')
es_fputs ("%0A", fp);
else if (*s == '\r')
es_fputs ("%0D", fp);
else
es_putc (*s, fp);
}
static void
write_dir_line_crl (estream_t fp, crl_cache_entry_t e)
{
if (e->invalid)
es_fprintf (fp, "i%d", e->invalid);
else if (e->user_trust_req)
es_putc ('u', fp);
else
es_putc ('c', fp);
es_putc (':', fp);
es_fputs (e->issuer_hash, fp);
es_putc (':', fp);
write_percented_string (e->issuer, fp);
es_putc (':', fp);
write_percented_string (e->url, fp);
es_putc (':', fp);
es_fwrite (e->this_update, 15, 1, fp);
es_putc (':', fp);
es_fwrite (e->next_update, 15, 1, fp);
es_putc (':', fp);
es_fputs (e->dbfile_hash, fp);
es_putc (':', fp);
if (e->crl_number)
es_fputs (e->crl_number, fp);
es_putc (':', fp);
if (e->authority_issuer)
write_percented_string (e->authority_issuer, fp);
es_putc (':', fp);
if (e->authority_serialno)
es_fputs (e->authority_serialno, fp);
es_putc (':', fp);
if (e->check_trust_anchor && e->user_trust_req)
es_fputs (e->check_trust_anchor, fp);
es_putc ('\n', fp);
}
/* Update the current dir file using the cache. */
static gpg_error_t
update_dir (crl_cache_t cache)
{
char *fname = NULL;
char *tmpfname = NULL;
char *line = NULL;
gpg_error_t lineerr = 0;
estream_t fp;
estream_t fpout = NULL;
crl_cache_entry_t e;
unsigned int lineno;
gpg_error_t err = 0;
fname = make_filename (opt.homedir_cache, DBDIR_D, DBDIRFILE, NULL);
/* Fixme: Take an update file lock here. */
for (e= cache->entries; e; e = e->next)
e->mark = 1;
lineno = 0;
fp = es_fopen (fname, "r");
if (!fp)
{
err = gpg_error_from_errno (errno);
log_error (_("failed to open cache dir file '%s': %s\n"),
fname, strerror (errno));
goto leave;
}
err = check_dir_version (&fp, fname, &lineno, 0);
if (err)
goto leave;
es_rewind (fp);
lineno = 0;
/* Create a temporary DIR file. */
{
char *tmpbuf, *p;
const char *nodename;
#ifndef HAVE_W32_SYSTEM
struct utsname utsbuf;
#endif
#ifdef HAVE_W32_SYSTEM
nodename = "unknown";
#else
if (uname (&utsbuf))
nodename = "unknown";
else
nodename = utsbuf.nodename;
#endif
gpgrt_asprintf (&tmpbuf, "DIR-tmp-%s-%u-%p.txt.tmp",
nodename, (unsigned int)getpid (), &tmpbuf);
if (!tmpbuf)
{
err = gpg_error_from_errno (errno);
log_error (_("failed to create temporary cache dir file '%s': %s\n"),
tmpfname, strerror (errno));
goto leave;
}
for (p=tmpbuf; *p; p++)
if (*p == '/')
*p = '.';
tmpfname = make_filename (opt.homedir_cache, DBDIR_D, tmpbuf, NULL);
xfree (tmpbuf);
}
fpout = es_fopen (tmpfname, "w");
if (!fpout)
{
err = gpg_error_from_errno (errno);
log_error (_("failed to create temporary cache dir file '%s': %s\n"),
tmpfname, strerror (errno));
goto leave;
}
while ((line = next_line_from_file (fp, &lineerr)))
{
lineno++;
if (*line == 'c' || *line == 'u' || *line == 'i')
{
/* Extract the issuer hash field. */
char *fieldp, *endp;
fieldp = strchr (line, ':');
endp = fieldp? strchr (++fieldp, ':') : NULL;
if (endp)
{
/* There should be no percent within the issuer hash
field, thus we can compare it pretty easily. */
*endp = 0;
e = find_entry ( cache->entries, fieldp);
*endp = ':'; /* Restore original line. */
if (e && e->deleted)
{
/* Marked for deletion, so don't write it. */
e->mark = 0;
}
else if (e)
{
/* Yep, this is valid entry we know about; write it out */
write_dir_line_crl (fpout, e);
e->mark = 0;
}
else
{ /* We ignore entries we don't have in our cache
because they may have been added in the meantime
by other instances of dirmngr. */
es_fprintf (fpout, "# Next line added by "
"another process; our pid is %lu\n",
(unsigned long)getpid ());
es_fputs (line, fpout);
es_putc ('\n', fpout);
}
}
else
{
es_fputs ("# Invalid line detected: ", fpout);
es_fputs (line, fpout);
es_putc ('\n', fpout);
}
}
else
{
/* Write out all non CRL lines as they are. */
es_fputs (line, fpout);
es_putc ('\n', fpout);
}
xfree (line);
}
if (!es_ferror (fp) && !es_ferror (fpout) && !lineerr)
{
/* Write out the remaining entries. */
for (e= cache->entries; e; e = e->next)
if (e->mark)
{
if (!e->deleted)
write_dir_line_crl (fpout, e);
e->mark = 0;
}
}
if (lineerr)
{
err = lineerr;
log_error (_("error reading '%s': %s\n"), fname, gpg_strerror (err));
goto leave;
}
if (es_ferror (fp))
{
err = gpg_error_from_errno (errno);
log_error (_("error reading '%s': %s\n"), fname, strerror (errno));
}
if (es_ferror (fpout))
{
err = gpg_error_from_errno (errno);
log_error (_("error writing '%s': %s\n"), tmpfname, strerror (errno));
}
if (err)
goto leave;
/* Rename the files. */
es_fclose (fp);
fp = NULL;
if (es_fclose (fpout))
{
err = gpg_error_from_errno (errno);
log_error (_("error closing '%s': %s\n"), tmpfname, strerror (errno));
goto leave;
}
fpout = NULL;
#ifdef HAVE_W32_SYSTEM
/* No atomic mv on W32 systems. */
gnupg_remove (fname);
#endif
if (rename (tmpfname, fname))
{
err = gpg_error_from_errno (errno);
log_error (_("error renaming '%s' to '%s': %s\n"),
tmpfname, fname, strerror (errno));
goto leave;
}
leave:
/* Fixme: Relinquish update lock. */
xfree (line);
es_fclose (fp);
xfree (fname);
if (fpout)
{
es_fclose (fpout);
if (err && tmpfname)
gnupg_remove (tmpfname);
}
xfree (tmpfname);
return err;
}
/* Create the filename for the cache file from the 40 byte ISSUER_HASH
string. Caller must release the return string. */
static char *
make_db_file_name (const char *issuer_hash)
{
char bname[50];
assert (strlen (issuer_hash) == 40);
memcpy (bname, "crl-", 4);
memcpy (bname + 4, issuer_hash, 40);
strcpy (bname + 44, ".db");
return make_filename (opt.homedir_cache, DBDIR_D, bname, NULL);
}
/* Hash the file FNAME and return the MD5 digest in MD5BUFFER. The
caller must allocate MD%buffer wityh at least 16 bytes. Returns 0
on success. */
static int
hash_dbfile (const char *fname, unsigned char *md5buffer)
{
estream_t fp;
char *buffer;
size_t n;
gcry_md_hd_t md5;
gpg_error_t err;
buffer = xtrymalloc (65536);
fp = buffer? es_fopen (fname, "rb") : NULL;
if (!fp)
{
log_error (_("can't hash '%s': %s\n"), fname, strerror (errno));
xfree (buffer);
return -1;
}
err = gcry_md_open (&md5, GCRY_MD_MD5, 0);
if (err)
{
log_error (_("error setting up MD5 hash context: %s\n"),
gpg_strerror (err));
xfree (buffer);
es_fclose (fp);
return -1;
}
/* We better hash some information about the cache file layout in. */
sprintf (buffer, "%.100s/%.100s:%d", DBDIR_D, DBDIRFILE, DBDIRVERSION);
gcry_md_write (md5, buffer, strlen (buffer));
for (;;)
{
n = es_fread (buffer, 1, 65536, fp);
if (n < 65536 && es_ferror (fp))
{
log_error (_("error hashing '%s': %s\n"), fname, strerror (errno));
xfree (buffer);
es_fclose (fp);
gcry_md_close (md5);
return -1;
}
if (!n)
break;
gcry_md_write (md5, buffer, n);
}
es_fclose (fp);
xfree (buffer);
gcry_md_final (md5);
memcpy (md5buffer, gcry_md_read (md5, GCRY_MD_MD5), 16);
gcry_md_close (md5);
return 0;
}
/* Compare the file FNAME against the dexified MD5 hash MD5HASH and
return 0 if they match. */
static int
check_dbfile (const char *fname, const char *md5hexvalue)
{
unsigned char buffer1[16], buffer2[16];
if (strlen (md5hexvalue) != 32)
{
log_error (_("invalid formatted checksum for '%s'\n"), fname);
return -1;
}
unhexify (buffer1, md5hexvalue);
if (hash_dbfile (fname, buffer2))
return -1;
return memcmp (buffer1, buffer2, 16);
}
/* Open the cache file for ENTRY. This function implements a caching
strategy and might close unused cache files. It is required to use
unlock_db_file after using the file. */
static struct cdb *
lock_db_file (crl_cache_t cache, crl_cache_entry_t entry)
{
char *fname;
int fd;
int open_count;
crl_cache_entry_t e;
if (entry->cdb)
{
entry->cdb_use_count++;
return entry->cdb;
}
for (open_count = 0, e = cache->entries; e; e = e->next)
{
if (e->cdb)
open_count++;
/* log_debug ("CACHE: cdb=%p use_count=%u lru_count=%u\n", */
/* e->cdb,e->cdb_use_count,e->cdb_lru_count); */
}
/* If there are too many file open, find the least recent used DB
file and close it. Note that for Pth thread safeness we need to
use a loop here. */
while (open_count >= MAX_OPEN_DB_FILES )
{
crl_cache_entry_t last_e = NULL;
unsigned int last_lru = (unsigned int)(-1);
for (e = cache->entries; e; e = e->next)
if (e->cdb && !e->cdb_use_count && e->cdb_lru_count < last_lru)
{
last_lru = e->cdb_lru_count;
last_e = e;
}
if (!last_e)
{
log_error (_("too many open cache files; can't open anymore\n"));
return NULL;
}
/* log_debug ("CACHE: closing file at cdb=%p\n", last_e->cdb); */
fd = cdb_fileno (last_e->cdb);
cdb_free (last_e->cdb);
xfree (last_e->cdb);
last_e->cdb = NULL;
if (close (fd))
log_error (_("error closing cache file: %s\n"), strerror(errno));
open_count--;
}
fname = make_db_file_name (entry->issuer_hash);
if (opt.verbose)
log_info (_("opening cache file '%s'\n"), fname );
if (!entry->dbfile_checked)
{
if (!check_dbfile (fname, entry->dbfile_hash))
entry->dbfile_checked = 1;
/* Note, in case of an error we don't print an error here but
let require the caller to do that check. */
}
entry->cdb = xtrycalloc (1, sizeof *entry->cdb);
if (!entry->cdb)
{
xfree (fname);
return NULL;
}
fd = open (fname, O_RDONLY | O_BINARY);
if (fd == -1)
{
log_error (_("error opening cache file '%s': %s\n"),
fname, strerror (errno));
xfree (entry->cdb);
entry->cdb = NULL;
xfree (fname);
return NULL;
}
if (cdb_init (entry->cdb, fd))
{
log_error (_("error initializing cache file '%s' for reading: %s\n"),
fname, strerror (errno));
xfree (entry->cdb);
entry->cdb = NULL;
close (fd);
xfree (fname);
return NULL;
}
xfree (fname);
entry->cdb_use_count = 1;
entry->cdb_lru_count = 0;
return entry->cdb;
}
/* Unlock a cache file, so that it can be reused. */
static void
unlock_db_file (crl_cache_t cache, crl_cache_entry_t entry)
{
if (!entry->cdb)
log_error (_("calling unlock_db_file on a closed file\n"));
else if (!entry->cdb_use_count)
log_error (_("calling unlock_db_file on an unlocked file\n"));
else
{
entry->cdb_use_count--;
entry->cdb_lru_count++;
}
/* If the entry was marked for deletion in the meantime do it now.
We do this for the sake of Pth thread safeness. */
if (!entry->cdb_use_count && entry->deleted)
{
crl_cache_entry_t eprev, enext;
enext = entry->next;
for (eprev = cache->entries;
eprev && eprev->next != entry; eprev = eprev->next)
;
assert (eprev);
if (eprev == cache->entries)
cache->entries = enext;
else
eprev->next = enext;
/* FIXME: Do we leak ENTRY? */
}
}
/* Find ISSUER_HASH in our cache FIRST. This may be used to enumerate
the linked list we use to keep the CRLs of an issuer. */
static crl_cache_entry_t
find_entry (crl_cache_entry_t first, const char *issuer_hash)
{
while (first && (first->deleted || strcmp (issuer_hash, first->issuer_hash)))
first = first->next;
return first;
}
/* Create a new CRL cache. This function is usually called only once.
never fail. */
void
crl_cache_init(void)
{
crl_cache_t cache = NULL;
gpg_error_t err;
if (current_cache)
{
log_error ("crl cache has already been initialized - not doing twice\n");
return;
}
err = open_dir (&cache);
if (err)
log_fatal (_("failed to create a new cache object: %s\n"),
gpg_strerror (err));
current_cache = cache;
}
/* Remove the cache information and all its resources. Note that we
still keep the cache on disk. */
void
crl_cache_deinit (void)
{
if (current_cache)
{
release_cache (current_cache);
current_cache = NULL;
}
}
/* Delete the cache from disk. Return 0 on success.*/
int
crl_cache_flush (void)
{
int rc;
rc = cleanup_cache_dir (0)? -1 : 0;
return rc;
}
/* Check whether the certificate identified by ISSUER_HASH and
SN/SNLEN is valid; i.e. not listed in our cache. With
FORCE_REFRESH set to true, a new CRL will be retrieved even if the
cache has not yet expired. We use a 30 minutes threshold here so
that invoking this function several times won't load the CRL over
and over. */
static crl_cache_result_t
cache_isvalid (ctrl_t ctrl, const char *issuer_hash,
const unsigned char *sn, size_t snlen,
int force_refresh)
{
crl_cache_t cache = get_current_cache ();
crl_cache_result_t retval;
struct cdb *cdb;
int rc;
crl_cache_entry_t entry;
gnupg_isotime_t current_time;
size_t n;
(void)ctrl;
entry = find_entry (cache->entries, issuer_hash);
if (!entry)
{
log_info (_("no CRL available for issuer id %s\n"), issuer_hash );
return CRL_CACHE_DONTKNOW;
}
gnupg_get_isotime (current_time);
if (strcmp (entry->next_update, current_time) < 0 )
{
log_info (_("cached CRL for issuer id %s too old; update required\n"),
issuer_hash);
return CRL_CACHE_DONTKNOW;
}
if (force_refresh)
{
gnupg_isotime_t tmptime;
if (*entry->last_refresh)
{
gnupg_copy_time (tmptime, entry->last_refresh);
add_seconds_to_isotime (tmptime, 30 * 60);
if (strcmp (tmptime, current_time) < 0 )
{
log_info (_("force-crl-refresh active and %d minutes passed for"
" issuer id %s; update required\n"),
30, issuer_hash);
return CRL_CACHE_DONTKNOW;
}
}
else
{
log_info (_("force-crl-refresh active for"
" issuer id %s; update required\n"),
issuer_hash);
return CRL_CACHE_DONTKNOW;
}
}
if (entry->invalid)
{
log_info (_("available CRL for issuer ID %s can't be used\n"),
issuer_hash);
return CRL_CACHE_CANTUSE;
}
cdb = lock_db_file (cache, entry);
if (!cdb)
return CRL_CACHE_DONTKNOW; /* Hmmm, not the best error code. */
if (!entry->dbfile_checked)
{
log_error (_("cached CRL for issuer id %s tampered; we need to update\n")
, issuer_hash);
unlock_db_file (cache, entry);
return CRL_CACHE_DONTKNOW;
}
rc = cdb_find (cdb, sn, snlen);
if (rc == 1)
{
n = cdb_datalen (cdb);
if (n != 16)
{
log_error (_("WARNING: invalid cache record length for S/N "));
log_printf ("0x");
log_printhex (sn, snlen, "");
}
else if (opt.verbose)
{
unsigned char record[16];
char *tmp = hexify_data (sn, snlen, 1);
if (cdb_read (cdb, record, n, cdb_datapos (cdb)))
log_error (_("problem reading cache record for S/N %s: %s\n"),
tmp, strerror (errno));
else
log_info (_("S/N %s is not valid; reason=%02X date=%.15s\n"),
tmp, *record, record+1);
xfree (tmp);
}
retval = CRL_CACHE_INVALID;
}
else if (!rc)
{
if (opt.verbose)
{
char *serialno = hexify_data (sn, snlen, 1);
log_info (_("S/N %s is valid, it is not listed in the CRL\n"),
serialno );
xfree (serialno);
}
retval = CRL_CACHE_VALID;
}
else
{
log_error (_("error getting data from cache file: %s\n"),
strerror (errno));
retval = CRL_CACHE_DONTKNOW;
}
if (entry->user_trust_req
&& (retval == CRL_CACHE_VALID || retval == CRL_CACHE_INVALID))
{
if (!entry->check_trust_anchor)
{
log_error ("inconsistent data on user trust check\n");
retval = CRL_CACHE_CANTUSE;
}
else if (get_istrusted_from_client (ctrl, entry->check_trust_anchor))
{
if (opt.verbose)
log_info ("no system trust and client does not trust either\n");
retval = CRL_CACHE_CANTUSE;
}
else
{
/* Okay, the CRL is considered valid by the client and thus
we can return the result as is. */
}
}
unlock_db_file (cache, entry);
return retval;
}
/* Check whether the certificate identified by ISSUER_HASH and
SERIALNO is valid; i.e. not listed in our cache. With
FORCE_REFRESH set to true, a new CRL will be retrieved even if the
cache has not yet expired. We use a 30 minutes threshold here so
that invoking this function several times won't load the CRL over
and over. */
crl_cache_result_t
crl_cache_isvalid (ctrl_t ctrl, const char *issuer_hash, const char *serialno,
int force_refresh)
{
crl_cache_result_t result;
unsigned char snbuf_buffer[50];
unsigned char *snbuf;
size_t n;
n = strlen (serialno)/2+1;
if (n < sizeof snbuf_buffer - 1)
snbuf = snbuf_buffer;
else
{
snbuf = xtrymalloc (n);
if (!snbuf)
return CRL_CACHE_DONTKNOW;
}
n = unhexify (snbuf, serialno);
result = cache_isvalid (ctrl, issuer_hash, snbuf, n, force_refresh);
if (snbuf != snbuf_buffer)
xfree (snbuf);
return result;
}
/* Check whether the certificate CERT is valid; i.e. not listed in our
cache. With FORCE_REFRESH set to true, a new CRL will be retrieved
even if the cache has not yet expired. We use a 30 minutes
threshold here so that invoking this function several times won't
load the CRL over and over. */
gpg_error_t
crl_cache_cert_isvalid (ctrl_t ctrl, ksba_cert_t cert,
int force_refresh)
{
gpg_error_t err;
crl_cache_result_t result;
unsigned char issuerhash[20];
char issuerhash_hex[41];
ksba_sexp_t serial;
unsigned char *sn;
size_t snlen;
char *endp, *tmp;
int i;
/* Compute the hash value of the issuer name. */
tmp = ksba_cert_get_issuer (cert, 0);
if (!tmp)
{
log_error ("oops: issuer missing in certificate\n");
return gpg_error (GPG_ERR_INV_CERT_OBJ);
}
gcry_md_hash_buffer (GCRY_MD_SHA1, issuerhash, tmp, strlen (tmp));
xfree (tmp);
for (i=0,tmp=issuerhash_hex; i < 20; i++, tmp += 2)
sprintf (tmp, "%02X", issuerhash[i]);
/* Get the serial number. */
serial = ksba_cert_get_serial (cert);
if (!serial)
{
log_error ("oops: S/N missing in certificate\n");
return gpg_error (GPG_ERR_INV_CERT_OBJ);
}
sn = serial;
if (*sn != '(')
{
log_error ("oops: invalid S/N\n");
xfree (serial);
return gpg_error (GPG_ERR_INV_CERT_OBJ);
}
sn++;
snlen = strtoul (sn, &endp, 10);
sn = endp;
if (*sn != ':')
{
log_error ("oops: invalid S/N\n");
xfree (serial);
return gpg_error (GPG_ERR_INV_CERT_OBJ);
}
sn++;
/* Check the cache. */
result = cache_isvalid (ctrl, issuerhash_hex, sn, snlen, force_refresh);
switch (result)
{
case CRL_CACHE_VALID:
err = 0;
break;
case CRL_CACHE_INVALID:
err = gpg_error (GPG_ERR_CERT_REVOKED);
break;
case CRL_CACHE_DONTKNOW:
err = gpg_error (GPG_ERR_NO_CRL_KNOWN);
break;
case CRL_CACHE_CANTUSE:
err = gpg_error (GPG_ERR_NO_CRL_KNOWN);
break;
default:
log_fatal ("cache_isvalid returned invalid status code %d\n", result);
}
xfree (serial);
return err;
}
/* Prepare a hash context for the signature verification. Input is
the CRL and the output is the hash context MD as well as the uses
algorithm identifier ALGO. */
static gpg_error_t
start_sig_check (ksba_crl_t crl, gcry_md_hd_t *md, int *algo)
{
gpg_error_t err;
const char *algoid;
algoid = ksba_crl_get_digest_algo (crl);
*algo = gcry_md_map_name (algoid);
if (!*algo)
{
log_error (_("unknown hash algorithm '%s'\n"), algoid? algoid:"?");
return gpg_error (GPG_ERR_DIGEST_ALGO);
}
err = gcry_md_open (md, *algo, 0);
if (err)
{
log_error (_("gcry_md_open for algorithm %d failed: %s\n"),
*algo, gcry_strerror (err));
return err;
}
if (DBG_HASHING)
gcry_md_debug (*md, "hash.cert");
ksba_crl_set_hash_function (crl, HASH_FNC, *md);
return 0;
}
/* Finish a hash context and verify the signature. This function
should return 0 on a good signature, GPG_ERR_BAD_SIGNATURE if the
signature does not verify or any other error code. CRL is the CRL
object we are working on, MD the hash context and ISSUER_CERT the
certificate of the CRL issuer. This function takes ownership of MD. */
static gpg_error_t
finish_sig_check (ksba_crl_t crl, gcry_md_hd_t md, int algo,
ksba_cert_t issuer_cert)
{
gpg_error_t err;
ksba_sexp_t sigval = NULL, pubkey = NULL;
const char *s;
char algoname[50];
size_t n;
gcry_sexp_t s_sig = NULL, s_hash = NULL, s_pkey = NULL;
unsigned int i;
/* This also stops debugging on the MD. */
gcry_md_final (md);
/* Get and convert the signature value. */
sigval = ksba_crl_get_sig_val (crl);
n = gcry_sexp_canon_len (sigval, 0, NULL, NULL);
if (!n)
{
log_error (_("got an invalid S-expression from libksba\n"));
err = gpg_error (GPG_ERR_INV_SEXP);
goto leave;
}
err = gcry_sexp_sscan (&s_sig, NULL, sigval, n);
if (err)
{
log_error (_("converting S-expression failed: %s\n"),
gcry_strerror (err));
goto leave;
}
/* Get and convert the public key for the issuer certificate. */
if (DBG_X509)
dump_cert ("crl_issuer_cert", issuer_cert);
pubkey = ksba_cert_get_public_key (issuer_cert);
n = gcry_sexp_canon_len (pubkey, 0, NULL, NULL);
if (!n)
{
log_error (_("got an invalid S-expression from libksba\n"));
err = gpg_error (GPG_ERR_INV_SEXP);
goto leave;
}
err = gcry_sexp_sscan (&s_pkey, NULL, pubkey, n);
if (err)
{
log_error (_("converting S-expression failed: %s\n"),
gcry_strerror (err));
goto leave;
}
/* Create an S-expression with the actual hash value. */
s = gcry_md_algo_name (algo);
for (i = 0; *s && i < sizeof(algoname) - 1; s++, i++)
algoname[i] = ascii_tolower (*s);
algoname[i] = 0;
err = gcry_sexp_build (&s_hash, NULL, "(data(flags pkcs1)(hash %s %b))",
algoname,
gcry_md_get_algo_dlen (algo), gcry_md_read (md, algo));
if (err)
{
log_error (_("creating S-expression failed: %s\n"), gcry_strerror (err));
goto leave;
}
/* Pass this on to the signature verification. */
err = gcry_pk_verify (s_sig, s_hash, s_pkey);
if (DBG_X509)
log_debug ("gcry_pk_verify: %s\n", gpg_strerror (err));
leave:
xfree (sigval);
xfree (pubkey);
gcry_sexp_release (s_sig);
gcry_sexp_release (s_hash);
gcry_sexp_release (s_pkey);
gcry_md_close (md);
return err;
}
/* Call this to match a start_sig_check that can not be completed
normally. Takes ownership of MD if MD is not NULL. */
static void
abort_sig_check (ksba_crl_t crl, gcry_md_hd_t md)
{
(void)crl;
if (md)
gcry_md_close (md);
}
/* Workhorse of the CRL loading machinery. The CRL is read using the
CRL object and stored in the data base file DB with the name FNAME
(only used for printing error messages). That DB should be a
temporary one and not the actual one. If the function fails the
caller should delete this temporary database file. CTRL is
required to retrieve certificates using the general dirmngr
callback service. R_CRLISSUER returns an allocated string with the
crl-issuer DN, THIS_UPDATE and NEXT_UPDATE are filled with the
corresponding data from the CRL. Note that these values might get
set even if the CRL processing fails at a later step; thus the
caller should free *R_ISSUER even if the function returns with an
error. R_TRUST_ANCHOR is set on exit to NULL or a string with the
hexified fingerprint of the root certificate, if checking this
certificate for trustiness is required.
*/
static int
crl_parse_insert (ctrl_t ctrl, ksba_crl_t crl,
struct cdb_make *cdb, const char *fname,
char **r_crlissuer,
ksba_isotime_t thisupdate, ksba_isotime_t nextupdate,
char **r_trust_anchor)
{
gpg_error_t err;
ksba_stop_reason_t stopreason;
ksba_cert_t crlissuer_cert = NULL;
gcry_md_hd_t md = NULL;
int algo = 0;
size_t n;
(void)fname;
*r_crlissuer = NULL;
*thisupdate = *nextupdate = 0;
*r_trust_anchor = NULL;
/* Start of the KSBA parser loop. */
do
{
err = ksba_crl_parse (crl, &stopreason);
if (err)
{
log_error (_("ksba_crl_parse failed: %s\n"), gpg_strerror (err) );
goto failure;
}
switch (stopreason)
{
case KSBA_SR_BEGIN_ITEMS:
{
err = start_sig_check (crl, &md, &algo);
if (err)
goto failure;
err = ksba_crl_get_update_times (crl, thisupdate, nextupdate);
if (err)
{
log_error (_("error getting update times of CRL: %s\n"),
gpg_strerror (err));
err = gpg_error (GPG_ERR_INV_CRL);
goto failure;
}
if (opt.verbose || !*nextupdate)
log_info (_("update times of this CRL: this=%s next=%s\n"),
thisupdate, nextupdate);
if (!*nextupdate)
{
log_info (_("nextUpdate not given; "
"assuming a validity period of one day\n"));
gnupg_copy_time (nextupdate, thisupdate);
add_seconds_to_isotime (nextupdate, 86400);
}
}
break;
case KSBA_SR_GOT_ITEM:
{
ksba_sexp_t serial;
const unsigned char *p;
ksba_isotime_t rdate;
ksba_crl_reason_t reason;
int rc;
unsigned char record[1+15];
err = ksba_crl_get_item (crl, &serial, rdate, &reason);
if (err)
{
log_error (_("error getting CRL item: %s\n"),
gpg_strerror (err));
err = gpg_error (GPG_ERR_INV_CRL);
ksba_free (serial);
goto failure;
}
p = serial_to_buffer (serial, &n);
if (!p)
BUG ();
record[0] = (reason & 0xff);
memcpy (record+1, rdate, 15);
rc = cdb_make_add (cdb, p, n, record, 1+15);
if (rc)
{
err = gpg_error_from_errno (errno);
log_error (_("error inserting item into "
"temporary cache file: %s\n"),
strerror (errno));
goto failure;
}
ksba_free (serial);
}
break;
case KSBA_SR_END_ITEMS:
break;
case KSBA_SR_READY:
{
char *crlissuer;
ksba_name_t authid;
ksba_sexp_t authidsn;
ksba_sexp_t keyid;
/* We need to look for the issuer only after having read
- all items. The issuer itselfs comes before the items
+ all items. The issuer itself comes before the items
but the optional authorityKeyIdentifier comes after the
items. */
err = ksba_crl_get_issuer (crl, &crlissuer);
if( err )
{
log_error (_("no CRL issuer found in CRL: %s\n"),
gpg_strerror (err) );
err = gpg_error (GPG_ERR_INV_CRL);
goto failure;
}
/* Note: This should be released by ksba_free, not xfree.
May need a memory reallocation dance. */
*r_crlissuer = crlissuer; /* (Do it here so we don't need
to free it later) */
if (!ksba_crl_get_auth_key_id (crl, &keyid, &authid, &authidsn))
{
const char *s;
if (opt.verbose)
log_info (_("locating CRL issuer certificate by "
"authorityKeyIdentifier\n"));
s = ksba_name_enum (authid, 0);
if (s && *authidsn)
crlissuer_cert = find_cert_bysn (ctrl, s, authidsn);
if (!crlissuer_cert && keyid)
crlissuer_cert = find_cert_bysubject (ctrl,
crlissuer, keyid);
if (!crlissuer_cert)
{
log_info ("CRL issuer certificate ");
if (keyid)
{
log_printf ("{");
dump_serial (keyid);
log_printf ("} ");
}
if (authidsn)
{
log_printf ("(#");
dump_serial (authidsn);
log_printf ("/");
dump_string (s);
log_printf (") ");
}
log_printf ("not found\n");
}
ksba_name_release (authid);
xfree (authidsn);
xfree (keyid);
}
else
crlissuer_cert = find_cert_bysubject (ctrl, crlissuer, NULL);
err = 0;
if (!crlissuer_cert)
{
err = gpg_error (GPG_ERR_MISSING_CERT);
goto failure;
}
err = finish_sig_check (crl, md, algo, crlissuer_cert);
md = NULL; /* Closed. */
if (err)
{
log_error (_("CRL signature verification failed: %s\n"),
gpg_strerror (err));
goto failure;
}
err = validate_cert_chain (ctrl, crlissuer_cert, NULL,
(VALIDATE_FLAG_TRUST_CONFIG
| VALIDATE_FLAG_CRL
| VALIDATE_FLAG_RECURSIVE),
r_trust_anchor);
if (err)
{
log_error (_("error checking validity of CRL "
"issuer certificate: %s\n"),
gpg_strerror (err));
goto failure;
}
}
break;
default:
log_debug ("crl_parse_insert: unknown stop reason\n");
err = gpg_error (GPG_ERR_BUG);
goto failure;
}
}
while (stopreason != KSBA_SR_READY);
assert (!err);
failure:
abort_sig_check (crl, md);
ksba_cert_release (crlissuer_cert);
return err;
}
/* Return the crlNumber extension as an allocated hex string or NULL
if there is none. */
static char *
get_crl_number (ksba_crl_t crl)
{
gpg_error_t err;
ksba_sexp_t number;
char *string;
err = ksba_crl_get_crl_number (crl, &number);
if (err)
return NULL;
string = serial_hex (number);
ksba_free (number);
return string;
}
/* Return the authorityKeyIdentifier or NULL if it is not available.
- The issuer name may consists of several parts - they are delimted by
+ The issuer name may consists of several parts - they are delimited by
0x01. */
static char *
get_auth_key_id (ksba_crl_t crl, char **serialno)
{
gpg_error_t err;
ksba_name_t name;
ksba_sexp_t sn;
int idx;
const char *s;
char *string;
size_t length;
*serialno = NULL;
err = ksba_crl_get_auth_key_id (crl, NULL, &name, &sn);
if (err)
return NULL;
*serialno = serial_hex (sn);
ksba_free (sn);
if (!name)
return xstrdup ("");
length = 0;
for (idx=0; (s = ksba_name_enum (name, idx)); idx++)
{
char *p = ksba_name_get_uri (name, idx);
length += strlen (p?p:s) + 1;
xfree (p);
}
string = xtrymalloc (length+1);
if (string)
{
*string = 0;
for (idx=0; (s = ksba_name_enum (name, idx)); idx++)
{
char *p = ksba_name_get_uri (name, idx);
if (*string)
strcat (string, "\x01");
strcat (string, p?p:s);
xfree (p);
}
}
ksba_name_release (name);
return string;
}
/* Insert the CRL retrieved using URL into the cache specified by
CACHE. The CRL itself will be read from the stream FP and is
expected in binary format.
Called by:
crl_cache_load
cmd_loadcrl
--load-crl
crl_cache_reload_crl
cmd_isvalid
cmd_checkcrl
cmd_loadcrl
--fetch-crl
*/
gpg_error_t
crl_cache_insert (ctrl_t ctrl, const char *url, ksba_reader_t reader)
{
crl_cache_t cache = get_current_cache ();
gpg_error_t err, err2;
ksba_crl_t crl;
char *fname = NULL;
char *newfname = NULL;
struct cdb_make cdb;
int fd_cdb = -1;
char *issuer = NULL;
char *issuer_hash = NULL;
ksba_isotime_t thisupdate, nextupdate;
crl_cache_entry_t entry = NULL;
crl_cache_entry_t e;
gnupg_isotime_t current_time;
char *checksum = NULL;
int invalidate_crl = 0;
int idx;
const char *oid;
int critical;
char *trust_anchor = NULL;
/* FIXME: We should acquire a mutex for the URL, so that we don't
simultaneously enter the same CRL twice. However this needs to be
interweaved with the checking function.*/
err2 = 0;
err = ksba_crl_new (&crl);
if (err)
{
log_error (_("ksba_crl_new failed: %s\n"), gpg_strerror (err));
goto leave;
}
err = ksba_crl_set_reader (crl, reader);
if ( err )
{
log_error (_("ksba_crl_set_reader failed: %s\n"), gpg_strerror (err));
goto leave;
}
/* Create a temporary cache file to load the CRL into. */
{
char *tmpfname, *p;
const char *nodename;
#ifndef HAVE_W32_SYSTEM
struct utsname utsbuf;
#endif
#ifdef HAVE_W32_SYSTEM
nodename = "unknown";
#else
if (uname (&utsbuf))
nodename = "unknown";
else
nodename = utsbuf.nodename;
#endif
gpgrt_asprintf (&tmpfname, "crl-tmp-%s-%u-%p.db.tmp",
nodename, (unsigned int)getpid (), &tmpfname);
if (!tmpfname)
{
err = gpg_error_from_syserror ();
goto leave;
}
for (p=tmpfname; *p; p++)
if (*p == '/')
*p = '.';
fname = make_filename (opt.homedir_cache, DBDIR_D, tmpfname, NULL);
xfree (tmpfname);
if (!gnupg_remove (fname))
log_info (_("removed stale temporary cache file '%s'\n"), fname);
else if (errno != ENOENT)
{
err = gpg_error_from_syserror ();
log_error (_("problem removing stale temporary cache file '%s': %s\n"),
fname, gpg_strerror (err));
goto leave;
}
}
fd_cdb = open (fname, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
if (fd_cdb == -1)
{
err = gpg_error_from_errno (errno);
log_error (_("error creating temporary cache file '%s': %s\n"),
fname, strerror (errno));
goto leave;
}
cdb_make_start(&cdb, fd_cdb);
err = crl_parse_insert (ctrl, crl, &cdb, fname,
&issuer, thisupdate, nextupdate, &trust_anchor);
if (err)
{
log_error (_("crl_parse_insert failed: %s\n"), gpg_strerror (err));
/* Error in cleanup ignored. */
cdb_make_finish (&cdb);
goto leave;
}
/* Finish the database. */
if (cdb_make_finish (&cdb))
{
err = gpg_error_from_errno (errno);
log_error (_("error finishing temporary cache file '%s': %s\n"),
fname, strerror (errno));
goto leave;
}
if (close (fd_cdb))
{
err = gpg_error_from_errno (errno);
log_error (_("error closing temporary cache file '%s': %s\n"),
fname, strerror (errno));
goto leave;
}
fd_cdb = -1;
/* Create a checksum. */
{
unsigned char md5buf[16];
if (hash_dbfile (fname, md5buf))
{
err = gpg_error (GPG_ERR_CHECKSUM);
goto leave;
}
checksum = hexify_data (md5buf, 16, 0);
}
/* Check whether that new CRL is still not expired. */
gnupg_get_isotime (current_time);
if (strcmp (nextupdate, current_time) < 0 )
{
if (opt.force)
log_info (_("WARNING: new CRL still too old; it expired on %s "
"- loading anyway\n"), nextupdate);
else
{
log_error (_("new CRL still too old; it expired on %s\n"),
nextupdate);
if (!err2)
err2 = gpg_error (GPG_ERR_CRL_TOO_OLD);
invalidate_crl |= 1;
}
}
/* Check for unknown critical extensions. */
for (idx=0; !(err=ksba_crl_get_extension (crl, idx, &oid, &critical,
NULL, NULL)); idx++)
{
if (!critical
|| !strcmp (oid, oidstr_authorityKeyIdentifier)
|| !strcmp (oid, oidstr_crlNumber) )
continue;
log_error (_("unknown critical CRL extension %s\n"), oid);
if (!err2)
err2 = gpg_error (GPG_ERR_INV_CRL);
invalidate_crl |= 2;
}
if (gpg_err_code (err) == GPG_ERR_EOF
|| gpg_err_code (err) == GPG_ERR_NO_DATA )
err = 0;
if (err)
{
log_error (_("error reading CRL extensions: %s\n"), gpg_strerror (err));
err = gpg_error (GPG_ERR_INV_CRL);
}
/* Create an hex encoded SHA-1 hash of the issuer DN to be
used as the key for the cache. */
issuer_hash = hashify_data (issuer, strlen (issuer));
/* Create an ENTRY. */
entry = xtrycalloc (1, sizeof *entry);
if (!entry)
{
err = gpg_error_from_syserror ();
goto leave;
}
entry->release_ptr = xtrymalloc (strlen (issuer_hash) + 1
+ strlen (issuer) + 1
+ strlen (url) + 1
+ strlen (checksum) + 1);
if (!entry->release_ptr)
{
err = gpg_error_from_syserror ();
xfree (entry);
entry = NULL;
goto leave;
}
entry->issuer_hash = entry->release_ptr;
entry->issuer = stpcpy (entry->issuer_hash, issuer_hash) + 1;
entry->url = stpcpy (entry->issuer, issuer) + 1;
entry->dbfile_hash = stpcpy (entry->url, url) + 1;
strcpy (entry->dbfile_hash, checksum);
gnupg_copy_time (entry->this_update, thisupdate);
gnupg_copy_time (entry->next_update, nextupdate);
gnupg_copy_time (entry->last_refresh, current_time);
entry->crl_number = get_crl_number (crl);
entry->authority_issuer = get_auth_key_id (crl, &entry->authority_serialno);
entry->invalid = invalidate_crl;
entry->user_trust_req = !!trust_anchor;
entry->check_trust_anchor = trust_anchor;
trust_anchor = NULL;
/* Check whether we already have an entry for this issuer and mark
it as deleted. We better use a loop, just in case duplicates got
somehow into the list. */
for (e = cache->entries; (e=find_entry (e, entry->issuer_hash)); e = e->next)
e->deleted = 1;
/* Rename the temporary DB to the real name. */
newfname = make_db_file_name (entry->issuer_hash);
if (opt.verbose)
log_info (_("creating cache file '%s'\n"), newfname);
/* Just in case close unused matching files. Actually we need this
only under Windows but saving file descriptors is never bad. */
{
int any;
do
{
any = 0;
for (e = cache->entries; e; e = e->next)
if (!e->cdb_use_count && e->cdb
&& !strcmp (e->issuer_hash, entry->issuer_hash))
{
int fd = cdb_fileno (e->cdb);
cdb_free (e->cdb);
xfree (e->cdb);
e->cdb = NULL;
if (close (fd))
log_error (_("error closing cache file: %s\n"),
strerror(errno));
any = 1;
break;
}
}
while (any);
}
#ifdef HAVE_W32_SYSTEM
gnupg_remove (newfname);
#endif
if (rename (fname, newfname))
{
err = gpg_error_from_syserror ();
log_error (_("problem renaming '%s' to '%s': %s\n"),
fname, newfname, gpg_strerror (err));
goto leave;
}
xfree (fname); fname = NULL; /*(let the cleanup code not try to remove it)*/
/* Link the new entry in. */
entry->next = cache->entries;
cache->entries = entry;
entry = NULL;
err = update_dir (cache);
if (err)
{
log_error (_("updating the DIR file failed - "
"cache entry will get lost with the next program start\n"));
err = 0; /* Keep on running. */
}
leave:
release_one_cache_entry (entry);
if (fd_cdb != -1)
close (fd_cdb);
if (fname)
{
gnupg_remove (fname);
xfree (fname);
}
xfree (newfname);
ksba_crl_release (crl);
xfree (issuer);
xfree (issuer_hash);
xfree (checksum);
xfree (trust_anchor);
return err ? err : err2;
}
/* Print one cached entry E in a human readable format to stream
FP. Return 0 on success. */
static gpg_error_t
list_one_crl_entry (crl_cache_t cache, crl_cache_entry_t e, estream_t fp)
{
struct cdb_find cdbfp;
struct cdb *cdb;
int rc;
int warn = 0;
const unsigned char *s;
es_fputs ("--------------------------------------------------------\n", fp );
es_fprintf (fp, _("Begin CRL dump (retrieved via %s)\n"), e->url );
es_fprintf (fp, " Issuer:\t%s\n", e->issuer );
es_fprintf (fp, " Issuer Hash:\t%s\n", e->issuer_hash );
es_fprintf (fp, " This Update:\t%s\n", e->this_update );
es_fprintf (fp, " Next Update:\t%s\n", e->next_update );
es_fprintf (fp, " CRL Number :\t%s\n", e->crl_number? e->crl_number: "none");
es_fprintf (fp, " AuthKeyId :\t%s\n",
e->authority_serialno? e->authority_serialno:"none");
if (e->authority_serialno && e->authority_issuer)
{
es_fputs (" \t", fp);
for (s=e->authority_issuer; *s; s++)
if (*s == '\x01')
es_fputs ("\n \t", fp);
else
es_putc (*s, fp);
es_putc ('\n', fp);
}
es_fprintf (fp, " Trust Check:\t%s\n",
!e->user_trust_req? "[system]" :
e->check_trust_anchor? e->check_trust_anchor:"[missing]");
if ((e->invalid & 1))
es_fprintf (fp, _(" ERROR: The CRL will not be used "
"because it was still too old after an update!\n"));
if ((e->invalid & 2))
es_fprintf (fp, _(" ERROR: The CRL will not be used "
"due to an unknown critical extension!\n"));
if ((e->invalid & ~3))
es_fprintf (fp, _(" ERROR: The CRL will not be used\n"));
cdb = lock_db_file (cache, e);
if (!cdb)
return gpg_error (GPG_ERR_GENERAL);
if (!e->dbfile_checked)
es_fprintf (fp, _(" ERROR: This cached CRL may have been tampered with!\n"));
es_putc ('\n', fp);
rc = cdb_findinit (&cdbfp, cdb, NULL, 0);
while (!rc && (rc=cdb_findnext (&cdbfp)) > 0 )
{
unsigned char keyrecord[256];
unsigned char record[16];
int reason;
int any = 0;
cdbi_t n;
cdbi_t i;
rc = 0;
n = cdb_datalen (cdb);
if (n != 16)
{
log_error (_(" WARNING: invalid cache record length\n"));
warn = 1;
continue;
}
if (cdb_read (cdb, record, n, cdb_datapos (cdb)))
{
log_error (_("problem reading cache record: %s\n"),
strerror (errno));
warn = 1;
continue;
}
n = cdb_keylen (cdb);
if (n > sizeof keyrecord)
n = sizeof keyrecord;
if (cdb_read (cdb, keyrecord, n, cdb_keypos (cdb)))
{
log_error (_("problem reading cache key: %s\n"), strerror (errno));
warn = 1;
continue;
}
reason = *record;
es_fputs (" ", fp);
for (i = 0; i < n; i++)
es_fprintf (fp, "%02X", keyrecord[i]);
es_fputs (":\t reasons( ", fp);
if (reason & KSBA_CRLREASON_UNSPECIFIED)
es_fputs( "unspecified ", fp ), any = 1;
if (reason & KSBA_CRLREASON_KEY_COMPROMISE )
es_fputs( "key_compromise ", fp ), any = 1;
if (reason & KSBA_CRLREASON_CA_COMPROMISE )
es_fputs( "ca_compromise ", fp ), any = 1;
if (reason & KSBA_CRLREASON_AFFILIATION_CHANGED )
es_fputs( "affiliation_changed ", fp ), any = 1;
if (reason & KSBA_CRLREASON_SUPERSEDED )
es_fputs( "superseded", fp ), any = 1;
if (reason & KSBA_CRLREASON_CESSATION_OF_OPERATION )
es_fputs( "cessation_of_operation", fp ), any = 1;
if (reason & KSBA_CRLREASON_CERTIFICATE_HOLD )
es_fputs( "certificate_hold", fp ), any = 1;
if (reason && !any)
es_fputs( "other", fp );
es_fprintf (fp, ") rdate: %.15s\n", record+1);
}
if (rc)
log_error (_("error reading cache entry from db: %s\n"), strerror (rc));
unlock_db_file (cache, e);
es_fprintf (fp, _("End CRL dump\n") );
es_putc ('\n', fp);
return (rc||warn)? gpg_error (GPG_ERR_GENERAL) : 0;
}
/* Print the contents of the CRL CACHE in a human readable format to
stream FP. */
gpg_error_t
crl_cache_list (estream_t fp)
{
crl_cache_t cache = get_current_cache ();
crl_cache_entry_t entry;
gpg_error_t err = 0;
for (entry = cache->entries;
entry && !entry->deleted && !err;
entry = entry->next )
err = list_one_crl_entry (cache, entry, fp);
return err;
}
/* Load the CRL containing the file named FILENAME into our CRL cache. */
gpg_error_t
crl_cache_load (ctrl_t ctrl, const char *filename)
{
gpg_error_t err;
estream_t fp;
ksba_reader_t reader;
fp = es_fopen (filename, "rb");
if (!fp)
{
err = gpg_error_from_errno (errno);
log_error (_("can't open '%s': %s\n"), filename, strerror (errno));
return err;
}
err = create_estream_ksba_reader (&reader, fp);
if (!err)
{
err = crl_cache_insert (ctrl, filename, reader);
ksba_reader_release (reader);
}
es_fclose (fp);
return err;
}
/* Locate the corresponding CRL for the certificate CERT, read and
verify the CRL and store it in the cache. */
gpg_error_t
crl_cache_reload_crl (ctrl_t ctrl, ksba_cert_t cert)
{
gpg_error_t err;
ksba_reader_t reader = NULL;
char *issuer = NULL;
ksba_name_t distpoint = NULL;
ksba_name_t issuername = NULL;
char *distpoint_uri = NULL;
char *issuername_uri = NULL;
int any_dist_point = 0;
int seq;
/* Loop over all distribution points, get the CRLs and put them into
the cache. */
if (opt.verbose)
log_info ("checking distribution points\n");
seq = 0;
while ( !(err = ksba_cert_get_crl_dist_point (cert, seq++,
&distpoint,
&issuername, NULL )))
{
int name_seq;
gpg_error_t last_err = 0;
if (!distpoint && !issuername)
{
if (opt.verbose)
log_info ("no issuer name and no distribution point\n");
break; /* Not allowed; i.e. an invalid certificate. We give
up here and hope that the default method returns a
suitable CRL. */
}
xfree (issuername_uri); issuername_uri = NULL;
/* Get the URIs. We do this in a loop to iterate over all names
in the crlDP. */
for (name_seq=0; ksba_name_enum (distpoint, name_seq); name_seq++)
{
xfree (distpoint_uri); distpoint_uri = NULL;
distpoint_uri = ksba_name_get_uri (distpoint, name_seq);
if (!distpoint_uri)
continue;
if (!strncmp (distpoint_uri, "ldap:", 5)
|| !strncmp (distpoint_uri, "ldaps:", 6))
{
if (opt.ignore_ldap_dp)
continue;
}
else if (!strncmp (distpoint_uri, "http:", 5)
|| !strncmp (distpoint_uri, "https:", 6))
{
if (opt.ignore_http_dp)
continue;
}
else
continue; /* Skip unknown schemes. */
any_dist_point = 1;
if (opt.verbose)
log_info ("fetching CRL from '%s'\n", distpoint_uri);
err = crl_fetch (ctrl, distpoint_uri, &reader);
if (err)
{
log_error (_("crl_fetch via DP failed: %s\n"),
gpg_strerror (err));
last_err = err;
continue; /* with the next name. */
}
if (opt.verbose)
log_info ("inserting CRL (reader %p)\n", reader);
err = crl_cache_insert (ctrl, distpoint_uri, reader);
if (err)
{
log_error (_("crl_cache_insert via DP failed: %s\n"),
gpg_strerror (err));
last_err = err;
continue; /* with the next name. */
}
last_err = 0;
break; /* Ready. */
}
if (last_err)
{
err = last_err;
goto leave;
}
ksba_name_release (distpoint); distpoint = NULL;
/* We don't do anything with issuername_uri yet but we keep the
code for documentation. */
issuername_uri = ksba_name_get_uri (issuername, 0);
ksba_name_release (issuername); issuername = NULL;
/* Close the reader. */
crl_close_reader (reader);
reader = NULL;
}
if (gpg_err_code (err) == GPG_ERR_EOF)
err = 0;
/* If we did not found any distpoint, try something reasonable. */
if (!any_dist_point )
{
if (opt.verbose)
log_info ("no distribution point - trying issuer name\n");
crl_close_reader (reader);
reader = NULL;
issuer = ksba_cert_get_issuer (cert, 0);
if (!issuer)
{
log_error ("oops: issuer missing in certificate\n");
err = gpg_error (GPG_ERR_INV_CERT_OBJ);
goto leave;
}
if (opt.verbose)
log_info ("fetching CRL from default location\n");
err = crl_fetch_default (ctrl, issuer, &reader);
if (err)
{
log_error ("crl_fetch via issuer failed: %s\n",
gpg_strerror (err));
goto leave;
}
if (opt.verbose)
log_info ("inserting CRL (reader %p)\n", reader);
err = crl_cache_insert (ctrl, "default location(s)", reader);
if (err)
{
log_error (_("crl_cache_insert via issuer failed: %s\n"),
gpg_strerror (err));
goto leave;
}
}
leave:
crl_close_reader (reader);
xfree (distpoint_uri);
xfree (issuername_uri);
ksba_name_release (distpoint);
ksba_name_release (issuername);
ksba_free (issuer);
return err;
}
diff --git a/dirmngr/dirmngr.c b/dirmngr/dirmngr.c
index 1696be578..80fb13476 100644
--- a/dirmngr/dirmngr.c
+++ b/dirmngr/dirmngr.c
@@ -1,2345 +1,2345 @@
/* dirmngr.c - Keyserver and X.509 LDAP access
* Copyright (C) 2002 Klarälvdalens Datakonsult AB
* Copyright (C) 2003, 2004, 2006, 2007, 2008, 2010, 2011 g10 Code GmbH
* Copyright (C) 2014 Werner Koch
*
* 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 .
*
* SPDX-License-Identifier: GPL-3.0+
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#ifndef HAVE_W32_SYSTEM
#include
#include
#endif
#include
#include
#ifdef HAVE_SIGNAL_H
# include
#endif
#ifdef HAVE_INOTIFY_INIT
# include
#endif /*HAVE_INOTIFY_INIT*/
#include
#include "dirmngr-err.h"
#if HTTP_USE_NTBTLS
# include
#elif HTTP_USE_GNUTLS
# include
#endif /*HTTP_USE_GNUTLS*/
#define GNUPG_COMMON_NEED_AFLOCAL
#include "dirmngr.h"
#include
#include "certcache.h"
#include "crlcache.h"
#include "crlfetch.h"
#include "misc.h"
#if USE_LDAP
# include "ldapserver.h"
#endif
#include "../common/asshelp.h"
#if USE_LDAP
# include "ldap-wrapper.h"
#endif
#include "../common/init.h"
#include "../common/gc-opt-flags.h"
#include "dns-stuff.h"
#include "http-common.h"
#ifndef ENAMETOOLONG
# define ENAMETOOLONG EINVAL
#endif
enum cmd_and_opt_values {
aNull = 0,
oCsh = 'c',
oQuiet = 'q',
oSh = 's',
oVerbose = 'v',
oNoVerbose = 500,
aServer,
aDaemon,
aSupervised,
aListCRLs,
aLoadCRL,
aFetchCRL,
aShutdown,
aFlush,
aGPGConfList,
aGPGConfTest,
oOptions,
oDebug,
oDebugAll,
oDebugWait,
oDebugLevel,
oGnutlsDebug,
oNoGreeting,
oNoOptions,
oHomedir,
oNoDetach,
oLogFile,
oBatch,
oDisableHTTP,
oDisableLDAP,
oDisableIPv4,
oDisableIPv6,
oIgnoreLDAPDP,
oIgnoreHTTPDP,
oIgnoreOCSPSvcUrl,
oHonorHTTPProxy,
oHTTPProxy,
oLDAPProxy,
oOnlyLDAPProxy,
oLDAPFile,
oLDAPTimeout,
oLDAPAddServers,
oOCSPResponder,
oOCSPSigner,
oOCSPMaxClockSkew,
oOCSPMaxPeriod,
oOCSPCurrentPeriod,
oMaxReplies,
oHkpCaCert,
oFakedSystemTime,
oForce,
oAllowOCSP,
oAllowVersionCheck,
oSocketName,
oLDAPWrapperProgram,
oHTTPWrapperProgram,
oIgnoreCertExtension,
oUseTor,
oNoUseTor,
oKeyServer,
oNameServer,
oDisableCheckOwnSocket,
oStandardResolver,
oRecursiveResolver,
oResolverTimeout,
oConnectTimeout,
oConnectQuickTimeout,
oListenBacklog,
aTest
};
static ARGPARSE_OPTS opts[] = {
ARGPARSE_group (300, N_("@Commands:\n ")),
ARGPARSE_c (aServer, "server", N_("run in server mode (foreground)") ),
ARGPARSE_c (aDaemon, "daemon", N_("run in daemon mode (background)") ),
#ifndef HAVE_W32_SYSTEM
ARGPARSE_c (aSupervised, "supervised", N_("run in supervised mode")),
#endif
ARGPARSE_c (aListCRLs, "list-crls", N_("list the contents of the CRL cache")),
ARGPARSE_c (aLoadCRL, "load-crl", N_("|FILE|load CRL from FILE into cache")),
ARGPARSE_c (aFetchCRL, "fetch-crl", N_("|URL|fetch a CRL from URL")),
ARGPARSE_c (aShutdown, "shutdown", N_("shutdown the dirmngr")),
ARGPARSE_c (aFlush, "flush", N_("flush the cache")),
ARGPARSE_c (aGPGConfList, "gpgconf-list", "@"),
ARGPARSE_c (aGPGConfTest, "gpgconf-test", "@"),
ARGPARSE_group (301, N_("@\nOptions:\n ")),
ARGPARSE_s_n (oVerbose, "verbose", N_("verbose")),
ARGPARSE_s_n (oQuiet, "quiet", N_("be somewhat more quiet")),
ARGPARSE_s_n (oSh, "sh", N_("sh-style command output")),
ARGPARSE_s_n (oCsh, "csh", N_("csh-style command output")),
ARGPARSE_s_s (oOptions, "options", N_("|FILE|read options from FILE")),
ARGPARSE_s_s (oDebugLevel, "debug-level",
N_("|LEVEL|set the debugging level to LEVEL")),
ARGPARSE_s_n (oNoDetach, "no-detach", N_("do not detach from the console")),
ARGPARSE_s_s (oLogFile, "log-file",
N_("|FILE|write server mode logs to FILE")),
ARGPARSE_s_n (oBatch, "batch", N_("run without asking a user")),
ARGPARSE_s_n (oForce, "force", N_("force loading of outdated CRLs")),
ARGPARSE_s_n (oAllowOCSP, "allow-ocsp", N_("allow sending OCSP requests")),
ARGPARSE_s_n (oAllowVersionCheck, "allow-version-check",
N_("allow online software version check")),
ARGPARSE_s_n (oDisableHTTP, "disable-http", N_("inhibit the use of HTTP")),
ARGPARSE_s_n (oDisableLDAP, "disable-ldap", N_("inhibit the use of LDAP")),
ARGPARSE_s_n (oIgnoreHTTPDP,"ignore-http-dp",
N_("ignore HTTP CRL distribution points")),
ARGPARSE_s_n (oIgnoreLDAPDP,"ignore-ldap-dp",
N_("ignore LDAP CRL distribution points")),
ARGPARSE_s_n (oIgnoreOCSPSvcUrl, "ignore-ocsp-service-url",
N_("ignore certificate contained OCSP service URLs")),
ARGPARSE_s_s (oHTTPProxy, "http-proxy",
N_("|URL|redirect all HTTP requests to URL")),
ARGPARSE_s_s (oLDAPProxy, "ldap-proxy",
N_("|HOST|use HOST for LDAP queries")),
ARGPARSE_s_n (oOnlyLDAPProxy, "only-ldap-proxy",
N_("do not use fallback hosts with --ldap-proxy")),
ARGPARSE_s_s (oLDAPFile, "ldapserverlist-file",
N_("|FILE|read LDAP server list from FILE")),
ARGPARSE_s_n (oLDAPAddServers, "add-servers",
N_("add new servers discovered in CRL distribution"
" points to serverlist")),
ARGPARSE_s_i (oLDAPTimeout, "ldaptimeout",
N_("|N|set LDAP timeout to N seconds")),
ARGPARSE_s_s (oOCSPResponder, "ocsp-responder",
N_("|URL|use OCSP responder at URL")),
ARGPARSE_s_s (oOCSPSigner, "ocsp-signer",
N_("|FPR|OCSP response signed by FPR")),
ARGPARSE_s_i (oOCSPMaxClockSkew, "ocsp-max-clock-skew", "@"),
ARGPARSE_s_i (oOCSPMaxPeriod, "ocsp-max-period", "@"),
ARGPARSE_s_i (oOCSPCurrentPeriod, "ocsp-current-period", "@"),
ARGPARSE_s_i (oMaxReplies, "max-replies",
N_("|N|do not return more than N items in one query")),
ARGPARSE_s_s (oNameServer, "nameserver", "@"),
ARGPARSE_s_s (oKeyServer, "keyserver", "@"),
ARGPARSE_s_s (oHkpCaCert, "hkp-cacert",
N_("|FILE|use the CA certificates in FILE for HKP over TLS")),
ARGPARSE_s_n (oUseTor, "use-tor", N_("route all network traffic via Tor")),
ARGPARSE_s_n (oNoUseTor, "no-use-tor", "@"),
ARGPARSE_s_n (oDisableIPv4, "disable-ipv4", "@"),
ARGPARSE_s_n (oDisableIPv6, "disable-ipv6", "@"),
ARGPARSE_s_s (oSocketName, "socket-name", "@"), /* Only for debugging. */
ARGPARSE_s_u (oFakedSystemTime, "faked-system-time", "@"), /*(epoch time)*/
ARGPARSE_s_s (oDebug, "debug", "@"),
ARGPARSE_s_n (oDebugAll, "debug-all", "@"),
ARGPARSE_s_i (oGnutlsDebug, "gnutls-debug", "@"),
ARGPARSE_s_i (oGnutlsDebug, "tls-debug", "@"),
ARGPARSE_s_i (oDebugWait, "debug-wait", "@"),
ARGPARSE_s_n (oDisableCheckOwnSocket, "disable-check-own-socket", "@"),
ARGPARSE_s_n (oNoGreeting, "no-greeting", "@"),
ARGPARSE_s_s (oHomedir, "homedir", "@"),
ARGPARSE_s_s (oLDAPWrapperProgram, "ldap-wrapper-program", "@"),
ARGPARSE_s_s (oHTTPWrapperProgram, "http-wrapper-program", "@"),
ARGPARSE_s_n (oHonorHTTPProxy, "honor-http-proxy", "@"),
ARGPARSE_s_s (oIgnoreCertExtension,"ignore-cert-extension", "@"),
ARGPARSE_s_n (oStandardResolver, "standard-resolver", "@"),
ARGPARSE_s_n (oRecursiveResolver, "recursive-resolver", "@"),
ARGPARSE_s_i (oResolverTimeout, "resolver-timeout", "@"),
ARGPARSE_s_i (oConnectTimeout, "connect-timeout", "@"),
ARGPARSE_s_i (oConnectQuickTimeout, "connect-quick-timeout", "@"),
ARGPARSE_s_i (oListenBacklog, "listen-backlog", "@"),
ARGPARSE_group (302,N_("@\n(See the \"info\" manual 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_CRYPTO_VALUE , "crypto" },
{ DBG_MEMORY_VALUE , "memory" },
{ DBG_CACHE_VALUE , "cache" },
{ DBG_MEMSTAT_VALUE, "memstat" },
{ DBG_HASHING_VALUE, "hashing" },
{ DBG_IPC_VALUE , "ipc" },
{ DBG_DNS_VALUE , "dns" },
{ DBG_NETWORK_VALUE, "network" },
{ DBG_LOOKUP_VALUE , "lookup" },
{ DBG_EXTPROG_VALUE, "extprog" },
{ 77, NULL } /* 77 := Do not exit on "help" or "?". */
};
#define DEFAULT_MAX_REPLIES 10
#define DEFAULT_LDAP_TIMEOUT 15 /* seconds */
#define DEFAULT_CONNECT_TIMEOUT (15*1000) /* 15 seconds */
#define DEFAULT_CONNECT_QUICK_TIMEOUT ( 2*1000) /* 2 seconds */
/* For the cleanup handler we need to keep track of the socket's name. */
static const char *socket_name;
/* If the socket has been redirected, this is the name of the
redirected socket.. */
static const char *redir_socket_name;
/* We need to keep track of the server's nonces (these are dummies for
POSIX systems). */
static assuan_sock_nonce_t socket_nonce;
/* Value for the listen() backlog argument.
* Change at runtime with --listen-backlog. */
static int listen_backlog = 64;
/* Only if this flag has been set will we remove the socket file. */
static int cleanup_socket;
/* Keep track of the current log file so that we can avoid updating
the log file after a SIGHUP if it didn't changed. Malloced. */
static char *current_logfile;
/* Helper to implement --debug-level. */
static const char *debug_level;
/* Helper to set the NTBTLS or GNUTLS log level. */
static int opt_gnutls_debug = -1;
/* Flag indicating that a shutdown has been requested. */
static volatile int shutdown_pending;
/* Flags to indicate that we shall not watch our own socket. */
static int disable_check_own_socket;
/* Flag to control the Tor mode. */
static enum
{ TOR_MODE_AUTO = 0, /* Switch to NO or YES */
TOR_MODE_NEVER, /* Never use Tor. */
TOR_MODE_NO, /* Do not use Tor */
TOR_MODE_YES, /* Use Tor */
TOR_MODE_FORCE /* Force using Tor */
} tor_mode;
/* Counter for the active connections. */
static int active_connections;
/* This flag is set by any network access and used by the housekeeping
* thread to run background network tasks. */
static int network_activity_seen;
-/* A list of filenames registred with --hkp-cacert. */
+/* A list of filenames registered with --hkp-cacert. */
static strlist_t hkp_cacert_filenames;
/* The timer tick used for housekeeping stuff. The second constant is used when a shutdown is pending. */
#define TIMERTICK_INTERVAL (60)
#define TIMERTICK_INTERVAL_SHUTDOWN (4)
/* How oft to run the housekeeping. */
#define HOUSEKEEPING_INTERVAL (600)
/* This union is used to avoid compiler warnings in case a pointer is
64 bit and an int 32 bit. We store an integer in a pointer and get
it back later (npth_getspecific et al.). */
union int_and_ptr_u
{
int aint;
assuan_fd_t afd;
void *aptr;
};
/* The key used to store the current file descriptor in the thread
local storage. We use this in conjunction with the
log_set_pid_suffix_cb feature. */
#ifndef HAVE_W32_SYSTEM
static npth_key_t my_tlskey_current_fd;
#endif
/* Prototypes. */
static void cleanup (void);
#if USE_LDAP
static ldap_server_t parse_ldapserver_file (const char* filename);
#endif /*USE_LDAP*/
static fingerprint_list_t parse_ocsp_signer (const char *string);
static void netactivity_action (void);
static void handle_connections (assuan_fd_t listen_fd);
/* NPth wrapper function definitions. */
ASSUAN_SYSTEM_NPTH_IMPL;
static const char *
my_strusage( int level )
{
const char *p;
switch ( level )
{
case 11: p = "@DIRMNGR@ (@GNUPG@)";
break;
case 13: p = VERSION; break;
case 17: p = PRINTABLE_OS_NAME; break;
/* TRANSLATORS: @EMAIL@ will get replaced by the actual bug
reporting address. This is so that we can change the
reporting address without breaking the translations. */
case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
case 49: p = PACKAGE_BUGREPORT; break;
case 1:
case 40: p = _("Usage: @DIRMNGR@ [options] (-h for help)");
break;
case 41: p = _("Syntax: @DIRMNGR@ [options] [command [args]]\n"
"Keyserver, CRL, and OCSP access for @GNUPG@\n");
break;
default: p = NULL;
}
return p;
}
/* Callback from libksba to hash a provided buffer. Our current
implementation does only allow SHA-1 for hashing. This may be
- extended by mapping the name, testing for algorithm availibility
+ extended by mapping the name, testing for algorithm availability
and adjust the length checks accordingly. */
static gpg_error_t
my_ksba_hash_buffer (void *arg, const char *oid,
const void *buffer, size_t length, size_t resultsize,
unsigned char *result, size_t *resultlen)
{
(void)arg;
if (oid && strcmp (oid, "1.3.14.3.2.26"))
return gpg_error (GPG_ERR_NOT_SUPPORTED);
if (resultsize < 20)
return gpg_error (GPG_ERR_BUFFER_TOO_SHORT);
gcry_md_hash_buffer (2, result, buffer, length);
*resultlen = 20;
return 0;
}
/* GNUTLS log function callback. */
#ifdef HTTP_USE_GNUTLS
static void
my_gnutls_log (int level, const char *text)
{
int n;
n = strlen (text);
while (n && text[n-1] == '\n')
n--;
log_debug ("gnutls:L%d: %.*s\n", level, n, text);
}
#endif /*HTTP_USE_GNUTLS*/
/* Setup the debugging. With a LEVEL of NULL only the active debug
flags are propagated to the subsystems. With LEVEL set, a specific
set of debug flags is set; thus overriding all flags already
set. */
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|DBG_LOOKUP_VALUE);
else if (!strcmp (debug_level, "expert") || (numok && numlvl <= 8))
opt.debug = (DBG_IPC_VALUE|DBG_X509_VALUE|DBG_LOOKUP_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);
log_info (_("valid debug levels are: %s\n"),
"none, basic, advanced, expert, guru");
opt.debug = 0; /* Reset debugging, so that prior debug
statements won't have an undesired effect. */
}
if (opt.debug && !opt.verbose)
{
opt.verbose = 1;
gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
}
if (opt.debug && opt.quiet)
opt.quiet = 0;
if (opt.debug & DBG_CRYPTO_VALUE )
gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1);
#if HTTP_USE_NTBTLS
if (opt_gnutls_debug >= 0)
{
ntbtls_set_debug (opt_gnutls_debug, NULL, NULL);
}
#elif HTTP_USE_GNUTLS
if (opt_gnutls_debug >= 0)
{
gnutls_global_set_log_function (my_gnutls_log);
gnutls_global_set_log_level (opt_gnutls_debug);
}
#endif /*HTTP_USE_GNUTLS*/
if (opt.debug)
parse_debug_flag (NULL, &opt.debug, debug_flags);
}
static void
set_tor_mode (void)
{
if (dirmngr_use_tor ())
{
- /* Enable Tor mode and when called again force a new curcuit
+ /* Enable Tor mode and when called again force a new circuit
* (e.g. on SIGHUP). */
enable_dns_tormode (1);
if (assuan_sock_set_flag (ASSUAN_INVALID_FD, "tor-mode", 1))
{
log_error ("error enabling Tor mode: %s\n", strerror (errno));
log_info ("(is your Libassuan recent enough?)\n");
}
}
else
disable_dns_tormode ();
}
/* Return true if Tor shall be used. */
int
dirmngr_use_tor (void)
{
if (tor_mode == TOR_MODE_AUTO)
{
/* Figure out whether Tor is running. */
assuan_fd_t sock;
sock = assuan_sock_connect_byname (NULL, 0, 0, NULL, ASSUAN_SOCK_TOR);
if (sock == ASSUAN_INVALID_FD)
tor_mode = TOR_MODE_NO;
else
{
tor_mode = TOR_MODE_YES;
assuan_sock_close (sock);
}
}
if (tor_mode == TOR_MODE_FORCE)
return 2; /* Use Tor (using 2 to indicate force mode) */
else if (tor_mode == TOR_MODE_YES)
return 1; /* Use Tor */
else
return 0; /* Do not use Tor. */
}
static void
wrong_args (const char *text)
{
es_fprintf (es_stderr, _("usage: %s [options] "), DIRMNGR_NAME);
es_fputs (text, es_stderr);
es_putc ('\n', es_stderr);
dirmngr_exit (2);
}
/* Helper to stop the reaper thread for the ldap wrapper. */
static void
shutdown_reaper (void)
{
#if USE_LDAP
ldap_wrapper_wait_connections ();
#endif
}
/* Handle options which are allowed to be reset after program start.
Return true if the current option in PARGS could be handled and
false if not. As a special feature, passing a value of NULL for
PARGS, resets the options to the default. REREAD should be set
true if it is not the initial option parsing. */
static int
parse_rereadable_options (ARGPARSE_ARGS *pargs, int reread)
{
if (!pargs)
{ /* Reset mode. */
opt.quiet = 0;
opt.verbose = 0;
opt.debug = 0;
opt.ldap_wrapper_program = NULL;
opt.disable_http = 0;
opt.disable_ldap = 0;
opt.honor_http_proxy = 0;
opt.http_proxy = NULL;
opt.ldap_proxy = NULL;
opt.only_ldap_proxy = 0;
opt.ignore_http_dp = 0;
opt.ignore_ldap_dp = 0;
opt.ignore_ocsp_service_url = 0;
opt.allow_ocsp = 0;
opt.allow_version_check = 0;
opt.ocsp_responder = NULL;
opt.ocsp_max_clock_skew = 10 * 60; /* 10 minutes. */
opt.ocsp_max_period = 90 * 86400; /* 90 days. */
opt.ocsp_current_period = 3 * 60 * 60; /* 3 hours. */
opt.max_replies = DEFAULT_MAX_REPLIES;
while (opt.ocsp_signer)
{
fingerprint_list_t tmp = opt.ocsp_signer->next;
xfree (opt.ocsp_signer);
opt.ocsp_signer = tmp;
}
FREE_STRLIST (opt.ignored_cert_extensions);
http_register_tls_ca (NULL);
FREE_STRLIST (hkp_cacert_filenames);
FREE_STRLIST (opt.keyserver);
/* Note: We do not allow resetting of TOR_MODE_FORCE at runtime. */
if (tor_mode != TOR_MODE_FORCE)
tor_mode = TOR_MODE_AUTO;
disable_check_own_socket = 0;
enable_standard_resolver (0);
set_dns_timeout (0);
opt.connect_timeout = 0;
opt.connect_quick_timeout = 0;
return 1;
}
switch (pargs->r_opt)
{
case oQuiet: opt.quiet = 1; break;
case oVerbose: opt.verbose++; break;
case oDebug:
parse_debug_flag (pargs->r.ret_str, &opt.debug, debug_flags);
break;
case oDebugAll: opt.debug = ~0; break;
case oDebugLevel: debug_level = pargs->r.ret_str; break;
case oGnutlsDebug: opt_gnutls_debug = pargs->r.ret_int; break;
case oLogFile:
if (!reread)
return 0; /* Not handled. */
if (!current_logfile || !pargs->r.ret_str
|| strcmp (current_logfile, pargs->r.ret_str))
{
log_set_file (pargs->r.ret_str);
xfree (current_logfile);
current_logfile = xtrystrdup (pargs->r.ret_str);
}
break;
case oDisableCheckOwnSocket: disable_check_own_socket = 1; break;
case oLDAPWrapperProgram:
opt.ldap_wrapper_program = pargs->r.ret_str;
break;
case oHTTPWrapperProgram:
opt.http_wrapper_program = pargs->r.ret_str;
break;
case oDisableHTTP: opt.disable_http = 1; break;
case oDisableLDAP: opt.disable_ldap = 1; break;
case oDisableIPv4: opt.disable_ipv4 = 1; break;
case oDisableIPv6: opt.disable_ipv6 = 1; break;
case oHonorHTTPProxy: opt.honor_http_proxy = 1; break;
case oHTTPProxy: opt.http_proxy = pargs->r.ret_str; break;
case oLDAPProxy: opt.ldap_proxy = pargs->r.ret_str; break;
case oOnlyLDAPProxy: opt.only_ldap_proxy = 1; break;
case oIgnoreHTTPDP: opt.ignore_http_dp = 1; break;
case oIgnoreLDAPDP: opt.ignore_ldap_dp = 1; break;
case oIgnoreOCSPSvcUrl: opt.ignore_ocsp_service_url = 1; break;
case oAllowOCSP: opt.allow_ocsp = 1; break;
case oAllowVersionCheck: opt.allow_version_check = 1; break;
case oOCSPResponder: opt.ocsp_responder = pargs->r.ret_str; break;
case oOCSPSigner:
opt.ocsp_signer = parse_ocsp_signer (pargs->r.ret_str);
break;
case oOCSPMaxClockSkew: opt.ocsp_max_clock_skew = pargs->r.ret_int; break;
case oOCSPMaxPeriod: opt.ocsp_max_period = pargs->r.ret_int; break;
case oOCSPCurrentPeriod: opt.ocsp_current_period = pargs->r.ret_int; break;
case oMaxReplies: opt.max_replies = pargs->r.ret_int; break;
case oHkpCaCert:
{
/* We need to register the filenames with gnutls (http.c) and
* also for our own cert cache. */
char *tmpname;
/* Do tilde expansion and make path absolute. */
tmpname = make_absfilename (pargs->r.ret_str, NULL);
http_register_tls_ca (tmpname);
add_to_strlist (&hkp_cacert_filenames, pargs->r.ret_str);
xfree (tmpname);
}
break;
case oIgnoreCertExtension:
add_to_strlist (&opt.ignored_cert_extensions, pargs->r.ret_str);
break;
case oUseTor:
tor_mode = TOR_MODE_FORCE;
break;
case oNoUseTor:
if (tor_mode != TOR_MODE_FORCE)
tor_mode = TOR_MODE_NEVER;
break;
case oStandardResolver: enable_standard_resolver (1); break;
case oRecursiveResolver: enable_recursive_resolver (1); break;
case oKeyServer:
if (*pargs->r.ret_str)
add_to_strlist (&opt.keyserver, pargs->r.ret_str);
break;
case oNameServer:
set_dns_nameserver (pargs->r.ret_str);
break;
case oResolverTimeout:
set_dns_timeout (pargs->r.ret_int);
break;
case oConnectTimeout:
opt.connect_timeout = pargs->r.ret_ulong * 1000;
break;
case oConnectQuickTimeout:
opt.connect_quick_timeout = pargs->r.ret_ulong * 1000;
break;
default:
return 0; /* Not handled. */
}
set_dns_verbose (opt.verbose, !!DBG_DNS);
http_set_verbose (opt.verbose, !!DBG_NETWORK);
set_dns_disable_ipv4 (opt.disable_ipv4);
set_dns_disable_ipv6 (opt.disable_ipv6);
return 1; /* Handled. */
}
-/* This fucntion is called after option parsing to adjust some values
+/* This function is called after option parsing to adjust some values
* and call option setup functions. */
static void
post_option_parsing (void)
{
/* It would be too surpirsing if the quick timeout is larger than
* the standard value. */
if (opt.connect_quick_timeout > opt.connect_timeout)
opt.connect_quick_timeout = opt.connect_timeout;
set_debug ();
set_tor_mode ();
}
#ifndef HAVE_W32_SYSTEM
static int
pid_suffix_callback (unsigned long *r_suffix)
{
union int_and_ptr_u value;
memset (&value, 0, sizeof value);
value.aptr = npth_getspecific (my_tlskey_current_fd);
*r_suffix = value.aint;
return (*r_suffix != -1); /* Use decimal representation. */
}
#endif /*!HAVE_W32_SYSTEM*/
#if HTTP_USE_NTBTLS
static void
my_ntbtls_log_handler (void *opaque, int level, const char *fmt, va_list argv)
{
(void)opaque;
if (level == -1)
log_logv_prefix (GPGRT_LOGLVL_INFO, "ntbtls: ", fmt, argv);
else
{
char prefix[10+20];
snprintf (prefix, sizeof prefix, "ntbtls(%d): ", level);
log_logv_prefix (GPGRT_LOGLVL_DEBUG, prefix, fmt, argv);
}
}
#endif
static void
thread_init (void)
{
npth_init ();
gpgrt_set_syscall_clamp (npth_unprotect, npth_protect);
/* Now with NPth running we can set the logging callback. Our
windows implementation does not yet feature the NPth TLS
functions. */
#ifndef HAVE_W32_SYSTEM
if (npth_key_create (&my_tlskey_current_fd, NULL) == 0)
if (npth_setspecific (my_tlskey_current_fd, NULL) == 0)
log_set_pid_suffix_cb (pid_suffix_callback);
#endif /*!HAVE_W32_SYSTEM*/
}
int
main (int argc, char **argv)
{
enum cmd_and_opt_values cmd = 0;
ARGPARSE_ARGS pargs;
int orig_argc;
char **orig_argv;
FILE *configfp = NULL;
char *configname = NULL;
const char *shell;
unsigned configlineno;
int parse_debug = 0;
int default_config =1;
int greeting = 0;
int nogreeting = 0;
int nodetach = 0;
int csh_style = 0;
char *logfile = NULL;
#if USE_LDAP
char *ldapfile = NULL;
#endif /*USE_LDAP*/
int debug_wait = 0;
int rc;
struct assuan_malloc_hooks malloc_hooks;
early_system_init ();
set_strusage (my_strusage);
log_set_prefix (DIRMNGR_NAME, GPGRT_LOG_WITH_PREFIX | GPGRT_LOG_WITH_PID);
/* Make sure that our subsystems are ready. */
i18n_init ();
init_common_subsystems (&argc, &argv);
gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
/* Check that the libraries are suitable. Do it here because
the option parsing may need services of the libraries. */
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) );
ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free );
ksba_set_hash_buffer_function (my_ksba_hash_buffer, NULL);
/* Init TLS library. */
#if HTTP_USE_NTBTLS
if (!ntbtls_check_version (NEED_NTBTLS_VERSION) )
log_fatal( _("%s is too old (need %s, have %s)\n"), "ntbtls",
NEED_NTBTLS_VERSION, ntbtls_check_version (NULL) );
#elif HTTP_USE_GNUTLS
rc = gnutls_global_init ();
if (rc)
log_fatal ("gnutls_global_init failed: %s\n", gnutls_strerror (rc));
#endif /*HTTP_USE_GNUTLS*/
/* Init Assuan. */
malloc_hooks.malloc = gcry_malloc;
malloc_hooks.realloc = gcry_realloc;
malloc_hooks.free = gcry_free;
assuan_set_malloc_hooks (&malloc_hooks);
assuan_set_assuan_log_prefix (log_get_prefix (NULL));
assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);
assuan_sock_init ();
setup_libassuan_logging (&opt.debug, dirmngr_assuan_log_monitor);
setup_libgcrypt_logging ();
#if HTTP_USE_NTBTLS
ntbtls_set_log_handler (my_ntbtls_log_handler, NULL);
#endif
/* Setup defaults. */
shell = getenv ("SHELL");
if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
csh_style = 1;
/* Reset rereadable options to default values. */
parse_rereadable_options (NULL, 0);
/* Default TCP timeouts. */
opt.connect_timeout = DEFAULT_CONNECT_TIMEOUT;
opt.connect_quick_timeout = DEFAULT_CONNECT_QUICK_TIMEOUT;
/* LDAP defaults. */
opt.add_new_ldapservers = 0;
opt.ldaptimeout = DEFAULT_LDAP_TIMEOUT;
/* Other defaults. */
/* Check whether we have a config file given on the commandline */
orig_argc = argc;
orig_argv = argv;
pargs.argc = &argc;
pargs.argv = &argv;
pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
while (arg_parse( &pargs, opts))
{
if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
parse_debug++;
else if (pargs.r_opt == oOptions)
{ /* Yes there is one, so we do not try the default one, but
read the option file when it is encountered at the
commandline */
default_config = 0;
}
else if (pargs.r_opt == oNoOptions)
default_config = 0; /* --no-options */
else if (pargs.r_opt == oHomedir)
{
gnupg_set_homedir (pargs.r.ret_str);
}
}
socket_name = dirmngr_socket_name ();
if (default_config)
configname = make_filename (gnupg_homedir (), DIRMNGR_NAME".conf", NULL );
argc = orig_argc;
argv = orig_argv;
pargs.argc = &argc;
pargs.argv = &argv;
pargs.flags= 1; /* do not remove the args */
next_pass:
if (configname)
{
configlineno = 0;
configfp = fopen (configname, "r");
if (!configfp)
{
if (default_config)
{
if( parse_debug )
log_info (_("Note: no default option file '%s'\n"),
configname );
}
else
{
log_error (_("option file '%s': %s\n"),
configname, strerror(errno) );
exit(2);
}
xfree (configname);
configname = NULL;
}
if (parse_debug && configname )
log_info (_("reading options from '%s'\n"), configname );
default_config = 0;
}
while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
{
if (parse_rereadable_options (&pargs, 0))
continue; /* Already handled */
switch (pargs.r_opt)
{
case aServer:
case aDaemon:
case aSupervised:
case aShutdown:
case aFlush:
case aListCRLs:
case aLoadCRL:
case aFetchCRL:
case aGPGConfList:
case aGPGConfTest:
cmd = pargs.r_opt;
break;
case oQuiet: opt.quiet = 1; break;
case oVerbose: opt.verbose++; break;
case oBatch: opt.batch=1; break;
case oDebugWait: debug_wait = pargs.r.ret_int; break;
case oOptions:
/* Config files may not be nested (silently ignore them) */
if (!configfp)
{
xfree(configname);
configname = xstrdup(pargs.r.ret_str);
goto next_pass;
}
break;
case oNoGreeting: nogreeting = 1; break;
case oNoVerbose: opt.verbose = 0; break;
case oNoOptions: break; /* no-options */
case oHomedir: /* Ignore this option here. */; break;
case oNoDetach: nodetach = 1; break;
case oLogFile: logfile = pargs.r.ret_str; break;
case oCsh: csh_style = 1; break;
case oSh: csh_style = 0; break;
case oLDAPFile:
# if USE_LDAP
ldapfile = pargs.r.ret_str;
# endif /*USE_LDAP*/
break;
case oLDAPAddServers: opt.add_new_ldapservers = 1; break;
case oLDAPTimeout:
opt.ldaptimeout = pargs.r.ret_int;
break;
case oFakedSystemTime:
gnupg_set_time ((time_t)pargs.r.ret_ulong, 0);
break;
case oForce: opt.force = 1; break;
case oSocketName: socket_name = pargs.r.ret_str; break;
case oListenBacklog:
listen_backlog = pargs.r.ret_int;
break;
default : pargs.err = configfp? 1:2; break;
}
}
if (configfp)
{
fclose (configfp);
configfp = NULL;
/* Keep a copy of the name so that it can be read on SIGHUP. */
opt.config_filename = configname;
configname = NULL;
goto next_pass;
}
xfree (configname);
configname = NULL;
if (log_get_errorcount(0))
exit(2);
if (nogreeting )
greeting = 0;
if (!opt.homedir_cache)
opt.homedir_cache = xstrdup (gnupg_homedir ());
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
log_info ("NOTE: this is a development version!\n");
#endif
/* 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]);
}
if (!access ("/etc/"DIRMNGR_NAME, F_OK)
&& !strncmp (gnupg_homedir (), "/etc/", 5))
log_info
("NOTE: DirMngr is now a proper part of %s. The configuration and"
" other directory names changed. Please check that no other version"
" of dirmngr is still installed. To disable this warning, remove the"
" directory '/etc/dirmngr'.\n", GNUPG_NAME);
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");
}
post_option_parsing ();
/* Get LDAP server list from file. */
#if USE_LDAP
if (!ldapfile)
{
ldapfile = make_filename (gnupg_homedir (),
"dirmngr_ldapservers.conf",
NULL);
opt.ldapservers = parse_ldapserver_file (ldapfile);
xfree (ldapfile);
}
else
opt.ldapservers = parse_ldapserver_file (ldapfile);
#endif /*USE_LDAP*/
#ifndef HAVE_W32_SYSTEM
/* We need to ignore the PIPE signal because the we might log to a
socket and that code handles EPIPE properly. The ldap wrapper
also requires us to ignore this silly signal. Assuan would set
this signal to ignore anyway.*/
signal (SIGPIPE, SIG_IGN);
#endif
/* Ready. Now to our duties. */
if (!cmd)
cmd = aServer;
rc = 0;
if (cmd == aServer)
{
/* Note that this server mode is mainly useful for debugging. */
if (argc)
wrong_args ("--server");
if (logfile)
{
log_set_file (logfile);
log_set_prefix (NULL, GPGRT_LOG_WITH_TIME | GPGRT_LOG_WITH_PID);
}
if (debug_wait)
{
log_debug ("waiting for debugger - my pid is %u .....\n",
(unsigned int)getpid());
gnupg_sleep (debug_wait);
log_debug ("... okay\n");
}
thread_init ();
cert_cache_init (hkp_cacert_filenames);
crl_cache_init ();
ks_hkp_init ();
http_register_netactivity_cb (netactivity_action);
start_command_handler (ASSUAN_INVALID_FD, 0);
shutdown_reaper ();
}
#ifndef HAVE_W32_SYSTEM
else if (cmd == aSupervised)
{
/* In supervised mode, we expect file descriptor 3 to be an
already opened, listening socket.
We will also not detach from the controlling process or close
stderr; the supervisor should handle all of that. */
struct stat statbuf;
if (fstat (3, &statbuf) == -1 && errno == EBADF)
{
log_error ("file descriptor 3 must be validin --supervised mode\n");
dirmngr_exit (1);
}
socket_name = gnupg_get_socket_name (3);
/* Now start with logging to a file if this is desired. */
if (logfile)
{
log_set_file (logfile);
log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
|GPGRT_LOG_WITH_TIME
|GPGRT_LOG_WITH_PID));
current_logfile = xstrdup (logfile);
}
else
log_set_prefix (NULL, 0);
thread_init ();
cert_cache_init (hkp_cacert_filenames);
crl_cache_init ();
ks_hkp_init ();
http_register_netactivity_cb (netactivity_action);
handle_connections (3);
shutdown_reaper ();
}
#endif /*HAVE_W32_SYSTEM*/
else if (cmd == aDaemon)
{
assuan_fd_t fd;
pid_t pid;
int len;
struct sockaddr_un serv_addr;
if (argc)
wrong_args ("--daemon");
/* Now start with logging to a file if this is desired. */
if (logfile)
{
log_set_file (logfile);
log_set_prefix (NULL, (GPGRT_LOG_WITH_PREFIX
|GPGRT_LOG_WITH_TIME
|GPGRT_LOG_WITH_PID));
current_logfile = xstrdup (logfile);
}
if (debug_wait)
{
log_debug ("waiting for debugger - my pid is %u .....\n",
(unsigned int)getpid());
gnupg_sleep (debug_wait);
log_debug ("... okay\n");
}
#ifndef HAVE_W32_SYSTEM
if (strchr (socket_name, ':'))
{
log_error (_("colons are not allowed in the socket name\n"));
dirmngr_exit (1);
}
#endif
fd = assuan_sock_new (AF_UNIX, SOCK_STREAM, 0);
if (fd == ASSUAN_INVALID_FD)
{
log_error (_("can't create socket: %s\n"), strerror (errno));
cleanup ();
dirmngr_exit (1);
}
{
int redirected;
if (assuan_sock_set_sockaddr_un (socket_name,
(struct sockaddr*)&serv_addr,
&redirected))
{
if (errno == ENAMETOOLONG)
log_error (_("socket name '%s' is too long\n"), socket_name);
else
log_error ("error preparing socket '%s': %s\n",
socket_name,
gpg_strerror (gpg_error_from_syserror ()));
dirmngr_exit (1);
}
if (redirected)
{
redir_socket_name = xstrdup (serv_addr.sun_path);
if (opt.verbose)
log_info ("redirecting socket '%s' to '%s'\n",
socket_name, redir_socket_name);
}
}
len = SUN_LEN (&serv_addr);
rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len);
if (rc == -1
&& (errno == EADDRINUSE
#ifdef HAVE_W32_SYSTEM
|| errno == EEXIST
#endif
))
{
/* Fixme: We should test whether a dirmngr is already running. */
gnupg_remove (redir_socket_name? redir_socket_name : socket_name);
rc = assuan_sock_bind (fd, (struct sockaddr*) &serv_addr, len);
}
if (rc != -1
&& (rc = assuan_sock_get_nonce ((struct sockaddr*) &serv_addr, len, &socket_nonce)))
log_error (_("error getting nonce for the socket\n"));
if (rc == -1)
{
log_error (_("error binding socket to '%s': %s\n"),
serv_addr.sun_path,
gpg_strerror (gpg_error_from_errno (errno)));
assuan_sock_close (fd);
dirmngr_exit (1);
}
cleanup_socket = 1;
if (gnupg_chmod (serv_addr.sun_path, "-rwx"))
log_error (_("can't set permissions of '%s': %s\n"),
serv_addr.sun_path, strerror (errno));
if (listen (FD2INT (fd), listen_backlog) == -1)
{
log_error ("listen(fd,%d) failed: %s\n",
listen_backlog, strerror (errno));
assuan_sock_close (fd);
dirmngr_exit (1);
}
if (opt.verbose)
log_info (_("listening on socket '%s'\n"), serv_addr.sun_path);
es_fflush (NULL);
/* Note: We keep the dirmngr_info output only for the sake of
existing scripts which might use this to detect a successful
start of the dirmngr. */
#ifdef HAVE_W32_SYSTEM
(void)csh_style;
(void)nodetach;
pid = getpid ();
es_printf ("set %s=%s;%lu;1\n",
DIRMNGR_INFO_NAME, socket_name, (ulong) pid);
#else
pid = fork();
if (pid == (pid_t)-1)
{
log_fatal (_("error forking process: %s\n"), strerror (errno));
dirmngr_exit (1);
}
if (pid)
{ /* We are the parent */
char *infostr;
/* Don't let cleanup() remove the socket - the child is
responsible for doing that. */
cleanup_socket = 0;
close (fd);
/* Create the info string: :: */
if (asprintf (&infostr, "%s=%s:%lu:1",
DIRMNGR_INFO_NAME, serv_addr.sun_path, (ulong)pid ) < 0)
{
log_error (_("out of core\n"));
kill (pid, SIGTERM);
dirmngr_exit (1);
}
/* Print the environment string, so that the caller can use
shell's eval to set it. But see above. */
if (csh_style)
{
*strchr (infostr, '=') = ' ';
es_printf ( "setenv %s;\n", infostr);
}
else
{
es_printf ( "%s; export %s;\n", infostr, DIRMNGR_INFO_NAME);
}
free (infostr);
exit (0);
/*NEVER REACHED*/
} /* end parent */
/*
This is the child
*/
/* Detach from tty and put process into a new session */
if (!nodetach )
{
int i;
unsigned int oldflags;
/* Close stdin, stdout and stderr unless it is the log stream */
for (i=0; i <= 2; i++)
{
if (!log_test_fd (i) && i != fd )
{
if ( !close (i)
&& open ("/dev/null", i? O_WRONLY : O_RDONLY) == -1)
{
log_error ("failed to open '%s': %s\n",
"/dev/null", strerror (errno));
cleanup ();
dirmngr_exit (1);
}
}
}
if (setsid() == -1)
{
log_error ("setsid() failed: %s\n", strerror(errno) );
dirmngr_exit (1);
}
log_get_prefix (&oldflags);
log_set_prefix (NULL, oldflags | GPGRT_LOG_RUN_DETACHED);
opt.running_detached = 1;
}
#endif
if (!nodetach )
{
if (gnupg_chdir (gnupg_daemon_rootdir ()))
{
log_error ("chdir to '%s' failed: %s\n",
gnupg_daemon_rootdir (), strerror (errno));
dirmngr_exit (1);
}
}
thread_init ();
cert_cache_init (hkp_cacert_filenames);
crl_cache_init ();
ks_hkp_init ();
http_register_netactivity_cb (netactivity_action);
handle_connections (fd);
shutdown_reaper ();
}
else if (cmd == aListCRLs)
{
/* Just list the CRL cache and exit. */
if (argc)
wrong_args ("--list-crls");
crl_cache_init ();
crl_cache_list (es_stdout);
}
else if (cmd == aLoadCRL)
{
struct server_control_s ctrlbuf;
memset (&ctrlbuf, 0, sizeof ctrlbuf);
dirmngr_init_default_ctrl (&ctrlbuf);
thread_init ();
cert_cache_init (hkp_cacert_filenames);
crl_cache_init ();
ks_hkp_init ();
if (!argc)
rc = crl_cache_load (&ctrlbuf, NULL);
else
{
for (; !rc && argc; argc--, argv++)
rc = crl_cache_load (&ctrlbuf, *argv);
}
dirmngr_deinit_default_ctrl (&ctrlbuf);
}
else if (cmd == aFetchCRL)
{
ksba_reader_t reader;
struct server_control_s ctrlbuf;
if (argc != 1)
wrong_args ("--fetch-crl URL");
memset (&ctrlbuf, 0, sizeof ctrlbuf);
dirmngr_init_default_ctrl (&ctrlbuf);
thread_init ();
cert_cache_init (hkp_cacert_filenames);
crl_cache_init ();
ks_hkp_init ();
rc = crl_fetch (&ctrlbuf, argv[0], &reader);
if (rc)
log_error (_("fetching CRL from '%s' failed: %s\n"),
argv[0], gpg_strerror (rc));
else
{
rc = crl_cache_insert (&ctrlbuf, argv[0], reader);
if (rc)
log_error (_("processing CRL from '%s' failed: %s\n"),
argv[0], gpg_strerror (rc));
crl_close_reader (reader);
}
dirmngr_deinit_default_ctrl (&ctrlbuf);
}
else if (cmd == aFlush)
{
/* Delete cache and exit. */
if (argc)
wrong_args ("--flush");
rc = crl_cache_flush();
}
else if (cmd == aGPGConfTest)
dirmngr_exit (0);
else if (cmd == aGPGConfList)
{
unsigned long flags = 0;
char *filename;
char *filename_esc;
/* First the configuration file. This is not an option, but it
is vital information for GPG Conf. */
if (!opt.config_filename)
opt.config_filename = make_filename (gnupg_homedir (),
"dirmngr.conf", NULL );
filename = percent_escape (opt.config_filename, NULL);
es_printf ("gpgconf-dirmngr.conf:%lu:\"%s\n",
GC_OPT_FLAG_DEFAULT, filename);
xfree (filename);
es_printf ("verbose:%lu:\n", flags | GC_OPT_FLAG_NONE);
es_printf ("quiet:%lu:\n", flags | GC_OPT_FLAG_NONE);
es_printf ("debug-level:%lu:\"none\n", flags | GC_OPT_FLAG_DEFAULT);
es_printf ("log-file:%lu:\n", flags | GC_OPT_FLAG_NONE);
es_printf ("force:%lu:\n", flags | GC_OPT_FLAG_NONE);
/* --csh and --sh are mutually exclusive, something we can not
express in GPG Conf. --options is only usable from the
command line, really. --debug-all interacts with --debug,
and having both of them is thus problematic. --no-detach is
also only usable on the command line. --batch is unused. */
filename = make_filename (gnupg_homedir (),
"dirmngr_ldapservers.conf",
NULL);
filename_esc = percent_escape (filename, NULL);
es_printf ("ldapserverlist-file:%lu:\"%s\n", flags | GC_OPT_FLAG_DEFAULT,
filename_esc);
xfree (filename_esc);
xfree (filename);
es_printf ("ldaptimeout:%lu:%u\n",
flags | GC_OPT_FLAG_DEFAULT, DEFAULT_LDAP_TIMEOUT);
es_printf ("max-replies:%lu:%u\n",
flags | GC_OPT_FLAG_DEFAULT, DEFAULT_MAX_REPLIES);
es_printf ("allow-ocsp:%lu:\n", flags | GC_OPT_FLAG_NONE);
es_printf ("allow-version-check:%lu:\n", flags | GC_OPT_FLAG_NONE);
es_printf ("ocsp-responder:%lu:\n", flags | GC_OPT_FLAG_NONE);
es_printf ("ocsp-signer:%lu:\n", flags | GC_OPT_FLAG_NONE);
es_printf ("faked-system-time:%lu:\n", flags | GC_OPT_FLAG_NONE);
es_printf ("no-greeting:%lu:\n", flags | GC_OPT_FLAG_NONE);
es_printf ("disable-http:%lu:\n", flags | GC_OPT_FLAG_NONE);
es_printf ("disable-ldap:%lu:\n", flags | GC_OPT_FLAG_NONE);
es_printf ("honor-http-proxy:%lu\n", flags | GC_OPT_FLAG_NONE);
es_printf ("http-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE);
es_printf ("ldap-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE);
es_printf ("only-ldap-proxy:%lu:\n", flags | GC_OPT_FLAG_NONE);
es_printf ("ignore-ldap-dp:%lu:\n", flags | GC_OPT_FLAG_NONE);
es_printf ("ignore-http-dp:%lu:\n", flags | GC_OPT_FLAG_NONE);
es_printf ("ignore-ocsp-service-url:%lu:\n", flags | GC_OPT_FLAG_NONE);
/* Note: The next one is to fix a typo in gpgconf - should be
removed eventually. */
es_printf ("ignore-ocsp-servic-url:%lu:\n", flags | GC_OPT_FLAG_NONE);
es_printf ("use-tor:%lu:\n", flags | GC_OPT_FLAG_NONE);
filename_esc = percent_escape (get_default_keyserver (0), NULL);
es_printf ("keyserver:%lu:\"%s:\n", flags | GC_OPT_FLAG_DEFAULT,
filename_esc);
xfree (filename_esc);
es_printf ("nameserver:%lu:\n", flags | GC_OPT_FLAG_NONE);
es_printf ("resolver-timeout:%lu:%u\n",
flags | GC_OPT_FLAG_DEFAULT, 0);
}
cleanup ();
return !!rc;
}
static void
cleanup (void)
{
crl_cache_deinit ();
cert_cache_deinit (1);
reload_dns_stuff (1);
#if USE_LDAP
ldapserver_list_free (opt.ldapservers);
#endif /*USE_LDAP*/
opt.ldapservers = NULL;
if (cleanup_socket)
{
cleanup_socket = 0;
if (redir_socket_name)
gnupg_remove (redir_socket_name);
else if (socket_name && *socket_name)
gnupg_remove (socket_name);
}
}
void
dirmngr_exit (int rc)
{
cleanup ();
exit (rc);
}
void
dirmngr_init_default_ctrl (ctrl_t ctrl)
{
ctrl->magic = SERVER_CONTROL_MAGIC;
if (opt.http_proxy)
ctrl->http_proxy = xstrdup (opt.http_proxy);
ctrl->http_no_crl = 1;
ctrl->timeout = opt.connect_timeout;
}
void
dirmngr_deinit_default_ctrl (ctrl_t ctrl)
{
if (!ctrl)
return;
ctrl->magic = 0xdeadbeef;
xfree (ctrl->http_proxy);
ctrl->http_proxy = NULL;
}
/* Create a list of LDAP servers from the file FILENAME. Returns the
list or NULL in case of errors.
The format fo such a file is line oriented where empty lines and
lines starting with a hash mark are ignored. All other lines are
assumed to be colon seprated with these fields:
1. field: Hostname
2. field: Portnumber
3. field: Username
4. field: Password
5. field: Base DN
*/
#if USE_LDAP
static ldap_server_t
parse_ldapserver_file (const char* filename)
{
char buffer[1024];
char *p;
ldap_server_t server, serverstart, *serverend;
int c;
unsigned int lineno = 0;
estream_t fp;
fp = es_fopen (filename, "r");
if (!fp)
{
log_error (_("error opening '%s': %s\n"), filename, strerror (errno));
return NULL;
}
serverstart = NULL;
serverend = &serverstart;
while (es_fgets (buffer, sizeof buffer, fp))
{
lineno++;
if (!*buffer || buffer[strlen(buffer)-1] != '\n')
{
if (*buffer && es_feof (fp))
; /* Last line not terminated - continue. */
else
{
log_error (_("%s:%u: line too long - skipped\n"),
filename, lineno);
while ( (c=es_fgetc (fp)) != EOF && c != '\n')
; /* Skip until end of line. */
continue;
}
}
/* Skip empty and comment lines.*/
for (p=buffer; spacep (p); p++)
;
if (!*p || *p == '\n' || *p == '#')
continue;
/* Parse the colon separated fields. */
server = ldapserver_parse_one (buffer, filename, lineno);
if (server)
{
*serverend = server;
serverend = &server->next;
}
}
if (es_ferror (fp))
log_error (_("error reading '%s': %s\n"), filename, strerror (errno));
es_fclose (fp);
return serverstart;
}
#endif /*USE_LDAP*/
static fingerprint_list_t
parse_ocsp_signer (const char *string)
{
gpg_error_t err;
char *fname;
estream_t fp;
char line[256];
char *p;
fingerprint_list_t list, *list_tail, item;
unsigned int lnr = 0;
int c, i, j;
int errflag = 0;
/* Check whether this is not a filename and treat it as a direct
fingerprint specification. */
if (!strpbrk (string, "/.~\\"))
{
item = xcalloc (1, sizeof *item);
for (i=j=0; (string[i] == ':' || hexdigitp (string+i)) && j < 40; i++)
if ( string[i] != ':' )
item->hexfpr[j++] = string[i] >= 'a'? (string[i] & 0xdf): string[i];
item->hexfpr[j] = 0;
if (j != 40 || !(spacep (string+i) || !string[i]))
{
log_error (_("%s:%u: invalid fingerprint detected\n"),
"--ocsp-signer", 0);
xfree (item);
return NULL;
}
return item;
}
/* Well, it is a filename. */
if (*string == '/' || (*string == '~' && string[1] == '/'))
fname = make_filename (string, NULL);
else
{
if (string[0] == '.' && string[1] == '/' )
string += 2;
fname = make_filename (gnupg_homedir (), string, NULL);
}
fp = es_fopen (fname, "r");
if (!fp)
{
err = gpg_error_from_syserror ();
log_error (_("can't open '%s': %s\n"), fname, gpg_strerror (err));
xfree (fname);
return NULL;
}
list = NULL;
list_tail = &list;
for (;;)
{
if (!es_fgets (line, DIM(line)-1, fp) )
{
if (!es_feof (fp))
{
err = gpg_error_from_syserror ();
log_error (_("%s:%u: read error: %s\n"),
fname, lnr, gpg_strerror (err));
errflag = 1;
}
es_fclose (fp);
if (errflag)
{
while (list)
{
fingerprint_list_t tmp = list->next;
xfree (list);
list = tmp;
}
}
xfree (fname);
return list; /* Ready. */
}
lnr++;
if (!*line || line[strlen(line)-1] != '\n')
{
/* Eat until end of line. */
while ( (c=es_getc (fp)) != EOF && c != '\n')
;
err = gpg_error (*line? GPG_ERR_LINE_TOO_LONG
/* */: GPG_ERR_INCOMPLETE_LINE);
log_error (_("%s:%u: read error: %s\n"),
fname, lnr, gpg_strerror (err));
errflag = 1;
continue;
}
/* Allow for empty lines and spaces */
for (p=line; spacep (p); p++)
;
if (!*p || *p == '\n' || *p == '#')
continue;
item = xcalloc (1, sizeof *item);
*list_tail = item;
list_tail = &item->next;
for (i=j=0; (p[i] == ':' || hexdigitp (p+i)) && j < 40; i++)
if ( p[i] != ':' )
item->hexfpr[j++] = p[i] >= 'a'? (p[i] & 0xdf): p[i];
item->hexfpr[j] = 0;
if (j != 40 || !(spacep (p+i) || p[i] == '\n'))
{
log_error (_("%s:%u: invalid fingerprint detected\n"), fname, lnr);
errflag = 1;
}
i++;
while (spacep (p+i))
i++;
if (p[i] && p[i] != '\n')
log_info (_("%s:%u: garbage at end of line ignored\n"), fname, lnr);
}
/*NOTREACHED*/
}
/*
Stuff used in daemon mode.
*/
/* Reread parts of the configuration. Note, that this function is
obviously not thread-safe and should only be called from the NPTH
signal handler.
Fixme: Due to the way the argument parsing works, we create a
memory leak here for all string type arguments. There is currently
no clean way to tell whether the memory for the argument has been
allocated or points into the process' original arguments. Unless
we have a mechanism to tell this, we need to live on with this. */
static void
reread_configuration (void)
{
ARGPARSE_ARGS pargs;
FILE *fp;
unsigned int configlineno = 0;
int dummy;
if (!opt.config_filename)
return; /* No config file. */
fp = fopen (opt.config_filename, "r");
if (!fp)
{
log_error (_("option file '%s': %s\n"),
opt.config_filename, strerror(errno) );
return;
}
parse_rereadable_options (NULL, 1); /* Start from the default values. */
memset (&pargs, 0, sizeof pargs);
dummy = 0;
pargs.argc = &dummy;
pargs.flags = 1; /* do not remove the args */
while (optfile_parse (fp, opt.config_filename, &configlineno, &pargs, opts) )
{
if (pargs.r_opt < -1)
pargs.err = 1; /* Print a warning. */
else /* Try to parse this option - ignore unchangeable ones. */
parse_rereadable_options (&pargs, 1);
}
fclose (fp);
post_option_parsing ();
}
/* A global function which allows us to trigger the reload stuff from
other places. */
void
dirmngr_sighup_action (void)
{
log_info (_("SIGHUP received - "
"re-reading configuration and flushing caches\n"));
reread_configuration ();
cert_cache_deinit (0);
crl_cache_deinit ();
cert_cache_init (hkp_cacert_filenames);
crl_cache_init ();
reload_dns_stuff (0);
ks_hkp_reload ();
}
/* This function is called if some network activity was done. At this
* point we know the we have a network and we can decide whether to
* run scheduled background tasks soon. The function should return
* quickly and only trigger actions for another thread. */
static void
netactivity_action (void)
{
network_activity_seen = 1;
}
/* The signal handler. */
#ifndef HAVE_W32_SYSTEM
static void
handle_signal (int signo)
{
switch (signo)
{
case SIGHUP:
dirmngr_sighup_action ();
break;
case SIGUSR1:
cert_cache_print_stats ();
domaininfo_print_stats ();
break;
case SIGUSR2:
log_info (_("SIGUSR2 received - no action defined\n"));
break;
case SIGTERM:
if (!shutdown_pending)
log_info (_("SIGTERM received - shutting down ...\n"));
else
log_info (_("SIGTERM received - still %d active connections\n"),
active_connections);
shutdown_pending++;
if (shutdown_pending > 2)
{
log_info (_("shutdown forced\n"));
log_info ("%s %s stopped\n", strusage(11), strusage(13) );
cleanup ();
dirmngr_exit (0);
}
break;
case SIGINT:
log_info (_("SIGINT received - immediate shutdown\n"));
log_info( "%s %s stopped\n", strusage(11), strusage(13));
cleanup ();
dirmngr_exit (0);
break;
default:
log_info (_("signal %d received - no action defined\n"), signo);
}
}
#endif /*!HAVE_W32_SYSTEM*/
/* Thread to do the housekeeping. */
static void *
housekeeping_thread (void *arg)
{
static int sentinel;
time_t curtime;
struct server_control_s ctrlbuf;
(void)arg;
curtime = gnupg_get_time ();
if (sentinel)
{
log_info ("housekeeping is already going on\n");
return NULL;
}
sentinel++;
if (opt.verbose > 1)
log_info ("starting housekeeping\n");
memset (&ctrlbuf, 0, sizeof ctrlbuf);
dirmngr_init_default_ctrl (&ctrlbuf);
ks_hkp_housekeeping (curtime);
if (network_activity_seen)
{
network_activity_seen = 0;
if (opt.allow_version_check)
dirmngr_load_swdb (&ctrlbuf, 0);
workqueue_run_global_tasks (&ctrlbuf, 1);
}
else
workqueue_run_global_tasks (&ctrlbuf, 0);
dirmngr_deinit_default_ctrl (&ctrlbuf);
if (opt.verbose > 1)
log_info ("ready with housekeeping\n");
sentinel--;
return NULL;
}
#if GPGRT_GCC_HAVE_PUSH_PRAGMA
# pragma GCC push_options
# pragma GCC optimize ("no-strict-overflow")
#endif
static int
time_for_housekeeping_p (time_t curtime)
{
static time_t last_housekeeping;
if (!last_housekeeping)
last_housekeeping = curtime;
if (last_housekeeping + HOUSEKEEPING_INTERVAL <= curtime
|| last_housekeeping > curtime /*(be prepared for y2038)*/)
{
last_housekeeping = curtime;
return 1;
}
return 0;
}
#if GPGRT_GCC_HAVE_PUSH_PRAGMA
# pragma GCC pop_options
#endif
/* This is the worker for the ticker. It is called every few seconds
and may only do fast operations. */
static void
handle_tick (void)
{
struct stat statbuf;
if (time_for_housekeeping_p (gnupg_get_time ()))
{
npth_t thread;
npth_attr_t tattr;
int err;
err = npth_attr_init (&tattr);
if (err)
log_error ("error preparing housekeeping thread: %s\n", strerror (err));
else
{
npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
err = npth_create (&thread, &tattr, housekeeping_thread, NULL);
if (err)
log_error ("error spawning housekeeping thread: %s\n",
strerror (err));
npth_attr_destroy (&tattr);
}
}
/* Check whether the homedir is still available. */
if (!shutdown_pending
&& stat (gnupg_homedir (), &statbuf) && errno == ENOENT)
{
shutdown_pending = 1;
log_info ("homedir has been removed - shutting down\n");
}
}
/* Check the nonce on a new connection. This is a NOP unless we are
using our Unix domain socket emulation under Windows. */
static int
check_nonce (assuan_fd_t fd, assuan_sock_nonce_t *nonce)
{
if (assuan_sock_check_nonce (fd, nonce))
{
log_info (_("error reading nonce on fd %d: %s\n"),
FD2INT (fd), strerror (errno));
assuan_sock_close (fd);
return -1;
}
else
return 0;
}
/* Helper to call a connection's main function. */
static void *
start_connection_thread (void *arg)
{
static unsigned int last_session_id;
unsigned int session_id;
union int_and_ptr_u argval;
gnupg_fd_t fd;
memset (&argval, 0, sizeof argval);
argval.aptr = arg;
fd = argval.afd;
if (check_nonce (fd, &socket_nonce))
{
log_error ("handler nonce check FAILED\n");
return NULL;
}
#ifndef HAVE_W32_SYSTEM
npth_setspecific (my_tlskey_current_fd, argval.aptr);
#endif
active_connections++;
if (opt.verbose)
log_info (_("handler for fd %d started\n"), FD2INT (fd));
session_id = ++last_session_id;
if (!session_id)
session_id = ++last_session_id;
start_command_handler (fd, session_id);
if (opt.verbose)
log_info (_("handler for fd %d terminated\n"), FD2INT (fd));
active_connections--;
workqueue_run_post_session_tasks (session_id);
#ifndef HAVE_W32_SYSTEM
argval.afd = ASSUAN_INVALID_FD;
npth_setspecific (my_tlskey_current_fd, argval.aptr);
#endif
return NULL;
}
#ifdef HAVE_INOTIFY_INIT
/* Read an inotify event and return true if it matches NAME. */
static int
my_inotify_is_name (int fd, const char *name)
{
union {
struct inotify_event ev;
char _buf[sizeof (struct inotify_event) + 100 + 1];
} buf;
int n;
const char *s;
s = strrchr (name, '/');
if (s && s[1])
name = s + 1;
n = npth_read (fd, &buf, sizeof buf);
if (n < sizeof (struct inotify_event))
return 0;
if (buf.ev.len < strlen (name)+1)
return 0;
if (strcmp (buf.ev.name, name))
return 0; /* Not the desired file. */
return 1; /* Found. */
}
#endif /*HAVE_INOTIFY_INIT*/
/* Main loop in daemon mode. Note that LISTEN_FD will be owned by
* this function. */
static void
handle_connections (assuan_fd_t listen_fd)
{
npth_attr_t tattr;
#ifndef HAVE_W32_SYSTEM
int signo;
#endif
struct sockaddr_un paddr;
socklen_t plen = sizeof( paddr );
int nfd, ret;
fd_set fdset, read_fdset;
struct timespec abstime;
struct timespec curtime;
struct timespec timeout;
int saved_errno;
int my_inotify_fd = -1;
npth_attr_init (&tattr);
npth_attr_setdetachstate (&tattr, NPTH_CREATE_DETACHED);
#ifndef HAVE_W32_SYSTEM /* FIXME */
npth_sigev_init ();
npth_sigev_add (SIGHUP);
npth_sigev_add (SIGUSR1);
npth_sigev_add (SIGUSR2);
npth_sigev_add (SIGINT);
npth_sigev_add (SIGTERM);
npth_sigev_fini ();
#endif
#ifdef HAVE_INOTIFY_INIT
if (disable_check_own_socket)
my_inotify_fd = -1;
else if ((my_inotify_fd = inotify_init ()) == -1)
log_info ("error enabling fast daemon termination: %s\n",
strerror (errno));
else
{
/* We need to watch the directory for the file because there
* won't be an IN_DELETE_SELF for a socket file. */
char *slash = strrchr (socket_name, '/');
log_assert (slash && slash[1]);
*slash = 0;
if (inotify_add_watch (my_inotify_fd, socket_name, IN_DELETE) == -1)
{
close (my_inotify_fd);
my_inotify_fd = -1;
}
*slash = '/';
}
#endif /*HAVE_INOTIFY_INIT*/
/* Setup the fdset. It has only one member. This is because we use
pth_select instead of pth_accept to properly sync timeouts with
to full second. */
FD_ZERO (&fdset);
FD_SET (FD2INT (listen_fd), &fdset);
nfd = FD2INT (listen_fd);
if (my_inotify_fd != -1)
{
FD_SET (my_inotify_fd, &fdset);
if (my_inotify_fd > nfd)
nfd = my_inotify_fd;
}
npth_clock_gettime (&abstime);
abstime.tv_sec += TIMERTICK_INTERVAL;
/* Main loop. */
for (;;)
{
/* Shutdown test. */
if (shutdown_pending)
{
if (!active_connections)
break; /* ready */
/* Do not accept new connections but keep on running the
* loop to cope with the timer events.
*
* Note that we do not close the listening socket because a
* client trying to connect to that socket would instead
* restart a new dirmngr instance - which is unlikely the
* intention of a shutdown. */
/* assuan_sock_close (listen_fd); */
/* listen_fd = -1; */
FD_ZERO (&fdset);
nfd = -1;
if (my_inotify_fd != -1)
{
FD_SET (my_inotify_fd, &fdset);
nfd = my_inotify_fd;
}
}
/* Take a copy of the fdset. */
read_fdset = fdset;
npth_clock_gettime (&curtime);
if (!(npth_timercmp (&curtime, &abstime, <)))
{
/* Timeout. When a shutdown is pending we use a shorter
* interval to handle the shutdown more quickly. */
handle_tick ();
npth_clock_gettime (&abstime);
abstime.tv_sec += (shutdown_pending
? TIMERTICK_INTERVAL_SHUTDOWN
: TIMERTICK_INTERVAL);
}
npth_timersub (&abstime, &curtime, &timeout);
#ifndef HAVE_W32_SYSTEM
ret = npth_pselect (nfd+1, &read_fdset, NULL, NULL, &timeout,
npth_sigev_sigmask());
saved_errno = errno;
while (npth_sigev_get_pending(&signo))
handle_signal (signo);
#else
ret = npth_eselect (nfd+1, &read_fdset, NULL, NULL, &timeout, NULL, NULL);
saved_errno = errno;
#endif
if (ret == -1 && saved_errno != EINTR)
{
log_error (_("npth_pselect failed: %s - waiting 1s\n"),
strerror (saved_errno));
npth_sleep (1);
continue;
}
if (ret <= 0)
{
/* Interrupt or timeout. Will be handled when calculating the
next timeout. */
continue;
}
if (shutdown_pending)
{
/* Do not anymore accept connections. */
continue;
}
#ifdef HAVE_INOTIFY_INIT
if (my_inotify_fd != -1 && FD_ISSET (my_inotify_fd, &read_fdset)
&& my_inotify_is_name (my_inotify_fd, socket_name))
{
shutdown_pending = 1;
log_info ("socket file has been removed - shutting down\n");
}
#endif /*HAVE_INOTIFY_INIT*/
if (FD_ISSET (FD2INT (listen_fd), &read_fdset))
{
gnupg_fd_t fd;
plen = sizeof paddr;
fd = INT2FD (npth_accept (FD2INT(listen_fd),
(struct sockaddr *)&paddr, &plen));
if (fd == GNUPG_INVALID_FD)
{
log_error ("accept failed: %s\n", strerror (errno));
}
else
{
char threadname[50];
union int_and_ptr_u argval;
npth_t thread;
memset (&argval, 0, sizeof argval);
argval.afd = fd;
snprintf (threadname, sizeof threadname,
"conn fd=%d", FD2INT(fd));
ret = npth_create (&thread, &tattr,
start_connection_thread, argval.aptr);
if (ret)
{
log_error ("error spawning connection handler: %s\n",
strerror (ret) );
assuan_sock_close (fd);
}
npth_setname_np (thread, threadname);
}
}
}
#ifdef HAVE_INOTIFY_INIT
if (my_inotify_fd != -1)
close (my_inotify_fd);
#endif /*HAVE_INOTIFY_INIT*/
npth_attr_destroy (&tattr);
if (listen_fd != GNUPG_INVALID_FD)
assuan_sock_close (listen_fd);
cleanup ();
log_info ("%s %s stopped\n", strusage(11), strusage(13));
}
const char*
dirmngr_get_current_socket_name (void)
{
if (socket_name)
return socket_name;
else
return dirmngr_socket_name ();
}
diff --git a/dirmngr/dirmngr_ldap.c b/dirmngr/dirmngr_ldap.c
index 8452c3ba0..dd7e4bda5 100644
--- a/dirmngr/dirmngr_ldap.c
+++ b/dirmngr/dirmngr_ldap.c
@@ -1,771 +1,771 @@
/* dirmngr-ldap.c - The LDAP helper for dirmngr.
* Copyright (C) 2004 g10 Code GmbH
* Copyright (C) 2010 Free Software Foundation, Inc.
*
* 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 .
*/
#include
#include
#include
#include
#include
#include
#ifdef HAVE_SIGNAL_H
# include
#endif
#include
#include
#include
#ifndef USE_LDAPWRAPPER
# include
#endif
#ifdef HAVE_W32_SYSTEM
# include
# include
# include
# include
# include "ldap-url.h"
#else
/* For OpenLDAP, to enable the API that we're using. */
# define LDAP_DEPRECATED 1
# include
#endif
#include
#include "../common/logging.h"
#include "../common/argparse.h"
#include "../common/stringhelp.h"
#include "../common/mischelp.h"
#include "../common/strlist.h"
#include "../common/i18n.h"
#include "../common/util.h"
#include "../common/init.h"
/* With the ldap wrapper, there is no need for the npth_unprotect and leave
functions; thus we redefine them to nops. If we are not using the
ldap wrapper process we need to include the prototype for our
module's main function. */
#ifdef USE_LDAPWRAPPER
static void npth_unprotect (void) { }
static void npth_protect (void) { }
#else
# include "./ldap-wrapper.h"
#endif
#ifdef HAVE_W32CE_SYSTEM
# include "w32-ldap-help.h"
# define my_ldap_init(a,b) \
_dirmngr_ldap_init ((a), (b))
# define my_ldap_simple_bind_s(a,b,c) \
_dirmngr_ldap_simple_bind_s ((a),(b),(c))
# define my_ldap_search_st(a,b,c,d,e,f,g,h) \
_dirmngr_ldap_search_st ((a), (b), (c), (d), (e), (f), (g), (h))
# define my_ldap_first_attribute(a,b,c) \
_dirmngr_ldap_first_attribute ((a),(b),(c))
# define my_ldap_next_attribute(a,b,c) \
_dirmngr_ldap_next_attribute ((a),(b),(c))
# define my_ldap_get_values_len(a,b,c) \
_dirmngr_ldap_get_values_len ((a),(b),(c))
# define my_ldap_free_attr(a) \
xfree ((a))
#else
# define my_ldap_init(a,b) ldap_init ((a), (b))
# define my_ldap_simple_bind_s(a,b,c) ldap_simple_bind_s ((a), (b), (c))
# define my_ldap_search_st(a,b,c,d,e,f,g,h) \
ldap_search_st ((a), (b), (c), (d), (e), (f), (g), (h))
# define my_ldap_first_attribute(a,b,c) ldap_first_attribute ((a),(b),(c))
# define my_ldap_next_attribute(a,b,c) ldap_next_attribute ((a),(b),(c))
# define my_ldap_get_values_len(a,b,c) ldap_get_values_len ((a),(b),(c))
# define my_ldap_free_attr(a) ldap_memfree ((a))
#endif
#ifdef HAVE_W32_SYSTEM
typedef LDAP_TIMEVAL my_ldap_timeval_t;
#else
typedef struct timeval my_ldap_timeval_t;
#endif
#define DEFAULT_LDAP_TIMEOUT 15 /* Arbitrary long timeout. */
/* Constants for the options. */
enum
{
oQuiet = 'q',
oVerbose = 'v',
oTimeout = 500,
oMulti,
oProxy,
oHost,
oPort,
oUser,
oPass,
oEnvPass,
oDN,
oFilter,
oAttr,
oOnlySearchTimeout,
oLogWithPID
};
/* The list of options as used by the argparse.c code. */
static ARGPARSE_OPTS opts[] = {
{ oVerbose, "verbose", 0, N_("verbose") },
{ oQuiet, "quiet", 0, N_("be somewhat more quiet") },
{ oTimeout, "timeout", 1, N_("|N|set LDAP timeout to N seconds")},
{ oMulti, "multi", 0, N_("return all values in"
" a record oriented format")},
{ oProxy, "proxy", 2,
N_("|NAME|ignore host part and connect through NAME")},
{ oHost, "host", 2, N_("|NAME|connect to host NAME")},
{ oPort, "port", 1, N_("|N|connect to port N")},
{ oUser, "user", 2, N_("|NAME|use user NAME for authentication")},
{ oPass, "pass", 2, N_("|PASS|use password PASS"
" for authentication")},
{ oEnvPass, "env-pass", 0, N_("take password from $DIRMNGR_LDAP_PASS")},
{ oDN, "dn", 2, N_("|STRING|query DN STRING")},
{ oFilter, "filter", 2, N_("|STRING|use STRING as filter expression")},
{ oAttr, "attr", 2, N_("|STRING|return the attribute STRING")},
{ oOnlySearchTimeout, "only-search-timeout", 0, "@"},
{ oLogWithPID,"log-with-pid", 0, "@"},
ARGPARSE_end ()
};
/* A structure with module options. This is not a static variable
because if we are not build as a standalone binary, each thread
using this module needs to handle its own values. */
struct my_opt_s
{
int quiet;
int verbose;
my_ldap_timeval_t timeout;/* Timeout for the LDAP search functions. */
unsigned int alarm_timeout; /* And for the alarm based timeout. */
int multi;
estream_t outstream; /* Send output to this stream. */
/* Note that we can't use const for the strings because ldap_* are
not defined that way. */
char *proxy; /* Host and Port override. */
char *user; /* Authentication user. */
char *pass; /* Authentication password. */
char *host; /* Override host. */
int port; /* Override port. */
char *dn; /* Override DN. */
char *filter;/* Override filter. */
char *attr; /* Override attribute. */
};
typedef struct my_opt_s *my_opt_t;
/* Prototypes. */
#ifndef HAVE_W32_SYSTEM
static void catch_alarm (int dummy);
#endif
static int process_url (my_opt_t myopt, const char *url);
/* Function called by argparse.c to display information. */
#ifdef USE_LDAPWRAPPER
static const char *
my_strusage (int level)
{
const char *p;
switch(level)
{
case 11: p = "dirmngr_ldap (@GNUPG@)";
break;
case 13: p = VERSION; break;
case 17: p = PRINTABLE_OS_NAME; break;
case 19: p = _("Please report bugs to <@EMAIL@>.\n"); break;
case 49: p = PACKAGE_BUGREPORT; break;
case 1:
case 40: p =
_("Usage: dirmngr_ldap [options] [URL] (-h for help)\n");
break;
case 41: p =
_("Syntax: dirmngr_ldap [options] [URL]\n"
"Internal LDAP helper for Dirmngr\n"
"Interface and options may change without notice\n");
break;
default: p = NULL;
}
return p;
}
#endif /*!USE_LDAPWRAPPER*/
int
#ifdef USE_LDAPWRAPPER
main (int argc, char **argv)
#else
ldap_wrapper_main (char **argv, estream_t outstream)
#endif
{
#ifndef USE_LDAPWRAPPER
int argc;
#endif
ARGPARSE_ARGS pargs;
int any_err = 0;
char *p;
int only_search_timeout = 0;
struct my_opt_s my_opt_buffer;
my_opt_t myopt = &my_opt_buffer;
char *malloced_buffer1 = NULL;
memset (&my_opt_buffer, 0, sizeof my_opt_buffer);
early_system_init ();
#ifdef USE_LDAPWRAPPER
set_strusage (my_strusage);
log_set_prefix ("dirmngr_ldap", GPGRT_LOG_WITH_PREFIX);
/* Setup I18N and common subsystems. */
i18n_init();
init_common_subsystems (&argc, &argv);
es_set_binary (es_stdout);
myopt->outstream = es_stdout;
#else /*!USE_LDAPWRAPPER*/
myopt->outstream = outstream;
for (argc=0; argv[argc]; argc++)
;
#endif /*!USE_LDAPWRAPPER*/
/* LDAP defaults */
myopt->timeout.tv_sec = DEFAULT_LDAP_TIMEOUT;
myopt->timeout.tv_usec = 0;
myopt->alarm_timeout = 0;
/* Parse the command line. */
pargs.argc = &argc;
pargs.argv = &argv;
pargs.flags= 1; /* Do not remove the args. */
while (arg_parse (&pargs, opts) )
{
switch (pargs.r_opt)
{
case oVerbose: myopt->verbose++; break;
case oQuiet: myopt->quiet++; break;
case oTimeout:
myopt->timeout.tv_sec = pargs.r.ret_int;
myopt->timeout.tv_usec = 0;
myopt->alarm_timeout = pargs.r.ret_int;
break;
case oOnlySearchTimeout: only_search_timeout = 1; break;
case oMulti: myopt->multi = 1; break;
case oUser: myopt->user = pargs.r.ret_str; break;
case oPass: myopt->pass = pargs.r.ret_str; break;
case oEnvPass:
myopt->pass = getenv ("DIRMNGR_LDAP_PASS");
break;
case oProxy: myopt->proxy = pargs.r.ret_str; break;
case oHost: myopt->host = pargs.r.ret_str; break;
case oPort: myopt->port = pargs.r.ret_int; break;
case oDN: myopt->dn = pargs.r.ret_str; break;
case oFilter: myopt->filter = pargs.r.ret_str; break;
case oAttr: myopt->attr = pargs.r.ret_str; break;
case oLogWithPID:
{
unsigned int oldflags;
log_get_prefix (&oldflags);
log_set_prefix (NULL, oldflags | GPGRT_LOG_WITH_PID);
}
break;
default :
#ifdef USE_LDAPWRAPPER
pargs.err = ARGPARSE_PRINT_ERROR;
#else
pargs.err = ARGPARSE_PRINT_WARNING; /* No exit() please. */
#endif
break;
}
}
if (only_search_timeout)
myopt->alarm_timeout = 0;
if (myopt->proxy)
{
malloced_buffer1 = xtrystrdup (myopt->proxy);
if (!malloced_buffer1)
{
log_error ("error copying string: %s\n", strerror (errno));
return 1;
}
myopt->host = malloced_buffer1;
p = strchr (myopt->host, ':');
if (p)
{
*p++ = 0;
myopt->port = atoi (p);
}
if (!myopt->port)
myopt->port = 389; /* make sure ports gets overridden. */
}
if (myopt->port < 0 || myopt->port > 65535)
log_error (_("invalid port number %d\n"), myopt->port);
#ifdef USE_LDAPWRAPPER
if (log_get_errorcount (0))
exit (2);
if (argc < 1)
usage (1);
#else
/* All passed arguments should be fine in this case. */
log_assert (argc);
#endif
#ifdef USE_LDAPWRAPPER
if (myopt->alarm_timeout)
{
#ifndef HAVE_W32_SYSTEM
# if defined(HAVE_SIGACTION) && defined(HAVE_STRUCT_SIGACTION)
struct sigaction act;
act.sa_handler = catch_alarm;
sigemptyset (&act.sa_mask);
act.sa_flags = 0;
if (sigaction (SIGALRM,&act,NULL))
# else
if (signal (SIGALRM, catch_alarm) == SIG_ERR)
# endif
log_fatal ("unable to register timeout handler\n");
#endif
}
#endif /*USE_LDAPWRAPPER*/
for (; argc; argc--, argv++)
if (process_url (myopt, *argv))
any_err = 1;
xfree (malloced_buffer1);
return any_err;
}
#ifndef HAVE_W32_SYSTEM
static void
catch_alarm (int dummy)
{
(void)dummy;
_exit (10);
}
#endif
#ifdef HAVE_W32_SYSTEM
static DWORD CALLBACK
alarm_thread (void *arg)
{
HANDLE timer = arg;
WaitForSingleObject (timer, INFINITE);
_exit (10);
return 0;
}
#endif
static void
set_timeout (my_opt_t myopt)
{
if (myopt->alarm_timeout)
{
#ifdef HAVE_W32_SYSTEM
static HANDLE timer;
LARGE_INTEGER due_time;
/* A negative value is a relative time. */
due_time.QuadPart = (unsigned long long)-10000000 * myopt->alarm_timeout;
if (!timer)
{
SECURITY_ATTRIBUTES sec_attr;
DWORD tid;
memset (&sec_attr, 0, sizeof sec_attr);
sec_attr.nLength = sizeof sec_attr;
sec_attr.bInheritHandle = FALSE;
- /* Create a manual resetable timer. */
+ /* Create a manual resettable timer. */
timer = CreateWaitableTimer (NULL, TRUE, NULL);
- /* Intially set the timer. */
+ /* Initially set the timer. */
SetWaitableTimer (timer, &due_time, 0, NULL, NULL, 0);
if (CreateThread (&sec_attr, 0, alarm_thread, timer, 0, &tid))
log_error ("failed to create alarm thread\n");
}
else /* Retrigger the timer. */
SetWaitableTimer (timer, &due_time, 0, NULL, NULL, 0);
#else
alarm (myopt->alarm_timeout);
#endif
}
}
/* Helper for fetch_ldap(). */
static int
print_ldap_entries (my_opt_t myopt, LDAP *ld, LDAPMessage *msg, char *want_attr)
{
LDAPMessage *item;
int any = 0;
for (npth_unprotect (), item = ldap_first_entry (ld, msg), npth_protect ();
item;
npth_unprotect (), item = ldap_next_entry (ld, item), npth_protect ())
{
BerElement *berctx;
char *attr;
if (myopt->verbose > 1)
log_info (_("scanning result for attribute '%s'\n"),
want_attr? want_attr : "[all]");
if (myopt->multi)
{ /* Write item marker. */
if (es_fwrite ("I\0\0\0\0", 5, 1, myopt->outstream) != 1)
{
log_error (_("error writing to stdout: %s\n"),
strerror (errno));
return -1;
}
}
for (npth_unprotect (), attr = my_ldap_first_attribute (ld, item, &berctx),
npth_protect ();
attr;
npth_unprotect (), attr = my_ldap_next_attribute (ld, item, berctx),
npth_protect ())
{
struct berval **values;
int idx;
if (myopt->verbose > 1)
log_info (_(" available attribute '%s'\n"), attr);
set_timeout (myopt);
/* I case we want only one attribute we do a case
insensitive compare without the optional extension
(i.e. ";binary"). Case insensitive is not really correct
but the best we can do. */
if (want_attr)
{
char *cp1, *cp2;
int cmpres;
cp1 = strchr (want_attr, ';');
if (cp1)
*cp1 = 0;
cp2 = strchr (attr, ';');
if (cp2)
*cp2 = 0;
cmpres = ascii_strcasecmp (want_attr, attr);
if (cp1)
*cp1 = ';';
if (cp2)
*cp2 = ';';
if (cmpres)
{
my_ldap_free_attr (attr);
continue; /* Not found: Try next attribute. */
}
}
npth_unprotect ();
values = my_ldap_get_values_len (ld, item, attr);
npth_protect ();
if (!values)
{
if (myopt->verbose)
log_info (_("attribute '%s' not found\n"), attr);
my_ldap_free_attr (attr);
continue;
}
if (myopt->verbose)
{
log_info (_("found attribute '%s'\n"), attr);
if (myopt->verbose > 1)
for (idx=0; values[idx]; idx++)
log_info (" length[%d]=%d\n",
idx, (int)values[0]->bv_len);
}
if (myopt->multi)
{ /* Write attribute marker. */
unsigned char tmp[5];
size_t n = strlen (attr);
tmp[0] = 'A';
tmp[1] = (n >> 24);
tmp[2] = (n >> 16);
tmp[3] = (n >> 8);
tmp[4] = (n);
if (es_fwrite (tmp, 5, 1, myopt->outstream) != 1
|| es_fwrite (attr, n, 1, myopt->outstream) != 1)
{
log_error (_("error writing to stdout: %s\n"),
strerror (errno));
ldap_value_free_len (values);
my_ldap_free_attr (attr);
ber_free (berctx, 0);
return -1;
}
}
for (idx=0; values[idx]; idx++)
{
if (myopt->multi)
{ /* Write value marker. */
unsigned char tmp[5];
size_t n = values[0]->bv_len;
tmp[0] = 'V';
tmp[1] = (n >> 24);
tmp[2] = (n >> 16);
tmp[3] = (n >> 8);
tmp[4] = (n);
if (es_fwrite (tmp, 5, 1, myopt->outstream) != 1)
{
log_error (_("error writing to stdout: %s\n"),
strerror (errno));
ldap_value_free_len (values);
my_ldap_free_attr (attr);
ber_free (berctx, 0);
return -1;
}
}
if (es_fwrite (values[0]->bv_val, values[0]->bv_len,
1, myopt->outstream) != 1)
{
log_error (_("error writing to stdout: %s\n"),
strerror (errno));
ldap_value_free_len (values);
my_ldap_free_attr (attr);
ber_free (berctx, 0);
return -1;
}
any = 1;
if (!myopt->multi)
break; /* Print only the first value. */
}
ldap_value_free_len (values);
my_ldap_free_attr (attr);
if (want_attr || !myopt->multi)
break; /* We only want to return the first attribute. */
}
ber_free (berctx, 0);
}
if (myopt->verbose > 1 && any)
log_info ("result has been printed\n");
return any?0:-1;
}
/* Helper for the URL based LDAP query. */
static int
fetch_ldap (my_opt_t myopt, const char *url, const LDAPURLDesc *ludp)
{
LDAP *ld;
LDAPMessage *msg;
int rc = 0;
char *host, *dn, *filter, *attrs[2], *attr;
int port;
int ret;
host = myopt->host? myopt->host : ludp->lud_host;
port = myopt->port? myopt->port : ludp->lud_port;
dn = myopt->dn? myopt->dn : ludp->lud_dn;
filter = myopt->filter? myopt->filter : ludp->lud_filter;
attrs[0] = myopt->attr? myopt->attr : ludp->lud_attrs? ludp->lud_attrs[0]:NULL;
attrs[1] = NULL;
attr = attrs[0];
if (!port)
port = (ludp->lud_scheme && !strcmp (ludp->lud_scheme, "ldaps"))? 636:389;
if (myopt->verbose)
{
log_info (_("processing url '%s'\n"), url);
if (myopt->user)
log_info (_(" user '%s'\n"), myopt->user);
if (myopt->pass)
log_info (_(" pass '%s'\n"), *myopt->pass?"*****":"");
if (host)
log_info (_(" host '%s'\n"), host);
log_info (_(" port %d\n"), port);
if (dn)
log_info (_(" DN '%s'\n"), dn);
if (filter)
log_info (_(" filter '%s'\n"), filter);
if (myopt->multi && !myopt->attr && ludp->lud_attrs)
{
int i;
for (i=0; ludp->lud_attrs[i]; i++)
log_info (_(" attr '%s'\n"), ludp->lud_attrs[i]);
}
else if (attr)
log_info (_(" attr '%s'\n"), attr);
}
if (!host || !*host)
{
log_error (_("no host name in '%s'\n"), url);
return -1;
}
if (!myopt->multi && !attr)
{
log_error (_("no attribute given for query '%s'\n"), url);
return -1;
}
if (!myopt->multi && !myopt->attr
&& ludp->lud_attrs && ludp->lud_attrs[0] && ludp->lud_attrs[1])
log_info (_("WARNING: using first attribute only\n"));
set_timeout (myopt);
npth_unprotect ();
ld = my_ldap_init (host, port);
npth_protect ();
if (!ld)
{
log_error (_("LDAP init to '%s:%d' failed: %s\n"),
host, port, strerror (errno));
return -1;
}
npth_unprotect ();
/* Fixme: Can we use MYOPT->user or is it shared with other theeads?. */
ret = my_ldap_simple_bind_s (ld, myopt->user, myopt->pass);
npth_protect ();
#ifdef LDAP_VERSION3
if (ret == LDAP_PROTOCOL_ERROR)
{
/* Protocol error could mean that the server only supports v3. */
int version = LDAP_VERSION3;
if (myopt->verbose)
log_info ("protocol error; retrying bind with v3 protocol\n");
npth_unprotect ();
ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &version);
ret = my_ldap_simple_bind_s (ld, myopt->user, myopt->pass);
npth_protect ();
}
#endif
if (ret)
{
log_error (_("binding to '%s:%d' failed: %s\n"),
host, port, ldap_err2string (ret));
ldap_unbind (ld);
return -1;
}
set_timeout (myopt);
npth_unprotect ();
rc = my_ldap_search_st (ld, dn, ludp->lud_scope, filter,
myopt->multi && !myopt->attr && ludp->lud_attrs?
ludp->lud_attrs:attrs,
0,
&myopt->timeout, &msg);
npth_protect ();
if (rc == LDAP_SIZELIMIT_EXCEEDED && myopt->multi)
{
if (es_fwrite ("E\0\0\0\x09truncated", 14, 1, myopt->outstream) != 1)
{
log_error (_("error writing to stdout: %s\n"), strerror (errno));
return -1;
}
}
else if (rc)
{
#ifdef HAVE_W32CE_SYSTEM
log_error ("searching '%s' failed: %d\n", url, rc);
#else
log_error (_("searching '%s' failed: %s\n"),
url, ldap_err2string (rc));
#endif
if (rc != LDAP_NO_SUCH_OBJECT)
{
/* FIXME: Need deinit (ld)? */
/* Hmmm: Do we need to released MSG in case of an error? */
return -1;
}
}
rc = print_ldap_entries (myopt, ld, msg, myopt->multi? NULL:attr);
ldap_msgfree (msg);
ldap_unbind (ld);
return rc;
}
/* Main processing. Take the URL and run the LDAP query. The result
is printed to stdout, errors are logged to the log stream. */
static int
process_url (my_opt_t myopt, const char *url)
{
int rc;
LDAPURLDesc *ludp = NULL;
if (!ldap_is_ldap_url (url))
{
log_error (_("'%s' is not an LDAP URL\n"), url);
return -1;
}
if (ldap_url_parse (url, &ludp))
{
log_error (_("'%s' is an invalid LDAP URL\n"), url);
return -1;
}
rc = fetch_ldap (myopt, url, ludp);
ldap_free_urldesc (ludp);
return rc;
}
diff --git a/dirmngr/dns-stuff.c b/dirmngr/dns-stuff.c
index 09b17c0fb..f86ccb0ae 100644
--- a/dirmngr/dns-stuff.c
+++ b/dirmngr/dns-stuff.c
@@ -1,2386 +1,2386 @@
/* dns-stuff.c - DNS related code including CERT RR (rfc-4398)
* Copyright (C) 2003, 2005, 2006, 2009 Free Software Foundation, Inc.
* Copyright (C) 2005, 2006, 2009, 2015. 2016 Werner Koch
*
* This file is part of GnuPG.
*
* This file is free software; you can redistribute it and/or modify
* it under the terms of either
*
* - the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* or
*
* - the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* or both in parallel, as here.
*
* This file 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 .
*/
#include
#include
#ifdef HAVE_W32_SYSTEM
# define WIN32_LEAN_AND_MEAN
# ifdef HAVE_WINSOCK2_H
# include
# endif
# include
# include
#else
# if HAVE_SYSTEM_RESOLVER
# include
# include
# include
# endif
# include
#endif
#ifdef HAVE_STAT
# include
#endif
#include
#include
/* William Ahern's DNS library, included as a source copy. */
#ifdef USE_LIBDNS
# include "dns.h"
#endif
/* dns.c has a dns_p_free but it is not exported. We use our own
* wrapper here so that we do not accidentally use xfree which would
* be wrong for dns.c allocated data. */
#define dns_free(a) free ((a))
#ifdef WITHOUT_NPTH /* Give the Makefile a chance to build without Pth. */
# undef USE_NPTH
#endif
#ifdef USE_NPTH
# include
#endif
#include "./dirmngr-err.h"
#include "../common/util.h"
#include "../common/host2net.h"
#include "dirmngr-status.h"
#include "dns-stuff.h"
#ifdef USE_NPTH
# define my_unprotect() npth_unprotect ()
# define my_protect() npth_protect ()
#else
# define my_unprotect() do { } while(0)
# define my_protect() do { } while(0)
#endif
/* We allow the use of 0 instead of AF_UNSPEC - check this assumption. */
#if AF_UNSPEC != 0
# error AF_UNSPEC does not have the value 0
#endif
/* Windows does not support the AI_ADDRCONFIG flag - use zero instead. */
#ifndef AI_ADDRCONFIG
# define AI_ADDRCONFIG 0
#endif
/* Not every installation has gotten around to supporting SRVs or
CERTs yet... */
#ifndef T_SRV
#define T_SRV 33
#endif
#undef T_CERT
#define T_CERT 37
/* The standard SOCKS and TOR ports. */
#define SOCKS_PORT 1080
#define TOR_PORT 9050
#define TOR_PORT2 9150 /* (Used by the Tor browser) */
/* The default nameserver used in Tor mode. */
#define DEFAULT_NAMESERVER "8.8.8.8"
/* The default timeout in seconds for libdns requests. */
#define DEFAULT_TIMEOUT 30
#define RESOLV_CONF_NAME "/etc/resolv.conf"
/* Two flags to enable verbose and debug mode. */
static int opt_verbose;
static int opt_debug;
/* The timeout in seconds for libdns requests. */
static int opt_timeout;
/* The flag to disable IPv4 access - right now this only skips
* returned A records. */
static int opt_disable_ipv4;
/* The flag to disable IPv6 access - right now this only skips
* returned AAAA records. */
static int opt_disable_ipv6;
/* If set force the use of the standard resolver. */
static int standard_resolver;
/* If set use recursive resolver when available. */
static int recursive_resolver;
/* If set Tor mode shall be used. */
static int tor_mode;
/* A string with the nameserver IP address used with Tor.
(40 should be sufficient for v6 but we add some extra for a scope.) */
static char tor_nameserver[40+20];
/* Two strings to hold the credentials presented to Tor. */
static char tor_socks_user[30];
static char tor_socks_password[20];
#ifdef USE_LIBDNS
-/* Libdns gobal data. */
+/* Libdns global data. */
struct libdns_s
{
struct dns_resolv_conf *resolv_conf;
struct dns_hosts *hosts;
struct dns_hints *hints;
struct sockaddr_storage socks_host;
} libdns;
/* If this flag is set, libdns shall be reinited for the next use. */
static int libdns_reinit_pending;
/* The Tor port to be used. */
static int libdns_tor_port;
#endif /*USE_LIBDNS*/
/* Calling this function with YES set to True forces the use of the
* standard resolver even if dirmngr has been built with support for
* an alternative resolver. */
void
enable_standard_resolver (int yes)
{
standard_resolver = yes;
}
/* Return true if the standard resolver is used. */
int
standard_resolver_p (void)
{
return standard_resolver;
}
/* Calling this function with YES switches libdns into recursive mode.
* It has no effect on the standard resolver. */
void
enable_recursive_resolver (int yes)
{
recursive_resolver = yes;
#ifdef USE_LIBDNS
libdns_reinit_pending = 1;
#endif
}
/* Return true iff the recursive resolver is used. */
int
recursive_resolver_p (void)
{
#if USE_LIBDNS
return !standard_resolver && recursive_resolver;
#else
return 0;
#endif
}
/* Puts this module eternally into Tor mode. When called agained with
* NEW_CIRCUIT request a new TOR circuit for the next DNS query. */
void
enable_dns_tormode (int new_circuit)
{
if (!*tor_socks_user || new_circuit)
{
static unsigned int counter;
gpgrt_snprintf (tor_socks_user, sizeof tor_socks_user,
"dirmngr-%lu", (unsigned long)getpid ());
gpgrt_snprintf (tor_socks_password, sizeof tor_socks_password,
"p%u", counter);
counter++;
}
tor_mode = 1;
}
/* Disable tor mode. */
void
disable_dns_tormode (void)
{
tor_mode = 0;
}
/* Set verbosity and debug mode for this module. */
void
set_dns_verbose (int verbose, int debug)
{
opt_verbose = verbose;
opt_debug = debug;
}
/* Set the Disable-IPv4 flag so that the name resolver does not return
* A addresses. */
void
set_dns_disable_ipv4 (int yes)
{
opt_disable_ipv4 = !!yes;
}
/* Set the Disable-IPv6 flag so that the name resolver does not return
* AAAA addresses. */
void
set_dns_disable_ipv6 (int yes)
{
opt_disable_ipv6 = !!yes;
}
/* Set the timeout for libdns requests to SECONDS. A value of 0 sets
* the default timeout and values are capped at 10 minutes. */
void
set_dns_timeout (int seconds)
{
if (!seconds)
seconds = DEFAULT_TIMEOUT;
else if (seconds < 1)
seconds = 1;
else if (seconds > 600)
seconds = 600;
opt_timeout = seconds;
}
/* Change the default IP address of the nameserver to IPADDR. The
address needs to be a numerical IP address and will be used for the
next DNS query. Note that this is only used in Tor mode. */
void
set_dns_nameserver (const char *ipaddr)
{
strncpy (tor_nameserver, ipaddr? ipaddr : DEFAULT_NAMESERVER,
sizeof tor_nameserver -1);
tor_nameserver[sizeof tor_nameserver -1] = 0;
#ifdef USE_LIBDNS
libdns_reinit_pending = 1;
libdns_tor_port = 0; /* Start again with the default port. */
#endif
}
/* Free an addressinfo linked list as returned by resolve_dns_name. */
void
free_dns_addrinfo (dns_addrinfo_t ai)
{
while (ai)
{
dns_addrinfo_t next = ai->next;
xfree (ai);
ai = next;
}
}
#ifndef HAVE_W32_SYSTEM
/* Return H_ERRNO mapped to a gpg-error code. Will never return 0. */
static gpg_error_t
get_h_errno_as_gpg_error (void)
{
gpg_err_code_t ec;
switch (h_errno)
{
case HOST_NOT_FOUND: ec = GPG_ERR_NO_NAME; break;
case TRY_AGAIN: ec = GPG_ERR_TRY_LATER; break;
case NO_RECOVERY: ec = GPG_ERR_SERVER_FAILED; break;
case NO_DATA: ec = GPG_ERR_NO_DATA; break;
default: ec = GPG_ERR_UNKNOWN_ERRNO; break;
}
return gpg_error (ec);
}
#endif /*!HAVE_W32_SYSTEM*/
static gpg_error_t
map_eai_to_gpg_error (int ec)
{
gpg_error_t err;
switch (ec)
{
case EAI_AGAIN: err = gpg_error (GPG_ERR_EAGAIN); break;
case EAI_BADFLAGS: err = gpg_error (GPG_ERR_INV_FLAG); break;
case EAI_FAIL: err = gpg_error (GPG_ERR_SERVER_FAILED); break;
case EAI_MEMORY: err = gpg_error (GPG_ERR_ENOMEM); break;
#ifdef EAI_NODATA
case EAI_NODATA: err = gpg_error (GPG_ERR_NO_DATA); break;
#endif
case EAI_NONAME: err = gpg_error (GPG_ERR_NO_NAME); break;
case EAI_SERVICE: err = gpg_error (GPG_ERR_NOT_SUPPORTED); break;
case EAI_FAMILY: err = gpg_error (GPG_ERR_EAFNOSUPPORT); break;
case EAI_SOCKTYPE: err = gpg_error (GPG_ERR_ESOCKTNOSUPPORT); break;
#ifndef HAVE_W32_SYSTEM
# ifdef EAI_ADDRFAMILY
case EAI_ADDRFAMILY:err = gpg_error (GPG_ERR_EADDRNOTAVAIL); break;
# endif
case EAI_SYSTEM: err = gpg_error_from_syserror (); break;
#endif
default: err = gpg_error (GPG_ERR_UNKNOWN_ERRNO); break;
}
return err;
}
#ifdef USE_LIBDNS
static gpg_error_t
libdns_error_to_gpg_error (int serr)
{
gpg_err_code_t ec;
switch (serr)
{
case 0: ec = 0; break;
case DNS_ENOBUFS: ec = GPG_ERR_BUFFER_TOO_SHORT; break;
case DNS_EILLEGAL: ec = GPG_ERR_INV_OBJ; break;
case DNS_EORDER: ec = GPG_ERR_INV_ORDER; break;
case DNS_ESECTION: ec = GPG_ERR_DNS_SECTION; break;
case DNS_EUNKNOWN: ec = GPG_ERR_DNS_UNKNOWN; break;
case DNS_EADDRESS: ec = GPG_ERR_DNS_ADDRESS; break;
case DNS_ENOQUERY: ec = GPG_ERR_DNS_NO_QUERY; break;
case DNS_ENOANSWER:ec = GPG_ERR_DNS_NO_ANSWER; break;
case DNS_EFETCHED: ec = GPG_ERR_ALREADY_FETCHED; break;
case DNS_ESERVICE: ec = GPG_ERR_NOT_SUPPORTED; break;
case DNS_ENONAME: ec = GPG_ERR_NO_NAME; break;
case DNS_EFAIL: ec = GPG_ERR_SERVER_FAILED; break;
case DNS_ECONNFIN: ec = GPG_ERR_DNS_CLOSED; break;
case DNS_EVERIFY: ec = GPG_ERR_DNS_VERIFY; break;
default:
if (serr >= 0)
ec = gpg_err_code_from_errno (serr);
else
ec = GPG_ERR_DNS_UNKNOWN;
break;
}
return gpg_error (ec);
}
#endif /*USE_LIBDNS*/
/* Return true if resolve.conf changed since it was last loaded. */
#ifdef USE_LIBDNS
static int
resolv_conf_changed_p (void)
{
#if defined(HAVE_W32_SYSTEM) || !defined(HAVE_STAT)
return 0;
#else
static time_t last_mtime;
const char *fname = RESOLV_CONF_NAME;
struct stat statbuf;
int changed = 0;
if (stat (fname, &statbuf))
{
log_error ("stat'ing '%s' failed: %s\n",
fname, gpg_strerror (gpg_error_from_syserror ()));
last_mtime = 1; /* Force a "changed" result the next time stat
* works. */
}
else if (!last_mtime)
last_mtime = statbuf.st_mtime;
else if (last_mtime != statbuf.st_mtime)
{
changed = 1;
last_mtime = statbuf.st_mtime;
}
return changed;
#endif
}
#endif /*USE_LIBDNS*/
#ifdef USE_LIBDNS
/* Initialize libdns. Returns 0 on success; prints a diagnostic and
* returns an error code on failure. */
static gpg_error_t
libdns_init (ctrl_t ctrl)
{
gpg_error_t err;
struct libdns_s ld;
int derr;
char *cfgstr = NULL;
const char *fname = NULL;
if (libdns.resolv_conf)
return 0; /* Already initialized. */
memset (&ld, 0, sizeof ld);
ld.resolv_conf = dns_resconf_open (&derr);
if (!ld.resolv_conf)
{
err = libdns_error_to_gpg_error (derr);
log_error ("failed to allocate DNS resconf object: %s\n",
gpg_strerror (err));
goto leave;
}
if (tor_mode)
{
if (!*tor_nameserver)
set_dns_nameserver (NULL);
if (!libdns_tor_port)
libdns_tor_port = TOR_PORT;
cfgstr = xtryasprintf ("[%s]:53", tor_nameserver);
if (!cfgstr)
err = gpg_error_from_syserror ();
else
err = libdns_error_to_gpg_error
(dns_resconf_pton (&ld.resolv_conf->nameserver[0], cfgstr));
if (err)
log_error ("failed to set nameserver '%s': %s\n",
cfgstr, gpg_strerror (err));
if (err)
goto leave;
ld.resolv_conf->options.tcp = DNS_RESCONF_TCP_SOCKS;
xfree (cfgstr);
cfgstr = xtryasprintf ("[%s]:%d", "127.0.0.1", libdns_tor_port);
if (!cfgstr)
err = gpg_error_from_syserror ();
else
err = libdns_error_to_gpg_error
(dns_resconf_pton (&ld.socks_host, cfgstr));
if (err)
{
log_error ("failed to set socks server '%s': %s\n",
cfgstr, gpg_strerror (err));
goto leave;
}
}
else
{
#ifdef HAVE_W32_SYSTEM
ULONG ninfo_len;
PFIXED_INFO ninfo;
PIP_ADDR_STRING pip;
int idx;
ninfo_len = 2048;
ninfo = xtrymalloc (ninfo_len);
if (!ninfo)
{
err = gpg_error_from_syserror ();
goto leave;
}
if (GetNetworkParams (ninfo, &ninfo_len))
{
log_error ("GetNetworkParms failed: %s\n", w32_strerror (-1));
err = gpg_error (GPG_ERR_GENERAL);
xfree (ninfo);
goto leave;
}
for (idx=0, pip = &(ninfo->DnsServerList);
pip && idx < DIM (ld.resolv_conf->nameserver);
pip = pip->Next)
{
if (opt_debug)
log_debug ("dns: dnsserver[%d] '%s'\n", idx, pip->IpAddress.String);
err = libdns_error_to_gpg_error
(dns_resconf_pton (&ld.resolv_conf->nameserver[idx],
pip->IpAddress.String));
if (err)
log_error ("failed to set nameserver[%d] '%s': %s\n",
idx, pip->IpAddress.String, gpg_strerror (err));
else
idx++;
}
xfree (ninfo);
#else /* Unix */
fname = RESOLV_CONF_NAME;
resolv_conf_changed_p (); /* Reset timestamp. */
err = libdns_error_to_gpg_error
(dns_resconf_loadpath (ld.resolv_conf, fname));
if (err)
{
log_error ("failed to load '%s': %s\n", fname, gpg_strerror (err));
goto leave;
}
fname = "/etc/nsswitch.conf";
err = libdns_error_to_gpg_error
(dns_nssconf_loadpath (ld.resolv_conf, fname));
if (err)
{
/* This is not a fatal error: nsswitch.conf is not used on
* all systems; assume classic behavior instead. */
if (gpg_err_code (err) != GPG_ERR_ENOENT)
log_error ("failed to load '%s': %s\n", fname, gpg_strerror (err));
if (opt_debug)
log_debug ("dns: fallback resolution order, files then DNS\n");
ld.resolv_conf->lookup[0] = 'f';
ld.resolv_conf->lookup[1] = 'b';
ld.resolv_conf->lookup[2] = '\0';
err = GPG_ERR_NO_ERROR;
}
else if (!strchr (ld.resolv_conf->lookup, 'b'))
{
/* No DNS resolution type found in the list. This might be
* due to systemd based systems which allow for custom
* keywords which are not known to us and thus we do not
* know whether DNS is wanted or not. Because DNS is
* important for our infrastructure, we forcefully append
* DNS to the end of the list. */
if (strlen (ld.resolv_conf->lookup)+2 < sizeof ld.resolv_conf->lookup)
{
if (opt_debug)
log_debug ("dns: appending DNS to resolution order\n");
strcat (ld.resolv_conf->lookup, "b");
}
else
log_error ("failed to append DNS to resolution order\n");
}
#endif /* Unix */
}
ld.hosts = dns_hosts_open (&derr);
if (!ld.hosts)
{
err = libdns_error_to_gpg_error (derr);
log_error ("failed to initialize hosts file: %s\n", gpg_strerror (err));
goto leave;
}
{
#if HAVE_W32_SYSTEM
char *hosts_path = xtryasprintf ("%s\\System32\\drivers\\etc\\hosts",
getenv ("SystemRoot"));
if (! hosts_path)
{
err = gpg_error_from_syserror ();
goto leave;
}
derr = dns_hosts_loadpath (ld.hosts, hosts_path);
xfree (hosts_path);
#else
derr = dns_hosts_loadpath (ld.hosts, "/etc/hosts");
#endif
if (derr)
{
err = libdns_error_to_gpg_error (derr);
log_error ("failed to load hosts file: %s\n", gpg_strerror (err));
err = 0; /* Do not bail out - having no /etc/hosts is legal. */
}
}
ld.resolv_conf->options.recurse = recursive_resolver_p ();
/* dns_hints_local for stub mode, dns_hints_root for recursive. */
ld.hints = (recursive_resolver
? dns_hints_root (ld.resolv_conf, &derr)
: dns_hints_local (ld.resolv_conf, &derr));
if (!ld.hints)
{
err = libdns_error_to_gpg_error (derr);
log_error ("failed to load DNS hints: %s\n", gpg_strerror (err));
fname = "[dns hints]";
goto leave;
}
/* All fine. Make the data global. */
libdns = ld;
if (opt_debug)
log_debug ("dns: libdns initialized%s\n", tor_mode?" (tor mode)":"");
leave:
if (!fname)
fname = cfgstr;
if (err && fname)
dirmngr_status_printf (ctrl, "WARNING",
"dns_config_problem %u"
" error accessing '%s': %s <%s>",
err, fname, gpg_strerror (err), gpg_strsource (err));
xfree (cfgstr);
return err;
}
#endif /*USE_LIBDNS*/
#ifdef USE_LIBDNS
/* Deinitialize libdns. */
static void
libdns_deinit (void)
{
struct libdns_s ld;
if (!libdns.resolv_conf)
return; /* Not initialized. */
ld = libdns;
memset (&libdns, 0, sizeof libdns);
dns_hints_close (ld.hints);
dns_hosts_close (ld.hosts);
dns_resconf_close (ld.resolv_conf);
}
#endif /*USE_LIBDNS*/
/* SIGHUP action handler for this module. With FORCE set objects are
* all immediately released. */
void
reload_dns_stuff (int force)
{
#ifdef USE_LIBDNS
if (force)
{
libdns_deinit ();
libdns_reinit_pending = 0;
}
else
{
libdns_reinit_pending = 1;
libdns_tor_port = 0; /* Start again with the default port. */
}
#else
(void)force;
#endif
}
#ifdef USE_LIBDNS
/*
* Initialize libdns if needed and open a dns_resolver context.
* Returns 0 on success and stores the new context at R_RES. On
* failure an error code is returned and NULL stored at R_RES.
*/
static gpg_error_t
libdns_res_open (ctrl_t ctrl, struct dns_resolver **r_res)
{
gpg_error_t err;
struct dns_resolver *res;
int derr;
*r_res = NULL;
/* Force a reload if resolv.conf has changed. */
if (resolv_conf_changed_p ())
{
if (opt_debug)
log_debug ("dns: resolv.conf changed - forcing reload\n");
libdns_reinit_pending = 1;
}
if (libdns_reinit_pending)
{
libdns_reinit_pending = 0;
libdns_deinit ();
}
err = libdns_init (ctrl);
if (err)
return err;
if (!opt_timeout)
set_dns_timeout (0);
res = dns_res_open (libdns.resolv_conf, libdns.hosts, libdns.hints, NULL,
dns_opts (.socks_host = &libdns.socks_host,
.socks_user = tor_socks_user,
.socks_password = tor_socks_password ),
&derr);
if (!res)
return libdns_error_to_gpg_error (derr);
*r_res = res;
return 0;
}
#endif /*USE_LIBDNS*/
#ifdef USE_LIBDNS
/* Helper to test whether we need to try again after having switched
* the Tor port. */
static int
libdns_switch_port_p (gpg_error_t err)
{
if (tor_mode && gpg_err_code (err) == GPG_ERR_ECONNREFUSED
&& libdns_tor_port == TOR_PORT)
{
/* Switch port and try again. */
if (opt_debug)
log_debug ("dns: switching from SOCKS port %d to %d\n",
TOR_PORT, TOR_PORT2);
libdns_tor_port = TOR_PORT2;
libdns_reinit_pending = 1;
return 1;
}
return 0;
}
#endif /*USE_LIBDNS*/
#ifdef USE_LIBDNS
/* Wrapper around dns_res_submit. */
static gpg_error_t
libdns_res_submit (struct dns_resolver *res, const char *qname,
enum dns_type qtype, enum dns_class qclass)
{
return libdns_error_to_gpg_error (dns_res_submit (res, qname, qtype, qclass));
}
#endif /*USE_LIBDNS*/
#ifdef USE_LIBDNS
/* Standard event handling loop. */
gpg_error_t
libdns_res_wait (struct dns_resolver *res)
{
gpg_error_t err;
while ((err = libdns_error_to_gpg_error (dns_res_check (res)))
&& gpg_err_code (err) == GPG_ERR_EAGAIN)
{
if (dns_res_elapsed (res) > opt_timeout)
{
err = gpg_error (GPG_ERR_DNS_TIMEOUT);
break;
}
my_unprotect ();
dns_res_poll (res, 1);
my_protect ();
}
return err;
}
#endif /*USE_LIBDNS*/
#ifdef USE_LIBDNS
static gpg_error_t
resolve_name_libdns (ctrl_t ctrl, const char *name, unsigned short port,
int want_family, int want_socktype,
dns_addrinfo_t *r_dai, char **r_canonname)
{
gpg_error_t err;
dns_addrinfo_t daihead = NULL;
dns_addrinfo_t dai;
struct dns_resolver *res = NULL;
struct dns_addrinfo *ai = NULL;
struct addrinfo hints;
struct addrinfo *ent;
char portstr_[21];
char *portstr = NULL;
char *namebuf = NULL;
int derr;
*r_dai = NULL;
if (r_canonname)
*r_canonname = NULL;
memset (&hints, 0, sizeof hints);
hints.ai_family = want_family;
hints.ai_socktype = want_socktype;
hints.ai_flags = AI_ADDRCONFIG;
if (r_canonname)
hints.ai_flags |= AI_CANONNAME;
if (port)
{
snprintf (portstr_, sizeof portstr_, "%hu", port);
portstr = portstr_;
}
err = libdns_res_open (ctrl, &res);
if (err)
goto leave;
if (is_ip_address (name))
{
hints.ai_flags |= AI_NUMERICHOST;
/* libdns does not grok brackets - remove them. */
if (*name == '[' && name[strlen(name)-1] == ']')
{
namebuf = xtrymalloc (strlen (name));
if (!namebuf)
{
err = gpg_error_from_syserror ();
goto leave;
}
strcpy (namebuf, name+1);
namebuf[strlen (namebuf)-1] = 0;
name = namebuf;
}
}
ai = dns_ai_open (name, portstr, 0, &hints, res, &derr);
if (!ai)
{
err = libdns_error_to_gpg_error (derr);
goto leave;
}
/* Loop over all records. */
for (;;)
{
err = libdns_error_to_gpg_error (dns_ai_nextent (&ent, ai));
if (gpg_err_code (err) == GPG_ERR_ENOENT)
{
if (daihead)
err = 0; /* We got some results, we're good. */
break; /* Ready. */
}
if (gpg_err_code (err) == GPG_ERR_EAGAIN)
{
if (dns_ai_elapsed (ai) > opt_timeout)
{
err = gpg_error (GPG_ERR_DNS_TIMEOUT);
goto leave;
}
my_unprotect ();
dns_ai_poll (ai, 1);
my_protect ();
continue;
}
if (err)
goto leave;
if (r_canonname && ! *r_canonname && ent && ent->ai_canonname)
{
*r_canonname = xtrystrdup (ent->ai_canonname);
if (!*r_canonname)
{
err = gpg_error_from_syserror ();
goto leave;
}
/* Libdns appends the root zone part which is problematic
* for most other functions - strip it. */
if (**r_canonname && (*r_canonname)[strlen (*r_canonname)-1] == '.')
(*r_canonname)[strlen (*r_canonname)-1] = 0;
}
dai = xtrymalloc (sizeof *dai);
if (dai == NULL)
{
err = gpg_error_from_syserror ();
goto leave;
}
dai->family = ent->ai_family;
dai->socktype = ent->ai_socktype;
dai->protocol = ent->ai_protocol;
dai->addrlen = ent->ai_addrlen;
memcpy (dai->addr, ent->ai_addr, ent->ai_addrlen);
dai->next = daihead;
daihead = dai;
xfree (ent);
}
leave:
dns_ai_close (ai);
dns_res_close (res);
if (err)
{
if (r_canonname)
{
xfree (*r_canonname);
*r_canonname = NULL;
}
free_dns_addrinfo (daihead);
}
else
*r_dai = daihead;
xfree (namebuf);
return err;
}
#endif /*USE_LIBDNS*/
/* Resolve a name using the standard system function. */
static gpg_error_t
resolve_name_standard (ctrl_t ctrl, const char *name, unsigned short port,
int want_family, int want_socktype,
dns_addrinfo_t *r_dai, char **r_canonname)
{
gpg_error_t err = 0;
dns_addrinfo_t daihead = NULL;
dns_addrinfo_t dai;
struct addrinfo *aibuf = NULL;
struct addrinfo hints, *ai;
char portstr[21];
int ret;
*r_dai = NULL;
if (r_canonname)
*r_canonname = NULL;
memset (&hints, 0, sizeof hints);
hints.ai_family = want_family;
hints.ai_socktype = want_socktype;
hints.ai_flags = AI_ADDRCONFIG;
if (r_canonname)
hints.ai_flags |= AI_CANONNAME;
if (is_ip_address (name))
hints.ai_flags |= AI_NUMERICHOST;
if (port)
snprintf (portstr, sizeof portstr, "%hu", port);
else
*portstr = 0;
/* We can't use the AI_IDN flag because that does the conversion
using the current locale. However, GnuPG always used UTF-8. To
support IDN we would need to make use of the libidn API. */
ret = getaddrinfo (name, *portstr? portstr : NULL, &hints, &aibuf);
if (ret)
{
aibuf = NULL;
err = map_eai_to_gpg_error (ret);
if (gpg_err_code (err) == GPG_ERR_NO_NAME)
{
/* There seems to be a bug in the glibc getaddrinfo function
if the CNAME points to a long list of A and AAAA records
in which case the function return NO_NAME. Let's do the
CNAME redirection again. */
char *cname;
if (get_dns_cname (ctrl, name, &cname))
goto leave; /* Still no success. */
ret = getaddrinfo (cname, *portstr? portstr : NULL, &hints, &aibuf);
xfree (cname);
if (ret)
{
aibuf = NULL;
err = map_eai_to_gpg_error (ret);
goto leave;
}
err = 0; /* Yep, now it worked. */
}
else
goto leave;
}
if (r_canonname && aibuf && aibuf->ai_canonname)
{
*r_canonname = xtrystrdup (aibuf->ai_canonname);
if (!*r_canonname)
{
err = gpg_error_from_syserror ();
goto leave;
}
}
for (ai = aibuf; ai; ai = ai->ai_next)
{
if (ai->ai_family != AF_INET6 && ai->ai_family != AF_INET)
continue;
if (opt_disable_ipv4 && ai->ai_family == AF_INET)
continue;
if (opt_disable_ipv6 && ai->ai_family == AF_INET6)
continue;
dai = xtrymalloc (sizeof *dai);
dai->family = ai->ai_family;
dai->socktype = ai->ai_socktype;
dai->protocol = ai->ai_protocol;
dai->addrlen = ai->ai_addrlen;
memcpy (dai->addr, ai->ai_addr, ai->ai_addrlen);
dai->next = daihead;
daihead = dai;
}
leave:
if (aibuf)
freeaddrinfo (aibuf);
if (err)
{
if (r_canonname)
{
xfree (*r_canonname);
*r_canonname = NULL;
}
free_dns_addrinfo (daihead);
}
else
*r_dai = daihead;
return err;
}
/* This a wrapper around getaddrinfo with slightly different semantics.
NAME is the name to resolve.
PORT is the requested port or 0.
WANT_FAMILY is either 0 (AF_UNSPEC), AF_INET6, or AF_INET4.
WANT_SOCKETTYPE is either SOCK_STREAM or SOCK_DGRAM.
On success the result is stored in a linked list with the head
stored at the address R_AI; the caller must call gpg_addrinfo_free
on this. If R_CANONNAME is not NULL the official name of the host
is stored there as a malloced string; if that name is not available
NULL is stored. */
gpg_error_t
resolve_dns_name (ctrl_t ctrl, const char *name, unsigned short port,
int want_family, int want_socktype,
dns_addrinfo_t *r_ai, char **r_canonname)
{
gpg_error_t err;
#ifdef USE_LIBDNS
if (!standard_resolver)
{
err = resolve_name_libdns (ctrl, name, port, want_family, want_socktype,
r_ai, r_canonname);
if (err && libdns_switch_port_p (err))
err = resolve_name_libdns (ctrl, name, port, want_family, want_socktype,
r_ai, r_canonname);
}
else
#endif /*USE_LIBDNS*/
err = resolve_name_standard (ctrl, name, port, want_family, want_socktype,
r_ai, r_canonname);
if (opt_debug)
log_debug ("dns: resolve_dns_name(%s): %s\n", name, gpg_strerror (err));
return err;
}
#ifdef USE_LIBDNS
/* Resolve an address using libdns. */
static gpg_error_t
resolve_addr_libdns (ctrl_t ctrl,
const struct sockaddr_storage *addr, int addrlen,
unsigned int flags, char **r_name)
{
gpg_error_t err;
char host[DNS_D_MAXNAME + 1];
struct dns_resolver *res = NULL;
struct dns_packet *ans = NULL;
struct dns_ptr ptr;
int derr;
*r_name = NULL;
/* First we turn ADDR into a DNS name (with ".arpa" suffix). */
err = 0;
if (addr->ss_family == AF_INET6)
{
const struct sockaddr_in6 *a6 = (const struct sockaddr_in6 *)addr;
if (!dns_aaaa_arpa (host, sizeof host, (void*)&a6->sin6_addr))
err = gpg_error (GPG_ERR_INV_OBJ);
}
else if (addr->ss_family == AF_INET)
{
const struct sockaddr_in *a4 = (const struct sockaddr_in *)addr;
if (!dns_a_arpa (host, sizeof host, (void*)&a4->sin_addr))
err = gpg_error (GPG_ERR_INV_OBJ);
}
else
err = gpg_error (GPG_ERR_EAFNOSUPPORT);
if (err)
goto leave;
err = libdns_res_open (ctrl, &res);
if (err)
goto leave;
err = libdns_res_submit (res, host, DNS_T_PTR, DNS_C_IN);
if (err)
goto leave;
err = libdns_res_wait (res);
if (err)
goto leave;
ans = dns_res_fetch (res, &derr);
if (!ans)
{
err = libdns_error_to_gpg_error (derr);
goto leave;
}
/* Check the rcode. */
switch (dns_p_rcode (ans))
{
case DNS_RC_NOERROR:
break;
case DNS_RC_NXDOMAIN:
err = gpg_error (GPG_ERR_NO_NAME);
break;
default:
err = GPG_ERR_SERVER_FAILED;
goto leave;
}
/* Parse the result. */
if (!err)
{
struct dns_rr rr;
struct dns_rr_i rri;
memset (&rri, 0, sizeof rri);
dns_rr_i_init (&rri, ans);
rri.section = DNS_S_ALL & ~DNS_S_QD;
rri.name = host;
rri.type = DNS_T_PTR;
if (!dns_rr_grep (&rr, 1, &rri, ans, &derr))
{
err = gpg_error (GPG_ERR_NOT_FOUND);
goto leave;
}
err = libdns_error_to_gpg_error (dns_ptr_parse (&ptr, &rr, ans));
if (err)
goto leave;
/* Copy result. */
*r_name = xtrystrdup (ptr.host);
if (!*r_name)
{
err = gpg_error_from_syserror ();
goto leave;
}
/* Libdns appends the root zone part which is problematic
* for most other functions - strip it. */
if (**r_name && (*r_name)[strlen (*r_name)-1] == '.')
(*r_name)[strlen (*r_name)-1] = 0;
}
else /* GPG_ERR_NO_NAME */
{
char *buffer, *p;
int buflen;
int ec;
buffer = ptr.host;
buflen = sizeof ptr.host;
p = buffer;
if (addr->ss_family == AF_INET6 && (flags & DNS_WITHBRACKET))
{
*p++ = '[';
buflen -= 2;
}
ec = getnameinfo ((const struct sockaddr *)addr,
addrlen, p, buflen, NULL, 0, NI_NUMERICHOST);
if (ec)
{
err = map_eai_to_gpg_error (ec);
goto leave;
}
if (addr->ss_family == AF_INET6 && (flags & DNS_WITHBRACKET))
strcat (buffer, "]");
}
leave:
dns_free (ans);
dns_res_close (res);
return err;
}
#endif /*USE_LIBDNS*/
/* Resolve an address using the standard system function. */
static gpg_error_t
resolve_addr_standard (const struct sockaddr_storage *addr, int addrlen,
unsigned int flags, char **r_name)
{
gpg_error_t err;
int ec;
char *buffer, *p;
int buflen;
*r_name = NULL;
buflen = NI_MAXHOST;
buffer = xtrymalloc (buflen + 2 + 1);
if (!buffer)
return gpg_error_from_syserror ();
if ((flags & DNS_NUMERICHOST) || tor_mode)
ec = EAI_NONAME;
else
ec = getnameinfo ((const struct sockaddr *)addr,
addrlen, buffer, buflen, NULL, 0, NI_NAMEREQD);
if (!ec && *buffer == '[')
ec = EAI_FAIL; /* A name may never start with a bracket. */
else if (ec == EAI_NONAME)
{
p = buffer;
if (addr->ss_family == AF_INET6 && (flags & DNS_WITHBRACKET))
{
*p++ = '[';
buflen -= 2;
}
ec = getnameinfo ((const struct sockaddr *)addr,
addrlen, p, buflen, NULL, 0, NI_NUMERICHOST);
if (!ec && addr->ss_family == AF_INET6 && (flags & DNS_WITHBRACKET))
strcat (buffer, "]");
}
if (ec)
err = map_eai_to_gpg_error (ec);
else
{
p = xtryrealloc (buffer, strlen (buffer)+1);
if (!p)
err = gpg_error_from_syserror ();
else
{
buffer = p;
err = 0;
}
}
if (err)
xfree (buffer);
else
*r_name = buffer;
return err;
}
/* A wrapper around getnameinfo. */
gpg_error_t
resolve_dns_addr (ctrl_t ctrl,
const struct sockaddr_storage *addr, int addrlen,
unsigned int flags, char **r_name)
{
gpg_error_t err;
#ifdef USE_LIBDNS
/* Note that we divert to the standard resolver for NUMERICHOST. */
if (!standard_resolver && !(flags & DNS_NUMERICHOST))
{
err = resolve_addr_libdns (ctrl, addr, addrlen, flags, r_name);
if (err && libdns_switch_port_p (err))
err = resolve_addr_libdns (ctrl, addr, addrlen, flags, r_name);
}
else
#endif /*USE_LIBDNS*/
err = resolve_addr_standard (addr, addrlen, flags, r_name);
if (opt_debug)
log_debug ("dns: resolve_dns_addr(): %s\n", gpg_strerror (err));
return err;
}
/* Check whether NAME is an IP address. Returns a true if it is
* either an IPv6 or a IPv4 numerical address. The actual return
* values can also be used to identify whether it is v4 or v6: The
* true value will surprisingly be 4 for IPv4 and 6 for IPv6. */
int
is_ip_address (const char *name)
{
const char *s;
int ndots, dblcol, n;
if (*name == '[')
return 6; /* yes: A legal DNS name may not contain this character;
this must be bracketed v6 address. */
if (*name == '.')
return 0; /* No. A leading dot is not a valid IP address. */
/* Check whether this is a v6 address. */
ndots = n = dblcol = 0;
for (s=name; *s; s++)
{
if (*s == ':')
{
ndots++;
if (s[1] == ':')
{
ndots++;
if (dblcol)
return 0; /* No: Only one "::" allowed. */
dblcol++;
if (s[1])
s++;
}
n = 0;
}
else if (*s == '.')
goto legacy;
else if (!strchr ("0123456789abcdefABCDEF", *s))
return 0; /* No: Not a hex digit. */
else if (++n > 4)
return 0; /* To many digits in a group. */
}
if (ndots > 7)
return 0; /* No: Too many colons. */
else if (ndots > 1)
return 6; /* Yes: At least 2 colons indicate an v6 address. */
legacy:
/* Check whether it is legacy IP address. */
ndots = n = 0;
for (s=name; *s; s++)
{
if (*s == '.')
{
if (s[1] == '.')
return 0; /* No: Double dot. */
if (atoi (s+1) > 255)
return 0; /* No: Ipv4 byte value too large. */
ndots++;
n = 0;
}
else if (!strchr ("0123456789", *s))
return 0; /* No: Not a digit. */
else if (++n > 3)
return 0; /* No: More than 3 digits. */
}
return (ndots == 3)? 4 : 0;
}
/* Return true if NAME is an onion address. */
int
is_onion_address (const char *name)
{
size_t len;
len = name? strlen (name) : 0;
if (len < 8 || strcmp (name + len - 6, ".onion"))
return 0;
/* Note that we require at least 2 characters before the suffix. */
return 1; /* Yes. */
}
/* libdns version of get_dns_cert. */
#ifdef USE_LIBDNS
static gpg_error_t
get_dns_cert_libdns (ctrl_t ctrl, const char *name, int want_certtype,
void **r_key, size_t *r_keylen,
unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
{
gpg_error_t err;
struct dns_resolver *res = NULL;
struct dns_packet *ans = NULL;
struct dns_rr rr;
struct dns_rr_i rri;
char host[DNS_D_MAXNAME + 1];
int derr;
int qtype;
/* Get the query type from WANT_CERTTYPE (which in general indicates
* the subtype we want). */
qtype = (want_certtype < DNS_CERTTYPE_RRBASE
? T_CERT
: (want_certtype - DNS_CERTTYPE_RRBASE));
err = libdns_res_open (ctrl, &res);
if (err)
goto leave;
if (dns_d_anchor (host, sizeof host, name, strlen (name)) >= sizeof host)
{
err = gpg_error (GPG_ERR_ENAMETOOLONG);
goto leave;
}
err = libdns_res_submit (res, name, qtype, DNS_C_IN);
if (err)
goto leave;
err = libdns_res_wait (res);
if (err)
goto leave;
ans = dns_res_fetch (res, &derr);
if (!ans)
{
err = libdns_error_to_gpg_error (derr);
goto leave;
}
/* Check the rcode. */
switch (dns_p_rcode (ans))
{
case DNS_RC_NOERROR: break;
case DNS_RC_NXDOMAIN: err = gpg_error (GPG_ERR_NO_NAME); break;
default: err = GPG_ERR_SERVER_FAILED; break;
}
if (err)
goto leave;
memset (&rri, 0, sizeof rri);
dns_rr_i_init (&rri, ans);
rri.section = DNS_S_ALL & ~DNS_S_QD;
rri.name = host;
rri.type = qtype;
err = gpg_error (GPG_ERR_NOT_FOUND);
while (dns_rr_grep (&rr, 1, &rri, ans, &derr))
{
unsigned char *rp = ans->data + rr.rd.p;
unsigned short len = rr.rd.len;
u16 subtype;
if (!len)
{
/* Definitely too short - skip. */
}
else if (want_certtype >= DNS_CERTTYPE_RRBASE
&& rr.type == (want_certtype - DNS_CERTTYPE_RRBASE)
&& r_key)
{
*r_key = xtrymalloc (len);
if (!*r_key)
err = gpg_error_from_syserror ();
else
{
memcpy (*r_key, rp, len);
*r_keylen = len;
err = 0;
}
goto leave;
}
else if (want_certtype >= DNS_CERTTYPE_RRBASE)
{
/* We did not found the requested RR - skip. */
}
else if (rr.type == T_CERT && len > 5)
{
/* We got a CERT type. */
subtype = buf16_to_u16 (rp);
rp += 2; len -= 2;
/* Skip the CERT key tag and algo which we don't need. */
rp += 3; len -= 3;
if (want_certtype && want_certtype != subtype)
; /* Not the requested subtype - skip. */
else if (subtype == DNS_CERTTYPE_PGP && len && r_key && r_keylen)
{
/* PGP subtype */
*r_key = xtrymalloc (len);
if (!*r_key)
err = gpg_error_from_syserror ();
else
{
memcpy (*r_key, rp, len);
*r_keylen = len;
err = 0;
}
goto leave;
}
else if (subtype == DNS_CERTTYPE_IPGP
&& len && len < 1023 && len >= rp[0] + 1)
{
/* IPGP type */
*r_fprlen = rp[0];
if (*r_fprlen)
{
*r_fpr = xtrymalloc (*r_fprlen);
if (!*r_fpr)
{
err = gpg_error_from_syserror ();
goto leave;
}
memcpy (*r_fpr, rp+1, *r_fprlen);
}
else
*r_fpr = NULL;
if (len > *r_fprlen + 1)
{
*r_url = xtrymalloc (len - (*r_fprlen + 1) + 1);
if (!*r_url)
{
err = gpg_error_from_syserror ();
xfree (*r_fpr);
*r_fpr = NULL;
goto leave;
}
memcpy (*r_url, rp + *r_fprlen + 1, len - (*r_fprlen + 1));
(*r_url)[len - (*r_fprlen + 1)] = 0;
}
else
*r_url = NULL;
err = 0;
goto leave;
}
else
{
/* Unknown subtype or record too short - skip. */
}
}
else
{
/* Not a requested type - skip. */
}
}
leave:
dns_free (ans);
dns_res_close (res);
return err;
}
#endif /*USE_LIBDNS*/
/* Standard resolver version of get_dns_cert. */
static gpg_error_t
get_dns_cert_standard (const char *name, int want_certtype,
void **r_key, size_t *r_keylen,
unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
{
#ifdef HAVE_SYSTEM_RESOLVER
gpg_error_t err;
unsigned char *answer;
int r;
u16 count;
/* Allocate a 64k buffer which is the limit for an DNS response. */
answer = xtrymalloc (65536);
if (!answer)
return gpg_error_from_syserror ();
err = gpg_error (GPG_ERR_NOT_FOUND);
r = res_query (name, C_IN,
(want_certtype < DNS_CERTTYPE_RRBASE
? T_CERT
: (want_certtype - DNS_CERTTYPE_RRBASE)),
answer, 65536);
/* Not too big, not too small, no errors and at least 1 answer. */
if (r >= sizeof (HEADER) && r <= 65536
&& (((HEADER *)(void *) answer)->rcode) == NOERROR
&& (count = ntohs (((HEADER *)(void *) answer)->ancount)))
{
int rc;
unsigned char *pt, *emsg;
emsg = &answer[r];
pt = &answer[sizeof (HEADER)];
/* Skip over the query */
rc = dn_skipname (pt, emsg);
if (rc == -1)
{
err = gpg_error (GPG_ERR_INV_OBJ);
goto leave;
}
pt += rc + QFIXEDSZ;
/* There are several possible response types for a CERT request.
We're interested in the PGP (a key) and IPGP (a URI) types.
Skip all others. TODO: A key is better than a URI since
we've gone through all this bother to fetch it, so favor that
if we have both PGP and IPGP? */
while (count-- > 0 && pt < emsg)
{
u16 type, class, dlen, ctype;
rc = dn_skipname (pt, emsg); /* the name we just queried for */
if (rc == -1)
{
err = gpg_error (GPG_ERR_INV_OBJ);
goto leave;
}
pt += rc;
/* Truncated message? 15 bytes takes us to the point where
we start looking at the ctype. */
if ((emsg - pt) < 15)
break;
type = buf16_to_u16 (pt);
pt += 2;
class = buf16_to_u16 (pt);
pt += 2;
if (class != C_IN)
break;
/* ttl */
pt += 4;
/* data length */
dlen = buf16_to_u16 (pt);
pt += 2;
/* Check the type and parse. */
if (want_certtype >= DNS_CERTTYPE_RRBASE
&& type == (want_certtype - DNS_CERTTYPE_RRBASE)
&& r_key)
{
*r_key = xtrymalloc (dlen);
if (!*r_key)
err = gpg_error_from_syserror ();
else
{
memcpy (*r_key, pt, dlen);
*r_keylen = dlen;
err = 0;
}
goto leave;
}
else if (want_certtype >= DNS_CERTTYPE_RRBASE)
{
/* We did not found the requested RR. */
pt += dlen;
}
else if (type == T_CERT)
{
/* We got a CERT type. */
ctype = buf16_to_u16 (pt);
pt += 2;
/* Skip the CERT key tag and algo which we don't need. */
pt += 3;
dlen -= 5;
/* 15 bytes takes us to here */
if (want_certtype && want_certtype != ctype)
; /* Not of the requested certtype. */
else if (ctype == DNS_CERTTYPE_PGP && dlen && r_key && r_keylen)
{
/* PGP type */
*r_key = xtrymalloc (dlen);
if (!*r_key)
err = gpg_error_from_syserror ();
else
{
memcpy (*r_key, pt, dlen);
*r_keylen = dlen;
err = 0;
}
goto leave;
}
else if (ctype == DNS_CERTTYPE_IPGP
&& dlen && dlen < 1023 && dlen >= pt[0] + 1)
{
/* IPGP type */
*r_fprlen = pt[0];
if (*r_fprlen)
{
*r_fpr = xtrymalloc (*r_fprlen);
if (!*r_fpr)
{
err = gpg_error_from_syserror ();
goto leave;
}
memcpy (*r_fpr, &pt[1], *r_fprlen);
}
else
*r_fpr = NULL;
if (dlen > *r_fprlen + 1)
{
*r_url = xtrymalloc (dlen - (*r_fprlen + 1) + 1);
if (!*r_url)
{
err = gpg_error_from_syserror ();
xfree (*r_fpr);
*r_fpr = NULL;
goto leave;
}
memcpy (*r_url, &pt[*r_fprlen + 1],
dlen - (*r_fprlen + 1));
(*r_url)[dlen - (*r_fprlen + 1)] = '\0';
}
else
*r_url = NULL;
err = 0;
goto leave;
}
/* No subtype matches, so continue with the next answer. */
pt += dlen;
}
else
{
/* Not a requested type - might be a CNAME. Try next item. */
pt += dlen;
}
}
}
leave:
xfree (answer);
return err;
#else /*!HAVE_SYSTEM_RESOLVER*/
(void)name;
(void)want_certtype;
(void)r_key;
(void)r_keylen;
(void)r_fpr;
(void)r_fprlen;
(void)r_url;
return gpg_error (GPG_ERR_NOT_SUPPORTED);
#endif /*!HAVE_SYSTEM_RESOLVER*/
}
/* Returns 0 on success or an error code. If a PGP CERT record was
found, the malloced data is returned at (R_KEY, R_KEYLEN) and
the other return parameters are set to NULL/0. If an IPGP CERT
record was found the fingerprint is stored as an allocated block at
R_FPR and its length at R_FPRLEN; an URL is allocated as a
string and returned at R_URL. If WANT_CERTTYPE is 0 this function
returns the first CERT found with a supported type; it is expected
that only one CERT record is used. If WANT_CERTTYPE is one of the
supported certtypes only records with this certtype are considered
and the first found is returned. (R_KEY,R_KEYLEN) are optional. */
gpg_error_t
get_dns_cert (ctrl_t ctrl, const char *name, int want_certtype,
void **r_key, size_t *r_keylen,
unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
{
gpg_error_t err;
if (r_key)
*r_key = NULL;
if (r_keylen)
*r_keylen = 0;
*r_fpr = NULL;
*r_fprlen = 0;
*r_url = NULL;
#ifdef USE_LIBDNS
if (!standard_resolver)
{
err = get_dns_cert_libdns (ctrl, name, want_certtype, r_key, r_keylen,
r_fpr, r_fprlen, r_url);
if (err && libdns_switch_port_p (err))
err = get_dns_cert_libdns (ctrl, name, want_certtype, r_key, r_keylen,
r_fpr, r_fprlen, r_url);
}
else
#endif /*USE_LIBDNS*/
err = get_dns_cert_standard (name, want_certtype, r_key, r_keylen,
r_fpr, r_fprlen, r_url);
if (opt_debug)
log_debug ("dns: get_dns_cert(%s): %s\n", name, gpg_strerror (err));
return err;
}
static int
priosort(const void *a,const void *b)
{
const struct srventry *sa=a,*sb=b;
if(sa->priority>sb->priority)
return 1;
else if(sa->prioritypriority)
return -1;
else
return 0;
}
/* Libdns based helper for getsrv. Note that it is expected that NULL
* is stored at the address of LIST and 0 is stored at the address of
* R_COUNT. */
#ifdef USE_LIBDNS
static gpg_error_t
getsrv_libdns (ctrl_t ctrl,
const char *name, struct srventry **list, unsigned int *r_count)
{
gpg_error_t err;
struct dns_resolver *res = NULL;
struct dns_packet *ans = NULL;
struct dns_rr rr;
struct dns_rr_i rri;
char host[DNS_D_MAXNAME + 1];
int derr;
unsigned int srvcount = 0;
err = libdns_res_open (ctrl, &res);
if (err)
goto leave;
if (dns_d_anchor (host, sizeof host, name, strlen (name)) >= sizeof host)
{
err = gpg_error (GPG_ERR_ENAMETOOLONG);
goto leave;
}
err = libdns_res_submit (res, name, DNS_T_SRV, DNS_C_IN);
if (err)
goto leave;
err = libdns_res_wait (res);
if (err)
goto leave;
ans = dns_res_fetch (res, &derr);
if (!ans)
{
err = libdns_error_to_gpg_error (derr);
goto leave;
}
/* Check the rcode. */
switch (dns_p_rcode (ans))
{
case DNS_RC_NOERROR: break;
case DNS_RC_NXDOMAIN: err = gpg_error (GPG_ERR_NO_NAME); break;
default: err = GPG_ERR_SERVER_FAILED; break;
}
if (err)
goto leave;
memset (&rri, 0, sizeof rri);
dns_rr_i_init (&rri, ans);
rri.section = DNS_S_ALL & ~DNS_S_QD;
rri.name = host;
rri.type = DNS_T_SRV;
while (dns_rr_grep (&rr, 1, &rri, ans, &derr))
{
struct dns_srv dsrv;
struct srventry *srv;
struct srventry *newlist;
err = libdns_error_to_gpg_error (dns_srv_parse(&dsrv, &rr, ans));
if (err)
goto leave;
newlist = xtryrealloc (*list, (srvcount+1)*sizeof(struct srventry));
if (!newlist)
{
err = gpg_error_from_syserror ();
goto leave;
}
*list = newlist;
memset (&(*list)[srvcount], 0, sizeof(struct srventry));
srv = &(*list)[srvcount];
srvcount++;
srv->priority = dsrv.priority;
srv->weight = dsrv.weight;
srv->port = dsrv.port;
mem2str (srv->target, dsrv.target, sizeof srv->target);
/* Libdns appends the root zone part which is problematic for
* most other functions - strip it. */
if (*srv->target && (srv->target)[strlen (srv->target)-1] == '.')
(srv->target)[strlen (srv->target)-1] = 0;
}
*r_count = srvcount;
leave:
if (err)
{
xfree (*list);
*list = NULL;
}
dns_free (ans);
dns_res_close (res);
return err;
}
#endif /*USE_LIBDNS*/
/* Standard resolver based helper for getsrv. Note that it is
* expected that NULL is stored at the address of LIST and 0 is stored
* at the address of R_COUNT. */
static gpg_error_t
getsrv_standard (const char *name,
struct srventry **list, unsigned int *r_count)
{
#ifdef HAVE_SYSTEM_RESOLVER
union {
unsigned char ans[2048];
HEADER header[1];
} res;
unsigned char *answer = res.ans;
HEADER *header = res.header;
unsigned char *pt, *emsg;
int r, rc;
u16 dlen;
unsigned int srvcount = 0;
u16 count;
/* Do not allow a query using the standard resolver in Tor mode. */
if (tor_mode)
return gpg_error (GPG_ERR_NOT_ENABLED);
my_unprotect ();
r = res_query (name, C_IN, T_SRV, answer, sizeof res.ans);
my_protect ();
if (r < 0)
return get_h_errno_as_gpg_error ();
if (r < sizeof (HEADER))
return gpg_error (GPG_ERR_SERVER_FAILED);
if (r > sizeof res.ans)
return gpg_error (GPG_ERR_SYSTEM_BUG);
if (header->rcode != NOERROR || !(count=ntohs (header->ancount)))
return gpg_error (GPG_ERR_NO_NAME); /* Error or no record found. */
emsg = &answer[r];
pt = &answer[sizeof(HEADER)];
/* Skip over the query */
rc = dn_skipname (pt, emsg);
if (rc == -1)
goto fail;
pt += rc + QFIXEDSZ;
while (count-- > 0 && pt < emsg)
{
struct srventry *srv;
u16 type, class;
struct srventry *newlist;
newlist = xtryrealloc (*list, (srvcount+1)*sizeof(struct srventry));
if (!newlist)
goto fail;
*list = newlist;
memset (&(*list)[srvcount], 0, sizeof(struct srventry));
srv = &(*list)[srvcount];
srvcount++;
rc = dn_skipname (pt, emsg); /* The name we just queried for. */
if (rc == -1)
goto fail;
pt += rc;
/* Truncated message? */
if ((emsg-pt) < 16)
goto fail;
type = buf16_to_u16 (pt);
pt += 2;
/* We asked for SRV and got something else !? */
if (type != T_SRV)
goto fail;
class = buf16_to_u16 (pt);
pt += 2;
/* We asked for IN and got something else !? */
if (class != C_IN)
goto fail;
pt += 4; /* ttl */
dlen = buf16_to_u16 (pt);
pt += 2;
srv->priority = buf16_to_ushort (pt);
pt += 2;
srv->weight = buf16_to_ushort (pt);
pt += 2;
srv->port = buf16_to_ushort (pt);
pt += 2;
/* Get the name. 2782 doesn't allow name compression, but
* dn_expand still works to pull the name out of the packet. */
rc = dn_expand (answer, emsg, pt, srv->target, sizeof srv->target);
if (rc == 1 && srv->target[0] == 0) /* "." */
{
xfree(*list);
*list = NULL;
return 0;
}
if (rc == -1)
goto fail;
pt += rc;
/* Corrupt packet? */
if (dlen != rc+6)
goto fail;
}
*r_count = srvcount;
return 0;
fail:
xfree (*list);
*list = NULL;
return gpg_error (GPG_ERR_GENERAL);
#else /*!HAVE_SYSTEM_RESOLVER*/
(void)name;
(void)list;
(void)r_count;
return gpg_error (GPG_ERR_NOT_SUPPORTED);
#endif /*!HAVE_SYSTEM_RESOLVER*/
}
/* Query a SRV record for SERVICE and PROTO for NAME. If SERVICE is
* NULL, NAME is expected to contain the full query name. Note that
* we do not return NONAME but simply store 0 at R_COUNT. On error an
* error code is returned and 0 stored at R_COUNT. */
gpg_error_t
get_dns_srv (ctrl_t ctrl,
const char *name, const char *service, const char *proto,
struct srventry **list, unsigned int *r_count)
{
gpg_error_t err;
char *namebuffer = NULL;
unsigned int srvcount;
int i;
*list = NULL;
*r_count = 0;
srvcount = 0;
/* If SERVICE is given construct the query from it and PROTO. */
if (service)
{
namebuffer = xtryasprintf ("_%s._%s.%s",
service, proto? proto:"tcp", name);
if (!namebuffer)
{
err = gpg_error_from_syserror ();
goto leave;
}
name = namebuffer;
}
#ifdef USE_LIBDNS
if (!standard_resolver)
{
err = getsrv_libdns (ctrl, name, list, &srvcount);
if (err && libdns_switch_port_p (err))
err = getsrv_libdns (ctrl, name, list, &srvcount);
}
else
#endif /*USE_LIBDNS*/
err = getsrv_standard (name, list, &srvcount);
if (err)
{
if (gpg_err_code (err) == GPG_ERR_NO_NAME)
err = 0;
goto leave;
}
/* Now we have an array of all the srv records. */
/* Order by priority */
qsort(*list,srvcount,sizeof(struct srventry),priosort);
/* For each priority, move the zero-weighted items first. */
for (i=0; i < srvcount; i++)
{
int j;
for (j=i;j < srvcount && (*list)[i].priority == (*list)[j].priority; j++)
{
if((*list)[j].weight==0)
{
/* Swap j with i */
if(j!=i)
{
struct srventry temp;
memcpy (&temp,&(*list)[j],sizeof(struct srventry));
memcpy (&(*list)[j],&(*list)[i],sizeof(struct srventry));
memcpy (&(*list)[i],&temp,sizeof(struct srventry));
}
break;
}
}
}
/* Run the RFC-2782 weighting algorithm. We don't need very high
quality randomness for this, so regular libc srand/rand is
sufficient. */
{
static int done;
if (!done)
{
done = 1;
srand (time (NULL)*getpid());
}
}
for (i=0; i < srvcount; i++)
{
int j;
float prio_count=0,chose;
for (j=i; j < srvcount && (*list)[i].priority == (*list)[j].priority; j++)
{
prio_count+=(*list)[j].weight;
(*list)[j].run_count=prio_count;
}
chose=prio_count*rand()/RAND_MAX;
for (j=i;j %u records\n", name, srvcount);
}
if (!err)
*r_count = srvcount;
xfree (namebuffer);
return err;
}
#ifdef USE_LIBDNS
/* libdns version of get_dns_cname. */
gpg_error_t
get_dns_cname_libdns (ctrl_t ctrl, const char *name, char **r_cname)
{
gpg_error_t err;
struct dns_resolver *res;
struct dns_packet *ans = NULL;
struct dns_cname cname;
int derr;
err = libdns_res_open (ctrl, &res);
if (err)
goto leave;
err = libdns_res_submit (res, name, DNS_T_CNAME, DNS_C_IN);
if (err)
goto leave;
err = libdns_res_wait (res);
if (err)
goto leave;
ans = dns_res_fetch (res, &derr);
if (!ans)
{
err = libdns_error_to_gpg_error (derr);
goto leave;
}
/* Check the rcode. */
switch (dns_p_rcode (ans))
{
case DNS_RC_NOERROR: break;
case DNS_RC_NXDOMAIN: err = gpg_error (GPG_ERR_NO_NAME); break;
default: err = GPG_ERR_SERVER_FAILED; break;
}
if (err)
goto leave;
/* Parse the result into CNAME. */
err = libdns_error_to_gpg_error (dns_p_study (ans));
if (err)
goto leave;
if (!dns_d_cname (&cname, sizeof cname, name, strlen (name), ans, &derr))
{
err = libdns_error_to_gpg_error (derr);
goto leave;
}
/* Copy result. */
*r_cname = xtrystrdup (cname.host);
if (!*r_cname)
err = gpg_error_from_syserror ();
else
{
/* Libdns appends the root zone part which is problematic
* for most other functions - strip it. */
if (**r_cname && (*r_cname)[strlen (*r_cname)-1] == '.')
(*r_cname)[strlen (*r_cname)-1] = 0;
}
leave:
dns_free (ans);
dns_res_close (res);
return err;
}
#endif /*USE_LIBDNS*/
/* Standard resolver version of get_dns_cname. */
gpg_error_t
get_dns_cname_standard (const char *name, char **r_cname)
{
#ifdef HAVE_SYSTEM_RESOLVER
gpg_error_t err;
int rc;
union {
unsigned char ans[2048];
HEADER header[1];
} res;
unsigned char *answer = res.ans;
HEADER *header = res.header;
unsigned char *pt, *emsg;
int r;
char *cname;
int cnamesize = 1025;
u16 count;
/* Do not allow a query using the standard resolver in Tor mode. */
if (tor_mode)
return -1;
my_unprotect ();
r = res_query (name, C_IN, T_CERT, answer, sizeof res.ans);
my_protect ();
if (r < 0)
return get_h_errno_as_gpg_error ();
if (r < sizeof (HEADER))
return gpg_error (GPG_ERR_SERVER_FAILED);
if (r > sizeof res.ans)
return gpg_error (GPG_ERR_SYSTEM_BUG);
if (header->rcode != NOERROR || !(count=ntohs (header->ancount)))
return gpg_error (GPG_ERR_NO_NAME); /* Error or no record found. */
if (count != 1)
return gpg_error (GPG_ERR_SERVER_FAILED);
emsg = &answer[r];
pt = &answer[sizeof(HEADER)];
rc = dn_skipname (pt, emsg);
if (rc == -1)
return gpg_error (GPG_ERR_SERVER_FAILED);
pt += rc + QFIXEDSZ;
if (pt >= emsg)
return gpg_error (GPG_ERR_SERVER_FAILED);
rc = dn_skipname (pt, emsg);
if (rc == -1)
return gpg_error (GPG_ERR_SERVER_FAILED);
pt += rc + 2 + 2 + 4;
if (pt+2 >= emsg)
return gpg_error (GPG_ERR_SERVER_FAILED);
pt += 2; /* Skip rdlen */
cname = xtrymalloc (cnamesize);
if (!cname)
return gpg_error_from_syserror ();
rc = dn_expand (answer, emsg, pt, cname, cnamesize -1);
if (rc == -1)
{
xfree (cname);
return gpg_error (GPG_ERR_SERVER_FAILED);
}
*r_cname = xtryrealloc (cname, strlen (cname)+1);
if (!*r_cname)
{
err = gpg_error_from_syserror ();
xfree (cname);
return err;
}
return 0;
#else /*!HAVE_SYSTEM_RESOLVER*/
(void)name;
(void)r_cname;
return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
#endif /*!HAVE_SYSTEM_RESOLVER*/
}
gpg_error_t
get_dns_cname (ctrl_t ctrl, const char *name, char **r_cname)
{
gpg_error_t err;
*r_cname = NULL;
#ifdef USE_LIBDNS
if (!standard_resolver)
{
err = get_dns_cname_libdns (ctrl, name, r_cname);
if (err && libdns_switch_port_p (err))
err = get_dns_cname_libdns (ctrl, name, r_cname);
return err;
}
#endif /*USE_LIBDNS*/
err = get_dns_cname_standard (name, r_cname);
if (opt_debug)
log_debug ("get_dns_cname(%s)%s%s\n", name,
err ? ": " : " -> ",
err ? gpg_strerror (err) : *r_cname);
return err;
}
diff --git a/dirmngr/dns.c b/dirmngr/dns.c
index 77f83f437..596e81fc9 100644
--- a/dirmngr/dns.c
+++ b/dirmngr/dns.c
@@ -1,11509 +1,11509 @@
/* ==========================================================================
* dns.c - Recursive, Reentrant DNS Resolver.
* --------------------------------------------------------------------------
* Copyright (c) 2008, 2009, 2010, 2012-2016 William Ahern
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
* ==========================================================================
*/
#if HAVE_CONFIG_H
#include "config.h"
#elif !defined _GNU_SOURCE
#define _GNU_SOURCE 1
#endif
#include /* INT_MAX */
#include