| 1308 | } |
| 1309 | |
| 1310 | static struct io_plan *write_to_peer(struct io_conn *peer_conn, |
| 1311 | struct peer *peer) |
| 1312 | { |
| 1313 | bool do_flush; |
| 1314 | assert(peer->to_peer == peer_conn); |
| 1315 | |
| 1316 | /* We always pad and send if we have an urgent msg or our |
| 1317 | * non-urgent has gone off, or we're trying to close. */ |
| 1318 | do_flush = (peer->peer_out_urgent != 0 |
| 1319 | || peer->flushing_nonurgent |
| 1320 | || peer->draining_state == WRITING_TO_PEER); |
| 1321 | |
| 1322 | peer->flushing_nonurgent = false; |
| 1323 | |
| 1324 | /* We wrote out some bytes from membuf. */ |
| 1325 | membuf_consume(&peer->encrypted_peer_out, peer->encrypted_peer_out_sent); |
| 1326 | peer->encrypted_peer_out_sent = 0; |
| 1327 | |
| 1328 | while (!have_full_encrypted_queue(peer)) { |
| 1329 | const u8 *msg; |
| 1330 | struct io_plan *dev_override; |
| 1331 | |
| 1332 | /* Pop tail of send queue (or gossip) */ |
| 1333 | msg = next_msg_for_peer(peer); |
| 1334 | if (!msg) { |
| 1335 | /* Draining? Shutdown socket (to avoid losing msgs) */ |
| 1336 | if (have_empty_encrypted_queue(peer) |
| 1337 | && peer->draining_state == WRITING_TO_PEER) { |
| 1338 | status_peer_debug(&peer->id, "draining done, shutting down"); |
| 1339 | io_wake(&peer->peer_in); |
| 1340 | return io_sock_shutdown(peer_conn); |
| 1341 | } |
| 1342 | |
| 1343 | /* If no urgent message, and not draining, we wait. */ |
| 1344 | if (!do_flush) { |
| 1345 | /* Tell them to read again, */ |
| 1346 | io_wake(&peer->subds); |
| 1347 | io_wake(&peer->peer_in); |
| 1348 | |
| 1349 | /* Set up a timer if not already set */ |
| 1350 | if (!have_empty_encrypted_queue(peer) |
| 1351 | && !peer->nonurgent_flush_timer) { |
| 1352 | /* Bias towards larger values, but don't be too predictable */ |
| 1353 | u32 max = pseudorand(1000); |
| 1354 | u32 msec = 1000 - pseudorand(1 + max); |
| 1355 | peer->nonurgent_flush_timer |
| 1356 | = new_reltimer(&peer->daemon->timers, |
| 1357 | peer, |
| 1358 | time_from_msec(msec), |
| 1359 | nonurgent_flush, peer); |
| 1360 | } |
| 1361 | |
| 1362 | /* Wait for them to wake us */ |
| 1363 | return msg_queue_wait(peer_conn, peer->peer_outq, write_to_peer, peer); |
| 1364 | } |
| 1365 | /* OK, add padding (only if supported). */ |
| 1366 | if (use_uniform_writes(peer)) |
| 1367 | pad_encrypted_queue(peer); |
no test coverage detected