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 | EPOLLET | 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)");
212 process_client(&clients[sock]);
215 void Server::add_client_from_serialized(const ClientProto &client)
217 MutexLock lock(&mutex);
218 Stream *stream = find_stream(client.stream_id());
219 clients.insert(make_pair(client.sock(), Client(client, stream)));
221 // Start listening on data from this socket.
223 if (client.state() == Client::READING_REQUEST) {
224 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
226 // If we don't have more data for this client, we'll be putting it into
227 // the sleeping array again soon.
228 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
230 ev.data.u64 = 0; // Keep Valgrind happy.
231 ev.data.fd = client.sock();
232 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
233 perror("epoll_ctl(EPOLL_CTL_ADD)");
237 process_client(&clients[client.sock()]);
240 void Server::add_stream(const string &stream_id)
242 MutexLock lock(&mutex);
243 streams.insert(make_pair(stream_id, new Stream(stream_id)));
246 void Server::add_stream_from_serialized(const StreamProto &stream)
248 MutexLock lock(&mutex);
249 streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
252 void Server::set_header(const string &stream_id, const string &header)
254 MutexLock lock(&mutex);
255 find_stream(stream_id)->header = header;
257 // If there are clients we haven't sent anything to yet, we should give
258 // them the header, so push back into the SENDING_HEADER state.
259 for (map<int, Client>::iterator client_it = clients.begin();
260 client_it != clients.end();
262 Client *client = &client_it->second;
263 if (client->state == Client::SENDING_DATA &&
264 client->bytes_sent == 0) {
265 construct_header(client);
270 void Server::add_data(const string &stream_id, const char *data, size_t bytes)
276 MutexLock lock(&mutex);
277 Stream *stream = find_stream(stream_id);
278 size_t pos = stream->data_size % BACKLOG_SIZE;
279 stream->data_size += bytes;
281 if (pos + bytes > BACKLOG_SIZE) {
282 size_t to_copy = BACKLOG_SIZE - pos;
283 memcpy(stream->data + pos, data, to_copy);
289 memcpy(stream->data + pos, data, bytes);
290 wake_up_all_clients();
293 // See the .h file for postconditions after this function.
294 void Server::process_client(Client *client)
296 switch (client->state) {
297 case Client::READING_REQUEST: {
299 // Try to read more of the request.
303 ret = read(client->sock, buf, sizeof(buf));
304 } while (ret == -1 && errno == EINTR);
306 if (ret == -1 && errno == EAGAIN) {
307 // No more data right now. Nothing to do.
308 // This is postcondition #2.
313 close_client(client);
317 // OK, the socket is closed.
318 close_client(client);
322 // Guard against overlong requests gobbling up all of our space.
323 if (client->request.size() + ret > MAX_CLIENT_REQUEST) {
324 fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
325 close_client(client);
329 // See if we have \r\n\r\n anywhere in the request. We start three bytes
330 // before what we just appended, in case we just got the final character.
331 size_t existing_req_bytes = client->request.size();
332 client->request.append(string(buf, buf + ret));
334 size_t start_at = (existing_req_bytes >= 3 ? existing_req_bytes - 3 : 0);
335 const char *ptr = reinterpret_cast<char *>(
336 memmem(client->request.data() + start_at, client->request.size() - start_at,
339 // OK, we don't have the entire header yet. Fine; we'll get it later.
340 // See if there's more data for us.
341 goto read_request_again;
344 if (ptr != client->request.data() + client->request.size() - 4) {
345 fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
346 close_client(client);
350 int error_code = parse_request(client);
351 if (error_code == 200) {
352 construct_header(client);
354 construct_error(client, error_code);
357 // We've changed states, so fall through.
358 assert(client->state == Client::SENDING_ERROR ||
359 client->state == Client::SENDING_HEADER);
361 case Client::SENDING_ERROR:
362 case Client::SENDING_HEADER: {
363 sending_header_or_error_again:
366 ret = write(client->sock,
367 client->header_or_error.data() + client->header_or_error_bytes_sent,
368 client->header_or_error.size() - client->header_or_error_bytes_sent);
369 } while (ret == -1 && errno == EINTR);
371 if (ret == -1 && errno == EAGAIN) {
372 // We're out of socket space, so now we're at the “low edge” of epoll's
373 // edge triggering. epoll will tell us when there is more room, so for now,
375 // This is postcondition #4.
380 // Error! Postcondition #1.
382 close_client(client);
386 client->header_or_error_bytes_sent += ret;
387 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
389 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
390 // We haven't sent all yet. Fine; go another round.
391 goto sending_header_or_error_again;
394 // We're done sending the header or error! Clear it to release some memory.
395 client->header_or_error.clear();
397 if (client->state == Client::SENDING_ERROR) {
398 // We're done sending the error, so now close.
399 // This is postcondition #1.
400 close_client(client);
404 // Start sending from the end. In other words, we won't send any of the backlog,
405 // but we'll start sending immediately as we get data.
406 // This is postcondition #3.
407 client->state = Client::SENDING_DATA;
408 client->bytes_sent = client->stream->data_size;
409 put_client_to_sleep(client);
412 case Client::SENDING_DATA: {
413 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
414 // but resync will be the mux's problem.
415 const Stream *stream = client->stream;
416 size_t bytes_to_send = stream->data_size - client->bytes_sent;
417 if (bytes_to_send == 0) {
420 if (bytes_to_send > BACKLOG_SIZE) {
421 fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
423 (long long int)(bytes_to_send - BACKLOG_SIZE));
424 client->bytes_sent = stream->data_size - BACKLOG_SIZE;
425 bytes_to_send = BACKLOG_SIZE;
428 // See if we need to split across the circular buffer.
430 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
431 size_t bytes_first_part = BACKLOG_SIZE - (client->bytes_sent % BACKLOG_SIZE);
434 iov[0].iov_base = const_cast<char *>(stream->data + (client->bytes_sent % BACKLOG_SIZE));
435 iov[0].iov_len = bytes_first_part;
437 iov[1].iov_base = const_cast<char *>(stream->data);
438 iov[1].iov_len = bytes_to_send - bytes_first_part;
441 ret = writev(client->sock, iov, 2);
442 } while (ret == -1 && errno == EINTR);
445 ret = write(client->sock,
446 stream->data + (client->bytes_sent % BACKLOG_SIZE),
448 } while (ret == -1 && errno == EINTR);
450 if (ret == -1 && errno == EAGAIN) {
451 // We're out of socket space, so return; epoll will wake us up
452 // when there is more room.
453 // This is postcondition #4.
457 // Error, close; postcondition #1.
458 perror("write/writev");
459 close_client(client);
462 client->bytes_sent += ret;
464 if (client->bytes_sent == stream->data_size) {
465 // We don't have any more data for this client, so put it to sleep.
466 // This is postcondition #3.
467 put_client_to_sleep(client);
469 // XXX: Do we need to go another round here to explicitly
479 int Server::parse_request(Client *client)
481 vector<string> lines = split_lines(client->request);
483 return 400; // Bad request (empty).
486 vector<string> request_tokens = split_tokens(lines[0]);
487 if (request_tokens.size() < 2) {
488 return 400; // Bad request (empty).
490 if (request_tokens[0] != "GET") {
491 return 400; // Should maybe be 405 instead?
493 if (streams.count(request_tokens[1]) == 0) {
494 return 404; // Not found.
497 client->stream_id = request_tokens[1];
498 client->stream = find_stream(client->stream_id);
499 client->request.clear();
504 void Server::construct_header(Client *client)
506 client->header_or_error = "HTTP/1.0 200 OK\r\nContent-type: video/x-flv\r\nCache-Control: no-cache\r\n\r\n" +
507 find_stream(client->stream_id)->header;
510 client->state = Client::SENDING_HEADER;
513 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
514 ev.data.u64 = 0; // Keep Valgrind happy.
515 ev.data.fd = client->sock;
517 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
518 perror("epoll_ctl(EPOLL_CTL_MOD)");
523 void Server::construct_error(Client *client, int error_code)
526 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
528 client->header_or_error = error;
531 client->state = Client::SENDING_ERROR;
534 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
535 ev.data.u64 = 0; // Keep Valgrind happy.
536 ev.data.fd = client->sock;
538 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
539 perror("epoll_ctl(EPOLL_CTL_MOD)");
544 void Server::close_client(Client *client)
546 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
547 perror("epoll_ctl(EPOLL_CTL_DEL)");
551 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
552 vector<Client *>::iterator new_end =
553 remove(sleeping_clients.begin(), sleeping_clients.end(), client);
554 sleeping_clients.erase(new_end, sleeping_clients.end());
559 ret = close(client->sock);
560 } while (ret == -1 && errno == EINTR);
566 clients.erase(client->sock);
569 void Server::put_client_to_sleep(Client *client)
571 sleeping_clients.push_back(client);
574 void Server::wake_up_all_clients()
576 vector<Client *> to_process;
577 swap(sleeping_clients, to_process);
578 for (unsigned i = 0; i < to_process.size(); ++i) {
579 process_client(to_process[i]);
583 Stream *Server::find_stream(const string &stream_id)
585 map<string, Stream *>::iterator it = streams.find(stream_id);
586 assert(it != streams.end());