lr.c 42.9 KB
Newer Older
Christian Neukirchen's avatar
Christian Neukirchen committed
1 2
/* lr - a better recursive ls/find */

3
/*
Leah Neukirchen's avatar
Leah Neukirchen committed
4
 * Copyright (C) 2015-2017 Leah Neukirchen <purl.org/net/chneukirchen>
Christian Neukirchen's avatar
Christian Neukirchen committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
 * Parts of code derived from musl libc, which is
 * Copyright (C) 2005-2014 Rich Felker, et al.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
27 28

/*
Christian Neukirchen's avatar
Christian Neukirchen committed
29
##% gcc -Os -Wall -g -o $STEM $FILE -Wno-switch -Wextra -Wwrite-strings
30 31
*/

Christian Neukirchen's avatar
Christian Neukirchen committed
32
#define _GNU_SOURCE
33 34 35 36 37

#include <sys/param.h>
#include <sys/stat.h>
#include <sys/types.h>

38
#ifdef __linux__
Christian Neukirchen's avatar
Christian Neukirchen committed
39
#include <sys/xattr.h>
40 41
#endif

42 43 44
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
Christian Neukirchen's avatar
Christian Neukirchen committed
45
#include <fnmatch.h>
Christian Neukirchen's avatar
Christian Neukirchen committed
46
#include <grp.h>
47
#include <limits.h>
Leah Neukirchen's avatar
Leah Neukirchen committed
48
#include <locale.h>
49
#include <paths.h>
Christian Neukirchen's avatar
Christian Neukirchen committed
50
#include <pwd.h>
Christian Neukirchen's avatar
Christian Neukirchen committed
51
#include <regex.h>
52
#include <search.h>
53
#include <stdarg.h>
54
#include <stdint.h>
55 56 57 58 59 60
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

61 62 63 64 65 66 67 68 69 70
#ifdef __has_include
  #if __has_include(<stdnoreturn.h>)
    #include <stdnoreturn.h>
  #else
    #define noreturn /**/
  #endif
#else
  #define noreturn /**/
#endif

71 72 73 74 75
/* For Solaris. */
#if !defined(FNM_CASEFOLD) && defined(FNM_IGNORECASE)
#define FNM_CASEFOLD FNM_IGNORECASE
#endif

76 77
static int Cflag;
static char *Cflags[64];
78
static int Gflag;
79
static int Dflag;
Christian Neukirchen's avatar
Christian Neukirchen committed
80 81
static int Hflag;
static int Lflag;
82
static int Qflag;
Christian Neukirchen's avatar
Christian Neukirchen committed
83
static int Uflag;
84
static int hflag;
Christian Neukirchen's avatar
Christian Neukirchen committed
85 86
static int lflag;
static int sflag;
87
static int xflag;
88
static char Tflag = 'T';
Christian Neukirchen's avatar
Christian Neukirchen committed
89 90 91 92 93 94

static char *argv0;
static char *format;
static char *ordering;
static struct expr *expr;
static void *root = NULL; // tree
95
static int prune;
96
static size_t prefixl;
97
static char input_delim = '\n';
98
static int current_color;
99
static int status;
100

Christian Neukirchen's avatar
Christian Neukirchen committed
101 102 103
static char default_ordering[] = "n";
static char default_format[] = "%p\\n";
static char type_format[] = "%p%F\\n";
104
static char long_format[] = "%M%x %n %u %g %s %\324F %\324R %p%F%l\n";
Christian Neukirchen's avatar
Christian Neukirchen committed
105
static char zero_format[] = "%p\\0";
106
static char stat_format[] = "%D %i %M %n %u %g %R %s \"%Ab %Ad %AT %AY\" \"%Tb %Td %TT %TY\" \"%Cb %Cd %CT %CY\" %b %p\n";
Christian Neukirchen's avatar
Christian Neukirchen committed
107

Christian Neukirchen's avatar
Christian Neukirchen committed
108 109
static void *users;
static void *groups;
110 111
static void *filesystems;
static int scanned_filesystems;
112 113 114 115 116 117

struct idmap {
	long id;
	char *name;
};

118 119 120
static int need_group;
static int need_user;
static int need_fstype;
121
static int need_xattr;
122 123 124 125 126 127 128

static dev_t maxdev;
static ino_t maxino;
static nlink_t maxnlink;
static uid_t maxuid;
static gid_t maxgid;
static dev_t maxrdev;
Christian Neukirchen's avatar
Christian Neukirchen committed
129
static off_t maxsize;
130
static blkcnt_t maxblocks;
131
static unsigned int maxxattr;
132 133

static int maxdepth;
134
static int uwid, gwid, fwid;
135

136
static time_t now;
137
static mode_t default_mask;
138

139 140
struct fileinfo {
	char *fpath;
141
	size_t prefixl;
142
	int depth;
143
	ino_t entries;
144
	struct stat sb;
145
	off_t total;
146
	char xattr[4];
147
	int color;
148 149 150
};

enum op {
Christian Neukirchen's avatar
Christian Neukirchen committed
151
	EXPR_OR = 1,
152 153 154 155 156
	EXPR_AND,
	EXPR_NOT,
	EXPR_LT,
	EXPR_LE,
	EXPR_EQ,
Christian Neukirchen's avatar
Christian Neukirchen committed
157
	EXPR_NEQ,
158 159
	EXPR_GE,
	EXPR_GT,
Christian Neukirchen's avatar
Christian Neukirchen committed
160 161
	EXPR_STREQ,
	EXPR_STREQI,
162
	EXPR_GLOB,
Christian Neukirchen's avatar
Christian Neukirchen committed
163
	EXPR_GLOBI,
Christian Neukirchen's avatar
Christian Neukirchen committed
164 165
	EXPR_REGEX,
	EXPR_REGEXI,
166
	EXPR_PRUNE,
167
	EXPR_PRINT,
168
	EXPR_COLOR,
Christian Neukirchen's avatar
Christian Neukirchen committed
169
	EXPR_TYPE,
170
	EXPR_ALLSET,
171
	EXPR_ANYSET,
172
	EXPR_CHMOD,
173 174 175
};

enum prop {
Christian Neukirchen's avatar
Christian Neukirchen committed
176
	PROP_ATIME = 1,
177 178 179
	PROP_CTIME,
	PROP_DEPTH,
	PROP_DEV,
180
	PROP_ENTRIES,
181
	PROP_FSTYPE,
182 183
	PROP_GID,
	PROP_GROUP,
184 185 186 187 188 189
	PROP_INODE,
	PROP_LINKS,
	PROP_MODE,
	PROP_MTIME,
	PROP_NAME,
	PROP_PATH,
Christian Neukirchen's avatar
Christian Neukirchen committed
190
	PROP_RDEV,
191
	PROP_SIZE,
192 193
	PROP_TARGET,
	PROP_TOTAL,
194 195
	PROP_UID,
	PROP_USER,
196
	PROP_XATTR,
Christian Neukirchen's avatar
Christian Neukirchen committed
197 198 199 200 201 202 203 204 205 206
};

