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