Skip to content

Commit 392b862

Browse files
illikainengitster
authored andcommitted
gpg-interface: refactor the free-and-xmemdupz pattern
Introduce a static replace_cstring() function to simplify repeated pattern of free-and-xmemdupz() for GPG status line parsing. This also helps us avoid potential memleaks if parsing of new status lines are introduced in the future. Signed-off-by: Hans Jerry Illikainen <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 75b2f01 commit 392b862

File tree

1 file changed

+15
-7
lines changed

1 file changed

+15
-7
lines changed

gpg-interface.c

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,16 @@ static struct {
105105
{ 0, "VALIDSIG ", GPG_STATUS_FINGERPRINT },
106106
};
107107

108+
static void replace_cstring(char **field, const char *line, const char *next)
109+
{
110+
free(*field);
111+
112+
if (line && next)
113+
*field = xmemdupz(line, next - line);
114+
else
115+
*field = NULL;
116+
}
117+
108118
static void parse_gpg_output(struct signature_check *sigc)
109119
{
110120
const char *buf = sigc->gpg_status;
@@ -136,21 +146,18 @@ static void parse_gpg_output(struct signature_check *sigc)
136146
/* Do we have key information? */
137147
if (sigcheck_gpg_status[i].flags & GPG_STATUS_KEYID) {
138148
next = strchrnul(line, ' ');
139-
free(sigc->key);
140-
sigc->key = xmemdupz(line, next - line);
149+
replace_cstring(&sigc->key, line, next);
141150
/* Do we have signer information? */
142151
if (*next && (sigcheck_gpg_status[i].flags & GPG_STATUS_UID)) {
143152
line = next + 1;
144153
next = strchrnul(line, '\n');
145-
free(sigc->signer);
146-
sigc->signer = xmemdupz(line, next - line);
154+
replace_cstring(&sigc->signer, line, next);
147155
}
148156
}
149157
/* Do we have fingerprint? */
150158
if (sigcheck_gpg_status[i].flags & GPG_STATUS_FINGERPRINT) {
151159
next = strchrnul(line, ' ');
152-
free(sigc->fingerprint);
153-
sigc->fingerprint = xmemdupz(line, next - line);
160+
replace_cstring(&sigc->fingerprint, line, next);
154161

155162
/* Skip interim fields */
156163
for (j = 9; j > 0; j--) {
@@ -162,7 +169,8 @@ static void parse_gpg_output(struct signature_check *sigc)
162169

163170
next = strchrnul(line, '\n');
164171
free(sigc->primary_key_fingerprint);
165-
sigc->primary_key_fingerprint = xmemdupz(line, next - line);
172+
replace_cstring(&sigc->primary_key_fingerprint,
173+
line, next);
166174
}
167175

168176
break;

0 commit comments

Comments
 (0)