libjuice-sys 0.9.7

Native bindings for libjuice
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
/**
 * Copyright (c) 2020 Paul-Louis Ageneau
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "stun.h"
#include "base64.h"
#include "const_time.h"
#include "crc32.h"
#include "juice.h"
#include "log.h"
#include "udp.h"

#include <assert.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define STUN_MAGIC 0x2112A442
#define STUN_FINGERPRINT_XOR 0x5354554E // "STUN"
#define STUN_ATTR_SIZE sizeof(struct stun_attr)

// STUN_MAX_PASSWORD_LEN > HASH_SHA256_SIZE > HASH_MD5_SIZE
#define MAX_HMAC_KEY_LEN STUN_MAX_PASSWORD_LEN

#define MAX_HMAC_INPUT_LEN (STUN_MAX_USERNAME_LEN + STUN_MAX_REALM_LEN + STUN_MAX_PASSWORD_LEN + 2)

#define MAX_USERHASH_INPUT_LEN (STUN_MAX_USERNAME_LEN + STUN_MAX_REALM_LEN + 1)

#ifndef htonll
#define htonll(x)                                                                                  \
	((uint64_t)(((uint64_t)htonl((uint32_t)(x))) << 32) | (uint64_t)htonl((uint32_t)((x) >> 32)))
#endif
#ifndef ntohll
#define ntohll(x) htonll(x)
#endif

static size_t align32(size_t len) {
	while (len & 0x03)
		++len;
	return len;
}

static size_t generate_hmac_key(const stun_message_t *msg, const char *password, void *key) {
	if (*msg->credentials.realm != '\0') {
		// long-term credentials
		if (*msg->credentials.username == '\0')
			JLOG_WARN("Generating HMAC key for long-term credentials with empty STUN username");

		char input[MAX_HMAC_INPUT_LEN];
		int input_len = snprintf(input, MAX_HMAC_INPUT_LEN, "%s:%s:%s", msg->credentials.username,
		                         msg->credentials.realm, password ? password : "");
		if (input_len < 0)
			return 0;

		if (input_len >= MAX_HMAC_INPUT_LEN)
			input_len = MAX_HMAC_INPUT_LEN - 1;

		switch (msg->credentials.password_algorithm) {
		case STUN_PASSWORD_ALGORITHM_SHA256:
			hash_sha256(input, input_len, key);
			return HASH_SHA256_SIZE;
		default:
			hash_md5(input, input_len, key);
			return HASH_MD5_SIZE;
		}
	} else {
		// short-term credentials
		int key_len = snprintf((char *)key, MAX_HMAC_KEY_LEN, "%s", password ? password : "");
		if (key_len < 0)
			return 0;

		if (key_len >= MAX_HMAC_KEY_LEN)
			key_len = MAX_HMAC_KEY_LEN - 1;

		return key_len;
	}
}

static size_t generate_password_algorithms_attr(uint8_t *attr) {
	// attr size must be at least STUN_PASSWORD_ALGORITHMS_ATTR_MAX_SIZE
	struct stun_value_password_algorithm *pwa = (struct stun_value_password_algorithm *)attr;
	pwa->algorithm = htons(STUN_PASSWORD_ALGORITHM_SHA256);
	pwa->parameters_length = 0;
	++pwa;
	pwa->algorithm = htons(STUN_PASSWORD_ALGORITHM_MD5);
	pwa->parameters_length = 0;
	++pwa;
	return (uint8_t *)pwa - attr;
}

int stun_write(void *buf, size_t size, const stun_message_t *msg, const char *password) {
	uint8_t *begin = buf;
	uint8_t *pos = begin;
	uint8_t *end = begin + size;

	JLOG_VERBOSE("Writing STUN message, class=0x%X, method=0x%X", (unsigned int)msg->msg_class,
	             (unsigned int)msg->msg_method);

	size_t len =
	    stun_write_header(pos, end - pos, msg->msg_class, msg->msg_method, msg->transaction_id);
	if (len <= 0)
		goto overflow;
	pos += len;
	uint8_t *attr_begin = pos;

	if (msg->error_code) {
		const char *reason = stun_get_error_reason(msg->error_code);
		char buffer[sizeof(struct stun_value_error_code) + STUN_MAX_ERROR_REASON_LEN + 1];
		struct stun_value_error_code *error = (struct stun_value_error_code *)buffer;
		memset(error, 0, sizeof(*error));
		error->code_class = (msg->error_code / 100) & 0x07;
		error->code_number = msg->error_code % 100;
		strcpy((char *)error->reason, reason);
		len = stun_write_attr(pos, end - pos, STUN_ATTR_ERROR_CODE, error,
		                      sizeof(struct stun_value_error_code) + strlen(reason));
		if (len <= 0)
			goto overflow;
		pos += len;
	}
	if (msg->mapped.len) {
		JLOG_VERBOSE("Writing XOR mapped address");
		uint8_t value[32];
		uint8_t mask[16];
		*((uint32_t *)mask) = htonl(STUN_MAGIC);
		memcpy(mask + 4, msg->transaction_id, 12);
		int value_len = stun_write_value_mapped_address(
		    value, 32, (const struct sockaddr *)&msg->mapped.addr, msg->mapped.len, mask);
		if (value_len > 0) {
			len = stun_write_attr(pos, end - pos, STUN_ATTR_XOR_MAPPED_ADDRESS, value, value_len);
			if (len <= 0)
				goto overflow;
			pos += len;
		}
	}
	if (msg->priority) {
		uint32_t priority = htonl(msg->priority);
		len = stun_write_attr(pos, end - pos, STUN_ATTR_PRIORITY, &priority, 4);
		if (len <= 0)
			goto overflow;
		pos += len;
	}
	if (msg->use_candidate) {
		len = stun_write_attr(pos, end - pos, STUN_ATTR_USE_CANDIDATE, NULL, 0);
		if (len <= 0)
			goto overflow;
		pos += len;
	}
	if (msg->ice_controlling) {
		uint64_t ice_controlling = htonll(msg->ice_controlling);
		len = stun_write_attr(pos, end - pos, STUN_ATTR_ICE_CONTROLLING, &ice_controlling, 8);
		if (len <= 0)
			goto overflow;
		pos += len;
	}
	if (msg->ice_controlled) {
		uint64_t ice_controlled = htonll(msg->ice_controlled);
		len = stun_write_attr(pos, end - pos, STUN_ATTR_ICE_CONTROLLED, &ice_controlled, 8);
		if (len <= 0)
			goto overflow;
		pos += len;
	}
	if (msg->channel_number) {
		struct stun_value_channel_number channel_number;
		memset(&channel_number, 0, sizeof(channel_number));
		channel_number.channel_number = htons(msg->channel_number);
		len = stun_write_attr(pos, end - pos, STUN_ATTR_CHANNEL_NUMBER, &channel_number,
		                      sizeof(channel_number));
		if (len <= 0)
			goto overflow;
		pos += len;
	}
	if (msg->lifetime_set || msg->lifetime) {
		uint32_t lifetime = htonl(msg->lifetime);
		len = stun_write_attr(pos, end - pos, STUN_ATTR_LIFETIME, &lifetime, 4);
		if (len <= 0)
			goto overflow;
		pos += len;
	}
	if (msg->peer.len) {
		JLOG_VERBOSE("Writing XOR peer address");
		uint8_t value[32];
		uint8_t mask[16];
		*((uint32_t *)mask) = htonl(STUN_MAGIC);
		memcpy(mask + 4, msg->transaction_id, 12);
		int value_len = stun_write_value_mapped_address(
		    value, 32, (const struct sockaddr *)&msg->peer.addr, msg->peer.len, mask);
		if (value_len > 0) {
			len = stun_write_attr(pos, end - pos, STUN_ATTR_XOR_PEER_ADDRESS, value, value_len);
			if (len <= 0)
				goto overflow;
			pos += len;
		}
	}
	if (msg->relayed.len) {
		JLOG_VERBOSE("Writing XOR relay address");
		uint8_t value[32];
		uint8_t mask[16];
		*((uint32_t *)mask) = htonl(STUN_MAGIC);
		memcpy(mask + 4, msg->transaction_id, 12);
		int value_len = stun_write_value_mapped_address(
		    value, 32, (const struct sockaddr *)&msg->relayed.addr, msg->relayed.len, mask);
		if (value_len > 0) {
			len = stun_write_attr(pos, end - pos, STUN_ATTR_XOR_RELAYED_ADDRESS, value, value_len);
			if (len <= 0)
				goto overflow;
			pos += len;
		}
	}
	if (msg->data) {
		len = stun_write_attr(pos, end - pos, STUN_ATTR_DATA, (const uint8_t *)msg->data,
		                      msg->data_size);
		if (len <= 0)
			goto overflow;
		pos += len;
	}
	if (msg->even_port) {
		struct stun_value_even_port even_port;
		memset(&even_port, 0, sizeof(even_port));
		if (msg->next_port)
			even_port.r |= 0x80;
		len = stun_write_attr(pos, end - pos, STUN_ATTR_CHANNEL_NUMBER, &even_port,
		                      sizeof(even_port));
		if (len <= 0)
			goto overflow;
		pos += len;
	}
	if (msg->requested_transport) {
		struct stun_value_requested_transport requested_transport;
		memset(&requested_transport, 0, sizeof(requested_transport));
		requested_transport.protocol = 17;
		len = stun_write_attr(pos, end - pos, STUN_ATTR_REQUESTED_TRANSPORT, &requested_transport,
		                      sizeof(requested_transport));
		if (len <= 0)
			goto overflow;
		pos += len;
	}
	if (msg->dont_fragment) {
		len = stun_write_attr(pos, end - pos, STUN_ATTR_DONT_FRAGMENT, NULL, 0);
		if (len <= 0)
			goto overflow;
		pos += len;
	}
	if (msg->reservation_token) {
		uint64_t reservation_token = htonll(msg->reservation_token);
		len = stun_write_attr(pos, end - pos, STUN_ATTR_RESERVATION_TOKEN, &reservation_token, 8);
		if (len <= 0)
			goto overflow;
		pos += len;
	}

	const char *software = "libjuice";
	len = stun_write_attr(pos, end - pos, STUN_ATTR_SOFTWARE, software, strlen(software));
	if (len <= 0)
		goto overflow;
	pos += len;

	if (msg->msg_class == STUN_CLASS_REQUEST) {
		if (msg->credentials.enable_userhash) {
			len = stun_write_attr(pos, end - pos, STUN_ATTR_USERHASH, msg->credentials.userhash,
			                      USERHASH_SIZE);
			if (len <= 0)
				goto overflow;
			pos += len;

		} else if (*msg->credentials.username != '\0') {
			len = stun_write_attr(pos, end - pos, STUN_ATTR_USERNAME, msg->credentials.username,
			                      strlen(msg->credentials.username));
			if (len <= 0)
				goto overflow;
			pos += len;
		}
	}
	if (msg->msg_class == STUN_CLASS_REQUEST ||
	    (msg->msg_class == STUN_CLASS_RESP_ERROR &&
	     (msg->error_code == 401 || msg->error_code == 438) // Unauthenticated or Stale Nonce
	     )) {
		if (*msg->credentials.realm != '\0') {
			len = stun_write_attr(pos, end - pos, STUN_ATTR_REALM, msg->credentials.realm,
			                      strlen(msg->credentials.realm));
			if (len <= 0)
				goto overflow;
			pos += len;
		}
		if (*msg->credentials.nonce != '\0') {
			len = stun_write_attr(pos, end - pos, STUN_ATTR_NONCE, msg->credentials.nonce,
			                      strlen(msg->credentials.nonce));
			if (len <= 0)
				goto overflow;
			pos += len;

			if (msg->credentials.password_algorithm > 0) {
				len = stun_write_attr(pos, end - pos, STUN_ATTR_PASSWORD_ALGORITHMS,
				                      msg->credentials.password_algorithms_value,
				                      msg->credentials.password_algorithms_value_size);
				if (len <= 0)
					goto overflow;
				pos += len;

			} else if (msg->msg_class != STUN_CLASS_REQUEST) {
				uint8_t pwa_value[STUN_MAX_PASSWORD_ALGORITHMS_VALUE_SIZE];
				size_t pwa_size = generate_password_algorithms_attr(pwa_value);
				len = stun_write_attr(pos, end - pos, STUN_ATTR_PASSWORD_ALGORITHMS, pwa_value,
				                      pwa_size);
				if (len <= 0)
					goto overflow;
				pos += len;
			}

			if (msg->msg_class == STUN_CLASS_REQUEST &&
			    msg->credentials.password_algorithm != STUN_PASSWORD_ALGORITHM_UNSET) {
				struct stun_value_password_algorithm pwa;
				pwa.algorithm = htons(msg->credentials.password_algorithm);
				len = stun_write_attr(pos, end - pos, STUN_ATTR_PASSWORD_ALGORITHM, &pwa,
				                      sizeof(pwa));
				if (len <= 0)
					goto overflow;
				pos += len;
			}
		}
	}
	if (msg->msg_class != STUN_CLASS_INDICATION && password) {
		uint8_t key[MAX_HMAC_KEY_LEN];
		size_t key_len = generate_hmac_key(msg, password, key);

		size_t tmp_length = pos - attr_begin + STUN_ATTR_SIZE + HMAC_SHA1_SIZE;
		stun_update_header_length(begin, tmp_length);

		uint8_t hmac[HMAC_SHA1_SIZE];
		hmac_sha1(begin, pos - begin, key, key_len, hmac);
		len = stun_write_attr(pos, end - pos, STUN_ATTR_MESSAGE_INTEGRITY, hmac, HMAC_SHA1_SIZE);
		if (len <= 0)
			goto overflow;
		pos += len;

		// According to RFC 8489, the agent must include both MESSAGE-INTEGRITY and
		// MESSAGE-INTEGRITY-SHA256. However, this makes legacy agents and servers fail with error
		// 420 Unknown Attribute. Therefore, unless the password algorithm SHA-256 is enabled, only
		// MESSAGE-INTEGRITY is included in the message for compatibility.
		if (msg->credentials.password_algorithm != STUN_PASSWORD_ALGORITHM_UNSET) {
			// If the response contains a PASSWORD-ALGORITHMS attribute, all the
			// subsequent requests MUST be authenticated using MESSAGE-INTEGRITY-
			// SHA256 only.
			size_t tmp_length = pos - attr_begin + STUN_ATTR_SIZE + HMAC_SHA256_SIZE;
			stun_update_header_length(begin, tmp_length);

			uint8_t hmac[HMAC_SHA256_SIZE];
			hmac_sha256(begin, pos - begin, key, key_len, hmac);
			len = stun_write_attr(pos, end - pos, STUN_ATTR_MESSAGE_INTEGRITY_SHA256, hmac,
			                      HMAC_SHA256_SIZE);
			if (len <= 0)
				goto overflow;
			pos += len;
		}
	}

	size_t length = pos - attr_begin + STUN_ATTR_SIZE + 4;
	if (length & 0x03) {
		JLOG_ERROR("Written STUN message length is not multiple of 4, length=%zu", length);
		return -1;
	}
	stun_update_header_length(begin, length);

	uint32_t fingerprint = htonl(CRC32(buf, pos - begin) ^ STUN_FINGERPRINT_XOR);
	len = stun_write_attr(pos, end - pos, STUN_ATTR_FINGERPRINT, &fingerprint, 4);
	if (len <= 0)
		goto overflow;
	pos += len;

	return (int)(pos - begin);

overflow:
	JLOG_ERROR("Not enough space in buffer for STUN message, size=%zu", size);
	return -1;
}

int stun_write_header(void *buf, size_t size, stun_class_t class, stun_method_t method,
                      const uint8_t *transaction_id) {
	if (size < sizeof(struct stun_header))
		return -1;

	uint16_t type = (uint16_t) class | (uint16_t)method;

	struct stun_header *header = buf;
	header->type = htons(type);
	header->length = htons(0);
	header->magic = htonl(STUN_MAGIC);
	memcpy(header->transaction_id, transaction_id, STUN_TRANSACTION_ID_SIZE);

	return sizeof(struct stun_header);
}

size_t stun_update_header_length(void *buf, size_t length) {
	struct stun_header *header = buf;
	size_t previous = ntohs(header->length);
	header->length = htons((uint16_t)length);
	return previous;
}

int stun_write_attr(void *buf, size_t size, uint16_t type, const void *value, size_t length) {
	JLOG_VERBOSE("Writing STUN attribute type 0x%X, length=%zu", (unsigned int)type, length);

	if (size < sizeof(struct stun_attr) + length)
		return -1;

	struct stun_attr *attr = buf;
	attr->type = htons(type);
	attr->length = htons((uint16_t)length);
	memcpy(attr->value, value, length);

	// Pad to align on 4 bytes
	while (length & 0x03)
		attr->value[length++] = 0;

	return (int)(sizeof(struct stun_attr) + length);
}

int stun_write_value_mapped_address(void *buf, size_t size, const struct sockaddr *addr,
                                    socklen_t addrlen, const uint8_t *mask) {
	if (size < sizeof(struct stun_value_mapped_address))
		return -1;

	struct stun_value_mapped_address *value = buf;
	value->padding = 0;
	switch (addr->sa_family) {
	case AF_INET: {
		value->family = STUN_ADDRESS_FAMILY_IPV4;
		if (size < sizeof(struct stun_value_mapped_address) + 4)
			return -1;
		if (addrlen < (socklen_t)sizeof(struct sockaddr_in))
			return -1;
		JLOG_VERBOSE("Writing IPv4 address");
		const struct sockaddr_in *sin = (const struct sockaddr_in *)addr;
		value->port = sin->sin_port ^ *((uint16_t *)mask);
		const uint8_t *bytes = (const uint8_t *)&sin->sin_addr;
		for (int i = 0; i < 4; ++i)
			value->address[i] = bytes[i] ^ mask[i];
		return sizeof(struct stun_value_mapped_address) + 4;
	}
	case AF_INET6: {
		value->family = STUN_ADDRESS_FAMILY_IPV6;
		if (size < sizeof(struct stun_value_mapped_address) + 16)
			return -1;
		if (addrlen < (socklen_t)sizeof(struct sockaddr_in6))
			return -1;
		JLOG_VERBOSE("Writing IPv6 address");
		const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)addr;
		value->port = sin6->sin6_port ^ *((uint16_t *)mask);
		const uint8_t *bytes = (const uint8_t *)&sin6->sin6_addr;
		for (int i = 0; i < 16; ++i)
			value->address[i] = bytes[i] ^ mask[i];
		return sizeof(struct stun_value_mapped_address) + 16;
	}
	default: {
		JLOG_DEBUG("Unknown address family %u", (unsigned int)addr->sa_family);
		return -1;
	}
	}
}

bool is_stun_datagram(const void *data, size_t size) {
	// RFC 8489: The most significant 2 bits of every STUN message MUST be zeroes. This can be used
	// to differentiate STUN packets from other protocols when STUN is multiplexed with other
	// protocols on the same port.
	if (!size || *((uint8_t *)data) & 0xC0) {
		JLOG_VERBOSE("Not a STUN message: first 2 bits are not zeroes");
		return false;
	}

	if (size < sizeof(struct stun_header)) {
		JLOG_VERBOSE("Not a STUN message: message too short, size=%zu", size);
		return false;
	}

	const struct stun_header *header = data;
	if (ntohl(header->magic) != STUN_MAGIC) {
		JLOG_VERBOSE("Not a STUN message: magic number invalid");
		return false;
	}

	// RFC 8489: The message length MUST contain the size of the message in bytes, not including the
	// 20-byte STUN header.  Since all STUN attributes are padded to a multiple of 4 bytes, the last
	// 2 bits of this field are always zero.  This provides another way to distinguish STUN packets
	// from packets of other protocols.
	const size_t length = ntohs(header->length);
	if (length & 0x03) {
		JLOG_VERBOSE("Not a STUN message: invalid length %zu not multiple of 4", length);
		return false;
	}
	if (size != sizeof(struct stun_header) + length) {
		JLOG_VERBOSE("Not a STUN message: invalid length %zu while expecting %zu", length,
		             size - sizeof(struct stun_header));
		return false;
	}

	return true;
}

int stun_read(void *data, size_t size, stun_message_t *msg) {
	memset(msg, 0, sizeof(*msg));

	const struct stun_header *header = data;
	const size_t length = ntohs(header->length);
	if (size < sizeof(struct stun_header) + length) {
		JLOG_ERROR("Invalid STUN message length, length=%zu, available=%zu", length,
		           size - sizeof(struct stun_header));
		return -1;
	}

	uint16_t type = ntohs(header->type);
	msg->msg_class = (stun_class_t)(type & STUN_CLASS_MASK);
	msg->msg_method = (stun_method_t)(type & ~STUN_CLASS_MASK);
	memcpy(msg->transaction_id, header->transaction_id, STUN_TRANSACTION_ID_SIZE);
	JLOG_VERBOSE("Reading STUN message, class=0x%X, method=0x%X", (unsigned int)msg->msg_class,
	             (unsigned int)msg->msg_method);

	uint32_t security_bits = 0;

	uint8_t *begin = data;
	uint8_t *attr_begin = begin + sizeof(struct stun_header);
	uint8_t *end = attr_begin + length;
	const uint8_t *pos = attr_begin;
	while (pos != end) {
		int ret = stun_read_attr(pos, end - pos, msg, begin, attr_begin, &security_bits);
		if (ret <= 0) {
			JLOG_DEBUG("Reading STUN attribute failed");
			return -1;
		}
		pos += ret;
	}

	JLOG_VERBOSE("Finished reading STUN attributes");

	stun_credentials_t *credentials = &msg->credentials;

	// RFC 8489: If the response is an error response with an error code of 401 (Unauthenticated) or
	// 438 (Stale Nonce), the client MUST test if the NONCE attribute value starts with the "nonce
	// cookie". If so and the "nonce cookie" has the STUN Security Feature "Password algorithms"
	// bit set to 1 but no PASSWORD-ALGORITHMS attribute is present, then the client MUST NOT retry
	// the request with a new transaction. See https://tools.ietf.org/html/rfc8489#section-9.2.5
	if (msg->msg_class == STUN_CLASS_RESP_ERROR &&
	    (msg->error_code == 401 || msg->error_code == 438) &&
	    security_bits & STUN_SECURITY_PASSWORD_ALGORITHMS_BIT &&
	    credentials->password_algorithms_value_size == 0) {
		JLOG_INFO("STUN Security Feature \"Password algorithms\" bit is set in %u error response "
		          "but the corresponding attribute is missing",
		          msg->error_code);
		msg->error_code = STUN_ERROR_INTERNAL_VALIDATION_FAILED; // so the agent will give up
	}

	// RFC 8489: If the request contains neither the PASSWORD-ALGORITHMS nor the
	// PASSWORD-ALGORITHM algorithm, then the request is processed as though
	// PASSWORD-ALGORITHM were MD5.
	// Otherwise, unless (1) PASSWORD-ALGORITHM and PASSWORD-ALGORITHMS are both
	// present, (2) PASSWORD-ALGORITHMS  matches the value sent in the response that sent
	// this NONCE, and (3) PASSWORD-ALGORITHM matches one of the entries in
	// PASSWORD-ALGORITHMS, the server MUST generate an error response with an error code of
	// 400 (Bad Request). See https://tools.ietf.org/html/rfc8489#section-9.2.4
	if (!STUN_IS_RESPONSE(msg->msg_class)) {
		if (credentials->password_algorithms_value_size == 0 &&
		    credentials->password_algorithm == STUN_PASSWORD_ALGORITHM_UNSET) {
			credentials->password_algorithm = STUN_PASSWORD_ALGORITHM_MD5;

		} else if (credentials->password_algorithm == STUN_PASSWORD_ALGORITHM_UNSET) {
			JLOG_INFO("No suitable password algorithm in STUN request");
			msg->error_code = STUN_ERROR_INTERNAL_VALIDATION_FAILED;

		} else if (credentials->password_algorithms_value_size == 0) {
			JLOG_INFO("Missing password algorithms list in STUN request");
			msg->error_code = STUN_ERROR_INTERNAL_VALIDATION_FAILED;

		} else {
			uint8_t pwa_value[STUN_MAX_PASSWORD_ALGORITHMS_VALUE_SIZE];
			size_t pwa_size = generate_password_algorithms_attr(pwa_value);
			if (pwa_size != credentials->password_algorithms_value_size ||
			    memcmp(credentials->password_algorithms_value, pwa_value, pwa_size) != 0) {
				JLOG_INFO("Password algorithms list is invalid in STUN request");
				msg->error_code = STUN_ERROR_INTERNAL_VALIDATION_FAILED;
			}
		}
	}

	if (security_bits & STUN_SECURITY_USERNAME_ANONYMITY_BIT) {
		JLOG_DEBUG("Remote agent supports user anonymity");
		credentials->enable_userhash = true;
	}

	return (int)(sizeof(struct stun_header) + length);
}

int stun_read_attr(const void *data, size_t size, stun_message_t *msg, uint8_t *begin,
                   uint8_t *attr_begin, uint32_t *security_bits) {
	// RFC 8489: When present, the FINGERPRINT attribute MUST be the last attribute in the
	// message and thus will appear after MESSAGE-INTEGRITY and MESSAGE-INTEGRITY-SHA256.
	if (msg->has_fingerprint) {
		JLOG_DEBUG("Invalid STUN attribute after fingerprint");
		return -1;
	}

	if (size < sizeof(struct stun_attr)) {
		JLOG_VERBOSE("STUN attribute too short");
		return -1;
	}

	const struct stun_attr *attr = data;
	size_t length = ntohs(attr->length);
	stun_attr_type_t type = (stun_attr_type_t)ntohs(attr->type);
	JLOG_VERBOSE("Reading attribute 0x%X, length=%zu", (unsigned int)type, length);
	if (size < sizeof(struct stun_attr) + length) {
		JLOG_DEBUG("STUN attribute length invalid, length=%zu, available=%zu", length,
		           size - sizeof(struct stun_attr));
		return -1;
	}

	// RFC 8489: Note that agents MUST ignore all attributes that follow MESSAGE-INTEGRITY, with
	// the exception of the MESSAGE-INTEGRITY-SHA256 and FINGERPRINT attributes.
	if (msg->has_integrity && type != STUN_ATTR_MESSAGE_INTEGRITY &&
	    type != STUN_ATTR_MESSAGE_INTEGRITY_SHA256 && type != STUN_ATTR_FINGERPRINT) {
		JLOG_DEBUG("Ignoring STUN attribute 0x%X after message integrity", (unsigned int)type);
		while (length & 0x03)
			++length; // attributes are aligned on 4 bytes
		return (int)(sizeof(struct stun_attr) + length);
	}

	switch (type) {
	case STUN_ATTR_MAPPED_ADDRESS: {
		JLOG_VERBOSE("Reading mapped address");
		uint8_t zero_mask[16] = {0};
		if (stun_read_value_mapped_address(attr->value, length, &msg->mapped, zero_mask) < 0)
			return -1;
		break;
	}
	case STUN_ATTR_XOR_MAPPED_ADDRESS: {
		JLOG_VERBOSE("Reading XOR mapped address");
		uint8_t mask[16];
		*((uint32_t *)mask) = htonl(STUN_MAGIC);
		memcpy(mask + 4, msg->transaction_id, 12);
		if (stun_read_value_mapped_address(attr->value, length, &msg->mapped, mask) < 0)
			return -1;
		break;
	}
	case STUN_ATTR_ALTERNATE_SERVER: {
		JLOG_VERBOSE("Reading alternate server");
		uint8_t zero_mask[16] = {0};
		if (stun_read_value_mapped_address(attr->value, length, &msg->alternate_server, zero_mask) < 0)
			return -1;
		break;
	}
	case STUN_ATTR_ERROR_CODE: {
		JLOG_VERBOSE("Reading error code");
		if (length < sizeof(struct stun_value_error_code)) {
			JLOG_DEBUG("STUN error code value too short, length=%zu", length);
			return -1;
		}
		const struct stun_value_error_code *error =
		    (const struct stun_value_error_code *)attr->value;
		msg->error_code = (error->code_class & 0x07) * 100 + error->code_number;

		if (msg->error_code == 401 || msg->error_code == 438) { // Unauthenticated or Stale Nonce
			JLOG_DEBUG("Got STUN error code %u", msg->error_code);

		} else if (JLOG_INFO_ENABLED) {
			size_t reason_length = length - sizeof(struct stun_value_error_code);
			if (reason_length >= STUN_MAX_ERROR_REASON_LEN)
				reason_length = STUN_MAX_ERROR_REASON_LEN - 1;

			char buffer[STUN_MAX_ERROR_REASON_LEN];
			memcpy(buffer, (const char *)error->reason, reason_length);
			buffer[reason_length] = '\0';

			JLOG_INFO("Got STUN error code %u, reason \"%s\"", msg->error_code, buffer);
		}
		break;
	}
	case STUN_ATTR_UNKNOWN_ATTRIBUTES: {
		JLOG_VERBOSE("Reading STUN unknown attributes");
		const uint16_t *attributes = (const uint16_t *)attr->value;
		for (int i = 0; i < (int)ntohs(attr->length) / 2; ++i) {
			stun_attr_type_t type = (stun_attr_type_t)ntohs(attributes[i]);
			JLOG_INFO("Got unknown attribute response for attribute 0x%X", (unsigned int)type);
		}
		break;
	}
	case STUN_ATTR_USERNAME: {
		JLOG_VERBOSE("Reading username");
		if (length + 1 > STUN_MAX_USERNAME_LEN) {
			JLOG_WARN("STUN username attribute value too long, length=%zu", length);
			return -1;
		}
		memcpy(msg->credentials.username, (const char *)attr->value, length);
		msg->credentials.username[length] = '\0';
		JLOG_VERBOSE("Got username: %s", msg->credentials.username);
		break;
	}
	case STUN_ATTR_MESSAGE_INTEGRITY: {
		JLOG_VERBOSE("Reading message integrity");
		if (length != HMAC_SHA1_SIZE) {
			JLOG_DEBUG("STUN message integrity length invalid, length=%zu", length);
			return -1;
		}
		msg->has_integrity = true;
		break;
	}
	case STUN_ATTR_MESSAGE_INTEGRITY_SHA256: {
		JLOG_VERBOSE("Reading message integrity SHA256");
		if (length != HMAC_SHA256_SIZE) {
			JLOG_DEBUG("STUN message integrity SHA256 length invalid, length=%zu", length);
			return -1;
		}
		msg->has_integrity = true;
		break;
	}
	case STUN_ATTR_FINGERPRINT: {
		JLOG_VERBOSE("Reading fingerprint");
		if (length != 4) {
			JLOG_DEBUG("STUN fingerprint length invalid, length=%zu", length);
			return -1;
		}
		size_t tmp_length = (uint8_t *)data - attr_begin + STUN_ATTR_SIZE + 4;
		size_t prev_length = stun_update_header_length(begin, tmp_length);
		uint32_t expected = CRC32(begin, (uint8_t *)data - begin) ^ STUN_FINGERPRINT_XOR;
		stun_update_header_length(begin, prev_length);

		uint32_t fingerprint = ntohl(*((uint32_t *)attr->value));
		if (fingerprint != expected) {
			JLOG_ERROR("STUN fingerprint check failed, expected=%lX, actual=%lX",
			           (unsigned long)expected, (unsigned long)fingerprint);
			return -1;
		}
		JLOG_VERBOSE("STUN fingerprint check succeeded");
		msg->has_fingerprint = true;
		break;
	}
	case STUN_ATTR_REALM: {
		JLOG_VERBOSE("Reading realm");
		if (length + 1 > STUN_MAX_REALM_LEN) {
			JLOG_WARN("STUN realm attribute value too long, length=%zu", length);
			return -1;
		}
		memcpy(msg->credentials.realm, (const char *)attr->value, length);
		msg->credentials.realm[length] = '\0';
		JLOG_VERBOSE("Got realm: %s", msg->credentials.realm);
		break;
	}
	case STUN_ATTR_NONCE: {
		JLOG_VERBOSE("Reading nonce");
		if (length + 1 > STUN_MAX_NONCE_LEN) {
			JLOG_WARN("STUN nonce attribute value too long, length=%zu", length);
			return -1;
		}
		memcpy(msg->credentials.nonce, (const char *)attr->value, length);
		msg->credentials.nonce[length] = '\0';
		JLOG_VERBOSE("Got nonce: %s", msg->credentials.nonce);

		// If the nonce of a response starts with the nonce cookie, decode the Security Feature bits
		// See https://tools.ietf.org/html/rfc8489#section-9.2
		if (STUN_IS_RESPONSE(msg->msg_class) &&
		    strlen(msg->credentials.nonce) > STUN_NONCE_COOKIE_LEN + 4 &&
		    strncmp(msg->credentials.nonce, STUN_NONCE_COOKIE, STUN_NONCE_COOKIE_LEN) == 0) {
			char encoded_security_bits[5];
			memcpy(encoded_security_bits, msg->credentials.nonce + STUN_NONCE_COOKIE_LEN, 4);
			encoded_security_bits[4] = '\0';

			uint8_t bytes[4];
			bytes[0] = 0;
			int len = BASE64_DECODE(encoded_security_bits, bytes + 1, 3);
			if (len == 3) {
				*security_bits = ntohl(*((uint32_t *)bytes));
				JLOG_VERBOSE("Nonce has cookie, Security Feature bits are 0x%lX",
				             (unsigned long)*security_bits);
			} else {
				JLOG_WARN("Nonce has cookie, but the encoded Security Feature bits field \"%s\" is "
				          "invalid",
				          encoded_security_bits);
				security_bits = 0;
			}
		} else if (msg->msg_class == STUN_CLASS_RESP_ERROR) {
			JLOG_DEBUG("Remote agent does not support RFC 8489");
		}
		break;
	}
	case STUN_ATTR_PASSWORD_ALGORITHM: {
		JLOG_VERBOSE("Reading password algorithm");
		if (length < sizeof(struct stun_value_password_algorithm)) {
			JLOG_WARN("STUN password algorithm value too short, length=%zu", length);
			return -1;
		}
		if (!STUN_IS_RESPONSE(msg->msg_class)) {
			const struct stun_value_password_algorithm *pwa =
			    (const struct stun_value_password_algorithm *)attr->value;
			stun_password_algorithm_t algorithm = ntohs(pwa->algorithm);
			if (algorithm == STUN_PASSWORD_ALGORITHM_MD5 ||
			    algorithm == STUN_PASSWORD_ALGORITHM_SHA256)
				msg->credentials.password_algorithm = algorithm;
			else
				JLOG_WARN("Unknown password algorithm 0x%hX", algorithm);
		} else {
			JLOG_WARN("Found password algorithm in response, ignoring");
		}
		break;
	}
	case STUN_ATTR_PASSWORD_ALGORITHMS: {
		JLOG_VERBOSE("Reading password algorithms list");
		if (length < sizeof(struct stun_value_password_algorithm)) {
			JLOG_WARN("STUN password algorithms list too short, length=%zu", length);
			return -1;
		}
		if (length > STUN_MAX_PASSWORD_ALGORITHMS_VALUE_SIZE) {
			JLOG_WARN("STUN password algorithms list too long, length=%zu", length);
			return -1;
		}

		memcpy(msg->credentials.password_algorithms_value, attr->value, length);
		msg->credentials.password_algorithms_value_size = length;

		if (!STUN_IS_RESPONSE(msg->msg_class)) {
			const uint8_t *pos = attr->value;
			const uint8_t *end = pos + length;
			while (pos < end) {
				if ((size_t)(end - pos) < sizeof(struct stun_value_password_algorithm)) {
					JLOG_WARN("STUN password algorithms list truncated, available=%zu", end - pos);
					return -1;
				}
				const struct stun_value_password_algorithm *pwa =
				    (const struct stun_value_password_algorithm *)pos;
				stun_password_algorithm_t algorithm = ntohs(pwa->algorithm);
				size_t parameters_length = ntohs(pwa->parameters_length);
				size_t padded_length = align32(parameters_length);

				pos += sizeof(struct stun_value_password_algorithm);

				if ((size_t)(end - pos) < padded_length) {
					JLOG_WARN(
					    "STUN password algorithm parameters too long, length=%zu, padded=%zu, "
					    "available=%zu",
					    parameters_length, padded_length, end - pos);
					return -1;
				}

				pos += padded_length;

				if (algorithm == STUN_PASSWORD_ALGORITHM_MD5 ||
				    algorithm == STUN_PASSWORD_ALGORITHM_SHA256) {
					msg->credentials.password_algorithm = algorithm;
					break;
				}

				JLOG_DEBUG("Unknown password algorithm 0x%hX", algorithm);
			}
		}
		break;
	}
	case STUN_ATTR_USERHASH: {
		JLOG_VERBOSE("Reading user hash");
		if (length != USERHASH_SIZE) {
			JLOG_WARN("STUN user hash value too long, length=%zu", length);
			return -1;
		}
		memcpy(msg->credentials.userhash, attr->value, USERHASH_SIZE);
		msg->credentials.enable_userhash = true;
		break;
	}
	case STUN_ATTR_SOFTWARE: {
		JLOG_VERBOSE("Reading software");
		if (length + 1 > STUN_MAX_SOFTWARE_LEN) {
			JLOG_WARN("STUN software attribute value too long, length=%zu", length);
			return -1;
		}
		char buffer[STUN_MAX_SOFTWARE_LEN];
		memcpy(buffer, (const char *)attr->value, length);
		buffer[length] = '\0';
		JLOG_VERBOSE("Remote agent is \"%s\"", buffer);
		break;
	}
	case STUN_ATTR_PRIORITY: {
		JLOG_VERBOSE("Reading priority");
		if (length != 4) {
			JLOG_DEBUG("STUN priority length invalid, length=%zu", length);
			return -1;
		}
		msg->priority = ntohl(*((uint32_t *)attr->value));
		JLOG_VERBOSE("Got priority: %lu", (unsigned long)msg->priority);
		break;
	}
	case STUN_ATTR_USE_CANDIDATE: {
		JLOG_VERBOSE("Found use candidate flag");
		msg->use_candidate = true;
		break;
	}
	case STUN_ATTR_ICE_CONTROLLING: {
		JLOG_VERBOSE("Found ICE controlling attribute");
		if (length != 8) {
			JLOG_DEBUG("STUN ICE controlling attribute length invalid, length=%zu", length);
			return -1;
		}
		msg->ice_controlling = ntohll(*((uint64_t *)attr->value));
		break;
	}
	case STUN_ATTR_ICE_CONTROLLED: {
		JLOG_VERBOSE("Found ICE controlled attribute");
		if (length != 8) {
			JLOG_DEBUG("STUN ICE controlled attribute length invalid, length=%zu", length);
			return -1;
		}
		msg->ice_controlled = ntohll(*((uint64_t *)attr->value));
		break;
	}
	case STUN_ATTR_CHANNEL_NUMBER: {
		JLOG_VERBOSE("Reading channel number attribute");
		if (length < sizeof(struct stun_value_channel_number)) {
			JLOG_DEBUG("STUN channel number attribute value too short, length=%zu", length);
			return -1;
		}
		const struct stun_value_channel_number *channel_number =
		    (const struct stun_value_channel_number *)attr->value;
		msg->channel_number = ntohs(channel_number->channel_number);
		break;
	}
	case STUN_ATTR_LIFETIME: {
		JLOG_VERBOSE("Reading lifetime attribute");
		if (length != 4) {
			JLOG_DEBUG("STUN lifetime attribute length invalid, length=%zu", length);
			return -1;
		}
		msg->lifetime = ntohl(*((uint32_t *)attr->value));
		msg->lifetime_set = true;
		break;
	}
	case STUN_ATTR_XOR_PEER_ADDRESS: {
		JLOG_VERBOSE("Reading XOR peer address");
		uint8_t mask[16];
		*((uint32_t *)mask) = htonl(STUN_MAGIC);
		memcpy(mask + 4, msg->transaction_id, 12);
		if (stun_read_value_mapped_address(attr->value, length, &msg->peer, mask) < 0)
			return -1;
		break;
	}
	case STUN_ATTR_XOR_RELAYED_ADDRESS: {
		JLOG_VERBOSE("Reading XOR relayed address");
		uint8_t mask[16];
		*((uint32_t *)mask) = htonl(STUN_MAGIC);
		memcpy(mask + 4, msg->transaction_id, 12);
		if (stun_read_value_mapped_address(attr->value, length, &msg->relayed, mask) < 0)
			return -1;
		break;
	}
	case STUN_ATTR_DATA: {
		JLOG_VERBOSE("Found data");
		msg->data = (const char *)attr->value;
		msg->data_size = length;
		break;
	}
	case STUN_ATTR_EVEN_PORT: {
		JLOG_VERBOSE("Found even port attribute");
		if (length < 1) {
			JLOG_DEBUG("STUN even port attribute length invalid, length=%zu", length);
			return -1;
		}
		msg->even_port = true;
		msg->next_port = ((struct stun_value_even_port *)attr->value)->r & 0x80;
		break;
	}
	case STUN_ATTR_REQUESTED_TRANSPORT: {
		JLOG_VERBOSE("Found requested transport attribute");
		if (length < sizeof(struct stun_value_requested_transport)) {
			JLOG_DEBUG("STUN requested transport attribute length invalid, length=%zu", length);
			return -1;
		}
		const struct stun_value_requested_transport *requested_transport =
		    (const struct stun_value_requested_transport *)attr->value;
		if (requested_transport->protocol != 17) { // UDP
			JLOG_WARN("Unexpected requested transport protocol: %d",
			          (int)requested_transport->protocol);
			return -1;
		}
		msg->requested_transport = true;
		break;
	}
	case STUN_ATTR_DONT_FRAGMENT: {
		JLOG_VERBOSE("Found don't fragment attribute");
		msg->dont_fragment = true;
		break;
	}
	case STUN_ATTR_RESERVATION_TOKEN: {
		JLOG_VERBOSE("Found reservation token");
		if (length != 8) {
			JLOG_DEBUG("STUN reservation token length invalid, length=%zu", length);
			return -1;
		}
		msg->reservation_token = ntohll(*((uint64_t *)attr->value));
		break;
	}
	default: {
		// Ignore
		if (STUN_IS_OPTIONAL_ATTR(type))
			JLOG_DEBUG("Ignoring unknown optional STUN attribute type 0x%X", (unsigned int)type);
		else
			JLOG_WARN("Unknown STUN attribute type 0x%X, ignoring", (unsigned int)type);
		break;
	}
	}
	return (int)(sizeof(struct stun_attr) + align32(length));
}

int stun_read_value_mapped_address(const void *data, size_t size, addr_record_t *mapped,
                                   const uint8_t *mask) {
	size_t len = sizeof(struct stun_value_mapped_address);
	if (size < len) {
		JLOG_VERBOSE("STUN mapped address value too short, size=%zu", size);
		return -1;
	}
	const struct stun_value_mapped_address *value = data;
	stun_address_family_t family = (stun_address_family_t)value->family;
	switch (family) {
	case STUN_ADDRESS_FAMILY_IPV4: {
		len += 4;
		if (size < len) {
			JLOG_DEBUG("IPv4 mapped address value too short, size=%zu", size);
			return -1;
		}
		JLOG_VERBOSE("Reading IPv4 address");
		mapped->len = sizeof(struct sockaddr_in);
		struct sockaddr_in *sin = (struct sockaddr_in *)&mapped->addr;
		sin->sin_family = AF_INET;
		sin->sin_port = value->port ^ *((uint16_t *)mask);
		uint8_t *bytes = (uint8_t *)&sin->sin_addr;
		for (int i = 0; i < 4; ++i)
			bytes[i] = value->address[i] ^ mask[i];
		break;
	}
	case STUN_ADDRESS_FAMILY_IPV6: {
		len += 16;
		if (size < len) {
			JLOG_DEBUG("IPv6 mapped address value too short, size=%zu", size);
			return -1;
		}
		JLOG_VERBOSE("Reading IPv6 address");
		mapped->len = sizeof(struct sockaddr_in6);
		struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&mapped->addr;
		sin6->sin6_family = AF_INET6;
		sin6->sin6_port = value->port ^ *((uint16_t *)mask);
		uint8_t *bytes = (uint8_t *)&sin6->sin6_addr;
		for (int i = 0; i < 16; ++i)
			bytes[i] = value->address[i] ^ mask[i];
		break;
	}
	default: {
		JLOG_DEBUG("Unknown STUN address family 0x%X", (unsigned int)family);
		len = size;
		break;
	}
	}
	return (int)len;
}

bool stun_check_integrity(void *buf, size_t size, const stun_message_t *msg, const char *password) {
	if (!msg->has_integrity)
		return false;

	const struct stun_header *header = buf;
	const size_t length = ntohs(header->length);
	if (size < sizeof(struct stun_header) + length)
		return false;

	uint8_t key[MAX_HMAC_KEY_LEN];
	size_t key_len = generate_hmac_key(msg, password, key);

	bool success = false;
	uint8_t *begin = buf;
	const uint8_t *attr_begin = begin + sizeof(struct stun_header);
	const uint8_t *end = attr_begin + length;
	const uint8_t *pos = attr_begin;
	while (pos != end) {
		const struct stun_attr *attr = (const struct stun_attr *)pos;
		size_t attr_length = ntohs(attr->length);
		if (size < sizeof(struct stun_attr) + attr_length)
			return false;

		stun_attr_type_t type = (stun_attr_type_t)ntohs(attr->type);
		switch (type) {
		case STUN_ATTR_MESSAGE_INTEGRITY: {
			if (attr_length != HMAC_SHA1_SIZE)
				return false;

			size_t tmp_length = pos - attr_begin + STUN_ATTR_SIZE + HMAC_SHA1_SIZE;
			size_t prev_length = stun_update_header_length(begin, tmp_length);
			uint8_t hmac[HMAC_SHA1_SIZE];
			hmac_sha1(begin, pos - begin, key, key_len, hmac);
			stun_update_header_length(begin, prev_length);

			const uint8_t *expected_hmac = attr->value;
			if (const_time_memcmp(hmac, expected_hmac, HMAC_SHA1_SIZE) != 0) {
				JLOG_DEBUG("STUN message integrity SHA1 check failed");
				return false;
			}

			success = true;
			break;
		}
		case STUN_ATTR_MESSAGE_INTEGRITY_SHA256: {
			if (attr_length != HMAC_SHA256_SIZE)
				return false;

			size_t tmp_length = pos - attr_begin + STUN_ATTR_SIZE + HMAC_SHA256_SIZE;
			size_t prev_length = stun_update_header_length(begin, tmp_length);
			uint8_t hmac[HMAC_SHA256_SIZE];
			hmac_sha256(begin, pos - begin, key, key_len, hmac);
			stun_update_header_length(begin, prev_length);

			const uint8_t *expected_hmac = attr->value;
			if (const_time_memcmp(hmac, expected_hmac, HMAC_SHA256_SIZE) != 0) {
				JLOG_DEBUG("STUN message integrity SHA256 check failed");
				return false;
			}

			success = true;
			break;
		}
		default:
			// Ignore
			break;
		}

		pos += sizeof(struct stun_attr) + align32(attr_length);
	}

	if (!success)
		return false;

	JLOG_VERBOSE("STUN message integrity check succeeded");
	return true;
}

void stun_prepend_nonce_cookie(char *nonce) {
	// RFC 8489: To indicate that it supports this specification, a server MUST prepend the
	// NONCE attribute value with the character string composed of "obMatJos2" concatenated with
	// the (4-character) base64 [RFC4648] encoding of the 24-bit STUN Security Features See
	// https://tools.ietf.org/html/rfc8489#section-9.2
	char copy[STUN_MAX_NONCE_LEN];
	strcpy(copy, nonce);

	char encoded_security_bits[5];
	uint32_t security_bits =
	    htonl(STUN_SECURITY_PASSWORD_ALGORITHMS_BIT | STUN_SECURITY_USERNAME_ANONYMITY_BIT);
	BASE64_ENCODE((uint8_t *)&security_bits + 1, 3, encoded_security_bits, 5);

	snprintf(nonce, STUN_MAX_NONCE_LEN, "%s%s%.*s", STUN_NONCE_COOKIE, encoded_security_bits,
	         STUN_MAX_NONCE_LEN - (STUN_NONCE_COOKIE_LEN + 5), copy);
}

void stun_compute_userhash(const char *username, const char *realm, uint8_t *out) {
	char input[MAX_USERHASH_INPUT_LEN];
	int input_len = snprintf(input, MAX_USERHASH_INPUT_LEN, "%s:%s", username, realm);
	if (input_len < 0)
		return;

	if (input_len >= MAX_USERHASH_INPUT_LEN)
		input_len = MAX_USERHASH_INPUT_LEN - 1;

	hash_sha256(input, input_len, out);
}

void stun_process_credentials(const stun_credentials_t *credentials, stun_credentials_t *dst) {
	char username[STUN_MAX_USERNAME_LEN];
	strcpy(username, dst->username);
	*dst = *credentials;
	strcpy(dst->username, username);

	if (credentials->enable_userhash)
		stun_compute_userhash(username, credentials->realm, dst->userhash);
}

const char *stun_get_error_reason(unsigned int code) {
	switch (code) {
	case 0:
		return "";
	case 300:
		return "Try Alternate";
	case 400:
		return "Bad Request";
	case 401:
		return "Unauthenticated";
	case 403:
		return "Forbidden";
	case 420:
		return "Unknown Attribute";
	case 437:
		return "Allocation Mismatch";
	case 438:
		return "Stale Nonce";
	case 440:
		return "Address Family not Supported";
	case 441:
		return "Wrong credentials";
	case 442:
		return "Unsupported Transport Protocol";
	case 443:
		return "Peer Address Family Mismatch";
	case 486:
		return "Allocation Quota Reached";
	case 500:
		return "Server Error";
	case 508:
		return "Insufficient Capacity";
	default:
		return "Error";
	}
}

JUICE_EXPORT int _juice_stun_read(void *data, size_t size, stun_message_t *msg) {
	return stun_read(data, size, msg);
}

JUICE_EXPORT bool _juice_stun_check_integrity(void *buf, size_t size, const stun_message_t *msg,
                                              const char *password) {
	return stun_check_integrity(buf, size, msg, password);
}