whitespace
[oweals/busybox.git] / coreutils / ls.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * tiny-ls.c version 0.1.0: A minimalist 'ls'
4  * Copyright (C) 1996 Brian Candler <B.Candler@pobox.com>
5  *
6  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
7  */
8
9 /*
10  * To achieve a small memory footprint, this version of 'ls' doesn't do any
11  * file sorting, and only has the most essential command line switches
12  * (i.e., the ones I couldn't live without :-) All features which involve
13  * linking in substantial chunks of libc can be disabled.
14  *
15  * Although I don't really want to add new features to this program to
16  * keep it small, I *am* interested to receive bug fixes and ways to make
17  * it more portable.
18  *
19  * KNOWN BUGS:
20  * 1. ls -l of a directory doesn't give "total <blocks>" header
21  * 2. ls of a symlink to a directory doesn't list directory contents
22  * 3. hidden files can make column width too large
23  *
24  * NON-OPTIMAL BEHAVIOUR:
25  * 1. autowidth reads directories twice
26  * 2. if you do a short directory listing without filetype characters
27  *    appended, there's no need to stat each one
28  * PORTABILITY:
29  * 1. requires lstat (BSD) - how do you do it without?
30  */
31
32 enum {
33         TERMINAL_WIDTH = 80,    /* use 79 if terminal has linefold bug */
34         COLUMN_GAP = 2,         /* includes the file type char */
35 };
36
37 /************************************************************************/
38
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <stdio.h>
42 #include <unistd.h>
43 #include <dirent.h>
44 #include <errno.h>
45 #include <stdio.h>
46 #include <string.h>
47 #include <stdlib.h>
48 #include <fcntl.h>
49 #include <signal.h>
50 #include <termios.h>
51 #include <getopt.h> /* struct option */
52 #include <sys/ioctl.h>
53 #include <sys/sysmacros.h>     /* major() and minor() */
54 #include "busybox.h"
55 #ifdef CONFIG_SELINUX
56 #include <selinux/selinux.h>   /* for is_selinux_enabled() */
57 #endif
58
59 #ifdef CONFIG_FEATURE_LS_TIMESTAMPS
60 #include <time.h>
61 #endif
62
63 /* what is the overall style of the listing */
64 #define STYLE_AUTO      (0)
65 #define STYLE_COLUMNS   (1U<<21)        /* fill columns */
66 #define STYLE_LONG      (2U<<21)        /* one record per line, extended info */
67 #define STYLE_SINGLE    (3U<<21)        /* one record per line */
68
69 #define STYLE_MASK                 STYLE_SINGLE
70 #define STYLE_ONE_RECORD_FLAG      STYLE_LONG
71
72 /* 51306 lrwxrwxrwx  1 root     root         2 May 11 01:43 /bin/view -> vi* */
73 /* what file information will be listed */
74 #define LIST_INO        (1U<<0)
75 #define LIST_BLOCKS     (1U<<1)
76 #define LIST_MODEBITS   (1U<<2)
77 #define LIST_NLINKS     (1U<<3)
78 #define LIST_ID_NAME    (1U<<4)
79 #define LIST_ID_NUMERIC (1U<<5)
80 #define LIST_CONTEXT    (1U<<6)
81 #define LIST_SIZE       (1U<<7)
82 #define LIST_DEV        (1U<<8)
83 #define LIST_DATE_TIME  (1U<<9)
84 #define LIST_FULLTIME   (1U<<10)
85 #define LIST_FILENAME   (1U<<11)
86 #define LIST_SYMLINK    (1U<<12)
87 #define LIST_FILETYPE   (1U<<13)
88 #define LIST_EXEC       (1U<<14)
89
90 #define LIST_MASK       ((LIST_EXEC << 1) - 1)
91
92 /* what files will be displayed */
93 /* TODO -- We may be able to make DISP_NORMAL 0 to save a bit slot. */
94 #define DISP_NORMAL     (1U<<14)        /* show normal filenames */
95 #define DISP_DIRNAME    (1U<<15)        /* 2 or more items? label directories */
96 #define DISP_HIDDEN     (1U<<16)        /* show filenames starting with .  */
97 #define DISP_DOT        (1U<<17)        /* show . and .. */
98 #define DISP_NOLIST     (1U<<18)        /* show directory as itself, not contents */
99 #define DISP_RECURSIVE  (1U<<19)        /* show directory and everything below it */
100 #define DISP_ROWS       (1U<<20)        /* print across rows */
101
102 #define DISP_MASK       (((DISP_ROWS << 1) - 1) & ~(DISP_NORMAL - 1))
103
104 #ifdef CONFIG_FEATURE_LS_SORTFILES
105 /* how will the files be sorted */
106 #define SORT_ORDER_FORWARD   0          /* sort in reverse order */
107 #define SORT_ORDER_REVERSE   (1U<<27)   /* sort in reverse order */
108
109 #define SORT_NAME      0                /* sort by file name */
110 #define SORT_SIZE      (1U<<28)         /* sort by file size */
111 #define SORT_ATIME     (2U<<28)         /* sort by last access time */
112 #define SORT_CTIME     (3U<<28)         /* sort by last change time */
113 #define SORT_MTIME     (4U<<28)         /* sort by last modification time */
114 #define SORT_VERSION   (5U<<28)         /* sort by version */
115 #define SORT_EXT       (6U<<28)         /* sort by file name extension */
116 #define SORT_DIR       (7U<<28)         /* sort by file or directory */
117
118 #define SORT_MASK      (7U<<28)
119 #endif
120
121 #ifdef CONFIG_FEATURE_LS_TIMESTAMPS
122 /* which of the three times will be used */
123 #define TIME_MOD       0
124 #define TIME_CHANGE    (1U<<23)
125 #define TIME_ACCESS    (1U<<24)
126
127 #define TIME_MASK      (3U<<23)
128 #endif
129
130 #ifdef CONFIG_FEATURE_LS_FOLLOWLINKS
131 #define FOLLOW_LINKS   (1U<<25)
132 #endif
133 #ifdef CONFIG_FEATURE_HUMAN_READABLE
134 #define LS_DISP_HR     (1U<<26)
135 #endif
136
137 #define LIST_SHORT      (LIST_FILENAME)
138 #define LIST_ISHORT     (LIST_INO | LIST_FILENAME)
139 #define LIST_LONG       (LIST_MODEBITS | LIST_NLINKS | LIST_ID_NAME | LIST_SIZE | \
140                                                 LIST_DATE_TIME | LIST_FILENAME | LIST_SYMLINK)
141 #define LIST_ILONG      (LIST_INO | LIST_LONG)
142
143 #define SPLIT_DIR      1
144 #define SPLIT_FILE     0
145 #define SPLIT_SUBDIR   2
146
147 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
148 #define TYPECHAR(mode)  ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
149
150 #if defined(CONFIG_FEATURE_LS_FILETYPES) || defined(CONFIG_FEATURE_LS_COLOR)
151 # define APPCHAR(mode)   ("\0|\0\0/\0\0\0\0\0@\0=\0\0\0" [TYPEINDEX(mode)])
152 #endif
153
154 /* colored LS support by JaWi, janwillem.janssen@lxtreme.nl */
155 #ifdef CONFIG_FEATURE_LS_COLOR
156
157 static int show_color = 0;
158
159 /* long option entry used only for --color, which has no short option
160  * equivalent.  */
161 static const struct option ls_color_opt[] =
162 {
163         {"color", optional_argument, NULL, 1},
164         {NULL, 0, NULL, 0}
165 };
166
167 #define COLOR(mode)     ("\000\043\043\043\042\000\043\043"\
168                          "\000\000\044\000\043\000\000\040" [TYPEINDEX(mode)])
169 #define ATTR(mode)      ("\00\00\01\00\01\00\01\00"\
170                          "\00\00\01\00\01\00\00\01" [TYPEINDEX(mode)])
171 #endif
172
173 /*
174  * a directory entry and its stat info are stored here
175  */
176 struct dnode {                  /* the basic node */
177         char *name;             /* the dir entry name */
178         char *fullname;         /* the dir entry name */
179         int   allocated;
180         struct stat dstat;      /* the file stat info */
181 #ifdef CONFIG_SELINUX
182         security_context_t sid;
183 #endif
184         struct dnode *next;     /* point at the next node */
185 };
186 typedef struct dnode dnode_t;
187
188 static struct dnode **list_dir(const char *);
189 static struct dnode **dnalloc(int);
190 static int list_single(struct dnode *);
191
192 static unsigned int all_fmt;
193
194 #ifdef CONFIG_FEATURE_AUTOWIDTH
195 static int terminal_width = TERMINAL_WIDTH;
196 static unsigned short tabstops = COLUMN_GAP;
197 #else
198 #define tabstops COLUMN_GAP
199 #define terminal_width TERMINAL_WIDTH
200 #endif
201
202 static int status = EXIT_SUCCESS;
203
204 static struct dnode *my_stat(char *fullname, char *name)
205 {
206         struct stat dstat;
207         struct dnode *cur;
208 #ifdef CONFIG_SELINUX
209         security_context_t sid=NULL;
210 #endif
211
212 #ifdef CONFIG_FEATURE_LS_FOLLOWLINKS
213         if (all_fmt & FOLLOW_LINKS) {
214 #ifdef CONFIG_SELINUX
215                 if (is_selinux_enabled())  {
216                          getfilecon(fullname,&sid);
217                 }
218 #endif
219                 if (stat(fullname, &dstat)) {
220                         bb_perror_msg("%s", fullname);
221                         status = EXIT_FAILURE;
222                         return 0;
223                 }
224         } else
225 #endif
226         {
227 #ifdef CONFIG_SELINUX
228                 if  (is_selinux_enabled())  {
229                   lgetfilecon(fullname,&sid);
230                 }
231 #endif
232                 if (lstat(fullname, &dstat)) {
233                         bb_perror_msg("%s", fullname);
234                         status = EXIT_FAILURE;
235                         return 0;
236                 }
237         }
238
239         cur = (struct dnode *) xmalloc(sizeof(struct dnode));
240         cur->fullname = fullname;
241         cur->name = name;
242         cur->dstat = dstat;
243 #ifdef CONFIG_SELINUX
244         cur->sid = sid;
245 #endif
246         return cur;
247 }
248
249 /*----------------------------------------------------------------------*/
250 #ifdef CONFIG_FEATURE_LS_COLOR
251 static char fgcolor(mode_t mode)
252 {
253         /* Check wheter the file is existing (if so, color it red!) */
254         if (errno == ENOENT) {
255                 return '\037';
256         }
257         if (LIST_EXEC && S_ISREG(mode)
258                 && (mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
259                 return COLOR(0xF000);   /* File is executable ... */
260         return COLOR(mode);
261 }
262
263 /*----------------------------------------------------------------------*/
264 static char bgcolor(mode_t mode)
265 {
266         if (LIST_EXEC && S_ISREG(mode)
267                 && (mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
268                 return ATTR(0xF000);    /* File is executable ... */
269         return ATTR(mode);
270 }
271 #endif
272
273 /*----------------------------------------------------------------------*/
274 #if defined(CONFIG_FEATURE_LS_FILETYPES) || defined(CONFIG_FEATURE_LS_COLOR)
275 static char append_char(mode_t mode)
276 {
277         if (!(all_fmt & LIST_FILETYPE))
278                 return '\0';
279         if ((all_fmt & LIST_EXEC) && S_ISREG(mode)
280                 && (mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
281                 return '*';
282         return APPCHAR(mode);
283 }
284 #endif
285
286 /*----------------------------------------------------------------------*/
287
288 #define countdirs(A,B) count_dirs((A), (B), 1)
289 #define countsubdirs(A,B) count_dirs((A), (B), 0)
290
291 static int count_dirs(struct dnode **dn, int nfiles, int notsubdirs)
292 {
293         int i, dirs;
294
295         if (dn == NULL || nfiles < 1)
296                 return (0);
297         dirs = 0;
298         for (i = 0; i < nfiles; i++) {
299                 if (S_ISDIR(dn[i]->dstat.st_mode)
300                         && (notsubdirs ||
301                         ((dn[i]->name[0] != '.') || (dn[i]->name[1]
302                                                 && ((dn[i]->name[1] != '.')
303                                                 || dn[i]->name[2])))))
304                         dirs++;
305         }
306         return (dirs);
307 }
308
309 static int countfiles(struct dnode **dnp)
310 {
311         int nfiles;
312         struct dnode *cur;
313
314         if (dnp == NULL)
315                 return (0);
316         nfiles = 0;
317         for (cur = dnp[0]; cur->next != NULL; cur = cur->next)
318                 nfiles++;
319         nfiles++;
320         return (nfiles);
321 }
322
323 /* get memory to hold an array of pointers */
324 static struct dnode **dnalloc(int num)
325 {
326         struct dnode **p;
327
328         if (num < 1)
329                 return (NULL);
330
331         p = (struct dnode **) xcalloc((size_t) num, (size_t) (sizeof(struct dnode *)));
332         return (p);
333 }
334
335 #ifdef CONFIG_FEATURE_LS_RECURSIVE
336 static void dfree(struct dnode **dnp, int nfiles)
337 {
338         int i;
339
340         if (dnp == NULL)
341                 return;
342
343         for (i = 0; i < nfiles; i++) {
344                 struct dnode *cur = dnp[i];
345                 if(cur->allocated)
346                         free(cur->fullname);    /* free the filename */
347                 free(cur);              /* free the dnode */
348         }
349         free(dnp);                      /* free the array holding the dnode pointers */
350 }
351 #else
352 #define dfree(...)
353 #endif
354
355 static struct dnode **splitdnarray(struct dnode **dn, int nfiles, int which)
356 {
357         int dncnt, i, d;
358         struct dnode **dnp;
359
360         if (dn == NULL || nfiles < 1)
361                 return (NULL);
362
363         /* count how many dirs and regular files there are */
364         if (which == SPLIT_SUBDIR)
365                 dncnt = countsubdirs(dn, nfiles);
366         else {
367                 dncnt = countdirs(dn, nfiles);  /* assume we are looking for dirs */
368                 if (which == SPLIT_FILE)
369                         dncnt = nfiles - dncnt; /* looking for files */
370         }
371
372         /* allocate a file array and a dir array */
373         dnp = dnalloc(dncnt);
374
375         /* copy the entrys into the file or dir array */
376         for (d = i = 0; i < nfiles; i++) {
377                 if (S_ISDIR(dn[i]->dstat.st_mode)) {
378                         if (which & (SPLIT_DIR|SPLIT_SUBDIR)) {
379                                 if ((which & SPLIT_DIR)
380                                         || ((dn[i]->name[0] != '.')
381                                                 || (dn[i]->name[1]
382                                                         && ((dn[i]->name[1] != '.')
383                                                                 || dn[i]->name[2])))) {
384                                                                         dnp[d++] = dn[i];
385                                                                 }
386                         }
387                 } else if (!(which & (SPLIT_DIR|SPLIT_SUBDIR))) {
388                         dnp[d++] = dn[i];
389                 }
390         }
391         return (dnp);
392 }
393
394 /*----------------------------------------------------------------------*/
395 #ifdef CONFIG_FEATURE_LS_SORTFILES
396 static int sortcmp(const void *a, const void *b)
397 {
398         struct dnode *d1 = *(struct dnode **)a;
399         struct dnode *d2 = *(struct dnode **)b;
400         unsigned int sort_opts = all_fmt & SORT_MASK;
401         int dif;
402
403         dif = 0;                        /* assume SORT_NAME */
404         if (sort_opts == SORT_SIZE) {
405                 dif = (int) (d2->dstat.st_size - d1->dstat.st_size);
406         } else if (sort_opts == SORT_ATIME) {
407                 dif = (int) (d2->dstat.st_atime - d1->dstat.st_atime);
408         } else if (sort_opts == SORT_CTIME) {
409                 dif = (int) (d2->dstat.st_ctime - d1->dstat.st_ctime);
410         } else if (sort_opts == SORT_MTIME) {
411                 dif = (int) (d2->dstat.st_mtime - d1->dstat.st_mtime);
412         } else if (sort_opts == SORT_DIR) {
413                 dif = S_ISDIR(d2->dstat.st_mode) - S_ISDIR(d1->dstat.st_mode);
414                 /* } else if (sort_opts == SORT_VERSION) { */
415                 /* } else if (sort_opts == SORT_EXT) { */
416         }
417
418         if (dif == 0) {
419                 /* sort by name- may be a tie_breaker for time or size cmp */
420 #ifdef CONFIG_LOCALE_SUPPORT
421                 dif = strcoll(d1->name, d2->name);
422 #else
423                 dif = strcmp(d1->name, d2->name);
424 #endif
425         }
426
427         if (all_fmt & SORT_ORDER_REVERSE) {
428                 dif = -dif;
429         }
430         return (dif);
431 }
432
433 /*----------------------------------------------------------------------*/
434 static void dnsort(struct dnode **dn, int size)
435 {
436         qsort(dn, size, sizeof *dn, sortcmp);
437 }
438 #endif
439
440 /*----------------------------------------------------------------------*/
441 static void showfiles(struct dnode **dn, int nfiles)
442 {
443         int i, ncols, nrows, row, nc;
444         int column = 0;
445         int nexttab = 0;
446         int column_width = 0; /* for STYLE_LONG and STYLE_SINGLE not used */
447
448         if (dn == NULL || nfiles < 1)
449                 return;
450
451         if (all_fmt & STYLE_ONE_RECORD_FLAG) {
452                 ncols = 1;
453         } else {
454                 /* find the longest file name-  use that as the column width */
455                 for (i = 0; i < nfiles; i++) {
456                         int len = strlen(dn[i]->name) +
457 #ifdef CONFIG_SELINUX
458                         ((all_fmt & LIST_CONTEXT) ? 33 : 0) +
459 #endif
460                         ((all_fmt & LIST_INO) ? 8 : 0) +
461                         ((all_fmt & LIST_BLOCKS) ? 5 : 0);
462                         if (column_width < len)
463                                 column_width = len;
464                 }
465                 column_width += tabstops;
466                 ncols = (int) (terminal_width / column_width);
467         }
468
469         if (ncols > 1) {
470                 nrows = nfiles / ncols;
471                 if ((nrows * ncols) < nfiles)
472                         nrows++;                /* round up fractionals */
473         } else {
474                 nrows = nfiles;
475                 ncols = 1;
476         }
477
478         for (row = 0; row < nrows; row++) {
479                 for (nc = 0; nc < ncols; nc++) {
480                         /* reach into the array based on the column and row */
481                         i = (nc * nrows) + row; /* assume display by column */
482                         if (all_fmt & DISP_ROWS)
483                                 i = (row * ncols) + nc; /* display across row */
484                         if (i < nfiles) {
485                                 if (column > 0) {
486                                         nexttab -= column;
487                                         while (nexttab--) {
488                                                 putchar(' ');
489                                                 column++;
490                                         }
491                         }
492                                 nexttab = column + column_width;
493                                 column += list_single(dn[i]);
494                 }
495                 }
496                 putchar('\n');
497                 column = 0;
498         }
499 }
500
501 /*----------------------------------------------------------------------*/
502 static void showdirs(struct dnode **dn, int ndirs, int first)
503 {
504         int i, nfiles;
505         struct dnode **subdnp;
506
507 #ifdef CONFIG_FEATURE_LS_RECURSIVE
508         int dndirs;
509         struct dnode **dnd;
510 #endif
511
512         if (dn == NULL || ndirs < 1)
513                 return;
514
515         for (i = 0; i < ndirs; i++) {
516                 if (all_fmt & (DISP_DIRNAME | DISP_RECURSIVE)) {
517                         if (!first)
518                                 printf("\n");
519                         first = 0;
520                         printf("%s:\n", dn[i]->fullname);
521                 }
522                 subdnp = list_dir(dn[i]->fullname);
523                 nfiles = countfiles(subdnp);
524                 if (nfiles > 0) {
525                         /* list all files at this level */
526 #ifdef CONFIG_FEATURE_LS_SORTFILES
527                         dnsort(subdnp, nfiles);
528 #endif
529                         showfiles(subdnp, nfiles);
530 #ifdef CONFIG_FEATURE_LS_RECURSIVE
531                         if (all_fmt & DISP_RECURSIVE) {
532                                 /* recursive- list the sub-dirs */
533                                 dnd = splitdnarray(subdnp, nfiles, SPLIT_SUBDIR);
534                                 dndirs = countsubdirs(subdnp, nfiles);
535                                 if (dndirs > 0) {
536 #ifdef CONFIG_FEATURE_LS_SORTFILES
537                                         dnsort(dnd, dndirs);
538 #endif
539                                         showdirs(dnd, dndirs, 0);
540                                         free(dnd);      /* free the array of dnode pointers to the dirs */
541                                 }
542                         }
543                         dfree(subdnp, nfiles);  /* free the dnodes and the fullname mem */
544 #endif
545                 }
546         }
547 }
548
549 /*----------------------------------------------------------------------*/
550 static struct dnode **list_dir(const char *path)
551 {
552         struct dnode *dn, *cur, **dnp;
553         struct dirent *entry;
554         DIR *dir;
555         int i, nfiles;
556
557         if (path == NULL)
558                 return (NULL);
559
560         dn = NULL;
561         nfiles = 0;
562         dir = bb_opendir(path);
563         if (dir == NULL) {
564                 status = EXIT_FAILURE;
565                 return (NULL);  /* could not open the dir */
566         }
567         while ((entry = readdir(dir)) != NULL) {
568                 char *fullname;
569
570                 /* are we going to list the file- it may be . or .. or a hidden file */
571                 if (entry->d_name[0] == '.') {
572                         if ((entry->d_name[1] == 0 || (
573                                 entry->d_name[1] == '.'
574                                 && entry->d_name[2] == 0))
575                                         && !(all_fmt & DISP_DOT))
576                         continue;
577                         if (!(all_fmt & DISP_HIDDEN))
578                         continue;
579                 }
580                 fullname = concat_path_file(path, entry->d_name);
581                 cur = my_stat(fullname, strrchr(fullname, '/') + 1);
582                 if (!cur)
583                         continue;
584                 cur->allocated = 1;
585                 cur->next = dn;
586                 dn = cur;
587                 nfiles++;
588         }
589         closedir(dir);
590
591         /* now that we know how many files there are
592            ** allocate memory for an array to hold dnode pointers
593          */
594         if (dn == NULL)
595                 return (NULL);
596         dnp = dnalloc(nfiles);
597         for (i = 0, cur = dn; i < nfiles; i++) {
598                 dnp[i] = cur;   /* save pointer to node in array */
599                 cur = cur->next;
600         }
601
602         return (dnp);
603 }
604
605 /*----------------------------------------------------------------------*/
606 static int list_single(struct dnode *dn)
607 {
608         int i, column = 0;
609
610 #ifdef CONFIG_FEATURE_LS_USERNAME
611         char scratch[16];
612 #endif
613 #ifdef CONFIG_FEATURE_LS_TIMESTAMPS
614         char *filetime;
615         time_t ttime, age;
616 #endif
617 #if defined(CONFIG_FEATURE_LS_FILETYPES) || defined (CONFIG_FEATURE_LS_COLOR)
618         struct stat info;
619         char append;
620 #endif
621
622         if (dn->fullname == NULL)
623                 return (0);
624
625 #ifdef CONFIG_FEATURE_LS_TIMESTAMPS
626         ttime = dn->dstat.st_mtime;     /* the default time */
627         if (all_fmt & TIME_ACCESS)
628                 ttime = dn->dstat.st_atime;
629         if (all_fmt & TIME_CHANGE)
630                 ttime = dn->dstat.st_ctime;
631         filetime = ctime(&ttime);
632 #endif
633 #ifdef CONFIG_FEATURE_LS_FILETYPES
634         append = append_char(dn->dstat.st_mode);
635 #endif
636
637         for (i = 0; i <= 31; i++) {
638                 switch (all_fmt & (1 << i)) {
639                 case LIST_INO:
640                         column += printf("%7ld ", (long int) dn->dstat.st_ino);
641                         break;
642                 case LIST_BLOCKS:
643 #if _FILE_OFFSET_BITS == 64
644                         column += printf("%4lld ", (long long)dn->dstat.st_blocks >> 1);
645 #else
646                         column += printf("%4ld ", dn->dstat.st_blocks >> 1);
647 #endif
648                         break;
649                 case LIST_MODEBITS:
650                         column += printf("%-10s ", (char *) bb_mode_string(dn->dstat.st_mode));
651                         break;
652                 case LIST_NLINKS:
653                         column += printf("%4ld ", (long) dn->dstat.st_nlink);
654                         break;
655                 case LIST_ID_NAME:
656 #ifdef CONFIG_FEATURE_LS_USERNAME
657                         bb_getpwuid(scratch, dn->dstat.st_uid, sizeof(scratch));
658                         printf("%-8.8s ", scratch);
659                         bb_getgrgid(scratch, dn->dstat.st_gid, sizeof(scratch));
660                         printf("%-8.8s", scratch);
661                         column += 17;
662                         break;
663 #endif
664                 case LIST_ID_NUMERIC:
665                         column += printf("%-8d %-8d", dn->dstat.st_uid, dn->dstat.st_gid);
666                         break;
667                 case LIST_SIZE:
668                 case LIST_DEV:
669                         if (S_ISBLK(dn->dstat.st_mode) || S_ISCHR(dn->dstat.st_mode)) {
670                                 column += printf("%4d, %3d ", (int) major(dn->dstat.st_rdev),
671                                            (int) minor(dn->dstat.st_rdev));
672                         } else {
673 #ifdef CONFIG_FEATURE_HUMAN_READABLE
674                                 if (all_fmt & LS_DISP_HR) {
675                                         column += printf("%9s ",
676                                                         make_human_readable_str(dn->dstat.st_size, 1, 0));
677                                 } else
678 #endif
679                                 {
680 #if _FILE_OFFSET_BITS == 64
681                                         column += printf("%9lld ", (long long) dn->dstat.st_size);
682 #else
683                                         column += printf("%9ld ", dn->dstat.st_size);
684 #endif
685                                 }
686                         }
687                         break;
688 #ifdef CONFIG_FEATURE_LS_TIMESTAMPS
689                 case LIST_FULLTIME:
690                         printf("%24.24s ", filetime);
691                         column += 25;
692                         break;
693                 case LIST_DATE_TIME:
694                         if ((all_fmt & LIST_FULLTIME) == 0) {
695                                 age = time(NULL) - ttime;
696                                 printf("%6.6s ", filetime + 4);
697                                 if (age < 3600L * 24 * 365 / 2 && age > -15 * 60) {
698                                         /* hh:mm if less than 6 months old */
699                                         printf("%5.5s ", filetime + 11);
700                                 } else {
701                                         printf(" %4.4s ", filetime + 20);
702                                 }
703                                 column += 13;
704                         }
705                         break;
706 #endif
707 #ifdef CONFIG_SELINUX
708                 case LIST_CONTEXT:
709                         {
710                                 char context[80];
711                                 int len = 0;
712
713                                 if (dn->sid) {
714                                   /*  I assume sid initilized with NULL  */
715                                   len = strlen(dn->sid)+1;
716                                   safe_strncpy(context, dn->sid, len);
717                                   freecon(dn->sid);
718                                 }else {
719                                   safe_strncpy(context, "unknown", 8);
720                                 }
721                                 printf("%-32s ", context);
722                                 column += MAX(33, len);
723                         }
724                         break;
725 #endif
726                 case LIST_FILENAME:
727 #ifdef CONFIG_FEATURE_LS_COLOR
728                         errno = 0;
729                         if (show_color && !lstat(dn->fullname, &info)) {
730                                 printf("\033[%d;%dm", bgcolor(info.st_mode),
731                                            fgcolor(info.st_mode));
732                         }
733 #endif
734                         column += printf("%s", dn->name);
735 #ifdef CONFIG_FEATURE_LS_COLOR
736                         if (show_color) {
737                                 printf("\033[0m");
738                         }
739 #endif
740                         break;
741                 case LIST_SYMLINK:
742                         if (S_ISLNK(dn->dstat.st_mode)) {
743                                 char *lpath = xreadlink(dn->fullname);
744
745                                 if (lpath) {
746                                         printf(" -> ");
747 #if defined(CONFIG_FEATURE_LS_FILETYPES) || defined (CONFIG_FEATURE_LS_COLOR)
748                                         if (!stat(dn->fullname, &info)) {
749                                                 append = append_char(info.st_mode);
750                                         }
751 #endif
752 #ifdef CONFIG_FEATURE_LS_COLOR
753                                         if (show_color) {
754                                                 errno = 0;
755                                                 printf("\033[%d;%dm", bgcolor(info.st_mode),
756                                                            fgcolor(info.st_mode));
757                                         }
758 #endif
759                                         column += printf("%s", lpath) + 4;
760 #ifdef CONFIG_FEATURE_LS_COLOR
761                                         if (show_color) {
762                                                 printf("\033[0m");
763                                         }
764 #endif
765                                         free(lpath);
766                                 }
767                         }
768                         break;
769 #ifdef CONFIG_FEATURE_LS_FILETYPES
770                 case LIST_FILETYPE:
771                         if (append != '\0') {
772                                 printf("%1c", append);
773                                 column++;
774                         }
775                         break;
776 #endif
777                 }
778         }
779
780         return column;
781 }
782
783 /*----------------------------------------------------------------------*/
784
785 /* "[-]Cadil1", POSIX mandated options, busybox always supports */
786 /* "[-]gnsx", POSIX non-mandated options, busybox always supports */
787 /* "[-]Ak" GNU options, busybox always supports */
788 /* "[-]FLRctur", POSIX mandated options, busybox optionally supports */
789 /* "[-]p", POSIX non-mandated options, busybox optionally supports */
790 /* "[-]SXvThw", GNU options, busybox optionally supports */
791 /* "[-]K", SELinux mandated options, busybox optionally supports */
792 /* "[-]e", I think we made this one up */
793
794 #ifdef CONFIG_FEATURE_LS_TIMESTAMPS
795 # define LS_STR_TIMESTAMPS      "cetu"
796 #else
797 # define LS_STR_TIMESTAMPS      ""
798 #endif
799
800 #ifdef CONFIG_FEATURE_LS_SORTFILES
801 # define LS_STR_SORTFILES       "SXrv"
802 #else
803 # define LS_STR_SORTFILES       ""
804 #endif
805
806 #ifdef CONFIG_FEATURE_LS_FILETYPES
807 # define LS_STR_FILETYPES       "Fp"
808 #else
809 # define LS_STR_FILETYPES       ""
810 #endif
811
812 #ifdef CONFIG_FEATURE_LS_FOLLOWLINKS
813 # define LS_STR_FOLLOW_LINKS    "L"
814 #else
815 # define LS_STR_FOLLOW_LINKS    ""
816 #endif
817
818 #ifdef CONFIG_FEATURE_LS_RECURSIVE
819 # define LS_STR_RECURSIVE       "R"
820 #else
821 # define LS_STR_RECURSIVE       ""
822 #endif
823
824 #ifdef CONFIG_FEATURE_HUMAN_READABLE
825 # define LS_STR_HUMAN_READABLE  "h"
826 #else
827 # define LS_STR_HUMAN_READABLE  ""
828 #endif
829
830 #ifdef CONFIG_SELINUX
831 # define LS_STR_SELINUX "K"
832 #else
833 # define LS_STR_SELINUX ""
834 #endif
835
836 #ifdef CONFIG_FEATURE_AUTOWIDTH
837 # define LS_STR_AUTOWIDTH       "T:w:"
838 #else
839 # define LS_STR_AUTOWIDTH       ""
840 #endif
841
842 static const char ls_options[]="Cadil1gnsxAk" \
843         LS_STR_TIMESTAMPS \
844         LS_STR_SORTFILES \
845         LS_STR_FILETYPES \
846         LS_STR_FOLLOW_LINKS \
847         LS_STR_RECURSIVE \
848         LS_STR_HUMAN_READABLE \
849         LS_STR_SELINUX \
850         LS_STR_AUTOWIDTH;
851
852 #define LIST_MASK_TRIGGER       0
853 #define STYLE_MASK_TRIGGER      STYLE_MASK
854 #define SORT_MASK_TRIGGER       SORT_MASK
855 #define DISP_MASK_TRIGGER       DISP_ROWS
856 #define TIME_MASK_TRIGGER       TIME_MASK
857
858 static const unsigned opt_flags[] = {
859         LIST_SHORT | STYLE_COLUMNS,     /* C */
860         DISP_HIDDEN | DISP_DOT,         /* a */
861         DISP_NOLIST,                            /* d */
862         LIST_INO,                                       /* i */
863         LIST_LONG | STYLE_LONG,         /* l - remember LS_DISP_HR in mask! */
864         LIST_SHORT | STYLE_SINGLE,      /* 1 */
865         0,                                                      /* g - ingored */
866         LIST_ID_NUMERIC,                        /* n */
867         LIST_BLOCKS,                            /* s */
868         DISP_ROWS,                                      /* x */
869         DISP_HIDDEN,                            /* A */
870 #ifdef CONFIG_SELINUX
871         LIST_CONTEXT,                           /* k */
872 #else
873         0,                                                      /* k - ingored */
874 #endif
875 #ifdef CONFIG_FEATURE_LS_TIMESTAMPS
876 # ifdef CONFIG_FEATURE_LS_SORTFILES
877         TIME_CHANGE | SORT_CTIME,       /* c */
878 # else
879         TIME_CHANGE,                            /* c */
880 # endif
881         LIST_FULLTIME,                          /* e */
882 # ifdef CONFIG_FEATURE_LS_SORTFILES
883         SORT_MTIME,                                     /* t */
884 # else
885         0,                                                      /* t - ignored -- is this correct? */
886 # endif
887 # ifdef CONFIG_FEATURE_LS_SORTFILES
888         TIME_ACCESS | SORT_ATIME,       /* u */
889 # else
890         TIME_ACCESS,                            /* u */
891 # endif
892 #endif
893 #ifdef CONFIG_FEATURE_LS_SORTFILES
894         SORT_SIZE,                                      /* S */
895         SORT_EXT,                                       /* X */
896         SORT_ORDER_REVERSE,                     /* r */
897         SORT_VERSION,                           /* v */
898 #endif
899 #ifdef CONFIG_FEATURE_LS_FILETYPES
900         LIST_FILETYPE | LIST_EXEC,      /* F */
901         LIST_FILETYPE,                          /* p */
902 #endif
903 #ifdef CONFIG_FEATURE_LS_FOLLOWLINKS
904         FOLLOW_LINKS,                           /* L */
905 #endif
906 #ifdef CONFIG_FEATURE_LS_RECURSIVE
907         DISP_RECURSIVE,                         /* R */
908 #endif
909 #ifdef CONFIG_FEATURE_HUMAN_READABLE
910         LS_DISP_HR,                                     /* h */
911 #endif
912 #ifdef CONFIG_SELINUX
913         LIST_MODEBITS|LIST_NLINKS|LIST_CONTEXT|LIST_SIZE|LIST_DATE_TIME, /* K */
914 #endif
915 #ifdef CONFIG_FEATURE_AUTOWIDTH
916        0, 0,                    /* T, w - ignored */
917 #endif
918         (1U<<31)
919 };
920
921
922 /*----------------------------------------------------------------------*/
923
924 int ls_main(int argc, char **argv)
925 {
926         struct dnode **dnd;
927         struct dnode **dnf;
928         struct dnode **dnp;
929         struct dnode *dn;
930         struct dnode *cur;
931         long opt;
932         int nfiles = 0;
933         int dnfiles;
934         int dndirs;
935         int oi;
936         int ac;
937         int i;
938         char **av;
939 #ifdef CONFIG_FEATURE_AUTOWIDTH
940         char *tabstops_str = NULL;
941         char *terminal_width_str = NULL;
942 #endif
943 #ifdef CONFIG_FEATURE_LS_COLOR
944         char *color_opt;
945 #endif
946
947         all_fmt = LIST_SHORT | DISP_NORMAL | STYLE_AUTO
948 #ifdef CONFIG_FEATURE_LS_TIMESTAMPS
949                 | TIME_MOD
950 #endif
951 #ifdef CONFIG_FEATURE_LS_SORTFILES
952                 | SORT_NAME | SORT_ORDER_FORWARD
953 #endif
954                 ;
955
956 #ifdef CONFIG_FEATURE_AUTOWIDTH
957         /* Obtain the terminal width.  */
958         get_terminal_width_height(STDOUT_FILENO, &terminal_width, NULL);
959         /* Go one less... */
960         terminal_width--;
961 #endif
962
963 #ifdef CONFIG_FEATURE_LS_COLOR
964         bb_applet_long_options = ls_color_opt;
965 #endif
966
967         /* process options */
968 #ifdef CONFIG_FEATURE_AUTOWIDTH
969         opt = bb_getopt_ulflags(argc, argv, ls_options, &tabstops_str, &terminal_width_str
970 #ifdef CONFIG_FEATURE_LS_COLOR
971                 , &color_opt
972 #endif
973                 );
974         if (tabstops_str) {
975                 tabstops = atoi(tabstops_str);
976         }
977         if (terminal_width_str) {
978                 terminal_width = atoi(terminal_width_str);
979         }
980 #else
981         opt = bb_getopt_ulflags(argc, argv, ls_options
982 #ifdef CONFIG_FEATURE_LS_COLOR
983                 , &color_opt
984 #endif
985                 );
986 #endif
987         for (i = 0; opt_flags[i] != (1U<<31); i++) {
988                 if (opt & (1 << i)) {
989                         unsigned int flags = opt_flags[i];
990
991                         if (flags & LIST_MASK_TRIGGER) {
992                                 all_fmt &= ~LIST_MASK;
993                         }
994                         if (flags & STYLE_MASK_TRIGGER) {
995                                 all_fmt &= ~STYLE_MASK;
996                         }
997 #ifdef CONFIG_FEATURE_LS_SORTFILES
998                         if (flags & SORT_MASK_TRIGGER) {
999                                 all_fmt &= ~SORT_MASK;
1000                         }
1001 #endif
1002                         if (flags & DISP_MASK_TRIGGER) {
1003                                 all_fmt &= ~DISP_MASK;
1004                         }
1005 #ifdef CONFIG_FEATURE_LS_TIMESTAMPS
1006                         if (flags & TIME_MASK_TRIGGER) {
1007                                 all_fmt &= ~TIME_MASK;
1008                         }
1009 #endif
1010                         if (flags & LIST_CONTEXT) {
1011                                 all_fmt |= STYLE_SINGLE;
1012                         }
1013 #ifdef CONFIG_FEATURE_HUMAN_READABLE
1014                         if (opt == 'l') {
1015                                 all_fmt &= ~LS_DISP_HR;
1016                         }
1017 #endif
1018                         all_fmt |= flags;
1019                 }
1020         }
1021
1022 #ifdef CONFIG_FEATURE_LS_COLOR
1023         {
1024                 /* find color bit value - last position for short getopt */
1025
1026 #if CONFIG_FEATURE_LS_COLOR_IS_DEFAULT
1027                 char *p;
1028
1029                 if ((p = getenv ("LS_COLORS")) != NULL &&
1030                         (*p == '\0' || (strcmp(p, "none") == 0))) {
1031                         ;
1032                 } else if (isatty(STDOUT_FILENO)) {
1033                         show_color = 1;
1034                 }
1035 #endif
1036
1037                 if((opt & (1 << i))) {  /* next flag after short options */
1038                         if (color_opt == NULL || strcmp("always", color_opt) == 0)
1039                                 show_color = 1;
1040                         else if (color_opt != NULL && strcmp("never", color_opt) == 0)
1041                                 show_color = 0;
1042                         else if (color_opt != NULL && strcmp("auto", color_opt) == 0 && isatty(STDOUT_FILENO))
1043                                 show_color = 1;
1044                 }
1045         }
1046 #endif
1047
1048         /* sort out which command line options take precedence */
1049 #ifdef CONFIG_FEATURE_LS_RECURSIVE
1050         if (all_fmt & DISP_NOLIST)
1051                 all_fmt &= ~DISP_RECURSIVE;     /* no recurse if listing only dir */
1052 #endif
1053 #if defined (CONFIG_FEATURE_LS_TIMESTAMPS) && defined (CONFIG_FEATURE_LS_SORTFILES)
1054         if (all_fmt & TIME_CHANGE)
1055                 all_fmt = (all_fmt & ~SORT_MASK) | SORT_CTIME;
1056         if (all_fmt & TIME_ACCESS)
1057                 all_fmt = (all_fmt & ~SORT_MASK) | SORT_ATIME;
1058 #endif
1059         if ((all_fmt & STYLE_MASK) != STYLE_LONG) /* only for long list */
1060                 all_fmt &= ~(LIST_ID_NUMERIC|LIST_FULLTIME|LIST_ID_NAME|LIST_ID_NUMERIC);
1061 #ifdef CONFIG_FEATURE_LS_USERNAME
1062         if ((all_fmt & STYLE_MASK) == STYLE_LONG && (all_fmt & LIST_ID_NUMERIC))
1063                 all_fmt &= ~LIST_ID_NAME;       /* don't list names if numeric uid */
1064 #endif
1065
1066         /* choose a display format */
1067         if ((all_fmt & STYLE_MASK) == STYLE_AUTO)
1068 #if STYLE_AUTO != 0
1069                 all_fmt = (all_fmt & ~STYLE_MASK)
1070                                 | (isatty(STDOUT_FILENO) ? STYLE_COLUMNS : STYLE_SINGLE);
1071 #else
1072                 all_fmt |= (isatty(STDOUT_FILENO) ? STYLE_COLUMNS : STYLE_SINGLE);
1073 #endif
1074
1075         /*
1076          * when there are no cmd line args we have to supply a default "." arg.
1077          * we will create a second argv array, "av" that will hold either
1078          * our created "." arg, or the real cmd line args.  The av array
1079          * just holds the pointers- we don't move the date the pointers
1080          * point to.
1081          */
1082         ac = argc - optind;     /* how many cmd line args are left */
1083         if (ac < 1) {
1084                 static const char * const dotdir[] = { "." };
1085
1086                 av = (char **) dotdir;
1087                 ac = 1;
1088         } else {
1089                 av = argv + optind;
1090         }
1091
1092         /* now, everything is in the av array */
1093         if (ac > 1)
1094                 all_fmt |= DISP_DIRNAME;        /* 2 or more items? label directories */
1095
1096         /* stuff the command line file names into an dnode array */
1097         dn = NULL;
1098         for (oi = 0; oi < ac; oi++) {
1099                 cur = my_stat(av[oi], av[oi]);
1100                 if (!cur)
1101                         continue;
1102                 cur->allocated = 0;
1103                 cur->next = dn;
1104                 dn = cur;
1105                 nfiles++;
1106         }
1107
1108         /* now that we know how many files there are
1109            ** allocate memory for an array to hold dnode pointers
1110          */
1111         dnp = dnalloc(nfiles);
1112         for (i = 0, cur = dn; i < nfiles; i++) {
1113                 dnp[i] = cur;   /* save pointer to node in array */
1114                 cur = cur->next;
1115         }
1116
1117         if (all_fmt & DISP_NOLIST) {
1118 #ifdef CONFIG_FEATURE_LS_SORTFILES
1119                 dnsort(dnp, nfiles);
1120 #endif
1121                 if (nfiles > 0)
1122                         showfiles(dnp, nfiles);
1123         } else {
1124                 dnd = splitdnarray(dnp, nfiles, SPLIT_DIR);
1125                 dnf = splitdnarray(dnp, nfiles, SPLIT_FILE);
1126                 dndirs = countdirs(dnp, nfiles);
1127                 dnfiles = nfiles - dndirs;
1128                 if (dnfiles > 0) {
1129 #ifdef CONFIG_FEATURE_LS_SORTFILES
1130                         dnsort(dnf, dnfiles);
1131 #endif
1132                         showfiles(dnf, dnfiles);
1133                         if (ENABLE_FEATURE_CLEAN_UP)
1134                                 free(dnf);
1135                 }
1136                 if (dndirs > 0) {
1137 #ifdef CONFIG_FEATURE_LS_SORTFILES
1138                         dnsort(dnd, dndirs);
1139 #endif
1140                         showdirs(dnd, dndirs, dnfiles == 0);
1141                         if (ENABLE_FEATURE_CLEAN_UP)
1142                                 free(dnd);
1143                 }
1144         }
1145         if (ENABLE_FEATURE_CLEAN_UP)
1146                 dfree(dnp, nfiles);
1147         return (status);
1148 }