| 1282 | } |
| 1283 | |
| 1284 | static struct io_plan *write_to_peer(struct io_conn *peer_conn, |
| 1285 | struct peer *peer) |
| 1286 | { |
| 1287 | bool do_flush; |
| 1288 | assert(peer->to_peer == peer_conn); |
| 1289 | |
| 1290 | /* We always pad and send if we have an urgent msg or our |
| 1291 | * non-urgent has gone off, or we're trying to close. */ |
| 1292 | do_flush = (peer->peer_out_urgent != 0 |
| 1293 | || peer->flushing_nonurgent |
| 1294 | || peer->draining_state == WRITING_TO_PEER); |
| 1295 | |
| 1296 | peer->flushing_nonurgent = false; |
| 1297 | |
| 1298 | /* We wrote out some bytes from membuf. */ |
| 1299 | membuf_consume(&peer->encrypted_peer_out, peer->encrypted_peer_out_sent); |
| 1300 | peer->encrypted_peer_out_sent = 0; |
| 1301 | |
| 1302 | while (!have_full_encrypted_queue(peer)) { |
| 1303 | const u8 *msg; |
| 1304 | struct io_plan *dev_override; |
| 1305 | |
| 1306 | /* Pop tail of send queue (or gossip) */ |
| 1307 | msg = next_msg_for_peer(peer); |
| 1308 | if (!msg) { |
| 1309 | /* Draining? Shutdown socket (to avoid losing msgs) */ |
| 1310 | if (have_empty_encrypted_queue(peer) |
| 1311 | && peer->draining_state == WRITING_TO_PEER) { |
| 1312 | status_peer_debug(&peer->id, "draining done, shutting down"); |
| 1313 | io_wake(&peer->peer_in); |
| 1314 | return io_sock_shutdown(peer_conn); |
| 1315 | } |
| 1316 | |
| 1317 | /* If no urgent message, and not draining, we wait. */ |
| 1318 | if (!do_flush) { |
| 1319 | /* Tell them to read again, */ |
| 1320 | io_wake(&peer->subds); |
| 1321 | io_wake(&peer->peer_in); |
| 1322 | |
| 1323 | /* Set up a timer if not already set */ |
| 1324 | if (!have_empty_encrypted_queue(peer) |
| 1325 | && !peer->nonurgent_flush_timer) { |
| 1326 | /* Bias towards larger values, but don't be too predictable */ |
| 1327 | u32 max = pseudorand(1000); |
| 1328 | u32 msec = 1000 - pseudorand(1 + max); |
| 1329 | peer->nonurgent_flush_timer |
| 1330 | = new_reltimer(&peer->daemon->timers, |
| 1331 | peer, |
| 1332 | time_from_msec(msec), |
| 1333 | nonurgent_flush, peer); |
| 1334 | } |
| 1335 | |
| 1336 | /* Wait for them to wake us */ |
| 1337 | return msg_queue_wait(peer_conn, peer->peer_outq, write_to_peer, peer); |
| 1338 | } |
| 1339 | /* OK, add padding (only if supported). */ |
| 1340 | if (use_uniform_writes(peer)) |
| 1341 | pad_encrypted_queue(peer); |
no test coverage detected