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 (size_t i = 0; i < streams.size(); ++i) {
79 vector<ClientStats> Server::get_client_stats() const
81 vector<ClientStats> ret;
83 MutexLock lock(&mutex);
84 for (map<int, Client>::const_iterator client_it = clients.begin();
85 client_it != clients.end();
87 ret.push_back(client_it->second.get_stats());
92 void Server::do_work()
94 while (!should_stop()) {
95 // Wait until there's activity on at least one of the fds,
96 // or 20 ms (about one frame at 50 fps) has elapsed.
98 // We could in theory wait forever and rely on wakeup()
99 // from add_client_deferred() and add_data_deferred(),
100 // but wakeup is a pretty expensive operation, and the
101 // two threads might end up fighting over a lock, so it's
102 // seemingly (much) more efficient to just have a timeout here.
103 int nfds = epoll_pwait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS, &sigset_without_usr1_block);
104 if (nfds == -1 && errno != EINTR) {
105 log_perror("epoll_wait");
109 MutexLock lock(&mutex); // We release the mutex between iterations.
111 process_queued_data();
113 // Process each client where we have socket activity.
114 for (int i = 0; i < nfds; ++i) {
115 Client *client = reinterpret_cast<Client *>(events[i].data.u64);
117 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
118 close_client(client);
122 process_client(client);
125 // Process each client where its stream has new data,
126 // even if there was no socket activity.
127 for (size_t i = 0; i < streams.size(); ++i) {
128 vector<Client *> to_process;
129 swap(streams[i]->to_process, to_process);
130 for (size_t i = 0; i < to_process.size(); ++i) {
131 process_client(to_process[i]);
135 // Finally, go through each client to see if it's timed out
136 // in the READING_REQUEST state. (Seemingly there are clients
137 // that can hold sockets up for days at a time without sending
139 timespec timeout_time;
140 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &timeout_time) == -1) {
141 log_perror("clock_gettime(CLOCK_MONOTONIC_COARSE)");
144 timeout_time.tv_sec -= REQUEST_READ_TIMEOUT_SEC;
145 while (!clients_ordered_by_connect_time.empty()) {
146 const pair<timespec, int> &connect_time_and_fd = clients_ordered_by_connect_time.front();
148 // See if we have reached the end of clients to process.
149 if (is_earlier(timeout_time, connect_time_and_fd.first)) {
153 // If this client doesn't exist anymore, just ignore it
154 // (it was deleted earlier).
155 map<int, Client>::iterator client_it = clients.find(connect_time_and_fd.second);
156 if (client_it == clients.end()) {
157 clients_ordered_by_connect_time.pop();
160 Client *client = &client_it->second;
161 if (!is_equal(client->connect_time, connect_time_and_fd.first)) {
162 // Another client has taken this fd in the meantime.
163 clients_ordered_by_connect_time.pop();
167 if (client->state != Client::READING_REQUEST) {
168 // Only READING_REQUEST can time out.
169 clients_ordered_by_connect_time.pop();
174 close_client(client);
175 clients_ordered_by_connect_time.pop();
180 CubemapStateProto Server::serialize()
182 // We don't serialize anything queued, so empty the queues.
183 process_queued_data();
185 // Set all clients in a consistent state before serializing
186 // (ie., they have no remaining lost data). Otherwise, increasing
187 // the backlog could take clients into a newly valid area of the backlog,
188 // sending a stream of zeros instead of skipping the data as it should.
190 // TODO: Do this when clients are added back from serialized state instead;
191 // it would probably be less wasteful.
192 for (map<int, Client>::iterator client_it = clients.begin();
193 client_it != clients.end();
195 skip_lost_data(&client_it->second);
198 CubemapStateProto serialized;
199 for (map<int, Client>::const_iterator client_it = clients.begin();
200 client_it != clients.end();
202 serialized.add_clients()->MergeFrom(client_it->second.serialize());
204 for (size_t i = 0; i < streams.size(); ++i) {
205 serialized.add_streams()->MergeFrom(streams[i]->serialize());
210 void Server::add_client_deferred(int sock, Acceptor *acceptor)
212 MutexLock lock(&queued_clients_mutex);
213 queued_add_clients.push_back(std::make_pair(sock, acceptor));
216 void Server::add_client(int sock, Acceptor *acceptor)
218 const bool is_tls = acceptor->is_tls();
219 pair<map<int, Client>::iterator, bool> ret =
220 clients.insert(make_pair(sock, Client(sock)));
221 assert(ret.second == true); // Should not already exist.
222 Client *client_ptr = &ret.first->second;
224 // Connection timestamps must be nondecreasing. I can't find any guarantee
225 // that even the monotonic clock can't go backwards by a small amount
226 // (think switching between CPUs with non-synchronized TSCs), so if
227 // this actually should happen, we hack around it by fudging
229 if (!clients_ordered_by_connect_time.empty() &&
230 is_earlier(client_ptr->connect_time, clients_ordered_by_connect_time.back().first)) {
231 client_ptr->connect_time = clients_ordered_by_connect_time.back().first;
233 clients_ordered_by_connect_time.push(make_pair(client_ptr->connect_time, sock));
235 // Start listening on data from this socket.
238 // Even in the initial state (READING_REQUEST), TLS needs to
239 // send data for the handshake, and thus might end up needing
240 // to know about EPOLLOUT.
241 ev.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLRDHUP;
243 // EPOLLOUT will be added once we go out of READING_REQUEST.
244 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
246 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
247 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
248 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
253 assert(tls_server_contexts.count(acceptor));
254 client_ptr->tls_context = tls_accept(tls_server_contexts[acceptor]);
255 if (client_ptr->tls_context == NULL) {
256 log(ERROR, "tls_accept() failed");
257 close_client(client_ptr);
260 tls_make_exportable(client_ptr->tls_context, 1);
263 process_client(client_ptr);
266 void Server::add_client_from_serialized(const ClientProto &client)
268 MutexLock lock(&mutex);
270 int stream_index = lookup_stream_by_url(client.url());
271 if (stream_index == -1) {
272 assert(client.state() != Client::SENDING_DATA);
275 stream = streams[stream_index];
277 pair<map<int, Client>::iterator, bool> ret =
278 clients.insert(make_pair(client.sock(), Client(client, stream)));
279 assert(ret.second == true); // Should not already exist.
280 Client *client_ptr = &ret.first->second;
282 // Connection timestamps must be nondecreasing.
283 assert(clients_ordered_by_connect_time.empty() ||
284 !is_earlier(client_ptr->connect_time, clients_ordered_by_connect_time.back().first));
285 clients_ordered_by_connect_time.push(make_pair(client_ptr->connect_time, client.sock()));
287 // Start listening on data from this socket.
289 if (client.state() == Client::READING_REQUEST) {
290 // See the corresponding comment in Server::add_client().
291 if (client.has_tls_context()) {
292 ev.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLRDHUP;
294 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
297 // If we don't have more data for this client, we'll be putting it into
298 // the sleeping array again soon.
299 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
301 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
302 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
303 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
307 if (client_ptr->state == Client::WAITING_FOR_KEYFRAME ||
308 client_ptr->state == Client::PREBUFFERING ||
309 (client_ptr->state == Client::SENDING_DATA &&
310 client_ptr->stream_pos == client_ptr->stream->bytes_received)) {
311 client_ptr->stream->put_client_to_sleep(client_ptr);
313 process_client(client_ptr);
317 int Server::lookup_stream_by_url(const string &url) const
319 map<string, int>::const_iterator stream_url_it = stream_url_map.find(url);
320 if (stream_url_it == stream_url_map.end()) {
323 return stream_url_it->second;
326 int Server::add_stream(const string &url, size_t backlog_size, size_t prebuffering_bytes, Stream::Encoding encoding, Stream::Encoding src_encoding)
328 MutexLock lock(&mutex);
329 stream_url_map.insert(make_pair(url, streams.size()));
330 streams.push_back(new Stream(url, backlog_size, prebuffering_bytes, encoding, src_encoding));
331 return streams.size() - 1;
334 int Server::add_stream_from_serialized(const StreamProto &stream, int data_fd)
336 MutexLock lock(&mutex);
337 stream_url_map.insert(make_pair(stream.url(), streams.size()));
338 streams.push_back(new Stream(stream, data_fd));
339 return streams.size() - 1;
342 void Server::set_backlog_size(int stream_index, size_t new_size)
344 MutexLock lock(&mutex);
345 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
346 streams[stream_index]->set_backlog_size(new_size);
349 void Server::set_prebuffering_bytes(int stream_index, size_t new_amount)
351 MutexLock lock(&mutex);
352 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
353 streams[stream_index]->prebuffering_bytes = new_amount;
356 void Server::set_encoding(int stream_index, Stream::Encoding encoding)
358 MutexLock lock(&mutex);
359 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
360 streams[stream_index]->encoding = encoding;
363 void Server::set_src_encoding(int stream_index, Stream::Encoding encoding)
365 MutexLock lock(&mutex);
366 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
367 streams[stream_index]->src_encoding = encoding;
370 void Server::set_header(int stream_index, const string &http_header, const string &stream_header)
372 MutexLock lock(&mutex);
373 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
374 streams[stream_index]->http_header = http_header;
376 if (stream_header != streams[stream_index]->stream_header) {
377 // We cannot start at any of the older starting points anymore,
378 // since they'd get the wrong header for the stream (not to mention
379 // that a changed header probably means the stream restarted,
380 // which means any client starting on the old one would probably
381 // stop playing properly at the change point). Next block
382 // should be a suitable starting point (if not, something is
383 // pretty strange), so it will fill up again soon enough.
384 streams[stream_index]->suitable_starting_points.clear();
386 streams[stream_index]->stream_header = stream_header;
389 void Server::set_pacing_rate(int stream_index, uint32_t pacing_rate)
391 MutexLock lock(&mutex);
392 assert(clients.empty());
393 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
394 streams[stream_index]->pacing_rate = pacing_rate;
397 void Server::add_gen204(const std::string &url, const std::string &allow_origin)
399 MutexLock lock(&mutex);
400 assert(clients.empty());
401 ping_url_map[url] = allow_origin;
404 void Server::create_tls_context_for_acceptor(const Acceptor *acceptor)
406 assert(acceptor->is_tls());
408 bool is_server = true;
409 TLSContext *server_context = tls_create_context(is_server, TLS_V12);
411 const string &cert = acceptor->get_certificate_chain();
412 int num_cert = tls_load_certificates(server_context, reinterpret_cast<const unsigned char *>(cert.data()), cert.size());
413 assert(num_cert > 0); // Should have been checked by config earlier.
415 const string &key = acceptor->get_private_key();
416 int num_key = tls_load_private_key(server_context, reinterpret_cast<const unsigned char *>(key.data()), key.size());
417 assert(num_key > 0); // Should have been checked by config earlier.
419 tls_server_contexts.insert(make_pair(acceptor, server_context));
422 void Server::add_data_deferred(int stream_index, const char *data, size_t bytes, uint16_t metacube_flags)
424 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
425 streams[stream_index]->add_data_deferred(data, bytes, metacube_flags);
428 // See the .h file for postconditions after this function.
429 void Server::process_client(Client *client)
431 switch (client->state) {
432 case Client::READING_REQUEST: {
433 if (client->tls_context != NULL) {
434 if (send_pending_tls_data(client)) {
435 // send_pending_tls_data() hit postconditions #1 or #4.
441 // Try to read more of the request.
444 if (client->tls_context == NULL) {
445 ret = read_nontls_data(client, buf, sizeof(buf));
447 // read_nontls_data() hit postconditions #1 or #2.
451 ret = read_tls_data(client, buf, sizeof(buf));
453 // read_tls_data() hit postconditions #1, #2 or #4.
458 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
461 case RP_OUT_OF_SPACE:
462 log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
463 close_client(client);
465 case RP_NOT_FINISHED_YET:
466 // OK, we don't have the entire header yet. Fine; we'll get it later.
467 // See if there's more data for us.
468 goto read_request_again;
470 log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
471 close_client(client);
477 assert(status == RP_FINISHED);
479 if (client->tls_context && !client->in_ktls_mode && tls_established(client->tls_context)) {
480 // We're ready to enter kTLS mode, unless we still have some
481 // handshake data to send (which then must be sent as non-kTLS).
482 if (send_pending_tls_data(client)) {
483 // send_pending_tls_data() hit postconditions #1 or #4.
486 ret = tls_make_ktls(client->tls_context, client->sock);
488 log_tls_error("tls_make_ktls", ret);
489 close_client(client);
492 client->in_ktls_mode = true;
495 int error_code = parse_request(client);
496 if (error_code == 200) {
497 construct_header(client);
498 } else if (error_code == 204) {
499 construct_204(client);
501 construct_error(client, error_code);
504 // We've changed states, so fall through.
505 assert(client->state == Client::SENDING_SHORT_RESPONSE ||
506 client->state == Client::SENDING_HEADER);
508 case Client::SENDING_SHORT_RESPONSE:
509 case Client::SENDING_HEADER: {
510 sending_header_or_short_response_again:
513 ret = write(client->sock,
514 client->header_or_short_response.data() + client->header_or_short_response_bytes_sent,
515 client->header_or_short_response.size() - client->header_or_short_response_bytes_sent);
516 } while (ret == -1 && errno == EINTR);
518 if (ret == -1 && errno == EAGAIN) {
519 // We're out of socket space, so now we're at the “low edge” of epoll's
520 // edge triggering. epoll will tell us when there is more room, so for now,
522 // This is postcondition #4.
527 // Error! Postcondition #1.
529 close_client(client);
533 client->header_or_short_response_bytes_sent += ret;
534 assert(client->header_or_short_response_bytes_sent <= client->header_or_short_response.size());
536 if (client->header_or_short_response_bytes_sent < client->header_or_short_response.size()) {
537 // We haven't sent all yet. Fine; go another round.
538 goto sending_header_or_short_response_again;
541 // We're done sending the header or error! Clear it to release some memory.
542 client->header_or_short_response.clear();
544 if (client->state == Client::SENDING_SHORT_RESPONSE) {
545 // We're done sending the error, so now close.
546 // This is postcondition #1.
547 close_client(client);
551 Stream *stream = client->stream;
552 if (client->stream_pos == size_t(-2)) {
553 // Start sending from the beginning of the backlog.
554 client->stream_pos = min<size_t>(
555 stream->bytes_received - stream->backlog_size,
557 client->state = Client::SENDING_DATA;
559 } else if (stream->prebuffering_bytes == 0) {
560 // Start sending from the first keyframe we get. In other
561 // words, we won't send any of the backlog, but we'll start
562 // sending immediately as we get the next keyframe block.
563 // Note that this is functionally identical to the next if branch,
564 // except that we save a binary search.
565 client->stream_pos = stream->bytes_received;
566 client->state = Client::WAITING_FOR_KEYFRAME;
568 // We're not going to send anything to the client before we have
569 // N bytes. However, this wait might be boring; we can just as well
570 // use it to send older data if we have it. We use lower_bound()
571 // so that we are conservative and never add extra latency over just
572 // waiting (assuming CBR or nearly so); otherwise, we could want e.g.
573 // 100 kB prebuffer but end up sending a 10 MB GOP.
574 deque<size_t>::const_iterator starting_point_it =
575 lower_bound(stream->suitable_starting_points.begin(),
576 stream->suitable_starting_points.end(),
577 stream->bytes_received - stream->prebuffering_bytes);
578 if (starting_point_it == stream->suitable_starting_points.end()) {
579 // None found. Just put us at the end, and then wait for the
580 // first keyframe to appear.
581 client->stream_pos = stream->bytes_received;
582 client->state = Client::WAITING_FOR_KEYFRAME;
584 client->stream_pos = *starting_point_it;
585 client->state = Client::PREBUFFERING;
591 case Client::WAITING_FOR_KEYFRAME: {
592 Stream *stream = client->stream;
593 if (stream->suitable_starting_points.empty() ||
594 client->stream_pos > stream->suitable_starting_points.back()) {
595 // We haven't received a keyframe since this stream started waiting,
596 // so keep on waiting for one.
597 // This is postcondition #3.
598 stream->put_client_to_sleep(client);
601 client->stream_pos = stream->suitable_starting_points.back();
602 client->state = Client::PREBUFFERING;
605 case Client::PREBUFFERING: {
607 Stream *stream = client->stream;
608 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
609 assert(bytes_to_send <= stream->backlog_size);
610 if (bytes_to_send < stream->prebuffering_bytes) {
611 // We don't have enough bytes buffered to start this client yet.
612 // This is postcondition #3.
613 stream->put_client_to_sleep(client);
616 client->state = Client::SENDING_DATA;
619 case Client::SENDING_DATA: {
621 skip_lost_data(client);
622 Stream *stream = client->stream;
625 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
626 assert(bytes_to_send <= stream->backlog_size);
627 if (bytes_to_send == 0) {
631 // See if we need to split across the circular buffer.
632 bool more_data = false;
633 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
634 bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
640 off_t offset = client->stream_pos % stream->backlog_size;
641 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
642 } while (ret == -1 && errno == EINTR);
644 if (ret == -1 && errno == EAGAIN) {
645 // We're out of socket space, so return; epoll will wake us up
646 // when there is more room.
647 // This is postcondition #4.
651 // Error, close; postcondition #1.
652 log_perror("sendfile");
653 close_client(client);
656 client->stream_pos += ret;
657 client->bytes_sent += ret;
659 if (client->stream_pos == stream->bytes_received) {
660 // We don't have any more data for this client, so put it to sleep.
661 // This is postcondition #3.
662 stream->put_client_to_sleep(client);
663 } else if (more_data && size_t(ret) == bytes_to_send) {
664 goto sending_data_again;
673 bool Server::send_pending_tls_data(Client *client)
675 // See if there's data from the TLS library to write.
676 if (client->tls_data_to_send == NULL) {
677 client->tls_data_to_send = tls_get_write_buffer(client->tls_context, &client->tls_data_left_to_send);
678 if (client->tls_data_to_send == NULL) {
679 // Really no data to send.
687 ret = write(client->sock, client->tls_data_to_send, client->tls_data_left_to_send);
688 } while (ret == -1 && errno == EINTR);
689 assert(ret < 0 || size_t(ret) <= client->tls_data_left_to_send);
691 if (ret == -1 && errno == EAGAIN) {
692 // We're out of socket space, so now we're at the “low edge” of epoll's
693 // edge triggering. epoll will tell us when there is more room, so for now,
695 // This is postcondition #4.
699 // Error! Postcondition #1.
701 close_client(client);
704 if (ret > 0 && size_t(ret) == client->tls_data_left_to_send) {
705 // All data has been sent, so we don't need to go to sleep.
706 tls_buffer_clear(client->tls_context);
707 client->tls_data_to_send = NULL;
711 // More data to send, so try again.
712 client->tls_data_to_send += ret;
713 client->tls_data_left_to_send -= ret;
714 goto send_data_again;
717 int Server::read_nontls_data(Client *client, char *buf, size_t max_size)
721 ret = read(client->sock, buf, max_size);
722 } while (ret == -1 && errno == EINTR);
724 if (ret == -1 && errno == EAGAIN) {
725 // No more data right now. Nothing to do.
726 // This is postcondition #2.
731 close_client(client);
735 // OK, the socket is closed.
736 close_client(client);
743 int Server::read_tls_data(Client *client, char *buf, size_t max_size)
748 ret = read(client->sock, buf, max_size);
749 } while (ret == -1 && errno == EINTR);
751 if (ret == -1 && errno == EAGAIN) {
752 // No more data right now. Nothing to do.
753 // This is postcondition #2.
758 close_client(client);
762 // OK, the socket is closed.
763 close_client(client);
767 // Give it to the TLS library.
768 int err = tls_consume_stream(client->tls_context, reinterpret_cast<const unsigned char *>(buf), ret, nullptr);
770 log_tls_error("tls_consume_stream", err);
771 close_client(client);
775 // Not consumed any data. See if we can read more.
779 // Read any decrypted data available for us. (We can reuse buf, since it's free now.)
780 ret = tls_read(client->tls_context, reinterpret_cast<unsigned char *>(buf), max_size);
782 // No decrypted data for us yet, but there might be some more handshaking
783 // to send. Do that if needed, then look for more data.
784 if (send_pending_tls_data(client)) {
785 // send_pending_tls_data() hit postconditions #1 or #4.
791 log_tls_error("tls_read", ret);
792 close_client(client);
800 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
801 // but resync will be the mux's problem.
802 void Server::skip_lost_data(Client *client)
804 Stream *stream = client->stream;
805 if (stream == NULL) {
808 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
809 if (bytes_to_send > stream->backlog_size) {
810 size_t bytes_lost = bytes_to_send - stream->backlog_size;
811 client->stream_pos = stream->bytes_received - stream->backlog_size;
812 client->bytes_lost += bytes_lost;
813 ++client->num_loss_events;
817 int Server::parse_request(Client *client)
819 vector<string> lines = split_lines(client->request);
821 return 400; // Bad request (empty).
824 // Parse the headers, for logging purposes.
825 // TODO: Case-insensitivity.
826 multimap<string, string> headers = extract_headers(lines, client->remote_addr);
827 multimap<string, string>::const_iterator referer_it = headers.find("Referer");
828 if (referer_it != headers.end()) {
829 client->referer = referer_it->second;
831 multimap<string, string>::const_iterator user_agent_it = headers.find("User-Agent");
832 if (user_agent_it != headers.end()) {
833 client->user_agent = user_agent_it->second;
836 vector<string> request_tokens = split_tokens(lines[0]);
837 if (request_tokens.size() < 2) {
838 return 400; // Bad request (empty).
840 if (request_tokens[0] != "GET") {
841 return 400; // Should maybe be 405 instead?
844 string url = request_tokens[1];
846 if (url.size() > 8 && url.find("?backlog") == url.size() - 8) {
847 client->stream_pos = -2;
848 url = url.substr(0, url.size() - 8);
850 client->stream_pos = -1;
853 map<string, int>::const_iterator stream_url_map_it = stream_url_map.find(url);
854 if (stream_url_map_it == stream_url_map.end()) {
855 map<string, string>::const_iterator ping_url_map_it = ping_url_map.find(url);
856 if (ping_url_map_it == ping_url_map.end()) {
857 return 404; // Not found.
859 return 204; // No error.
863 Stream *stream = streams[stream_url_map_it->second];
864 if (stream->http_header.empty()) {
865 return 503; // Service unavailable.
868 client->stream = stream;
869 if (setsockopt(client->sock, SOL_SOCKET, SO_MAX_PACING_RATE, &client->stream->pacing_rate, sizeof(client->stream->pacing_rate)) == -1) {
870 if (client->stream->pacing_rate != ~0U) {
871 log_perror("setsockopt(SO_MAX_PACING_RATE)");
874 client->request.clear();
879 void Server::construct_header(Client *client)
881 Stream *stream = client->stream;
882 if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
883 client->header_or_short_response = stream->http_header +
885 stream->stream_header;
886 } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
887 client->header_or_short_response = stream->http_header +
888 "Content-encoding: metacube\r\n" +
890 if (!stream->stream_header.empty()) {
891 metacube2_block_header hdr;
892 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
893 hdr.size = htonl(stream->stream_header.size());
894 hdr.flags = htons(METACUBE_FLAGS_HEADER);
895 hdr.csum = htons(metacube2_compute_crc(&hdr));
896 client->header_or_short_response.append(
897 string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
899 client->header_or_short_response.append(stream->stream_header);
905 client->state = Client::SENDING_HEADER;
908 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
909 ev.data.u64 = reinterpret_cast<uint64_t>(client);
911 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
912 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
917 void Server::construct_error(Client *client, int error_code)
920 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
922 client->header_or_short_response = error;
925 client->state = Client::SENDING_SHORT_RESPONSE;
928 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
929 ev.data.u64 = reinterpret_cast<uint64_t>(client);
931 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
932 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
937 void Server::construct_204(Client *client)
939 map<string, string>::const_iterator ping_url_map_it = ping_url_map.find(client->url);
940 assert(ping_url_map_it != ping_url_map.end());
942 if (ping_url_map_it->second.empty()) {
943 client->header_or_short_response =
944 "HTTP/1.0 204 No Content\r\n"
948 snprintf(response, 256,
949 "HTTP/1.0 204 No Content\r\n"
950 "Access-Control-Allow-Origin: %s\r\n"
952 ping_url_map_it->second.c_str());
953 client->header_or_short_response = response;
957 client->state = Client::SENDING_SHORT_RESPONSE;
960 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
961 ev.data.u64 = reinterpret_cast<uint64_t>(client);
963 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
964 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
970 void delete_from(vector<T> *v, T elem)
972 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
973 v->erase(new_end, v->end());
976 void Server::close_client(Client *client)
978 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
979 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
983 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
984 if (client->stream != NULL) {
985 delete_from(&client->stream->sleeping_clients, client);
986 delete_from(&client->stream->to_process, client);
989 // Log to access_log.
990 access_log->write(client->get_stats());
993 safe_close(client->sock);
995 clients.erase(client->sock);
998 void Server::process_queued_data()
1001 MutexLock lock(&queued_clients_mutex);
1003 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
1004 add_client(queued_add_clients[i].first, queued_add_clients[i].second);
1006 queued_add_clients.clear();
1009 for (size_t i = 0; i < streams.size(); ++i) {
1010 streams[i]->process_queued_data();