enum filetype {
	TYPE_BLOCK = 'b',
	TYPE_CHAR = 'c',
	TYPE_DIR = 'd',
	TYPE_FIFO = 'p',
	TYPE_REGULAR = 'f',
	TYPE_SOCKET = 's',
	TYPE_SYMLINK = 'l',
207 208 209 210 211 212
};

struct expr {
	enum op op;
	union {
		enum prop prop;
Christian Neukirchen's avatar
Christian Neukirchen committed
213
		enum filetype filetype;
214 215
		struct expr *expr;
		char *string;
216
		int64_t num;
Christian Neukirchen's avatar
Christian Neukirchen committed
217
		regex_t *regex;
218 219 220 221 222
	} a, b;
};

static char *pos;

223
noreturn static void
224
parse_error(const char *msg, ...)
225
{
226 227 228 229 230
	va_list ap;
	va_start(ap, msg);
	fprintf(stderr, "%s: parse error: ", argv0);
	vfprintf(stderr, msg, ap);
	fprintf(stderr, "\n");
231 232 233
	exit(2);
}

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
int
test_chmod(char *c, mode_t oldmode)
{
	mode_t newmode = oldmode;
	mode_t whom, what;
	char op;

	do {
		whom = 0;
		what = 0;

		while (1) {
			switch(*c) {
			case 'u': whom |= 04700; break;
			case 'g': whom |= 02070; break;
			case 'o': whom |= 01007; break;
			case 'a': whom |= 07777; break;
			default: goto op;
			}
			c++;
		}
op:
		if (whom == 0)
			whom = default_mask;
		op = *c++;
		if (!(op == '-' || op == '+' || op == '='))
			parse_error("invalid mode operator");

		switch(*c) {
263 264 265
		case 'u': what = 00111 * ((newmode >> 6) & 0007); c++; break;
		case 'g': what = 00111 * ((newmode >> 3) & 0007); c++; break;
		case 'o': what = 00111 * ((newmode     ) & 0007); c++; break;
266 267 268 269 270 271
		default:
			while (1) {
				switch(*c) {
				case 'r': what |= 00444; break;
				case 'w': what |= 00222; break;
				case 'x': what |= 00111; break;
272
				case 'X': if (oldmode & 00111) what |= 00111; break;
273 274 275 276 277 278 279 280 281 282 283 284
				case 's': what |= 06000; break;
				case 't': what |= 01000; break;
				case ',': case 0: goto doit;
				default: parse_error("invalid permission");
				}
				c++;
			}
		}
doit:
		switch (op) {
		case '-': newmode &= ~(whom & what); break;
		case '+': newmode |= (whom & what); break;
285
		case '=': newmode = (newmode & ~whom) | (whom & what); break;
286 287 288 289 290 291 292 293 294
		}
	} while (*c == ',' && c++);

	if (*c)
		parse_error("trailing garbage in mode string '%s'", c);

	return newmode == oldmode;
}

Christian Neukirchen's avatar
Christian Neukirchen committed
295
static struct expr *
296 297
mkexpr(enum op op)
{
Christian Neukirchen's avatar
Christian Neukirchen committed
298
	struct expr *e = malloc(sizeof (struct expr));
299 300 301 302 303 304
	if (!e)
		parse_error("out of memory");
	e->op = op;
	return e;
}

Christian Neukirchen's avatar
Christian Neukirchen committed
305
static void
306 307
ws()
{
308
	while (isspace((unsigned char) *pos))
309 310 311
		pos++;
}

Christian Neukirchen's avatar
Christian Neukirchen committed
312
static int
313 314 315 316 317 318 319 320 321 322 323
token(const char *token)
{
	if (strncmp(pos, token, strlen(token)) == 0) {
		pos += strlen(token);
		ws();
		return 1;
	} else {
		return 0;
	}
}

324
static int64_t
325
parse_num(int64_t *r)
326
{
327
	char *s = pos;
328
	if (isdigit((unsigned char) *pos)) {
329 330
		int64_t n;

331
		for (n = 0; isdigit((unsigned char) *pos) && n <= INT64_MAX / 10 - 10; pos++)
Christian Neukirchen's avatar
Christian Neukirchen committed
332
			n = 10 * n + (*pos - '0');
333
		if (isdigit((unsigned char) *pos))
334
			parse_error("number too big: %s", s);
Christian Neukirchen's avatar
Christian Neukirchen committed
335
		if (token("c"))      ;
336 337 338 339 340
		else if (token("b")) n *= 512LL;
		else if (token("k")) n *= 1024LL;
		else if (token("M")) n *= 1024LL * 1024;
		else if (token("G")) n *= 1024LL * 1024 * 1024;
		else if (token("T")) n *= 1024LL * 1024 * 1024 * 1024;
341 342 343 344 345 346 347 348
		ws();
		*r = n;
		return 1;
	} else {
		return 0;
	}
}

349 350 351
int
parse_octal(long *r)
{
352
	char *s = pos;
353 354 355 356 357 358
	if (*pos >= '0' && *pos <= '7') {
		long n = 0;
		while (*pos >= '0' && *pos <= '7') {
			n *= 8;
			n += *pos - '0';
			pos++;
Christian Neukirchen's avatar
Christian Neukirchen committed
359
			if (n > 07777)
360
				parse_error("number to big: %s", s);
361 362 363 364 365 366 367 368 369
		}
		ws();
		*r = n;
		return 1;
	} else {
		return 0;
	}
}

Christian Neukirchen's avatar
Christian Neukirchen committed
370
static enum op
371 372 373 374 375 376 377 378 379 380
parse_op()
{
	if (token("<="))
		return EXPR_LE;
	else if (token("<"))
		return EXPR_LT;
	else if (token(">="))
		return EXPR_GE;
	else if (token(">"))
		return EXPR_GT;
381
	else if (token("==") || token("="))
382
		return EXPR_EQ;
Christian Neukirchen's avatar
Christian Neukirchen committed
383 384
	else if (token("!="))
		return EXPR_NEQ;
385 386 387 388

	return 0;
}

Christian Neukirchen's avatar
Christian Neukirchen committed
389 390
static struct expr *parse_cmp();
static struct expr *parse_or();
Christian Neukirchen's avatar
Christian Neukirchen committed
391

Christian Neukirchen's avatar
Christian Neukirchen committed
392
static struct expr *
393 394 395
parse_inner()
{
	if (token("prune")) {
396
		struct expr *e = mkexpr(EXPR_PRUNE);
397
		return e;
398 399 400
	} else if (token("print")) {
		struct expr *e = mkexpr(EXPR_PRINT);
		return e;
401 402 403 404 405 406 407 408 409 410
	} else if (token("color")) {
		struct expr *e = mkexpr(EXPR_COLOR);
		int64_t n;
		if (parse_num(&n) && n >= 0 && n <= 255) {
			e->a.num = n;
			return e;
		} else {
			parse_error("invalid 256-color at '%.15s'", pos);
			return 0;
		}
Christian Neukirchen's avatar
Christian Neukirchen committed
411 412
	} else if (token("!")) {
		struct expr *e = parse_cmp();
413
		struct expr *not = mkexpr(EXPR_NOT);
Christian Neukirchen's avatar
Christian Neukirchen committed
414 415
		not->a.expr = e;
		return not;
Christian Neukirchen's avatar
Christian Neukirchen committed
416 417 418 419
	} else if (token("(")) {
		struct expr *e = parse_or();
		if (token(")"))
			return e;
420
		parse_error("missing ) at '%.15s'", pos);
Christian Neukirchen's avatar
Christian Neukirchen committed
421
		return 0;
422
	} else {
423
		parse_error("unknown expression at '%.15s'", pos);
424
		return 0;
425
	}
426 427
}

