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