+ client->stream_pos = client->stream->bytes_received;
+ client->stream->put_client_to_sleep(client);
+ return;
+ }
+ case Client::SENDING_DATA: {
+sending_data_again:
+ // See if there's some data we've lost. Ideally, we should drop to a block boundary,
+ // but resync will be the mux's problem.
+ Stream *stream = client->stream;
+ size_t bytes_to_send = stream->bytes_received - client->stream_pos;
+ if (bytes_to_send == 0) {
+ return;
+ }
+ if (bytes_to_send > stream->backlog_size) {
+ log(WARNING, "[%s] Client lost %lld bytes, maybe too slow connection",
+ client->remote_addr.c_str(),
+ (long long int)(bytes_to_send - stream->backlog_size));
+ client->stream_pos = stream->bytes_received - stream->backlog_size;
+ client->bytes_lost += bytes_to_send - stream->backlog_size;
+ ++client->num_loss_events;
+ bytes_to_send = stream->backlog_size;
+ }
+
+ // See if we need to split across the circular buffer.
+ bool more_data = false;
+ if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
+ bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
+ more_data = true;
+ }
+
+ ssize_t ret;
+ do {
+ loff_t offset = client->stream_pos % stream->backlog_size;
+ ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
+ } while (ret == -1 && errno == EINTR);
+
+ if (ret == -1 && errno == EAGAIN) {
+ // We're out of socket space, so return; epoll will wake us up
+ // when there is more room.
+ // This is postcondition #4.
+ return;
+ }
+ if (ret == -1) {
+ // Error, close; postcondition #1.
+ log_perror("sendfile");
+ close_client(client);
+ return;
+ }
+ client->stream_pos += ret;
+ client->bytes_sent += ret;
+
+ if (client->stream_pos == stream->bytes_received) {
+ // We don't have any more data for this client, so put it to sleep.
+ // This is postcondition #3.
+ stream->put_client_to_sleep(client);
+ } else if (more_data && size_t(ret) == bytes_to_send) {
+ goto sending_data_again;
+ }
+ break;