-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathstream.cpp
More file actions
2359 lines (1919 loc) · 92.2 KB
/
Copy pathstream.cpp
File metadata and controls
2359 lines (1919 loc) · 92.2 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/stream.cpp
* @brief Definitions for the streaming protocols.
*/
// standard includes
#include <fstream>
#include <future>
#include <queue>
// lib includes
#include <boost/endian/arithmetic.hpp>
#include <openssl/err.h>
#include <rs.h>
extern "C" {
// clang-format off
#include <moonlight-common-c/src/Limelight-internal.h>
// clang-format on
}
// local includes
#include "config.h"
#include "display_device.h"
#include "globals.h"
#include "input.h"
#include "logging.h"
#include "network.h"
#include "platform/common.h"
#include "process.h"
#include "stream.h"
#include "sync.h"
#include "system_tray.h"
#include "thread_safe.h"
#include "utility.h"
constexpr int IDX_START_A = 0; ///< Control-stream message index for the first stream-start packet.
constexpr int IDX_START_B = 1; ///< Control-stream message index for the second stream-start packet.
constexpr int IDX_INVALIDATE_REF_FRAMES = 2; ///< Control-stream message index for invalidate ref frames.
constexpr int IDX_LOSS_STATS = 3; ///< Control-stream message index for loss stats.
constexpr int IDX_INPUT_DATA = 5; ///< Control-stream message index for input data.
constexpr int IDX_RUMBLE_DATA = 6; ///< Control-stream message index for rumble data.
constexpr int IDX_TERMINATION = 7; ///< Control-stream message index for termination.
constexpr int IDX_PERIODIC_PING = 8; ///< Control-stream message index for periodic ping.
constexpr int IDX_REQUEST_IDR_FRAME = 9; ///< Control-stream message index for request idr frame.
constexpr int IDX_ENCRYPTED = 10; ///< Control-stream message index for encrypted.
constexpr int IDX_HDR_MODE = 11; ///< Control-stream message index for hdr mode.
constexpr int IDX_RUMBLE_TRIGGER_DATA = 12; ///< Control-stream message index for rumble trigger data.
constexpr int IDX_SET_MOTION_EVENT = 13; ///< Control-stream message index for set motion event.
constexpr int IDX_SET_RGB_LED = 14; ///< Control-stream message index for set rgb led.
constexpr int IDX_SET_ADAPTIVE_TRIGGERS = 15; ///< Control-stream message index for set adaptive triggers.
constexpr int IDX_SET_PLAYER_LEDS = 16; ///< Control-stream message index for set player indicator LEDs.
static const short packetTypes[] = {
0x0305, // Start A
0x0307, // Start B
0x0301, // Invalidate reference frames
0x0201, // Loss Stats
0x0204, // Frame Stats (unused)
0x0206, // Input data
0x010b, // Rumble data
0x0109, // Termination
0x0200, // Periodic Ping
0x0302, // IDR frame
0x0001, // fully encrypted
0x010e, // HDR mode
0x5500, // Rumble triggers (Sunshine protocol extension)
0x5501, // Set motion event (Sunshine protocol extension)
0x5502, // Set RGB LED (Sunshine protocol extension)
0x5503, // Set Adaptive triggers (Sunshine protocol extension)
0x5504, // Set player indicator LEDs (Sunshine protocol extension)
};
namespace asio = boost::asio;
namespace sys = boost::system;
using asio::ip::tcp;
using asio::ip::udp;
using namespace std::literals;
namespace stream {
/**
* @brief Enumerates supported socket options.
*/
enum class socket_e : int {
video, ///< Video
audio ///< Audio
};
#pragma pack(push, 1)
/**
* @brief Packed short video frame header sent before video payload bytes.
*/
struct video_short_frame_header_t {
/**
* @brief Return a pointer to the protocol payload following the packet header.
*
* @return Parsed or serialized payload data.
*/
uint8_t *payload() {
return (uint8_t *) (this + 1);
}
std::uint8_t headerType; ///< Always 0x01 for short headers.
// Sunshine extension
// Frame processing latency, in 1/10 ms units
// zero when the frame is repeated or there is no backend implementation
boost::endian::little_uint16_at frame_processing_latency; ///< Frame processing latency.
// Currently known values:
// 1 = Normal P-frame
// 2 = IDR-frame
// 4 = P-frame with intra-refresh blocks
// 5 = P-frame after reference frame invalidation
std::uint8_t frameType; ///< Frame type.
// Length of the final packet payload for codecs that cannot handle
// zero padding, such as AV1 (Sunshine extension).
boost::endian::little_uint16_at lastPayloadLen; ///< Last payload len.
std::uint8_t unknown[2]; ///< Reserved bytes with no known client-visible meaning.
};
static_assert(
sizeof(video_short_frame_header_t) == 8,
"Short frame header must be 8 bytes"
);
/**
* @brief Packed RTP and video headers for an unencrypted video packet.
*/
struct video_packet_raw_t {
/**
* @brief Return a pointer to the protocol payload following the packet header.
*
* @return Parsed or serialized payload data.
*/
uint8_t *payload() {
return (uint8_t *) (this + 1);
}
RTP_PACKET rtp; ///< RTP header that prefixes this payload.
char reserved[4]; ///< Reserved protocol padding bytes.
NV_VIDEO_PACKET packet; ///< GameStream video packet header.
};
/**
* @brief AES-GCM prefix written before encrypted video packet payloads.
*/
struct video_packet_enc_prefix_t {
/**
* @brief IV.
*/
std::uint8_t iv[12]; // 12-byte IV is ideal for AES-GCM
std::uint32_t frameNumber; ///< Frame number.
std::uint8_t tag[16]; ///< Authentication tag appended to the encrypted payload.
};
/**
* @brief Packed RTP header for an audio packet.
*/
struct audio_packet_t {
RTP_PACKET rtp; ///< RTP header that prefixes this payload.
};
/**
* @brief Packed control-channel header used before control payloads.
*/
struct control_header_v2 {
std::uint16_t type; ///< Control message type.
std::uint16_t payloadLength; ///< Payload length.
/**
* @brief Return a pointer to the protocol payload following the packet header.
*
* @return Parsed or serialized payload data.
*/
uint8_t *payload() {
return (uint8_t *) (this + 1);
}
};
/**
* @brief Control-channel termination message payload.
*/
struct control_terminate_t {
control_header_v2 header; ///< Control message header preceding this payload.
std::uint32_t ec; ///< Error code reported by the termination message.
};
/**
* @brief Control payload that sets controller rumble motors.
*/
struct control_rumble_t {
control_header_v2 header; ///< Control message header preceding this payload.
std::uint32_t useless; ///< Reserved field kept for protocol compatibility.
std::uint16_t id; ///< Controller identifier associated with this message.
std::uint16_t lowfreq; ///< Low-frequency rumble motor intensity.
std::uint16_t highfreq; ///< High-frequency rumble motor intensity.
};
/**
* @brief Control payload that sets trigger rumble motors.
*/
struct control_rumble_triggers_t {
control_header_v2 header; ///< Control message header preceding this payload.
std::uint16_t id; ///< Controller identifier associated with this message.
std::uint16_t left; ///< Left trigger or motor intensity.
std::uint16_t right; ///< Right trigger or motor intensity.
};
/**
* @brief Control payload that enables or disables motion reports.
*/
struct control_set_motion_event_t {
control_header_v2 header; ///< Control message header preceding this payload.
std::uint16_t id; ///< Controller identifier associated with this message.
std::uint16_t reportrate; ///< Requested motion report rate.
std::uint8_t type; ///< Protocol or controller type discriminator.
};
/**
* @brief Control payload that sets controller RGB LED color.
*/
struct control_set_rgb_led_t {
control_header_v2 header; ///< Control message header preceding this payload.
std::uint16_t id; ///< Controller identifier associated with this message.
std::uint8_t r; ///< Red LED channel.
std::uint8_t g; ///< Green LED channel.
std::uint8_t b; ///< Blue LED channel.
};
/**
* @brief Control payload that sets controller player indicator LEDs.
*/
struct control_set_player_leds_t {
control_header_v2 header; ///< Control message header preceding this payload.
std::uint16_t id; ///< Controller identifier associated with this message.
std::uint8_t solid; ///< Four-bit mask of solid player indicators.
std::uint8_t flashing; ///< Four-bit mask of flashing player indicators.
};
/**
* @brief Control payload that configures DualSense adaptive triggers.
*/
struct control_adaptive_triggers_t {
control_header_v2 header; ///< Control message header preceding this payload.
std::uint16_t id; ///< Controller identifier associated with this message.
/**
* 0x04 - Right trigger
* 0x08 - Left trigger
*/
std::uint8_t event_flags;
std::uint8_t type_left; ///< Adaptive-trigger mode for the left trigger.
std::uint8_t type_right; ///< Adaptive-trigger mode for the right trigger.
std::uint8_t left[DS_EFFECT_PAYLOAD_SIZE]; ///< Left adaptive-trigger effect payload.
std::uint8_t right[DS_EFFECT_PAYLOAD_SIZE]; ///< Right adaptive-trigger effect payload.
};
/**
* @brief Control payload that toggles HDR mode and carries metadata.
*/
struct control_hdr_mode_t {
control_header_v2 header; ///< Control message header preceding this payload.
std::uint8_t enabled; ///< Nonzero when HDR should be enabled.
// Sunshine protocol extension
SS_HDR_METADATA metadata; ///< HDR10 metadata sent with the control message.
};
/**
* @brief Packed encrypted control-channel envelope.
*/
typedef struct control_encrypted_t {
std::uint16_t encryptedHeaderType; ///< Always LE 0x0001.
std::uint16_t length; ///< Size of seq, tag, secondary header, and data.
// seq is accepted as an arbitrary value in Moonlight
std::uint32_t seq; ///< Monotonically increasing sequence number used as the AES-GCM IV.
/**
* @brief Return a pointer to the protocol payload following the packet header.
*
* @return Parsed or serialized payload data.
*/
uint8_t *payload() {
return (uint8_t *) (this + 1);
}
// encrypted control_header_v2 and payload data follow
} *control_encrypted_p; ///< Alias for control encrypted p.
/**
* @brief Packed RTP and FEC headers for an audio recovery packet.
*/
struct audio_fec_packet_t {
RTP_PACKET rtp; ///< RTP header that prefixes this payload.
AUDIO_FEC_HEADER fecHeader; ///< Audio forward-error-correction header.
};
#pragma pack(pop)
/**
* @brief Round a byte count up to the next PKCS#7 padding boundary.
*
* @param size Number of bytes or elements requested.
* @return `size` rounded up to the next PKCS#7 block boundary.
*/
constexpr std::size_t round_to_pkcs7_padded(std::size_t size) {
return ((size + 15) / 16) * 16;
}
constexpr std::size_t MAX_AUDIO_PACKET_SIZE = 1400; ///< Protocol or platform constant for max audio packet size.
/**
* @brief AES key storage used for audio packet encryption.
*/
using audio_aes_t = std::array<char, round_to_pkcs7_padded(MAX_AUDIO_PACKET_SIZE)>;
/**
* @brief Audio/video session identifier carried by GameStream packets.
*/
using av_session_id_t = std::variant<asio::ip::address, std::string>; // IP address or SS-Ping-Payload from RTSP handshake
/**
* @brief Mail queue carrying encoded stream packets to sender threads.
*/
using message_queue_t = std::shared_ptr<safe::queue_t<std::pair<udp::endpoint, std::string>>>;
/**
* @brief Shared queue set used to distribute packet queues to broadcast workers.
*/
using message_queue_queue_t = std::shared_ptr<safe::queue_t<std::tuple<socket_e, av_session_id_t, message_queue_t>>>;
// return bytes written on success
// return -1 on error
static inline int encode_audio(bool encrypted, const audio::buffer_t &plaintext, uint8_t *destination, crypto::aes_t &iv, crypto::cipher::cbc_t &cbc) {
// If encryption isn't enabled
if (!encrypted) {
std::copy(std::begin(plaintext), std::end(plaintext), destination);
return (int) plaintext.size();
}
return cbc.encrypt(std::string_view {(char *) std::begin(plaintext), plaintext.size()}, destination, &iv);
}
static inline void while_starting_do_nothing(std::atomic<session::state_e> &state) {
while (state.load(std::memory_order_acquire) == session::state_e::STARTING) {
std::this_thread::sleep_for(1ms);
}
}
/**
* @brief ENet control server that routes incoming control packets to stream sessions.
*/
class control_server_t {
public:
/**
* @brief Bind the underlying socket or graphics resource to its target.
*
* @param address_family Address family.
* @param port TCP or UDP port number.
* @return Network operation status.
*/
int bind(net::af_e address_family, std::uint16_t port) {
_host = net::host_create(address_family, _addr, port);
return !(bool) _host;
}
// Get session associated with address.
// If none are found, try to find a session not yet claimed. (It will be marked by a port of value 0
// If none of those are found, return nullptr
/**
* @brief Return the session value from the backend.
*
* @param peer Remote endpoint associated with the socket.
* @param connect_data Connect data.
* @return Existing session for the peer/connect-data pair, or nullptr when none matches.
*/
session_t *get_session(const net::peer_t peer, uint32_t connect_data);
// Circular dependency:
// iterate refers to session
// session refers to broadcast_ctx_t
// broadcast_ctx_t refers to control_server_t
// Therefore, iterate is implemented further down the source file
/**
* @brief Visit each active control server session.
*
* @param timeout Maximum time to wait for the operation.
*/
void iterate(std::chrono::milliseconds timeout);
/**
* @brief Call the handler for a given control stream message.
* @param type The message type.
* @param session The session the message was received on.
* @param payload The payload of the message.
* @param reinjected `true` if this message is being reprocessed after decryption.
*/
void call(std::uint16_t type, session_t *session, const std::string_view &payload, bool reinjected);
/**
* @brief Register or visit handlers stored in the map.
*
* @param type Protocol, message, or resource type selector.
* @param cb Callback invoked for each matching message or session.
*/
void map(uint16_t type, std::function<void(session_t *, const std::string_view &)> cb) {
_map_type_cb.emplace(type, std::move(cb));
}
/**
* @brief Send the serialized response over the active socket.
*
* @param payload Optional payload body to include in the response.
* @param peer Remote endpoint associated with the socket.
* @return Network operation status.
*/
int send(const std::string_view &payload, net::peer_t peer) {
auto packet = enet_packet_create(payload.data(), payload.size(), ENET_PACKET_FLAG_RELIABLE);
if (enet_peer_send(peer, 0, packet)) {
enet_packet_destroy(packet);
return -1;
}
return 0;
}
/**
* @brief Flush pending packets to the stream socket.
*/
void flush() {
enet_host_flush(_host.get());
}
// Callbacks
std::unordered_map<std::uint16_t, std::function<void(session_t *, const std::string_view &)>> _map_type_cb; ///< Control-message handlers keyed by packet type.
// All active sessions (including those still waiting for a peer to connect)
sync_util::sync_t<std::vector<session_t *>> _sessions; ///< Active sessions registered with the control server.
// ENet peer to session mapping for sessions with a peer connected
sync_util::sync_t<std::map<net::peer_t, session_t *>> _peer_to_session; ///< Peer to session.
ENetAddress _addr; ///< Local ENet address used by the control channel.
net::host_t _host; ///< ENet host object that owns the control socket.
};
/**
* @brief UDP broadcast socket and target address state.
*/
struct broadcast_ctx_t {
message_queue_queue_t message_queue_queue; ///< Queues carrying encoded video and audio packets to sender threads.
std::jthread recv_thread; ///< Thread that receives incoming control-channel messages.
std::jthread video_thread; ///< Thread that sends encoded video packets.
std::jthread audio_thread; ///< Thread that sends encoded audio packets.
std::jthread control_thread; ///< Thread that runs the ENet control server.
asio::io_context io_context; ///< Asio context used by the UDP broadcast sockets.
udp::socket video_sock {io_context}; ///< UDP socket bound for video packet transmission.
udp::socket audio_sock {io_context}; ///< UDP socket bound for audio packet transmission.
control_server_t control_server; ///< ENet server for GameStream control packets.
};
/**
* @brief Runtime state for one audio/video streaming session.
*/
struct session_t {
config_t config; ///< Stream or encoder configuration captured for the worker.
safe::mail_t mail; ///< Mailbox used to distribute packets and lifecycle events.
std::shared_ptr<input::input_t> input; ///< Platform input device state for this stream.
std::jthread audioThread; ///< Audio thread.
std::jthread videoThread; ///< Video thread.
std::chrono::steady_clock::time_point pingTimeout; ///< Deadline for receiving the next client ping.
safe::shared_t<broadcast_ctx_t>::ptr_t broadcast_ref; ///< Shared broadcast context retained while the session is active.
boost::asio::ip::address localAddress; ///< Local address.
struct {
std::string ping_payload;
int lowseq;
udp::endpoint peer;
std::optional<crypto::cipher::gcm_t> cipher;
std::uint64_t gcm_iv_counter;
safe::mail_raw_t::event_t<bool> idr_events;
safe::mail_raw_t::event_t<std::pair<int64_t, int64_t>> invalidate_ref_frames_events;
std::unique_ptr<platf::deinit_t> qos;
} video; ///< Video worker thread state for the active stream.
struct {
crypto::cipher::cbc_t cipher;
std::string ping_payload;
std::uint16_t sequenceNumber;
// avRiKeyId == util::endian::big(First (sizeof(avRiKeyId)) bytes of launch_session->iv)
std::uint32_t avRiKeyId;
std::uint32_t timestamp;
udp::endpoint peer;
util::buffer_t<char> shards;
util::buffer_t<uint8_t *> shards_p;
audio_fec_packet_t fec_packet;
std::unique_ptr<platf::deinit_t> qos;
} audio; ///< Audio capture configuration for the stream..
struct {
crypto::cipher::gcm_t cipher;
crypto::aes_t legacy_input_enc_iv; // Only used when the client doesn't support full control stream encryption
crypto::aes_t incoming_iv;
crypto::aes_t outgoing_iv;
std::uint32_t connect_data; // Used for new clients with ML_FF_SESSION_ID_V1
std::string expected_peer_address; // Only used for legacy clients without ML_FF_SESSION_ID_V1
net::peer_t peer;
std::uint32_t seq;
platf::feedback_queue_t feedback_queue;
safe::mail_raw_t::event_t<video::hdr_info_t> hdr_queue;
} control; ///< Runtime state for the encrypted GameStream control channel.
std::uint32_t launch_session_id; ///< RTSP launch-session ID associated with this stream.
std::string client_cert; ///< PEM certificate for the paired client owning the stream.
std::string input_session_id; ///< Stable client identity used to retain input devices across resume.
safe::mail_raw_t::event_t<bool> shutdown_event; ///< Event raised when the stream should shut down.
safe::signal_t controlEnd; ///< Signal raised when the control channel exits.
std::atomic<session::state_e> state; ///< Current lifecycle state observed by stream workers.
};
/**
* First part of cipher must be struct of type control_encrypted_t
*
* returns empty string_view on failure
* returns string_view pointing to payload data
*/
template<std::size_t max_payload_size>
static inline std::string_view encode_control(session_t *session, const std::string_view &plaintext, std::array<std::uint8_t, max_payload_size> &tagged_cipher) {
static_assert(
max_payload_size >= sizeof(control_encrypted_t) + sizeof(crypto::cipher::tag_size),
"max_payload_size >= sizeof(control_encrypted_t) + sizeof(crypto::cipher::tag_size)"
);
if (session->config.controlProtocolType != 13) {
return plaintext;
}
auto seq = session->control.seq++;
auto &iv = session->control.outgoing_iv;
if (session->config.encryptionFlagsEnabled & SS_ENC_CONTROL_V2) {
// 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 'CH' 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 control stream messages
// to be sent to each client before the IV repeats.
iv.resize(12);
std::copy_n((uint8_t *) &seq, sizeof(seq), std::begin(iv));
iv[10] = 'H'; // Host originated
iv[11] = 'C'; // Control stream
} else {
// Nvidia's old style encryption uses a 16-byte IV
iv.resize(16);
iv[0] = (std::uint8_t) seq;
}
auto packet = (control_encrypted_p) tagged_cipher.data();
auto bytes = session->control.cipher.encrypt(plaintext, packet->payload(), &iv);
if (bytes <= 0) {
BOOST_LOG(error) << "Couldn't encrypt control data"sv;
return {};
}
std::uint16_t packet_length = bytes + crypto::cipher::tag_size + sizeof(control_encrypted_t::seq);
packet->encryptedHeaderType = util::endian::little(0x0001);
packet->length = util::endian::little(packet_length);
packet->seq = util::endian::little(seq);
return std::string_view {(char *) tagged_cipher.data(), packet_length + sizeof(control_encrypted_t) - sizeof(control_encrypted_t::seq)};
}
/**
* @brief Start periodic mDNS and service-discovery broadcasts.
*
* @param ctx Native context object used by the operation or callback.
* @return 0 on success; nonzero when broadcast setup fails.
*/
int start_broadcast(broadcast_ctx_t &ctx);
/**
* @brief Stop broadcast processing.
*
* @param ctx Native context object used by the operation or callback.
*/
void end_broadcast(broadcast_ctx_t &ctx);
static auto broadcast = safe::make_shared<broadcast_ctx_t>(start_broadcast, end_broadcast);
session_t *control_server_t::get_session(const net::peer_t peer, uint32_t connect_data) {
{
// Fast path - look up existing session by peer
auto lg = _peer_to_session.lock();
auto it = _peer_to_session->find(peer);
if (it != _peer_to_session->end()) {
return it->second;
}
}
// Slow path - process new session
TUPLE_2D(peer_port, peer_addr, platf::from_sockaddr_ex((sockaddr *) &peer->address.address));
auto lg = _sessions.lock();
for (auto pos = std::begin(*_sessions); pos != std::end(*_sessions); ++pos) {
auto session_p = *pos;
// Skip sessions that are already established
if (session_p->control.peer) {
continue;
}
// Identify the connection by the unique connect data if the client supports it.
// Only fall back to IP address matching for clients without session ID support.
if (session_p->config.mlFeatureFlags & ML_FF_SESSION_ID_V1) {
if (session_p->control.connect_data != connect_data) {
continue;
} else {
BOOST_LOG(debug) << "Initialized new control stream session by connect data match [v2]"sv;
}
} else {
if (session_p->control.expected_peer_address != peer_addr) {
continue;
} else {
BOOST_LOG(debug) << "Initialized new control stream session by IP address match [v1]"sv;
}
}
// Once the control stream connection is established, RTSP session state can be torn down
rtsp_stream::launch_session_clear(session_p->launch_session_id);
session_p->control.peer = peer;
// Use the local address from the control connection as the source address
// for other communications to the client. This is necessary to ensure
// proper routing on multi-homed hosts.
auto local_address = platf::from_sockaddr((sockaddr *) &peer->localAddress.address);
try {
session_p->localAddress = boost::asio::ip::make_address(local_address);
} catch (const boost::system::system_error &e) {
BOOST_LOG(error) << "boost::system::system_error in address parsing: " << e.what() << " (code: " << e.code() << ")"sv;
throw;
}
BOOST_LOG(debug) << "Control local address ["sv << local_address << ']';
BOOST_LOG(debug) << "Control peer address ["sv << peer_addr << ':' << peer_port << ']';
// Insert this into the map for O(1) lookups in the future
auto ptslg = _peer_to_session.lock();
_peer_to_session->emplace(peer, session_p);
return session_p;
}
return nullptr;
}
/**
* @brief Call the handler for a given control stream message.
* @param type The message type.
* @param session The session the message was received on.
* @param payload The payload of the message.
* @param reinjected `true` if this message is being reprocessed after decryption.
*/
void control_server_t::call(std::uint16_t type, session_t *session, const std::string_view &payload, bool reinjected) {
// If we are using the encrypted control stream protocol, drop any messages that come off the wire unencrypted
if (session->config.controlProtocolType == 13 && !reinjected && type != packetTypes[IDX_ENCRYPTED]) {
BOOST_LOG(error) << "Dropping unencrypted message on encrypted control stream: "sv << util::hex(type).to_string_view();
return;
}
auto cb = _map_type_cb.find(type);
if (cb == std::end(_map_type_cb)) {
BOOST_LOG(debug)
<< "type [Unknown] { "sv << util::hex(type).to_string_view() << " }"sv << std::endl
<< "---data---"sv << std::endl
<< util::hex_vec(payload) << std::endl
<< "---end data---"sv;
} else {
cb->second(session, payload);
}
}
void control_server_t::iterate(std::chrono::milliseconds timeout) {
ENetEvent event;
auto res = enet_host_service(_host.get(), &event, (enet_uint32) timeout.count());
if (res > 0) {
auto session = get_session(event.peer, event.data);
if (!session) {
BOOST_LOG(warning) << "Rejected connection from ["sv << platf::from_sockaddr((sockaddr *) &event.peer->address.address) << "]: it's not properly set up"sv;
enet_peer_disconnect_now(event.peer, 0);
return;
}
session->pingTimeout = std::chrono::steady_clock::now() + config::stream.ping_timeout;
switch (event.type) {
case ENET_EVENT_TYPE_RECEIVE:
{
net::packet_t packet {event.packet};
auto type = *(std::uint16_t *) packet->data;
std::string_view payload {(char *) packet->data + sizeof(type), packet->dataLength - sizeof(type)};
call(type, session, payload, false);
}
break;
case ENET_EVENT_TYPE_CONNECT:
BOOST_LOG(info) << "CLIENT CONNECTED"sv;
break;
case ENET_EVENT_TYPE_DISCONNECT:
BOOST_LOG(info) << "CLIENT DISCONNECTED"sv;
// No more clients to send video data to ^_^
if (session->state == session::state_e::RUNNING) {
session::stop(*session);
}
break;
case ENET_EVENT_TYPE_NONE:
break;
}
}
}
namespace fec {
/**
* @brief Owning pointer for a Reed-Solomon encoder instance.
*/
using rs_t = util::safe_ptr<reed_solomon, [](reed_solomon *rs) {
reed_solomon_release(rs);
}>;
/**
* @brief Reed-Solomon FEC encoder state for video packets.
*/
struct fec_t {
size_t data_shards; ///< Number of original packet shards in each FEC block.
size_t nr_shards; ///< Total data and recovery shards generated for each FEC block.
size_t percentage; ///< Recovery-shard percentage requested for the stream.
size_t blocksize; ///< Bytes reserved for the payload portion of each shard.
size_t prefixsize; ///< Bytes reserved before each shard payload for protocol headers.
util::buffer_t<char> shards; ///< Contiguous backing storage for all encoded FEC shards.
util::buffer_t<char> headers; ///< Backing storage for the RTP/FEC headers attached to shards.
util::buffer_t<uint8_t *> shards_p; ///< Pointer table passed to the Reed-Solomon encoder.
std::vector<platf::buffer_descriptor_t> payload_buffers; ///< Platform send descriptors for FEC payload buffers.
/**
* @brief Return the FEC shard data pointer for a packet-group element.
*
* @param el Packet-group element index.
* @return Pointer to the shard bytes for the requested element.
*/
char *data(size_t el) {
return (char *) shards_p[el];
}
/**
* @brief Return the FEC prefix bytes for the current packet group.
*
* @param el Packet-group element index.
* @return Pointer to the element's prefix bytes, or nullptr when no prefix is used.
*/
char *prefix(size_t el) {
return prefixsize ? &headers[el * prefixsize] : nullptr;
}
/**
* @brief Return the serialized size of the current object.
*
* @return Number of elements currently stored.
*/
size_t size() const {
return nr_shards;
}
};
static fec_t encode(const std::string_view &payload, size_t blocksize, size_t fecpercentage, size_t minparityshards, size_t prefixsize) {
auto payload_size = payload.size();
auto pad = payload_size % blocksize != 0;
auto aligned_data_shards = payload_size / blocksize;
auto data_shards = aligned_data_shards + (pad ? 1 : 0);
auto parity_shards = (data_shards * fecpercentage + 99) / 100;
// increase the FEC percentage for this frame if the parity shard minimum is not met
if (parity_shards < minparityshards && fecpercentage != 0) {
parity_shards = minparityshards;
fecpercentage = (100 * parity_shards) / data_shards;
BOOST_LOG(verbose) << "Increasing FEC percentage to "sv << fecpercentage << " to meet parity shard minimum"sv << std::endl;
}
auto nr_shards = data_shards + parity_shards;
// If we need to store a zero-padded data shard, allocate that first to
// to keep the shards in order and reduce buffer fragmentation
auto parity_shard_offset = pad ? 1 : 0;
util::buffer_t<char> shards {(parity_shard_offset + parity_shards) * blocksize};
util::buffer_t<uint8_t *> shards_p {nr_shards};
std::vector<platf::buffer_descriptor_t> payload_buffers;
payload_buffers.reserve(2);
// Point into the payload buffer for all except the final padded data shard
auto next = std::begin(payload);
for (auto x = 0; x < aligned_data_shards; ++x) {
shards_p[x] = (uint8_t *) next;
next += blocksize;
}
payload_buffers.emplace_back(std::begin(payload), aligned_data_shards * blocksize);
// If the last data shard needs to be zero-padded, we must use the shards buffer
if (pad) {
shards_p[aligned_data_shards] = (uint8_t *) &shards[0];
// GCC doesn't figure out that std::copy_n() can be replaced with memcpy() here
// and ends up compiling a horribly slow element-by-element copy loop, so we
// help it by using memcpy()/memset() directly.
auto copy_len = std::min<size_t>(blocksize, std::end(payload) - next);
std::memcpy(shards_p[aligned_data_shards], next, copy_len);
if (copy_len < blocksize) {
// Zero any additional space after the end of the payload
std::memset(shards_p[aligned_data_shards] + copy_len, 0, blocksize - copy_len);
}
}
// Add a payload buffer describing the shard buffer
payload_buffers.emplace_back(std::begin(shards), shards.size());
if (fecpercentage != 0) {
// Point into our allocated buffer for the parity shards
for (auto x = 0; x < parity_shards; ++x) {
shards_p[data_shards + x] = (uint8_t *) &shards[(parity_shard_offset + x) * blocksize];
}
// packets = parity_shards + data_shards
rs_t rs {reed_solomon_new((int) data_shards, (int) parity_shards)};
reed_solomon_encode(rs.get(), shards_p.begin(), (int) nr_shards, (int) blocksize);
}
return {
data_shards,
nr_shards,
fecpercentage,
blocksize,
prefixsize,
std::move(shards),
util::buffer_t<char> {nr_shards * prefixsize},
std::move(shards_p),
std::move(payload_buffers),
};
}
} // namespace fec
/**
* @brief Combines two buffers and inserts new buffers at each slice boundary of the result.
* @param insert_size The number of bytes to insert.
* @param slice_size The number of bytes between insertions.
* @param data1 The first data buffer.
* @param data2 The second data buffer.
*
* @return Combined buffer with insert padding written at each slice boundary.
*/
std::vector<uint8_t> concat_and_insert(uint64_t insert_size, uint64_t slice_size, const std::string_view &data1, const std::string_view &data2) {
auto data_size = data1.size() + data2.size();
auto pad = data_size % slice_size != 0;
auto elements = data_size / slice_size + (pad ? 1 : 0);
std::vector<uint8_t> result;
result.resize(elements * insert_size + data_size);
auto next = std::begin(data1);
auto end = std::end(data1);
for (auto x = 0; x < elements; ++x) {
void *p = &result[x * (insert_size + slice_size)];
// For the last iteration, only copy to the end of the data
if (x == elements - 1) {
slice_size = data_size - (x * slice_size);
}
// Test if this slice will extend into the next buffer
if (next + slice_size > end) {
// Copy the first portion from the first buffer
auto copy_len = end - next;
std::copy(next, end, (char *) p + insert_size);
// Copy the remaining portion from the second buffer
next = std::begin(data2);
end = std::end(data2);
std::copy(next, next + (slice_size - copy_len), (char *) p + copy_len + insert_size);
next += slice_size - copy_len;
} else {
std::copy(next, next + slice_size, (char *) p + insert_size);
next += slice_size;
}
}
return result;
}
/**
* @brief Replace a byte sequence in an encoded packet.
*
* @param original Original text value used when reporting a parsing failure.
* @param old Byte sequence to replace in encoded packets.
* @param _new Replacement byte sequence inserted into encoded packets.
* @return Copy of the original buffer with each matching byte sequence replaced.
*/
std::vector<uint8_t> replace(const std::string_view &original, const std::string_view &old, const std::string_view &_new) {
std::vector<uint8_t> replaced;
replaced.reserve(original.size() + _new.size() - old.size());
auto begin = std::begin(original);
auto end = std::end(original);
auto next = std::search(begin, end, std::begin(old), std::end(old));
std::copy(begin, next, std::back_inserter(replaced));
if (next != end) {
std::copy(std::begin(_new), std::end(_new), std::back_inserter(replaced));
std::copy(next + old.size(), end, std::back_inserter(replaced));
}
return replaced;
}
/**
* @brief Pass gamepad feedback data back to the client.
* @param session The session object.
* @param msg The message to pass.
* @return 0 on success.
*/
int send_feedback_msg(session_t *session, platf::gamepad_feedback_msg_t &msg) {
if (!session->control.peer) {
BOOST_LOG(warning) << "Couldn't send gamepad feedback data, still waiting for PING from Moonlight"sv;
// Still waiting for PING from Moonlight
return -1;
}
std::string payload;
if (msg.type == platf::gamepad_feedback_e::rumble) {
control_rumble_t plaintext;
plaintext.header.type = packetTypes[IDX_RUMBLE_DATA];
plaintext.header.payloadLength = sizeof(plaintext) - sizeof(control_header_v2);
auto &data = msg.data.rumble;
plaintext.useless = 0xC0FFEE;
plaintext.id = util::endian::little(msg.id);
plaintext.lowfreq = util::endian::little(data.lowfreq);
plaintext.highfreq = util::endian::little(data.highfreq);
BOOST_LOG(verbose) << "Rumble: "sv << msg.id << " :: "sv << util::hex(data.lowfreq).to_string_view() << " :: "sv << util::hex(data.highfreq).to_string_view();
std::array<std::uint8_t, sizeof(control_encrypted_t) + crypto::cipher::round_to_pkcs7_padded(sizeof(plaintext)) + crypto::cipher::tag_size>
encrypted_payload;