Example #1
0
void
initscreen()
{
    if (!SCREENTEST())
        errx(1, "can't sail on this terminal.");
    /* initscr() already done in SCREENTEST() */
    view_w = newwin(VIEW_Y, VIEW_X, VIEW_T, VIEW_L);
    slot_w = newwin(SLOT_Y, SLOT_X, SLOT_T, SLOT_L);
    scroll_w = newwin(SCROLL_Y, SCROLL_X, SCROLL_T, SCROLL_L);
    stat_w = newwin(STAT_Y, STAT_X, STAT_T, STAT_L);
    turn_w = newwin(TURN_Y, TURN_X, TURN_T, TURN_L);
    done_curses++;
    (void) leaveok(view_w, 1);
    (void) leaveok(slot_w, 1);
    (void) leaveok(stat_w, 1);
    (void) leaveok(turn_w, 1);
    noecho();
    cbreak();
}
Example #2
0
static void draw_log_window(void)
{
	idlok(win_txt, FALSE);
	/* Get scrolling */
	scrollok(win_txt, TRUE);

	/* Leave cursor where it was */
	leaveok(win_txt, TRUE);
	wbkgd(win_txt, COLOR_PAIR(BLACK_ON_CYAN));
	wrefresh(win_txt);
}
Example #3
0
cCursesOsd::cCursesOsd(int Left, int Top)
:cOsd(Left, Top, 0)
{
  savedRegion = NULL;

  memset(colorPairs, 0x00, sizeof(colorPairs));
  start_color();
  leaveok(stdscr, true);

  window = subwin(stdscr, ScOsdHeight, ScOsdWidth, 0, 0);
  syncok(window, true);
}
Example #4
0
void
screen_showDialog(Screen *self, const char *title, const char *fmt, ...)
{
    va_list ap;
    int w, h, y, x, i;
    size_t l;
    char *buf;
    char *lines[10];
    WINDOW *dlg;

    l = strlen(fmt)*2;
    buf = malloc(l);
    va_start(ap, fmt);
    vsnprintf(buf, l, fmt, ap);
    va_end(ap);

    lines[0] = strtok(buf, "\n");
    for (i = 1; i < 10; ++i)
    {
        lines[i] = strtok(0, "\n");
        if (!lines[i]) break;
    }
    h = i;

    w = (int)strlen(title);
    for (i = 0; i < h; ++i)
    {
        l = strlen(lines[i]);
        if (l > (size_t)w) w = (int)l;
    }

    h += 4;
    w += 4;
    y = (self->h - h) >> 1;
    x = (self->w - w) >> 1;

    dlg = subwin(self->field, h, w, y, x);
    leaveok(dlg, 1);
    werase(dlg);
    wbkgd(dlg, COLOR_PAIR(CP_DIALOG));
    box(dlg, 0, 0);

    mvwaddstr(dlg, 1, 2 + (w-4-(int)strlen(title))/2, title);
    for (i = 0; i < h-4; ++i)
    {
        mvwaddstr(dlg, i+3, 2, lines[i]);
    }

    free(buf);
    wrefresh(dlg);
    delwin(dlg);
}
Example #5
0
/*
 * getguess:
 *	Get another guess
 */
getguess()
{
	register int	i;
	register int	ch;
	register bool	correct;

	leaveok(stdscr, FALSE);
	for (;;) {
		move(PROMPTY, PROMPTX + sizeof "Guess: ");
		refresh();
		ch = readch();
		if (isalpha(ch)) {
			if (isupper(ch))
				ch = tolower(ch);
			if (Guessed[ch - 'a'])
				mvprintw(MESGY, MESGX, "Already guessed '%c'", ch);
			else
				break;
		}
		else if (ch == CTRL(D))
			die();
		else
			mvprintw(MESGY, MESGX, "Not a valid guess: '%s'",
				unctrl(ch));
	}
	leaveok(stdscr, TRUE);
	move(MESGY, MESGX);
	clrtoeol();

	Guessed[ch - 'a'] = TRUE;
	correct = FALSE;
	for (i = 0; Word[i] != '\0'; i++)
		if (Word[i] == ch) {
			Known[i] = ch;
			correct = TRUE;
		}
	if (!correct)
		Errors++;
}
Example #6
0
static void stats_display_layout(uint8_t in_place)
{
	uint8_t cur_stats_height;

	cur_stats_height = current_screen->get_height();
	cur_stats_height = cur_stats_height > max_n_lines? max_n_lines: cur_stats_height;

	display_lock();
	if (!in_place) {
		// moving existing windows does not work
		delwin(win_txt);
		delwin(win_general);
		delwin(win_title);
		delwin(win_tabs);
		delwin(win_cmd);
		delwin(win_txt);
		delwin(win_help);

		clear();
	}

	if (!in_place) {
		win_stat = create_subwindow(cur_stats_height + 2, 0, 4, 0);
		win_tabs = create_subwindow(1, 0, 1, 0);
		win_general = create_subwindow(2, 0, 2, 0);
		win_title = create_subwindow(1, 0, 0, 0);
		win_cmd = create_subwindow(1, 0, cur_stats_height + 2 + 4,  0);
		win_txt_height = LINES - cur_stats_height - 2 - 3 - 3;
		win_txt = create_subwindow(win_txt_height, 0, cur_stats_height + 4 + 3, 0);
		win_help = create_subwindow(1, 0, LINES - 1, 0);
	}

	draw_title();
	draw_general_frame();
	/* Command line */
	wbkgd(win_cmd, COLOR_PAIR(BLACK_ON_YELLOW));
	idlok(win_cmd, FALSE);
	/* Move cursor at insertion point */
	leaveok(win_cmd, FALSE);

	draw_status_bar();
	draw_log_window();

	/* Draw everything to the screen */
	refresh();
	current_screen->draw_frame(&screen_state);
	display_unlock();

	refresh_cmd_win();
	display_stats();
}
Example #7
0
/*
 *	Get a yes or no answer to the given question.  Saves are
 * also allowed.  Return TRUE if the answer was yes, FALSE if no.
 */
