3 #include <netinet/in.h>
10 #include <sys/sendfile.h>
11 #include <sys/socket.h>
12 #include <sys/types.h>
20 #include "accesslog.h"
22 #include "metacube2.h"
23 #include "mutexlock.h"
30 #ifndef SO_MAX_PACING_RATE
31 #define SO_MAX_PACING_RATE 47
36 extern AccessLogThread *access_log;
40 inline bool is_equal(timespec a, timespec b)
42 return a.tv_sec == b.tv_sec &&
43 a.tv_nsec == b.tv_nsec;
46 inline bool is_earlier(timespec a, timespec b)
48 if (a.tv_sec != b.tv_sec)
49 return a.tv_sec < b.tv_sec;
50 return a.tv_nsec < b.tv_nsec;
57 pthread_mutex_init(&mutex, NULL);
58 pthread_mutex_init(&queued_clients_mutex, NULL);
60 epoll_fd = epoll_create(1024); // Size argument is ignored.
62 log_perror("epoll_fd");
69 for (size_t i = 0; i < streams.size(); ++i) {
76 vector<ClientStats> Server::get_client_stats() const
78 vector<ClientStats> ret;
80 MutexLock lock(&mutex);
81 for (map<int, Client>::const_iterator client_it = clients.begin();
82 client_it != clients.end();
84 ret.push_back(client_it->second.get_stats());
89 void Server::do_work()
91 while (!should_stop()) {
92 // Wait until there's activity on at least one of the fds,
93 // or 20 ms (about one frame at 50 fps) has elapsed.
95 // We could in theory wait forever and rely on wakeup()
96 // from add_client_deferred() and add_data_deferred(),
97 // but wakeup is a pretty expensive operation, and the
98 // two threads might end up fighting over a lock, so it's
99 // seemingly (much) more efficient to just have a timeout here.
100 int nfds = epoll_pwait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS, &sigset_without_usr1_block);
101 if (nfds == -1 && errno != EINTR) {
102 log_perror("epoll_wait");
106 MutexLock lock(&mutex); // We release the mutex between iterations.
108 process_queued_data();
110 // Process each client where we have socket activity.
111 for (int i = 0; i < nfds; ++i) {
112 Client *client = reinterpret_cast<Client *>(events[i].data.u64);
114 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
115 close_client(client);
119 process_client(client);
122 // Process each client where its stream has new data,
123 // even if there was no socket activity.
124 for (size_t i = 0; i < streams.size(); ++i) {
125 vector<Client *> to_process;
126 swap(streams[i]->to_process, to_process);
127 for (size_t i = 0; i < to_process.size(); ++i) {
128 process_client(to_process[i]);
132 // Finally, go through each client to see if it's timed out
133 // in the READING_REQUEST state. (Seemingly there are clients
134 // that can hold sockets up for days at a time without sending
136 timespec timeout_time;
137 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &timeout_time) == -1) {
138 log_perror("clock_gettime(CLOCK_MONOTONIC_COARSE)");
141 timeout_time.tv_sec -= REQUEST_READ_TIMEOUT_SEC;
142 while (!clients_ordered_by_connect_time.empty()) {
143 const pair<timespec, int> &connect_time_and_fd = clients_ordered_by_connect_time.front();
145 // See if we have reached the end of clients to process.
146 if (is_earlier(timeout_time, connect_time_and_fd.first)) {
150 // If this client doesn't exist anymore, just ignore it
151 // (it was deleted earlier).
152 map<int, Client>::iterator client_it = clients.find(connect_time_and_fd.second);
153 if (client_it == clients.end()) {
154 clients_ordered_by_connect_time.pop();
157 Client *client = &client_it->second;
158 if (!is_equal(client->connect_time, connect_time_and_fd.first)) {
159 // Another client has taken this fd in the meantime.
160 clients_ordered_by_connect_time.pop();
164 if (client->state != Client::READING_REQUEST) {
165 // Only READING_REQUEST can time out.
166 clients_ordered_by_connect_time.pop();
171 close_client(client);
172 clients_ordered_by_connect_time.pop();
177 CubemapStateProto Server::serialize()
179 // We don't serialize anything queued, so empty the queues.
180 process_queued_data();
182 // Set all clients in a consistent state before serializing
183 // (ie., they have no remaining lost data). Otherwise, increasing
184 // the backlog could take clients into a newly valid area of the backlog,
185 // sending a stream of zeros instead of skipping the data as it should.
187 // TODO: Do this when clients are added back from serialized state instead;
188 // it would probably be less wasteful.
189 for (map<int, Client>::iterator client_it = clients.begin();
190 client_it != clients.end();
192 skip_lost_data(&client_it->second);
195 CubemapStateProto serialized;
196 for (map<int, Client>::const_iterator client_it = clients.begin();
197 client_it != clients.end();
199 serialized.add_clients()->MergeFrom(client_it->second.serialize());
201 for (size_t i = 0; i < streams.size(); ++i) {
202 serialized.add_streams()->MergeFrom(streams[i]->serialize());
207 void Server::add_client_deferred(int sock)
209 MutexLock lock(&queued_clients_mutex);
210 queued_add_clients.push_back(sock);
213 void Server::add_client(int sock)
215 pair<map<int, Client>::iterator, bool> ret =
216 clients.insert(make_pair(sock, Client(sock)));
217 assert(ret.second == true); // Should not already exist.
218 Client *client_ptr = &ret.first->second;
220 // Connection timestamps must be nondecreasing. I can't find any guarantee
221 // that even the monotonic clock can't go backwards by a small amount
222 // (think switching between CPUs with non-synchronized TSCs), so if
223 // this actually should happen, we hack around it by fudging
225 if (!clients_ordered_by_connect_time.empty() &&
226 is_earlier(client_ptr->connect_time, clients_ordered_by_connect_time.back().first)) {
227 client_ptr->connect_time = clients_ordered_by_connect_time.back().first;
229 clients_ordered_by_connect_time.push(make_pair(client_ptr->connect_time, sock));
231 // Start listening on data from this socket.
233 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
234 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
235 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
236 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
240 process_client(client_ptr);
243 void Server::add_client_from_serialized(const ClientProto &client)
245 MutexLock lock(&mutex);
247 int stream_index = lookup_stream_by_url(client.url());
248 if (stream_index == -1) {
249 assert(client.state() != Client::SENDING_DATA);
252 stream = streams[stream_index];
254 pair<map<int, Client>::iterator, bool> ret =
255 clients.insert(make_pair(client.sock(), Client(client, stream)));
256 assert(ret.second == true); // Should not already exist.
257 Client *client_ptr = &ret.first->second;
259 // Connection timestamps must be nondecreasing.
260 assert(clients_ordered_by_connect_time.empty() ||
261 !is_earlier(client_ptr->connect_time, clients_ordered_by_connect_time.back().first));
262 clients_ordered_by_connect_time.push(make_pair(client_ptr->connect_time, client.sock()));
264 // Start listening on data from this socket.
266 if (client.state() == Client::READING_REQUEST) {
267 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
269 // If we don't have more data for this client, we'll be putting it into
270 // the sleeping array again soon.
271 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
273 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
274 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
275 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
279 if (client_ptr->state == Client::WAITING_FOR_KEYFRAME ||
280 client_ptr->state == Client::PREBUFFERING ||
281 (client_ptr->state == Client::SENDING_DATA &&
282 client_ptr->stream_pos == client_ptr->stream->bytes_received)) {
283 client_ptr->stream->put_client_to_sleep(client_ptr);
285 process_client(client_ptr);
289 int Server::lookup_stream_by_url(const string &url) const
291 map<string, int>::const_iterator stream_url_it = stream_url_map.find(url);
292 if (stream_url_it == stream_url_map.end()) {
295 return stream_url_it->second;
298 int Server::add_stream(const string &url, size_t backlog_size, size_t prebuffering_bytes, Stream::Encoding encoding)
300 MutexLock lock(&mutex);
301 stream_url_map.insert(make_pair(url, streams.size()));
302 streams.push_back(new Stream(url, backlog_size, prebuffering_bytes, encoding));
303 return streams.size() - 1;
306 int Server::add_stream_from_serialized(const StreamProto &stream, int data_fd)
308 MutexLock lock(&mutex);
309 stream_url_map.insert(make_pair(stream.url(), streams.size()));
310 streams.push_back(new Stream(stream, data_fd));
311 return streams.size() - 1;
314 void Server::set_backlog_size(int stream_index, size_t new_size)
316 MutexLock lock(&mutex);
317 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
318 streams[stream_index]->set_backlog_size(new_size);
321 void Server::set_prebuffering_bytes(int stream_index, size_t new_amount)
323 MutexLock lock(&mutex);
324 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
325 streams[stream_index]->prebuffering_bytes = new_amount;
328 void Server::set_encoding(int stream_index, Stream::Encoding encoding)
330 MutexLock lock(&mutex);
331 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
332 streams[stream_index]->encoding = encoding;
335 void Server::set_header(int stream_index, const string &http_header, const string &stream_header)
337 MutexLock lock(&mutex);
338 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
339 streams[stream_index]->http_header = http_header;
341 if (stream_header != streams[stream_index]->stream_header) {
342 // We cannot start at any of the older starting points anymore,
343 // since they'd get the wrong header for the stream (not to mention
344 // that a changed header probably means the stream restarted,
345 // which means any client starting on the old one would probably
346 // stop playing properly at the change point). Next block
347 // should be a suitable starting point (if not, something is
348 // pretty strange), so it will fill up again soon enough.
349 streams[stream_index]->suitable_starting_points.clear();
351 streams[stream_index]->stream_header = stream_header;
354 void Server::set_pacing_rate(int stream_index, uint32_t pacing_rate)
356 MutexLock lock(&mutex);
357 assert(clients.empty());
358 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
359 streams[stream_index]->pacing_rate = pacing_rate;
362 void Server::add_gen204(const std::string &url, const std::string &allow_origin)
364 MutexLock lock(&mutex);
365 assert(clients.empty());
366 ping_url_map[url] = allow_origin;
369 void Server::add_data_deferred(int stream_index, const char *data, size_t bytes, StreamStartSuitability suitable_for_stream_start)
371 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
372 streams[stream_index]->add_data_deferred(data, bytes, suitable_for_stream_start);
375 // See the .h file for postconditions after this function.
376 void Server::process_client(Client *client)
378 switch (client->state) {
379 case Client::READING_REQUEST: {
381 // Try to read more of the request.
385 ret = read(client->sock, buf, sizeof(buf));
386 } while (ret == -1 && errno == EINTR);
388 if (ret == -1 && errno == EAGAIN) {
389 // No more data right now. Nothing to do.
390 // This is postcondition #2.
395 close_client(client);
399 // OK, the socket is closed.
400 close_client(client);
404 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
407 case RP_OUT_OF_SPACE:
408 log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
409 close_client(client);
411 case RP_NOT_FINISHED_YET:
412 // OK, we don't have the entire header yet. Fine; we'll get it later.
413 // See if there's more data for us.
414 goto read_request_again;
416 log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
417 close_client(client);
423 assert(status == RP_FINISHED);
425 int error_code = parse_request(client);
426 if (error_code == 200) {
427 construct_header(client);
428 } else if (error_code == 204) {
429 construct_204(client);
431 construct_error(client, error_code);
434 // We've changed states, so fall through.
435 assert(client->state == Client::SENDING_SHORT_RESPONSE ||
436 client->state == Client::SENDING_HEADER);
438 case Client::SENDING_SHORT_RESPONSE:
439 case Client::SENDING_HEADER: {
440 sending_header_or_short_response_again:
443 ret = write(client->sock,
444 client->header_or_short_response.data() + client->header_or_short_response_bytes_sent,
445 client->header_or_short_response.size() - client->header_or_short_response_bytes_sent);
446 } while (ret == -1 && errno == EINTR);
448 if (ret == -1 && errno == EAGAIN) {
449 // We're out of socket space, so now we're at the “low edge” of epoll's
450 // edge triggering. epoll will tell us when there is more room, so for now,
452 // This is postcondition #4.
457 // Error! Postcondition #1.
459 close_client(client);
463 client->header_or_short_response_bytes_sent += ret;
464 assert(client->header_or_short_response_bytes_sent <= client->header_or_short_response.size());
466 if (client->header_or_short_response_bytes_sent < client->header_or_short_response.size()) {
467 // We haven't sent all yet. Fine; go another round.
468 goto sending_header_or_short_response_again;
471 // We're done sending the header or error! Clear it to release some memory.
472 client->header_or_short_response.clear();
474 if (client->state == Client::SENDING_SHORT_RESPONSE) {
475 // We're done sending the error, so now close.
476 // This is postcondition #1.
477 close_client(client);
481 Stream *stream = client->stream;
482 if (client->stream_pos == size_t(-2)) {
483 // Start sending from the beginning of the backlog.
484 client->stream_pos = min<size_t>(
485 stream->bytes_received - stream->backlog_size,
487 client->state = Client::SENDING_DATA;
489 } else if (stream->prebuffering_bytes == 0) {
490 // Start sending from the first keyframe we get. In other
491 // words, we won't send any of the backlog, but we'll start
492 // sending immediately as we get the next keyframe block.
493 // Note that this is functionally identical to the next if branch,
494 // except that we save a binary search.
495 client->stream_pos = stream->bytes_received;
496 client->state = Client::WAITING_FOR_KEYFRAME;
498 // We're not going to send anything to the client before we have
499 // N bytes. However, this wait might be boring; we can just as well
500 // use it to send older data if we have it. We use lower_bound()
501 // so that we are conservative and never add extra latency over just
502 // waiting (assuming CBR or nearly so); otherwise, we could want e.g.
503 // 100 kB prebuffer but end up sending a 10 MB GOP.
504 deque<size_t>::const_iterator starting_point_it =
505 lower_bound(stream->suitable_starting_points.begin(),
506 stream->suitable_starting_points.end(),
507 stream->bytes_received - stream->prebuffering_bytes);
508 if (starting_point_it == stream->suitable_starting_points.end()) {
509 // None found. Just put us at the end, and then wait for the
510 // first keyframe to appear.
511 client->stream_pos = stream->bytes_received;
512 client->state = Client::WAITING_FOR_KEYFRAME;
514 client->stream_pos = *starting_point_it;
515 client->state = Client::PREBUFFERING;
521 case Client::WAITING_FOR_KEYFRAME: {
522 Stream *stream = client->stream;
523 if (stream->suitable_starting_points.empty() ||
524 client->stream_pos > stream->suitable_starting_points.back()) {
525 // We haven't received a keyframe since this stream started waiting,
526 // so keep on waiting for one.
527 // This is postcondition #3.
528 stream->put_client_to_sleep(client);
531 client->stream_pos = stream->suitable_starting_points.back();
532 client->state = Client::PREBUFFERING;
535 case Client::PREBUFFERING: {
537 Stream *stream = client->stream;
538 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
539 assert(bytes_to_send <= stream->backlog_size);
540 if (bytes_to_send < stream->prebuffering_bytes) {
541 // We don't have enough bytes buffered to start this client yet.
542 // This is postcondition #3.
543 stream->put_client_to_sleep(client);
546 client->state = Client::SENDING_DATA;
549 case Client::SENDING_DATA: {
551 skip_lost_data(client);
552 Stream *stream = client->stream;
555 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
556 assert(bytes_to_send <= stream->backlog_size);
557 if (bytes_to_send == 0) {
561 // See if we need to split across the circular buffer.
562 bool more_data = false;
563 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
564 bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
570 off_t offset = client->stream_pos % stream->backlog_size;
571 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
572 } while (ret == -1 && errno == EINTR);
574 if (ret == -1 && errno == EAGAIN) {
575 // We're out of socket space, so return; epoll will wake us up
576 // when there is more room.
577 // This is postcondition #4.
581 // Error, close; postcondition #1.
582 log_perror("sendfile");
583 close_client(client);
586 client->stream_pos += ret;
587 client->bytes_sent += ret;
589 if (client->stream_pos == stream->bytes_received) {
590 // We don't have any more data for this client, so put it to sleep.
591 // This is postcondition #3.
592 stream->put_client_to_sleep(client);
593 } else if (more_data && size_t(ret) == bytes_to_send) {
594 goto sending_data_again;
603 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
604 // but resync will be the mux's problem.
605 void Server::skip_lost_data(Client *client)
607 Stream *stream = client->stream;
608 if (stream == NULL) {
611 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
612 if (bytes_to_send > stream->backlog_size) {
613 size_t bytes_lost = bytes_to_send - stream->backlog_size;
614 client->stream_pos = stream->bytes_received - stream->backlog_size;
615 client->bytes_lost += bytes_lost;
616 ++client->num_loss_events;
620 int Server::parse_request(Client *client)
622 vector<string> lines = split_lines(client->request);
624 return 400; // Bad request (empty).
627 // Parse the headers, for logging purposes.
628 // TODO: Case-insensitivity.
629 multimap<string, string> headers = extract_headers(lines, client->remote_addr);
630 multimap<string, string>::const_iterator referer_it = headers.find("Referer");
631 if (referer_it != headers.end()) {
632 client->referer = referer_it->second;
634 multimap<string, string>::const_iterator user_agent_it = headers.find("User-Agent");
635 if (user_agent_it != headers.end()) {
636 client->user_agent = user_agent_it->second;
639 vector<string> request_tokens = split_tokens(lines[0]);
640 if (request_tokens.size() < 2) {
641 return 400; // Bad request (empty).
643 if (request_tokens[0] != "GET") {
644 return 400; // Should maybe be 405 instead?
647 string url = request_tokens[1];
649 if (url.find("?backlog") == url.size() - 8) {
650 client->stream_pos = -2;
651 url = url.substr(0, url.size() - 8);
653 client->stream_pos = -1;
656 map<string, int>::const_iterator stream_url_map_it = stream_url_map.find(url);
657 if (stream_url_map_it == stream_url_map.end()) {
658 map<string, string>::const_iterator ping_url_map_it = ping_url_map.find(url);
659 if (ping_url_map_it == ping_url_map.end()) {
660 return 404; // Not found.
662 return 204; // No error.
666 Stream *stream = streams[stream_url_map_it->second];
667 if (stream->http_header.empty()) {
668 return 503; // Service unavailable.
671 client->stream = stream;
672 if (setsockopt(client->sock, SOL_SOCKET, SO_MAX_PACING_RATE, &client->stream->pacing_rate, sizeof(client->stream->pacing_rate)) == -1) {
673 if (client->stream->pacing_rate != ~0U) {
674 log_perror("setsockopt(SO_MAX_PACING_RATE)");
677 client->request.clear();
682 void Server::construct_header(Client *client)
684 Stream *stream = client->stream;
685 if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
686 client->header_or_short_response = stream->http_header +
688 stream->stream_header;
689 } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
690 client->header_or_short_response = stream->http_header +
691 "Content-encoding: metacube\r\n" +
693 if (!stream->stream_header.empty()) {
694 metacube2_block_header hdr;
695 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
696 hdr.size = htonl(stream->stream_header.size());
697 hdr.flags = htons(METACUBE_FLAGS_HEADER);
698 hdr.csum = htons(metacube2_compute_crc(&hdr));
699 client->header_or_short_response.append(
700 string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
702 client->header_or_short_response.append(stream->stream_header);
708 client->state = Client::SENDING_HEADER;
711 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
712 ev.data.u64 = reinterpret_cast<uint64_t>(client);
714 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
715 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
720 void Server::construct_error(Client *client, int error_code)
723 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
725 client->header_or_short_response = error;
728 client->state = Client::SENDING_SHORT_RESPONSE;
731 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
732 ev.data.u64 = reinterpret_cast<uint64_t>(client);
734 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
735 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
740 void Server::construct_204(Client *client)
742 map<string, string>::const_iterator ping_url_map_it = ping_url_map.find(client->url);
743 assert(ping_url_map_it != ping_url_map.end());
745 if (ping_url_map_it->second.empty()) {
746 client->header_or_short_response =
747 "HTTP/1.0 204 No Content\r\n"
751 snprintf(response, 256,
752 "HTTP/1.0 204 No Content\r\n"
753 "Access-Control-Allow-Origin: %s\r\n"
755 ping_url_map_it->second.c_str());
756 client->header_or_short_response = response;
760 client->state = Client::SENDING_SHORT_RESPONSE;
763 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
764 ev.data.u64 = reinterpret_cast<uint64_t>(client);
766 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
767 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
773 void delete_from(vector<T> *v, T elem)
775 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
776 v->erase(new_end, v->end());
779 void Server::close_client(Client *client)
781 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
782 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
786 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
787 if (client->stream != NULL) {
788 delete_from(&client->stream->sleeping_clients, client);
789 delete_from(&client->stream->to_process, client);
792 // Log to access_log.
793 access_log->write(client->get_stats());
796 safe_close(client->sock);
798 clients.erase(client->sock);
801 void Server::process_queued_data()
804 MutexLock lock(&queued_clients_mutex);
806 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
807 add_client(queued_add_clients[i]);
809 queued_add_clients.clear();
812 for (size_t i = 0; i < streams.size(); ++i) {
813 streams[i]->process_queued_data();