ls.c revision 0b1ff6be08844c541e36fd735b41990453582ec1
1#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> 16#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} 140 141// bits for flags argument 142#define LIST_LONG (1 << 0) 143#define LIST_ALL (1 << 1) 144#define LIST_RECURSIVE (1 << 2) 145#define LIST_DIRECTORIES (1 << 3) 146#define LIST_SIZE (1 << 4) 147 148// fwd 149static int listpath(const char *name, int flags); 150 151static char mode2kind(unsigned mode) 152{ 153 switch(mode & S_IFMT){ 154 case S_IFSOCK: return 's'; 155 case S_IFLNK: return 'l'; 156 case S_IFREG: return '-'; 157 case S_IFDIR: return 'd'; 158 case S_IFBLK: return 'b'; 159 case S_IFCHR: return 'c'; 160 case S_IFIFO: return 'p'; 161 default: return '?'; 162 } 163} 164 165static void mode2str(unsigned mode, char *out) 166{ 167 *out++ = mode2kind(mode); 168 169 *out++ = (mode & 0400) ? 'r' : '-'; 170 *out++ = (mode & 0200) ? 'w' : '-'; 171 if(mode & 04000) { 172 *out++ = (mode & 0100) ? 's' : 'S'; 173 } else { 174 *out++ = (mode & 0100) ? 'x' : '-'; 175 } 176 *out++ = (mode & 040) ? 'r' : '-'; 177 *out++ = (mode & 020) ? 'w' : '-'; 178 if(mode & 02000) { 179 *out++ = (mode & 010) ? 's' : 'S'; 180 } else { 181 *out++ = (mode & 010) ? 'x' : '-'; 182 } 183 *out++ = (mode & 04) ? 'r' : '-'; 184 *out++ = (mode & 02) ? 'w' : '-'; 185 if(mode & 01000) { 186 *out++ = (mode & 01) ? 't' : 'T'; 187 } else { 188 *out++ = (mode & 01) ? 'x' : '-'; 189 } 190 *out = 0; 191} 192 193static void user2str(unsigned uid, char *out) 194{ 195 struct passwd *pw = getpwuid(uid); 196 if(pw) { 197 strcpy(out, pw->pw_name); 198 } else { 199 sprintf(out, "%d", uid); 200 } 201} 202 203static void group2str(unsigned gid, char *out) 204{ 205 struct group *gr = getgrgid(gid); 206 if(gr) { 207 strcpy(out, gr->gr_name); 208 } else { 209 sprintf(out, "%d", gid); 210 } 211} 212 213static int show_total_size(const char *dirname, DIR *d, int flags) 214{ 215 struct dirent *de; 216 char tmp[1024]; 217 struct stat s; 218 int sum = 0; 219 220 /* run through the directory and sum up the file block sizes */ 221 while ((de = readdir(d)) != 0) { 222 if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0) 223 continue; 224 if (de->d_name[0] == '.' && (flags & LIST_ALL) == 0) 225 continue; 226 227 if (strcmp(dirname, "/") == 0) 228 snprintf(tmp, sizeof(tmp), "/%s", de->d_name); 229 else 230 snprintf(tmp, sizeof(tmp), "%s/%s", dirname, de->d_name); 231 232 if (lstat(tmp, &s) < 0) { 233 fprintf(stderr, "stat failed on %s: %s\n", tmp, strerror(errno)); 234 rewinddir(d); 235 return -1; 236 } 237 238 sum += s.st_blocks / 2; 239 } 240 241 printf("total %d\n", sum); 242 rewinddir(d); 243 return 0; 244} 245 246static int listfile_size(const char *path, const char *filename, int flags) 247{ 248 struct stat s; 249 250 if (lstat(path, &s) < 0) { 251 fprintf(stderr, "lstat '%s' failed: %s\n", path, strerror(errno)); 252 return -1; 253 } 254 255 /* blocks are 512 bytes, we want output to be KB */ 256 printf("%lld %s\n", s.st_blocks / 2, filename); 257 return 0; 258} 259 260static int listfile_long(const char *path, int flags) 261{ 262 struct stat s; 263 char date[32]; 264 char mode[16]; 265 char user[16]; 266 char group[16]; 267 const char *name; 268 269 /* name is anything after the final '/', or the whole path if none*/ 270 name = strrchr(path, '/'); 271 if(name == 0) { 272 name = path; 273 } else { 274 name++; 275 } 276 277 if(lstat(path, &s) < 0) { 278 return -1; 279 } 280 281 mode2str(s.st_mode, mode); 282 user2str(s.st_uid, user); 283 group2str(s.st_gid, group); 284 285 strftime(date, 32, "%Y-%m-%d %H:%M", localtime((const time_t*)&s.st_mtime)); 286 date[31] = 0; 287 288// 12345678901234567890123456789012345678901234567890123456789012345678901234567890 289// MMMMMMMM UUUUUUUU GGGGGGGGG XXXXXXXX YYYY-MM-DD HH:MM NAME (->LINK) 290 291 switch(s.st_mode & S_IFMT) { 292 case S_IFBLK: 293 case S_IFCHR: 294 printf("%s %-8s %-8s %3d, %3d %s %s\n", 295 mode, user, group, 296 (int) MAJOR(s.st_rdev), (int) MINOR(s.st_rdev), 297 date, name); 298 break; 299 case S_IFREG: 300 printf("%s %-8s %-8s %8lld %s %s\n", 301 mode, user, group, s.st_size, date, name); 302 break; 303 case S_IFLNK: { 304 char linkto[256]; 305 int len; 306 307 len = readlink(path, linkto, 256); 308 if(len < 0) return -1; 309 310 if(len > 255) { 311 linkto[252] = '.'; 312 linkto[253] = '.'; 313 linkto[254] = '.'; 314 linkto[255] = 0; 315 } else { 316 linkto[len] = 0; 317 } 318 319 printf("%s %-8s %-8s %s %s -> %s\n", 320 mode, user, group, date, name, linkto); 321 break; 322 } 323 default: 324 printf("%s %-8s %-8s %s %s\n", 325 mode, user, group, date, name); 326 327 } 328 return 0; 329} 330 331static int listfile(const char *dirname, const char *filename, int flags) 332{ 333 if ((flags & (LIST_LONG | LIST_SIZE)) == 0) { 334 printf("%s\n", filename); 335 return 0; 336 } 337 338 char tmp[4096]; 339 const char* pathname = filename; 340 341 if (dirname != NULL) { 342 snprintf(tmp, sizeof(tmp), "%s/%s", dirname, filename); 343 pathname = tmp; 344 } else { 345 pathname = filename; 346 } 347 348 if ((flags & LIST_LONG) != 0) { 349 return listfile_long(pathname, flags); 350 } else /*((flags & LIST_SIZE) != 0)*/ { 351 return listfile_size(pathname, filename, flags); 352 } 353} 354 355static int listdir(const char *name, int flags) 356{ 357 char tmp[4096]; 358 DIR *d; 359 struct dirent *de; 360 strlist_t files = STRLIST_INITIALIZER; 361 362 d = opendir(name); 363 if(d == 0) { 364 fprintf(stderr, "opendir failed, %s\n", strerror(errno)); 365 return -1; 366 } 367 368 if ((flags & LIST_SIZE) != 0) { 369 show_total_size(name, d, flags); 370 } 371 372 while((de = readdir(d)) != 0){ 373 if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) continue; 374 if(de->d_name[0] == '.' && (flags & LIST_ALL) == 0) continue; 375 376 strlist_append_dup(&files, de->d_name); 377 } 378 379 strlist_sort(&files); 380 STRLIST_FOREACH(&files, filename, listfile(name, filename, flags)); 381 strlist_done(&files); 382 383 if (flags & LIST_RECURSIVE) { 384 strlist_t subdirs = STRLIST_INITIALIZER; 385 386 rewinddir(d); 387 388 while ((de = readdir(d)) != 0) { 389 struct stat s; 390 int err; 391 392 if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) 393 continue; 394 if (de->d_name[0] == '.' && (flags & LIST_ALL) == 0) 395 continue; 396 397 if (!strcmp(name, "/")) 398 snprintf(tmp, sizeof(tmp), "/%s", de->d_name); 399 else 400 snprintf(tmp, sizeof(tmp), "%s/%s", name, de->d_name); 401 402 /* 403 * If the name ends in a '/', use stat() so we treat it like a 404 * directory even if it's a symlink. 405 */ 406 if (tmp[strlen(tmp)-1] == '/') 407 err = stat(tmp, &s); 408 else 409 err = lstat(tmp, &s); 410 411 if (err < 0) { 412 perror(tmp); 413 closedir(d); 414 return -1; 415 } 416 417 if (S_ISDIR(s.st_mode)) { 418 strlist_append_dup(&subdirs, tmp); 419 } 420 } 421 strlist_sort(&subdirs); 422 STRLIST_FOREACH(&subdirs, path, { 423 printf("\n%s:\n", path); 424 listdir(path, flags); 425 }); 426 strlist_done(&subdirs); 427 } 428 429 closedir(d); 430 return 0; 431} 432 433static int listpath(const char *name, int flags) 434{ 435 struct stat s; 436 int err; 437 438 /* 439 * If the name ends in a '/', use stat() so we treat it like a 440 * directory even if it's a symlink. 441 */ 442 if (name[strlen(name)-1] == '/') 443 err = stat(name, &s); 444 else 445 err = lstat(name, &s); 446 447 if (err < 0) { 448 perror(name); 449 return -1; 450 } 451 452 if ((flags & LIST_DIRECTORIES) == 0 && S_ISDIR(s.st_mode)) { 453 if (flags & LIST_RECURSIVE) 454 printf("\n%s:\n", name); 455 return listdir(name, flags); 456 } else { 457 /* yeah this calls stat() again*/ 458 return listfile(NULL, name, flags); 459 } 460} 461 462int ls_main(int argc, char **argv) 463{ 464 int flags = 0; 465 int listed = 0; 466 467 if(argc > 1) { 468 int i; 469 int err = 0; 470 strlist_t files = STRLIST_INITIALIZER; 471 472 for (i = 1; i < argc; i++) { 473 if (argv[i][0] == '-') { 474 /* an option ? */ 475 const char *arg = argv[i]+1; 476 while (arg[0]) { 477 switch (arg[0]) { 478 case 'l': flags |= LIST_LONG; break; 479 case 's': flags |= LIST_SIZE; break; 480 case 'R': flags |= LIST_RECURSIVE; break; 481 case 'd': flags |= LIST_DIRECTORIES; break; 482 case 'a': flags |= LIST_ALL; break; 483 default: 484 fprintf(stderr, "%s: Unknown option '-%c'. Aborting.\n", "ls", arg[0]); 485 exit(1); 486 } 487 arg++; 488 } 489 } else { 490 /* not an option ? */ 491 strlist_append_dup(&files, argv[i]); 492 } 493 } 494 495 if (files.count > 0) { 496 STRLIST_FOREACH(&files, path, { 497 if (listpath(path, flags) != 0) { 498 err = EXIT_FAILURE; 499 } 500 }); 501 strlist_done(&files); 502 return err; 503 } 504 } 505 506 // list working directory if no files or directories were specified 507 return listpath(".", flags); 508} 509