From bde872d34c0b71bf78be2729f77a042d74f69c49 Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Mon, 20 Mar 2017 06:54:14 +1030 Subject: [PATCH] lightningd/msg_queue: support queueing/dequeueing of fds. Signed-off-by: Rusty Russell --- lightningd/msg_queue.c | 30 +++++++++++++++++++++++++++++- lightningd/msg_queue.h | 11 +++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/lightningd/msg_queue.c b/lightningd/msg_queue.c index 8b3b48312..6e7052f81 100644 --- a/lightningd/msg_queue.c +++ b/lightningd/msg_queue.c @@ -1,4 +1,7 @@ +#include +#include #include +#include void msg_queue_init(struct msg_queue *q, const tal_t *ctx) { @@ -6,7 +9,7 @@ void msg_queue_init(struct msg_queue *q, const tal_t *ctx) q->ctx = ctx; } -void msg_enqueue(struct msg_queue *q, const u8 *add) +static void do_enqueue(struct msg_queue *q, const u8 *add) { size_t n = tal_count(q->q); tal_resize(&q->q, n+1); @@ -16,6 +19,20 @@ void msg_enqueue(struct msg_queue *q, const u8 *add) io_wake(q); } +void msg_enqueue(struct msg_queue *q, const u8 *add) +{ + assert(fromwire_peektype(add) != MSG_PASS_FD); + do_enqueue(q, add); +} + +void msg_enqueue_fd(struct msg_queue *q, int fd) +{ + u8 *fdmsg = tal_arr(q->ctx, u8, 0); + towire_u16(&fdmsg, MSG_PASS_FD); + towire_u32(&fdmsg, fd); + do_enqueue(q, take(fdmsg)); +} + const u8 *msg_dequeue(struct msg_queue *q) { size_t n = tal_count(q->q); @@ -29,3 +46,14 @@ const u8 *msg_dequeue(struct msg_queue *q) tal_resize(&q->q, n-1); return msg; } + +int msg_is_fd(const u8 *msg) +{ + const u8 *p = msg + sizeof(u16); + size_t len = tal_count(msg) - sizeof(u16); + + if (fromwire_peektype(msg) != MSG_PASS_FD) + return -1; + + return fromwire_u32(&p, &len); +} diff --git a/lightningd/msg_queue.h b/lightningd/msg_queue.h index 3bee179e6..3d998e03f 100644 --- a/lightningd/msg_queue.h +++ b/lightningd/msg_queue.h @@ -5,6 +5,9 @@ #include #include +/* Reserved type used to indicate we're actually passing an fd. */ +#define MSG_PASS_FD 0xFFFF + struct msg_queue { const u8 **q; const tal_t *ctx; @@ -12,10 +15,18 @@ struct msg_queue { void msg_queue_init(struct msg_queue *q, const tal_t *ctx); +/* If add is taken(), freed after sending. */ void msg_enqueue(struct msg_queue *q, const u8 *add); +/* Fd is closed after sending. */ +void msg_enqueue_fd(struct msg_queue *q, int fd); + +/* Returns NULL if nothing to do. */ const u8 *msg_dequeue(struct msg_queue *q); +/* Returns -1 if not an fd: close after sending. */ +int msg_is_fd(const u8 *msg); + #define msg_queue_wait(conn, q, next, arg) \ io_out_wait((conn), (q), (next), (arg))