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