7 #include <sys/socket.h>
10 #include <sys/ioctl.h>
11 #include <sys/epoll.h>
20 #include "mutexlock.h"
26 Client::Client(int sock)
28 state(Client::READING_REQUEST),
30 header_or_error_bytes_sent(0),
33 request.reserve(1024);
36 Client::Client(const ClientProto &serialized, Stream *stream)
37 : sock(serialized.sock()),
38 state(State(serialized.state())),
39 request(serialized.request()),
40 stream_id(serialized.stream_id()),
42 header_or_error(serialized.header_or_error()),
43 header_or_error_bytes_sent(serialized.header_or_error_bytes_sent()),
44 bytes_sent(serialized.bytes_sent())
48 ClientProto Client::serialize() const
50 ClientProto serialized;
51 serialized.set_sock(sock);
52 serialized.set_state(state);
53 serialized.set_request(request);
54 serialized.set_stream_id(stream_id);
55 serialized.set_header_or_error(header_or_error);
56 serialized.set_header_or_error_bytes_sent(serialized.header_or_error_bytes_sent());
57 serialized.set_bytes_sent(bytes_sent);
61 Stream::Stream(const string &stream_id)
62 : stream_id(stream_id),
63 data(new char[BACKLOG_SIZE]),
66 memset(data, 0, BACKLOG_SIZE);
74 Stream::Stream(const StreamProto &serialized)
75 : stream_id(serialized.stream_id()),
76 header(serialized.header()),
77 data(new char[BACKLOG_SIZE]),
78 data_size(serialized.data_size())
80 assert(serialized.data().size() == BACKLOG_SIZE);
81 memcpy(data, serialized.data().data(), BACKLOG_SIZE);
84 StreamProto Stream::serialize() const
86 StreamProto serialized;
87 serialized.set_header(header);
88 serialized.set_data(string(data, data + BACKLOG_SIZE));
89 serialized.set_data_size(data_size);
90 serialized.set_stream_id(stream_id);
94 void Stream::put_client_to_sleep(Client *client)
96 sleeping_clients.push_back(client);
99 void Stream::wake_up_all_clients()
101 if (to_process.empty()) {
102 swap(sleeping_clients, to_process);
104 to_process.insert(to_process.end(), sleeping_clients.begin(), sleeping_clients.end());
105 sleeping_clients.clear();
111 pthread_mutex_init(&mutex, NULL);
112 pthread_mutex_init(&queued_data_mutex, NULL);
114 epoll_fd = epoll_create(1024); // Size argument is ignored.
115 if (epoll_fd == -1) {
125 ret = close(epoll_fd);
126 } while (ret == -1 && errno == EINTR);
129 perror("close(epoll_fd)");
137 // Joinable is already the default, but it's good to be certain.
139 pthread_attr_init(&attr);
140 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
141 pthread_create(&worker_thread, &attr, Server::do_work_thunk, this);
147 MutexLock lock(&mutex);
151 if (pthread_join(worker_thread, NULL) == -1) {
152 perror("pthread_join");
157 void *Server::do_work_thunk(void *arg)
159 Server *server = static_cast<Server *>(arg);
164 void Server::do_work()
167 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
168 if (nfds == -1 && errno == EINTR) {
172 perror("epoll_wait");
176 MutexLock lock(&mutex); // We release the mutex between iterations.
182 process_queued_data();
184 for (int i = 0; i < nfds; ++i) {
185 int fd = events[i].data.fd;
186 assert(clients.count(fd) != 0);
187 Client *client = &clients[fd];
189 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
190 close_client(client);
194 process_client(client);
197 for (map<string, Stream *>::iterator stream_it = streams.begin();
198 stream_it != streams.end();
200 Stream *stream = stream_it->second;
201 for (size_t i = 0; i < stream->to_process.size(); ++i) {
202 process_client(stream->to_process[i]);
204 stream->to_process.clear();
209 CubemapStateProto Server::serialize()
211 // We don't serialize anything queued, so empty the queues.
212 process_queued_data();
214 CubemapStateProto serialized;
215 for (map<int, Client>::const_iterator client_it = clients.begin();
216 client_it != clients.end();
218 serialized.add_clients()->MergeFrom(client_it->second.serialize());
220 for (map<string, Stream *>::const_iterator stream_it = streams.begin();
221 stream_it != streams.end();
223 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
228 void Server::add_client_deferred(int sock)
230 MutexLock lock(&queued_data_mutex);
231 queued_add_clients.push_back(sock);
234 void Server::add_client(int sock)
236 clients.insert(make_pair(sock, Client(sock)));
238 // Start listening on data from this socket.
240 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
241 ev.data.u64 = 0; // Keep Valgrind happy.
243 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
244 perror("epoll_ctl(EPOLL_CTL_ADD)");
248 process_client(&clients[sock]);
251 void Server::add_client_from_serialized(const ClientProto &client)
253 MutexLock lock(&mutex);
254 Stream *stream = find_stream(client.stream_id());
255 clients.insert(make_pair(client.sock(), Client(client, stream)));
256 Client *client_ptr = &clients[client.sock()];
258 // Start listening on data from this socket.
260 if (client.state() == Client::READING_REQUEST) {
261 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
263 // If we don't have more data for this client, we'll be putting it into
264 // the sleeping array again soon.
265 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
267 ev.data.u64 = 0; // Keep Valgrind happy.
268 ev.data.fd = client.sock();
269 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
270 perror("epoll_ctl(EPOLL_CTL_ADD)");
274 if (client_ptr->state == Client::SENDING_DATA &&
275 client_ptr->bytes_sent == client_ptr->stream->data_size) {
276 client_ptr->stream->put_client_to_sleep(client_ptr);
278 process_client(client_ptr);
282 void Server::add_stream(const string &stream_id)
284 MutexLock lock(&mutex);
285 streams.insert(make_pair(stream_id, new Stream(stream_id)));
288 void Server::add_stream_from_serialized(const StreamProto &stream)
290 MutexLock lock(&mutex);
291 streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
294 void Server::set_header(const string &stream_id, const string &header)
296 MutexLock lock(&mutex);
297 find_stream(stream_id)->header = header;
299 // If there are clients we haven't sent anything to yet, we should give
300 // them the header, so push back into the SENDING_HEADER state.
301 for (map<int, Client>::iterator client_it = clients.begin();
302 client_it != clients.end();
304 Client *client = &client_it->second;
305 if (client->state == Client::SENDING_DATA &&
306 client->bytes_sent == 0) {
307 construct_header(client);
312 void Server::add_data_deferred(const string &stream_id, const char *data, size_t bytes)
314 MutexLock lock(&queued_data_mutex);
315 queued_data[stream_id].append(string(data, data + bytes));
318 void Server::add_data(const string &stream_id, const char *data, size_t bytes)
320 Stream *stream = find_stream(stream_id);
321 size_t pos = stream->data_size % BACKLOG_SIZE;
322 stream->data_size += bytes;
324 if (pos + bytes > BACKLOG_SIZE) {
325 size_t to_copy = BACKLOG_SIZE - pos;
326 memcpy(stream->data + pos, data, to_copy);
332 memcpy(stream->data + pos, data, bytes);
333 stream->wake_up_all_clients();
336 // See the .h file for postconditions after this function.
337 void Server::process_client(Client *client)
339 switch (client->state) {
340 case Client::READING_REQUEST: {
342 // Try to read more of the request.
346 ret = read(client->sock, buf, sizeof(buf));
347 } while (ret == -1 && errno == EINTR);
349 if (ret == -1 && errno == EAGAIN) {
350 // No more data right now. Nothing to do.
351 // This is postcondition #2.
356 close_client(client);
360 // OK, the socket is closed.
361 close_client(client);
365 // Guard against overlong requests gobbling up all of our space.
366 if (client->request.size() + ret > MAX_CLIENT_REQUEST) {
367 fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
368 close_client(client);
372 // See if we have \r\n\r\n anywhere in the request. We start three bytes
373 // before what we just appended, in case we just got the final character.
374 size_t existing_req_bytes = client->request.size();
375 client->request.append(string(buf, buf + ret));
377 size_t start_at = (existing_req_bytes >= 3 ? existing_req_bytes - 3 : 0);
378 const char *ptr = reinterpret_cast<char *>(
379 memmem(client->request.data() + start_at, client->request.size() - start_at,
382 // OK, we don't have the entire header yet. Fine; we'll get it later.
383 // See if there's more data for us.
384 goto read_request_again;
387 if (ptr != client->request.data() + client->request.size() - 4) {
388 fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
389 close_client(client);
393 int error_code = parse_request(client);
394 if (error_code == 200) {
395 construct_header(client);
397 construct_error(client, error_code);
400 // We've changed states, so fall through.
401 assert(client->state == Client::SENDING_ERROR ||
402 client->state == Client::SENDING_HEADER);
404 case Client::SENDING_ERROR:
405 case Client::SENDING_HEADER: {
406 sending_header_or_error_again:
409 ret = write(client->sock,
410 client->header_or_error.data() + client->header_or_error_bytes_sent,
411 client->header_or_error.size() - client->header_or_error_bytes_sent);
412 } while (ret == -1 && errno == EINTR);
414 if (ret == -1 && errno == EAGAIN) {
415 // We're out of socket space, so now we're at the “low edge” of epoll's
416 // edge triggering. epoll will tell us when there is more room, so for now,
418 // This is postcondition #4.
423 // Error! Postcondition #1.
425 close_client(client);
429 client->header_or_error_bytes_sent += ret;
430 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
432 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
433 // We haven't sent all yet. Fine; go another round.
434 goto sending_header_or_error_again;
437 // We're done sending the header or error! Clear it to release some memory.
438 client->header_or_error.clear();
440 if (client->state == Client::SENDING_ERROR) {
441 // We're done sending the error, so now close.
442 // This is postcondition #1.
443 close_client(client);
447 // Start sending from the end. In other words, we won't send any of the backlog,
448 // but we'll start sending immediately as we get data.
449 // This is postcondition #3.
450 client->state = Client::SENDING_DATA;
451 client->bytes_sent = client->stream->data_size;
452 client->stream->put_client_to_sleep(client);
455 case Client::SENDING_DATA: {
456 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
457 // but resync will be the mux's problem.
458 Stream *stream = client->stream;
459 size_t bytes_to_send = stream->data_size - client->bytes_sent;
460 if (bytes_to_send == 0) {
463 if (bytes_to_send > BACKLOG_SIZE) {
464 fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
466 (long long int)(bytes_to_send - BACKLOG_SIZE));
467 client->bytes_sent = stream->data_size - BACKLOG_SIZE;
468 bytes_to_send = BACKLOG_SIZE;
471 // See if we need to split across the circular buffer.
473 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
474 size_t bytes_first_part = BACKLOG_SIZE - (client->bytes_sent % BACKLOG_SIZE);
477 iov[0].iov_base = const_cast<char *>(stream->data + (client->bytes_sent % BACKLOG_SIZE));
478 iov[0].iov_len = bytes_first_part;
480 iov[1].iov_base = const_cast<char *>(stream->data);
481 iov[1].iov_len = bytes_to_send - bytes_first_part;
484 ret = writev(client->sock, iov, 2);
485 } while (ret == -1 && errno == EINTR);
488 ret = write(client->sock,
489 stream->data + (client->bytes_sent % BACKLOG_SIZE),
491 } while (ret == -1 && errno == EINTR);
493 if (ret == -1 && errno == EAGAIN) {
494 // We're out of socket space, so return; epoll will wake us up
495 // when there is more room.
496 // This is postcondition #4.
500 // Error, close; postcondition #1.
501 perror("write/writev");
502 close_client(client);
505 client->bytes_sent += ret;
507 if (client->bytes_sent == stream->data_size) {
508 // We don't have any more data for this client, so put it to sleep.
509 // This is postcondition #3.
510 stream->put_client_to_sleep(client);
512 // XXX: Do we need to go another round here to explicitly
522 int Server::parse_request(Client *client)
524 vector<string> lines = split_lines(client->request);
526 return 400; // Bad request (empty).
529 vector<string> request_tokens = split_tokens(lines[0]);
530 if (request_tokens.size() < 2) {
531 return 400; // Bad request (empty).
533 if (request_tokens[0] != "GET") {
534 return 400; // Should maybe be 405 instead?
536 if (streams.count(request_tokens[1]) == 0) {
537 return 404; // Not found.
540 client->stream_id = request_tokens[1];
541 client->stream = find_stream(client->stream_id);
542 client->request.clear();
547 void Server::construct_header(Client *client)
549 client->header_or_error = "HTTP/1.0 200 OK\r\nContent-type: video/x-flv\r\nCache-Control: no-cache\r\n\r\n" +
550 find_stream(client->stream_id)->header;
553 client->state = Client::SENDING_HEADER;
556 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
557 ev.data.u64 = 0; // Keep Valgrind happy.
558 ev.data.fd = client->sock;
560 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
561 perror("epoll_ctl(EPOLL_CTL_MOD)");
566 void Server::construct_error(Client *client, int error_code)
569 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
571 client->header_or_error = error;
574 client->state = Client::SENDING_ERROR;
577 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
578 ev.data.u64 = 0; // Keep Valgrind happy.
579 ev.data.fd = client->sock;
581 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
582 perror("epoll_ctl(EPOLL_CTL_MOD)");
587 void Server::close_client(Client *client)
589 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
590 perror("epoll_ctl(EPOLL_CTL_DEL)");
594 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
595 if (client->stream != NULL) {
596 vector<Client *>::iterator new_end =
597 remove(client->stream->sleeping_clients.begin(),
598 client->stream->sleeping_clients.end(),
600 client->stream->sleeping_clients.erase(
601 new_end, client->stream->sleeping_clients.end());
607 ret = close(client->sock);
608 } while (ret == -1 && errno == EINTR);
614 clients.erase(client->sock);
617 Stream *Server::find_stream(const string &stream_id)
619 map<string, Stream *>::iterator it = streams.find(stream_id);
620 assert(it != streams.end());
624 void Server::process_queued_data()
626 MutexLock lock(&queued_data_mutex);
628 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
629 add_client(queued_add_clients[i]);
631 queued_add_clients.clear();
633 for (map<string, string>::iterator queued_it = queued_data.begin();
634 queued_it != queued_data.end();
636 add_data(queued_it->first, queued_it->second.data(), queued_it->second.size());