]> git.sesse.net Git - cubemap/blob - server.h
Fix infinite CPU usage on waitpid().
[cubemap] / server.h
1 #ifndef _SERVER_H
2 #define _SERVER_H 1
3
4 #include <stddef.h>
5 #include <stdint.h>
6 #include <sys/epoll.h>
7 #include <sys/types.h>
8 #include <time.h>
9 #include <memory>
10 #include <mutex>
11 #include <queue>
12 #include <string>
13 #include <unordered_map>
14 #include <vector>
15
16 #include "tlse.h"
17
18 #include "client.h"
19 #include "stream.h"
20 #include "thread.h"
21
22 class Acceptor;
23 class ClientProto;
24 struct Stream;
25
26 #define EPOLL_MAX_EVENTS 8192
27 #define EPOLL_TIMEOUT_MS 20
28 #define MAX_CLIENT_REQUEST 16384
29 #define REQUEST_READ_TIMEOUT_SEC 60
30
31 class CubemapStateProto;
32 class StreamProto;
33 class HLSZombieProto;
34
35 // See Server::hls_zombies, below.
36 struct HLSZombie {
37         std::string remote_addr;
38         std::string url;
39         std::string referer;
40         std::string user_agent;
41         timespec expires;
42 };
43
44 class Server : public Thread {
45 public:
46         Server();
47         ~Server();
48
49         // Get the list of all currently connected clients.     
50         std::vector<ClientStats> get_client_stats() const;
51
52         // See hls_zombies, below.
53         std::vector<HLSZombie> get_hls_zombies();
54
55         // Set header (both HTTP header and any stream headers) for the given stream.
56         void set_header(int stream_index,
57                         const std::string &http_header,
58                         const std::string &stream_header);
59
60         // Sets the given stream as unavailable (will always return 503 to new clients).
61         void set_unavailable(int stream_index);
62
63         // Set that the given stream should use the given max pacing rate from now on.
64         // NOTE: This should be set before any clients are connected!
65         void set_pacing_rate(int stream_index, uint32_t pacing_rate);
66
67         // These will be deferred until the next time an iteration in do_work() happens,
68         // and the order between them are undefined.
69         // XXX: header should ideally be ordered with respect to data.
70         void add_client_deferred(int sock, Acceptor *acceptor);
71         void add_data_deferred(int stream_index, const char *data, size_t bytes, uint16_t metacube_flags, const RationalPTS &pts);
72
73         // These should not be called while running, since that would violate
74         // threading assumptions (ie., that epoll is only called from one thread
75         // at the same time).
76         CubemapStateProto serialize(std::unordered_map<const std::string *, size_t> *short_response_pool);
77         void add_client_from_serialized(const ClientProto &client, const std::vector<std::shared_ptr<const std::string>> &short_responses);
78         int add_stream(const std::string &url,
79                        const std::string &hls_url,
80                        size_t bytes_received,
81                        size_t prebuffering_bytes,
82                        Stream::Encoding encoding,
83                        Stream::Encoding src_encoding,
84                        unsigned hls_frag_duration,
85                        size_t hls_backlog_margin,
86                        const std::string &allow_origin);
87         int add_stream_from_serialized(const StreamProto &stream, int data_fd);
88         void add_hls_zombie_from_serialized(const HLSZombieProto &hls_zombie);
89         int lookup_stream_by_url(const std::string &url) const;
90         void set_backlog_size(int stream_index, size_t new_size);
91         void set_prebuffering_bytes(int stream_index, size_t new_amount);
92         void set_encoding(int stream_index, Stream::Encoding encoding);
93         void set_src_encoding(int stream_index, Stream::Encoding encoding);
94         void set_hls_frag_duration(int stream_index, unsigned hls_frag_duration);
95         void set_hls_backlog_margin(int stream_index, size_t hls_backlog_margin);
96         void set_allow_origin(int stream_index, const std::string &allow_origin);
97         void register_hls_url(int stream_index, const std::string &hls_url);
98         void add_gen204(const std::string &url, const std::string &allow_origin);
99         void create_tls_context_for_acceptor(const Acceptor *acceptor);
100
101 private:
102         // Mutex protecting queued_add_clients.
103         // Note that if you want to hold both this and <mu> below,
104         // you will need to take <mu> before this one.
105         mutable std::mutex queued_clients_mutex;
106
107         // Deferred commands that should be run from the do_work() thread as soon as possible.
108         // We defer these for two reasons:
109         //
110         //  - We only want to fiddle with epoll from one thread at any given time,
111         //    and doing add_client() from the acceptor thread would violate that.
112         //  - We don't want the input thread(s) hanging on <mu> when doing
113         //    add_data(), since they want to do add_data() rather often, and <mu>
114         //    can be taken a lot of the time.
115         //      
116         // Protected by <queued_clients_mutex>.
117         std::vector<std::pair<int, Acceptor *>> queued_add_clients;
118
119         // All variables below this line are protected by the mutex.
120         mutable std::mutex mu;
121
122         // All streams.
123         std::vector<std::unique_ptr<Stream>> streams;
124
125         // Map from URL to index into <streams>.
126         std::unordered_map<std::string, int> stream_url_map, stream_hls_url_map;
127
128         // Map from URL to CORS Allow-Origin header (or empty string).
129         std::unordered_map<std::string, std::string> ping_url_map;
130
131         // Map from file descriptor to client.
132         std::unordered_map<int, Client> clients;
133
134         // A list of all clients, ordered by the time they connected (first element),
135         // and their file descriptor (second element). It is ordered by connection time
136         // (and thus also by read timeout time) so that we can read clients from the
137         // start and stop processing once we get to one that isn't ready to be
138         // timed out yet (which means we only have to look at each client exactly once,
139         // save for the first element of the queue, which is always checked).
140         //
141         // Note that when we delete a client, we don't update this queue.
142         // This means that when reading it, we need to check if the client it
143         // describes is still exists (ie., that the fd still exists, and that
144         // the timespec matches).
145         std::queue<std::pair<timespec, int>> clients_ordered_by_connect_time;
146
147         // HLS is harder to keep viewer statistics for than regular streams,
148         // since there's no 1:1 mapping between ongoing HTTP connections and
149         // actual viewers. After a HLS fragment has been successfully sent,
150         // we keep a note of that in this structure, so that we can add some
151         // fake entries in the .stats file for clients that we believe are still
152         // watching, but are not downloading anything right now. We clean this
153         // out whenever we write statistics centrally.
154         //
155         // The structure is keyed by X-Playback-Session-Id if it exists
156         // (typically iOS clients) or IP address otherwise; we can't use the socket,
157         // since clients can (and do) keep open multiple HTTP connections for
158         // the same video playack session, and may also close the socket
159         // between downloading fragments. This means multiple clients between
160         // the same NAT may be undercounted, but that's how it is.
161         std::unordered_map<std::string, HLSZombie> hls_zombies;
162
163         // Used for epoll implementation (obviously).
164         int epoll_fd;
165         epoll_event events[EPOLL_MAX_EVENTS];
166
167         // For each TLS-enabled acceptor, our private server context for its key pair.
168         std::unordered_map<const Acceptor *, TLSContext *> tls_server_contexts;
169
170         // The actual worker thread.
171         virtual void do_work();
172
173         // Process a client; read and write data as far as we can.
174         // After this call, one of these four is true:
175         //
176         //  1. The socket is closed, and the client deleted.
177         //  2. We are still waiting for more data from the client.
178         //  3. We've sent all the data we have to the client,
179         //     and put it in <sleeping_clients>.
180         //  4. The socket buffer is full (which means we still have
181         //     data outstanding).
182         //
183         // For #2, we listen for EPOLLIN events. For #3 and #4, we listen
184         // for EPOLLOUT in edge-triggered mode; it will never fire for #3,
185         // but it's cheaper than taking it in and out all the time.
186         void process_client(Client *client);
187
188         // If the TLS library wants to write anything to this client,
189         // output it. Returns true if the processing should go to sleep
190         // (an error, or lack of outgoing buffer space).
191         bool send_pending_tls_data(Client *client);
192
193         // Reads regular data fro ma socket. Returns -1 if the processing
194         // should go to sleep (an error, or no data available yet), otherwise
195         // the number of bytes read.
196         int read_plain_data(Client *client, char *buf, size_t max_size);
197
198         // Reads (decrypted) data from a TLS socket. Returns -1 if the processing
199         // should go to sleep (an error, or no data available yet), otherwise
200         // the number of bytes read. The buffer will be used as scratch space
201         // for TLS data, so it can be overwritten by more bytes than what is returned.
202         int read_tls_data(Client *client, char *buf, size_t max_size);
203
204         // Close a given client socket, and clean up after it.
205         void close_client(Client *client);
206
207         // Listen for a different set of epoll events.
208         void change_epoll_events(Client *client, uint32_t events);
209
210         // If we're supposed to listen for more requests (persistent HTTP connections),
211         // puts the client back into READING_REQUEST, changes its epoll flags and returns
212         // true.
213         bool more_requests(Client *client);
214
215         // Parse the HTTP request. Returns a HTTP status code (200/204/400/404).
216         int parse_request(Client *client);
217
218         // Construct the HTTP header for a regular stream, and set the client into
219         // the SENDING_HEADER state.
220         void construct_stream_header(Client *client);
221
222         // Construct a HLS playlist (or get it from the cache), and set the client into
223         // the SENDING_HEADER state.
224         void construct_hls_playlist(Client *client);
225
226         // Construct a generic error with the given line, and set the client into
227         // the SENDING_SHORT_RESPONSE state.
228         void construct_error(Client *client, int error_code);
229
230         // Construct a 204, and set the client into the SENDING_SHORT_RESPONSE state.
231         void construct_204(Client *client);
232
233         void process_queued_data();
234         void skip_lost_data(Client *client);
235
236         void add_client(int sock, Acceptor *acceptor);
237
238         // Mark that a client just went into READING_REQUEST state, so we should
239         // note the current time of day and then put it into <clients_ordered_by_connect_time>.
240         void start_client_timeout_timer(Client *client);
241 };
242
243 #endif  // !defined(_SERVER_H)