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