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