Blob


1 /*
2 * Copyright (c) 2024 Omar Polo <op@openbsd.org>
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 <sys/time.h>
18 #include <sys/types.h>
19 #include <sys/socket.h>
21 #include <err.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <limits.h>
25 #include <netdb.h>
26 #include <poll.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
32 #include "got_opentemp.h"
33 #include "got_version.h"
35 #include "bufio.h"
36 #include "utf8d.h"
38 #define USERAGENT "got-notify-http/" GOT_VERSION_STR
40 static int http_timeout = 300; /* 5 minutes in seconds */
42 __dead static void
43 usage(void)
44 {
45 fprintf(stderr, "usage: %s [-c] -h host -p port path\n",
46 getprogname());
47 exit(1);
48 }
50 static int
51 dial(const char *host, const char *port)
52 {
53 struct addrinfo hints, *res, *res0;
54 const char *cause = NULL;
55 int s, error, save_errno;
57 memset(&hints, 0, sizeof(hints));
58 hints.ai_family = AF_UNSPEC;
59 hints.ai_socktype = SOCK_STREAM;
60 error = getaddrinfo(host, port, &hints, &res0);
61 if (error)
62 errx(1, "failed to resolve %s:%s: %s", host, port,
63 gai_strerror(error));
65 s = -1;
66 for (res = res0; res; res = res->ai_next) {
67 s = socket(res->ai_family, res->ai_socktype,
68 res->ai_protocol);
69 if (s == -1) {
70 cause = "socket";
71 continue;
72 }
74 if (connect(s, res->ai_addr, res->ai_addrlen) == -1) {
75 cause = "connect";
76 save_errno = errno;
77 close(s);
78 errno = save_errno;
79 s = -1;
80 continue;
81 }
83 break;
84 }
86 freeaddrinfo(res0);
87 if (s == -1)
88 err(1, "%s", cause);
89 return s;
90 }
92 static void
93 escape(FILE *fp, const uint8_t *s)
94 {
95 uint32_t codepoint, state;
96 const uint8_t *start = s;
98 state = 0;
99 for (; *s; ++s) {
100 switch (decode(&state, &codepoint, *s)) {
101 case UTF8_ACCEPT:
102 switch (codepoint) {
103 case '"':
104 case '\\':
105 fprintf(fp, "\\%c", *s);
106 break;
107 case '\b':
108 fprintf(fp, "\\b");
109 break;
110 case '\f':
111 fprintf(fp, "\\f");
112 break;
113 case '\n':
114 fprintf(fp, "\\n");
115 break;
116 case '\r':
117 fprintf(fp, "\\r");
118 break;
119 case '\t':
120 fprintf(fp, "\\t");
121 break;
122 default:
123 /* other control characters */
124 if (codepoint < ' ' || codepoint == 0x7F) {
125 fprintf(fp, "\\u%04x", codepoint);
126 break;
128 fwrite(start, 1, s - start + 1, fp);
129 break;
131 start = s + 1;
132 break;
134 case UTF8_REJECT:
135 /* bad UTF-8 sequence; try to recover */
136 fputs("\\uFFFD", fp);
137 state = UTF8_ACCEPT;
138 start = s + 1;
139 break;
144 static void
145 json_field(FILE *fp, const char *key, const char *val, int comma)
147 fprintf(fp, "\"%s\":\"", key);
148 escape(fp, val);
149 fprintf(fp, "\"%s", comma ? "," : "");
152 static void
153 json_author(FILE *fp, const char *type, char *address, int comma)
155 char *gt, *lt, *at, *email, *endname;
157 fprintf(fp, "\"%s\":{", type);
159 gt = strchr(address, '<');
160 if (gt != NULL) {
161 /* long format, e.g. "Omar Polo <op@openbsd.org>" */
163 json_field(fp, "full", address, 1);
165 endname = gt;
166 while (endname > address && endname[-1] == ' ')
167 endname--;
169 *endname = '\0';
170 json_field(fp, "name", address, 1);
172 email = gt + 1;
173 lt = strchr(email, '>');
174 if (lt)
175 *lt = '\0';
177 json_field(fp, "mail", email, 1);
179 at = strchr(email, '@');
180 if (at)
181 *at = '\0';
183 json_field(fp, "user", email, 0);
184 } else {
185 /* short format only shows the username */
186 json_field(fp, "user", address, 0);
189 fprintf(fp, "}%s", comma ? "," : "");
192 static int
193 jsonify_commit_short(FILE *fp, char *line)
195 char *t, *date, *id, *author, *message;
197 t = line;
198 date = t;
199 if ((t = strchr(t, ' ')) == NULL)
200 errx(1, "malformed line");
201 *t++ = '\0';
203 id = t;
204 if ((t = strchr(t, ' ')) == NULL)
205 errx(1, "malformed line");
206 *t++ = '\0';
208 author = t;
209 if ((t = strchr(t, ' ')) == NULL)
210 errx(1, "malformed line");
211 *t++ = '\0';
213 message = t;
215 fprintf(fp, "{\"type\":\"commit\",\"short\":true,");
216 json_field(fp, "id", id, 1);
217 json_author(fp, "committer", author, 1);
218 json_field(fp, "date", date, 1);
219 json_field(fp, "short_message", message, 0);
220 fprintf(fp, "}");
222 return 0;
225 static int
226 jsonify_commit(FILE *fp, char **line, ssize_t *linesize)
228 const char *errstr;
229 char *author = NULL;
230 char *l;
231 ssize_t linelen;
232 int parent = 0;
233 int msglen = 0, msgwrote = 0;
234 int done = 0;
235 enum {
236 P_FROM,
237 P_VIA,
238 P_DATE,
239 P_PARENT,
240 P_MSGLEN,
241 P_MSG,
242 P_DST,
243 P_SUM,
244 } phase = P_FROM;
246 l = *line;
247 if (strncmp(l, "commit ", 7) != 0)
248 errx(1, "%s: unexpected line: %s", __func__, l);
249 l += 7;
250 fprintf(fp, "{\"type\":\"commit\",\"short\":false,");
251 json_field(fp, "id", l, 1);
253 while (!done) {
254 if ((linelen = getline(line, linesize, stdin)) == -1)
255 break;
257 if ((*line)[linelen - 1] == '\n')
258 (*line)[--linelen] = '\0';
260 l = *line;
261 switch (phase) {
262 case P_FROM:
263 if (strncmp(l, "from: ", 6) != 0)
264 errx(1, "unexpected from line");
265 l += 6;
267 author = strdup(l);
268 if (author == NULL)
269 err(1, "strdup");
271 json_author(fp, "author", l, 1);
273 phase = P_VIA;
274 break;
276 case P_VIA:
277 /* optional */
278 if (!strncmp(l, "via: ", 5)) {
279 l += 5;
280 json_author(fp, "committer", l, 1);
281 phase = P_DATE;
282 break;
285 if (author == NULL) /* impossible */
286 err(1, "from not specified");
287 json_author(fp, "committer", author, 1);
288 free(author);
289 author = NULL;
291 phase = P_DATE;
292 /* fallthrough */
294 case P_DATE:
295 /* optional */
296 if (!strncmp(l, "date: ", 6)) {
297 l += 6;
298 json_field(fp, "date", l, 1);
299 phase = P_PARENT;
300 break;
302 phase = P_PARENT;
303 /* fallthough */
305 case P_PARENT:
306 /* optional - more than one */
307 if (!strncmp(l, "parent ", 7)) {
308 l += 7;
309 l += strcspn(l, ":");
310 l += strspn(l, " ");
312 if (parent == 0) {
313 parent = 1;
314 fprintf(fp, "\"parents\":[");
317 fputc('"', fp);
318 escape(fp, l);
319 fputc('"', fp);
321 break;
323 if (parent != 0) {
324 fprintf(fp, "],");
325 parent = 0;
327 phase = P_MSGLEN;
328 /* fallthrough */
330 case P_MSGLEN:
331 if (strncmp(l, "messagelen: ", 12) != 0)
332 errx(1, "unexpected messagelen line");
333 l += 12;
334 msglen = strtonum(l, 1, INT_MAX, &errstr);
335 if (errstr)
336 errx(1, "message len is %s: %s", errstr, l);
338 phase = P_MSG;
339 break;
341 case P_MSG:
342 /*
343 * The commit message is indented with one extra
344 * space which is not accounted for in messagelen,
345 * but we also strip the trailing \n so that
346 * accounts for it.
348 * Since we read line-by-line and there is always
349 * a \n added at the end of the message,
350 * tolerate one byte less than advertised.
351 */
352 if (*l == ' ') {
353 l++; /* skip leading space */
354 linelen--;
356 if (msgwrote == 0 && linelen != 0) {
357 json_field(fp, "short_message", l, 1);
358 fprintf(fp, "\"message\":\"");
359 escape(fp, l);
360 escape(fp, "\n");
361 msgwrote += linelen;
362 } else if (msgwrote != 0) {
363 escape(fp, l);
364 escape(fp, "\n");
367 msglen -= linelen + 1;
368 if (msglen <= 1) {
369 fprintf(fp, "\",");
370 msgwrote = 0;
371 phase = P_DST;
373 break;
375 case P_DST:
376 /* XXX: ignore the diffstat for now */
377 if (*l == '\0') {
378 fprintf(fp, "\"diffstat\":{},");
379 phase = P_SUM;
380 break;
382 break;
384 case P_SUM:
385 /* XXX: ignore the sum of changes for now */
386 fprintf(fp, "\"changes\":{}}");
387 done = 1;
388 break;
390 default:
391 /* unreachable */
392 errx(1, "unexpected line: %s", *line);
395 if (ferror(stdin))
396 err(1, "getline");
397 if (!done)
398 errx(1, "unexpected EOF");
400 return 0;
403 static int
404 jsonify(FILE *fp)
406 char *line = NULL;
407 size_t linesize = 0;
408 ssize_t linelen;
409 int needcomma = 0;
411 fprintf(fp, "{\"notifications\":[");
412 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
413 if (line[linelen - 1] == '\n')
414 line[--linelen] = '\0';
416 if (*line == '\0')
417 continue;
419 if (needcomma)
420 fputc(',', fp);
421 needcomma = 1;
423 if (strncmp(line, "commit ", 7) == 0) {
424 if (jsonify_commit(fp, &line, &linesize) == -1)
425 err(1, "jsonify_commit");
426 continue;
429 if (*line >= '0' && *line <= '9') {
430 if (jsonify_commit_short(fp, line) == -1)
431 err(1, "jsonify_commit_short");
432 continue;
435 errx(1, "unexpected line: %s", line);
437 if (ferror(stdin))
438 err(1, "getline");
439 fprintf(fp, "]}");
441 return 0;
444 static char *
445 basic_auth(const char *username, const char *password)
447 char *tmp;
448 int len;
450 len = asprintf(&tmp, "%s:%s", username, password);
451 if (len == -1)
452 err(1, "asprintf");
454 /* XXX base64-ify */
455 return tmp;
458 static inline int
459 bufio2poll(struct bufio *bio)
461 int f, ret = 0;
463 f = bufio_ev(bio);
464 if (f & BUFIO_WANT_READ)
465 ret |= POLLIN;
466 if (f & BUFIO_WANT_WRITE)
467 ret |= POLLOUT;
468 return ret;
471 int
472 main(int argc, char **argv)
474 FILE *tmpfp;
475 struct bufio bio;
476 struct pollfd pfd;
477 struct timespec timeout;
478 const char *username;
479 const char *password;
480 const char *timeoutstr;
481 const char *errstr;
482 const char *host = NULL, *port = NULL, *path = NULL;
483 char *auth, *line, *spc;
484 size_t len;
485 ssize_t r;
486 off_t paylen;
487 int tls = 0;
488 int response_code = 0, done = 0;
489 int ch, flags, ret, nonstd = 0;
491 #ifndef PROFILE
492 if (pledge("stdio rpath tmppath dns inet", NULL) == -1)
493 err(1, "pledge");
494 #endif
496 while ((ch = getopt(argc, argv, "ch:p:")) != -1) {
497 switch (ch) {
498 case 'c':
499 tls = 1;
500 break;
501 case 'h':
502 host = optarg;
503 break;
504 case 'p':
505 port = optarg;
506 break;
507 default:
508 usage();
511 argc -= optind;
512 argv += optind;
514 if (host == NULL || argc != 1)
515 usage();
516 if (tls && port == NULL)
517 port = "443";
518 path = argv[0];
520 username = getenv("GOT_NOTIFY_HTTP_USER");
521 password = getenv("GOT_NOTIFY_HTTP_PASS");
522 if ((username != NULL && password == NULL) ||
523 (username == NULL && password != NULL))
524 errx(1, "username or password are not specified");
525 if (username && *password == '\0')
526 errx(1, "password can't be empty");
528 /* used by the regression test suite */
529 timeoutstr = getenv("GOT_NOTIFY_TIMEOUT");
530 if (timeoutstr) {
531 http_timeout = strtonum(timeoutstr, 0, 600, &errstr);
532 if (errstr != NULL)
533 errx(1, "timeout in seconds is %s: %s",
534 errstr, timeoutstr);
537 memset(&timeout, 0, sizeof(timeout));
538 timeout.tv_sec = http_timeout;
540 tmpfp = got_opentemp();
541 if (tmpfp == NULL)
542 err(1, "opentemp");
544 jsonify(tmpfp);
546 paylen = ftello(tmpfp);
547 if (paylen == -1)
548 err(1, "ftello");
549 if (fseeko(tmpfp, 0, SEEK_SET) == -1)
550 err(1, "fseeko");
552 #ifndef PROFILE
553 /* drop tmppath */
554 if (pledge("stdio rpath dns inet", NULL) == -1)
555 err(1, "pledge");
556 #endif
558 memset(&pfd, 0, sizeof(pfd));
559 pfd.fd = dial(host, port);
561 if ((flags = fcntl(pfd.fd, F_GETFL)) == -1)
562 err(1, "fcntl(F_GETFL)");
563 if (fcntl(pfd.fd, F_SETFL, flags | O_NONBLOCK) == -1)
564 err(1, "fcntl(F_SETFL)");
566 if (bufio_init(&bio) == -1)
567 err(1, "bufio_init");
568 bufio_set_fd(&bio, pfd.fd);
569 if (tls && bufio_starttls(&bio, host, 0, NULL, 0, NULL, 0) == -1)
570 err(1, "bufio_starttls");
572 #ifndef PROFILE
573 /* drop rpath dns inet */
574 if (pledge("stdio", NULL) == -1)
575 err(1, "pledge");
576 #endif
578 if ((!tls && strcmp(port, "80") != 0) ||
579 (tls && strcmp(port, "443")) != 0)
580 nonstd = 1;
582 ret = bufio_compose_fmt(&bio,
583 "POST %s HTTP/1.1\r\n"
584 "Host: %s%s%s\r\n"
585 "Content-Type: application/json\r\n"
586 "Content-Length: %lld\r\n"
587 "User-Agent: %s\r\n"
588 "Connection: close\r\n",
589 path, host,
590 nonstd ? ":" : "", nonstd ? port : "",
591 (long long)paylen, USERAGENT);
592 if (ret == -1)
593 err(1, "bufio_compose_fmt");
595 if (username) {
596 auth = basic_auth(username, password);
597 ret = bufio_compose_fmt(&bio, "Authorization: basic %s\r\n",
598 auth);
599 if (ret == -1)
600 err(1, "bufio_compose_fmt");
601 free(auth);
604 if (bufio_compose(&bio, "\r\n", 2) == -1)
605 err(1, "bufio_compose");
607 while (!done) {
608 struct timespec elapsed, start, stop;
609 char buf[BUFSIZ];
611 pfd.events = bufio2poll(&bio);
612 clock_gettime(CLOCK_MONOTONIC, &start);
613 ret = ppoll(&pfd, 1, &timeout, NULL);
614 if (ret == -1)
615 err(1, "poll");
616 clock_gettime(CLOCK_MONOTONIC, &stop);
617 timespecsub(&stop, &start, &elapsed);
618 timespecsub(&timeout, &elapsed, &timeout);
619 if (ret == 0 || timeout.tv_sec <= 0)
620 errx(1, "timeout");
622 if (bio.wbuf.len > 0 && (pfd.revents & POLLOUT)) {
623 if (bufio_write(&bio) == -1 && errno != EAGAIN)
624 errx(1, "bufio_write: %s", bufio_io_err(&bio));
626 if (pfd.revents & POLLIN) {
627 r = bufio_read(&bio);
628 if (r == -1 && errno != EAGAIN)
629 errx(1, "bufio_read: %s", bufio_io_err(&bio));
630 if (r == 0)
631 errx(1, "unexpected EOF");
633 for (;;) {
634 line = buf_getdelim(&bio.rbuf, "\r\n", &len);
635 if (line == NULL)
636 break;
637 if (response_code && *line == '\0') {
638 /*
639 * end of headers, don't bother
640 * reading the body, if there is.
641 */
642 done = 1;
643 break;
645 if (response_code) {
646 buf_drain(&bio.rbuf, len);
647 continue;
649 spc = strchr(line, ' ');
650 if (spc == NULL)
651 errx(1, "bad reply");
652 *spc++ = '\0';
653 if (strcasecmp(line, "HTTP/1.1") != 0)
654 errx(1, "unexpected protocol: %s",
655 line);
656 line = spc;
658 spc = strchr(line, ' ');
659 if (spc == NULL)
660 errx(1, "bad reply");
661 *spc++ = '\0';
663 response_code = strtonum(line, 100, 599,
664 &errstr);
665 if (errstr != NULL)
666 errx(1, "response code is %s: %s",
667 errstr, line);
669 buf_drain(&bio.rbuf, len);
671 if (done)
672 break;
675 if (!feof(tmpfp) && bio.wbuf.len < sizeof(buf)) {
676 len = fread(buf, 1, sizeof(buf), tmpfp);
677 if (len == 0) {
678 if (ferror(tmpfp))
679 err(1, "fread");
680 continue;
683 if (bufio_compose(&bio, buf, len) == -1)
684 err(1, "buf_compose");
688 if (response_code >= 200 && response_code < 300)
689 return 0;
690 errx(1, "request failed with code %d", response_code);