2 * netsniff-ng - the packet sniffing beast
3 * Copyright 2009, 2010 Daniel Borkmann.
4 * Copyright 2013 Tobias Klauser.
5 * Subject to the GPL, version 2.
9 #define _DEFAULT_SOURCE
13 #include <sys/ioctl.h>
20 #define term_trailing_size 5
21 #define term_starting_size 3
23 #define term_curr_size (get_tty_size() - term_trailing_size)
25 static char buffer
[1024];
27 static volatile size_t buffer_use
= 0;
29 static struct spinlock buffer_lock
;
31 static int get_tty_size(void)
34 struct ttysize ts
= {0};
36 return (ioctl(0, TIOCGSIZE
, &ts
) == 0 ? ts
.ts_cols
: DEFAULT_TTY_SIZE
);
37 #elif defined(TIOCGWINSZ)
40 return (ioctl(0, TIOCGWINSZ
, &ts
) == 0 ? ts
.ws_col
: DEFAULT_TTY_SIZE
);
42 return DEFAULT_TTY_SIZE
;
46 static inline void __tprintf_flush_newline(void)
51 for (i
= 0; i
< term_starting_size
; ++i
)
55 static inline int __tprintf_flush_skip(char *buf
, int i
)
59 if (val
== ' ' || val
== ',')
65 static void __tprintf_flush(void)
68 static ssize_t line_count
= 0;
69 ssize_t term_len
= term_curr_size
;
70 size_t color_open
= 0;
72 for (i
= 0; i
< buffer_use
; ++i
) {
73 if (buffer
[i
] == '\n') {
74 term_len
= term_curr_size
;
78 /* Start of an color escape sequence? */
79 if (buffer
[i
] == 033) {
80 if ((i
+ 1) < buffer_use
&& buffer
[i
+ 1] == '[')
84 if (color_open
== 0 && line_count
>= term_len
) {
85 __tprintf_flush_newline();
86 line_count
= term_starting_size
;
88 while (i
< buffer_use
&&
89 __tprintf_flush_skip(buffer
, i
))
93 /* End of the color escape sequence? */
94 if (color_open
> 0 && buffer
[i
] == 'm')
97 fputc(buffer
[i
], stdout
);
105 void tprintf_flush(void)
107 spinlock_lock(&buffer_lock
);
109 spinlock_unlock(&buffer_lock
);
112 void tprintf_init(void)
114 spinlock_init(&buffer_lock
);
116 setvbuf(stdout
, NULL
, _IONBF
, 0);
117 setvbuf(stderr
, NULL
, _IONBF
, 0);
120 void tprintf_cleanup(void)
123 spinlock_destroy(&buffer_lock
);
126 void tprintf(char *msg
, ...)
132 spinlock_lock(&buffer_lock
);
134 avail
= sizeof(buffer
) - buffer_use
;
138 ret
= vsnprintf(buffer
+ buffer_use
, avail
, msg
, vl
);
142 panic("vsnprintf screwed up in tprintf!\n");
143 if ((size_t) ret
> sizeof(buffer
))
144 panic("No mem in tprintf left!\n");
148 avail
= sizeof(buffer
) - buffer_use
;
152 ret
= vsnprintf(buffer
+ buffer_use
, avail
, msg
, vl
);
156 panic("vsnprintf screwed up in tprintf!\n");
161 spinlock_unlock(&buffer_lock
);
164 void tputchar_safe(int c
)
166 unsigned char ch
= (unsigned char)(c
& 0xff);
171 tprintf("\\0x%02x", ch
);
174 void tputs_safe(const char *str
, size_t len
)