-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathrtsp.cpp
More file actions
1276 lines (1013 loc) · 47.3 KB
/
Copy pathrtsp.cpp
File metadata and controls
1276 lines (1013 loc) · 47.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file src/rtsp.cpp
* @brief Definitions for RTSP streaming.
*/
#define BOOST_BIND_GLOBAL_PLACEHOLDERS
extern "C" {
#include <moonlight-common-c/src/Limelight-internal.h>
#include <moonlight-common-c/src/Rtsp.h>
}
// standard includes
#include <array>
#include <cctype>
#include <format>
#include <set>
#include <unordered_map>
#include <utility>
// lib includes
#include <boost/asio.hpp>
#include <boost/bind.hpp>
// local includes
#include "config.h"
#include "globals.h"
#include "input.h"
#include "logging.h"
#include "network.h"
#include "rtsp.h"
#include "stream.h"
#include "sync.h"
#include "video.h"
namespace asio = boost::asio;
using asio::ip::tcp;
using asio::ip::udp;
using namespace std::literals;
namespace rtsp_stream {
void free_msg(PRTSP_MESSAGE msg) {
freeMessage(msg);
delete msg;
}
#pragma pack(push, 1)
struct encrypted_rtsp_header_t {
// We set the MSB in encrypted RTSP messages to allow format-agnostic
// parsing code to be able to tell encrypted from plaintext messages.
static constexpr std::uint32_t ENCRYPTED_MESSAGE_TYPE_BIT = 0x80000000;
uint8_t *payload() {
return (uint8_t *) (this + 1);
}
std::uint32_t payload_length() {
return util::endian::big<std::uint32_t>(typeAndLength) & ~ENCRYPTED_MESSAGE_TYPE_BIT;
}
bool is_encrypted() {
return !!(util::endian::big<std::uint32_t>(typeAndLength) & ENCRYPTED_MESSAGE_TYPE_BIT);
}
// This field is the length of the payload + ENCRYPTED_MESSAGE_TYPE_BIT in big-endian
std::uint32_t typeAndLength;
// This field is the number used to initialize the bottom 4 bytes of the AES IV in big-endian
std::uint32_t sequenceNumber;
// This field is the AES GCM authentication tag
std::uint8_t tag[16];
};
#pragma pack(pop)
class rtsp_server_t;
using msg_t = util::safe_ptr<RTSP_MESSAGE, free_msg>;
using cmd_func_t = std::function<void(rtsp_server_t *server, tcp::socket &, launch_session_t &, msg_t &&)>;
void print_msg(PRTSP_MESSAGE msg);
void cmd_not_found(tcp::socket &sock, launch_session_t &, msg_t &&req);
void respond(tcp::socket &sock, launch_session_t &session, POPTION_ITEM options, int statuscode, const char *status_msg, int seqn, const std::string_view &payload);
class socket_t: public std::enable_shared_from_this<socket_t> {
public:
socket_t(boost::asio::io_context &io_context, std::function<void(tcp::socket &sock, launch_session_t &, msg_t &&)> &&handle_data_fn):
handle_data_fn {std::move(handle_data_fn)},
sock {io_context} {
}
/**
* @brief Queue an asynchronous read to begin the next message.
*/
void read() {
if (begin == std::end(msg_buf) || (session->rtsp_cipher && begin + sizeof(encrypted_rtsp_header_t) >= std::end(msg_buf))) {
BOOST_LOG(error) << "RTSP: read(): Exceeded maximum rtsp packet size: "sv << msg_buf.size();
respond(sock, *session, nullptr, 400, "BAD REQUEST", 0, {});
boost::system::error_code ec;
sock.close(ec);
return;
}
if (session->rtsp_cipher) {
// For encrypted RTSP, we will read the the entire header first
boost::asio::async_read(sock, boost::asio::buffer(begin, sizeof(encrypted_rtsp_header_t)), boost::bind(&socket_t::handle_read_encrypted_header, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
} else {
sock.async_read_some(
boost::asio::buffer(begin, (std::size_t) (std::end(msg_buf) - begin)),
boost::bind(
&socket_t::handle_read_plaintext,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred
)
);
}
}
/**
* @brief Handle the initial read of the header of an encrypted message.
* @param socket The socket the message was received on.
* @param ec The error code of the read operation.
* @param bytes The number of bytes read.
*/
static void handle_read_encrypted_header(std::shared_ptr<socket_t> &socket, const boost::system::error_code &ec, std::size_t bytes) {
BOOST_LOG(debug) << "handle_read_encrypted_header(): Handle read of size: "sv << bytes << " bytes"sv;
auto sock_close = util::fail_guard([&socket]() {
boost::system::error_code ec;
socket->sock.close(ec);
if (ec) {
BOOST_LOG(error) << "RTSP: handle_read_encrypted_header(): Couldn't close tcp socket: "sv << ec.message();
}
});
if (ec || bytes < sizeof(encrypted_rtsp_header_t)) {
BOOST_LOG(error) << "RTSP: handle_read_encrypted_header(): Couldn't read from tcp socket: "sv << ec.message();
respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {});
return;
}
auto header = (encrypted_rtsp_header_t *) socket->begin;
if (!header->is_encrypted()) {
BOOST_LOG(error) << "RTSP: handle_read_encrypted_header(): Rejecting unencrypted RTSP message"sv;
respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {});
return;
}
auto payload_length = header->payload_length();
// Check if we have enough space to read this message
if (socket->begin + sizeof(*header) + payload_length >= std::end(socket->msg_buf)) {
BOOST_LOG(error) << "RTSP: handle_read_encrypted_header(): Exceeded maximum rtsp packet size: "sv << socket->msg_buf.size();
respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {});
return;
}
sock_close.disable();
// Read the remainder of the header and full encrypted payload
boost::asio::async_read(socket->sock, boost::asio::buffer(socket->begin + bytes, payload_length), boost::bind(&socket_t::handle_read_encrypted_message, socket->shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
/**
* @brief Handle the final read of the content of an encrypted message.
* @param socket The socket the message was received on.
* @param ec The error code of the read operation.
* @param bytes The number of bytes read.
*/
static void handle_read_encrypted_message(std::shared_ptr<socket_t> &socket, const boost::system::error_code &ec, std::size_t bytes) {
BOOST_LOG(debug) << "handle_read_encrypted(): Handle read of size: "sv << bytes << " bytes"sv;
auto sock_close = util::fail_guard([&socket]() {
boost::system::error_code ec;
socket->sock.close(ec);
if (ec) {
BOOST_LOG(error) << "RTSP: handle_read_encrypted_message(): Couldn't close tcp socket: "sv << ec.message();
}
});
auto header = (encrypted_rtsp_header_t *) socket->begin;
auto payload_length = header->payload_length();
auto seq = util::endian::big<std::uint32_t>(header->sequenceNumber);
if (ec || bytes < payload_length) {
BOOST_LOG(error) << "RTSP: handle_read_encrypted(): Couldn't read from tcp socket: "sv << ec.message();
respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {});
return;
}
// We use the deterministic IV construction algorithm specified in NIST SP 800-38D
// Section 8.2.1. The sequence number is our "invocation" field and the 'RC' in the
// high bytes is the "fixed" field. Because each client provides their own unique
// key, our values in the fixed field need only uniquely identify each independent
// use of the client's key with AES-GCM in our code.
//
// The sequence number is 32 bits long which allows for 2^32 RTSP messages to be
// received from each client before the IV repeats.
crypto::aes_t iv(12);
std::copy_n((uint8_t *) &seq, sizeof(seq), std::begin(iv));
iv[10] = 'C'; // Client originated
iv[11] = 'R'; // RTSP
std::vector<uint8_t> plaintext;
if (socket->session->rtsp_cipher->decrypt(std::string_view {(const char *) header->tag, sizeof(header->tag) + bytes}, plaintext, &iv)) {
BOOST_LOG(error) << "Failed to verify RTSP message tag"sv;
respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {});
return;
}
msg_t req {new msg_t::element_type {}};
if (auto status = parseRtspMessage(req.get(), (char *) plaintext.data(), (int) plaintext.size())) {
BOOST_LOG(error) << "Malformed RTSP message: ["sv << status << ']';
respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {});
return;
}
sock_close.disable();
print_msg(req.get());
socket->handle_data(std::move(req));
}
/**
* @brief Queue an asynchronous read of the payload portion of a plaintext message.
*/
void read_plaintext_payload() {
if (begin == std::end(msg_buf)) {
BOOST_LOG(error) << "RTSP: read_plaintext_payload(): Exceeded maximum rtsp packet size: "sv << msg_buf.size();
respond(sock, *session, nullptr, 400, "BAD REQUEST", 0, {});
boost::system::error_code ec;
sock.close(ec);
return;
}
sock.async_read_some(
boost::asio::buffer(begin, (std::size_t) (std::end(msg_buf) - begin)),
boost::bind(
&socket_t::handle_plaintext_payload,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred
)
);
}
/**
* @brief Handle the read of the payload portion of a plaintext message.
* @param socket The socket the message was received on.
* @param ec The error code of the read operation.
* @param bytes The number of bytes read.
*/
static void handle_plaintext_payload(std::shared_ptr<socket_t> &socket, const boost::system::error_code &ec, std::size_t bytes) {
BOOST_LOG(debug) << "handle_plaintext_payload(): Handle read of size: "sv << bytes << " bytes"sv;
auto sock_close = util::fail_guard([&socket]() {
boost::system::error_code ec;
socket->sock.close(ec);
if (ec) {
BOOST_LOG(error) << "RTSP: handle_plaintext_payload(): Couldn't close tcp socket: "sv << ec.message();
}
});
if (ec) {
BOOST_LOG(error) << "RTSP: handle_plaintext_payload(): Couldn't read from tcp socket: "sv << ec.message();
return;
}
auto end = socket->begin + bytes;
msg_t req {new msg_t::element_type {}};
if (auto status = parseRtspMessage(req.get(), socket->msg_buf.data(), (int) (end - socket->msg_buf.data()))) {
BOOST_LOG(error) << "Malformed RTSP message: ["sv << status << ']';
respond(socket->sock, *socket->session, nullptr, 400, "BAD REQUEST", 0, {});
return;
}
sock_close.disable();
auto fg = util::fail_guard([&socket]() {
socket->read_plaintext_payload();
});
auto content_length = 0;
for (auto option = req->options; option != nullptr; option = option->next) {
if ("Content-length"sv == option->option) {
BOOST_LOG(debug) << "Found Content-Length: "sv << option->content << " bytes"sv;
// If content_length > bytes read, then we need to store current data read,
// to be appended by the next read.
std::string_view content {option->content};
auto begin = std::find_if(std::begin(content), std::end(content), [](auto ch) {
return (bool) std::isdigit(ch);
});
content_length = (int) util::from_chars(begin, std::end(content));
break;
}
}
if (end - socket->crlf >= content_length) {
if (end - socket->crlf > content_length) {
BOOST_LOG(warning) << "(end - socket->crlf) > content_length -- "sv << (std::size_t) (end - socket->crlf) << " > "sv << content_length;
}
fg.disable();
print_msg(req.get());
socket->handle_data(std::move(req));
}
socket->begin = end;
}
/**
* @brief Handle the read of the header portion of a plaintext message.
* @param socket The socket the message was received on.
* @param ec The error code of the read operation.
* @param bytes The number of bytes read.
*/
static void handle_read_plaintext(std::shared_ptr<socket_t> &socket, const boost::system::error_code &ec, std::size_t bytes) {
BOOST_LOG(debug) << "handle_read_plaintext(): Handle read of size: "sv << bytes << " bytes"sv;
if (ec) {
BOOST_LOG(error) << "RTSP: handle_read_plaintext(): Couldn't read from tcp socket: "sv << ec.message();
boost::system::error_code ec;
socket->sock.close(ec);
if (ec) {
BOOST_LOG(error) << "RTSP: handle_read_plaintext(): Couldn't close tcp socket: "sv << ec.message();
}
return;
}
auto fg = util::fail_guard([&socket]() {
socket->read();
});
auto begin = std::max(socket->begin - 4, socket->begin);
auto buf_size = bytes + (begin - socket->begin);
auto end = begin + buf_size;
constexpr auto needle = "\r\n\r\n"sv;
auto it = std::search(begin, begin + buf_size, std::begin(needle), std::end(needle));
if (it == end) {
socket->begin = end;
return;
}
// Emulate read completion for payload data
socket->begin = it + needle.size();
socket->crlf = socket->begin;
buf_size = end - socket->begin;
fg.disable();
handle_plaintext_payload(socket, ec, buf_size);
}
void handle_data(msg_t &&req) {
handle_data_fn(sock, *session, std::move(req));
}
std::function<void(tcp::socket &sock, launch_session_t &, msg_t &&)> handle_data_fn;
tcp::socket sock;
std::array<char, 2048> msg_buf;
char *crlf;
char *begin = msg_buf.data();
std::shared_ptr<launch_session_t> session;
};
class rtsp_server_t {
public:
~rtsp_server_t() {
clear();
}
int bind(net::af_e af, std::uint16_t port, boost::system::error_code &ec) {
acceptor.open(af == net::IPV4 ? tcp::v4() : tcp::v6(), ec);
if (ec) {
return -1;
}
acceptor.set_option(boost::asio::socket_base::reuse_address {true});
auto bind_addr_str = net::get_bind_address(af);
const auto bind_addr = boost::asio::ip::make_address(bind_addr_str, ec);
if (ec) {
BOOST_LOG(error) << "Invalid bind address: "sv << bind_addr_str << " - " << ec.message();
return -1;
}
acceptor.bind(tcp::endpoint(bind_addr, port), ec);
if (ec) {
return -1;
}
acceptor.listen(4096, ec);
if (ec) {
return -1;
}
next_socket = std::make_shared<socket_t>(io_context, [this](tcp::socket &sock, launch_session_t &session, msg_t &&msg) {
handle_msg(sock, session, std::move(msg));
});
acceptor.async_accept(next_socket->sock, [this](const auto &ec) {
handle_accept(ec);
});
return 0;
}
void handle_msg(tcp::socket &sock, launch_session_t &session, msg_t &&req) {
auto func = _map_cmd_cb.find(req->message.request.command);
if (func != std::end(_map_cmd_cb)) {
func->second(this, sock, session, std::move(req));
} else {
cmd_not_found(sock, session, std::move(req));
}
boost::system::error_code ec;
sock.shutdown(boost::asio::socket_base::shutdown_type::shutdown_both, ec);
}
void handle_accept(const boost::system::error_code &ec) {
if (ec) {
BOOST_LOG(error) << "Couldn't accept incoming connections: "sv << ec.message();
// Stop server
clear();
return;
}
auto socket = std::move(next_socket);
auto launch_session {launch_event.view(0s)};
if (launch_session) {
// Associate the current RTSP session with this socket and start reading
socket->session = launch_session;
socket->read();
} else {
// This can happen due to normal things like port scanning, so let's not make these visible by default
BOOST_LOG(debug) << "No pending session for incoming RTSP connection"sv;
// If there is no session pending, close the connection immediately
boost::system::error_code ec;
socket->sock.close(ec);
}
// Queue another asynchronous accept for the next incoming connection
next_socket = std::make_shared<socket_t>(io_context, [this](tcp::socket &sock, launch_session_t &session, msg_t &&msg) {
handle_msg(sock, session, std::move(msg));
});
acceptor.async_accept(next_socket->sock, [this](const auto &ec) {
handle_accept(ec);
});
}
void map(const std::string_view &type, cmd_func_t cb) {
_map_cmd_cb.emplace(type, std::move(cb));
}
/**
* @brief Launch a new streaming session.
* @note If the client does not begin streaming within the ping_timeout,
* the session will be discarded.
* @param launch_session Streaming session information.
*/
void session_raise(std::shared_ptr<launch_session_t> launch_session) {
// If a launch event is still pending, don't overwrite it.
if (launch_event.view(0s)) {
return;
}
// Raise the new launch session to prepare for the RTSP handshake
launch_event.raise(std::move(launch_session));
// Arm the timer to expire this launch session if the client times out
raised_timer.expires_after(config::stream.ping_timeout);
raised_timer.async_wait([this](const boost::system::error_code &ec) {
if (!ec) {
auto discarded = launch_event.pop(0s);
if (discarded) {
BOOST_LOG(debug) << "Event timeout: "sv << discarded->unique_id;
}
}
});
}
/**
* @brief Clear state for the oldest launch session.
* @param launch_session_id The ID of the session to clear.
*/
void session_clear(uint32_t launch_session_id) {
// We currently only support a single pending RTSP session,
// so the ID should always match the one for that session.
auto launch_session = launch_event.view(0s);
if (launch_session) {
if (launch_session->id != launch_session_id) {
BOOST_LOG(error) << "Attempted to clear unexpected session: "sv << launch_session_id << " vs "sv << launch_session->id;
} else {
raised_timer.cancel();
launch_event.pop();
}
}
}
/**
* @brief Get the number of active sessions.
* @return Count of active sessions.
*/
int session_count() {
auto lg = _session_slots.lock();
return (int) _session_slots->size();
}
safe::event_t<std::shared_ptr<launch_session_t>> launch_event;
/**
* @brief Clear launch sessions.
* @param all If true, clear all sessions. Otherwise, only clear timed out and stopped sessions.
* @examples
* clear(false);
* @examples_end
*/
void clear(bool all = true) {
auto lg = _session_slots.lock();
for (auto i = _session_slots->begin(); i != _session_slots->end();) {
auto &slot = *(*i);
if (all || stream::session::state(slot) == stream::session::state_e::STOPPING) {
stream::session::stop(slot);
stream::session::join(slot);
i = _session_slots->erase(i);
} else {
i++;
}
}
}
void clear_by_cert(std::string_view cert) {
auto lg = _session_slots.lock();
for (auto i = _session_slots->begin(); i != _session_slots->end();) {
auto &slot = *(*i);
if (stream::session::client_cert(slot) == cert) {
stream::session::stop(slot);
stream::session::join(slot);
i = _session_slots->erase(i);
} else {
i++;
}
}
}
/**
* @brief Removes the provided session from the set of sessions.
* @param session The session to remove.
*/
void remove(const std::shared_ptr<stream::session_t> &session) {
auto lg = _session_slots.lock();
_session_slots->erase(session);
}
/**
* @brief Inserts the provided session into the set of sessions.
* @param session The session to insert.
*/
void insert(const std::shared_ptr<stream::session_t> &session) {
auto lg = _session_slots.lock();
_session_slots->emplace(session);
BOOST_LOG(info) << "New streaming session started [active sessions: "sv << _session_slots->size() << ']';
}
/**
* @brief Runs an iteration of the RTSP server loop
*/
void iterate() {
// If we have a session, we will return to the server loop every
// 500ms to allow session cleanup to happen.
if (session_count() > 0) {
io_context.run_one_for(500ms);
} else {
io_context.run_one();
}
}
/**
* @brief Stop the RTSP server.
*/
void stop() {
acceptor.close();
io_context.stop();
clear();
}
private:
std::unordered_map<std::string_view, cmd_func_t> _map_cmd_cb;
sync_util::sync_t<std::set<std::shared_ptr<stream::session_t>>> _session_slots;
boost::asio::io_context io_context;
tcp::acceptor acceptor {io_context};
boost::asio::steady_timer raised_timer {io_context};
std::shared_ptr<socket_t> next_socket;
};
rtsp_server_t server {};
void launch_session_raise(std::shared_ptr<launch_session_t> launch_session) {
server.session_raise(std::move(launch_session));
}
void launch_session_clear(uint32_t launch_session_id) {
server.session_clear(launch_session_id);
}
int session_count() {
// Ensure session_count is up-to-date
server.clear(false);
return server.session_count();
}
void terminate_sessions() {
server.clear(true);
}
void terminate_sessions_by_cert(std::string_view cert) {
server.clear_by_cert(cert);
}
int send(tcp::socket &sock, const std::string_view &sv) {
std::size_t bytes_send = 0;
while (bytes_send != sv.size()) {
boost::system::error_code ec;
bytes_send += sock.send(boost::asio::buffer(sv.substr(bytes_send)), 0, ec);
if (ec) {
BOOST_LOG(error) << "RTSP: Couldn't send data over tcp socket: "sv << ec.message();
return -1;
}
}
return 0;
}
void respond(tcp::socket &sock, launch_session_t &session, msg_t &resp) {
auto payload = std::make_pair(resp->payload, resp->payloadLength);
// Restore response message for proper destruction
auto lg = util::fail_guard([&]() {
resp->payload = payload.first;
resp->payloadLength = payload.second;
});
resp->payload = nullptr;
resp->payloadLength = 0;
int serialized_len;
util::c_ptr<char> raw_resp {serializeRtspMessage(resp.get(), &serialized_len)};
BOOST_LOG(debug)
<< "---Begin Response---"sv << std::endl
<< std::string_view {raw_resp.get(), (std::size_t) serialized_len} << std::endl
<< std::string_view {payload.first, (std::size_t) payload.second} << std::endl
<< "---End Response---"sv << std::endl;
// Encrypt the RTSP message if encryption is enabled
if (session.rtsp_cipher) {
// We use the deterministic IV construction algorithm specified in NIST SP 800-38D
// Section 8.2.1. The sequence number is our "invocation" field and the 'RH' in the
// high bytes is the "fixed" field. Because each client provides their own unique
// key, our values in the fixed field need only uniquely identify each independent
// use of the client's key with AES-GCM in our code.
//
// The sequence number is 32 bits long which allows for 2^32 RTSP messages to be
// sent to each client before the IV repeats.
crypto::aes_t iv(12);
session.rtsp_iv_counter++;
std::copy_n((uint8_t *) &session.rtsp_iv_counter, sizeof(session.rtsp_iv_counter), std::begin(iv));
iv[10] = 'H'; // Host originated
iv[11] = 'R'; // RTSP
// Allocate the message with an empty header and reserved space for the payload
auto payload_length = serialized_len + payload.second;
std::vector<uint8_t> message(sizeof(encrypted_rtsp_header_t));
message.reserve(message.size() + payload_length);
// Copy the complete plaintext into the message
std::copy_n(raw_resp.get(), serialized_len, std::back_inserter(message));
std::copy_n(payload.first, payload.second, std::back_inserter(message));
// Initialize the message header
auto header = (encrypted_rtsp_header_t *) message.data();
header->typeAndLength = util::endian::big<std::uint32_t>(encrypted_rtsp_header_t::ENCRYPTED_MESSAGE_TYPE_BIT + payload_length);
header->sequenceNumber = util::endian::big<std::uint32_t>(session.rtsp_iv_counter);
// Encrypt the RTSP message in place
session.rtsp_cipher->encrypt(std::string_view {(const char *) header->payload(), (std::size_t) payload_length}, header->tag, &iv);
// Send the full encrypted message
send(sock, std::string_view {(char *) message.data(), message.size()});
} else {
std::string_view tmp_resp {raw_resp.get(), (size_t) serialized_len};
// Send the plaintext RTSP message header
if (send(sock, tmp_resp)) {
return;
}
// Send the plaintext RTSP message payload (if present)
send(sock, std::string_view {payload.first, (std::size_t) payload.second});
}
}
void respond(tcp::socket &sock, launch_session_t &session, POPTION_ITEM options, int statuscode, const char *status_msg, int seqn, const std::string_view &payload) {
msg_t resp {new msg_t::element_type};
createRtspResponse(resp.get(), nullptr, 0, const_cast<char *>("RTSP/1.0"), statuscode, const_cast<char *>(status_msg), seqn, options, const_cast<char *>(payload.data()), (int) payload.size());
respond(sock, session, resp);
}
void cmd_not_found(tcp::socket &sock, launch_session_t &session, msg_t &&req) {
respond(sock, session, nullptr, 404, "NOT FOUND", req->sequenceNumber, {});
}
void cmd_option(rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) {
OPTION_ITEM option {};
// I know these string literals will not be modified
option.option = const_cast<char *>("CSeq");
auto seqn_str = std::to_string(req->sequenceNumber);
option.content = const_cast<char *>(seqn_str.c_str());
respond(sock, session, &option, 200, "OK", req->sequenceNumber, {});
}
void cmd_describe(rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) {
OPTION_ITEM option {};
// I know these string literals will not be modified
option.option = const_cast<char *>("CSeq");
auto seqn_str = std::to_string(req->sequenceNumber);
option.content = const_cast<char *>(seqn_str.c_str());
std::stringstream ss;
// Tell the client about our supported features
ss << "a=x-ss-general.featureFlags:" << (uint32_t) platf::get_capabilities() << std::endl;
// Always request new control stream encryption if the client supports it
uint32_t encryption_flags_supported = SS_ENC_CONTROL_V2 | SS_ENC_AUDIO;
uint32_t encryption_flags_requested = SS_ENC_CONTROL_V2;
// Determine the encryption desired for this remote endpoint
auto encryption_mode = net::encryption_mode_for_address(sock.remote_endpoint().address());
if (encryption_mode != config::ENCRYPTION_MODE_NEVER) {
// Advertise support for video encryption if it's not disabled
encryption_flags_supported |= SS_ENC_VIDEO;
// If it's mandatory, also request it to enable use if the client
// didn't explicitly opt in, but it otherwise has support.
if (encryption_mode == config::ENCRYPTION_MODE_MANDATORY) {
encryption_flags_requested |= SS_ENC_VIDEO | SS_ENC_AUDIO;
}
}
// Report supported and required encryption flags
ss << "a=x-ss-general.encryptionSupported:" << encryption_flags_supported << std::endl;
ss << "a=x-ss-general.encryptionRequested:" << encryption_flags_requested << std::endl;
if (video::last_encoder_probe_supported_ref_frames_invalidation) {
ss << "a=x-nv-video[0].refPicInvalidation:1"sv << std::endl;
}
if (video::active_hevc_mode != 1) {
ss << "sprop-parameter-sets=AAAAAU"sv << std::endl;
}
if (video::active_av1_mode != 1) {
ss << "a=rtpmap:98 AV1/90000"sv << std::endl;
}
if (video::active_mpeg2_mode >= 2) {
ss << "a=rtpmap:98 MPV/90000"sv << std::endl;
}
if (video::active_h263p_mode == 2) {
ss << "a=rtpmap:98 H263-1998/90000"sv << std::endl;
}
if (!session.surround_params.empty()) {
// If we have our own surround parameters, advertise them twice first
ss << "a=fmtp:97 surround-params="sv << session.surround_params << std::endl;
ss << "a=fmtp:97 surround-params="sv << session.surround_params << std::endl;
}
for (int x = 0; x < audio::MAX_STREAM_CONFIG; ++x) {
auto &stream_config = audio::stream_configs[x];
std::uint8_t mapping[platf::speaker::MAX_SPEAKERS];
auto mapping_p = stream_config.mapping;
/**
* GFE advertises incorrect mapping for normal quality configurations,
* as a result, Moonlight rotates all channels from index '3' to the right
* To work around this, rotate channels to the left from index '3'
*/
if (x == audio::SURROUND51 || x == audio::SURROUND71) {
std::copy_n(mapping_p, stream_config.channelCount, mapping);
std::rotate(mapping + 3, mapping + 4, mapping + audio::MAX_STREAM_CONFIG);
mapping_p = mapping;
}
ss << "a=fmtp:97 surround-params="sv << stream_config.channelCount << stream_config.streams << stream_config.coupledStreams;
std::for_each_n(mapping_p, stream_config.channelCount, [&ss](std::uint8_t digit) {
ss << (char) (digit + '0');
});
ss << std::endl;
}
respond(sock, session, &option, 200, "OK", req->sequenceNumber, ss.str());
}
void cmd_setup(rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) {
OPTION_ITEM options[4] {};
auto &seqn = options[0];
auto &session_option = options[1];
auto &port_option = options[2];
auto &payload_option = options[3];
seqn.option = const_cast<char *>("CSeq");
auto seqn_str = std::to_string(req->sequenceNumber);
seqn.content = const_cast<char *>(seqn_str.c_str());
std::string_view target {req->message.request.target};
auto begin = std::find(std::begin(target), std::end(target), '=') + 1;
auto end = std::find(begin, std::end(target), '/');
std::string_view type {begin, (size_t) std::distance(begin, end)};
std::uint16_t port;
if (type == "audio"sv) {
port = net::map_port(stream::AUDIO_STREAM_PORT);
} else if (type == "video"sv) {
port = net::map_port(stream::VIDEO_STREAM_PORT);
} else if (type == "control"sv) {
port = net::map_port(stream::CONTROL_PORT);
} else {
cmd_not_found(sock, session, std::move(req));
return;
}
seqn.next = &session_option;
session_option.option = const_cast<char *>("Session");
session_option.content = const_cast<char *>("DEADBEEFCAFE;timeout = 90");
session_option.next = &port_option;
// Moonlight merely requires 'server_port=<port>'
auto port_value = std::format("server_port={}", static_cast<int>(port));
port_option.option = const_cast<char *>("Transport");
port_option.content = port_value.data();
// Send identifiers that will be echoed in the other connections
auto connect_data = std::to_string(session.control_connect_data);
if (type == "control"sv) {
payload_option.option = const_cast<char *>("X-SS-Connect-Data");
payload_option.content = connect_data.data();
} else {
payload_option.option = const_cast<char *>("X-SS-Ping-Payload");
payload_option.content = session.av_ping_payload.data();
}
port_option.next = &payload_option;
respond(sock, session, &seqn, 200, "OK", req->sequenceNumber, {});
}
void cmd_announce(rtsp_server_t *server, tcp::socket &sock, launch_session_t &session, msg_t &&req) {
OPTION_ITEM option {};
// I know these string literals will not be modified
option.option = const_cast<char *>("CSeq");
auto seqn_str = std::to_string(req->sequenceNumber);
option.content = const_cast<char *>(seqn_str.c_str());
std::string_view payload {req->payload, (size_t) req->payloadLength};
std::vector<std::string_view> lines;
auto whitespace = [](char ch) {
return ch == '\n' || ch == '\r';
};
{
auto pos = std::begin(payload);
auto begin = pos;
while (pos != std::end(payload)) {
if (whitespace(*pos++)) {
lines.emplace_back(begin, pos - begin - 1);
while (pos != std::end(payload) && whitespace(*pos)) {
++pos;
}
begin = pos;
}
}
}
std::string_view client;
std::unordered_map<std::string_view, std::string_view> args;
for (auto line : lines) {
auto type = line.substr(0, 2);
if (type == "s="sv) {
client = line.substr(2);
} else if (type == "a=") {
auto pos = line.find(':');
auto name = line.substr(2, pos - 2);
auto val = line.substr(pos + 1);
if (val[val.size() - 1] == ' ') {
val = val.substr(0, val.size() - 1);
}
args.emplace(name, val);
}
}
// Initialize any omitted parameters to defaults
args.try_emplace("x-nv-video[0].encoderCscMode"sv, "0"sv);
args.try_emplace("x-nv-vqos[0].bitStreamFormat"sv, "0"sv);
args.try_emplace("x-nv-video[0].dynamicRangeMode"sv, "0"sv);
args.try_emplace("x-nv-aqos.packetDuration"sv, "5"sv);
args.try_emplace("x-nv-general.useReliableUdp"sv, "1"sv);
args.try_emplace("x-nv-vqos[0].fec.minRequiredFecPackets"sv, "0"sv);
args.try_emplace("x-nv-general.featureFlags"sv, "135"sv);
args.try_emplace("x-ml-general.featureFlags"sv, "0"sv);
args.try_emplace("x-nv-vqos[0].qosTrafficType"sv, "5"sv);
args.try_emplace("x-nv-aqos.qosTrafficType"sv, "4"sv);
args.try_emplace("x-ml-video.configuredBitrateKbps"sv, "0"sv);
args.try_emplace("x-ss-general.encryptionEnabled"sv, "0"sv);
args.try_emplace("x-ss-video[0].chromaSamplingType"sv, "0"sv);
args.try_emplace("x-ss-video[0].intraRefresh"sv, "0"sv);
args.try_emplace("x-nv-video[0].clientRefreshRateX100"sv, "0"sv);
stream::config_t config;
std::int64_t configuredBitrateKbps;
config.audio.flags[audio::config_t::HOST_AUDIO] = session.host_audio;
try {
config.audio.channels = (int) util::from_view(args.at("x-nv-audio.surround.numChannels"sv));
config.audio.mask = (int) util::from_view(args.at("x-nv-audio.surround.channelMask"sv));
config.audio.packetDuration = (int) util::from_view(args.at("x-nv-aqos.packetDuration"sv));
config.audio.flags[audio::config_t::HIGH_QUALITY] =
util::from_view(args.at("x-nv-audio.surround.AudioQuality"sv));