ui.c 32.5 KB
Newer Older
pdw's avatar
pdw committed
1 2 3 4 5
/*
 * ui.c:
 *
 */

chris's avatar
chris committed
6 7
#include <sys/types.h>

chris's avatar
chris committed
8
#include <ctype.h>
pdw's avatar
pdw committed
9
#include <curses.h>
chris's avatar
chris committed
10
#include <errno.h>
pdw's avatar
pdw committed
11
#include <string.h>
chris's avatar
chris committed
12
#include <math.h>
pdw's avatar
pdw committed
13
#include <pthread.h>
chris's avatar
chris committed
14
#include <signal.h>
pdw's avatar
pdw committed
15
#include <stdlib.h>
chris's avatar
chris committed
16
#include <unistd.h>
17
#include <netdb.h>
chris's avatar
chris committed
18

chris's avatar
chris committed
19 20
#include <sys/wait.h>

pdw's avatar
pdw committed
21
#include "addr_hash.h"
22
#include "serv_hash.h"
pdw's avatar
pdw committed
23 24 25
#include "iftop.h"
#include "resolver.h"
#include "sorted_list.h"
pdw's avatar
pdw committed
26
#include "options.h"
27
#include "screenfilter.h"
pdw's avatar
pdw committed
28

chris's avatar
chris committed
29
#define HOSTNAME_LENGTH 256
pdw's avatar
pdw committed
30

chris's avatar
chris committed
31
#define HISTORY_DIVISIONS   3
pdw's avatar
pdw committed
32

pdw's avatar
pdw committed
33 34
#define HELP_TIME 2

pdw's avatar
pdw committed
35
#define HELP_MESSAGE \
chris's avatar
chris committed
36
"Host display:                          General:\n"\
37
" n - toggle DNS host resolution         P - pause display\n"\
chris's avatar
chris committed
38 39
" s - toggle show source host            h - toggle this help display\n"\
" d - toggle show destination host       b - toggle bar graph display\n"\
pdw's avatar
pdw committed
40
" t - cycle line display mode            B - cycle bar graph average\n"\
41
"                                        T - toggle cumulative line totals\n"\
pdw's avatar
pdw committed
42
"Port display:                           j/k - scroll display\n"\
43
" N - toggle service resolution          f - edit filter code\n"\
pdw's avatar
pdw committed
44 45 46 47
" S - toggle show source port            l - set screen filter\n"\
" D - toggle show destination port       L - lin/log scales\n"\
" p - toggle port display                ! - shell command\n"\
"                                        q - quit\n"\
chris's avatar
chris committed
48
"Sorting:\n"\
pdw's avatar
pdw committed
49 50 51
" 1/2/3 - sort by 1st/2nd/3rd column\n"\
" < - sort by source name\n"\
" > - sort by dest name\n"\
52
" o - freeze current order\n"\
chris's avatar
chris committed
53 54
"\n"\
"iftop, version " IFTOP_VERSION 
pdw's avatar
pdw committed
55 56


pdw's avatar
pdw committed
57
/* 2, 10 and 40 seconds */
pdw's avatar
pdw committed
58
int history_divs[HISTORY_DIVISIONS] = {1, 5, 20};
pdw's avatar
pdw committed
59

60
#define UNIT_DIVISIONS 4
61 62
char* unit_bits[UNIT_DIVISIONS] =  { "b", "kb", "Mb", "Gb"};
char* unit_bytes[UNIT_DIVISIONS] =  { "B", "kB", "MB", "GB"};
pdw's avatar
pdw committed
63 64

typedef struct host_pair_line_tag {
65
    addr_pair ap;
pdw's avatar
pdw committed
66 67
    double long total_recv;
    double long total_sent;
68 69
    double long recv[HISTORY_DIVISIONS];
    double long sent[HISTORY_DIVISIONS];
pdw's avatar
pdw committed
70 71 72 73 74 75 76
} host_pair_line;


extern hash_type* history;
extern int history_pos;
extern int history_len;

pdw's avatar
pdw committed
77 78
extern options_t options ;

chris's avatar
chris committed
79 80
void ui_finish();

81
hash_type* screen_hash;
82
hash_type* service_hash;
83 84 85 86
sorted_list_type screen_list;
host_pair_line totals;
int peaksent, peakrecv, peaktotal;

pdw's avatar
pdw committed
87
#define HELP_MSG_SIZE 80
pdw's avatar
pdw committed
88
int showhelphint = 0;
89 90
int persistenthelp = 0;
time_t helptimer = 0;
pdw's avatar
pdw committed
91
char helpmsg[HELP_MSG_SIZE];
chris's avatar
chris committed
92
int dontshowdisplay = 0;
pdw's avatar
pdw committed
93

pdw's avatar
pdw committed
94 95 96 97 98
/*
 * Compare two screen lines based on bandwidth.  Start comparing from the 
 * specified column
 */
int screen_line_bandwidth_compare(host_pair_line* aa, host_pair_line* bb, int start_div) {
pdw's avatar
pdw committed
99
    int i;
100 101 102 103 104 105 106 107 108 109 110 111 112
    switch(options.linedisplay) {
      case OPTION_LINEDISPLAY_ONE_LINE_SENT:
	for(i = start_div; i < HISTORY_DIVISIONS; i++) {
	    if(aa->sent[i] != bb->sent[i]) {
	        return(aa->sent[i] < bb->sent[i]);
	    }
        }
        break;
      case OPTION_LINEDISPLAY_ONE_LINE_RECV:
	for(i = start_div; i < HISTORY_DIVISIONS; i++) {
	    if(aa->recv[i] != bb->recv[i]) {
	        return(aa->recv[i] < bb->recv[i]);
	    }
pdw's avatar
pdw committed
113
        }
114 115 116 117 118 119 120 121 122 123
        break;
      case OPTION_LINEDISPLAY_TWO_LINE:
      case OPTION_LINEDISPLAY_ONE_LINE_BOTH:
        /* fallback to the combined sent+recv that also act as fallback for sent/recv */
	break;
    }
    for(i = start_div; i < HISTORY_DIVISIONS; i++) {
	if(aa->recv[i] + aa->sent[i] != bb->recv[i] + bb->sent[i]) {
	    return(aa->recv[i] + aa->sent[i] < bb->recv[i] + bb->sent[i]);
	}
pdw's avatar
pdw committed
124 125
    }
    return 1;
pdw's avatar
pdw committed
126 127
}

