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);
181 CubemapStateProto Server::serialize() const
183 CubemapStateProto serialized;
184 for (map<int, Client>::const_iterator client_it = clients.begin();
185 client_it != clients.end();
187 serialized.add_clients()->MergeFrom(client_it->second.serialize());
189 for (map<string, Stream *>::const_iterator stream_it = streams.begin();
190 stream_it != streams.end();
192 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
197 void Server::add_client(int sock)
199 MutexLock lock(&mutex);
200 clients.insert(make_pair(sock, Client(sock)));
202 // Start listening on data from this socket.
204 ev.events = EPOLLIN | EPOLLRDHUP;
205 ev.data.u64 = 0; // Keep Valgrind happy.
207 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
208 perror("epoll_ctl(EPOLL_CTL_ADD)");
213 void Server::add_client_from_serialized(const ClientProto &client)
215 MutexLock lock(&mutex);
216 Stream *stream = find_stream(client.stream_id());
217 clients.insert(make_pair(client.sock(), Client(client, stream)));
219 // Start listening on data from this socket.
221 if (client.state() == Client::READING_REQUEST) {
222 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
224 // If we don't have more data for this client, we'll be putting it into
225 // the sleeping array again soon.
226 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
228 ev.data.u64 = 0; // Keep Valgrind happy.
229 ev.data.fd = client.sock();
230 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
231 perror("epoll_ctl(EPOLL_CTL_ADD)");
235 process_client(&clients[client.sock()]);
238 void Server::add_stream(const string &stream_id)
240 MutexLock lock(&mutex);
241 streams.insert(make_pair(stream_id, new Stream(stream_id)));
244 void Server::add_stream_from_serialized(const StreamProto &stream)
246 MutexLock lock(&mutex);
247 streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
250 void Server::set_header(const string &stream_id, const string &header)
252 MutexLock lock(&mutex);
253 find_stream(stream_id)->header = header;
255 // If there are clients we haven't sent anything to yet, we should give
256 // them the header, so push back into the SENDING_HEADER state.
257 for (map<int, Client>::iterator client_it = clients.begin();
258 client_it != clients.end();
260 Client *client = &client_it->second;
261 if (client->state == Client::SENDING_DATA &&
262 client->bytes_sent == 0) {
263 construct_header(client);
268 void Server::add_data(const string &stream_id, const char *data, size_t bytes)
274 MutexLock lock(&mutex);
275 Stream *stream = find_stream(stream_id);
276 size_t pos = stream->data_size % BACKLOG_SIZE;
277 stream->data_size += bytes;
279 if (pos + bytes > BACKLOG_SIZE) {
280 size_t to_copy = BACKLOG_SIZE - pos;
281 memcpy(stream->data + pos, data, to_copy);
287 memcpy(stream->data + pos, data, bytes);
288 wake_up_all_clients();
291 // See the .h file for postconditions after this function.
292 void Server::process_client(Client *client)
294 switch (client->state) {
295 case Client::READING_REQUEST: {
297 // Try to read more of the request.
301 ret = read(client->sock, buf, sizeof(buf));
302 } while (ret == -1 && errno == EINTR);
304 if (ret == -1 && errno == EAGAIN) {
305 // No more data right now. Nothing to do.
306 // This is postcondition #2.
311 close_client(client);
315 // OK, the socket is closed.
316 close_client(client);
320 // Guard against overlong requests gobbling up all of our space.
321 if (client->request.size() + ret > MAX_CLIENT_REQUEST) {
322 fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
323 close_client(client);
327 // See if we have \r\n\r\n anywhere in the request. We start three bytes
328 // before what we just appended, in case we just got the final character.
329 size_t existing_req_bytes = client->request.size();
330 client->request.append(string(buf, buf + ret));
332 size_t start_at = (existing_req_bytes >= 3 ? existing_req_bytes - 3 : 0);
333 const char *ptr = reinterpret_cast<char *>(
334 memmem(client->request.data() + start_at, client->request.size() - start_at,
337 // OK, we don't have the entire header yet. Fine; we'll get it later.
338 // See if there's more data for us.
339 goto read_request_again;
342 if (ptr != client->request.data() + client->request.size() - 4) {
343 fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
344 close_client(client);
348 int error_code = parse_request(client);
349 if (error_code == 200) {
350 construct_header(client);
352 construct_error(client, error_code);
355 // We've changed states, so fall through.
356 assert(client->state == Client::SENDING_ERROR ||
357 client->state == Client::SENDING_HEADER);
359 case Client::SENDING_ERROR:
360 case Client::SENDING_HEADER: {
361 sending_header_or_error_again:
364 ret = write(client->sock,
365 client->header_or_error.data() + client->header_or_error_bytes_sent,
366 client->header_or_error.size() - client->header_or_error_bytes_sent);
367 } while (ret == -1 && errno == EINTR);
369 if (ret == -1 && errno == EAGAIN) {
370 // We're out of socket space, so now we're at the “low edge” of epoll's
371 // edge triggering. epoll will tell us when there is more room, so for now,
373 // This is postcondition #4.
378 // Error! Postcondition #1.
380 close_client(client);
384 client->header_or_error_bytes_sent += ret;
385 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
387 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
388 // We haven't sent all yet. Fine; go another round.
389 goto sending_header_or_error_again;
392 // We're done sending the header or error! Clear it to release some memory.
393 client->header_or_error.clear();
395 if (client->state == Client::SENDING_ERROR) {
396 // We're done sending the error, so now close.
397 // This is postcondition #1.
398 close_client(client);
402 // Start sending from the end. In other words, we won't send any of the backlog,
403 // but we'll start sending immediately as we get data.
404 // This is postcondition #3.
405 client->state = Client::SENDING_DATA;
406 client->bytes_sent = client->stream->data_size;
407 put_client_to_sleep(client);
410 case Client::SENDING_DATA: {
411 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
412 // but resync will be the mux's problem.
413 const Stream *stream = client->stream;
414 size_t bytes_to_send = stream->data_size - client->bytes_sent;
415 if (bytes_to_send == 0) {
418 if (bytes_to_send > BACKLOG_SIZE) {
419 fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
421 (long long int)(bytes_to_send - BACKLOG_SIZE));
422 client->bytes_sent = stream->data_size - BACKLOG_SIZE;
423 bytes_to_send = BACKLOG_SIZE;
426 // See if we need to split across the circular buffer.
428 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
429 size_t bytes_first_part = BACKLOG_SIZE - (client->bytes_sent % BACKLOG_SIZE);
432 iov[0].iov_base = const_cast<char *>(stream->data + (client->bytes_sent % BACKLOG_SIZE));
433 iov[0].iov_len = bytes_first_part;
435 iov[1].iov_base = const_cast<char *>(stream->data);
436 iov[1].iov_len = bytes_to_send - bytes_first_part;
439 ret = writev(client->sock, iov, 2);
440 } while (ret == -1 && errno == EINTR);
443 ret = write(client->sock,
444 stream->data + (client->bytes_sent % BACKLOG_SIZE),
446 } while (ret == -1 && errno == EINTR);
448 if (ret == -1 && errno == EAGAIN) {
449 // We're out of socket space, so return; epoll will wake us up
450 // when there is more room.
451 // This is postcondition #4.
455 // Error, close; postcondition #1.
456 perror("write/writev");
457 close_client(client);
460 client->bytes_sent += ret;
462 if (client->bytes_sent == stream->data_size) {
463 // We don't have any more data for this client, so put it to sleep.
464 // This is postcondition #3.
465 put_client_to_sleep(client);
467 // XXX: Do we need to go another round here to explicitly
477 int Server::parse_request(Client *client)
479 vector<string> lines = split_lines(client->request);
481 return 400; // Bad request (empty).
484 vector<string> request_tokens = split_tokens(lines[0]);
485 if (request_tokens.size() < 2) {
486 return 400; // Bad request (empty).
488 if (request_tokens[0] != "GET") {
489 return 400; // Should maybe be 405 instead?
491 if (streams.count(request_tokens[1]) == 0) {
492 return 404; // Not found.
495 client->stream_id = request_tokens[1];
496 client->stream = find_stream(client->stream_id);
497 client->request.clear();
502 void Server::construct_header(Client *client)
504 client->header_or_error = "HTTP/1.0 200 OK\r\nContent-type: video/x-flv\r\nCache-Control: no-cache\r\n\r\n" +
505 find_stream(client->stream_id)->header;
508 client->state = Client::SENDING_HEADER;
511 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
512 ev.data.u64 = 0; // Keep Valgrind happy.
513 ev.data.fd = client->sock;
515 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
516 perror("epoll_ctl(EPOLL_CTL_MOD)");
521 void Server::construct_error(Client *client, int error_code)
524 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
526 client->header_or_error = error;
529 client->state = Client::SENDING_ERROR;
532 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
533 ev.data.u64 = 0; // Keep Valgrind happy.
534 ev.data.fd = client->sock;
536 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
537 perror("epoll_ctl(EPOLL_CTL_MOD)");
542 void Server::close_client(Client *client)
544 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
545 perror("epoll_ctl(EPOLL_CTL_DEL)");
549 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
550 vector<Client *>::iterator new_end =
551 remove(sleeping_clients.begin(), sleeping_clients.end(), client);
552 sleeping_clients.erase(new_end, sleeping_clients.end());
557 ret = close(client->sock);
558 } while (ret == -1 && errno == EINTR);
564 clients.erase(client->sock);
567 void Server::put_client_to_sleep(Client *client)
569 sleeping_clients.push_back(client);
572 void Server::wake_up_all_clients()
574 vector<Client *> to_process;
575 swap(sleeping_clients, to_process);
576 for (unsigned i = 0; i < to_process.size(); ++i) {
577 process_client(to_process[i]);
581 Stream *Server::find_stream(const string &stream_id)
583 map<string, Stream *>::iterator it = streams.find(stream_id);
584 assert(it != streams.end());