aboutsummaryrefslogtreecommitdiff
path: root/gg.c
blob: 8765b1117bafe89450fa8b19d889240db66aaecc (plain)
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
/*
 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "gmid.h"

#include <sys/socket.h>

#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <string.h>

enum debug {
	DEBUG_NONE,
	DEBUG_CODE,
	DEBUG_HEADER,
	DEBUG_META,
	DEBUG_ALL,
};

/* flags */
int		 debug;
int		 dont_verify_name;
int		 flag2;
int		 flag3;
int		 nop;
int		 redirects = 5;
int		 timer;
int		 verbose;
const char	*cert;
const char	*key;
const char	*proxy_host;
const char	*proxy_port;
const char	*sni;

/* state */
struct tls_config *tls_conf;

static void
timeout(int signo)
{
	dprintf(2, "%s: timer expired\n", getprogname());
	exit(1);
}

static void
load_tls_conf(void)
{
	if ((tls_conf = tls_config_new()) == NULL)
		err(1, "tls_config_new");

	tls_config_insecure_noverifycert(tls_conf);
	if (dont_verify_name)
		tls_config_insecure_noverifyname(tls_conf);

	if (flag2 &&
	    tls_config_set_protocols(tls_conf, TLS_PROTOCOL_TLSv1_2) == -1)
		errx(1, "can't set TLSv1.2");
	if (flag3 &&
	    tls_config_set_protocols(tls_conf, TLS_PROTOCOL_TLSv1_3) == -1)
		errx(1, "can't set TLSv1.3");

	if (cert != NULL &&
	    tls_config_set_keypair_file(tls_conf, cert, key) == -1)
		errx(1, "can't load client certificate %s", cert);
}

static void
connectto(struct tls *ctx, const char *host, const char *port)
{
	struct addrinfo hints, *res, *res0;
	int error;
	int saved_errno;
	int s;
	const char *cause = NULL;
	const char *sname;

	if (proxy_host != NULL) {
		host = proxy_host;
		port = proxy_port;
	}

	if ((sname = sni) == NULL)
		sname = host;

	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	error = getaddrinfo(host, port, &hints, &res0);
	if (error)
		errx(1, "%s", gai_strerror(error));

	s = -1;
	for (res = res0; res != NULL; res = res->ai_next) {
		s = socket(res->ai_family, res->ai_socktype,
		    res->ai_protocol);
		if (s == -1) {
			cause = "socket";
			continue;
		}

		if (connect(s, res->ai_addr, res->ai_addrlen) == -1) {
			cause = "connect";
			saved_errno = errno;
			close(s);
			errno = saved_errno;
			s = -1;
			continue;
		}

		break;
	}

	if (s == -1)
		err(1, "%s: can't connect to %s:%s", cause,
		    host, port);

	freeaddrinfo(res0);

	if (tls_connect_socket(ctx, s, sname) == -1)
		errx(1, "tls_connect_socket: %s", tls_error(ctx));
}

static void
doreq(struct tls *ctx, const char *buf)
{
	size_t	s;
	ssize_t	w;

	s = strlen(buf);
	while (s != 0) {
		switch (w = tls_write(ctx, buf, s)) {
		case 0:
		case -1:
			errx(1, "tls_write: %s", tls_error(ctx));
		case TLS_WANT_POLLIN:
		case TLS_WANT_POLLOUT:
			continue;
		}

		s -= w;
		buf += w;
	}
}

static size_t
dorep(struct tls *ctx, void *buf, size_t len)
{
	ssize_t	w;
	size_t	tot = 0;

	while (len != 0) {
		switch (w = tls_read(ctx, buf, len)) {
		case 0:
			return tot;
		case -1:
			errx(1, "tls_write: %s", tls_error(ctx));
		case TLS_WANT_POLLIN:
		case TLS_WANT_POLLOUT:
			continue;
		}

		len -= w;
		buf += w;
		tot += w;
	}

	return tot;
}

