7 #include <sys/socket.h>
10 #include <sys/ioctl.h>
11 #include <sys/epoll.h>
20 #include "mutexlock.h"
25 Client::Client(int sock)
27 state(Client::READING_REQUEST),
31 request.reserve(1024);
34 Client::Client(const ClientProto &serialized)
35 : sock(serialized.sock()),
36 state(State(serialized.state())),
37 request(serialized.request()),
38 stream_id(serialized.stream_id()),
39 header(serialized.header()),
40 header_bytes_sent(serialized.header_bytes_sent()),
41 bytes_sent(serialized.bytes_sent())
45 ClientProto Client::serialize() const
47 ClientProto serialized;
48 serialized.set_sock(sock);
49 serialized.set_state(state);
50 serialized.set_request(request);
51 serialized.set_stream_id(stream_id);
52 serialized.set_header(header);
53 serialized.set_header_bytes_sent(serialized.header_bytes_sent());
54 serialized.set_bytes_sent(bytes_sent);
58 Stream::Stream(const string &stream_id)
59 : stream_id(stream_id),
60 data(new char[BACKLOG_SIZE]),
63 memset(data, 0, BACKLOG_SIZE);
71 Stream::Stream(const StreamProto &serialized)
72 : header(serialized.header()),
73 data(new char[BACKLOG_SIZE]),
74 data_size(serialized.data_size())
76 assert(serialized.data().size() == BACKLOG_SIZE);
77 memcpy(data, serialized.data().data(), BACKLOG_SIZE);
80 StreamProto Stream::serialize() const
82 StreamProto serialized;
83 serialized.set_header(header);
84 serialized.set_data(string(data, data + BACKLOG_SIZE));
85 serialized.set_data_size(data_size);
91 pthread_mutex_init(&mutex, NULL);
93 epoll_fd = epoll_create(1024); // Size argument is ignored.
104 // Joinable is already the default, but it's good to be certain.
106 pthread_attr_init(&attr);
107 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
108 pthread_create(&worker_thread, &attr, Server::do_work_thunk, this);
114 MutexLock lock(&mutex);
118 if (pthread_join(worker_thread, NULL) == -1) {
119 perror("pthread_join");
124 void *Server::do_work_thunk(void *arg)
126 Server *server = static_cast<Server *>(arg);
131 void Server::do_work()
134 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
136 perror("epoll_wait");
140 MutexLock lock(&mutex); // We release the mutex between iterations.
146 for (int i = 0; i < nfds; ++i) {
147 int fd = events[i].data.fd;
148 assert(clients.count(fd) != 0);
149 Client *client = &clients[fd];
151 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
152 close_client(client);
156 process_client(client);
161 CubemapStateProto Server::serialize() const
163 CubemapStateProto serialized;
164 for (map<int, Client>::const_iterator client_it = clients.begin();
165 client_it != clients.end();
167 serialized.add_clients()->MergeFrom(client_it->second.serialize());
169 for (map<string, Stream *>::const_iterator stream_it = streams.begin();
170 stream_it != streams.end();
172 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
177 void Server::add_client(int sock)
179 MutexLock lock(&mutex);
180 clients.insert(make_pair(sock, Client(sock)));
182 // Start listening on data from this socket.
184 ev.events = EPOLLIN | EPOLLRDHUP;
185 ev.data.u64 = 0; // Keep Valgrind happy.
187 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
188 perror("epoll_ctl(EPOLL_CTL_ADD)");
193 void Server::add_stream(const string &stream_id)
195 MutexLock lock(&mutex);
196 streams.insert(make_pair(stream_id, new Stream(stream_id)));
199 void Server::set_header(const string &stream_id, const string &header)
201 MutexLock lock(&mutex);
202 find_stream(stream_id)->header = header;
204 // If there are clients we haven't sent anything to yet, we should give
205 // them the header, so push back into the SENDING_HEADER state.
206 for (map<int, Client>::iterator client_it = clients.begin();
207 client_it != clients.end();
209 Client *client = &client_it->second;
210 if (client->state == Client::SENDING_DATA &&
211 client->bytes_sent == 0) {
212 construct_header(client);
217 void Server::add_data(const string &stream_id, const char *data, size_t bytes)
223 MutexLock lock(&mutex);
224 Stream *stream = find_stream(stream_id);
225 size_t pos = stream->data_size % BACKLOG_SIZE;
226 stream->data_size += bytes;
228 if (pos + bytes > BACKLOG_SIZE) {
229 size_t to_copy = BACKLOG_SIZE - pos;
230 memcpy(stream->data + pos, data, to_copy);
236 memcpy(stream->data + pos, data, bytes);
237 wake_up_all_clients();
240 void Server::process_client(Client *client)
242 switch (client->state) {
243 case Client::READING_REQUEST: {
244 // Try to read more of the request.
246 int ret = read(client->sock, buf, sizeof(buf));
249 close_client(client);
253 // No data? This really means that we were triggered for something else than
254 // POLLIN (which suggests a logic error in epoll).
255 fprintf(stderr, "WARNING: fd %d returned unexpectedly 0 bytes!\n", client->sock);
256 close_client(client);
260 // Guard against overlong requests gobbling up all of our space.
261 if (client->request.size() + ret > MAX_CLIENT_REQUEST) {
262 fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
263 close_client(client);
267 // See if we have \r\n\r\n anywhere in the request. We start three bytes
268 // before what we just appended, in case we just got the final character.
269 size_t existing_req_bytes = client->request.size();
270 client->request.append(string(buf, buf + ret));
272 size_t start_at = (existing_req_bytes >= 3 ? existing_req_bytes - 3 : 0);
273 const char *ptr = reinterpret_cast<char *>(
274 memmem(client->request.data() + start_at, client->request.size() - start_at,
277 // OK, we don't have the entire header yet. Fine; we'll get it later.
281 if (ptr != client->request.data() + client->request.size() - 4) {
282 fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
283 close_client(client);
287 parse_request(client);
288 construct_header(client);
291 case Client::SENDING_HEADER: {
292 int ret = write(client->sock,
293 client->header.data() + client->header_bytes_sent,
294 client->header.size() - client->header_bytes_sent);
297 close_client(client);
301 client->header_bytes_sent += ret;
302 assert(client->header_bytes_sent <= client->header.size());
304 if (client->header_bytes_sent < client->header.size()) {
305 // We haven't sent all yet. Fine; we'll do that later.
309 // We're done sending the header! Clear the entire header to release some memory.
310 client->header.clear();
312 // Start sending from the end. In other words, we won't send any of the backlog,
313 // but we'll start sending immediately as we get data.
314 client->state = Client::SENDING_DATA;
315 client->bytes_sent = find_stream(client->stream_id)->data_size;
318 case Client::SENDING_DATA: {
319 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
320 // but resync will be the mux's problem.
321 const Stream &stream = *find_stream(client->stream_id);
322 size_t bytes_to_send = stream.data_size - client->bytes_sent;
323 if (bytes_to_send > BACKLOG_SIZE) {
324 fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
326 (long long int)(bytes_to_send - BACKLOG_SIZE));
327 client->bytes_sent = find_stream(client->stream_id)->data_size - BACKLOG_SIZE;
328 bytes_to_send = BACKLOG_SIZE;
331 // See if we need to split across the circular buffer.
333 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
334 size_t bytes_first_part = BACKLOG_SIZE - (client->bytes_sent % BACKLOG_SIZE);
337 iov[0].iov_base = const_cast<char *>(stream.data + (client->bytes_sent % BACKLOG_SIZE));
338 iov[0].iov_len = bytes_first_part;
340 iov[1].iov_base = const_cast<char *>(stream.data);
341 iov[1].iov_len = bytes_to_send - bytes_first_part;
343 ret = writev(client->sock, iov, 2);
345 ret = write(client->sock,
346 stream.data + (client->bytes_sent % BACKLOG_SIZE),
350 perror("write/writev");
351 close_client(client);
354 client->bytes_sent += ret;
356 if (client->bytes_sent == stream.data_size) {
357 // We don't have any more data for this client, so put it to sleep.
358 put_client_to_sleep(client);
367 void Server::parse_request(Client *client)
369 // TODO: Actually parse the request. :-)
370 client->stream_id = "stream";
371 client->request.clear();
374 void Server::construct_header(Client *client)
376 client->header = "HTTP/1.0 200 OK\r\nContent-type: video/x-flv\r\nCache-Control: no-cache\r\n\r\n" +
377 find_stream(client->stream_id)->header;
380 client->state = Client::SENDING_HEADER;
383 ev.events = EPOLLOUT | EPOLLRDHUP;
384 ev.data.u64 = 0; // Keep Valgrind happy.
385 ev.data.fd = client->sock;
387 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
388 perror("epoll_ctl(EPOLL_CTL_MOD)");
393 void Server::close_client(Client *client)
395 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
396 perror("epoll_ctl(EPOLL_CTL_DEL)");
400 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
401 vector<int>::iterator new_end =
402 remove(sleeping_clients.begin(), sleeping_clients.end(), client->sock);
403 sleeping_clients.erase(new_end, sleeping_clients.end());
407 clients.erase(client->sock);
410 void Server::put_client_to_sleep(Client *client)
413 ev.events = EPOLLRDHUP;
414 ev.data.u64 = 0; // Keep Valgrind happy.
415 ev.data.fd = client->sock;
417 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
418 perror("epoll_ctl(EPOLL_CTL_MOD)");
422 sleeping_clients.push_back(client->sock);
425 void Server::wake_up_all_clients()
427 for (unsigned i = 0; i < sleeping_clients.size(); ++i) {
429 ev.events = EPOLLOUT | EPOLLRDHUP;
430 ev.data.u64 = 0; // Keep Valgrind happy.
431 ev.data.fd = sleeping_clients[i];
432 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, sleeping_clients[i], &ev) == -1) {
433 perror("epoll_ctl(EPOLL_CTL_MOD)");
437 sleeping_clients.clear();
440 Stream *Server::find_stream(const string &stream_id)
442 map<string, Stream *>::iterator it = streams.find(stream_id);
443 assert(it != streams.end());