about summary refs log tree commit diff
path: root/mscan.c
blob: 04944097dd830ffef488d631bc5f5595fe50665e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
#ifndef _XOPEN_SOURCE
#define _XOPEN_SOURCE 700
#endif
#ifdef __sun
#define __EXTENSIONS__ /* to get TIOCGWINSZ */
#endif

#include "xpledge.h"

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

#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>
#include <wchar.h>
#include <termios.h>

#include "blaze822.h"
#include "u8decode.h"

static int cols;
static wchar_t replacement = L'?';
static char *cur;

static char *aliases[32];
static int alias_idx;

static int Iflag;
static int nflag;
static int vflag;
static int curyear;
static time_t now;
static char default_fflag[] = "%c%u%r %-3n %10d %17f %t %2i%s";
static char *fflag = default_fflag;

ssize_t
u8putstr(FILE *out, char *s, ssize_t l, int pad)
{
	ssize_t ol = l;

	while (*s && l > 0) {
		if (*s == '\t')
			*s = ' ';

		if ((unsigned)*s < 32 || *s == 127) {  // C0
			fprintf(out, "%lc", (wint_t)(*s == 127 ? 0x2421 : 0x2400+*s));
			s++;
			l--;
		} else {
			uint32_t c;
			int r = u8decode(s, &c);
			if (r < 0) {
				r = 1;
				l--;
				fprintf(out, "%lc", (wint_t)replacement);
			} else {
				int w = wcwidth((wchar_t)c);
				if (w < 0)
					w = 2;   /* assume worst width */
				l -= w;
				if (l >= 0)
					fwrite(s, 1, r, out);
			}
			s += r;
		}
	}
	if (pad)
		while (l-- > 0)
			putc(' ', out);

	if (l < 0)
		l = 0;
	return ol - l;
}

int
itsme(char *v)
{
	int i;

	char *disp, *addr;
	while ((v = blaze822_addr(v, &disp, &addr)))
		for (i = 0; addr && i < alias_idx; i++)
			if (strcmp(aliases[i], addr) == 0)
				return 1;
	return 0;
}

static int init;

void
numline(char *file)
{
	if (!init) {
		// delay loading of the seq until we need to scan the first
		// file, in case someone in the pipe updated the map before
		char *seq = blaze822_seq_open(0);
		blaze822_seq_load(seq);
		cur = blaze822_seq_cur();
		init = 1;
	}

	while (*file == ' ' || *file == '\t')
		file++;

	long lineno = blaze822_seq_find(file);
	if (lineno)
		printf("%ld\n", lineno);
	else
		printf("%s\n", file);
}

static char *
fmt_date(struct message *msg, int w, int iso)
{
	static char date[32];
	char *v;

	if (!msg)
		return "";

	v = blaze822_hdr(msg, "date");
	if (!v)
		return "(unknown)";
	time_t t = blaze822_date(v);
	if (t == -1)
		return "(invalid)";

	struct tm *tm;
	tm = localtime(&t);

	if (iso) {
		if (w >= 19)
			strftime(date, sizeof date, "%Y-%m-%d %H:%M:%S", tm);
		else if (w >= 16)
			strftime(date, sizeof date, "%Y-%m-%d %H:%M", tm);
		else
			strftime(date, sizeof date, "%Y-%m-%d", tm);
	} else if (w >= 19) {
		// https://dotti.me/

		tm = gmtime(&t);
		strftime(date, sizeof date, "%Y-%m-%dT%H\xc2\xb7%M", tm);
		char *d = date + strlen(date);

		char *e = v + strlen(v);
		while (e > v && (*e != '+' && *e != '-'))
			e--;

		if (isdigit(e[1]) && isdigit(e[2]) && isdigit(e[3]) && isdigit(e[4])) {
			*d++ = e[0];
			*d++ = e[1];
			*d++ = e[2];
			if (e[3] != '0' || e[4] != '0') {
				*d++ = ':';
				*d++ = e[3];
				*d++ = e[4];
			}
			*d = 0;
		} else {
			*d++ = '+';
			*d++ = '0';
			*d++ = '0';
			*d = 0;
		}
	} else if (w < 10) {
		if (tm->tm_year != curyear)
			strftime(date, sizeof date, "%b%y", tm);
		else if (t > now || now - t > 86400)
			strftime(date, sizeof date, "%d%b", tm);
		else
			strftime(date, sizeof date, "%H:%M", tm);
	} else {
		if (tm->tm_year != curyear)
			strftime(date, sizeof date, "%Y-%m-%d", tm);
		else if (t > now || now - t > 86400)
			strftime(date, sizeof date, "%a %b %e", tm);
		else
			strftime(date, sizeof date, "%a  %H:%M", tm);
	}

	return date;
}

