1/*	$NetBSD: wire_test.c,v 1.9 2024/02/21 22:51:13 christos Exp $	*/
2
3/*
4 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
5 *
6 * SPDX-License-Identifier: MPL-2.0
7 *
8 * This Source Code Form is subject to the terms of the Mozilla Public
9 * License, v. 2.0. If a copy of the MPL was not distributed with this
10 * file, you can obtain one at https://mozilla.org/MPL/2.0/.
11 *
12 * See the COPYRIGHT file distributed with this work for additional
13 * information regarding copyright ownership.
14 */
15
16#include <inttypes.h>
17#include <stdbool.h>
18#include <stdlib.h>
19
20#include <isc/buffer.h>
21#include <isc/commandline.h>
22#include <isc/file.h>
23#include <isc/mem.h>
24#include <isc/print.h>
25#include <isc/result.h>
26#include <isc/string.h>
27#include <isc/util.h>
28
29#include <dns/message.h>
30
31int parseflags = 0;
32isc_mem_t *mctx = NULL;
33bool printmemstats = false;
34bool dorender = false;
35
36static void
37process_message(isc_buffer_t *source);
38
39static isc_result_t
40printmessage(dns_message_t *msg);
41
42static void
43CHECKRESULT(isc_result_t result, const char *msg) {
44	if (result != ISC_R_SUCCESS) {
45		printf("%s: %s\n", msg, isc_result_totext(result));
46
47		exit(1);
48	}
49}
50
51static int
52fromhex(char c) {
53	if (c >= '0' && c <= '9') {
54		return (c - '0');
55	} else if (c >= 'a' && c <= 'f') {
56		return (c - 'a' + 10);
57	} else if (c >= 'A' && c <= 'F') {
58		return (c - 'A' + 10);
59	}
60
61	fprintf(stderr, "bad input format: %02x\n", c);
62	exit(3);
63}
64
65static void
66usage(void) {
67	fprintf(stderr, "wire_test [-b] [-d] [-p] [-r] [-s]\n");
68	fprintf(stderr, "          [-m {usage|trace|record|size|mctx}]\n");
69	fprintf(stderr, "          [filename]\n\n");
70	fprintf(stderr, "\t-b\tBest-effort parsing (ignore some errors)\n");
71	fprintf(stderr, "\t-d\tRead input as raw binary data\n");
72	fprintf(stderr, "\t-p\tPreserve order of the records in messages\n");
73	fprintf(stderr, "\t-r\tAfter parsing, re-render the message\n");
74	fprintf(stderr, "\t-s\tPrint memory statistics\n");
75	fprintf(stderr, "\t-t\tTCP mode - ignore the first 2 bytes\n");
76}
77
78static isc_result_t
79printmessage(dns_message_t *msg) {
80	isc_buffer_t b;
81	char *buf = NULL;
82	int len = 1024;
83	isc_result_t result = ISC_R_SUCCESS;
84
85	do {
86		buf = isc_mem_get(mctx, len);
87
88		isc_buffer_init(&b, buf, len);
89		result = dns_message_totext(msg, &dns_master_style_debug, 0,
90					    &b);
91		if (result == ISC_R_NOSPACE) {
92			isc_mem_put(mctx, buf, len);
93			len *= 2;
94		} else if (result == ISC_R_SUCCESS) {
95			printf("%.*s\n", (int)isc_buffer_usedlength(&b), buf);
96		}
97	} while (result == ISC_R_NOSPACE);
98
99	if (buf != NULL) {
100		isc_mem_put(mctx, buf, len);
101	}
102
103	return (result);
104}
105
106int
107main(int argc, char *argv[]) {
108	isc_buffer_t *input = NULL;
109	bool need_close = false;
110	bool tcp = false;
111	bool rawdata = false;
112	isc_result_t result;
113	uint8_t c;
114	FILE *f;
115	int ch;
116
117#define CMDLINE_FLAGS "bdm:prst"
118	/*
119	 * Process memory debugging argument first.
120	 */
121	while ((ch = isc_commandline_parse(argc, argv, CMDLINE_FLAGS)) != -1) {
122		switch (ch) {
123		case 'm':
124			if (strcasecmp(isc_commandline_argument, "record") == 0)
125			{
126				isc_mem_debugging |= ISC_MEM_DEBUGRECORD;
127			}
128			if (strcasecmp(isc_commandline_argument, "trace") == 0)
129			{
130				isc_mem_debugging |= ISC_MEM_DEBUGTRACE;
131			}
132			if (strcasecmp(isc_commandline_argument, "usage") == 0)
133			{
134				isc_mem_debugging |= ISC_MEM_DEBUGUSAGE;
135			}
136			break;
137		default:
138			break;
139		}
140	}
141	isc_commandline_reset = true;
142
143	isc_mem_create(&mctx);
144
145	while ((ch = isc_commandline_parse(argc, argv, CMDLINE_FLAGS)) != -1) {
146		switch (ch) {
147		case 'b':
148			parseflags |= DNS_MESSAGEPARSE_BESTEFFORT;
149			break;
150		case 'd':
151			rawdata = true;
152			break;
153		case 'm':
154			break;
155		case 'p':
156			parseflags |= DNS_MESSAGEPARSE_PRESERVEORDER;
157			break;
158		case 'r':
159			dorender = true;
160			break;
161		case 's':
162			printmemstats = true;
163			break;
164		case 't':
165			tcp = true;
166			break;
167		default:
168			usage();
169			exit(1);
170		}
171	}
172
173	argc -= isc_commandline_index;
174	argv += isc_commandline_index;
175
176	if (argc >= 1) {
177		f = fopen(argv[0], "r");
178		if (f == NULL) {
179			fprintf(stderr, "%s: fopen failed\n", argv[0]);
180			exit(1);
181		}
182		need_close = true;
183	} else {
184		f = stdin;
185	}
186
187	isc_buffer_allocate(mctx, &input, 64 * 1024);
188
189	if (rawdata) {
190		while (fread(&c, 1, 1, f) != 0) {
191			result = isc_buffer_reserve(&input, 1);
192			RUNTIME_CHECK(result == ISC_R_SUCCESS);
193			isc_buffer_putuint8(input, (uint8_t)c);
194		}
195	} else {
196		char s[BUFSIZ];
197
198		while (fgets(s, sizeof(s), f) != NULL) {
199			char *rp = s, *wp = s;
200			size_t i, len = 0;
201
202			while (*rp != '\0') {
203				if (*rp == '#') {
204					break;
205				}
206				if (*rp != ' ' && *rp != '\t' && *rp != '\r' &&
207				    *rp != '\n')
208				{
209					*wp++ = *rp;
210					len++;
211				}
212				rp++;
213			}
214			if (len == 0U) {
215				continue;
216			}
217			if (len % 2 != 0U) {
218				fprintf(stderr, "bad input format: %lu\n",
219					(unsigned long)len);
220				exit(1);
221			}
222
223			rp = s;
224			for (i = 0; i < len; i += 2) {
225				c = fromhex(*rp++);
226				c *= 16;
227				c += fromhex(*rp++);
228				result = isc_buffer_reserve(&input, 1);
229				RUNTIME_CHECK(result == ISC_R_SUCCESS);
230				isc_buffer_putuint8(input, (uint8_t)c);
231			}
232		}
233	}
234
235	if (need_close) {
236		fclose(f);
237	}
238
239	if (tcp) {
240		while (isc_buffer_remaininglength(input) != 0) {
241			unsigned int tcplen;
242
243			if (isc_buffer_remaininglength(input) < 2) {
244				fprintf(stderr, "premature end of packet\n");
245				exit(1);
246			}
247			tcplen = isc_buffer_getuint16(input);
248
249			if (isc_buffer_remaininglength(input) < tcplen) {
250				fprintf(stderr, "premature end of packet\n");
251				exit(1);
252			}
253			process_message(input);
254		}
255	} else {
256		process_message(input);
257	}
258
259	isc_buffer_free(&input);
260
261	if (printmemstats) {
262		isc_mem_stats(mctx, stdout);
263	}
264	isc_mem_destroy(&mctx);
265
266	return (0);
267}
268
269static void
270process_message(isc_buffer_t *source) {
271	dns_message_t *message;
272	isc_result_t result;
273	int i;
274
275	message = NULL;
276	dns_message_create(mctx, DNS_MESSAGE_INTENTPARSE, &message);
277
278	result = dns_message_parse(message, source, parseflags);
279	if (result == DNS_R_RECOVERABLE) {
280		result = ISC_R_SUCCESS;
281	}
282	CHECKRESULT(result, "dns_message_parse failed");
283
284	result = printmessage(message);
285	CHECKRESULT(result, "printmessage() failed");
286
287	if (printmemstats) {
288		isc_mem_stats(mctx, stdout);
289	}
290
291	if (dorender) {
292		unsigned char b2[65535];
293		isc_buffer_t buffer;
294		dns_compress_t cctx;
295
296		isc_buffer_init(&buffer, b2, sizeof(b2));
297
298		/*
299		 * XXXMLG
300		 * Changing this here is a hack, and should not be done in
301		 * reasonable application code, ever.
302		 */
303		message->from_to_wire = DNS_MESSAGE_INTENTRENDER;
304
305		for (i = 0; i < DNS_SECTION_MAX; i++) {
306			message->counts[i] = 0; /* Another hack XXX */
307		}
308
309		result = dns_compress_init(&cctx, -1, mctx);
310		CHECKRESULT(result, "dns_compress_init() failed");
311
312		result = dns_message_renderbegin(message, &cctx, &buffer);
313		CHECKRESULT(result, "dns_message_renderbegin() failed");
314
315		result = dns_message_rendersection(message,
316						   DNS_SECTION_QUESTION, 0);
317		CHECKRESULT(result, "dns_message_rendersection(QUESTION) "
318				    "failed");
319
320		result = dns_message_rendersection(message, DNS_SECTION_ANSWER,
321						   0);
322		CHECKRESULT(result, "dns_message_rendersection(ANSWER) failed");
323
324		result = dns_message_rendersection(message,
325						   DNS_SECTION_AUTHORITY, 0);
326		CHECKRESULT(result, "dns_message_rendersection(AUTHORITY) "
327				    "failed");
328
329		result = dns_message_rendersection(message,
330						   DNS_SECTION_ADDITIONAL, 0);
331		CHECKRESULT(result, "dns_message_rendersection(ADDITIONAL) "
332				    "failed");
333
334		dns_message_renderend(message);
335
336		dns_compress_invalidate(&cctx);
337
338		message->from_to_wire = DNS_MESSAGE_INTENTPARSE;
339		dns_message_detach(&message);
340
341		printf("Message rendered.\n");
342		if (printmemstats) {
343			isc_mem_stats(mctx, stdout);
344		}
345
346		dns_message_create(mctx, DNS_MESSAGE_INTENTPARSE, &message);
347
348		result = dns_message_parse(message, &buffer, parseflags);
349		CHECKRESULT(result, "dns_message_parse failed");
350
351		result = printmessage(message);
352		CHECKRESULT(result, "printmessage() failed");
353	}
354	dns_message_detach(&message);
355}
356