int
getyn(int promptno)
{
	char	c;

	Saved = FALSE;
	for (;;) {
		leaveok(Board, FALSE);
		prompt(promptno);
		clrtoeol();
		refresh();
		switch (c = readch()) {
		  case 'n':	case 'N':
			addch('N');
			refresh();
			leaveok(Board, TRUE);
			return FALSE;
		  case 'y':	case 'Y':
			addch('Y');
			refresh();
			leaveok(Board, TRUE);
			return TRUE;
		  case 's':	case 'S':
			addch('S');
			refresh();
			Saved = save();
			continue;
		  case CTRL('L'):
			wrefresh(curscr);
			break;
		  default:
			addstr(unctrl(c));
			refresh();
			putchar('\07');
			break;
		}
	}
}
Example #8
0
void startmenu(menu *mp, char *mtitle)
{
    initscr();
    incurses = TRUE;
    initcolor();

    wtitl = subwin(stdscr, th, bw, 0, 0);
    wmain = subwin(stdscr, mh, bw, th, 0);
    wbody = subwin(stdscr, bh, bw, th + mh, 0);
    wstat = subwin(stdscr, sh, bw, th + mh + bh, 0);

    colorbox(wtitl, TITLECOLOR, 0);
    colorbox(wmain, MAINMENUCOLOR, 0);
    colorbox(wbody, BODYCOLOR, 0);
    colorbox(wstat, STATUSCOLOR, 0);

    if (mtitle)
        titlemsg(mtitle);

    cbreak();              /* direct input (no newline required)... */
    noecho();              /* ... without echoing */
    curs_set(0);           /* hide cursor (if possible) */
    nodelay(wbody, TRUE);  /* don't wait for input... */
    halfdelay(10);         /* ...well, no more than a second, anyway */
    keypad(wbody, TRUE);   /* enable cursor keys */
    scrollok(wbody, TRUE); /* enable scrolling in main window */

    leaveok(stdscr, TRUE);
    leaveok(wtitl, TRUE);
    leaveok(wmain, TRUE);
    leaveok(wstat, TRUE);

    mainmenu(mp);

    cleanup();
}
Example #9
0
int win_ini(int *fil, int *col, char creq, unsigned int inv)
{
  int p_fil,p_col;
  chtype wc;

  if (hi_ha_win) return(-1);       /* error si ja s'havia creat la finestra */
  if (initscr() == NULL) return(-2);    /* error en iniciar les curses */
  if ((*fil > LINES) || (*col > COLS))    /* error en les mides */
  { endwin();
    return(-3);
  }
  if (*fil == 0) *fil = LINES;	/* cas de mida maxima */
  if (*col == 0) *col = COLS;
  p_fil = (LINES - *fil)/ 2;		/* posicio de la finestra centrada */
  p_col = (COLS - *col) / 2;
                              /* canviar interrupcio de final de proces */
  oldsig = signal(SIGINT,win_fi);
	                     /* configuracio preliminar de les curses */
  cbreak();			/* rep tecles sense buffering */
  noecho();			/* no fa echo de les tecles llegides */
  nonl();			/* el newline \n no es tradueix a CR i LF */
  intrflush(stdscr,FALSE);	/* ^C no s'esborra del buffer d'entrada */
  keypad(stdscr,TRUE);		/* s'activa el teclat numeric i mov. cursor */

  win = newwin(*fil, *col, p_fil, p_col);

  if (win == NULL)            /* error en la creacio de la finestra */
  { endwin();
    return(-4);
  }
  hi_ha_win = TRUE;

  leaveok(win,TRUE);	/* dibuixar en pantalla no modificara el cursor */
  curs_set(0);		/* fixa el cursor com a invisible */
  nodelay(win,TRUE);
  refresh();		/* refresca la pantalla (inicialment l'esborra) */

  ufil = *fil;			/* memoritza numero files */
  ucol = *col;			/* memoritza numero columnes */
  wc = creq;			/* dibuixa el requadre */
  if (inv) wc |= A_REVERSE;
  mvwhline(win,0,0,wc,ucol);		/* fila superior */
  mvwhline(win,ufil-2,0,wc,ucol);	/* fila inferior */
  mvwvline(win,1,0,wc,ufil-2);		/* columna dreta */
  mvwvline(win,1,ucol-1,wc,ufil-2);	/* columna esquerra */
  wrefresh(win);		/* redibuixa el contingut de la finestra */
  return(0);			/* retorna OK */
}
Example #10
0
void display_init(void)
{
	scr = initscr();
	start_color();
	/* Assign default foreground/background colors to color number -1 */
	use_default_colors();

	init_pair(NO_COLOR,   -1,  -1);
	init_pair(RED_ON_BLACK,     COLOR_RED,  COLOR_BLACK);
	init_pair(BLACK_ON_CYAN,   COLOR_BLACK,  COLOR_CYAN);
	init_pair(BLACK_ON_GREEN,  COLOR_BLACK,  COLOR_GREEN);
	init_pair(BLACK_ON_WHITE,  COLOR_BLACK,  COLOR_WHITE);
	init_pair(BLACK_ON_YELLOW, COLOR_BLACK,  COLOR_YELLOW);
	init_pair(YELLOW_ON_BLACK, COLOR_YELLOW,  COLOR_BLACK);
	init_pair(WHITE_ON_RED,    COLOR_WHITE,  COLOR_RED);
	init_pair(YELLOW_ON_NOTHING,   COLOR_YELLOW,  -1);
	init_pair(GREEN_ON_NOTHING,   COLOR_GREEN,  -1);
	init_pair(RED_ON_NOTHING,   COLOR_RED,  -1);
	init_pair(BLUE_ON_NOTHING,  COLOR_BLUE, -1);
	init_pair(CYAN_ON_NOTHING,  COLOR_CYAN, -1);
	init_pair(MAGENTA_ON_NOTHING,  COLOR_MAGENTA, -1);
	init_pair(WHITE_ON_NOTHING,  COLOR_WHITE, -1);
	/* nodelay(scr, TRUE); */
	noecho();
	curs_set(0);
	/* Create fullscreen log window. When stats are displayed
	   later, it is recreated with appropriate dimensions. */
	win_txt = create_subwindow(0, 0, 0, 0);
	wbkgd(win_txt, COLOR_PAIR(0));

	idlok(win_txt, FALSE);
	/* Get scrolling */
	scrollok(win_txt, TRUE);
	/* Leave cursor where it was */
	leaveok(win_txt, TRUE);

	refresh();

	set_signal_handler();

	max_n_lines = (LINES - 5 - 2 - 3);
	/* core_port_height = max_n_lines < stats_get_n_tasks_tot()? max_n_lines : stats_get_n_tasks_tot(); */

	display_init_screens();
	display_screen(0);
	stats_display_layout(0);
}
Example #11
0
/*
 * make_level:
 *	Make the current level
 */
