| 1212 | } |
| 1213 | |
| 1214 | static struct io_plan *write_to_peer(struct io_conn *peer_conn, |
| 1215 | struct peer *peer) |
| 1216 | { |
| 1217 | bool do_flush; |
| 1218 | assert(peer->to_peer == peer_conn); |
| 1219 | |
| 1220 | /* We always pad and send if we have an urgent msg or our |
| 1221 | * non-urgent has gone off, or we're trying to close. */ |
| 1222 | do_flush = (peer->peer_out_urgent != 0 |
| 1223 | || peer->flushing_nonurgent |
| 1224 | || peer->draining_state == WRITING_TO_PEER); |
| 1225 | |
| 1226 | peer->flushing_nonurgent = false; |
| 1227 | |
| 1228 | /* We wrote out some bytes from membuf. */ |
| 1229 | membuf_consume(&peer->encrypted_peer_out, peer->encrypted_peer_out_sent); |
| 1230 | peer->encrypted_peer_out_sent = 0; |
| 1231 | |
| 1232 | while (!have_full_encrypted_queue(peer)) { |
| 1233 | const u8 *msg; |
| 1234 | struct io_plan *dev_override; |
| 1235 | |
| 1236 | /* Pop tail of send queue (or gossip) */ |
| 1237 | msg = next_msg_for_peer(peer); |
| 1238 | if (!msg) { |
| 1239 | /* Draining? Shutdown socket (to avoid losing msgs) */ |
| 1240 | if (have_empty_encrypted_queue(peer) |
| 1241 | && peer->draining_state == WRITING_TO_PEER) { |
| 1242 | status_peer_debug(&peer->id, "draining done, shutting down"); |
| 1243 | io_wake(&peer->peer_in); |
| 1244 | return io_sock_shutdown(peer_conn); |
| 1245 | } |
| 1246 | |
| 1247 | /* If no urgent message, and not draining, we wait. */ |
| 1248 | if (!do_flush) { |
| 1249 | /* Tell them to read again, */ |
| 1250 | io_wake(&peer->subds); |
| 1251 | io_wake(&peer->peer_in); |
| 1252 | |
| 1253 | /* Set up a timer if not already set */ |
| 1254 | if (!have_empty_encrypted_queue(peer) |
| 1255 | && !peer->nonurgent_flush_timer) { |
| 1256 | /* Bias towards larger values, but don't be too predictable */ |
| 1257 | u32 max = pseudorand(1000); |
| 1258 | u32 msec = 1000 - pseudorand(1 + max); |
| 1259 | peer->nonurgent_flush_timer |
| 1260 | = new_reltimer(&peer->daemon->timers, |
| 1261 | peer, |
| 1262 | time_from_msec(msec), |
| 1263 | nonurgent_flush, peer); |
| 1264 | } |
| 1265 | |
| 1266 | /* Wait for them to wake us */ |
| 1267 | return msg_queue_wait(peer_conn, peer->peer_outq, write_to_peer, peer); |
| 1268 | } |
| 1269 | /* OK, add padding (only if supported). */ |
| 1270 | if (use_uniform_writes(peer)) |
| 1271 | pad_encrypted_queue(peer); |
no test coverage detected