about summary refs log tree commit diff
path: root/mmime.c
blob: 5d667b9e4cb7e524417e54f8df565a51c419f4a5 (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
#include <sys/stat.h>
#include <sys/types.h>

#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <pwd.h>
#include <search.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include "blaze822.h"

static int cflag;
static int rflag;
static char *tflag = "multipart/mixed";

int gen_b64(uint8_t *s, off_t size)
{
	static char *b64 =
	    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

	off_t i;
	int l;
	uint32_t v;
	for (i = 0, l = 0; i+2 < size; i += 3) {
		v = (s[i] << 16) | (s[i+1] << 8) | s[i+2];
		putc_unlocked(b64[(v & 0xfc0000) >> 18], stdout);
		putc_unlocked(b64[(v & 0x03f000) >> 12], stdout);
		putc_unlocked(b64[(v & 0x000fc0) >>  6], stdout);
		putc_unlocked(b64[(v & 0x3f)], stdout);
		l += 4;
		if (l > 72) {
			l = 0;
			printf("\n");
		}
	}
	if (size - i == 2) { // 2 bytes left, XXX=
		v = (s[size - 2] << 16) | (s[size - 1] << 8);
		putc_unlocked(b64[(v & 0xfc0000) >> 18], stdout);
		putc_unlocked(b64[(v & 0x03f000) >> 12], stdout);
		putc_unlocked(b64[(v & 0x000fc0) >>  6], stdout);
		putc_unlocked('=', stdout);
	} else if (size - i == 1) { // 1 byte left, XX==
		v = s[size - 1] << 16;
		putc_unlocked(b64[(v & 0xfc0000) >> 18], stdout);
		putc_unlocked(b64[(v & 0x03f000) >> 12], stdout);
		putc_unlocked('=', stdout);
		putc_unlocked('=', stdout);
	}
	printf("\n");
	return 0;
}

int gen_qp(uint8_t *s, off_t size, int maxlinelen, int linelen)
{
	off_t i;
	int header = linelen > 0;
	char prev = 0;

	for (i = 0; i < size; i++) {
		// inspect utf8 sequence to not wrap in between multibyte
		int mb;
		if      ((s[i] & 0x80) == 0)    mb = 3;
		else if ((s[i] & 0xc0) == 0x80) mb = 3;
		else if ((s[i] & 0xe0) == 0xc0) mb = 6;
		else if ((s[i] & 0xf0) == 0xe0) mb = 9;
		else if ((s[i] & 0xf8) == 0xf0) mb = 12;
		else mb = 3;

		if (linelen >= maxlinelen-mb-!!header) {
			linelen = 0;
			prev = '\n';
			if (header) {
				printf("?=\n =?UTF-8?Q?");
				linelen += 11;
			} else {
				puts("=");
			}
		}

		if ((s[i] > 126) ||
		    (s[i] < 32 && s[i] != '\n' && s[i] != '\t') ||
		    (s[i] == '=')) {
			printf("=%02X", s[i]);
			linelen += 3;
			prev = s[i];
		} else if (header &&
			   (s[i] == '\n' || s[i] == '\t' || s[i] == '_')) {
			printf("=%02X", s[i]);
			linelen += 3;
			prev = '_';
		} else if (header && s[i] == ' ') {
			putc_unlocked('_', stdout);
			linelen++;
			prev = '_';
		} else if (s[i] == '\n') {
			if (prev == ' ' || prev == '\t')
				puts("=");
			putc_unlocked('\n', stdout);
			linelen = 0;
			prev = 0;
		} else {
			putc_unlocked(s[i], stdout);
			linelen++;
			prev = s[i];
		}
	}
	if (linelen > 0 && !header)
		puts("=");
	return linelen;
}

static const char *
basenam(const char *s)
{
	char *r = strrchr(s, '/');
	return r ? r + 1 : s;
}

static void
gen_attachment(const char *filename, char *content_disposition)
{
	const char *s = filename;
	int quote = 0;

	if (!*filename) {
		printf("Content-Disposition: %s\n", content_disposition);
		return;
	}

	for (s = (char *) filename; *s; s++) {
		if (*s < 32 || *s == '"' || *s >= 127 || s - filename > 35)
			goto rfc2231;
		if (strchr(" ()<>@,;:\\/[]?=", *s))
			quote = 1;
	}

	// filename SHOULD be an atom if possible
	printf("Content-Disposition: %s; filename=%s%s%s\n", content_disposition,
	    quote ? "\"" : "", filename, quote ? "\"" : "");
	return;

rfc2231:
	printf("Content-Disposition: %s", content_disposition);
	int i = 0;
	int d = 0;

	s = filename;

	while (*s) {
		i = printf(";\n filename*%d*=", d);
		if (d++ == 0) {
			printf("UTF-8''");
			i += 7;
		}
		while (*s && i < 78 - 3) {
			if (*s <= 32 || *s == '"' || *s > 126)
				i += printf("%%%02x", (uint8_t) *s++);
			else
				i += printf("%c", (uint8_t) *s++);
		}
	}

	printf("\n");
}

int
gen_file(char *file, char *ct)
{
	uint8_t *content;
	off_t size;

	char *cd = "attachment";
	char *s = strchr(ct, '#');
	if (s) {
		*s = 0;
		cd = s + 1;
	}

	const char *filename = basenam(file);
	s = strchr(file, '>');
	if (s) {
		*s = 0;
		filename = s + 1;
	}

	int r = slurp(file, (char **)&content, &size);
	if (r != 0) {
		fprintf(stderr, "mmime: error attaching file '%s': %s\n",
		    file, strerror(r));
		return -1;
	}
	
	if (strcmp(ct, "mblaze/raw") == 0)
		goto raw;

	off_t bithigh = 0;
	off_t bitlow = 0;
	off_t linelen = 0;
	off_t maxlinelen = 0;
	off_t i;
	for (i = 0; i < size; i++) {
		if (content[i] == '\n') {
			if (maxlinelen < linelen)
				maxlinelen = linelen;
			linelen = 0;
		} else {
			linelen++;
		}
		if (content[i] != '\t' && content[i] != '\n' && content[i] < 32)
			bitlow++;
		if (content[i] > 127)
			bithigh++;
	}

	gen_attachment(filename, cd);

	if (bitlow == 0 && bithigh == 0 &&
	    maxlinelen <= 78 && content[size-1] == '\n') {
		if (!ct)
			ct = "text/plain";
		printf("Content-Type: %s\n", ct);
		printf("Content-Transfer-Encoding: 7bit\n\n");
raw:
		fwrite(content, 1, size, stdout);
		return 0;
	} else if (bitlow == 0 && bithigh == 0) {
		if (!ct)
			ct = "text/plain";
		printf("Content-Type: %s\n", ct);
		printf("Content-Transfer-Encoding: quoted-printable\n\n");
		gen_qp(content, size, 78, 0);
		return 0;
	} else if (bitlow > size/10 || bithigh > size/4) {
		if (!ct)
			ct = "application/binary";
		printf("Content-Type: %s\n", ct);
		printf("Content-Transfer-Encoding: base64\n\n");
		return gen_b64(content, size);
	} else {
		if (!ct)
			ct = "text/plain";
		printf("Content-Type: %s\n", ct);
		printf("Content-Transfer-Encoding: quoted-printable\n\n");
		gen_qp(content, size, 78, 0);
		return 0;
	}
}

void
print_header(char *line) {
	char *s, *e;
	size_t l = strlen(line);

	if (line[l-1] == '\n')
		line[l-1] = 0;

	/* iterate word-wise, encode words when needed. */

	s = line;

	if (!(*s == ' ' || *s == '\t')) {
		// raw header name
		while (*s && *s != ':')
			putc_unlocked(*s++, stdout);
		if (*s == ':')
			putc_unlocked(*s++, stdout);
	}

	int prevq = 0;  // was the previous word encoded as qp?

	int linelen = s - line;

	while (*s) {
		size_t highbit = 0;
		e = s;
		while (*e && *e == ' ')
			e++;
		for (; *e && *e != ' '; e++) {
			if ((uint8_t) *e >= 127)
				highbit++;
		}

		if (!highbit) {
			if (e-s >= 998)
				goto force_qp;
			if (e-s >= 78 - linelen) {
				// wrap in advance before long word
				printf("\n");
				linelen = 0;
			}
			if (linelen <= 1 && s[0] == ' ' && s[1] == ' ') {
				// space at beginning of line
				goto force_qp;
			}
			if (*s != ' ') {
				printf(" ");
				linelen++;
			}
			fwrite(s, 1, e-s, stdout);
			linelen += e-s;
			prevq = 0;
		} else {
force_qp:
			if (!prevq && *s == ' ')
				s++;
			if (linelen >= 78 - 13 - 4 ||
			    (e-s < (78 - 13)/3 &&
			     e-s >= (78 - linelen - 13)/3)) {
				// wrap in advance
				printf("\n");
				linelen = 0;
			}
			printf(" =?UTF-8?Q?");
			linelen += 11;
			linelen = gen_qp((uint8_t *)s, e-s, 78, linelen);
			printf("?=");
			linelen += 2;
			prevq = 1;
		}
		s = e;
	}
	printf("\n");
}

int
gen_build()
{
	char sep[100];
	snprintf(sep, sizeof sep, "----_=_%08lx%08lx%08lx_=_",
	    lrand48(), lrand48(), lrand48());

	char *line = 0;
	size_t linelen = 0;
	int inheader = 1;
	int intext = 0;

	while (1) {
		int read = getdelim(&line, &linelen, '\n', stdin);
		if (read == -1) {
			if (feof(stdin))
				break;
			else
				exit(1);
		}
		if (inheader) {
			if (line[0] == '\n') {
				inheader = 0;
				printf("MIME-Version: 1.0\n");
				if (rflag) {
					printf("Content-Type: text/plain; charset=UTF-8\n");
					printf("Content-Transfer-Encoding: quoted-printable\n\n");

				} else {
					printf("Content-Type: %s; boundary=\"%s\"\n", tflag, sep);
					printf("\n");
					printf("This is a multipart message in MIME format.\n");
				}
			} else {
				print_header(line);
			}
			continue;
		}

		if (!rflag && line[0] == '#') {
			char *f = strchr(line, ' ');
			if (f) {
				char of = *f;
				*f = 0;
				if (strchr(line, '/')) {
					printf("\n--%s\n", sep);
					if (line[read-1] == '\n')
						line[read-1] = 0;
					gen_file(f+1, (char *)line+1);
					intext = 0;
					continue;
				}
				*f = of;
			}
		}

		if (!rflag && !intext) {
			printf("\n--%s\n", sep);
			printf("Content-Type: text/plain; charset=UTF-8\n");
			printf("Content-Disposition: inline\n");
			printf("Content-Transfer-Encoding: quoted-printable\n\n");
			
			intext = 1;
		}

		gen_qp((uint8_t *)line, strlen(line), 78, 0);
	}
	if (!rflag && !inheader)
		printf("\n--%s--\n", sep);

	free(line);
	return 0;
}

int
check()
{
	off_t bithigh = 0;
	off_t bitlow = 0;
	off_t linelen = 0;
	off_t maxheadlinelen = 0;
	off_t maxbodylinelen = 0;

	int c;
	int l = -1;

	while ((c = getchar()) != EOF) {
		if (c == '\n') {
			if (maxheadlinelen < linelen)
				maxheadlinelen = linelen;
			linelen = 0;
			if (l == '\n')
				break;
		} else {
			linelen++;
		}
		if (c != '\t' && c != '\n' && c < 32)
			bitlow++;
		if (c > 127)
			bithigh++;
		l = c;
	}

	while ((c = getchar()) != EOF) {
		if (c == '\n') {
			if (maxbodylinelen < linelen)
				maxbodylinelen = linelen;
			linelen = 0;
		} else {
			linelen++;
		}
		if (c != '\t' && c != '\n' && c < 32)
			bitlow++;
		if (c > 127)
			bithigh++;
		l = c;
	}

	if (bitlow == 0 && bithigh == 0 &&
	    maxheadlinelen < 998 && maxbodylinelen <= 78 &&
	    l == '\n')
		return 0;
	else
		return 1;
}

int
main(int argc, char *argv[])
{
	srand48(time(0) ^ getpid());

	int c;
	while ((c = getopt(argc, argv, "crt:")) != -1)
		switch(c) {
		case 'r': rflag = 1; break;
		case 'c': cflag = 1; break;
		case 't': tflag = optarg; break;
		default:
		usage:
			fprintf(stderr,
"Usage: mmime [-c|-r] [-t CONTENT-TYPE] < message\n");
			exit(1);
		}

	if (argc != optind)
		goto usage;

	if (cflag)
		return check();

	return gen_build();
}