void
make_level()
{
	register int	i;
	register COORD	*cp;
	register int	x;

	reset_count();
	for (i = 1; i < Y_FIELDSIZE; i++)
		for (x = 1; x < X_FIELDSIZE; x++)
			if (Field[i][x] != 0)
				mvaddch(i, x, ' ');
	if (My_pos.y > 0)
		mvaddch(My_pos.y, My_pos.x, ' ');

	Waiting = FALSE;
	Wait_bonus = 0;
	leaveok(stdscr, FALSE);
	for (cp = Robots; cp < &Robots[MAXROBOTS]; cp++)
		cp->y = -1;
	My_pos.y = -1;

	bzero(Field, sizeof Field);
	Min.y = Y_FIELDSIZE;
	Min.x = X_FIELDSIZE;
	Max.y = 0;
	Max.x = 0;
	if ((i = Level * 10) > MAXROBOTS)
		i = MAXROBOTS;
	Num_robots = i;
	while (i-- > 0) {
		cp = rnd_pos();
		Robots[i] = *cp;
		Field[cp->y][cp->x]++;
		if (cp->y < Min.y)
			Min.y = cp->y;
		if (cp->x < Min.x)
			Min.x = cp->x;
		if (cp->y > Max.y)
			Max.y = cp->y;
		if (cp->x > Max.x)
			Max.x = cp->x;
	}
	My_pos = *rnd_pos();
	refresh();
}
Example #12
0
File: xxx.c Project: yaomoon/GT2440
static void init(void)
{
    int x, y;

#ifdef yaomoon
moon_log = fopen("moon_log","w+");
#endif
    /* Initialize the curses library */
    if (isatty(STDIN_FILENO)) {
        cursed = !!initscr();
    } else {
    /* Leave stdin and stdout alone when acting as a pager. */
        FILE *io = fopen("/dev/tty", "r+");

        cursed = !!newterm(NULL, io, io);
    }

    if (!cursed)
        die("Failed to initialize curses");

	nonl();         /* tell curses not to do NL->CR/NL on output */
	cbreak();       /* take input chars one at a time, no wait for \n */
	noecho();       /* don't echo input */
    leaveok(stdscr, TRUE);

	if (has_colors())
    {
		init_colors();
    }

    getmaxyx(stdscr, y, x);
#ifdef yaomoon
fprintf(moon_log,"getmaxyx y=%d\n",y);
fprintf(moon_log,"getmaxyx x=%d\n",x);

#endif

    status_win = newwin(1, 0, y - 10, 0);
    if (!status_win)
        die("failed to create status window");

    keypad(status_win, TRUE);
    wbkgdset(status_win, get_line_attr(LINE_STATUS));

}
Example #13
0
void init_curses(void)
{
    initscr();
    start_color();
    init_pair(PANEL,COLOR_BLUE,COLOR_WHITE);
    init_pair(BAR,COLOR_WHITE,COLOR_BLUE);
    init_pair(3,COLOR_RED,COLOR_GREEN);
    init_pair(4,COLOR_GREEN,COLOR_RED);
    init_pair(5,COLOR_GREEN,COLOR_BLUE);
    nonl();
    cbreak();
    noecho();
    leaveok(stdscr, TRUE);
    
#ifdef debug
moon_log = fopen("moon_log","w+");
#endif
}
Example #14
0
void curses_init()
{
    null = g_fopen("/dev/null", "w");
    unsetenv("COLUMNS");
    unsetenv("LINES");
    initscr();
    noecho();
    nonl();
    cbreak();
    keypad(stdscr, TRUE);
    meta(stdscr, TRUE);
    intrflush(stdscr, FALSE);
    leaveok(stdscr, TRUE);

    if (has_colors())
    {
        start_color();
        use_default_colors();
        init_pair(COLORPAIR, conf.fg, conf.bg);
    }
    else
        conf.color = FALSE;

    curs_set(false);

    ws = newwin(1, COLS, EL, 0);

    view.current = 0;
    view.top_x   = 0;
    view.top_y   = 0;

    prompt.buf   = g_string_new("");
    prompt.on    = false;
    prompt.regex = NULL;

    grid = g_array_sized_new(FALSE, TRUE, sizeof(grid_line_t*), SL);
    for (glong i = 0; i < SL; i++)
    {
        grid_line_t* grid_line = g_malloc(sizeof(grid_line_t));
        g_array_append_val(grid, grid_line);
    }

    regrid();
}
Example #15
0
int main(){
    setlocale(LC_ALL,"");
    initscr();
    signal(SIGINT, SIG_IGN);
    noecho();
    curs_set(0);
    nodelay(stdscr, TRUE);
    leaveok(stdscr, TRUE);
    scrollok(stdscr, FALSE);
    for(int i=COLS-12;i>2;i--){
        erase();
        title(i%2);
        takenoko(i, gizagiza());
        refresh();
        usleep(50000);
    }
    endwin();
    return 0;
}
Example #16
0
File: bn.c Project: sh19910711/webn
/* 初期化 */
static inline void init_bn(void) {
    if (initscr() == NULL){
        fprintf(stderr, "initscr failure\n");
        exit(EXIT_FAILURE);
    }

    /* 端末が色の使用と変更が可能なら設定 */
    start_color();

    /* 色の初期化 */
    /* 色番号(1 ~ COLORSの間とする) r, g, b, それぞれ0~1000の範囲 */
    init_color(BN_COLOR_RED,    CONVERT_RANGE(215), CONVERT_RANGE(0),   CONVERT_RANGE(58));
    init_color(BN_COLOR_GREEN,  CONVERT_RANGE(56),  CONVERT_RANGE(180), CONVERT_RANGE(139));
    init_color(BN_COLOR_BLUE,   CONVERT_RANGE(44),  CONVERT_RANGE(169), CONVERT_RANGE(225));
    init_color(BN_COLOR_BLACK,   CONVERT_RANGE(43),  CONVERT_RANGE(43),  CONVERT_RANGE(43));

    /* 前景と背景のペアを作成 */
    /* 色番号(1 ~ COLOR_PAIRS-1の範囲であること) 前景 背景 */
    init_pair(BN_COLOR_PAIR_WG, COLOR_WHITE, BN_COLOR_BLACK);
    init_pair(BN_COLOR_PAIR_BG, BN_COLOR_BLUE, BN_COLOR_BLACK);
    init_pair(BN_COLOR_PAIR_GG, BN_COLOR_GREEN, BN_COLOR_BLACK);

    if (SIG_ERR == signal(SIGQUIT, signal_handler)) {
        fprintf(stderr, "setting signal handler failure\n");
        endwin();
        exit(EXIT_FAILURE);
    }

    /* シグナルを無視する */
    signal(SIGINT, SIG_IGN);
    /* キー入力された文字を表示しない */
    noecho();
    /* カーソルを表示しない */
    leaveok(stdscr, TRUE);
    /* スクロールしない */
    scrollok(stdscr, FALSE);
    /* カーソルを非表示に */
    curs_set(0);
    timeout(0);
    keypad(stdscr, TRUE);

}
Example #17
0
main()
{
	srand(getpid());		/* initialize random sequence */

	if (!initscr()) {
	  fprintf(stderr, "Could not initialize libcurses.\n");
	  exit(1);
	}
	signal(SIGINT, die);
	noecho();
	nonl();
	leaveok(stdscr, TRUE);
	scrollok(stdscr, FALSE);

	for (;;) {
		makeboard();		/* make the board setup */
		puton('*');		/* put on '*'s */
		puton(' ');		/* cover up with ' 's */
	}
}
Example #18
0
int main(void)
{
	initscr();
	start_color();
	init_pair(1,COLOR_WHITE,COLOR_BLUE);

	addstr("This is the standard screen as it normally appears.\n");
	addstr("The cursor is synchronized ->");
	refresh();
	getch();

	leaveok(stdscr,TRUE);
	bkgd(COLOR_PAIR(1));
	addstr("\n\nThe cursor is now not being updated.\n");
	addstr("This means that it's position could be anywhere.\n");
	refresh();
	getch();

	endwin();
	return 0;
}
Example #19
0
/* Set up a curses window for our display
*/
void initcurses(void) {
    if (!using_curses)
        return;
    term = newterm(NULL, stdout, stdin);
    if (term != NULL) {
        int screen_width, screen_height;
        int window_width = linelen+2;
        int window_height = LINE_COUNT+2;
        int org_x, org_y;

        using_curses = 1;

        cbreak();
        noecho();
        nonl();

        nodelay(stdscr, TRUE);
        intrflush(stdscr, FALSE);
        keypad(stdscr, TRUE);
        leaveok(stdscr, TRUE);
        curs_set(0);

        getmaxyx(stdscr, screen_height, screen_width);
        org_x = (screen_width - window_width) / 2;
        org_y = (screen_height - window_height - 1) / 2;

        slimwin = subwin(stdscr, window_height, window_width, org_y, org_x);
        box(slimwin, 0, 0);

        if (screen_height > LINE_COUNT+2) {
            /* create one-line error message subwindow */
            errwin = subwin(stdscr, 1, screen_width, org_y+window_height, 0);
        }

        wrefresh(curscr);
    } else {
        using_curses = 0;
    }
}
Example #20
0
File: sl.c Project: ryanmjacobs/sl
int main(int argc, char *argv[])
{
    int x, i;

    for (i = 1; i < argc; ++i) {
        if (*argv[i] == '-') {
            option(argv[i] + 1);
        }
    }
    initscr();
    if (INTR == 0) {
        signal(SIGINT, SIG_IGN);
    }
    signal(SIGTSTP, SIG_IGN);
    noecho();
    curs_set(0);
    nodelay(stdscr, TRUE);
    leaveok(stdscr, TRUE);
    scrollok(stdscr, FALSE);

    for (x = COLS - 1; ; --x) {
        if (LOGO == 1) {
            if (add_sl(x) == ERR) break;
        }
        else if (C51 == 1) {
            if (add_C51(x) == ERR) break;
        }
        else {
            if (add_D51(x) == ERR) break;
        }
        getch();
        refresh();
        usleep(40000);
    }
    mvcur(0, COLS - 1, LINES - 1, 0);
    endwin();
}
Example #21
0
int
sc_enterStructuredMode ()
{
  if (initscr() == NULL)
    return FALSE;

  start_color();

  scrollok(stdscr, TRUE);
  immedok(stdscr, FALSE);
  leaveok(stdscr, FALSE);
  idlok(stdscr, TRUE);
  idcok(stdscr, TRUE);
  intrflush(stdscr, FALSE);
  keypad(stdscr, FALSE);

  notimeout(stdscr, FALSE);

  raw();
  noecho();
  nl();

  return TRUE;
}
Example #22
0
int
main(int argc, char **argv)
{
    int NTiles, FromCol, ToCol;

    setlocale(LC_ALL, "");

    switch (argc) {
    case 1:
	NTiles = DEFAULTTILES;
	break;
    case 2:
	NTiles = atoi(argv[1]);
	if (NTiles > MAXTILES || NTiles < MINTILES) {
	    fprintf(stderr, "Range %d to %d\n", MINTILES, MAXTILES);
	    ExitProgram(EXIT_FAILURE);
	}
	break;
    case 3:
	if (strcmp(argv[2], "a")) {
	    Usage();
	    ExitProgram(EXIT_FAILURE);
	}
	NTiles = atoi(argv[1]);
	if (NTiles > MAXTILES || NTiles < MINTILES) {
	    fprintf(stderr, "Range %d to %d\n", MINTILES, MAXTILES);
	    ExitProgram(EXIT_FAILURE);
	}
	AutoFlag = TRUE;
	break;
    default:
	Usage();
	ExitProgram(EXIT_FAILURE);
    }
#ifdef TRACE
    trace(TRACE_MAXIMUM);
#endif
    initscr();
    if (has_colors()) {
	int i;
	short bg = COLOR_BLACK;
	start_color();
#if HAVE_USE_DEFAULT_COLORS
	if (use_default_colors() == OK)
	    bg = -1;
#endif
	for (i = 0; i < 9; i++)
	    init_pair((short) (i + 1), bg, TileColour[i]);
    }
    cbreak();
    if (LINES < 24) {
	endwin();
	fprintf(stderr, "Min screen length 24 lines\n");
	ExitProgram(EXIT_FAILURE);
    }
    if (AutoFlag) {
	curs_set(0);
	leaveok(stdscr, TRUE);	/* Attempt to remove cursor */
    }
    InitTiles(NTiles);
    DisplayTiles();
    if (AutoFlag) {
	do {
	    noecho();
	    AutoMove(0, 2, NTiles);
	} while (!Solved(NTiles));
	sleep(2);
    } else {
	echo();
	for (;;) {
	    if (GetMove(&FromCol, &ToCol))
		break;
	    if (InvalidMove(FromCol, ToCol)) {
		MvAddStr(STATUSLINE, 0, "Invalid Move !!");
		refresh();
		beep();
		continue;
	    }
	    MakeMove(FromCol, ToCol);
	    if (Solved(NTiles)) {
		MvPrintw(STATUSLINE, 0,
			 "Well Done !! You did it in %d moves", NMoves);
		refresh();
		sleep(5);
		break;
	    }
	}
    }
    endwin();
    ExitProgram(EXIT_SUCCESS);
}
Example #23
0
void hostmon(const struct OPTIONS *options, time_t facilitytime, char *ifptr,
	     struct filterstate *ofilter)
{
	int logging = options->logging;
	struct ethtab table;
	struct ethtabent *entry;

