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);
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 for (int i = 0; i < nfds; ++i) {
182 int fd = events[i].data.fd;
183 assert(clients.count(fd) != 0);
184 Client *client = &clients[fd];
186 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
187 close_client(client);
191 process_client(client);
194 for (map<string, Stream *>::iterator stream_it = streams.begin();
195 stream_it != streams.end();
197 Stream *stream = stream_it->second;
198 for (size_t i = 0; i < stream->to_process.size(); ++i) {
199 process_client(stream->to_process[i]);
201 stream->to_process.clear();
206 CubemapStateProto Server::serialize() const
208 CubemapStateProto serialized;
209 for (map<int, Client>::const_iterator client_it = clients.begin();
210 client_it != clients.end();
212 serialized.add_clients()->MergeFrom(client_it->second.serialize());
214 for (map<string, Stream *>::const_iterator stream_it = streams.begin();
215 stream_it != streams.end();
217 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
222 void Server::add_client(int sock)
224 MutexLock lock(&mutex);
225 clients.insert(make_pair(sock, Client(sock)));
227 // Start listening on data from this socket.
229 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
230 ev.data.u64 = 0; // Keep Valgrind happy.
232 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
233 perror("epoll_ctl(EPOLL_CTL_ADD)");
237 process_client(&clients[sock]);
240 void Server::add_client_from_serialized(const ClientProto &client)
242 MutexLock lock(&mutex);
243 Stream *stream = find_stream(client.stream_id());
244 clients.insert(make_pair(client.sock(), Client(client, stream)));
245 Client *client_ptr = &clients[client.sock()];
247 // Start listening on data from this socket.
249 if (client.state() == Client::READING_REQUEST) {
250 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
252 // If we don't have more data for this client, we'll be putting it into
253 // the sleeping array again soon.
254 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
256 ev.data.u64 = 0; // Keep Valgrind happy.
257 ev.data.fd = client.sock();
258 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
259 perror("epoll_ctl(EPOLL_CTL_ADD)");
263 if (client_ptr->state == Client::SENDING_DATA &&
264 client_ptr->bytes_sent == client_ptr->stream->data_size) {
265 client_ptr->stream->put_client_to_sleep(client_ptr);
267 process_client(client_ptr);
271 void Server::add_stream(const string &stream_id)
273 MutexLock lock(&mutex);
274 streams.insert(make_pair(stream_id, new Stream(stream_id)));
277 void Server::add_stream_from_serialized(const StreamProto &stream)
279 MutexLock lock(&mutex);
280 streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
283 void Server::set_header(const string &stream_id, const string &header)
285 MutexLock lock(&mutex);
286 find_stream(stream_id)->header = header;
288 // If there are clients we haven't sent anything to yet, we should give
289 // them the header, so push back into the SENDING_HEADER state.
290 for (map<int, Client>::iterator client_it = clients.begin();
291 client_it != clients.end();
293 Client *client = &client_it->second;
294 if (client->state == Client::SENDING_DATA &&
295 client->bytes_sent == 0) {
296 construct_header(client);
301 void Server::add_data(const string &stream_id, const char *data, size_t bytes)
307 MutexLock lock(&mutex);
308 Stream *stream = find_stream(stream_id);
309 size_t pos = stream->data_size % BACKLOG_SIZE;
310 stream->data_size += bytes;
312 if (pos + bytes > BACKLOG_SIZE) {
313 size_t to_copy = BACKLOG_SIZE - pos;
314 memcpy(stream->data + pos, data, to_copy);
320 memcpy(stream->data + pos, data, bytes);
321 stream->wake_up_all_clients();
324 // See the .h file for postconditions after this function.
325 void Server::process_client(Client *client)
327 switch (client->state) {
328 case Client::READING_REQUEST: {
330 // Try to read more of the request.
334 ret = read(client->sock, buf, sizeof(buf));
335 } while (ret == -1 && errno == EINTR);
337 if (ret == -1 && errno == EAGAIN) {
338 // No more data right now. Nothing to do.
339 // This is postcondition #2.
344 close_client(client);
348 // OK, the socket is closed.
349 close_client(client);
353 // Guard against overlong requests gobbling up all of our space.
354 if (client->request.size() + ret > MAX_CLIENT_REQUEST) {
355 fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
356 close_client(client);
360 // See if we have \r\n\r\n anywhere in the request. We start three bytes
361 // before what we just appended, in case we just got the final character.
362 size_t existing_req_bytes = client->request.size();
363 client->request.append(string(buf, buf + ret));
365 size_t start_at = (existing_req_bytes >= 3 ? existing_req_bytes - 3 : 0);
366 const char *ptr = reinterpret_cast<char *>(
367 memmem(client->request.data() + start_at, client->request.size() - start_at,
370 // OK, we don't have the entire header yet. Fine; we'll get it later.
371 // See if there's more data for us.
372 goto read_request_again;
375 if (ptr != client->request.data() + client->request.size() - 4) {
376 fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
377 close_client(client);
381 int error_code = parse_request(client);
382 if (error_code == 200) {
383 construct_header(client);
385 construct_error(client, error_code);
388 // We've changed states, so fall through.
389 assert(client->state == Client::SENDING_ERROR ||
390 client->state == Client::SENDING_HEADER);
392 case Client::SENDING_ERROR:
393 case Client::SENDING_HEADER: {
394 sending_header_or_error_again:
397 ret = write(client->sock,
398 client->header_or_error.data() + client->header_or_error_bytes_sent,
399 client->header_or_error.size() - client->header_or_error_bytes_sent);
400 } while (ret == -1 && errno == EINTR);
402 if (ret == -1 && errno == EAGAIN) {
403 // We're out of socket space, so now we're at the “low edge” of epoll's
404 // edge triggering. epoll will tell us when there is more room, so for now,
406 // This is postcondition #4.
411 // Error! Postcondition #1.
413 close_client(client);
417 client->header_or_error_bytes_sent += ret;
418 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
420 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
421 // We haven't sent all yet. Fine; go another round.
422 goto sending_header_or_error_again;
425 // We're done sending the header or error! Clear it to release some memory.
426 client->header_or_error.clear();
428 if (client->state == Client::SENDING_ERROR) {
429 // We're done sending the error, so now close.
430 // This is postcondition #1.
431 close_client(client);
435 // Start sending from the end. In other words, we won't send any of the backlog,
436 // but we'll start sending immediately as we get data.
437 // This is postcondition #3.
438 client->state = Client::SENDING_DATA;
439 client->bytes_sent = client->stream->data_size;
440 client->stream->put_client_to_sleep(client);
443 case Client::SENDING_DATA: {
444 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
445 // but resync will be the mux's problem.
446 Stream *stream = client->stream;
447 size_t bytes_to_send = stream->data_size - client->bytes_sent;
448 if (bytes_to_send == 0) {
451 if (bytes_to_send > BACKLOG_SIZE) {
452 fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
454 (long long int)(bytes_to_send - BACKLOG_SIZE));
455 client->bytes_sent = stream->data_size - BACKLOG_SIZE;
456 bytes_to_send = BACKLOG_SIZE;
459 // See if we need to split across the circular buffer.
461 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
462 size_t bytes_first_part = BACKLOG_SIZE - (client->bytes_sent % BACKLOG_SIZE);
465 iov[0].iov_base = const_cast<char *>(stream->data + (client->bytes_sent % BACKLOG_SIZE));
466 iov[0].iov_len = bytes_first_part;
468 iov[1].iov_base = const_cast<char *>(stream->data);
469 iov[1].iov_len = bytes_to_send - bytes_first_part;
472 ret = writev(client->sock, iov, 2);
473 } while (ret == -1 && errno == EINTR);
476 ret = write(client->sock,
477 stream->data + (client->bytes_sent % BACKLOG_SIZE),
479 } while (ret == -1 && errno == EINTR);
481 if (ret == -1 && errno == EAGAIN) {
482 // We're out of socket space, so return; epoll will wake us up
483 // when there is more room.
484 // This is postcondition #4.
488 // Error, close; postcondition #1.
489 perror("write/writev");
490 close_client(client);
493 client->bytes_sent += ret;
495 if (client->bytes_sent == stream->data_size) {
496 // We don't have any more data for this client, so put it to sleep.
497 // This is postcondition #3.
498 stream->put_client_to_sleep(client);
500 // XXX: Do we need to go another round here to explicitly
510 int Server::parse_request(Client *client)
512 vector<string> lines = split_lines(client->request);
514 return 400; // Bad request (empty).
517 vector<string> request_tokens = split_tokens(lines[0]);
518 if (request_tokens.size() < 2) {
519 return 400; // Bad request (empty).
521 if (request_tokens[0] != "GET") {
522 return 400; // Should maybe be 405 instead?
524 if (streams.count(request_tokens[1]) == 0) {
525 return 404; // Not found.
528 client->stream_id = request_tokens[1];
529 client->stream = find_stream(client->stream_id);
530 client->request.clear();
535 void Server::construct_header(Client *client)
537 client->header_or_error = "HTTP/1.0 200 OK\r\nContent-type: video/x-flv\r\nCache-Control: no-cache\r\n\r\n" +
538 find_stream(client->stream_id)->header;
541 client->state = Client::SENDING_HEADER;
544 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
545 ev.data.u64 = 0; // Keep Valgrind happy.
546 ev.data.fd = client->sock;
548 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
549 perror("epoll_ctl(EPOLL_CTL_MOD)");
554 void Server::construct_error(Client *client, int error_code)
557 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
559 client->header_or_error = error;
562 client->state = Client::SENDING_ERROR;
565 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
566 ev.data.u64 = 0; // Keep Valgrind happy.
567 ev.data.fd = client->sock;
569 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
570 perror("epoll_ctl(EPOLL_CTL_MOD)");
575 void Server::close_client(Client *client)
577 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
578 perror("epoll_ctl(EPOLL_CTL_DEL)");
582 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
583 if (client->stream != NULL) {
584 vector<Client *>::iterator new_end =
585 remove(client->stream->sleeping_clients.begin(),
586 client->stream->sleeping_clients.end(),
588 client->stream->sleeping_clients.erase(
589 new_end, client->stream->sleeping_clients.end());
595 ret = close(client->sock);
596 } while (ret == -1 && errno == EINTR);
602 clients.erase(client->sock);
605 Stream *Server::find_stream(const string &stream_id)
607 map<string, Stream *>::iterator it = streams.find(stream_id);
608 assert(it != streams.end());