forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.c
2126 lines (1825 loc) · 59.5 KB
/
plugin.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "config.h"
#include <ccan/array_size/array_size.h>
#include <ccan/ccan/tal/grab_file/grab_file.h>
#include <ccan/crc32c/crc32c.h>
#include <ccan/io/io.h>
#include <ccan/mem/mem.h>
#include <ccan/opt/opt.h>
#include <ccan/pipecmd/pipecmd.h>
#include <ccan/tal/path/path.h>
#include <ccan/tal/str/str.h>
#include <ccan/utf8/utf8.h>
#include <common/configdir.h>
#include <common/features.h>
#include <common/json_command.h>
#include <common/json_helpers.h>
#include <common/memleak.h>
#include <common/timeout.h>
#include <common/version.h>
#include <dirent.h>
#include <errno.h>
#include <lightningd/io_loop_with_timers.h>
#include <lightningd/notification.h>
#include <lightningd/plugin.h>
#include <lightningd/plugin_control.h>
#include <lightningd/plugin_hook.h>
#include <sys/stat.h>
/* Only this file can include this generated header! */
# include <plugins/list_of_builtin_plugins_gen.h>
/* How many seconds may the plugin take to reply to the `getmanifest`
* call? This is the maximum delay to `lightningd --help` and until
* we can start the main `io_loop` to communicate with peers. If this
* hangs we can't do much, so we put an upper bound on the time we're
* willing to wait. Plugins shouldn't do any initialization in the
* `getmanifest` call anyway, that's what `init` is for. */
#define PLUGIN_MANIFEST_TIMEOUT 60
/* A simple struct associating an incoming RPC method call with the plugin
* that is handling it and the downstream jsonrpc_request. */
struct plugin_rpccall {
struct list_node list;
struct command *cmd;
struct plugin *plugin;
struct jsonrpc_request *request;
};
#if DEVELOPER
static void memleak_help_pending_requests(struct htable *memtable,
struct plugins *plugins)
{
memleak_remove_uintmap(memtable, &plugins->pending_requests);
}
#endif /* DEVELOPER */
static const char *state_desc(const struct plugin *plugin)
{
switch (plugin->plugin_state) {
case UNCONFIGURED:
return "unconfigured";
case AWAITING_GETMANIFEST_RESPONSE:
return "before replying to getmanifest";
case NEEDS_INIT:
return "before we sent init";
case AWAITING_INIT_RESPONSE:
return "before replying to init";
case INIT_COMPLETE:
return "during normal operation";
}
fatal("Invalid plugin state %i for %s",
plugin->plugin_state, plugin->cmd);
}
struct plugins *plugins_new(const tal_t *ctx, struct log_book *log_book,
struct lightningd *ld)
{
struct plugins *p;
p = tal(ctx, struct plugins);
list_head_init(&p->plugins);
p->log_book = log_book;
p->log = new_log(p, log_book, NULL, "plugin-manager");
p->ld = ld;
p->startup = true;
p->plugin_cmds = tal_arr(p, struct plugin_command *, 0);
p->blacklist = tal_arr(p, const char *, 0);
p->plugin_idx = 0;
#if DEVELOPER
p->dev_builtin_plugins_unimportant = false;
#endif /* DEVELOPER */
uintmap_init(&p->pending_requests);
memleak_add_helper(p, memleak_help_pending_requests);
return p;
}
/* Check that all the plugin's subscriptions are actually for known
* notification topics. Emit a warning if that's not the case, but
* don't kill the plugin. */
static void plugin_check_subscriptions(struct plugins *plugins,
struct plugin *plugin)
{
for (size_t i = 0; i < tal_count(plugin->subscriptions); i++) {
const char *topic = plugin->subscriptions[i];
if (!notifications_have_topic(plugins, topic))
log_unusual(
plugin->log,
"topic '%s' is not a known notification topic",
topic);
}
}
static bool plugins_any_in_state(const struct plugins *plugins,
enum plugin_state state)
{
const struct plugin *p;
list_for_each(&plugins->plugins, p, list) {
if (p->plugin_state == state)
return true;
}
return false;
}
static bool plugins_all_in_state(const struct plugins *plugins,
enum plugin_state state)
{
const struct plugin *p;
list_for_each(&plugins->plugins, p, list) {
if (p->plugin_state != state)
return false;
}
return true;
}
/* Once they've all replied with their manifests, we can order them. */
static void check_plugins_manifests(struct plugins *plugins)
{
struct plugin *plugin;
struct plugin **depfail;
if (plugins_any_in_state(plugins, AWAITING_GETMANIFEST_RESPONSE))
return;
/* Now things are settled, try to order hooks. */
depfail = plugin_hooks_make_ordered(tmpctx);
for (size_t i = 0; i < tal_count(depfail); i++) {
/* Only complain and free plugins! */
if (depfail[i]->plugin_state != NEEDS_INIT)
continue;
plugin_kill(depfail[i], LOG_UNUSUAL,
"Cannot meet required hook dependencies");
}
/* Check that all the subscriptions are matched with real
* topics. */
list_for_each(&plugins->plugins, plugin, list) {
plugin_check_subscriptions(plugin->plugins, plugin);
}
/* As startup, we break out once all getmanifest are returned */
if (plugins->startup)
io_break(plugins);
else
/* Otherwise we go straight into configuring them */
plugins_config(plugins);
}
static void check_plugins_initted(struct plugins *plugins)
{
struct plugin_command **plugin_cmds;
if (!plugins_all_in_state(plugins, INIT_COMPLETE))
return;
/* Clear commands first, in case callbacks add new ones.
* Paranoia, but wouldn't that be a nasty bug to find? */
plugin_cmds = plugins->plugin_cmds;
plugins->plugin_cmds = tal_arr(plugins, struct plugin_command *, 0);
for (size_t i = 0; i < tal_count(plugin_cmds); i++)
plugin_cmd_all_complete(plugins, plugin_cmds[i]);
tal_free(plugin_cmds);
}
struct command_result *plugin_register_all_complete(struct lightningd *ld,
struct plugin_command *pcmd)
{
if (plugins_all_in_state(ld->plugins, INIT_COMPLETE))
return plugin_cmd_all_complete(ld->plugins, pcmd);
tal_arr_expand(&ld->plugins->plugin_cmds, pcmd);
return NULL;
}
static void destroy_plugin(struct plugin *p)
{
struct plugin_rpccall *call;
list_del(&p->list);
/* Terminate all pending RPC calls with an error. */
list_for_each(&p->pending_rpccalls, call, list) {
was_pending(command_fail(
call->cmd, PLUGIN_TERMINATED,
"Plugin terminated before replying to RPC call."));
}
/* Reset, so calls below don't try to fail it again! */
list_head_init(&p->pending_rpccalls);
/* If this was last one manifests were waiting for, handle deps */
if (p->plugin_state == AWAITING_GETMANIFEST_RESPONSE)
check_plugins_manifests(p->plugins);
/* Daemon shutdown overrules plugin's importance; aborts init checks */
if (p->plugins->ld->state == LD_STATE_SHUTDOWN) {
/* But return if this was the last plugin! */
if (list_empty(&p->plugins->plugins))
io_break(destroy_plugin);
return;
}
/* If this was the last one init was waiting for, handle cmd replies */
if (p->plugin_state == AWAITING_INIT_RESPONSE)
check_plugins_initted(p->plugins);
/* Now check if the dying plugin is important. */
if (p->important) {
log_broken(p->log,
"Plugin marked as important, "
"shutting down lightningd!");
lightningd_exit(p->plugins->ld, 1);
}
}
static u32 file_checksum(struct lightningd *ld, const char *path)
{
char *content;
if (IFDEV(ld->dev_no_plugin_checksum, false))
return 0;
content = grab_file(tmpctx, path);
if (content == NULL) return 0;
return crc32c(0, content, tal_count(content));
}
struct plugin *plugin_register(struct plugins *plugins, const char* path TAKES,
struct plugin_command *start_cmd, bool important,
const char *parambuf STEALS,
const jsmntok_t *params STEALS)
{
struct plugin *p, *p_temp;
u32 chksum;
/* Don't register an already registered plugin */
list_for_each(&plugins->plugins, p_temp, list) {
if (streq(path, p_temp->cmd)) {
/* If added as "important", upgrade to "important". */
if (important)
p_temp->important = true;
/* stop and restart plugin on different checksum */
chksum = file_checksum(plugins->ld, path);
if (p_temp->checksum != chksum && !p_temp->important) {
plugin_kill(p_temp, LOG_INFORM,
"Plugin changed, needs restart.");
break;
}
if (taken(path))
tal_free(path);
return NULL;
}
}
p = tal(plugins, struct plugin);
p->plugins = plugins;
p->cmd = tal_strdup(p, path);
p->checksum = file_checksum(plugins->ld, p->cmd);
p->shortname = path_basename(p, p->cmd);
p->start_cmd = start_cmd;
p->plugin_state = UNCONFIGURED;
p->js_arr = tal_arr(p, struct json_stream *, 0);
p->used = 0;
p->notification_topics = tal_arr(p, const char *, 0);
p->subscriptions = NULL;
p->dynamic = false;
p->index = plugins->plugin_idx++;
p->log = new_log(p, plugins->log_book, NULL, "plugin-%s", p->shortname);
p->methods = tal_arr(p, const char *, 0);
list_head_init(&p->plugin_opts);
list_add_tail(&plugins->plugins, &p->list);
tal_add_destructor(p, destroy_plugin);
list_head_init(&p->pending_rpccalls);
p->important = important;
p->parambuf = tal_steal(p, parambuf);
p->params = tal_steal(p, params);
return p;
}
bool plugin_paths_match(const char *cmd, const char *name)
{
if (strchr(name, PATH_SEP)) {
const char *cmd_canon, *name_canon;
if (streq(cmd, name))
return true;
/* These return NULL path doesn't exist */
cmd_canon = path_canon(tmpctx, cmd);
name_canon = path_canon(tmpctx, name);
return cmd_canon && name_canon && streq(name_canon, cmd_canon);
} else {
/* No path separator means a basename match. */
const char *base = path_basename(tmpctx, cmd);
return streq(base, name);
}
}
void plugin_blacklist(struct plugins *plugins, const char *name)
{
struct plugin *p, *next;
log_debug(plugins->log, "blacklist for %s", name);
list_for_each_safe(&plugins->plugins, p, next, list) {
if (plugin_paths_match(p->cmd, name)) {
log_info(plugins->log, "%s: disabled via disable-plugin",
p->cmd);
list_del_from(&plugins->plugins, &p->list);
/* disable-plugin overrides important-plugin. */
p->important = false;
tal_free(p);
}
}
tal_arr_expand(&plugins->blacklist,
tal_strdup(plugins->blacklist, name));
}
bool plugin_blacklisted(struct plugins *plugins, const char *name)
{
for (size_t i = 0; i < tal_count(plugins->blacklist); i++)
if (plugin_paths_match(name, plugins->blacklist[i]))
return true;
return false;
}
void plugin_kill(struct plugin *plugin, enum log_level loglevel,
const char *fmt, ...)
{
va_list ap;
const char *msg;
va_start(ap, fmt);
msg = tal_vfmt(tmpctx, fmt, ap);
va_end(ap);
log_(plugin->log, loglevel,
NULL, loglevel >= LOG_UNUSUAL,
"Killing plugin: %s", msg);
kill(plugin->pid, SIGKILL);
if (plugin->start_cmd) {
plugin_cmd_killed(plugin->start_cmd, plugin, msg);
plugin->start_cmd = NULL;
}
/* Don't come back when we free stdout_conn! */
io_set_finish(plugin->stdout_conn, NULL, NULL);
tal_free(plugin);
}
/**
* Send a JSON-RPC message (request or notification) to the plugin.
*/
static void plugin_send(struct plugin *plugin, struct json_stream *stream)
{
tal_steal(plugin->js_arr, stream);
tal_arr_expand(&plugin->js_arr, stream);
io_wake(plugin);
}
/* Returns the error string, or NULL */
static const char *plugin_log_handle(struct plugin *plugin,
const jsmntok_t *paramstok)
WARN_UNUSED_RESULT;
static const char *plugin_log_handle(struct plugin *plugin,
const jsmntok_t *paramstok)
{
const jsmntok_t *msgtok, *leveltok;
enum log_level level;
bool call_notifier;
msgtok = json_get_member(plugin->buffer, paramstok, "message");
leveltok = json_get_member(plugin->buffer, paramstok, "level");
if (!msgtok || msgtok->type != JSMN_STRING) {
return tal_fmt(plugin, "Log notification from plugin doesn't have "
"a string \"message\" field");
}
if (!leveltok)
level = LOG_INFORM;
else if (!log_level_parse(plugin->buffer + leveltok->start,
leveltok->end - leveltok->start,
&level)
/* FIXME: Allow io logging? */
|| level == LOG_IO_IN
|| level == LOG_IO_OUT) {
return tal_fmt(plugin,
"Unknown log-level %.*s, valid values are "
"\"debug\", \"info\", \"warn\", or \"error\".",
json_tok_full_len(leveltok),
json_tok_full(plugin->buffer, leveltok));
}
call_notifier = (level == LOG_BROKEN || level == LOG_UNUSUAL)? true : false;
/* FIXME: Let plugin specify node_id? */
log_(plugin->log, level, NULL, call_notifier, "%.*s", msgtok->end - msgtok->start,
plugin->buffer + msgtok->start);
return NULL;
}
static const char *plugin_notify_handle(struct plugin *plugin,
const jsmntok_t *methodtok,
const jsmntok_t *paramstok)
{
const jsmntok_t *idtok;
u64 id;
struct jsonrpc_request *request;
/* id inside params tells us which id to redirect to. */
idtok = json_get_member(plugin->buffer, paramstok, "id");
if (!idtok || !json_to_u64(plugin->buffer, idtok, &id)) {
return tal_fmt(plugin,
"JSON-RPC notify \"id\"-field is not a u64");
}
request = uintmap_get(&plugin->plugins->pending_requests, id);
if (!request) {
return tal_fmt(
plugin,
"Received a JSON-RPC notify for non-existent request");
}
/* Ignore if they don't have a callback */
if (request->notify_cb)
request->notify_cb(plugin->buffer, methodtok, paramstok, idtok,
request->response_cb_arg);
return NULL;
}
/* Check if the plugin is allowed to send a notification of the
* specified topic, i.e., whether the plugin has announced the topic
* correctly in its manifest. */
static bool plugin_notification_allowed(const struct plugin *plugin, const char *topic)
{
for (size_t i=0; i<tal_count(plugin->notification_topics); i++)
if (streq(plugin->notification_topics[i], topic))
return true;
return false;
}
/* Returns the error string, or NULL */
static const char *plugin_notification_handle(struct plugin *plugin,
const jsmntok_t *toks)
WARN_UNUSED_RESULT;
static const char *plugin_notification_handle(struct plugin *plugin,
const jsmntok_t *toks)
{
const jsmntok_t *methtok, *paramstok;
const char *methname;
struct jsonrpc_notification *n;
methtok = json_get_member(plugin->buffer, toks, "method");
paramstok = json_get_member(plugin->buffer, toks, "params");
if (!methtok || !paramstok) {
return tal_fmt(plugin,
"Malformed JSON-RPC notification missing "
"\"method\" or \"params\": %.*s",
toks->end - toks->start,
plugin->buffer + toks->start);
}
/* Dispatch incoming notifications. This is currently limited
* to just a few method types, should this ever become
* unwieldy we can switch to the AUTODATA construction to
* register notification handlers in a variety of places. */
if (json_tok_streq(plugin->buffer, methtok, "log")) {
return plugin_log_handle(plugin, paramstok);
} else if (json_tok_streq(plugin->buffer, methtok, "message")
|| json_tok_streq(plugin->buffer, methtok, "progress")) {
return plugin_notify_handle(plugin, methtok, paramstok);
}
methname = json_strdup(tmpctx, plugin->buffer, methtok);
if (!plugin_notification_allowed(plugin, methname)) {
log_unusual(plugin->log,
"Plugin attempted to send a notification to topic "
"\"%s\" it hasn't declared in its manifest, not "
"forwarding to subscribers.",
methname);
} else if (notifications_have_topic(plugin->plugins, methname)) {
n = jsonrpc_notification_start(NULL, methname);
json_add_string(n->stream, "origin", plugin->shortname);
json_add_tok(n->stream, "payload", paramstok, plugin->buffer);
jsonrpc_notification_end(n);
plugins_notify(plugin->plugins, take(n));
}
return NULL;
}
struct plugin_destroyed {
const struct plugin *plugin;
};
static void mark_plugin_destroyed(const struct plugin *unused,
struct plugin_destroyed *pd)
{
pd->plugin = NULL;
}
static struct plugin_destroyed *
plugin_detect_destruction(const struct plugin *plugin)
{
struct plugin_destroyed *pd = tal(NULL, struct plugin_destroyed);
pd->plugin = plugin;
tal_add_destructor2(plugin, mark_plugin_destroyed, pd);
return pd;
}
static bool was_plugin_destroyed(struct plugin_destroyed *pd)
{
if (pd->plugin) {
tal_del_destructor2(pd->plugin, mark_plugin_destroyed, pd);
tal_free(pd);
return false;
}
tal_free(pd);
return true;
}
/* Returns the error string, or NULL */
static const char *plugin_response_handle(struct plugin *plugin,
const jsmntok_t *toks,
const jsmntok_t *idtok)
WARN_UNUSED_RESULT;
static const char *plugin_response_handle(struct plugin *plugin,
const jsmntok_t *toks,
const jsmntok_t *idtok)
{
struct plugin_destroyed *pd;
struct jsonrpc_request *request;
u64 id;
/* We only send u64 ids, so if this fails it's a critical error (note
* that this also works if id is inside a JSON string!). */
if (!json_to_u64(plugin->buffer, idtok, &id)) {
return tal_fmt(plugin,
"JSON-RPC response \"id\"-field is not a u64");
}
request = uintmap_get(&plugin->plugins->pending_requests, id);
if (!request) {
return tal_fmt(
plugin,
"Received a JSON-RPC response for non-existent request");
}
/* Ignore responses when shutting down */
if (plugin->plugins->ld->state == LD_STATE_SHUTDOWN) {
return NULL;
}
/* We expect the request->cb to copy if needed */
pd = plugin_detect_destruction(plugin);
request->response_cb(plugin->buffer, toks, idtok, request->response_cb_arg);
/* Note that in the case of 'plugin stop' this can free request (since
* plugin is parent), so detect that case */
if (!was_plugin_destroyed(pd))
tal_free(request);
return NULL;
}
/**
* Try to parse a complete message from the plugin's buffer.
*
* Returns NULL if there was no error.
* If it can parse a JSON message, sets *@complete, and returns any error
* from the callback.
*
* If @destroyed was set, it means the plugin called plugin stop on itself.
*/
static const char *plugin_read_json_one(struct plugin *plugin,
bool *complete,
bool *destroyed)
{
const jsmntok_t *jrtok, *idtok;
struct plugin_destroyed *pd;
const char *err;
*destroyed = false;
/* Note that in the case of 'plugin stop' this can free request (since
* plugin is parent), so detect that case */
if (!json_parse_input(&plugin->parser, &plugin->toks,
plugin->buffer, plugin->used,
complete)) {
return tal_fmt(plugin,
"Failed to parse JSON response '%.*s'",
(int)plugin->used, plugin->buffer);
}
if (!*complete) {
/* We need more. */
return NULL;
}
/* Empty buffer? (eg. just whitespace). */
if (tal_count(plugin->toks) == 1) {
plugin->used = 0;
jsmn_init(&plugin->parser);
toks_reset(plugin->toks);
/* We need more. */
*complete = false;
return NULL;
}
jrtok = json_get_member(plugin->buffer, plugin->toks, "jsonrpc");
idtok = json_get_member(plugin->buffer, plugin->toks, "id");
if (!jrtok) {
return tal_fmt(
plugin,
"JSON-RPC message does not contain \"jsonrpc\" field");
}
pd = plugin_detect_destruction(plugin);
if (!idtok) {
/* A Notification is a Request object without an "id"
* member. A Request object that is a Notification
* signifies the Client's lack of interest in the
* corresponding Response object, and as such no
* Response object needs to be returned to the
* client. The Server MUST NOT reply to a
* Notification, including those that are within a
* batch request.
*
* https://www.jsonrpc.org/specification#notification
*/
err = plugin_notification_handle(plugin, plugin->toks);
} else {
/* When a rpc call is made, the Server MUST reply with
* a Response, except for in the case of
* Notifications. The Response is expressed as a
* single JSON Object, with the following members:
*
* - jsonrpc: A String specifying the version of the
* JSON-RPC protocol. MUST be exactly "2.0".
*
* - result: This member is REQUIRED on success. This
* member MUST NOT exist if there was an error
* invoking the method. The value of this member is
* determined by the method invoked on the Server.
*
* - error: This member is REQUIRED on error. This
* member MUST NOT exist if there was no error
* triggered during invocation.
*
* - id: This member is REQUIRED. It MUST be the same
* as the value of the id member in the Request
* Object. If there was an error in detecting the id
* in the Request object (e.g. Parse error/Invalid
* Request), it MUST be Null. Either the result
* member or error member MUST be included, but both
* members MUST NOT be included.
*
* https://www.jsonrpc.org/specification#response_object
*/
err = plugin_response_handle(plugin, plugin->toks, idtok);
}
/* Corner case: rpc_command hook can destroy plugin for 'plugin
* stop'! */
if (was_plugin_destroyed(pd)) {
*destroyed = true;
} else {
/* Move this object out of the buffer */
memmove(plugin->buffer, plugin->buffer + plugin->toks[0].end,
tal_count(plugin->buffer) - plugin->toks[0].end);
plugin->used -= plugin->toks[0].end;
jsmn_init(&plugin->parser);
toks_reset(plugin->toks);
}
return err;
}
static struct io_plan *plugin_read_json(struct io_conn *conn,
struct plugin *plugin)
{
bool success;
bool have_full;
log_io(plugin->log, LOG_IO_IN, NULL, "",
plugin->buffer + plugin->used, plugin->len_read);
/* Our JSON parser is pretty good at incremental parsing, but
* `getrawblock` gives a giant 2MB token, which forces it to re-parse
* every time until we have all of it. However, we can't complete a
* JSON object without a '}', so we do a cheaper check here.
*/
have_full = memchr(plugin->buffer + plugin->used, '}',
plugin->len_read);
plugin->used += plugin->len_read;
if (plugin->used == tal_count(plugin->buffer))
tal_resize(&plugin->buffer, plugin->used * 2);
/* Read and process all messages from the connection */
if (have_full) {
do {
bool destroyed;
const char *err;
err =
plugin_read_json_one(plugin, &success, &destroyed);
/* If it's destroyed, conn is already freed! */
if (destroyed)
return io_close(NULL);
if (err) {
plugin_kill(plugin, LOG_UNUSUAL,
"%s", err);
/* plugin_kill frees plugin */
return io_close(NULL);
}
} while (success);
}
/* Now read more from the connection */
return io_read_partial(plugin->stdout_conn,
plugin->buffer + plugin->used,
tal_count(plugin->buffer) - plugin->used,
&plugin->len_read, plugin_read_json, plugin);
}
/* Mutual recursion */
static struct io_plan *plugin_write_json(struct io_conn *conn,
struct plugin *plugin);
static struct io_plan *plugin_stream_complete(struct io_conn *conn, struct json_stream *js, struct plugin *plugin)
{
assert(tal_count(plugin->js_arr) > 0);
/* Remove js and shift all remainig over */
tal_arr_remove(&plugin->js_arr, 0);
/* It got dropped off the queue, free it. */
tal_free(js);
return plugin_write_json(conn, plugin);
}
static struct io_plan *plugin_write_json(struct io_conn *conn,
struct plugin *plugin)
{
if (tal_count(plugin->js_arr)) {
return json_stream_output(plugin->js_arr[0], plugin->stdin_conn, plugin_stream_complete, plugin);
}
return io_out_wait(conn, plugin, plugin_write_json, plugin);
}
/* This catches the case where their stdout closes (usually they're dead). */
static void plugin_conn_finish(struct io_conn *conn, struct plugin *plugin)
{
/* This is expected at shutdown of course. */
plugin_kill(plugin,
plugin->plugins->ld->state == LD_STATE_SHUTDOWN
? LOG_DBG : LOG_INFORM,
"exited %s", state_desc(plugin));
}
struct io_plan *plugin_stdin_conn_init(struct io_conn *conn,
struct plugin *plugin)
{
/* We write to their stdin */
/* We don't have anything queued yet, wait for notification */
return io_wait(conn, plugin, plugin_write_json, plugin);
}
struct io_plan *plugin_stdout_conn_init(struct io_conn *conn,
struct plugin *plugin)
{
/* We read from their stdout */
io_set_finish(conn, plugin_conn_finish, plugin);
return io_read_partial(conn, plugin->buffer,
tal_bytelen(plugin->buffer), &plugin->len_read,
plugin_read_json, plugin);
}
/* Returns NULL if invalid value for that type */
static struct plugin_opt_value *plugin_opt_value(const tal_t *ctx,
const char *type,
const char *arg)
{
struct plugin_opt_value *v = tal(ctx, struct plugin_opt_value);
v->as_str = tal_strdup(v, arg);
if (streq(type, "int")) {
long long l;
char *endp;
errno = 0;
l = strtoll(arg, &endp, 0);
if (errno || *endp)
return tal_free(v);
v->as_int = l;
/* Check if the number did not fit in `s64` (in case `long long`
* is a bigger type). */
if (v->as_int != l)
return tal_free(v);
} else if (streq(type, "bool")) {
/* valid values are 'true', 'True', '1', '0', 'false', 'False', or '' */
if (streq(arg, "true") || streq(arg, "True") || streq(arg, "1")) {
v->as_bool = true;
} else if (streq(arg, "false") || streq(arg, "False")
|| streq(arg, "0")) {
v->as_bool = false;
} else
return tal_free(v);
} else if (streq(type, "flag")) {
v->as_bool = true;
}
return v;
}
char *plugin_opt_flag_set(struct plugin_opt *popt)
{
/* A set flag is a true */
tal_free(popt->values);
popt->values = tal_arr(popt, struct plugin_opt_value *, 1);
popt->values[0] = plugin_opt_value(popt->values, popt->type, "true");
return NULL;
}
char *plugin_opt_set(const char *arg, struct plugin_opt *popt)
{
struct plugin_opt_value *v;
/* Warn them that this is deprecated */
if (popt->deprecated && !deprecated_apis)
return tal_fmt(tmpctx, "deprecated option (will be removed!)");
if (!popt->multi) {
tal_free(popt->values);
popt->values = tal_arr(popt, struct plugin_opt_value *, 0);
}
v = plugin_opt_value(popt->values, popt->type, arg);
if (!v)
return tal_fmt(tmpctx, "%s does not parse as type %s",
arg, popt->type);
tal_arr_expand(&popt->values, v);
return NULL;
}
static void destroy_plugin_opt(struct plugin_opt *opt)
{
if (!opt_unregister(opt->name))
fatal("Could not unregister %s", opt->name);
list_del(&opt->list);
}
/* Add a single plugin option to the plugin as well as registering it with the
* command line options. */
static const char *plugin_opt_add(struct plugin *plugin, const char *buffer,
const jsmntok_t *opt)
{
const jsmntok_t *nametok, *typetok, *defaulttok, *desctok, *deptok, *multitok;
struct plugin_opt *popt;
nametok = json_get_member(buffer, opt, "name");
typetok = json_get_member(buffer, opt, "type");
desctok = json_get_member(buffer, opt, "description");
defaulttok = json_get_member(buffer, opt, "default");
deptok = json_get_member(buffer, opt, "deprecated");
multitok = json_get_member(buffer, opt, "multi");
if (!typetok || !nametok || !desctok) {
return tal_fmt(plugin,
"An option is missing either \"name\", \"description\" or \"type\"");
}
popt = tal(plugin, struct plugin_opt);
popt->values = tal_arr(popt, struct plugin_opt_value *, 0);
popt->name = tal_fmt(popt, "--%.*s", nametok->end - nametok->start,
buffer + nametok->start);
popt->description = NULL;
if (deptok) {
if (!json_to_bool(buffer, deptok, &popt->deprecated))
return tal_fmt(plugin,
"%s: invalid \"deprecated\" field %.*s",
popt->name,
deptok->end - deptok->start,
buffer + deptok->start);
} else
popt->deprecated = false;
if (multitok) {
if (!json_to_bool(buffer, multitok, &popt->multi))
return tal_fmt(plugin,
"%s: invalid \"multi\" field %.*s",
popt->name,
multitok->end - multitok->start,
buffer + multitok->start);
} else
popt->multi = false;
popt->def = NULL;
if (json_tok_streq(buffer, typetok, "string")) {
popt->type = "string";
} else if (json_tok_streq(buffer, typetok, "int")) {
popt->type = "int";
} else if (json_tok_streq(buffer, typetok, "bool")
|| json_tok_streq(buffer, typetok, "flag")) {
popt->type = json_strdup(popt, buffer, typetok);
if (popt->multi)
return tal_fmt(plugin,
"%s type \"%s\" cannot have multi",
popt->name, popt->type);
/* We default flags to false, the default token is ignored */
if (json_tok_streq(buffer, typetok, "flag"))
defaulttok = NULL;
} else {
return tal_fmt(plugin,
"Only \"string\", \"int\", \"bool\", and \"flag\" options are supported");
}
if (defaulttok) {
popt->def = plugin_opt_value(popt, popt->type,
json_strdup(tmpctx, buffer, defaulttok));
if (!popt->def)
return tal_fmt(tmpctx, "default %.*s is not a valid %s",
json_tok_full_len(defaulttok),
json_tok_full(buffer, defaulttok),
popt->type);
}
if (!popt->description)
popt->description = json_strdup(popt, buffer, desctok);
list_add_tail(&plugin->plugin_opts, &popt->list);
if (streq(popt->type, "flag"))
opt_register_noarg(popt->name, plugin_opt_flag_set, popt,
popt->description);
else
opt_register_arg(popt->name, plugin_opt_set, NULL, popt,
popt->description);
tal_add_destructor(popt, destroy_plugin_opt);
return NULL;
}
/* Iterate through the options in the manifest response, and add them
* to the plugin and the command line options */
static const char *plugin_opts_add(struct plugin *plugin,
const char *buffer,
const jsmntok_t *resulttok)
{
const jsmntok_t *options = json_get_member(buffer, resulttok, "options");
if (!options) {
return tal_fmt(plugin,
"\"result.options\" was not found in the manifest");
}
if (options->type != JSMN_ARRAY) {
return tal_fmt(plugin, "\"result.options\" is not an array");
}
for (size_t i = 0; i < options->size; i++) {
const char *err;
err = plugin_opt_add(plugin, buffer, json_get_arr(options, i));
if (err)