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>
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 *buffer
, int i
, size_t max
)
59 if (val
== ' ' || val
== ',')
65 static void __tprintf_flush(void)
68 static ssize_t line_count
= 0;
69 size_t term_len
= term_curr_size
;
71 for (i
= 0; i
< buffer_use
; ++i
) {
72 if (buffer
[i
] == '\n') {
73 term_len
= term_curr_size
;
77 if (line_count
== term_len
) {
78 __tprintf_flush_newline();
79 line_count
= term_starting_size
;
81 while (i
< buffer_use
&&
82 __tprintf_flush_skip(buffer
, i
, buffer_use
))
86 fputc(buffer
[i
], stdout
);
94 void tprintf_flush(void)
96 spinlock_lock(&buffer_lock
);
98 spinlock_unlock(&buffer_lock
);
101 void tprintf_init(void)
103 spinlock_init(&buffer_lock
);
105 setvbuf(stdout
, NULL
, _IONBF
, 0);
106 setvbuf(stderr
, NULL
, _IONBF
, 0);
109 void tprintf_cleanup(void)
112 spinlock_destroy(&buffer_lock
);
115 void tprintf(char *msg
, ...)
121 spinlock_lock(&buffer_lock
);
123 avail
= sizeof(buffer
) - buffer_use
;
127 ret
= vsnprintf(buffer
+ buffer_use
, avail
, msg
, vl
);
131 panic("vsnprintf screwed up in tprintf!\n");
132 if (ret
> sizeof(buffer
))
133 panic("No mem in tprintf left!\n");
137 avail
= sizeof(buffer
) - buffer_use
;
141 ret
= vsnprintf(buffer
+ buffer_use
, avail
, msg
, vl
);
145 panic("vsnprintf screwed up in tprintf!\n");
150 spinlock_unlock(&buffer_lock
);
153 void tputchar_safe(int c
)
155 unsigned char ch
= (unsigned char)(c
& 0xff);
160 tprintf("\\0x%02x", ch
);
163 void tputs_safe(const char *str
, size_t len
)