blob: 59ba35ecae80c4a3a9475c2b103f772e0b490e5d [file] [log] [blame]
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4#include <sys/types.h>
5#include <dirent.h>
6#include <errno.h>
7
8#include <sys/stat.h>
9#include <unistd.h>
10#include <time.h>
11
12#include <pwd.h>
13#include <grp.h>
14
15#include <linux/kdev_t.h>
David 'Digit' Turneraa2106b2010-06-04 10:44:56 -070016#include <limits.h>
17
18// dynamic arrays
19typedef struct {
20 int count;
21 int capacity;
22 void** items;
23} dynarray_t;
24
25#define DYNARRAY_INITIALIZER { 0, 0, NULL }
26
27static void dynarray_init( dynarray_t *a )
28{
29 a->count = a->capacity = 0;
30 a->items = NULL;
31}
32
33static void dynarray_reserve_more( dynarray_t *a, int count )
34{
35 int old_cap = a->capacity;
36 int new_cap = old_cap;
37 const int max_cap = INT_MAX/sizeof(void*);
38 void** new_items;
39 int new_count = a->count + count;
40
41 if (count <= 0)
42 return;
43
44 if (count > max_cap - a->count)
45 abort();
46
47 new_count = a->count + count;
48
49 while (new_cap < new_count) {
50 old_cap = new_cap;
51 new_cap += (new_cap >> 2) + 4;
52 if (new_cap < old_cap || new_cap > max_cap) {
53 new_cap = max_cap;
54 }
55 }
56 new_items = realloc(a->items, new_cap*sizeof(void*));
57 if (new_items == NULL)
58 abort();
59
60 a->items = new_items;
61 a->capacity = new_cap;
62}
63
64static void dynarray_append( dynarray_t *a, void* item )
65{
66 if (a->count >= a->capacity)
67 dynarray_reserve_more(a, 1);
68
69 a->items[a->count++] = item;
70}
71
72static void dynarray_done( dynarray_t *a )
73{
74 free(a->items);
75 a->items = NULL;
76 a->count = a->capacity = 0;
77}
78
79#define DYNARRAY_FOREACH_TYPE(_array,_item_type,_item,_stmnt) \
80 do { \
81 int _nn_##__LINE__ = 0; \
82 for (;_nn_##__LINE__ < (_array)->count; ++ _nn_##__LINE__) { \
83 _item_type _item = (_item_type)(_array)->items[_nn_##__LINE__]; \
84 _stmnt; \
85 } \
86 } while (0)
87
88#define DYNARRAY_FOREACH(_array,_item,_stmnt) \
89 DYNARRAY_FOREACH_TYPE(_array,void *,_item,_stmnt)
90
91// string arrays
92
93typedef dynarray_t strlist_t;
94
95#define STRLIST_INITIALIZER DYNARRAY_INITIALIZER
96
97#define STRLIST_FOREACH(_list,_string,_stmnt) \
98 DYNARRAY_FOREACH_TYPE(_list,char *,_string,_stmnt)
99
100static void strlist_init( strlist_t *list )
101{
102 dynarray_init(list);
103}
104
105static void strlist_append_b( strlist_t *list, const void* str, size_t slen )
106{
107 char *copy = malloc(slen+1);
108 memcpy(copy, str, slen);
109 copy[slen] = '\0';
110 dynarray_append(list, copy);
111}
112
113static void strlist_append_dup( strlist_t *list, const char *str)
114{
115 strlist_append_b(list, str, strlen(str));
116}
117
118static void strlist_done( strlist_t *list )
119{
120 STRLIST_FOREACH(list, string, free(string));
121 dynarray_done(list);
122}
123
124static int strlist_compare_strings(const void* a, const void* b)
125{
126 const char *sa = *(const char **)a;
127 const char *sb = *(const char **)b;
128 return strcmp(sa, sb);
129}
130
131static void strlist_sort( strlist_t *list )
132{
133 if (list->count > 0) {
134 qsort(list->items,
135 (size_t)list->count,
136 sizeof(void*),
137 strlist_compare_strings);
138 }
139}
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800140
141// bits for flags argument
Andy McFaddenb33d3412009-04-08 19:25:35 -0700142#define LIST_LONG (1 << 0)
143#define LIST_ALL (1 << 1)
144#define LIST_RECURSIVE (1 << 2)
145#define LIST_DIRECTORIES (1 << 3)
Andy McFadden327e6962009-08-18 11:10:03 -0700146#define LIST_SIZE (1 << 4)
Kenny Root40dac652011-07-13 09:14:33 -0700147#define LIST_CLASSIFY (1 << 6)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800148
149// fwd
150static int listpath(const char *name, int flags);
151
152static char mode2kind(unsigned mode)
153{
154 switch(mode & S_IFMT){
155 case S_IFSOCK: return 's';
156 case S_IFLNK: return 'l';
157 case S_IFREG: return '-';
158 case S_IFDIR: return 'd';
159 case S_IFBLK: return 'b';
160 case S_IFCHR: return 'c';
161 case S_IFIFO: return 'p';
162 default: return '?';
163 }
164}
165
166static void mode2str(unsigned mode, char *out)
167{
168 *out++ = mode2kind(mode);
169
170 *out++ = (mode & 0400) ? 'r' : '-';
171 *out++ = (mode & 0200) ? 'w' : '-';
172 if(mode & 04000) {
173 *out++ = (mode & 0100) ? 's' : 'S';
174 } else {
175 *out++ = (mode & 0100) ? 'x' : '-';
176 }
177 *out++ = (mode & 040) ? 'r' : '-';
178 *out++ = (mode & 020) ? 'w' : '-';
179 if(mode & 02000) {
180 *out++ = (mode & 010) ? 's' : 'S';
181 } else {
182 *out++ = (mode & 010) ? 'x' : '-';
183 }
184 *out++ = (mode & 04) ? 'r' : '-';
185 *out++ = (mode & 02) ? 'w' : '-';
186 if(mode & 01000) {
187 *out++ = (mode & 01) ? 't' : 'T';
188 } else {
189 *out++ = (mode & 01) ? 'x' : '-';
190 }
191 *out = 0;
192}
193
194static void user2str(unsigned uid, char *out)
195{
196 struct passwd *pw = getpwuid(uid);
197 if(pw) {
198 strcpy(out, pw->pw_name);
199 } else {
200 sprintf(out, "%d", uid);
201 }
202}
203
204static void group2str(unsigned gid, char *out)
205{
206 struct group *gr = getgrgid(gid);
207 if(gr) {
208 strcpy(out, gr->gr_name);
209 } else {
210 sprintf(out, "%d", gid);
211 }
212}
213
Andy McFadden9feee022009-09-27 15:13:56 -0700214static int show_total_size(const char *dirname, DIR *d, int flags)
215{
216 struct dirent *de;
217 char tmp[1024];
218 struct stat s;
219 int sum = 0;
220
221 /* run through the directory and sum up the file block sizes */
222 while ((de = readdir(d)) != 0) {
223 if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
224 continue;
225 if (de->d_name[0] == '.' && (flags & LIST_ALL) == 0)
226 continue;
227
228 if (strcmp(dirname, "/") == 0)
229 snprintf(tmp, sizeof(tmp), "/%s", de->d_name);
230 else
231 snprintf(tmp, sizeof(tmp), "%s/%s", dirname, de->d_name);
232
233 if (lstat(tmp, &s) < 0) {
234 fprintf(stderr, "stat failed on %s: %s\n", tmp, strerror(errno));
235 rewinddir(d);
236 return -1;
237 }
238
239 sum += s.st_blocks / 2;
240 }
241
242 printf("total %d\n", sum);
243 rewinddir(d);
244 return 0;
245}
246
247static int listfile_size(const char *path, const char *filename, int flags)
Andy McFadden327e6962009-08-18 11:10:03 -0700248{
249 struct stat s;
250
Andy McFadden9feee022009-09-27 15:13:56 -0700251 if (lstat(path, &s) < 0) {
252 fprintf(stderr, "lstat '%s' failed: %s\n", path, strerror(errno));
Andy McFadden327e6962009-08-18 11:10:03 -0700253 return -1;
Andy McFadden9feee022009-09-27 15:13:56 -0700254 }
Andy McFadden327e6962009-08-18 11:10:03 -0700255
256 /* blocks are 512 bytes, we want output to be KB */
Kenny Root40dac652011-07-13 09:14:33 -0700257 if ((flags & LIST_SIZE) != 0) {
258 printf("%lld ", s.st_blocks / 2);
259 }
260
261 if ((flags & LIST_CLASSIFY) != 0) {
262 char filetype = mode2kind(s.st_mode);
263 if (filetype != 'l') {
264 printf("%c ", filetype);
265 } else {
266 struct stat link_dest;
267 if (!stat(path, &link_dest)) {
268 printf("l%c ", mode2kind(link_dest.st_mode));
269 } else {
270 fprintf(stderr, "stat '%s' failed: %s\n", path, strerror(errno));
271 printf("l? ");
272 }
273 }
274 }
275
276 printf("%s\n", filename);
277
Andy McFadden327e6962009-08-18 11:10:03 -0700278 return 0;
279}
280
281static int listfile_long(const char *path, int flags)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800282{
283 struct stat s;
284 char date[32];
285 char mode[16];
286 char user[16];
287 char group[16];
288 const char *name;
289
290 /* name is anything after the final '/', or the whole path if none*/
291 name = strrchr(path, '/');
292 if(name == 0) {
293 name = path;
294 } else {
295 name++;
296 }
297
298 if(lstat(path, &s) < 0) {
299 return -1;
300 }
301
302 mode2str(s.st_mode, mode);
303 user2str(s.st_uid, user);
304 group2str(s.st_gid, group);
305
306 strftime(date, 32, "%Y-%m-%d %H:%M", localtime((const time_t*)&s.st_mtime));
307 date[31] = 0;
308
309// 12345678901234567890123456789012345678901234567890123456789012345678901234567890
310// MMMMMMMM UUUUUUUU GGGGGGGGG XXXXXXXX YYYY-MM-DD HH:MM NAME (->LINK)
311
312 switch(s.st_mode & S_IFMT) {
313 case S_IFBLK:
314 case S_IFCHR:
315 printf("%s %-8s %-8s %3d, %3d %s %s\n",
316 mode, user, group,
317 (int) MAJOR(s.st_rdev), (int) MINOR(s.st_rdev),
318 date, name);
319 break;
320 case S_IFREG:
Kenny Rooteb421702010-06-25 09:08:05 -0700321 printf("%s %-8s %-8s %8lld %s %s\n",
322 mode, user, group, s.st_size, date, name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800323 break;
324 case S_IFLNK: {
325 char linkto[256];
326 int len;
327
328 len = readlink(path, linkto, 256);
329 if(len < 0) return -1;
330
331 if(len > 255) {
332 linkto[252] = '.';
333 linkto[253] = '.';
334 linkto[254] = '.';
335 linkto[255] = 0;
336 } else {
337 linkto[len] = 0;
338 }
339
340 printf("%s %-8s %-8s %s %s -> %s\n",
341 mode, user, group, date, name, linkto);
342 break;
343 }
344 default:
345 printf("%s %-8s %-8s %s %s\n",
346 mode, user, group, date, name);
347
348 }
349 return 0;
350}
351
Andy McFadden327e6962009-08-18 11:10:03 -0700352static int listfile(const char *dirname, const char *filename, int flags)
353{
Kenny Root40dac652011-07-13 09:14:33 -0700354 if ((flags & (LIST_LONG | LIST_SIZE | LIST_CLASSIFY)) == 0) {
Andy McFadden327e6962009-08-18 11:10:03 -0700355 printf("%s\n", filename);
356 return 0;
357 }
358
359 char tmp[4096];
360 const char* pathname = filename;
361
362 if (dirname != NULL) {
363 snprintf(tmp, sizeof(tmp), "%s/%s", dirname, filename);
364 pathname = tmp;
365 } else {
366 pathname = filename;
367 }
368
369 if ((flags & LIST_LONG) != 0) {
370 return listfile_long(pathname, flags);
371 } else /*((flags & LIST_SIZE) != 0)*/ {
Andy McFadden9feee022009-09-27 15:13:56 -0700372 return listfile_size(pathname, filename, flags);
Andy McFadden327e6962009-08-18 11:10:03 -0700373 }
374}
375
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800376static int listdir(const char *name, int flags)
377{
378 char tmp[4096];
379 DIR *d;
380 struct dirent *de;
David 'Digit' Turneraa2106b2010-06-04 10:44:56 -0700381 strlist_t files = STRLIST_INITIALIZER;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800382
383 d = opendir(name);
384 if(d == 0) {
385 fprintf(stderr, "opendir failed, %s\n", strerror(errno));
386 return -1;
387 }
388
Andy McFadden9feee022009-09-27 15:13:56 -0700389 if ((flags & LIST_SIZE) != 0) {
390 show_total_size(name, d, flags);
391 }
392
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800393 while((de = readdir(d)) != 0){
394 if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) continue;
395 if(de->d_name[0] == '.' && (flags & LIST_ALL) == 0) continue;
Andy McFadden327e6962009-08-18 11:10:03 -0700396
David 'Digit' Turneraa2106b2010-06-04 10:44:56 -0700397 strlist_append_dup(&files, de->d_name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800398 }
399
David 'Digit' Turneraa2106b2010-06-04 10:44:56 -0700400 strlist_sort(&files);
401 STRLIST_FOREACH(&files, filename, listfile(name, filename, flags));
402 strlist_done(&files);
403
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800404 if (flags & LIST_RECURSIVE) {
David 'Digit' Turneraa2106b2010-06-04 10:44:56 -0700405 strlist_t subdirs = STRLIST_INITIALIZER;
406
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800407 rewinddir(d);
408
409 while ((de = readdir(d)) != 0) {
410 struct stat s;
411 int err;
412
413 if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
414 continue;
415 if (de->d_name[0] == '.' && (flags & LIST_ALL) == 0)
416 continue;
417
Andy McFadden327e6962009-08-18 11:10:03 -0700418 if (!strcmp(name, "/"))
419 snprintf(tmp, sizeof(tmp), "/%s", de->d_name);
420 else
421 snprintf(tmp, sizeof(tmp), "%s/%s", name, de->d_name);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800422
423 /*
424 * If the name ends in a '/', use stat() so we treat it like a
425 * directory even if it's a symlink.
426 */
427 if (tmp[strlen(tmp)-1] == '/')
428 err = stat(tmp, &s);
429 else
430 err = lstat(tmp, &s);
431
432 if (err < 0) {
433 perror(tmp);
434 closedir(d);
435 return -1;
436 }
437
438 if (S_ISDIR(s.st_mode)) {
David 'Digit' Turneraa2106b2010-06-04 10:44:56 -0700439 strlist_append_dup(&subdirs, tmp);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800440 }
441 }
David 'Digit' Turneraa2106b2010-06-04 10:44:56 -0700442 strlist_sort(&subdirs);
443 STRLIST_FOREACH(&subdirs, path, {
444 printf("\n%s:\n", path);
445 listdir(path, flags);
446 });
447 strlist_done(&subdirs);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800448 }
449
450 closedir(d);
451 return 0;
452}
453
454static int listpath(const char *name, int flags)
455{
456 struct stat s;
457 int err;
458
459 /*
460 * If the name ends in a '/', use stat() so we treat it like a
461 * directory even if it's a symlink.
462 */
463 if (name[strlen(name)-1] == '/')
464 err = stat(name, &s);
465 else
466 err = lstat(name, &s);
467
468 if (err < 0) {
469 perror(name);
470 return -1;
471 }
472
Andy McFaddenb33d3412009-04-08 19:25:35 -0700473 if ((flags & LIST_DIRECTORIES) == 0 && S_ISDIR(s.st_mode)) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800474 if (flags & LIST_RECURSIVE)
475 printf("\n%s:\n", name);
476 return listdir(name, flags);
477 } else {
Andy McFadden327e6962009-08-18 11:10:03 -0700478 /* yeah this calls stat() again*/
479 return listfile(NULL, name, flags);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800480 }
481}
482
483int ls_main(int argc, char **argv)
484{
485 int flags = 0;
486 int listed = 0;
487
488 if(argc > 1) {
489 int i;
490 int err = 0;
David 'Digit' Turneraa2106b2010-06-04 10:44:56 -0700491 strlist_t files = STRLIST_INITIALIZER;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800492
493 for (i = 1; i < argc; i++) {
David 'Digit' Turneraa2106b2010-06-04 10:44:56 -0700494 if (argv[i][0] == '-') {
495 /* an option ? */
496 const char *arg = argv[i]+1;
497 while (arg[0]) {
498 switch (arg[0]) {
499 case 'l': flags |= LIST_LONG; break;
500 case 's': flags |= LIST_SIZE; break;
501 case 'R': flags |= LIST_RECURSIVE; break;
502 case 'd': flags |= LIST_DIRECTORIES; break;
503 case 'a': flags |= LIST_ALL; break;
Kenny Root40dac652011-07-13 09:14:33 -0700504 case 'F': flags |= LIST_CLASSIFY; break;
David 'Digit' Turneraa2106b2010-06-04 10:44:56 -0700505 default:
506 fprintf(stderr, "%s: Unknown option '-%c'. Aborting.\n", "ls", arg[0]);
507 exit(1);
508 }
509 arg++;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800510 }
David 'Digit' Turneraa2106b2010-06-04 10:44:56 -0700511 } else {
512 /* not an option ? */
513 strlist_append_dup(&files, argv[i]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800514 }
515 }
516
David 'Digit' Turneraa2106b2010-06-04 10:44:56 -0700517 if (files.count > 0) {
518 STRLIST_FOREACH(&files, path, {
519 if (listpath(path, flags) != 0) {
520 err = EXIT_FAILURE;
521 }
522 });
523 strlist_done(&files);
524 return err;
525 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800526 }
527
528 // list working directory if no files or directories were specified
529 return listpath(".", flags);
530}