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 <hji@dyntopia.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Hans Jerry Illikainen committed
Nov 21, 2019 at 23:43 UTC
392b862e9aea69acf43532527e27644c97e3ea56
1 file changed
+15
-7
gpg-interface.c
+15
-7
@@ -105,6 +105,16 @@ static struct {
105
{ 0, "VALIDSIG ", GPG_STATUS_FINGERPRINT },
106
};
107
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
+
118
static void parse_gpg_output(struct signature_check *sigc)
119
{
120
const char *buf = sigc->gpg_status;
@@ -136,21 +146,18 @@ static void parse_gpg_output(struct signature_check *sigc)
146
/* Do we have key information? */
147
if (sigcheck_gpg_status[i].flags & GPG_STATUS_KEYID) {
148
next = strchrnul(line, ' ');
139
- free(sigc->key);
140
- sigc->key = xmemdupz(line, next - line);
149
+ replace_cstring(&sigc->key, line, next);
150
/* Do we have signer information? */
151
if (*next && (sigcheck_gpg_status[i].flags & GPG_STATUS_UID)) {
152
line = next + 1;
153
next = strchrnul(line, '\n');
145
- free(sigc->signer);
146
- sigc->signer = xmemdupz(line, next - line);
154
+ replace_cstring(&sigc->signer, line, next);
155
}
156
}
157
/* Do we have fingerprint? */
158
if (sigcheck_gpg_status[i].flags & GPG_STATUS_FINGERPRINT) {
159
next = strchrnul(line, ' ');
152
- free(sigc->fingerprint);
153
- sigc->fingerprint = xmemdupz(line, next - line);
160
+ replace_cstring(&sigc->fingerprint, line, next);
161
162
/* Skip interim fields */
163
for (j = 9; j > 0; j--) {
@@ -162,7 +169,8 @@ static void parse_gpg_output(struct signature_check *sigc)
169
170
next = strchrnul(line, '\n');
171
free(sigc->primary_key_fingerprint);
165
- sigc->primary_key_fingerprint = xmemdupz(line, next - line);
172
+ replace_cstring(&sigc->primary_key_fingerprint,
173
+ line, next);
174
}
175
176
break;