Blob


1 /*
2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include "gmid.h"
19 #include <sys/socket.h>
21 #include <assert.h>
22 #include <ctype.h>
23 #include <errno.h>
24 #include <string.h>
26 enum debug {
27 DEBUG_NONE,
28 DEBUG_CODE,
29 DEBUG_HEADER,
30 DEBUG_META,
31 DEBUG_ALL,
32 };
34 /* flags */
35 int debug;
36 int dont_verify_name;
37 int flag2;
38 int flag3;
39 int nop;
40 int redirects = 5;
41 int timer;
42 int verbose;
43 const char *cert;
44 const char *key;
45 const char *proxy_host;
46 const char *proxy_port;
47 const char *sni;
49 /* state */
50 struct tls_config *tls_conf;
52 static void
53 timeout(int signo)
54 {
55 dprintf(2, "%s: timer expired\n", getprogname());
56 exit(1);
57 }
59 static void
60 load_tls_conf(void)
61 {
62 if ((tls_conf = tls_config_new()) == NULL)
63 err(1, "tls_config_new");
65 tls_config_insecure_noverifycert(tls_conf);
66 if (dont_verify_name)
67 tls_config_insecure_noverifyname(tls_conf);
69 if (flag2 &&
70 tls_config_set_protocols(tls_conf, TLS_PROTOCOL_TLSv1_2) == -1)
71 errx(1, "can't set TLSv1.2");
72 if (flag3 &&
73 tls_config_set_protocols(tls_conf, TLS_PROTOCOL_TLSv1_3) == -1)
74 errx(1, "can't set TLSv1.3");
76 if (cert != NULL &&
77 tls_config_set_keypair_file(tls_conf, cert, key) == -1)
78 errx(1, "can't load client certificate %s", cert);
79 }
81 static void
82 connectto(struct tls *ctx, const char *host, const char *port)
83 {
84 struct addrinfo hints, *res, *res0;
85 int error;
86 int saved_errno;
87 int s;
88 const char *cause = NULL;
89 const char *sname;
91 if (proxy_host != NULL) {
92 host = proxy_host;
93 port = proxy_port;
94 }
96 if ((sname = sni) == NULL)
97 sname = host;
99 memset(&hints, 0, sizeof(hints));
100 hints.ai_family = AF_UNSPEC;
101 hints.ai_socktype = SOCK_STREAM;
102 error = getaddrinfo(host, port, &hints, &res0);
103 if (error)
104 errx(1, "%s", gai_strerror(error));
106 s = -1;
107 for (res = res0; res != NULL; res = res->ai_next) {
108 s = socket(res->ai_family, res->ai_socktype,
109 res->ai_protocol);
110 if (s == -1) {
111 cause = "socket";
112 continue;
115 if (connect(s, res->ai_addr, res->ai_addrlen) == -1) {
116 cause = "connect";
117 saved_errno = errno;
118 close(s);
119 errno = saved_errno;
120 s = -1;
121 continue;
124 break;
127 if (s == -1)
128 err(1, "%s: can't connect to %s:%s", cause,
129 host, port);
131 freeaddrinfo(res0);
133 if (tls_connect_socket(ctx, s, sname) == -1)
134 errx(1, "tls_connect_socket: %s", tls_error(ctx));
137 static void
138 doreq(struct tls *ctx, const char *buf)
140 size_t s;
141 ssize_t w;
143 s = strlen(buf);
144 while (s != 0) {
145 switch (w = tls_write(ctx, buf, s)) {
146 case 0:
147 case -1:
148 errx(1, "tls_write: %s", tls_error(ctx));
149 case TLS_WANT_POLLIN:
150 case TLS_WANT_POLLOUT:
151 continue;
154 s -= w;
155 buf += w;
159 static size_t
160 dorep(struct tls *ctx, void *buf, size_t len)
162 ssize_t w;
163 size_t tot = 0;
165 while (len != 0) {
166 switch (w = tls_read(ctx, buf, len)) {
167 case 0:
168 return tot;
169 case -1:
170 errx(1, "tls_write: %s", tls_error(ctx));
171 case TLS_WANT_POLLIN:
172 case TLS_WANT_POLLOUT:
173 continue;
176 len -= w;
177 buf += w;
178 tot += w;
181 return tot;
184 static int
185 get(const char *r)
187 struct tls *ctx;
188 struct iri iri;
189 int foundhdr = 0, code = -1, od;
190 char iribuf[GEMINI_URL_LEN];
191 char req[GEMINI_URL_LEN];
192 char buf[2048];
193 const char *parse_err, *host, *port;
195 if (strlcpy(iribuf, r, sizeof(iribuf)) >= sizeof(iribuf))
196 errx(1, "iri too long: %s", r);
198 if (strlcpy(req, r, sizeof(req)) >= sizeof(req))
199 errx(1, "iri too long: %s", r);
201 if (strlcat(req, "\r\n", sizeof(req)) >= sizeof(req))
202 errx(1, "iri too long: %s", r);
204 if (!parse_iri(iribuf, &iri, &parse_err))
205 errx(1, "invalid IRI: %s", parse_err);
207 if (nop)
208 errx(0, "IRI OK");
210 if ((ctx = tls_client()) == NULL)
211 errx(1, "can't create tls context");
213 if (tls_configure(ctx, tls_conf) == -1)
214 errx(1, "tls_configure: %s", tls_error(ctx));
216 host = iri.host;
217 port = "1965";
218 if (*iri.port != '\0')
219 port = iri.port;
221 connectto(ctx, host, port);
223 od = 0;
224 while (!od) {
225 switch (tls_handshake(ctx)) {
226 case 0:
227 od = 1;
228 break;
229 case -1:
230 errx(1, "handshake: %s", tls_error(ctx));
234 if (verbose)
235 printf("%s", req);
237 doreq(ctx, req);
239 for (;;) {
240 char *t;
241 size_t len;
243 len = dorep(ctx, buf, sizeof(buf));
244 if (len == 0)
245 goto close;
247 if (foundhdr) {
248 write(1, buf, len);
249 continue;
251 foundhdr = 1;
253 if (memmem(buf, len, "\r\n", 2) == NULL)
254 errx(1, "invalid reply: no \\r\\n");
255 if (!isdigit(buf[0]) || !isdigit(buf[1]) || buf[2] != ' ')
256 errx(1, "invalid reply: invalid response format");
258 code = (buf[0] - '0') * 10 + buf[1] - '0';
260 if (debug == DEBUG_CODE) {
261 printf("%d\n", code);
262 goto close;
265 if (debug == DEBUG_HEADER) {
266 t = memmem(buf, len, "\r\n", 2);
267 assert(t != NULL);
268 *t = '\0';
269 printf("%s\n", buf);
270 goto close;
273 if (debug == DEBUG_META) {
274 t = memmem(buf, len, "\r\n", 2);
275 assert(t != NULL);
276 *t = '\0';
277 printf("%s\n", buf+3);
278 goto close;
281 if (debug == DEBUG_ALL) {
282 write(1, buf, len);
283 continue;
286 /* skip the header */
287 t = memmem(buf, len, "\r\n", 2);
288 assert(t != NULL);
289 t += 2; /* skip \r\n */
290 len -= t - buf;
291 write(1, t, len);
294 close:
295 od = tls_close(ctx);
296 if (od == TLS_WANT_POLLIN || od == TLS_WANT_POLLOUT)
297 goto close;
299 tls_close(ctx);
300 tls_free(ctx);
301 return code;
304 static void __attribute__((noreturn))
305 usage(void)
307 fprintf(stderr, "version: " GG_STRING "\n");
308 fprintf(stderr, "usage: %s [-23Nnv] [-C cert] [-d mode] [-H sni] "
309 "[-K key] [-P host[:port]]\n",
310 getprogname());
311 fprintf(stderr, " [-T seconds] gemini://...\n");
312 exit(1);
315 static int
316 parse_debug(const char *arg)
318 if (!strcmp(arg, "none"))
319 return DEBUG_NONE;
320 if (!strcmp(arg, "code"))
321 return DEBUG_CODE;
322 if (!strcmp(arg, "header"))
323 return DEBUG_HEADER;
324 if (!strcmp(arg, "meta"))
325 return DEBUG_META;
326 if (!strcmp(arg, "all"))
327 return DEBUG_ALL;
328 usage();
331 static void
332 parse_proxy(const char *arg)
334 char *at;
336 if ((proxy_host = strdup(arg)) == NULL)
337 err(1, "strdup");
339 proxy_port = "1965";
341 if ((at = strchr(proxy_host, ':')) == NULL)
342 return;
343 *at = '\0';
344 proxy_port = ++at;
346 if (strchr(proxy_port, ':') != NULL)
347 errx(1, "invalid port %s", proxy_port);
350 int
351 main(int argc, char **argv)
353 int ch, code;
354 const char *errstr;
356 while ((ch = getopt(argc, argv, "23C:d:H:K:NP:T:v")) != -1) {
357 switch (ch) {
358 case '2':
359 flag2 = 1;
360 break;
361 case '3':
362 flag3 = 1;
363 break;
364 case 'C':
365 cert = optarg;
366 break;
367 case 'd':
368 debug = parse_debug(optarg);
369 break;
370 case 'H':
371 sni = optarg;
372 break;
373 case 'K':
374 key = optarg;
375 break;
376 case 'N':
377 dont_verify_name = 1;
378 break;
379 case 'n':
380 nop = 1;
381 break;
382 case 'P':
383 parse_proxy(optarg);
384 dont_verify_name = 1;
385 break;
386 case 'T':
387 timer = strtonum(optarg, 1, 1000, &errstr);
388 if (errstr != NULL)
389 errx(1, "timeout is %s: %s",
390 errstr, optarg);
391 signal(SIGALRM, timeout);
392 alarm(timer);
393 break;
394 case 'v':
395 verbose++;
396 break;
397 default:
398 usage();
401 argc -= optind;
402 argv += optind;
404 if (flag2 + flag3 > 1) {
405 warnx("only -2 or -3 can be specified at the same time");
406 usage();
409 if ((cert != NULL && key == NULL) ||
410 (cert == NULL && key != NULL)) {
411 warnx("cert or key is missing");
412 usage();
415 if (argc != 1)
416 usage();
418 load_tls_conf();
420 signal(SIGPIPE, SIG_IGN);
422 #ifdef __OpenBSD__
423 if (pledge("stdio inet dns", NULL) == -1)
424 err(1, "pledge");
425 #endif
427 code = get(*argv);
429 return code < 20 || code >= 30;