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 | 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 | 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 void Server::process_client(Client *client)
288 switch (client->state) {
289 case Client::READING_REQUEST: {
290 // Try to read more of the request.
294 ret = read(client->sock, buf, sizeof(buf));
295 } while (ret == -1 && errno == EINTR);
298 close_client(client);
302 // No data? This really means that we were triggered for something else than
303 // POLLIN (which suggests a logic error in epoll).
304 fprintf(stderr, "WARNING: fd %d returned unexpectedly 0 bytes!\n", client->sock);
305 close_client(client);
309 // Guard against overlong requests gobbling up all of our space.
310 if (client->request.size() + ret > MAX_CLIENT_REQUEST) {
311 fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
312 close_client(client);
316 // See if we have \r\n\r\n anywhere in the request. We start three bytes
317 // before what we just appended, in case we just got the final character.
318 size_t existing_req_bytes = client->request.size();
319 client->request.append(string(buf, buf + ret));
321 size_t start_at = (existing_req_bytes >= 3 ? existing_req_bytes - 3 : 0);
322 const char *ptr = reinterpret_cast<char *>(
323 memmem(client->request.data() + start_at, client->request.size() - start_at,
326 // OK, we don't have the entire header yet. Fine; we'll get it later.
330 if (ptr != client->request.data() + client->request.size() - 4) {
331 fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
332 close_client(client);
336 int error_code = parse_request(client);
337 if (error_code == 200) {
338 construct_header(client);
340 construct_error(client, error_code);
344 case Client::SENDING_ERROR:
345 case Client::SENDING_HEADER: {
348 ret = write(client->sock,
349 client->header_or_error.data() + client->header_or_error_bytes_sent,
350 client->header_or_error.size() - client->header_or_error_bytes_sent);
351 } while (ret == -1 && errno == EINTR);
354 close_client(client);
358 client->header_or_error_bytes_sent += ret;
359 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
361 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
362 // We haven't sent all yet. Fine; we'll do that later.
366 // We're done sending the header or error! Clear it to release some memory.
367 client->header_or_error.clear();
369 if (client->state == Client::SENDING_ERROR) {
370 close_client(client);
372 // Start sending from the end. In other words, we won't send any of the backlog,
373 // but we'll start sending immediately as we get data.
374 client->state = Client::SENDING_DATA;
375 client->bytes_sent = find_stream(client->stream_id)->data_size;
379 case Client::SENDING_DATA: {
380 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
381 // but resync will be the mux's problem.
382 const Stream &stream = *find_stream(client->stream_id);
383 size_t bytes_to_send = stream.data_size - client->bytes_sent;
384 if (bytes_to_send > BACKLOG_SIZE) {
385 fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
387 (long long int)(bytes_to_send - BACKLOG_SIZE));
388 client->bytes_sent = find_stream(client->stream_id)->data_size - BACKLOG_SIZE;
389 bytes_to_send = BACKLOG_SIZE;
392 // See if we need to split across the circular buffer.
394 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
395 size_t bytes_first_part = BACKLOG_SIZE - (client->bytes_sent % BACKLOG_SIZE);
398 iov[0].iov_base = const_cast<char *>(stream.data + (client->bytes_sent % BACKLOG_SIZE));
399 iov[0].iov_len = bytes_first_part;
401 iov[1].iov_base = const_cast<char *>(stream.data);
402 iov[1].iov_len = bytes_to_send - bytes_first_part;
405 ret = writev(client->sock, iov, 2);
406 } while (ret == -1 && errno == EINTR);
409 ret = write(client->sock,
410 stream.data + (client->bytes_sent % BACKLOG_SIZE),
412 } while (ret == -1 && errno == EINTR);
415 perror("write/writev");
416 close_client(client);
419 client->bytes_sent += ret;
421 if (client->bytes_sent == stream.data_size) {
422 // We don't have any more data for this client, so put it to sleep.
423 put_client_to_sleep(client);
432 int Server::parse_request(Client *client)
434 vector<string> lines = split_lines(client->request);
436 return 400; // Bad request (empty).
439 vector<string> request_tokens = split_tokens(lines[0]);
440 if (request_tokens.size() < 2) {
441 return 400; // Bad request (empty).
443 if (request_tokens[0] != "GET") {
444 return 400; // Should maybe be 405 instead?
446 if (streams.count(request_tokens[1]) == 0) {
447 return 404; // Not found.
450 client->stream_id = request_tokens[1];
451 client->request.clear();
456 void Server::construct_header(Client *client)
458 client->header_or_error = "HTTP/1.0 200 OK\r\nContent-type: video/x-flv\r\nCache-Control: no-cache\r\n\r\n" +
459 find_stream(client->stream_id)->header;
462 client->state = Client::SENDING_HEADER;
465 ev.events = EPOLLOUT | EPOLLRDHUP;
466 ev.data.u64 = 0; // Keep Valgrind happy.
467 ev.data.fd = client->sock;
469 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
470 perror("epoll_ctl(EPOLL_CTL_MOD)");
475 void Server::construct_error(Client *client, int error_code)
478 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
480 client->header_or_error = error;
483 client->state = Client::SENDING_ERROR;
486 ev.events = EPOLLOUT | EPOLLRDHUP;
487 ev.data.u64 = 0; // Keep Valgrind happy.
488 ev.data.fd = client->sock;
490 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
491 perror("epoll_ctl(EPOLL_CTL_MOD)");
496 void Server::close_client(Client *client)
498 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
499 perror("epoll_ctl(EPOLL_CTL_DEL)");
503 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
504 vector<int>::iterator new_end =
505 remove(sleeping_clients.begin(), sleeping_clients.end(), client->sock);
506 sleeping_clients.erase(new_end, sleeping_clients.end());
511 ret = close(client->sock);
512 } while (ret == -1 && errno == EINTR);
518 clients.erase(client->sock);
521 void Server::put_client_to_sleep(Client *client)
524 ev.events = 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)");
533 sleeping_clients.push_back(client->sock);
536 void Server::wake_up_all_clients()
538 for (unsigned i = 0; i < sleeping_clients.size(); ++i) {
540 ev.events = EPOLLOUT | EPOLLRDHUP;
541 ev.data.u64 = 0; // Keep Valgrind happy.
542 ev.data.fd = sleeping_clients[i];
543 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, sleeping_clients[i], &ev) == -1) {
544 perror("epoll_ctl(EPOLL_CTL_MOD)");
548 sleeping_clients.clear();
551 Stream *Server::find_stream(const string &stream_id)
553 map<string, Stream *>::iterator it = streams.find(stream_id);
554 assert(it != streams.end());