pdw's avatar
pdw committed
128 129 130 131
/*
 * Compare two screen lines based on hostname / IP.  Fall over to compare by
 * bandwidth.
 */
132
int screen_line_host_compare(void* a, void* b, host_pair_line* aa, host_pair_line* bb) {
pdw's avatar
pdw committed
133 134 135 136 137 138
    char hosta[HOSTNAME_LENGTH], hostb[HOSTNAME_LENGTH];
    int r;

    /* This isn't overly efficient because we resolve again before 
       display. */
    if (options.dnsresolution) {
139 140
        resolve(aa->ap.af, a, hosta, HOSTNAME_LENGTH);
        resolve(bb->ap.af, b, hostb, HOSTNAME_LENGTH);
pdw's avatar
pdw committed
141 142
    }
    else {
143 144
        inet_ntop(aa->ap.af, a, hosta, sizeof(hosta));
        inet_ntop(bb->ap.af, b, hostb, sizeof(hostb));
pdw's avatar
pdw committed
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
    }

    r = strcmp(hosta, hostb);

    if(r == 0) {
        return screen_line_bandwidth_compare(aa, bb, 2);
    }
    else {
        return (r > 0);
    }


}

int screen_line_compare(void* a, void* b) {
    host_pair_line* aa = (host_pair_line*)a;
    host_pair_line* bb = (host_pair_line*)b;
    if(options.sort == OPTION_SORT_DIV1) {
      return screen_line_bandwidth_compare(aa, bb, 0);
    }
    else if(options.sort == OPTION_SORT_DIV2) {
      return screen_line_bandwidth_compare(aa, bb, 1);
    }
    else if(options.sort == OPTION_SORT_DIV3) {
      return screen_line_bandwidth_compare(aa, bb, 2);
    }
    else if(options.sort == OPTION_SORT_SRC) {
172
      return screen_line_host_compare(&(aa->ap.src6), &(bb->ap.src6), aa, bb);
pdw's avatar
pdw committed
173 174
    }
    else if(options.sort == OPTION_SORT_DEST) {
175
      return screen_line_host_compare(&(aa->ap.dst6), &(bb->ap.dst6), aa, bb);
pdw's avatar
pdw committed
176 177 178 179 180
    }

    return 1;
}

pdw's avatar
pdw committed
181
void readable_size(float n, char* buf, int bsize, int ksize, int bytes) {
182 183

    int i = 0;
184
    float size = 1;
185

186 187 188 189 190
    /* Convert to bits? */
    if(bytes == 0) { 
      n *= 8;
    }

191
    while(1) {
192
      if(n < size * 1000 || i >= UNIT_DIVISIONS - 1) {
193 194 195 196 197 198 199 200 201 202 203 204 205 206
        snprintf(buf, bsize, " %4.0f%s", n / size, bytes ? unit_bytes[i] : unit_bits[i]); 
        break;
      }
      i++;
      size *= ksize;
      if(n < size * 10) {
        snprintf(buf, bsize, " %4.2f%s", n / size, bytes ? unit_bytes[i] : unit_bits[i]); 
        break;
      }
      else if(n < size * 100) {
        snprintf(buf, bsize, " %4.1f%s", n / size, bytes ? unit_bytes[i] : unit_bits[i]); 
        break;
      }
  }
pdw's avatar
pdw committed
207 208
}

chris's avatar
chris committed
209 210 211 212 213

/* Barchart scales. */
static struct {
    int max, interval;
} scale[] = {
214 215 216 217 218 219 220
        {      64000,     10 },     /* 64 kbit/s */
        {     128000,     10 },
        {     256000,     10 },
        {    1000000,     10 },     /* 1 Mbit/s */
        {   10000000,     10 },     
        {  100000000,    100 },
        { 1000000000,    100 }      /* 1 Gbit/s */
chris's avatar
chris committed
221 222
    };
static int rateidx = 0, wantbiggerrate;
chris's avatar
chris committed
223

224 225
static int rateidx_init = 0;

226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
static int get_bar_interval(float bandwidth) {
    int i = 10;
    if(bandwidth > 100000000) {
        i = 100;
    }
    return i;
}

static float get_max_bandwidth() {
    float max;
    if(options.max_bandwidth > 0) {
        max = options.max_bandwidth;
    }
    else {
        max = scale[rateidx].max;
    }
    return max;
}

245
/* rate in bits */
chris's avatar
chris committed
246 247 248 249
static int get_bar_length(const int rate) {
    float l;
    if (rate <= 0)
        return 0;
250 251 252 253 254 255 256 257
    if (rate > scale[rateidx].max) {
      wantbiggerrate = 1;
      if(! rateidx_init) {
	while(rate > scale[rateidx_init++].max) {
	}
	rateidx = rateidx_init;
      }
    }
258 259 260 261 262 263
    if(options.log_scale) {
        l = log(rate) / log(get_max_bandwidth());
    }
    else {
        l = rate / get_max_bandwidth();
    }
pdw's avatar
pdw committed
264
    return (l * COLS);
chris's avatar
chris committed
265 266
}