	char scratch_saddr[ETH_ALEN];
	char scratch_daddr[ETH_ALEN];
	unsigned int idx = 1;
	int is_ip;
	int ch;

	char *ifname = ifptr;

	struct timeval tv;
	time_t starttime;
	time_t now = 0;
	unsigned long long unow = 0;
	time_t statbegin = 0;
	time_t startlog = 0;
	time_t updtime = 0;
	unsigned long long updtime_usec = 0;

	struct eth_desc *list = NULL;

	FILE *logfile = NULL;

	int pkt_result;

	WINDOW *sortwin;
	PANEL *sortpanel;
	int keymode = 0;

	int instance_id;

	int fd;

	struct promisc_states *promisc_list;

	if (!facility_active(LANMONIDFILE, ifptr))
		mark_facility(LANMONIDFILE, "LAN monitor", ifptr);
	else {
		write_error("LAN station monitor already running on %s",
			 gen_iface_msg(ifptr));
		return;
	}

	if (ifptr != NULL) {
		if (!dev_up(ifptr)) {
			err_iface_down();
			unmark_facility(LANMONIDFILE, ifptr);
			return;
		}
	}

	if ((first_active_facility()) && (options->promisc)) {
		init_promisc_list(&promisc_list);
		save_promisc_list(promisc_list);
		srpromisc(1, promisc_list);
		destroy_promisc_list(&promisc_list);
	}

	adjust_instance_count(PROCCOUNTFILE, 1);
	instance_id = adjust_instance_count(LANMONCOUNTFILE, 1);

	hostmonhelp();

	initethtab(&table, options->actmode);

	/* Ethernet description list */
	struct eth_desc *elist = load_eth_desc(ARPHRD_ETHER);

	/* FDDI description list */
	struct eth_desc *flist = load_eth_desc(ARPHRD_FDDI);

	if (logging) {
		if (strcmp(current_logfile, "") == 0) {
			strncpy(current_logfile,
				gen_instance_logname(LANLOG, instance_id), 80);

			if (!daemonized)
				input_logfile(current_logfile, &logging);
		}
	}

	if (logging) {
		opentlog(&logfile, current_logfile);

		if (logfile == NULL)
			logging = 0;
	}
	if (logging) {
		signal(SIGUSR1, rotate_lanlog);

		rotate_flag = 0;
		writelog(logging, logfile,
			 "******** LAN traffic monitor started ********");
	}

	leaveok(table.tabwin, TRUE);

	fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
	if(fd == -1) {
		write_error("Unable to obtain monitoring socket");
		goto err;
	}
	if(ifptr && dev_bind_ifname(fd, ifptr) == -1) {
		write_error("Unable to bind interface on the socket");
		goto err_close;
	}

	exitloop = 0;
	gettimeofday(&tv, NULL);
	starttime = statbegin = startlog = tv.tv_sec;

	PACKET_INIT(pkt);