Christian Neukirchen's avatar
Christian Neukirchen committed
428
static struct expr *
Christian Neukirchen's avatar
Christian Neukirchen committed
429 430
parse_type()
{
Christian Neukirchen's avatar
Christian Neukirchen committed
431 432
	int negate = 0;

Christian Neukirchen's avatar
Christian Neukirchen committed
433
	if (token("type")) {
Christian Neukirchen's avatar
Christian Neukirchen committed
434 435
		if (token("==") || token("=")
		    || (token("!=") && ++negate)) {
436
			struct expr *e = mkexpr(EXPR_TYPE);
Christian Neukirchen's avatar
Christian Neukirchen committed
437 438 439 440 441 442 443 444 445 446 447 448 449 450
			if (token("b"))
				e->a.filetype = TYPE_BLOCK;
			else if (token("c"))
				e->a.filetype = TYPE_CHAR;
			else if (token("d"))
				e->a.filetype = TYPE_DIR;
			else if (token("p"))
				e->a.filetype = TYPE_FIFO;
			else if (token("f"))
				e->a.filetype = TYPE_REGULAR;
			else if (token("l"))
				e->a.filetype = TYPE_SYMLINK;
			else if (token("s"))
				e->a.filetype = TYPE_SOCKET;
451 452
			else if (*pos)
				parse_error("invalid file type '%c'", *pos);
Christian Neukirchen's avatar
Christian Neukirchen committed
453
			else
454
				parse_error("no file type given");
Christian Neukirchen's avatar
Christian Neukirchen committed
455 456 457 458 459 460 461
			if (negate) {
				struct expr *not = mkexpr(EXPR_NOT);
				not->a.expr = e;
				return not;
			} else {
				return e;
			}
462
		} else {
463 464
			parse_error("invalid file type comparison at '%.15s'",
			    pos);
Christian Neukirchen's avatar
Christian Neukirchen committed
465 466 467 468 469 470
		}
	}

	return parse_inner();
}

Christian Neukirchen's avatar
Christian Neukirchen committed
471
static int
Christian Neukirchen's avatar
Christian Neukirchen committed
472 473
parse_string(char **s)
{
474 475 476 477
	char *buf = 0;
	size_t bufsiz = 0;
	size_t len = 0;

Christian Neukirchen's avatar
Christian Neukirchen committed
478 479
	if (*pos == '"') {
		pos++;
480 481
		while (*pos &&
		    (*pos != '"' || (*pos == '"' && *(pos+1) == '"'))) {
482 483 484 485 486 487 488 489 490 491
			if (len >= bufsiz) {
				bufsiz = 2*bufsiz + 16;
				buf = realloc(buf, bufsiz);
				if (!buf)
					parse_error("string too long");
			}
			if (*pos == '"')
				pos++;
			buf[len++] = *pos++;
		}
492 493
		if (!*pos)
			parse_error("unterminated string");
494 495 496
		if (buf)
			buf[len] = 0;
		pos++;
Christian Neukirchen's avatar
Christian Neukirchen committed
497
		ws();
498
		*s = buf ? buf : (char *) "";
Christian Neukirchen's avatar
Christian Neukirchen committed
499
		return 1;
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
	} else if (*pos == '$') {
		char t;
		char *e = ++pos;

		while (isalnum((unsigned char) *pos) || *pos == '_')
			pos++;
		if (e == pos)
			parse_error("invalid environment variable name");

		t = *pos;
		*pos = 0;
		*s = getenv(e);
		if (!*s)
			*s = (char *) "";
		*pos = t;
		ws();
		return 1;
Christian Neukirchen's avatar
Christian Neukirchen committed
517 518 519 520 521
	}

	return 0;
}

522 523 524 525 526 527 528 529 530 531
static int
parse_dur(int64_t *n)
{
	char *s, *r;
	if (!parse_string(&s))
		return 0;

	if (*s == '/' || *s == '.') {
		struct stat st;
		if (stat(s, &st) < 0)
532 533
			parse_error("can't stat file '%s': %s",
			    s, strerror(errno));
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
		*n = st.st_mtime;
		return 1;
	}

	struct tm tm = { 0 };
	r = strptime(s, "%Y-%m-%d %H:%M:%S", &tm);
	if (r && !*r) {
		*n = mktime(&tm);
		return 1;
	}
	r = strptime(s, "%Y-%m-%d", &tm);
	if (r && !*r) {
		tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
		*n = mktime(&tm);
		return 1;
	}
	r = strptime(s, "%H:%M:%S", &tm);
	if (r && !*r) {
		struct tm *tmnow = localtime(&now);
		tm.tm_year = tmnow->tm_year;
		tm.tm_mon = tmnow->tm_mon;
		tm.tm_mday = tmnow->tm_mday;
		*n = mktime(&tm);
		return 1;
	}
	r = strptime(s, "%H:%M", &tm);
	if (r && !*r) {
		struct tm *tmnow = localtime(&now);
		tm.tm_year = tmnow->tm_year;
		tm.tm_mon = tmnow->tm_mon;
		tm.tm_mday = tmnow->tm_mday;
		tm.tm_sec = 0;
		*n = mktime(&tm);
		return 1;
	}

	if (*s == '-') {
		s++;

		errno = 0;
		int64_t d;
		d = strtol(s, &r, 10);
		if (errno == 0 && r[0] == 'd' && !r[1]) {
			struct tm *tmnow = localtime(&now);
			tmnow->tm_mday -= d;
			tmnow->tm_hour = tmnow->tm_min = tmnow->tm_sec = 0;
			*n = mktime(tmnow);
			return 1;
		}
		if (errno == 0 && r[0] == 'h' && !r[1]) {
			*n = now - (d*60*60);
			return 1;
		}
		if (errno == 0 && r[0] == 'm' && !r[1]) {
			*n = now - (d*60);
			return 1;
		}
		if (errno == 0 && r[0] == 's' && !r[1]) {
			*n = now - d;
			return 1;
		}
595
		parse_error("invalid relative time format '%s'", s-1);
596 597
	}

598
	parse_error("invalid time format '%s'", s);
599 600 601
	return 0;
}

