Merge from vendor branch TNFTP:
[dragonfly.git] / bin / ls / print.c
1 /*
2  * Copyright (c) 1989, 1993, 1994
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Michael Fischbein.
7  *
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  * 4. 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.
19  *
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.
31  *
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 $
34  * $DragonFly: src/bin/ls/print.c,v 1.17 2005/11/06 11:44:02 swildner Exp $
35  */
36
37 #include <sys/param.h>
38 #include <sys/stat.h>
39
40 #include <err.h>
41 #include <errno.h>
42 #include <fts.h>
43 #include <langinfo.h>
44 #include <libutil.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <time.h>
49 #include <unistd.h>
50 #ifdef COLORLS
51 #include <ctype.h>
52 #include <termcap.h>
53 #include <signal.h>
54 #endif
55
56 #include "ls.h"
57 #include "extern.h"
58
59 static int      printaname(const FTSENT *, u_long, u_long);
60 static void     printlink(const FTSENT *);
61 static void     printtime(time_t);
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
68
69 #define IS_NOPRINT(p)   ((p)->fts_number == NO_PRINT)
70
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;
89
90 static const char *defcolors = "exfxcxdxbxegedabagacad";
91
92 /* colors for file types */
93 static struct {
94         int     num[2];
95         int     bold;
96 } colors[C_NUMCOLORS];
97 #endif
98
99 void
100 printscol(const DISPLAY *dp)
101 {
102         FTSENT *p;
103
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');
109         }
110 }
111
112 /*
113  * print name in current style
114  */
115 int
116 printname(const char *name)
117 {
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);
124 }
125
126 void
127 printlong(const DISPLAY *dp)
128 {
129         struct stat *sp;
130         FTSENT *p;
131         NAMES *np;
132         char buf[20];
133 #ifdef COLORLS
134         int color_printed = 0;
135 #endif
136
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));
140         }
141
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("%*lu ", dp->s_inode, (u_long)sp->st_ino);
148                 if (f_size)
149                         printf("%*lld ",
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_fsmid)
157                         printf("%s ", np->fsmid);
158                 if (f_flags)
159                         printf("%-*s ", dp->s_flags, np->flags);
160                 if (S_ISCHR(sp->st_mode) || S_ISBLK(sp->st_mode))
161                         if (minor(sp->st_rdev) > 255 || minor(sp->st_rdev) < 0)
162                                 printf("%3d, 0x%08x ",
163                                     major(sp->st_rdev),
164                                     (u_int)minor(sp->st_rdev));
165                         else
166                                 printf("%3d, %3d ",
167                                     major(sp->st_rdev), minor(sp->st_rdev));
168                 else if (dp->bcfile)
169                         printf("%*s%*lld ",
170                             8 - dp->s_size, "", dp->s_size, sp->st_size);
171                 else
172                         printsize(dp->s_size, sp->st_size);
173                 if (f_accesstime)
174                         printtime(sp->st_atime);
175                 else if (f_statustime)
176                         printtime(sp->st_ctime);
177                 else
178                         printtime(sp->st_mtime);
179 #ifdef COLORLS
180                 if (f_color)
181                         color_printed = colortype(sp->st_mode);
182 #endif
183                 printname(p->fts_name);
184 #ifdef COLORLS
185                 if (f_color && color_printed)
186                         endcolor(0);
187 #endif
188                 if (f_type)
189                         printtype(sp->st_mode);
190                 if (S_ISLNK(sp->st_mode))
191                         printlink(p);
192                 putchar('\n');
193         }
194 }
195
196 void
197 printstream(const DISPLAY *dp)
198 {
199         FTSENT *p;
200         int chcnt;
201
202         for (p = dp->list, chcnt = 0; p; p = p->fts_link) {
203                 if (p->fts_number == NO_PRINT)
204                         continue;
205                 /* XXX strlen does not take octal escapes into account. */
206                 if (strlen(p->fts_name) + chcnt +
207                     (p->fts_link ? 2 : 0) >= (unsigned)termwidth) {
208                         putchar('\n');
209                         chcnt = 0;
210                 }
211                 chcnt += printaname(p, dp->s_inode, dp->s_block);
212                 if (p->fts_link) {
213                         printf(", ");
214                         chcnt += 2;
215                 }
216         }
217         if (chcnt)
218                 putchar('\n');
219 }
220                 
221 void
222 printcol(const DISPLAY *dp)
223 {
224         static FTSENT **array;
225         static int lastentries = -1;
226         FTSENT *p;
227         FTSENT **narray;
228         int base;
229         int chcnt;
230         int cnt;
231         int col;
232         int colwidth;
233         int endcol;
234         int num;
235         int numcols;
236         int numrows;
237         int row;
238         int tabwidth;
239
240         if (f_notabs)
241                 tabwidth = 1;
242         else
243                 tabwidth = 8;
244
245         /*
246          * Have to do random access in the linked list -- build a table
247          * of pointers.
248          */
249         if (dp->entries > lastentries) {
250                 lastentries = dp->entries;
251                 if ((narray =
252                     realloc(array, dp->entries * sizeof(FTSENT *))) == NULL) {
253                         warn(NULL);
254                         printscol(dp);
255                         return;
256                 }
257                 lastentries = dp->entries;
258                 array = narray;
259         }
260         for (p = dp->list, num = 0; p; p = p->fts_link)
261                 if (p->fts_number != NO_PRINT)
262                         array[num++] = p;
263
264         colwidth = dp->maxlen;
265         if (f_inode)
266                 colwidth += dp->s_inode + 1;
267         if (f_size)
268                 colwidth += dp->s_block + 1;
269         if (f_type)
270                 colwidth += 1;
271
272         colwidth = (colwidth + tabwidth) & ~(tabwidth - 1);
273         if (termwidth < 2 * colwidth) {
274                 printscol(dp);
275                 return;
276         }
277         numcols = termwidth / colwidth;
278         numrows = num / numcols;
279         if (num % numcols)
280                 ++numrows;
281
282         if ((dp->list == NULL || dp->list->fts_level != FTS_ROOTLEVEL) &&
283             (f_longform || f_size)) {
284                 printf("total %lu\n", howmany(dp->btotal, blocksize));
285         }
286
287         /* counter if f_sortacross, else case-by-case */
288         base = 0;
289
290         for (row = 0; row < numrows; ++row) {
291                 endcol = colwidth;
292                 if (!f_sortacross)
293                         base = row;
294                 for (col = 0, chcnt = 0; col < numcols; ++col) {
295                         chcnt += printaname(array[base], dp->s_inode,
296                             dp->s_block);
297                         if (f_sortacross)
298                                 base++;
299                         else
300                                 base += numrows;
301                         if (base >= num)
302                                 break;
303                         while ((cnt = ((chcnt + tabwidth) & ~(tabwidth - 1)))
304                             <= endcol) {
305                                 if (f_sortacross && col + 1 >= numcols)
306                                         break;
307                                 putchar(f_notabs ? ' ' : '\t');
308                                 chcnt = cnt;
309                         }
310                         endcol += colwidth;
311                 }
312                 putchar('\n');
313         }
314 }
315
316 /*
317  * print [inode] [size] name
318  * return # of characters printed, no trailing characters.
319  */
320 static int
321 printaname(const FTSENT *p, u_long inodefield, u_long sizefield)
322 {
323         struct stat *sp;
324         int chcnt;
325 #ifdef COLORLS
326         int color_printed = 0;
327 #endif
328
329         sp = p->fts_statp;
330         chcnt = 0;
331         if (f_inode)
332                 chcnt += printf("%*lu ", (int)inodefield, (u_long)sp->st_ino);
333         if (f_size)
334                 chcnt += printf("%*lld ",
335                     (int)sizefield, howmany(sp->st_blocks, blocksize));
336 #ifdef COLORLS
337         if (f_color)
338                 color_printed = colortype(sp->st_mode);
339 #endif
340         chcnt += printname(p->fts_name);
341 #ifdef COLORLS
342         if (f_color && color_printed)
343                 endcolor(0);
344 #endif
345         if (f_type)
346                 chcnt += printtype(sp->st_mode);
347         return (chcnt);
348 }
349
350 static void
351 printtime(time_t ftime)
352 {
353         char longstring[80];
354         static time_t now;
355         const char *format;
356         static int d_first = -1;
357
358         if (d_first < 0)
359                 d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
360         if (now == 0)
361                 now = time(NULL);
362
363 #define SIXMONTHS       ((365 / 2) * 86400)
364         if (f_sectime)
365                 /* mmm dd hh:mm:ss yyyy || dd mmm hh:mm:ss yyyy */
366                 format = d_first ? "%e %b %T %Y " : "%b %e %T %Y ";
367         else if (ftime + SIXMONTHS > now && ftime < now + SIXMONTHS)
368                 /* mmm dd hh:mm || dd mmm hh:mm */
369                 format = d_first ? "%e %b %R " : "%b %e %R ";
370         else
371                 /* mmm dd  yyyy || dd mmm  yyyy */
372                 format = d_first ? "%e %b  %Y " : "%b %e  %Y ";
373         strftime(longstring, sizeof(longstring), format, localtime(&ftime));
374         fputs(longstring, stdout);
375 }
376
377 static int
378 printtype(u_int mode)
379 {
380
381         if (f_slash) {
382                 if ((mode & S_IFMT) == S_IFDIR) {
383                         putchar('/');
384                         return (1);
385                 }
386                 return (0);
387         }
388
389         switch (mode & S_IFMT) {
390         case S_IFDIR:
391                 putchar('/');
392                 return (1);
393         case S_IFIFO:
394                 putchar('|');
395                 return (1);
396         case S_IFLNK:
397                 putchar('@');
398                 return (1);
399         case S_IFSOCK:
400                 putchar('=');
401                 return (1);
402         case S_IFWHT:
403                 putchar('%');
404                 return (1);
405         default:
406                 break;
407         }
408         if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
409                 putchar('*');
410                 return (1);
411         }
412         return (0);
413 }
414
415 #ifdef COLORLS
416 static int
417 putch(int c)
418 {
419         putchar(c);
420         return 0;
421 }
422
423 static int
424 writech(int c)
425 {
426         char tmp = (char)c;
427
428         write(STDOUT_FILENO, &tmp, 1);
429         return 0;
430 }
431
432 static void
433 printcolor(Colors c)
434 {
435         char *ansiseq;
436
437         if (colors[c].bold)
438                 tputs(enter_bold, 1, putch);
439
440         if (colors[c].num[0] != -1) {
441                 ansiseq = tgoto(ansi_fgcol, 0, colors[c].num[0]);
442                 if (ansiseq)
443                         tputs(ansiseq, 1, putch);
444         }
445         if (colors[c].num[1] != -1) {
446                 ansiseq = tgoto(ansi_bgcol, 0, colors[c].num[1]);
447                 if (ansiseq)
448                         tputs(ansiseq, 1, putch);
449         }
450 }
451
452 static void
453 endcolor(int sig)
454 {
455         tputs(ansi_coloff, 1, sig ? writech : putch);
456         tputs(attrs_off, 1, sig ? writech : putch);
457 }
458
459 static int
460 colortype(mode_t mode)
461 {
462         switch (mode & S_IFMT) {
463         case S_IFDIR:
464                 if (mode & S_IWOTH)
465                         if (mode & S_ISTXT)
466                                 printcolor(C_WSDIR);
467                         else
468                                 printcolor(C_WDIR);
469                 else
470                         printcolor(C_DIR);
471                 return (1);
472         case S_IFLNK:
473                 printcolor(C_LNK);
474                 return (1);
475         case S_IFSOCK:
476                 printcolor(C_SOCK);
477                 return (1);
478         case S_IFIFO:
479                 printcolor(C_FIFO);
480                 return (1);
481         case S_IFBLK:
482                 printcolor(C_BLK);
483                 return (1);
484         case S_IFCHR:
485                 printcolor(C_CHR);
486                 return (1);
487         default:;
488         }
489         if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
490                 if (mode & S_ISUID)
491                         printcolor(C_SUID);
492                 else if (mode & S_ISGID)
493                         printcolor(C_SGID);
494                 else
495                         printcolor(C_EXEC);
496                 return (1);
497         }
498         return (0);
499 }
500
501 void
502 parsecolors(const char *cs)
503 {
504         int i;
505         int j;
506         size_t len;
507         char c[2];
508         short legacy_warn = 0;
509
510         if (cs == NULL)
511                 cs = "";        /* LSCOLORS not set */
512         len = strlen(cs);
513         for (i = 0; i < C_NUMCOLORS; i++) {
514                 colors[i].bold = 0;
515
516                 if (len <= 2 * (size_t)i) {
517                         c[0] = defcolors[2 * i];
518                         c[1] = defcolors[2 * i + 1];
519                 } else {
520                         c[0] = cs[2 * i];
521                         c[1] = cs[2 * i + 1];
522                 }
523                 for (j = 0; j < 2; j++) {
524                         /* Legacy colours used 0-7 */
525                         if (c[j] >= '0' && c[j] <= '7') {
526                                 colors[i].num[j] = c[j] - '0';
527                                 if (!legacy_warn) {
528                                         warnx("LSCOLORS should use "
529                                               "characters a-h instead of 0-9 ("
530                                               "see the manual page)\n");
531                                 }
532                                 legacy_warn = 1;
533                         } else if (c[j] >= 'a' && c[j] <= 'h')
534                                 colors[i].num[j] = c[j] - 'a';
535                         else if (c[j] >= 'A' && c[j] <= 'H') {
536                                 colors[i].num[j] = c[j] - 'A';
537                                 colors[i].bold = 1;
538                         } else if (tolower((unsigned char)c[j] == 'x'))
539                                 colors[i].num[j] = -1;
540                         else {
541                                 warnx("invalid character '%c' in LSCOLORS"
542                                       " env var\n", c[j]);
543                                 colors[i].num[j] = -1;
544                         }
545                 }
546         }
547 }
548
549 void
550 colorquit(int sig)
551 {
552         endcolor(sig);
553
554         signal(sig, SIG_DFL);
555         kill(getpid(), sig);
556 }
557
558 #endif /* COLORLS */
559
560 static void
561 printlink(const FTSENT *p)
562 {
563         int lnklen;
564         char name[MAXPATHLEN + 1];
565         char path[MAXPATHLEN + 1];
566
567         if (p->fts_level == FTS_ROOTLEVEL)
568                 snprintf(name, sizeof(name), "%s", p->fts_name);
569         else
570                 snprintf(name, sizeof(name),
571                     "%s/%s", p->fts_parent->fts_accpath, p->fts_name);
572         if ((lnklen = readlink(name, path, sizeof(path) - 1)) == -1) {
573                 fprintf(stderr, "\nls: %s: %s\n", name, strerror(errno));
574                 return;
575         }
576         path[lnklen] = '\0';
577         printf(" -> ");
578         printname(path);
579 }
580
581 static void
582 printsize(size_t width, off_t bytes)
583 {
584         if (f_humanval) {
585                 char buf[5];
586
587                 humanize_number(buf, sizeof(buf), (int64_t)bytes, "",
588                                 HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
589                 printf("%5s ", buf);
590         } else
591                 printf("%*lld ", width, bytes);
592 }