File: display.c

package info (click to toggle)
pktstat 1.8.5-8
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 696 kB
  • sloc: ansic: 5,105; sh: 1,032; makefile: 34
file content (697 lines) | stat: -rw-r--r-- 14,587 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
/* David Leonard, 2002. Public domain. */
/* $Id: display.c 1212 2012-03-04 14:38:41Z d $ */

/*
 * This compilation unit uses curses to display the current
 * list of active tags on the screen. It also handles keystroke
 * input to make changes to flag settings.
 * And, although this is not the right place for it, all
 * the averages are computed here.
 */

#if HAVE_CONFIG_H
# include "config.h"
#endif

#if STDC_HEADERS
# include <stdio.h>
# include <stdlib.h>
# include <stdarg.h>
# include <string.h>
#endif

#if HAVE_CURSES_H
# include <curses.h>
#else
# if HAVE_NCURSES_H
#  include <ncurses.h>
# endif
#endif

#if HAVE_EXP
# if HAVE_MATH_H
#  include <math.h>
# endif
#endif

#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
#  include <sys/time.h>
# else
#  include <time.h>
# endif
#endif

#if HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif
#if HAVE_SYS_PARAM_H
# include <sys/param.h>
#endif

#if HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif
#if HAVE_NET_IF_H
# include <net/if.h>
#endif

#include "compat.h"
#include "display.h"
#include "flow.h"
#include "main.h"
#include "resize.h"
#include "ifc.h"
#include "tag.h"

#undef MIN
#undef MAX
#define MIN(a,b)	((a) < (b) ? (a) : (b))
#define MAX(a,b)	((a) > (b) ? (a) : (b))

#ifndef NBBY
# define NBBY 8	/* Number of bits per byte */
#endif

#define BITS(r)	(Bflag ? (r) : (r) * NBBY)
#define BPSS	(Bflag ? "Bps" : "bps")
#define BS	(Bflag ? "B" : "b")

static uint64_t total_octets = 0;
static double total_time = 0;
static double bps = 0;
static double maxbps = -1;
static double minbps = -1;
static const char *display_device, *display_filter;
static int display_opened = 0;
#if HAVE_EXP
static double avg[3] = { 0.0, 0.0, 0.0 };
static double avg_pkt[3] = { 0.0, 0.0, 0.0 };
#endif
static int showhelp = 0;
static int wasdown = 0;

static uint64_t total_packets = 0;
static double pps = 0;
static double maxpps = -1;
static double minpps = -1;

static int prompting = 0;
static int replybuflen = 0;
static char prompt[40];
static char replybuf[40];

static const char *mega(double, const char *);
static const char *days(double);
static void printhelp(void);

/* Return SI unit representation for number x, e.g (3000,"%.1f") -> "3.0k" */
static
const char *
mega(x, fmt)
	double x;
	const char *fmt;
{
	static char buf[1024];	/* XXX - arbitrary size */
	static char suffix[] = " kMGTPE";
	int i;
	int len;

	i = 0;
	while (x >= 999.95 && suffix[i]) {
		x /= 1000.0;
		i++;
	}
	if (!suffix[i]) {
		x /= 0.0;	/* IEEE Inf */
		i = 0;		/* no unit */
	}
	snprintf(buf, sizeof buf - 1, fmt, x);
	len = strlen(buf);
	if (i)
		buf[len++] = suffix[i];
	buf[len] = '\0';
	return buf;
}

/* Return human-friendly time expression, eg in days, weeks, hours etc. */
static const char *
days(td)
	double td;
{
	static char buf[1024];	/* XXX - arbitrary size */
	unsigned long t = td;

	static const int Mn = 60;
	static const int Hr = 60 * 60;
	static const int Dy = 24 * 60 * 60;

	if (t < Mn) {
		snprintf(buf, sizeof buf, "%lds", t);
		return buf;
	}
	if (t < Hr) {
		snprintf(buf, sizeof buf, "%ldm%02lds",
			t / Mn,
			(t % Mn) / 1
		);
		return buf;
	}
	if (t < Dy) {
		snprintf(buf, sizeof buf, "%ldh%02ldm%02lds",
			t / Hr,
			(t % Hr) / Mn,
			((t % Hr) % Mn) / 1
		);
		return buf;
	}
	snprintf(buf, sizeof buf, "%ldd%02ldh%02ldm%02lds",
		t / Dy,
		(t % Dy) / Hr,
		((t % Dy) % Hr) / Mn,
		(((t % Dy) % Hr) % Mn) / 1
	);
	return buf;
}

/* Prepare the display using curses */
void
display_open(device, filter)
	const char *device, *filter;
{

	display_device = device;
	display_filter = filter;
	initscr();
	cbreak();
	noecho();
	scrollok(stdscr, FALSE);
	nodelay(stdscr, TRUE);
	display_opened = 1;
	resize_init();
	ifc_init(device);		/* XXX shouldn't be here */
}

