summaryrefslogtreecommitdiff
path: root/src/libknot/packet/packet.c
blob: 9b7e7c7081d52fe940fbcbc022e66172feade3c0 (plain)
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
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
/*  Copyright (C) 2011 CZ.NIC, z.s.p.o. <knot-dns@labs.nic.cz>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <assert.h>

#include "packet/packet.h"
#include "util/debug.h"
#include "common.h"
#include "util/descriptor.h"
#include "util/wire.h"
#include "tsig.h"

/*----------------------------------------------------------------------------*/

#define DEFAULT_RRCOUNT_QUERY(type) DEFAULT_##type##COUNT_QUERY
#define DEFAULT_RRCOUNT(type) DEFAULT_##type##COUNT

#define DEFAULT_RRSET_COUNT(type, packet) \
	((packet->prealloc_type == KNOT_PACKET_PREALLOC_NONE)  \
		? 0  \
		: (packet->prealloc_type == KNOT_PACKET_PREALLOC_QUERY)  \
			? DEFAULT_##type##_QUERY  \
			: DEFAULT_##type)



typedef enum {
	KNOT_PACKET_DUPL_IGNORE,
	KNOT_PACKET_DUPL_SKIP,
	KNOT_PACKET_DUPL_MERGE
} knot_packet_duplicate_handling_t;
/*----------------------------------------------------------------------------*/
/* Non-API functions                                                          */
/*----------------------------------------------------------------------------*/
/*!
 * \brief Sets all the pointers in the packet structure to the respective
 *        parts of the pre-allocated space.
 */
static void knot_packet_init_pointers_response(knot_packet_t *pkt)
{
	dbg_packet_detail("Packet pointer: %p\n", pkt);
	
	char *pos = (char *)pkt + PREALLOC_PACKET;

	// put QNAME directly after the structure
	pkt->question.qname = (knot_dname_t *)pos;
	pos += PREALLOC_QNAME_DNAME;

	dbg_packet_detail("QNAME: %p\n", pkt->question.qname);

	pkt->question.qname->name = (uint8_t *)pos;
	pos += PREALLOC_QNAME_NAME;
	pkt->question.qname->labels = (uint8_t *)pos;
	pos += PREALLOC_QNAME_LABELS;

	pkt->owner_tmp = (uint8_t *)pos;
	dbg_packet_detail("Tmp owner: %p\n", pkt->owner_tmp);
	pos += PREALLOC_RR_OWNER;

	// then answer, authority and additional sections
	if (DEFAULT_ANCOUNT == 0) {
		pkt->answer = NULL;
	} else {
		pkt->answer = (const knot_rrset_t **)pos;
		pos += DEFAULT_ANCOUNT * sizeof(const knot_rrset_t *);
	}
	
	if (DEFAULT_NSCOUNT == 0) {
		pkt->authority = NULL;
	} else {
		pkt->authority = (const knot_rrset_t **)pos;
		pos += DEFAULT_NSCOUNT * sizeof(const knot_rrset_t *);
	}
	
	if (DEFAULT_ARCOUNT == 0) {
		pkt->additional = NULL;
	} else {
		pkt->additional = (const knot_rrset_t **)pos;
		pos += DEFAULT_ARCOUNT * sizeof(const knot_rrset_t *);
	}

	dbg_packet_detail("Answer section: %p\n", pkt->answer);
	dbg_packet_detail("Authority section: %p\n", pkt->authority);
	dbg_packet_detail("Additional section: %p\n", pkt->additional);

	pkt->max_an_rrsets = DEFAULT_ANCOUNT;
	pkt->max_ns_rrsets = DEFAULT_NSCOUNT;
	pkt->max_ar_rrsets = DEFAULT_ARCOUNT;

	// then domain names for compression and offsets
	pkt->compression.dnames = (const knot_dname_t **)pos;
	pos += DEFAULT_DOMAINS_IN_RESPONSE * sizeof(const knot_dname_t *);
	pkt->compression.offsets = (size_t *)pos;
	pos += DEFAULT_DOMAINS_IN_RESPONSE * sizeof(size_t);
	pkt->compression.to_free = (int *)pos;
	pos += DEFAULT_DOMAINS_IN_RESPONSE * sizeof(int);

	dbg_packet_detail("Compression dnames: %p\n", pkt->compression.dnames);
	dbg_packet_detail("Compression offsets: %p\n", pkt->compression.offsets);
	dbg_packet_detail("Compression to_free: %p\n", pkt->compression.to_free);

	pkt->compression.max = DEFAULT_DOMAINS_IN_RESPONSE;
	pkt->compression.default_count = DEFAULT_DOMAINS_IN_RESPONSE;

	// wildcard nodes and SNAMEs associated with them
	pkt->wildcard_nodes.nodes = (const knot_node_t **)pos;
	pos += DEFAULT_WILDCARD_NODES * sizeof(const knot_node_t *);
	pkt->wildcard_nodes.snames = (const knot_dname_t **)pos;
	pos += DEFAULT_WILDCARD_NODES * sizeof(knot_dname_t *);

	dbg_packet_detail("Wildcard nodes: %p\n", pkt->wildcard_nodes.nodes);
	dbg_packet_detail("Wildcard SNAMEs: %p\n", pkt->wildcard_nodes.snames);

	pkt->wildcard_nodes.default_count = DEFAULT_WILDCARD_NODES;
	pkt->wildcard_nodes.max = DEFAULT_WILDCARD_NODES;

	pkt->tmp_rrsets = (const knot_rrset_t **)pos;
	pos += DEFAULT_TMP_RRSETS * sizeof(const knot_rrset_t *);

	dbg_packet_detail("Tmp rrsets: %p\n", pkt->tmp_rrsets);

	pkt->tmp_rrsets_max = DEFAULT_TMP_RRSETS;

	assert((char *)pos == (char *)pkt + PREALLOC_RESPONSE);
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief Sets all the pointers in the packet structure to the respective
 *        parts of the pre-allocated space.
 */
static void knot_packet_init_pointers_query(knot_packet_t *pkt)
{
	dbg_packet_detail("Packet pointer: %p\n", pkt);
	
	char *pos = (char *)pkt + PREALLOC_PACKET;

	// put QNAME directly after the structure
	pkt->question.qname = (knot_dname_t *)pos;
	pos += PREALLOC_QNAME_DNAME;

	dbg_packet_detail("QNAME: %p (%zu after start of packet)\n",
	                  pkt->question.qname,
	                  (void *)pkt->question.qname - (void *)pkt);

	pkt->question.qname->name = (uint8_t *)pos;
	pos += PREALLOC_QNAME_NAME;
	pkt->question.qname->labels = (uint8_t *)pos;
	pos += PREALLOC_QNAME_LABELS;


	// then answer, authority and additional sections
	if (DEFAULT_ANCOUNT_QUERY == 0) {
		pkt->answer = NULL;
	} else {
		pkt->answer = (const knot_rrset_t **)pos;
		pos += DEFAULT_ANCOUNT_QUERY * sizeof(const knot_rrset_t *);
	}
	
	if (DEFAULT_NSCOUNT_QUERY == 0) {
		pkt->authority = NULL;
	} else {
		pkt->authority = (const knot_rrset_t **)pos;
		pos += DEFAULT_NSCOUNT_QUERY * sizeof(const knot_rrset_t *);
	}
	
	if (DEFAULT_ARCOUNT_QUERY == 0) {
		pkt->additional = NULL;
	} else {
		pkt->additional = (const knot_rrset_t **)pos;
		pos += DEFAULT_ARCOUNT_QUERY * sizeof(const knot_rrset_t *);
	}

	dbg_packet_detail("Answer section: %p\n", pkt->answer);
	dbg_packet_detail("Authority section: %p\n", pkt->authority);
	dbg_packet_detail("Additional section: %p\n", pkt->additional);

	pkt->max_an_rrsets = DEFAULT_ANCOUNT_QUERY;
	pkt->max_ns_rrsets = DEFAULT_NSCOUNT_QUERY;
	pkt->max_ar_rrsets = DEFAULT_ARCOUNT_QUERY;

	pkt->tmp_rrsets = (const knot_rrset_t **)pos;
	pos += DEFAULT_TMP_RRSETS_QUERY * sizeof(const knot_rrset_t *);

	dbg_packet_detail("Tmp rrsets: %p\n", pkt->tmp_rrsets);

	pkt->tmp_rrsets_max = DEFAULT_TMP_RRSETS_QUERY;

	dbg_packet_detail("Allocated total: %u\n", PREALLOC_QUERY);

	assert(pos == (char *)pkt + PREALLOC_QUERY);
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief Parses DNS header from the wire format.
 *
 * \note This function also adjusts the position (\a pos) and size of remaining
 *       bytes in the wire format (\a remaining) according to what was parsed
 *       (though it actually always parses the 12 bytes of the header).
 *
 * \param[in,out] pos Wire format to parse the header from.
 * \param[in,out] remaining Remaining size of the wire format.
 * \param[out] header Header structure to fill in.
 *
 * \retval KNOT_EOK
 * \retval KNOT_EFEWDATA
 */
static int knot_packet_parse_header(const uint8_t *wire, size_t *pos,
                                      size_t size, knot_header_t *header)
{
	assert(wire != NULL);
	assert(pos != NULL);
	assert(header != NULL);

	if (size - *pos < KNOT_WIRE_HEADER_SIZE) {
		dbg_packet("Not enough data to parse header.\n");
		return KNOT_EFEWDATA;
	}

	header->id = knot_wire_get_id(wire);
	// copy some of the flags: OPCODE and RD
	// do this by copying flags1 and setting QR to 1, AA to 0 and TC to 0
	header->flags1 = knot_wire_get_flags1(wire);
	// do not copy flags2 (all set by server)

	header->qdcount = knot_wire_get_qdcount(wire);
	header->ancount = knot_wire_get_ancount(wire);
	header->nscount = knot_wire_get_nscount(wire);
	header->arcount = knot_wire_get_arcount(wire);

	*pos += KNOT_WIRE_HEADER_SIZE;

	return KNOT_EOK;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief Parses DNS Question entry from the wire format.
 *
 * \note This function also adjusts the position (\a pos) and size of remaining
 *       bytes in the wire format (\a remaining) according to what was parsed.
 *
 * \param[in,out] pos Wire format to parse the Question from.
 * \param[in,out] remaining Remaining size of the wire format.
 * \param[out] question DNS Question structure to be filled.
 *
 * \retval KNOT_EOK
 * \retval KNOT_EFEWDATA
 * \retval KNOT_ENOMEM
 */
static int knot_packet_parse_question(const uint8_t *wire, size_t *pos,
                                        size_t size,
                                        knot_question_t *question, int alloc)
{
	assert(pos != NULL);
	assert(wire != NULL);
	assert(question != NULL);

	if (size - *pos < KNOT_WIRE_QUESTION_MIN_SIZE) {
		dbg_packet("Not enough data to parse question.\n");
		return KNOT_EFEWDATA;  // malformed
	}

	dbg_packet("Parsing Question starting on position %zu.\n", *pos);

	// domain name must end with 0, so just search for 0
	int i = *pos;
	while (i < size && wire[i] != 0) {
		++i;
	}

	if (size - i - 1 < 4) {
		dbg_packet("Not enough data to parse question.\n");
		return KNOT_EFEWDATA;  // no 0 found or not enough data left
	}

	dbg_packet_verb("Parsing dname starting on position %zu and "
	                      "%zu bytes long.\n", *pos, i - *pos + 1);
	dbg_packet_verb("Alloc: %d\n", alloc);
	size_t bp = *pos;
	if (alloc) {
		question->qname = knot_dname_parse_from_wire(wire, pos,
		                                             i + 1,
		                                             NULL, NULL);
		if (question->qname == NULL) {
			return KNOT_ENOMEM;
		}
	} else {
		void *parsed = knot_dname_parse_from_wire(wire, pos,
		                                     i + 1,
	                                             NULL, question->qname);
		if (!parsed) {
			return KNOT_EMALF;
		}
	}
	if (*pos != i + 1) {
		dbg_packet("Parsed dname expected len=%zu, parsed=%zu.\n", i+1-bp, *pos-bp);
	}
	question->qtype = knot_wire_read_u16(wire + i + 1);
	question->qclass = knot_wire_read_u16(wire + i + 3);
	*pos += 4;

	return KNOT_EOK;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief Reallocate space for RRSets.
 *
 * \param rrsets Space for RRSets.
 * \param max_count Size of the space available for the RRSets.
 * \param default_max_count Size of the space pre-allocated for the RRSets when
 *        the response structure was initialized.
 * \param step How much the space should be increased.
 *
 * \retval KNOT_EOK
 * \retval KNOT_ENOMEM
 */
static int knot_packet_realloc_rrsets(const knot_rrset_t ***rrsets,
                                        short *max_count,
                                        short default_max_count, short step)
{
	dbg_packet_verb("Max count: %d, default max count: %d\n",
	       *max_count, default_max_count);
	int free_old = (*max_count) != default_max_count;
	const knot_rrset_t **old = *rrsets;

	short new_max_count = *max_count + step;
	const knot_rrset_t **new_rrsets = (const knot_rrset_t **)malloc(
		new_max_count * sizeof(knot_rrset_t *));
	CHECK_ALLOC_LOG(new_rrsets, KNOT_ENOMEM);

	memcpy(new_rrsets, *rrsets, (*max_count) * sizeof(knot_rrset_t *));

	*rrsets = new_rrsets;
	*max_count = new_max_count;

	if (free_old) {
		free(old);
	}

	return KNOT_EOK;
}

/*----------------------------------------------------------------------------*/

static knot_rdata_t *knot_packet_parse_rdata(const uint8_t *wire,
	size_t *pos, size_t total_size, size_t rdlength,
	const knot_rrtype_descriptor_t *desc)
{
	knot_rdata_t *rdata = knot_rdata_new();
	if (rdata == NULL) {
		return NULL;
	}

	int rc = knot_rdata_from_wire(rdata, wire, pos, total_size, rdlength,
	                                desc);

	if (rc != KNOT_EOK) {
		dbg_packet("rdata_from_wire() returned: %s\n",
		           knot_strerror(rc));
		knot_rdata_free(&rdata);
		return NULL;
	}

	return rdata;
}

/*----------------------------------------------------------------------------*/

static knot_rrset_t *knot_packet_parse_rr(const uint8_t *wire, size_t *pos,
                                              size_t size)
{
	dbg_packet("Parsing RR from position: %zu, total size: %zu\n",
	           *pos, size);

	knot_dname_t *owner = knot_dname_parse_from_wire(wire, pos, size,
	                                                     NULL, NULL);
	dbg_packet_detail("Created owner: %p, actual position: %zu\n", owner,
	                  *pos);
	if (owner == NULL) {
		return NULL;
	}

dbg_packet_exec_verb(
	char *name = knot_dname_to_str(owner);
	dbg_packet_verb("Parsed name: %s\n", name);
	free(name);
);

	/*! @todo Get rid of the numerical constant. */
	if (size - *pos < 10) {
		dbg_packet("Malformed RR: Not enough data to parse RR"
		           " header.\n");
		knot_dname_release(owner);
		return NULL;
	}

	dbg_packet_detail("Reading type from position %zu\n", *pos);

	uint16_t type = knot_wire_read_u16(wire + *pos);
	uint16_t rclass = knot_wire_read_u16(wire + *pos + 2);
	uint32_t ttl = knot_wire_read_u32(wire + *pos + 4);

	knot_rrset_t *rrset = knot_rrset_new(owner, type, rclass, ttl);

	/* Owner is either referenced in rrset or rrset creation failed. */
	knot_dname_release(owner);

	/* Check rrset allocation. */
	if (rrset == NULL) {
		return NULL;
	}

	uint16_t rdlength = knot_wire_read_u16(wire + *pos + 8);

	dbg_packet_detail("Read RR header: type %u, class %u, ttl %u, "
	                    "rdlength %u\n", rrset->type, rrset->rclass,
	                    rrset->ttl, rdlength);

	*pos += 10;

	if (size - *pos < rdlength) {
		dbg_packet("Malformed RR: Not enough data to parse RR"
		           " RDATA (size: %zu, position: %zu).\n", size, *pos);
		knot_rrset_deep_free(&rrset, 1, 1, 0);
		return NULL;
	}

	rrset->rrsigs = NULL;

	if (rdlength == 0) {
		return rrset;
	}

	// parse RDATA
	knot_rdata_t *rdata = knot_packet_parse_rdata(wire, pos, size,
	                         rdlength,
	                         knot_rrtype_descriptor_by_type(rrset->type));
	if (rdata == NULL) {
		dbg_packet("Malformed RR: Could not parse RDATA.\n");
		knot_rrset_deep_free(&rrset, 1, 1, 0);
		return NULL;
	}

	if (knot_rrset_add_rdata(rrset, rdata) != KNOT_EOK) {
		dbg_packet("Malformed RR: Could not add RDATA to RRSet.\n");
		knot_rdata_free(&rdata);
		knot_rrset_deep_free(&rrset, 1, 1, 0);
		return NULL;
	}

	return rrset;
}

/*----------------------------------------------------------------------------*/

static int knot_packet_add_rrset(knot_rrset_t *rrset,
                                 const knot_rrset_t ***rrsets,
                                 short *rrset_count,
                                 short *max_rrsets,
                                 short default_rrsets,
                                 const knot_packet_t *packet,
                                 knot_packet_duplicate_handling_t dupl)
{
	assert(rrset != NULL);
	assert(rrsets != NULL);
	assert(rrset_count != NULL);
	assert(max_rrsets != NULL);

dbg_packet_exec_verb(
	char *name = knot_dname_to_str(rrset->owner);
	dbg_packet_verb("packet_add_rrset(), owner: %s, type: %s\n",
	                name, knot_rrtype_to_string(rrset->type));
	free(name);
);

	if (*rrset_count == *max_rrsets
	    && knot_packet_realloc_rrsets(rrsets, max_rrsets, default_rrsets,
	                                    STEP_ANCOUNT) != KNOT_EOK) {
		return KNOT_ENOMEM;
	}

	if (dupl == KNOT_PACKET_DUPL_SKIP &&
	    knot_packet_contains(packet, rrset, KNOT_RRSET_COMPARE_PTR)) {
		/*! \todo This should also return > 0, as it means that the
		          RRSet was not used actually. */
		return KNOT_EOK;
	}

	if (dupl == KNOT_PACKET_DUPL_MERGE) {
		// try to find the RRSet in this array of RRSets
		for (int i = 0; i < *rrset_count; ++i) {

dbg_packet_exec_detail(
			char *name = knot_dname_to_str((*rrsets)[i]->owner);
			dbg_packet_detail("Comparing to RRSet: owner: %s, "
			                  "type: %s\n", name,
			                  knot_rrtype_to_string(
			                       (*rrsets)[i]->type));
			free(name);
);

			if (knot_rrset_match((*rrsets)[i], rrset,
			                         KNOT_RRSET_COMPARE_HEADER)) {
				/*! \todo Test this!!! */
				// no duplicate checking here, the packet should
				// look exactly as it came from wire
				int rc = knot_rrset_merge(
				    (void **)((*rrsets) + i), (void **)&rrset);
				if (rc != KNOT_EOK) {
					return rc;
				}
				return 1;
			}
		}
	}

	(*rrsets)[*rrset_count] = rrset;
	++(*rrset_count);

	return KNOT_EOK;
}

/*----------------------------------------------------------------------------*/

static int knot_packet_parse_rrs(const uint8_t *wire, size_t *pos,
                                 size_t size, uint16_t rr_count,
                                 uint16_t *parsed_rrs,
                                 const knot_rrset_t ***rrsets,
                                 short *rrset_count, short *max_rrsets,
                                 short default_rrsets,
                                 knot_packet_t *packet)
{
	assert(pos != NULL);
	assert(wire != NULL);
	assert(rrsets != NULL);
	assert(rrset_count != NULL);
	assert(max_rrsets != NULL);
	assert(packet != NULL);

	dbg_packet("Parsing RRSets starting on position: %zu\n", *pos);

	/*
	 * The RRs from one RRSet may be scattered in the current section.
	 * We must parse all RRs separately and try to add them to already
	 * parsed RRSets.
	 */
	int err = KNOT_EOK;
	knot_rrset_t *rrset = NULL;

	/* Start parsing from the first RR not parsed. */
	for (int i = *parsed_rrs; i < rr_count; ++i) {
		rrset = knot_packet_parse_rr(wire, pos, size);
		if (rrset == NULL) {
			dbg_packet("Failed to parse RR!\n");
			err = KNOT_EMALF;
			break;
		}

		++(*parsed_rrs);

		err = knot_packet_add_rrset(rrset, rrsets, rrset_count,
		                            max_rrsets, default_rrsets, packet,
		                            KNOT_PACKET_DUPL_MERGE);
		if (err < 0) {
			break;
		} else if (err > 0) {	// merged
			dbg_packet_detail("RRSet merged, freeing.\n");
			knot_rrset_deep_free(&rrset, 1, 0, 0);  // TODO: ok??
			continue;
		}

		err = knot_packet_add_tmp_rrset(packet, rrset);
		if (err != KNOT_EOK) {
			// remove the last RRSet from the list of RRSets
			// - just decrement the count
			--(*rrset_count);
			knot_rrset_deep_free(&rrset, 1, 1, 1);
			break;
		}

		if (knot_rrset_type(rrset) == KNOT_RRTYPE_TSIG) {
			// if there is some TSIG already, treat as malformed
			if (knot_packet_tsig(packet) != NULL) {
				err = KNOT_EMALF;
				break;
			}

			// First check the format of the TSIG RR
			if (!tsig_rdata_is_ok(rrset)) {
				err = KNOT_EMALF;
				break;
			}

			// store the TSIG into the packet
			knot_packet_set_tsig(packet, rrset);
		}
	}

	return (err < 0) ? err : KNOT_EOK;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief Deallocates all space which was allocated additionally to the
 *        pre-allocated space of the response structure.
 *
 * \param resp Response structure that holds pointers to the allocated space.
 */
static void knot_packet_free_allocated_space(knot_packet_t *pkt)
{
	dbg_packet_verb("Freeing additional space in packet.\n");
	if (pkt->prealloc_type == KNOT_PACKET_PREALLOC_NONE) {
		dbg_packet_detail("Freeing QNAME.\n");
		knot_dname_release(pkt->question.qname);
	}

	if (pkt->max_an_rrsets > DEFAULT_RRSET_COUNT(ANCOUNT, pkt)) {
		free(pkt->answer);
	}
	if (pkt->max_ns_rrsets > DEFAULT_RRSET_COUNT(NSCOUNT, pkt)) {
		free(pkt->authority);
	}
	if (pkt->max_ar_rrsets > DEFAULT_RRSET_COUNT(ARCOUNT, pkt)) {
		free(pkt->additional);
	}

	if (pkt->compression.max > pkt->compression.default_count) {
		free(pkt->compression.dnames);
		free(pkt->compression.offsets);
		free(pkt->compression.to_free);
	}

	if (pkt->wildcard_nodes.max > pkt->wildcard_nodes.default_count) {
		free(pkt->wildcard_nodes.nodes);
		free(pkt->wildcard_nodes.snames);
	}

	if (pkt->tmp_rrsets_max > DEFAULT_RRSET_COUNT(TMP_RRSETS, pkt)) {
		free(pkt->tmp_rrsets);
	}
}

/*----------------------------------------------------------------------------*/

static int knot_packet_parse_rr_sections(knot_packet_t *packet,
                                           size_t *pos)
{
	assert(packet != NULL);
	assert(packet->wireformat != NULL);
	assert(packet->size > 0);
	assert(pos != NULL);
	assert(*pos > 0);

	int err;

	assert(packet->tsig_rr == NULL);

	dbg_packet_verb("Parsing Answer RRs...\n");
	if ((err = knot_packet_parse_rrs(packet->wireformat, pos,
	   packet->size, packet->header.ancount, &packet->parsed_an,
	   &packet->answer, &packet->an_rrsets, &packet->max_an_rrsets,
	   DEFAULT_RRSET_COUNT(ANCOUNT, packet), packet)) != KNOT_EOK) {
		return err;
	}

	if (packet->tsig_rr != NULL) {
		dbg_packet("TSIG in Answer section.\n");
		return KNOT_EMALF;
	}

	dbg_packet_verb("Parsing Authority RRs...\n");
	if ((err = knot_packet_parse_rrs(packet->wireformat, pos,
	   packet->size, packet->header.nscount, &packet->parsed_ns,
	   &packet->authority, &packet->ns_rrsets, &packet->max_ns_rrsets,
	   DEFAULT_RRSET_COUNT(NSCOUNT, packet), packet)) != KNOT_EOK) {
		return err;
	}

	if (packet->tsig_rr != NULL) {
		dbg_packet("TSIG in Authority section.\n");
		return KNOT_EMALF;
	}

	dbg_packet_verb("Parsing Additional RRs...\n");
	if ((err = knot_packet_parse_rrs(packet->wireformat, pos,
	   packet->size, packet->header.arcount, &packet->parsed_ar,
	   &packet->additional, &packet->ar_rrsets, &packet->max_ar_rrsets,
	   DEFAULT_RRSET_COUNT(ARCOUNT, packet), packet)) != KNOT_EOK) {
		return err;
	}

	// If TSIG is not the last record
	if (packet->tsig_rr != NULL
	    && packet->ar_rrsets[packet->additional - 1] != packet->tsig_rr) {
		dbg_packet("TSIG in Additonal section but not last.\n");
		return KNOT_EMALF;
	}

	dbg_packet_verb("Trying to find OPT RR in the packet.\n");

	for (int i = 0; i < packet->ar_rrsets; ++i) {
		assert(packet->additional[i] != NULL);
		if (knot_rrset_type(packet->additional[i]) == KNOT_RRTYPE_OPT) {
			dbg_packet_detail("Found OPT RR, filling.\n");
			err = knot_edns_new_from_rr(&packet->opt_rr,
			                              packet->additional[i]);
			if (err != KNOT_EOK) {
				return err;
			}
			break;
		}
	}

	packet->parsed = *pos;

	if (*pos < packet->size) {
		// If there is some trailing garbage, treat the packet as
		// malformed
		dbg_packet_verb("Packet: %zu bytes of trailing garbage "
		                "in packet.\n", packet->size - (*pos));
		return KNOT_EMALF;
	}

	return KNOT_EOK;
}

/*----------------------------------------------------------------------------*/
/* API functions                                                              */
/*----------------------------------------------------------------------------*/

knot_packet_t *knot_packet_new(knot_packet_prealloc_type_t prealloc)
{
	knot_packet_t *pkt;
	void (*init_pointers)(knot_packet_t *pkt) = NULL;
	size_t size = 0;

	switch (prealloc) {
	case KNOT_PACKET_PREALLOC_NONE:
		size = sizeof(knot_packet_t);
		break;
	case KNOT_PACKET_PREALLOC_QUERY:
		size = PREALLOC_QUERY;
		init_pointers = knot_packet_init_pointers_query;
		break;
	case KNOT_PACKET_PREALLOC_RESPONSE:
		size = PREALLOC_RESPONSE;
		init_pointers = knot_packet_init_pointers_response;
		break;
	}

	pkt = (knot_packet_t *)malloc(size);
	CHECK_ALLOC_LOG(pkt, NULL);
	memset(pkt, 0, size);
	if (init_pointers != NULL) {
		init_pointers(pkt);
	}

	pkt->prealloc_type = prealloc;

	// set EDNS version to not supported
	pkt->opt_rr.version = EDNS_NOT_SUPPORTED;

	return pkt;
}

/*----------------------------------------------------------------------------*/

int knot_packet_parse_from_wire(knot_packet_t *packet,
                                  const uint8_t *wireformat, size_t size,
                                  int question_only)
{
	if (packet == NULL || wireformat == NULL) {
		return KNOT_EINVAL;
	}

	int err;

	// save the wireformat in the packet
	// TODO: can we just save the pointer, or we have to copy the data??
	assert(packet->wireformat == NULL);
	packet->wireformat = (uint8_t*)wireformat;
	packet->size = size;
	packet->free_wireformat = 0;

	if (size < 2) {
		return KNOT_EMALF;
	}

	size_t pos = 0;

	dbg_packet_verb("Parsing wire format of packet (size %zu).\nHeader\n",
	                size);
	if ((err = knot_packet_parse_header(wireformat, &pos, size,
	                                      &packet->header)) != KNOT_EOK) {
		return err;
	}

	packet->parsed = pos;

	dbg_packet_verb("Question (prealloc type: %d)...\n",
	                packet->prealloc_type);

	if (packet->header.qdcount > 1) {
		dbg_packet("QDCOUNT larger than 1, FORMERR.\n");
		return KNOT_EMALF;
	}

	if (packet->header.qdcount == 1) {
		if ((err = knot_packet_parse_question(wireformat, &pos, size,
		             &packet->question, packet->prealloc_type 
		                                == KNOT_PACKET_PREALLOC_NONE)
		     ) != KNOT_EOK) {
			return err;
		}
		packet->parsed = pos;
	}

dbg_packet_exec_detail(
	knot_packet_dump(packet);
);

	if (question_only) {
		return KNOT_EOK;
	}

	/*! \todo Replace by call to parse_rest()? */
	err = knot_packet_parse_rest(packet);

dbg_packet_exec_detail(
	knot_packet_dump(packet);
);

	return err;
}

/*----------------------------------------------------------------------------*/

int knot_packet_parse_rest(knot_packet_t *packet)
{
	if (packet == NULL) {
		return KNOT_EINVAL;
	}

	if (packet->header.ancount == packet->parsed_an
	    && packet->header.nscount == packet->parsed_ns
	    && packet->header.arcount == packet->parsed_ar
	    && packet->parsed == packet->size) {
		return KNOT_EOK;
	}

	// If there is less data then required, the next function will find out.
	// If there is more data than required, it also returns EMALF.
	
	size_t pos = packet->parsed;

	/*! \todo If we already parsed some part of the packet, it is not ok
	 *        to begin parsing from the Answer section.
	 */
	return knot_packet_parse_rr_sections(packet, &pos);
}

/*----------------------------------------------------------------------------*/

int knot_packet_parse_next_rr_answer(knot_packet_t *packet,
                                       knot_rrset_t **rr)
{
	if (packet == NULL || rr == NULL) {
		return KNOT_EINVAL;
	}

	*rr = NULL;

	if (packet->parsed >= packet->size) {
		assert(packet->an_rrsets <= packet->header.ancount);
		if (packet->parsed_an != packet->header.ancount) {
			dbg_packet("Parsed less RRs than expected.\n");
			return KNOT_EMALF;
		} else {
			dbg_packet_detail("Whole packet parsed\n");
			return KNOT_EOK;
		}
	}

	if (packet->parsed_an == packet->header.ancount) {
		assert(packet->parsed < packet->size);
		//dbg_packet("Trailing garbage, ignoring...\n");
		// there may be other data in the packet 
		// (authority or additional).
		return KNOT_EOK;
	}

	size_t pos = packet->parsed;

	dbg_packet_verb("Parsing next Answer RR (pos: %zu)...\n", pos);
	*rr = knot_packet_parse_rr(packet->wireformat, &pos, packet->size);
	if (*rr == NULL) {
		dbg_packet_verb("Failed to parse RR!\n");
		return KNOT_EMALF;
	}
	
	dbg_packet_detail("Parsed. Pos: %zu.\n", pos);

	packet->parsed = pos;
	// increment the number of answer RRSets, though there are no saved
	// in the packet; it is OK, because packet->answer is NULL
	++packet->an_rrsets;
	++packet->parsed_an;

	return KNOT_EOK;
}

/*----------------------------------------------------------------------------*/

int knot_packet_parse_next_rr_additional(knot_packet_t *packet,
                                         knot_rrset_t **rr)
{
	/*! \todo Implement. */
	if (packet == NULL || rr == NULL) {
		return KNOT_EINVAL;
	}

	*rr = NULL;

	if (packet->parsed >= packet->size) {
		assert(packet->ar_rrsets <= packet->header.arcount);
		if (packet->parsed_ar != packet->header.arcount) {
			dbg_packet("Parsed less RRs than expected.\n");
			return KNOT_EMALF;
		} else {
			dbg_packet_detail("Whole packet parsed\n");
			return KNOT_EOK;
		}
	}

	if (packet->parsed_ar == packet->header.arcount) {
		assert(packet->parsed < packet->size);
		dbg_packet_verb("Trailing garbage, treating as malformed...\n");
		return KNOT_EMALF;
	}

	size_t pos = packet->parsed;

	dbg_packet_verb("Parsing next Additional RR (pos: %zu)...\n", pos);
	*rr = knot_packet_parse_rr(packet->wireformat, &pos, packet->size);
	if (*rr == NULL) {
		dbg_packet_verb("Failed to parse RR!\n");
		return KNOT_EMALF;
	}
	
	dbg_packet_detail("Parsed. Pos: %zu.\n", pos);

	packet->parsed = pos;
	// increment the number of answer RRSets, though there are no saved
	// in the packet; it is OK, because packet->answer is NULL
	++packet->ar_rrsets;
	++packet->parsed_ar;

	return KNOT_EOK;
}

/*----------------------------------------------------------------------------*/

size_t knot_packet_size(const knot_packet_t *packet)
{
	return packet->size;
}

/*----------------------------------------------------------------------------*/

size_t knot_packet_question_size(const knot_packet_t *packet)
{
	return (KNOT_WIRE_HEADER_SIZE + 4
	        + knot_dname_size(packet->question.qname));
}

/*----------------------------------------------------------------------------*/

size_t knot_packet_parsed(const knot_packet_t *packet)
{
	return packet->parsed;
}

/*----------------------------------------------------------------------------*/

int knot_packet_set_max_size(knot_packet_t *packet, int max_size)
{
	if (packet == NULL || max_size <= 0) {
		return KNOT_EINVAL;
	}

	if (packet->max_size < max_size) {
		// reallocate space for the wire format (and copy anything
		// that might have been there before
		uint8_t *wire_new = (uint8_t *)malloc(max_size);
		if (wire_new == NULL) {
			return KNOT_ENOMEM;
		}

		uint8_t *wire_old = packet->wireformat;

		memcpy(wire_new, packet->wireformat, packet->max_size);
		packet->wireformat = wire_new;

		if (packet->max_size > 0 && packet->free_wireformat) {
			free(wire_old);
		}

		packet->free_wireformat = 1;
	}

	// set max size
	packet->max_size = max_size;

	return KNOT_EOK;
}

/*----------------------------------------------------------------------------*/

uint16_t knot_packet_id(const knot_packet_t *packet)
{
	assert(packet != NULL);
	return packet->header.id;
}

/*----------------------------------------------------------------------------*/

void knot_packet_set_id(knot_packet_t *packet, uint16_t id)
{
	if (packet == NULL) {
		return;
	}

	packet->header.id = id;
}

/*----------------------------------------------------------------------------*/

void knot_packet_set_random_id(knot_packet_t *packet)
{
	if (packet == NULL) {
		return;
	}

	packet->header.id = knot_random_id();
}

/*----------------------------------------------------------------------------*/

uint8_t knot_packet_opcode(const knot_packet_t *packet)
{
	assert(packet != NULL);
	return knot_wire_flags_get_opcode(packet->header.flags1);
}

/*----------------------------------------------------------------------------*/

const knot_dname_t *knot_packet_qname(const knot_packet_t *packet)
{
	if (packet == NULL) {
		return NULL;
	}

	return packet->question.qname;
}

/*----------------------------------------------------------------------------*/

uint16_t knot_packet_qtype(const knot_packet_t *packet)
{
	assert(packet != NULL);
	return packet->question.qtype;
}

/*----------------------------------------------------------------------------*/

void knot_packet_set_qtype(knot_packet_t *packet, knot_rr_type_t qtype)
{
	assert(packet != NULL);
	packet->question.qtype = qtype;
}

/*----------------------------------------------------------------------------*/

uint16_t knot_packet_qclass(const knot_packet_t *packet)
{
	assert(packet != NULL);
	return packet->question.qclass;
}

/*----------------------------------------------------------------------------*/

int knot_packet_is_query(const knot_packet_t *packet)
{
	if (packet == NULL) {
		return KNOT_EINVAL;
	}

	return (knot_wire_flags_get_qr(packet->header.flags1) == 0);
}

/*----------------------------------------------------------------------------*/

const knot_packet_t *knot_packet_query(const knot_packet_t *packet)
{
	if (packet == NULL) {
		return NULL;
	}

	return packet->query;
}

/*----------------------------------------------------------------------------*/

int knot_packet_rcode(const knot_packet_t *packet)
{
	if (packet == NULL) {
		return KNOT_EINVAL;
	}
	
	return knot_wire_flags_get_rcode(packet->header.flags2);
}

/*----------------------------------------------------------------------------*/

int knot_packet_tc(const knot_packet_t *packet)
{
	if (packet == NULL) {
		return KNOT_EINVAL;
	}
	
	return knot_wire_flags_get_tc(packet->header.flags1);
}

/*----------------------------------------------------------------------------*/

int knot_packet_qdcount(const knot_packet_t *packet)
{
	if (packet == NULL) {
		return KNOT_EINVAL;
	}

	return packet->header.qdcount;
}

/*----------------------------------------------------------------------------*/

int knot_packet_ancount(const knot_packet_t *packet)
{
	if (packet == NULL) {
		return KNOT_EINVAL;
	}

	return packet->header.ancount;
}

/*----------------------------------------------------------------------------*/

int knot_packet_nscount(const knot_packet_t *packet)
{
	if (packet == NULL) {
		return KNOT_EINVAL;
	}

	return packet->header.nscount;
}

/*----------------------------------------------------------------------------*/

int knot_packet_arcount(const knot_packet_t *packet)
{
	if (packet == NULL) {
		return KNOT_EINVAL;
	}

	return packet->header.arcount;
}

/*----------------------------------------------------------------------------*/

void knot_packet_set_tsig_size(knot_packet_t *packet, size_t tsig_size)
{
	packet->tsig_size = tsig_size;
}

/*----------------------------------------------------------------------------*/

const knot_rrset_t *knot_packet_tsig(const knot_packet_t *packet)
{
	return packet->tsig_rr;
}

/*----------------------------------------------------------------------------*/

void knot_packet_set_tsig(knot_packet_t *packet, const knot_rrset_t *tsig_rr)
{
	packet->tsig_rr = (knot_rrset_t *)tsig_rr;
}

/*----------------------------------------------------------------------------*/

short knot_packet_answer_rrset_count(const knot_packet_t *packet)
{
	if (packet == NULL) {
		return KNOT_EINVAL;
	}

	return packet->an_rrsets;
}

/*----------------------------------------------------------------------------*/

short knot_packet_authority_rrset_count(const knot_packet_t *packet)
{
	if (packet == NULL) {
		return KNOT_EINVAL;
	}

	return packet->ns_rrsets;
}

/*----------------------------------------------------------------------------*/

short knot_packet_additional_rrset_count(const knot_packet_t *packet)
{
	if (packet == NULL) {
		return KNOT_EINVAL;
	}

	return packet->ar_rrsets;
}

/*----------------------------------------------------------------------------*/

const knot_rrset_t *knot_packet_answer_rrset(
	const knot_packet_t *packet, short pos)
{
	if (packet == NULL || pos > packet->an_rrsets) {
		return NULL;
	}

	return packet->answer[pos];
}

/*----------------------------------------------------------------------------*/

const knot_rrset_t *knot_packet_authority_rrset(
	const knot_packet_t *packet, short pos)
{
	if (packet == NULL || pos > packet->ns_rrsets) {
		return NULL;
	}

	return packet->authority[pos];
}

/*----------------------------------------------------------------------------*/

const knot_rrset_t *knot_packet_additional_rrset(
    const knot_packet_t *packet, short pos)
{
	if (packet == NULL || pos > packet->ar_rrsets) {
		return NULL;
	}

	return packet->additional[pos];
}

/*----------------------------------------------------------------------------*/

int knot_packet_contains(const knot_packet_t *packet,
                           const knot_rrset_t *rrset,
                           knot_rrset_compare_type_t cmp)
{
	if (packet == NULL || rrset == NULL) {
		return KNOT_EINVAL;
	}

	for (int i = 0; i < packet->an_rrsets; ++i) {
		if (knot_rrset_match(packet->answer[i], rrset, cmp)) {
			return 1;
		}
	}

	for (int i = 0; i < packet->ns_rrsets; ++i) {
		if (knot_rrset_match(packet->authority[i], rrset, cmp)) {
			return 1;
		}
	}

	for (int i = 0; i < packet->ar_rrsets; ++i) {
		if (knot_rrset_match(packet->additional[i], rrset, cmp)) {
			return 1;
		}
	}

	return 0;
}

/*----------------------------------------------------------------------------*/

int knot_packet_add_tmp_rrset(knot_packet_t *packet,
                                knot_rrset_t *tmp_rrset)
{
	if (packet == NULL || tmp_rrset == NULL) {
		return KNOT_EINVAL;
	}

	if (packet->tmp_rrsets_count == packet->tmp_rrsets_max
	    && knot_packet_realloc_rrsets(&packet->tmp_rrsets,
			&packet->tmp_rrsets_max,
			DEFAULT_RRSET_COUNT(TMP_RRSETS, packet),
			STEP_TMP_RRSETS) != KNOT_EOK) {
		return KNOT_ENOMEM;
	}

	packet->tmp_rrsets[packet->tmp_rrsets_count++] = tmp_rrset;
	dbg_packet_detail("Current tmp RRSets count: %d, max count: %d\n",
	                  packet->tmp_rrsets_count, packet->tmp_rrsets_max);

	return KNOT_EOK;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief Frees all temporary RRSets stored in the response structure.
 *
 * \param resp Response structure to free the temporary RRSets from.
 */
void knot_packet_free_tmp_rrsets(knot_packet_t *pkt)
{
	if (pkt == NULL) {
		return;
	}

	for (int i = 0; i < pkt->tmp_rrsets_count; ++i) {
dbg_packet_exec(
		char *name = knot_dname_to_str(
			(((knot_rrset_t **)(pkt->tmp_rrsets))[i])->owner);
		dbg_packet_verb("Freeing tmp RRSet on ptr: %p (ptr to ptr:"
		       " %p, type: %s, owner: %s)\n",
		       (((knot_rrset_t **)(pkt->tmp_rrsets))[i]),
		       &(((knot_rrset_t **)(pkt->tmp_rrsets))[i]),
		       knot_rrtype_to_string(
		            (((knot_rrset_t **)(pkt->tmp_rrsets))[i])->type),
		       name);
		free(name);
);
		// TODO: this is quite ugly, but better than copying whole
		// function (for reallocating rrset array)
		knot_rrset_deep_free(
			&(((knot_rrset_t **)(pkt->tmp_rrsets))[i]), 1, 1, 1);
	}
}

/*----------------------------------------------------------------------------*/

void knot_packet_header_to_wire(const knot_header_t *header,
                                  uint8_t **pos, size_t *size)
{
	if (header == NULL || pos == NULL || *pos == NULL || size == NULL) {
		return;
	}

	knot_wire_set_id(*pos, header->id);
	knot_wire_set_flags1(*pos, header->flags1);
	knot_wire_set_flags2(*pos, header->flags2);
	knot_wire_set_qdcount(*pos, header->qdcount);
	knot_wire_set_ancount(*pos, header->ancount);
	knot_wire_set_nscount(*pos, header->nscount);
	knot_wire_set_arcount(*pos, header->arcount);

	*pos += KNOT_WIRE_HEADER_SIZE;
	*size += KNOT_WIRE_HEADER_SIZE;
}

/*----------------------------------------------------------------------------*/

int knot_packet_question_to_wire(knot_packet_t *packet)
{
	if (packet == NULL || packet->question.qname == NULL) {
		return KNOT_EINVAL;
	}

	if (packet->size > KNOT_WIRE_HEADER_SIZE) {
		return KNOT_ERROR;
	}

	// TODO: get rid of the numeric constants
	size_t qsize = 4 + knot_dname_size(packet->question.qname);
	if (qsize > packet->max_size - KNOT_WIRE_HEADER_SIZE) {
		return KNOT_ESPACE;
	}

	// create the wireformat of Question
	uint8_t *pos = packet->wireformat + KNOT_WIRE_HEADER_SIZE;
	memcpy(pos, knot_dname_name(packet->question.qname),
	       knot_dname_size(packet->question.qname));

	pos += knot_dname_size(packet->question.qname);
	knot_wire_write_u16(pos, packet->question.qtype);
	pos += 2;
	knot_wire_write_u16(pos, packet->question.qclass);

	packet->size += knot_dname_size(packet->question.qname) + 4;

	return KNOT_EOK;
}

/*----------------------------------------------------------------------------*/

int knot_packet_edns_to_wire(knot_packet_t *packet)
{
	if (packet == NULL) {
		return KNOT_EINVAL;
	}

	packet->size += knot_edns_to_wire(&packet->opt_rr,
	                                  packet->wireformat + packet->size,
	                                  packet->max_size - packet->size);

	packet->header.arcount += 1;

	return KNOT_EOK;
}

/*----------------------------------------------------------------------------*/

int knot_packet_to_wire(knot_packet_t *packet,
                          uint8_t **wire, size_t *wire_size)
{
	if (packet == NULL || wire == NULL || wire_size == NULL
	    || *wire != NULL) {
		return KNOT_EINVAL;
	}

	assert(packet->size <= packet->max_size);

	// if there are no additional RRSets, add EDNS OPT RR
	if (packet->header.arcount == 0
	    && packet->opt_rr.version != EDNS_NOT_SUPPORTED) {
	    knot_packet_edns_to_wire(packet);
	}

	// set QDCOUNT (in response it is already set, in query it is needed)
	knot_wire_set_qdcount(packet->wireformat, packet->header.qdcount);
	// set ANCOUNT to the packet
	knot_wire_set_ancount(packet->wireformat, packet->header.ancount);
	// set NSCOUNT to the packet
	knot_wire_set_nscount(packet->wireformat, packet->header.nscount);
	// set ARCOUNT to the packet
	knot_wire_set_arcount(packet->wireformat, packet->header.arcount);

	//assert(response->size == size);
	*wire = packet->wireformat;
	*wire_size = packet->size;

	return KNOT_EOK;
}

/*----------------------------------------------------------------------------*/

const uint8_t *knot_packet_wireformat(const knot_packet_t *packet)
{
	return packet->wireformat;
}

/*----------------------------------------------------------------------------*/

void knot_packet_free(knot_packet_t **packet)
{
	if (packet == NULL || *packet == NULL) {
		return;
	}

	// free temporary domain names
	dbg_packet("Freeing tmp RRSets...\n");
	knot_packet_free_tmp_rrsets(*packet);

	dbg_packet("Freeing copied dnames for compression...\n");
	for (int i = 0; i < (*packet)->compression.count; ++i) {
		if ((*packet)->compression.to_free[i]) {
			knot_dname_release(
			      (knot_dname_t *)(*packet)->compression.dnames[i]);
		}
	}

	/*! \note The above code will free the domain names pointed to by
	 *        the list of wildcard nodes. It should not matter, however.
	 */

	// check if some additional space was allocated for the packet
	dbg_packet("Freeing additional allocated space...\n");
	knot_packet_free_allocated_space(*packet);

	// free the space for wireformat
	if ((*packet)->wireformat != NULL && (*packet)->free_wireformat) {
		free((*packet)->wireformat);
	}

	// free EDNS options
	knot_edns_free_options(&(*packet)->opt_rr);

	dbg_packet("Freeing packet structure\n");
	free(*packet);
	*packet = NULL;
}

/*----------------------------------------------------------------------------*/
#ifdef KNOT_PACKET_DEBUG
static void knot_packet_dump_rrsets(const knot_rrset_t **rrsets,
                                      int count)
{
	assert((rrsets != NULL && *rrsets != NULL) || count < 1);

	for (int i = 0; i < count; ++i) {
		knot_rrset_dump(rrsets[i], 0);
	}
}
#endif
/*----------------------------------------------------------------------------*/

void knot_packet_dump(const knot_packet_t *packet)
{
	if (packet == NULL) {
		return;
	}

#ifdef KNOT_PACKET_DEBUG
	dbg_packet("DNS packet:\n-----------------------------\n");

	dbg_packet("\nHeader:\n");
	dbg_packet("  ID: %u\n", packet->header.id);
	dbg_packet("  FLAGS: %s %s %s %s %s %s %s\n",
	       knot_wire_flags_get_qr(packet->header.flags1) ? "qr" : "",
	       knot_wire_flags_get_aa(packet->header.flags1) ? "aa" : "",
	       knot_wire_flags_get_tc(packet->header.flags1) ? "tc" : "",
	       knot_wire_flags_get_rd(packet->header.flags1) ? "rd" : "",
	       knot_wire_flags_get_ra(packet->header.flags2) ? "ra" : "",
	       knot_wire_flags_get_ad(packet->header.flags2) ? "ad" : "",
	       knot_wire_flags_get_cd(packet->header.flags2) ? "cd" : "");
	dbg_packet("  RCODE: %u\n", knot_wire_flags_get_rcode(
	                   packet->header.flags2));
	dbg_packet("  OPCODE: %u\n", knot_wire_flags_get_opcode(
	                   packet->header.flags1));
	dbg_packet("  QDCOUNT: %u\n", packet->header.qdcount);
	dbg_packet("  ANCOUNT: %u\n", packet->header.ancount);
	dbg_packet("  NSCOUNT: %u\n", packet->header.nscount);
	dbg_packet("  ARCOUNT: %u\n", packet->header.arcount);

	if (knot_packet_qdcount(packet) > 0) {
		dbg_packet("\nQuestion:\n");
		char *qname = knot_dname_to_str(packet->question.qname);
		dbg_packet("  QNAME: %s\n", qname);
		free(qname);
		dbg_packet("  QTYPE: %u (%s)\n", packet->question.qtype,
		       knot_rrtype_to_string(packet->question.qtype));
		dbg_packet("  QCLASS: %u (%s)\n", packet->question.qclass,
		       knot_rrclass_to_string(packet->question.qclass));
	}

	dbg_packet("\nAnswer RRSets:\n");
	knot_packet_dump_rrsets(packet->answer, packet->an_rrsets);
	dbg_packet("\nAuthority RRSets:\n");
	knot_packet_dump_rrsets(packet->authority, packet->ns_rrsets);
	dbg_packet("\nAdditional RRSets:\n");
	knot_packet_dump_rrsets(packet->additional, packet->ar_rrsets);

	/*! \todo Dumping of Answer, Authority and Additional sections. */

	dbg_packet("\nEDNS:\n");
	dbg_packet("  Version: %u\n", packet->opt_rr.version);
	dbg_packet("  Payload: %u\n", packet->opt_rr.payload);
	dbg_packet("  Extended RCODE: %u\n",
	                      packet->opt_rr.ext_rcode);

	dbg_packet("\nPacket size: %zu\n", packet->size);
	dbg_packet("\n-----------------------------\n");
#endif
}