2 * Copyright (c) 2024 Omar Polo <op@openbsd.org>
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.
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.
18 #include <sys/types.h>
19 #include <sys/socket.h>
34 #include "got_opentemp.h"
35 #include "got_version.h"
41 #define USERAGENT "got-notify-http/" GOT_VERSION_STR
43 static int http_timeout = 300; /* 5 minutes in seconds */
48 fprintf(stderr, "usage: %s [-c] -r repo -h host -p port path\n",
54 dial(const char *host, const char *port)
56 struct addrinfo hints, *res, *res0;
57 const char *cause = NULL;
58 int s, error, save_errno;
60 memset(&hints, 0, sizeof(hints));
61 hints.ai_family = AF_UNSPEC;
62 hints.ai_socktype = SOCK_STREAM;
63 error = getaddrinfo(host, port, &hints, &res0);
65 errx(1, "failed to resolve %s:%s: %s", host, port,
69 for (res = res0; res; res = res->ai_next) {
70 s = socket(res->ai_family, res->ai_socktype,
77 if (connect(s, res->ai_addr, res->ai_addrlen) == -1) {
96 escape(FILE *fp, const uint8_t *s)
98 uint32_t codepoint, state;
99 const uint8_t *start = s;
103 switch (decode(&state, &codepoint, *s)) {
108 fprintf(fp, "\\%c", *s);
126 /* other control characters */
127 if (codepoint < ' ' || codepoint == 0x7F) {
128 fprintf(fp, "\\u%04x", codepoint);
131 fwrite(start, 1, s - start + 1, fp);
138 /* bad UTF-8 sequence; try to recover */
139 fputs("\\uFFFD", fp);
148 json_field(FILE *fp, const char *key, const char *val, int comma)
150 fprintf(fp, "\"%s\":\"", key);
152 fprintf(fp, "\"%s", comma ? "," : "");
156 json_author(FILE *fp, const char *type, char *address, int comma)
158 char *gt, *lt, *at, *email, *endname;
160 fprintf(fp, "\"%s\":{", type);
162 gt = strchr(address, '<');
164 /* long format, e.g. "Omar Polo <op@openbsd.org>" */
166 json_field(fp, "full", address, 1);
169 while (endname > address && endname[-1] == ' ')
173 json_field(fp, "name", address, 1);
176 lt = strchr(email, '>');
180 json_field(fp, "mail", email, 1);
182 at = strchr(email, '@');
186 json_field(fp, "user", email, 0);
188 /* short format only shows the username */
189 json_field(fp, "user", address, 0);
192 fprintf(fp, "}%s", comma ? "," : "");
196 jsonify_branch_rm(FILE *fp, char *line, const char *repo)
200 line = strchr(line, ' ');
202 errx(1, "invalid branch rm line");
203 line += strspn(line, " ");
207 line = strchr(line, ':');
209 errx(1, "invalid branch rm line");
211 id = line + strspn(line, " ");
214 json_field(fp, "type", "branch-deleted", 1);
215 json_field(fp, "repo", repo, 1);
216 json_field(fp, "ref", ref, 1);
217 json_field(fp, "id", id, 0);
224 jsonify_commit_short(FILE *fp, char *line, const char *repo)
226 char *t, *date, *id, *author, *message;
230 if ((t = strchr(t, ' ')) == NULL)
231 errx(1, "malformed line");
235 if ((t = strchr(t, ' ')) == NULL)
236 errx(1, "malformed line");
240 if ((t = strchr(t, ' ')) == NULL)
241 errx(1, "malformed line");
246 fprintf(fp, "{\"type\":\"commit\",\"short\":true,");
247 json_field(fp, "repo", repo, 1);
248 json_field(fp, "id", id, 1);
249 json_author(fp, "committer", author, 1);
250 json_field(fp, "date", date, 1);
251 json_field(fp, "short_message", message, 0);
258 jsonify_commit(FILE *fp, const char *repo, char **line, ssize_t *linesize)
266 int msglen = 0, msgwrote = 0;
281 if (strncmp(l, "commit ", 7) != 0)
282 errx(1, "%s: unexpected line: %s", __func__, l);
285 fprintf(fp, "{\"type\":\"commit\",\"short\":false,");
286 json_field(fp, "repo", repo, 1);
287 json_field(fp, "id", l, 1);
290 if ((linelen = getline(line, linesize, stdin)) == -1)
293 if ((*line)[linelen - 1] == '\n')
294 (*line)[--linelen] = '\0';
299 if (strncmp(l, "from: ", 6) != 0)
300 errx(1, "unexpected from line");
307 json_author(fp, "author", l, 1);
314 if (!strncmp(l, "via: ", 5)) {
316 json_author(fp, "committer", l, 1);
321 if (author == NULL) /* impossible */
322 err(1, "from not specified");
323 json_author(fp, "committer", author, 1);
332 if (!strncmp(l, "date: ", 6)) {
334 json_field(fp, "date", l, 1);
342 /* optional - more than one */
343 if (!strncmp(l, "parent ", 7)) {
345 l += strcspn(l, ":");
350 fprintf(fp, "\"parents\":[");
367 if (strncmp(l, "messagelen: ", 12) != 0)
368 errx(1, "unexpected messagelen line");
370 msglen = strtonum(l, 1, INT_MAX, &errstr);
372 errx(1, "message len is %s: %s", errstr, l);
381 * The commit message is indented with one extra
382 * space which is not accounted for in messagelen,
383 * but we also strip the trailing \n so that
386 * Since we read line-by-line and there is always
387 * a \n added at the end of the message,
388 * tolerate one byte less than advertised.
391 errx(1, "unexpected line in commit message");
393 l++; /* skip leading space */
396 if (msgwrote == 0 && linelen != 0) {
397 json_field(fp, "short_message", l, 1);
398 fprintf(fp, "\"message\":\"");
402 } else if (msgwrote != 0) {
407 msglen -= linelen + 1;
416 if (files == 0 && !strcmp(l, " "))
420 fputs("\"diffstat\":{\"files\":[", fp);
429 errx(1, "bad diffstat line");
438 json_field(fp, "action", "added", 1);
441 json_field(fp, "action", "deleted", 1);
444 json_field(fp, "action", "modified", 1);
447 json_field(fp, "action", "mode changed", 1);
450 json_field(fp, "action", "unknown", 1);
458 errx(1, "invalid diffstat: no filename");
463 errx(1, "invalid diffstat: no separator");
465 while (t > filename && *t == ' ')
467 json_field(fp, "file", filename, 1);
475 errx(1, "invalid diffstat: no added counter");
478 n = strtonum(l, 0, INT_MAX, &errstr);
480 errx(1, "added counter is %s: %s", errstr, l);
481 fprintf(fp, "\"added\":%d,", n);
489 errx(1, "invalid diffstat: no del counter");
492 n = strtonum(l, 0, INT_MAX, &errstr);
494 errx(1, "del counter is %s: %s", errstr, l);
495 fprintf(fp, "\"removed\":%d", n);
504 fputs("\"total\":{", fp);
509 errx(1, "missing number of additions");
512 n = strtonum(t, 0, INT_MAX, &errstr);
514 errx(1, "add counter is %s: %s", errstr, t);
515 fprintf(fp, "\"added\":%d,", n);
519 errx(1, "missing number of deletions");
526 errx(1, "malformed diffstat sum line");
529 n = strtonum(l, 0, INT_MAX, &errstr);
531 errx(1, "del counter is %s: %s", errstr, l);
532 fprintf(fp, "\"removed\":%d", n);
540 errx(1, "unexpected line: %s", *line);
546 errx(1, "unexpected EOF");
553 jsonify_tag(FILE *fp, const char *repo, char **line, ssize_t *linesize)
558 int msglen = 0, msgwrote = 0;
569 if (strncmp(l, "tag ", 4) != 0)
570 errx(1, "%s: unexpected line: %s", __func__, l);
574 json_field(fp, "type", "tag", 1);
575 json_field(fp, "repo", repo, 1);
576 json_field(fp, "tag", l, 1);
579 if ((linelen = getline(line, linesize, stdin)) == -1)
582 if ((*line)[linelen - 1] == '\n')
583 (*line)[--linelen] = '\0';
588 if (strncmp(l, "from: ", 6) != 0)
589 errx(1, "unexpected from line");
592 json_author(fp, "tagger", l, 1);
599 if (!strncmp(l, "date: ", 6)) {
601 json_field(fp, "date", l, 1);
610 if (!strncmp(l, "object: ", 8)) {
617 errx(1, "malformed tag object line");
620 fputs("\"object\":{", fp);
621 json_field(fp, "type", type, 1);
622 json_field(fp, "id", id, 0);
632 if (strncmp(l, "messagelen: ", 12) != 0)
633 errx(1, "unexpected messagelen line");
635 msglen = strtonum(l, 1, INT_MAX, &errstr);
637 errx(1, "message len is %s: %s", errstr, l);
646 errx(1, "unexpected line in tag message");
648 l++; /* skip leading space */
651 if (msgwrote == 0 && linelen != 0) {
652 fprintf(fp, "\"message\":\"");
656 } else if (msgwrote != 0) {
661 msglen -= linelen + 1;
671 errx(1, "unexpected line: %s", *line);
677 errx(1, "unexpected EOF");
684 jsonify(FILE *fp, const char *repo)
691 fprintf(fp, "{\"notifications\":[");
692 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
693 if (line[linelen - 1] == '\n')
694 line[--linelen] = '\0';
703 if (strncmp(line, "Removed refs/heads/", 19) == 0) {
704 if (jsonify_branch_rm(fp, line, repo) == -1)
705 err(1, "jsonify_branch_rm");
709 if (strncmp(line, "commit ", 7) == 0) {
710 if (jsonify_commit(fp, repo, &line, &linesize) == -1)
711 err(1, "jsonify_commit");
715 if (*line >= '0' && *line <= '9') {
716 if (jsonify_commit_short(fp, line, repo) == -1)
717 err(1, "jsonify_commit_short");
721 if (strncmp(line, "tag ", 4) == 0) {
722 if (jsonify_tag(fp, repo, &line, &linesize) == -1)
723 err(1, "jsonify_tag");
727 errx(1, "unexpected line: %s", line);
755 errx(1, "invalid sixet 0x%x", c);
759 basic_auth(const char *username, const char *password)
761 char *str, *tmp, *end, *s, *p;
765 r = asprintf(&str, "%s:%s", username, password);
770 * Will need 4 * r/3 bytes to encode the string, plus a
771 * rounding to the next multiple of 4 for padding, plus NUL.
774 len = (len + 3) & ~3;
777 tmp = calloc(1, len);
784 memset(buf, 0, sizeof(buf));
785 for (i = 0; i < 3 && *s != '\0'; ++i, ++s)
788 *p++ = sixet2ch(buf[0] >> 2);
789 *p++ = sixet2ch((buf[1] >> 4) | (buf[0] << 4));
791 *p++ = sixet2ch((buf[1] << 2) | (buf[2] >> 6));
793 *p++ = sixet2ch(buf[2]);
796 for (end = tmp + len - 1; p < end; ++p)
804 bufio2poll(struct bufio *bio)
809 if (f & BUFIO_WANT_READ)
811 if (f & BUFIO_WANT_WRITE)
817 main(int argc, char **argv)
822 struct timespec timeout;
823 const char *username;
824 const char *password;
825 const char *timeoutstr;
827 const char *repo = NULL;
828 const char *host = NULL, *port = NULL, *path = NULL;
829 char *auth, *line, *spc;
834 int response_code = 0, done = 0;
835 int ch, flags, ret, nonstd = 0;
838 if (pledge("stdio rpath tmppath dns inet", NULL) == -1)
842 log_init(0, LOG_DAEMON);
844 while ((ch = getopt(argc, argv, "ch:p:r:")) != -1) {
865 if (host == NULL || repo == NULL || argc != 1)
867 if (tls && port == NULL)
871 username = getenv("GOT_NOTIFY_HTTP_USER");
872 password = getenv("GOT_NOTIFY_HTTP_PASS");
873 if ((username != NULL && password == NULL) ||
874 (username == NULL && password != NULL))
875 fatalx("username or password are not specified");
876 if (username && *password == '\0')
877 fatalx("password can't be empty");
879 /* used by the regression test suite */
880 timeoutstr = getenv("GOT_NOTIFY_TIMEOUT");
882 http_timeout = strtonum(timeoutstr, 0, 600, &errstr);
884 fatalx("timeout in seconds is %s: %s",
888 memset(&timeout, 0, sizeof(timeout));
889 timeout.tv_sec = http_timeout;
891 tmpfp = got_opentemp();
895 jsonify(tmpfp, repo);
897 paylen = ftello(tmpfp);
900 if (fseeko(tmpfp, 0, SEEK_SET) == -1)
905 if (pledge("stdio rpath dns inet", NULL) == -1)
909 memset(&pfd, 0, sizeof(pfd));
910 pfd.fd = dial(host, port);
912 if ((flags = fcntl(pfd.fd, F_GETFL)) == -1)
913 fatal("fcntl(F_GETFL)");
914 if (fcntl(pfd.fd, F_SETFL, flags | O_NONBLOCK) == -1)
915 fatal("fcntl(F_SETFL)");
917 if (bufio_init(&bio) == -1)
919 bufio_set_fd(&bio, pfd.fd);
920 if (tls && bufio_starttls(&bio, host, 0, NULL, 0, NULL, 0) == -1)
921 fatal("bufio_starttls");
924 /* drop rpath dns inet */
925 if (pledge("stdio", NULL) == -1)
929 if ((!tls && strcmp(port, "80") != 0) ||
930 (tls && strcmp(port, "443")) != 0)
933 ret = bufio_compose_fmt(&bio,
934 "POST %s HTTP/1.1\r\n"
936 "Content-Type: application/json\r\n"
937 "Content-Length: %lld\r\n"
939 "Connection: close\r\n",
941 nonstd ? ":" : "", nonstd ? port : "",
942 (long long)paylen, USERAGENT);
944 fatal("bufio_compose_fmt");
947 auth = basic_auth(username, password);
948 ret = bufio_compose_fmt(&bio, "Authorization: basic %s\r\n",
951 fatal("bufio_compose_fmt");
955 if (bufio_compose(&bio, "\r\n", 2) == -1)
956 fatal("bufio_compose");
959 struct timespec elapsed, start, stop;
962 pfd.events = bufio2poll(&bio);
963 clock_gettime(CLOCK_MONOTONIC, &start);
964 ret = ppoll(&pfd, 1, &timeout, NULL);
967 clock_gettime(CLOCK_MONOTONIC, &stop);
968 timespecsub(&stop, &start, &elapsed);
969 timespecsub(&timeout, &elapsed, &timeout);
970 if (ret == 0 || timeout.tv_sec <= 0)
973 if (bio.wbuf.len > 0) {
974 if (bufio_write(&bio) == -1 && errno != EAGAIN)
975 fatalx("bufio_write: %s", bufio_io_err(&bio));
978 r = bufio_read(&bio);
979 if (r == -1 && errno != EAGAIN)
980 fatalx("bufio_read: %s", bufio_io_err(&bio));
982 fatalx("unexpected EOF");
985 line = buf_getdelim(&bio.rbuf, "\r\n", &len);
988 if (response_code && *line == '\0') {
990 * end of headers, don't bother
991 * reading the body, if there is.
997 buf_drain(&bio.rbuf, len);
1000 spc = strchr(line, ' ');
1002 fatalx("bad HTTP response from server");
1004 if (strcasecmp(line, "HTTP/1.1") != 0)
1005 log_warnx("unexpected protocol: %s", line);
1008 spc = strchr(line, ' ');
1010 fatalx("bad HTTP response from server");
1013 response_code = strtonum(line, 100, 599,
1016 log_warnx("response code is %s: %s",
1019 buf_drain(&bio.rbuf, len);
1024 if (!feof(tmpfp) && bio.wbuf.len < sizeof(buf)) {
1025 len = fread(buf, 1, sizeof(buf), tmpfp);
1032 if (bufio_compose(&bio, buf, len) == -1)
1033 fatal("buf_compose");
1037 if (response_code >= 200 && response_code < 300)
1039 fatal("request failed with code %d", response_code);