]> granicus.if.org Git - sudo/blob - lib/util/ttysize.c
66fa1463f5ac8a586378c5763d70641bb45f9c85
[sudo] / lib / util / ttysize.c
1 /*
2  * Copyright (c) 2010-2012, 2014-2015 Todd C. Miller <Todd.Miller@sudo.ws>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16
17 /*
18  * This is an open source non-commercial project. Dear PVS-Studio, please check it.
19  * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
20  */
21
22 #include <config.h>
23
24 #include <sys/types.h>
25 #include <sys/ioctl.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <unistd.h>
29 #include <termios.h>            /* for struct winsize on HP-UX */
30 #include <limits.h>
31
32 #include "sudo_compat.h"
33 #include "sudo_debug.h"
34 #include "sudo_util.h"
35
36 static int
37 get_ttysize_ioctl(int *rowp, int *colp)
38 {
39     struct winsize wsize;
40     debug_decl(get_ttysize_ioctl, SUDO_DEBUG_UTIL)
41
42     if (ioctl(STDERR_FILENO, TIOCGWINSZ, &wsize) == 0 &&
43         wsize.ws_row != 0 && wsize.ws_col  != 0) {
44         *rowp = wsize.ws_row;
45         *colp = wsize.ws_col;
46         debug_return_int(0);
47     }
48     debug_return_int(-1);
49 }
50
51 void
52 sudo_get_ttysize_v1(int *rowp, int *colp)
53 {
54     debug_decl(sudo_get_ttysize, SUDO_DEBUG_UTIL)
55
56     if (get_ttysize_ioctl(rowp, colp) == -1) {
57         char *p;
58
59         /* Fall back on $LINES and $COLUMNS. */
60         if ((p = getenv("LINES")) == NULL ||
61             (*rowp = strtonum(p, 1, INT_MAX, NULL)) <= 0) {
62             *rowp = 24;
63         }
64         if ((p = getenv("COLUMNS")) == NULL ||
65             (*colp = strtonum(p, 1, INT_MAX, NULL)) <= 0) {
66             *colp = 80;
67         }
68     }
69
70     debug_return;
71 }