/* Close the display */
void
display_close()
{
	if (display_opened)
		endwin();
	display_opened = 0;
}

static void
update_stats(period)
	double period;
{
	int i;
	unsigned long sum;
	unsigned long sum_packets;

	/* sort the flows by their packet octet count */
	qsort(flows, nflows, sizeof (struct flow), 
		lflag ? lastcmp 
		      : tflag ? (pflag ? packetcmp : octetcmp)
			      : tagcmp);

	/* Compute total number of octets we have just seen go by */
	sum = 0;
	sum_packets = 0;
	for (i = 0; i < nflows; i++) {
		sum += flows[i].octets;
		sum_packets += flows[i].packets;
	}

	/* Keep track of totals for the -T flag */
	total_octets += sum;
	total_packets += sum_packets;
	total_time += period;

	/* Compute minimum and maximum octet rates */
	bps = 0;
	pps = 0;
	if (period > 0) {
		bps = sum / period;
		if (minbps < 0 || bps < minbps)
			minbps = bps;
		if (maxbps < 0 || bps > maxbps)
			maxbps = bps;
		pps = sum_packets / period;
		if (minpps < 0 || pps < minpps)
			minpps = pps;
		if (maxpps < 0 || pps > maxpps)
			maxpps = pps;

#if HAVE_EXP
		/* Compute the 1, 5 and 15 minute average packet/bit rates */
		for (i = 0; i < 3; i++) {
			static double T[3] = { 60, 5 * 60, 15 * 60 };
			double eT = exp(-period / T[i]);
			avg[i] = avg[i] * eT + bps * (1.0 - eT);
			avg_pkt[i] = avg_pkt[i] * eT + pps * (1.0 - eT);
		}
#endif
	}
}

/* Like display_update() but writes to stdout */
void
batch_update(double period)
{
	int i;

	update_stats(period);

	printf("%u %f\n", nflows, period);
	for (i = 0; i < nflows; i++) {
	    printf("%.0f %.0f %s\n",	    /* XXX should be integer format */
		(double)flows[i].octets,
		(double)flows[i].packets,
		flows[i].tag);
	}
	fflush(stdout);
}

