forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonrpc.c
1214 lines (1026 loc) · 33.3 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 "ccan/config.h"
#include <arpa/inet.h>
#include <bitcoin/address.h>
#include <bitcoin/base58.h>
#include <bitcoin/script.h>
#include <ccan/array_size/array_size.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/str/hex/hex.h>
#include <ccan/strmap/strmap.h>
#include <ccan/tal/str/str.h>
#include <common/bech32.h>
#include <common/json_command.h>
#include <common/jsonrpc_errors.h>
#include <common/memleak.h>
#include <common/param.h>
#include <common/timeout.h>
#include <common/version.h>
#include <common/wireaddr.h>
#include <errno.h>
#include <fcntl.h>
#include <lightningd/chaintopology.h>
#include <lightningd/json.h>
#include <lightningd/jsonrpc.h>
#include <lightningd/log.h>
#include <lightningd/memdump.h>
#include <lightningd/options.h>
#include <stdio.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.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;
/* Our commands */
struct list_head commands;
/* 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;
struct log *log;
/* 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) {
log_debug(jcon->log, "Abandoning command %s", c->json_cmd->name);
c->jcon = NULL;
}
/* Make sure this happens last! */
tal_free(jcon->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();
/* This can't have closed yet! */
cmd->ld->stop_conn = cmd->jcon->conn;
log_unusual(cmd->ld->log, "JSON-RPC shutdown");
/* 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");
/* id may be a string or number, so copy direct. */
memcpy(json_out_member_direct(jout, "id", strlen(cmd->id)),
cmd->id, strlen(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
static struct command_result *json_rhash(struct command *cmd,
const char *buffer,
const jsmntok_t *obj UNUSED,
const jsmntok_t *params)
{
struct json_stream *response;
struct sha256 *secret;
if (!param(cmd, buffer, params,
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_hex(response, "rhash", secret, sizeof(*secret));
return command_success(cmd, response);
}
static const struct json_command dev_rhash_command = {
"dev-rhash",
"developer",
json_rhash,
"Show SHA256 of {secret}"
};
AUTODATA(json_command, &dev_rhash_command);
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_slowcmd(struct command *cmd,
const char *buffer,
const jsmntok_t *obj UNUSED,
const jsmntok_t *params)
{
struct slowcmd *sc = tal(cmd, struct slowcmd);
sc->cmd = cmd;
if (!param(cmd, buffer, params,
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);
}
static const struct json_command dev_slowcmd_command = {
"dev-slowcmd",
"developer",
json_slowcmd,
"Torture test for slow commands, optional {msec}"
};
AUTODATA(json_command, &dev_slowcmd_command);
static struct command_result *json_crash(struct command *cmd UNUSED,
const char *buffer,
const jsmntok_t *obj UNNEEDED,
const jsmntok_t *params)
{
if (!param(cmd, buffer, params, NULL))
return command_param_failed();
fatal("Crash at user request");
}
static const struct json_command dev_crash_command = {
"dev-crash",
"developer",
json_crash,
"Crash lightningd by calling fatal()"
};
AUTODATA(json_command, &dev_crash_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;
usage = tal_fmt(cmd, "%s %s",
json_command->name,
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 *buffer,
const jsmntok_t *cmdtok)
{
for (size_t i = 0; i < tal_count(commands); i++) {
if (json_tok_streq(buffer, cmdtok, 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 jsmntok_t *cmdtok;
struct json_command **commands;
const struct json_command *one_cmd;
if (!param(cmd, buffer, params,
p_opt("command", param_tok, &cmdtok),
NULL))
return command_param_failed();
commands = cmd->ld->jsonrpc->commands;
if (cmdtok) {
one_cmd = find_command(commands, buffer, cmdtok);
if (!one_cmd)
return command_fail(cmd, JSONRPC2_METHOD_NOT_FOUND,
"Unknown command '%.*s'",
cmdtok->end - cmdtok->start,
buffer + cmdtok->start);
} 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);
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);
json_object_end(result);
json_object_compat_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_compat_end(result);
return command_raw_complete(cmd, result);
}
struct command_result *command_fail(struct command *cmd, int 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 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_literal(js, "id", id, strlen(id));
json_object_start(js, "error");
json_add_member(js, "code", false, "%d", JSONRPC2_INVALID_REQUEST);
json_add_string(js, "message", error);
json_object_end(js);
json_object_compat_end(js);
json_stream_close(js, NULL);
}
struct json_stream *json_stream_raw_for_cmd(struct command *cmd)
{
struct json_stream *js;
/* 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, 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");
json_add_literal(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");
return r;
}
struct json_stream *json_stream_fail_nodata(struct command *cmd,
int code,
const char *errmsg)
{
struct json_stream *js = json_start(cmd);
assert(code);
json_object_start(js, "error");
json_add_member(js, "code", false, "%d", code);
json_add_string(js, "message", errmsg);
return js;
}
struct json_stream *json_stream_fail(struct command *cmd,
int code,
const char *errmsg)
{
struct json_stream *r = json_stream_fail_nodata(cmd, code, errmsg);
json_object_start(r, "data");
return r;
}
/* 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;
struct command *c;
struct command_result *res;
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");
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;
}
/* 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->ld = jcon->ld;
c->pending = false;
c->json_stream = NULL;
c->id = tal_strndup(c,
json_tok_full(jcon->buffer, id),
json_tok_full_len(id));
c->mode = CMD_NORMAL;
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");
}
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",
method->end - method->start,
jcon->buffer + method->start);
}
db_begin_transaction(jcon->ld->wallet->db);
res = c->json_cmd->dispatch(c, jcon->buffer, tok, params);
db_commit_transaction(jcon->ld->wallet->db);
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(c->pending);
list_for_each(&jcon->commands, c, list)
assert(c->pending);
return res;
}
/* Mutual recursion */
static struct io_plan *stream_out_complete(struct io_conn *conn,
struct json_stream *js,
struct json_connection *jcon);
static struct io_plan *start_json_stream(struct io_conn *conn,
struct json_connection *jcon)
{
/* If something has created an output buffer, start streaming. */
if (tal_count(jcon->js_arr))
return json_stream_output(jcon->js_arr[0], conn,
stream_out_complete, jcon);
/* Tell reader it can run next command. */
io_wake(conn);
/* Once the stop_conn conn is drained, we can shut down. */
if (jcon->ld->stop_conn == conn) {
/* Return us to toplevel lightningd.c */
io_break(jcon->ld);
/* We never come back. */
return io_out_wait(conn, conn, io_never, conn);
}
return io_out_wait(conn, jcon, start_json_stream, jcon);
}
/* Command has completed writing, and we've written it all out to conn. */
static struct io_plan *stream_out_complete(struct io_conn *conn,
struct json_stream *js,
struct json_connection *jcon)
{
jcon_remove_json_stream(jcon, js);
tal_free(js);
/* Wait for more output. */
return start_json_stream(conn, jcon);
}
static struct io_plan *read_json(struct io_conn *conn,
struct json_connection *jcon)
{
jsmntok_t *toks;
bool valid;
if (jcon->len_read)
log_io(jcon->log, LOG_IO_IN, "",
jcon->buffer + jcon->used, jcon->len_read);
/* Resize larger if we're full. */
jcon->used += jcon->len_read;
if (jcon->used == tal_count(jcon->buffer))
tal_resize(&jcon->buffer, jcon->used * 2);
/* We wait for pending output to be consumed, to avoid DoS */
if (tal_count(jcon->js_arr) != 0) {
jcon->len_read = 0;
return io_wait(conn, conn, read_json, jcon);
}
toks = json_parse_input(jcon->buffer, jcon->buffer, jcon->used, &valid);
if (!toks) {
if (!valid) {
log_unusual(jcon->log,
"Invalid token in json input: '%.*s'",
(int)jcon->used, jcon->buffer);
json_command_malformed(
jcon, "null",
"Invalid token in json input");
return io_halfclose(conn);
}
/* We need more. */
goto read_more;
}
/* Empty buffer? (eg. just whitespace). */
if (tal_count(toks) == 1) {
jcon->used = 0;
goto read_more;
}
parse_request(jcon, toks);
/* Remove first {}. */
memmove(jcon->buffer, jcon->buffer + toks[0].end,
tal_count(jcon->buffer) - toks[0].end);
jcon->used -= toks[0].end;
/* If we have more to process, try again. FIXME: this still gets
* first priority in io_loop, so can starve others. Hack would be
* a (non-zero) timer, but better would be to have io_loop avoid
* such livelock */
if (jcon->used) {
tal_free(toks);
jcon->len_read = 0;
return io_always(conn, read_json, jcon);
}
read_more:
tal_free(toks);
return io_read_partial(conn, jcon->buffer + jcon->used,
tal_count(jcon->buffer) - jcon->used,
&jcon->len_read, read_json, jcon);
}
static struct io_plan *jcon_connected(struct io_conn *conn,
struct lightningd *ld)
{
struct json_connection *jcon;
/* We live as long as the connection, so we're not a leak. */
jcon = notleak(tal(conn, struct json_connection));
jcon->conn = conn;
jcon->ld = ld;
jcon->used = 0;
jcon->buffer = tal_arr(jcon, char, 64);
jcon->js_arr = tal_arr(jcon, struct json_stream *, 0);
jcon->len_read = 0;
list_head_init(&jcon->commands);
/* We want to log on destruction, so we free this in destructor. */
jcon->log = new_log(ld->log_book, ld->log_book, "%sjcon fd %i:",
log_prefix(ld->log), io_conn_fd(conn));
tal_add_destructor(jcon, destroy_jcon);
/* Note that write_json and read_json alternate manually, by waking
* each other. It would be simpler to not use a duplex io, and have
* read_json parse one command, then io_wait() for command completion
* and go to write_json.
*
* However, if we ever have notifications, this neat cmd-response
* pattern would break down, so we use this trick. */
return io_duplex(conn,
read_json(conn, jcon),
start_json_stream(conn, jcon));
}
static struct io_plan *incoming_jcon_connected(struct io_conn *conn,
struct lightningd *ld)
{
/* Lifetime of JSON conn is limited to fd connect time. */
return jcon_connected(notleak(conn), ld);
}
static void destroy_json_command(struct json_command *command, struct jsonrpc *rpc)
{
strmap_del(&rpc->usagemap, command->name, NULL);
for (size_t i = 0; i < tal_count(rpc->commands); i++) {
if (rpc->commands[i] == command) {
tal_arr_remove(&rpc->commands, i);
return;
}
}
abort();
}
static bool command_add(struct jsonrpc *rpc, struct json_command *command)
{
size_t count = tal_count(rpc->commands);
/* Check that we don't clobber a method */
for (size_t i = 0; i < count; i++)
if (streq(rpc->commands[i]->name, command->name))
return false;
tal_arr_expand(&rpc->commands, command);
return true;
}
/* Built-in commands get called to construct usage string via param() */
static void setup_command_usage(struct lightningd *ld,
struct json_command *command)
{
const struct command_result *res;
struct command *dummy;
/* Call it with minimal cmd, to fill out usagemap */
dummy = tal(tmpctx, struct command);
dummy->mode = CMD_USAGE;
dummy->ld = ld;
dummy->json_cmd = command;
res = command->dispatch(dummy, NULL, NULL, NULL);
assert(res == ¶m_failed);
assert(strmap_get(&ld->jsonrpc->usagemap, command->name));
}
bool jsonrpc_command_add(struct jsonrpc *rpc, struct json_command *command,
const char *usage TAKES)
{
if (!command_add(rpc, command))
return false;
usage = tal_strdup(command, usage);
strmap_add(&rpc->usagemap, command->name, usage);
tal_add_destructor2(command, destroy_json_command, rpc);
return true;
}
static bool jsonrpc_command_add_perm(struct lightningd *ld,
struct jsonrpc *rpc,
struct json_command *command)
{
if (!command_add(rpc, command))
return false;
setup_command_usage(ld, command);
return true;
}
static void destroy_jsonrpc(struct jsonrpc *jsonrpc)
{
strmap_clear(&jsonrpc->usagemap);
}
void jsonrpc_setup(struct lightningd *ld)
{
struct json_command **commands = get_cmdlist();
ld->jsonrpc = tal(ld, struct jsonrpc);
strmap_init(&ld->jsonrpc->usagemap);
ld->jsonrpc->commands = tal_arr(ld->jsonrpc, struct json_command *, 0);
ld->jsonrpc->log = new_log(ld->jsonrpc, ld->log_book, "jsonrpc");
for (size_t i=0; i<num_cmdlist; i++) {
if (!jsonrpc_command_add_perm(ld, ld->jsonrpc, commands[i]))
fatal("Cannot add duplicate command %s",
commands[i]->name);
}
ld->jsonrpc->rpc_listener = NULL;
tal_add_destructor(ld->jsonrpc, destroy_jsonrpc);
}
bool command_usage_only(const struct command *cmd)
{
return cmd->mode == CMD_USAGE;
}
void command_set_usage(struct command *cmd, const char *usage TAKES)
{
usage = tal_strdup(cmd->ld, usage);
if (!strmap_add(&cmd->ld->jsonrpc->usagemap, cmd->json_cmd->name, usage))
fatal("Two usages for command %s?", cmd->json_cmd->name);
}
bool command_check_only(const struct command *cmd)
{
return cmd->mode == CMD_CHECK;
}
void jsonrpc_listen(struct jsonrpc *jsonrpc, struct lightningd *ld)
{
struct sockaddr_un addr;
int fd, old_umask;
const char *rpc_filename = ld->rpc_filename;
/* Should not initialize it twice. */
assert(!jsonrpc->rpc_listener);
if (streq(rpc_filename, "/dev/tty")) {
fd = open(rpc_filename, O_RDWR);
if (fd == -1)
err(1, "Opening %s", rpc_filename);
/* Technically this is a leak, but there's only one */
notleak(io_new_conn(ld, fd, jcon_connected, ld));
return;
}
fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd < 0) {
errx(1, "domain socket creation failed");
}
if (strlen(rpc_filename) + 1 > sizeof(addr.sun_path))
errx(1, "rpc filename '%s' too long", rpc_filename);
strcpy(addr.sun_path, rpc_filename);
addr.sun_family = AF_UNIX;
/* Of course, this is racy! */
if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) == 0)
errx(1, "rpc filename '%s' in use", rpc_filename);
unlink(rpc_filename);
/* This file is only rw by us! */
old_umask = umask(0177);
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)))
err(1, "Binding rpc socket to '%s'", rpc_filename);
umask(old_umask);
if (listen(fd, 1) != 0)
err(1, "Listening on '%s'", rpc_filename);
jsonrpc->rpc_listener = io_new_listener(
ld->rpc_filename, fd, incoming_jcon_connected, ld);
log_debug(jsonrpc->log, "Listening on '%s'", ld->rpc_filename);
}
/**
* segwit_addr_net_decode - Try to decode a Bech32 address and detect
* testnet/mainnet/regtest
*
* This processes the address and returns a string if it is a Bech32
* address specified by BIP173. The string is set whether it is
* testnet ("tb"), mainnet ("bc"), or regtest ("bcrt")
* It does not check, witness version and program size restrictions.
*
* Out: witness_version: Pointer to an int that will be updated to contain
* the witness program version (between 0 and 16 inclusive).
* witness_program: Pointer to a buffer of size 40 that will be updated
* to contain the witness program bytes.
* witness_program_len: Pointer to a size_t that will be updated to
* contain the length of bytes in witness_program.
* In: addrz: Pointer to the null-terminated address.
* Returns string containing the human readable segment of bech32 address
*/
static const char *segwit_addr_net_decode(int *witness_version,
uint8_t *witness_program,
size_t *witness_program_len,
const char *addrz,
const struct chainparams *chainparams)
{
if (segwit_addr_decode(witness_version, witness_program,
witness_program_len, chainparams->bip173_name,
addrz))
return chainparams->bip173_name;
else
return NULL;
}
enum address_parse_result
json_tok_address_scriptpubkey(const tal_t *cxt,
const struct chainparams *chainparams,
const char *buffer,
const jsmntok_t *tok, const u8 **scriptpubkey)
{