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),
29 header_or_error_bytes_sent(0),
32 request.reserve(1024);
35 Client::Client(const ClientProto &serialized)
36 : sock(serialized.sock()),
37 state(State(serialized.state())),
38 request(serialized.request()),
39 stream_id(serialized.stream_id()),
40 header_or_error(serialized.header_or_error()),
41 header_or_error_bytes_sent(serialized.header_or_error_bytes_sent()),
42 bytes_sent(serialized.bytes_sent())
46 ClientProto Client::serialize() const
48 ClientProto serialized;
49 serialized.set_sock(sock);
50 serialized.set_state(state);
51 serialized.set_request(request);
52 serialized.set_stream_id(stream_id);
53 serialized.set_header_or_error(header_or_error);
54 serialized.set_header_or_error_bytes_sent(serialized.header_or_error_bytes_sent());
55 serialized.set_bytes_sent(bytes_sent);
59 Stream::Stream(const string &stream_id)
60 : stream_id(stream_id),
61 data(new char[BACKLOG_SIZE]),
64 memset(data, 0, BACKLOG_SIZE);
72 Stream::Stream(const StreamProto &serialized)
73 : stream_id(serialized.stream_id()),
74 header(serialized.header()),
75 data(new char[BACKLOG_SIZE]),
76 data_size(serialized.data_size())
78 assert(serialized.data().size() == BACKLOG_SIZE);
79 memcpy(data, serialized.data().data(), BACKLOG_SIZE);
82 StreamProto Stream::serialize() const
84 StreamProto serialized;
85 serialized.set_header(header);
86 serialized.set_data(string(data, data + BACKLOG_SIZE));
87 serialized.set_data_size(data_size);
88 serialized.set_stream_id(stream_id);
94 pthread_mutex_init(&mutex, NULL);
96 epoll_fd = epoll_create(1024); // Size argument is ignored.
107 ret = close(epoll_fd);
108 } while (ret == -1 && errno == EINTR);
111 perror("close(epoll_fd)");
119 // Joinable is already the default, but it's good to be certain.
121 pthread_attr_init(&attr);
122 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
123 pthread_create(&worker_thread, &attr, Server::do_work_thunk, this);
129 MutexLock lock(&mutex);
133 if (pthread_join(worker_thread, NULL) == -1) {
134 perror("pthread_join");
139 void *Server::do_work_thunk(void *arg)
141 Server *server = static_cast<Server *>(arg);
146 void Server::do_work()
149 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
150 if (nfds == -1 && errno == EINTR) {
154 perror("epoll_wait");
158 MutexLock lock(&mutex); // We release the mutex between iterations.
164 for (int i = 0; i < nfds; ++i) {
165 int fd = events[i].data.fd;
166 assert(clients.count(fd) != 0);
167 Client *client = &clients[fd];
169 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
170 close_client(client);
174 process_client(client);
179 CubemapStateProto Server::serialize() const
181 CubemapStateProto serialized;
182 for (map<int, Client>::const_iterator client_it = clients.begin();
183 client_it != clients.end();
185 serialized.add_clients()->MergeFrom(client_it->second.serialize());
187 for (map<string, Stream *>::const_iterator stream_it = streams.begin();
188 stream_it != streams.end();
190 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
195 void Server::add_client(int sock)
197 MutexLock lock(&mutex);
198 clients.insert(make_pair(sock, Client(sock)));
200 // Start listening on data from this socket.
202 ev.events = EPOLLIN | EPOLLRDHUP;
203 ev.data.u64 = 0; // Keep Valgrind happy.
205 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
206 perror("epoll_ctl(EPOLL_CTL_ADD)");
211 void Server::add_client_from_serialized(const ClientProto &client)
213 MutexLock lock(&mutex);
214 clients.insert(make_pair(client.sock(), Client(client)));
216 // Start listening on data from this socket.
218 if (client.state() == Client::READING_REQUEST) {
219 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
221 // If we don't have more data for this client, we'll be putting it into
222 // the sleeping array again soon.
223 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
225 ev.data.u64 = 0; // Keep Valgrind happy.
226 ev.data.fd = client.sock();
227 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
228 perror("epoll_ctl(EPOLL_CTL_ADD)");
233 void Server::add_stream(const string &stream_id)
235 MutexLock lock(&mutex);
236 streams.insert(make_pair(stream_id, new Stream(stream_id)));
239 void Server::add_stream_from_serialized(const StreamProto &stream)
241 MutexLock lock(&mutex);
242 streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
245 void Server::set_header(const string &stream_id, const string &header)
247 MutexLock lock(&mutex);
248 find_stream(stream_id)->header = header;
250 // If there are clients we haven't sent anything to yet, we should give
251 // them the header, so push back into the SENDING_HEADER state.
252 for (map<int, Client>::iterator client_it = clients.begin();
253 client_it != clients.end();
255 Client *client = &client_it->second;
256 if (client->state == Client::SENDING_DATA &&
257 client->bytes_sent == 0) {
258 construct_header(client);
263 void Server::add_data(const string &stream_id, const char *data, size_t bytes)
269 MutexLock lock(&mutex);
270 Stream *stream = find_stream(stream_id);
271 size_t pos = stream->data_size % BACKLOG_SIZE;
272 stream->data_size += bytes;
274 if (pos + bytes > BACKLOG_SIZE) {
275 size_t to_copy = BACKLOG_SIZE - pos;
276 memcpy(stream->data + pos, data, to_copy);
282 memcpy(stream->data + pos, data, bytes);
283 wake_up_all_clients();
286 // See the .h file for postconditions after this function.
287 void Server::process_client(Client *client)
289 switch (client->state) {
290 case Client::READING_REQUEST: {
292 // Try to read more of the request.
296 ret = read(client->sock, buf, sizeof(buf));
297 } while (ret == -1 && errno == EINTR);
299 if (ret == -1 && errno == EAGAIN) {
300 // No more data right now. Nothing to do.
301 // This is postcondition #2.
306 close_client(client);
310 // OK, the socket is closed.
311 close_client(client);
315 // Guard against overlong requests gobbling up all of our space.
316 if (client->request.size() + ret > MAX_CLIENT_REQUEST) {
317 fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
318 close_client(client);
322 // See if we have \r\n\r\n anywhere in the request. We start three bytes
323 // before what we just appended, in case we just got the final character.
324 size_t existing_req_bytes = client->request.size();
325 client->request.append(string(buf, buf + ret));
327 size_t start_at = (existing_req_bytes >= 3 ? existing_req_bytes - 3 : 0);
328 const char *ptr = reinterpret_cast<char *>(
329 memmem(client->request.data() + start_at, client->request.size() - start_at,
332 // OK, we don't have the entire header yet. Fine; we'll get it later.
333 // See if there's more data for us.
334 goto read_request_again;
337 if (ptr != client->request.data() + client->request.size() - 4) {
338 fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
339 close_client(client);
343 int error_code = parse_request(client);
344 if (error_code == 200) {
345 construct_header(client);
347 construct_error(client, error_code);
350 // We've changed states, so fall through.
351 assert(client->state == Client::SENDING_ERROR ||
352 client->state == Client::SENDING_HEADER);
354 case Client::SENDING_ERROR:
355 case Client::SENDING_HEADER: {
356 sending_header_or_error_again:
359 ret = write(client->sock,
360 client->header_or_error.data() + client->header_or_error_bytes_sent,
361 client->header_or_error.size() - client->header_or_error_bytes_sent);
362 } while (ret == -1 && errno == EINTR);
364 if (ret == -1 && errno == EAGAIN) {
365 // We're out of socket space, so now we're at the “low edge” of epoll's
366 // edge triggering. epoll will tell us when there is more room, so for now,
368 // This is postcondition #4.
373 // Error! Postcondition #1.
375 close_client(client);
379 client->header_or_error_bytes_sent += ret;
380 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
382 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
383 // We haven't sent all yet. Fine; go another round.
384 goto sending_header_or_error_again;
387 // We're done sending the header or error! Clear it to release some memory.
388 client->header_or_error.clear();
390 if (client->state == Client::SENDING_ERROR) {
391 // We're done sending the error, so now close.
392 // This is postcondition #1.
393 close_client(client);
397 // Start sending from the end. In other words, we won't send any of the backlog,
398 // but we'll start sending immediately as we get data.
399 // This is postcondition #3.
400 client->state = Client::SENDING_DATA;
401 client->bytes_sent = find_stream(client->stream_id)->data_size;
402 sleeping_clients.push_back(client);
405 case Client::SENDING_DATA: {
406 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
407 // but resync will be the mux's problem.
408 const Stream &stream = *find_stream(client->stream_id);
409 size_t bytes_to_send = stream.data_size - client->bytes_sent;
410 if (bytes_to_send > BACKLOG_SIZE) {
411 fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
413 (long long int)(bytes_to_send - BACKLOG_SIZE));
414 client->bytes_sent = find_stream(client->stream_id)->data_size - BACKLOG_SIZE;
415 bytes_to_send = BACKLOG_SIZE;
418 // See if we need to split across the circular buffer.
420 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
421 size_t bytes_first_part = BACKLOG_SIZE - (client->bytes_sent % BACKLOG_SIZE);
424 iov[0].iov_base = const_cast<char *>(stream.data + (client->bytes_sent % BACKLOG_SIZE));
425 iov[0].iov_len = bytes_first_part;
427 iov[1].iov_base = const_cast<char *>(stream.data);
428 iov[1].iov_len = bytes_to_send - bytes_first_part;
431 ret = writev(client->sock, iov, 2);
432 } while (ret == -1 && errno == EINTR);
435 ret = write(client->sock,
436 stream.data + (client->bytes_sent % BACKLOG_SIZE),
438 } while (ret == -1 && errno == EINTR);
440 if (ret == -1 && errno == EAGAIN) {
441 // We're out of socket space, so return; epoll will wake us up
442 // when there is more room.
443 // This is postcondition #4.
447 // Error, close; postcondition #1.
448 perror("write/writev");
449 close_client(client);
452 client->bytes_sent += ret;
454 if (client->bytes_sent == stream.data_size) {
455 // We don't have any more data for this client, so put it to sleep.
456 // This is postcondition #3.
457 put_client_to_sleep(client);
459 // XXX: Do we need to go another round here to explicitly
469 int Server::parse_request(Client *client)
471 vector<string> lines = split_lines(client->request);
473 return 400; // Bad request (empty).
476 vector<string> request_tokens = split_tokens(lines[0]);
477 if (request_tokens.size() < 2) {
478 return 400; // Bad request (empty).
480 if (request_tokens[0] != "GET") {
481 return 400; // Should maybe be 405 instead?
483 if (streams.count(request_tokens[1]) == 0) {
484 return 404; // Not found.
487 client->stream_id = request_tokens[1];
488 client->request.clear();
493 void Server::construct_header(Client *client)
495 client->header_or_error = "HTTP/1.0 200 OK\r\nContent-type: video/x-flv\r\nCache-Control: no-cache\r\n\r\n" +
496 find_stream(client->stream_id)->header;
499 client->state = Client::SENDING_HEADER;
502 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
503 ev.data.u64 = 0; // Keep Valgrind happy.
504 ev.data.fd = client->sock;
506 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
507 perror("epoll_ctl(EPOLL_CTL_MOD)");
512 void Server::construct_error(Client *client, int error_code)
515 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
517 client->header_or_error = error;
520 client->state = Client::SENDING_ERROR;
523 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
524 ev.data.u64 = 0; // Keep Valgrind happy.
525 ev.data.fd = client->sock;
527 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
528 perror("epoll_ctl(EPOLL_CTL_MOD)");
533 void Server::close_client(Client *client)
535 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
536 perror("epoll_ctl(EPOLL_CTL_DEL)");
540 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
541 vector<Client *>::iterator new_end =
542 remove(sleeping_clients.begin(), sleeping_clients.end(), client);
543 sleeping_clients.erase(new_end, sleeping_clients.end());
548 ret = close(client->sock);
549 } while (ret == -1 && errno == EINTR);
555 clients.erase(client->sock);
558 void Server::put_client_to_sleep(Client *client)
560 sleeping_clients.push_back(client);
563 void Server::wake_up_all_clients()
565 vector<Client *> to_process;
566 swap(sleeping_clients, to_process);
567 for (unsigned i = 0; i < to_process.size(); ++i) {
568 process_client(to_process[i]);
572 Stream *Server::find_stream(const string &stream_id)
574 map<string, Stream *>::iterator it = streams.find(stream_id);
575 assert(it != streams.end());