pdw's avatar
pdw committed
267
static void draw_bar_scale(int* y) {
268
    float i;
269 270 271
    float max,interval;
    max = get_max_bandwidth();
    interval = get_bar_interval(max);
pdw's avatar
pdw committed
272
    if(options.showbars) {
273
        float stop;
pdw's avatar
pdw committed
274
        /* Draw bar graph scale on top of the window. */
chris's avatar
chris committed
275 276
        move(*y, 0);
        clrtoeol();
pdw's avatar
pdw committed
277
        mvhline(*y + 1, 0, 0, COLS);
278
        /* i in bytes */
279 280 281 282 283 284 285 286 287 288 289 290

        if(options.log_scale) {
            i = 1.25;
            stop = max / 8;
        }
        else {
            i = max / (5 * 8);
            stop = max / 8;
        }

        /* for (i = 1.25; i * 8 <= max; i *= interval) { */
        while(i <= stop) {
pdw's avatar
pdw committed
291 292
            char s[40], *p;
            int x;
293
            /* This 1024 vs 1000 stuff is just plain evil */
chris's avatar
chris committed
294
            readable_size(i, s, sizeof s, options.log_scale ? 1000 : 1024, options.bandwidth_in_bytes);
pdw's avatar
pdw committed
295
            p = s + strspn(s, " ");
296
            x = get_bar_length(i * 8);
pdw's avatar
pdw committed
297 298 299 300
            mvaddch(*y + 1, x, ACS_BTEE);
            if (x + strlen(p) >= COLS)
                x = COLS - strlen(p);
            mvaddstr(*y, x, p);
301 302 303 304 305 306 307

            if(options.log_scale) {
                i *= interval;
            }
            else {
                i += max / (5 * 8);
            }
pdw's avatar
pdw committed
308 309 310 311 312 313 314
        }
        mvaddch(*y + 1, 0, ACS_LLCORNER);
        *y += 2;
    }
    else {
        mvhline(*y, 0, 0, COLS);
        *y += 1;
chris's avatar
chris committed
315
    }
pdw's avatar
pdw committed
316 317
}

chris's avatar
chris committed
318 319 320 321 322 323 324
int history_length(const int d) {
    if (history_len < history_divs[d])
        return history_len * RESOLUTION;
    else
        return history_divs[d] * RESOLUTION;
}

pdw's avatar
pdw committed
325
void draw_line_total(float sent, float recv, int y, int x, option_linedisplay_t linedisplay, int bytes) {
pdw's avatar
pdw committed
326
    char buf[10];
pdw's avatar
pdw committed
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    float n;
    switch(linedisplay) {
        case OPTION_LINEDISPLAY_TWO_LINE:
          draw_line_total(sent, recv, y, x, OPTION_LINEDISPLAY_ONE_LINE_SENT, bytes);
          draw_line_total(sent, recv, y+1, x, OPTION_LINEDISPLAY_ONE_LINE_RECV, bytes);
          break;
        case OPTION_LINEDISPLAY_ONE_LINE_SENT:
          n = sent;
          break;
        case OPTION_LINEDISPLAY_ONE_LINE_RECV:
          n = recv;
          break;
        case OPTION_LINEDISPLAY_ONE_LINE_BOTH:
          n = recv + sent;
          break;
    }
    if(linedisplay != OPTION_LINEDISPLAY_TWO_LINE) {
        readable_size(n, buf, 10, 1024, bytes);
        mvaddstr(y, x, buf);
    }
pdw's avatar
pdw committed
347 348 349
}

void draw_bar(float n, int y) {
350 351 352 353 354
    int L;
    mvchgat(y, 0, -1, A_NORMAL, 0, NULL);
    L = get_bar_length(8 * n);
    if (L > 0)
        mvchgat(y, 0, L + 1, A_REVERSE, 0, NULL);
pdw's avatar
pdw committed
355 356 357 358
}

void draw_line_totals(int y, host_pair_line* line, option_linedisplay_t linedisplay) {
    int j;
pdw's avatar
pdw committed
359 360 361
    int x = (COLS - 8 * HISTORY_DIVISIONS);

    for(j = 0; j < HISTORY_DIVISIONS; j++) {
pdw's avatar
pdw committed
362 363
        draw_line_total(line->sent[j], line->recv[j], y, x, linedisplay, options.bandwidth_in_bytes);
        x += 8;
pdw's avatar
pdw committed
364
    }
chris's avatar
chris committed
365
    
pdw's avatar
pdw committed
366
    if(options.showbars) {
pdw's avatar
pdw committed
367 368
      switch(linedisplay) {
        case OPTION_LINEDISPLAY_TWO_LINE:
pdw's avatar
pdw committed
369 370
          draw_bar(line->sent[options.bar_interval],y);
          draw_bar(line->recv[options.bar_interval],y+1);
pdw's avatar
pdw committed
371 372
          break;
        case OPTION_LINEDISPLAY_ONE_LINE_SENT:
pdw's avatar
pdw committed
373
          draw_bar(line->sent[options.bar_interval],y);
pdw's avatar
pdw committed
374 375
          break;
        case OPTION_LINEDISPLAY_ONE_LINE_RECV:
pdw's avatar
pdw committed
376
          draw_bar(line->recv[options.bar_interval],y);
pdw's avatar
pdw committed
377 378
          break;
        case OPTION_LINEDISPLAY_ONE_LINE_BOTH:
pdw's avatar
pdw committed
379
          draw_bar(line->recv[options.bar_interval] + line->sent[options.bar_interval],y);
pdw's avatar
pdw committed
380 381
          break;
      }
pdw's avatar
pdw committed
382
    }
pdw's avatar
pdw committed
383 384 385 386
}

void draw_totals(host_pair_line* totals) {
    /* Draw rule */
pdw's avatar
pdw committed
387
    int y = LINES - 4;
pdw's avatar
pdw committed
388
    int j;
pdw's avatar
pdw committed
389 390
    char buf[10];
    int x = (COLS - 8 * HISTORY_DIVISIONS);
pdw's avatar
pdw committed
391
    y++;
pdw's avatar
pdw committed
392
    draw_line_totals(y, totals, OPTION_LINEDISPLAY_TWO_LINE);
pdw's avatar
pdw committed
393 394
    y += 2;
    for(j = 0; j < HISTORY_DIVISIONS; j++) {
pdw's avatar
pdw committed
395
        readable_size((totals->sent[j] + totals->recv[j]) , buf, 10, 1024, options.bandwidth_in_bytes);
pdw's avatar
pdw committed
396 397 398
        mvaddstr(y, x, buf);
        x += 8;
    }
chris's avatar
chris committed
399 400
}

pdw's avatar
pdw committed
401
extern history_type history_totals;
pdw's avatar
pdw committed
402

