about summary refs log tree commit diff
path: root/export.c
blob: 4728810833c682d94523d4d7ead0c7b8362fdc4d (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
/* Copyright (C) 2020  C. McEnroe <june@causal.agency>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include <err.h>
#include <errno.h>
#include <inttypes.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/stat.h>
#include <sysexits.h>
#include <unistd.h>

#include "archive.h"
#include "imap.h"

static const char *exportPath(uint32_t uid, const char *type) {
	static char buf[PATH_MAX];
	char str[32];
	snprintf(str, sizeof(str), "%" PRIu32, uid);
	struct Variable vars[] = {
		{ "uid", str },
		{ "type", type },
		{0},
	};
	templateBuffer(buf, sizeof(buf), PATH_UID, vars, escapePath);
	return buf;
}

bool exportFetch(FILE *imap, enum Atom tag, struct List threads) {
	struct List uids = {0};
	listFlatten(&uids, threads);
	for (size_t i = uids.len - 1; i < uids.len; --i) {
		uint32_t uid = dataCheck(uids.ptr[i], Number).number;
		int error = 0
			|| access(exportPath(uid, "atom"), F_OK)
			|| access(exportPath(uid, "html"), F_OK)
			|| access(exportPath(uid, "mbox"), F_OK);
		if (!error) uids.ptr[i] = uids.ptr[--uids.len];
	}
	if (!uids.len) {
		listFree(uids);
		return false;
	}

	fprintf(imap, "%s UID FETCH ", Atoms[tag]);
	for (size_t i = 0; i < uids.len; ++i) {
		fprintf(imap, "%s%" PRIu32, (i ? "," : ""), uids.ptr[i].number);
	}
	listFree(uids);
	fprintf(
		imap,
		" (UID ENVELOPE BODYSTRUCTURE"
		" BODY[HEADER.FIELDS (" MBOX_HEADERS ")] BODY[TEXT])\r\n"
	);
	return true;
}

static void exportMbox(
	uint32_t uid, const struct Envelope *envelope,
	const char *header, const char *body
) {
	const char *path = exportPath(uid, "mbox");
	FILE *file = fopen(path, "w");
	if (!file) err(EX_CANTCREAT, "%s", path);
	int error = 0
		|| mboxFrom(file)
		|| mboxHeader(file, header)
		|| mboxBody(file, body)
		|| fclose(file);
	if (error) err(EX_IOERR, "%s", path);

	char buf[PATH_MAX];
	struct Variable vars[] = {
		{ "messageID", envelope->messageID },
		{ "type", "mbox" },
		{0},
	};
	templateBuffer(buf, sizeof(buf), PATH_MESSAGE, vars, escapePath);

	unlink(buf);
	error = link(path, buf);
	if (error) err(EX_CANTCREAT, "%s", buf);
}

static bool isInline(const struct BodyPart *part) {
	if (!bodyPartType(part, "text", "plain")) return false;
	if (!part->disposition.type) return true;
	return !strcasecmp(part->disposition.type, "inline");
}

static bool isAttachment(const struct BodyPart *part) {
	if (isInline(part)) return false;
	return !part->multipart && !part->message.structure;
}

static void exportAtom(
	uint32_t uid, const struct Envelope *envelope,
	const struct BodyPart *structure, struct Data body
) {
	const char *path = exportPath(uid, "atom");
	FILE *file = fopen(path, "w");
	if (!file) err(EX_CANTCREAT, "%s", path);

	int error = atomEntryOpen(file, envelope);
	if (error) err(EX_IOERR, "%s", path);

	const struct BodyPart *part = structure;
	while (part->multipart) {
		if (bodyPartType(part, "multipart", "alternative")) {
			for (size_t i = part->parts.len - 1; i < part->parts.len; --i) {
				if (!isInline(&part->parts.ptr[i])) continue;
				part = &part->parts.ptr[i];
				body = dataCheck(body, List).list.ptr[i];
				break;
			}
			if (part->multipart) break;
		} else {
			part = &part->parts.ptr[0];
			body = dataCheck(body, List).list.ptr[0];
		}
	}
	if (isInline(part)) {
		char *content = decodeToString(part, dataCheck(body, String).string);
		error = atomContent(file, content);
		if (error) err(EX_IOERR, "%s", path);
		free(content);
	}

	error = atomEntryClose(file) || fclose(file);
	if (error) err(EX_IOERR, "%s", path);
}

static const char *sectionName(struct List section) {
	static char buf[1024];
	char str[32];
	buf[0] = '\0';
	for (size_t i = 0; i < section.len; ++i) {
		snprintf(
			str, sizeof(str), "%s%" PRIu32,
			(i ? "." : ""), dataCheck(section.ptr[i], Number).number
		);
		strlcat(buf, str, sizeof(buf));
	}
	return buf;
}

static int exportHTMLAttachment(
	FILE *file, const struct Envelope *envelope, struct List section,
	const struct BodyPart *part, struct Data body
) {
	const char *name = paramGet(part->disposition.params, "filename");
	if (!name) name = paramGet(part->params, "name");

	const char *disposition = part->disposition.type;
	if (!disposition) disposition = "INLINE";

	char path[PATH_MAX];
	struct Variable vars[] = {
		{ "messageID", envelope->messageID },
		{ "section", sectionName(section) },
		{ "name", (name ? name : "") },
		{ "disposition", (name ? "" : disposition) },
		{ ".", (name ? "" : ".") },
		{ "subtype", (name ? "" : part->subtype) },
		{0},
	};
	templateBuffer(path, sizeof(path), PATH_ATTACHMENT, vars, escapePath);

	for (char *ch = path; (ch = strchr(ch, '/')); ++ch) {
		*ch = '\0';
		int error = mkdir(path, 0775);
		if (error && errno != EEXIST) err(EX_CANTCREAT, "%s", path);
		*ch = '/';
	}

	FILE *attachment = fopen(path, "w");
	if (!file) err(EX_CANTCREAT, "%s", path);

	int error = 0
		|| decodeToFile(attachment, part, dataCheck(body, String).string)
		|| fclose(attachment);
	if (error) err(EX_IOERR, "%s", path);

	return htmlAttachment(file, part, vars);
}

static int exportHTMLBody(
	FILE *file, const struct Envelope *envelope, struct List *section,
	const struct BodyPart *part, struct Data body
) {
	if (bodyPartType(part, "multipart", "alternative")) {
		for (size_t i = part->parts.len - 1; i < part->parts.len; --i) {
			if (!isInline(&part->parts.ptr[i])) continue;
			return exportHTMLBody(
				file, envelope, section,
				&part->parts.ptr[i], dataCheck(body, List).list.ptr[i]
			);
		}
		return exportHTMLBody(
			file, envelope, section,
			&part->parts.ptr[part->parts.len - 1],
			dataCheck(body, List).list.ptr[part->parts.len - 1]
		);

	} else if (part->multipart) {
		int error;
		bool attached = false;
		for (size_t i = 0; i < part->parts.len; ++i) {
			if (attached != isAttachment(&part->parts.ptr[i])) {
				attached ^= true;
				error = attached
					? htmlAttachmentOpen(file)
					: htmlAttachmentClose(file);
				if (error) return error;
			}
			struct Data num = { .type = Number, .number = 1 + i };
			listPush(section, num);
			error = exportHTMLBody(
				file, envelope, section,
				&part->parts.ptr[i], dataCheck(body, List).list.ptr[i]
			);
			if (error) return error;
			section->len--;
		}
		return (attached ? htmlAttachmentClose(file) : 0);

	} else if (part->message.structure) {
		const struct BodyPart *structure = part->message.structure;
		int error = 0
			|| htmlMessageOpen(file, part->message.envelope)
			|| exportHTMLBody(file, envelope, section, structure, body)
			|| htmlMessageClose(file);
		return error;

	} else if (isInline(part)) {
		char *content = decodeToString(part, dataCheck(body, String).string);
		int error = htmlInline(file, part, content);
		free(content);
		return error;

	} else {
		return exportHTMLAttachment(file, envelope, *section, part, body);
	}
}

static void exportHTML(
	uint32_t uid, const struct Envelope *envelope,
	const struct BodyPart *structure, struct Data body
) {
	const char *path = exportPath(uid, "html");
	FILE *file = fopen(path, "w");
	if (!file) err(EX_CANTCREAT, "%s", path);

	int error = htmlMessageOpen(file, envelope);
	if (error) err(EX_IOERR, "%s", path);

	struct List section = {0};
	error = exportHTMLBody(file, envelope, &section, structure, body);
	if (error) err(EX_IOERR, "%s", path);
	listFree(section);

	error = htmlMessageClose(file) || fclose(file);
	if (error) err(EX_IOERR, "%s", path);
}

static void fetchParts(
	FILE *imap, struct List *section, const struct BodyPart *structure
) {
	if (structure->multipart) {
		for (size_t i = 0; i < structure->parts.len; ++i) {
			struct Data part = { .type = Number, .number = 1 + i };
			listPush(section, part);
			fetchParts(imap, section, &structure->parts.ptr[i]);
			section->len--;
		}
	} else if (
		structure->message.structure &&
		structure->message.structure->multipart
	) {
		fetchParts(imap, section, structure->message.structure);
	} else {
		fprintf(
			imap, " BODY[%s%s]",
			sectionName(*section), (structure->message.structure ? ".TEXT" : "")
		);
	}
}

static void checkBodyParts(const struct BodyPart *structure, struct Data body) {
	if (structure->multipart) {
		struct List list = dataCheck(body, List).list;
		if (list.len < structure->parts.len) {
			errx(EX_PROTOCOL, "missing body parts");
		}
		for (size_t i = 0; i < structure->parts.len; ++i) {
			checkBodyParts(&structure->parts.ptr[i], list.ptr[i]);
		}
	} else if (
		structure->message.structure &&
		structure->message.structure->multipart
	) {
		checkBodyParts(structure->message.structure, body);
	} else if (body.type != String) {
		errx(EX_PROTOCOL, "missing body part");
	}
}

bool exportData(FILE *imap, enum Atom tag, struct List items) {
	uint32_t uid = 0;
	struct Envelope envelope = {0};
	struct BodyPart structure = {0};
	struct Data bodyHeader = {0};
	struct Data bodyText = {0};
	struct Data bodyParts = {0};

	for (size_t i = 0; i + 1 < items.len; i += 2) {
		enum Atom name = dataCheck(items.ptr[i], Atom).atom;
		struct Data data = items.ptr[i + 1];
		if (name == AtomUID) {
			uid = dataCheck(data, Number).number;
		} else if (name == AtomEnvelope) {
			parseEnvelope(&envelope, dataCheck(data, List).list);
		} else if (name == AtomBodyStructure) {
			parseBodyPart(&structure, dataCheck(data, List).list);
		}
		if (name != AtomBody) continue;

		struct List section = dataCheck(data, List).list;
		if (!section.len) {
			errx(EX_PROTOCOL, "missing body data item section");
		}
		i++;
		if (i + 1 >= items.len) {
			errx(EX_PROTOCOL, "missing body data item value");
		}
		data = items.ptr[i + 1];

		if (section.ptr[0].type == Atom) {
			name = section.ptr[0].atom;
			if (name == AtomHeader) {
				bodyHeader = data;
			} else if (name == AtomText) {
				bodyText = data;
			}
			continue;
		}

		struct Data *dest = &bodyParts;
		for (size_t i = 0; i < section.len; ++i) {
			if (section.ptr[i].type != Number) continue;
			uint32_t num = section.ptr[i].number;
			if (dest->type != List) {
				*dest = (struct Data) { .type = List };
			}
			while (dest->list.len < num) {
				listPush(&dest->list, (struct Data) {0});
			}
			dest = &dest->list.ptr[num - 1];
		}
		// Free with bodyParts:
		*dest = dataTake(&items.ptr[i + 1]);
	}

	if (!uid) {
		errx(EX_PROTOCOL, "missing UID data item");
	}
	if (!envelope.subject) {
		errx(EX_PROTOCOL, "missing ENVELOPE data item");
	}
	if (!structure.subtype) {
		errx(EX_PROTOCOL, "missing BODYSTRUCTURE data item");
	}
	if (bodyParts.type == List) {
		checkBodyParts(&structure, bodyParts);
	}

	if (bodyHeader.type == String && bodyText.type == String) {
		exportMbox(uid, &envelope, bodyHeader.string, bodyText.string);
	}

	bool fetch = false;
	if (!structure.multipart) {
		exportAtom(uid, &envelope, &structure, bodyText);
		exportHTML(uid, &envelope, &structure, bodyText);
	} else if (bodyParts.type == List) {
		exportAtom(uid, &envelope, &structure, bodyParts);
		exportHTML(uid, &envelope, &structure, bodyParts);
	} else {
		fetch = true;
		fprintf(
			imap, "%s UID FETCH %" PRIu32 " (UID ENVELOPE BODYSTRUCTURE",
			Atoms[tag], uid
		);
		struct List section = {0};
		fetchParts(imap, &section, &structure);
		listFree(section);
		fprintf(imap, ")\r\n");
	}

	envelopeFree(envelope);
	bodyPartFree(structure);
	dataFree(bodyParts);
	return fetch;
}