blob: 99cedf5f0ec7a84639051ca9da8b68693602669d [file] [log] [blame]
Eric Andersen9d3aba71999-10-06 09:04:55 +00001/*
2 * Mini ls implementation for busybox
3 *
4 * Copyright (C) 1998 by Erik Andersen <andersee@debian.org>
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 GNU
14 * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 *
20 */
21
22#if fooBar
23
24#include <stdio.h>
25#include <unistd.h>
26#include <dirent.h>
27#include "internal.h"
28
29
30static const char ls_usage[] = "ls [OPTION]... [FILE]...\n"
31"List information about the FILEs (the current directory by default).\n";
32
33int oneFlag=FALSE;
34int allFlag=FALSE;
35int directoryFlag=FALSE;
36int longFlag=FALSE;
37int typeFlag=FALSE;
38int dereferenceFlag=FALSE;
39int recursiveFlag=FALSE;
40
41static int fileAction(const char *fileName)
42{
43 if ( allFlag==FALSE && ((strcmp(fileName, "..") == 0)
44 || (strcmp(fileName, ".") == 0)) ) {
45 return( TRUE);
46 }
47 //struct stat statBuf;
48 //if (stat(fileName, &statBuf) > 0) {
49 fprintf(stdout, "%s\n", fileName);
50 return( TRUE);
51 //}
52 //else {
53// perror(fileName);
54// return( FALSE);
55// }
56}
57
58static int dirAction(const char *fileName)
59{
60 DIR *dir;
61 struct dirent *entry;
62
63 fprintf(stdout, "%s\n", fileName);
64
65 dir = opendir( fileName);
66 if (!dir) {
67 perror("Can't open directory");
68 exit(FALSE);
69 }
70 while ((entry = readdir(dir)) != NULL) {
71 recursiveAction( entry->d_name, recursiveFlag, dereferenceFlag, fileAction, dirAction);
72 }
73 return( TRUE);
74}
75
76int ls_main(int argc, char **argv)
77{
78 if (argc <= 1) {
79 char buf[NAME_MAX];
80 getcwd( buf, NAME_MAX);
81 dirAction( buf);
82 }
83
84 /* peel of the "ls" */
85 argc--;
86 argv++;
87
88 /* Parse any options */
89 while (**argv == '-') {
90 while (*++(*argv)) switch (**argv) {
91 case '1':
92 oneFlag = TRUE;
93 break;
94 case 'a':
95 allFlag = TRUE;
96 break;
97 case 'd':
98 directoryFlag = TRUE;
99 break;
100 case 'l':
101 longFlag = TRUE;
102 break;
103 case 'F':
104 typeFlag = TRUE;
105 break;
106 case 'L':
107 dereferenceFlag = TRUE;
108 break;
109 case 'R':
110 recursiveFlag = TRUE;
111 break;
112 default:
113 fprintf(stderr, "Usage: %s\n", ls_usage);
114 exit( FALSE);
115 }
116 argc--;
117 argv++;
118 }
119
120 /* Ok, ready to do the deed now */
121 fprintf(stderr, "B\n");
122 while (argc-- > 1) {
123 fprintf(stderr, "C\n");
124 recursiveAction( *argv, recursiveFlag, dereferenceFlag, fileAction, dirAction);
125 }
126 exit(TRUE);
127}
128
129
130
131#else
132
133
Eric Andersencc8ed391999-10-05 16:24:54 +0000134#include "internal.h"
135/*
136 * tiny-ls.c version 0.1.0: A minimalist 'ls'
137 * Copyright (C) 1996 Brian Candler <B.Candler@pobox.com>
138 *
139 * This program is free software; you can redistribute it and/or modify
140 * it under the terms of the GNU General Public License as published by
141 * the Free Software Foundation; either version 2 of the License, or
142 * (at your option) any later version.
143 *
144 * This program is distributed in the hope that it will be useful,
145 * but WITHOUT ANY WARRANTY; without even the implied warranty of
146 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
147 * GNU General Public License for more details.
148 *
149 * You should have received a copy of the GNU General Public License
150 * along with this program; if not, write to the Free Software
151 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
152 */
153
154/*
155 * To achieve a small memory footprint, this version of 'ls' doesn't do any
156 * file sorting, and only has the most essential command line switches
157 * (i.e. the ones I couldn't live without :-) All features which involve
158 * linking in substantial chunks of libc can be disabled.
159 *
160 * Although I don't really want to add new features to this program to
161 * keep it small, I *am* interested to receive bug fixes and ways to make
162 * it more portable.
163 *
164 * KNOWN BUGS:
165 * 1. messy output if you mix files and directories on the command line
166 * 2. ls -l of a directory doesn't give "total <blocks>" header
167 * 3. ls of a symlink to a directory doesn't list directory contents
168 * 4. hidden files can make column width too large
169 * NON-OPTIMAL BEHAVIOUR:
170 * 1. autowidth reads directories twice
171 * 2. if you do a short directory listing without filetype characters
172 * appended, there's no need to stat each one
173 * PORTABILITY:
174 * 1. requires lstat (BSD) - how do you do it without?
175 */
176
177#define FEATURE_USERNAME /* show username/groupnames (libc6 uses NSS) */
178#define FEATURE_TIMESTAMPS /* show file timestamps */
179#define FEATURE_AUTOWIDTH /* calculate terminal & column widths */
180#define FEATURE_FILETYPECHAR /* enable -p and -F */
181
182#undef OP_BUF_SIZE 1024 /* leave undefined for unbuffered output */
183
184#define TERMINAL_WIDTH 80 /* use 79 if your terminal has linefold bug */
185#define COLUMN_WIDTH 14 /* default if AUTOWIDTH not defined */
186#define COLUMN_GAP 2 /* includes the file type char, if present */
187
188/************************************************************************/
189
190#define HAS_REWINDDIR
191
192#if 1 /* FIXME libc 6 */
193# include <linux/types.h>
194#else
195# include <sys/types.h>
196#endif
197#include <sys/stat.h>
198#include <stdio.h>
199#include <unistd.h>
200#include <dirent.h>
201#include <errno.h>
202#include <stdio.h>
203#ifdef FEATURE_USERNAME
204#include <pwd.h>
205#include <grp.h>
206#endif
207#ifdef FEATURE_TIMESTAMPS
208#include <time.h>
209#endif
210
211#define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
212#define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
213#ifdef FEATURE_FILETYPECHAR
214#define APPCHAR(mode) ("\0|\0\0/\0\0\0\0\0@\0=\0\0\0" [TYPEINDEX(mode)])
215#endif
216
217#ifndef MAJOR
218#define MAJOR(dev) (((dev)>>8)&0xff)
219#define MINOR(dev) ((dev)&0xff)
220#endif
221
222#define MODE1 "rwxrwxrwx"
223#define MODE0 "---------"
224#define SMODE1 "..s..s..t"
225#define SMODE0 "..S..S..T"
226
227/* The 9 mode bits to test */
228
229static const umode_t MBIT[] = {
230 S_IRUSR, S_IWUSR, S_IXUSR,
231 S_IRGRP, S_IWGRP, S_IXGRP,
232 S_IROTH, S_IWOTH, S_IXOTH
233};
234
235/* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
236
237static const umode_t SBIT[] = {
238 0, 0, S_ISUID,
239 0, 0, S_ISGID,
240 0, 0, S_ISVTX
241};
242
243#define FMT_AUTO 0
244#define FMT_LONG 1 /* one record per line, extended info */
245#define FMT_SINGLE 2 /* one record per line */
246#define FMT_ROWS 3 /* print across rows */
247#define FMT_COLUMNS 3 /* fill columns (same, since we don't sort) */
248
249#define TIME_MOD 0
250#define TIME_CHANGE 1
251#define TIME_ACCESS 2
252
253#define DISP_FTYPE 1 /* show character for file type */
254#define DISP_EXEC 2 /* show '*' if regular executable file */
255#define DISP_HIDDEN 4 /* show files starting . (except . and ..) */
256#define DISP_DOT 8 /* show . and .. */
257#define DISP_NUMERIC 16 /* numeric uid and gid */
258#define DISP_FULLTIME 32 /* show extended time display */
259#define DIR_NOLIST 64 /* show directory as itself, not contents */
260#define DISP_DIRNAME 128 /* show directory name (for internal use) */
261#define DIR_RECURSE 256 /* -R (not yet implemented) */
262
263static unsigned char display_fmt = FMT_AUTO;
264static unsigned short opts = 0;
265static unsigned short column = 0;
266
267#ifdef FEATURE_AUTOWIDTH
268static unsigned short terminal_width = 0, column_width = 0;
269#else
270#define terminal_width TERMINAL_WIDTH
271#define column_width COLUMN_WIDTH
272#endif
273
274#ifdef FEATURE_TIMESTAMPS
275static unsigned char time_fmt = TIME_MOD;
276#endif
277
278#define wr(data,len) fwrite(data, 1, len, stdout)
279
280static void writenum(long val, short minwidth)
281{
282 char scratch[20];
283
284 char *p = scratch + sizeof(scratch);
285 short len = 0;
286 short neg = (val < 0);
287
288 if (neg) val = -val;
289 do
290 *--p = (val % 10) + '0', len++, val /= 10;
291 while (val);
292 if (neg)
293 *--p = '-', len++;
294 while (len < minwidth)
295 *--p = ' ', len++;
296 wr(p, len);
297 column += len;
298}
299
300static void newline(void)
301{
302 if (column > 0) {
303 wr("\n", 1);
304 column = 0;
305 }
306}
307
308static void tab(short col)
309{
310 static const char spaces[] = " ";
311 #define nspaces ((sizeof spaces)-1) /* null terminator! */
312
313 short n = col - column;
314
315 if (n > 0) {
316 column = col;
317 while (n > nspaces) {
318 wr(spaces, nspaces);
319 n -= nspaces;
320 }
321 /* must be 1...(sizeof spaces) left */
322 wr(spaces, n);
323 }
324 #undef nspaces
325}
326
327#ifdef FEATURE_FILETYPECHAR
328static char append_char(umode_t mode)
329{
330 if (!(opts & DISP_FTYPE))
331 return '\0';
332 if ((opts & DISP_EXEC) && S_ISREG(mode) && (mode & (S_IXUSR|S_IXGRP|S_IXOTH)))
333 return '*';
334 return APPCHAR(mode);
335}
336#endif
337
338/**
339 **
340 ** Display a file or directory as a single item
341 ** (in either long or short format)
342 **
343 **/
344
345static void list_single(const char *name, struct stat *info)
346{
347 char scratch[20];
348 short len = strlen(name);
349#ifdef FEATURE_FILETYPECHAR
350 char append = append_char(info->st_mode);
351#endif
352
353 if (display_fmt == FMT_LONG) {
354 umode_t mode = info->st_mode;
355 int i;
356
357 scratch[0] = TYPECHAR(mode);
358 for (i=0; i<9; i++)
359 if (mode & SBIT[i])
360 scratch[i+1] = (mode & MBIT[i])
361 ? SMODE1[i]
362 : SMODE0[i];
363 else
364 scratch[i+1] = (mode & MBIT[i])
365 ? MODE1[i]
366 : MODE0[i];
367 newline();
368 wr(scratch, 10);
369 column=10;
370 writenum((long)info->st_nlink,(short)4);
371 fputs(" ", stdout);
372#ifdef FEATURE_USERNAME
373 if (!(opts & DISP_NUMERIC)) {
374 struct passwd *pw = getpwuid(info->st_uid);
375 if (pw)
376 fputs(pw->pw_name, stdout);
377 else
378 writenum((long)info->st_uid,(short)0);
379 } else
380#endif
381 writenum((long)info->st_uid,(short)0);
382 tab(24);
383#ifdef FEATURE_USERNAME
384 if (!(opts & DISP_NUMERIC)) {
385 struct group *gr = getgrgid(info->st_gid);
386 if (gr)
387 fputs(gr->gr_name, stdout);
388 else
389 writenum((long)info->st_gid,(short)0);
390 } else
391#endif
392 writenum((long)info->st_gid,(short)0);
393 tab(33);
394 if (S_ISBLK(mode) || S_ISCHR(mode)) {
395 writenum((long)MAJOR(info->st_rdev),(short)3);
396 fputs(", ", stdout);
397 writenum((long)MINOR(info->st_rdev),(short)3);
398 }
399 else
400 writenum((long)info->st_size,(short)8);
401 fputs(" ", stdout);
402#ifdef FEATURE_TIMESTAMPS
403 {
404 time_t cal;
405 char *string;
406
407 switch(time_fmt) {
408 case TIME_CHANGE:
409 cal=info->st_ctime; break;
410 case TIME_ACCESS:
411 cal=info->st_atime; break;
412 default:
413 cal=info->st_mtime; break;
414 }
415 string=ctime(&cal);
416 if (opts & DISP_FULLTIME)
417 wr(string,24);
418 else {
419 time_t age = time(NULL) - cal;
420 wr(string+4,7); /* mmm_dd_ */
421 if(age < 3600L*24*365/2 && age > -15*60)
422 /* hh:mm if less than 6 months old */
423 wr(string+11,5);
424 else
425 /* _yyyy otherwise */
426 wr(string+19,5);
427 }
428 wr(" ", 1);
429 }
430#else
431 fputs("--- -- ----- ", stdout);
432#endif
433 wr(name, len);
434 if (S_ISLNK(mode)) {
435 wr(" -> ", 4);
436 len = readlink(name, scratch, sizeof scratch);
437 if (len > 0) fwrite(scratch, 1, len, stdout);
438#ifdef FEATURE_FILETYPECHAR
439 /* show type of destination */
440 if (opts & DISP_FTYPE) {
441 if (!stat(name, info)) {
442 append = append_char(info->st_mode);
443 if (append)
444 fputc(append, stdout);
445 }
446 }
447#endif
448 }
449#ifdef FEATURE_FILETYPECHAR
450 else if (append)
451 wr(&append, 1);
452#endif
453 } else {
454 static short nexttab = 0;
455
456 /* sort out column alignment */
457 if (column == 0)
458 ; /* nothing to do */
459 else if (display_fmt == FMT_SINGLE)
460 newline();
461 else {
462 if (nexttab + column_width > terminal_width
463#ifndef FEATURE_AUTOWIDTH
464 || nexttab + len >= terminal_width
465#endif
466 )
467 newline();
468 else
469 tab(nexttab);
470 }
471 /* work out where next column starts */
472#ifdef FEATURE_AUTOWIDTH
473 /* we know the calculated width is big enough */
474 nexttab = column + column_width + COLUMN_GAP;
475#else
476 /* might cover more than one fixed-width column */
477 nexttab = column;
478 do
479 nexttab += column_width + COLUMN_GAP;
480 while (nexttab < (column + len + COLUMN_GAP));
481#endif
482 /* now write the data */
483 wr(name, len);
484 column = column + len;
485#ifdef FEATURE_FILETYPECHAR
486 if (append)
487 wr(&append, 1), column++;
488#endif
489 }
490}
491
492/**
493 **
494 ** List the given file or directory, expanding a directory
495 ** to show its contents if required
496 **
497 **/
498
499static int list_item(const char *name)
500{
501 struct stat info;
502 DIR *dir;
503 struct dirent *entry;
504 char fullname[MAXNAMLEN+1], *fnend;
505
506 if (lstat(name, &info))
507 goto listerr;
508
509 if (!S_ISDIR(info.st_mode) ||
510 (opts & DIR_NOLIST)) {
511 list_single(name, &info);
512 return 0;
513 }
514
515 /* Otherwise, it's a directory we want to list the contents of */
516
517 if (opts & DISP_DIRNAME) { /* identify the directory */
518 if (column)
519 wr("\n\n", 2), column = 0;
520 wr(name, strlen(name));
521 wr(":\n", 2);
522 }
523
524 dir = opendir(name);
525 if (!dir) goto listerr;
526#ifdef FEATURE_AUTOWIDTH
527 column_width = 0;
528 while ((entry = readdir(dir)) != NULL) {
529 short w = strlen(entry->d_name);
530 if (column_width < w)
531 column_width = w;
532 }
533#ifdef HAS_REWINDDIR
534 rewinddir(dir);
535#else
536 closedir(dir);
537 dir = opendir(name);
538 if (!dir) goto listerr;
539#endif
540#endif
541
542 /* List the contents */
543
544 strcpy(fullname,name); /* *** ignore '.' by itself */
545 fnend=fullname+strlen(fullname);
546 if (fnend[-1] != '/')
547 *fnend++ = '/';
548
549 while ((entry = readdir(dir)) != NULL) {
550 const char *en=entry->d_name;
551 if (en[0] == '.') {
552 if (!en[1] || (en[1] == '.' && !en[2])) { /* . or .. */
553 if (!(opts & DISP_DOT))
554 continue;
555 }
556 else if (!(opts & DISP_HIDDEN))
557 continue;
558 }
559 /* FIXME: avoid stat if not required */
560 strcpy(fnend, entry->d_name);
561 if (lstat(fullname, &info))
562 goto direrr; /* (shouldn't fail) */
563 list_single(entry->d_name, &info);
564 }
565 closedir(dir);
566 return 0;
567
568direrr:
569 closedir(dir);
570listerr:
571 newline();
Eric Andersen9d3aba71999-10-06 09:04:55 +0000572 perror(name);
Eric Andersencc8ed391999-10-05 16:24:54 +0000573 return 1;
574}
575
576const char ls_usage[] = "Usage: ls [-1a"
577#ifdef FEATURE_TIMESTAMPS
578 "c"
579#endif
580 "d"
581#ifdef FEATURE_TIMESTAMPS
582 "e"
583#endif
584 "ln"
585#ifdef FEATURE_FILETYPECHAR
586 "p"
587#endif
588#ifdef FEATURE_TIMESTAMPS
589 "u"
590#endif
591 "xAC"
592#ifdef FEATURE_FILETYPECHAR
593 "F"
594#endif
595#ifdef FEATURE_RECURSIVE
596 "R"
597#endif
598 "] [filenames...]\n";
599
600extern int
Eric Andersen9d3aba71999-10-06 09:04:55 +0000601ls_main(int argc, char * * argv)
Eric Andersencc8ed391999-10-05 16:24:54 +0000602{
603 int argi=1, i;
604
605 /* process options */
606 while (argi < argc && argv[argi][0] == '-') {
607 const char *p = &argv[argi][1];
608
609 if (!*p) goto print_usage_message; /* "-" by itself not allowed */
610 if (*p == '-') {
611 if (!p[1]) { /* "--" forces end of options */
612 argi++;
613 break;
614 }
615 /* it's a long option name - we don't support them */
616 goto print_usage_message;
617 }
618
619 while (*p)
620 switch (*p++) {
621 case 'l': display_fmt = FMT_LONG; break;
622 case '1': display_fmt = FMT_SINGLE; break;
623 case 'x': display_fmt = FMT_ROWS; break;
624 case 'C': display_fmt = FMT_COLUMNS; break;
625#ifdef FEATURE_FILETYPECHAR
626 case 'p': opts |= DISP_FTYPE; break;
627 case 'F': opts |= DISP_FTYPE|DISP_EXEC; break;
628#endif
629 case 'A': opts |= DISP_HIDDEN; break;
630 case 'a': opts |= DISP_HIDDEN|DISP_DOT; break;
631 case 'n': opts |= DISP_NUMERIC; break;
632 case 'd': opts |= DIR_NOLIST; break;
633#ifdef FEATURE_RECURSIVE
634 case 'R': opts |= DIR_RECURSE; break;
635#endif
636#ifdef FEATURE_TIMESTAMPS
637 case 'u': time_fmt = TIME_ACCESS; break;
638 case 'c': time_fmt = TIME_CHANGE; break;
639 case 'e': opts |= DISP_FULLTIME; break;
640#endif
641 default: goto print_usage_message;
642 }
643
644 argi++;
645 }
646
647 /* choose a display format */
648 if (display_fmt == FMT_AUTO)
649 display_fmt = isatty(STDOUT_FILENO) ? FMT_COLUMNS : FMT_SINGLE;
650 if (argi < argc - 1)
651 opts |= DISP_DIRNAME; /* 2 or more items? label directories */
652#ifdef FEATURE_AUTOWIDTH
653 /* could add a -w option and/or TIOCGWINSZ call */
654 if (terminal_width < 1) terminal_width = TERMINAL_WIDTH;
655
656 for (i = argi; i < argc; i++) {
657 int len = strlen(argv[i]);
658 if (column_width < len)
659 column_width = len;
660 }
661#endif
662
663 /* process files specified, or current directory if none */
664 i=0;
665 if (argi == argc)
666 i = list_item(".");
667 while (argi < argc)
668 i |= list_item(argv[argi++]);
669 newline();
670 return i;
671
672print_usage_message:
Eric Andersen9d3aba71999-10-06 09:04:55 +0000673 fprintf(stderr, "Usage: %s\n", ls_usage);
Eric Andersencc8ed391999-10-05 16:24:54 +0000674 return 1;
675}
Eric Andersen9d3aba71999-10-06 09:04:55 +0000676
677#endif