Christian Neukirchen's avatar
Christian Neukirchen committed
602
static struct expr *
Christian Neukirchen's avatar
Christian Neukirchen committed
603 604 605 606
parse_strcmp()
{
	enum prop prop;
	enum op op;
Leah Neukirchen's avatar
Leah Neukirchen committed
607
	int negate = 0;
Christian Neukirchen's avatar
Christian Neukirchen committed
608

609 610 611
	if (token("fstype"))
		prop = PROP_FSTYPE;
	else if (token("group"))
612 613
		prop = PROP_GROUP;
	else if (token("name"))
Christian Neukirchen's avatar
Christian Neukirchen committed
614 615 616 617 618
		prop = PROP_NAME;
	else if (token("path"))
		prop = PROP_PATH;
	else if (token("target"))
		prop = PROP_TARGET;
619 620
	else if (token("user"))
		prop = PROP_USER;
621 622
	else if (token("xattr"))
		prop = PROP_XATTR;
Christian Neukirchen's avatar
Christian Neukirchen committed
623 624 625
	else
		return parse_type();

626
	if (token("~~~"))
Christian Neukirchen's avatar
Christian Neukirchen committed
627 628 629
		op = EXPR_GLOBI;
	else if (token("~~"))
		op = EXPR_GLOB;
Christian Neukirchen's avatar
Christian Neukirchen committed
630 631 632 633
	else if (token("=~~"))
		op = EXPR_REGEXI;
	else if (token("=~"))
		op = EXPR_REGEX;
634 635 636 637 638 639
	else if (token("==="))
		op = EXPR_STREQI;
	else if (token("=="))
		op = EXPR_STREQ;
	else if (token("="))
		op = EXPR_STREQ;
Leah Neukirchen's avatar
Leah Neukirchen committed
640 641 642 643 644 645 646 647 648 649 650 651
	else if (token("!~~~"))
		negate = 1, op = EXPR_GLOBI;
	else if (token("!~~"))
		negate = 1, op = EXPR_GLOB;
	else if (token("!=~~"))
		negate = 1, op = EXPR_REGEXI;
	else if (token("!=~") || token("!~"))
		negate = 1, op = EXPR_REGEX;
	else if (token("!==="))
		negate = 1, op = EXPR_STREQI;
	else if (token("!==") || token("!="))
		negate = 1, op = EXPR_STREQ;
Christian Neukirchen's avatar
Christian Neukirchen committed
652
	else
653
		parse_error("invalid string operator at '%.15s'", pos);
Christian Neukirchen's avatar
Christian Neukirchen committed
654 655 656

	char *s;
	if (parse_string(&s)) {
657
		int r = 0;
658
		struct expr *e = mkexpr(op);
Christian Neukirchen's avatar
Christian Neukirchen committed
659
		e->a.prop = prop;
Christian Neukirchen's avatar
Christian Neukirchen committed
660
		if (op == EXPR_REGEX) {
Christian Neukirchen's avatar
Christian Neukirchen committed
661
			e->b.regex = malloc(sizeof (regex_t));
662
			r = regcomp(e->b.regex, s, REG_EXTENDED | REG_NOSUB);
Christian Neukirchen's avatar
Christian Neukirchen committed
663
		} else if (op == EXPR_REGEXI) {
Christian Neukirchen's avatar
Christian Neukirchen committed
664
			e->b.regex = malloc(sizeof (regex_t));
665
			r = regcomp(e->b.regex, s, REG_EXTENDED | REG_NOSUB | REG_ICASE);
Christian Neukirchen's avatar
Christian Neukirchen committed
666 667 668
		} else {
			e->b.string = s;
		}
669 670 671 672

		if (r != 0) {
			char msg[256];
			regerror(r, e->b.regex, msg, sizeof msg);
673
			parse_error("invalid regex '%s': %s", s, msg);
674 675 676
			exit(2);
		}

Leah Neukirchen's avatar
Leah Neukirchen committed
677 678 679 680 681 682
		if (negate) {
			struct expr *not = mkexpr(EXPR_NOT);
			not->a.expr = e;
			return not;
		}

Christian Neukirchen's avatar
Christian Neukirchen committed
683 684 685
		return e;
	}

686
	parse_error("invalid string at '%.15s'", pos);
Christian Neukirchen's avatar
Christian Neukirchen committed
687
	return 0;
Christian Neukirchen's avatar
Christian Neukirchen committed
688 689
}

Christian Neukirchen's avatar
Christian Neukirchen committed
690
static struct expr *
691 692
parse_mode()
{
693
	struct expr *e = mkexpr(0);
694
	long n;
695
	char *s;
696 697 698

	e->a.prop = PROP_MODE;

699
	if (token("==") || token("=")) {
700 701 702 703 704 705
		e->op = EXPR_EQ;
	} else if (token("&")) {
		e->op = EXPR_ALLSET;
	} else if (token("|")) {
		e->op = EXPR_ANYSET;
	} else {
706
		parse_error("invalid mode comparison at '%.15s'", pos);
707 708 709 710
	}

	if (parse_octal(&n)) {
		e->b.num = n;
Christian Neukirchen's avatar
Christian Neukirchen committed
711
	} else if (e->op == EXPR_EQ && parse_string(&s)) {
712 713
		e->op = EXPR_CHMOD;
		e->b.string = s;
714
		umask(default_mask = 07777 & ~umask(0));  /* for future usage */
715
		test_chmod(s, 0);  /* run once to check for syntax */
716
	} else {
717
		parse_error("invalid mode at '%.15s'", pos);
718 719 720 721 722
	}

	return e;
}

Christian Neukirchen's avatar
Christian Neukirchen committed
723
static struct expr *
724 725 726 727 728
parse_cmp()
{
	enum prop prop;
	enum op op;

729
	if (token("depth"))
730 731 732
		prop = PROP_DEPTH;
	else if (token("dev"))
		prop = PROP_DEV;
733 734
	else if (token("entries"))
		prop = PROP_ENTRIES;
735 736
	else if (token("gid"))
		prop = PROP_GID;
737 738 739 740 741
	else if (token("inode"))
		prop = PROP_INODE;
	else if (token("links"))
		prop = PROP_LINKS;
	else if (token("mode"))
742
		return parse_mode();
Christian Neukirchen's avatar
Christian Neukirchen committed
743 744
	else if (token("rdev"))
		prop = PROP_RDEV;
745 746
	else if (token("size"))
		prop = PROP_SIZE;
747 748
	else if (token("total"))
		prop = PROP_TOTAL;
749 750
	else if (token("uid"))
		prop = PROP_UID;
751
	else
Christian Neukirchen's avatar
Christian Neukirchen committed
752
		return parse_strcmp();
Christian Neukirchen's avatar
Christian Neukirchen committed
753

754 755
	op = parse_op();
	if (!op)
756
		parse_error("invalid comparison at '%.15s'", pos);
757

758
	int64_t n;
759
	if (parse_num(&n)) {
760
		struct expr *e = mkexpr(op);
761 762 763 764 765 766 767 768
		e->a.prop = prop;
		e->b.num = n;
		return e;
	}

	return 0;
}

