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