Get rid of the third clause from the UCB license.
[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.19.2.7 2002/11/17 10:27:34 tjr Exp $
34  * $DragonFly: src/bin/ls/print.c,v 1.9 2005/09/18 10:39:35 asmodai 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 <math.h>
44 #include <langinfo.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(FTSENT *, u_long, u_long);
60 static void     printlink(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 #define KILO_SZ(n) (n)
72 #define MEGA_SZ(n) ((n) * (n))
73 #define GIGA_SZ(n) ((n) * (n) * (n))
74 #define TERA_SZ(n) ((n) * (n) * (n) * (n))
75 #define PETA_SZ(n) ((n) * (n) * (n) * (n) * (n))
76
77 #define KILO_2_SZ (KILO_SZ(1024ULL))
78 #define MEGA_2_SZ (MEGA_SZ(1024ULL))
79 #define GIGA_2_SZ (GIGA_SZ(1024ULL))
80 #define TERA_2_SZ (TERA_SZ(1024ULL))
81 #define PETA_2_SZ (PETA_SZ(1024ULL))
82
83 static unsigned long long vals_base2[] = {1, KILO_2_SZ, MEGA_2_SZ, GIGA_2_SZ, TERA_2_SZ, PETA_2_SZ};
84
85 typedef enum {
86         NONE, KILO, MEGA, GIGA, TERA, PETA, UNIT_MAX
87 } unit_t;
88 static unit_t unit_adjust(off_t *);
89
90 static int unitp[] = {NONE, KILO, MEGA, GIGA, TERA, PETA};
91
92 #ifdef COLORLS
93 /* Most of these are taken from <sys/stat.h> */
94 typedef enum Colors {
95         C_DIR,                  /* directory */
96         C_LNK,                  /* symbolic link */
97         C_SOCK,                 /* socket */
98         C_FIFO,                 /* pipe */
99         C_EXEC,                 /* executable */
100         C_BLK,                  /* block special */
101         C_CHR,                  /* character special */
102         C_SUID,                 /* setuid executable */
103         C_SGID,                 /* setgid executable */
104         C_WSDIR,                /* directory writeble to others, with sticky
105                                  * bit */
106         C_WDIR,                 /* directory writeble to others, without
107                                  * sticky bit */
108         C_NUMCOLORS             /* just a place-holder */
109 } Colors;
110
111 static const char *defcolors = "exfxcxdxbxegedabagacad";
112
113 /* colors for file types */
114 static struct {
115         int     num[2];
116         int     bold;
117 } colors[C_NUMCOLORS];
118 #endif
119
120 void
121 printscol(DISPLAY *dp)
122 {
123         FTSENT *p;
124
125         for (p = dp->list; p; p = p->fts_link) {
126                 if (IS_NOPRINT(p))
127                         continue;
128                 printaname(p, dp->s_inode, dp->s_block);
129                 putchar('\n');
130         }
131 }
132
133 /*
134  * print name in current style
135  */
136 int
137 printname(const char *name)
138 {
139         if (f_octal || f_octal_escape)
140                 return prn_octal(name);
141         else if (f_nonprint)
142                 return prn_printable(name);
143         else
144                 return printf("%s", name);
145 }
146
147 void
148 printlong(DISPLAY *dp)
149 {
150         struct stat *sp;
151         FTSENT *p;
152         NAMES *np;
153         char buf[20];
154 #ifdef COLORLS
155         int color_printed = 0;
156 #endif
157
158         if (dp->list->fts_level != FTS_ROOTLEVEL && (f_longform || f_size))
159                 printf("total %lu\n", howmany(dp->btotal, blocksize));
160
161         for (p = dp->list; p; p = p->fts_link) {
162                 if (IS_NOPRINT(p))
163                         continue;
164                 sp = p->fts_statp;
165                 if (f_inode)
166                         printf("%*lu ", dp->s_inode, (u_long)sp->st_ino);
167                 if (f_size)
168                         printf("%*lld ",
169                             dp->s_block, howmany(sp->st_blocks, blocksize));
170                 strmode(sp->st_mode, buf);
171                 np = p->fts_pointer;
172                 printf("%s %*u %-*s  %-*s  ", buf, dp->s_nlink,
173                     sp->st_nlink, dp->s_user, np->user, dp->s_group,
174                     np->group);
175                 if (f_fsmid)
176                         printf("%s ", np->fsmid);
177                 if (f_flags)
178                         printf("%-*s ", dp->s_flags, np->flags);
179                 if (S_ISCHR(sp->st_mode) || S_ISBLK(sp->st_mode))
180                         if (minor(sp->st_rdev) > 255 || minor(sp->st_rdev) < 0)
181                                 printf("%3d, 0x%08x ",
182                                     major(sp->st_rdev),
183                                     (u_int)minor(sp->st_rdev));
184                         else
185                                 printf("%3d, %3d ",
186                                     major(sp->st_rdev), minor(sp->st_rdev));
187                 else if (dp->bcfile)
188                         printf("%*s%*lld ",
189                             8 - dp->s_size, "", dp->s_size, sp->st_size);
190                 else
191                         printsize(dp->s_size, sp->st_size);
192                 if (f_accesstime)
193                         printtime(sp->st_atime);
194                 else if (f_statustime)
195                         printtime(sp->st_ctime);
196                 else
197                         printtime(sp->st_mtime);
198 #ifdef COLORLS
199                 if (f_color)
200                         color_printed = colortype(sp->st_mode);
201 #endif
202                 printname(p->fts_name);
203 #ifdef COLORLS
204                 if (f_color && color_printed)
205                         endcolor(0);
206 #endif
207                 if (f_type)
208                         printtype(sp->st_mode);
209                 if (S_ISLNK(sp->st_mode))
210                         printlink(p);
211                 putchar('\n');
212         }
213 }
214
215 void
216 printstream(DISPLAY *dp)
217 {
218         FTSENT *p;
219         int chcnt;
220
221         for (p = dp->list, chcnt = 0; p; p = p->fts_link) {
222                 if (p->fts_number == NO_PRINT)
223                         continue;
224                 if (strlen(p->fts_name) + chcnt +
225                     (p->fts_link ? 2 : 0) >= (unsigned)termwidth) {
226                         putchar('\n');
227                         chcnt = 0;
228                 }
229                 chcnt += printaname(p, dp->s_inode, dp->s_block);
230                 if (p->fts_link) {
231                         printf(", ");
232                         chcnt += 2;
233                 }
234         }
235         if (chcnt)
236                 putchar('\n');
237 }
238                 
239 void
240 printcol(DISPLAY *dp)
241 {
242         static FTSENT **array;
243         static int lastentries = -1;
244         FTSENT *p;
245         FTSENT **narray;
246         int base;
247         int chcnt;
248         int cnt;
249         int col;
250         int colwidth;
251         int endcol;
252         int num;
253         int numcols;
254         int numrows;
255         int row;
256         int tabwidth;
257
258         if (f_notabs)
259                 tabwidth = 1;
260         else
261                 tabwidth = 8;
262
263         /*
264          * Have to do random access in the linked list -- build a table
265          * of pointers.
266          */
267         if (dp->entries > lastentries) {
268                 lastentries = dp->entries;
269                 if ((narray =
270                     realloc(array, dp->entries * sizeof(FTSENT *))) == NULL) {
271                         warn(NULL);
272                         printscol(dp);
273                         return;
274                 }
275                 lastentries = dp->entries;
276                 array = narray;
277         }
278         for (p = dp->list, num = 0; p; p = p->fts_link)
279                 if (p->fts_number != NO_PRINT)
280                         array[num++] = p;
281
282         colwidth = dp->maxlen;
283         if (f_inode)
284                 colwidth += dp->s_inode + 1;
285         if (f_size)
286                 colwidth += dp->s_block + 1;
287         if (f_type)
288                 colwidth += 1;
289
290         colwidth = (colwidth + tabwidth) & ~(tabwidth - 1);
291         if (termwidth < 2 * colwidth) {
292                 printscol(dp);
293                 return;
294         }
295         numcols = termwidth / colwidth;
296         numrows = num / numcols;
297         if (num % numcols)
298                 ++numrows;
299
300         if (dp->list->fts_level != FTS_ROOTLEVEL && (f_longform || f_size))
301                 printf("total %lu\n", howmany(dp->btotal, blocksize));
302
303         /* counter if f_sortacross, else case-by-case */
304         base = 0;
305
306         for (row = 0; row < numrows; ++row) {
307                 endcol = colwidth;
308                 if (!f_sortacross)
309                         base = row;
310                 for (col = 0, chcnt = 0; col < numcols; ++col) {
311                         chcnt += printaname(array[base], dp->s_inode,
312                             dp->s_block);
313                         if (f_sortacross)
314                                 base++;
315                         else
316                                 base += numrows;
317                         if (base >= num)
318                                 break;
319                         while ((cnt = ((chcnt + tabwidth) & ~(tabwidth - 1)))
320                             <= endcol) {
321                                 if (f_sortacross && col + 1 >= numcols)
322                                         break;
323                                 putchar(f_notabs ? ' ' : '\t');
324                                 chcnt = cnt;
325                         }
326                         endcol += colwidth;
327                 }
328                 putchar('\n');
329         }
330 }
331
332 /*
333  * print [inode] [size] name
334  * return # of characters printed, no trailing characters.
335  */
336 static int
337 printaname(FTSENT *p, u_long inodefield, u_long sizefield)
338 {
339         struct stat *sp;
340         int chcnt;
341 #ifdef COLORLS
342         int color_printed = 0;
343 #endif
344
345         sp = p->fts_statp;
346         chcnt = 0;
347         if (f_inode)
348                 chcnt += printf("%*lu ", (int)inodefield, (u_long)sp->st_ino);
349         if (f_size)
350                 chcnt += printf("%*lld ",
351                     (int)sizefield, howmany(sp->st_blocks, blocksize));
352 #ifdef COLORLS
353         if (f_color)
354                 color_printed = colortype(sp->st_mode);
355 #endif
356         chcnt += printname(p->fts_name);
357 #ifdef COLORLS
358         if (f_color && color_printed)
359                 endcolor(0);
360 #endif
361         if (f_type)
362                 chcnt += printtype(sp->st_mode);
363         return (chcnt);
364 }
365
366 static void
367 printtime(time_t ftime)
368 {
369         char longstring[80];
370         static time_t now;
371         const char *format;
372         static int d_first = -1;
373
374         if (d_first < 0)
375                 d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
376         if (now == 0)
377                 now = time(NULL);
378
379 #define SIXMONTHS       ((365 / 2) * 86400)
380         if (f_sectime)
381                 /* mmm dd hh:mm:ss yyyy || dd mmm hh:mm:ss yyyy */
382                 format = d_first ? "%e %b %T %Y " : "%b %e %T %Y ";
383         else if (ftime + SIXMONTHS > now && ftime < now + SIXMONTHS)
384                 /* mmm dd hh:mm || dd mmm hh:mm */
385                 format = d_first ? "%e %b %R " : "%b %e %R ";
386         else
387                 /* mmm dd  yyyy || dd mmm  yyyy */
388                 format = d_first ? "%e %b  %Y " : "%b %e  %Y ";
389         strftime(longstring, sizeof(longstring), format, localtime(&ftime));
390         fputs(longstring, stdout);
391 }
392
393 static int
394 printtype(u_int mode)
395 {
396
397         if (f_slash) {
398                 if ((mode & S_IFMT) == S_IFDIR) {
399                         putchar('/');
400                         return (1);
401                 }
402                 return (0);
403         }
404
405         switch (mode & S_IFMT) {
406         case S_IFDIR:
407                 putchar('/');
408                 return (1);
409         case S_IFIFO:
410                 putchar('|');
411                 return (1);
412         case S_IFLNK:
413                 putchar('@');
414                 return (1);
415         case S_IFSOCK:
416                 putchar('=');
417                 return (1);
418         case S_IFWHT:
419                 putchar('%');
420                 return (1);
421         default:
422                 break;
423         }
424         if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
425                 putchar('*');
426                 return (1);
427         }
428         return (0);
429 }
430
431 #ifdef COLORLS
432 static int
433 putch(int c)
434 {
435         putchar(c);
436         return 0;
437 }
438
439 static int
440 writech(int c)
441 {
442         char tmp = c;
443
444         write(STDOUT_FILENO, &tmp, 1);
445         return 0;
446 }
447
448 static void
449 printcolor(Colors c)
450 {
451         char *ansiseq;
452
453         if (colors[c].bold)
454                 tputs(enter_bold, 1, putch);
455
456         if (colors[c].num[0] != -1) {
457                 ansiseq = tgoto(ansi_fgcol, 0, colors[c].num[0]);
458                 if (ansiseq)
459                         tputs(ansiseq, 1, putch);
460         }
461         if (colors[c].num[1] != -1) {
462                 ansiseq = tgoto(ansi_bgcol, 0, colors[c].num[1]);
463                 if (ansiseq)
464                         tputs(ansiseq, 1, putch);
465         }
466 }
467
468 static void
469 endcolor(int sig)
470 {
471         tputs(ansi_coloff, 1, sig ? writech : putch);
472         tputs(attrs_off, 1, sig ? writech : putch);
473 }
474
475 static int
476 colortype(mode_t mode)
477 {
478         switch (mode & S_IFMT) {
479         case S_IFDIR:
480                 if (mode & S_IWOTH)
481                         if (mode & S_ISTXT)
482                                 printcolor(C_WSDIR);
483                         else
484                                 printcolor(C_WDIR);
485                 else
486                         printcolor(C_DIR);
487                 return (1);
488         case S_IFLNK:
489                 printcolor(C_LNK);
490                 return (1);
491         case S_IFSOCK:
492                 printcolor(C_SOCK);
493                 return (1);
494         case S_IFIFO:
495                 printcolor(C_FIFO);
496                 return (1);
497         case S_IFBLK:
498                 printcolor(C_BLK);
499                 return (1);
500         case S_IFCHR:
501                 printcolor(C_CHR);
502                 return (1);
503         }
504         if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
505                 if (mode & S_ISUID)
506                         printcolor(C_SUID);
507                 else if (mode & S_ISGID)
508                         printcolor(C_SGID);
509                 else
510                         printcolor(C_EXEC);
511                 return (1);
512         }
513         return (0);
514 }
515
516 void
517 parsecolors(const char *cs)
518 {
519         int i;
520         int j;
521         int len;
522         char c[2];
523         short legacy_warn = 0;
524
525         if (cs == NULL)
526                 cs = "";        /* LSCOLORS not set */
527         len = strlen(cs);
528         for (i = 0; i < C_NUMCOLORS; i++) {
529                 colors[i].bold = 0;
530
531                 if (len <= 2 * i) {
532                         c[0] = defcolors[2 * i];
533                         c[1] = defcolors[2 * i + 1];
534                 } else {
535                         c[0] = cs[2 * i];
536                         c[1] = cs[2 * i + 1];
537                 }
538                 for (j = 0; j < 2; j++) {
539                         /* Legacy colours used 0-7 */
540                         if (c[j] >= '0' && c[j] <= '7') {
541                                 colors[i].num[j] = c[j] - '0';
542                                 if (!legacy_warn) {
543                                         fprintf(stderr,
544                                             "warn: LSCOLORS should use "
545                                             "characters a-h instead of 0-9 ("
546                                             "see the manual page)\n");
547                                 }
548                                 legacy_warn = 1;
549                         } else if (c[j] >= 'a' && c[j] <= 'h')
550                                 colors[i].num[j] = c[j] - 'a';
551                         else if (c[j] >= 'A' && c[j] <= 'H') {
552                                 colors[i].num[j] = c[j] - 'A';
553                                 colors[i].bold = 1;
554                         } else if (tolower((unsigned char)c[j] == 'x'))
555                                 colors[i].num[j] = -1;
556                         else {
557                                 fprintf(stderr,
558                                     "error: invalid character '%c' in LSCOLORS"
559                                     " env var\n", c[j]);
560                                 colors[i].num[j] = -1;
561                         }
562                 }
563         }
564 }
565
566 void
567 colorquit(int sig)
568 {
569         endcolor(sig);
570
571         signal(sig, SIG_DFL);
572         kill(getpid(), sig);
573 }
574
575 #endif /* COLORLS */
576
577 static void
578 printlink(FTSENT *p)
579 {
580         int lnklen;
581         char name[MAXPATHLEN + 1];
582         char path[MAXPATHLEN + 1];
583
584         if (p->fts_level == FTS_ROOTLEVEL)
585                 snprintf(name, sizeof(name), "%s", p->fts_name);
586         else
587                 snprintf(name, sizeof(name),
588                     "%s/%s", p->fts_parent->fts_accpath, p->fts_name);
589         if ((lnklen = readlink(name, path, sizeof(path) - 1)) == -1) {
590                 fprintf(stderr, "\nls: %s: %s\n", name, strerror(errno));
591                 return;
592         }
593         path[lnklen] = '\0';
594         printf(" -> ");
595         printname(path);
596 }
597
598 static void
599 printsize(size_t width, off_t bytes)
600 {
601         unit_t unit;
602
603         if (f_humanval) {
604                 unit = unit_adjust(&bytes);
605
606                 if (bytes == 0)
607                         printf("%*s ", width, "0B");
608                 else
609                         printf("%*lld%c ", width - 1, bytes,
610                             "BKMGTPE"[unit]);
611         } else
612                 printf("%*lld ", width, bytes);
613 }
614
615 /*
616  * Output in "human-readable" format.  Uses 3 digits max and puts
617  * unit suffixes at the end.  Makes output compact and easy to read,
618  * especially on huge disks.
619  *
620  */
621 static unit_t
622 unit_adjust(off_t *val)
623 {
624         double abval;
625         unit_t unit;
626         unsigned int unit_sz;
627
628         abval = fabs((double)*val);
629
630         unit_sz = abval ? ilogb(abval) / 10 : 0;
631
632         if (unit_sz >= UNIT_MAX) {
633                 unit = NONE;
634         } else {
635                 unit = unitp[unit_sz];
636                 *val /= (double)vals_base2[unit_sz];
637         }
638
639         return (unit);
640 }