Imported Upstream version 1.7.6p1
[debian/sudo] / lbuf.c
diff --git a/lbuf.c b/lbuf.c
index bd218da873b32cc7ef68cce0245cf230659cff14..bafea18f8c65be2f9f4b564e11ae37ff61def04f 100644 (file)
--- a/lbuf.c
+++ b/lbuf.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007-2010 Todd C. Miller <Todd.Miller@courtesan.com>
+ * Copyright (c) 2007-2011 Todd C. Miller <Todd.Miller@courtesan.com>
  *
  * Permission to use, copy, modify, and distribute this software for any
  * purpose with or without fee is hereby granted, provided that the above
@@ -31,6 +31,9 @@
 # endif
 #endif /* STDC_HEADERS */
 #ifdef HAVE_STRING_H
+# if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
+#  include <memory.h>
+# endif
 # include <string.h>
 #endif /* HAVE_STRING_H */
 #ifdef HAVE_STRINGS_H
 #include "sudo.h"
 #include "lbuf.h"
 
-#if !defined(TIOCGSIZE) && defined(TIOCGWINSZ)
-# define TIOCGSIZE     TIOCGWINSZ
-# define ttysize       winsize
-# define ts_cols       ws_col
+/* Compatibility with older tty systems. */
+#if !defined(TIOCGWINSZ) && defined(TIOCGSIZE)
+# define TIOCGWINSZ    TIOCGSIZE
+# define winsize       ttysize
+# define ws_col                ts_cols
 #endif
 
 int
@@ -62,17 +66,17 @@ get_ttycols()
 {
     char *p;
     int cols;
-#ifdef TIOCGSIZE
-    struct ttysize win;
+#ifdef TIOCGWINSZ
+    struct winsize wsize;
 
-    if (ioctl(STDERR_FILENO, TIOCGSIZE, &win) == 0 && win.ts_cols != 0)
-       return((int)win.ts_cols);
+    if (ioctl(STDERR_FILENO, TIOCGWINSZ, &wsize) == 0 && wsize.ws_col != 0)
+       return (int)wsize.ws_col;
 #endif
 
     /* Fall back on $COLUMNS. */
     if ((p = getenv("COLUMNS")) == NULL || (cols = atoi(p)) <= 0)
        cols = 80;
-    return(cols);
+    return cols;
 }
 
 void
@@ -276,14 +280,16 @@ lbuf_print(lbuf)
     struct lbuf *lbuf;
 {
     char *cp, *ep;
-    int len, contlen;
+    int len;
 
-    contlen = lbuf->continuation ? strlen(lbuf->continuation) : 0;
+    if (lbuf->buf == NULL || lbuf->len == 0)
+       goto done;
 
     /* For very small widths just give up... */
-    if (lbuf->cols <= lbuf->indent + contlen + 20) {
+    len = lbuf->continuation ? strlen(lbuf->continuation) : 0;
+    if (lbuf->cols <= lbuf->indent + len + 20) {
+       lbuf->buf[lbuf->len] = '\0';
        lbuf->output(lbuf->buf);
-       lbuf->output("\n");
        goto done;
     }
 
@@ -293,9 +299,11 @@ lbuf_print(lbuf)
            lbuf->output("\n");
            cp++;
        } else {
-           ep = memchr(cp, '\n', lbuf->len - (cp - lbuf->buf));
-           len = ep ? (int)(ep - cp) : lbuf->len;
-           lbuf_println(lbuf, cp, len);
+           len = lbuf->len - (cp - lbuf->buf);
+           if ((ep = memchr(cp, '\n', len)) != NULL)
+               len = (int)(ep - cp);
+           if (len)
+               lbuf_println(lbuf, cp, len);
            cp = ep ? ep + 1 : NULL;
        }
     }