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>
35 #include "got_opentemp.h"
36 #include "got_version.h"
42 #define USERAGENT "got-notify-http/" GOT_VERSION_STR
44 static int http_timeout = 300; /* 5 minutes in seconds */
49 fprintf(stderr, "usage: %s [-c] -r repo -h host -p port -u user path\n",
55 dial(const char *host, const char *port)
57 struct addrinfo hints, *res, *res0;
58 const char *cause = NULL;
59 int s, error, save_errno;
61 memset(&hints, 0, sizeof(hints));
62 hints.ai_family = AF_UNSPEC;
63 hints.ai_socktype = SOCK_STREAM;
64 error = getaddrinfo(host, port, &hints, &res0);
66 errx(1, "failed to resolve %s:%s: %s", host, port,
70 for (res = res0; res; res = res->ai_next) {
71 s = socket(res->ai_family, res->ai_socktype,
78 if (connect(s, res->ai_addr, res->ai_addrlen) == -1) {
92 fatal("%s %s:%s", cause, host, port);
97 escape(FILE *fp, const uint8_t *s)
99 uint32_t codepoint, state;
100 const uint8_t *start = s;
104 switch (decode(&state, &codepoint, *s)) {
109 fprintf(fp, "\\%c", *s);
127 /* other control characters */
128 if (codepoint < ' ' || codepoint == 0x7F) {
129 fprintf(fp, "\\u%04x", codepoint);
132 fwrite(start, 1, s - start + 1, fp);
139 /* bad UTF-8 sequence; try to recover */
140 fputs("\\uFFFD", fp);
149 json_field(FILE *fp, const char *key, const char *val, int comma)
151 fprintf(fp, "\"%s\":\"", key);
153 fprintf(fp, "\"%s", comma ? "," : "");
157 json_date(FILE *fp, const char *key, const char *date, int comma)
159 fprintf(fp, "\"%s\":%s%s", key, date, comma ? "," : "");
163 json_author(FILE *fp, const char *type, char *address, int comma)
165 char *gt, *lt, *at, *email, *endname;
167 fprintf(fp, "\"%s\":{", type);
169 gt = strchr(address, '<');
171 /* long format, e.g. "Omar Polo <op@openbsd.org>" */
173 json_field(fp, "full", address, 1);
176 while (endname > address && endname[-1] == ' ')
180 json_field(fp, "name", address, 1);
183 lt = strchr(email, '>');
187 json_field(fp, "mail", email, 1);
189 at = strchr(email, '@');
193 json_field(fp, "user", email, 0);
195 /* short format only shows the username */
196 json_field(fp, "user", address, 0);
199 fprintf(fp, "}%s", comma ? "," : "");
203 jsonify_branch_rm(FILE *fp, char *line, const char *repo, const char *user)
207 line = strchr(line, ' ');
209 errx(1, "invalid branch rm line");
210 line += strspn(line, " ");
214 line = strchr(line, ':');
216 errx(1, "invalid branch rm line");
218 id = line + strspn(line, " ");
221 json_field(fp, "type", "branch-deleted", 1);
222 json_field(fp, "repo", repo, 1);
223 json_field(fp, "authenticated_user", user, 1);
224 json_field(fp, "ref", ref, 1);
225 json_field(fp, "id", id, 0);
232 jsonify_commit_short(FILE *fp, char *line, const char *repo, const char *user)
234 char *t, *date, *id, *author, *message;
238 if ((t = strchr(t, ' ')) == NULL)
239 errx(1, "malformed line");
243 if ((t = strchr(t, ' ')) == NULL)
244 errx(1, "malformed line");
248 if ((t = strchr(t, ' ')) == NULL)
249 errx(1, "malformed line");
254 fprintf(fp, "{\"type\":\"commit\",\"short\":true,");
255 json_field(fp, "repo", repo, 1);
256 json_field(fp, "authenticated_user", user, 1);
257 json_field(fp, "id", id, 1);
258 json_author(fp, "committer", author, 1);
259 json_date(fp, "date", date, 1);
260 json_field(fp, "short_message", message, 0);
267 jsonify_commit(FILE *fp, const char *repo, const char *user,
268 char **line, ssize_t *linesize)
276 int msglen = 0, msgwrote = 0;
291 if (strncmp(l, "commit ", 7) != 0)
292 errx(1, "%s: unexpected line: %s", __func__, l);
295 fprintf(fp, "{\"type\":\"commit\",\"short\":false,");
296 json_field(fp, "repo", repo, 1);
297 json_field(fp, "authenticated_user", user, 1);
298 json_field(fp, "id", l, 1);
301 if ((linelen = getline(line, linesize, stdin)) == -1)
304 if ((*line)[linelen - 1] == '\n')
305 (*line)[--linelen] = '\0';
310 if (strncmp(l, "from: ", 6) != 0)
311 errx(1, "unexpected from line");
318 json_author(fp, "author", l, 1);
325 if (!strncmp(l, "via: ", 5)) {
327 json_author(fp, "committer", l, 1);
332 if (author == NULL) /* impossible */
333 fatalx("from not specified");
334 json_author(fp, "committer", author, 1);
343 if (!strncmp(l, "date: ", 6)) {
345 json_date(fp, "date", l, 1);
353 /* optional - more than one */
354 if (!strncmp(l, "parent ", 7)) {
356 l += strcspn(l, ":");
361 fprintf(fp, "\"parents\":[");
378 if (strncmp(l, "messagelen: ", 12) != 0)
379 errx(1, "unexpected messagelen line");
381 msglen = strtonum(l, 1, INT_MAX, &errstr);
383 errx(1, "message len is %s: %s", errstr, l);
392 * The commit message is indented with one extra
393 * space which is not accounted for in messagelen,
394 * but we also strip the trailing \n so that
397 * Since we read line-by-line and there is always
398 * a \n added at the end of the message,
399 * tolerate one byte less than advertised.
402 errx(1, "unexpected line in commit message");
404 l++; /* skip leading space */
407 if (msgwrote == 0 && linelen != 0) {
408 json_field(fp, "short_message", l, 1);
409 fprintf(fp, "\"message\":\"");
413 } else if (msgwrote != 0) {
418 msglen -= linelen + 1;
427 if (files == 0 && !strcmp(l, " "))
431 fputs("\"diffstat\":{\"files\":[", fp);
440 errx(1, "bad diffstat line");
449 json_field(fp, "action", "added", 1);
452 json_field(fp, "action", "deleted", 1);
455 json_field(fp, "action", "modified", 1);
458 json_field(fp, "action", "mode changed", 1);
461 json_field(fp, "action", "unknown", 1);
469 errx(1, "invalid diffstat: no filename");
474 errx(1, "invalid diffstat: no separator");
476 while (t > filename && *t == ' ')
478 json_field(fp, "file", filename, 1);
486 errx(1, "invalid diffstat: no added counter");
489 n = strtonum(l, 0, INT_MAX, &errstr);
491 errx(1, "added counter is %s: %s", errstr, l);
492 fprintf(fp, "\"added\":%d,", n);
500 errx(1, "invalid diffstat: no del counter");
503 n = strtonum(l, 0, INT_MAX, &errstr);
505 errx(1, "del counter is %s: %s", errstr, l);
506 fprintf(fp, "\"removed\":%d", n);
515 fputs("\"total\":{", fp);
520 errx(1, "missing number of additions");
523 n = strtonum(t, 0, INT_MAX, &errstr);
525 errx(1, "add counter is %s: %s", errstr, t);
526 fprintf(fp, "\"added\":%d,", n);
530 errx(1, "missing number of deletions");
537 errx(1, "malformed diffstat sum line");
540 n = strtonum(l, 0, INT_MAX, &errstr);
542 errx(1, "del counter is %s: %s", errstr, l);
543 fprintf(fp, "\"removed\":%d", n);
551 errx(1, "unexpected line: %s", *line);
557 fatalx("%s: unexpected EOF", __func__);
564 jsonify_tag(FILE *fp, const char *repo, const char *user,
565 char **line, ssize_t *linesize)
570 int msglen = 0, msgwrote = 0;
581 if (strncmp(l, "tag ", 4) != 0)
582 errx(1, "%s: unexpected line: %s", __func__, l);
586 json_field(fp, "type", "tag", 1);
587 json_field(fp, "repo", repo, 1);
588 json_field(fp, "authenticated_user", user, 1);
589 json_field(fp, "tag", l, 1);
592 if ((linelen = getline(line, linesize, stdin)) == -1)
595 if ((*line)[linelen - 1] == '\n')
596 (*line)[--linelen] = '\0';
601 if (strncmp(l, "from: ", 6) != 0)
602 errx(1, "unexpected from line");
605 json_author(fp, "tagger", l, 1);
612 if (!strncmp(l, "date: ", 6)) {
614 json_date(fp, "date", l, 1);
623 if (!strncmp(l, "object: ", 8)) {
630 errx(1, "malformed tag object line");
633 fputs("\"object\":{", fp);
634 json_field(fp, "type", type, 1);
635 json_field(fp, "id", id, 0);
645 if (strncmp(l, "messagelen: ", 12) != 0)
646 errx(1, "unexpected messagelen line");
648 msglen = strtonum(l, 1, INT_MAX, &errstr);
650 errx(1, "message len is %s: %s", errstr, l);
659 errx(1, "unexpected line in tag message");
661 l++; /* skip leading space */
664 if (msgwrote == 0 && linelen != 0) {
665 fprintf(fp, "\"message\":\"");
669 } else if (msgwrote != 0) {
674 msglen -= linelen + 1;
684 errx(1, "unexpected line: %s", *line);
690 fatalx("%s: unexpected EOF", __func__);
697 jsonify(FILE *fp, const char *repo, const char *user)
704 fprintf(fp, "{\"notifications\":[");
705 while ((linelen = getline(&line, &linesize, stdin)) != -1) {
706 if (line[linelen - 1] == '\n')
707 line[--linelen] = '\0';
716 if (strncmp(line, "Removed refs/heads/", 19) == 0) {
717 if (jsonify_branch_rm(fp, line, repo, user) == -1)
718 fatal("jsonify_branch_rm");
722 if (strncmp(line, "commit ", 7) == 0) {
723 if (jsonify_commit(fp, repo, user,
724 &line, &linesize) == -1)
725 fatal("jsonify_commit");
729 if (*line >= '0' && *line <= '9') {
730 if (jsonify_commit_short(fp, line, repo, user) == -1)
731 fatal("jsonify_commit_short");
735 if (strncmp(line, "tag ", 4) == 0) {
736 if (jsonify_tag(fp, repo, user, &line, &linesize) == -1)
737 fatal("jsonify_tag");
741 errx(1, "unexpected line: %s", line);
769 errx(1, "invalid sixet 0x%x", c);
773 basic_auth(const char *username, const char *password)
775 char *str, *tmp, *end, *s, *p;
779 r = asprintf(&str, "%s:%s", username, password);
784 * Will need 4 * r/3 bytes to encode the string, plus a
785 * rounding to the next multiple of 4 for padding, plus NUL.
788 len = (len + 3) & ~3;
791 tmp = calloc(1, len);
798 memset(buf, 0, sizeof(buf));
799 for (i = 0; i < 3 && *s != '\0'; ++i, ++s)
802 *p++ = sixet2ch(buf[0] >> 2);
803 *p++ = sixet2ch((buf[1] >> 4) | (buf[0] << 4));
805 *p++ = sixet2ch((buf[1] << 2) | (buf[2] >> 6));
807 *p++ = sixet2ch(buf[2]);
810 for (end = tmp + len - 1; p < end; ++p)
818 bufio2poll(struct bufio *bio)
823 * If we have data queued up, retry for both POLLIN and POLLOUT
824 * since we want to push this data to the server while still
825 * processing an eventual reply. Otherwise, we could wait
826 * indefinitely for the server to reply without us having
827 * sent the HTTP request completely.
830 return POLLIN|POLLOUT;
833 if (f & BUFIO_WANT_READ)
835 if (f & BUFIO_WANT_WRITE)
841 main(int argc, char **argv)
846 struct timespec timeout;
847 const char *username;
848 const char *password;
849 const char *timeoutstr;
851 const char *repo = NULL;
852 const char *host = NULL, *port = NULL, *path = NULL;
853 const char *gotd_auth_user = NULL;
854 char *auth, *line, *spc;
859 int response_code = 0, done = 0;
860 int ch, flags, ret, nonstd = 0;
863 if (pledge("stdio rpath tmppath dns inet", NULL) == -1)
867 log_init(0, LOG_DAEMON);
869 while ((ch = getopt(argc, argv, "ch:p:r:u:")) != -1) {
884 gotd_auth_user = optarg;
893 if (host == NULL || repo == NULL || gotd_auth_user == NULL || argc != 1)
895 if (tls && port == NULL)
899 username = getenv("GOT_NOTIFY_HTTP_USER");
900 password = getenv("GOT_NOTIFY_HTTP_PASS");
901 if ((username != NULL && password == NULL) ||
902 (username == NULL && password != NULL))
903 fatalx("username or password are not specified");
904 if (username && *password == '\0')
905 fatalx("password can't be empty");
907 /* used by the regression test suite */
908 timeoutstr = getenv("GOT_NOTIFY_TIMEOUT");
910 http_timeout = strtonum(timeoutstr, 0, 600, &errstr);
912 fatalx("timeout in seconds is %s: %s",
916 memset(&timeout, 0, sizeof(timeout));
917 timeout.tv_sec = http_timeout;
919 tmpfp = got_opentemp();
923 jsonify(tmpfp, repo, gotd_auth_user);
925 paylen = ftello(tmpfp);
928 if (fseeko(tmpfp, 0, SEEK_SET) == -1)
933 if (pledge("stdio rpath dns inet", NULL) == -1)
937 memset(&pfd, 0, sizeof(pfd));
938 pfd.fd = dial(host, port);
940 if ((flags = fcntl(pfd.fd, F_GETFL)) == -1)
941 fatal("fcntl(F_GETFL)");
942 if (fcntl(pfd.fd, F_SETFL, flags | O_NONBLOCK) == -1)
943 fatal("fcntl(F_SETFL)");
945 if (bufio_init(&bio) == -1)
947 bufio_set_fd(&bio, pfd.fd);
948 if (tls && bufio_starttls(&bio, host, 0, NULL, 0, NULL, 0) == -1)
949 fatal("bufio_starttls");
952 /* drop rpath dns inet */
953 if (pledge("stdio", NULL) == -1)
957 if ((!tls && strcmp(port, "80") != 0) ||
958 (tls && strcmp(port, "443")) != 0)
961 ret = bufio_compose_fmt(&bio,
962 "POST %s HTTP/1.1\r\n"
964 "Content-Type: application/json\r\n"
965 "Content-Length: %lld\r\n"
967 "Connection: close\r\n",
969 nonstd ? ":" : "", nonstd ? port : "",
970 (long long)paylen, USERAGENT);
972 fatal("bufio_compose_fmt");
975 auth = basic_auth(username, password);
976 ret = bufio_compose_fmt(&bio, "Authorization: basic %s\r\n",
979 fatal("bufio_compose_fmt");
983 if (bufio_compose(&bio, "\r\n", 2) == -1)
984 fatal("bufio_compose");
987 struct timespec elapsed, start, stop;
990 pfd.events = bufio2poll(&bio);
991 clock_gettime(CLOCK_MONOTONIC, &start);
992 ret = ppoll(&pfd, 1, &timeout, NULL);
995 clock_gettime(CLOCK_MONOTONIC, &stop);
996 timespecsub(&stop, &start, &elapsed);
997 timespecsub(&timeout, &elapsed, &timeout);
998 if (ret == 0 || timeout.tv_sec <= 0)
1001 if (bio.wbuf.len > 0) {
1002 if (bufio_write(&bio) == -1 && errno != EAGAIN)
1003 fatalx("bufio_write: %s", bufio_io_err(&bio));
1006 r = bufio_read(&bio);
1007 if (r == -1 && errno != EAGAIN)
1008 fatalx("bufio_read: %s", bufio_io_err(&bio));
1010 fatalx("unexpected EOF from upstream HTTP server");
1013 line = buf_getdelim(&bio.rbuf, "\r\n", &len);
1016 if (response_code && *line == '\0') {
1018 * end of headers, don't bother
1019 * reading the body, if there is.
1024 if (response_code) {
1025 buf_drain(&bio.rbuf, len);
1028 spc = strchr(line, ' ');
1030 fatalx("bad HTTP response from server");
1032 if (strcasecmp(line, "HTTP/1.1") != 0)
1033 log_warnx("unexpected protocol: %s", line);
1036 spc = strchr(line, ' ');
1038 fatalx("bad HTTP response from server");
1041 response_code = strtonum(line, 100, 599,
1044 log_warnx("response code is %s: %s",
1047 buf_drain(&bio.rbuf, len);
1052 if (!feof(tmpfp) && bio.wbuf.len < sizeof(buf)) {
1053 len = fread(buf, 1, sizeof(buf), tmpfp);
1060 if (bufio_compose(&bio, buf, len) == -1)
1061 fatal("buf_compose");
1065 if (response_code >= 200 && response_code < 300)
1067 fatalx("request failed with code %d", response_code);