403 404 405 406
void screen_list_init() {
    screen_list.compare = &screen_line_compare;
    sorted_list_initialise(&screen_list);
}
chris's avatar
chris committed
407

408
void screen_list_clear() {
pdw's avatar
pdw committed
409
    sorted_list_node* nn = NULL;
410 411 412
    peaksent = peakrecv = peaktotal = 0;
    while((nn = sorted_list_next_item(&screen_list, nn)) != NULL) {
        free(nn->data);
chris's avatar
chris committed
413
    }
414 415
    sorted_list_destroy(&screen_list);
}
chris's avatar
chris committed
416

pdw's avatar
pdw committed
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
void calculate_totals() {
    int i;

    /**
     * Calculate peaks and totals
     */
    for(i = 0; i < HISTORY_LENGTH; i++) {
        int j;
        int ii = (HISTORY_LENGTH + history_pos - i) % HISTORY_LENGTH;

        for(j = 0; j < HISTORY_DIVISIONS; j++) {
            if(i < history_divs[j]) {
                totals.recv[j] += history_totals.recv[ii];
                totals.sent[j] += history_totals.sent[ii];
            }
        }

        if(history_totals.recv[i] > peakrecv) {
            peakrecv = history_totals.recv[i];
        }
        if(history_totals.sent[i] > peaksent) {
            peaksent = history_totals.sent[i];
        }
        if(history_totals.recv[i] + history_totals.sent[i] > peaktotal) {
            peaktotal = history_totals.recv[i] + history_totals.sent[i];	
        }
    }
pdw's avatar
pdw committed
444 445 446 447 448
    for(i = 0; i < HISTORY_DIVISIONS; i++) {
      int t = history_length(i);
      totals.recv[i] /= t;
      totals.sent[i] /= t;
    }
pdw's avatar
pdw committed
449 450 451 452 453
}

void make_screen_list() {
    hash_node_type* n = NULL;
    while(hash_next_item(screen_hash, &n) == HASH_STATUS_OK) {
pdw's avatar
pdw committed
454 455 456 457 458 459 460
        host_pair_line* line = (host_pair_line*)n->rec;
        int i;
        for(i = 0; i < HISTORY_DIVISIONS; i++) {
          line->recv[i] /= history_length(i);
          line->sent[i] /= history_length(i);
        }

pdw's avatar
pdw committed
461 462 463 464 465 466
        /* Don't make a new, sorted screen list if order is frozen
         */
        if(!options.freezeorder) {
            sorted_list_insert(&screen_list, line);
        } 
	 
pdw's avatar
pdw committed
467 468 469
    }
}

470 471 472 473 474 475 476
/*
 * Zeros all data in the screen hash, but does not remove items.
 */
void screen_hash_clear() {
    hash_node_type* n = NULL;
    while(hash_next_item(screen_hash, &n) == HASH_STATUS_OK) {
        host_pair_line* hpl = (host_pair_line*)n->rec;
477
        hpl->total_recv = hpl->total_sent = 0;
478 479 480 481 482
        memset(hpl->recv, 0, sizeof(hpl->recv));
        memset(hpl->sent, 0, sizeof(hpl->sent));
    }
}

483 484
void analyse_data() {
    hash_node_type* n = NULL;
pdw's avatar
pdw committed
485

pdw's avatar
pdw committed
486
    if(options.paused == 1) {
pdw's avatar
pdw committed
487 488 489
      return;
    }

pdw's avatar
pdw committed
490
    // Zero totals
pdw's avatar
pdw committed
491 492
    memset(&totals, 0, sizeof totals);

493 494 495 496 497 498 499
    if(options.freezeorder) {
      screen_hash_clear();
    }
    else {
      screen_list_clear();
      hash_delete_all(screen_hash);
    }
500

pdw's avatar
pdw committed
501 502 503
    while(hash_next_item(history, &n) == HASH_STATUS_OK) {
        history_type* d = (history_type*)n->rec;
        host_pair_line* screen_line;
504 505 506 507
	union {
	    host_pair_line **h_p_l_pp;
	    void **void_pp;
	} u_screen_line = { &screen_line };
508
        addr_pair ap;
pdw's avatar
pdw committed
509
        int i;
510 511
        int tsent, trecv;
        tsent = trecv = 0;
pdw's avatar
pdw committed
512

513

514 515
        ap = *(addr_pair*)n->key;

516
        /* Aggregate hosts, if required */
517
        if(options.aggregate_src) {
518
            memset(&ap.src6, '\0', sizeof(ap.src6));
519
        }
520
        if(options.aggregate_dest) {
521
            memset(&ap.dst6, '\0', sizeof(ap.dst6));
522
        }
523 524

        /* Aggregate ports, if required */
525
        if(options.showports == OPTION_PORTS_DEST || options.showports == OPTION_PORTS_OFF) {
526 527
            ap.src_port = 0;
        }
528
        if(options.showports == OPTION_PORTS_SRC || options.showports == OPTION_PORTS_OFF) {
529 530
            ap.dst_port = 0;
        }
pdw's avatar
pdw committed
531 532 533
        if(options.showports == OPTION_PORTS_OFF) {
            ap.protocol = 0;
        }
534

535
	
536
        if(hash_find(screen_hash, &ap, u_screen_line.void_pp) == HASH_STATUS_KEY_NOT_FOUND) {
537
            screen_line = xcalloc(1, sizeof *screen_line);
538 539 540
            hash_insert(screen_hash, &ap, screen_line);
            screen_line->ap = ap;
        }
pdw's avatar
pdw committed
541
        
pdw's avatar
pdw committed
542 543 544
	screen_line->total_sent += d->total_sent;
	screen_line->total_recv += d->total_recv;

pdw's avatar
pdw committed
545 546 547
        for(i = 0; i < HISTORY_LENGTH; i++) {
            int j;
            int ii = (HISTORY_LENGTH + history_pos - i) % HISTORY_LENGTH;
pdw's avatar
pdw committed
548

pdw's avatar
pdw committed
549 550 551 552 553 554 555 556 557
            for(j = 0; j < HISTORY_DIVISIONS; j++) {
                if(i < history_divs[j]) {
                    screen_line->recv[j] += d->recv[ii];
                    screen_line->sent[j] += d->sent[ii];
                }
            }
        }

    }
558

pdw's avatar
pdw committed
559
    make_screen_list();
pdw's avatar
pdw committed
560

pdw's avatar
pdw committed
561
    
pdw's avatar
pdw committed
562
    calculate_totals();
pdw's avatar
pdw committed
563

564 565
}