static int
get(const char *r)
{
	struct tls	*ctx;
	struct iri	 iri;
	int		 foundhdr = 0, code = -1, od;
	char		 iribuf[GEMINI_URL_LEN];
	char		 req[GEMINI_URL_LEN];
	char		 buf[2048];
	const char	*parse_err, *host, *port;

	if (strlcpy(iribuf, r, sizeof(iribuf)) >= sizeof(iribuf))
		errx(1, "iri too long: %s", r);

	if (strlcpy(req, r, sizeof(req)) >= sizeof(req))
		errx(1, "iri too long: %s", r);

	if (strlcat(req, "\r\n", sizeof(req)) >= sizeof(req))
		errx(1, "iri too long: %s", r);

	if (!parse_iri(iribuf, &iri, &parse_err))
		errx(1, "invalid IRI: %s", parse_err);

	if (nop)
		errx(0, "IRI OK");

	if ((ctx = tls_client()) == NULL)
		errx(1, "can't create tls context");

	if (tls_configure(ctx, tls_conf) == -1)
		errx(1, "tls_configure: %s", tls_error(ctx));

	host = iri.host;
	port = "1965";
	if (*iri.port != '\0')
		port = iri.port;

	connectto(ctx, host, port);

	od = 0;
	while (!od) {
		switch (tls_handshake(ctx)) {
		case 0:
			od = 1;
			break;
		case -1:
			errx(1, "handshake: %s", tls_error(ctx));
		}
	}

	if (verbose)
		printf("%s", req);

	doreq(ctx, req);

	for (;;) {
		char	*t;
		size_t	 len;

		len = dorep(ctx, buf, sizeof(buf));
		if (len == 0)
			goto close;

		if (foundhdr) {
			write(1, buf, len);
			continue;
		}
		foundhdr = 1;

		if (memmem(buf, len, "\r\n", 2) == NULL)
			errx(1, "invalid reply: no \\r\\n");
		if (!isdigit(buf[0]) || !isdigit(buf[1]) || buf[2] != ' ')
			errx(1, "invalid reply: invalid response format");

		code = (buf[0] - '0') * 10 + buf[1] - '0';

		if (debug == DEBUG_CODE) {
			printf("%d\n", code);
			goto close;
		}

		if (debug == DEBUG_HEADER) {
			t = memmem(buf, len, "\r\n", 2);
			assert(t != NULL);
			*t = '\0';
			printf("%s\n", buf);
			goto close;
		}

		if (debug == DEBUG_META) {
			t = memmem(buf, len, "\r\n", 2);
			assert(t != NULL);
			*t = '\0';
			printf("%s\n", buf+3);
			goto close;
		}

		if (debug == DEBUG_ALL) {
			write(1, buf, len);
			continue;
		}

		/* skip the header */
		t = memmem(buf, len, "\r\n", 2);
		assert(t != NULL);
		t += 2; /* skip \r\n */
		len -= t - buf;
		write(1, t, len);
	}

close:
	od = tls_close(ctx);
	if (od == TLS_WANT_POLLIN || od == TLS_WANT_POLLOUT)
		goto close;

	tls_close(ctx);
	tls_free(ctx);
	return code;
}

static void __attribute__((noreturn))
usage(void)
{
	fprintf(stderr, "usage: %s [-23Nnv] [-C cert] [-d mode] [-H sni] "
	    "[-K key] [-P host[:port]]\n",
	    getprogname());
	fprintf(stderr, "          [-T seconds] gemini://...\n");
	exit(1);
}

static int
parse_debug(const char *arg)
{
	if (!strcmp(arg, "none"))
		return DEBUG_NONE;
	if (!strcmp(arg, "code"))
		return DEBUG_CODE;
	if (!strcmp(arg, "header"))
		return DEBUG_HEADER;
	if (!strcmp(arg, "meta"))
		return DEBUG_META;
	if (!strcmp(arg, "all"))
		return DEBUG_ALL;
	usage();
}

static void
parse_proxy(const char *arg)
{
	char *at;

	if ((proxy_host = strdup(arg)) == NULL)
		err(1, "strdup");

	proxy_port = "1965";

	if ((at = strchr(proxy_host, ':')) == NULL)
		return;
	*at = '\0';
	proxy_port = ++at;

	if (strchr(proxy_port, ':') != NULL)
		errx(1, "invalid port %s", proxy_port);
}

int
main(int argc, char **argv)
{
	int		 ch, code;
	const char	*errstr;

	while ((ch = getopt(argc, argv, "23C:d:H:K:NP:T:v")) != -1) {
		switch (ch) {
		case '2':
			flag2 = 1;
			break;
		case '3':
			flag3 = 1;
			break;
		case 'C':
			cert = optarg;
			break;
		case 'd':
			debug = parse_debug(optarg);
			break;
		case 'H':
			sni = optarg;
			break;
		case 'K':
			key = optarg;
			break;
		case 'N':
			dont_verify_name = 1;
			break;
		case 'n':
			nop = 1;
			break;
		case 'P':
			parse_proxy(optarg);
			dont_verify_name = 1;
			break;
		case 'T':
			timer = strtonum(optarg, 1, 1000, &errstr);
			if (errstr != NULL)
				errx(1, "timeout is %s: %s",
				    errstr, optarg);
			signal(SIGALRM, timeout);
			alarm(timer);
			break;
		case 'v':
			verbose++;
			break;
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (flag2 + flag3 > 1) {
		warnx("only -2 or -3 can be specified at the same time");
		usage();
	}

	if ((cert != NULL && key == NULL) ||
	    (cert == NULL && key != NULL)) {
		warnx("cert or key is missing");
		usage();
	}

	if (argc != 1)
		usage();

	load_tls_conf();

	signal(SIGPIPE, SIG_IGN);

#ifdef __OpenBSD__
	if (pledge("stdio inet dns", NULL) == -1)
		err(1, "pledge");
#endif

	code = get(*argv);

	return code < 20 || code >= 30;
}