Files
splinter/plugins/a2a/a2a.c
T
lotherk d95ac721be a2a: discover the endpoint from an agent card
SPLINTER_A2A_CARD names the card; the first send picks the JSONRPC entry
from supportedInterfaces, falls back to the older single url field, and
keeps the discovered URL for the session. SPLINTER_A2A_URL still wins
when both are set. The card fetch uses the same secret handling as a
send: the bearer token goes through curl's stdin.

The fake agent serves both card shapes, and test_a2a.sh covers discovery
with and without supportedInterfaces.
2026-11-09 23:34:59 +00:00

1003 lines
25 KiB
C

/*
* splinter -- a2a: another agent as the backend, over the A2A protocol.
*
* Copyright (c) 2026 Konrad Lother
* SPDX-License-Identifier: BSD-3-Clause
*
* A2A (Agent2Agent) is how one agent hands a message to another without
* sharing its tools or its memory. This is the client half, and only the part
* a chat turn needs:
*
* SendMessage JSON-RPC 2.0, one text part, blocking
*
* The answer may come back as a direct Message or as a Task in a terminal
* state; both are read, and text parts from the status message and the
* artifacts are joined. A Task id and context id are remembered for the rest
* of the session, so the next turn continues the same conversation.
*
* Not implemented, and said out loud: streaming (SendStreamingMessage), file
* and structured-data parts, push notifications, task cancel/get, and the
* agent-card discovery step. The endpoint is configured directly:
*
* SPLINTER_A2A_URL the JSON-RPC endpoint (required)
* SPLINTER_A2A_TOKEN optional bearer token
* SPLINTER_A2A_TIMEOUT seconds, default 300
* SPLINTER_A2A_FULL=1 send the whole transcript, not just the last user turn
*
* The transport is selected like any other: --plugin plugins/a2a/a2a.so
* --transport a2a.
*/
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <strings.h>
#include "splinter.h"
#include "splinter_plugin.h"
#include "curl.h"
#include "mcp.h"
struct a2a_cfg {
char url[512];
char card[512];
char token[512];
char task_id[128];
char context_id[128];
long timeout;
int full;
};
static int
render(const struct sp_conv *conv, int full, struct sp_buf *out)
{
size_t i, from = 0;
sp_buf_clear(out);
if (!full) {
for (i = conv->n; i > 0; i--) {
if (conv->v[i - 1].role != NULL &&
strcmp(conv->v[i - 1].role, "user") == 0) {
from = i - 1;
break;
}
}
}
for (i = from; i < conv->n; i++) {
const struct sp_msg *m = &conv->v[i];
if (m->content == NULL || m->content[0] == '\0')
continue;
if (out->len > 0 && sp_buf_puts(out, "\n") != 0)
return -1;
if (full &&
sp_buf_printf(out, "%s: ", m->role != NULL ? m->role :
"?") != 0)
return -1;
if (sp_buf_puts(out, m->content) != 0)
return -1;
}
return 0;
}
static void
make_id(char *out, size_t cap, const char *prefix)
{
static unsigned seq;
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
snprintf(out, cap, "%s-%ld-%d-%u", prefix, (long)ts.tv_sec,
(int)getpid(), ++seq);
}
static int
build_request(struct a2a_cfg *c, const char *method, const char *text,
struct sp_buf *out)
{
char rid[96], mid[96];
make_id(rid, sizeof(rid), "rpc");
make_id(mid, sizeof(mid), "msg");
if (sp_buf_printf(out,
"{\"jsonrpc\":\"2.0\",\"id\":\"%s\",\"method\":\"%s\","
"\"params\":{\"message\":{\"messageId\":\"%s\","
"\"role\":\"ROLE_USER\",", rid, method, mid) != 0)
return -1;
if (c->task_id[0] != '\0' &&
sp_buf_printf(out, "\"taskId\":\"%s\",", c->task_id) != 0)
return -1;
if (c->context_id[0] != '\0' &&
sp_buf_printf(out, "\"contextId\":\"%s\",", c->context_id) != 0)
return -1;
if (sp_buf_puts(out, "\"parts\":[{\"text\":\"") != 0 ||
sp_json_escape(out, text) != 0 ||
sp_buf_puts(out, "\"}]},\"configuration\":{"
"\"acceptedOutputModes\":[\"text/plain\"],"
"\"returnImmediately\":false}}}") != 0)
return -1;
return 0;
}
/* text parts -> out, joined by newlines; 0 when at least one was found */
static int
collect_parts(const mcp_json *parts, struct sp_buf *out)
{
size_t i, n;
int found = 0;
if (parts == NULL || parts->t != MCP_ARR)
return 0;
n = mcp_array_len(parts);
for (i = 0; i < n; i++) {
const mcp_json *p = mcp_array_at(parts, i);
const char *t = mcp_arg_string(p, "text");
if (t == NULL || *t == '\0')
continue;
if (out->len > 0 && sp_buf_puts(out, "\n") != 0)
return 0;
if (sp_buf_puts(out, t) != 0)
return 0;
found = 1;
}
return found;
}
static int
collect_task(struct a2a_cfg *c, const mcp_json *task, struct sp_buf *text,
struct sp_buf *err)
{
const mcp_json *status, *msg, *artifacts;
const char *id, *ctx, *state;
size_t i, n;
int got = 0;
ctx = mcp_arg_string(task, "contextId");
if (ctx != NULL && *ctx != '\0')
snprintf(c->context_id, sizeof(c->context_id), "%s", ctx);
status = mcp_arg(task, "status");
state = status != NULL ? mcp_arg_string(status, "state") : NULL;
/*
* A terminal task cannot take another message. Keep the context (the
* conversation), drop the task id, so the next turn starts a new task
* in the same context instead of asking a closed one to continue.
*/
id = mcp_arg_string(task, "id");
if (id != NULL && *id != '\0') {
if (state != NULL &&
(strcmp(state, "TASK_STATE_COMPLETED") == 0 ||
strcmp(state, "TASK_STATE_FAILED") == 0 ||
strcmp(state, "TASK_STATE_CANCELED") == 0 ||
strcmp(state, "TASK_STATE_REJECTED") == 0))
c->task_id[0] = '\0';
else
snprintf(c->task_id, sizeof(c->task_id), "%s", id);
}
if (state != NULL && strcmp(state, "TASK_STATE_FAILED") == 0) {
struct sp_buf why;
sp_buf_init(&why);
msg = mcp_arg(status, "message");
if (msg != NULL)
(void)collect_parts(mcp_arg(msg, "parts"), &why);
sp_buf_printf(err, "a2a: task failed%s%s", why.len > 0 ? ": " : "",
why.p != NULL ? why.p : "");
sp_buf_free(&why);
return -1;
}
if (state != NULL && (strcmp(state, "TASK_STATE_INPUT_REQUIRED") == 0 ||
strcmp(state, "TASK_STATE_AUTH_REQUIRED") == 0)) {
sp_buf_printf(err, "a2a: task needs %s (state %s)",
strcmp(state, "TASK_STATE_AUTH_REQUIRED") == 0 ?
"authentication" : "input", state);
return -1;
}
msg = status != NULL ? mcp_arg(status, "message") : NULL;
if (msg != NULL && collect_parts(mcp_arg(msg, "parts"), text))
got = 1;
artifacts = mcp_arg(task, "artifacts");
if (artifacts != NULL && artifacts->t == MCP_ARR) {
n = mcp_array_len(artifacts);
for (i = 0; i < n; i++) {
const mcp_json *a = mcp_array_at(artifacts, i);
if (collect_parts(mcp_arg(a, "parts"), text))
got = 1;
}
}
if (state != NULL && strcmp(state, "TASK_STATE_COMPLETED") != 0) {
sp_buf_printf(err, "a2a: task not complete (state %s)", state);
return -1;
}
if (!got) {
sp_buf_puts(err, "a2a: task has no text parts");
return -1;
}
return 0;
}
static int
parse_answer(struct a2a_cfg *c, const char *raw, struct sp_reply *out,
struct sp_buf *err)
{
mcp_json *v = NULL;
const mcp_json *error, *result, *task, *message;
struct sp_buf text;
int rc = -1;
if (sp_buf_init(&text) != 0)
return -1;
v = mcp_parse(raw);
if (v == NULL) {
sp_buf_puts(err, "a2a: response is not JSON");
goto out;
}
error = mcp_arg(v, "error");
if (error != NULL) {
const char *m = mcp_arg_string(error, "message");
sp_buf_printf(err, "a2a: %s", m != NULL ? m : "JSON-RPC error");
goto out;
}
result = mcp_arg(v, "result");
if (result == NULL) {
sp_buf_puts(err, "a2a: no result in the response");
goto out;
}
task = mcp_arg(result, "task");
message = mcp_arg(result, "message");
if (task == NULL && message == NULL) {
/* some servers put the object itself in result */
if (mcp_arg(result, "status") != NULL)
task = result;
else if (mcp_arg(result, "parts") != NULL)
message = result;
}
if (task != NULL && collect_task(c, task, &text, err) != 0)
goto out;
if (message != NULL) {
const char *ctx = mcp_arg_string(message, "contextId");
if (ctx != NULL && *ctx != '\0')
snprintf(c->context_id, sizeof(c->context_id), "%s",
ctx);
(void)collect_parts(mcp_arg(message, "parts"), &text);
}
if (text.len == 0) {
sp_buf_puts(err, "a2a: empty answer");
goto out;
}
out->content = strdup(text.p);
if (out->content == NULL) {
sp_buf_puts(err, "a2a: out of memory");
goto out;
}
out->status = 200;
rc = 0;
out:
if (v != NULL)
mcp_json_free(v);
sp_buf_free(&text);
return rc;
}
static void
dump_request(const char *body, size_t len)
{
const char *path = getenv("SPLINTER_DUMP_REQUEST");
FILE *f;
if (path == NULL || *path == '\0')
return;
f = fopen(path, "w");
if (f == NULL)
return;
if (len > 0)
(void)fwrite(body, 1, len, f);
fclose(f);
}
/*
* Start curl and return the read end. *templ keeps the temp file path; the
* caller unlinks it after waitpid, so curl has certainly read the body.
*/
static int
start_post(struct a2a_cfg *c, const char *body, int stream, pid_t *pid,
char *templ, size_t templcap, struct sp_buf *err)
{
char tmo[32], data[700], auth[sizeof(c->token) + 32];
const char *args[20];
const char *hdrs[2] = { NULL, NULL };
const char *dir;
size_t len = strlen(body);
int fd, n = 0;
dir = getenv("TMPDIR");
if (dir == NULL || *dir == '\0')
dir = "/var/tmp";
snprintf(templ, templcap, "%s/splinter-a2a-XXXXXX", dir);
fd = mkstemp(templ);
if (fd < 0) {
sp_buf_printf(err, "a2a: mkstemp: %s", strerror(errno));
return -1;
}
if (write(fd, body, len) != (ssize_t)len) {
sp_buf_printf(err, "a2a: short write: %s", strerror(errno));
close(fd);
unlink(templ);
return -1;
}
close(fd);
snprintf(tmo, sizeof(tmo), "%ld", c->timeout);
snprintf(data, sizeof(data), "@%s", templ);
args[n++] = "-sS";
if (stream)
args[n++] = "-N";
args[n++] = "-m";
args[n++] = tmo;
args[n++] = "-X";
args[n++] = "POST";
args[n++] = "-H";
args[n++] = "Content-Type: application/json";
args[n++] = "-H";
args[n++] = stream ? "Accept: text/event-stream" :
"Accept: application/json";
args[n++] = "--data-binary";
args[n++] = data;
args[n++] = "-w";
args[n++] = "\n%{http_code}";
args[n] = NULL;
if (c->token[0] != '\0') {
snprintf(auth, sizeof(auth), "Authorization: Bearer %s",
c->token);
hdrs[0] = auth;
}
fd = sp_curl_start(args, c->url, hdrs, 0, pid, err);
memset(auth, 0, sizeof(auth));
if (fd < 0) {
unlink(templ);
return -1;
}
return fd;
}
/*
* GET a document (the agent card) with the same secret handling as a send:
* the bearer token travels on curl's stdin, never in argv.
*/
static int
fetch(struct a2a_cfg *c, const char *url, struct sp_buf *body, long *http,
struct sp_buf *err)
{
char tmo[32], auth[sizeof(c->token) + 32];
const char *args[10];
const char *hdrs[2] = { NULL, NULL };
pid_t pid = -1;
FILE *f;
char chunk[4096];
size_t got;
int fd, status = 0;
char *nl;
snprintf(tmo, sizeof(tmo), "%ld", c->timeout);
args[0] = "-sS";
args[1] = "-m";
args[2] = tmo;
args[3] = "-H";
args[4] = "Accept: application/json";
args[5] = "-w";
args[6] = "\n%{http_code}";
args[7] = NULL;
if (c->token[0] != '\0') {
snprintf(auth, sizeof(auth), "Authorization: Bearer %s",
c->token);
hdrs[0] = auth;
}
fd = sp_curl_start(args, url, hdrs, 0, &pid, err);
memset(auth, 0, sizeof(auth));
if (fd < 0)
return -1;
f = fdopen(fd, "r");
if (f == NULL) {
close(fd);
(void)kill(pid, SIGKILL);
(void)waitpid(pid, NULL, 0);
sp_buf_printf(err, "a2a: fdopen: %s", strerror(errno));
return -1;
}
while ((got = fread(chunk, 1, sizeof(chunk), f)) > 0)
if (sp_buf_add(body, chunk, got) != 0) {
fclose(f);
(void)kill(pid, SIGKILL);
(void)waitpid(pid, NULL, 0);
sp_buf_puts(err, "a2a: out of memory");
return -1;
}
fclose(f);
if (waitpid(pid, &status, 0) < 0 || !WIFEXITED(status) ||
WEXITSTATUS(status) != 0) {
sp_buf_printf(err, "a2a: card transfer failed for %s", url);
return -1;
}
*http = 0;
if (body->len < 2 || (nl = strrchr(body->p, '\n')) == NULL) {
sp_buf_puts(err, "a2a: card response has no HTTP status");
return -1;
}
*http = strtol(nl + 1, NULL, 10);
*nl = '\0';
return 0;
}
/*
* Discovery: the card names the interfaces. Prefer a JSONRPC one, else fall
* back to the older single "url" field. SPLINTER_A2A_URL wins over the card.
*/
static int
discover(struct a2a_cfg *c, struct sp_buf *err)
{
struct sp_buf body;
mcp_json *v = NULL;
const mcp_json *ifaces;
const char *found = NULL;
char url[512];
long http = 0;
size_t i, n;
int rc = -1;
if (c->url[0] != '\0' || c->card[0] == '\0')
return 0;
memset(&body, 0, sizeof(body));
if (sp_buf_init(&body) != 0)
return -1;
if (fetch(c, c->card, &body, &http, err) != 0)
goto out;
if (http < 200 || http > 299) {
sp_buf_printf(err, "a2a: agent card HTTP %ld", http);
goto out;
}
v = mcp_parse(body.p);
if (v == NULL) {
sp_buf_puts(err, "a2a: agent card is not JSON");
goto out;
}
ifaces = mcp_arg(v, "supportedInterfaces");
if (ifaces != NULL && ifaces->t == MCP_ARR) {
n = mcp_array_len(ifaces);
for (i = 0; i < n; i++) {
const mcp_json *it = mcp_array_at(ifaces, i);
const char *b = mcp_arg_string(it, "protocolBinding");
const char *u = mcp_arg_string(it, "url");
if (u == NULL || *u == '\0')
continue;
if (b == NULL || strcasecmp(b, "JSONRPC") == 0) {
snprintf(url, sizeof(url), "%s", u);
found = url;
break;
}
}
}
if (found == NULL) {
const char *u = mcp_arg_string(v, "url");
if (u != NULL && *u != '\0') {
snprintf(url, sizeof(url), "%s", u);
found = url;
}
}
if (found == NULL) {
sp_buf_puts(err, "a2a: agent card names no JSON-RPC interface");
goto out;
}
snprintf(c->url, sizeof(c->url), "%s", found);
rc = 0;
out:
if (v != NULL)
mcp_json_free(v);
sp_buf_free(&body);
return rc;
}
static int
post(struct a2a_cfg *c, const char *body, struct sp_buf *raw,
struct sp_buf *err)
{
char templ[600], chunk[4096];
pid_t pid = -1;
FILE *f;
size_t got;
int fd, status = 0;
fd = start_post(c, body, 0, &pid, templ, sizeof(templ), err);
if (fd < 0)
return -1;
f = fdopen(fd, "r");
if (f == NULL) {
close(fd);
(void)kill(pid, SIGKILL);
(void)waitpid(pid, NULL, 0);
sp_buf_printf(err, "a2a: fdopen: %s", strerror(errno));
unlink(templ);
return -1;
}
while ((got = fread(chunk, 1, sizeof(chunk), f)) > 0)
if (sp_buf_add(raw, chunk, got) != 0) {
fclose(f);
(void)kill(pid, SIGKILL);
(void)waitpid(pid, NULL, 0);
unlink(templ);
sp_buf_puts(err, "a2a: out of memory");
return -1;
}
fclose(f);
if (waitpid(pid, &status, 0) < 0 || !WIFEXITED(status) ||
WEXITSTATUS(status) != 0) {
sp_buf_printf(err, "a2a: transfer failed for %s", c->url);
unlink(templ);
return -1;
}
unlink(templ);
return 0;
}
static void
set_ids(struct a2a_cfg *c, const char *task_id, const char *context_id,
int terminal)
{
if (context_id != NULL && *context_id != '\0')
snprintf(c->context_id, sizeof(c->context_id), "%s",
context_id);
if (task_id != NULL && *task_id != '\0') {
if (terminal)
c->task_id[0] = '\0';
else
snprintf(c->task_id, sizeof(c->task_id), "%s",
task_id);
}
}
/* append one event's text parts and hand the piece to the screen */
static int
emit_parts(const mcp_json *parts, struct sp_buf *text, int *saw_text,
sp_stream_cb cb, void *cbctx)
{
struct sp_buf piece;
if (sp_buf_init(&piece) != 0)
return -1;
if (collect_parts(parts, &piece) && piece.len > 0) {
if (sp_buf_add(text, piece.p, piece.len) != 0) {
sp_buf_free(&piece);
return -1;
}
*saw_text = 1;
if (cb != NULL)
cb(cbctx, SP_STREAM_TEXT, piece.p);
}
sp_buf_free(&piece);
return 0;
}
static int
is_terminal(const char *state)
{
return state != NULL &&
(strcmp(state, "TASK_STATE_COMPLETED") == 0 ||
strcmp(state, "TASK_STATE_FAILED") == 0 ||
strcmp(state, "TASK_STATE_CANCELED") == 0 ||
strcmp(state, "TASK_STATE_REJECTED") == 0);
}
/* states that end the turn with an error, not with an answer */
static int
state_is_error(const char *state)
{
return state != NULL &&
(strcmp(state, "TASK_STATE_FAILED") == 0 ||
strcmp(state, "TASK_STATE_CANCELED") == 0 ||
strcmp(state, "TASK_STATE_REJECTED") == 0 ||
strcmp(state, "TASK_STATE_INPUT_REQUIRED") == 0 ||
strcmp(state, "TASK_STATE_AUTH_REQUIRED") == 0);
}
/*
* One StreamResponse. The answer text can arrive as a direct Message, as
* artifact chunks, or (when neither came) as the message on the final status.
* Intermediate status notes are progress, not the answer, and are ignored.
*/
static int
stream_event(struct a2a_cfg *c, const char *payload, struct sp_buf *text,
int *saw_text, int *finished, sp_stream_cb cb, void *cbctx,
struct sp_buf *err)
{
mcp_json *v = NULL;
const mcp_json *error, *result, *task, *message, *su, *au, *status;
const char *state;
int rc = -1;
v = mcp_parse(payload);
if (v == NULL) {
sp_buf_puts(err, "a2a: stream event is not JSON");
return -1;
}
error = mcp_arg(v, "error");
if (error != NULL) {
const char *m = mcp_arg_string(error, "message");
sp_buf_printf(err, "a2a: %s", m != NULL ? m : "JSON-RPC error");
goto out;
}
result = mcp_arg(v, "result");
if (result == NULL) {
sp_buf_puts(err, "a2a: stream event has no result");
goto out;
}
task = mcp_arg(result, "task");
message = mcp_arg(result, "message");
su = mcp_arg(result, "statusUpdate");
au = mcp_arg(result, "artifactUpdate");
if (task != NULL) {
const mcp_json *artifacts;
status = mcp_arg(task, "status");
state = status != NULL ? mcp_arg_string(status, "state") :
NULL;
set_ids(c, mcp_arg_string(task, "id"),
mcp_arg_string(task, "contextId"), is_terminal(state));
if (state_is_error(state)) {
sp_buf_printf(err, "a2a: task ended in %s", state);
goto out;
}
artifacts = mcp_arg(task, "artifacts");
if (artifacts != NULL && artifacts->t == MCP_ARR) {
size_t i, n = mcp_array_len(artifacts);
for (i = 0; i < n; i++) {
const mcp_json *a = mcp_array_at(artifacts, i);
if (emit_parts(mcp_arg(a, "parts"), text,
saw_text, cb, cbctx) != 0)
goto oom;
}
}
if (is_terminal(state)) {
if (!*saw_text) {
const mcp_json *sm = status != NULL ?
mcp_arg(status, "message") : NULL;
if (sm != NULL &&
emit_parts(mcp_arg(sm, "parts"), text,
saw_text, cb, cbctx) != 0)
goto oom;
}
*finished = 1;
}
} else if (message != NULL) {
set_ids(c, NULL, mcp_arg_string(message, "contextId"), 0);
if (emit_parts(mcp_arg(message, "parts"), text, saw_text, cb,
cbctx) != 0)
goto oom;
*finished = 1;
} else if (su != NULL) {
status = mcp_arg(su, "status");
state = status != NULL ? mcp_arg_string(status, "state") :
NULL;
set_ids(c, mcp_arg_string(su, "taskId"),
mcp_arg_string(su, "contextId"), is_terminal(state));
if (state_is_error(state)) {
sp_buf_printf(err, "a2a: task ended in %s", state);
goto out;
}
if (strcmp(state != NULL ? state : "",
"TASK_STATE_COMPLETED") == 0) {
if (!*saw_text) {
const mcp_json *sm = mcp_arg(status, "message");
if (sm != NULL &&
emit_parts(mcp_arg(sm, "parts"), text,
saw_text, cb, cbctx) != 0)
goto oom;
}
*finished = 1;
}
} else if (au != NULL) {
set_ids(c, mcp_arg_string(au, "taskId"),
mcp_arg_string(au, "contextId"), 0);
if (emit_parts(mcp_arg(mcp_arg(au, "artifact"), "parts"),
text, saw_text, cb, cbctx) != 0)
goto oom;
} else {
sp_buf_puts(err, "a2a: unknown stream event");
goto out;
}
rc = 0;
goto out;
oom:
sp_buf_puts(err, "a2a: out of memory");
out:
if (v != NULL)
mcp_json_free(v);
return rc;
}
/* one line of the SSE stream: data, or the numeric HTTP status at the end */
static int
stream_line(struct a2a_cfg *c, char *line, size_t len, struct sp_buf *text,
int *saw_text, int *finished, int *http, sp_stream_cb cb, void *cbctx,
struct sp_buf *err)
{
char *p;
if (len > 0 && line[len - 1] == '\r')
line[--len] = '\0';
if (len == 0)
return 0;
if (strncmp(line, "data:", 5) == 0) {
p = line + 5;
while (*p == ' ')
p++;
if (strcmp(p, "[DONE]") == 0)
return 0;
return stream_event(c, p, text, saw_text, finished, cb, cbctx,
err);
}
if (line[0] >= '0' && line[0] <= '9') {
char *end;
*http = (int)strtol(line, &end, 10);
if (*end == '\0')
return 0;
}
return 0; /* event:, id:, comments, status */
}
static int
a2a_stream(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
struct sp_buf *err, sp_stream_cb cb, void *cbctx)
{
struct a2a_cfg *c = ctx;
struct sp_buf body, text, lbuf;
char templ[600], chunk[4096], *nl, *line;
pid_t pid = -1;
size_t start, len;
ssize_t got;
int fd = -1, http = 0, finished = 0, saw_text = 0;
int rc = -1, status = 0;
if (c == NULL || conv == NULL || out == NULL)
return -1;
if (discover(c, err) != 0)
return -1;
if (c->url[0] == '\0') {
sp_buf_puts(err, "a2a: neither SPLINTER_A2A_URL nor "
"SPLINTER_A2A_CARD is set");
return -1;
}
memset(out, 0, sizeof(*out));
out->status = 200;
memset(&body, 0, sizeof(body));
memset(&text, 0, sizeof(text));
memset(&lbuf, 0, sizeof(lbuf));
if (sp_buf_init(&body) != 0 || sp_buf_init(&text) != 0 ||
sp_buf_init(&lbuf) != 0) {
sp_buf_free(&body);
sp_buf_free(&text);
sp_buf_free(&lbuf);
return -1;
}
if (render(conv, c->full, &text) != 0) {
sp_buf_puts(err, "a2a: out of memory");
goto out;
}
if (text.len == 0) {
sp_buf_puts(err, "a2a: nothing to send");
goto out;
}
if (build_request(c, "SendStreamingMessage", text.p, &body) != 0) {
sp_buf_puts(err, "a2a: out of memory");
goto out;
}
sp_buf_clear(&text);
dump_request(body.p, body.len);
fd = start_post(c, body.p, 1, &pid, templ, sizeof(templ), err);
if (fd < 0)
goto out;
while ((got = read(fd, chunk, sizeof(chunk))) > 0) {
if (sp_buf_add(&lbuf, chunk, (size_t)got) != 0) {
sp_buf_puts(err, "a2a: out of memory");
goto fail;
}
start = 0;
while ((nl = memchr(lbuf.p + start, '\n',
lbuf.len - start)) != NULL) {
*nl = '\0';
line = lbuf.p + start;
len = (size_t)(nl - line);
if (stream_line(c, line, len, &text, &saw_text,
&finished, &http, cb, cbctx, err) != 0)
goto fail;
start = (size_t)(nl - lbuf.p) + 1;
}
if (start > 0) {
memmove(lbuf.p, lbuf.p + start, lbuf.len - start);
lbuf.len -= start;
lbuf.p[lbuf.len] = '\0';
}
}
if (got < 0 && errno == EINTR) {
sp_buf_puts(err, "a2a: read interrupted");
goto fail;
}
if (got < 0) {
sp_buf_printf(err, "a2a: read: %s", strerror(errno));
goto fail;
}
/* the last line may not end in a newline */
if (lbuf.len > 0) {
if (stream_line(c, lbuf.p, lbuf.len, &text, &saw_text,
&finished, &http, cb, cbctx, err) != 0)
goto fail;
}
close(fd);
fd = -1;
if (waitpid(pid, &status, 0) < 0 || !WIFEXITED(status) ||
WEXITSTATUS(status) != 0) {
sp_buf_printf(err, "a2a: transfer failed for %s", c->url);
goto out;
}
unlink(templ);
if (http < 200 || http > 299) {
sp_buf_printf(err, "a2a: HTTP %d", http);
goto out;
}
if (!finished) {
sp_buf_puts(err, "a2a: stream ended before a terminal state");
goto out;
}
if (text.len == 0) {
sp_buf_puts(err, "a2a: empty answer");
goto out;
}
out->content = strdup(text.p);
if (out->content == NULL) {
sp_buf_puts(err, "a2a: out of memory");
goto out;
}
rc = 0;
goto out;
fail:
if (fd >= 0)
close(fd);
(void)kill(pid, SIGKILL);
(void)waitpid(pid, NULL, 0);
unlink(templ);
out:
sp_buf_free(&body);
sp_buf_free(&text);
sp_buf_free(&lbuf);
return rc;
}
static int
a2a_send(void *ctx, const struct sp_conv *conv, struct sp_reply *out,
struct sp_buf *err)
{
struct a2a_cfg *c = ctx;
struct sp_buf body, raw, text;
char *nl;
long http;
int rc = -1;
if (c == NULL || conv == NULL || out == NULL)
return -1;
if (discover(c, err) != 0)
return -1;
if (c->url[0] == '\0') {
sp_buf_puts(err, "a2a: neither SPLINTER_A2A_URL nor "
"SPLINTER_A2A_CARD is set");
return -1;
}
memset(out, 0, sizeof(*out));
out->status = 200;
if (sp_buf_init(&body) != 0)
return -1;
if (sp_buf_init(&raw) != 0) {
sp_buf_free(&body);
return -1;
}
if (sp_buf_init(&text) != 0) {
sp_buf_free(&body);
sp_buf_free(&raw);
return -1;
}
if (render(conv, c->full, &text) != 0) {
sp_buf_puts(err, "a2a: out of memory");
goto out;
}
if (text.len == 0) {
sp_buf_puts(err, "a2a: nothing to send");
goto out;
}
if (build_request(c, "SendMessage", text.p, &body) != 0) {
sp_buf_puts(err, "a2a: out of memory");
goto out;
}
dump_request(body.p, body.len);
if (post(c, body.p, &raw, err) != 0)
goto out;
if (raw.len < 2 || (nl = strrchr(raw.p, '\n')) == NULL) {
sp_buf_puts(err, "a2a: unparseable response (no HTTP status)");
goto out;
}
http = strtol(nl + 1, NULL, 10);
*nl = '\0';
if (http < 200 || http > 299) {
sp_buf_printf(err, "a2a: HTTP %ld: %.200s", http,
raw.p != NULL ? raw.p : "");
goto out;
}
if (parse_answer(c, raw.p, out, err) != 0)
goto out;
rc = 0;
out:
sp_buf_free(&body);
sp_buf_free(&raw);
sp_buf_free(&text);
return rc;
}
static int
a2a_init(struct sp_host *h)
{
static struct a2a_cfg cfg;
static struct sp_transport tr;
const char *url = getenv("SPLINTER_A2A_URL");
const char *card = getenv("SPLINTER_A2A_CARD");
const char *tok = getenv("SPLINTER_A2A_TOKEN");
const char *to = getenv("SPLINTER_A2A_TIMEOUT");
const char *full = getenv("SPLINTER_A2A_FULL");
memset(&cfg, 0, sizeof(cfg));
if (url != NULL)
snprintf(cfg.url, sizeof(cfg.url), "%s", url);
if (card != NULL)
snprintf(cfg.card, sizeof(cfg.card), "%s", card);
if (tok != NULL)
snprintf(cfg.token, sizeof(cfg.token), "%s", tok);
cfg.timeout = 300;
if (to != NULL && *to != '\0')
cfg.timeout = strtol(to, NULL, 10);
cfg.full = full != NULL && strcmp(full, "0") != 0;
memset(&tr, 0, sizeof(tr));
tr.send = a2a_send;
tr.send_stream = a2a_stream;
tr.ctx = &cfg;
tr.provider = "a2a";
return sp_host_add_transport(h, "a2a", tr);
}
static const struct sp_plugin a2a_plugin = {
SP_PLUGIN_ABI, "a2a", "0.1.0", a2a_init, NULL, NULL
};
const struct sp_plugin *
sp_plugin_describe(void)
{
return &a2a_plugin;
}