566
void sprint_host(char * line, int af, struct in6_addr* addr, unsigned int port, unsigned int protocol, int L, int unspecified_as_star) {
567
    char hostname[HOSTNAME_LENGTH];
568 569
    char service[HOSTNAME_LENGTH];
    char* s_name;
570 571 572 573 574
    union {
        char **ch_pp;
        void **void_pp;
    } u_s_name = { &s_name };

575
    ip_service skey;
576
    int left;
577

578
    if(IN6_IS_ADDR_UNSPECIFIED(addr) && unspecified_as_star) {
579 580 581 582
        sprintf(hostname, " * ");
    }
    else {
        if (options.dnsresolution)
583
            resolve(af, addr, hostname, L);
584
        else
585
            inet_ntop(af, addr, hostname, sizeof(hostname));
586 587 588 589
    }
    left = strlen(hostname);

    if(port != 0) {
590 591
      skey.port = port;
      skey.protocol = protocol;
592
      if(options.portresolution && hash_find(service_hash, &skey, u_s_name.void_pp) == HASH_STATUS_OK) {
593
        snprintf(service, HOSTNAME_LENGTH, ":%s", s_name);
594 595
      }
      else {
596
        snprintf(service, HOSTNAME_LENGTH, ":%d", port);
597 598 599 600 601
      }
    }
    else {
      service[0] = '\0';
    }
602 603 604 605 606 607 608 609 610 611
    
    /* If we're showing IPv6 addresses with a port number, put them in square
     * brackets. */
    if(port == 0 || af == AF_INET || L < 2) {
      sprintf(line, "%-*s", L, hostname);
    }
    else {
      sprintf(line, "[%-.*s]", L-2, hostname);
      left += 2;
    }
612 613 614 615 616 617 618 619 620
    if(left > (L - strlen(service))) {
        left = L - strlen(service);
        if(left < 0) {
           left = 0;
        }
    }
    sprintf(line + left, "%-*s", L-left, service);
}

pdw's avatar
pdw committed
621

pdw's avatar
pdw committed
622