	do {
		gettimeofday(&tv, NULL);
		now = tv.tv_sec;
		unow = tv.tv_sec * 1000000ULL + tv.tv_usec;

		if ((now - starttime) >= 5) {
			printelapsedtime(statbegin, now, LINES - 3, 15,
					 table.borderwin);
			updateethrates(&table, options->actmode, starttime, now,
				       idx);
			starttime = now;
		}
		if (logging) {
			check_rotate_flag(&logfile);
			if ((now - startlog) >= options->logspan) {
				writeethlog(table.head, options->actmode,
					    now - statbegin, logfile);
				startlog = now;
			}
		}
		if (((options->updrate != 0)
		     && (now - updtime >= options->updrate))
		    || ((options->updrate == 0)
			&& (unow - updtime_usec >= DEFAULT_UPDATE_DELAY))) {
			update_panels();
			doupdate();
			updtime = now;
			updtime_usec = unow;
		}

		if ((facilitytime != 0)
		    && (((now - statbegin) / 60) >= facilitytime))
			exitloop = 1;

		if (packet_get(fd, &pkt, &ch, table.tabwin) == -1) {
			write_error("Packet receive failed");
			exitloop = 1;
			break;
		}

		if (ch != ERR) {
			if (keymode == 0) {
				switch (ch) {
				case KEY_UP:
					scrollethwin(&table, SCROLLDOWN, &idx);
					break;
				case KEY_DOWN:
					scrollethwin(&table, SCROLLUP, &idx);
					break;
				case KEY_PPAGE:
				case '-':
					pageethwin(&table, SCROLLDOWN, &idx);
					break;
				case KEY_NPAGE:
				case ' ':
					pageethwin(&table, SCROLLUP, &idx);
					break;
				case 12:
				case 'l':
				case 'L':
					tx_refresh_screen();
					break;
				case 's':
				case 'S':
					show_hostsort_keywin(&sortwin,
							     &sortpanel);
					keymode = 1;
					break;
				case 'q':
				case 'Q':
				case 'x':
				case 'X':
				case 27:
				case 24:
					exitloop = 1;
				}
			} else if (keymode == 1) {
				del_panel(sortpanel);
				delwin(sortwin);
				sort_hosttab(&table, &idx, ch);
				keymode = 0;
			}
		}
		if (pkt.pkt_len > 0) {
			char ifnamebuf[IFNAMSIZ];

			pkt_result =
			    packet_process(&pkt, NULL, NULL, NULL,
					  ofilter,
					  MATCH_OPPOSITE_USECONFIG,
					  0);

			if (pkt_result != PACKET_OK)
				continue;

			if (!ifptr) {
				/* we're capturing on "All interfaces", */
				/* so get the name of the interface */
				/* of this packet */
				int r = dev_get_ifname(pkt.pkt_ifindex, ifnamebuf);
				if (r != 0) {
					write_error("Unable to get interface name");
					break;	/* can't get interface name, get out! */
				}
				ifname = ifnamebuf;
			}

			/* get HW addresses */
			switch (pkt.pkt_hatype) {
			case ARPHRD_ETHER: {
				struct ethhdr *hdr_eth =
					(struct ethhdr *)pkt.pkt_buf;
				memcpy(scratch_saddr, hdr_eth->h_source,
				       ETH_ALEN);
				memcpy(scratch_daddr, hdr_eth->h_dest,
				       ETH_ALEN);
				list = elist;
				break; }
			case ARPHRD_FDDI: {
				struct fddihdr *hdr_fddi =
					(struct fddihdr *)pkt.pkt_buf;
				memcpy(scratch_saddr, hdr_fddi->saddr,
				       FDDI_K_ALEN);
				memcpy(scratch_daddr, hdr_fddi->daddr,
				       FDDI_K_ALEN);
				list = flist;
				break; }
			case ARPHRD_IEEE802:
			case ARPHRD_IEEE802_TR: {
				struct trh_hdr *hdr_trh =
					(struct trh_hdr *)pkt.pkt_buf;
				memcpy(scratch_saddr, hdr_trh->saddr,
				       TR_ALEN);
				memcpy(scratch_daddr, hdr_trh->daddr,
				       TR_ALEN);
				list = flist;
				break; }
			default:
				/* unknown link protocol */
				continue;
			}

			switch(pkt.pkt_protocol) {
			case ETH_P_IP:
			case ETH_P_IPV6:
				is_ip = 1;
				break;
			default:
				is_ip = 0;
				break;
			}

			/* Check source address entry */
			entry = in_ethtable(&table, pkt.pkt_hatype,
					scratch_saddr);

			if (!entry)
				entry = addethentry(&table, pkt.pkt_hatype,
						ifname, scratch_saddr, list);

			if (entry != NULL) {
				updateethent(entry, pkt.pkt_len, is_ip, 1);
				if (!entry->prev_entry->un.desc.printed)
					printethent(&table, entry->prev_entry,
						    idx);

				printethent(&table, entry, idx);
			}

			/* Check destination address entry */
			entry = in_ethtable(&table, pkt.pkt_hatype,
					scratch_daddr);
			if (!entry)
				entry = addethentry(&table, pkt.pkt_hatype,
						ifname, scratch_daddr, list);

			if (entry != NULL) {
				updateethent(entry, pkt.pkt_len, is_ip, 0);
				if (!entry->prev_entry->un.desc.printed)
					printethent(&table, entry->prev_entry,
						    idx);

				printethent(&table, entry, idx);
			}
		}
	} while (!exitloop);

err_close:
	close(fd);

err:
	if ((options->promisc) && (is_last_instance())) {
		load_promisc_list(&promisc_list);
		srpromisc(0, promisc_list);
		destroy_promisc_list(&promisc_list);
	}

	adjust_instance_count(PROCCOUNTFILE, -1);
	adjust_instance_count(LANMONCOUNTFILE, -1);

	if (logging) {
		signal(SIGUSR1, SIG_DFL);
		writeethlog(table.head, options->actmode,
			    time(NULL) - statbegin, logfile);
		writelog(logging, logfile,
			 "******** LAN traffic monitor stopped ********");
		fclose(logfile);
	}


	del_panel(table.tabpanel);
	delwin(table.tabwin);
	del_panel(table.borderpanel);
	delwin(table.borderwin);
	update_panels();
	doupdate();
	destroyethtab(&table);

	free_eth_desc(elist);
	free_eth_desc(flist);

	unmark_facility(LANMONIDFILE, ifptr);
	strcpy(current_logfile, "");
}
EIF_INTEGER c_ecurses_leaveok (EIF_POINTER p, EIF_BOOLEAN b)
{
    return leaveok( ((WINDOW *)  p), (bool)b);
};
Example #25
0
int
main(int argc, char **argv)
{
int NTiles, FromCol, ToCol;
unsigned char AutoFlag = 0;

	switch(argc) {
	case 1:
		NTiles = DEFAULTTILES;
		break;
	case 2:
		NTiles = atoi(argv[1]);
		if (NTiles > MAXTILES || NTiles < MINTILES) {
			fprintf(stderr, "Range %d to %d\n", MINTILES, MAXTILES);
			exit(1);
		}
		break;
	case 3:
		if (strcmp(argv[2], "a")) {
			Usage();
			exit(1);
		}
		NTiles = atoi(argv[1]);
		if (NTiles > MAXTILES || NTiles < MINTILES) {
			fprintf(stderr, "Range %d to %d\n", MINTILES, MAXTILES);
			exit(1);
		}
		AutoFlag = TRUE;
		break;
	default:
		Usage();
		exit(1);
	}
#ifdef NCURSES_VERSION
	trace(TRACE_MAXIMUM);
#endif
	initscr();
	if (!has_colors()) {
		endwin();
		puts("terminal doesn't support color.");
		exit(1);
	}
	start_color();
	{
	int i;
	for (i = 0; i < 9; i++)
		init_pair(i+1, COLOR_BLACK, TileColour[i]);
	}
	cbreak();
	if (LINES < 24) {
		endwin();
		fprintf(stderr, "Min screen length 24 lines\n");
		exit(1);
	}
	if(AutoFlag)
		leaveok(stdscr, TRUE);	/* Attempt to remove cursor */
	InitTiles(NTiles);
	DisplayTiles();
	if(AutoFlag) {
		do {
			noecho();
			AutoMove(0, 2, NTiles);
		} while(!Solved(NTiles));
		sleep(2);
	} else {
		for(;;) {
			if(GetMove(&FromCol, &ToCol))
				break;
			if(InvalidMove(FromCol, ToCol)) {
				mvaddstr(STATUSLINE, 0, "Invalid Move !!");
				refresh();
				beep();
				continue;
			}
			MakeMove(FromCol, ToCol);
			if(Solved(NTiles)) {
				mvprintw(STATUSLINE, 0, "Well Done !! You did it in %d moves", NMoves);
				refresh();
				sleep(5);
				break;
			}
		}
	}
	curs_set(1);
	endwin();
	exit(0);
}
Example #26
0
/*
 * The detailed interface statistics function
 */
