3 #include <netinet/in.h>
10 #include <sys/sendfile.h>
11 #include <sys/socket.h>
12 #include <sys/types.h>
23 #include "accesslog.h"
25 #include "metacube2.h"
26 #include "mutexlock.h"
33 #ifndef SO_MAX_PACING_RATE
34 #define SO_MAX_PACING_RATE 47
39 extern AccessLogThread *access_log;
43 inline bool is_equal(timespec a, timespec b)
45 return a.tv_sec == b.tv_sec &&
46 a.tv_nsec == b.tv_nsec;
49 inline bool is_earlier(timespec a, timespec b)
51 if (a.tv_sec != b.tv_sec)
52 return a.tv_sec < b.tv_sec;
53 return a.tv_nsec < b.tv_nsec;
60 pthread_mutex_init(&mutex, NULL);
61 pthread_mutex_init(&queued_clients_mutex, NULL);
63 epoll_fd = epoll_create(1024); // Size argument is ignored.
65 log_perror("epoll_fd");
72 for (Stream *stream : streams) {
79 vector<ClientStats> Server::get_client_stats() const
81 vector<ClientStats> ret;
83 MutexLock lock(&mutex);
84 for (const auto &fd_and_client : clients) {
85 ret.push_back(fd_and_client.second.get_stats());
90 void Server::do_work()
92 while (!should_stop()) {
93 // Wait until there's activity on at least one of the fds,
94 // or 20 ms (about one frame at 50 fps) has elapsed.
96 // We could in theory wait forever and rely on wakeup()
97 // from add_client_deferred() and add_data_deferred(),
98 // but wakeup is a pretty expensive operation, and the
99 // two threads might end up fighting over a lock, so it's
100 // seemingly (much) more efficient to just have a timeout here.
101 int nfds = epoll_pwait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS, &sigset_without_usr1_block);
102 if (nfds == -1 && errno != EINTR) {
103 log_perror("epoll_wait");
107 MutexLock lock(&mutex); // We release the mutex between iterations.
109 process_queued_data();
111 // Process each client where we have socket activity.
112 for (int i = 0; i < nfds; ++i) {
113 Client *client = reinterpret_cast<Client *>(events[i].data.ptr);
115 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
116 close_client(client);
120 process_client(client);
123 // Process each client where its stream has new data,
124 // even if there was no socket activity.
125 for (Stream *stream : streams) {
126 vector<Client *> to_process;
127 swap(stream->to_process, to_process);
128 for (Client *client : to_process) {
129 process_client(client);
133 // Finally, go through each client to see if it's timed out
134 // in the READING_REQUEST state. (Seemingly there are clients
135 // that can hold sockets up for days at a time without sending
137 timespec timeout_time;
138 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &timeout_time) == -1) {
139 log_perror("clock_gettime(CLOCK_MONOTONIC_COARSE)");
142 timeout_time.tv_sec -= REQUEST_READ_TIMEOUT_SEC;
143 while (!clients_ordered_by_connect_time.empty()) {
144 const pair<timespec, int> &connect_time_and_fd = clients_ordered_by_connect_time.front();
146 // See if we have reached the end of clients to process.
147 if (is_earlier(timeout_time, connect_time_and_fd.first)) {
151 // If this client doesn't exist anymore, just ignore it
152 // (it was deleted earlier).
153 auto client_it = clients.find(connect_time_and_fd.second);
154 if (client_it == clients.end()) {
155 clients_ordered_by_connect_time.pop();
158 Client *client = &client_it->second;
159 if (!is_equal(client->connect_time, connect_time_and_fd.first)) {
160 // Another client has taken this fd in the meantime.
161 clients_ordered_by_connect_time.pop();
165 if (client->state != Client::READING_REQUEST) {
166 // Only READING_REQUEST can time out.
167 clients_ordered_by_connect_time.pop();
172 close_client(client);
173 clients_ordered_by_connect_time.pop();
178 CubemapStateProto Server::serialize()
180 // We don't serialize anything queued, so empty the queues.
181 process_queued_data();
183 // Set all clients in a consistent state before serializing
184 // (ie., they have no remaining lost data). Otherwise, increasing
185 // the backlog could take clients into a newly valid area of the backlog,
186 // sending a stream of zeros instead of skipping the data as it should.
188 // TODO: Do this when clients are added back from serialized state instead;
189 // it would probably be less wasteful.
190 for (auto &fd_and_client : clients) {
191 skip_lost_data(&fd_and_client.second);
194 CubemapStateProto serialized;
195 for (const auto &fd_and_client : clients) {
196 serialized.add_clients()->MergeFrom(fd_and_client.second.serialize());
198 for (Stream *stream : streams) {
199 serialized.add_streams()->MergeFrom(stream->serialize());
204 void Server::add_client_deferred(int sock, Acceptor *acceptor)
206 MutexLock lock(&queued_clients_mutex);
207 queued_add_clients.push_back(std::make_pair(sock, acceptor));
210 void Server::add_client(int sock, Acceptor *acceptor)
212 const bool is_tls = acceptor->is_tls();
213 auto inserted = clients.insert(make_pair(sock, Client(sock)));
214 assert(inserted.second == true); // Should not already exist.
215 Client *client_ptr = &inserted.first->second;
217 // Connection timestamps must be nondecreasing. I can't find any guarantee
218 // that even the monotonic clock can't go backwards by a small amount
219 // (think switching between CPUs with non-synchronized TSCs), so if
220 // this actually should happen, we hack around it by fudging
222 if (!clients_ordered_by_connect_time.empty() &&
223 is_earlier(client_ptr->connect_time, clients_ordered_by_connect_time.back().first)) {
224 client_ptr->connect_time = clients_ordered_by_connect_time.back().first;
226 clients_ordered_by_connect_time.push(make_pair(client_ptr->connect_time, sock));
228 // Start listening on data from this socket.
231 // Even in the initial state (READING_REQUEST), TLS needs to
232 // send data for the handshake, and thus might end up needing
233 // to know about EPOLLOUT.
234 ev.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLRDHUP;
236 // EPOLLOUT will be added once we go out of READING_REQUEST.
237 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
239 ev.data.ptr = client_ptr;
240 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
241 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
246 assert(tls_server_contexts.count(acceptor));
247 client_ptr->tls_context = tls_accept(tls_server_contexts[acceptor]);
248 if (client_ptr->tls_context == NULL) {
249 log(ERROR, "tls_accept() failed");
250 close_client(client_ptr);
253 tls_make_exportable(client_ptr->tls_context, 1);
256 process_client(client_ptr);
259 void Server::add_client_from_serialized(const ClientProto &client)
261 MutexLock lock(&mutex);
263 int stream_index = lookup_stream_by_url(client.url());
264 if (stream_index == -1) {
265 assert(client.state() != Client::SENDING_DATA);
268 stream = streams[stream_index];
270 auto inserted = clients.insert(make_pair(client.sock(), Client(client, stream)));
271 assert(inserted.second == true); // Should not already exist.
272 Client *client_ptr = &inserted.first->second;
274 // Connection timestamps must be nondecreasing.
275 assert(clients_ordered_by_connect_time.empty() ||
276 !is_earlier(client_ptr->connect_time, clients_ordered_by_connect_time.back().first));
277 clients_ordered_by_connect_time.push(make_pair(client_ptr->connect_time, client.sock()));
279 // Start listening on data from this socket.
281 if (client.state() == Client::READING_REQUEST) {
282 // See the corresponding comment in Server::add_client().
283 if (client.has_tls_context()) {
284 ev.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLRDHUP;
286 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
289 // If we don't have more data for this client, we'll be putting it into
290 // the sleeping array again soon.
291 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
293 ev.data.ptr = client_ptr;
294 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
295 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
299 if (client_ptr->state == Client::WAITING_FOR_KEYFRAME ||
300 client_ptr->state == Client::PREBUFFERING ||
301 (client_ptr->state == Client::SENDING_DATA &&
302 client_ptr->stream_pos == client_ptr->stream->bytes_received)) {
303 client_ptr->stream->put_client_to_sleep(client_ptr);
305 process_client(client_ptr);
309 int Server::lookup_stream_by_url(const string &url) const
311 map<string, int>::const_iterator stream_url_it = stream_url_map.find(url);
312 if (stream_url_it == stream_url_map.end()) {
315 return stream_url_it->second;
318 int Server::add_stream(const string &url, size_t backlog_size, size_t prebuffering_bytes, Stream::Encoding encoding, Stream::Encoding src_encoding)
320 MutexLock lock(&mutex);
321 stream_url_map.insert(make_pair(url, streams.size()));
322 streams.push_back(new Stream(url, backlog_size, prebuffering_bytes, encoding, src_encoding));
323 return streams.size() - 1;
326 int Server::add_stream_from_serialized(const StreamProto &stream, int data_fd)
328 MutexLock lock(&mutex);
329 stream_url_map.insert(make_pair(stream.url(), streams.size()));
330 streams.push_back(new Stream(stream, data_fd));
331 return streams.size() - 1;
334 void Server::set_backlog_size(int stream_index, size_t new_size)
336 MutexLock lock(&mutex);
337 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
338 streams[stream_index]->set_backlog_size(new_size);
341 void Server::set_prebuffering_bytes(int stream_index, size_t new_amount)
343 MutexLock lock(&mutex);
344 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
345 streams[stream_index]->prebuffering_bytes = new_amount;
348 void Server::set_encoding(int stream_index, Stream::Encoding encoding)
350 MutexLock lock(&mutex);
351 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
352 streams[stream_index]->encoding = encoding;
355 void Server::set_src_encoding(int stream_index, Stream::Encoding encoding)
357 MutexLock lock(&mutex);
358 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
359 streams[stream_index]->src_encoding = encoding;
362 void Server::set_header(int stream_index, const string &http_header, const string &stream_header)
364 MutexLock lock(&mutex);
365 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
366 streams[stream_index]->http_header = http_header;
368 if (stream_header != streams[stream_index]->stream_header) {
369 // We cannot start at any of the older starting points anymore,
370 // since they'd get the wrong header for the stream (not to mention
371 // that a changed header probably means the stream restarted,
372 // which means any client starting on the old one would probably
373 // stop playing properly at the change point). Next block
374 // should be a suitable starting point (if not, something is
375 // pretty strange), so it will fill up again soon enough.
376 streams[stream_index]->suitable_starting_points.clear();
378 streams[stream_index]->stream_header = stream_header;
381 void Server::set_pacing_rate(int stream_index, uint32_t pacing_rate)
383 MutexLock lock(&mutex);
384 assert(clients.empty());
385 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
386 streams[stream_index]->pacing_rate = pacing_rate;
389 void Server::add_gen204(const std::string &url, const std::string &allow_origin)
391 MutexLock lock(&mutex);
392 assert(clients.empty());
393 ping_url_map[url] = allow_origin;
396 void Server::create_tls_context_for_acceptor(const Acceptor *acceptor)
398 assert(acceptor->is_tls());
400 bool is_server = true;
401 TLSContext *server_context = tls_create_context(is_server, TLS_V12);
403 const string &cert = acceptor->get_certificate_chain();
404 int num_cert = tls_load_certificates(server_context, reinterpret_cast<const unsigned char *>(cert.data()), cert.size());
405 assert(num_cert > 0); // Should have been checked by config earlier.
407 const string &key = acceptor->get_private_key();
408 int num_key = tls_load_private_key(server_context, reinterpret_cast<const unsigned char *>(key.data()), key.size());
409 assert(num_key > 0); // Should have been checked by config earlier.
411 tls_server_contexts.insert(make_pair(acceptor, server_context));
414 void Server::add_data_deferred(int stream_index, const char *data, size_t bytes, uint16_t metacube_flags)
416 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
417 streams[stream_index]->add_data_deferred(data, bytes, metacube_flags);
420 // See the .h file for postconditions after this function.
421 void Server::process_client(Client *client)
423 switch (client->state) {
424 case Client::READING_REQUEST: {
425 if (client->tls_context != NULL) {
426 if (send_pending_tls_data(client)) {
427 // send_pending_tls_data() hit postconditions #1 or #4.
433 // Try to read more of the request.
436 if (client->tls_context == NULL) {
437 ret = read_nontls_data(client, buf, sizeof(buf));
439 // read_nontls_data() hit postconditions #1 or #2.
443 ret = read_tls_data(client, buf, sizeof(buf));
445 // read_tls_data() hit postconditions #1, #2 or #4.
450 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
453 case RP_OUT_OF_SPACE:
454 log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
455 close_client(client);
457 case RP_NOT_FINISHED_YET:
458 // OK, we don't have the entire header yet. Fine; we'll get it later.
459 // See if there's more data for us.
460 goto read_request_again;
462 log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
463 close_client(client);
469 assert(status == RP_FINISHED);
471 if (client->tls_context && !client->in_ktls_mode && tls_established(client->tls_context)) {
472 // We're ready to enter kTLS mode, unless we still have some
473 // handshake data to send (which then must be sent as non-kTLS).
474 if (send_pending_tls_data(client)) {
475 // send_pending_tls_data() hit postconditions #1 or #4.
478 ret = tls_make_ktls(client->tls_context, client->sock);
480 log_tls_error("tls_make_ktls", ret);
481 close_client(client);
484 client->in_ktls_mode = true;
487 int error_code = parse_request(client);
488 if (error_code == 200) {
489 construct_header(client);
490 } else if (error_code == 204) {
491 construct_204(client);
493 construct_error(client, error_code);
496 // We've changed states, so fall through.
497 assert(client->state == Client::SENDING_SHORT_RESPONSE ||
498 client->state == Client::SENDING_HEADER);
500 case Client::SENDING_SHORT_RESPONSE:
501 case Client::SENDING_HEADER: {
502 sending_header_or_short_response_again:
505 ret = write(client->sock,
506 client->header_or_short_response.data() + client->header_or_short_response_bytes_sent,
507 client->header_or_short_response.size() - client->header_or_short_response_bytes_sent);
508 } while (ret == -1 && errno == EINTR);
510 if (ret == -1 && errno == EAGAIN) {
511 // We're out of socket space, so now we're at the “low edge” of epoll's
512 // edge triggering. epoll will tell us when there is more room, so for now,
514 // This is postcondition #4.
519 // Error! Postcondition #1.
521 close_client(client);
525 client->header_or_short_response_bytes_sent += ret;
526 assert(client->header_or_short_response_bytes_sent <= client->header_or_short_response.size());
528 if (client->header_or_short_response_bytes_sent < client->header_or_short_response.size()) {
529 // We haven't sent all yet. Fine; go another round.
530 goto sending_header_or_short_response_again;
533 // We're done sending the header or error! Clear it to release some memory.
534 client->header_or_short_response.clear();
536 if (client->state == Client::SENDING_SHORT_RESPONSE) {
537 // We're done sending the error, so now close.
538 // This is postcondition #1.
539 close_client(client);
543 Stream *stream = client->stream;
544 if (client->stream_pos == size_t(-2)) {
545 // Start sending from the beginning of the backlog.
546 client->stream_pos = min<size_t>(
547 stream->bytes_received - stream->backlog_size,
549 client->state = Client::SENDING_DATA;
551 } else if (stream->prebuffering_bytes == 0) {
552 // Start sending from the first keyframe we get. In other
553 // words, we won't send any of the backlog, but we'll start
554 // sending immediately as we get the next keyframe block.
555 // Note that this is functionally identical to the next if branch,
556 // except that we save a binary search.
557 client->stream_pos = stream->bytes_received;
558 client->state = Client::WAITING_FOR_KEYFRAME;
560 // We're not going to send anything to the client before we have
561 // N bytes. However, this wait might be boring; we can just as well
562 // use it to send older data if we have it. We use lower_bound()
563 // so that we are conservative and never add extra latency over just
564 // waiting (assuming CBR or nearly so); otherwise, we could want e.g.
565 // 100 kB prebuffer but end up sending a 10 MB GOP.
566 deque<size_t>::const_iterator starting_point_it =
567 lower_bound(stream->suitable_starting_points.begin(),
568 stream->suitable_starting_points.end(),
569 stream->bytes_received - stream->prebuffering_bytes);
570 if (starting_point_it == stream->suitable_starting_points.end()) {
571 // None found. Just put us at the end, and then wait for the
572 // first keyframe to appear.
573 client->stream_pos = stream->bytes_received;
574 client->state = Client::WAITING_FOR_KEYFRAME;
576 client->stream_pos = *starting_point_it;
577 client->state = Client::PREBUFFERING;
583 case Client::WAITING_FOR_KEYFRAME: {
584 Stream *stream = client->stream;
585 if (stream->suitable_starting_points.empty() ||
586 client->stream_pos > stream->suitable_starting_points.back()) {
587 // We haven't received a keyframe since this stream started waiting,
588 // so keep on waiting for one.
589 // This is postcondition #3.
590 stream->put_client_to_sleep(client);
593 client->stream_pos = stream->suitable_starting_points.back();
594 client->state = Client::PREBUFFERING;
597 case Client::PREBUFFERING: {
599 Stream *stream = client->stream;
600 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
601 assert(bytes_to_send <= stream->backlog_size);
602 if (bytes_to_send < stream->prebuffering_bytes) {
603 // We don't have enough bytes buffered to start this client yet.
604 // This is postcondition #3.
605 stream->put_client_to_sleep(client);
608 client->state = Client::SENDING_DATA;
611 case Client::SENDING_DATA: {
613 skip_lost_data(client);
614 Stream *stream = client->stream;
617 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
618 assert(bytes_to_send <= stream->backlog_size);
619 if (bytes_to_send == 0) {
623 // See if we need to split across the circular buffer.
624 bool more_data = false;
625 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
626 bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
632 off_t offset = client->stream_pos % stream->backlog_size;
633 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
634 } while (ret == -1 && errno == EINTR);
636 if (ret == -1 && errno == EAGAIN) {
637 // We're out of socket space, so return; epoll will wake us up
638 // when there is more room.
639 // This is postcondition #4.
643 // Error, close; postcondition #1.
644 log_perror("sendfile");
645 close_client(client);
648 client->stream_pos += ret;
649 client->bytes_sent += ret;
651 if (client->stream_pos == stream->bytes_received) {
652 // We don't have any more data for this client, so put it to sleep.
653 // This is postcondition #3.
654 stream->put_client_to_sleep(client);
655 } else if (more_data && size_t(ret) == bytes_to_send) {
656 goto sending_data_again;
665 bool Server::send_pending_tls_data(Client *client)
667 // See if there's data from the TLS library to write.
668 if (client->tls_data_to_send == NULL) {
669 client->tls_data_to_send = tls_get_write_buffer(client->tls_context, &client->tls_data_left_to_send);
670 if (client->tls_data_to_send == NULL) {
671 // Really no data to send.
679 ret = write(client->sock, client->tls_data_to_send, client->tls_data_left_to_send);
680 } while (ret == -1 && errno == EINTR);
681 assert(ret < 0 || size_t(ret) <= client->tls_data_left_to_send);
683 if (ret == -1 && errno == EAGAIN) {
684 // We're out of socket space, so now we're at the “low edge” of epoll's
685 // edge triggering. epoll will tell us when there is more room, so for now,
687 // This is postcondition #4.
691 // Error! Postcondition #1.
693 close_client(client);
696 if (ret > 0 && size_t(ret) == client->tls_data_left_to_send) {
697 // All data has been sent, so we don't need to go to sleep.
698 tls_buffer_clear(client->tls_context);
699 client->tls_data_to_send = NULL;
703 // More data to send, so try again.
704 client->tls_data_to_send += ret;
705 client->tls_data_left_to_send -= ret;
706 goto send_data_again;
709 int Server::read_nontls_data(Client *client, char *buf, size_t max_size)
713 ret = read(client->sock, buf, max_size);
714 } while (ret == -1 && errno == EINTR);
716 if (ret == -1 && errno == EAGAIN) {
717 // No more data right now. Nothing to do.
718 // This is postcondition #2.
723 close_client(client);
727 // OK, the socket is closed.
728 close_client(client);
735 int Server::read_tls_data(Client *client, char *buf, size_t max_size)
740 ret = read(client->sock, buf, max_size);
741 } while (ret == -1 && errno == EINTR);
743 if (ret == -1 && errno == EAGAIN) {
744 // No more data right now. Nothing to do.
745 // This is postcondition #2.
750 close_client(client);
754 // OK, the socket is closed.
755 close_client(client);
759 // Give it to the TLS library.
760 int err = tls_consume_stream(client->tls_context, reinterpret_cast<const unsigned char *>(buf), ret, nullptr);
762 log_tls_error("tls_consume_stream", err);
763 close_client(client);
767 // Not consumed any data. See if we can read more.
771 // Read any decrypted data available for us. (We can reuse buf, since it's free now.)
772 ret = tls_read(client->tls_context, reinterpret_cast<unsigned char *>(buf), max_size);
774 // No decrypted data for us yet, but there might be some more handshaking
775 // to send. Do that if needed, then look for more data.
776 if (send_pending_tls_data(client)) {
777 // send_pending_tls_data() hit postconditions #1 or #4.
783 log_tls_error("tls_read", ret);
784 close_client(client);
792 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
793 // but resync will be the mux's problem.
794 void Server::skip_lost_data(Client *client)
796 Stream *stream = client->stream;
797 if (stream == NULL) {
800 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
801 if (bytes_to_send > stream->backlog_size) {
802 size_t bytes_lost = bytes_to_send - stream->backlog_size;
803 client->stream_pos = stream->bytes_received - stream->backlog_size;
804 client->bytes_lost += bytes_lost;
805 ++client->num_loss_events;
809 int Server::parse_request(Client *client)
811 vector<string> lines = split_lines(client->request);
813 return 400; // Bad request (empty).
816 // Parse the headers, for logging purposes.
817 // TODO: Case-insensitivity.
818 multimap<string, string> headers = extract_headers(lines, client->remote_addr);
819 multimap<string, string>::const_iterator referer_it = headers.find("Referer");
820 if (referer_it != headers.end()) {
821 client->referer = referer_it->second;
823 multimap<string, string>::const_iterator user_agent_it = headers.find("User-Agent");
824 if (user_agent_it != headers.end()) {
825 client->user_agent = user_agent_it->second;
828 vector<string> request_tokens = split_tokens(lines[0]);
829 if (request_tokens.size() < 2) {
830 return 400; // Bad request (empty).
832 if (request_tokens[0] != "GET") {
833 return 400; // Should maybe be 405 instead?
836 string url = request_tokens[1];
838 if (url.size() > 8 && url.find("?backlog") == url.size() - 8) {
839 client->stream_pos = -2;
840 url = url.substr(0, url.size() - 8);
842 client->stream_pos = -1;
845 map<string, int>::const_iterator stream_url_map_it = stream_url_map.find(url);
846 if (stream_url_map_it == stream_url_map.end()) {
847 map<string, string>::const_iterator ping_url_map_it = ping_url_map.find(url);
848 if (ping_url_map_it == ping_url_map.end()) {
849 return 404; // Not found.
851 return 204; // No error.
855 Stream *stream = streams[stream_url_map_it->second];
856 if (stream->http_header.empty()) {
857 return 503; // Service unavailable.
860 client->stream = stream;
861 if (setsockopt(client->sock, SOL_SOCKET, SO_MAX_PACING_RATE, &client->stream->pacing_rate, sizeof(client->stream->pacing_rate)) == -1) {
862 if (client->stream->pacing_rate != ~0U) {
863 log_perror("setsockopt(SO_MAX_PACING_RATE)");
866 client->request.clear();
871 void Server::construct_header(Client *client)
873 Stream *stream = client->stream;
874 if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
875 client->header_or_short_response = stream->http_header +
877 stream->stream_header;
878 } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
879 client->header_or_short_response = stream->http_header +
880 "Content-encoding: metacube\r\n" +
882 if (!stream->stream_header.empty()) {
883 metacube2_block_header hdr;
884 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
885 hdr.size = htonl(stream->stream_header.size());
886 hdr.flags = htons(METACUBE_FLAGS_HEADER);
887 hdr.csum = htons(metacube2_compute_crc(&hdr));
888 client->header_or_short_response.append(
889 string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
891 client->header_or_short_response.append(stream->stream_header);
897 client->state = Client::SENDING_HEADER;
898 change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
901 void Server::construct_error(Client *client, int error_code)
904 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
906 client->header_or_short_response = error;
909 client->state = Client::SENDING_SHORT_RESPONSE;
910 change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
913 void Server::construct_204(Client *client)
915 map<string, string>::const_iterator ping_url_map_it = ping_url_map.find(client->url);
916 assert(ping_url_map_it != ping_url_map.end());
918 if (ping_url_map_it->second.empty()) {
919 client->header_or_short_response =
920 "HTTP/1.0 204 No Content\r\n"
924 snprintf(response, 256,
925 "HTTP/1.0 204 No Content\r\n"
926 "Access-Control-Allow-Origin: %s\r\n"
928 ping_url_map_it->second.c_str());
929 client->header_or_short_response = response;
933 client->state = Client::SENDING_SHORT_RESPONSE;
934 change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
938 void delete_from(vector<T> *v, T elem)
940 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
941 v->erase(new_end, v->end());
944 void Server::close_client(Client *client)
946 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
947 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
951 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
952 if (client->stream != NULL) {
953 delete_from(&client->stream->sleeping_clients, client);
954 delete_from(&client->stream->to_process, client);
957 if (client->tls_context) {
958 tls_destroy_context(client->tls_context);
961 // Log to access_log.
962 access_log->write(client->get_stats());
965 safe_close(client->sock);
967 clients.erase(client->sock);
970 void Server::change_epoll_events(Client *client, uint32_t events)
974 ev.data.ptr = client;
976 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
977 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
982 void Server::process_queued_data()
985 MutexLock lock(&queued_clients_mutex);
987 for (const pair<int, Acceptor *> &id_and_acceptor : queued_add_clients) {
988 add_client(id_and_acceptor.first, id_and_acceptor.second);
990 queued_add_clients.clear();
993 for (Stream *stream : streams) {
994 stream->process_queued_data();