623 624
void ui_print() {
    sorted_list_node* nn = NULL;
625
    char host1[HOSTNAME_LENGTH], host2[HOSTNAME_LENGTH];
626 627
    static char *line;
    static int lcols;
pdw's avatar
pdw committed
628
    int y = 0;
629

chris's avatar
chris committed
630 631 632
    if (dontshowdisplay)
        return;

633 634 635 636 637
    if (!line || lcols != COLS) {
        xfree(line);
        line = calloc(COLS + 1, 1);
    }

pdw's avatar
pdw committed
638 639 640 641 642
    /* 
     * erase() is faster than clear().  Dunno why we switched to 
     * clear() -pdw 24/10/02
     */
    erase();
643

644 645
    draw_bar_scale(&y);

pdw's avatar
pdw committed
646 647 648 649
    if(options.showhelp) {
      mvaddstr(y,0,HELP_MESSAGE);
    }
    else {
pdw's avatar
pdw committed
650 651 652 653 654
      int i = 0;

      while(i < options.screen_offset && ((nn = sorted_list_next_item(&screen_list, nn)) != NULL)) {
        i++;
      }
655

pdw's avatar
pdw committed
656 657 658
      /* Screen layout: we have 2 * HISTORY_DIVISIONS 6-character wide history
       * items, and so can use COLS - 12 * HISTORY_DIVISIONS to print the two
       * host names. */
chris's avatar
chris committed
659

pdw's avatar
pdw committed
660 661 662
      if(i == 0 || nn != NULL) {
        while((y < LINES - 5) && ((nn = sorted_list_next_item(&screen_list, nn)) != NULL)) {
            int x = 0, L;
663

pdw's avatar
pdw committed
664

pdw's avatar
pdw committed
665
            host_pair_line* screen_line = (host_pair_line*)nn->data;
pdw's avatar
pdw committed
666

pdw's avatar
pdw committed
667 668
            if(y < LINES - 5) {
                L = (COLS - 8 * HISTORY_DIVISIONS - 4) / 2;
pdw's avatar
pdw committed
669 670 671
                if(options.show_totals) {
                    L -= 4;    
                }
pdw's avatar
pdw committed
672 673 674
                if(L > HOSTNAME_LENGTH) {
                    L = HOSTNAME_LENGTH;
                }
675

676 677 678
                sprint_host(host1, screen_line->ap.af,
                            &(screen_line->ap.src6),
                            screen_line->ap.src_port,
679
                            screen_line->ap.protocol, L, options.aggregate_src);
680 681 682
                sprint_host(host2, screen_line->ap.af,
                            &(screen_line->ap.dst6),
                            screen_line->ap.dst_port,
683
                            screen_line->ap.protocol, L, options.aggregate_dest);
684

pdw's avatar
pdw committed
685 686 687
                if(!screen_filter_match(host1) && !screen_filter_match(host2)) {
                  continue;
                }
pdw's avatar
pdw committed
688

pdw's avatar
pdw committed
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
                mvaddstr(y, x, host1);
                x += L;

                switch(options.linedisplay) {
                  case OPTION_LINEDISPLAY_TWO_LINE:
                    mvaddstr(y, x, " => ");
                    mvaddstr(y+1, x, " <= ");
                    break;
                  case OPTION_LINEDISPLAY_ONE_LINE_BOTH:
                    mvaddstr(y, x, "<=> ");
                    break;
                  case OPTION_LINEDISPLAY_ONE_LINE_SENT:
                    mvaddstr(y, x, " => ");
                    break;
                  case OPTION_LINEDISPLAY_ONE_LINE_RECV:
                    mvaddstr(y, x, " <= ");
                    break;
                }
pdw's avatar
pdw committed
707

pdw's avatar
pdw committed
708
                x += 4;
709 710


pdw's avatar
pdw committed
711 712
                mvaddstr(y, x, host2);
                
pdw's avatar
pdw committed
713 714 715 716
                if(options.show_totals) {
                    draw_line_total(screen_line->total_sent, screen_line->total_recv, y, COLS - 8 * (HISTORY_DIVISIONS + 1), options.linedisplay, 1);
                }

pdw's avatar
pdw committed
717
                draw_line_totals(y, screen_line, options.linedisplay);
pdw's avatar
pdw committed
718

pdw's avatar
pdw committed
719 720 721 722 723 724 725 726
            }
            if(options.linedisplay == OPTION_LINEDISPLAY_TWO_LINE) {
              y += 2;
            }
            else {
              y += 1;
            }
        }
pdw's avatar
pdw committed
727
      }
pdw's avatar
pdw committed
728
    }
pdw's avatar
pdw committed
729 730


pdw's avatar
pdw committed
731
    y = LINES - 3;
pdw's avatar
pdw committed
732 733
    
    mvhline(y-1, 0, 0, COLS);
pdw's avatar
pdw committed
734

pdw's avatar
pdw committed
735 736
    mvaddstr(y, 0, "TX: ");
    mvaddstr(y+1, 0, "RX: ");
pdw's avatar
pdw committed
737
    mvaddstr(y+2, 0, "TOTAL: ");
pdw's avatar
pdw committed
738

pdw's avatar
pdw committed
739
    /* Cummulative totals */
740
    mvaddstr(y, 16, "cum: ");
pdw's avatar
pdw committed
741

pdw's avatar
pdw committed
742
    readable_size(history_totals.total_sent, line, 10, 1024, 1);
pdw's avatar
pdw committed
743 744
    mvaddstr(y, 22, line);

pdw's avatar
pdw committed
745
    readable_size(history_totals.total_recv, line, 10, 1024, 1);
pdw's avatar
pdw committed
746 747
    mvaddstr(y+1, 22, line);

pdw's avatar
pdw committed
748
    readable_size(history_totals.total_recv + history_totals.total_sent, line, 10, 1024, 1);
pdw's avatar
pdw committed
749
    mvaddstr(y+2, 22, line);
pdw's avatar
pdw committed
750 751 752

    /* peak traffic */
    mvaddstr(y, 32, "peak: ");
pdw's avatar
pdw committed
753

754
    readable_size(peaksent / RESOLUTION, line, 10, 1024, options.bandwidth_in_bytes);
pdw's avatar
pdw committed
755
    mvaddstr(y, 39, line);
pdw's avatar
pdw committed
756

757
    readable_size(peakrecv / RESOLUTION, line, 10, 1024, options.bandwidth_in_bytes);
pdw's avatar
pdw committed
758
    mvaddstr(y+1, 39, line);
pdw's avatar
pdw committed
759

pdw's avatar
pdw committed
760
    readable_size(peaktotal / RESOLUTION, line, 10, 1024, options.bandwidth_in_bytes);
pdw's avatar
pdw committed
761
    mvaddstr(y+2, 39, line);
pdw's avatar
pdw committed
762 763

    mvaddstr(y, COLS - 8 * HISTORY_DIVISIONS - 8, "rates:");
pdw's avatar
pdw committed
764

chris's avatar
chris committed
765
    draw_totals(&totals);
pdw's avatar
pdw committed
766

pdw's avatar
pdw committed
767

pdw's avatar
pdw committed
768
    if(showhelphint) {
chris's avatar
chris committed
769 770 771 772
      mvaddstr(0, 0, " ");
      mvaddstr(0, 1, helpmsg);
      mvaddstr(0, 1 + strlen(helpmsg), " ");
      mvchgat(0, 0, strlen(helpmsg) + 2, A_REVERSE, 0, NULL);
pdw's avatar
pdw committed
773
    }
774
    move(LINES - 1, COLS - 1);
chris's avatar
chris committed
775
    
pdw's avatar
pdw committed
776 777
    refresh();

chris's avatar
chris committed
778
    /* Bar chart auto scale */
779
    if (wantbiggerrate && options.max_bandwidth == 0) {
780 781
      ++rateidx;
      wantbiggerrate = 0;
chris's avatar
chris committed
782
    }
pdw's avatar
pdw committed
783 784
}

pdw's avatar
pdw committed
785 786 787 788
void ui_tick(int print) {
  if(print) {
    ui_print();
  }
789
  else if(showhelphint && (time(NULL) - helptimer > HELP_TIME) && !persistenthelp) {
pdw's avatar
pdw committed
790 791 792 793 794
    showhelphint = 0;
    ui_print();
  }
}

chris's avatar
chris committed
795
void ui_curses_init() {
pdw's avatar
pdw committed
796 797 798 799 800
    (void) initscr();      /* initialize the curses library */
    keypad(stdscr, TRUE);  /* enable keyboard mapping */
    (void) nonl();         /* tell curses not to do NL->CR/NL on output */
    (void) cbreak();       /* take input chars one at a time, no wait for \n */
    (void) noecho();       /* don't echo input */
pdw's avatar
pdw committed
801
    halfdelay(2);
chris's avatar
chris committed
802
}
pdw's avatar
pdw committed
803

804 805 806 807 808 809 810 811
void showhelp(const char * s) {
  strncpy(helpmsg, s, HELP_MSG_SIZE);
  showhelphint = 1;
  helptimer = time(NULL);
  persistenthelp = 0;
  tick(1);
}

chris's avatar
chris committed
812
void ui_init() {
813
    char msg[20];
chris's avatar
chris committed
814 815
    ui_curses_init();
    
chris's avatar
chris committed
816
    erase();
817 818

    screen_list_init();
819
    screen_hash = addr_hash_create();
820

821 822 823
    service_hash = serv_hash_create();
    serv_hash_initialise(service_hash);

824 825
    snprintf(msg,20,"Listening on %s",options.interface);
    showhelp(msg);
826

827

pdw's avatar
pdw committed
828 829
}

830