static char *
fmt_subject(struct message *msg, char *file, int strip)
{
	static char subjdec[100];
	char *subj = "(no subject)";
	char *v;

	if (!msg) {
		snprintf(subjdec, sizeof subjdec, "\\_ %s", file);
		return subjdec;
	}

	if ((v = blaze822_hdr(msg, "subject")))
		subj = v;

	blaze822_decode_rfc2047(subjdec, subj, sizeof subjdec - 1, "UTF-8");

	if (strip) {
		size_t i;
		for (i = 0; subjdec[i]; ) {
			if (subjdec[i] == ' ') {
				i++;
				continue;
			} else if (strncasecmp("re:", subjdec+i, 3) == 0 ||
				   strncasecmp("aw:", subjdec+i, 3) == 0) {
				i += 3;
				continue;
			} else if (strncasecmp("fwd:", subjdec+i, 4) == 0) {
				i += 4;
				continue;
			}
			break;
		}
		return subjdec + i;
	}

	return subjdec;
}

static char *
fmt_from(struct message *msg)
{
	static char fromdec[256];
	char *from = "(unknown)";
	char *v, *w;

	if (!msg)
		return "";

	if ((v = blaze822_hdr(msg, "from"))) {
		blaze822_decode_rfc2047(fromdec, v, sizeof fromdec - 1, "UTF-8");
		fromdec[sizeof fromdec - 1] = 0;
		from = fromdec;

		if (itsme(fromdec) && ((w = blaze822_hdr(msg, "to")))) {
			memcpy(fromdec, "TO:", 4);
			blaze822_decode_rfc2047(fromdec + 3, w,
			    sizeof fromdec - 1 - 3, "UTF-8");
			from = fromdec;
		} else {
			char *disp, *addr;
			blaze822_addr(fromdec, &disp, &addr);
			if (disp)
				from = disp;
			else if (addr)
				from = addr;
		}
	}

	return from;
}

static char *
fmt_to_flag(struct message *msg)
{
	char *v;

	if (!msg || !alias_idx)
		return " ";

	if ((v = blaze822_hdr(msg, "to")) && itsme(v))
		return ">";
	else if ((v = blaze822_hdr(msg, "cc")) && itsme(v))
		return "+";
	else if ((v = blaze822_hdr(msg, "resent-to")) && itsme(v))
		return ":";
	else if ((v = blaze822_hdr(msg, "from")) && itsme(v))
		return "<";
	else
		return " ";
}

static ssize_t
print_human(intmax_t i, int w)
{
	double d = i / 1024.0;
	const char *u = "\0\0M\0G\0T\0P\0E\0Z\0Y\0";
	while (d >= 1024) {
		u += 2;
		d /= 1024.0;
	}

	if (d < 1.0)
		return printf("%*.2f", w, d);
	else if (!*u)
		return printf("%*.0f", w, d);
	else if (d < 10.0)
		return printf("%*.1f%s", w-1, d, u);
	else
		return printf("%*.0f%s", w-1, d, u);
}

