forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonrpc.c
1558 lines (1317 loc) · 42.5 KB
/
jsonrpc.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
/* Code for JSON_RPC API.
*
* Each socket connection is represented by a `struct json_connection`.
*
* This can have zero, one or more `struct command` in progress at a time:
* because the json_connection can be closed at any point, these `struct command`
* have a independent lifetimes.
*
* Each `struct command` writes into a `struct json_stream`, which is created
* the moment they start writing output (see attach_json_stream). Initially
* the struct command owns it since they're writing into it. When they're
* done, the `json_connection` needs to drain it (if it's still around). At
* that point, the `json_connection` becomes the owner (or it's simply freed).
*/
/* eg: { "jsonrpc":"2.0", "method" : "dev-echo", "params" : [ "hello", "Arabella!" ], "id" : "1" } */
#include "config.h"
#include <ccan/asort/asort.h>
#include <ccan/err/err.h>
#include <ccan/io/io.h>
#include <ccan/json_escape/json_escape.h>
#include <ccan/json_out/json_out.h>
#include <ccan/tal/str/str.h>
#include <common/configdir.h>
#include <common/json_command.h>
#include <common/json_filter.h>
#include <common/json_param.h>
#include <common/memleak.h>
#include <common/timeout.h>
#include <db/exec.h>
#include <fcntl.h>
#include <lightningd/jsonrpc.h>
#include <lightningd/plugin_hook.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
/* Dummy structure. */
struct command_result {
char c;
};
static struct command_result param_failed, complete, pending, unknown;
struct command_result *command_param_failed(void)
{
return ¶m_failed;
}
struct command_result *command_its_complicated(const char *relationship_details
UNNEEDED)
{
return &unknown;
}
/* This represents a JSON RPC connection. It can invoke multiple commands, but
* a command can outlive the connection, which could close any time. */
struct json_connection {
/* The global state */
struct lightningd *ld;
/* This io_conn (and our owner!) */
struct io_conn *conn;
/* Logging for this json connection. */
struct log *log;
/* The buffer (required to interpret tokens). */
char *buffer;
/* Internal state: */
/* How much is already filled. */
size_t used;
/* How much has just been filled. */
size_t len_read;
/* JSON parsing state. */
jsmn_parser input_parser;
jsmntok_t *input_toks;
/* Our commands */
struct list_head commands;
/* Are notifications enabled? */
bool notifications_enabled;
/* Are we allowed to batch database commitments? */
bool db_batching;
/* Our json_streams (owned by the commands themselves while running).
* Since multiple streams could start returning data at once, we
* always service these in order, freeing once empty. */
struct json_stream **js_arr;
};
/**
* `jsonrpc` encapsulates the entire state of the JSON-RPC interface,
* including a list of methods that the interface supports (can be
* appended dynamically, e.g., for plugins, and logs. It also serves
* as a convenient `tal`-parent for all JSON-RPC related allocations.
*/
struct jsonrpc {
struct io_listener *rpc_listener;
struct json_command **commands;
/* Map from json command names to usage strings: we don't put this inside
* struct json_command as it's good practice to have those const. */
STRMAP(const char *) usagemap;
};
/* The command itself usually owns the stream, because jcon may get closed.
* The command transfers ownership once it's done though. */
static struct json_stream *jcon_new_json_stream(const tal_t *ctx,
struct json_connection *jcon,
struct command *writer)
{
struct json_stream *js = new_json_stream(ctx, writer, jcon->log);
/* Wake writer to start streaming, in case it's not already. */
io_wake(jcon);
/* FIXME: Keep streams around for recycling. */
tal_arr_expand(&jcon->js_arr, js);
return js;
}
static void jcon_remove_json_stream(struct json_connection *jcon,
struct json_stream *js)
{
for (size_t i = 0; i < tal_count(jcon->js_arr); i++) {
if (js != jcon->js_arr[i])
continue;
tal_arr_remove(&jcon->js_arr, i);
return;
}
abort();
}
/* jcon and cmd have separate lifetimes: we detach them on either destruction */
static void destroy_jcon(struct json_connection *jcon)
{
struct command *c;
list_for_each(&jcon->commands, c, list)
c->jcon = NULL;
/* Make sure this happens last! */
tal_free(jcon->log);
}
struct log *command_log(struct command *cmd)
{
if (cmd->jcon)
return cmd->jcon->log;
return cmd->ld->log;
}
static struct command_result *json_help(struct command *cmd,
const char *buffer,
const jsmntok_t *obj UNNEEDED,
const jsmntok_t *params);
static const struct json_command help_command = {
"help",
"utility",
json_help,
"List available commands, or give verbose help on one {command}.",
.verbose = "help [command]\n"
"Without [command]:\n"
" Outputs an array of objects with 'command' and 'description'\n"
"With [command]:\n"
" Give a single object containing 'verbose', which completely describes\n"
" the command inputs and outputs."
};
AUTODATA(json_command, &help_command);
static struct command_result *json_stop(struct command *cmd,
const char *buffer,
const jsmntok_t *obj UNNEEDED,
const jsmntok_t *params)
{
struct json_out *jout;
const char *p;
size_t len;
if (!param(cmd, buffer, params, NULL))
return command_param_failed();
log_unusual(cmd->ld->log, "JSON-RPC shutdown");
/* With rpc_command_hook, jcon might have closed in the meantime! */
if (!cmd->jcon) {
/* Return us to toplevel lightningd.c */
log_debug(cmd->ld->log, "io_break: %s", __func__);
io_break(cmd->ld);
return command_still_pending(cmd);
}
cmd->ld->stop_conn = cmd->jcon->conn;
/* This is the one place where result is a literal string. */
jout = json_out_new(tmpctx);
json_out_start(jout, NULL, '{');
json_out_addstr(jout, "jsonrpc", "2.0");
json_out_add(jout, "id", cmd->id_is_string, "%s", cmd->id);
json_out_addstr(jout, "result", "Shutdown complete");
json_out_end(jout, '}');
json_out_finished(jout);
/* Add two \n */
memcpy(json_out_direct(jout, 2), "\n\n", strlen("\n\n"));
p = json_out_contents(jout, &len);
cmd->ld->stop_response = tal_strndup(cmd->ld, p, len);
/* Wake write loop in case it's not already. */
io_wake(cmd->jcon);
return command_still_pending(cmd);
}
static const struct json_command stop_command = {
"stop",
"utility",
json_stop,
"Shut down the lightningd process"
};
AUTODATA(json_command, &stop_command);
#if DEVELOPER
struct slowcmd {
struct command *cmd;
unsigned *msec;
struct json_stream *js;
};
static void slowcmd_finish(struct slowcmd *sc)
{
json_add_num(sc->js, "msec", *sc->msec);
was_pending(command_success(sc->cmd, sc->js));
}
static void slowcmd_start(struct slowcmd *sc)
{
sc->js = json_stream_success(sc->cmd);
new_reltimer(sc->cmd->ld->timers, sc, time_from_msec(*sc->msec),
slowcmd_finish, sc);
}
static struct command_result *json_dev(struct command *cmd UNUSED,
const char *buffer,
const jsmntok_t *obj UNNEEDED,
const jsmntok_t *params)
{
const char *subcmd;
subcmd = param_subcommand(cmd, buffer, params,
"crash", "rhash", "slowcmd", NULL);
if (!subcmd)
return command_param_failed();
if (streq(subcmd, "crash")) {
if (!param(cmd, buffer, params,
p_req("subcommand", param_ignore, cmd),
NULL))
return command_param_failed();
fatal("Crash at user request");
} else if (streq(subcmd, "slowcmd")) {
struct slowcmd *sc = tal(cmd, struct slowcmd);
sc->cmd = cmd;
if (!param(cmd, buffer, params,
p_req("subcommand", param_ignore, cmd),
p_opt_def("msec", param_number, &sc->msec, 1000),
NULL))
return command_param_failed();
new_reltimer(cmd->ld->timers, sc, time_from_msec(0),
slowcmd_start, sc);
return command_still_pending(cmd);
} else {
assert(streq(subcmd, "rhash"));
struct json_stream *response;
struct sha256 *secret;
if (!param(cmd, buffer, params,
p_req("subcommand", param_ignore, cmd),
p_req("secret", param_sha256, &secret),
NULL))
return command_param_failed();
/* Hash in place. */
sha256(secret, secret, sizeof(*secret));
response = json_stream_success(cmd);
json_add_sha256(response, "rhash", secret);
return command_success(cmd, response);
}
}
static const struct json_command dev_command = {
"dev",
"developer",
json_dev,
"Developer command test multiplexer",
.verbose = "dev rhash {secret}\n"
" Show SHA256 of {secret}\n"
"dev crash\n"
" Crash lightningd by calling fatal()\n"
"dev slowcmd {msec}\n"
" Torture test for slow commands, optional {msec}\n"
};
AUTODATA(json_command, &dev_command);
#endif /* DEVELOPER */
static size_t num_cmdlist;
static struct json_command **get_cmdlist(void)
{
static struct json_command **cmdlist;
if (!cmdlist)
cmdlist = autodata_get(json_command, &num_cmdlist);
return cmdlist;
}
static void json_add_help_command(struct command *cmd,
struct json_stream *response,
struct json_command *json_command)
{
char *usage;
/* If they disallow deprecated APIs, don't even list them */
if (!deprecated_apis && json_command->deprecated)
return;
usage = tal_fmt(cmd, "%s%s %s",
json_command->name,
json_command->deprecated ? " (DEPRECATED!)" : "",
strmap_get(&cmd->ld->jsonrpc->usagemap,
json_command->name));
json_object_start(response, NULL);
json_add_string(response, "command", usage);
json_add_string(response, "category", json_command->category);
json_add_string(response, "description", json_command->description);
if (!json_command->verbose) {
json_add_string(response, "verbose",
"HELP! Please contribute"
" a description for this"
" json_command!");
} else {
struct json_escape *esc;
esc = json_escape(NULL, json_command->verbose);
json_add_escaped_string(response, "verbose", take(esc));
}
json_object_end(response);
}
static const struct json_command *find_command(struct json_command **commands,
const char *cmdname)
{
for (size_t i = 0; i < tal_count(commands); i++) {
if (streq(cmdname, commands[i]->name))
return commands[i];
}
return NULL;
}
static int compare_commands_name(struct json_command *const *a,
struct json_command *const *b, void *unused)
{
return strcmp((*a)->name, (*b)->name);
}
static struct command_result *json_help(struct command *cmd,
const char *buffer,
const jsmntok_t *obj UNNEEDED,
const jsmntok_t *params)
{
struct json_stream *response;
const char *cmdname;
struct json_command **commands;
const struct json_command *one_cmd;
if (!param(cmd, buffer, params,
p_opt("command", param_string, &cmdname),
NULL))
return command_param_failed();
commands = cmd->ld->jsonrpc->commands;
if (cmdname) {
one_cmd = find_command(commands, cmdname);
if (!one_cmd)
return command_fail(cmd, JSONRPC2_METHOD_NOT_FOUND,
"Unknown command %s",
cmdname);
if (!deprecated_apis && one_cmd->deprecated)
return command_fail(cmd, JSONRPC2_METHOD_NOT_FOUND,
"Deprecated command %s",
cmdname);
} else
one_cmd = NULL;
asort(commands, tal_count(commands), compare_commands_name, NULL);
response = json_stream_success(cmd);
json_array_start(response, "help");
for (size_t i = 0; i < tal_count(commands); i++) {
if (!one_cmd || one_cmd == commands[i])
json_add_help_command(cmd, response, commands[i]);
}
json_array_end(response);
/* Tell cli this is simple enough to be formatted flat for humans */
json_add_string(response, "format-hint", "simple");
return command_success(cmd, response);
}
static const struct json_command *find_cmd(const struct jsonrpc *rpc,
const char *buffer,
const jsmntok_t *tok)
{
struct json_command **commands = rpc->commands;
for (size_t i = 0; i < tal_count(commands); i++)
if (json_tok_streq(buffer, tok, commands[i]->name))
return commands[i];
return NULL;
}
/* This can be called directly on shutdown, even with unfinished cmd */
static void destroy_command(struct command *cmd)
{
if (!cmd->jcon) {
log_debug(cmd->ld->log,
"Command returned result after jcon close");
return;
}
list_del_from(&cmd->jcon->commands, &cmd->list);
}
struct command_result *command_raw_complete(struct command *cmd,
struct json_stream *result)
{
json_stream_close(result, cmd);
/* If we have a jcon, it will free result for us. */
if (cmd->jcon)
tal_steal(cmd->jcon, result);
tal_free(cmd);
return &complete;
}
struct command_result *command_success(struct command *cmd,
struct json_stream *result)
{
assert(cmd);
assert(cmd->json_stream == result);
/* Filter will get upset if we close "result" object it didn't
* see! */
if (cmd->filter) {
const char *err = json_stream_detach_filter(tmpctx, result);
if (err)
json_add_string(result, "warning_parameter_filter",
err);
}
json_object_end(result);
json_object_end(result);
return command_raw_complete(cmd, result);
}
struct command_result *command_failed(struct command *cmd,
struct json_stream *result)
{
assert(cmd->json_stream == result);
/* Have to close error */
json_object_end(result);
json_object_end(result);
return command_raw_complete(cmd, result);
}
struct command_result *command_fail(struct command *cmd, enum jsonrpc_errcode code,
const char *fmt, ...)
{
const char *errmsg;
struct json_stream *r;
va_list ap;
va_start(ap, fmt);
errmsg = tal_vfmt(cmd, fmt, ap);
va_end(ap);
r = json_stream_fail_nodata(cmd, code, errmsg);
return command_failed(cmd, r);
}
struct json_filter **command_filter_ptr(struct command *cmd)
{
return &cmd->filter;
}
struct command_result *command_still_pending(struct command *cmd)
{
notleak_with_children(cmd);
cmd->pending = true;
/* If we've started writing, wake reader. */
if (cmd->json_stream)
json_stream_flush(cmd->json_stream);
return &pending;
}
static void json_command_malformed(struct json_connection *jcon,
const char *id,
const char *error)
{
/* NULL writer is OK here, since we close it immediately. */
struct json_stream *js = jcon_new_json_stream(jcon, jcon, NULL);
json_object_start(js, NULL);
json_add_string(js, "jsonrpc", "2.0");
json_add_primitive(js, "id", id);
json_object_start(js, "error");
json_add_jsonrpc_errcode(js, "code", JSONRPC2_INVALID_REQUEST);
json_add_string(js, "message", error);
json_object_end(js);
json_object_end(js);
json_stream_close(js, NULL);
}
void json_notify_fmt(struct command *cmd,
enum log_level level,
const char *fmt, ...)
{
va_list ap;
struct json_stream *js;
if (!cmd->send_notifications)
return;
js = json_stream_raw_for_cmd(cmd);
va_start(ap, fmt);
json_object_start(js, NULL);
json_add_string(js, "jsonrpc", "2.0");
json_add_string(js, "method", "message");
json_object_start(js, "params");
if (cmd->id_is_string)
json_add_string(js, "id", cmd->id);
else
json_add_jsonstr(js, "id", cmd->id, strlen(cmd->id));
json_add_string(js, "level", log_level_name(level));
json_add_string(js, "message", tal_vfmt(tmpctx, fmt, ap));
json_object_end(js);
json_object_end(js);
json_stream_double_cr(js);
json_stream_flush(js);
}
struct json_stream *json_stream_raw_for_cmd(struct command *cmd)
{
struct json_stream *js;
/* Might have already opened it for a notification */
if (cmd->json_stream)
return cmd->json_stream;
/* If they still care about the result, attach it to them. */
if (cmd->jcon)
js = jcon_new_json_stream(cmd, cmd->jcon, cmd);
else
js = new_json_stream(cmd, cmd, NULL);
assert(!cmd->json_stream);
cmd->json_stream = js;
return js;
}
void json_stream_log_suppress_for_cmd(struct json_stream *js,
const struct command *cmd)
{
const char *nm = cmd->json_cmd->name;
const char *s = tal_fmt(tmpctx, "Suppressing logging of %s command", nm);
log_io(cmd->jcon->log, LOG_IO_OUT, NULL, s, NULL, 0);
json_stream_log_suppress(js, strdup(nm));
}
static struct json_stream *json_start(struct command *cmd)
{
struct json_stream *js = json_stream_raw_for_cmd(cmd);
json_object_start(js, NULL);
json_add_string(js, "jsonrpc", "2.0");
if (cmd->id_is_string)
json_add_string(js, "id", cmd->id);
else
json_add_jsonstr(js, "id", cmd->id, strlen(cmd->id));
return js;
}
struct json_stream *json_stream_success(struct command *cmd)
{
struct json_stream *r = json_start(cmd);
json_object_start(r, "result");
/* We have results? OK, start filtering */
if (cmd->filter)
json_stream_attach_filter(r, cmd->filter);
return r;
}
struct json_stream *json_stream_fail_nodata(struct command *cmd,
enum jsonrpc_errcode code,
const char *errmsg)
{
struct json_stream *js = json_start(cmd);
assert(code);
json_object_start(js, "error");
json_add_jsonrpc_errcode(js, "code", code);
json_add_string(js, "message", errmsg);
return js;
}
struct json_stream *json_stream_fail(struct command *cmd,
enum jsonrpc_errcode code,
const char *errmsg)
{
struct json_stream *r = json_stream_fail_nodata(cmd, code, errmsg);
json_object_start(r, "data");
return r;
}
static struct command_result *command_exec(struct json_connection *jcon,
struct command *cmd,
const char *buffer,
const jsmntok_t *request,
const jsmntok_t *params)
{
struct command_result *res;
res = cmd->json_cmd->dispatch(cmd, buffer, request, params);
assert(res == ¶m_failed
|| res == &complete
|| res == &pending
|| res == &unknown);
/* If they didn't complete it, they must call command_still_pending.
* If they completed it, it's freed already. */
if (res == &pending)
assert(cmd->pending);
/* The command might outlive the connection. */
if (jcon)
list_for_each(&jcon->commands, cmd, list)
assert(cmd->pending);
return res;
}
/* A plugin hook to take over (fail/alter) RPC commands */
struct rpc_command_hook_payload {
struct command *cmd;
const char *buffer;
const jsmntok_t *request;
/* custom response/replace/error options plugins can have */
const char *custom_result;
const char *custom_error;
const jsmntok_t *custom_replace;
const char *custom_buffer;
};
static void rpc_command_hook_serialize(struct rpc_command_hook_payload *p,
struct json_stream *s,
struct plugin *plugin)
{
const jsmntok_t *tok;
size_t i;
char *key;
json_object_start(s, "rpc_command");
json_for_each_obj(i, tok, p->request) {
key = tal_strndup(NULL, p->buffer + tok->start,
tok->end - tok->start);
json_add_tok(s, key, tok + 1, p->buffer);
tal_free(key);
}
json_object_end(s);
}
static void replace_command(struct rpc_command_hook_payload *p,
const char *buffer,
const jsmntok_t *replacetok)
{
const jsmntok_t *method = NULL, *params = NULL;
const char *bad;
/* Must contain "method", "params" and "id" */
if (replacetok->type != JSMN_OBJECT) {
bad = "'replace' must be an object";
goto fail;
}
method = json_get_member(buffer, replacetok, "method");
if (!method) {
bad = "missing 'method'";
goto fail;
}
params = json_get_member(buffer, replacetok, "params");
if (!params) {
bad = "missing 'params'";
goto fail;
}
if (!json_get_member(buffer, replacetok, "id")) {
bad = "missing 'id'";
goto fail;
}
p->cmd->json_cmd = find_cmd(p->cmd->ld->jsonrpc, buffer, method);
if (!p->cmd->json_cmd) {
bad = tal_fmt(tmpctx, "redirected to unknown method '%.*s'",
method->end - method->start,
buffer + method->start);
goto fail;
}
// deprecated phase to give the possibility to all to migrate and stay safe
// from this more restrictive change.
if (!deprecated_apis) {
const jsmntok_t *jsonrpc = json_get_member(buffer, replacetok, "jsonrpc");
if (!jsonrpc || jsonrpc->type != JSMN_STRING || !json_tok_streq(buffer, jsonrpc, "2.0")) {
bad = "jsonrpc: \"2.0\" must be specified in the request";
goto fail;
}
}
was_pending(command_exec(p->cmd->jcon, p->cmd, buffer, replacetok,
params));
return;
fail:
was_pending(command_fail(p->cmd, JSONRPC2_INVALID_REQUEST,
"Bad response to 'rpc_command' hook: %s", bad));
}
static void rpc_command_hook_final(struct rpc_command_hook_payload *p STEALS)
{
const jsmntok_t *params;
/* Free payload with cmd */
tal_steal(p->cmd, p);
if (p->custom_result != NULL) {
struct json_stream *s = json_start(p->cmd);
json_add_jsonstr(s, "result",
p->custom_result, strlen(p->custom_result));
json_object_end(s);
return was_pending(command_raw_complete(p->cmd, s));
}
if (p->custom_error != NULL) {
struct json_stream *s = json_start(p->cmd);
json_add_jsonstr(s, "error",
p->custom_error, strlen(p->custom_error));
json_object_end(s);
return was_pending(command_raw_complete(p->cmd, s));
}
if (p->custom_replace != NULL)
return replace_command(p, p->custom_buffer, p->custom_replace);
/* If no plugin requested a change, just continue command execution. */
params = json_get_member(p->buffer, p->request, "params");
return was_pending(command_exec(p->cmd->jcon,
p->cmd,
p->buffer,
p->request,
params));
}
static bool
rpc_command_hook_callback(struct rpc_command_hook_payload *p,
const char *buffer, const jsmntok_t *resulttok)
{
const struct lightningd *ld = p->cmd->ld;
const jsmntok_t *tok, *custom_return;
static char *error = "";
char *method;
if (!resulttok || !buffer)
return true;
tok = json_get_member(buffer, resulttok, "result");
if (tok) {
if (!json_tok_streq(buffer, tok, "continue")) {
error = "'result' should only be 'continue'.";
goto log_error_and_skip;
}
/* plugin tells us to do nothing. just pass. */
return true;
}
/* didn't just continue but hook was already modified by prior plugin */
if (p->custom_result != NULL ||
p->custom_error != NULL ||
p->custom_replace != NULL) {
/* get method name and log error (only the first time). */
tok = json_get_member(p->buffer, p->request, "method");
method = tal_strndup(p, p->buffer + tok->start, tok->end - tok->start);
log_unusual(ld->log, "rpc_command hook '%s' already modified, ignoring.", method );
rpc_command_hook_final(p);
return false;
}
/* If the registered plugin did not respond with continue,
* it wants either to replace the request... */
tok = json_get_member(buffer, resulttok, "replace");
if (tok) {
/* We need to make copies here, as buffer and tokens
* can be reused. */
p->custom_replace = json_tok_copy(p, tok);
p->custom_buffer = tal_dup_talarr(p, char, buffer);
return true;
}
/* ...or return a custom JSONRPC response. */
tok = json_get_member(buffer, resulttok, "return");
if (tok) {
custom_return = json_get_member(buffer, tok, "result");
if (custom_return) {
p->custom_result = json_strdup(p, buffer, custom_return);
return true;
}
custom_return = json_get_member(buffer, tok, "error");
if (custom_return) {
enum jsonrpc_errcode code;
const char *errmsg;
if (!json_to_jsonrpc_errcode(buffer,
json_get_member(buffer, custom_return, "code"),
&code)) {
error = "'error' object does not contain a code.";
goto log_error_and_skip;
}
errmsg = json_strdup(tmpctx, buffer,
json_get_member(buffer, custom_return, "message"));
if (!errmsg) {
error = "'error' object does not contain a message.";
goto log_error_and_skip;
}
p->custom_error = json_strdup(p, buffer, custom_return);
return true;
}
}
log_error_and_skip:
/* Just log BROKEN errors. Give other plugins a chance. */
log_broken(ld->log, "Bad response to 'rpc_command' hook. %s", error);
return true;
}
REGISTER_PLUGIN_HOOK(rpc_command,
rpc_command_hook_callback,
rpc_command_hook_final,
rpc_command_hook_serialize,
struct rpc_command_hook_payload *);
/* We return struct command_result so command_fail return value has a natural
* sink; we don't actually use the result. */
static struct command_result *
parse_request(struct json_connection *jcon, const jsmntok_t tok[])
{
const jsmntok_t *method, *id, *params, *filter;
struct command *c;
struct rpc_command_hook_payload *rpc_hook;
bool completed;
if (tok[0].type != JSMN_OBJECT) {
json_command_malformed(jcon, "null",
"Expected {} for json command");
return NULL;
}
method = json_get_member(jcon->buffer, tok, "method");
params = json_get_member(jcon->buffer, tok, "params");
filter = json_get_member(jcon->buffer, tok, "filter");
id = json_get_member(jcon->buffer, tok, "id");
if (!id) {
json_command_malformed(jcon, "null", "No id");
return NULL;
}
if (id->type != JSMN_STRING && id->type != JSMN_PRIMITIVE) {
json_command_malformed(jcon, "null",
"Expected string/primitive for id");
return NULL;
}
// Adding a deprecated phase to make sure that all the Core Lightning wrapper
// can migrate all the frameworks
if (!deprecated_apis) {
const jsmntok_t *jsonrpc = json_get_member(jcon->buffer, tok, "jsonrpc");
if (!jsonrpc || jsonrpc->type != JSMN_STRING || !json_tok_streq(jcon->buffer, jsonrpc, "2.0")) {
json_command_malformed(jcon, "null", "jsonrpc: \"2.0\" must be specified in the request");
return NULL;
}
}
/* Allocate the command off of the `jsonrpc` object and not
* the connection since the command may outlive `conn`. */
c = tal(jcon->ld->jsonrpc, struct command);
c->jcon = jcon;
c->send_notifications = jcon->notifications_enabled;
c->ld = jcon->ld;
c->pending = false;
c->json_stream = NULL;
c->id_is_string = (id->type == JSMN_STRING);
c->id = json_strdup(c, jcon->buffer, id);
c->mode = CMD_NORMAL;
c->filter = NULL;
list_add_tail(&jcon->commands, &c->list);
tal_add_destructor(c, destroy_command);
if (!method || !params) {
return command_fail(c, JSONRPC2_INVALID_REQUEST,
method ? "No params" : "No method");
}
if (method->type != JSMN_STRING) {
return command_fail(c, JSONRPC2_INVALID_REQUEST,
"Expected string for method");
}
if (filter) {
struct command_result *ret;
ret = parse_filter(c, "filter", jcon->buffer, filter);
if (ret)
return ret;
}
/* Debug was too chatty, so we use IO here, even though we're
* actually just logging the id */
log_io(jcon->log, LOG_IO_IN, NULL, c->id, NULL, 0);
c->json_cmd = find_cmd(jcon->ld->jsonrpc, jcon->buffer, method);
if (!c->json_cmd) {
return command_fail(
c, JSONRPC2_METHOD_NOT_FOUND, "Unknown command '%.*s'",
method->end - method->start, jcon->buffer + method->start);
}
if (c->json_cmd->deprecated && !deprecated_apis) {
return command_fail(c, JSONRPC2_METHOD_NOT_FOUND,
"Command %.*s is deprecated",
json_tok_full_len(method),
json_tok_full(jcon->buffer, method));
}
rpc_hook = tal(c, struct rpc_command_hook_payload);
rpc_hook->cmd = c;
/* Duplicate since we might outlive the connection */
rpc_hook->buffer = tal_dup_talarr(rpc_hook, char, jcon->buffer);
rpc_hook->request = tal_dup_talarr(rpc_hook, jsmntok_t, tok);
/* NULL the custom_ values for the hooks */
rpc_hook->custom_result = NULL;
rpc_hook->custom_error = NULL;
rpc_hook->custom_replace = NULL;
rpc_hook->custom_buffer = NULL;
completed = plugin_hook_call_rpc_command(jcon->ld, c->id, rpc_hook);
/* If it's deferred, mark it (otherwise, it's completed) */
if (!completed)
return command_still_pending(c);
return NULL;
}
/* Mutual recursion */
static struct io_plan *stream_out_complete(struct io_conn *conn,
struct json_stream *js,
struct json_connection *jcon);