poll - Fix events == 0 handling for TAP and TUN, fix console spam
[dragonfly.git] / bin / ls / print.c
blob7e7982bdc793835bcf232b421951f0b2d005d413
1 /*-
2 * Copyright (c) 1989, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * Michael Fischbein.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
32 * @(#)print.c 8.4 (Berkeley) 4/17/94
33 * $FreeBSD: src/bin/ls/print.c,v 1.73 2004/06/08 09:27:42 das Exp $
36 #include <sys/param.h>
37 #include <sys/stat.h>
39 #include <err.h>
40 #include <errno.h>
41 #include <fts.h>
42 #include <langinfo.h>
43 #include <libutil.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <time.h>
48 #include <unistd.h>
49 #include <locale.h>
50 #ifdef COLORLS
51 #include <ctype.h>
52 #include <termcap.h>
53 #include <signal.h>
54 #endif
56 #include "ls.h"
57 #include "extern.h"
59 static int printaname(const FTSENT *, u_long, u_long);
60 static void printlink(const FTSENT *);
61 static void printtime(const struct timespec);
62 static int printtype(u_int);
63 static void printsize(size_t, off_t);
64 #ifdef COLORLS
65 static void endcolor(int);
66 static int colortype(mode_t);
67 #endif
69 #define IS_NOPRINT(p) ((p)->fts_number == NO_PRINT)
71 #ifdef COLORLS
72 /* Most of these are taken from <sys/stat.h> */
73 typedef enum Colors {
74 C_DIR, /* directory */
75 C_LNK, /* symbolic link */
76 C_SOCK, /* socket */
77 C_FIFO, /* pipe */
78 C_EXEC, /* executable */
79 C_BLK, /* block special */
80 C_CHR, /* character special */
81 C_SUID, /* setuid executable */
82 C_SGID, /* setgid executable */
83 C_WSDIR, /* directory writeble to others, with sticky
84 * bit */
85 C_WDIR, /* directory writeble to others, without
86 * sticky bit */
87 C_NUMCOLORS /* just a place-holder */
88 } Colors;
90 static const char *defcolors = "exfxcxdxbxegedabagacad";
92 /* colors for file types */
93 static struct {
94 int num[2];
95 int bold;
96 } colors[C_NUMCOLORS];
97 #endif
99 void
100 printscol(const DISPLAY *dp)
102 FTSENT *p;
104 for (p = dp->list; p; p = p->fts_link) {
105 if (IS_NOPRINT(p))
106 continue;
107 printaname(p, dp->s_inode, dp->s_block);
108 putchar('\n');
113 * print name in current style
116 printname(const char *name)
118 if (f_octal || f_octal_escape)
119 return prn_octal(name);
120 else if (f_nonprint)
121 return prn_printable(name);
122 else
123 return prn_normal(name);
126 void
127 printlong(const DISPLAY *dp)
129 struct stat *sp;
130 FTSENT *p;
131 NAMES *np;
132 char buf[20];
133 #ifdef COLORLS
134 int color_printed = 0;
135 #endif
137 if ((dp->list == NULL || dp->list->fts_level != FTS_ROOTLEVEL) &&
138 (f_longform || f_size)) {
139 printf("total %lu\n", howmany(dp->btotal, blocksize));
142 for (p = dp->list; p; p = p->fts_link) {
143 if (IS_NOPRINT(p))
144 continue;
145 sp = p->fts_statp;
146 if (f_inode)
147 printf("%*ju ", dp->s_inode, (uintmax_t)sp->st_ino);
148 if (f_size)
149 printf("%*jd ",
150 dp->s_block, howmany(sp->st_blocks, blocksize));
151 strmode(sp->st_mode, buf);
152 np = p->fts_pointer;
153 printf("%s %*u %-*s %-*s ", buf, dp->s_nlink,
154 sp->st_nlink, dp->s_user, np->user, dp->s_group,
155 np->group);
156 if (f_flags)
157 printf("%-*s ", dp->s_flags, np->flags);
158 if (S_ISCHR(sp->st_mode) || S_ISBLK(sp->st_mode))
159 printf("%3d, 0x%08x ",
160 major(sp->st_rdev), (u_int)minor(sp->st_rdev));
161 else if (dp->bcfile)
162 printf("%*s%*jd ",
163 8 - dp->s_size, "", dp->s_size, (intmax_t)sp->st_size);
164 else
165 printsize(dp->s_size, sp->st_size);
166 if (f_accesstime)
167 printtime(sp->st_atim);
168 else if (f_statustime)
169 printtime(sp->st_ctim);
170 else
171 printtime(sp->st_mtim);
172 putchar(' ');
173 #ifdef COLORLS
174 if (f_color)
175 color_printed = colortype(sp->st_mode);
176 #endif
177 printname(p->fts_name);
178 #ifdef COLORLS
179 if (f_color && color_printed)
180 endcolor(0);
181 #endif
182 if (f_type)
183 printtype(sp->st_mode);
184 if (S_ISLNK(sp->st_mode))
185 printlink(p);
186 putchar('\n');
190 void
191 printstream(const DISPLAY *dp)
193 FTSENT *p;
194 int chcnt;
196 for (p = dp->list, chcnt = 0; p; p = p->fts_link) {
197 if (p->fts_number == NO_PRINT)
198 continue;
199 /* XXX strlen does not take octal escapes into account. */
200 if (strlen(p->fts_name) + chcnt +
201 (p->fts_link ? 2 : 0) >= (unsigned)termwidth) {
202 putchar('\n');
203 chcnt = 0;
205 chcnt += printaname(p, dp->s_inode, dp->s_block);
206 if (p->fts_link) {
207 printf(", ");
208 chcnt += 2;
211 if (chcnt)
212 putchar('\n');
215 void
216 printcol(const DISPLAY *dp)
218 static FTSENT **array;
219 static int lastentries = -1;
220 FTSENT *p;
221 FTSENT **narray;
222 int base;
223 int chcnt;
224 int cnt;
225 int col;
226 int colwidth;
227 int endcol;
228 int num;
229 int numcols;
230 int numrows;
231 int row;
232 int tabwidth;
234 if (f_notabs)
235 tabwidth = 1;
236 else
237 tabwidth = 8;
240 * Have to do random access in the linked list -- build a table
241 * of pointers.
243 if (dp->entries > lastentries) {
244 lastentries = dp->entries;
245 if ((narray =
246 realloc(array, dp->entries * sizeof(FTSENT *))) == NULL) {
247 warn(NULL);
248 printscol(dp);
249 return;
251 lastentries = dp->entries;
252 array = narray;
254 for (p = dp->list, num = 0; p; p = p->fts_link)
255 if (p->fts_number != NO_PRINT)
256 array[num++] = p;
258 colwidth = dp->maxlen;
259 if (f_inode)
260 colwidth += dp->s_inode + 1;
261 if (f_size)
262 colwidth += dp->s_block + 1;
263 if (f_type)
264 colwidth += 1;
266 colwidth = rounddown2(colwidth + tabwidth, tabwidth);
267 if (termwidth < 2 * colwidth) {
268 printscol(dp);
269 return;
271 numcols = termwidth / colwidth;
272 numrows = num / numcols;
273 if (num % numcols)
274 ++numrows;
276 if ((dp->list == NULL || dp->list->fts_level != FTS_ROOTLEVEL) &&
277 (f_longform || f_size)) {
278 printf("total %lu\n", howmany(dp->btotal, blocksize));
281 /* counter if f_sortacross, else case-by-case */
282 base = 0;
284 for (row = 0; row < numrows; ++row) {
285 endcol = colwidth;
286 if (!f_sortacross)
287 base = row;
288 for (col = 0, chcnt = 0; col < numcols; ++col) {
289 chcnt += printaname(array[base], dp->s_inode,
290 dp->s_block);
291 if (f_sortacross)
292 base++;
293 else
294 base += numrows;
295 if (base >= num)
296 break;
297 while ((cnt = (rounddown2(chcnt + tabwidth, tabwidth)))
298 <= endcol) {
299 if (f_sortacross && col + 1 >= numcols)
300 break;
301 putchar(f_notabs ? ' ' : '\t');
302 chcnt = cnt;
304 endcol += colwidth;
306 putchar('\n');
311 * print [inode] [size] name
312 * return # of characters printed, no trailing characters.
314 static int
315 printaname(const FTSENT *p, u_long inodefield, u_long sizefield)
317 struct stat *sp;
318 int chcnt;
319 #ifdef COLORLS
320 int color_printed = 0;
321 #endif
323 sp = p->fts_statp;
324 chcnt = 0;
325 if (f_inode) {
326 chcnt += printf("%*ju ", (int)inodefield,
327 (uintmax_t)sp->st_ino);
329 if (f_size)
330 chcnt += printf("%*jd ",
331 (int)sizefield, howmany(sp->st_blocks, blocksize));
332 #ifdef COLORLS
333 if (f_color)
334 color_printed = colortype(sp->st_mode);
335 #endif
336 chcnt += printname(p->fts_name);
337 #ifdef COLORLS
338 if (f_color && color_printed)
339 endcolor(0);
340 #endif
341 if (f_type)
342 chcnt += printtype(sp->st_mode);
343 return (chcnt);
346 static void
347 printtime(const struct timespec stt)
349 char longstring[80];
350 static time_t now;
351 const struct tm *ptime;
352 const char *format;
353 static char *lc_time;
354 static int posix_time;
356 #define SIXMONTHS ((365 / 2) * 86400)
358 if (now == 0)
359 now = time(NULL);
361 if (lc_time == NULL) {
362 lc_time = setlocale(LC_TIME, NULL);
363 posix_time = (strcmp(lc_time, "C") == 0);
366 if (f_timeformat) {
368 * User specified format
370 format = f_timeformat;
371 } else if (f_sectime) {
373 * POSIX: Not covered by standard. If C/POSIX locale used
374 * the old convention of mmm dd hh:mm:ss yyyy is kept.
375 * Named locales use the extended ISO 8601 format without T:
376 * YYYY-DD-MM hh:mm:ss
378 format = posix_time ? "%b %e %T %Y" : "%F %T";
379 } else if (posix_time) {
381 * POSIX: Future or older than 6 months returns equivalent of
382 * date "+%b %e %Y"
383 * If file was modified within the past 6 months,
384 * return equivalent of: date "+%b %e %H:%M"
386 if ((stt.tv_sec > now) || (stt.tv_sec < now - SIXMONTHS))
387 format = "%b %e %Y";
388 else
389 format = "%b %e %R";
390 } else {
392 * Named locales use format DD-MMM-YYYY hh:mm
393 * Regardless of locale, English is used for month field
395 format = "%d-%b-%Y %H:%M";
399 * If printing the nanotime field, always use GMT time
401 if (f_nanotime)
402 ptime = gmtime(&(stt.tv_sec));
403 else
404 ptime = localtime(&(stt.tv_sec));
406 strftime_l(longstring, sizeof(longstring), format, ptime, NULL);
407 fputs(longstring, stdout);
408 if (f_nanotime)
409 printf(".%09ju", stt.tv_nsec);
412 static int
413 printtype(u_int mode)
416 if (f_slash) {
417 if ((mode & S_IFMT) == S_IFDIR) {
418 putchar('/');
419 return (1);
421 return (0);
424 switch (mode & S_IFMT) {
425 case S_IFDIR:
426 putchar('/');
427 return (1);
428 case S_IFIFO:
429 putchar('|');
430 return (1);
431 case S_IFLNK:
432 putchar('@');
433 return (1);
434 case S_IFSOCK:
435 putchar('=');
436 return (1);
437 case S_IFWHT:
438 putchar('%');
439 return (1);
440 default:
441 break;
443 if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
444 putchar('*');
445 return (1);
447 return (0);
450 #ifdef COLORLS
451 static int
452 putch(int c)
454 putchar(c);
455 return 0;
458 static int
459 writech(int c)
461 char tmp = (char)c;
463 write(STDOUT_FILENO, &tmp, 1);
464 return 0;
467 static void
468 printcolor(Colors c)
470 char *ansiseq;
472 if (colors[c].bold)
473 tputs(enter_bold, 1, putch);
475 if (colors[c].num[0] != -1) {
476 ansiseq = tgoto(ansi_fgcol, 0, colors[c].num[0]);
477 if (ansiseq)
478 tputs(ansiseq, 1, putch);
480 if (colors[c].num[1] != -1) {
481 ansiseq = tgoto(ansi_bgcol, 0, colors[c].num[1]);
482 if (ansiseq)
483 tputs(ansiseq, 1, putch);
487 static void
488 endcolor(int sig)
490 tputs(ansi_coloff, 1, sig ? writech : putch);
491 tputs(attrs_off, 1, sig ? writech : putch);
494 static int
495 colortype(mode_t mode)
497 switch (mode & S_IFMT) {
498 case S_IFDIR:
499 if (mode & S_IWOTH)
500 if (mode & S_ISTXT)
501 printcolor(C_WSDIR);
502 else
503 printcolor(C_WDIR);
504 else
505 printcolor(C_DIR);
506 return (1);
507 case S_IFLNK:
508 printcolor(C_LNK);
509 return (1);
510 case S_IFSOCK:
511 printcolor(C_SOCK);
512 return (1);
513 case S_IFIFO:
514 printcolor(C_FIFO);
515 return (1);
516 case S_IFBLK:
517 printcolor(C_BLK);
518 return (1);
519 case S_IFCHR:
520 printcolor(C_CHR);
521 return (1);
522 default:;
524 if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
525 if (mode & S_ISUID)
526 printcolor(C_SUID);
527 else if (mode & S_ISGID)
528 printcolor(C_SGID);
529 else
530 printcolor(C_EXEC);
531 return (1);
533 return (0);
536 void
537 parsecolors(const char *cs)
539 int i;
540 int j;
541 size_t len;
542 char c[2];
543 short legacy_warn = 0;
545 if (cs == NULL)
546 cs = ""; /* LSCOLORS not set */
547 len = strlen(cs);
548 for (i = 0; i < C_NUMCOLORS; i++) {
549 colors[i].bold = 0;
551 if (len <= 2 * (size_t)i) {
552 c[0] = defcolors[2 * i];
553 c[1] = defcolors[2 * i + 1];
554 } else {
555 c[0] = cs[2 * i];
556 c[1] = cs[2 * i + 1];
558 for (j = 0; j < 2; j++) {
559 /* Legacy colours used 0-7 */
560 if (c[j] >= '0' && c[j] <= '7') {
561 colors[i].num[j] = c[j] - '0';
562 if (!legacy_warn) {
563 warnx("LSCOLORS should use "
564 "characters a-h instead of 0-9 ("
565 "see the manual page)\n");
567 legacy_warn = 1;
568 } else if (c[j] >= 'a' && c[j] <= 'h')
569 colors[i].num[j] = c[j] - 'a';
570 else if (c[j] >= 'A' && c[j] <= 'H') {
571 colors[i].num[j] = c[j] - 'A';
572 colors[i].bold = 1;
573 } else if (tolower((unsigned char)c[j]) == 'x')
574 colors[i].num[j] = -1;
575 else {
576 warnx("invalid character '%c' in LSCOLORS"
577 " env var\n", c[j]);
578 colors[i].num[j] = -1;
584 void
585 colorquit(int sig)
587 endcolor(sig);
589 signal(sig, SIG_DFL);
590 kill(getpid(), sig);
593 #endif /* COLORLS */
595 static void
596 printlink(const FTSENT *p)
598 int lnklen;
599 char name[MAXPATHLEN + 1];
600 char path[MAXPATHLEN + 1];
602 if (p->fts_level == FTS_ROOTLEVEL)
603 snprintf(name, sizeof(name), "%s", p->fts_name);
604 else
605 snprintf(name, sizeof(name),
606 "%s/%s", p->fts_parent->fts_accpath, p->fts_name);
607 if ((lnklen = readlink(name, path, sizeof(path) - 1)) == -1) {
608 fprintf(stderr, "\nls: %s: %s\n", name, strerror(errno));
609 return;
611 path[lnklen] = '\0';
612 printf(" -> ");
613 printname(path);
616 static void
617 printsize(size_t width, off_t bytes)
619 if (f_humanval) {
620 char buf[5];
622 humanize_number(buf, sizeof(buf), (int64_t)bytes, "",
623 HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
624 printf("%5s ", buf);
625 } else
626 printf("%*jd ", (int)width, (uintmax_t)bytes);