void
oneline(char *file)
{
	if (!init) {
		// delay loading of the seq until we need to scan the first
		// file, in case someone in the pipe updated the map before
		char *seq = blaze822_seq_open(0);
		blaze822_seq_load(seq);
		cur = blaze822_seq_cur();
		init = 1;
	}

	int indent = 0;
	while (*file == ' ' || *file == '\t') {
		indent++;
		file++;
	}

	struct message *msg = blaze822(file);
	char *flags = msg ? strstr(file, ":2,") : 0;
	if (!flags)
		flags = "";
	else
		flags += 3;

	int wleft = cols;

	char *f;
	for (f = fflag; *f; f++) {
		if (*f == '\\') {
			f++;
			switch (*f) {
			case 'n': putchar('\n'); wleft = cols; break;
			case 't': putchar('\t'); wleft -= (8 - wleft % 8); break;
			default:
				putchar('\\'); wleft--;
				putchar(*f); wleft--;
			}
			continue;
		}
		if (*f != '%') {
			putchar(*f);
			wleft--;
			continue;
		}
		f++;

		int w = 0;
		if ((*f >= '0' && *f <= '9') || *f == '-') {
			errno = 0;
			char *e;
			w = strtol(f, &e, 10);
			if (errno != 0)
				w = 0;
			else
				f = e;
		}

		if (!*f)
			break;

		switch (*f) {
		case '%':
			putchar('%');
			wleft--;
			break;
		case 'c':
			if (cur && strcmp(cur, file) == 0)
				putchar('>');
			else
				putchar(' ');
			wleft--;
			break;
		case 'u':  // unseen
			if (strchr(flags, 'T'))
				putchar('x');
			else if (strchr(flags, 'F'))
				putchar('*');
			else if (msg && !strchr(flags, 'S'))
				putchar('.');
			else
				putchar(' ');
			wleft--;
			break;
		case 'r':  // replied
			if (strchr(flags, 'R'))
				putchar('-');
			else if (strchr(flags, 'P'))
				putchar(':');
			else
				putchar(' ');
			wleft--;
			break;
		case 't':  // to-flag
			wleft -= printf("%s", fmt_to_flag(msg));
			break;
		case 'M':  // raw Maildir flags
			if (!w) w = -3;
			wleft -= printf("%*s", w, flags);
			break;
		case 'n':
			{
				long lineno = msg ? blaze822_seq_find(file) : 0;

				if (lineno)
					wleft -= printf("%*ld", w, lineno);
				else
					wleft -= printf("%*s", w, "");
			}
			break;
		case 'd':
		case 'D':
			if (!w) w = 10;
			wleft -= printf("%*s", w,
			    fmt_date(msg, w, Iflag || *f == 'D'));
			break;
		case 'f':
			if (w < 0)
				w += wleft;
			if (w)
				wleft -= u8putstr(stdout,
				    fmt_from(msg), w, 1);
			else
				wleft -= u8putstr(stdout,
				    fmt_from(msg), wleft, 0);
			break;
		case 'i':
			{
				int z;
				if (!w)
					w = 1;

				if (indent >= 10) {
					wleft -= printf("..%2d..", indent);
					indent = 10 - 6/w;
				}

				for (z = 0; z < w*indent; z++)
					putchar(' ');
				wleft -= w*indent;
			}
			break;
		case 's':
		case 'S':
			if (w < 0)
				w += wleft;
			if (w)
				wleft -= u8putstr(stdout,
				    fmt_subject(msg, file, *f == 'S'), w, 1);
			else
				wleft -= u8putstr(stdout,
				    fmt_subject(msg, file, *f == 'S'), wleft, 0);
			break;
		case 'b':
			{
				struct stat st;
				if (msg) {
					if (stat(file, &st) != 0)
						st.st_size = 0;
					wleft -= print_human(st.st_size, w);
				} else {
					wleft -= printf("%.*s", w, "");
				}
			}
			break;
		case 'F':
			{
				char *e = file + strlen(file);

				if (!msg)
					goto empty;

				while (file < e && *e != '/')
					e--;
				if (file == e)
					goto empty;
				e--;
				while (file < e && *e != '/')
					e--;
				while (file < e && *e == '/')
					e--;
				if (file == e)
					goto empty;
				char *b = e;
				e++;
				while (file < b && *b != '/')
					b--;
				if (*b == '/')
					b++;
				if (*b == '.')
					b++;

				if (0) {
empty:
					b = e = "";
				}
				if (w) {
					if (w < 0)
						w = -w;
					wleft -= printf("%*.*s",
					    -w, (int)(e-b < w ? e-b : w), b);
				} else {
					wleft -= printf("%.*s", (int)(e-b), b);
				}
			}
			break;
		case 'R':
			if (w)
				wleft -= printf("%*.*s", w, w, file);
			else
				wleft -= printf("%s", file);
			break;
		case 'I':
			{
				char *m = msg ? blaze822_hdr(msg, "message-id") : 0;
				if (!m)
					m = "(unknown)";
				if (w)
					wleft -= printf("%*.*s", w, w, m);
				else
					wleft -= printf("%s", m);
			}
			break;
		default:
			putchar('%');
			putchar(*f);
			wleft -= 2;
		}
	}

	printf("\n");

	blaze822_free(msg);
}

