| 197 | } |
| 198 | |
| 199 | static struct client *new_client(const tal_t *ctx, |
| 200 | const struct chainparams *chainparams, |
| 201 | const struct node_id *id, |
| 202 | u64 dbid, |
| 203 | const u64 capabilities, |
| 204 | int fd) |
| 205 | { |
| 206 | struct client *c = tal(ctx, struct client); |
| 207 | |
| 208 | c->msg_in = NULL; |
| 209 | c->sent_fd = NULL; |
| 210 | |
| 211 | /*~ All-zero pubkey is used for the initial master connection */ |
| 212 | if (id) { |
| 213 | c->id = *id; |
| 214 | if (!node_id_valid(id)) |
| 215 | status_failed(STATUS_FAIL_INTERNAL_ERROR, |
| 216 | "Invalid node id %s", |
| 217 | fmt_node_id(tmpctx, id)); |
| 218 | } else { |
| 219 | memset(&c->id, 0, sizeof(c->id)); |
| 220 | } |
| 221 | c->dbid = dbid; |
| 222 | |
| 223 | c->capabilities = capabilities; |
| 224 | c->chainparams = chainparams; |
| 225 | |
| 226 | /*~ This is the core of ccan/io: the connection creation calls a |
| 227 | * callback which returns the initial plan to execute: in our case, |
| 228 | * read a message.*/ |
| 229 | c->conn = io_new_conn(ctx, fd, client_read_next, c); |
| 230 | |
| 231 | /*~ tal_steal() moves a pointer to a new parent. At this point, the |
| 232 | * hierarchy is: |
| 233 | * |
| 234 | * ctx -> c |
| 235 | * ctx -> c->conn |
| 236 | * |
| 237 | * We want to the c->conn to own 'c', so that if the io_conn closes, |
| 238 | * the client is freed: |
| 239 | * |
| 240 | * ctx -> c->conn -> c. |
| 241 | */ |
| 242 | tal_steal(c->conn, c); |
| 243 | |
| 244 | /* We put the special zero-db HSM connections into an array, the rest |
| 245 | * go into the map. */ |
| 246 | if (dbid == 0) { |
| 247 | assert(num_dbid_zero_clients < ARRAY_SIZE(dbid_zero_clients)); |
| 248 | dbid_zero_clients[num_dbid_zero_clients++] = c; |
| 249 | c->hsmd_client = hsmd_client_new_main(c, c->capabilities, c); |
| 250 | } else { |
| 251 | struct client *old_client = uintmap_get(&clients, dbid); |
| 252 | |
| 253 | /* Close conn and free any old client of this dbid. */ |
| 254 | if (old_client) |
| 255 | io_close(old_client->conn); |
| 256 | |