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