]> git.sesse.net Git - nageru/blob - httpd.cpp
Do not link kaeru against CEF.
[nageru] / httpd.cpp
1 #include "httpd.h"
2
3 #include <assert.h>
4 #include <byteswap.h>
5 #include <endian.h>
6 #include <microhttpd.h>
7 #include <netinet/in.h>
8 #include <stdio.h>
9 #include <string.h>
10 #include <sys/time.h>
11 #include <time.h>
12 #include <memory>
13
14 #include "defs.h"
15 #include "metacube2.h"
16 #include "metrics.h"
17
18 struct MHD_Connection;
19 struct MHD_Response;
20
21 using namespace std;
22
23 HTTPD::HTTPD()
24 {
25         global_metrics.add("num_connected_clients", &metric_num_connected_clients, Metrics::TYPE_GAUGE);
26 }
27
28 HTTPD::~HTTPD()
29 {
30         if (mhd) {
31                 MHD_quiesce_daemon(mhd);
32                 for (Stream *stream : streams) {
33                         stream->stop();
34                 }
35                 MHD_stop_daemon(mhd);
36         }
37 }
38
39 void HTTPD::start(int port)
40 {
41         mhd = MHD_start_daemon(MHD_USE_THREAD_PER_CONNECTION | MHD_USE_POLL_INTERNALLY | MHD_USE_DUAL_STACK,
42                                port,
43                                nullptr, nullptr,
44                                &answer_to_connection_thunk, this,
45                                MHD_OPTION_NOTIFY_COMPLETED, nullptr, this,
46                                MHD_OPTION_END);
47         if (mhd == nullptr) {
48                 fprintf(stderr, "Warning: Could not open HTTP server. (Port already in use?)\n");
49         }
50 }
51
52 void HTTPD::add_data(const char *buf, size_t size, bool keyframe)
53 {
54         unique_lock<mutex> lock(streams_mutex);
55         for (Stream *stream : streams) {
56                 stream->add_data(buf, size, keyframe ? Stream::DATA_TYPE_KEYFRAME : Stream::DATA_TYPE_OTHER);
57         }
58 }
59
60 int HTTPD::answer_to_connection_thunk(void *cls, MHD_Connection *connection,
61                                       const char *url, const char *method,
62                                       const char *version, const char *upload_data,
63                                       size_t *upload_data_size, void **con_cls)
64 {
65         HTTPD *httpd = (HTTPD *)cls;
66         return httpd->answer_to_connection(connection, url, method, version, upload_data, upload_data_size, con_cls);
67 }
68
69 int HTTPD::answer_to_connection(MHD_Connection *connection,
70                                 const char *url, const char *method,
71                                 const char *version, const char *upload_data,
72                                 size_t *upload_data_size, void **con_cls)
73 {
74         // See if the URL ends in “.metacube”.
75         HTTPD::Stream::Framing framing;
76         if (strstr(url, ".metacube") == url + strlen(url) - strlen(".metacube")) {
77                 framing = HTTPD::Stream::FRAMING_METACUBE;
78         } else {
79                 framing = HTTPD::Stream::FRAMING_RAW;
80         }
81
82         if (strcmp(url, "/metrics") == 0) {
83                 string contents = global_metrics.serialize();
84                 MHD_Response *response = MHD_create_response_from_buffer(
85                         contents.size(), &contents[0], MHD_RESPMEM_MUST_COPY);
86                 MHD_add_response_header(response, "Content-type", "text/plain");
87                 int ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
88                 MHD_destroy_response(response);  // Only decreases the refcount; actual free is after the request is done.
89                 return ret;
90         }
91         if (endpoints.count(url)) {
92                 pair<string, string> contents_and_type = endpoints[url].callback();
93                 MHD_Response *response = MHD_create_response_from_buffer(
94                         contents_and_type.first.size(), &contents_and_type.first[0], MHD_RESPMEM_MUST_COPY);
95                 MHD_add_response_header(response, "Content-type", contents_and_type.second.c_str());
96                 if (endpoints[url].cors_policy == ALLOW_ALL_ORIGINS) {
97                         MHD_add_response_header(response, "Access-Control-Allow-Origin", "*");
98                 }
99                 int ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
100                 MHD_destroy_response(response);  // Only decreases the refcount; actual free is after the request is done.
101                 return ret;
102         }
103
104         // Small hack; reject unknown /channels/foo.
105         if (string(url).find("/channels/") == 0) {
106                 string contents = "Not found.";
107                 MHD_Response *response = MHD_create_response_from_buffer(
108                         contents.size(), &contents[0], MHD_RESPMEM_MUST_COPY);
109                 MHD_add_response_header(response, "Content-type", "text/plain");
110                 int ret = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, response);
111                 MHD_destroy_response(response);  // Only decreases the refcount; actual free is after the request is done.
112                 return ret;
113         }
114
115         HTTPD::Stream *stream = new HTTPD::Stream(this, framing);
116         stream->add_data(header.data(), header.size(), Stream::DATA_TYPE_HEADER);
117         {
118                 unique_lock<mutex> lock(streams_mutex);
119                 streams.insert(stream);
120         }
121         ++metric_num_connected_clients;
122         *con_cls = stream;
123
124         // Does not strictly have to be equal to MUX_BUFFER_SIZE.
125         MHD_Response *response = MHD_create_response_from_callback(
126                 (size_t)-1, MUX_BUFFER_SIZE, &HTTPD::Stream::reader_callback_thunk, stream, &HTTPD::free_stream);
127         // TODO: Content-type?
128         if (framing == HTTPD::Stream::FRAMING_METACUBE) {
129                 MHD_add_response_header(response, "Content-encoding", "metacube");
130         }
131
132         int ret = MHD_queue_response(connection, MHD_HTTP_OK, response);
133         MHD_destroy_response(response);  // Only decreases the refcount; actual free is after the request is done.
134
135         return ret;
136 }
137
138 void HTTPD::free_stream(void *cls)
139 {
140         HTTPD::Stream *stream = (HTTPD::Stream *)cls;
141         HTTPD *httpd = stream->get_parent();
142         {
143                 unique_lock<mutex> lock(httpd->streams_mutex);
144                 delete stream;
145                 httpd->streams.erase(stream);
146         }
147         --httpd->metric_num_connected_clients;
148 }
149
150 ssize_t HTTPD::Stream::reader_callback_thunk(void *cls, uint64_t pos, char *buf, size_t max)
151 {
152         HTTPD::Stream *stream = (HTTPD::Stream *)cls;
153         return stream->reader_callback(pos, buf, max);
154 }
155
156 ssize_t HTTPD::Stream::reader_callback(uint64_t pos, char *buf, size_t max)
157 {
158         unique_lock<mutex> lock(buffer_mutex);
159         has_buffered_data.wait(lock, [this]{ return should_quit || !buffered_data.empty(); });
160         if (should_quit) {
161                 return 0;
162         }
163
164         ssize_t ret = 0;
165         while (max > 0 && !buffered_data.empty()) {
166                 const string &s = buffered_data.front();
167                 assert(s.size() > used_of_buffered_data);
168                 size_t len = s.size() - used_of_buffered_data;
169                 if (max >= len) {
170                         // Consume the entire (rest of the) string.
171                         memcpy(buf, s.data() + used_of_buffered_data, len);
172                         buf += len;
173                         ret += len;
174                         max -= len;
175                         buffered_data.pop_front();
176                         used_of_buffered_data = 0;
177                 } else {
178                         // We don't need the entire string; just use the first part of it.
179                         memcpy(buf, s.data() + used_of_buffered_data, max);
180                         buf += max;
181                         used_of_buffered_data += max;
182                         ret += max;
183                         max = 0;
184                 }
185         }
186
187         return ret;
188 }
189
190 void HTTPD::Stream::add_data(const char *buf, size_t buf_size, HTTPD::Stream::DataType data_type)
191 {
192         if (buf_size == 0) {
193                 return;
194         }
195         if (data_type == DATA_TYPE_KEYFRAME) {
196                 seen_keyframe = true;
197         } else if (data_type == DATA_TYPE_OTHER && !seen_keyframe) {
198                 // Start sending only once we see a keyframe.
199                 return;
200         }
201
202         unique_lock<mutex> lock(buffer_mutex);
203
204         if (framing == FRAMING_METACUBE) {
205                 metacube2_block_header hdr;
206                 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
207                 hdr.size = htonl(buf_size);
208                 int flags = 0;
209                 if (data_type == DATA_TYPE_HEADER) {
210                         flags |= METACUBE_FLAGS_HEADER;
211                 } else if (data_type == DATA_TYPE_OTHER) {
212                         flags |= METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START;
213                 }
214                 hdr.flags = htons(flags);
215                 hdr.csum = htons(metacube2_compute_crc(&hdr));
216                 buffered_data.emplace_back((char *)&hdr, sizeof(hdr));
217         }
218         buffered_data.emplace_back(buf, buf_size);
219
220         // Send a Metacube2 timestamp every keyframe.
221         if (framing == FRAMING_METACUBE && data_type == DATA_TYPE_KEYFRAME) {
222                 timespec now;
223                 clock_gettime(CLOCK_REALTIME, &now);
224
225                 metacube2_timestamp_packet packet;
226                 packet.type = htobe64(METACUBE_METADATA_TYPE_ENCODER_TIMESTAMP);
227                 packet.tv_sec = htobe64(now.tv_sec);
228                 packet.tv_nsec = htobe64(now.tv_nsec);
229
230                 metacube2_block_header hdr;
231                 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
232                 hdr.size = htonl(sizeof(packet));
233                 hdr.flags = htons(METACUBE_FLAGS_METADATA);
234                 hdr.csum = htons(metacube2_compute_crc(&hdr));
235                 buffered_data.emplace_back((char *)&hdr, sizeof(hdr));
236                 buffered_data.emplace_back((char *)&packet, sizeof(packet));
237         }
238
239         has_buffered_data.notify_all(); 
240 }
241
242 void HTTPD::Stream::stop()
243 {
244         unique_lock<mutex> lock(buffer_mutex);
245         should_quit = true;
246         has_buffered_data.notify_all();
247 }