diff --git a/src/backend/sse.c b/src/backend/sse.c index 13b945f..1645690 100644 --- a/src/backend/sse.c +++ b/src/backend/sse.c @@ -499,7 +499,7 @@ sp_sse_finish(struct sp_sse *s, struct sp_reply *out, struct sp_buf *err) snprintf(out->finish, sizeof(out->finish), "%s", s->finish); out->content = strdup(s->content.p != NULL ? s->content.p : ""); if (out->content == NULL) - return -1; + goto fail; for (i = 0; i < s->ncalls; i++) if (s->calls[i].seen) any = 1; @@ -507,13 +507,8 @@ sp_sse_finish(struct sp_sse *s, struct sp_reply *out, struct sp_buf *err) return 0; out->calls = calloc(s->ncalls, sizeof(*out->calls)); - if (out->calls == NULL) { - /* the content is already in out; a failed reply is not freed by - * the caller, so it must be released here */ - free(out->content); - out->content = NULL; - return -1; - } + if (out->calls == NULL) + goto fail; out->ncalls = s->ncalls; for (i = 0; i < s->ncalls; i++) { char idbuf[32]; @@ -527,18 +522,21 @@ sp_sse_finish(struct sp_sse *s, struct sp_reply *out, struct sp_buf *err) out->calls[i].args = strdup(s->calls[i].args.p != NULL ? s->calls[i].args.p : "{}"); if (out->calls[i].id == NULL || out->calls[i].name == NULL || - out->calls[i].args == NULL) { - sp_reply_free(out); - return -1; - } + out->calls[i].args == NULL) + goto fail; } - /* hand the provider's structure back verbatim next round */ + /* + * hand the provider's structure back verbatim next round. Building it + * can fail too, and the caller does not free a reply it was told + * failed (agent_request only frees on its own paths), so every exit + * from here on goes through `fail`. + */ { struct sp_buf json; if (sp_buf_init(&json) != 0) - return -1; + goto fail; sp_buf_puts(&json, "["); for (i = 0; i < s->ncalls; i++) { if (i > 0) @@ -556,8 +554,12 @@ sp_sse_finish(struct sp_sse *s, struct sp_reply *out, struct sp_buf *err) out->calls_json = strdup(json.p); sp_buf_free(&json); if (out->calls_json == NULL) - return -1; + goto fail; } (void)err; return 0; + +fail: + sp_reply_free(out); + return -1; }