769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
static struct expr *
parse_timecmp()
{
	enum prop prop;
	enum op op;

	if (token("atime"))
		prop = PROP_ATIME;
	else if (token("ctime"))
		prop = PROP_CTIME;
	else if (token("mtime"))
		prop = PROP_MTIME;
	else
		return parse_cmp();

	op = parse_op();
	if (!op)
786
		parse_error("invalid comparison at '%.15s'", pos);
787 788 789 790 791 792 793 794 795 796 797 798

	int64_t n;
	if (parse_num(&n) || parse_dur(&n)) {
		struct expr *e = mkexpr(op);
		e->a.prop = prop;
		e->b.num = n;
		return e;
	}

	return 0;
}

Christian Neukirchen's avatar
Christian Neukirchen committed
799
static struct expr *
800 801 802
chain(struct expr *e1, enum op op, struct expr *e2)
{
	struct expr *i, *j, *e;
803 804
	if (!e1)
		return e2;
805 806
	if (!e2)
		return e1;
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
	for (j = 0, i = e1; i->op == op; j = i, i = i->b.expr)
		;
	if (!j) {
		e = mkexpr(op);
		e->a.expr = e1;
		e->b.expr = e2;
		return e;
	} else {
		e = mkexpr(op);
		e->a.expr = i;
		e->b.expr = e2;
		j->b.expr = e;
		return e1;
	}
}

Christian Neukirchen's avatar
Christian Neukirchen committed
823
static struct expr *
824 825
parse_and()
{
826
	struct expr *e1 = parse_timecmp();
827 828 829
	struct expr *r = e1;

	while (token("&&")) {
830
		struct expr *e2 = parse_timecmp();
831
		r = chain(r, EXPR_AND, e2);
832
	}
Christian Neukirchen's avatar
Christian Neukirchen committed
833

834 835 836
	return r;
}

837

Christian Neukirchen's avatar
Christian Neukirchen committed
838
static struct expr *
839 840 841 842 843 844 845
parse_or()
{
	struct expr *e1 = parse_and();
	struct expr *r = e1;

	while (token("||")) {
		struct expr *e2 = parse_and();
846
		r = chain(r, EXPR_OR, e2);
847
	}
Christian Neukirchen's avatar
Christian Neukirchen committed
848

849 850 851
	return r;
}

Christian Neukirchen's avatar
Christian Neukirchen committed
852
static struct expr *
853
parse_expr(const char *s)
854
{
Christian Neukirchen's avatar
Christian Neukirchen committed
855
	pos = (char *)s;
856 857
	struct expr *e = parse_or();
	if (*pos)
858
		parse_error("trailing garbage at '%.15s'", pos);
859
	return e;
860 861
}

Christian Neukirchen's avatar
Christian Neukirchen committed
862
static const char *
Christian Neukirchen's avatar
Christian Neukirchen committed
863 864 865 866 867 868
basenam(const char *s)
{
	char *r = strrchr(s, '/');
	return r ? r + 1 : s;
}

Christian Neukirchen's avatar
Christian Neukirchen committed
869 870 871 872 873 874 875 876 877 878
static const char *
extnam(const char *s)
{
	char *r = strrchr(s, '/');
	char *e = strrchr(s, '.');
	if (!r || r < e)
		return e ? e + 1 : "";
	return "";
}

Christian Neukirchen's avatar
Christian Neukirchen committed
879
static const char *
Christian Neukirchen's avatar
Christian Neukirchen committed
880 881 882 883 884 885 886 887 888 889
readlin(const char *p, const char *alt)
{
	static char b[PATH_MAX];
	int r = readlink(p, b, sizeof b - 1);
	if (r < 0)
		return alt;
	b[r] = 0;
	return b;
}

890 891 892
int
idorder(const void *a, const void *b)
{
Christian Neukirchen's avatar
Christian Neukirchen committed
893 894
	struct idmap *ia = (struct idmap *)a;
	struct idmap *ib = (struct idmap *)b;
895 896 897 898 899 900 901 902 903 904 905 906 907

	if (ia->id == ib->id)
		return 0;
	else if (ia->id < ib->id)
		return -1;
	else
		return 1;
}

static char *
strid(long id)
{
	static char buf[32];
908
	snprintf(buf, sizeof buf, "%ld", id);
909 910 911 912 913 914 915 916 917 918 919 920 921
	return buf;
}

static char *
groupname(gid_t gid)
{
	struct idmap key, **result;
	key.id = gid;
	key.name = 0;

	if (!(result = tfind(&key, &groups, idorder))) {
		struct group *g = getgrgid(gid);
		if (g) {
Christian Neukirchen's avatar
Christian Neukirchen committed
922
			struct idmap *newkey = malloc(sizeof (struct idmap));
923 924
			newkey->id = gid;
			newkey->name = strdup(g->gr_name);
Christian Neukirchen's avatar
Christian Neukirchen committed
925
			if ((int)strlen(g->gr_name) > gwid)
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
				gwid = strlen(g->gr_name);
			tsearch(newkey, &groups, idorder);
			return newkey->name;
		}
	}

	return result ? (*result)->name : strid(gid);
}

static char *
username(uid_t uid)
{
	struct idmap key, **result;
	key.id = uid;
	key.name = 0;

	if (!(result = tfind(&key, &users, idorder))) {
		struct passwd *p = getpwuid(uid);
		if (p) {
Christian Neukirchen's avatar
Christian Neukirchen committed
945
			struct idmap *newkey = malloc(sizeof (struct idmap));
946 947
			newkey->id = uid;
			newkey->name = strdup(p->pw_name);
Christian Neukirchen's avatar
Christian Neukirchen committed
948
			if ((int)strlen(p->pw_name) > uwid)
949 950 951 952 953 954 955 956 957
				uwid = strlen(p->pw_name);
			tsearch(newkey, &users, idorder);
			return newkey->name;
		}
	}

	return result ? (*result)->name : strid(uid);
}

