6 #include <sys/socket.h>
10 #include <sys/epoll.h>
19 #include "mutexlock.h"
25 Client::Client(int sock)
27 state(Client::READING_REQUEST),
29 header_or_error_bytes_sent(0),
32 request.reserve(1024);
35 Client::Client(const ClientProto &serialized, Stream *stream)
36 : sock(serialized.sock()),
37 state(State(serialized.state())),
38 request(serialized.request()),
39 stream_id(serialized.stream_id()),
41 header_or_error(serialized.header_or_error()),
42 header_or_error_bytes_sent(serialized.header_or_error_bytes_sent()),
43 bytes_sent(serialized.bytes_sent())
47 ClientProto Client::serialize() const
49 ClientProto serialized;
50 serialized.set_sock(sock);
51 serialized.set_state(state);
52 serialized.set_request(request);
53 serialized.set_stream_id(stream_id);
54 serialized.set_header_or_error(header_or_error);
55 serialized.set_header_or_error_bytes_sent(serialized.header_or_error_bytes_sent());
56 serialized.set_bytes_sent(bytes_sent);
60 Stream::Stream(const string &stream_id)
61 : stream_id(stream_id),
62 data(new char[BACKLOG_SIZE]),
65 memset(data, 0, BACKLOG_SIZE);
73 Stream::Stream(const StreamProto &serialized)
74 : stream_id(serialized.stream_id()),
75 header(serialized.header()),
76 data(new char[BACKLOG_SIZE]),
77 data_size(serialized.data_size())
79 assert(serialized.data().size() == BACKLOG_SIZE);
80 memcpy(data, serialized.data().data(), BACKLOG_SIZE);
83 StreamProto Stream::serialize() const
85 StreamProto serialized;
86 serialized.set_header(header);
87 serialized.set_data(string(data, data + BACKLOG_SIZE));
88 serialized.set_data_size(data_size);
89 serialized.set_stream_id(stream_id);
93 void Stream::put_client_to_sleep(Client *client)
95 sleeping_clients.push_back(client);
98 void Stream::wake_up_all_clients()
100 if (to_process.empty()) {
101 swap(sleeping_clients, to_process);
103 to_process.insert(to_process.end(), sleeping_clients.begin(), sleeping_clients.end());
104 sleeping_clients.clear();
110 pthread_mutex_init(&mutex, NULL);
111 pthread_mutex_init(&queued_data_mutex, NULL);
113 epoll_fd = epoll_create(1024); // Size argument is ignored.
114 if (epoll_fd == -1) {
124 ret = close(epoll_fd);
125 } while (ret == -1 && errno == EINTR);
128 perror("close(epoll_fd)");
136 // Joinable is already the default, but it's good to be certain.
138 pthread_attr_init(&attr);
139 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
140 pthread_create(&worker_thread, &attr, Server::do_work_thunk, this);
146 MutexLock lock(&mutex);
150 if (pthread_join(worker_thread, NULL) == -1) {
151 perror("pthread_join");
156 void *Server::do_work_thunk(void *arg)
158 Server *server = static_cast<Server *>(arg);
163 void Server::do_work()
166 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
167 if (nfds == -1 && errno == EINTR) {
171 perror("epoll_wait");
175 MutexLock lock(&mutex); // We release the mutex between iterations.
181 process_queued_data();
183 for (int i = 0; i < nfds; ++i) {
184 int fd = events[i].data.fd;
185 assert(clients.count(fd) != 0);
186 Client *client = &clients[fd];
188 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
189 close_client(client);
193 process_client(client);
196 for (map<string, Stream *>::iterator stream_it = streams.begin();
197 stream_it != streams.end();
199 vector<Client *> to_process;
200 swap(stream_it->second->to_process, to_process);
201 for (size_t i = 0; i < to_process.size(); ++i) {
202 process_client(to_process[i]);
208 CubemapStateProto Server::serialize()
210 // We don't serialize anything queued, so empty the queues.
211 process_queued_data();
213 CubemapStateProto serialized;
214 for (map<int, Client>::const_iterator client_it = clients.begin();
215 client_it != clients.end();
217 serialized.add_clients()->MergeFrom(client_it->second.serialize());
219 for (map<string, Stream *>::const_iterator stream_it = streams.begin();
220 stream_it != streams.end();
222 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
227 void Server::add_client_deferred(int sock)
229 MutexLock lock(&queued_data_mutex);
230 queued_add_clients.push_back(sock);
233 void Server::add_client(int sock)
235 clients.insert(make_pair(sock, Client(sock)));
237 // Start listening on data from this socket.
239 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
240 ev.data.u64 = 0; // Keep Valgrind happy.
242 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
243 perror("epoll_ctl(EPOLL_CTL_ADD)");
247 process_client(&clients[sock]);
250 void Server::add_client_from_serialized(const ClientProto &client)
252 MutexLock lock(&mutex);
253 Stream *stream = find_stream(client.stream_id());
254 clients.insert(make_pair(client.sock(), Client(client, stream)));
255 Client *client_ptr = &clients[client.sock()];
257 // Start listening on data from this socket.
259 if (client.state() == Client::READING_REQUEST) {
260 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
262 // If we don't have more data for this client, we'll be putting it into
263 // the sleeping array again soon.
264 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
266 ev.data.u64 = 0; // Keep Valgrind happy.
267 ev.data.fd = client.sock();
268 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
269 perror("epoll_ctl(EPOLL_CTL_ADD)");
273 if (client_ptr->state == Client::SENDING_DATA &&
274 client_ptr->bytes_sent == client_ptr->stream->data_size) {
275 client_ptr->stream->put_client_to_sleep(client_ptr);
277 process_client(client_ptr);
281 void Server::add_stream(const string &stream_id)
283 MutexLock lock(&mutex);
284 streams.insert(make_pair(stream_id, new Stream(stream_id)));
287 void Server::add_stream_from_serialized(const StreamProto &stream)
289 MutexLock lock(&mutex);
290 streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
293 void Server::set_header(const string &stream_id, const string &header)
295 MutexLock lock(&mutex);
296 find_stream(stream_id)->header = header;
298 // If there are clients we haven't sent anything to yet, we should give
299 // them the header, so push back into the SENDING_HEADER state.
300 for (map<int, Client>::iterator client_it = clients.begin();
301 client_it != clients.end();
303 Client *client = &client_it->second;
304 if (client->state == Client::SENDING_DATA &&
305 client->bytes_sent == 0) {
306 construct_header(client);
311 void Server::add_data_deferred(const string &stream_id, const char *data, size_t bytes)
313 MutexLock lock(&queued_data_mutex);
314 queued_data[stream_id].append(string(data, data + bytes));
317 void Server::add_data(const string &stream_id, const char *data, size_t bytes)
319 Stream *stream = find_stream(stream_id);
320 size_t pos = stream->data_size % BACKLOG_SIZE;
321 stream->data_size += bytes;
323 if (pos + bytes > BACKLOG_SIZE) {
324 size_t to_copy = BACKLOG_SIZE - pos;
325 memcpy(stream->data + pos, data, to_copy);
331 memcpy(stream->data + pos, data, bytes);
332 stream->wake_up_all_clients();
335 // See the .h file for postconditions after this function.
336 void Server::process_client(Client *client)
338 switch (client->state) {
339 case Client::READING_REQUEST: {
341 // Try to read more of the request.
345 ret = read(client->sock, buf, sizeof(buf));
346 } while (ret == -1 && errno == EINTR);
348 if (ret == -1 && errno == EAGAIN) {
349 // No more data right now. Nothing to do.
350 // This is postcondition #2.
355 close_client(client);
359 // OK, the socket is closed.
360 close_client(client);
364 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
367 case RP_OUT_OF_SPACE:
368 fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
369 close_client(client);
371 case RP_NOT_FINISHED_YET:
372 // OK, we don't have the entire header yet. Fine; we'll get it later.
373 // See if there's more data for us.
374 goto read_request_again;
376 fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
377 close_client(client);
383 assert(status == RP_FINISHED);
385 int error_code = parse_request(client);
386 if (error_code == 200) {
387 construct_header(client);
389 construct_error(client, error_code);
392 // We've changed states, so fall through.
393 assert(client->state == Client::SENDING_ERROR ||
394 client->state == Client::SENDING_HEADER);
396 case Client::SENDING_ERROR:
397 case Client::SENDING_HEADER: {
398 sending_header_or_error_again:
401 ret = write(client->sock,
402 client->header_or_error.data() + client->header_or_error_bytes_sent,
403 client->header_or_error.size() - client->header_or_error_bytes_sent);
404 } while (ret == -1 && errno == EINTR);
406 if (ret == -1 && errno == EAGAIN) {
407 // We're out of socket space, so now we're at the “low edge” of epoll's
408 // edge triggering. epoll will tell us when there is more room, so for now,
410 // This is postcondition #4.
415 // Error! Postcondition #1.
417 close_client(client);
421 client->header_or_error_bytes_sent += ret;
422 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
424 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
425 // We haven't sent all yet. Fine; go another round.
426 goto sending_header_or_error_again;
429 // We're done sending the header or error! Clear it to release some memory.
430 client->header_or_error.clear();
432 if (client->state == Client::SENDING_ERROR) {
433 // We're done sending the error, so now close.
434 // This is postcondition #1.
435 close_client(client);
439 // Start sending from the end. In other words, we won't send any of the backlog,
440 // but we'll start sending immediately as we get data.
441 // This is postcondition #3.
442 client->state = Client::SENDING_DATA;
443 client->bytes_sent = client->stream->data_size;
444 client->stream->put_client_to_sleep(client);
447 case Client::SENDING_DATA: {
448 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
449 // but resync will be the mux's problem.
450 Stream *stream = client->stream;
451 size_t bytes_to_send = stream->data_size - client->bytes_sent;
452 if (bytes_to_send == 0) {
455 if (bytes_to_send > BACKLOG_SIZE) {
456 fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
458 (long long int)(bytes_to_send - BACKLOG_SIZE));
459 client->bytes_sent = stream->data_size - BACKLOG_SIZE;
460 bytes_to_send = BACKLOG_SIZE;
463 // See if we need to split across the circular buffer.
465 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
466 size_t bytes_first_part = BACKLOG_SIZE - (client->bytes_sent % BACKLOG_SIZE);
469 iov[0].iov_base = const_cast<char *>(stream->data + (client->bytes_sent % BACKLOG_SIZE));
470 iov[0].iov_len = bytes_first_part;
472 iov[1].iov_base = const_cast<char *>(stream->data);
473 iov[1].iov_len = bytes_to_send - bytes_first_part;
476 ret = writev(client->sock, iov, 2);
477 } while (ret == -1 && errno == EINTR);
480 ret = write(client->sock,
481 stream->data + (client->bytes_sent % BACKLOG_SIZE),
483 } while (ret == -1 && errno == EINTR);
485 if (ret == -1 && errno == EAGAIN) {
486 // We're out of socket space, so return; epoll will wake us up
487 // when there is more room.
488 // This is postcondition #4.
492 // Error, close; postcondition #1.
493 perror("write/writev");
494 close_client(client);
497 client->bytes_sent += ret;
499 if (client->bytes_sent == stream->data_size) {
500 // We don't have any more data for this client, so put it to sleep.
501 // This is postcondition #3.
502 stream->put_client_to_sleep(client);
504 // XXX: Do we need to go another round here to explicitly
514 int Server::parse_request(Client *client)
516 vector<string> lines = split_lines(client->request);
518 return 400; // Bad request (empty).
521 vector<string> request_tokens = split_tokens(lines[0]);
522 if (request_tokens.size() < 2) {
523 return 400; // Bad request (empty).
525 if (request_tokens[0] != "GET") {
526 return 400; // Should maybe be 405 instead?
528 if (streams.count(request_tokens[1]) == 0) {
529 return 404; // Not found.
532 client->stream_id = request_tokens[1];
533 client->stream = find_stream(client->stream_id);
534 client->request.clear();
539 void Server::construct_header(Client *client)
541 client->header_or_error = "HTTP/1.0 200 OK\r\nContent-type: video/x-flv\r\nCache-Control: no-cache\r\n\r\n" +
542 find_stream(client->stream_id)->header;
545 client->state = Client::SENDING_HEADER;
548 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
549 ev.data.u64 = 0; // Keep Valgrind happy.
550 ev.data.fd = client->sock;
552 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
553 perror("epoll_ctl(EPOLL_CTL_MOD)");
558 void Server::construct_error(Client *client, int error_code)
561 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
563 client->header_or_error = error;
566 client->state = Client::SENDING_ERROR;
569 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
570 ev.data.u64 = 0; // Keep Valgrind happy.
571 ev.data.fd = client->sock;
573 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
574 perror("epoll_ctl(EPOLL_CTL_MOD)");
580 void delete_from(vector<T> *v, T elem)
582 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
583 v->erase(new_end, v->end());
586 void Server::close_client(Client *client)
588 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
589 perror("epoll_ctl(EPOLL_CTL_DEL)");
593 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
594 if (client->stream != NULL) {
595 delete_from(&client->stream->sleeping_clients, client);
596 delete_from(&client->stream->to_process, client);
602 ret = close(client->sock);
603 } while (ret == -1 && errno == EINTR);
609 clients.erase(client->sock);
612 Stream *Server::find_stream(const string &stream_id)
614 map<string, Stream *>::iterator it = streams.find(stream_id);
615 assert(it != streams.end());
619 void Server::process_queued_data()
621 MutexLock lock(&queued_data_mutex);
623 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
624 add_client(queued_add_clients[i]);
626 queued_add_clients.clear();
628 for (map<string, string>::iterator queued_it = queued_data.begin();
629 queued_it != queued_data.end();
631 add_data(queued_it->first, queued_it->second.data(), queued_it->second.size());