]> The Tcpdump Group git mirrors - tcpdump/blob - util.c
Give more details for --time-stamp-precision.
[tcpdump] / util.c
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 #define NETDISSECT_REWORKED
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26
27 #include <tcpdump-stdinc.h>
28
29 #include <sys/stat.h>
30
31 #ifdef HAVE_FCNTL_H
32 #include <fcntl.h>
33 #endif
34 #include <stdio.h>
35 #include <stdarg.h>
36 #include <stdlib.h>
37 #include <string.h>
38
39 #include "interface.h"
40
41 /*
42 * Print out a null-terminated filename (or other ascii string).
43 * If ep is NULL, assume no truncation check is needed.
44 * Return true if truncated.
45 */
46 int
47 fn_print(netdissect_options *ndo,
48 register const u_char *s, register const u_char *ep)
49 {
50 register int ret;
51 register u_char c;
52
53 ret = 1; /* assume truncated */
54 while (ep == NULL || s < ep) {
55 c = *s++;
56 if (c == '\0') {
57 ret = 0;
58 break;
59 }
60 if (!ND_ISASCII(c)) {
61 c = ND_TOASCII(c);
62 ND_PRINT((ndo, "M-"));
63 }
64 if (!ND_ISPRINT(c)) {
65 c ^= 0x40; /* DEL to ?, others to alpha */
66 ND_PRINT((ndo, "^"));
67 }
68 ND_PRINT((ndo, "%c", c));
69 }
70 return(ret);
71 }
72
73 /*
74 * Print out a counted filename (or other ascii string).
75 * If ep is NULL, assume no truncation check is needed.
76 * Return true if truncated.
77 */
78 int
79 fn_printn(netdissect_options *ndo,
80 register const u_char *s, register u_int n, register const u_char *ep)
81 {
82 register u_char c;
83
84 while (n > 0 && (ep == NULL || s < ep)) {
85 n--;
86 c = *s++;
87 if (!ND_ISASCII(c)) {
88 c = ND_TOASCII(c);
89 ND_PRINT((ndo, "M-"));
90 }
91 if (!ND_ISPRINT(c)) {
92 c ^= 0x40; /* DEL to ?, others to alpha */
93 ND_PRINT((ndo, "^"));
94 }
95 ND_PRINT((ndo, "%c", c));
96 }
97 return (n == 0) ? 0 : 1;
98 }
99
100 /*
101 * Print out a null-padded filename (or other ascii string).
102 * If ep is NULL, assume no truncation check is needed.
103 * Return true if truncated.
104 */
105 int
106 fn_printzp(netdissect_options *ndo,
107 register const u_char *s, register u_int n,
108 register const u_char *ep)
109 {
110 register int ret;
111 register u_char c;
112
113 ret = 1; /* assume truncated */
114 while (n > 0 && (ep == NULL || s < ep)) {
115 n--;
116 c = *s++;
117 if (c == '\0') {
118 ret = 0;
119 break;
120 }
121 if (!ND_ISASCII(c)) {
122 c = ND_TOASCII(c);
123 ND_PRINT((ndo, "M-"));
124 }
125 if (!ND_ISPRINT(c)) {
126 c ^= 0x40; /* DEL to ?, others to alpha */
127 ND_PRINT((ndo, "^"));
128 }
129 ND_PRINT((ndo, "%c", c));
130 }
131 return (n == 0) ? 0 : ret;
132 }
133
134 /*
135 * Format the timestamp
136 */
137 static char *
138 ts_format(netdissect_options *ndo, int sec, int usec)
139 {
140 static char buf[sizeof("00:00:00.000000000")];
141 const char *format = ndo->ndo_tstamp_precision == PCAP_TSTAMP_PRECISION_NANO ?
142 "%02d:%02d:%02d.%09u" : "%02d:%02d:%02d.%06u";
143
144 snprintf(buf, sizeof(buf), format,
145 sec / 3600, (sec % 3600) / 60, sec % 60, usec);
146
147 return buf;
148 }
149
150 /*
151 * Print the timestamp
152 */
153 void
154 ts_print(netdissect_options *ndo,
155 register const struct timeval *tvp)
156 {
157 register int s;
158 struct tm *tm;
159 time_t Time;
160 static unsigned b_sec;
161 static unsigned b_usec;
162 int d_usec;
163 int d_sec;
164
165 switch (ndo->ndo_tflag) {
166
167 case 0: /* Default */
168 s = (tvp->tv_sec + thiszone) % 86400;
169 ND_PRINT((ndo, "%s ", ts_format(ndo, s, tvp->tv_usec)));
170 break;
171
172 case 1: /* No time stamp */
173 break;
174
175 case 2: /* Unix timeval style */
176 ND_PRINT((ndo, "%u.%06u ",
177 (unsigned)tvp->tv_sec,
178 (unsigned)tvp->tv_usec));
179 break;
180
181 case 3: /* Microseconds since previous packet */
182 case 5: /* Microseconds since first packet */
183 if (b_sec == 0) {
184 /* init timestamp for first packet */
185 b_usec = tvp->tv_usec;
186 b_sec = tvp->tv_sec;
187 }
188
189 d_usec = tvp->tv_usec - b_usec;
190 d_sec = tvp->tv_sec - b_sec;
191
192 while (d_usec < 0) {
193 d_usec += 1000000;
194 d_sec--;
195 }
196
197 ND_PRINT((ndo, "%s ", ts_format(ndo, d_sec, d_usec)));
198
199 if (ndo->ndo_tflag == 3) { /* set timestamp for last packet */
200 b_sec = tvp->tv_sec;
201 b_usec = tvp->tv_usec;
202 }
203 break;
204
205 case 4: /* Default + Date*/
206 s = (tvp->tv_sec + thiszone) % 86400;
207 Time = (tvp->tv_sec + thiszone) - s;
208 tm = gmtime (&Time);
209 if (!tm)
210 ND_PRINT((ndo, "Date fail "));
211 else
212 ND_PRINT((ndo, "%04d-%02d-%02d %s ",
213 tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
214 ts_format(ndo, s, tvp->tv_usec)));
215 break;
216 }
217 }
218
219 /*
220 * Print a relative number of seconds (e.g. hold time, prune timer)
221 * in the form 5m1s. This does no truncation, so 32230861 seconds
222 * is represented as 1y1w1d1h1m1s.
223 */
224 void
225 relts_print(netdissect_options *ndo,
226 int secs)
227 {
228 static const char *lengths[] = {"y", "w", "d", "h", "m", "s"};
229 static const int seconds[] = {31536000, 604800, 86400, 3600, 60, 1};
230 const char **l = lengths;
231 const int *s = seconds;
232
233 if (secs == 0) {
234 ND_PRINT((ndo, "0s"));
235 return;
236 }
237 if (secs < 0) {
238 ND_PRINT((ndo, "-"));
239 secs = -secs;
240 }
241 while (secs > 0) {
242 if (secs >= *s) {
243 ND_PRINT((ndo, "%d%s", secs / *s, *l));
244 secs -= (secs / *s) * *s;
245 }
246 s++;
247 l++;
248 }
249 }
250
251 /*
252 * this is a generic routine for printing unknown data;
253 * we pass on the linefeed plus indentation string to
254 * get a proper output - returns 0 on error
255 */
256
257 int
258 print_unknown_data(netdissect_options *ndo, const u_char *cp,const char *ident,int len)
259 {
260 if (len < 0) {
261 ND_PRINT((ndo,"%sDissector error: print_unknown_data called with negative length",
262 ident));
263 return(0);
264 }
265 if (ndo->ndo_snapend - cp < len)
266 len = ndo->ndo_snapend - cp;
267 if (len < 0) {
268 ND_PRINT((ndo,"%sDissector error: print_unknown_data called with pointer past end of packet",
269 ident));
270 return(0);
271 }
272 hex_print(ndo, ident,cp,len);
273 return(1); /* everything is ok */
274 }
275
276 /*
277 * Convert a token value to a string; use "fmt" if not found.
278 */
279 const char *
280 tok2strbuf(register const struct tok *lp, register const char *fmt,
281 register u_int v, char *buf, size_t bufsize)
282 {
283 if (lp != NULL) {
284 while (lp->s != NULL) {
285 if (lp->v == v)
286 return (lp->s);
287 ++lp;
288 }
289 }
290 if (fmt == NULL)
291 fmt = "#%d";
292
293 (void)snprintf(buf, bufsize, fmt, v);
294 return (const char *)buf;
295 }
296
297 /*
298 * Convert a token value to a string; use "fmt" if not found.
299 */
300 const char *
301 tok2str(register const struct tok *lp, register const char *fmt,
302 register int v)
303 {
304 static char buf[4][128];
305 static int idx = 0;
306 char *ret;
307
308 ret = buf[idx];
309 idx = (idx+1) & 3;
310 return tok2strbuf(lp, fmt, v, ret, sizeof(buf[0]));
311 }
312
313 /*
314 * Convert a bit token value to a string; use "fmt" if not found.
315 * this is useful for parsing bitfields, the output strings are seperated
316 * if the s field is positive.
317 */
318 static char *
319 bittok2str_internal(register const struct tok *lp, register const char *fmt,
320 register int v, register int sep)
321 {
322 static char buf[256]; /* our stringbuffer */
323 int buflen=0;
324 register int rotbit; /* this is the bit we rotate through all bitpositions */
325 register int tokval;
326 const char * sepstr = "";
327
328 while (lp != NULL && lp->s != NULL) {
329 tokval=lp->v; /* load our first value */
330 rotbit=1;
331 while (rotbit != 0) {
332 /*
333 * lets AND the rotating bit with our token value
334 * and see if we have got a match
335 */
336 if (tokval == (v&rotbit)) {
337 /* ok we have found something */
338 buflen+=snprintf(buf+buflen, sizeof(buf)-buflen, "%s%s",
339 sepstr, lp->s);
340 sepstr = sep ? ", " : "";
341 break;
342 }
343 rotbit=rotbit<<1; /* no match - lets shift and try again */
344 }
345 lp++;
346 }
347
348 if (buflen == 0)
349 /* bummer - lets print the "unknown" message as advised in the fmt string if we got one */
350 (void)snprintf(buf, sizeof(buf), fmt == NULL ? "#%d" : fmt, v);
351 return (buf);
352 }
353
354 /*
355 * Convert a bit token value to a string; use "fmt" if not found.
356 * this is useful for parsing bitfields, the output strings are not seperated.
357 */
358 char *
359 bittok2str_nosep(register const struct tok *lp, register const char *fmt,
360 register int v)
361 {
362 return (bittok2str_internal(lp, fmt, v, 0));
363 }
364
365 /*
366 * Convert a bit token value to a string; use "fmt" if not found.
367 * this is useful for parsing bitfields, the output strings are comma seperated.
368 */
369 char *
370 bittok2str(register const struct tok *lp, register const char *fmt,
371 register int v)
372 {
373 return (bittok2str_internal(lp, fmt, v, 1));
374 }
375
376 /*
377 * Convert a value to a string using an array; the macro
378 * tok2strary() in <interface.h> is the public interface to
379 * this function and ensures that the second argument is
380 * correct for bounds-checking.
381 */
382 const char *
383 tok2strary_internal(register const char **lp, int n, register const char *fmt,
384 register int v)
385 {
386 static char buf[128];
387
388 if (v >= 0 && v < n && lp[v] != NULL)
389 return lp[v];
390 if (fmt == NULL)
391 fmt = "#%d";
392 (void)snprintf(buf, sizeof(buf), fmt, v);
393 return (buf);
394 }
395
396 /*
397 * Convert a 32-bit netmask to prefixlen if possible
398 * the function returns the prefix-len; if plen == -1
399 * then conversion was not possible;
400 */
401
402 int
403 mask2plen(uint32_t mask)
404 {
405 uint32_t bitmasks[33] = {
406 0x00000000,
407 0x80000000, 0xc0000000, 0xe0000000, 0xf0000000,
408 0xf8000000, 0xfc000000, 0xfe000000, 0xff000000,
409 0xff800000, 0xffc00000, 0xffe00000, 0xfff00000,
410 0xfff80000, 0xfffc0000, 0xfffe0000, 0xffff0000,
411 0xffff8000, 0xffffc000, 0xffffe000, 0xfffff000,
412 0xfffff800, 0xfffffc00, 0xfffffe00, 0xffffff00,
413 0xffffff80, 0xffffffc0, 0xffffffe0, 0xfffffff0,
414 0xfffffff8, 0xfffffffc, 0xfffffffe, 0xffffffff
415 };
416 int prefix_len = 32;
417
418 /* let's see if we can transform the mask into a prefixlen */
419 while (prefix_len >= 0) {
420 if (bitmasks[prefix_len] == mask)
421 break;
422 prefix_len--;
423 }
424 return (prefix_len);
425 }
426
427 #ifdef INET6
428 int
429 mask62plen(const u_char *mask)
430 {
431 u_char bitmasks[9] = {
432 0x00,
433 0x80, 0xc0, 0xe0, 0xf0,
434 0xf8, 0xfc, 0xfe, 0xff
435 };
436 int byte;
437 int cidr_len = 0;
438
439 for (byte = 0; byte < 16; byte++) {
440 u_int bits;
441
442 for (bits = 0; bits < (sizeof (bitmasks) / sizeof (bitmasks[0])); bits++) {
443 if (mask[byte] == bitmasks[bits]) {
444 cidr_len += bits;
445 break;
446 }
447 }
448
449 if (mask[byte] != 0xff)
450 break;
451 }
452 return (cidr_len);
453 }
454 #endif /* INET6 */
455
456 /* VARARGS */
457 void
458 error(const char *fmt, ...)
459 {
460 va_list ap;
461
462 (void)fprintf(stderr, "%s: ", program_name);
463 va_start(ap, fmt);
464 (void)vfprintf(stderr, fmt, ap);
465 va_end(ap);
466 if (*fmt) {
467 fmt += strlen(fmt);
468 if (fmt[-1] != '\n')
469 (void)fputc('\n', stderr);
470 }
471 exit(1);
472 /* NOTREACHED */
473 }
474
475 /* VARARGS */
476 void
477 warning(const char *fmt, ...)
478 {
479 va_list ap;
480
481 (void)fprintf(stderr, "%s: WARNING: ", program_name);
482 va_start(ap, fmt);
483 (void)vfprintf(stderr, fmt, ap);
484 va_end(ap);
485 if (*fmt) {
486 fmt += strlen(fmt);
487 if (fmt[-1] != '\n')
488 (void)fputc('\n', stderr);
489 }
490 }
491
492 /*
493 * Copy arg vector into a new buffer, concatenating arguments with spaces.
494 */
495 char *
496 copy_argv(register char **argv)
497 {
498 register char **p;
499 register u_int len = 0;
500 char *buf;
501 char *src, *dst;
502
503 p = argv;
504 if (*p == 0)
505 return 0;
506
507 while (*p)
508 len += strlen(*p++) + 1;
509
510 buf = (char *)malloc(len);
511 if (buf == NULL)
512 error("copy_argv: malloc");
513
514 p = argv;
515 dst = buf;
516 while ((src = *p++) != NULL) {
517 while ((*dst++ = *src++) != '\0')
518 ;
519 dst[-1] = ' ';
520 }
521 dst[-1] = '\0';
522
523 return buf;
524 }
525
526 /*
527 * On Windows, we need to open the file in binary mode, so that
528 * we get all the bytes specified by the size we get from "fstat()".
529 * On UNIX, that's not necessary. O_BINARY is defined on Windows;
530 * we define it as 0 if it's not defined, so it does nothing.
531 */
532 #ifndef O_BINARY
533 #define O_BINARY 0
534 #endif
535
536 char *
537 read_infile(char *fname)
538 {
539 register int i, fd, cc;
540 register char *cp;
541 struct stat buf;
542
543 fd = open(fname, O_RDONLY|O_BINARY);
544 if (fd < 0)
545 error("can't open %s: %s", fname, pcap_strerror(errno));
546
547 if (fstat(fd, &buf) < 0)
548 error("can't stat %s: %s", fname, pcap_strerror(errno));
549
550 cp = malloc((u_int)buf.st_size + 1);
551 if (cp == NULL)
552 error("malloc(%d) for %s: %s", (u_int)buf.st_size + 1,
553 fname, pcap_strerror(errno));
554 cc = read(fd, cp, (u_int)buf.st_size);
555 if (cc < 0)
556 error("read %s: %s", fname, pcap_strerror(errno));
557 if (cc != buf.st_size)
558 error("short read %s (%d != %d)", fname, cc, (int)buf.st_size);
559
560 close(fd);
561 /* replace "# comment" with spaces */
562 for (i = 0; i < cc; i++) {
563 if (cp[i] == '#')
564 while (i < cc && cp[i] != '\n')
565 cp[i++] = ' ';
566 }
567 cp[cc] = '\0';
568 return (cp);
569 }
570
571 void
572 safeputs(netdissect_options *ndo,
573 const u_char *s, const u_int maxlen)
574 {
575 u_int idx = 0;
576
577 while (*s && idx < maxlen) {
578 safeputchar(ndo, *s);
579 idx++;
580 s++;
581 }
582 }
583
584 void
585 safeputchar(netdissect_options *ndo,
586 const u_char c)
587 {
588 ND_PRINT((ndo, (c < 0x80 && ND_ISPRINT(c)) ? "%c" : "\\0x%02x", c));
589 }
590
591 #ifdef LBL_ALIGN
592 /*
593 * Some compilers try to optimize memcpy(), using the alignment constraint
594 * on the argument pointer type. by using this function, we try to avoid the
595 * optimization.
596 */
597 void
598 unaligned_memcpy(void *p, const void *q, size_t l)
599 {
600 memcpy(p, q, l);
601 }
602
603 /* As with memcpy(), so with memcmp(). */
604 int
605 unaligned_memcmp(const void *p, const void *q, size_t l)
606 {
607 return (memcmp(p, q, l));
608 }
609 #endif