]> git.saurik.com Git - apple/file_cmds.git/blob - ls/print.c
d13715695b282396448c0b60ce9ae9cf5fb446d9
[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 #ifdef __APPLE__
48 #include <sys/acl.h>
49 #include <sys/xattr.h>
50 #include <sys/types.h>
51 #include <grp.h>
52 #include <pwd.h>
53 #include <TargetConditionals.h>
54 #if !TARGET_OS_EMBEDDED
55 #include <membership.h>
56 #include <membershipPriv.h>
57 #endif
58 #include <uuid/uuid.h>
59 #endif
60
61 #include <err.h>
62 #include <errno.h>
63 #include <fts.h>
64 #include <math.h>
65 #include <langinfo.h>
66 #include <libutil.h>
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <string.h>
70 #include <time.h>
71 #include <unistd.h>
72 #ifdef COLORLS
73 #include <ctype.h>
74 #include <termcap.h>
75 #include <signal.h>
76 #endif
77 #include <stdint.h> /* intmax_t */
78 #include <assert.h>
79 #ifdef __APPLE__
80 #include <get_compat.h>
81 #else
82 #define COMPAT_MODE(a,b) (1)
83 #endif /* __APPLE__ */
84
85 #include "ls.h"
86 #include "extern.h"
87
88 static int printaname(FTSENT *, u_long, u_long);
89 static void printlink(FTSENT *);
90 static void printtime(time_t);
91 static int printtype(u_int);
92 static void printsize(size_t, off_t);
93 #ifdef COLORLS
94 static void endcolor(int);
95 static int colortype(mode_t);
96 #endif
97
98 #define IS_NOPRINT(p) ((p)->fts_number == NO_PRINT)
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 assert(dp);
134 if (COMPAT_MODE("bin/ls", "Unix2003") && (dp->list != NULL)) {
135 if (dp->list->fts_level != FTS_ROOTLEVEL && (f_longform || f_size))
136 (void)printf("total %qu\n", (u_int64_t)howmany(dp->btotal, blocksize));
137 }
138
139 for (p = dp->list; p; p = p->fts_link) {
140 if (IS_NOPRINT(p))
141 continue;
142 (void)printaname(p, dp->s_inode, dp->s_block);
143 (void)putchar('\n');
144 }
145 }
146
147 /*
148 * print name in current style
149 */
150 static int
151 printname(const char *name)
152 {
153 if (f_octal || f_octal_escape)
154 return prn_octal(name);
155 else if (f_nonprint)
156 return prn_printable(name);
157 else
158 return prn_normal(name);
159 }
160
161 /*
162 * print access control list
163 */
164 static struct {
165 acl_perm_t perm;
166 char *name;
167 int flags;
168 #define ACL_PERM_DIR (1<<0)
169 #define ACL_PERM_FILE (1<<1)
170 } acl_perms[] = {
171 {ACL_READ_DATA, "read", ACL_PERM_FILE},
172 {ACL_LIST_DIRECTORY, "list", ACL_PERM_DIR},
173 {ACL_WRITE_DATA, "write", ACL_PERM_FILE},
174 {ACL_ADD_FILE, "add_file", ACL_PERM_DIR},
175 {ACL_EXECUTE, "execute", ACL_PERM_FILE},
176 {ACL_SEARCH, "search", ACL_PERM_DIR},
177 {ACL_DELETE, "delete", ACL_PERM_FILE | ACL_PERM_DIR},
178 {ACL_APPEND_DATA, "append", ACL_PERM_FILE},
179 {ACL_ADD_SUBDIRECTORY, "add_subdirectory", ACL_PERM_DIR},
180 {ACL_DELETE_CHILD, "delete_child", ACL_PERM_DIR},
181 {ACL_READ_ATTRIBUTES, "readattr", ACL_PERM_FILE | ACL_PERM_DIR},
182 {ACL_WRITE_ATTRIBUTES, "writeattr", ACL_PERM_FILE | ACL_PERM_DIR},
183 {ACL_READ_EXTATTRIBUTES, "readextattr", ACL_PERM_FILE | ACL_PERM_DIR},
184 {ACL_WRITE_EXTATTRIBUTES, "writeextattr", ACL_PERM_FILE | ACL_PERM_DIR},
185 {ACL_READ_SECURITY, "readsecurity", ACL_PERM_FILE | ACL_PERM_DIR},
186 {ACL_WRITE_SECURITY, "writesecurity", ACL_PERM_FILE | ACL_PERM_DIR},
187 {ACL_CHANGE_OWNER, "chown", ACL_PERM_FILE | ACL_PERM_DIR},
188 {0, NULL, 0}
189 };
190
191 static struct {
192 acl_flag_t flag;
193 char *name;
194 int flags;
195 } acl_flags[] = {
196 {ACL_ENTRY_FILE_INHERIT, "file_inherit", ACL_PERM_DIR},
197 {ACL_ENTRY_DIRECTORY_INHERIT, "directory_inherit", ACL_PERM_DIR},
198 {ACL_ENTRY_LIMIT_INHERIT, "limit_inherit", ACL_PERM_FILE | ACL_PERM_DIR},
199 {ACL_ENTRY_ONLY_INHERIT, "only_inherit", ACL_PERM_DIR},
200 {0, NULL, 0}
201 };
202
203 static char *
204 uuid_to_name(uuid_t *uu)
205 {
206 #if TARGET_OS_EMBEDDED
207 return strdup("<UNKNOWN>");
208 #else /* !TARGET_OS_EMBEDDED */
209 int is_gid = -1;
210 struct group *tgrp = NULL;
211 struct passwd *tpass = NULL;
212 char *name = NULL;
213 uid_t id;
214
215
216 #define MAXNAMETAG (MAXLOGNAME + 6) /* + strlen("group:") */
217 name = (char *) malloc(MAXNAMETAG);
218
219 if (NULL == name)
220 err(1, "malloc");
221
222 if (!f_numericonly) {
223 if (0 != mbr_uuid_to_id(*uu, &id, &is_gid))
224 goto errout;
225 }
226
227 switch (is_gid) {
228 case ID_TYPE_UID:
229 tpass = getpwuid(id);
230 if (!tpass) {
231 goto errout;
232 }
233 snprintf(name, MAXNAMETAG, "%s:%s", "user", tpass->pw_name);
234 break;
235 case ID_TYPE_GID:
236 tgrp = getgrgid((gid_t) id);
237 if (!tgrp) {
238 goto errout;
239 }
240 snprintf(name, MAXNAMETAG, "%s:%s", "group", tgrp->gr_name);
241 break;
242 default:
243 goto errout;
244 }
245 return name;
246 errout:
247 uuid_unparse_upper(*uu, name);
248 return name;
249 #endif /* !TARGET_OS_EMBEDDED */
250 }
251
252 static void
253 printxattr(DISPLAY *dp, int count, char *buf, int sizes[])
254 {
255 for (int i = 0; i < count; i++) {
256 putchar('\t');
257 printname(buf);
258 putchar('\t');
259 printsize(dp->s_size, sizes[i]);
260 putchar('\n');
261 buf += strlen(buf) + 1;
262 }
263 }
264
265 static void
266 printacl(acl_t acl, int isdir)
267 {
268 acl_entry_t entry = NULL;
269 int index;
270 uuid_t *applicable;
271 char *name = NULL;
272 acl_tag_t tag;
273 acl_flagset_t flags;
274 acl_permset_t perms;
275 char *type;
276 int i, first;
277
278
279 for (index = 0;
280 acl_get_entry(acl, entry == NULL ? ACL_FIRST_ENTRY : ACL_NEXT_ENTRY, &entry) == 0;
281 index++) {
282 if (acl_get_tag_type(entry, &tag) != 0)
283 continue;
284 if (acl_get_flagset_np(entry, &flags) != 0)
285 continue;
286 if (acl_get_permset(entry, &perms) != 0)
287 continue;
288 if ((applicable = (uuid_t *) acl_get_qualifier(entry)) == NULL)
289 continue;
290 name = uuid_to_name(applicable);
291 acl_free(applicable);
292 switch(tag) {
293 case ACL_EXTENDED_ALLOW:
294 type = "allow";
295 break;
296 case ACL_EXTENDED_DENY:
297 type = "deny";
298 break;
299 default:
300 type = "unknown";
301 }
302
303 (void)printf(" %d: %s%s %s ",
304 index,
305 name,
306 acl_get_flag_np(flags, ACL_ENTRY_INHERITED) ? " inherited" : "",
307 type);
308
309 if (name)
310 free(name);
311
312 for (i = 0, first = 0; acl_perms[i].name != NULL; i++) {
313 if (acl_get_perm_np(perms, acl_perms[i].perm) == 0)
314 continue;
315 if (!(acl_perms[i].flags & (isdir ? ACL_PERM_DIR : ACL_PERM_FILE)))
316 continue;
317 (void)printf("%s%s", first++ ? "," : "", acl_perms[i].name);
318 }
319 for (i = 0; acl_flags[i].name != NULL; i++) {
320 if (acl_get_flag_np(flags, acl_flags[i].flag) == 0)
321 continue;
322 if (!(acl_flags[i].flags & (isdir ? ACL_PERM_DIR : ACL_PERM_FILE)))
323 continue;
324 (void)printf("%s%s", first++ ? "," : "", acl_flags[i].name);
325 }
326
327 (void)putchar('\n');
328 }
329
330 }
331
332 void
333 printlong(DISPLAY *dp)
334 {
335 struct stat *sp;
336 FTSENT *p;
337 NAMES *np;
338 char buf[20];
339 #ifdef COLORLS
340 int color_printed = 0;
341 #endif
342
343 if (dp->list->fts_level != FTS_ROOTLEVEL && (f_longform || f_size))
344 (void)printf("total %qu\n", (u_int64_t)howmany(dp->btotal, blocksize));
345
346 for (p = dp->list; p; p = p->fts_link) {
347 if (IS_NOPRINT(p))
348 continue;
349 sp = p->fts_statp;
350 if (f_inode)
351 #if _DARWIN_FEATURE_64_BIT_INODE
352 (void)printf("%*llu ", dp->s_inode, (u_quad_t)sp->st_ino);
353 #else
354 (void)printf("%*lu ", dp->s_inode, (u_long)sp->st_ino);
355 #endif
356 if (f_size)
357 (void)printf("%*qu ",
358 dp->s_block, (u_int64_t)howmany(sp->st_blocks, blocksize));
359 strmode(sp->st_mode, buf);
360 np = p->fts_pointer;
361 #ifdef __APPLE__
362 buf[10] = '\0'; /* make +/@ abut the mode */
363 char str[2] = { np->mode_suffix, '\0' };
364 #endif /* __APPLE__ */
365 if (f_group && f_owner) { /* means print neither */
366 #ifdef __APPLE__
367 (void)printf("%s%s %*u ", buf, str, dp->s_nlink,
368 sp->st_nlink);
369 #else /* ! __APPLE__ */
370 (void)printf("%s %*u ", buf, dp->s_nlink,
371 sp->st_nlink);
372 #endif /* __APPLE__ */
373 }
374 else if (f_group) {
375 #ifdef __APPLE__
376 (void)printf("%s%s %*u %-*s ", buf, str, dp->s_nlink,
377 sp->st_nlink, dp->s_group, np->group);
378 #else /* ! __APPLE__ */
379 (void)printf("%s %*u %-*s ", buf, dp->s_nlink,
380 sp->st_nlink, dp->s_group, np->group);
381 #endif /* __APPLE__ */
382 }
383 else if (f_owner) {
384 #ifdef __APPLE__
385 (void)printf("%s%s %*u %-*s ", buf, str, dp->s_nlink,
386 sp->st_nlink, dp->s_user, np->user);
387 #else /* ! __APPLE__ */
388 (void)printf("%s %*u %-*s ", buf, dp->s_nlink,
389 sp->st_nlink, dp->s_user, np->user);
390 #endif /* __APPLE__ */
391 }
392 else {
393 #ifdef __APPLE__
394 (void)printf("%s%s %*u %-*s %-*s ", buf, str, dp->s_nlink,
395 sp->st_nlink, dp->s_user, np->user, dp->s_group,
396 np->group);
397 #else /* ! __APPLE__ */
398 (void)printf("%s %*u %-*s %-*s ", buf, dp->s_nlink,
399 sp->st_nlink, dp->s_user, np->user, dp->s_group,
400 np->group);
401 #endif /* ! __APPLE__ */
402 }
403 if (f_flags)
404 (void)printf("%-*s ", dp->s_flags, np->flags);
405 if (S_ISCHR(sp->st_mode) || S_ISBLK(sp->st_mode))
406 if (minor(sp->st_rdev) > 255 || minor(sp->st_rdev) < 0)
407 (void)printf("%3d, 0x%08x ",
408 major(sp->st_rdev),
409 (u_int)minor(sp->st_rdev));
410 else
411 (void)printf("%3d, %3d ",
412 major(sp->st_rdev), minor(sp->st_rdev));
413 else if (dp->bcfile)
414 (void)printf("%*s%*qu ",
415 8 - dp->s_size, "", dp->s_size, (u_int64_t)sp->st_size);
416 else
417 printsize(dp->s_size, sp->st_size);
418 if (f_accesstime)
419 printtime(sp->st_atime);
420 else if (f_statustime)
421 printtime(sp->st_ctime);
422 else if (f_birthtime)
423 printtime(sp->st_birthtime);
424 else
425 printtime(sp->st_mtime);
426 #ifdef COLORLS
427 if (f_color)
428 color_printed = colortype(sp->st_mode);
429 #endif
430 (void)printname(p->fts_name);
431 #ifdef COLORLS
432 if (f_color && color_printed)
433 endcolor(0);
434 #endif
435 if (f_type)
436 (void)printtype(sp->st_mode);
437 if (S_ISLNK(sp->st_mode))
438 printlink(p);
439 (void)putchar('\n');
440 #ifdef __APPLE__
441 if (np->xattr_count && f_xattr) {
442 printxattr(dp, np->xattr_count, np->xattr_names, np->xattr_sizes);
443 }
444 if (np->acl != NULL && f_acl) {
445 printacl(np->acl, S_ISDIR(sp->st_mode));
446 }
447 #endif /* __APPLE__ */
448 }
449 }
450
451 void
452 printstream(DISPLAY *dp)
453 {
454 FTSENT *p;
455 extern int termwidth;
456 int chcnt;
457
458 for (p = dp->list, chcnt = 0; p; p = p->fts_link) {
459 if (p->fts_number == NO_PRINT)
460 continue;
461 if (strlen(p->fts_name) + chcnt +
462 (p->fts_link ? 2 : 0) >= (unsigned)termwidth) {
463 putchar('\n');
464 chcnt = 0;
465 }
466 chcnt += printaname(p, dp->s_inode, dp->s_block);
467 if (p->fts_link) {
468 printf(", ");
469 chcnt += 2;
470 }
471 }
472 if (chcnt)
473 putchar('\n');
474 }
475
476 void
477 printcol(DISPLAY *dp)
478 {
479 extern int termwidth;
480 static FTSENT **array;
481 static int lastentries = -1;
482 FTSENT *p;
483 int base;
484 int chcnt;
485 int cnt;
486 int col;
487 int colwidth;
488 int endcol;
489 int num;
490 int numcols;
491 int numrows;
492 int row;
493 int tabwidth;
494
495 if (f_notabs)
496 tabwidth = 1;
497 else
498 tabwidth = 8;
499
500 /*
501 * Have to do random access in the linked list -- build a table
502 * of pointers.
503 */
504 if ((lastentries == -1) || (dp->entries > lastentries)) {
505 lastentries = dp->entries;
506 if ((array = realloc(array, dp->entries * sizeof(FTSENT *))) == NULL) {
507 warn(NULL);
508 printscol(dp);
509 return;
510 }
511 }
512 memset(array, 0, dp->entries * sizeof(FTSENT *));
513 for (p = dp->list, num = 0; p; p = p->fts_link)
514 if (p->fts_number != NO_PRINT)
515 array[num++] = p;
516
517 colwidth = dp->maxlen;
518 if (f_inode)
519 colwidth += dp->s_inode + 1;
520 if (f_size)
521 colwidth += dp->s_block + 1;
522 if (f_type)
523 colwidth += 1;
524
525 colwidth = (colwidth + tabwidth) & ~(tabwidth - 1);
526 if (termwidth < 2 * colwidth) {
527 printscol(dp);
528 return;
529 }
530 numcols = termwidth / colwidth;
531 numrows = num / numcols;
532 if (num % numcols)
533 ++numrows;
534
535 assert(dp->list);
536 if (dp->list->fts_level != FTS_ROOTLEVEL && (f_longform || f_size))
537 (void)printf("total %qu\n", (u_int64_t)howmany(dp->btotal, blocksize));
538
539 base = 0;
540 for (row = 0; row < numrows; ++row) {
541 endcol = colwidth;
542 if (!f_sortacross)
543 base = row;
544 for (col = 0, chcnt = 0; col < numcols; ++col) {
545 assert(base < dp->entries);
546 chcnt += printaname(array[base], dp->s_inode, dp->s_block);
547 if (f_sortacross)
548 base++;
549 else
550 base += numrows;
551 if (base >= num)
552 break;
553 while ((cnt = ((chcnt + tabwidth) & ~(tabwidth - 1)))
554 <= endcol) {
555 if (f_sortacross && col + 1 >= numcols)
556 break;
557 (void)putchar(f_notabs ? ' ' : '\t');
558 chcnt = cnt;
559 }
560 endcol += colwidth;
561 }
562 (void)putchar('\n');
563 }
564 }
565
566 /*
567 * print [inode] [size] name
568 * return # of characters printed, no trailing characters.
569 */
570 static int
571 printaname(FTSENT *p, u_long inodefield, u_long sizefield)
572 {
573 struct stat *sp;
574 int chcnt;
575 #ifdef COLORLS
576 int color_printed = 0;
577 #endif
578
579 sp = p->fts_statp;
580 chcnt = 0;
581 if (f_inode)
582 #if _DARWIN_FEATURE_64_BIT_INODE
583 chcnt += printf("%*llu ", (int)inodefield, (u_quad_t)sp->st_ino);
584 #else
585 chcnt += printf("%*lu ", (int)inodefield, (u_long)sp->st_ino);
586 #endif
587 if (f_size)
588 chcnt += printf("%*qu ",
589 (int)sizefield, (u_int64_t)howmany(sp->st_blocks, blocksize));
590 #ifdef COLORLS
591 if (f_color)
592 color_printed = colortype(sp->st_mode);
593 #endif
594 chcnt += printname(p->fts_name);
595 #ifdef COLORLS
596 if (f_color && color_printed)
597 endcolor(0);
598 #endif
599 if (f_type)
600 chcnt += printtype(sp->st_mode);
601 return (chcnt);
602 }
603
604 static void
605 printtime(time_t ftime)
606 {
607 char longstring[80];
608 static time_t now;
609 const char *format;
610 static int d_first = -1;
611
612 if (d_first < 0)
613 d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
614 if (now == 0)
615 now = time(NULL);
616
617 #define SIXMONTHS ((365 / 2) * 86400)
618 if (f_sectime)
619 /* mmm dd hh:mm:ss yyyy || dd mmm hh:mm:ss yyyy */
620 format = d_first ? "%e %b %T %Y " : "%b %e %T %Y ";
621 else if (COMPAT_MODE("bin/ls", "Unix2003")) {
622 if (ftime + SIXMONTHS > now && ftime <= now)
623 /* mmm dd hh:mm || dd mmm hh:mm */
624 format = d_first ? "%e %b %R " : "%b %e %R ";
625 else
626 /* mmm dd yyyy || dd mmm yyyy */
627 format = d_first ? "%e %b %Y " : "%b %e %Y ";
628 }
629 else if (ftime + SIXMONTHS > now && ftime < now + SIXMONTHS)
630 /* mmm dd hh:mm || dd mmm hh:mm */
631 format = d_first ? "%e %b %R " : "%b %e %R ";
632 else
633 /* mmm dd yyyy || dd mmm yyyy */
634 format = d_first ? "%e %b %Y " : "%b %e %Y ";
635 strftime(longstring, sizeof(longstring), format, localtime(&ftime));
636 fputs(longstring, stdout);
637 }
638
639 static int
640 printtype(u_int mode)
641 {
642
643 if (f_slash) {
644 if ((mode & S_IFMT) == S_IFDIR) {
645 (void)putchar('/');
646 return (1);
647 }
648 return (0);
649 }
650
651 switch (mode & S_IFMT) {
652 case S_IFDIR:
653 (void)putchar('/');
654 return (1);
655 case S_IFIFO:
656 (void)putchar('|');
657 return (1);
658 case S_IFLNK:
659 (void)putchar('@');
660 return (1);
661 case S_IFSOCK:
662 (void)putchar('=');
663 return (1);
664 case S_IFWHT:
665 (void)putchar('%');
666 return (1);
667 default:
668 break;
669 }
670 if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
671 (void)putchar('*');
672 return (1);
673 }
674 return (0);
675 }
676
677 #ifdef COLORLS
678 static int
679 putch(int c)
680 {
681 (void)putchar(c);
682 return 0;
683 }
684
685 static int
686 writech(int c)
687 {
688 char tmp = c;
689
690 (void)write(STDOUT_FILENO, &tmp, 1);
691 return 0;
692 }
693
694 static void
695 printcolor(Colors c)
696 {
697 char *ansiseq;
698
699 if (colors[c].bold)
700 tputs(enter_bold, 1, putch);
701
702 if (colors[c].num[0] != -1) {
703 ansiseq = tgoto(ansi_fgcol, 0, colors[c].num[0]);
704 if (ansiseq)
705 tputs(ansiseq, 1, putch);
706 }
707 if (colors[c].num[1] != -1) {
708 ansiseq = tgoto(ansi_bgcol, 0, colors[c].num[1]);
709 if (ansiseq)
710 tputs(ansiseq, 1, putch);
711 }
712 }
713
714 static void
715 endcolor(int sig)
716 {
717 tputs(ansi_coloff, 1, sig ? writech : putch);
718 tputs(attrs_off, 1, sig ? writech : putch);
719 }
720
721 static int
722 colortype(mode_t mode)
723 {
724 switch (mode & S_IFMT) {
725 case S_IFDIR:
726 if (mode & S_IWOTH)
727 if (mode & S_ISTXT)
728 printcolor(C_WSDIR);
729 else
730 printcolor(C_WDIR);
731 else
732 printcolor(C_DIR);
733 return (1);
734 case S_IFLNK:
735 printcolor(C_LNK);
736 return (1);
737 case S_IFSOCK:
738 printcolor(C_SOCK);
739 return (1);
740 case S_IFIFO:
741 printcolor(C_FIFO);
742 return (1);
743 case S_IFBLK:
744 printcolor(C_BLK);
745 return (1);
746 case S_IFCHR:
747 printcolor(C_CHR);
748 return (1);
749 }
750 if (mode & (S_IXUSR | S_IXGRP | S_IXOTH)) {
751 if (mode & S_ISUID)
752 printcolor(C_SUID);
753 else if (mode & S_ISGID)
754 printcolor(C_SGID);
755 else
756 printcolor(C_EXEC);
757 return (1);
758 }
759 return (0);
760 }
761
762 void
763 parsecolors(const char *cs)
764 {
765 int i;
766 int j;
767 int len;
768 char c[2];
769 short legacy_warn = 0;
770
771 if (cs == NULL)
772 cs = ""; /* LSCOLORS not set */
773 len = strlen(cs);
774 for (i = 0; i < C_NUMCOLORS; i++) {
775 colors[i].bold = 0;
776
777 if (len <= 2 * i) {
778 c[0] = defcolors[2 * i];
779 c[1] = defcolors[2 * i + 1];
780 } else {
781 c[0] = cs[2 * i];
782 c[1] = cs[2 * i + 1];
783 }
784 for (j = 0; j < 2; j++) {
785 /* Legacy colours used 0-7 */
786 if (c[j] >= '0' && c[j] <= '7') {
787 colors[i].num[j] = c[j] - '0';
788 if (!legacy_warn) {
789 fprintf(stderr,
790 "warn: LSCOLORS should use "
791 "characters a-h instead of 0-9 ("
792 "see the manual page)\n");
793 }
794 legacy_warn = 1;
795 } else if (c[j] >= 'a' && c[j] <= 'h')
796 colors[i].num[j] = c[j] - 'a';
797 else if (c[j] >= 'A' && c[j] <= 'H') {
798 colors[i].num[j] = c[j] - 'A';
799 colors[i].bold = 1;
800 } else if (tolower((unsigned char)c[j] == 'x'))
801 colors[i].num[j] = -1;
802 else {
803 fprintf(stderr,
804 "error: invalid character '%c' in LSCOLORS"
805 " env var\n", c[j]);
806 colors[i].num[j] = -1;
807 }
808 }
809 }
810 }
811
812 void
813 colorquit(int sig)
814 {
815 endcolor(sig);
816
817 (void)signal(sig, SIG_DFL);
818 (void)kill(getpid(), sig);
819 }
820
821 #endif /* COLORLS */
822
823 static void
824 printlink(FTSENT *p)
825 {
826 int lnklen;
827 char name[MAXPATHLEN + 1];
828 char path[MAXPATHLEN + 1];
829
830 if (p->fts_level == FTS_ROOTLEVEL)
831 (void)snprintf(name, sizeof(name), "%s", p->fts_name);
832 else
833 (void)snprintf(name, sizeof(name),
834 "%s/%s", p->fts_parent->fts_accpath, p->fts_name);
835 if ((lnklen = readlink(name, path, sizeof(path) - 1)) == -1) {
836 (void)fprintf(stderr, "\nls: %s: %s\n", name, strerror(errno));
837 return;
838 }
839 path[lnklen] = '\0';
840 (void)printf(" -> ");
841 (void)printname(path);
842 }
843
844 static void
845 printsize(size_t width, off_t bytes)
846 {
847
848 if (f_humanval) {
849 char buf[5];
850
851 humanize_number(buf, sizeof(buf), (int64_t)bytes, "",
852 HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
853 (void)printf("%5s ", buf);
854 } else
855 (void)printf("%*jd ", (u_int)width, (intmax_t)bytes);
856 }