gpg-interface: fix misdesigned signing key interfaces

The interfaces to retrieve signing keys and their IDs are misdesigned as
they return string constants even though they indeed allocate memory,
which leads to memory leaks. Refactor the code to instead always return
allocated strings and let the callers free them accordingly.

Signed-off-by: Patrick Steinhardt <ps@pks.im>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
This commit is contained in:
Patrick Steinhardt
2024-09-05 12:09:07 +02:00
committed by Junio C Hamano
parent 49d47eb541
commit b8849e236f
6 changed files with 30 additions and 19 deletions

View File

@@ -45,8 +45,8 @@ struct gpg_format {
size_t signature_size);
int (*sign_buffer)(struct strbuf *buffer, struct strbuf *signature,
const char *signing_key);
const char *(*get_default_key)(void);
const char *(*get_key_id)(void);
char *(*get_default_key)(void);
char *(*get_key_id)(void);
};
static const char *openpgp_verify_args[] = {
@@ -86,9 +86,9 @@ static int sign_buffer_gpg(struct strbuf *buffer, struct strbuf *signature,
static int sign_buffer_ssh(struct strbuf *buffer, struct strbuf *signature,
const char *signing_key);
static const char *get_default_ssh_signing_key(void);
static char *get_default_ssh_signing_key(void);
static const char *get_ssh_key_id(void);
static char *get_ssh_key_id(void);
static struct gpg_format gpg_format[] = {
{
@@ -847,7 +847,7 @@ static char *get_ssh_key_fingerprint(const char *signing_key)
}
/* Returns the first public key from an ssh-agent to use for signing */
static const char *get_default_ssh_signing_key(void)
static char *get_default_ssh_signing_key(void)
{
struct child_process ssh_default_key = CHILD_PROCESS_INIT;
int ret = -1;
@@ -899,12 +899,16 @@ static const char *get_default_ssh_signing_key(void)
return default_key;
}
static const char *get_ssh_key_id(void) {
return get_ssh_key_fingerprint(get_signing_key());
static char *get_ssh_key_id(void)
{
char *signing_key = get_signing_key();
char *key_id = get_ssh_key_fingerprint(signing_key);
free(signing_key);
return key_id;
}
/* Returns a textual but unique representation of the signing key */
const char *get_signing_key_id(void)
char *get_signing_key_id(void)
{
gpg_interface_lazy_init();
@@ -916,17 +920,17 @@ const char *get_signing_key_id(void)
return get_signing_key();
}
const char *get_signing_key(void)
char *get_signing_key(void)
{
gpg_interface_lazy_init();
if (configured_signing_key)
return configured_signing_key;
return xstrdup(configured_signing_key);
if (use_format->get_default_key) {
return use_format->get_default_key();
}
return git_committer_info(IDENT_STRICT | IDENT_NO_DATE);
return xstrdup(git_committer_info(IDENT_STRICT | IDENT_NO_DATE));
}
const char *gpg_trust_level_to_str(enum signature_trust_level level)