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