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