int
main(int argc, char *argv[])
{
	pid_t pager_pid = -1;

	int c;
	while ((c = getopt(argc, argv, "If:nv")) != -1)
		switch (c) {
		case 'I': Iflag++; break;
		case 'f': fflag = optarg; break;
		case 'n': nflag = 1; break;
		case 'v': vflag = 1; break;
		default:
			fprintf(stderr, "Usage: mscan [-Inv] [-f format] [msgs...]\n");
			exit(1);
		}

	xpledge("stdio rpath tty proc exec", NULL);

	if (nflag) {
		if (argc == optind && isatty(0))
			blaze822_loop1(":", numline);
		else
			blaze822_loop(argc-optind, argv+optind, numline);
		return 0;
	}

	now = time(0);
	struct tm *tm = localtime(&now);
	curyear = tm->tm_year;

	setlocale(LC_ALL, "");  // for wcwidth later
	if (wcwidth(0xfffd) > 0)
		replacement = 0xfffd;

	struct winsize w;
	int ttyfd = open("/dev/tty", O_RDONLY | O_NOCTTY);
	if (ttyfd >= 0 && ioctl(ttyfd, TIOCGWINSZ, &w) == 0) {
		cols = w.ws_col;

		char *pg;
		pg = getenv("MBLAZE_PAGER");
		if (!pg)
			pg = getenv("PAGER");
		if (pg && *pg && strcmp(pg, "cat") != 0) {
			pager_pid = pipeto(pg);
			if (pager_pid < 0)
				fprintf(stderr,
				    "mscan: spawning pager '%s': %s\n",
				    pg, strerror(errno));
		}
	}
	if (ttyfd >= 0)
		close(ttyfd);

	xpledge("stdio rpath", "");

	if (getenv("COLUMNS"))
		cols = atoi(getenv("COLUMNS"));
	if (cols <= 40)
		cols = 80;

	char *f = blaze822_home_file("profile");
	struct message *config = blaze822(f);

	if (config) {
		char *v, *d, *a;
		if ((v = blaze822_hdr(config, "local-mailbox")))
			while (alias_idx < (int)(sizeof aliases / sizeof aliases[0]) &&
			    (v = blaze822_addr(v, &d, &a)))
				if (a)
					aliases[alias_idx++] = strdup(a);
		if ((v = blaze822_hdr(config, "alternate-mailboxes")))
			while (alias_idx < (int)(sizeof aliases / sizeof aliases[0]) &&
			    (v = blaze822_addr(v, &d, &a)))
				if (a)
					aliases[alias_idx++] = strdup(a);
		if ((v = blaze822_hdr(config, "scan-format")))
			if (fflag == default_fflag)  // NB. ==
				fflag = v;
	}

	long i;
	if (argc == optind && isatty(0))
		i = blaze822_loop1(":", oneline);
	else
		i = blaze822_loop(argc-optind, argv+optind, oneline);

	if (pager_pid > 0)
		pipeclose(pager_pid);

	if (vflag)
		fprintf(stderr, "%ld mails scanned\n", i);

	return 0;
}