/* Update the display, sorting and drawing all the computed tags */
void
display_update(period)
	double period;
{
	int i, flags, ch;
	int maxx, maxy, y, x;
	int maxi;
	int redraw_needed = 0;
	int clearflows = 0;

	if (resize_needed()) {
		resize();
		redraw_needed = 1;
	}

	getmaxyx(stdscr, maxy, maxx);

        ch = getch();
	if (prompting)
	    switch (ch) {
	    case '[' & 0x3f:	/* Escape */
	    	prompting = 0;
		break;
	    case ERR:		/* No key */
		break;
	    case 'U' & 0x3f:
	    	replybuflen = 0;
		break;
	    case KEY_BACKSPACE:
	    case KEY_LEFT:
	    case 'H' & 0x3f: case 0x7f:
	    	if (replybuflen)
			replybuflen--;
		break;
	    case KEY_ENTER:
	    case '\r': case '\n':
	        replybuf[replybuflen] = 0;
		switch (prompting) {
		case 'w':
		    sscanf(replybuf, "%d", &wflag);
		    break;
		}
	    	prompting = 0;
		break;
	    case ('L'&0x3f):		/* control-L to redraw */
		redraw_needed = 1;
		break;
	    default:
	    	if (replybuflen < sizeof replybuf - 1)
		    replybuf[replybuflen++] = ch;
		break;
	    }
		    
	else

	/* Handle keystroke since the last screen update */
	switch (ch) {
	case ('L'&0x3f):		/* control-L to redraw */
		redraw_needed = 1;
		break;
	case 'q':			/* q for quit */
		exit(0);
	case 't':			/* toggle -t */
		tflag = !tflag;
		if (tflag)
			lflag = 0;
		break;
	case 'l':			/* toggle -l */
		lflag = !lflag;
		if (lflag)
			tflag = 0;
		break;
	case 'T':			/* toggle -T */
		Tflag = !Tflag;
		break;
	case 'n':			/* toggle -n */
		nflag = !nflag;
		clearflows = 1;
		break;
	case 'b': case 'B':		/* toggle -B */
		Bflag = !Bflag;
		break;
	case 'p':			/* toggle -p */
		pflag = !pflag;
		break;
	case 'f': case 'F':		/* toggle -F */
		Fflag = !Fflag;
		clearflows = 1;
		break;
	case 'r':			/* reset stats */
		display_reset();
		period = 0;
		break;
	case 'w':
		snprintf(prompt, sizeof prompt, "Wait interval [%d]", wflag);
		prompting = ch;
		showhelp = 0;
		replybuflen = 0;
		break;
	case '?':			/* show help line */
		if (showhelp > 0)
			showhelp = 0;
		else
			showhelp = 1;
		break;
	case ERR:			/* no key */
		break;
	default:			/* unknown key */
		break;	
	}

	update_stats(period);

	if (redraw_needed)
		clearok(curscr, TRUE);

	move(0,0);

	/* Print information about the interface */
	printw("interface: %s ", display_device);

	flags = ifc_flags();
	if ((flags & IFF_UP) == 0) {
		static char since[27];
		int oattr = attron(A_REVERSE);
		printw("down");
		attrset(oattr);
		if (!wasdown) {
			time_t now = time(0);
			char *c = ctime(&now);
			memcpy(since, c, 24);
			since[24] = '\0';
			beep();
			wasdown = 1;
		}
		printw(" (since %s) ", since);
	} else
		wasdown = 0;

	if ((flags & IFF_RUNNING) == 0)
		printw("(not running) ");

	if (Tflag)
		printw("   total: %s%s (%s)", mega(
		    pflag ? total_packets : (double)BITS(total_octets), "%.1f"),
		    pflag ? "p" : BS, days(total_time));
	clrtoeol();
	printw("\n");

	if (!Tflag) {
#if HAVE_EXP
		/* Display simple load average */
		printw("load averages: ");
		printw("%s ", mega(pflag ? avg_pkt[0] : BITS(avg[0]), "%.1f"));
		printw("%s ", mega(pflag ? avg_pkt[1] : BITS(avg[1]), "%.1f"));
		printw("%s ", mega(pflag ? avg_pkt[2] : BITS(avg[2]), "%.1f"));
#endif
	} else {
		/* Display sophisticated load averages for the -T flag */
		if (period > 0) {
			printw("cur: %s ", mega(pflag ? pps : BITS(bps),
			    "%.1f"));
			if (mflag > 0)
				printw("(%u%%) ", (int)(100.0 * bps / mflag));
			else if (maxbps > 0)
				printw("(%u%%) ", (int)(100.0 * bps / maxbps));
		}
#if HAVE_EXP
		printw("[%s ", mega(pflag ? avg_pkt[0] : BITS(avg[0]),
		    "%.1f"));
		printw("%s ", mega(pflag ? avg_pkt[1] : BITS(avg[1]),
		    "%.1f"));
		printw("%s] ", mega(pflag ? avg_pkt[1] : BITS(avg[2]),
		    "%.1f"));
#endif
		if (minbps >= 0)
			printw("min: %s ",
				mega(pflag ? minpps : BITS(minbps), "%.1f"));
		if (!pflag && mflag > 0) {
			printw("max: ");
			attron(A_UNDERLINE);
			printw("%s", mega(BITS(mflag), "%.1f"));
			attrset(A_NORMAL);
			if (maxbps > mflag)
				printw(" (%s)", mega(BITS(maxbps), "%.1f"));
			printw(" ");
		} else if (maxbps >= 0)
			printw("max: %s ", 
				mega(pflag ? maxpps : BITS(maxbps), "%.1f"));
		if (total_time > 0) {
			printw("avg: %s ", mega(
			    (pflag ? total_packets : BITS(total_octets)) /
			    total_time, "%.1f"));
		}
	}
	printw("%s", pflag ? "pps" : BPSS);
	clrtoeol();

	/* Print information about the filter (if any) */
	move(2, 0);
	if (display_filter)
		printw("filter: %s", display_filter);
	clrtoeol();
	move(3, 0);

/* Computing the indent for tag descripions now */
#define LLEN	(13 + (Tflag ? 7 : 0) - (pflag ? 5 : 0))

	/* Print the heading row */
	attron(A_UNDERLINE); printw("%6s", pflag ? "pps" : BPSS);
	attrset(A_NORMAL); printw(" ");
	if (!pflag) {
		attron(A_UNDERLINE); printw("%4s", "%");
		attrset(A_NORMAL); printw(" ");
	}
	if (Tflag) {
		attron(A_UNDERLINE); printw("%6s", pflag ? "p" : BS);
		attrset(A_NORMAL); printw(" ");
	}
	attron(A_UNDERLINE); printw("%-*s", 
		MIN(maxx - LLEN, 
		    MAX(sizeof flows->desc + 2, sizeof flows->tag) - 1),
		"desc");
	attrset(A_NORMAL); 
	clrtoeol();
	printw("\n");

	clrtobot();

	maxi = nflows;
	for (i = 0; i < nflows; i++) {

		/* Handle going off the bottom of the screen */
		getyx(stdscr, y, x);
		if (y >= maxy - 2) {
			maxi = i + 10;
			break;
		}

		/* Ignore flows that have stopped for a while */
		if (!lflag && flows[i].octets == 0 && flows[i].keepalive <= 0)
			continue;

		/* Dim flows that have paused */
		if (flows[i].octets == 0)
			attron(A_DIM);
		/* Embolden flows that have started up again */
		else if (flows[i].keepalive < kflag)
			attron(A_BOLD);

		/* Print the bitrate of active flows */
		if (flows[i].octets && period > 0) {
			printw("%6s ", mega(
			    (pflag ? flows[i].packets : BITS(flows[i].octets)) /
			    period, "%5.1f"));
			if (!pflag) printw("%3d%% ", 
			    (int)(100.0 * (flows[i].octets / period / 
					   (mflag>0 ? mflag : maxbps))));
		} else {
			printw("%6s ", "");
			if (!pflag) printw("%4s ", "");
		}

		/* Show a flow's total bit history with the -T flag */
		if (Tflag)
			printw("%6s ", 
				mega((double) (pflag 
				    ? flows[i].total_packets
				    : BITS(flows[i].total_octets)),
				    "%5.1f"));

		/* Finally, the flow's name */
		printw("%.*s\n", MIN(maxx - LLEN, sizeof flows[i].tag - 1),
		    flows[i].tag);

		/* On a new line, show the flow's description, if it has one */
		if (flows[i].desc[0] != '\0') {
			printw("%6s ", "");
			if (!pflag) printw("%4s ", "");
			if (Tflag)
				printw("%6s ", "");
			/* Show a right angle if the connection is live */
			if (flows[i].dontdel)
				addch(ACS_LLCORNER);
			else
				addch('-');
			printw(" %.*s\n", MIN(maxx - LLEN - 2, 
			    sizeof flows[i].desc - 1), flows[i].desc);
		}
		attrset(A_NORMAL);
	}

	if (prompting) {
		move(maxy - 1, 0);
		printw("%s> %.*s", prompt, replybuflen, replybuf);
	} if (showhelp) {
		move(maxy - 1, 0);
		printhelp();
	}

	/* Flush output to the screen */
	refresh();

	/* Decrement keepalive counter for flows that have paused. */
	for (i = 0; i < nflows; i++) {
		if (flows[i].octets > 0) {
			flows[i].keepalive = kflag;
			continue;
		}
		if (flows[i].keepalive > 0)
			flows[i].keepalive -= period;
		if ((!lflag || i >= maxi) && flows[i].keepalive <= 0 && !flows[i].dontdel) {
			flow_del(&flows[i]);
			i--;	/* because a new flow slips in */
		}
	}

	/* If tag names are about to change, we need to reset everything */
	if (clearflows)
		while (nflows)
			flow_del(flows);
}

