1 #include <bitcoin/chainparams.h>
2 #include <bitcoin/privkey.h>
3 #include <ccan/io/io.h>
4 #include <ccan/json_out/json_out.h>
5 #include <ccan/read_write_all/read_write_all.h>
6 #include <ccan/tal/str/str.h>
7 #include <common/daemon.h>
8 #include <common/json_stream.h>
9 #include <common/memleak.h>
10 #include <common/route.h>
11 #include <errno.h>
12 #include <plugins/libplugin.h>
13 #include <stdio.h>
14 #include <sys/socket.h>
15 #include <sys/un.h>
16 
17 #define READ_CHUNKSIZE 4096
18 
19 bool deprecated_apis;
20 
21 struct plugin_timer {
22 	struct timer timer;
23 	void (*cb)(void *cb_arg);
24 	void *cb_arg;
25 };
26 
27 struct rpc_conn {
28 	int fd;
29 	MEMBUF(char) mb;
30 };
31 
32 struct plugin {
33 	/* lightningd interaction */
34 	struct io_conn *stdin_conn;
35 	struct io_conn *stdout_conn;
36 
37 	/* To read from lightningd */
38 	char *buffer;
39 	size_t used, len_read;
40 	jsmn_parser parser;
41 	jsmntok_t *toks;
42 
43 	/* To write to lightningd */
44 	struct json_stream **js_arr;
45 
46 	/* Asynchronous RPC interaction */
47 	struct io_conn *io_rpc_conn;
48 	struct json_stream **rpc_js_arr;
49 	char *rpc_buffer;
50 	size_t rpc_used, rpc_len_read;
51 	jsmn_parser rpc_parser;
52 	jsmntok_t *rpc_toks;
53 	/* Tracking async RPC requests */
54 	UINTMAP(struct out_req *) out_reqs;
55 	u64 next_outreq_id;
56 
57 	/* Synchronous RPC interaction */
58 	struct rpc_conn *rpc_conn;
59 
60 	/* Plugin information details */
61 	enum plugin_restartability restartability;
62 	const struct plugin_command *commands;
63 	size_t num_commands;
64 	const struct plugin_notification *notif_subs;
65 	size_t num_notif_subs;
66 	const struct plugin_hook *hook_subs;
67 	size_t num_hook_subs;
68 	struct plugin_option *opts;
69 
70 	/* Anything special to do at init ? */
71 	const char *(*init)(struct plugin *p,
72 			    const char *buf, const jsmntok_t *);
73 	/* Has the manifest been sent already ? */
74 	bool manifested;
75 	/* Has init been received ? */
76 	bool initialized;
77 	/* Are we exiting? */
78 	bool exiting;
79 
80 	/* Map from json command names to usage strings: we don't put this inside
81 	 * struct json_command as it's good practice to have those const. */
82 	STRMAP(const char *) usagemap;
83 	/* Timers */
84 	struct timers timers;
85 	size_t in_timer;
86 
87 	/* Feature set for lightningd */
88 	struct feature_set *our_features;
89 
90 	/* Location of the RPC filename in case we need to defer RPC
91 	 * initialization or need to recover from a disconnect. */
92 	const char *rpc_location;
93 
94 	const char **notif_topics;
95 	size_t num_notif_topics;
96 
97 #if DEVELOPER
98 	/* Lets them remove ptrs from leak detection. */
99 	void (*mark_mem)(struct plugin *plugin, struct htable *memtable);
100 #endif
101 };
102 
103 /* command_result is mainly used as a compile-time check to encourage you
104  * to return as soon as you get one (and not risk use-after-free of command).
105  * Here we use two values: complete (cmd freed) and pending (still going) */
106 struct command_result {
107 	char c;
108 };
109 static struct command_result complete, pending;
110 
command_param_failed(void)111 struct command_result *command_param_failed(void)
112 {
113 	return &complete;
114 }
115 
command_done(void)116 struct command_result *command_done(void)
117 {
118 	return &complete;
119 }
120 
ld_send(struct plugin * plugin,struct json_stream * stream)121 static void ld_send(struct plugin *plugin, struct json_stream *stream)
122 {
123 	tal_steal(plugin->js_arr, stream);
124 	tal_arr_expand(&plugin->js_arr, stream);
125 	io_wake(plugin);
126 }
127 
ld_rpc_send(struct plugin * plugin,struct json_stream * stream)128 static void ld_rpc_send(struct plugin *plugin, struct json_stream *stream)
129 {
130 	tal_steal(plugin->rpc_js_arr, stream);
131 	tal_arr_expand(&plugin->rpc_js_arr, stream);
132 	io_wake(plugin->io_rpc_conn);
133 }
134 
135 /* FIXME: Move lightningd/jsonrpc to common/ ? */
136 
137 struct out_req *
jsonrpc_request_start_(struct plugin * plugin,struct command * cmd,const char * method,struct command_result * (* cb)(struct command * command,const char * buf,const jsmntok_t * result,void * arg),struct command_result * (* errcb)(struct command * command,const char * buf,const jsmntok_t * result,void * arg),void * arg)138 jsonrpc_request_start_(struct plugin *plugin, struct command *cmd,
139 		       const char *method,
140 		       struct command_result *(*cb)(struct command *command,
141 						    const char *buf,
142 						    const jsmntok_t *result,
143 						    void *arg),
144 		       struct command_result *(*errcb)(struct command *command,
145 						       const char *buf,
146 						       const jsmntok_t *result,
147 						       void *arg),
148 		       void *arg)
149 {
150 	struct out_req *out;
151 
152 	out = tal(plugin, struct out_req);
153 	out->id = plugin->next_outreq_id++;
154 	out->cmd = cmd;
155 	out->cb = cb;
156 	out->errcb = errcb;
157 	out->arg = arg;
158 	uintmap_add(&plugin->out_reqs, out->id, out);
159 
160 	out->js = new_json_stream(NULL, cmd, NULL);
161 	json_object_start(out->js, NULL);
162 	json_add_string(out->js, "jsonrpc", "2.0");
163 	json_add_u64(out->js, "id", out->id);
164 	json_add_string(out->js, "method", method);
165 	json_object_start(out->js, "params");
166 
167 	return out;
168 }
169 
plugin_feature_set(const struct plugin * p)170 const struct feature_set *plugin_feature_set(const struct plugin *p)
171 {
172 	return p->our_features;
173 }
174 
jsonrpc_finish_and_send(struct plugin * p,struct json_stream * js)175 static void jsonrpc_finish_and_send(struct plugin *p, struct json_stream *js)
176 {
177 	json_object_compat_end(js);
178 	json_stream_close(js, NULL);
179 	ld_send(p, js);
180 }
181 
jsonrpc_stream_start(struct command * cmd)182 static struct json_stream *jsonrpc_stream_start(struct command *cmd)
183 {
184 	struct json_stream *js = new_json_stream(cmd, cmd, NULL);
185 
186 	json_object_start(js, NULL);
187 	json_add_string(js, "jsonrpc", "2.0");
188 	json_add_u64(js, "id", *cmd->id);
189 
190 	return js;
191 }
192 
jsonrpc_stream_success(struct command * cmd)193 struct json_stream *jsonrpc_stream_success(struct command *cmd)
194 {
195 	struct json_stream *js = jsonrpc_stream_start(cmd);
196 
197 	json_object_start(js, "result");
198 	return js;
199 }
200 
jsonrpc_stream_fail(struct command * cmd,int code,const char * err)201 struct json_stream *jsonrpc_stream_fail(struct command *cmd,
202 					int code,
203 					const char *err)
204 {
205 	struct json_stream *js = jsonrpc_stream_start(cmd);
206 
207 	json_object_start(js, "error");
208 	json_add_member(js, "code", false, "%d", code);
209 	json_add_string(js, "message", err);
210 
211 	return js;
212 }
213 
jsonrpc_stream_fail_data(struct command * cmd,int code,const char * err)214 struct json_stream *jsonrpc_stream_fail_data(struct command *cmd,
215 					     int code,
216 					     const char *err)
217 {
218 	struct json_stream *js = jsonrpc_stream_fail(cmd, code, err);
219 
220 	json_object_start(js, "data");
221 	return js;
222 }
223 
command_complete(struct command * cmd,struct json_stream * result)224 static struct command_result *command_complete(struct command *cmd,
225 					       struct json_stream *result)
226 {
227 	/* Global object */
228 	json_object_compat_end(result);
229 	json_stream_close(result, cmd);
230 	ld_send(cmd->plugin, result);
231 	tal_free(cmd);
232 
233 	return &complete;
234 }
235 
command_finished(struct command * cmd,struct json_stream * response)236 struct command_result *command_finished(struct command *cmd,
237 					struct json_stream *response)
238 {
239 	/* "result" or "error" object */
240 	json_object_end(response);
241 
242 	return command_complete(cmd, response);
243 }
244 
245 struct command_result *WARN_UNUSED_RESULT
command_still_pending(struct command * cmd)246 command_still_pending(struct command *cmd)
247 {
248 	return &pending;
249 }
250 
json_out_obj(const tal_t * ctx,const char * fieldname,const char * str)251 struct json_out *json_out_obj(const tal_t *ctx,
252 			      const char *fieldname,
253 			      const char *str)
254 {
255 	struct json_out *jout = json_out_new(ctx);
256 	json_out_start(jout, NULL, '{');
257 	if (str)
258 		json_out_addstr(jout, fieldname, str);
259 	json_out_end(jout, '}');
260 	json_out_finished(jout);
261 
262 	return jout;
263 }
264 
265 /* Realloc helper for tal membufs */
membuf_tal_realloc(struct membuf * mb,void * rawelems,size_t newsize)266 static void *membuf_tal_realloc(struct membuf *mb, void *rawelems,
267 				size_t newsize)
268 {
269 	char *p = rawelems;
270 
271 	tal_resize(&p, newsize);
272 	return p;
273 }
274 
read_json_from_rpc(struct plugin * p)275 static int read_json_from_rpc(struct plugin *p)
276 {
277 	char *end;
278 
279 	/* We rely on the double-\n marker which only terminates JSON top
280 	 * levels.  Thanks lightningd! */
281 	while ((end = memmem(membuf_elems(&p->rpc_conn->mb),
282 			     membuf_num_elems(&p->rpc_conn->mb), "\n\n", 2))
283 	       == NULL) {
284 		ssize_t r;
285 
286 		/* Make sure we've room for at least READ_CHUNKSIZE. */
287 		membuf_prepare_space(&p->rpc_conn->mb, READ_CHUNKSIZE);
288 		r = read(p->rpc_conn->fd, membuf_space(&p->rpc_conn->mb),
289 			 membuf_num_space(&p->rpc_conn->mb));
290 		/* lightningd goes away, we go away. */
291 		if (r == 0)
292 			exit(0);
293 		if (r < 0)
294 			plugin_err(p, "Reading JSON input: %s", strerror(errno));
295 		membuf_added(&p->rpc_conn->mb, r);
296 	}
297 
298 	return end + 2 - membuf_elems(&p->rpc_conn->mb);
299 }
300 
301 /* This starts a JSON RPC message with boilerplate */
start_json_rpc(const tal_t * ctx,u64 id)302 static struct json_out *start_json_rpc(const tal_t *ctx, u64 id)
303 {
304 	struct json_out *jout = json_out_new(ctx);
305 
306 	json_out_start(jout, NULL, '{');
307 	json_out_addstr(jout, "jsonrpc", "2.0");
308 	json_out_add(jout, "id", false, "%"PRIu64, id);
309 
310 	return jout;
311 }
312 
313 /* This closes a JSON response and writes it out. */
finish_and_send_json(int fd,struct json_out * jout)314 static void finish_and_send_json(int fd, struct json_out *jout)
315 {
316 	size_t len;
317 	const char *p;
318 
319 	json_out_end(jout, '}');
320 	/* We double-\n terminate.  Don't need to, but it's more readable. */
321 	memcpy(json_out_direct(jout, 2), "\n\n", 2);
322 	json_out_finished(jout);
323 
324 	p = json_out_contents(jout, &len);
325 	write_all(fd, p, len);
326 	json_out_consume(jout, len);
327 }
328 
329 /* str is raw JSON from RPC output. */
330 static struct command_result *WARN_UNUSED_RESULT
command_done_raw(struct command * cmd,const char * label,const char * str,int size)331 command_done_raw(struct command *cmd,
332 		 const char *label,
333 		 const char *str, int size)
334 {
335 	struct json_stream *js = jsonrpc_stream_start(cmd);
336 
337 	memcpy(json_out_member_direct(js->jout, label, size), str, size);
338 
339 	return command_complete(cmd, js);
340 }
341 
342 struct command_result *WARN_UNUSED_RESULT
command_success(struct command * cmd,const struct json_out * result)343 command_success(struct command *cmd, const struct json_out *result)
344 {
345 	struct json_stream *js = jsonrpc_stream_start(cmd);
346 
347 	json_out_add_splice(js->jout, "result", result);
348 	return command_complete(cmd, js);
349 }
350 
command_done_err(struct command * cmd,errcode_t code,const char * errmsg,const struct json_out * data)351 struct command_result *command_done_err(struct command *cmd,
352 					errcode_t code,
353 					const char *errmsg,
354 					const struct json_out *data)
355 {
356 	struct json_stream *js = jsonrpc_stream_start(cmd);
357 
358 	json_object_start(js, "error");
359 	json_add_errcode(js, "code", code);
360 	json_add_string(js, "message", errmsg);
361 
362 	if (data)
363 		json_out_add_splice(js->jout, "data", data);
364 	json_object_end(js);
365 
366 	return command_complete(cmd, js);
367 }
368 
command_err_raw(struct command * cmd,const char * json_str)369 struct command_result *command_err_raw(struct command *cmd,
370 				       const char *json_str)
371 {
372 	return command_done_raw(cmd, "error",
373 				json_str, strlen(json_str));
374 }
375 
timer_complete(struct plugin * p)376 struct command_result *timer_complete(struct plugin *p)
377 {
378 	assert(p->in_timer > 0);
379 	p->in_timer--;
380 	return &complete;
381 }
382 
forward_error(struct command * cmd,const char * buf,const jsmntok_t * error,void * arg UNNEEDED)383 struct command_result *forward_error(struct command *cmd,
384 				     const char *buf,
385 				     const jsmntok_t *error,
386 				     void *arg UNNEEDED)
387 {
388 	/* Push through any errors. */
389 	return command_done_raw(cmd, "error",
390 				buf + error->start, error->end - error->start);
391 }
392 
forward_result(struct command * cmd,const char * buf,const jsmntok_t * result,void * arg UNNEEDED)393 struct command_result *forward_result(struct command *cmd,
394 				      const char *buf,
395 				      const jsmntok_t *result,
396 				      void *arg UNNEEDED)
397 {
398 	/* Push through the result. */
399 	return command_done_raw(cmd, "result",
400 				buf + result->start, result->end - result->start);
401 }
402 
403 /* Called by param() directly if it's malformed. */
command_fail(struct command * cmd,errcode_t code,const char * fmt,...)404 struct command_result *command_fail(struct command *cmd,
405 				    errcode_t code, const char *fmt, ...)
406 {
407 	va_list ap;
408 	struct command_result *res;
409 
410 	va_start(ap, fmt);
411 	res = command_done_err(cmd, code, tal_vfmt(cmd, fmt, ap), NULL);
412 	va_end(ap);
413 	return res;
414 }
415 
416 /* We invoke param for usage at registration time. */
command_usage_only(const struct command * cmd)417 bool command_usage_only(const struct command *cmd)
418 {
419 	return cmd->usage_only;
420 }
421 
422 /* FIXME: would be good to support this! */
command_check_only(const struct command * cmd)423 bool command_check_only(const struct command *cmd)
424 {
425 	return false;
426 }
427 
command_set_usage(struct command * cmd,const char * usage TAKES)428 void command_set_usage(struct command *cmd, const char *usage TAKES)
429 {
430 	usage = tal_strdup(NULL, usage);
431 	if (!strmap_add(&cmd->plugin->usagemap, cmd->methodname, usage))
432 		plugin_err(cmd->plugin, "Two usages for command %s?",
433 			   cmd->methodname);
434 }
435 
436 /* Reads rpc reply and returns tokens, setting contents to 'error' or
437  * 'result' (depending on *error). */
read_rpc_reply(const tal_t * ctx,struct plugin * plugin,const jsmntok_t ** contents,bool * error,int * reqlen)438 static const jsmntok_t *read_rpc_reply(const tal_t *ctx,
439 				       struct plugin *plugin,
440 				       const jsmntok_t **contents,
441 				       bool *error,
442 				       int *reqlen)
443 {
444 	const jsmntok_t *toks;
445 
446 	do {
447 		*reqlen = read_json_from_rpc(plugin);
448 
449 		toks = json_parse_simple(ctx,
450 					 membuf_elems(&plugin->rpc_conn->mb),
451 					 *reqlen);
452 		if (!toks)
453 			plugin_err(plugin, "Malformed JSON reply '%.*s'",
454 				   *reqlen, membuf_elems(&plugin->rpc_conn->mb));
455 		/* FIXME: Don't simply ignore notifications here! */
456 	} while (!json_get_member(membuf_elems(&plugin->rpc_conn->mb), toks,
457 				  "id"));
458 
459 	*contents = json_get_member(membuf_elems(&plugin->rpc_conn->mb), toks, "error");
460 	if (*contents)
461 		*error = true;
462 	else {
463 		*contents = json_get_member(membuf_elems(&plugin->rpc_conn->mb), toks,
464 					    "result");
465 		if (!*contents)
466 			plugin_err(plugin, "JSON reply with no 'result' nor 'error'? '%.*s'",
467 				   *reqlen, membuf_elems(&plugin->rpc_conn->mb));
468 		*error = false;
469 	}
470 	return toks;
471 }
472 
start_json_request(const tal_t * ctx,u64 id,const char * method,const struct json_out * params TAKES)473 static struct json_out *start_json_request(const tal_t *ctx,
474 					   u64 id,
475 					   const char *method,
476 					   const struct json_out *params TAKES)
477 {
478 	struct json_out *jout;
479 
480 	jout = start_json_rpc(tmpctx, id);
481 	json_out_addstr(jout, "method", method);
482 	json_out_add_splice(jout, "params", params);
483 	if (taken(params))
484 		tal_free(params);
485 
486 	return jout;
487 }
488 
489 /* Synchronous routine to send command and extract fields from response */
rpc_scan(struct plugin * plugin,const char * method,const struct json_out * params TAKES,const char * guide,...)490 void rpc_scan(struct plugin *plugin,
491 	      const char *method,
492 	      const struct json_out *params TAKES,
493 	      const char *guide,
494 	      ...)
495 {
496 	bool error;
497 	const char *err;
498 	const jsmntok_t *contents;
499 	int reqlen;
500 	const char *p;
501 	struct json_out *jout;
502 	va_list ap;
503 
504 	jout = start_json_request(tmpctx, 0, method, params);
505 	finish_and_send_json(plugin->rpc_conn->fd, jout);
506 
507 	read_rpc_reply(tmpctx, plugin, &contents, &error, &reqlen);
508 	if (error)
509 		plugin_err(plugin, "Got error reply to %s: '%.*s'",
510 		     method, reqlen, membuf_elems(&plugin->rpc_conn->mb));
511 
512 	p = membuf_consume(&plugin->rpc_conn->mb, reqlen);
513 
514 	va_start(ap, guide);
515 	err = json_scanv(tmpctx, p, contents, guide, ap);
516 	va_end(ap);
517 
518 	if (err)
519 		plugin_err(plugin, "Could not parse %s in reply to %s: %s: '%.*s'",
520 			   guide, method, err,
521 			   reqlen, membuf_elems(&plugin->rpc_conn->mb));
522 }
523 
handle_rpc_reply(struct plugin * plugin,const jsmntok_t * toks)524 static void handle_rpc_reply(struct plugin *plugin, const jsmntok_t *toks)
525 {
526 	const jsmntok_t *idtok, *contenttok;
527 	struct out_req *out;
528 	struct command_result *res;
529 	u64 id;
530 
531 	idtok = json_get_member(plugin->rpc_buffer, toks, "id");
532 	if (!idtok)
533 		/* FIXME: Don't simply ignore notifications! */
534 		return;
535 
536 	if (!json_to_u64(plugin->rpc_buffer, idtok, &id))
537 		plugin_err(plugin, "JSON reply without numeric id '%.*s'",
538 			   json_tok_full_len(toks),
539 			   json_tok_full(plugin->rpc_buffer, toks));
540 	out = uintmap_get(&plugin->out_reqs, id);
541 	if (!out)
542 		plugin_err(plugin, "JSON reply with unknown id '%.*s' (%"PRIu64")",
543 			   json_tok_full_len(toks),
544 			   json_tok_full(plugin->rpc_buffer, toks), id);
545 
546 	/* We want to free this if callback doesn't. */
547 	tal_steal(tmpctx, out);
548 	uintmap_del(&plugin->out_reqs, out->id);
549 
550 	contenttok = json_get_member(plugin->rpc_buffer, toks, "error");
551 	if (contenttok)
552 		res = out->errcb(out->cmd, plugin->rpc_buffer,
553 				 contenttok, out->arg);
554 	else {
555 		contenttok = json_get_member(plugin->rpc_buffer, toks, "result");
556 		if (!contenttok)
557 			plugin_err(plugin, "Bad JSONRPC, no 'error' nor 'result': '%.*s'",
558 				   json_tok_full_len(toks),
559 				   json_tok_full(plugin->rpc_buffer, toks));
560 		res = out->cb(out->cmd, plugin->rpc_buffer, contenttok, out->arg);
561 	}
562 
563 	assert(res == &pending || res == &complete);
564 }
565 
566 struct command_result *
send_outreq(struct plugin * plugin,const struct out_req * req)567 send_outreq(struct plugin *plugin, const struct out_req *req)
568 {
569 	/* The "param" object. */
570 	json_object_end(req->js);
571 	json_object_compat_end(req->js);
572 	json_stream_close(req->js, req->cmd);
573 
574 	ld_rpc_send(plugin, req->js);
575 
576 	return &pending;
577 }
578 
579 static struct command_result *
handle_getmanifest(struct command * getmanifest_cmd,const char * buf,const jsmntok_t * getmanifest_params)580 handle_getmanifest(struct command *getmanifest_cmd,
581 		   const char *buf,
582 		   const jsmntok_t *getmanifest_params)
583 {
584 	struct json_stream *params = jsonrpc_stream_success(getmanifest_cmd);
585 	struct plugin *p = getmanifest_cmd->plugin;
586 	const jsmntok_t *dep;
587 	bool has_shutdown_notif;
588 
589 	/* This was added post 0.9.0 */
590 	dep = json_get_member(buf, getmanifest_params, "allow-deprecated-apis");
591 	if (!dep)
592 		deprecated_apis = true;
593 	else {
594 		if (!json_to_bool(buf, dep, &deprecated_apis))
595 			plugin_err(p, "Invalid allow-deprecated-apis '%.*s'",
596 				   json_tok_full_len(dep),
597 				   json_tok_full(buf, dep));
598 	}
599 
600 	json_array_start(params, "options");
601 	for (size_t i = 0; i < tal_count(p->opts); i++) {
602 		json_object_start(params, NULL);
603 		json_add_string(params, "name", p->opts[i].name);
604 		json_add_string(params, "type", p->opts[i].type);
605 		json_add_string(params, "description", p->opts[i].description);
606 		json_add_bool(params, "deprecated", p->opts[i].deprecated);
607 		json_object_end(params);
608 	}
609 	json_array_end(params);
610 
611 	json_array_start(params, "rpcmethods");
612 	for (size_t i = 0; i < p->num_commands; i++) {
613 		json_object_start(params, NULL);
614 		json_add_string(params, "name", p->commands[i].name);
615 		json_add_string(params, "usage",
616 				strmap_get(&p->usagemap, p->commands[i].name));
617 		json_add_string(params, "description", p->commands[i].description);
618 		if (p->commands[i].long_description)
619 			json_add_string(params, "long_description",
620 					p->commands[i].long_description);
621 		json_add_bool(params, "deprecated", p->commands[i].deprecated);
622 		json_object_end(params);
623 	}
624 	json_array_end(params);
625 
626 	json_array_start(params, "subscriptions");
627 	has_shutdown_notif = false;
628 	for (size_t i = 0; i < p->num_notif_subs; i++) {
629 		json_add_string(params, NULL, p->notif_subs[i].name);
630 		if (streq(p->notif_subs[i].name, "shutdown"))
631 			has_shutdown_notif = true;
632 	}
633 #if DEVELOPER
634 	/* For memleak detection, always get notified of shutdown. */
635 	if (!has_shutdown_notif)
636 		json_add_string(params, NULL, "shutdown");
637 #else
638 	/* Don't care this is unused: compiler don't complain! */
639 	(void)has_shutdown_notif;
640 #endif
641 	json_array_end(params);
642 
643 	json_array_start(params, "hooks");
644 	for (size_t i = 0; i < p->num_hook_subs; i++) {
645 		json_object_start(params, NULL);
646 		json_add_string(params, "name", p->hook_subs[i].name);
647 		if (p->hook_subs[i].before) {
648 			json_array_start(params, "before");
649 			for (size_t j = 0; p->hook_subs[i].before[j]; j++)
650 				json_add_string(params, NULL,
651 						p->hook_subs[i].before[j]);
652 			json_array_end(params);
653 		}
654 		if (p->hook_subs[i].after) {
655 			json_array_start(params, "after");
656 			for (size_t j = 0; p->hook_subs[i].after[j]; j++)
657 				json_add_string(params, NULL,
658 						p->hook_subs[i].after[j]);
659 			json_array_end(params);
660 		}
661 		json_object_end(params);
662 	}
663 	json_array_end(params);
664 
665 	if (p->our_features != NULL) {
666 		json_object_start(params, "featurebits");
667 		for (size_t i = 0; i < NUM_FEATURE_PLACE; i++) {
668 			u8 *f = p->our_features->bits[i];
669 			const char *fieldname = feature_place_names[i];
670 			if (fieldname == NULL)
671 				continue;
672 			json_add_hex(params, fieldname, f, tal_bytelen(f));
673 		}
674 		json_object_end(params);
675 	}
676 
677 	json_add_bool(params, "dynamic", p->restartability == PLUGIN_RESTARTABLE);
678 
679 	json_array_start(params, "notifications");
680 	for (size_t i = 0; p->notif_topics && i < p->num_notif_topics; i++) {
681 		json_object_start(params, NULL);
682 		json_add_string(params, "method", p->notif_topics[i]);
683 		json_object_end(params);
684 	}
685 	json_array_end(params);
686 
687 	return command_finished(getmanifest_cmd, params);
688 }
689 
rpc_conn_finished(struct io_conn * conn,struct plugin * plugin)690 static void rpc_conn_finished(struct io_conn *conn,
691 			      struct plugin *plugin)
692 {
693 	plugin_err(plugin, "Lost connection to the RPC socket.");
694 }
695 
rpc_read_response_one(struct plugin * plugin)696 static bool rpc_read_response_one(struct plugin *plugin)
697 {
698 	const jsmntok_t *jrtok;
699 	bool complete;
700 
701 	if (!json_parse_input(&plugin->rpc_parser, &plugin->rpc_toks,
702 			      plugin->rpc_buffer, plugin->rpc_used, &complete)) {
703 		plugin_err(plugin, "Failed to parse RPC JSON response '%.*s'",
704 			   (int)plugin->rpc_used, plugin->rpc_buffer);
705 		return false;
706 	}
707 
708 	if (!complete) {
709 		/* We need more. */
710 		return false;
711 	}
712 
713 	/* Empty buffer? (eg. just whitespace). */
714 	if (tal_count(plugin->rpc_toks) == 1) {
715 		plugin->rpc_used = 0;
716 		jsmn_init(&plugin->rpc_parser);
717 		toks_reset(plugin->rpc_toks);
718 		return false;
719 	}
720 
721 	jrtok = json_get_member(plugin->rpc_buffer, plugin->rpc_toks, "jsonrpc");
722 	if (!jrtok) {
723 		plugin_err(plugin, "JSON-RPC message does not contain \"jsonrpc\" field: '%.*s'",
724                                    (int)plugin->rpc_used, plugin->rpc_buffer);
725 		return false;
726 	}
727 
728 	handle_rpc_reply(plugin, plugin->rpc_toks);
729 
730 	/* Move this object out of the buffer */
731 	memmove(plugin->rpc_buffer, plugin->rpc_buffer + plugin->rpc_toks[0].end,
732 		tal_count(plugin->rpc_buffer) - plugin->rpc_toks[0].end);
733 	plugin->rpc_used -= plugin->rpc_toks[0].end;
734 	jsmn_init(&plugin->rpc_parser);
735 	toks_reset(plugin->rpc_toks);
736 
737 	return true;
738 }
739 
rpc_conn_read_response(struct io_conn * conn,struct plugin * plugin)740 static struct io_plan *rpc_conn_read_response(struct io_conn *conn,
741 					      struct plugin *plugin)
742 {
743 	plugin->rpc_used += plugin->rpc_len_read;
744 	if (plugin->rpc_used == tal_count(plugin->rpc_buffer))
745 		tal_resize(&plugin->rpc_buffer, plugin->rpc_used * 2);
746 
747 	/* Read and process all messages from the connection */
748 	while (rpc_read_response_one(plugin))
749 		;
750 
751 	/* Read more, if there is. */
752 	return io_read_partial(plugin->io_rpc_conn,
753 			       plugin->rpc_buffer + plugin->rpc_used,
754 			       tal_bytelen(plugin->rpc_buffer) - plugin->rpc_used,
755 			       &plugin->rpc_len_read,
756 			       rpc_conn_read_response, plugin);
757 }
758 
759 static struct io_plan *rpc_conn_write_request(struct io_conn *conn,
760 					      struct plugin *plugin);
761 
762 static struct io_plan *
rpc_stream_complete(struct io_conn * conn,struct json_stream * js,struct plugin * plugin)763 rpc_stream_complete(struct io_conn *conn, struct json_stream *js,
764 		    struct plugin *plugin)
765 {
766 	assert(tal_count(plugin->rpc_js_arr) > 0);
767 	/* Remove js and shift all remaining over */
768 	tal_arr_remove(&plugin->rpc_js_arr, 0);
769 
770 	/* It got dropped off the queue, free it. */
771 	tal_free(js);
772 
773 	return rpc_conn_write_request(conn, plugin);
774 }
775 
rpc_conn_write_request(struct io_conn * conn,struct plugin * plugin)776 static struct io_plan *rpc_conn_write_request(struct io_conn *conn,
777 					      struct plugin *plugin)
778 {
779 	if (tal_count(plugin->rpc_js_arr) > 0)
780 		return json_stream_output(plugin->rpc_js_arr[0], conn,
781 					  rpc_stream_complete, plugin);
782 
783 	return io_out_wait(conn, plugin->io_rpc_conn,
784 			   rpc_conn_write_request, plugin);
785 }
786 
rpc_conn_init(struct io_conn * conn,struct plugin * plugin)787 static struct io_plan *rpc_conn_init(struct io_conn *conn,
788 				     struct plugin *plugin)
789 {
790 	plugin->io_rpc_conn = conn;
791 	io_set_finish(conn, rpc_conn_finished, plugin);
792 	return io_duplex(conn,
793 			 rpc_conn_read_response(conn, plugin),
794 			 rpc_conn_write_request(conn, plugin));
795 }
796 
json_to_feature_set(struct plugin * plugin,const char * buf,const jsmntok_t * features)797 static struct feature_set *json_to_feature_set(struct plugin *plugin,
798 					       const char *buf,
799 					       const jsmntok_t *features)
800 {
801 	struct feature_set *fset = talz(plugin, struct feature_set);
802 	const jsmntok_t *t;
803 	size_t i;
804 
805 	json_for_each_obj(i, t, features) {
806 		enum feature_place p;
807 		if (json_tok_streq(buf, t, "init"))
808 			p = INIT_FEATURE;
809 		else if (json_tok_streq(buf, t, "node"))
810 			p = NODE_ANNOUNCE_FEATURE;
811 		else if (json_tok_streq(buf, t, "channel"))
812 			p = CHANNEL_FEATURE;
813 		else if (json_tok_streq(buf, t, "invoice"))
814 			p = BOLT11_FEATURE;
815 		else
816 			continue;
817 		fset->bits[p] = json_tok_bin_from_hex(fset, buf, t + 1);
818 	}
819 	return fset;
820 }
821 
handle_init(struct command * cmd,const char * buf,const jsmntok_t * params)822 static struct command_result *handle_init(struct command *cmd,
823 					  const char *buf,
824 					  const jsmntok_t *params)
825 {
826 	const jsmntok_t *configtok, *opttok, *t;
827 	struct sockaddr_un addr;
828 	size_t i;
829 	char *dir, *network;
830 	struct plugin *p = cmd->plugin;
831 	bool with_rpc = p->rpc_conn != NULL;
832 	const char *err;
833 
834 	configtok = json_get_member(buf, params, "configuration");
835 	err = json_scan(tmpctx, buf, configtok,
836 			"{lightning-dir:%"
837 			",network:%"
838 			",feature_set:%"
839 			",rpc-file:%}",
840 			JSON_SCAN_TAL(tmpctx, json_strdup, &dir),
841 			JSON_SCAN_TAL(tmpctx, json_strdup, &network),
842 			JSON_SCAN_TAL(p, json_to_feature_set, &p->our_features),
843 			JSON_SCAN_TAL(p, json_strdup, &p->rpc_location));
844 	if (err)
845 		plugin_err(p, "cannot scan init params: %s: %.*s",
846 			   err, json_tok_full_len(params),
847 			   json_tok_full(buf, params));
848 
849 	/* Move into lightning directory: other files are relative */
850 	if (chdir(dir) != 0)
851 		plugin_err(p, "chdir to %s: %s", dir, strerror(errno));
852 
853 	chainparams = chainparams_for_network(network);
854 
855 	/* Only attempt to connect if the plugin has configured the rpc_conn
856 	 * already, if that's not the case we were told to run without an RPC
857 	 * connection, so don't even log an error. */
858 	/* FIXME: Move this to its own function so we can initialize at a
859 	 * later point in time. */
860 	if (p->rpc_conn != NULL) {
861 		p->rpc_conn->fd = socket(AF_UNIX, SOCK_STREAM, 0);
862 		if (strlen(p->rpc_location) + 1 > sizeof(addr.sun_path))
863 			plugin_err(p, "rpc filename '%s' too long",
864 				   p->rpc_location);
865 		strcpy(addr.sun_path, p->rpc_location);
866 		addr.sun_family = AF_UNIX;
867 
868 		if (connect(p->rpc_conn->fd, (struct sockaddr *)&addr,
869 			    sizeof(addr)) != 0) {
870 			with_rpc = false;
871 			plugin_log(p, LOG_UNUSUAL,
872 				   "Could not connect to '%s': %s",
873 				   p->rpc_location, strerror(errno));
874 		}
875 
876 		membuf_init(&p->rpc_conn->mb, tal_arr(p, char, READ_CHUNKSIZE),
877 			    READ_CHUNKSIZE, membuf_tal_realloc);
878 
879 	}
880 
881 	opttok = json_get_member(buf, params, "options");
882 	json_for_each_obj(i, t, opttok) {
883 		char *opt = json_strdup(NULL, buf, t);
884 		for (size_t i = 0; i < tal_count(p->opts); i++) {
885 			char *problem;
886 			if (!streq(p->opts[i].name, opt))
887 				continue;
888 			problem = p->opts[i].handle(json_strdup(opt, buf, t+1),
889 						    p->opts[i].arg);
890 			if (problem)
891 				plugin_err(p, "option '%s': %s",
892 					   p->opts[i].name, problem);
893 			break;
894 		}
895 		tal_free(opt);
896 	}
897 
898 	if (p->init) {
899 		const char *disable = p->init(p, buf, configtok);
900 		if (disable)
901 			return command_success(cmd, json_out_obj(cmd, "disable",
902 								 disable));
903 	}
904 
905 	if (with_rpc)
906 		io_new_conn(p, p->rpc_conn->fd, rpc_conn_init, p);
907 
908 	return command_success(cmd, json_out_obj(cmd, NULL, NULL));
909 }
910 
u64_option(const char * arg,u64 * i)911 char *u64_option(const char *arg, u64 *i)
912 {
913 	char *endp;
914 
915 	/* This is how the manpage says to do it.  Yech. */
916 	errno = 0;
917 	*i = strtol(arg, &endp, 0);
918 	if (*endp || !arg[0])
919 		return tal_fmt(NULL, "'%s' is not a number", arg);
920 	if (errno)
921 		return tal_fmt(NULL, "'%s' is out of range", arg);
922 	return NULL;
923 }
924 
u32_option(const char * arg,u32 * i)925 char *u32_option(const char *arg, u32 *i)
926 {
927 	char *endp;
928 	u64 n;
929 
930 	errno = 0;
931 	n = strtoul(arg, &endp, 0);
932 	if (*endp || !arg[0])
933 		return tal_fmt(NULL, "'%s' is not a number", arg);
934 	if (errno)
935 		return tal_fmt(NULL, "'%s' is out of range", arg);
936 
937 	*i = n;
938 	if (*i != n)
939 		return tal_fmt(NULL, "'%s' is too large (overflow)", arg);
940 
941 	return NULL;
942 }
943 
u16_option(const char * arg,u16 * i)944 char *u16_option(const char *arg, u16 *i)
945 {
946 	char *endp;
947 	u64 n;
948 
949 	errno = 0;
950 	n = strtoul(arg, &endp, 0);
951 	if (*endp || !arg[0])
952 		return tal_fmt(NULL, "'%s' is not a number", arg);
953 	if (errno)
954 		return tal_fmt(NULL, "'%s' is out of range", arg);
955 
956 	*i = n;
957 	if (*i != n)
958 		return tal_fmt(NULL, "'%s' is too large (overflow)", arg);
959 
960 	return NULL;
961 }
962 
bool_option(const char * arg,bool * i)963 char *bool_option(const char *arg, bool *i)
964 {
965 	if (!streq(arg, "true") && !streq(arg, "false"))
966 		return tal_fmt(NULL, "'%s' is not a bool, must be \"true\" or \"false\"", arg);
967 
968 	*i = streq(arg, "true");
969 	return NULL;
970 }
971 
flag_option(const char * arg,bool * i)972 char *flag_option(const char *arg, bool *i)
973 {
974 	/* We only get called if the flag was provided, so *i should be false
975 	 * by default */
976 	assert(*i == false);
977 	if (!streq(arg, "true"))
978 		return tal_fmt(NULL, "Invalid argument '%s' passed to a flag", arg);
979 
980 	*i = true;
981 	return NULL;
982 }
983 
charp_option(const char * arg,char ** p)984 char *charp_option(const char *arg, char **p)
985 {
986 	*p = tal_strdup(NULL, arg);
987 	return NULL;
988 }
989 
setup_command_usage(struct plugin * p)990 static void setup_command_usage(struct plugin *p)
991 {
992 	struct command *usage_cmd = tal(tmpctx, struct command);
993 
994 	/* This is how common/param can tell it's just a usage request */
995 	usage_cmd->usage_only = true;
996 	usage_cmd->plugin = p;
997 	for (size_t i = 0; i < p->num_commands; i++) {
998 		struct command_result *res;
999 
1000 		usage_cmd->methodname = p->commands[i].name;
1001 		res = p->commands[i].handle(usage_cmd, NULL, NULL);
1002 		assert(res == &complete);
1003 		assert(strmap_get(&p->usagemap, p->commands[i].name));
1004 	}
1005 }
1006 
call_plugin_timer(struct plugin * p,struct timer * timer)1007 static void call_plugin_timer(struct plugin *p, struct timer *timer)
1008 {
1009 	struct plugin_timer *t = container_of(timer, struct plugin_timer, timer);
1010 
1011 	p->in_timer++;
1012 	/* Free this if they don't. */
1013 	tal_steal(tmpctx, t);
1014 	t->cb(t->cb_arg);
1015 }
1016 
destroy_plugin_timer(struct plugin_timer * timer,struct plugin * p)1017 static void destroy_plugin_timer(struct plugin_timer *timer, struct plugin *p)
1018 {
1019 	timer_del(&p->timers, &timer->timer);
1020 }
1021 
plugin_timer_(struct plugin * p,struct timerel t,void (* cb)(void * cb_arg),void * cb_arg)1022 struct plugin_timer *plugin_timer_(struct plugin *p, struct timerel t,
1023 				   void (*cb)(void *cb_arg),
1024 				   void *cb_arg)
1025 {
1026 	struct plugin_timer *timer = notleak(tal(NULL, struct plugin_timer));
1027 	timer->cb = cb;
1028 	timer->cb_arg = cb_arg;
1029 	timer_init(&timer->timer);
1030 	timer_addrel(&p->timers, &timer->timer, t);
1031 	tal_add_destructor2(timer, destroy_plugin_timer, p);
1032 	return timer;
1033 }
1034 
plugin_logv(struct plugin * p,enum log_level l,const char * fmt,va_list ap)1035 static void plugin_logv(struct plugin *p, enum log_level l,
1036 			const char *fmt, va_list ap)
1037 {
1038 	struct json_stream *js = new_json_stream(NULL, NULL, NULL);
1039 
1040 	json_object_start(js, NULL);
1041 	json_add_string(js, "jsonrpc", "2.0");
1042 	json_add_string(js, "method", "log");
1043 
1044 	json_object_start(js, "params");
1045 	json_add_string(js, "level",
1046 			l == LOG_DBG ? "debug"
1047 			: l == LOG_INFORM ? "info"
1048 			: l == LOG_UNUSUAL ? "warn"
1049 			: "error");
1050 	json_out_addv(js->jout, "message", true, fmt, ap);
1051 	json_object_end(js);
1052 
1053 	jsonrpc_finish_and_send(p, js);
1054 }
1055 
plugin_notification_start(struct plugin * plugin,const char * method)1056 struct json_stream *plugin_notification_start(struct plugin *plugin,
1057 					      const char *method)
1058 {
1059 	struct json_stream *js = new_json_stream(plugin, NULL, NULL);
1060 
1061 	json_object_start(js, NULL);
1062 	json_add_string(js, "jsonrpc", "2.0");
1063 	json_add_string(js, "method", method);
1064 
1065 	json_object_start(js, "params");
1066 	return js;
1067 }
plugin_notification_end(struct plugin * plugin,struct json_stream * stream)1068 void plugin_notification_end(struct plugin *plugin,
1069 			     struct json_stream *stream)
1070 {
1071 	json_object_end(stream);
1072 	jsonrpc_finish_and_send(plugin, stream);
1073 }
1074 
plugin_notify_start(struct command * cmd,const char * method)1075 struct json_stream *plugin_notify_start(struct command *cmd, const char *method)
1076 {
1077 	struct json_stream *js = new_json_stream(cmd, NULL, NULL);
1078 
1079 	json_object_start(js, NULL);
1080 	json_add_string(js, "jsonrpc", "2.0");
1081 	json_add_string(js, "method", method);
1082 
1083 	json_object_start(js, "params");
1084 	json_add_u64(js, "id", *cmd->id);
1085 
1086 	return js;
1087 }
1088 
plugin_notify_end(struct command * cmd,struct json_stream * js)1089 void plugin_notify_end(struct command *cmd, struct json_stream *js)
1090 {
1091 	json_object_end(js);
1092 
1093 	jsonrpc_finish_and_send(cmd->plugin, js);
1094 }
1095 
1096 /* Convenience wrapper for notify with "message" */
plugin_notify_message(struct command * cmd,enum log_level level,const char * fmt,...)1097 void plugin_notify_message(struct command *cmd,
1098 			   enum log_level level,
1099 			   const char *fmt, ...)
1100 {
1101 	va_list ap;
1102 	struct json_stream *js;
1103 	const char *msg;
1104 
1105 	va_start(ap, fmt);
1106 	msg = tal_vfmt(tmpctx, fmt, ap);
1107 	va_end(ap);
1108 
1109 	/* Also log, debug level */
1110 	plugin_log(cmd->plugin, LOG_DBG, "notify msg %s: %s",
1111 		   log_level_name(level), msg);
1112 
1113 	js = plugin_notify_start(cmd, "message");
1114 	json_add_string(js, "level", log_level_name(level));
1115 
1116 	/* In case we're OOM */
1117 	if (js->jout)
1118 		json_out_addstr(js->jout, "message", msg);
1119 
1120 	plugin_notify_end(cmd, js);
1121 }
1122 
plugin_notify_progress(struct command * cmd,u32 num_stages,u32 stage,u32 num_progress,u32 progress)1123 void plugin_notify_progress(struct command *cmd,
1124 			    u32 num_stages, u32 stage,
1125 			    u32 num_progress, u32 progress)
1126 {
1127 	struct json_stream *js = plugin_notify_start(cmd, "progress");
1128 
1129 	assert(progress < num_progress);
1130 	json_add_u32(js, "num", progress);
1131 	json_add_u32(js, "total", num_progress);
1132 	if (num_stages > 0) {
1133 		assert(stage < num_stages);
1134 		json_object_start(js, "stage");
1135 		json_add_u32(js, "num", stage);
1136 		json_add_u32(js, "total", num_stages);
1137 		json_object_end(js);
1138 	}
1139 	plugin_notify_end(cmd, js);
1140 }
1141 
plugin_exit(struct plugin * p,int exitcode)1142 void NORETURN plugin_exit(struct plugin *p, int exitcode)
1143 {
1144 	p->exiting = true;
1145 	io_conn_out_exclusive(p->stdout_conn, true);
1146 	io_wake(p);
1147 	io_loop(NULL, NULL);
1148 	exit(exitcode);
1149 }
1150 
plugin_err(struct plugin * p,const char * fmt,...)1151 void NORETURN plugin_err(struct plugin *p, const char *fmt, ...)
1152 {
1153 	va_list ap;
1154 
1155 	va_start(ap, fmt);
1156 	plugin_logv(p, LOG_BROKEN, fmt, ap);
1157 	va_end(ap);
1158 	va_start(ap, fmt);
1159 	vfprintf(stderr, fmt, ap);
1160 	fprintf(stderr, "\n");
1161 	va_end(ap);
1162 	plugin_exit(p, 1);
1163 }
1164 
plugin_log(struct plugin * p,enum log_level l,const char * fmt,...)1165 void plugin_log(struct plugin *p, enum log_level l, const char *fmt, ...)
1166 {
1167 	va_list ap;
1168 
1169 	va_start(ap, fmt);
1170 	plugin_logv(p, l, fmt, ap);
1171 	va_end(ap);
1172 }
1173 
1174 #if DEVELOPER
1175 /* Hack since we have no extra ptr to log_memleak */
1176 static struct plugin *memleak_plugin;
log_memleak(const char * fmt,...)1177 static void PRINTF_FMT(1,2) log_memleak(const char *fmt, ...)
1178 {
1179 	va_list ap;
1180 
1181 	va_start(ap, fmt);
1182 	plugin_logv(memleak_plugin, LOG_BROKEN, fmt, ap);
1183 	va_end(ap);
1184 }
1185 
memleak_check(struct plugin * plugin,struct command * cmd)1186 static void memleak_check(struct plugin *plugin, struct command *cmd)
1187 {
1188 	struct htable *memtable;
1189 
1190 	memtable = memleak_find_allocations(tmpctx, cmd, cmd);
1191 
1192 	/* Now delete plugin and anything it has pointers to. */
1193 	memleak_remove_region(memtable, plugin, sizeof(*plugin));
1194 
1195 	/* We know usage strings are referred to. */
1196 	memleak_remove_strmap(memtable, &cmd->plugin->usagemap);
1197 
1198 	if (plugin->mark_mem)
1199 		plugin->mark_mem(plugin, memtable);
1200 
1201 	memleak_plugin = plugin;
1202 	dump_memleak(memtable, log_memleak);
1203 }
1204 
plugin_set_memleak_handler(struct plugin * plugin,void (* mark_mem)(struct plugin * plugin,struct htable * memtable))1205 void plugin_set_memleak_handler(struct plugin *plugin,
1206 				void (*mark_mem)(struct plugin *plugin,
1207 						 struct htable *memtable))
1208 {
1209 	plugin->mark_mem = mark_mem;
1210 }
1211 #endif /* DEVELOPER */
1212 
ld_command_handle(struct plugin * plugin,const jsmntok_t * toks)1213 static void ld_command_handle(struct plugin *plugin,
1214 			      const jsmntok_t *toks)
1215 {
1216 	const jsmntok_t *idtok, *methtok, *paramstok;
1217 	struct command *cmd;
1218 
1219 	idtok = json_get_member(plugin->buffer, toks, "id");
1220 	methtok = json_get_member(plugin->buffer, toks, "method");
1221 	paramstok = json_get_member(plugin->buffer, toks, "params");
1222 
1223 	if (!methtok || !paramstok)
1224 		plugin_err(plugin, "Malformed JSON-RPC notification missing "
1225 			   "\"method\" or \"params\": %.*s",
1226 			   json_tok_full_len(toks),
1227 			   json_tok_full(plugin->buffer, toks));
1228 
1229 	cmd = tal(plugin, struct command);
1230 	cmd->plugin = plugin;
1231 	cmd->id = NULL;
1232 	cmd->usage_only = false;
1233 	cmd->methodname = json_strdup(cmd, plugin->buffer, methtok);
1234 	if (idtok) {
1235 		cmd->id = tal(cmd, u64);
1236 		if (!json_to_u64(plugin->buffer, idtok, cmd->id))
1237 			plugin_err(plugin, "JSON id '%*.s' is not a number",
1238 				   json_tok_full_len(idtok),
1239 				   json_tok_full(plugin->buffer, idtok));
1240 	}
1241 
1242 	if (!plugin->manifested) {
1243 		if (streq(cmd->methodname, "getmanifest")) {
1244 			handle_getmanifest(cmd, plugin->buffer, paramstok);
1245 			plugin->manifested = true;
1246 			return;
1247 		}
1248 		plugin_err(plugin, "Did not receive 'getmanifest' yet, but got '%s'"
1249 			   " instead", cmd->methodname);
1250 	}
1251 
1252 	if (!plugin->initialized) {
1253 		if (streq(cmd->methodname, "init")) {
1254 			handle_init(cmd, plugin->buffer, paramstok);
1255 			plugin->initialized = true;
1256 			return;
1257 		}
1258 		plugin_err(plugin, "Did not receive 'init' yet, but got '%s'"
1259 			   " instead", cmd->methodname);
1260 	}
1261 
1262 	/* If that's a notification. */
1263 	if (!cmd->id) {
1264 #if DEVELOPER
1265 		bool is_shutdown = streq(cmd->methodname, "shutdown");
1266 		if (is_shutdown)
1267 			memleak_check(plugin, cmd);
1268 #endif
1269 		for (size_t i = 0; i < plugin->num_notif_subs; i++) {
1270 			if (streq(cmd->methodname,
1271 				  plugin->notif_subs[i].name)) {
1272 				plugin->notif_subs[i].handle(cmd,
1273 							     plugin->buffer,
1274 							     paramstok);
1275 				return;
1276 			}
1277 		}
1278 
1279 #if DEVELOPER
1280 		/* We subscribe them to this always */
1281 		if (is_shutdown)
1282 			plugin_exit(plugin, 0);
1283 #endif
1284 
1285 		plugin_err(plugin, "Unregistered notification %.*s",
1286 			   json_tok_full_len(methtok),
1287 			   json_tok_full(plugin->buffer, methtok));
1288 	}
1289 
1290 	for (size_t i = 0; i < plugin->num_hook_subs; i++) {
1291 		if (streq(cmd->methodname, plugin->hook_subs[i].name)) {
1292 			plugin->hook_subs[i].handle(cmd,
1293 						    plugin->buffer,
1294 						    paramstok);
1295 			return;
1296 		}
1297 	}
1298 
1299 	for (size_t i = 0; i < plugin->num_commands; i++) {
1300 		if (streq(cmd->methodname, plugin->commands[i].name)) {
1301 			plugin->commands[i].handle(cmd,
1302 						   plugin->buffer,
1303 						   paramstok);
1304 			return;
1305 		}
1306 	}
1307 
1308 	plugin_err(plugin, "Unknown command '%s'", cmd->methodname);
1309 }
1310 
1311 /**
1312  * Try to parse a complete message from lightningd's buffer, and return true
1313  * if we could handle it.
1314  */
ld_read_json_one(struct plugin * plugin)1315 static bool ld_read_json_one(struct plugin *plugin)
1316 {
1317 	bool complete;
1318 
1319 	if (!json_parse_input(&plugin->parser, &plugin->toks,
1320 			      plugin->buffer, plugin->used,
1321 			      &complete)) {
1322 		plugin_err(plugin, "Failed to parse JSON response '%.*s'",
1323 			   (int)plugin->used, plugin->buffer);
1324 		return false;
1325 	}
1326 
1327 	if (!complete) {
1328 		/* We need more. */
1329 		return false;
1330 	}
1331 
1332 	/* Empty buffer? (eg. just whitespace). */
1333 	if (tal_count(plugin->toks) == 1) {
1334 		toks_reset(plugin->toks);
1335 		jsmn_init(&plugin->parser);
1336 		plugin->used = 0;
1337 		return false;
1338 	}
1339 
1340 	/* FIXME: Spark doesn't create proper jsonrpc 2.0!  So we don't
1341 	 * check for "jsonrpc" here. */
1342 	ld_command_handle(plugin, plugin->toks);
1343 
1344 	/* Move this object out of the buffer */
1345 	memmove(plugin->buffer, plugin->buffer + plugin->toks[0].end,
1346 		tal_count(plugin->buffer) - plugin->toks[0].end);
1347 	plugin->used -= plugin->toks[0].end;
1348 	toks_reset(plugin->toks);
1349 	jsmn_init(&plugin->parser);
1350 
1351 	return true;
1352 }
1353 
ld_read_json(struct io_conn * conn,struct plugin * plugin)1354 static struct io_plan *ld_read_json(struct io_conn *conn,
1355 				    struct plugin *plugin)
1356 {
1357 	plugin->used += plugin->len_read;
1358 	if (plugin->used && plugin->used == tal_count(plugin->buffer))
1359 		tal_resize(&plugin->buffer, plugin->used * 2);
1360 
1361 	/* Read and process all messages from the connection */
1362 	while (ld_read_json_one(plugin))
1363 		;
1364 
1365 	/* Now read more from the connection */
1366 	return io_read_partial(plugin->stdin_conn,
1367 			       plugin->buffer + plugin->used,
1368 			       tal_count(plugin->buffer) - plugin->used,
1369 			       &plugin->len_read, ld_read_json, plugin);
1370 }
1371 
1372 static struct io_plan *ld_write_json(struct io_conn *conn,
1373 				     struct plugin *plugin);
1374 
1375 static struct io_plan *
ld_stream_complete(struct io_conn * conn,struct json_stream * js,struct plugin * plugin)1376 ld_stream_complete(struct io_conn *conn, struct json_stream *js,
1377 		   struct plugin *plugin)
1378 {
1379 	assert(tal_count(plugin->js_arr) > 0);
1380 	/* Remove js and shift all remainig over */
1381 	tal_arr_remove(&plugin->js_arr, 0);
1382 
1383 	/* It got dropped off the queue, free it. */
1384 	tal_free(js);
1385 
1386 	return ld_write_json(conn, plugin);
1387 }
1388 
ld_write_json(struct io_conn * conn,struct plugin * plugin)1389 static struct io_plan *ld_write_json(struct io_conn *conn,
1390 				     struct plugin *plugin)
1391 {
1392 	if (tal_count(plugin->js_arr) > 0)
1393 		return json_stream_output(plugin->js_arr[0], plugin->stdout_conn,
1394 					  ld_stream_complete, plugin);
1395 
1396 	/* If we were simply flushing final output, stop now. */
1397 	if (plugin->exiting)
1398 		io_break(plugin);
1399 	return io_out_wait(conn, plugin, ld_write_json, plugin);
1400 }
1401 
ld_conn_finish(struct io_conn * conn,struct plugin * plugin)1402 static void ld_conn_finish(struct io_conn *conn, struct plugin *plugin)
1403 {
1404 	/* Without one of the conns there is no reason to stay alive. That
1405 	 * certainly means lightningd died, since there is no cleaner way
1406 	 * to stop, return 0. */
1407 	exit(0);
1408 }
1409 
1410 /* lightningd writes on our stdin */
stdin_conn_init(struct io_conn * conn,struct plugin * plugin)1411 static struct io_plan *stdin_conn_init(struct io_conn *conn,
1412 				       struct plugin *plugin)
1413 {
1414 	plugin->stdin_conn = conn;
1415 	io_set_finish(conn, ld_conn_finish, plugin);
1416 	return io_read_partial(plugin->stdin_conn, plugin->buffer,
1417 			       tal_bytelen(plugin->buffer), &plugin->len_read,
1418 			       ld_read_json, plugin);
1419 }
1420 
1421 /* lightningd reads from our stdout */
stdout_conn_init(struct io_conn * conn,struct plugin * plugin)1422 static struct io_plan *stdout_conn_init(struct io_conn *conn,
1423                                         struct plugin *plugin)
1424 {
1425 	plugin->stdout_conn = conn;
1426 	io_set_finish(conn, ld_conn_finish, plugin);
1427 	return io_wait(plugin->stdout_conn, plugin, ld_write_json, plugin);
1428 }
1429 
new_plugin(const tal_t * ctx,const char * (* init)(struct plugin * p,const char * buf,const jsmntok_t *),const enum plugin_restartability restartability,bool init_rpc,struct feature_set * features STEALS,const struct plugin_command * commands TAKES,size_t num_commands,const struct plugin_notification * notif_subs TAKES,size_t num_notif_subs,const struct plugin_hook * hook_subs TAKES,size_t num_hook_subs,const char ** notif_topics TAKES,size_t num_notif_topics,va_list ap)1430 static struct plugin *new_plugin(const tal_t *ctx,
1431 				 const char *(*init)(struct plugin *p,
1432 						     const char *buf,
1433 						     const jsmntok_t *),
1434 				 const enum plugin_restartability restartability,
1435 				 bool init_rpc,
1436 				 struct feature_set *features STEALS,
1437 				 const struct plugin_command *commands TAKES,
1438 				 size_t num_commands,
1439 				 const struct plugin_notification *notif_subs TAKES,
1440 				 size_t num_notif_subs,
1441 				 const struct plugin_hook *hook_subs TAKES,
1442 				 size_t num_hook_subs,
1443 				 const char **notif_topics TAKES,
1444 				 size_t num_notif_topics,
1445 				 va_list ap)
1446 {
1447 	const char *optname;
1448 	struct plugin *p = tal(ctx, struct plugin);
1449 
1450 	p->buffer = tal_arr(p, char, 64);
1451 	p->js_arr = tal_arr(p, struct json_stream *, 0);
1452 	p->used = 0;
1453 	p->len_read = 0;
1454 	jsmn_init(&p->parser);
1455 	p->toks = toks_alloc(p);
1456 	/* Async RPC */
1457 	p->rpc_buffer = tal_arr(p, char, 64);
1458 	p->rpc_js_arr = tal_arr(p, struct json_stream *, 0);
1459 	p->rpc_used = 0;
1460 	p->rpc_len_read = 0;
1461 	jsmn_init(&p->rpc_parser);
1462 	p->rpc_toks = toks_alloc(p);
1463 	p->next_outreq_id = 0;
1464 	uintmap_init(&p->out_reqs);
1465 
1466 	p->our_features = tal_steal(p, features);
1467 	if (init_rpc) {
1468 		/* Sync RPC FIXME: maybe go full async ? */
1469 		p->rpc_conn = tal(p, struct rpc_conn);
1470 	} else {
1471 		p->rpc_conn = NULL;
1472 	}
1473 
1474 	p->init = init;
1475 	p->manifested = p->initialized = p->exiting = false;
1476 	p->restartability = restartability;
1477 	strmap_init(&p->usagemap);
1478 	p->in_timer = 0;
1479 
1480 	p->commands = commands;
1481 	if (taken(commands))
1482 		tal_steal(p, commands);
1483 	p->num_commands = num_commands;
1484 	p->notif_topics = notif_topics;
1485 	if (taken(notif_topics))
1486 		tal_steal(p, notif_topics);
1487 	p->num_notif_topics = num_notif_topics;
1488 	p->notif_subs = notif_subs;
1489 	if (taken(notif_subs))
1490 		tal_steal(p, notif_subs);
1491 	p->num_notif_subs = num_notif_subs;
1492 	p->hook_subs = hook_subs;
1493 	if (taken(hook_subs))
1494 		tal_steal(p, hook_subs);
1495 	p->num_hook_subs = num_hook_subs;
1496 	p->opts = tal_arr(p, struct plugin_option, 0);
1497 
1498 	while ((optname = va_arg(ap, const char *)) != NULL) {
1499 		struct plugin_option o;
1500 		o.name = optname;
1501 		o.type = va_arg(ap, const char *);
1502 		o.description = va_arg(ap, const char *);
1503 		o.handle = va_arg(ap, char *(*)(const char *str, void *arg));
1504 		o.arg = va_arg(ap, void *);
1505 		o.deprecated = va_arg(ap, int); /* bool gets promoted! */
1506 		tal_arr_expand(&p->opts, o);
1507 	}
1508 
1509 #if DEVELOPER
1510 	p->mark_mem = NULL;
1511 #endif
1512 	return p;
1513 }
1514 
plugin_main(char * argv[],const char * (* init)(struct plugin * p,const char * buf,const jsmntok_t *),const enum plugin_restartability restartability,bool init_rpc,struct feature_set * features STEALS,const struct plugin_command * commands TAKES,size_t num_commands,const struct plugin_notification * notif_subs TAKES,size_t num_notif_subs,const struct plugin_hook * hook_subs TAKES,size_t num_hook_subs,const char ** notif_topics TAKES,size_t num_notif_topics,...)1515 void plugin_main(char *argv[],
1516 		 const char *(*init)(struct plugin *p,
1517 				     const char *buf, const jsmntok_t *),
1518 		 const enum plugin_restartability restartability,
1519 		 bool init_rpc,
1520 		 struct feature_set *features STEALS,
1521 		 const struct plugin_command *commands TAKES,
1522 		 size_t num_commands,
1523 		 const struct plugin_notification *notif_subs TAKES,
1524 		 size_t num_notif_subs,
1525 		 const struct plugin_hook *hook_subs TAKES,
1526 		 size_t num_hook_subs,
1527 		 const char **notif_topics TAKES,
1528 		 size_t num_notif_topics,
1529 		 ...)
1530 {
1531 	struct plugin *plugin;
1532 	va_list ap;
1533 
1534 	setup_locale();
1535 
1536 	daemon_maybe_debug(argv);
1537 
1538 	/* Note this already prints to stderr, which is enough for now */
1539 	daemon_setup(argv[0], NULL, NULL);
1540 
1541 	va_start(ap, num_notif_topics);
1542 	plugin = new_plugin(NULL, init, restartability, init_rpc, features, commands,
1543 			    num_commands, notif_subs, num_notif_subs, hook_subs,
1544 			    num_hook_subs, notif_topics, num_notif_topics, ap);
1545 	va_end(ap);
1546 	setup_command_usage(plugin);
1547 
1548 	timers_init(&plugin->timers, time_mono());
1549 
1550 	io_new_conn(plugin, STDIN_FILENO, stdin_conn_init, plugin);
1551 	io_new_conn(plugin, STDOUT_FILENO, stdout_conn_init, plugin);
1552 
1553 	for (;;) {
1554 		struct timer *expired = NULL;
1555 
1556 		clean_tmpctx();
1557 
1558 		/* Will only exit if a timer has expired. */
1559 		io_loop(&plugin->timers, &expired);
1560 		call_plugin_timer(plugin, expired);
1561 	}
1562 
1563 	tal_free(plugin);
1564 }
1565 
json_to_listpeers_channel(const tal_t * ctx,const char * buffer,const jsmntok_t * tok)1566 static struct listpeers_channel *json_to_listpeers_channel(const tal_t *ctx,
1567 							   const char *buffer,
1568 							   const jsmntok_t *tok)
1569 {
1570 	struct listpeers_channel *chan;
1571 	const jsmntok_t *privtok = json_get_member(buffer, tok, "private"),
1572 			*statetok = json_get_member(buffer, tok, "state"),
1573 			*ftxidtok =
1574 			    json_get_member(buffer, tok, "funding_txid"),
1575 			*scidtok =
1576 			    json_get_member(buffer, tok, "short_channel_id"),
1577 			*dirtok = json_get_member(buffer, tok, "direction"),
1578 			*tmsattok =
1579 			    json_get_member(buffer, tok, "total_msat"),
1580 			*smsattok =
1581 			    json_get_member(buffer, tok, "spendable_msat");
1582 
1583 	if (privtok == NULL || privtok->type != JSMN_PRIMITIVE ||
1584 	    statetok == NULL || statetok->type != JSMN_STRING ||
1585 	    ftxidtok == NULL || ftxidtok->type != JSMN_STRING ||
1586 	    (scidtok != NULL && scidtok->type != JSMN_STRING) ||
1587 	    (dirtok != NULL && dirtok->type != JSMN_PRIMITIVE) ||
1588 	    tmsattok == NULL || tmsattok->type != JSMN_STRING ||
1589 	    smsattok == NULL || smsattok->type != JSMN_STRING)
1590 		return NULL;
1591 
1592 	chan = tal(ctx, struct listpeers_channel);
1593 
1594 	json_to_bool(buffer, privtok, &chan->private);
1595 	chan->state = json_strdup(chan, buffer, statetok);
1596 	json_to_txid(buffer, ftxidtok, &chan->funding_txid);
1597 	if (scidtok != NULL) {
1598 		assert(dirtok != NULL);
1599 		chan->scid = tal(chan, struct short_channel_id);
1600 		chan->direction = tal(chan, int);
1601 		json_to_short_channel_id(buffer, scidtok, chan->scid);
1602 		json_to_int(buffer, dirtok, chan->direction);
1603 	}else {
1604 		assert(dirtok == NULL);
1605 		chan->scid = NULL;
1606 		chan->direction = NULL;
1607 	}
1608 
1609 	json_to_msat(buffer, tmsattok, &chan->total_msat);
1610 	json_to_msat(buffer, smsattok, &chan->spendable_msat);
1611 
1612 	return chan;
1613 }
1614 
json_to_listpeers_peer(const tal_t * ctx,const char * buffer,const jsmntok_t * tok)1615 static struct listpeers_peer *json_to_listpeers_peer(const tal_t *ctx,
1616 						  const char *buffer,
1617 						  const jsmntok_t *tok)
1618 {
1619 	struct listpeers_peer *res;
1620 	size_t i;
1621 	const jsmntok_t *iter;
1622 	const jsmntok_t *idtok = json_get_member(buffer, tok, "id"),
1623 			*conntok = json_get_member(buffer, tok, "connected"),
1624 			*netaddrtok = json_get_member(buffer, tok, "netaddr"),
1625 			*channelstok = json_get_member(buffer, tok, "channels");
1626 
1627 	/* Preliminary sanity checks. */
1628 	if (idtok == NULL || idtok->type != JSMN_STRING || conntok == NULL ||
1629 	    conntok->type != JSMN_PRIMITIVE ||
1630 	    (netaddrtok != NULL && netaddrtok->type != JSMN_ARRAY) ||
1631 	    channelstok == NULL || channelstok->type != JSMN_ARRAY)
1632 		return NULL;
1633 
1634 	res = tal(ctx, struct listpeers_peer);
1635 	json_to_node_id(buffer, idtok, &res->id);
1636 	json_to_bool(buffer, conntok, &res->connected);
1637 
1638 	res->netaddr = tal_arr(res, const char *, 0);
1639 	if (netaddrtok != NULL) {
1640 		json_for_each_arr(i, iter, netaddrtok) {
1641 			tal_arr_expand(&res->netaddr,
1642 				       json_strdup(res, buffer, iter));
1643 		}
1644 	}
1645 
1646 	res->channels = tal_arr(res, struct listpeers_channel *, 0);
1647 	json_for_each_arr(i, iter, channelstok) {
1648 		struct listpeers_channel *chan = json_to_listpeers_channel(res, buffer, iter);
1649 		assert(chan != NULL);
1650 		tal_arr_expand(&res->channels, chan);
1651 	}
1652 
1653 	return res;
1654 }
1655 
json_to_listpeers_result(const tal_t * ctx,const char * buffer,const jsmntok_t * toks)1656 struct listpeers_result *json_to_listpeers_result(const tal_t *ctx,
1657 							  const char *buffer,
1658 							  const jsmntok_t *toks)
1659 {
1660 	size_t i;
1661 	const jsmntok_t *iter;
1662 	struct listpeers_result *res;
1663 	const jsmntok_t *peerstok = json_get_member(buffer, toks, "peers");
1664 
1665 	if (peerstok == NULL || peerstok->type != JSMN_ARRAY)
1666 		return NULL;
1667 
1668 	res = tal(ctx, struct listpeers_result);
1669 	res->peers = tal_arr(res, struct listpeers_peer *, 0);
1670 
1671 	json_for_each_obj(i, iter, peerstok) {
1672 		struct listpeers_peer *p =
1673 		    json_to_listpeers_peer(res, buffer, iter);
1674 		if (p == NULL)
1675 			return tal_free(res);
1676 		tal_arr_expand(&res->peers, p);
1677 	}
1678 	return res;
1679 }
1680 
json_to_createonion_response(const tal_t * ctx,const char * buffer,const jsmntok_t * toks)1681 struct createonion_response *json_to_createonion_response(const tal_t *ctx,
1682 							  const char *buffer,
1683 							  const jsmntok_t *toks)
1684 {
1685 	size_t i;
1686 	struct createonion_response *resp;
1687 	const jsmntok_t *oniontok = json_get_member(buffer, toks, "onion");
1688 	const jsmntok_t *secretstok = json_get_member(buffer, toks, "shared_secrets");
1689 	const jsmntok_t *cursectok;
1690 
1691 	if (oniontok == NULL || secretstok == NULL)
1692 		return NULL;
1693 
1694 	resp = tal(ctx, struct createonion_response);
1695 
1696 	if (oniontok->type != JSMN_STRING)
1697 		goto fail;
1698 
1699 	resp->onion = json_tok_bin_from_hex(resp, buffer, oniontok);
1700 	resp->shared_secrets = tal_arr(resp, struct secret, secretstok->size);
1701 
1702 	json_for_each_arr(i, cursectok, secretstok) {
1703 		if (cursectok->type != JSMN_STRING)
1704 			goto fail;
1705 		json_to_secret(buffer, cursectok, &resp->shared_secrets[i]);
1706 	}
1707 	return resp;
1708 
1709 fail:
1710 	return tal_free(resp);
1711 }
1712 
json_to_route_hop_inplace(struct route_hop * dst,const char * buffer,const jsmntok_t * toks)1713 static bool json_to_route_hop_inplace(struct route_hop *dst, const char *buffer,
1714 				      const jsmntok_t *toks)
1715 {
1716 	const jsmntok_t *idtok = json_get_member(buffer, toks, "id");
1717 	const jsmntok_t *channeltok = json_get_member(buffer, toks, "channel");
1718 	const jsmntok_t *directiontok = json_get_member(buffer, toks, "direction");
1719 	const jsmntok_t *amounttok = json_get_member(buffer, toks, "amount_msat");
1720 	const jsmntok_t *delaytok = json_get_member(buffer, toks, "delay");
1721 	const jsmntok_t *styletok = json_get_member(buffer, toks, "style");
1722 
1723 	if (idtok == NULL || channeltok == NULL || directiontok == NULL ||
1724 	    amounttok == NULL || delaytok == NULL || styletok == NULL)
1725 		return false;
1726 
1727 	json_to_node_id(buffer, idtok, &dst->node_id);
1728 	json_to_short_channel_id(buffer, channeltok, &dst->scid);
1729 	json_to_int(buffer, directiontok, &dst->direction);
1730 	json_to_msat(buffer, amounttok, &dst->amount);
1731 	json_to_number(buffer, delaytok, &dst->delay);
1732 	dst->style = json_tok_streq(buffer, styletok, "legacy")
1733 			 ? ROUTE_HOP_LEGACY
1734 			 : ROUTE_HOP_TLV;
1735 	return true;
1736 }
1737 
json_to_route(const tal_t * ctx,const char * buffer,const jsmntok_t * toks)1738 struct route_hop *json_to_route(const tal_t *ctx, const char *buffer,
1739 				const jsmntok_t *toks)
1740 {
1741 	size_t num = toks->size, i;
1742 	struct route_hop *hops;
1743 	const jsmntok_t *rtok;
1744 	if (toks->type != JSMN_ARRAY)
1745 		return NULL;
1746 
1747 	hops = tal_arr(ctx, struct route_hop, num);
1748 	json_for_each_arr(i, rtok, toks) {
1749 		if (!json_to_route_hop_inplace(&hops[i], buffer, rtok))
1750 			return tal_free(hops);
1751 	}
1752 	return hops;
1753 }
1754 
1755 struct command_result *WARN_UNUSED_RESULT
command_hook_success(struct command * cmd)1756 command_hook_success(struct command *cmd)
1757 {
1758 	struct json_stream *response = jsonrpc_stream_success(cmd);
1759 	json_add_string(response, "result", "continue");
1760 	return command_finished(cmd, response);
1761 }
1762 
1763 struct command_result *WARN_UNUSED_RESULT
notification_handled(struct command * cmd)1764 notification_handled(struct command *cmd)
1765 {
1766 	tal_free(cmd);
1767 	return &complete;
1768 }
1769