3 #include <netinet/in.h>
10 #include <sys/sendfile.h>
11 #include <sys/socket.h>
12 #include <sys/types.h>
20 #include "accesslog.h"
23 #include "metacube2.h"
24 #include "mutexlock.h"
31 #ifndef SO_MAX_PACING_RATE
32 #define SO_MAX_PACING_RATE 47
37 extern AccessLogThread *access_log;
41 pthread_mutex_init(&mutex, NULL);
42 pthread_mutex_init(&queued_clients_mutex, NULL);
44 epoll_fd = epoll_create(1024); // Size argument is ignored.
46 log_perror("epoll_fd");
53 for (size_t i = 0; i < streams.size(); ++i) {
60 vector<ClientStats> Server::get_client_stats() const
62 vector<ClientStats> ret;
64 MutexLock lock(&mutex);
65 for (map<int, Client>::const_iterator client_it = clients.begin();
66 client_it != clients.end();
68 ret.push_back(client_it->second.get_stats());
73 void Server::do_work()
75 while (!should_stop()) {
76 // Wait until there's activity on at least one of the fds,
77 // or 20 ms (about one frame at 50 fps) has elapsed.
79 // We could in theory wait forever and rely on wakeup()
80 // from add_client_deferred() and add_data_deferred(),
81 // but wakeup is a pretty expensive operation, and the
82 // two threads might end up fighting over a lock, so it's
83 // seemingly (much) more efficient to just have a timeout here.
84 int nfds = epoll_pwait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS, &sigset_without_usr1_block);
85 if (nfds == -1 && errno != EINTR) {
86 log_perror("epoll_wait");
90 MutexLock lock(&mutex); // We release the mutex between iterations.
92 process_queued_data();
94 for (int i = 0; i < nfds; ++i) {
95 Client *client = reinterpret_cast<Client *>(events[i].data.u64);
97 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
102 process_client(client);
105 for (size_t i = 0; i < streams.size(); ++i) {
106 vector<Client *> to_process;
107 swap(streams[i]->to_process, to_process);
108 for (size_t i = 0; i < to_process.size(); ++i) {
109 process_client(to_process[i]);
115 CubemapStateProto Server::serialize()
117 // We don't serialize anything queued, so empty the queues.
118 process_queued_data();
120 // Set all clients in a consistent state before serializing
121 // (ie., they have no remaining lost data). Otherwise, increasing
122 // the backlog could take clients into a newly valid area of the backlog,
123 // sending a stream of zeros instead of skipping the data as it should.
125 // TODO: Do this when clients are added back from serialized state instead;
126 // it would probably be less wasteful.
127 for (map<int, Client>::iterator client_it = clients.begin();
128 client_it != clients.end();
130 skip_lost_data(&client_it->second);
133 CubemapStateProto serialized;
134 for (map<int, Client>::const_iterator client_it = clients.begin();
135 client_it != clients.end();
137 serialized.add_clients()->MergeFrom(client_it->second.serialize());
139 for (size_t i = 0; i < streams.size(); ++i) {
140 serialized.add_streams()->MergeFrom(streams[i]->serialize());
145 void Server::add_client_deferred(int sock)
147 MutexLock lock(&queued_clients_mutex);
148 queued_add_clients.push_back(sock);
151 void Server::add_client(int sock)
153 pair<map<int, Client>::iterator, bool> ret =
154 clients.insert(make_pair(sock, Client(sock)));
155 assert(ret.second == true); // Should not already exist.
156 Client *client_ptr = &ret.first->second;
158 // Start listening on data from this socket.
160 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
161 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
162 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
163 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
167 process_client(client_ptr);
170 void Server::add_client_from_serialized(const ClientProto &client)
172 MutexLock lock(&mutex);
174 int stream_index = lookup_stream_by_url(client.url());
175 if (stream_index == -1) {
176 assert(client.state() != Client::SENDING_DATA);
179 stream = streams[stream_index];
181 pair<map<int, Client>::iterator, bool> ret =
182 clients.insert(make_pair(client.sock(), Client(client, stream)));
183 assert(ret.second == true); // Should not already exist.
184 Client *client_ptr = &ret.first->second;
186 // Start listening on data from this socket.
188 if (client.state() == Client::READING_REQUEST) {
189 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
191 // If we don't have more data for this client, we'll be putting it into
192 // the sleeping array again soon.
193 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
195 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
196 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
197 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
201 if (client_ptr->state == Client::WAITING_FOR_KEYFRAME ||
202 (client_ptr->state == Client::SENDING_DATA &&
203 client_ptr->stream_pos == client_ptr->stream->bytes_received)) {
204 client_ptr->stream->put_client_to_sleep(client_ptr);
206 process_client(client_ptr);
210 int Server::lookup_stream_by_url(const std::string &url) const
212 map<string, int>::const_iterator url_it = url_map.find(url);
213 if (url_it == url_map.end()) {
216 return url_it->second;
219 int Server::add_stream(const string &url, size_t backlog_size, Stream::Encoding encoding)
221 MutexLock lock(&mutex);
222 url_map.insert(make_pair(url, streams.size()));
223 streams.push_back(new Stream(url, backlog_size, encoding));
224 return streams.size() - 1;
227 int Server::add_stream_from_serialized(const StreamProto &stream, int data_fd)
229 MutexLock lock(&mutex);
230 url_map.insert(make_pair(stream.url(), streams.size()));
231 streams.push_back(new Stream(stream, data_fd));
232 return streams.size() - 1;
235 void Server::set_backlog_size(int stream_index, size_t new_size)
237 MutexLock lock(&mutex);
238 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
239 streams[stream_index]->set_backlog_size(new_size);
242 void Server::set_encoding(int stream_index, Stream::Encoding encoding)
244 MutexLock lock(&mutex);
245 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
246 streams[stream_index]->encoding = encoding;
249 void Server::set_header(int stream_index, const string &http_header, const string &stream_header)
251 MutexLock lock(&mutex);
252 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
253 streams[stream_index]->http_header = http_header;
254 streams[stream_index]->stream_header = stream_header;
257 void Server::set_mark_pool(int stream_index, MarkPool *mark_pool)
259 MutexLock lock(&mutex);
260 assert(clients.empty());
261 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
262 streams[stream_index]->mark_pool = mark_pool;
265 void Server::set_pacing_rate(int stream_index, uint32_t pacing_rate)
267 MutexLock lock(&mutex);
268 assert(clients.empty());
269 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
270 streams[stream_index]->pacing_rate = pacing_rate;
273 void Server::add_data_deferred(int stream_index, const char *data, size_t bytes, StreamStartSuitability suitable_for_stream_start)
275 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
276 streams[stream_index]->add_data_deferred(data, bytes, suitable_for_stream_start);
279 // See the .h file for postconditions after this function.
280 void Server::process_client(Client *client)
282 switch (client->state) {
283 case Client::READING_REQUEST: {
285 // Try to read more of the request.
289 ret = read(client->sock, buf, sizeof(buf));
290 } while (ret == -1 && errno == EINTR);
292 if (ret == -1 && errno == EAGAIN) {
293 // No more data right now. Nothing to do.
294 // This is postcondition #2.
299 close_client(client);
303 // OK, the socket is closed.
304 close_client(client);
308 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
311 case RP_OUT_OF_SPACE:
312 log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
313 close_client(client);
315 case RP_NOT_FINISHED_YET:
316 // OK, we don't have the entire header yet. Fine; we'll get it later.
317 // See if there's more data for us.
318 goto read_request_again;
320 log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
321 close_client(client);
327 assert(status == RP_FINISHED);
329 int error_code = parse_request(client);
330 if (error_code == 200) {
331 construct_header(client);
333 construct_error(client, error_code);
336 // We've changed states, so fall through.
337 assert(client->state == Client::SENDING_ERROR ||
338 client->state == Client::SENDING_HEADER);
340 case Client::SENDING_ERROR:
341 case Client::SENDING_HEADER: {
342 sending_header_or_error_again:
345 ret = write(client->sock,
346 client->header_or_error.data() + client->header_or_error_bytes_sent,
347 client->header_or_error.size() - client->header_or_error_bytes_sent);
348 } while (ret == -1 && errno == EINTR);
350 if (ret == -1 && errno == EAGAIN) {
351 // We're out of socket space, so now we're at the “low edge” of epoll's
352 // edge triggering. epoll will tell us when there is more room, so for now,
354 // This is postcondition #4.
359 // Error! Postcondition #1.
361 close_client(client);
365 client->header_or_error_bytes_sent += ret;
366 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
368 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
369 // We haven't sent all yet. Fine; go another round.
370 goto sending_header_or_error_again;
373 // We're done sending the header or error! Clear it to release some memory.
374 client->header_or_error.clear();
376 if (client->state == Client::SENDING_ERROR) {
377 // We're done sending the error, so now close.
378 // This is postcondition #1.
379 close_client(client);
383 // Start sending from the first keyframe we get. In other
384 // words, we won't send any of the backlog, but we'll start
385 // sending immediately as we get the next keyframe block.
386 // This is postcondition #3.
387 if (client->stream_pos == size_t(-2)) {
388 client->stream_pos = std::min<size_t>(
389 client->stream->bytes_received - client->stream->backlog_size,
391 client->state = Client::SENDING_DATA;
393 // client->stream_pos should be -1, but it might not be,
394 // if we have clients from an older version.
395 client->stream_pos = client->stream->bytes_received;
396 client->state = Client::WAITING_FOR_KEYFRAME;
398 client->stream->put_client_to_sleep(client);
401 case Client::WAITING_FOR_KEYFRAME: {
402 Stream *stream = client->stream;
403 if (ssize_t(client->stream_pos) > stream->last_suitable_starting_point) {
404 // We haven't received a keyframe since this stream started waiting,
405 // so keep on waiting for one.
406 // This is postcondition #3.
407 stream->put_client_to_sleep(client);
410 client->stream_pos = stream->last_suitable_starting_point;
411 client->state = Client::SENDING_DATA;
414 case Client::SENDING_DATA: {
415 skip_lost_data(client);
416 Stream *stream = client->stream;
419 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
420 assert(bytes_to_send <= stream->backlog_size);
421 if (bytes_to_send == 0) {
425 // See if we need to split across the circular buffer.
426 bool more_data = false;
427 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
428 bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
434 off_t offset = client->stream_pos % stream->backlog_size;
435 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
436 } while (ret == -1 && errno == EINTR);
438 if (ret == -1 && errno == EAGAIN) {
439 // We're out of socket space, so return; epoll will wake us up
440 // when there is more room.
441 // This is postcondition #4.
445 // Error, close; postcondition #1.
446 log_perror("sendfile");
447 close_client(client);
450 client->stream_pos += ret;
451 client->bytes_sent += ret;
453 if (client->stream_pos == stream->bytes_received) {
454 // We don't have any more data for this client, so put it to sleep.
455 // This is postcondition #3.
456 stream->put_client_to_sleep(client);
457 } else if (more_data && size_t(ret) == bytes_to_send) {
458 goto sending_data_again;
467 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
468 // but resync will be the mux's problem.
469 void Server::skip_lost_data(Client *client)
471 Stream *stream = client->stream;
472 if (stream == NULL) {
475 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
476 if (bytes_to_send > stream->backlog_size) {
477 size_t bytes_lost = bytes_to_send - stream->backlog_size;
478 client->stream_pos = stream->bytes_received - stream->backlog_size;
479 client->bytes_lost += bytes_lost;
480 ++client->num_loss_events;
484 int Server::parse_request(Client *client)
486 vector<string> lines = split_lines(client->request);
488 return 400; // Bad request (empty).
491 vector<string> request_tokens = split_tokens(lines[0]);
492 if (request_tokens.size() < 2) {
493 return 400; // Bad request (empty).
495 if (request_tokens[0] != "GET") {
496 return 400; // Should maybe be 405 instead?
499 string url = request_tokens[1];
500 if (url.find("?backlog") == url.size() - 8) {
501 client->stream_pos = -2;
502 url = url.substr(0, url.size() - 8);
504 client->stream_pos = -1;
507 map<string, int>::const_iterator url_map_it = url_map.find(url);
508 if (url_map_it == url_map.end()) {
509 return 404; // Not found.
512 Stream *stream = streams[url_map_it->second];
513 if (stream->http_header.empty()) {
514 return 503; // Service unavailable.
517 client->url = request_tokens[1];
518 client->stream = stream;
519 if (client->stream->mark_pool != NULL) {
520 client->fwmark = client->stream->mark_pool->get_mark();
522 client->fwmark = 0; // No mark.
524 if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {
525 if (client->fwmark != 0) {
526 log_perror("setsockopt(SO_MARK)");
529 if (setsockopt(client->sock, SOL_SOCKET, SO_MAX_PACING_RATE, &client->stream->pacing_rate, sizeof(client->stream->pacing_rate)) == -1) {
530 if (client->stream->pacing_rate != ~0U) {
531 log_perror("setsockopt(SO_MAX_PACING_RATE)");
534 client->request.clear();
539 void Server::construct_header(Client *client)
541 Stream *stream = client->stream;
542 if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
543 client->header_or_error = stream->http_header +
545 stream->stream_header;
546 } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
547 client->header_or_error = stream->http_header +
548 "Content-encoding: metacube\r\n" +
550 if (!stream->stream_header.empty()) {
551 metacube2_block_header hdr;
552 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
553 hdr.size = htonl(stream->stream_header.size());
554 hdr.flags = htons(METACUBE_FLAGS_HEADER);
555 hdr.csum = htons(metacube2_compute_crc(&hdr));
556 client->header_or_error.append(
557 string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
559 client->header_or_error.append(stream->stream_header);
565 client->state = Client::SENDING_HEADER;
568 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
569 ev.data.u64 = reinterpret_cast<uint64_t>(client);
571 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
572 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
577 void Server::construct_error(Client *client, int error_code)
580 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
582 client->header_or_error = error;
585 client->state = Client::SENDING_ERROR;
588 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
589 ev.data.u64 = reinterpret_cast<uint64_t>(client);
591 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
592 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
598 void delete_from(vector<T> *v, T elem)
600 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
601 v->erase(new_end, v->end());
604 void Server::close_client(Client *client)
606 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
607 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
611 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
612 if (client->stream != NULL) {
613 delete_from(&client->stream->sleeping_clients, client);
614 delete_from(&client->stream->to_process, client);
615 if (client->stream->mark_pool != NULL) {
616 int fwmark = client->fwmark;
617 client->stream->mark_pool->release_mark(fwmark);
621 // Log to access_log.
622 access_log->write(client->get_stats());
625 safe_close(client->sock);
627 clients.erase(client->sock);
630 void Server::process_queued_data()
633 MutexLock lock(&queued_clients_mutex);
635 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
636 add_client(queued_add_clients[i]);
638 queued_add_clients.clear();
641 for (size_t i = 0; i < streams.size(); ++i) {
642 streams[i]->process_queued_data();