diff --git a/lightningd/jsonrpc.c b/lightningd/jsonrpc.c index d30562403..ed1dc4d77 100644 --- a/lightningd/jsonrpc.c +++ b/lightningd/jsonrpc.c @@ -31,6 +31,16 @@ #include #include +/* Realloc helper for tal membufs */ +static void *membuf_tal_realloc(struct membuf *mb, + void *rawelems, size_t newsize) +{ + char *p = rawelems; + + tal_resize(&p, newsize); + return p; +} + /* jcon and cmd have separate lifetimes: we detach them on either destruction */ static void destroy_jcon(struct json_connection *jcon) { @@ -266,7 +276,11 @@ static void json_done(struct json_connection *jcon, const char *json TAKES) { /* Queue for writing, and wake writer. */ - jcon->outbuf = tal_strdup(jcon, json); + size_t len = strlen(json); + char *p = membuf_add(&jcon->outbuf, len); + memcpy(p, json, len); + if (taken(json)) + tal_free(json); io_wake(jcon); /* Can be NULL if we failed to parse! */ @@ -496,7 +510,7 @@ static struct io_plan *locked_write_json(struct io_conn *conn, static struct io_plan *write_json_done(struct io_conn *conn, struct json_connection *jcon) { - jcon->outbuf = tal_free(jcon->outbuf); + membuf_consume(&jcon->outbuf, jcon->out_amount); if (jcon->stop) { log_unusual(jcon->log, "JSON-RPC shutdown"); @@ -516,7 +530,9 @@ static struct io_plan *write_json_done(struct io_conn *conn, static struct io_plan *write_json(struct io_conn *conn, struct json_connection *jcon) { - return io_write(conn, jcon->outbuf, strlen(jcon->outbuf), + jcon->out_amount = membuf_num_elems(&jcon->outbuf); + return io_write(conn, + membuf_elems(&jcon->outbuf), jcon->out_amount, write_json_done, jcon); } @@ -603,7 +619,8 @@ static struct io_plan *jcon_connected(struct io_conn *conn, jcon->buffer = tal_arr(jcon, char, 64); jcon->stop = false; jcon->lock = io_lock_new(jcon); - jcon->outbuf = NULL; + membuf_init(&jcon->outbuf, + tal_arr(jcon, char, 64), 64, membuf_tal_realloc); jcon->len_read = 0; jcon->command = NULL; diff --git a/lightningd/jsonrpc.h b/lightningd/jsonrpc.h index 43bad9da7..1def17f3e 100644 --- a/lightningd/jsonrpc.h +++ b/lightningd/jsonrpc.h @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -62,7 +63,10 @@ struct json_connection { struct command *command; /* Current command's output. */ - const char *outbuf; + MEMBUF(char) outbuf; + + /* How much we're writing right now. */ + size_t out_amount; struct io_lock *lock; };