xref: /freebsd/contrib/tcpdump/util-print.c (revision 0a7e5f1f02aad2ff5fff1c60f44c6975fd07e1d9)
1 /*
2  * Copyright (c) 1990, 1991, 1993, 1994, 1995, 1996, 1997
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that: (1) source code distributions
7  * retain the above copyright notice and this paragraph in its entirety, (2)
8  * distributions including binary code include the above copyright notice and
9  * this paragraph in its entirety in the documentation or other materials
10  * provided with the distribution, and (3) all advertising materials mentioning
11  * features or use of this software display the following acknowledgement:
12  * ``This product includes software developed by the University of California,
13  * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
14  * the University nor the names of its contributors may be used to endorse
15  * or promote products derived from this software without specific prior
16  * written permission.
17  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
18  * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
19  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
20  */
21 
22 /*
23  * txtproto_print() derived from original code by Hannes Gredler
24  * (hannes@gredler.at):
25  *
26  * Redistribution and use in source and binary forms, with or without
27  * modification, are permitted provided that: (1) source code
28  * distributions retain the above copyright notice and this paragraph
29  * in its entirety, and (2) distributions including binary code include
30  * the above copyright notice and this paragraph in its entirety in
31  * the documentation or other materials provided with the distribution.
32  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND
33  * WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT
34  * LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
35  * FOR A PARTICULAR PURPOSE.
36  */
37 
38 #include <config.h>
39 
40 #include "netdissect-stdinc.h"
41 
42 #include <sys/stat.h>
43 
44 #include <stdio.h>
45 #include <stdarg.h>
46 #include <stdlib.h>
47 #include <string.h>
48 
49 #include "netdissect-ctype.h"
50 
51 #include "netdissect.h"
52 #include "extract.h"
53 #include "ascii_strcasecmp.h"
54 #include "timeval-operations.h"
55 
56 #define TOKBUFSIZE 128
57 
58 enum date_flag { WITHOUT_DATE = 0, WITH_DATE = 1 };
59 enum time_flag { UTC_TIME = 0, LOCAL_TIME = 1 };
60 
61 /*
62  * Print out a character, filtering out the non-printable ones
63  */
64 void
fn_print_char(netdissect_options * ndo,u_char c)65 fn_print_char(netdissect_options *ndo, u_char c)
66 {
67 	if (!ND_ISASCII(c)) {
68 		c = ND_TOASCII(c);
69 		ND_PRINT("M-");
70 	}
71 	if (!ND_ASCII_ISPRINT(c)) {
72 		c ^= 0x40;	/* DEL to ?, others to alpha */
73 		ND_PRINT("^");
74 	}
75 	ND_PRINT("%c", c);
76 }
77 
78 /*
79  * Print a null-terminated string, filtering out non-printable characters.
80  * DON'T USE IT with a pointer on the packet buffer because there is no
81  * truncation check. For this use, see the nd_printX() functions below.
82  */
83 void
fn_print_str(netdissect_options * ndo,const u_char * s)84 fn_print_str(netdissect_options *ndo, const u_char *s)
85 {
86 	while (*s != '\0') {
87 		fn_print_char(ndo, *s);
88 		s++;
89        }
90 }
91 
92 /*
93  * Print out a null-terminated filename (or other ASCII string) from
94  * a fixed-length field in the packet buffer, or from what remains of
95  * the packet.
96  *
97  * n is the length of the fixed-length field, or the number of bytes
98  * remaining in the packet based on its on-the-network length.
99  *
100  * If ep is non-null, it should point just past the last captured byte
101  * of the packet, e.g. ndo->ndo_snapend.  If ep is NULL, we assume no
102  * truncation check, other than the checks of the field length/remaining
103  * packet data length, is needed.
104  *
105  * Return the number of bytes of string processed, including the
106  * terminating null, if not truncated; as the terminating null is
107  * included in the count, and as there must be a terminating null,
108  * this will always be non-zero.  Return 0 if truncated.
109  */
110 u_int
nd_printztn(netdissect_options * ndo,const u_char * s,u_int n,const u_char * ep)111 nd_printztn(netdissect_options *ndo,
112          const u_char *s, u_int n, const u_char *ep)
113 {
114 	u_int bytes;
115 	u_char c;
116 
117 	bytes = 0;
118 	for (;;) {
119 		if (n == 0 || (ep != NULL && s >= ep)) {
120 			/*
121 			 * Truncated.  This includes "no null before we
122 			 * got to the end of the fixed-length buffer or
123 			 * the end of the packet".
124 			 *
125 			 * XXX - BOOTP says "null-terminated", which
126 			 * means the maximum length of the string, in
127 			 * bytes, is 1 less than the size of the buffer,
128 			 * as there must always be a terminating null.
129 			 */
130 			bytes = 0;
131 			break;
132 		}
133 
134 		c = GET_U_1(s);
135 		s++;
136 		bytes++;
137 		n--;
138 		if (c == '\0') {
139 			/* End of string */
140 			break;
141 		}
142 		fn_print_char(ndo, c);
143 	}
144 	return(bytes);
145 }
146 
147 /*
148  * Print out a counted filename (or other ASCII string), part of
149  * the packet buffer.
150  * If ep is NULL, assume no truncation check is needed.
151  * Return true if truncated.
152  * Stop at ep (if given) or after n bytes, whichever is first.
153  */
154 int
nd_printn(netdissect_options * ndo,const u_char * s,u_int n,const u_char * ep)155 nd_printn(netdissect_options *ndo,
156           const u_char *s, u_int n, const u_char *ep)
157 {
158 	u_char c;
159 
160 	while (n > 0 && (ep == NULL || s < ep)) {
161 		n--;
162 		c = GET_U_1(s);
163 		s++;
164 		fn_print_char(ndo, c);
165 	}
166 	return (n == 0) ? 0 : 1;
167 }
168 
169 /*
170  * Print a counted filename (or other ASCII string), part of
171  * the packet buffer, filtering out non-printable characters.
172  * Stop if truncated (via GET_U_1/longjmp) or after n bytes,
173  * whichever is first.
174  * The suffix comes from: j:longJmp, n:after N bytes.
175  */
176 void
nd_printjn(netdissect_options * ndo,const u_char * s,u_int n)177 nd_printjn(netdissect_options *ndo, const u_char *s, u_int n)
178 {
179 	while (n > 0) {
180 		fn_print_char(ndo, GET_U_1(s));
181 		n--;
182 		s++;
183 	}
184 }
185 
186 /*
187  * Print a null-padded filename (or other ASCII string), part of
188  * the packet buffer, filtering out non-printable characters.
189  * Stop if truncated (via GET_U_1/longjmp) or after n bytes or before
190  * the null char, whichever occurs first.
191  * The suffix comes from: j:longJmp, n:after N bytes, p:null-Padded.
192  */
193 void
nd_printjnp(netdissect_options * ndo,const u_char * s,u_int n)194 nd_printjnp(netdissect_options *ndo, const u_char *s, u_int n)
195 {
196 	u_char c;
197 
198 	while (n > 0) {
199 		c = GET_U_1(s);
200 		if (c == '\0')
201 			break;
202 		fn_print_char(ndo, c);
203 		n--;
204 		s++;
205 	}
206 }
207 
208 /*
209  * Print the timestamp .FRAC part (Microseconds/nanoseconds)
210  */
211 static void
ts_frac_print(netdissect_options * ndo,const struct timeval * tv)212 ts_frac_print(netdissect_options *ndo, const struct timeval *tv)
213 {
214 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
215 	switch (ndo->ndo_tstamp_precision) {
216 
217 	case PCAP_TSTAMP_PRECISION_MICRO:
218 		ND_PRINT(".%06u", (unsigned)tv->tv_usec);
219 		break;
220 
221 	case PCAP_TSTAMP_PRECISION_NANO:
222 		ND_PRINT(".%09u", (unsigned)tv->tv_usec);
223 		break;
224 
225 	default:
226 		ND_PRINT(".{unknown}");
227 		break;
228 	}
229 #else
230 	ND_PRINT(".%06u", (unsigned)tv->tv_usec);
231 #endif
232 }
233 
234 /*
235  * Print the timestamp as [YY:MM:DD] HH:MM:SS.FRAC.
236  *   if time_flag == LOCAL_TIME print local time else UTC/GMT time
237  *   if date_flag == WITH_DATE print YY:MM:DD before HH:MM:SS.FRAC
238  */
239 static void
ts_date_hmsfrac_print(netdissect_options * ndo,const struct timeval * tv,enum date_flag date_flag,enum time_flag time_flag)240 ts_date_hmsfrac_print(netdissect_options *ndo, const struct timeval *tv,
241 		      enum date_flag date_flag, enum time_flag time_flag)
242 {
243 	struct tm *tm;
244 	char timebuf[32];
245 	const char *timestr;
246 
247 	if (tv->tv_sec < 0) {
248 		ND_PRINT("[timestamp < 1970-01-01 00:00:00 UTC]");
249 		return;
250 	}
251 
252 	if (time_flag == LOCAL_TIME)
253 		tm = localtime(&tv->tv_sec);
254 	else
255 		tm = gmtime(&tv->tv_sec);
256 
257 	if (date_flag == WITH_DATE) {
258 		timestr = nd_format_time(timebuf, sizeof(timebuf),
259 		    "%Y-%m-%d %H:%M:%S", tm);
260 	} else {
261 		timestr = nd_format_time(timebuf, sizeof(timebuf),
262 		    "%H:%M:%S", tm);
263 	}
264 	ND_PRINT("%s", timestr);
265 
266 	ts_frac_print(ndo, tv);
267 }
268 
269 /*
270  * Print the timestamp - Unix timeval style, as SECS.FRAC.
271  */
272 static void
ts_unix_print(netdissect_options * ndo,const struct timeval * tv)273 ts_unix_print(netdissect_options *ndo, const struct timeval *tv)
274 {
275 	if (tv->tv_sec < 0) {
276 		ND_PRINT("[timestamp < 1970-01-01 00:00:00 UTC]");
277 		return;
278 	}
279 
280 	ND_PRINT("%u", (unsigned)tv->tv_sec);
281 	ts_frac_print(ndo, tv);
282 }
283 
284 /*
285  * Print the timestamp
286  */
287 void
ts_print(netdissect_options * ndo,const struct timeval * tvp)288 ts_print(netdissect_options *ndo,
289          const struct timeval *tvp)
290 {
291 	static struct timeval tv_ref;
292 	struct timeval tv_result;
293 	int negative_offset;
294 	int nano_prec;
295 
296 	switch (ndo->ndo_tflag) {
297 
298 	case 0: /* Default */
299 		ts_date_hmsfrac_print(ndo, tvp, WITHOUT_DATE, LOCAL_TIME);
300 		ND_PRINT(" ");
301 		break;
302 
303 	case 1: /* No time stamp */
304 		break;
305 
306 	case 2: /* Unix timeval style */
307 		ts_unix_print(ndo, tvp);
308 		ND_PRINT(" ");
309 		break;
310 
311 	case 3: /* Microseconds/nanoseconds since previous packet */
312         case 5: /* Microseconds/nanoseconds since first packet */
313 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
314 		switch (ndo->ndo_tstamp_precision) {
315 		case PCAP_TSTAMP_PRECISION_MICRO:
316 			nano_prec = 0;
317 			break;
318 		case PCAP_TSTAMP_PRECISION_NANO:
319 			nano_prec = 1;
320 			break;
321 		default:
322 			nano_prec = 0;
323 			break;
324 		}
325 #else
326 		nano_prec = 0;
327 #endif
328 		if (!(netdissect_timevalisset(&tv_ref)))
329 			tv_ref = *tvp; /* set timestamp for first packet */
330 
331 		negative_offset = netdissect_timevalcmp(tvp, &tv_ref, <);
332 		if (negative_offset)
333 			netdissect_timevalsub(&tv_ref, tvp, &tv_result, nano_prec);
334 		else
335 			netdissect_timevalsub(tvp, &tv_ref, &tv_result, nano_prec);
336 
337 		ND_PRINT((negative_offset ? "-" : " "));
338 		ts_date_hmsfrac_print(ndo, &tv_result, WITHOUT_DATE, UTC_TIME);
339 		ND_PRINT(" ");
340 
341                 if (ndo->ndo_tflag == 3)
342 			tv_ref = *tvp; /* set timestamp for previous packet */
343 		break;
344 
345 	case 4: /* Date + Default */
346 		ts_date_hmsfrac_print(ndo, tvp, WITH_DATE, LOCAL_TIME);
347 		ND_PRINT(" ");
348 		break;
349 	}
350 }
351 
352 /*
353  * Print an unsigned relative number of seconds (e.g. hold time, prune timer)
354  * in the form 5m1s.  This does no truncation, so 32230861 seconds
355  * is represented as 1y1w1d1h1m1s.
356  */
357 void
unsigned_relts_print(netdissect_options * ndo,uint32_t secs)358 unsigned_relts_print(netdissect_options *ndo,
359                      uint32_t secs)
360 {
361 	static const char *lengths[] = {"y", "w", "d", "h", "m", "s"};
362 	static const u_int seconds[] = {31536000, 604800, 86400, 3600, 60, 1};
363 	const char **l = lengths;
364 	const u_int *s = seconds;
365 
366 	if (secs == 0) {
367 		ND_PRINT("0s");
368 		return;
369 	}
370 	while (secs > 0) {
371 		if (secs >= *s) {
372 			ND_PRINT("%u%s", secs / *s, *l);
373 			secs -= (secs / *s) * *s;
374 		}
375 		s++;
376 		l++;
377 	}
378 }
379 
380 /*
381  * Print a signed relative number of seconds (e.g. hold time, prune timer)
382  * in the form 5m1s.  This does no truncation, so 32230861 seconds
383  * is represented as 1y1w1d1h1m1s.
384  */
385 void
signed_relts_print(netdissect_options * ndo,int32_t secs)386 signed_relts_print(netdissect_options *ndo,
387                    int32_t secs)
388 {
389 	if (secs < 0) {
390 		ND_PRINT("-");
391 		if (secs == INT32_MIN) {
392 			/*
393 			 * -2^31; you can't fit its absolute value into
394 			 * a 32-bit signed integer.
395 			 *
396 			 * Just directly pass said absolute value to
397 			 * unsigned_relts_print() directly.
398 			 *
399 			 * (XXX - does ISO C guarantee that -(-2^n),
400 			 * when calculated and cast to an n-bit unsigned
401 			 * integer type, will have the value 2^n?)
402 			 */
403 			unsigned_relts_print(ndo, 2147483648U);
404 		} else {
405 			/*
406 			 * We now know -secs will fit into an int32_t;
407 			 * negate it and pass that to unsigned_relts_print().
408 			 */
409 			unsigned_relts_print(ndo, -secs);
410 		}
411 		return;
412 	}
413 	unsigned_relts_print(ndo, secs);
414 }
415 
416 /*
417  * Format a struct tm with strftime().
418  * If the pointer to the struct tm is null, that means that the
419  * routine to convert a time_t to a struct tm failed; the localtime()
420  * and gmtime() in the Microsoft Visual Studio C library will fail,
421  * returning null, if the value is before the UNIX Epoch.
422  */
423 const char *
nd_format_time(char * buf,size_t bufsize,const char * format,const struct tm * timeptr)424 nd_format_time(char *buf, size_t bufsize, const char *format,
425          const struct tm *timeptr)
426 {
427 	if (timeptr != NULL) {
428 		if (strftime(buf, bufsize, format, timeptr) != 0)
429 			return (buf);
430 		else
431 			return ("[nd_format_time() buffer is too small]");
432 	} else
433 		return ("[localtime() or gmtime() couldn't convert the date and time]");
434 }
435 
436 /* Print the truncated string */
nd_print_trunc(netdissect_options * ndo)437 void nd_print_trunc(netdissect_options *ndo)
438 {
439 	ND_PRINT(" [|%s]", ndo->ndo_protocol);
440 }
441 
442 /* Print the protocol name */
nd_print_protocol(netdissect_options * ndo)443 void nd_print_protocol(netdissect_options *ndo)
444 {
445 	ND_PRINT("%s", ndo->ndo_protocol);
446 }
447 
448 /* Print the protocol name in caps (uppercases) */
nd_print_protocol_caps(netdissect_options * ndo)449 void nd_print_protocol_caps(netdissect_options *ndo)
450 {
451 	const char *p;
452         for (p = ndo->ndo_protocol; *p != '\0'; p++)
453                 ND_PRINT("%c", ND_ASCII_TOUPPER(*p));
454 }
455 
456 /* Print the invalid string */
nd_print_invalid(netdissect_options * ndo)457 void nd_print_invalid(netdissect_options *ndo)
458 {
459 	ND_PRINT(" (invalid)");
460 }
461 
462 /*
463  *  this is a generic routine for printing unknown data;
464  *  we pass on the linefeed plus indentation string to
465  *  get a proper output - returns 0 on error
466  */
467 
468 int
print_unknown_data(netdissect_options * ndo,const u_char * cp,const char * ident,u_int len)469 print_unknown_data(netdissect_options *ndo, const u_char *cp,
470                    const char *ident, u_int len)
471 {
472 	u_int len_to_print;
473 
474 	len_to_print = len;
475 	if (!ND_TTEST_LEN(cp, 0)) {
476 		ND_PRINT("%sDissector error: print_unknown_data called with pointer past end of packet",
477 		    ident);
478 		return(0);
479 	}
480 	if (ND_BYTES_AVAILABLE_AFTER(cp) < len_to_print)
481 		len_to_print = ND_BYTES_AVAILABLE_AFTER(cp);
482 	hex_print(ndo, ident, cp, len_to_print);
483 	return(1); /* everything is ok */
484 }
485 
486 /*
487  * Convert a token value to a string; use "fmt" if not found.
488  */
489 static const char *
tok2strbuf(const struct tok * lp,const char * fmt,u_int v,char * buf,size_t bufsize)490 tok2strbuf(const struct tok *lp, const char *fmt,
491 	   u_int v, char *buf, size_t bufsize)
492 {
493 	if (lp != NULL) {
494 		while (lp->s != NULL) {
495 			if (lp->v == v)
496 				return (lp->s);
497 			++lp;
498 		}
499 	}
500 	if (fmt == NULL)
501 		fmt = "#%d";
502 
503 	(void)snprintf(buf, bufsize, fmt, v);
504 	return (const char *)buf;
505 }
506 
507 /*
508  * Convert a token value to a string; use "fmt" if not found.
509  * Uses tok2strbuf() on one of four local static buffers of size TOKBUFSIZE
510  * in round-robin fashion.
511  */
512 const char *
tok2str(const struct tok * lp,const char * fmt,u_int v)513 tok2str(const struct tok *lp, const char *fmt,
514 	u_int v)
515 {
516 	static char buf[4][TOKBUFSIZE];
517 	static int idx = 0;
518 	char *ret;
519 
520 	ret = buf[idx];
521 	idx = (idx+1) & 3;
522 	return tok2strbuf(lp, fmt, v, ret, sizeof(buf[0]));
523 }
524 
525 /*
526  * Convert a bit token value to a string; use "fmt" if not found.
527  * this is useful for parsing bitfields, the output strings are separated
528  * if the s field is positive.
529  *
530  * A token matches iff it has one or more bits set and every bit that is set
531  * in the token is set in v. Consequently, a 0 token never matches.
532  */
533 static char *
bittok2str_internal(const struct tok * lp,const char * fmt,u_int v,const char * sep)534 bittok2str_internal(const struct tok *lp, const char *fmt,
535 	   u_int v, const char *sep)
536 {
537         static char buf[1024+1]; /* our string buffer */
538         char *bufp = buf;
539         size_t space_left = sizeof(buf), string_size;
540         const char * sepstr = "";
541 
542         while (lp != NULL && lp->s != NULL) {
543             if (lp->v && (v & lp->v) == lp->v) {
544                 /* ok we have found something */
545                 if (space_left <= 1)
546                     return (buf); /* only enough room left for NUL, if that */
547                 string_size = strlcpy(bufp, sepstr, space_left);
548                 if (string_size >= space_left)
549                     return (buf);    /* we ran out of room */
550                 bufp += string_size;
551                 space_left -= string_size;
552                 if (space_left <= 1)
553                     return (buf); /* only enough room left for NUL, if that */
554                 string_size = strlcpy(bufp, lp->s, space_left);
555                 if (string_size >= space_left)
556                     return (buf);    /* we ran out of room */
557                 bufp += string_size;
558                 space_left -= string_size;
559                 sepstr = sep;
560             }
561             lp++;
562         }
563 
564         if (bufp == buf)
565             /* bummer - lets print the "unknown" message as advised in the fmt string if we got one */
566             (void)snprintf(buf, sizeof(buf), fmt == NULL ? "#%08x" : fmt, v);
567         return (buf);
568 }
569 
570 /*
571  * Convert a bit token value to a string; use "fmt" if not found.
572  * this is useful for parsing bitfields, the output strings are not separated.
573  */
574 char *
bittok2str_nosep(const struct tok * lp,const char * fmt,u_int v)575 bittok2str_nosep(const struct tok *lp, const char *fmt,
576 	   u_int v)
577 {
578     return (bittok2str_internal(lp, fmt, v, ""));
579 }
580 
581 /*
582  * Convert a bit token value to a string; use "fmt" if not found.
583  * this is useful for parsing bitfields, the output strings are comma separated.
584  */
585 char *
bittok2str(const struct tok * lp,const char * fmt,u_int v)586 bittok2str(const struct tok *lp, const char *fmt,
587 	   u_int v)
588 {
589     return (bittok2str_internal(lp, fmt, v, ", "));
590 }
591 
592 /*
593  * Convert a value to a string using an array; the macro
594  * tok2strary() in <netdissect.h> is the public interface to
595  * this function and ensures that the second argument is
596  * correct for bounds-checking.
597  */
598 const char *
tok2strary_internal(const char ** lp,int n,const char * fmt,int v)599 tok2strary_internal(const char **lp, int n, const char *fmt,
600 	int v)
601 {
602 	static char buf[TOKBUFSIZE];
603 
604 	if (v >= 0 && v < n && lp[v] != NULL)
605 		return lp[v];
606 	if (fmt == NULL)
607 		fmt = "#%d";
608 	(void)snprintf(buf, sizeof(buf), fmt, v);
609 	return (buf);
610 }
611 
612 const struct tok *
uint2tokary_internal(const struct uint_tokary dict[],const size_t size,const u_int val)613 uint2tokary_internal(const struct uint_tokary dict[], const size_t size,
614                      const u_int val)
615 {
616 	size_t i;
617 	/* Try a direct lookup before the full scan. */
618 	if (val < size && dict[val].uintval == val)
619 		return dict[val].tokary; /* OK if NULL */
620 	for (i = 0; i < size; i++)
621 		if (dict[i].uintval == val)
622 			return dict[i].tokary; /* OK if NULL */
623 	return NULL;
624 }
625 
626 /*
627  * Convert a 32-bit netmask to prefixlen if possible
628  * the function returns the prefix-len; if plen == -1
629  * then conversion was not possible;
630  */
631 
632 int
mask2plen(uint32_t mask)633 mask2plen(uint32_t mask)
634 {
635 	const uint32_t bitmasks[33] = {
636 		0x00000000,
637 		0x80000000, 0xc0000000, 0xe0000000, 0xf0000000,
638 		0xf8000000, 0xfc000000, 0xfe000000, 0xff000000,
639 		0xff800000, 0xffc00000, 0xffe00000, 0xfff00000,
640 		0xfff80000, 0xfffc0000, 0xfffe0000, 0xffff0000,
641 		0xffff8000, 0xffffc000, 0xffffe000, 0xfffff000,
642 		0xfffff800, 0xfffffc00, 0xfffffe00, 0xffffff00,
643 		0xffffff80, 0xffffffc0, 0xffffffe0, 0xfffffff0,
644 		0xfffffff8, 0xfffffffc, 0xfffffffe, 0xffffffff
645 	};
646 	int prefix_len = 32;
647 
648 	/* let's see if we can transform the mask into a prefixlen */
649 	while (prefix_len >= 0) {
650 		if (bitmasks[prefix_len] == mask)
651 			break;
652 		prefix_len--;
653 	}
654 	return (prefix_len);
655 }
656 
657 int
mask62plen(const u_char * mask)658 mask62plen(const u_char *mask)
659 {
660 	u_char bitmasks[9] = {
661 		0x00,
662 		0x80, 0xc0, 0xe0, 0xf0,
663 		0xf8, 0xfc, 0xfe, 0xff
664 	};
665 	int byte;
666 	int cidr_len = 0;
667 
668 	for (byte = 0; byte < 16; byte++) {
669 		u_int bits;
670 
671 		for (bits = 0; bits < (sizeof (bitmasks) / sizeof (bitmasks[0])); bits++) {
672 			if (mask[byte] == bitmasks[bits]) {
673 				cidr_len += bits;
674 				break;
675 			}
676 		}
677 
678 		if (mask[byte] != 0xff)
679 			break;
680 	}
681 	return (cidr_len);
682 }
683 
684 /*
685  * Routine to print out information for text-based protocols such as FTP,
686  * HTTP, SMTP, RTSP, SIP, ....
687  */
688 #define MAX_TOKEN	128
689 
690 /*
691  * Fetch a token from a packet, starting at the specified index,
692  * and return the length of the token.
693  *
694  * Returns 0 on error; yes, this is indistinguishable from an empty
695  * token, but an "empty token" isn't a valid token - it just means
696  * either a space character at the beginning of the line (this
697  * includes a blank line) or no more tokens remaining on the line.
698  */
699 static int
fetch_token(netdissect_options * ndo,const u_char * pptr,u_int idx,u_int len,u_char * tbuf,size_t tbuflen)700 fetch_token(netdissect_options *ndo, const u_char *pptr, u_int idx, u_int len,
701     u_char *tbuf, size_t tbuflen)
702 {
703 	size_t toklen = 0;
704 	u_char c;
705 
706 	for (; idx < len; idx++) {
707 		if (!ND_TTEST_1(pptr + idx)) {
708 			/* ran past end of captured data */
709 			return (0);
710 		}
711 		c = GET_U_1(pptr + idx);
712 		if (!ND_ISASCII(c)) {
713 			/* not an ASCII character */
714 			return (0);
715 		}
716 		if (c == ' ' || c == '\t' || c == '\r' || c == '\n') {
717 			/* end of token */
718 			break;
719 		}
720 		if (!ND_ASCII_ISPRINT(c)) {
721 			/* not part of a command token or response code */
722 			return (0);
723 		}
724 		if (toklen + 2 > tbuflen) {
725 			/* no room for this character and terminating '\0' */
726 			return (0);
727 		}
728 		tbuf[toklen] = c;
729 		toklen++;
730 	}
731 	if (toklen == 0) {
732 		/* no token */
733 		return (0);
734 	}
735 	tbuf[toklen] = '\0';
736 
737 	/*
738 	 * Skip past any white space after the token, until we see
739 	 * an end-of-line (CR or LF).
740 	 */
741 	for (; idx < len; idx++) {
742 		if (!ND_TTEST_1(pptr + idx)) {
743 			/* ran past end of captured data */
744 			break;
745 		}
746 		c = GET_U_1(pptr + idx);
747 		if (c == '\r' || c == '\n') {
748 			/* end of line */
749 			break;
750 		}
751 		if (!ND_ASCII_ISPRINT(c)) {
752 			/* not a printable ASCII character */
753 			break;
754 		}
755 		if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
756 			/* beginning of next token */
757 			break;
758 		}
759 	}
760 	return (idx);
761 }
762 
763 /*
764  * Scan a buffer looking for a line ending - LF or CR-LF.
765  * Return the index of the character after the line ending or 0 if
766  * we encounter a non-ASCII or non-printable character or don't find
767  * the line ending.
768  */
769 static u_int
print_txt_line(netdissect_options * ndo,const char * prefix,const u_char * pptr,u_int idx,u_int len)770 print_txt_line(netdissect_options *ndo, const char *prefix,
771 	       const u_char *pptr, u_int idx, u_int len)
772 {
773 	u_int startidx;
774 	u_int linelen;
775 	u_char c;
776 
777 	startidx = idx;
778 	while (idx < len) {
779 		c = GET_U_1(pptr + idx);
780 		if (c == '\n') {
781 			/*
782 			 * LF without CR; end of line.
783 			 * Skip the LF and print the line, with the
784 			 * exception of the LF.
785 			 */
786 			linelen = idx - startidx;
787 			idx++;
788 			goto print;
789 		} else if (c == '\r') {
790 			/* CR - any LF? */
791 			if ((idx+1) >= len) {
792 				/* not in this packet */
793 				return (0);
794 			}
795 			if (GET_U_1(pptr + idx + 1) == '\n') {
796 				/*
797 				 * CR-LF; end of line.
798 				 * Skip the CR-LF and print the line, with
799 				 * the exception of the CR-LF.
800 				 */
801 				linelen = idx - startidx;
802 				idx += 2;
803 				goto print;
804 			}
805 
806 			/*
807 			 * CR followed by something else; treat this
808 			 * as if it were binary data, and don't print
809 			 * it.
810 			 */
811 			return (0);
812 		} else if (!ND_ASCII_ISPRINT(c) && c != '\t') {
813 			/*
814 			 * Not a printable ASCII character and not a tab;
815 			 * treat this as if it were binary data, and
816 			 * don't print it.
817 			 */
818 			return (0);
819 		}
820 		idx++;
821 	}
822 
823 	/*
824 	 * All printable ASCII, but no line ending after that point
825 	 * in the buffer.
826 	 */
827 	linelen = idx - startidx;
828 	ND_PRINT("%s%.*s", prefix, (int)linelen, pptr + startidx);
829 	return (0);
830 
831 print:
832 	ND_PRINT("%s%.*s", prefix, (int)linelen, pptr + startidx);
833 	return (idx);
834 }
835 
836 /* Assign needed before calling txtproto_print(): ndo->ndo_protocol = "proto" */
837 void
txtproto_print(netdissect_options * ndo,const u_char * pptr,u_int len,const char ** cmds,u_int flags)838 txtproto_print(netdissect_options *ndo, const u_char *pptr, u_int len,
839 	       const char **cmds, u_int flags)
840 {
841 	u_int idx, eol;
842 	u_char token[MAX_TOKEN+1];
843 	const char *cmd;
844 	int print_this = 0;
845 
846 	if (cmds != NULL) {
847 		/*
848 		 * This protocol has more than just request and
849 		 * response lines; see whether this looks like a
850 		 * request or response and, if so, print it and,
851 		 * in verbose mode, print everything after it.
852 		 *
853 		 * This is for HTTP-like protocols, where we
854 		 * want to print requests and responses, but
855 		 * don't want to print continuations of request
856 		 * or response bodies in packets that don't
857 		 * contain the request or response line.
858 		 */
859 		idx = fetch_token(ndo, pptr, 0, len, token, sizeof(token));
860 		if (idx != 0) {
861 			/* Is this a valid request name? */
862 			while ((cmd = *cmds++) != NULL) {
863 				if (ascii_strcasecmp((const char *)token, cmd) == 0) {
864 					/* Yes. */
865 					print_this = 1;
866 					break;
867 				}
868 			}
869 
870 			/*
871 			 * No - is this a valid response code (3 digits)?
872 			 *
873 			 * Is this token the response code, or is the next
874 			 * token the response code?
875 			 */
876 			if (flags & RESP_CODE_SECOND_TOKEN) {
877 				/*
878 				 * Next token - get it.
879 				 */
880 				idx = fetch_token(ndo, pptr, idx, len, token,
881 				    sizeof(token));
882 			}
883 			if (idx != 0) {
884 				if (ND_ASCII_ISDIGIT(token[0]) && ND_ASCII_ISDIGIT(token[1]) &&
885 				    ND_ASCII_ISDIGIT(token[2]) && token[3] == '\0') {
886 					/* Yes. */
887 					print_this = 1;
888 				}
889 			}
890 		}
891 	} else {
892 		/*
893 		 * Either:
894 		 *
895 		 * 1) This protocol has only request and response lines
896 		 *    (e.g., FTP, where all the data goes over a different
897 		 *    connection); assume the payload is a request or
898 		 *    response.
899 		 *
900 		 * or
901 		 *
902 		 * 2) This protocol is just text, so that we should
903 		 *    always, at minimum, print the first line and,
904 		 *    in verbose mode, print all lines.
905 		 */
906 		print_this = 1;
907 	}
908 
909 	nd_print_protocol_caps(ndo);
910 
911 	if (print_this) {
912 		/*
913 		 * In non-verbose mode, just print the protocol, followed
914 		 * by the first line.
915 		 *
916 		 * In verbose mode, print lines as text until we run out
917 		 * of characters or see something that's not a
918 		 * printable-ASCII line.
919 		 */
920 		if (ndo->ndo_vflag) {
921 			/*
922 			 * We're going to print all the text lines in the
923 			 * request or response; just print the length
924 			 * on the first line of the output.
925 			 */
926 			ND_PRINT(", length: %u", len);
927 			for (idx = 0;
928 			    idx < len && (eol = print_txt_line(ndo, "\n\t", pptr, idx, len)) != 0;
929 			    idx = eol)
930 				;
931 		} else {
932 			/*
933 			 * Just print the first text line.
934 			 */
935 			print_txt_line(ndo, ": ", pptr, 0, len);
936 		}
937 	}
938 }
939 
940 #if (defined(__i386__) || defined(_M_IX86) || defined(__X86__) || defined(__x86_64__) || defined(_M_X64)) || \
941     (defined(__arm__) || defined(_M_ARM) || defined(__aarch64__)) || \
942     (defined(__m68k__) && (!defined(__mc68000__) && !defined(__mc68010__))) || \
943     (defined(__ppc__) || defined(__ppc64__) || defined(_M_PPC) || defined(_ARCH_PPC) || defined(_ARCH_PPC64)) || \
944     (defined(__s390__) || defined(__s390x__) || defined(__zarch__)) || \
945     defined(__vax__)
946 /*
947  * The processor natively handles unaligned loads, so just use memcpy()
948  * and memcmp(), to enable those optimizations.
949  *
950  * XXX - are those all the x86 tests we need?
951  * XXX - do we need to worry about ARMv1 through ARMv5, which didn't
952  * support unaligned loads, and, if so, do we need to worry about all
953  * of them, or just some of them, e.g. ARMv5?
954  * XXX - are those the only 68k tests we need not to generated
955  * unaligned accesses if the target is the 68000 or 68010?
956  * XXX - are there any tests we don't need, because some definitions are for
957  * compilers that also predefine the GCC symbols?
958  * XXX - do we need to test for both 32-bit and 64-bit versions of those
959  * architectures in all cases?
960  */
961 #else
962 /*
963  * The processor doesn't natively handle unaligned loads,
964  * and the compiler might "helpfully" optimize memcpy()
965  * and memcmp(), when handed pointers that would normally
966  * be properly aligned, into sequences that assume proper
967  * alignment.
968  *
969  * Do copies and compares of possibly-unaligned data by
970  * calling routines that wrap memcpy() and memcmp(), to
971  * prevent that optimization.
972  */
973 void
unaligned_memcpy(void * p,const void * q,size_t l)974 unaligned_memcpy(void *p, const void *q, size_t l)
975 {
976 	memcpy(p, q, l);
977 }
978 
979 /* As with memcpy(), so with memcmp(). */
980 int
unaligned_memcmp(const void * p,const void * q,size_t l)981 unaligned_memcmp(const void *p, const void *q, size_t l)
982 {
983 	return (memcmp(p, q, l));
984 }
985 #endif
986 
987