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