958
#if defined(__linux__) || defined(__CYGWIN__)
959 960 961 962 963 964 965 966 967 968 969
#include <mntent.h>
void
scan_filesystems()
{
	FILE *mtab;
	struct mntent *mnt;
	struct stat st;

	/* Approach: iterate over mtab and memorize st_dev for each mountpoint.
	 * this will fail if we are not allowed to read the mountpoint, but then
	 * we should not have to look up this st_dev value... */
970
	mtab = setmntent(_PATH_MOUNTED, "r");
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
	if (!mtab)
		return;

	while ((mnt = getmntent(mtab))) {
		if (stat(mnt->mnt_dir, &st) < 0)
			continue;

		struct idmap *newkey = malloc(sizeof (struct idmap));
		newkey->id = st.st_dev;
		newkey->name = strdup(mnt->mnt_type);
		tsearch(newkey, &filesystems, idorder);
	};

	endmntent(mtab);

	scanned_filesystems = 1;
}
988 989 990 991 992 993 994 995 996
#elif defined(__SVR4)
#include <sys/mnttab.h>
void
scan_filesystems()
{
	FILE *mtab;
	struct mnttab mnt;
	struct stat st;

997
	mtab = fopen(MNTTAB, "r");
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
	if (!mtab)
		return;

	while (getmntent(mtab, &mnt) == 0) {
		if (stat(mnt.mnt_mountp, &st) < 0)
			continue;

		struct idmap *newkey = malloc(sizeof (struct idmap));
		newkey->id = st.st_dev;
		newkey->name = strdup(mnt.mnt_fstype);
		tsearch(newkey, &filesystems, idorder);
	};

	fclose(mtab);

	scanned_filesystems = 1;
}
1015
#elif defined(__FreeBSD__) || defined(__OpenBSD__) || (defined(__APPLE__) && defined(__MACH__))
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
#include <sys/param.h>
#include <sys/ucred.h>
#include <sys/mount.h>
void
scan_filesystems()
{
	struct statfs *mnt;
	struct stat st;
	int i = getmntinfo(&mnt, MNT_NOWAIT);

	while (i-- > 0) {
		if (stat(mnt->f_mntonname, &st) < 0)
			continue;

		struct idmap *newkey = malloc(sizeof (struct idmap));
		newkey->id = st.st_dev;
		newkey->name = strdup(mnt->f_fstypename);
		tsearch(newkey, &filesystems, idorder);
		mnt++;
	};

	scanned_filesystems = 1;
}
Christian Neukirchen's avatar
Christian Neukirchen committed
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
#elif defined(__NetBSD__)
#include <sys/types.h>
#include <sys/statvfs.h>
void
scan_filesystems()
{
	struct statvfs *mnt;
	struct stat st;
	int i = getmntinfo(&mnt, MNT_NOWAIT);

	while (i-- > 0) {
		if (stat(mnt->f_mntonname, &st) < 0)
			continue;

		struct idmap *newkey = malloc(sizeof (struct idmap));
		newkey->id = st.st_dev;
		newkey->name = strdup(mnt->f_fstypename);
		tsearch(newkey, &filesystems, idorder);
		mnt++;
	};

	scanned_filesystems = 1;
}
1062
#else
1063
#warning fstype lookup not implemented on this platform, keeping st_dev as number
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
void
scan_filesystems()
{
}
#endif

static char *
fstype(dev_t devid)
{
	struct idmap key, **result;
	key.id = devid;
	key.name = 0;

	if (!scanned_filesystems)
		scan_filesystems();
	result = tfind(&key, &filesystems, idorder);

1081 1082 1083
	if (result && (int)strlen((*result)->name) > fwid)
		fwid = strlen((*result)->name);

1084 1085 1086
	return result ? (*result)->name : strid(devid);
}

1087
static char *
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
xattr_string(const char *f)
{
#ifdef __linux__
	char xattr[1024];
	int i, r;
	int have_xattr = 0, have_cap = 0, have_acl = 0;

	if (Lflag)
		r = listxattr(f, xattr, sizeof xattr);
	else
		r = llistxattr(f, xattr, sizeof xattr);
	if (r < 0 && errno == ERANGE) {
		/* just look at prefix */
		r = sizeof xattr;
		xattr[r-1] = 0;
	}
	// ignoring ENOTSUP or r == 0

	for (i = 0; i < r; i += strlen(xattr+i) + 1)
		if (strcmp(xattr+i, "security.capability") == 0)
			have_cap = 1;
		else if (strcmp(xattr+i, "system.posix_acl_access") == 0 ||
		    strcmp(xattr+i, "system.posix_acl_default") == 0)
			have_acl = 1;
		else
			have_xattr = 1;

	static char buf[4];
	char *c = buf;
	if (have_cap)
		*c++ = '#';
	if (have_acl)
		*c++ = '+';
	if (have_xattr)
		*c++ = '@';
	*c = 0;

	return buf;
#else
1127 1128 1129
	static char empty[] = "";
	(void) f;
	return empty;		// No support for xattrs on this platform.
1130 1131 1132
#endif
}

1133
static ino_t
1134 1135
count_entries(struct fileinfo *fi)
{
1136
	ino_t c = 0;
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
	struct dirent *de;
	DIR *d;

	if (Dflag)
		return fi->entries;

	if (!S_ISDIR(fi->sb.st_mode))
		return 0;

	d = opendir(fi->fpath);
	if (!d)
		return 0;
	while ((de = readdir(d))) {
		if (de->d_name[0] == '.' &&
		    (!de->d_name[1] || (de->d_name[1]=='.' && !de->d_name[2])))
			continue;
		c++;
	}
	closedir(d);

	return c;
}