void detstats(char *iface, time_t facilitytime)
{
	int logging = options.logging;

	WINDOW *statwin;
	PANEL *statpanel;

	int pkt_result = 0;

	FILE *logfile = NULL;

	unsigned int iplen = 0;

	struct ifcounts ifcounts;

	int ch;

	struct timeval tv;
	struct timeval start_tv;
	struct timeval updtime;
	time_t starttime;
	time_t now;
	time_t statbegin;
	time_t startlog;

	struct proto_counter span;

	struct rate rate;
	struct rate rate_in;
	struct rate rate_out;
	unsigned long peakactivity = 0;
	unsigned long peakactivity_in = 0;
	unsigned long peakactivity_out = 0;

	struct rate pps_rate;
	struct rate pps_rate_in;
	struct rate pps_rate_out;
	unsigned long peakpps = 0;
	unsigned long peakpps_in = 0;
	unsigned long peakpps_out = 0;

	int fd;

	if (!dev_up(iface)) {
		err_iface_down();
		return;
	}

	LIST_HEAD(promisc);
	if (options.promisc) {
		promisc_init(&promisc, iface);
		promisc_set_list(&promisc);
	}

	move(LINES - 1, 1);
	stdexitkeyhelp();
	statwin = newwin(LINES - 2, COLS, 1, 0);
	statpanel = new_panel(statwin);
	tx_stdwinset(statwin);
	wtimeout(statwin, -1);
	wattrset(statwin, BOXATTR);
	tx_colorwin(statwin);
	tx_box(statwin, ACS_VLINE, ACS_HLINE);
	wmove(statwin, 0, 1);
	wprintw(statwin, " Statistics for %s ", iface);
	wattrset(statwin, STDATTR);
	update_panels();
	doupdate();

	memset(&ifcounts, 0, sizeof(struct ifcounts));

	if (logging) {
		if (strcmp(current_logfile, "") == 0) {
			snprintf(current_logfile, 64, "%s-%s.log", DSTATLOG,
				 iface);

			if (!daemonized)
				input_logfile(current_logfile, &logging);
		}
	}

	if (logging) {
		opentlog(&logfile, current_logfile);

		if (logfile == NULL)
			logging = 0;
	}
	if (logging) {
		signal(SIGUSR1, rotate_dstat_log);

		rotate_flag = 0;
		writelog(logging, logfile,
			 "******** Detailed interface statistics started ********");
	}

	printdetlabels(statwin);
	printdetails(&ifcounts, statwin);
	update_panels();
	doupdate();

	memset(&span, 0, sizeof(span));
	rate_alloc(&rate, 5);
	rate_alloc(&rate_in, 5);
	rate_alloc(&rate_out, 5);

	rate_alloc(&pps_rate, 5);
	rate_alloc(&pps_rate_in, 5);
	rate_alloc(&pps_rate_out, 5);

	gettimeofday(&tv, NULL);
	start_tv = tv;
	updtime = tv;
	starttime = startlog = statbegin = tv.tv_sec;

	leaveok(statwin, TRUE);

	fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
	if(fd == -1) {
		write_error("Unable to obtain monitoring socket");
		goto err;
	}
	if(dev_bind_ifname(fd, iface) == -1) {
		write_error("Unable to bind interface on the socket");
		goto err_close;
	}

	exitloop = 0;

	PACKET_INIT(pkt);

	/*
	 * Data-gathering loop
	 */

	while (!exitloop) {
		gettimeofday(&tv, NULL);
		now = tv.tv_sec;

		if ((now - starttime) >= 1) {
			char buf[64];
			unsigned long activity, activity_in, activity_out;
			unsigned long pps, pps_in, pps_out;
			unsigned long msecs;

			wattrset(statwin, BOXATTR);
			printelapsedtime(statbegin, now, LINES - 3, 1, statwin);

			msecs = timeval_diff_msec(&tv, &start_tv);

			rate_add_rate(&rate, span.proto_total.pc_bytes, msecs);
			activity = rate_get_average(&rate);
			rate_add_rate(&rate_in, span.proto_in.pc_bytes, msecs);
			activity_in = rate_get_average(&rate_in);
			rate_add_rate(&rate_out, span.proto_out.pc_bytes, msecs);
			activity_out = rate_get_average(&rate_out);

			rate_add_rate(&pps_rate, span.proto_total.pc_packets, msecs);
			pps = rate_get_average(&pps_rate);
			rate_add_rate(&pps_rate_in, span.proto_in.pc_packets, msecs);
			pps_in = rate_get_average(&pps_rate_in);
			rate_add_rate(&pps_rate_out, span.proto_out.pc_packets, msecs);
			pps_out = rate_get_average(&pps_rate_out);

			memset(&span, 0, sizeof(span));
			starttime = now;
			start_tv = tv;

			wattrset(statwin, HIGHATTR);
			rate_print(activity, buf, sizeof(buf));
			mvwprintw(statwin, 14, 19, "%s", buf);
			rate_print_pps(pps, buf, sizeof(buf));
			mvwprintw(statwin, 15, 19, "%s", buf);
			rate_print(activity_in, buf, sizeof(buf));
			mvwprintw(statwin, 17, 19, "%s", buf);
			rate_print_pps(pps_in, buf, sizeof(buf));
			mvwprintw(statwin, 18, 19, "%s", buf);
			rate_print(activity_out, buf, sizeof(buf));
			mvwprintw(statwin, 20, 19, "%s", buf);
			rate_print_pps(pps_out, buf, sizeof(buf));
			mvwprintw(statwin, 21, 19, "%s", buf);

			if (activity > peakactivity)
				peakactivity = activity;

			if (activity_in > peakactivity_in)
				peakactivity_in = activity_in;

			if (activity_out > peakactivity_out)
				peakactivity_out = activity_out;

			if (pps > peakpps)
				peakpps = pps;

			if (pps_in > peakpps_in)
				peakpps_in = pps_in;

			if (pps_out > peakpps_out)
				peakpps_out = pps_out;
		}
		if (logging) {
			check_rotate_flag(&logfile);
			if ((now - startlog) >= options.logspan) {
				writedstatlog(iface,
					      peakactivity, peakpps,
					      peakactivity_in, peakpps_in,
					      peakactivity_out, peakpps_out,
					      &ifcounts, time(NULL) - statbegin,
					      logfile);

				startlog = now;
			}
		}

		if (screen_update_needed(&tv, &updtime)) {
			printdetails(&ifcounts, statwin);
			update_panels();
			doupdate();

			updtime = tv;
		}

		if ((facilitytime != 0)
		    && (((now - statbegin) / 60) >= facilitytime))
			exitloop = 1;

		if (packet_get(fd, &pkt, &ch, statwin) == -1) {
			write_error("Packet receive failed");
			exitloop = 1;
			break;
		}

		switch (ch) {
		case ERR:
			/* no key ready, do nothing */
			break;
		case 12:
		case 'l':
		case 'L':
			tx_refresh_screen();
			break;

		case 'Q':
		case 'q':
		case 'X':
		case 'x':
		case 24:
		case 27:
			exitloop = 1;
			break;
		}
		if (pkt.pkt_len <= 0)
			continue;

		int outgoing;

		pkt_result =
			packet_process(&pkt, NULL, NULL, NULL,
				       MATCH_OPPOSITE_USECONFIG,
				       options.v6inv4asv6);

		if (pkt_result != PACKET_OK
		    && pkt_result != MORE_FRAGMENTS)
			continue;

		outgoing = (pkt.pkt_pkttype == PACKET_OUTGOING);
		update_proto_counter(&ifcounts.total, outgoing, pkt.pkt_len);
		if (pkt.pkt_pkttype == PACKET_BROADCAST) {
			update_pkt_counter(&ifcounts.bcast, pkt.pkt_len);
		}

		update_proto_counter(&span, outgoing, pkt.pkt_len);

		/* account network layer protocol */
		switch(pkt.pkt_protocol) {
		case ETH_P_IP:
			if (pkt_result == CHECKSUM_ERROR) {
				update_pkt_counter(&ifcounts.bad, pkt.pkt_len);
				continue;
			}

			iplen = ntohs(pkt.iphdr->tot_len);

			update_proto_counter(&ifcounts.ipv4, outgoing, iplen);
			break;
		case ETH_P_IPV6:
			iplen = ntohs(pkt.ip6_hdr->ip6_plen) + 40;

			update_proto_counter(&ifcounts.ipv6, outgoing, iplen);
			break;
		default:
			update_proto_counter(&ifcounts.nonip, outgoing, iplen);
			continue;
		}

		__u8 ip_protocol = pkt_ip_protocol(&pkt);

		/* account transport layer protocol */
		switch (ip_protocol) {
		case IPPROTO_TCP:
			update_proto_counter(&ifcounts.tcp, outgoing, iplen);
			break;
		case IPPROTO_UDP:
			update_proto_counter(&ifcounts.udp, outgoing, iplen);
			break;
		case IPPROTO_ICMP:
		case IPPROTO_ICMPV6:
			update_proto_counter(&ifcounts.icmp, outgoing, iplen);
			break;
		default:
			update_proto_counter(&ifcounts.other, outgoing, iplen);
			break;
		}
	}

err_close:
	close(fd);

err:
	rate_destroy(&pps_rate_out);
	rate_destroy(&pps_rate_in);
	rate_destroy(&pps_rate);

	rate_destroy(&rate_out);
	rate_destroy(&rate_in);
	rate_destroy(&rate);

	if (options.promisc) {
		promisc_restore_list(&promisc);
		promisc_destroy(&promisc);
	}

	if (logging) {
		signal(SIGUSR1, SIG_DFL);
		writedstatlog(iface,
			      peakactivity, peakpps, peakactivity_in,
			      peakpps_in, peakactivity_out, peakpps_out,
			      &ifcounts, time(NULL) - statbegin,
			      logfile);
		writelog(logging, logfile,
			 "******** Detailed interface statistics stopped ********");
		fclose(logfile);
	}

	del_panel(statpanel);
	delwin(statwin);
	strcpy(current_logfile, "");
	pkt_cleanup();
	update_panels();
	doupdate();
}
Example #27
0
save() {

	reg char	*sp;
	reg int		outf;
	reg time_t	*tp;
	char		buf[80];
	time_t		tme;
	STAT		junk;

	tp = &tme;
	if (Fromfile && getyn(SAMEFILEPROMPT))
		strcpy(buf, Fromfile);
	else {
over:
		prompt(FILEPROMPT);
		leaveok(Board, FALSE);
		refresh();
		sp = buf;
		while ((*sp = readch()) != '\n') {
			if (*sp == killchar())
				goto over;
			else if (*sp == erasechar()) {
				if (--sp < buf)
					sp = buf;
				else {
					addch('\b');
					/*
					 * if the previous char was a control
					 * char, cover up two characters.
					 */
					if (*sp < ' ')
						addch('\b');
					clrtoeol();
				}
			}
			else
				addstr(unctrl(*sp++));
			refresh();
		}
		*sp = '\0';
		leaveok(Board, TRUE);
	}

	/*
	 * check for existing files, and confirm overwrite if needed
	 */

	if (sp == buf || (!Fromfile && stat(buf, &junk) > -1
	    && getyn(OVERWRITEFILEPROMPT) == FALSE))
		return FALSE;

	if ((outf = creat(buf, 0644)) < 0) {
		error(strerror(errno));
		return FALSE;
	}
	mvwaddstr(Score, ERR_Y, ERR_X, buf);
	wrefresh(Score);
	time(tp);			/* get current time		*/
	strcpy(buf, ctime(tp));
	for (sp = buf; *sp != '\n'; sp++)
		continue;
	*sp = '\0';
	varpush(outf, write);
	close(outf);
	wprintw(Score, " [%s]", buf);
	wclrtoeol(Score);
	wrefresh(Score);
	return TRUE;
}
Example #28
0
File: display.c Project: JakeSc/tig
void
init_display(void)
{
    const char *term;
    int x, y;

    die_callback = done_display;
    /* XXX: Restore tty modes and let the OS cleanup the rest! */
    if (atexit(done_display))
        die("Failed to register done_display");

    /* Initialize the curses library */
    if (isatty(STDIN_FILENO)) {
        cursed = !!initscr();
        opt_tty = stdin;
    } else {
        /* Leave stdin and stdout alone when acting as a pager. */
        opt_tty = fopen("/dev/tty", "r+");
        if (!opt_tty)
            die("Failed to open /dev/tty");
        cursed = !!newterm(NULL, opt_tty, opt_tty);
    }

    if (!cursed)
        die("Failed to initialize curses");

    nonl();		/* Disable conversion and detect newlines from input. */
    cbreak();       /* Take input chars one at a time, no wait for \n */
    noecho();       /* Don't echo input */
    leaveok(stdscr, FALSE);

    if (has_colors())
        init_colors();

    getmaxyx(stdscr, y, x);
    status_win = newwin(1, x, y - 1, 0);
    if (!status_win)
        die("Failed to create status window");

    /* Enable keyboard mapping */
    keypad(status_win, TRUE);
    wbkgdset(status_win, get_line_attr(NULL, LINE_STATUS));
    enable_mouse(opt_mouse);

#if defined(NCURSES_VERSION_PATCH) && (NCURSES_VERSION_PATCH >= 20080119)
    set_tabsize(opt_tab_size);
#else
    TABSIZE = opt_tab_size;
#endif

    term = getenv("XTERM_VERSION") ? NULL : getenv("COLORTERM");
    if (term && !strcmp(term, "gnome-terminal")) {
        /* In the gnome-terminal-emulator, the message from
         * scrolling up one line when impossible followed by
         * scrolling down one line causes corruption of the
         * status line. This is fixed by calling wclear. */
        use_scroll_status_wclear = TRUE;
        use_scroll_redrawwin = FALSE;

    } else if (term && !strcmp(term, "xrvt-xpm")) {
        /* No problems with full optimizations in xrvt-(unicode)
         * and aterm. */
        use_scroll_status_wclear = use_scroll_redrawwin = FALSE;

    } else {
        /* When scrolling in (u)xterm the last line in the
         * scrolling direction will update slowly. */
        use_scroll_redrawwin = TRUE;
        use_scroll_status_wclear = FALSE;
    }
}
Example #29
0
void hostmon(time_t facilitytime, char *ifptr)
{
	int logging = options.logging;
	struct ethtab table;
	struct ethtabent *entry;

	char scratch_saddr[ETH_ALEN];
	char scratch_daddr[ETH_ALEN];
	unsigned int idx = 1;
	int is_ip;
	int ch;

	char *ifname = ifptr;

	struct timeval tv;
	struct timeval tv_rate;
	time_t now = 0;
	time_t statbegin = 0;
	time_t startlog = 0;
	struct timeval updtime;

	struct eth_desc *list = NULL;

	FILE *logfile = NULL;

	int pkt_result;

	WINDOW *sortwin;
	PANEL *sortpanel;
	int keymode = 0;

	int fd;

	if (ifptr && !dev_up(ifptr)) {
		err_iface_down();
		return;
	}

	LIST_HEAD(promisc);
	if (options.promisc) {
		promisc_init(&promisc, ifptr);
		promisc_set_list(&promisc);
	}

	hostmonhelp();

	initethtab(&table);

	/* Ethernet description list */
	struct eth_desc *elist = load_eth_desc(ARPHRD_ETHER);

	/* FDDI description list */
	struct eth_desc *flist = load_eth_desc(ARPHRD_FDDI);

	if (logging) {
		if (strcmp(current_logfile, "") == 0) {
			strncpy(current_logfile,
				gen_instance_logname(LANLOG, getpid()), 80);

			if (!daemonized)
				input_logfile(current_logfile, &logging);
		}
	}

	if (logging) {
		opentlog(&logfile, current_logfile);

		if (logfile == NULL)
			logging = 0;
	}
	if (logging) {
		signal(SIGUSR1, rotate_lanlog);

		rotate_flag = 0;
		writelog(logging, logfile,
			 "******** LAN traffic monitor started ********");
	}

	leaveok(table.tabwin, TRUE);

	fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
	if(fd == -1) {
		write_error("Unable to obtain monitoring socket");
		goto err;
	}
	if(ifptr && dev_bind_ifname(fd, ifptr) == -1) {
		write_error("Unable to bind interface on the socket");
		goto err_close;
	}

	exitloop = 0;
	gettimeofday(&tv, NULL);
	tv_rate = tv;
	updtime = tv;
	statbegin = startlog = tv.tv_sec;

	PACKET_INIT(pkt);

	do {
		gettimeofday(&tv, NULL);
		now = tv.tv_sec;

		unsigned long msecs = timeval_diff_msec(&tv, &tv_rate);
		if (msecs >= 1000) {
			printelapsedtime(statbegin, now, LINES - 3, 15,
					 table.borderwin);
			updateethrates(&table, msecs, idx);
			tv_rate = tv;
		}
		if (logging) {
			check_rotate_flag(&logfile);
			if ((now - startlog) >= options.logspan) {
				writeethlog(table.head, now - statbegin,
					    logfile);
				startlog = now;
			}
		}
		if (screen_update_needed(&tv, &updtime)) {
			update_panels();
			doupdate();

			updtime = tv;
		}

		if ((facilitytime != 0)
		    && (((now - statbegin) / 60) >= facilitytime))
			exitloop = 1;

		if (packet_get(fd, &pkt, &ch, table.tabwin) == -1) {
			write_error("Packet receive failed");
			exitloop = 1;
			break;
		}

		if (ch != ERR) {
			if (keymode == 0) {
				switch (ch) {
				case KEY_UP:
					scrollethwin(&table, SCROLLDOWN, &idx);
					break;
				case KEY_DOWN:
					scrollethwin(&table, SCROLLUP, &idx);
					break;
				case KEY_PPAGE:
				case '-':
					pageethwin(&table, SCROLLDOWN, &idx);
					break;
				case KEY_NPAGE:
				case ' ':
					pageethwin(&table, SCROLLUP, &idx);
					break;
				case 12:
				case 'l':
				case 'L':
					tx_refresh_screen();
					break;
				case 's':
				case 'S':
					show_hostsort_keywin(&sortwin,
							     &sortpanel);
					keymode = 1;
					break;
				case 'q':
				case 'Q':
				case 'x':
				case 'X':
				case 27:
				case 24:
					exitloop = 1;
				}
			} else if (keymode == 1) {
				del_panel(sortpanel);
				delwin(sortwin);
				sort_hosttab(&table, &idx, ch);
				keymode = 0;
			}
		}

		if (pkt.pkt_len <= 0)
			continue;

		char ifnamebuf[IFNAMSIZ];

		pkt_result =
			packet_process(&pkt, NULL, NULL, NULL,
				       MATCH_OPPOSITE_USECONFIG,
				       0);

		if (pkt_result != PACKET_OK)
			continue;

		if (!ifptr) {
			/* we're capturing on "All interfaces", */
			/* so get the name of the interface */
			/* of this packet */
			int r = dev_get_ifname(pkt.pkt_ifindex, ifnamebuf);
			if (r != 0) {
				write_error("Unable to get interface name");
				break;	/* can't get interface name, get out! */
			}
			ifname = ifnamebuf;
		}

		/* get HW addresses */
		switch (pkt.pkt_hatype) {
		case ARPHRD_ETHER: {
			memcpy(scratch_saddr, pkt.ethhdr->h_source, ETH_ALEN);
			memcpy(scratch_daddr, pkt.ethhdr->h_dest, ETH_ALEN);
			list = elist;
			break; }
		case ARPHRD_FDDI: {
			memcpy(scratch_saddr, pkt.fddihdr->saddr, FDDI_K_ALEN);
			memcpy(scratch_daddr, pkt.fddihdr->daddr, FDDI_K_ALEN);
			list = flist;
			break; }
		default:
			/* unknown link protocol */
			continue;
		}

		switch(pkt.pkt_protocol) {
		case ETH_P_IP:
		case ETH_P_IPV6:
			is_ip = 1;
			break;
		default:
			is_ip = 0;
			break;
		}

		/* Check source address entry */
		entry = in_ethtable(&table, pkt.pkt_hatype,
				    scratch_saddr);

		if (!entry)
			entry = addethentry(&table, pkt.pkt_hatype,
					    ifname, scratch_saddr, list);

		if (entry != NULL) {
			updateethent(entry, pkt.pkt_len, is_ip, 1);
			if (!entry->prev_entry->un.desc.printed)
				printethent(&table, entry->prev_entry,
					    idx);

			printethent(&table, entry, idx);
		}

		/* Check destination address entry */
		entry = in_ethtable(&table, pkt.pkt_hatype,
				    scratch_daddr);
		if (!entry)
			entry = addethentry(&table, pkt.pkt_hatype,
					    ifname, scratch_daddr, list);

		if (entry != NULL) {
			updateethent(entry, pkt.pkt_len, is_ip, 0);
			if (!entry->prev_entry->un.desc.printed)
				printethent(&table, entry->prev_entry,
					    idx);

			printethent(&table, entry, idx);
		}
	} while (!exitloop);

err_close:
	close(fd);

err:
	if (options.promisc) {
		promisc_restore_list(&promisc);
		promisc_destroy(&promisc);
	}

	if (logging) {
		signal(SIGUSR1, SIG_DFL);
		writeethlog(table.head, time(NULL) - statbegin, logfile);
		writelog(logging, logfile,
			 "******** LAN traffic monitor stopped ********");
		fclose(logfile);
	}


	del_panel(table.tabpanel);
	delwin(table.tabwin);
	del_panel(table.borderpanel);
	delwin(table.borderwin);
	update_panels();
	doupdate();
	destroyethtab(&table);

	free_eth_desc(elist);
	free_eth_desc(flist);

	strcpy(current_logfile, "");
}
Example #30
0
/*
 * get_move:
 *	Get and execute a move from the player
 */
