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);
96 pthread_mutex_init(&mutex, NULL);
98 epoll_fd = epoll_create(1024); // Size argument is ignored.
109 ret = close(epoll_fd);
110 } while (ret == -1 && errno == EINTR);
113 perror("close(epoll_fd)");
121 // Joinable is already the default, but it's good to be certain.
123 pthread_attr_init(&attr);
124 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
125 pthread_create(&worker_thread, &attr, Server::do_work_thunk, this);
131 MutexLock lock(&mutex);
135 if (pthread_join(worker_thread, NULL) == -1) {
136 perror("pthread_join");
141 void *Server::do_work_thunk(void *arg)
143 Server *server = static_cast<Server *>(arg);
148 void Server::do_work()
151 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
152 if (nfds == -1 && errno == EINTR) {
156 perror("epoll_wait");
160 MutexLock lock(&mutex); // We release the mutex between iterations.
166 for (int i = 0; i < nfds; ++i) {
167 int fd = events[i].data.fd;
168 assert(clients.count(fd) != 0);
169 Client *client = &clients[fd];
171 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
172 close_client(client);
176 process_client(client);
179 for (unsigned i = 0; i < to_process.size(); ++i) {
180 process_client(to_process[i]);
186 CubemapStateProto Server::serialize() const
188 CubemapStateProto serialized;
189 for (map<int, Client>::const_iterator client_it = clients.begin();
190 client_it != clients.end();
192 serialized.add_clients()->MergeFrom(client_it->second.serialize());
194 for (map<string, Stream *>::const_iterator stream_it = streams.begin();
195 stream_it != streams.end();
197 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
202 void Server::add_client(int sock)
204 MutexLock lock(&mutex);
205 clients.insert(make_pair(sock, Client(sock)));
207 // Start listening on data from this socket.
209 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
210 ev.data.u64 = 0; // Keep Valgrind happy.
212 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
213 perror("epoll_ctl(EPOLL_CTL_ADD)");
217 process_client(&clients[sock]);
220 void Server::add_client_from_serialized(const ClientProto &client)
222 MutexLock lock(&mutex);
223 Stream *stream = find_stream(client.stream_id());
224 clients.insert(make_pair(client.sock(), Client(client, stream)));
225 Client *client_ptr = &clients[client.sock()];
227 // Start listening on data from this socket.
229 if (client.state() == Client::READING_REQUEST) {
230 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
232 // If we don't have more data for this client, we'll be putting it into
233 // the sleeping array again soon.
234 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
236 ev.data.u64 = 0; // Keep Valgrind happy.
237 ev.data.fd = client.sock();
238 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
239 perror("epoll_ctl(EPOLL_CTL_ADD)");
243 if (client_ptr->state == Client::SENDING_DATA &&
244 client_ptr->bytes_sent == client_ptr->stream->data_size) {
245 put_client_to_sleep(client_ptr);
247 process_client(client_ptr);
251 void Server::add_stream(const string &stream_id)
253 MutexLock lock(&mutex);
254 streams.insert(make_pair(stream_id, new Stream(stream_id)));
257 void Server::add_stream_from_serialized(const StreamProto &stream)
259 MutexLock lock(&mutex);
260 streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
263 void Server::set_header(const string &stream_id, const string &header)
265 MutexLock lock(&mutex);
266 find_stream(stream_id)->header = header;
268 // If there are clients we haven't sent anything to yet, we should give
269 // them the header, so push back into the SENDING_HEADER state.
270 for (map<int, Client>::iterator client_it = clients.begin();
271 client_it != clients.end();
273 Client *client = &client_it->second;
274 if (client->state == Client::SENDING_DATA &&
275 client->bytes_sent == 0) {
276 construct_header(client);
281 void Server::add_data(const string &stream_id, const char *data, size_t bytes)
287 MutexLock lock(&mutex);
288 Stream *stream = find_stream(stream_id);
289 size_t pos = stream->data_size % BACKLOG_SIZE;
290 stream->data_size += bytes;
292 if (pos + bytes > BACKLOG_SIZE) {
293 size_t to_copy = BACKLOG_SIZE - pos;
294 memcpy(stream->data + pos, data, to_copy);
300 memcpy(stream->data + pos, data, bytes);
301 wake_up_all_clients();
304 // See the .h file for postconditions after this function.
305 void Server::process_client(Client *client)
307 switch (client->state) {
308 case Client::READING_REQUEST: {
310 // Try to read more of the request.
314 ret = read(client->sock, buf, sizeof(buf));
315 } while (ret == -1 && errno == EINTR);
317 if (ret == -1 && errno == EAGAIN) {
318 // No more data right now. Nothing to do.
319 // This is postcondition #2.
324 close_client(client);
328 // OK, the socket is closed.
329 close_client(client);
333 // Guard against overlong requests gobbling up all of our space.
334 if (client->request.size() + ret > MAX_CLIENT_REQUEST) {
335 fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
336 close_client(client);
340 // See if we have \r\n\r\n anywhere in the request. We start three bytes
341 // before what we just appended, in case we just got the final character.
342 size_t existing_req_bytes = client->request.size();
343 client->request.append(string(buf, buf + ret));
345 size_t start_at = (existing_req_bytes >= 3 ? existing_req_bytes - 3 : 0);
346 const char *ptr = reinterpret_cast<char *>(
347 memmem(client->request.data() + start_at, client->request.size() - start_at,
350 // OK, we don't have the entire header yet. Fine; we'll get it later.
351 // See if there's more data for us.
352 goto read_request_again;
355 if (ptr != client->request.data() + client->request.size() - 4) {
356 fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
357 close_client(client);
361 int error_code = parse_request(client);
362 if (error_code == 200) {
363 construct_header(client);
365 construct_error(client, error_code);
368 // We've changed states, so fall through.
369 assert(client->state == Client::SENDING_ERROR ||
370 client->state == Client::SENDING_HEADER);
372 case Client::SENDING_ERROR:
373 case Client::SENDING_HEADER: {
374 sending_header_or_error_again:
377 ret = write(client->sock,
378 client->header_or_error.data() + client->header_or_error_bytes_sent,
379 client->header_or_error.size() - client->header_or_error_bytes_sent);
380 } while (ret == -1 && errno == EINTR);
382 if (ret == -1 && errno == EAGAIN) {
383 // We're out of socket space, so now we're at the “low edge” of epoll's
384 // edge triggering. epoll will tell us when there is more room, so for now,
386 // This is postcondition #4.
391 // Error! Postcondition #1.
393 close_client(client);
397 client->header_or_error_bytes_sent += ret;
398 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
400 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
401 // We haven't sent all yet. Fine; go another round.
402 goto sending_header_or_error_again;
405 // We're done sending the header or error! Clear it to release some memory.
406 client->header_or_error.clear();
408 if (client->state == Client::SENDING_ERROR) {
409 // We're done sending the error, so now close.
410 // This is postcondition #1.
411 close_client(client);
415 // Start sending from the end. In other words, we won't send any of the backlog,
416 // but we'll start sending immediately as we get data.
417 // This is postcondition #3.
418 client->state = Client::SENDING_DATA;
419 client->bytes_sent = client->stream->data_size;
420 put_client_to_sleep(client);
423 case Client::SENDING_DATA: {
424 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
425 // but resync will be the mux's problem.
426 const Stream *stream = client->stream;
427 size_t bytes_to_send = stream->data_size - client->bytes_sent;
428 if (bytes_to_send == 0) {
431 if (bytes_to_send > BACKLOG_SIZE) {
432 fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
434 (long long int)(bytes_to_send - BACKLOG_SIZE));
435 client->bytes_sent = stream->data_size - BACKLOG_SIZE;
436 bytes_to_send = BACKLOG_SIZE;
439 // See if we need to split across the circular buffer.
441 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
442 size_t bytes_first_part = BACKLOG_SIZE - (client->bytes_sent % BACKLOG_SIZE);
445 iov[0].iov_base = const_cast<char *>(stream->data + (client->bytes_sent % BACKLOG_SIZE));
446 iov[0].iov_len = bytes_first_part;
448 iov[1].iov_base = const_cast<char *>(stream->data);
449 iov[1].iov_len = bytes_to_send - bytes_first_part;
452 ret = writev(client->sock, iov, 2);
453 } while (ret == -1 && errno == EINTR);
456 ret = write(client->sock,
457 stream->data + (client->bytes_sent % BACKLOG_SIZE),
459 } while (ret == -1 && errno == EINTR);
461 if (ret == -1 && errno == EAGAIN) {
462 // We're out of socket space, so return; epoll will wake us up
463 // when there is more room.
464 // This is postcondition #4.
468 // Error, close; postcondition #1.
469 perror("write/writev");
470 close_client(client);
473 client->bytes_sent += ret;
475 if (client->bytes_sent == stream->data_size) {
476 // We don't have any more data for this client, so put it to sleep.
477 // This is postcondition #3.
478 put_client_to_sleep(client);
480 // XXX: Do we need to go another round here to explicitly
490 int Server::parse_request(Client *client)
492 vector<string> lines = split_lines(client->request);
494 return 400; // Bad request (empty).
497 vector<string> request_tokens = split_tokens(lines[0]);
498 if (request_tokens.size() < 2) {
499 return 400; // Bad request (empty).
501 if (request_tokens[0] != "GET") {
502 return 400; // Should maybe be 405 instead?
504 if (streams.count(request_tokens[1]) == 0) {
505 return 404; // Not found.
508 client->stream_id = request_tokens[1];
509 client->stream = find_stream(client->stream_id);
510 client->request.clear();
515 void Server::construct_header(Client *client)
517 client->header_or_error = "HTTP/1.0 200 OK\r\nContent-type: video/x-flv\r\nCache-Control: no-cache\r\n\r\n" +
518 find_stream(client->stream_id)->header;
521 client->state = Client::SENDING_HEADER;
524 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
525 ev.data.u64 = 0; // Keep Valgrind happy.
526 ev.data.fd = client->sock;
528 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
529 perror("epoll_ctl(EPOLL_CTL_MOD)");
534 void Server::construct_error(Client *client, int error_code)
537 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
539 client->header_or_error = error;
542 client->state = Client::SENDING_ERROR;
545 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
546 ev.data.u64 = 0; // Keep Valgrind happy.
547 ev.data.fd = client->sock;
549 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
550 perror("epoll_ctl(EPOLL_CTL_MOD)");
555 void Server::close_client(Client *client)
557 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
558 perror("epoll_ctl(EPOLL_CTL_DEL)");
562 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
563 vector<Client *>::iterator new_end =
564 remove(sleeping_clients.begin(), sleeping_clients.end(), client);
565 sleeping_clients.erase(new_end, sleeping_clients.end());
570 ret = close(client->sock);
571 } while (ret == -1 && errno == EINTR);
577 clients.erase(client->sock);
580 void Server::put_client_to_sleep(Client *client)
582 sleeping_clients.push_back(client);
585 void Server::wake_up_all_clients()
587 if (to_process.empty()) {
588 swap(sleeping_clients, to_process);
590 to_process.insert(to_process.end(), sleeping_clients.begin(), sleeping_clients.end());
591 sleeping_clients.clear();
595 Stream *Server::find_stream(const string &stream_id)
597 map<string, Stream *>::iterator it = streams.find(stream_id);
598 assert(it != streams.end());