1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
int
eval(struct expr *e, struct fileinfo *fi)
{
	switch (e->op) {
	case EXPR_OR:
		return eval(e->a.expr, fi) || eval(e->b.expr, fi);
	case EXPR_AND:
		return eval(e->a.expr, fi) && eval(e->b.expr, fi);
	case EXPR_NOT:
		return !eval(e->a.expr, fi);
	case EXPR_PRUNE:
		prune = 1;
		return 1;
1173 1174
	case EXPR_PRINT:
		return 1;
1175 1176 1177
	case EXPR_COLOR:
		fi->color = e->a.num;
		return 1;
1178 1179 1180
	case EXPR_LT:
	case EXPR_LE:
	case EXPR_EQ:
Christian Neukirchen's avatar
Christian Neukirchen committed
1181
	case EXPR_NEQ:
1182 1183
	case EXPR_GE:
	case EXPR_GT:
1184
	case EXPR_ALLSET:
Christian Neukirchen's avatar
Christian Neukirchen committed
1185
	case EXPR_ANYSET: {
1186 1187 1188 1189 1190 1191
		long v = 0;
		switch (e->a.prop) {
		case PROP_ATIME: v = fi->sb.st_atime; break;
		case PROP_CTIME: v = fi->sb.st_ctime; break;
		case PROP_DEPTH: v = fi->depth; break;
		case PROP_DEV: v = fi->sb.st_dev; break;
1192
		case PROP_ENTRIES: v = count_entries(fi); break;
1193 1194
		case PROP_GID: v = fi->sb.st_gid; break;
		case PROP_INODE: v = fi->sb.st_ino; break;
1195
		case PROP_LINKS: v = fi->sb.st_nlink; break;
1196
		case PROP_MODE: v = fi->sb.st_mode & 07777; break;
1197
		case PROP_MTIME: v = fi->sb.st_mtime; break;
Christian Neukirchen's avatar
Christian Neukirchen committed
1198
		case PROP_RDEV: v = fi->sb.st_rdev; break;
1199
		case PROP_SIZE: v = fi->sb.st_size; break;
1200
		case PROP_TOTAL: v = fi->total; break;
1201
		case PROP_UID: v = fi->sb.st_uid; break;
1202
		default:
1203
			parse_error("unknown property");
1204 1205 1206 1207 1208 1209
		}

		switch (e->op) {
		case EXPR_LT: return v < e->b.num;
		case EXPR_LE: return v <= e->b.num;
		case EXPR_EQ: return v == e->b.num;
Christian Neukirchen's avatar
Christian Neukirchen committed
1210
		case EXPR_NEQ: return v != e->b.num;
1211 1212
		case EXPR_GE: return v >= e->b.num;
		case EXPR_GT: return v > e->b.num;
1213 1214
		case EXPR_ALLSET: return (v & e->b.num) == e->b.num;
		case EXPR_ANYSET: return (v & e->b.num) > 0;
1215 1216
		}
	}
1217 1218
	case EXPR_CHMOD:
		return test_chmod(e->b.string, fi->sb.st_mode & 07777);
Christian Neukirchen's avatar
Christian Neukirchen committed
1219
	case EXPR_TYPE:	{
Christian Neukirchen's avatar
Christian Neukirchen committed
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
		switch (e->a.filetype) {
		case TYPE_BLOCK: return S_ISBLK(fi->sb.st_mode);
		case TYPE_CHAR: return S_ISCHR(fi->sb.st_mode);
		case TYPE_DIR: return S_ISDIR(fi->sb.st_mode);
		case TYPE_FIFO: return S_ISFIFO(fi->sb.st_mode);
		case TYPE_REGULAR: return S_ISREG(fi->sb.st_mode);
		case TYPE_SOCKET: return S_ISSOCK(fi->sb.st_mode);
		case TYPE_SYMLINK: return S_ISLNK(fi->sb.st_mode);
		}
	}
Christian Neukirchen's avatar
Christian Neukirchen committed
1230 1231 1232 1233
	case EXPR_STREQ:
	case EXPR_STREQI:
	case EXPR_GLOB:
	case EXPR_GLOBI:
Christian Neukirchen's avatar
Christian Neukirchen committed
1234
	case EXPR_REGEX:
Christian Neukirchen's avatar
Christian Neukirchen committed
1235
	case EXPR_REGEXI: {
Christian Neukirchen's avatar
Christian Neukirchen committed
1236 1237
		const char *s = "";
		switch(e->a.prop) {
1238
		case PROP_FSTYPE: s = fstype(fi->sb.st_dev); break;
1239
		case PROP_GROUP: s = groupname(fi->sb.st_gid); break;
Christian Neukirchen's avatar
Christian Neukirchen committed
1240 1241 1242
		case PROP_NAME: s = basenam(fi->fpath); break;
		case PROP_PATH: s = fi->fpath; break;
		case PROP_TARGET: s = readlin(fi->fpath, ""); break;
1243
		case PROP_USER: s = username(fi->sb.st_uid); break;
1244
		case PROP_XATTR: s = xattr_string(fi->fpath); break;
Christian Neukirchen's avatar
Christian Neukirchen committed
1245 1246
		}
		switch (e->op) {
1247 1248 1249 1250
		case EXPR_STREQ: return strcmp(e->b.string, s) == 0;
		case EXPR_STREQI: return strcasecmp(e->b.string, s) == 0;
		case EXPR_GLOB: return fnmatch(e->b.string, s, 0) == 0;
		case EXPR_GLOBI: return fnmatch(e->b.string, s, FNM_CASEFOLD) == 0;
Christian Neukirchen's avatar
Christian Neukirchen committed
1251
		case EXPR_REGEX:
1252
		case EXPR_REGEXI: return regexec(e->b.regex, s, 0, 0, 0) == 0;
Christian Neukirchen's avatar
Christian Neukirchen committed
1253 1254
		}
	}
1255 1256
	default:
		parse_error("invalid operation %d, please file a bug.", e->op);
1257 1258 1259 1260 1261
	}

	return 0;
}

1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
int
dircmp(char *a, char *b)
{
	char *ea = strrchr(a, '/');
	char *eb = strrchr(b, '/');
	if (!ea)
		ea = a + strlen(a);
	if (!eb)
		eb = b + strlen(b);

	while (a != ea && b != eb && *a == *b) {
		a++;
		b++;
	}

	if (a == ea && b == eb)
		return 0;
	if (a == ea)
		return -1;
	if (b == eb)
		return 1;
	return *a - *b;
}

1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
// taken straight from musl@a593414
int mystrverscmp(const char *l0, const char *r0)
{
	const unsigned char *l = (const void *)l0;
	const unsigned char *r = (const void *)r0;
	size_t i, dp, j;
	int z = 1;

	/* Find maximal matching prefix and track its maximal digit
	 * suffix and whether those digits are all zeros. */
	for (dp=i=0; l[i]==r[i]; i++) {
		int c = l[i];
		if (!c) return 0;
		if (!isdigit(c)) dp=i+1, z=1;
		else if (c!='0') z=0;
	}

	if (l[dp]!='0' && r[dp]!='0') {
		/* If we're not looking at a digit sequence that began
		 * with a zero, longest digit string is greater. */
		for (j=i; isdigit(l[j]); j++)
			if (!isdigit(r[j])) return 1;
		if (isdigit(r[j])) return -1;
	} else if (z && dp<i && (isdigit(l[i]) || isdigit(r[i]))) {
		/* Otherwise, if common prefix of digit sequence is
		 * all zeros, digits order less than non-digits. */
		return (unsigned char)(l[i]-'0') - (unsigned char)(r[i]-'0');
	}

	return l[i] - r[i];
}

1318 1319
#define CMP(a, b) if ((a) == (b)) break; else if ((a) < (b)) return -1; else return 1
#define STRCMP(a, b) if (strcmp(a, b) == 0) break; else return (strcmp(a, b));
1320
#define DIRCMP(a, b) { int r = dircmp(a, b); if (r == 0) break; else return r; };
1321
#define VERCMP(a, b) if (mystrverscmp(a, b) == 0) break; else return (mystrverscmp(a, b));
1322 1323 1324 1325

int
order(const void *a, const void *b)
{
Christian Neukirchen's avatar
Christian Neukirchen committed
1326 1327
	struct fileinfo *fa = (struct fileinfo *)a;
	struct fileinfo *fb = (struct fileinfo *)b;
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
	char *s;

	for (s = ordering; *s; s++) {
		switch (*s) {
		// XXX use nanosecond timestamps
		case 'c': CMP(fa->sb.st_ctime, fb->sb.st_ctime);
		case 'C': CMP(fb->sb.st_ctime, fa->sb.st_ctime);
		case 'a': CMP(fa->sb.st_atime, fb->sb.st_atime);
		case 'A': CMP(fb->sb.st_atime, fa->sb.st_atime);
		case 'm': CMP(fa->sb.st_mtime, fb->sb.st_mtime);
		case 'M': CMP(fb->sb.st_mtime, fa->sb.st_mtime);
		case 's': CMP(fa->sb.st_size, fb->sb.st_size);
		case 'S': CMP(fb->sb.st_size, fa->sb.st_size);
Christian Neukirchen's avatar
Christian Neukirchen committed
1341 1342
		case 'i': CMP(fa->sb.st_ino, fb->sb.st_ino);
		case 'I': CMP(fb->sb.st_ino, fa->sb.st_ino);
1343 1344
		case 'd': CMP(fa->depth, fb->depth);
		case 'D': CMP(fb->depth, fa->depth);
Christian Neukirchen's avatar
Christian Neukirchen committed
1345 1346 1347 1348
		case 't': CMP("ZZZZAZZZZZZZZZZZ"[(fa->sb.st_mode >> 12) & 0x0f],
		              "ZZZZAZZZZZZZZZZZ"[(fb->sb.st_mode >> 12) & 0x0f]);
		case 'T': CMP("ZZZZAZZZZZZZZZZZ"[(fb->sb.st_mode >> 12) & 0x0f],
		              "ZZZZAZZZZZZZZZZZ"[(fa->sb.st_mode >> 12) & 0x0f]);
1349 1350
		case 'n': STRCMP(fa->fpath, fb->fpath);
		case 'N': STRCMP(fb->fpath, fa->fpath);
Christian Neukirchen's avatar
Christian Neukirchen committed
1351 1352
		case 'e': STRCMP(extnam(fa->fpath), extnam(fb->fpath));
		case 'E': STRCMP(extnam(fb->fpath), extnam(fa->fpath));
1353 1354
		case 'p': DIRCMP(fa->fpath, fb->fpath);
		case 'P': DIRCMP(fb->fpath, fa->fpath);
1355 1356
		case 'v': VERCMP(fa->fpath, fb->fpath);
		case 'V': VERCMP(fb->fpath, fa->fpath);
1357 1358 1359 1360 1361 1362 1363
		default: STRCMP(fa->fpath, fb->fpath);
		}
	}

	return strcmp(fa->fpath, fb->fpath);
}