void
get_move(void)
{
	int c;
#ifdef FANCY
	int lastmove;
#endif
	if (Waiting)
		return;

#ifdef FANCY
	if (Pattern_roll) {
		if (Next_move >= Move_list)
			lastmove = *Next_move;
		else
			lastmove = -1;	/* flag for "first time in" */
	} else
		lastmove = 0; /* Shut up gcc */
#endif
	for (;;) {
		if (Teleport && must_telep())
			goto teleport;
		if (Running)
			c = Run_ch;
		else if (Count != 0)
			c = Cnt_move;
#ifdef FANCY
		else if (Num_robots > 1 && Stand_still)
			c = '>';
		else if (Num_robots > 1 && Pattern_roll) {
			if (*++Next_move == '\0') {
				if (lastmove < 0)
					goto over;
				Next_move = Move_list;
			}
			c = *Next_move;
			mvaddch(0, 0, c);
			if (c == lastmove)
				goto over;
		}
#endif
		else {
over:
			c = getchar();
			if (isdigit(c)) {
				Count = (c - '0');
				while (isdigit(c = getchar()))
					Count = Count * 10 + (c - '0');
				if (c == ESC)
					goto over;
				Cnt_move = c;
				if (Count)
					leaveok(stdscr, true);
			}
		}

		switch (c) {
		  case ' ':
		  case '.':
			if (do_move(0, 0))
				goto ret;
			break;
		  case 'y':
			if (do_move(-1, -1))
				goto ret;
			break;
		  case 'k':
			if (do_move(-1, 0))
				goto ret;
			break;
		  case 'u':
			if (do_move(-1, 1))
				goto ret;
			break;
		  case 'h':
			if (do_move(0, -1))
				goto ret;
			break;
		  case 'l':
			if (do_move(0, 1))
				goto ret;
			break;
		  case 'b':
			if (do_move(1, -1))
				goto ret;
			break;
		  case 'j':
			if (do_move(1, 0))
				goto ret;
			break;
		  case 'n':
			if (do_move(1, 1))
				goto ret;
			break;
		  case 'Y': case 'U': case 'H': case 'J':
		  case 'K': case 'L': case 'B': case 'N':
		  case '>':
			Running = true;
			if (c == '>')
				Run_ch = ' ';
			else
				Run_ch = tolower(c);
			leaveok(stdscr, true);
			break;
		  case 'q':
		  case 'Q':
			if (query("Really quit?"))
				quit();
			refresh();
			break;
		  case 'w':
		  case 'W':
			Waiting = true;
			leaveok(stdscr, true);
			goto ret;
		  case 't':
		  case 'T':
teleport:
			Running = false;
			mvaddch(My_pos.y, My_pos.x, ' ');
			My_pos = *rnd_pos();
			mvaddch(My_pos.y, My_pos.x, PLAYER);
			leaveok(stdscr, false);
			refresh();
			flush_in();
			goto ret;
		  case CTRL('L'):
			wrefresh(curscr);
			break;
		  case EOF:
			break;
		  default:
			putchar(CTRL('G'));
			reset_count();
			fflush(stdout);
			break;
		}
	}
ret:
	if (Count > 0)
		if (--Count == 0)
			leaveok(stdscr, false);
}