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.
12 #include <sys/ioctl.h>
19 #define term_trailing_size 5
20 #define term_starting_size 3
22 #define term_curr_size (get_tty_size() - term_trailing_size)
24 static char buffer
[1024];
26 static volatile size_t buffer_use
= 0;
28 static struct spinlock buffer_lock
;
30 static int get_tty_size(void)
33 struct ttysize ts
= {0};
35 return (ioctl(0, TIOCGSIZE
, &ts
) == 0 ? ts
.ts_cols
: DEFAULT_TTY_SIZE
);
36 #elif defined(TIOCGWINSZ)
39 return (ioctl(0, TIOCGWINSZ
, &ts
) == 0 ? ts
.ws_col
: DEFAULT_TTY_SIZE
);
41 return DEFAULT_TTY_SIZE
;
45 static inline void __tprintf_flush_newline(void)
50 for (i
= 0; i
< term_starting_size
; ++i
)
54 static inline int __tprintf_flush_skip(char *buf
, int i
, size_t max
)
58 if (val
== ' ' || val
== ',')
64 static void __tprintf_flush(void)
67 static ssize_t line_count
= 0;
68 size_t term_len
= term_curr_size
;
70 for (i
= 0; i
< buffer_use
; ++i
) {
71 if (buffer
[i
] == '\n') {
72 term_len
= term_curr_size
;
76 if (line_count
== term_len
) {
77 __tprintf_flush_newline();
78 line_count
= term_starting_size
;
80 while (i
< buffer_use
&&
81 __tprintf_flush_skip(buffer
, i
, buffer_use
))
85 fputc(buffer
[i
], stdout
);
93 void tprintf_flush(void)
95 spinlock_lock(&buffer_lock
);
97 spinlock_unlock(&buffer_lock
);
100 void tprintf_init(void)
102 spinlock_init(&buffer_lock
);
104 setvbuf(stdout
, NULL
, _IONBF
, 0);
105 setvbuf(stderr
, NULL
, _IONBF
, 0);
108 void tprintf_cleanup(void)
111 spinlock_destroy(&buffer_lock
);
114 void tprintf(char *msg
, ...)
120 spinlock_lock(&buffer_lock
);
122 avail
= sizeof(buffer
) - buffer_use
;
126 ret
= vsnprintf(buffer
+ buffer_use
, avail
, msg
, vl
);
130 panic("vsnprintf screwed up in tprintf!\n");
131 if (ret
> sizeof(buffer
))
132 panic("No mem in tprintf left!\n");
136 avail
= sizeof(buffer
) - buffer_use
;
140 ret
= vsnprintf(buffer
+ buffer_use
, avail
, msg
, vl
);
144 panic("vsnprintf screwed up in tprintf!\n");
149 spinlock_unlock(&buffer_lock
);
152 void tputchar_safe(int c
)
154 unsigned char ch
= (unsigned char)(c
& 0xff);
159 tprintf("\\0x%02x", ch
);
162 void tputs_safe(const char *str
, size_t len
)