/* Display an informational message at the bottom of the screen */
void
display_message(const char *fmt, ...)
{
	int maxy, maxx;
	char *buf;
	va_list ap;

	if (oneflag) {
#if 0
		va_start(ap, fmt);
		vfprintf(stderr, fmt, ap);
		va_end(ap);
		fprintf(stderr, "\n");
#endif
		return;
	}


	if (resize_needed()) {
	    resize();
	    clearok(stdscr, TRUE);
	    refresh();
	}

	getmaxyx(stdscr, maxy, maxx);
	buf = alloca(maxx);

	va_start(ap, fmt);
	vsnprintf(buf, maxx - 2, fmt, ap);
	va_end(ap);

	move(maxy - 2, 0);
	clrtoeol();
	if (buf[0])
		addstr(buf);

	refresh();
}

/* Print the help text */
static void
printhelp()
{
	static struct helplabel {
		int	*flagp;
		const char *name;
	} helplabels[] = {
		{ &tflag, "top" },
		{ &lflag, "last" },
		{ &nflag, "numeric" },
		{ &Bflag, "Byte" },
		{ &pflag, "packet" },
		{ &Fflag, "FQDN" },
		{ &Tflag, "Total" },
		{ NULL,   "reset" },
		{ NULL,   "quit" },
		{ NULL,   "?help" },
	};
#define nhelplabels (sizeof helplabels / sizeof helplabels[0])

	struct helplabel *h;

	for (h = helplabels; h < helplabels + nhelplabels; h++) {
		attrset(A_UNDERLINE);
		if (h->flagp && *h->flagp)
			attron(A_REVERSE);
		printw("%c", h->name[0]);
		attroff(A_UNDERLINE);
		printw("%s", (char *)h->name + 1);
		attrset(0);
		printw(" ");
	}
	printw(" - pktstat %s", version);
}

void
display_reset()
{
	total_octets = 0;
	total_packets = 0;
	total_time = 0;
	maxbps = -1;
	minbps = -1;
	maxpps = -1;
	minpps = -1;
	flow_free();
	#if HAVE_EXP
	for (i = 0; i < 3; i++)	/* clear averages */
		avg[i] = avg_pkt[i] = 0;
	#endif
	ip_reset();
	udp_reset();
	tcp_reset();
}