summary refs log tree commit diff
path: root/imbox.c
blob: 24ac67b5380b5549bcca4b93479e1a8f5575d5e0 (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
/* Copyright (C) 2019  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 "compat.h"

#include <ctype.h>
#include <err.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <sysexits.h>
#include <tls.h>
#include <unistd.h>

#ifndef NO_READPASSPHRASE_H
#include <readpassphrase.h>
#endif

#if !defined(DIG_PATH) && !defined(DRILL_PATH)
#	ifdef __FreeBSD__
#		define DRILL_PATH "/usr/bin/drill"
#	else
#		define DIG_PATH "dig"
#	endif
#endif

static void mboxrd(char *headers, char *body) {
	printf("From mboxrd@z Thu Jan  1 00:00:00 1970\n");
	for (char *crlf; (crlf = strstr(headers, "\r\n")); headers = &crlf[2]) {
		*crlf = '\0';
		printf("%s\n", headers);
	}
	for (char *crlf; (crlf = strstr(body, "\r\n")); body = &crlf[2]) {
		*crlf = '\0';
		char *from = body;
		while (*from == '>') from++;
		if (!strncmp(from, "From ", 5)) {
			printf(">%s\n", body);
		} else {
			printf("%s\n", body);
		}
	}
	printf("\n");
}

static void lookup(const char **host, const char **port, const char *domain) {
	static char buf[1024];
	snprintf(buf, sizeof(buf), "_imaps._tcp.%s", domain);

	int rw[2];
	int error = pipe(rw);
	if (error) err(EX_OSERR, "pipe");

	pid_t pid = fork();
	if (pid < 0) err(EX_OSERR, "fork");

	if (!pid) {
		close(rw[0]);
		dup2(rw[1], STDOUT_FILENO);
		dup2(rw[1], STDERR_FILENO);
		close(rw[1]);
#ifdef DRILL_PATH
		execlp(DRILL_PATH, DRILL_PATH, buf, "SRV", NULL);
		err(EX_CONFIG, "%s", DRILL_PATH);
#else
		execlp(DIG_PATH, DIG_PATH, "-t", "SRV", "-q", buf, "+short", NULL);
		err(EX_CONFIG, "%s", DIG_PATH);
#endif
	}

	int status;
	pid = wait(&status);
	if (pid < 0) err(EX_OSERR, "wait");

	close(rw[1]);
	FILE *pipe = fdopen(rw[0], "r");
	if (!pipe) err(EX_IOERR, "fdopen");

	fgets(buf, sizeof(buf), pipe);
	if (ferror(pipe)) err(EX_IOERR, "fgets");

	if (!WIFEXITED(status) || WEXITSTATUS(status)) {
		fprintf(stderr, "%s", buf);
		exit(WEXITSTATUS(status));
	}

	char *ptr = buf;
#ifdef DRILL_PATH
	for (;;) {
		char *line = fgets(buf, sizeof(buf), pipe);
		if (!line || !strcmp(line, ";; ANSWER SECTION:\n")) break;
	}
	fgets(buf, sizeof(buf), pipe);
	if (ferror(pipe)) err(EX_IOERR, "fgets");
	ptr = strrchr(buf, '\t');
	ptr = (ptr ? ptr + 1 : buf);
#endif
	fclose(pipe);

	char *dot = strrchr(ptr, '.');
	if (dot) *dot = '\0';
	strsep(&ptr, " \n"); // priority
	strsep(&ptr, " \n"); // weight
	*port = strsep(&ptr, " \n");
	*host = strsep(&ptr, " \n");
	if (!*host) {
		*host = domain;
		*port = "imaps";
	}
}

static bool verbose;

static int tlsRead(void *_tls, char *ptr, int len) {
	struct tls *tls = _tls;
	ssize_t ret;
	do {
		ret = tls_read(tls, ptr, len);
	} while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
	if (ret < 0) errx(EX_IOERR, "tls_read: %s", tls_error(tls));
	if (verbose) fprintf(stderr, "%.*s", (int)ret, ptr);
	return ret;
}

static int tlsWrite(void *_tls, const char *ptr, int len) {
	struct tls *tls = _tls;
	ssize_t ret;
	do {
		ret = tls_write(tls, ptr, len);
	} while (ret == TLS_WANT_POLLIN || ret == TLS_WANT_POLLOUT);
	if (ret < 0) errx(EX_IOERR, "tls_write: %s", tls_error(tls));
	if (verbose) fprintf(stderr, "%.*s", (int)ret, ptr);
	return ret;
}

static int tlsClose(void *_tls) {
	struct tls *tls = _tls;
	int error = tls_close(tls);
	if (error) errx(EX_IOERR, "tls_close: %s", tls_error(tls));
	return error;
}

#define ENUM_ATOM \
	X(Unknown, "") \
	X(Untagged, "*") \
	X(Ok, "OK") \
	X(No, "NO") \
	X(Bad, "BAD") \
	X(Bye, "BYE") \
	X(Login, "LOGIN") \
	X(Examine, "EXAMINE") \
	X(Search, "SEARCH") \
	X(Fetch, "FETCH")

enum Atom {
#define X(id, _) id,
	ENUM_ATOM
#undef X
	AtomsLen,
};

static const char *Atoms[AtomsLen] = {
#define X(id, str) [id] = str,
	ENUM_ATOM
#undef X
};

static enum Atom atom(const char *str) {
	if (!str) return Unknown;
	for (enum Atom i = 0; i < AtomsLen; ++i) {
		if (!strcmp(str, Atoms[i])) return i;
	}
	return Unknown;
}

static char *readLiteral(FILE *imap, const char *line) {
	char *prefix = strrchr(line, '{');
	if (!prefix) errx(EX_PROTOCOL, "no literal prefix");

	size_t size = strtoul(prefix + 1, NULL, 10);
	if (!size) errx(EX_PROTOCOL, "invalid literal size");

	char *literal = malloc(size + 1);
	if (!literal) err(EX_OSERR, "malloc");

	size_t count = fread(literal, size, 1, imap);
	if (!count) errx(EX_PROTOCOL, "could not read literal");

	literal[size] = '\0';
	return literal;
}

int main(int argc, char *argv[]) {
	const char *host = NULL;
	const char *port = "imaps";
	const char *mailbox = "INBOX";
	const char *subject = "[PATCH";
	const char *from = NULL;
	const char *to = NULL;
	const char *cc = NULL;
	int rppFlags = 0;

	int opt;
	while (0 < (opt = getopt(argc, argv, "C:F:S:T:h:m:p:vw"))) {
		switch (opt) {
			break; case 'C': cc = optarg;
			break; case 'F': from = optarg;
			break; case 'S': subject = optarg;
			break; case 'T': to = optarg;
			break; case 'h': host = optarg;
			break; case 'm': mailbox = optarg;
			break; case 'p': port = optarg;
			break; case 'v': verbose = true;
			break; case 'w': rppFlags |= RPP_STDIN;
			break; default:  return EX_USAGE;
		}
	}

	const char *user = argv[optind];
	if (!user) errx(EX_USAGE, "username required");

	if (!host) {
		const char *domain = strchr(user, '@');
		if (!domain) errx(EX_USAGE, "no domain in username");
		lookup(&host, &port, &domain[1]);
	}

	char buf[1024];
	char *pass = readpassphrase(
		(rppFlags & RPP_STDIN ? "" : "Password: "),
		buf, sizeof(buf), rppFlags
	);
	if (!pass) err(EX_UNAVAILABLE, "readpassphrase");

	struct tls *client = tls_client();
	if (!client) errx(EX_SOFTWARE, "tls_client");

	struct tls_config *config = tls_config_new();
	if (!config) errx(EX_SOFTWARE, "tls_config_new");

	int error = tls_configure(client, config);
	if (error) errx(EX_SOFTWARE, "tls_configure: %s", tls_error(client));
	tls_config_free(config);

	error = tls_connect(client, host, port);
	if (error) errx(EX_NOHOST, "tls_connect: %s", tls_error(client));

	FILE *imap = funopen(client, tlsRead, tlsWrite, NULL, tlsClose);
	if (!imap) err(EX_SOFTWARE, "funopen");
	setlinebuf(imap);

	bool login = false;
	char *nums = NULL;

	char *line = NULL;
	size_t cap = 0;
	while (0 < getline(&line, &cap, imap)) {
		char *cr = strchr(line, '\r');
		if (cr) *cr = '\0';

		char *rest = line;
		enum Atom tag = atom(strsep(&rest, " "));
		if (rest && isdigit(rest[0])) {
			strsep(&rest, " ");
		}
		enum Atom resp = atom(strsep(&rest, " "));

		if (resp == No || resp == Bad || resp == Bye) {
			errx(
				EX_CONFIG, "%s: %s %s",
				Atoms[tag], Atoms[resp], (rest ? rest : "")
			);
		}

		switch (tag) {
			break; case Untagged: {
				if (login) break;
				fprintf(
					imap, "%s LOGIN \"%s\" \"%s\"\r\n",
					Atoms[Login], user, pass
				);
				login = true;
			}
			break; case Login: {
				fprintf(imap, "%s EXAMINE \"%s\"\r\n", Atoms[Examine], mailbox);
			}
			break; case Examine: {
				fprintf(
					imap,
					"%s SEARCH CHARSET UTF-8 OR "
					"NOT HEADER Content-Type \"\" "
					"HEADER Content-Type \"text/plain\"",
					Atoms[Search]
				);
				if (subject) fprintf(imap, " SUBJECT \"%s\"", subject);
				if (from) fprintf(imap, " FROM \"%s\"", from);
				if (to) fprintf(imap, " TO \"%s\"", to);
				if (cc) fprintf(imap, " CC \"%s\"", cc);
				fprintf(imap, "\r\n");
			}
			break; case Search: {
				if (!nums) errx(EX_PROTOCOL, "no search response");
				for (char *ch = nums; *ch; ++ch) {
					if (*ch == ' ') *ch = ',';
				}
				fprintf(
					imap,
					"%s FETCH %s (BODY[HEADER.FIELDS ("
					"Date From To Cc Subject Message-Id In-Reply-To References "
					"Content-Transfer-Encoding"
					")] BODY[TEXT])\r\n",
					Atoms[Fetch], nums
				);
				free(nums);
				nums = NULL;
			}
			break; case Fetch: {
				fprintf(imap, "ayy LOGOUT\r\n");
				fclose(imap);
				return EX_OK;
			}
			break; default:;
		}

		switch (resp) {
			break; case Search: {
				if (!rest) errx(EX_TEMPFAIL, "no matching messages");
				nums = strdup(rest);
				if (!nums) err(EX_OSERR, "strdup");
			}
			break; case Fetch: {
				char *headers = readLiteral(imap, rest);

				ssize_t len = getline(&line, &cap, imap);
				if (len <= 0) errx(EX_PROTOCOL, "unexpected eof after headers");

				char *body = readLiteral(imap, line);

				len = getline(&line, &cap, imap);
				if (len <= 0) errx(EX_PROTOCOL, "unexpected eof after body");
				if (strcmp(line, ")\r\n")) {
					errx(EX_PROTOCOL, "trailing data after headers and body");
				}

				mboxrd(headers, body);
				free(headers);
				free(body);
			}
			break; default:;
		}
	}
	errx(EX_PROTOCOL, "unexpected eof");
}