pdw's avatar
pdw committed
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
void showportstatus() {
  if(options.showports == OPTION_PORTS_ON) {
    showhelp("Port display ON");
  }
  else if(options.showports == OPTION_PORTS_OFF) {
    showhelp("Port display OFF");
  }
  else if(options.showports == OPTION_PORTS_DEST) {
    showhelp("Port display DEST");
  }
  else if(options.showports == OPTION_PORTS_SRC) {
    showhelp("Port display SOURCE");
  }
}

chris's avatar
chris committed
846

847
void ui_loop() {
chris's avatar
chris committed
848 849 850
    /* in edline.c */
    char *edline(int linenum, const char *prompt, const char *initial);
    /* in iftop.c */
chris's avatar
chris committed
851
    char *set_filter_code(const char *filter);
chris's avatar
chris committed
852

853
    extern sig_atomic_t foad;
chris's avatar
chris committed
854

chris's avatar
chris committed
855
    while(foad == 0) {
chris's avatar
chris committed
856
        int i;
857
        i = getch();
chris's avatar
chris committed
858
        switch (i) {
859
            case 'q':
chris's avatar
chris committed
860 861 862
                foad = 1;
                break;

863
            case 'n':
pdw's avatar
pdw committed
864 865 866 867 868 869 870 871
                if(options.dnsresolution) {
                    options.dnsresolution = 0;
                    showhelp("DNS resolution off");
                }
                else {
                    options.dnsresolution = 1;
                    showhelp("DNS resolution on");
                }
872
                tick(1);
chris's avatar
chris committed
873
                break;
pdw's avatar
pdw committed
874

875
            case 'N':
pdw's avatar
pdw committed
876 877 878 879 880 881 882 883
                if(options.portresolution) {
                    options.portresolution = 0;
                    showhelp("Port resolution off");
                }
                else {
                    options.portresolution = 1;
                    showhelp("Port resolution on");
                }
884 885 886
                tick(1);
                break;

pdw's avatar
pdw committed
887
            case 'h':
chris's avatar
chris committed
888
            case '?':
pdw's avatar
pdw committed
889 890 891 892
                options.showhelp = !options.showhelp;
                tick(1);
                break;

pdw's avatar
pdw committed
893
            case 'b':
pdw's avatar
pdw committed
894 895 896 897 898 899 900 901
                if(options.showbars) {
                    options.showbars = 0;
                    showhelp("Bars off");
                }
                else {
                    options.showbars = 1;
                    showhelp("Bars on");
                }
902
                tick(1);
pdw's avatar
pdw committed
903
                break;
904

pdw's avatar
pdw committed
905 906 907 908 909 910 911 912 913 914 915 916 917
            case 'B':
                options.bar_interval = (options.bar_interval + 1) % 3;
                if(options.bar_interval == 0) {
                    showhelp("Bars show 2s average");
                }
                else if(options.bar_interval == 1) { 
                    showhelp("Bars show 10s average");
                }
                else {
                    showhelp("Bars show 40s average");
                }
                ui_print();
                break;
918
            case 's':
pdw's avatar
pdw committed
919 920 921 922 923 924 925 926
                if(options.aggregate_src) {
                    options.aggregate_src = 0;
                    showhelp("Show source host");
                }
                else {
                    options.aggregate_src = 1;
                    showhelp("Hide source host");
                }
927
                break;
928
            case 'd':
pdw's avatar
pdw committed
929 930 931 932 933 934 935 936
                if(options.aggregate_dest) {
                    options.aggregate_dest = 0;
                    showhelp("Show dest host");
                }
                else {
                    options.aggregate_dest = 1;
                    showhelp("Hide dest host");
                }
937
                break;
938 939 940 941 942 943 944 945 946 947 948 949 950 951
            case 'S':
                /* Show source ports */
                if(options.showports == OPTION_PORTS_OFF) {
                  options.showports = OPTION_PORTS_SRC;
                }
                else if(options.showports == OPTION_PORTS_DEST) {
                  options.showports = OPTION_PORTS_ON;
                }
                else if(options.showports == OPTION_PORTS_ON) {
                  options.showports = OPTION_PORTS_DEST;
                }
                else {
                  options.showports = OPTION_PORTS_OFF;
                }
pdw's avatar
pdw committed
952
                showportstatus();
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
                break;
            case 'D':
                /* Show dest ports */
                if(options.showports == OPTION_PORTS_OFF) {
                  options.showports = OPTION_PORTS_DEST;
                }
                else if(options.showports == OPTION_PORTS_SRC) {
                  options.showports = OPTION_PORTS_ON;
                }
                else if(options.showports == OPTION_PORTS_ON) {
                  options.showports = OPTION_PORTS_SRC;
                }
                else {
                  options.showports = OPTION_PORTS_OFF;
                }
pdw's avatar
pdw committed
968
                showportstatus();
969 970
                break;
            case 'p':
971 972 973 974
                options.showports = 
                  (options.showports == OPTION_PORTS_OFF)
                  ? OPTION_PORTS_ON
                  : OPTION_PORTS_OFF;
pdw's avatar
pdw committed
975
                showportstatus();
976 977
                // Don't tick here, otherwise we get a bogus display
                break;
pdw's avatar
pdw committed
978
            case 'P':
979 980 981 982 983 984 985 986 987
                if(options.paused) {
                    options.paused = 0;
                    showhelp("Display unpaused");
                }
                else {
                    options.paused = 1;
                    showhelp("Display paused");
                    persistenthelp = 1;
                }
pdw's avatar
pdw committed
988
                break;
989 990 991 992 993 994 995 996
            case 'o':
                if(options.freezeorder) {
                    options.freezeorder = 0;
                    showhelp("Order unfrozen");
                }
                else {
                    options.freezeorder = 1;
                    showhelp("Order frozen");
997
                    persistenthelp = 1;
998 999
                }
                break;
pdw's avatar
pdw committed
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
            case '1':
                options.sort = OPTION_SORT_DIV1;
                showhelp("Sort by col 1");
                break;
            case '2':
                options.sort = OPTION_SORT_DIV2;
                showhelp("Sort by col 2");
                break;
            case '3':
                options.sort = OPTION_SORT_DIV3;
                showhelp("Sort by col 3");
                break;
            case '<':
                options.sort = OPTION_SORT_SRC;
                showhelp("Sort by source");
                break;
            case '>':
                options.sort = OPTION_SORT_DEST;
                showhelp("Sort by dest");
                break;
pdw's avatar
pdw committed
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
            case 'j':
                options.screen_offset++;
                ui_print();
                break;
            case 'k':
                if(options.screen_offset > 0) {
                  options.screen_offset--;
                  ui_print();
                }
                break;
            case 't':
                options.linedisplay = (options.linedisplay + 1) % 4;
                switch(options.linedisplay) {
                  case OPTION_LINEDISPLAY_TWO_LINE:
                    showhelp("Two lines per host");
                    break;
                  case OPTION_LINEDISPLAY_ONE_LINE_SENT:
                    showhelp("Sent traffic only");
                    break;
                  case OPTION_LINEDISPLAY_ONE_LINE_RECV:
                    showhelp("Received traffic only");
                    break;
                  case OPTION_LINEDISPLAY_ONE_LINE_BOTH:
                    showhelp("One line per host");
                    break;
                }
                ui_print();
                break;
chris's avatar
chris committed
1048 1049 1050
            case 'f': {
                char *s;
                dontshowdisplay = 1;
1051
                if ((s = edline(0, "Net filter", options.filtercode))) {
chris's avatar
chris committed
1052
                    char *m;
chris's avatar
chris committed
1053 1054 1055 1056 1057
                    if (s[strspn(s, " \t")] == 0) {
                        /* Empty filter; set to NULL. */
                        xfree(s);
                        s = NULL;
                    }
chris's avatar
chris committed
1058 1059 1060
                    if (!(m = set_filter_code(s))) {
                        xfree(options.filtercode);
                        options.filtercode = s;
chris's avatar
chris committed
1061 1062
                        /* -lpcap will write junk to stderr; we do our best to
                         * erase it.... */
chris's avatar
chris committed
1063 1064 1065
                        move(COLS - 1, LINES - 1);
                        wrefresh(curscr);
                        showhelp("Installed new filter");
chris's avatar
chris committed
1066 1067 1068 1069 1070 1071
                    } else {
                        showhelp(m);
                        xfree(s);
                    }
                }
                dontshowdisplay = 0;
pdw's avatar
pdw committed
1072
                ui_print();
chris's avatar
chris committed
1073 1074
                break;
            }
1075
            case 'l': {
chris's avatar
chris committed
1076
#ifdef HAVE_REGCOMP
1077 1078 1079 1080 1081 1082 1083 1084
                char *s;
                dontshowdisplay = 1;
                if ((s = edline(0, "Screen filter", options.screenfilter))) {
                    if(!screen_filter_set(s)) {
                        showhelp("Invalid regexp");
                    }
                }
                dontshowdisplay = 0;
pdw's avatar
pdw committed
1085
                ui_print();
chris's avatar
chris committed
1086 1087 1088
#else
                showhelp("Sorry, screen filters not supported on this platform")
#endif
1089 1090
                break;
            }
chris's avatar
chris committed
1091
            case '!': {
1092
#ifdef ALLOW_SUBSHELL
chris's avatar
chris committed
1093 1094
                char *s;
                dontshowdisplay = 1;
chris's avatar
chris committed
1095
                if ((s = edline(0, "Command", "")) && s[strspn(s, " \t")]) {
chris's avatar
chris committed
1096
                    int i, dowait = 0;
chris's avatar
chris committed
1097 1098 1099 1100 1101 1102 1103
                    erase();
                    refresh();
                    endwin();
                    errno = 0;
                    i = system(s);
                    if (i == -1 || (i == 127 && errno != 0)) {
                        fprintf(stderr, "system: %s: %s\n", s, strerror(errno));
chris's avatar
chris committed
1104
                        dowait = 1;
chris's avatar
chris committed
1105 1106 1107 1108 1109
                    } else if (i != 0) {
                        if (WIFEXITED(i))
                            fprintf(stderr, "%s: exited with code %d\n", s, WEXITSTATUS(i));
                        else if (WIFSIGNALED(i))
                            fprintf(stderr, "%s: killed by signal %d\n", s, WTERMSIG(i));
chris's avatar
chris committed
1110
                        dowait = 1;
chris's avatar
chris committed
1111 1112
                    }
                    ui_curses_init();
chris's avatar
chris committed
1113 1114 1115 1116
                    if (dowait) {
                        fprintf(stderr, "Press any key....");
                        while (getch() == ERR);
                    }
chris's avatar
chris committed
1117 1118 1119 1120
                    erase();
                    xfree(s);
                }
                dontshowdisplay = 0;
1121 1122 1123
#else
                showhelp("Sorry, subshells have been disabled.");
#endif
chris's avatar
chris committed
1124
                break;
chris's avatar
chris committed
1125
            }
pdw's avatar
pdw committed
1126 1127 1128
            case 'T':
                options.show_totals = !options.show_totals;
                if(options.show_totals) {
1129
                    showhelp("Show cumulative totals");
pdw's avatar
pdw committed
1130 1131
                }
                else {
1132
                    showhelp("Hide cumulative totals");
pdw's avatar
pdw committed
1133 1134 1135
                }
                ui_print();
                break;
pdw's avatar
pdw committed
1136 1137 1138 1139 1140
            case 'L':
                options.log_scale = !options.log_scale;
                showhelp(options.log_scale ? "Logarithmic scale" : "Linear scale");
                ui_print();
                break;
chris's avatar
chris committed
1141 1142 1143 1144
            case KEY_CLEAR:
            case 12:    /* ^L */
                wrefresh(curscr);
                break;
pdw's avatar
pdw committed
1145 1146 1147
            case ERR:
                break;
            default:
chris's avatar
chris committed
1148
                showhelp("Press H or ? for help");
pdw's avatar
pdw committed
1149
                break;
pdw's avatar
pdw committed
1150
        }
1151
        tick(0);
pdw's avatar
pdw committed
1152 1153 1154 1155 1156 1157
    }
}

void ui_finish() {
    endwin();
}