-
-
Notifications
You must be signed in to change notification settings - Fork 75
/
takion.c
1669 lines (1402 loc) · 53.5 KB
/
takion.c
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
// SPDX-License-Identifier: LicenseRef-AGPL-3.0-only-OpenSSL
#include "chiaki/feedback.h"
#include <chiaki/takion.h>
#include <chiaki/congestioncontrol.h>
#include <chiaki/random.h>
#include <chiaki/gkcrypt.h>
#include <chiaki/time.h>
#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <assert.h>
#ifdef __APPLE__
#include <CoreServices/CoreServices.h>
#endif
#ifdef _WIN32
#include <ws2tcpip.h>
#elif defined(__SWITCH__)
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#else
#include <unistd.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <sys/socket.h>
#endif
// VERY similar to SCTP, see RFC 4960
#define TAKION_A_RWND 0x19000
#define TAKION_OUTBOUND_STREAMS 0x64
#define TAKION_INBOUND_STREAMS 0x64
#define TAKION_REORDER_QUEUE_SIZE_EXP 4 // => 16 entries
#define TAKION_SEND_BUFFER_SIZE 16
#define TAKION_POSTPONE_PACKETS_SIZE 32
#define TAKION_MESSAGE_HEADER_SIZE 0x10
#define TAKION_PACKET_BASE_TYPE_MASK 0xf
#define TAKION_EXPECT_TIMEOUT_MS 5000
/**
* Base type of Takion packets. Lower nibble of the first byte in datagrams.
*/
typedef enum takion_packet_type_t {
TAKION_PACKET_TYPE_CONTROL = 0,
TAKION_PACKET_TYPE_FEEDBACK_HISTORY = 1,
TAKION_PACKET_TYPE_VIDEO = 2,
TAKION_PACKET_TYPE_AUDIO = 3,
TAKION_PACKET_TYPE_HANDSHAKE = 4,
TAKION_PACKET_TYPE_CONGESTION = 5,
TAKION_PACKET_TYPE_FEEDBACK_STATE = 6,
TAKION_PACKET_TYPE_CLIENT_INFO = 8,
} TakionPacketType;
/**
* @return The offset of the mac of size CHIAKI_GKCRYPT_GMAC_SIZE inside a packet of type or -1 if unknown.
*/
int takion_packet_type_mac_offset(TakionPacketType type)
{
switch(type)
{
case TAKION_PACKET_TYPE_CONTROL:
return 5;
case TAKION_PACKET_TYPE_VIDEO:
case TAKION_PACKET_TYPE_AUDIO:
return 0xa;
case TAKION_PACKET_TYPE_CONGESTION:
return 7;
default:
return -1;
}
}
/**
* @return The offset of the 4-byte key_pos inside a packet of type or -1 if unknown.
*/
int takion_packet_type_key_pos_offset(TakionPacketType type)
{
switch(type)
{
case TAKION_PACKET_TYPE_CONTROL:
return 0x9;
case TAKION_PACKET_TYPE_VIDEO:
case TAKION_PACKET_TYPE_AUDIO:
return 0xe;
case TAKION_PACKET_TYPE_CONGESTION:
return 0xb;
default:
return -1;
}
}
typedef enum takion_chunk_type_t {
TAKION_CHUNK_TYPE_DATA = 0,
TAKION_CHUNK_TYPE_INIT = 1,
TAKION_CHUNK_TYPE_INIT_ACK = 2,
TAKION_CHUNK_TYPE_DATA_ACK = 3,
TAKION_CHUNK_TYPE_COOKIE = 0xa,
TAKION_CHUNK_TYPE_COOKIE_ACK = 0xb,
} TakionChunkType;
typedef struct takion_message_t
{
uint32_t tag;
//uint8_t zero[4];
uint64_t key_pos;
uint8_t chunk_type;
uint8_t chunk_flags;
uint16_t payload_size;
uint8_t *payload;
} TakionMessage;
typedef struct takion_message_payload_init_t
{
uint32_t tag;
uint32_t a_rwnd;
uint16_t outbound_streams;
uint16_t inbound_streams;
uint32_t initial_seq_num;
} TakionMessagePayloadInit;
#define TAKION_COOKIE_SIZE 0x20
typedef struct takion_message_payload_init_ack_t
{
uint32_t tag;
uint32_t a_rwnd;
uint16_t outbound_streams;
uint16_t inbound_streams;
uint32_t initial_seq_num;
uint8_t cookie[TAKION_COOKIE_SIZE];
} TakionMessagePayloadInitAck;
typedef struct
{
uint8_t *packet_buf;
size_t packet_size;
uint8_t type_b;
uint8_t *payload; // inside packet_buf
size_t payload_size;
uint16_t channel;
} TakionDataPacketEntry;
typedef struct chiaki_takion_postponed_packet_t
{
uint8_t *buf;
size_t buf_size;
} ChiakiTakionPostponedPacket;
static void *takion_thread_func(void *user);
static void takion_handle_packet(ChiakiTakion *takion, uint8_t *buf, size_t buf_size);
static ChiakiErrorCode takion_handle_packet_mac(ChiakiTakion *takion, uint8_t base_type, uint8_t *buf, size_t buf_size);
static void takion_handle_packet_message(ChiakiTakion *takion, uint8_t *buf, size_t buf_size);
static void takion_handle_packet_message_data(ChiakiTakion *takion, uint8_t *packet_buf, size_t packet_buf_size, uint8_t type_b, uint8_t *payload, size_t payload_size);
static void takion_handle_packet_message_data_ack(ChiakiTakion *takion, uint8_t flags, uint8_t *buf, size_t buf_size);
static ChiakiErrorCode takion_parse_message(ChiakiTakion *takion, uint8_t *buf, size_t buf_size, TakionMessage *msg);
static void takion_write_message_header(uint8_t *buf, uint32_t tag, uint64_t key_pos, uint8_t chunk_type, uint8_t chunk_flags, size_t payload_data_size);
static ChiakiErrorCode takion_send_message_init(ChiakiTakion *takion, TakionMessagePayloadInit *payload);
static ChiakiErrorCode takion_send_message_cookie(ChiakiTakion *takion, uint8_t *cookie);
static ChiakiErrorCode takion_recv(ChiakiTakion *takion, uint8_t *buf, size_t *buf_size, uint64_t timeout_ms);
static ChiakiErrorCode takion_recv_message_init_ack(ChiakiTakion *takion, TakionMessagePayloadInitAck *payload);
static ChiakiErrorCode takion_recv_message_cookie_ack(ChiakiTakion *takion);
static void takion_handle_packet_av(ChiakiTakion *takion, uint8_t base_type, uint8_t *buf, size_t buf_size);
static ChiakiErrorCode takion_read_extra_sock_messages(ChiakiTakion *takion);
CHIAKI_EXPORT ChiakiErrorCode chiaki_takion_connect(ChiakiTakion *takion, ChiakiTakionConnectInfo *info, chiaki_socket_t *sock)
{
ChiakiErrorCode ret = CHIAKI_ERR_SUCCESS;
takion->log = info->log;
takion->close_socket = info->close_socket;
takion->version = info->protocol_version;
switch(takion->version)
{
case 7:
takion->av_packet_parse = chiaki_takion_v7_av_packet_parse;
break;
case 9:
takion->av_packet_parse = chiaki_takion_v9_av_packet_parse;
break;
case 12:
takion->av_packet_parse = chiaki_takion_v12_av_packet_parse;
break;
default:
CHIAKI_LOGE(takion->log, "Unknown Takion Protocol Version %u", (unsigned int)takion->version);
return CHIAKI_ERR_INVALID_DATA;
}
takion->gkcrypt_local = NULL;
ret = chiaki_mutex_init(&takion->gkcrypt_local_mutex, true);
if(ret != CHIAKI_ERR_SUCCESS)
return ret;
takion->key_pos_local = 0;
takion->gkcrypt_remote = NULL;
takion->cb = info->cb;
takion->cb_user = info->cb_user;
takion->a_rwnd = TAKION_A_RWND;
takion->tag_local = chiaki_random_32(); // 0x4823
takion->seq_num_local = takion->tag_local;
ret = chiaki_mutex_init(&takion->seq_num_local_mutex, false);
if(ret != CHIAKI_ERR_SUCCESS)
goto error_gkcrypt_local_mutex;
takion->tag_remote = 0;
takion->enable_crypt = info->enable_crypt;
takion->postponed_packets = NULL;
takion->postponed_packets_size = 0;
takion->postponed_packets_count = 0;
takion->enable_dualsense = info->enable_dualsense;
CHIAKI_LOGI(takion->log, "Takion connecting (version %u)", (unsigned int)info->protocol_version);
bool mac_dontfrag = true;
ChiakiErrorCode err = chiaki_stop_pipe_init(&takion->stop_pipe);
if(err != CHIAKI_ERR_SUCCESS)
{
CHIAKI_LOGE(takion->log, "Takion failed to create stop pipe");
goto error_seq_num_local_mutex;
}
if(sock)
{
takion->sock = *sock;
err = takion_read_extra_sock_messages(takion);
if(err != CHIAKI_ERR_SUCCESS && err != CHIAKI_ERR_TIMEOUT)
{
CHIAKI_LOGE(takion->log, "Takion had problem reading extra messages from socket using PSN Connection with error: " CHIAKI_SOCKET_ERROR_FMT, CHIAKI_SOCKET_ERROR_VALUE);
goto error_sock;
}
const int rcvbuf_val = takion->a_rwnd;
int r = setsockopt(takion->sock, SOL_SOCKET, SO_RCVBUF, (const CHIAKI_SOCKET_BUF_TYPE)&rcvbuf_val, sizeof(rcvbuf_val));
if(r < 0)
{
CHIAKI_LOGE(takion->log, "Takion failed to setsockopt SO_RCVBUF: " CHIAKI_SOCKET_ERROR_FMT, CHIAKI_SOCKET_ERROR_VALUE);
ret = CHIAKI_ERR_NETWORK;
goto error_sock;
}
#if defined(__APPLE__)
SInt32 majorVersion;
Gestalt(gestaltSystemVersionMajor, &majorVersion);
if(majorVersion < 11)
{
mac_dontfrag = false;
}
#endif
if(info->ip_dontfrag)
{
#if defined(_WIN32)
const DWORD dontfragment_val = 1;
r = setsockopt(takion->sock, IPPROTO_IP, IP_DONTFRAGMENT, (const CHIAKI_SOCKET_BUF_TYPE)&dontfragment_val, sizeof(dontfragment_val));
#elif defined(__FreeBSD__) || defined(__SWITCH__) || defined(__APPLE__)
if(mac_dontfrag)
{
const int dontfrag_val = 1;
r = setsockopt(takion->sock, IPPROTO_IP, IP_DONTFRAG, (const CHIAKI_SOCKET_BUF_TYPE)&dontfrag_val, sizeof(dontfrag_val));
}
else
CHIAKI_LOGW(takion->log, "Don't fragment is not supported on this platform, MTU values may be incorrect.");
#elif defined(IP_PMTUDISC_DO)
const int mtu_discover_val = IP_PMTUDISC_DO;
r = setsockopt(takion->sock, IPPROTO_IP, IP_MTU_DISCOVER, (const CHIAKI_SOCKET_BUF_TYPE)&mtu_discover_val, sizeof(mtu_discover_val));
#else
// macOS older than MacOS Big Sur (11) and OpenBSD
CHIAKI_LOGW(takion->log, "Don't fragment is not supported on this platform, MTU values may be incorrect.");
#define NO_DONTFRAG
#endif
#ifndef NO_DONTFRAG
if(r < 0 && mac_dontfrag)
{
CHIAKI_LOGE(takion->log, "Takion failed to setsockopt IP_MTU_DISCOVER: " CHIAKI_SOCKET_ERROR_FMT, CHIAKI_SOCKET_ERROR_VALUE);
ret = CHIAKI_ERR_NETWORK;
goto error_sock;
}
CHIAKI_LOGI(takion->log, "Takion enabled Don't Fragment Bit");
#endif
}
else
{
#if defined(_WIN32)
const DWORD dontfragment_val = 0;
r = setsockopt(takion->sock, IPPROTO_IP, IP_DONTFRAGMENT, (const CHIAKI_SOCKET_BUF_TYPE)&dontfragment_val, sizeof(dontfragment_val));
#elif defined(__FreeBSD__) || defined(__SWITCH__) || defined(__APPLE__)
if(mac_dontfrag)
{
const int dontfrag_val = 0;
r = setsockopt(takion->sock, IPPROTO_IP, IP_DONTFRAG, (const CHIAKI_SOCKET_BUF_TYPE)&dontfrag_val, sizeof(dontfrag_val));
}
#elif defined(IP_PMTUDISC_DO)
const int mtu_discover_val = IP_PMTUDISC_DONT;
r = setsockopt(takion->sock, IPPROTO_IP, IP_MTU_DISCOVER, (const CHIAKI_SOCKET_BUF_TYPE)&mtu_discover_val, sizeof(mtu_discover_val));
#else
// macOS older than MacOS Big Sur (11) and OpenBSD
#define NO_DONTFRAG
#endif
#ifndef NO_DONTFRAG
if(r < 0 && mac_dontfrag)
{
CHIAKI_LOGE(takion->log, "Takion failed to unset setsockopt IP_MTU_DISCOVER: " CHIAKI_SOCKET_ERROR_FMT, CHIAKI_SOCKET_ERROR_VALUE);
ret = CHIAKI_ERR_NETWORK;
goto error_sock;
}
CHIAKI_LOGI(takion->log, "Takion disabled Don't Fragment Bit");
#endif
}
}
else
{
takion->sock = socket(info->sa->sa_family, SOCK_DGRAM, IPPROTO_UDP);
if(CHIAKI_SOCKET_IS_INVALID(takion->sock))
{
CHIAKI_LOGE(takion->log, "Takion failed to create socket");
ret = CHIAKI_ERR_NETWORK;
goto error_pipe;
}
const int rcvbuf_val = takion->a_rwnd;
int r = setsockopt(takion->sock, SOL_SOCKET, SO_RCVBUF, (const CHIAKI_SOCKET_BUF_TYPE)&rcvbuf_val, sizeof(rcvbuf_val));
if(r < 0)
{
CHIAKI_LOGE(takion->log, "Takion failed to setsockopt SO_RCVBUF: " CHIAKI_SOCKET_ERROR_FMT, CHIAKI_SOCKET_ERROR_VALUE);
ret = CHIAKI_ERR_NETWORK;
goto error_sock;
}
if(info->ip_dontfrag)
{
#if defined(__APPLE__)
SInt32 majorVersion;
Gestalt(gestaltSystemVersionMajor, &majorVersion);
if(majorVersion < 11)
{
mac_dontfrag = false;
}
#endif
#if defined(_WIN32)
const DWORD dontfragment_val = 1;
r = setsockopt(takion->sock, IPPROTO_IP, IP_DONTFRAGMENT, (const CHIAKI_SOCKET_BUF_TYPE)&dontfragment_val, sizeof(dontfragment_val));
#elif defined(__FreeBSD__) || defined(__SWITCH__) || defined(__APPLE__)
const int dontfrag_val = 1;
r = setsockopt(takion->sock, IPPROTO_IP, IP_DONTFRAG, (const CHIAKI_SOCKET_BUF_TYPE)&dontfrag_val, sizeof(dontfrag_val));
#elif defined(IP_PMTUDISC_DO)
if(mac_dontfrag)
{
const int mtu_discover_val = IP_PMTUDISC_DO;
r = setsockopt(takion->sock, IPPROTO_IP, IP_MTU_DISCOVER, (const CHIAKI_SOCKET_BUF_TYPE)&mtu_discover_val, sizeof(mtu_discover_val));
}
else
CHIAKI_LOGW(takion->log, "Don't fragment is not supported on this platform, MTU values may be incorrect.");
#else
// macOS older than MacOS Big Sur (11) and OpenBSD
CHIAKI_LOGW(takion->log, "Don't fragment is not supported on this platform, MTU values may be incorrect.");
#define NO_DONTFRAG
#endif
#ifndef NO_DONTFRAG
if(r < 0 && mac_dontfrag)
{
CHIAKI_LOGE(takion->log, "Takion failed to setsockopt IP_MTU_DISCOVER: " CHIAKI_SOCKET_ERROR_FMT, CHIAKI_SOCKET_ERROR_VALUE);
ret = CHIAKI_ERR_NETWORK;
goto error_sock;
}
CHIAKI_LOGI(takion->log, "Takion enabled Don't Fragment Bit");
#endif
}
r = connect(takion->sock, info->sa, info->sa_len);
if(r < 0)
{
CHIAKI_LOGE(takion->log, "Takion failed to connect: " CHIAKI_SOCKET_ERROR_FMT, CHIAKI_SOCKET_ERROR_VALUE);
ret = CHIAKI_ERR_NETWORK;
goto error_sock;
}
if(r != CHIAKI_ERR_SUCCESS)
{
ret = err;
goto error_sock;
}
}
err = chiaki_thread_create(&takion->thread, takion_thread_func, takion);
chiaki_thread_set_name(&takion->thread, "Chiaki Takion");
return CHIAKI_ERR_SUCCESS;
error_sock:
if(!CHIAKI_SOCKET_IS_INVALID(takion->sock))
{
CHIAKI_SOCKET_CLOSE(takion->sock);
takion->sock = CHIAKI_INVALID_SOCKET;
}
error_pipe:
chiaki_stop_pipe_fini(&takion->stop_pipe);
error_seq_num_local_mutex:
chiaki_mutex_fini(&takion->seq_num_local_mutex);
error_gkcrypt_local_mutex:
chiaki_mutex_fini(&takion->gkcrypt_local_mutex);
return ret;
}
CHIAKI_EXPORT void chiaki_takion_close(ChiakiTakion *takion)
{
chiaki_stop_pipe_stop(&takion->stop_pipe);
chiaki_thread_join(&takion->thread, NULL);
chiaki_stop_pipe_fini(&takion->stop_pipe);
chiaki_mutex_fini(&takion->seq_num_local_mutex);
chiaki_mutex_fini(&takion->gkcrypt_local_mutex);
}
CHIAKI_EXPORT ChiakiErrorCode chiaki_takion_crypt_advance_key_pos(ChiakiTakion *takion, size_t data_size, uint64_t *key_pos)
{
data_size += data_size % CHIAKI_GKCRYPT_BLOCK_SIZE;
ChiakiErrorCode err = chiaki_mutex_lock(&takion->gkcrypt_local_mutex);
if(err != CHIAKI_ERR_SUCCESS)
return err;
if(takion->gkcrypt_local)
{
uint64_t cur = takion->key_pos_local;
if(SIZE_MAX - cur < data_size)
{
chiaki_mutex_unlock(&takion->gkcrypt_local_mutex);
return CHIAKI_ERR_OVERFLOW;
}
*key_pos = cur;
takion->key_pos_local = cur + data_size;
}
else
*key_pos = 0;
chiaki_mutex_unlock(&takion->gkcrypt_local_mutex);
return CHIAKI_ERR_SUCCESS;
}
CHIAKI_EXPORT ChiakiErrorCode chiaki_takion_send_raw(ChiakiTakion *takion, const uint8_t *buf, size_t buf_size)
{
int r = send(takion->sock, buf, buf_size, 0);
if(r < 0)
{
CHIAKI_LOGE(takion->log, "Takion failed to send raw: " CHIAKI_SOCKET_ERROR_FMT, CHIAKI_SOCKET_ERROR_VALUE);
return CHIAKI_ERR_NETWORK;
}
return CHIAKI_ERR_SUCCESS;
}
static ChiakiErrorCode chiaki_takion_packet_read_key_pos(ChiakiTakion *takion, uint8_t *buf, size_t buf_size, uint64_t *key_pos_out)
{
if(buf_size < 1)
return CHIAKI_ERR_BUF_TOO_SMALL;
TakionPacketType base_type = buf[0] & TAKION_PACKET_BASE_TYPE_MASK;
int key_pos_offset = takion_packet_type_key_pos_offset(base_type);
if(key_pos_offset < 0)
return CHIAKI_ERR_INVALID_DATA;
if(buf_size < key_pos_offset + sizeof(uint32_t))
return CHIAKI_ERR_BUF_TOO_SMALL;
uint32_t key_pos_low = ntohl(*((chiaki_unaligned_uint32_t *)(buf + key_pos_offset)));
*key_pos_out = chiaki_key_state_request_pos(&takion->key_state, key_pos_low, false);
return CHIAKI_ERR_SUCCESS;
}
CHIAKI_EXPORT ChiakiErrorCode chiaki_takion_packet_mac(ChiakiGKCrypt *crypt, uint8_t *buf, size_t buf_size, uint64_t key_pos, uint8_t *mac_out, uint8_t *mac_old_out)
{
if(buf_size < 1)
return CHIAKI_ERR_BUF_TOO_SMALL;
TakionPacketType base_type = buf[0] & TAKION_PACKET_BASE_TYPE_MASK;
int mac_offset = takion_packet_type_mac_offset(base_type);
int key_pos_offset = takion_packet_type_key_pos_offset(base_type);
if(mac_offset < 0 || key_pos_offset < 0)
return CHIAKI_ERR_INVALID_DATA;
if(buf_size < mac_offset + CHIAKI_GKCRYPT_GMAC_SIZE || buf_size < key_pos_offset + sizeof(uint32_t))
return CHIAKI_ERR_BUF_TOO_SMALL;
if(mac_old_out)
memcpy(mac_old_out, buf + mac_offset, CHIAKI_GKCRYPT_GMAC_SIZE);
memset(buf + mac_offset, 0, CHIAKI_GKCRYPT_GMAC_SIZE);
if(crypt)
{
uint8_t key_pos_tmp[sizeof(uint32_t)];
if(base_type == TAKION_PACKET_TYPE_CONTROL || base_type == TAKION_PACKET_TYPE_CONGESTION)
{
memcpy(key_pos_tmp, buf + key_pos_offset, sizeof(uint32_t));
memset(buf + key_pos_offset, 0, sizeof(uint32_t));
}
ChiakiErrorCode err = chiaki_gkcrypt_gmac(crypt, key_pos, buf, buf_size, buf + mac_offset);
if(err != CHIAKI_ERR_SUCCESS)
return err;
if(base_type == TAKION_PACKET_TYPE_CONTROL || base_type == TAKION_PACKET_TYPE_CONGESTION)
memcpy(buf + key_pos_offset, key_pos_tmp, sizeof(uint32_t));
}
if(mac_out)
memcpy(mac_out, buf + mac_offset, CHIAKI_GKCRYPT_GMAC_SIZE);
return CHIAKI_ERR_SUCCESS;
}
CHIAKI_EXPORT ChiakiErrorCode chiaki_takion_send(ChiakiTakion *takion, uint8_t *buf, size_t buf_size, uint64_t key_pos)
{
ChiakiErrorCode err = chiaki_mutex_lock(&takion->gkcrypt_local_mutex);
if(err != CHIAKI_ERR_SUCCESS)
return err;
uint8_t mac[CHIAKI_GKCRYPT_GMAC_SIZE];
err = chiaki_takion_packet_mac(takion->gkcrypt_local, buf, buf_size, key_pos, mac, NULL);
chiaki_mutex_unlock(&takion->gkcrypt_local_mutex);
if(err != CHIAKI_ERR_SUCCESS)
return err;
//CHIAKI_LOGD(takion->log, "Takion sending:");
//chiaki_log_hexdump(takion->log, CHIAKI_LOG_DEBUG, buf, buf_size);
return chiaki_takion_send_raw(takion, buf, buf_size);
}
CHIAKI_EXPORT ChiakiErrorCode chiaki_takion_send_message_data(ChiakiTakion *takion, uint8_t chunk_flags, uint16_t channel, uint8_t *buf, size_t buf_size, ChiakiSeqNum32 *seq_num)
{
// TODO: can we make this more memory-efficient?
// TODO: split packet if necessary?
uint64_t key_pos;
ChiakiErrorCode err = chiaki_takion_crypt_advance_key_pos(takion, buf_size, &key_pos);
if(err != CHIAKI_ERR_SUCCESS)
return err;
size_t packet_size = 1 + TAKION_MESSAGE_HEADER_SIZE + 9 + buf_size;
uint8_t *packet_buf = malloc(packet_size);
if(!packet_buf)
return CHIAKI_ERR_MEMORY;
packet_buf[0] = TAKION_PACKET_TYPE_CONTROL;
takion_write_message_header(packet_buf + 1, takion->tag_remote, key_pos, TAKION_CHUNK_TYPE_DATA, chunk_flags, 9 + buf_size);
uint8_t *msg_payload = packet_buf + 1 + TAKION_MESSAGE_HEADER_SIZE;
err = chiaki_mutex_lock(&takion->seq_num_local_mutex);
if(err != CHIAKI_ERR_SUCCESS)
return err;
ChiakiSeqNum32 seq_num_val = takion->seq_num_local++;
chiaki_mutex_unlock(&takion->seq_num_local_mutex);
*((chiaki_unaligned_uint32_t *)(msg_payload + 0)) = htonl(seq_num_val);
*((chiaki_unaligned_uint16_t *)(msg_payload + 4)) = htons(channel);
*((chiaki_unaligned_uint16_t *)(msg_payload + 6)) = 0;
*(msg_payload + 8) = 0;
memcpy(msg_payload + 9, buf, buf_size);
err = chiaki_takion_send(takion, packet_buf, packet_size, key_pos); // will alter packet_buf with gmac
if(err != CHIAKI_ERR_SUCCESS)
{
CHIAKI_LOGE(takion->log, "Takion failed to send data packet: %s", chiaki_error_string(err));
free(packet_buf);
return err;
}
chiaki_takion_send_buffer_push(&takion->send_buffer, seq_num_val, packet_buf, packet_size);
if(seq_num)
*seq_num = seq_num_val;
return err;
}
CHIAKI_EXPORT ChiakiErrorCode chiaki_takion_send_message_data_cont(ChiakiTakion *takion, uint8_t chunk_flags, uint16_t channel, uint8_t *buf, size_t buf_size, ChiakiSeqNum32 *seq_num)
{
// TODO: can we make this more memory-efficient?
// TODO: split packet if necessary?
uint64_t key_pos;
ChiakiErrorCode err = chiaki_takion_crypt_advance_key_pos(takion, buf_size, &key_pos);
if(err != CHIAKI_ERR_SUCCESS)
return err;
size_t packet_size = 1 + TAKION_MESSAGE_HEADER_SIZE + 8 + buf_size;
uint8_t *packet_buf = malloc(packet_size);
if(!packet_buf)
return CHIAKI_ERR_MEMORY;
packet_buf[0] = TAKION_PACKET_TYPE_CONTROL;
takion_write_message_header(packet_buf + 1, takion->tag_remote, key_pos, TAKION_CHUNK_TYPE_DATA, chunk_flags, 8 + buf_size);
uint8_t *msg_payload = packet_buf + 1 + TAKION_MESSAGE_HEADER_SIZE;
err = chiaki_mutex_lock(&takion->seq_num_local_mutex);
if(err != CHIAKI_ERR_SUCCESS)
return err;
ChiakiSeqNum32 seq_num_val = takion->seq_num_local++;
chiaki_mutex_unlock(&takion->seq_num_local_mutex);
*((chiaki_unaligned_uint32_t *)(msg_payload + 0)) = htonl(seq_num_val);
*((chiaki_unaligned_uint16_t *)(msg_payload + 4)) = htons(channel);
*((chiaki_unaligned_uint16_t *)(msg_payload + 6)) = 0;
memcpy(msg_payload + 8, buf, buf_size);
err = chiaki_takion_send(takion, packet_buf, packet_size, key_pos); // will alter packet_buf with gmac
if(err != CHIAKI_ERR_SUCCESS)
{
CHIAKI_LOGE(takion->log, "Takion failed to send data packet: %s", chiaki_error_string(err));
free(packet_buf);
return err;
}
chiaki_takion_send_buffer_push(&takion->send_buffer, seq_num_val, packet_buf, packet_size);
if(seq_num)
*seq_num = seq_num_val;
return err;
}
static ChiakiErrorCode chiaki_takion_send_message_data_ack(ChiakiTakion *takion, uint32_t seq_num)
{
uint8_t buf[1 + TAKION_MESSAGE_HEADER_SIZE + 0xc];
buf[0] = TAKION_PACKET_TYPE_CONTROL;
uint64_t key_pos;
ChiakiErrorCode err = chiaki_takion_crypt_advance_key_pos(takion, sizeof(buf), &key_pos);
if(err != CHIAKI_ERR_SUCCESS)
return err;
takion_write_message_header(buf + 1, takion->tag_remote, key_pos, TAKION_CHUNK_TYPE_DATA_ACK, 0, 0xc);
uint8_t *data_ack = buf + 1 + TAKION_MESSAGE_HEADER_SIZE;
*((chiaki_unaligned_uint32_t *)(data_ack + 0)) = htonl(seq_num);
*((chiaki_unaligned_uint32_t *)(data_ack + 4)) = htonl(takion->a_rwnd);
*((chiaki_unaligned_uint16_t *)(data_ack + 8)) = 0;
*((chiaki_unaligned_uint16_t *)(data_ack + 0xa)) = 0;
return chiaki_takion_send(takion, buf, sizeof(buf), key_pos);
}
CHIAKI_EXPORT void chiaki_takion_format_congestion(uint8_t *buf, ChiakiTakionCongestionPacket *packet, uint64_t key_pos)
{
buf[0] = TAKION_PACKET_TYPE_CONGESTION;
*((chiaki_unaligned_uint16_t *)(buf + 1)) = htons(packet->word_0);
*((chiaki_unaligned_uint16_t *)(buf + 3)) = htons(packet->received);
*((chiaki_unaligned_uint16_t *)(buf + 5)) = htons(packet->lost);
*((chiaki_unaligned_uint32_t *)(buf + 7)) = 0;
*((chiaki_unaligned_uint32_t *)(buf + 0xb)) = htonl((uint32_t)key_pos);
}
CHIAKI_EXPORT ChiakiErrorCode chiaki_takion_send_congestion(ChiakiTakion *takion, ChiakiTakionCongestionPacket *packet)
{
uint64_t key_pos;
ChiakiErrorCode err = chiaki_takion_crypt_advance_key_pos(takion, CHIAKI_TAKION_CONGESTION_PACKET_SIZE, &key_pos);
if(err != CHIAKI_ERR_SUCCESS)
return err;
uint8_t buf[CHIAKI_TAKION_CONGESTION_PACKET_SIZE];
chiaki_takion_format_congestion(buf, packet, key_pos);
return chiaki_takion_send(takion, buf, sizeof(buf), key_pos);
}
static ChiakiErrorCode takion_send_feedback_packet(ChiakiTakion *takion, uint8_t *buf, size_t buf_size)
{
assert(buf_size >= 0xc);
size_t payload_size = buf_size - 0xc;
ChiakiErrorCode err = chiaki_mutex_lock(&takion->gkcrypt_local_mutex);
if(err != CHIAKI_ERR_SUCCESS)
return err;
uint64_t key_pos;
err = chiaki_takion_crypt_advance_key_pos(takion, payload_size + CHIAKI_GKCRYPT_BLOCK_SIZE, &key_pos);
if(err != CHIAKI_ERR_SUCCESS)
goto beach;
err = chiaki_gkcrypt_encrypt(takion->gkcrypt_local, key_pos + CHIAKI_GKCRYPT_BLOCK_SIZE, buf + 0xc, payload_size);
if(err != CHIAKI_ERR_SUCCESS)
goto beach;
*((chiaki_unaligned_uint32_t *)(buf + 4)) = htonl((uint32_t)key_pos);
err = chiaki_gkcrypt_gmac(takion->gkcrypt_local, key_pos, buf, buf_size, buf + 8);
if(err != CHIAKI_ERR_SUCCESS)
goto beach;
chiaki_takion_send_raw(takion, buf, buf_size);
beach:
chiaki_mutex_unlock(&takion->gkcrypt_local_mutex);
return err;
}
CHIAKI_EXPORT ChiakiErrorCode chiaki_takion_send_feedback_state(ChiakiTakion *takion, ChiakiSeqNum16 seq_num, ChiakiFeedbackState *feedback_state)
{
uint8_t buf[0xc + CHIAKI_FEEDBACK_STATE_BUF_SIZE_MAX];
buf[0] = TAKION_PACKET_TYPE_FEEDBACK_STATE;
*((chiaki_unaligned_uint16_t *)(buf + 1)) = htons(seq_num);
buf[3] = 0; // TODO
*((chiaki_unaligned_uint32_t *)(buf + 4)) = 0; // key pos
*((chiaki_unaligned_uint32_t *)(buf + 8)) = 0; // gmac
size_t buf_sz;
if(takion->version <= 9)
{
buf_sz = 0xc + CHIAKI_FEEDBACK_STATE_BUF_SIZE_V9;
chiaki_feedback_state_format_v9(buf + 0xc, feedback_state);
}
else
{
buf_sz = 0xc + CHIAKI_FEEDBACK_STATE_BUF_SIZE_V12;
chiaki_feedback_state_format_v12(buf + 0xc, feedback_state);
}
return takion_send_feedback_packet(takion, buf, buf_sz);
}
CHIAKI_EXPORT ChiakiErrorCode chiaki_takion_send_mic_packet(ChiakiTakion *takion, uint8_t *buf, size_t buf_size, bool ps5)
{
uint8_t ps5_packet = 0;
if(ps5)
ps5_packet = 1;
size_t payload_size = buf_size - 19 - ps5_packet;
ChiakiErrorCode err = chiaki_mutex_lock(&takion->gkcrypt_local_mutex);
if(err != CHIAKI_ERR_SUCCESS)
return err;
uint64_t key_pos;
err = chiaki_takion_crypt_advance_key_pos(takion, payload_size + CHIAKI_GKCRYPT_BLOCK_SIZE, &key_pos);
if(err != CHIAKI_ERR_SUCCESS)
goto beach;
err = chiaki_gkcrypt_encrypt(takion->gkcrypt_local, key_pos + CHIAKI_GKCRYPT_BLOCK_SIZE, buf + 19 + ps5_packet, payload_size);
if(err != CHIAKI_ERR_SUCCESS)
goto beach;
*((chiaki_unaligned_uint32_t *)(buf + 14)) = htonl((uint32_t)key_pos);
err = chiaki_gkcrypt_gmac(takion->gkcrypt_local, key_pos, buf, buf_size, buf + 10);
if(err != CHIAKI_ERR_SUCCESS)
goto beach;
chiaki_takion_send_raw(takion, buf, buf_size);
beach:
chiaki_mutex_unlock(&takion->gkcrypt_local_mutex);
return err;
}
CHIAKI_EXPORT ChiakiErrorCode chiaki_takion_send_feedback_history(ChiakiTakion *takion, ChiakiSeqNum16 seq_num, uint8_t *payload, size_t payload_size)
{
size_t buf_size = 0xc + payload_size;
uint8_t *buf = malloc(buf_size);
if(!buf)
return CHIAKI_ERR_MEMORY;
buf[0] = TAKION_PACKET_TYPE_FEEDBACK_HISTORY;
*((chiaki_unaligned_uint16_t *)(buf + 1)) = htons(seq_num);
buf[3] = 0; // TODO
*((chiaki_unaligned_uint32_t *)(buf + 4)) = 0; // key pos
*((chiaki_unaligned_uint32_t *)(buf + 8)) = 0; // gmac
memcpy(buf + 0xc, payload, payload_size);
ChiakiErrorCode err = takion_send_feedback_packet(takion, buf, buf_size);
free(buf);
return err;
}
static ChiakiErrorCode takion_handshake(ChiakiTakion *takion, uint32_t *seq_num_remote_initial)
{
ChiakiErrorCode err;
// INIT ->
TakionMessagePayloadInit init_payload;
init_payload.tag = takion->tag_local;
init_payload.a_rwnd = TAKION_A_RWND;
init_payload.outbound_streams = TAKION_OUTBOUND_STREAMS;
init_payload.inbound_streams = TAKION_INBOUND_STREAMS;
init_payload.initial_seq_num = takion->seq_num_local;
err = takion_send_message_init(takion, &init_payload);
if(err != CHIAKI_ERR_SUCCESS)
{
CHIAKI_LOGE(takion->log, "Takion failed to send init");
return err;
}
CHIAKI_LOGI(takion->log, "Takion sent init");
// INIT_ACK <-
TakionMessagePayloadInitAck init_ack_payload;
err = takion_recv_message_init_ack(takion, &init_ack_payload);
if(err != CHIAKI_ERR_SUCCESS)
{
CHIAKI_LOGE(takion->log, "Takion failed to receive init ack");
return err;
}
if(init_ack_payload.tag == 0)
{
CHIAKI_LOGE(takion->log, "Takion remote tag in init ack is 0");
return CHIAKI_ERR_INVALID_RESPONSE;
}
CHIAKI_LOGI(takion->log, "Takion received init ack with remote tag %#x, outbound streams: %#x, inbound streams: %#x",
init_ack_payload.tag, init_ack_payload.outbound_streams, init_ack_payload.inbound_streams);
takion->tag_remote = init_ack_payload.tag;
*seq_num_remote_initial = takion->tag_remote; //init_ack_payload.initial_seq_num;
if(init_ack_payload.outbound_streams == 0 || init_ack_payload.inbound_streams == 0 || init_ack_payload.outbound_streams > TAKION_INBOUND_STREAMS || init_ack_payload.inbound_streams < TAKION_OUTBOUND_STREAMS)
{
CHIAKI_LOGE(takion->log, "Takion min/max check failed");
return CHIAKI_ERR_INVALID_RESPONSE;
}
// COOKIE ->
err = takion_send_message_cookie(takion, init_ack_payload.cookie);
if(err != CHIAKI_ERR_SUCCESS)
{
CHIAKI_LOGE(takion->log, "Takion failed to send cookie");
return err;
}
CHIAKI_LOGI(takion->log, "Takion sent cookie");
// COOKIE_ACK <-
err = takion_recv_message_cookie_ack(takion);
if(err != CHIAKI_ERR_SUCCESS)
{
CHIAKI_LOGE(takion->log, "Takion failed to receive cookie ack");
return err;
}
CHIAKI_LOGI(takion->log, "Takion received cookie ack");
// done!
CHIAKI_LOGI(takion->log, "Takion connected");
return CHIAKI_ERR_SUCCESS;
}
static void takion_data_drop(uint64_t seq_num, void *elem_user, void *cb_user)
{
ChiakiTakion *takion = cb_user;
CHIAKI_LOGE(takion->log, "Takion dropping data with seq num %#llx", (unsigned long long)seq_num);
TakionDataPacketEntry *entry = elem_user;
free(entry->packet_buf);
free(entry);
}
static void *takion_thread_func(void *user)
{
ChiakiTakion *takion = user;
uint32_t seq_num_remote_initial;
if(takion_handshake(takion, &seq_num_remote_initial) != CHIAKI_ERR_SUCCESS)
goto beach;
if(chiaki_reorder_queue_init_32(&takion->data_queue, TAKION_REORDER_QUEUE_SIZE_EXP, seq_num_remote_initial) != CHIAKI_ERR_SUCCESS)
goto beach;
chiaki_reorder_queue_set_drop_cb(&takion->data_queue, takion_data_drop, takion);
// The send buffer size MUST be consistent with the acked seqnums array size in takion_handle_packet_message_data_ack()
if(chiaki_takion_send_buffer_init(&takion->send_buffer, takion, TAKION_SEND_BUFFER_SIZE) != CHIAKI_ERR_SUCCESS)
goto error_reoder_queue;
if(takion->cb)
{
ChiakiTakionEvent event = { 0 };
event.type = CHIAKI_TAKION_EVENT_TYPE_CONNECTED;
takion->cb(&event, takion->cb_user);
}
bool crypt_available = takion->gkcrypt_remote ? true : false;
while(true)
{
if(takion->enable_crypt && !crypt_available && takion->gkcrypt_remote)
{
crypt_available = true;
CHIAKI_LOGI(takion->log, "Crypt has become available. Re-checking MACs of %llu packets", (unsigned long long)chiaki_reorder_queue_count(&takion->data_queue));
for(uint64_t i=0; i<chiaki_reorder_queue_count(&takion->data_queue); i++)
{
TakionDataPacketEntry *packet;
bool peeked = chiaki_reorder_queue_peek(&takion->data_queue, i, NULL, (void **)&packet);
if(!peeked)
continue;
if(packet->packet_size == 0)
continue;
uint8_t base_type = (uint8_t)(packet->packet_buf[0] & TAKION_PACKET_BASE_TYPE_MASK);
if(takion_handle_packet_mac(takion, base_type, packet->packet_buf, packet->packet_size) != CHIAKI_ERR_SUCCESS)
{
CHIAKI_LOGW(takion->log, "Found an invalid MAC");
chiaki_reorder_queue_drop(&takion->data_queue, i);
}
}
}
if(takion->postponed_packets && takion->gkcrypt_remote)
{
// there are some postponed packets that were waiting until crypt is initialized and it is now :-)
CHIAKI_LOGI(takion->log, "Takion flushing %llu postpone packet(s)", (unsigned long long)takion->postponed_packets_count);
for(size_t i=0; i<takion->postponed_packets_count; i++)
{
ChiakiTakionPostponedPacket *packet = &takion->postponed_packets[i];
takion_handle_packet(takion, packet->buf, packet->buf_size);
}
free(takion->postponed_packets);
takion->postponed_packets = NULL;
takion->postponed_packets_size = 0;
takion->postponed_packets_count = 0;
}
size_t received_size = 1500;
uint8_t *buf = malloc(received_size); // TODO: no malloc?
if(!buf)
break;
ChiakiErrorCode err = takion_recv(takion, buf, &received_size, UINT64_MAX);
if(err != CHIAKI_ERR_SUCCESS)
{
free(buf);
break;
}
uint8_t *resized_buf = realloc(buf, received_size);
if(!resized_buf)
{
free(buf);
continue;
}
takion_handle_packet(takion, resized_buf, received_size);
}
chiaki_takion_send_buffer_fini(&takion->send_buffer);
error_reoder_queue:
chiaki_reorder_queue_fini(&takion->data_queue);
beach:
if(takion->cb)
{
ChiakiTakionEvent event = { 0 };
event.type = CHIAKI_TAKION_EVENT_TYPE_DISCONNECT;
takion->cb(&event, takion->cb_user);
}
if(takion->close_socket)
{
if(!CHIAKI_SOCKET_IS_INVALID(takion->sock))
{
CHIAKI_SOCKET_CLOSE(takion->sock);
takion->sock = CHIAKI_INVALID_SOCKET;
}
}
return NULL;
}
static ChiakiErrorCode takion_recv(ChiakiTakion *takion, uint8_t *buf, size_t *buf_size, uint64_t timeout_ms)
{
ChiakiErrorCode err = chiaki_stop_pipe_select_single(&takion->stop_pipe, takion->sock, false, timeout_ms);
if(err == CHIAKI_ERR_TIMEOUT || err == CHIAKI_ERR_CANCELED)
return err;
if(err != CHIAKI_ERR_SUCCESS)
{
CHIAKI_LOGE(takion->log, "Takion select failed: " CHIAKI_SOCKET_ERROR_FMT, CHIAKI_SOCKET_ERROR_VALUE);
return err;
}
CHIAKI_SSIZET_TYPE received_sz = recv(takion->sock, buf, *buf_size, 0);
if(received_sz <= 0)
{
if(received_sz < 0)
CHIAKI_LOGE(takion->log, "Takion recv failed: " CHIAKI_SOCKET_ERROR_FMT, CHIAKI_SOCKET_ERROR_VALUE);
else
CHIAKI_LOGE(takion->log, "Takion recv returned 0");
return CHIAKI_ERR_NETWORK;
}
*buf_size = (size_t)received_sz;
return CHIAKI_ERR_SUCCESS;