Christian Neukirchen's avatar
Christian Neukirchen committed
1364
static int
1365
intlen(intmax_t i)
1366 1367 1368 1369 1370 1371 1372
{
	int s;
	for (s = 1; i > 9; i /= 10)
		s++;
	return s;
}

Christian Neukirchen's avatar
Christian Neukirchen committed
1373
static void
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
print_mode(int mode)
{
	putchar("0pcCd?bB-?l?s???"[(mode >> 12) & 0x0f]);
	putchar(mode & 00400 ? 'r' : '-');
	putchar(mode & 00200 ? 'w' : '-');
	putchar(mode & 04000 ? (mode & 00100 ? 's' : 'S')
	                     : (mode & 00100 ? 'x' : '-'));
	putchar(mode & 00040 ? 'r' : '-');
	putchar(mode & 00020 ? 'w' : '-');
	putchar(mode & 02000 ? (mode & 00010 ? 's' : 'S')
	                     : (mode & 00010 ? 'x' : '-'));
	putchar(mode & 00004 ? 'r' : '-');
	putchar(mode & 00002 ? 'w' : '-');
1387
	putchar(mode & 01000 ? (mode & 00001 ? 't' : 'T')
1388 1389 1390
	                     : (mode & 00001 ? 'x' : '-'));
}

1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
static void
fgbold()
{
	printf("\033[1m");
}

static void
fg256(int c)
{
	printf("\033[38;5;%dm", c);
}

static void
fgdefault()
{
	if (Gflag)
		printf("\033[0m");
}

static void
color_size_on(off_t s)
{
	int c;

Christian Neukirchen's avatar
Christian Neukirchen committed
1415
	if (!Gflag)
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
		return;

	if	(s <		  1024LL) c = 46;
	else if (s <		4*1024LL) c = 82;
	else if (s <	       16*1024LL) c = 118;
	else if (s <	       32*1024LL) c = 154;
	else if (s <	      128*1024LL) c = 190;
	else if (s <	      512*1024LL) c = 226;
	else if (s <	     1024*1024LL) c = 220;
	else if (s <	 700*1024*1024LL) c = 214;
	else if (s <  2*1048*1024*1024LL) c = 208;
	else if (s < 50*1024*1024*1024LL) c = 202;
	else				  c = 196;

	fg256(c);
}

1433 1434 1435 1436 1437 1438 1439 1440 1441
static void
print_human(intmax_t i)
{
	double d = i;
	const char *u = "\0\0K\0M\0G\0T\0P\0E\0Z\0Y\0";
	while (d >= 1024) {
		u += 2;
		d /= 1024.0;
	}
1442 1443 1444

	color_size_on(i);

1445 1446 1447 1448 1449 1450
	if (!*u)
		printf("%5.0f", d);
	else if (d < 10.0)
		printf("%4.1f%s", d, u);
	else
		printf("%4.0f%s", d, u);
1451 1452 1453

	fgdefault();

1454 1455
}

Christian Neukirchen's avatar
Christian Neukirchen committed
1456
static void
1457
print_shquoted(const char *s)
Christian Neukirchen's avatar
Christian Neukirchen committed
1458
{
1459 1460 1461 1462 1463
	if (!Qflag || !strpbrk(s, "\001\002\003\004\005\006\007\010"
	                          "\011\012\013\014\015\016\017\020"
	                          "\021\022\023\024\025\026\027\030"
	                          "\031\032\033\034\035\036\037\040"
	                          "`^#*[]=|\\?${}()'\"<>&;\177")) {
Christian Neukirchen's avatar
Christian Neukirchen committed
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
		printf("%s", s);
		return;
	}

	putchar('\'');
	for (; *s; s++)
		if (*s == '\'')
			printf("'\\''");
		else
			putchar(*s);
	putchar('\'');
}

1477 1478 1479
void
print_noprefix(struct fileinfo *fi)
{
1480
	if (fi->prefixl == 0 && fi->fpath[0])
1481 1482
		print_shquoted(fi->fpath);
	else if (strlen(fi->fpath) > fi->prefixl + 1)  /* strip prefix */
1483 1484 1485 1486 1487 1488 1489
		print_shquoted(fi->fpath + fi->prefixl + 1);
	else if (S_ISDIR(fi->sb.st_mode))  /* turn empty string into "." */
		printf(".");
	else  /* turn empty string into basename */
		print_shquoted(basenam(fi->fpath));
}

1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
void
analyze_format()
{
	char *s;
	for (s = format; *s; s++) {
		if (*s == '\\') {
			s++;
			continue;
		}
	       	if (*s != '%')
			continue;
		switch (*++s) {
		case 'g': need_group++; break;
		case 'u': need_user++; break;
		case 'Y': need_fstype++; break;
1505
		case 'x': need_xattr++; break;
1506 1507 1508 1509
		}
	}
}

1510 1511 1512 1513 1514 1515
static void
color_age_on(time_t t)
{
	time_t age = now - t;
	int c;

Christian Neukirchen's avatar
Christian Neukirchen committed
1516
	if (!Gflag)
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
		return;

	if	(age <		     0LL) c = 196;
	else if (age <		    60LL) c = 255;
	else if (age <		 60*60LL) c = 252;
	else if (age <	      24*60*60LL) c = 250;
	else if (age <	    7*24*60*60LL) c = 244;
	else if (age <	  4*7*24*60*60LL) c = 244;
	else if (age <	 26*7*24*60*60LL) c = 242;
	else if (age <	 52*7*24*60*60LL) c = 240;
	else if (age < 2*52*7*24*60*60LL) c = 238;
	else				  c = 236;

	fg256(c);
}

static void
1534
color_name_on(int c, const char *f, mode_t m)
1535 1536 1537 1538 1539 1540
{
	const char *b;

	if (!Gflag)
		return;

1541 1542 1543 1544 1545
	if (c != -1) {
		fg256(c);
		return;
	}