207c617636cb81c48d1077fd0eb1c1e6af6f9249
[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 #define TERMINAL_WIDTH  80              /* use 79 if your terminal has linefold bug */
45 #define COLUMN_WIDTH    14              /* default if AUTOWIDTH not defined */
46 #define COLUMN_GAP      2                       /* includes the file type char, if present */
47 #define HAS_REWINDDIR
48
49 /************************************************************************/
50
51 #include "internal.h"
52 # include <sys/types.h>
53 #include <stdio.h>
54 #include <unistd.h>
55 #include <dirent.h>
56 #include <errno.h>
57 #include <stdio.h>
58 #ifdef BB_FEATURE_LS_TIMESTAMPS
59 #include <time.h>
60 #endif
61
62 #define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
63 #define TYPECHAR(mode)  ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
64 #ifdef BB_FEATURE_LS_FILETYPES
65 #define APPCHAR(mode)   ("\0|\0\0/\0\0\0\0\0@\0=\0\0\0" [TYPEINDEX(mode)])
66 #endif
67
68 #define FMT_AUTO        0
69 #define FMT_LONG        1                       /* one record per line, extended info */
70 #define FMT_SINGLE      2                       /* one record per line */
71 #define FMT_ROWS        3                       /* print across rows */
72 #define FMT_COLUMNS     3                       /* fill columns (same, since we don't sort) */
73
74 #define TIME_MOD        0
75 #define TIME_CHANGE     1
76 #define TIME_ACCESS     2
77
78 #define DISP_FTYPE      1                       /* show character for file type */
79 #define DISP_EXEC       2                       /* show '*' if regular executable file */
80 #define DISP_HIDDEN     4                       /* show files starting . (except . and ..) */
81 #define DISP_DOT        8                       /* show . and .. */
82 #define DISP_NUMERIC    16              /* numeric uid and gid */
83 #define DISP_FULLTIME   32              /* show extended time display */
84 #define DIR_NOLIST              64              /* show directory as itself, not contents */
85 #define DISP_DIRNAME    128             /* show directory name (for internal use) */
86 #define DISP_RECURSIVE  256             /* Do a recursive listing */
87
88 #ifndef MAJOR
89 #define MAJOR(dev) (((dev)>>8)&0xff)
90 #define MINOR(dev) ((dev)&0xff)
91 #endif
92
93 #ifdef BB_FEATURE_LS_SORTFILES
94 struct dnode {                          /* the basic node */
95         char *name;                             /* the dir entry name */
96         char *fullname;                 /* the dir entry name */
97         struct stat dstat;              /* the file stat info */
98 };
99 typedef struct dnode dnode_t;
100 #endif 
101 static unsigned char display_fmt = FMT_AUTO;
102 static unsigned short opts = 0;
103 static unsigned short column = 0;
104
105 #ifdef BB_FEATURE_AUTOWIDTH
106 static unsigned short terminal_width = 0;
107 static unsigned short column_width = 0;
108 static unsigned short toplevel_column_width = 0;
109 #else
110 #define terminal_width  TERMINAL_WIDTH
111 #define column_width    COLUMN_WIDTH
112 #endif
113
114 #ifdef BB_FEATURE_LS_TIMESTAMPS
115 static unsigned char time_fmt = TIME_MOD;
116 #endif
117
118 #define wr(data,len) fwrite(data, 1, len, stdout)
119
120 static void writenum(long val, short minwidth)
121 {
122         char scratch[128];
123
124         char *p = scratch + sizeof(scratch);
125         short len = 0;
126         short neg = (val < 0);
127
128         if (neg)
129                 val = -val;
130         do
131                 *--p = (val % 10) + '0', len++, val /= 10;
132         while (val);
133         if (neg)
134                 *--p = '-', len++;
135         while (len < minwidth)
136                 *--p = ' ', len++;
137         wr(p, len);
138         column += len;
139 }
140
141 static void newline(void)
142 {
143         if (column > 0) {
144                 wr("\n", 1);
145                 column = 0;
146         }
147 }
148
149 static void tab(short col)
150 {
151         static const char spaces[] = "                ";
152
153 #define nspaces ((sizeof spaces)-1)     /* null terminator! */
154
155         short n = col - column;
156
157         if (n > 0) {
158                 column = col;
159                 while (n > nspaces) {
160                         wr(spaces, nspaces);
161                         n -= nspaces;
162                 }
163                 /* must be 1...(sizeof spaces) left */
164                 wr(spaces, n);
165         }
166 #undef nspaces
167 }
168
169 #ifdef BB_FEATURE_LS_FILETYPES
170 static char append_char(mode_t mode)
171 {
172         if (!(opts & DISP_FTYPE))
173                 return '\0';
174         if ((opts & DISP_EXEC) && S_ISREG(mode)
175                 && (mode & (S_IXUSR | S_IXGRP | S_IXOTH))) return '*';
176         return APPCHAR(mode);
177 }
178 #endif
179
180 /**
181  **
182  ** Display a file or directory as a single item
183  ** (in either long or short format)
184  **
185  **/
186
187 static void list_single(const char *name, struct stat *info,
188                                                 const char *fullname)
189 {
190         char scratch[BUFSIZ + 1];
191         short len = strlen(name);
192
193 #ifdef BB_FEATURE_LS_FILETYPES
194         char append = append_char(info->st_mode);
195 #endif
196
197         if (display_fmt == FMT_LONG) {
198                 mode_t mode = info->st_mode;
199
200                 newline();
201                 wr(modeString(mode), 10);
202                 column = 10;
203                 writenum((long) info->st_nlink, (short) 5);
204                 fputs(" ", stdout);
205 #ifdef BB_FEATURE_LS_USERNAME
206                 if (!(opts & DISP_NUMERIC)) {
207                         memset(scratch, 0, sizeof(scratch));
208                         my_getpwuid(scratch, info->st_uid);
209                         if (*scratch) {
210                                 fputs(scratch, stdout);
211                                 if (strlen(scratch) <= 8)
212                                         wr("          ", 9 - strlen(scratch));
213                         } else {
214                                 writenum((long) info->st_uid, (short) 8);
215                                 fputs(" ", stdout);
216                         }
217                 } else
218 #endif
219                 {
220                         writenum((long) info->st_uid, (short) 8);
221                         fputs(" ", stdout);
222                 }
223 #ifdef BB_FEATURE_LS_USERNAME
224                 if (!(opts & DISP_NUMERIC)) {
225                         memset(scratch, 0, sizeof(scratch));
226                         my_getgrgid(scratch, info->st_gid);
227                         if (*scratch) {
228                                 fputs(scratch, stdout);
229                                 if (strlen(scratch) <= 8)
230                                         wr("         ", 8 - strlen(scratch));
231                         } else
232                                 writenum((long) info->st_gid, (short) 8);
233                 } else
234 #endif
235                         writenum((long) info->st_gid, (short) 8);
236                 //tab(26);
237                 if (S_ISBLK(mode) || S_ISCHR(mode)) {
238                         writenum((long) MAJOR(info->st_rdev), (short) 3);
239                         fputs(", ", stdout);
240                         writenum((long) MINOR(info->st_rdev), (short) 3);
241                 } else
242                         writenum((long) info->st_size, (short) 8);
243                 fputs(" ", stdout);
244                 //tab(32);
245 #ifdef BB_FEATURE_LS_TIMESTAMPS
246                 {
247                         time_t cal;
248                         char *string;
249
250                         switch (time_fmt) {
251                         case TIME_CHANGE:
252                                 cal = info->st_ctime;
253                                 break;
254                         case TIME_ACCESS:
255                                 cal = info->st_atime;
256                                 break;
257                         default:
258                                 cal = info->st_mtime;
259                                 break;
260                         }
261                         string = ctime(&cal);
262                         if (opts & DISP_FULLTIME)
263                                 wr(string, 24);
264                         else {
265                                 time_t age = time(NULL) - cal;
266
267                                 wr(string + 4, 7);      /* mmm_dd_ */
268                                 if (age < 3600L * 24 * 365 / 2 && age > -15 * 60)
269                                         /* hh:mm if less than 6 months old */
270                                         wr(string + 11, 5);
271                                 else
272                                         /* _yyyy otherwise */
273                                         wr(string + 19, 5);
274                         }
275                         wr(" ", 1);
276                 }
277 #else
278                 fputs("--- -- ----- ", stdout);
279 #endif
280                 wr(name, len);
281                 if (S_ISLNK(mode)) {
282                         wr(" -> ", 4);
283                         len = readlink(fullname, scratch, sizeof scratch);
284                         if (len > 0)
285                                 fwrite(scratch, 1, len, stdout);
286 #ifdef BB_FEATURE_LS_FILETYPES
287                         /* show type of destination */
288                         if (opts & DISP_FTYPE) {
289                                 if (!stat(fullname, info)) {
290                                         append = append_char(info->st_mode);
291                                         if (append)
292                                                 fputc(append, stdout);
293                                 }
294                         }
295 #endif
296                 }
297 #ifdef BB_FEATURE_LS_FILETYPES
298                 else if (append)
299                         wr(&append, 1);
300 #endif
301         } else {
302                 static short nexttab = 0;
303
304                 /* sort out column alignment */
305                 if (column == 0);               /* nothing to do */
306                 else if (display_fmt == FMT_SINGLE)
307                         newline();
308                 else {
309                         if (nexttab + column_width > terminal_width
310 #ifndef BB_FEATURE_AUTOWIDTH
311                                 || nexttab + len >= terminal_width
312 #endif
313                                 )
314                                 newline();
315                         else
316                                 tab(nexttab);
317                 }
318                 /* work out where next column starts */
319 #ifdef BB_FEATURE_AUTOWIDTH
320                 /* we know the calculated width is big enough */
321                 nexttab = column + column_width + COLUMN_GAP;
322 #else
323                 /* might cover more than one fixed-width column */
324                 nexttab = column;
325                 do
326                         nexttab += column_width + COLUMN_GAP;
327                 while (nexttab < (column + len + COLUMN_GAP));
328 #endif
329                 /* now write the data */
330                 wr(name, len);
331                 column = column + len;
332 #ifdef BB_FEATURE_LS_FILETYPES
333                 if (append)
334                         wr(&append, 1), column++;
335 #endif
336         }
337 }
338
339 #ifdef BB_FEATURE_LS_SORTFILES
340 void shellsort(struct dnode *dn[], int size)
341 {
342     struct dnode *temp;
343     int gap, i, j;
344
345     /* shell short the array */
346     for (gap= size/2; gap>0; gap /=2) {
347         for (i=gap; i<size; i++) {
348             for (j= i-gap; j>=0; j-=gap) {
349                 if (strcmp(dn[j]->name, dn[j+gap]->name) <= 0)
350                     break;
351                 temp= dn[j];
352                 dn[j]= dn[j+gap];
353                 dn[j+gap]= temp;
354             }
355         }
356     }
357 }
358
359 void showdnodes(struct dnode *dn[], int nfiles)
360 {
361         int nf, nc;
362         int ncols, fpc, i;
363
364         ncols= (int)(terminal_width / (column_width + COLUMN_GAP));
365         /* files per column.  The +1 means the last col is shorter than others */
366         fpc= (nfiles / ncols) + 1;
367         for (nf=0; nf<fpc; nf++) {
368                 for (nc=0; nc<ncols; nc++) {
369                         /* reach into the array based on the column and row */
370                         i= (nc * fpc) + nf;
371                         if (i >= nfiles) {
372                                 newline();
373                         } else {
374                                 list_single(dn[i]->name, &dn[i]->dstat, dn[i]->fullname);
375                         }
376                 }
377         }
378 }
379 #endif
380
381 /**
382  **
383  ** List the given file or directory, expanding a directory
384  ** to show its contents if required
385  **
386  **/
387
388 static int list_item(const char *name)
389 {
390         struct stat info;
391         DIR *dir;
392         struct dirent *entry;
393         char fullname[BUFSIZ + 1], *fnend;
394 #ifdef BB_FEATURE_LS_SORTFILES
395         int ni=0, nfiles=0;
396         struct dnode **dnp;
397         dnode_t *cur;
398 #endif
399
400         if (lstat(name, &info))
401                 goto listerr;
402
403         if (!S_ISDIR(info.st_mode) || (opts & DIR_NOLIST)) {
404 #ifdef BB_FEATURE_AUTOWIDTH
405                 column_width = toplevel_column_width;
406 #endif
407                 list_single(name, &info, name);
408                 return 0;
409         }
410
411         /* Otherwise, it's a directory we want to list the contents of */
412
413         if (opts & DISP_DIRNAME) {      /* identify the directory */
414                 if (column)
415                         wr("\n\n", 2), column = 0;
416                 wr(name, strlen(name));
417                 wr(":\n", 2);
418         }
419
420         dir = opendir(name);
421         if (!dir)
422                 goto listerr;
423 #ifdef BB_FEATURE_AUTOWIDTH
424         column_width = 0;
425         while ((entry = readdir(dir)) != NULL) {
426                 short w = strlen(entry->d_name);
427 #ifdef BB_FEATURE_LS_SORTFILES
428                 const char *en = entry->d_name;
429
430                 if (en[0] == '.') {
431                         if (!en[1] || (en[1] == '.' && !en[2])) {       /* . or .. */
432                                 if (!(opts & DISP_DOT))
433                                         continue;
434                         } else if (!(opts & DISP_HIDDEN))
435                                 continue;
436                 }
437                 nfiles++;       /* count how many files there will be */
438 #endif
439
440                 if (column_width < w)
441                         column_width = w;
442         }
443 #ifdef HAS_REWINDDIR
444         rewinddir(dir);
445 #else
446         closedir(dir);
447         dir = opendir(name);
448         if (!dir)
449                 goto listerr;
450 #endif
451 #endif
452 #ifdef BB_FEATURE_LS_SORTFILES
453         /* now that we know how many files there are
454          * allocate memory for an array to hold dnode pointers
455          */
456         dnp= (struct dnode **)calloc((size_t)nfiles, (size_t)(sizeof(struct dnode *)));
457 #endif
458
459         /* List the contents */
460
461         strcpy(fullname, name);         /* *** ignore '.' by itself */
462         fnend = fullname + strlen(fullname);
463         if (fnend[-1] != '/')
464                 *fnend++ = '/';
465
466         while ((entry = readdir(dir)) != NULL) {
467                 const char *en = entry->d_name;
468
469                 if (en[0] == '.') {
470                         if (!en[1] || (en[1] == '.' && !en[2])) {       /* . or .. */
471                                 if (!(opts & DISP_DOT))
472                                         continue;
473                         } else if (!(opts & DISP_HIDDEN))
474                                 continue;
475                 }
476                 /* FIXME: avoid stat if not required */
477                 strcpy(fnend, entry->d_name);
478 #ifdef BB_FEATURE_LS_SORTFILES
479                 /* allocate memory for a node and memory for the file name */
480                 cur= (struct dnode *)malloc(sizeof(struct dnode));
481                 cur->fullname= strcpy((char *)malloc(strlen(fullname)+1), fullname);
482                 cur->name= cur->fullname + (int)(fnend - fullname) ;
483                 lstat(fullname, &cur->dstat);   /* get file stat info into node */
484                 dnp[ni++]= cur;   /* save pointer to node in array */
485 #else
486                 if (lstat(fullname, &info)) {
487                         closedir(dir);
488                         goto listerr;           /* (shouldn't fail) */
489                 }
490                 list_single(entry->d_name, &info, fullname);
491 #endif
492         }
493         closedir(dir);
494 #ifdef BB_FEATURE_LS_SORTFILES
495         shellsort(dnp, nfiles);
496         showdnodes(dnp, nfiles);
497 #endif
498
499         if (opts & DISP_DIRNAME) {      /* separate the directory */
500                 if (column) {
501                         wr("\n", 1);
502                 }
503                 wr("\n", 1);
504                 column = 0;
505         }
506
507         return 0;
508
509   listerr:
510         newline();
511         perror(name);
512         return 1;
513 }
514
515 #ifdef BB_FEATURE_LS_RECURSIVE
516 static int dirAction(const char *fileName, struct stat *statbuf, void* junk)
517 {
518         int i;
519         fprintf(stdout, "\n%s:\n", fileName);
520         i = list_item(fileName);
521         newline();
522         return (i);
523 }
524 #endif
525
526 extern int ls_main(int argc, char **argv)
527 {
528         int argi = 1, i;
529
530         /* process options */
531         while (argi < argc && argv[argi][0] == '-') {
532                 const char *p = &argv[argi][1];
533
534                 if (!*p)
535                         goto print_usage_message;       /* "-" by itself not allowed */
536                 if (*p == '-') {
537                         if (!p[1]) {            /* "--" forces end of options */
538                                 argi++;
539                                 break;
540                         }
541                         /* it's a long option name - we don't support them */
542                         goto print_usage_message;
543                 }
544
545                 while (*p)
546                         switch (*p++) {
547                         case 'l':
548                                 display_fmt = FMT_LONG;
549                                 break;
550                         case '1':
551                                 display_fmt = FMT_SINGLE;
552                                 break;
553                         case 'x':
554                                 display_fmt = FMT_ROWS;
555                                 break;
556                         case 'C':
557                                 display_fmt = FMT_COLUMNS;
558                                 break;
559 #ifdef BB_FEATURE_LS_FILETYPES
560                         case 'p':
561                                 opts |= DISP_FTYPE;
562                                 break;
563                         case 'F':
564                                 opts |= DISP_FTYPE | DISP_EXEC;
565                                 break;
566 #endif
567                         case 'A':
568                                 opts |= DISP_HIDDEN;
569                                 break;
570                         case 'a':
571                                 opts |= DISP_HIDDEN | DISP_DOT;
572                                 break;
573                         case 'n':
574                                 opts |= DISP_NUMERIC;
575                                 break;
576                         case 'd':
577                                 opts |= DIR_NOLIST;
578                                 break;
579 #ifdef BB_FEATURE_LS_TIMESTAMPS
580                         case 'u':
581                                 time_fmt = TIME_ACCESS;
582                                 break;
583                         case 'c':
584                                 time_fmt = TIME_CHANGE;
585                                 break;
586                         case 'e':
587                                 opts |= DISP_FULLTIME;
588                                 break;
589 #endif
590 #ifdef BB_FEATURE_LS_RECURSIVE
591                         case 'R':
592                                 opts |= DISP_RECURSIVE;
593                                 break;
594 #endif
595                         case 'g': /* ignore -- for ftp servers */
596                                 break;
597                         default:
598                                 goto print_usage_message;
599                         }
600
601                 argi++;
602         }
603
604         /* choose a display format */
605         if (display_fmt == FMT_AUTO)
606                 display_fmt = isatty(fileno(stdout)) ? FMT_COLUMNS : FMT_SINGLE;
607         if (argi < argc - 1)
608                 opts |= DISP_DIRNAME;   /* 2 or more items? label directories */
609 #ifdef BB_FEATURE_AUTOWIDTH
610         /* could add a -w option and/or TIOCGWINSZ call */
611         if (terminal_width < 1)
612                 terminal_width = TERMINAL_WIDTH;
613
614         for (i = argi; i < argc; i++) {
615                 int len = strlen(argv[i]);
616
617                 if (toplevel_column_width < len)
618                         toplevel_column_width = len;
619         }
620 #endif
621
622         /* process files specified, or current directory if none */
623 #ifdef BB_FEATURE_LS_RECURSIVE
624         if (opts & DISP_RECURSIVE) {
625                 i = 0;
626                 if (argi == argc) {
627                         i = recursiveAction(".", TRUE, FALSE, FALSE, NULL, dirAction, NULL);
628                 }
629                 while (argi < argc) {
630                         i |= recursiveAction(argv[argi++], TRUE, FALSE, FALSE, NULL, dirAction, NULL);
631                 }
632         } else 
633 #endif
634         {
635                 i = 0;
636                 if (argi == argc)
637                         i = list_item(".");
638                 while (argi < argc)
639                         i |= list_item(argv[argi++]);
640                 newline();
641         }
642         exit(i);
643
644   print_usage_message:
645         usage(ls_usage);
646         exit(FALSE);
647 }