xref: /plan9/sys/src/cmd/ip/snoopy/dump.c (revision 2cca75a1b2b8c6083390679d69d5c50cf66d9a01)
1 #include <u.h>
2 #include <libc.h>
3 #include <ip.h>
4 #include <ctype.h>
5 #include "dat.h"
6 #include "protos.h"
7 
8 static void
p_compile(Filter *)9 p_compile(Filter *)
10 {
11 }
12 
13 static char tohex[16] = {
14 	'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
15 	'a', 'b', 'c', 'd', 'e', 'f'
16 };
17 
18 static int
p_seprint(Msg * m)19 p_seprint(Msg *m)
20 {
21 	int c, i, n, isstring;
22 	uchar *ps = m->ps;
23 	char *p = m->p;
24 	char *e = m->e;
25 
26 	n = m->pe - ps;
27 	if(n > Nflag)
28 		n = Nflag;
29 
30 	isstring = 1;
31 	for(i = 0; i < n; i++){
32 		c = ps[i];
33 		if(!isprint(c) && !isspace(c)){
34 			isstring = 0;
35 			break;
36 		}
37 	}
38 
39 	if(isstring){
40 		for(i = 0; i < n && p+1<e; i++){
41 			c = ps[i];
42 			switch(c){
43 			case '\t':
44 				*p++ = '\\';
45 				*p++ = 't';
46 				break;
47 			case '\r':
48 				*p++ = '\\';
49 				*p++ = 'r';
50 				break;
51 			case '\n':
52 				*p++ = '\\';
53 				*p++ = 'n';
54 				break;
55 			default:
56 				*p++ = c;
57 			}
58 		}
59 	} else {
60 		for(i = 0; i < n && p+1<e; i++){
61 			c = ps[i];
62 			*p++ = tohex[c>>4];
63 			*p++ = tohex[c&0xf];
64 		}
65 	}
66 
67 	m->pr = nil;
68 	m->p = p;
69 	m->ps = ps;
70 
71 	return 0;
72 }
73 
74 Proto dump =
75 {
76 	"dump",
77 	p_compile,
78 	nil,
79 	p_seprint,
80 	nil,
81 	nil,
82 	nil,
83 	defaultframer,
84 };
85