ls(1): Alter time portion of "long format"
[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  * 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.
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  */
35
36 #include <sys/param.h>
37 #include <sys/stat.h>
38
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 #ifdef COLORLS
50 #include <ctype.h>
51 #include <termcap.h>
52 #include <signal.h>
53 #endif
54
55 #include "ls.h"
56 #include "extern.h"
57
58 static int      printaname(const FTSENT *, u_long, u_long);
59 static void     printlink(const FTSENT *);
60 static void     printtime(time_t);
61 static int      printtype(u_int);
62 static void     printsize(size_t, off_t);
63 #ifdef COLORLS
64 static void     endcolor(int);
65 static int      colortype(mode_t);
66 #endif
67
68 #define IS_NOPRINT(p)   ((p)->fts_number == NO_PRINT)
69
70 #ifdef COLORLS
71 /* Most of these are taken from <sys/stat.h> */
72 typedef enum Colors {
73         C_DIR,                  /* directory */
74         C_LNK,                  /* symbolic link */
75         C_SOCK,                 /* socket */
76         C_FIFO,                 /* pipe */
77         C_EXEC,                 /* executable */
78         C_BLK,                  /* block special */
79         C_CHR,                  /* character special */
80         C_SUID,                 /* setuid executable */
81         C_SGID,                 /* setgid executable */
82         C_WSDIR,                /* directory writeble to others, with sticky
83                                  * bit */
84         C_WDIR,                 /* directory writeble to others, without
85                                  * sticky bit */
86         C_NUMCOLORS             /* just a place-holder */
87 } Colors;
88
89 static const char *defcolors = "exfxcxdxbxegedabagacad";
90
91 /* colors for file types */
92 static struct {
93         int     num[2];
94         int     bold;
95 } colors[C_NUMCOLORS];
96 #endif
97
98 void
99 printscol(const DISPLAY *dp)
100 {
101         FTSENT *p;
102
103         for (p = dp->list; p; p = p->fts_link) {
104                 if (IS_NOPRINT(p))
105                         continue;
106                 printaname(p, dp->s_inode, dp->s_block);
107                 putchar('\n');
108         }
109 }
110
111 /*
112  * print name in current style
113  */
114 int
115 printname(const char *name)
116 {
117         if (f_octal || f_octal_escape)
118                 return prn_octal(name);
119         else if (f_nonprint)
120                 return prn_printable(name);
121         else
122                 return prn_normal(name);
123 }
124
125 void
126 printlong(const DISPLAY *dp)
127 {
128         struct stat *sp;
129         FTSENT *p;
130         NAMES *np;
131         char buf[20];
132 #ifdef COLORLS
133         int color_printed = 0;
134 #endif
135
136         if ((dp->list == NULL || dp->list->fts_level != FTS_ROOTLEVEL) &&
137             (f_longform || f_size)) {
138                 printf("total %lu\n", howmany(dp->btotal, blocksize));
139         }
140
141         for (p = dp->list; p; p = p->fts_link) {
142                 if (IS_NOPRINT(p))
143                         continue;
144                 sp = p->fts_statp;
145                 if (f_inode)
146                         printf("%*ju ", dp->s_inode, (uintmax_t)sp->st_ino);
147                 if (f_size)
148                         printf("%*jd ",
149                             dp->s_block, howmany(sp->st_blocks, blocksize));
150                 strmode(sp->st_mode, buf);
151                 np = p->fts_pointer;
152                 printf("%s %*u %-*s  %-*s  ", buf, dp->s_nlink,
153                     sp->st_nlink, dp->s_user, np->user, dp->s_group,
154                     np->group);
155                 if (f_fsmid)
156                         printf("%s ", np->fsmid);
157                 if (f_flags)
158                         printf("%-*s ", dp->s_flags, np->flags);
159                 if (S_ISCHR(sp->st_mode) || S_ISBLK(sp->st_mode))
160                         printf("%3d, 0x%08x ",
161                                major(sp->st_rdev), (u_int)minor(sp->st_rdev));
162                 else if (dp->bcfile)
163                         printf("%*s%*jd ",
164                             8 - dp->s_size, "", dp->s_size, (intmax_t)sp->st_size);
165                 else
166                         printsize(dp->s_size, sp->st_size);
167                 if (f_accesstime)
168                         printtime(sp->st_atime);
169                 else if (f_statustime)
170                         printtime(sp->st_ctime);
171                 else
172                         printtime(sp->st_mtime);
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');
187         }
188 }
189
190 void
191 printstream(const DISPLAY *dp)
192 {
193         FTSENT *p;
194         int chcnt;
195
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;
204                 }
205                 chcnt += printaname(p, dp->s_inode, dp->s_block);
206                 if (p->fts_link) {
207                         printf(", ");
208                         chcnt += 2;
209                 }
210         }
211         if (chcnt)
212                 putchar('\n');
213 }
214                 
215 void
216 printcol(const DISPLAY *dp)
217 {
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;
233
234         if (f_notabs)
235                 tabwidth = 1;
236         else
237                 tabwidth = 8;
238
239         /*
240          * Have to do random access in the linked list -- build a table
241          * of pointers.
242          */
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;
250                 }
251                 lastentries = dp->entries;
252                 array = narray;
253         }
254         for (p = dp->list, num = 0; p; p = p->fts_link)
255                 if (p->fts_number != NO_PRINT)
256                         array[num++] = p;
257
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;
265
266         colwidth = (colwidth + tabwidth) & ~(tabwidth - 1);
267         if (termwidth < 2 * colwidth) {
268                 printscol(dp);
269                 return;
270         }
271         numcols = termwidth / colwidth;
272         numrows = num / numcols;
273         if (num % numcols)
274                 ++numrows;
275
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));
279         }
280
281         /* counter if f_sortacross, else case-by-case */
282         base = 0;
283
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 = ((chcnt + tabwidth) & ~(tabwidth - 1)))
298                             <= endcol) {
299                                 if (f_sortacross && col + 1 >= numcols)
300                                         break;
301                                 putchar(f_notabs ? ' ' : '\t');
302                                 chcnt = cnt;
303                         }
304                         endcol += colwidth;
305                 }
306                 putchar('\n');
307         }
308 }
309
310 /*
311  * print [inode] [size] name
312  * return # of characters printed, no trailing characters.
313  */
314 static int
315 printaname(const FTSENT *p, u_long inodefield, u_long sizefield)
316 {
317         struct stat *sp;
318         int chcnt;
319 #ifdef COLORLS
320         int color_printed = 0;
321 #endif
322
323         sp = p->fts_statp;
324         chcnt = 0;
325         if (f_inode) {
326                 chcnt += printf("%*ju ", (int)inodefield,
327                                 (uintmax_t)sp->st_ino);
328         }
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);
344 }
345
346 static void
347 printtime(time_t ftime)
348 {
349         char longstring[80];
350         static time_t now;
351         const char *format;
352
353         if (now == 0)
354                 now = time(NULL);
355
356         if (f_sectime)
357                 /* ISO 8601 (extended without T): YYYY-DD-MM hh:mm:ss */
358                 format = "%F %T ";
359         else
360                 /* ISO 8601 (basic with T): YYYYDDMMThh */
361                 format = "%Y%m%dT%H ";
362         strftime(longstring, sizeof(longstring), format, localtime(&ftime));
363         fputs(longstring, stdout);
364 }
365
366 static int
367 printtype(u_int mode)
368 {
369
370         if (f_slash) {
371                 if ((mode & S_IFMT) == S_IFDIR) {
372                         putchar('/');
373                         return (1);
374                 }
375                 return (0);
376         }
377
378         switch (mode & S_IFMT) {
379         case S_IFDIR:
380                 putchar('/');
381                 return (1);
382         case S_IFIFO:
383                 putchar('|');
384                 return (1);
385         case S_IFLNK:
386                 putchar('@');
387                 return (1);
388         case S_IFSOCK:
389                 putchar('=');
390                 return (1);
391         case S_IFWHT:
392                 putchar('%');
393                 return (1);
394         default:
395                 break;
396         }
397         if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
398                 putchar('*');
399                 return (1);
400         }
401         return (0);
402 }
403
404 #ifdef COLORLS
405 static int
406 putch(int c)
407 {
408         putchar(c);
409         return 0;
410 }
411
412 static int
413 writech(int c)
414 {
415         char tmp = (char)c;
416
417         write(STDOUT_FILENO, &tmp, 1);
418         return 0;
419 }
420
421 static void
422 printcolor(Colors c)
423 {
424         char *ansiseq;
425
426         if (colors[c].bold)
427                 tputs(enter_bold, 1, putch);
428
429         if (colors[c].num[0] != -1) {
430                 ansiseq = tgoto(ansi_fgcol, 0, colors[c].num[0]);
431                 if (ansiseq)
432                         tputs(ansiseq, 1, putch);
433         }
434         if (colors[c].num[1] != -1) {
435                 ansiseq = tgoto(ansi_bgcol, 0, colors[c].num[1]);
436                 if (ansiseq)
437                         tputs(ansiseq, 1, putch);
438         }
439 }
440
441 static void
442 endcolor(int sig)
443 {
444         tputs(ansi_coloff, 1, sig ? writech : putch);
445         tputs(attrs_off, 1, sig ? writech : putch);
446 }
447
448 static int
449 colortype(mode_t mode)
450 {
451         switch (mode & S_IFMT) {
452         case S_IFDIR:
453                 if (mode & S_IWOTH)
454                         if (mode & S_ISTXT)
455                                 printcolor(C_WSDIR);
456                         else
457                                 printcolor(C_WDIR);
458                 else
459                         printcolor(C_DIR);
460                 return (1);
461         case S_IFLNK:
462                 printcolor(C_LNK);
463                 return (1);
464         case S_IFSOCK:
465                 printcolor(C_SOCK);
466                 return (1);
467         case S_IFIFO:
468                 printcolor(C_FIFO);
469                 return (1);
470         case S_IFBLK:
471                 printcolor(C_BLK);
472                 return (1);
473         case S_IFCHR:
474                 printcolor(C_CHR);
475                 return (1);
476         default:;
477         }
478         if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
479                 if (mode & S_ISUID)
480                         printcolor(C_SUID);
481                 else if (mode & S_ISGID)
482                         printcolor(C_SGID);
483                 else
484                         printcolor(C_EXEC);
485                 return (1);
486         }
487         return (0);
488 }
489
490 void
491 parsecolors(const char *cs)
492 {
493         int i;
494         int j;
495         size_t len;
496         char c[2];
497         short legacy_warn = 0;
498
499         if (cs == NULL)
500                 cs = "";        /* LSCOLORS not set */
501         len = strlen(cs);
502         for (i = 0; i < C_NUMCOLORS; i++) {
503                 colors[i].bold = 0;
504
505                 if (len <= 2 * (size_t)i) {
506                         c[0] = defcolors[2 * i];
507                         c[1] = defcolors[2 * i + 1];
508                 } else {
509                         c[0] = cs[2 * i];
510                         c[1] = cs[2 * i + 1];
511                 }
512                 for (j = 0; j < 2; j++) {
513                         /* Legacy colours used 0-7 */
514                         if (c[j] >= '0' && c[j] <= '7') {
515                                 colors[i].num[j] = c[j] - '0';
516                                 if (!legacy_warn) {
517                                         warnx("LSCOLORS should use "
518                                               "characters a-h instead of 0-9 ("
519                                               "see the manual page)\n");
520                                 }
521                                 legacy_warn = 1;
522                         } else if (c[j] >= 'a' && c[j] <= 'h')
523                                 colors[i].num[j] = c[j] - 'a';
524                         else if (c[j] >= 'A' && c[j] <= 'H') {
525                                 colors[i].num[j] = c[j] - 'A';
526                                 colors[i].bold = 1;
527                         } else if (tolower((unsigned char)c[j] == 'x'))
528                                 colors[i].num[j] = -1;
529                         else {
530                                 warnx("invalid character '%c' in LSCOLORS"
531                                       " env var\n", c[j]);
532                                 colors[i].num[j] = -1;
533                         }
534                 }
535         }
536 }
537
538 void
539 colorquit(int sig)
540 {
541         endcolor(sig);
542
543         signal(sig, SIG_DFL);
544         kill(getpid(), sig);
545 }
546
547 #endif /* COLORLS */
548
549 static void
550 printlink(const FTSENT *p)
551 {
552         int lnklen;
553         char name[MAXPATHLEN + 1];
554         char path[MAXPATHLEN + 1];
555
556         if (p->fts_level == FTS_ROOTLEVEL)
557                 snprintf(name, sizeof(name), "%s", p->fts_name);
558         else
559                 snprintf(name, sizeof(name),
560                     "%s/%s", p->fts_parent->fts_accpath, p->fts_name);
561         if ((lnklen = readlink(name, path, sizeof(path) - 1)) == -1) {
562                 fprintf(stderr, "\nls: %s: %s\n", name, strerror(errno));
563                 return;
564         }
565         path[lnklen] = '\0';
566         printf(" -> ");
567         printname(path);
568 }
569
570 static void
571 printsize(size_t width, off_t bytes)
572 {
573         if (f_humanval) {
574                 char buf[5];
575
576                 humanize_number(buf, sizeof(buf), (int64_t)bytes, "",
577                                 HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
578                 printf("%5s ", buf);
579         } else
580                 printf("%*jd ", (int)width, (uintmax_t)bytes);
581 }