1 #include <ccan/err/err.h>
2 #include <ccan/tal/str/str.h>
3 #include <common/configdir.h>
4 #include <common/json_command.h>
5 #include <common/json_helpers.h>
6 #include <common/json_tok.h>
7 #include <common/memleak.h>
8 #include <common/param.h>
9 #include <common/timeout.h>
10 #include <common/type_to_string.h>
11 #include <connectd/connectd_wiregen.h>
12 #include <hsmd/capabilities.h>
13 #include <lightningd/channel.h>
14 #include <lightningd/connect_control.h>
15 #include <lightningd/dual_open_control.h>
16 #include <lightningd/hsm_control.h>
17 #include <lightningd/jsonrpc.h>
18 #include <lightningd/lightningd.h>
19 #include <lightningd/opening_common.h>
20 #include <lightningd/peer_control.h>
21
22 struct connect {
23 struct list_node list;
24 struct node_id id;
25 struct command *cmd;
26 };
27
destroy_connect(struct connect * c)28 static void destroy_connect(struct connect *c)
29 {
30 list_del(&c->list);
31 }
32
new_connect(struct lightningd * ld,const struct node_id * id,struct command * cmd)33 static struct connect *new_connect(struct lightningd *ld,
34 const struct node_id *id,
35 struct command *cmd)
36 {
37 struct connect *c = tal(cmd, struct connect);
38 c->id = *id;
39 c->cmd = cmd;
40 list_add_tail(&ld->connects, &c->list);
41 tal_add_destructor(c, destroy_connect);
42 return c;
43 }
44
45 /* Finds first command which matches. */
find_connect(struct lightningd * ld,const struct node_id * id)46 static struct connect *find_connect(struct lightningd *ld,
47 const struct node_id *id)
48 {
49 struct connect *i;
50
51 list_for_each(&ld->connects, i, list) {
52 if (node_id_eq(&i->id, id))
53 return i;
54 }
55 return NULL;
56 }
57
connect_cmd_succeed(struct command * cmd,const struct peer * peer,bool incoming,const struct wireaddr_internal * addr)58 static struct command_result *connect_cmd_succeed(struct command *cmd,
59 const struct peer *peer,
60 bool incoming,
61 const struct wireaddr_internal *addr)
62 {
63 struct json_stream *response = json_stream_success(cmd);
64 json_add_node_id(response, "id", &peer->id);
65 json_add_hex_talarr(response, "features", peer->their_features);
66 json_add_string(response, "direction", incoming ? "in" : "out");
67 json_add_address_internal(response, "address", addr);
68 return command_success(cmd, response);
69 }
70
json_connect(struct command * cmd,const char * buffer,const jsmntok_t * obj UNNEEDED,const jsmntok_t * params)71 static struct command_result *json_connect(struct command *cmd,
72 const char *buffer,
73 const jsmntok_t *obj UNNEEDED,
74 const jsmntok_t *params)
75 {
76 u32 *port;
77 jsmntok_t *idtok;
78 struct node_id id;
79 char *id_str;
80 char *atptr;
81 char *ataddr = NULL;
82 const char *name;
83 struct wireaddr_internal *addr;
84 u8 *msg;
85 const char *err_msg;
86 struct peer *peer;
87
88 if (!param(cmd, buffer, params,
89 p_req("id", param_tok, (const jsmntok_t **) &idtok),
90 p_opt("host", param_string, &name),
91 p_opt("port", param_number, &port),
92 NULL))
93 return command_param_failed();
94
95 /* Check for id@addrport form */
96 id_str = json_strdup(cmd, buffer, idtok);
97 atptr = strchr(id_str, '@');
98 if (atptr) {
99 int atidx = atptr - id_str;
100 ataddr = tal_strdup(cmd, atptr + 1);
101 /* Cut id. */
102 idtok->end = idtok->start + atidx;
103 }
104
105 if (!json_to_node_id(buffer, idtok, &id)) {
106 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
107 "id %.*s not valid",
108 json_tok_full_len(idtok),
109 json_tok_full(buffer, idtok));
110 }
111
112 if (name && ataddr) {
113 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
114 "Can't specify host as both xxx@yyy "
115 "and separate argument");
116 }
117
118 /* Get parseable host if provided somehow */
119 if (!name && ataddr)
120 name = ataddr;
121
122 /* Port without host name? */
123 if (port && !name) {
124 return command_fail(cmd, JSONRPC2_INVALID_PARAMS,
125 "Can't specify port without host");
126 }
127
128 /* If we know about peer, see if it's already connected. */
129 peer = peer_by_id(cmd->ld, &id);
130 if (peer) {
131 struct channel *channel = peer_active_channel(peer);
132
133 if (!channel)
134 channel = peer_unsaved_channel(peer);
135
136 if (peer->uncommitted_channel
137 || (channel && channel->connected)) {
138 log_debug(cmd->ld->log, "Already connected via %s",
139 type_to_string(tmpctx, struct wireaddr_internal, &peer->addr));
140 return connect_cmd_succeed(cmd, peer,
141 peer->connected_incoming,
142 &peer->addr);
143 }
144 }
145
146 /* Was there parseable host name? */
147 if (name) {
148 /* Is there a port? */
149 if (!port) {
150 port = tal(cmd, u32);
151 *port = DEFAULT_PORT;
152 }
153 addr = tal(cmd, struct wireaddr_internal);
154 if (!parse_wireaddr_internal(name, addr, *port, false,
155 !cmd->ld->always_use_proxy
156 && !cmd->ld->pure_tor_setup,
157 true, deprecated_apis,
158 &err_msg)) {
159 return command_fail(cmd, LIGHTNINGD,
160 "Host %s:%u not valid: %s",
161 name, *port,
162 err_msg ? err_msg : "port is 0");
163 }
164 } else
165 addr = NULL;
166
167 msg = towire_connectd_connect_to_peer(NULL, &id, 0, addr);
168 subd_send_msg(cmd->ld->connectd, take(msg));
169
170 /* Leave this here for peer_connected or connect_failed. */
171 new_connect(cmd->ld, &id, cmd);
172 return command_still_pending(cmd);
173 }
174
175 static const struct json_command connect_command = {
176 "connect",
177 "network",
178 json_connect,
179 "Connect to {id} at {host} (which can end in ':port' if not default). "
180 "{id} can also be of the form id@host"
181 };
182 AUTODATA(json_command, &connect_command);
183
184 struct delayed_reconnect {
185 struct channel *channel;
186 u32 seconds_delayed;
187 struct wireaddr_internal *addrhint;
188 };
189
maybe_reconnect(struct delayed_reconnect * d)190 static void maybe_reconnect(struct delayed_reconnect *d)
191 {
192 struct peer *peer = d->channel->peer;
193
194 /* Might have gone onchain since we started timer. */
195 if (channel_active(d->channel)) {
196 u8 *msg = towire_connectd_connect_to_peer(NULL, &peer->id,
197 d->seconds_delayed,
198 d->addrhint);
199 subd_send_msg(peer->ld->connectd, take(msg));
200 }
201 tal_free(d);
202 }
203
delay_then_reconnect(struct channel * channel,u32 seconds_delay,const struct wireaddr_internal * addrhint)204 void delay_then_reconnect(struct channel *channel, u32 seconds_delay,
205 const struct wireaddr_internal *addrhint)
206 {
207 struct delayed_reconnect *d;
208 struct lightningd *ld = channel->peer->ld;
209
210 if (!ld->reconnect)
211 return;
212
213 d = tal(channel, struct delayed_reconnect);
214 d->channel = channel;
215 d->seconds_delayed = seconds_delay;
216 if (addrhint)
217 d->addrhint = tal_dup(d, struct wireaddr_internal, addrhint);
218 else
219 d->addrhint = NULL;
220
221 log_debug(channel->log, "Will try reconnect in %u seconds",
222 seconds_delay);
223
224 /* We fuzz the timer by up to 1 second, to avoid getting into
225 * simultanous-reconnect deadlocks with peer. */
226 notleak(new_reltimer(ld->timers, d,
227 timerel_add(time_from_sec(seconds_delay),
228 time_from_usec(pseudorand(1000000))),
229 maybe_reconnect, d));
230 }
231
connect_failed(struct lightningd * ld,const u8 * msg)232 static void connect_failed(struct lightningd *ld, const u8 *msg)
233 {
234 struct node_id id;
235 errcode_t errcode;
236 char *errmsg;
237 struct connect *c;
238 u32 seconds_to_delay;
239 struct wireaddr_internal *addrhint;
240 struct channel *channel;
241
242 if (!fromwire_connectd_connect_failed(tmpctx, msg, &id, &errcode, &errmsg,
243 &seconds_to_delay, &addrhint))
244 fatal("Connect gave bad CONNECTD_CONNECT_FAILED message %s",
245 tal_hex(msg, msg));
246
247 /* We can have multiple connect commands: fail them all */
248 while ((c = find_connect(ld, &id)) != NULL) {
249 /* They delete themselves from list */
250 was_pending(command_fail(c->cmd, errcode, "%s", errmsg));
251 }
252
253 /* If we have an active channel, then reconnect. */
254 channel = active_channel_by_id(ld, &id, NULL);
255 if (channel)
256 delay_then_reconnect(channel, seconds_to_delay, addrhint);
257 }
258
connect_succeeded(struct lightningd * ld,const struct peer * peer,bool incoming,const struct wireaddr_internal * addr)259 void connect_succeeded(struct lightningd *ld, const struct peer *peer,
260 bool incoming,
261 const struct wireaddr_internal *addr)
262 {
263 struct connect *c;
264
265 /* We can have multiple connect commands: fail them all */
266 while ((c = find_connect(ld, &peer->id)) != NULL) {
267 /* They delete themselves from list */
268 connect_cmd_succeed(c->cmd, peer, incoming, addr);
269 }
270 }
271
peer_please_disconnect(struct lightningd * ld,const u8 * msg)272 static void peer_please_disconnect(struct lightningd *ld, const u8 *msg)
273 {
274 struct node_id id;
275 struct channel *c;
276 struct uncommitted_channel *uc;
277
278 if (!fromwire_connectd_reconnected(msg, &id))
279 fatal("Bad msg %s from connectd", tal_hex(tmpctx, msg));
280
281 c = active_channel_by_id(ld, &id, &uc);
282 if (uc)
283 kill_uncommitted_channel(uc, "Reconnected");
284 else if (c) {
285 channel_cleanup_commands(c, "Reconnected");
286 channel_fail_reconnect(c, "Reconnected");
287 }
288 else if ((c = unsaved_channel_by_id(ld, &id))) {
289 log_info(c->log, "Killing opening daemon: Reconnected");
290 channel_unsaved_close_conn(c, "Reconnected");
291 }
292 }
293
connectd_msg(struct subd * connectd,const u8 * msg,const int * fds)294 static unsigned connectd_msg(struct subd *connectd, const u8 *msg, const int *fds)
295 {
296 enum connectd_wire t = fromwire_peektype(msg);
297
298 switch (t) {
299 /* These are messages we send, not them. */
300 case WIRE_CONNECTD_INIT:
301 case WIRE_CONNECTD_ACTIVATE:
302 case WIRE_CONNECTD_CONNECT_TO_PEER:
303 case WIRE_CONNECTD_PEER_DISCONNECTED:
304 case WIRE_CONNECTD_DEV_MEMLEAK:
305 case WIRE_CONNECTD_PEER_FINAL_MSG:
306 /* This is a reply, so never gets through to here. */
307 case WIRE_CONNECTD_INIT_REPLY:
308 case WIRE_CONNECTD_ACTIVATE_REPLY:
309 case WIRE_CONNECTD_DEV_MEMLEAK_REPLY:
310 break;
311
312 case WIRE_CONNECTD_RECONNECTED:
313 peer_please_disconnect(connectd->ld, msg);
314 break;
315
316 case WIRE_CONNECTD_PEER_CONNECTED:
317 if (tal_count(fds) != 3)
318 return 3;
319 peer_connected(connectd->ld, msg, fds[0], fds[1], fds[2]);
320 break;
321
322 case WIRE_CONNECTD_CONNECT_FAILED:
323 connect_failed(connectd->ld, msg);
324 break;
325 }
326 return 0;
327 }
328
connect_init_done(struct subd * connectd,const u8 * reply,const int * fds UNUSED,void * unused UNUSED)329 static void connect_init_done(struct subd *connectd,
330 const u8 *reply,
331 const int *fds UNUSED,
332 void *unused UNUSED)
333 {
334 struct lightningd *ld = connectd->ld;
335
336 if (!fromwire_connectd_init_reply(ld, reply,
337 &ld->binding,
338 &ld->announcable))
339 fatal("Bad connectd_activate_reply: %s",
340 tal_hex(reply, reply));
341
342 /* Break out of loop, so we can begin */
343 io_break(connectd);
344 }
345
connectd_init(struct lightningd * ld)346 int connectd_init(struct lightningd *ld)
347 {
348 int fds[2];
349 u8 *msg;
350 int hsmfd;
351 struct wireaddr_internal *wireaddrs = ld->proposed_wireaddr;
352 enum addr_listen_announce *listen_announce = ld->proposed_listen_announce;
353 const char *websocket_helper_path;
354
355 websocket_helper_path = subdaemon_path(tmpctx, ld,
356 "lightning_websocketd");
357
358 if (socketpair(AF_LOCAL, SOCK_STREAM, 0, fds) != 0)
359 fatal("Could not socketpair for connectd<->gossipd");
360
361 hsmfd = hsm_get_global_fd(ld, HSM_CAP_ECDH);
362
363 ld->connectd = new_global_subd(ld, "lightning_connectd",
364 connectd_wire_name, connectd_msg,
365 take(&hsmfd), take(&fds[1]), NULL);
366 if (!ld->connectd)
367 err(1, "Could not subdaemon connectd");
368
369 /* If no addr specified, hand wildcard to connectd */
370 if (tal_count(wireaddrs) == 0 && ld->autolisten) {
371 wireaddrs = tal_arrz(tmpctx, struct wireaddr_internal, 1);
372 listen_announce = tal_arr(tmpctx, enum addr_listen_announce, 1);
373 wireaddrs->itype = ADDR_INTERNAL_ALLPROTO;
374 wireaddrs->u.port = ld->portnum;
375 *listen_announce = ADDR_LISTEN_AND_ANNOUNCE;
376 }
377
378 msg = towire_connectd_init(
379 tmpctx, chainparams,
380 ld->our_features,
381 &ld->id,
382 wireaddrs,
383 listen_announce,
384 ld->proxyaddr, ld->always_use_proxy || ld->pure_tor_setup,
385 IFDEV(ld->dev_allow_localhost, false), ld->config.use_dns,
386 ld->tor_service_password ? ld->tor_service_password : "",
387 ld->config.use_v3_autotor,
388 ld->config.connection_timeout_secs,
389 websocket_helper_path,
390 ld->websocket_port);
391
392 subd_req(ld->connectd, ld->connectd, take(msg), -1, 0,
393 connect_init_done, NULL);
394
395 /* Wait for init_reply */
396 io_loop(NULL, NULL);
397
398 return fds[0];
399 }
400
connect_activate_done(struct subd * connectd,const u8 * reply UNUSED,const int * fds UNUSED,void * unused UNUSED)401 static void connect_activate_done(struct subd *connectd,
402 const u8 *reply UNUSED,
403 const int *fds UNUSED,
404 void *unused UNUSED)
405 {
406 /* Break out of loop, so we can begin */
407 io_break(connectd);
408 }
409
connectd_activate(struct lightningd * ld)410 void connectd_activate(struct lightningd *ld)
411 {
412 const u8 *msg = towire_connectd_activate(NULL, ld->listen);
413
414 subd_req(ld->connectd, ld->connectd, take(msg), -1, 0,
415 connect_activate_done, NULL);
416
417 /* Wait for activate_reply */
418 io_loop(NULL, NULL);
419 }
420
421