/* * Copyright (c) 2020-2022 joshua stein * * 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 #include #include "dnr.h" #include "http.h" #include "util.h" char * http_user_agent(void); struct http_request * http_init_req(const char *verb, const char *surl, const char *headers, const char *body, size_t body_len); ssize_t http_req_ingest(struct http_request *req); size_t strappend(char *str, size_t str_size, size_t str_len, char *append); struct url * url_parse(const char *str) { struct url *url = NULL; char *buf, *scheme, *host, *path; unsigned short port; short ret, pos; size_t len, schemelen, hostlen, pathlen; len = strlen(str); scheme = xmalloc(len + 1); if (scheme == NULL) { warn("http: Failed allocating %ld", len + 1); return NULL; } host = xmalloc(len + 1); if (host == NULL) { warn("http: Failed allocating %ld", len + 1); xfree(&scheme); return NULL; } path = xmalloc(len + 1); if (path == NULL) { warn("http: Failed allocating %ld", len + 1); xfree(&host); xfree(&scheme); return NULL; } /* scheme://host:port/path */ ret = sscanf(str, "%[^:]://%[^:]:%d%s%n", scheme, host, &port, path, &pos); if (ret == 4) { if (pos > len) panic("url_parse sscanf overflow"); goto consolidate; } /* scheme://host/path */ ret = sscanf(str, "%[^:]://%[^/]%s%n", scheme, host, path, &pos); if (ret == 3) { if (pos > len) panic("url_parse sscanf overflow"); if (strcmp(scheme, "http") == 0) port = 80; else if (strcmp(scheme, "https") == 0) port = 443; else goto cleanup; goto consolidate; } goto cleanup; consolidate: schemelen = strlen(scheme); hostlen = strlen(host); pathlen = strlen(path); /* * Put everything in a single chunk of memory so the caller can just * free(url) */ len = sizeof(struct url) + schemelen + 1 + hostlen + 1 + pathlen + 1; url = xmalloc(len); if (url == NULL) { warn("http: Failed allocating %ld for URL", len); goto cleanup; } url->scheme = (char *)url + sizeof(struct url); len = strlcpy(url->scheme, scheme, schemelen + 1); url->host = url->scheme + len + 1; len = strlcpy(url->host, host, hostlen + 1); url->path = url->host + len + 1; len = strlcpy(url->path, path, pathlen + 1); url->port = port; cleanup: xfree(&scheme); xfree(&host); xfree(&path); return url; } ssize_t url_encode(unsigned char *str, size_t strlimit, unsigned char *dst, size_t dstsize) { size_t len, n; bool encode = false; char a, b; unsigned char c; encode: for (n = 0, len = 0; str[n] != '\0' && (strlimit ? n < strlimit : 1); n++) { c = str[n]; if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~' || c == ' ') { if (len >= dstsize) return -1; if (c == ' ') c = '+'; dst[len] = c; len++; } else { if (len + 3 >= dstsize) return -1; snprintf((char *)dst + len, dstsize - len, "%%%02X", c); len += 3; } } dst[len] = '\0'; return len; } char * http_user_agent(void) { static char agent[32] = { 0 }; if (agent[0] == '\0') snprintf(agent, sizeof(agent), "Amend/%s", get_version(false)); return agent; } struct http_request * http_init_req(const char *verb, const char *surl, const char *headers, const char *body, size_t body_len) { struct url *url; struct http_request *req; size_t len, alen, hlen; short err; char ip_s[16], trail[2], clength[30]; char *oheaders = NULL, *mheaders = NULL; ip_addr local_ip; tcp_port local_port; _TCPInit(); url = url_parse(surl); if (url == NULL) return NULL; req = xmalloczero(sizeof(struct http_request)); if (req == NULL) { warn("http: Failed allocating http_request"); return NULL; } req->url = url; req->tcp_buf_size = (4 * 1500) + sizeof(req->chunk); req->tcp_buf = xmalloc(req->tcp_buf_size); if (req->tcp_buf == NULL) { warn("http: Failed allocating tcp_buf"); xfree(&req); return NULL; } err = _TCPCreate(&req->tcp_iopb, &req->tcp_stream, (Ptr)req->tcp_buf, req->tcp_buf_size, nil, nil, nil, false); if (err) goto error; err = DNSResolveName(req->url->host, &req->host_ip, NULL); if (err) goto error; long2ip(req->host_ip, (char *)&ip_s); alen = 256 + strlen(req->url->host); oheaders = xmalloc(alen); if (oheaders == NULL) { warn("http: Failed allocating headers"); goto error; } if (body_len) snprintf(clength, sizeof(clength), "Content-Length: %lu\r\n", body_len); else clength[0] = '\0'; hlen = snprintf(oheaders, alen, "Host: %s\r\n" "User-Agent: %s\r\n" "Accept: */*\r\n" "%s", req->url->host, http_user_agent(), clength); if (hlen > alen) { warn("http: Truncated headers"); goto error; } if (headers != NULL) { hlen = http_merge_headers(oheaders, headers, &mheaders); xfree(&oheaders); oheaders = mheaders; mheaders = NULL; } alen = 64 + strlen(req->url->path) + hlen; req->message = xmalloc(alen); if (req->message == NULL) { warn("http: Failed allocating message"); goto error; } len = snprintf(req->message, alen, "%s %s HTTP/1.0\r\n" "%s" "\r\n%s", verb, req->url->path, oheaders, body_len ? "\r\n" : ""); xfree(&oheaders); if (len > alen) { warn("http: Truncated message"); goto error; } err = _TCPActiveOpen(&req->tcp_iopb, req->tcp_stream, req->host_ip, req->url->port, &local_ip, &local_port, nil, nil, false); if (err) goto error; memset(&req->tcp_wds, 0, sizeof(req->tcp_wds)); req->tcp_wds[0].ptr = req->message; req->tcp_wds[0].length = len; if (body_len) { req->tcp_wds[1].ptr = (char *)body; req->tcp_wds[1].length = body_len; } err = _TCPSend(&req->tcp_iopb, req->tcp_stream, req->tcp_wds, nil, nil, false); if (err) goto error; return req; error: http_req_free(&req); return NULL; } struct http_request * http_get(const char *surl, const char *headers) { return http_init_req("GET", surl, headers, NULL, 0); } struct http_request * http_post(const char *surl, const char *headers, const char *body, size_t body_len) { return http_init_req("POST", surl, headers, body, body_len); } size_t http_merge_headers(const char *lheaders, const char *rheaders, char **mheaders) { /* rheaders take precedence */ size_t lhlen, rhlen, mhlen; size_t l, r, lastl, lastr; char *h; bool found; lhlen = strlen(lheaders); rhlen = strlen(rheaders); h = *mheaders = xmalloczero(lhlen + rhlen + 1); if (*mheaders == NULL) panic("http: Failed allocating space for new headers"); /* add each in lheaders, unless it's in rheaders */ mhlen = 0; for (l = 0, lastl = 0; l < lhlen; l++) { *h++ = lheaders[l]; mhlen++; if (lheaders[l] != ':') continue; found = false; for (r = 0, lastr = 0; r < rhlen; r++) { if (rheaders[r] == '\n') { lastr = r + 1; continue; } if (rheaders[r] != ':') continue; if (strncasecmp(lheaders + lastl, rheaders + lastr, r - lastr + 1) == 0) { /* take rvalue */ found = true; for (r = r + 1; r < rhlen; r++) { *h++ = rheaders[r]; mhlen++; if (rheaders[r] == '\n') break; } break; } } for (l = l + 1; l < lhlen; l++) { if (!found) { *h++ = lheaders[l]; mhlen++; } if (lheaders[l] == '\n') break; } lastl = l + 1; } (*mheaders)[mhlen] = '\0'; /* now add each in rheaders, unless it's in lheaders */ for (r = 0, lastr = 0; r < rhlen; r++) { if (rheaders[r] != ':') continue; found = false; for (l = 0, lastl = 0; l < lhlen; l++) { if (lheaders[l] == '\n') { lastl = l + 1; continue; } if (lheaders[l] != ':') continue; if (strncasecmp(lheaders + lastl, rheaders + lastr, l - lastl + 1) == 0) { found = true; break; } } for (r = lastr; r < rhlen; r++) { if (!found) { *h++ = rheaders[r]; mhlen++; } if (rheaders[r] == '\n') break; } lastr = r + 1; } (*mheaders)[mhlen] = '\0'; return mhlen; } ssize_t http_req_ingest(struct http_request *req) { short err; unsigned short rlen; if (!req) return -1; err = _TCPStatus(&req->tcp_iopb, req->tcp_stream, &req->tcp_status_pb, nil, nil, false); if (err || req->tcp_status_pb.connectionState != ConnectionStateEstablished) return -1; if (req->tcp_status_pb.amtUnreadData == 0) return 0; if (req->chunk_len == sizeof(req->chunk)) return 0; rlen = MIN(req->tcp_status_pb.amtUnreadData, sizeof(req->chunk) - req->chunk_len); err = _TCPRcv(&req->tcp_iopb, req->tcp_stream, req->chunk + req->chunk_len, &rlen, nil, nil, false); if (err) return -1; req->chunk_len += rlen; return rlen; } ssize_t http_req_read_line(struct http_request *req, char *ret, size_t len) { ssize_t n, copy = -1, skip = 0; bool dead = false; for (;;) { if (!dead && http_req_ingest(req) < 0) dead = true; for (n = 1; n < req->chunk_len; n++) { if (req->chunk[n - 1] == '\r' && req->chunk[n] == '\n') { copy = n - 1; skip = 2; break; } else if (n + 1 == len) { copy = n + 1; break; } } if (copy == -1 && dead && req->chunk_len < len) { copy = req->chunk_len; break; } if (copy >= 0) break; } if (ret != NULL && copy > 0) memcpy(ret, req->chunk, copy); if (req->chunk_len <= copy + skip) req->chunk_len = 0; else { memmove(req->chunk, req->chunk + copy + skip, req->chunk_len - copy - skip); req->chunk_len -= copy + skip; } return copy; } bool http_req_skip_headers(struct http_request *req) { ssize_t size; size_t length; char header[128]; for (;;) { size = http_req_read_line(req, (char *)&header, sizeof(header)); if (size < 0) return false; if (size == 0) return true; if (size >= sizeof(header)) size = sizeof(header) - 1; header[size] = '\0'; if (strncmp(header, "Content-Length: ", 16) == 0) { if (sscanf(header, "Content-Length: %ld", &length) == 1) req->content_len = length; } } return false; } void http_req_free(void *reqptr) { unsigned long *addr = (unsigned long *)reqptr; void *ptr = (void *)*addr; struct http_request *req = (struct http_request *)ptr; if (req == NULL) return; _TCPRelease(&req->tcp_iopb, req->tcp_stream, nil, nil, false); if (req->message != NULL) xfree(&req->message); xfree(&req->tcp_buf); xfree(&req->url); xfree(&req); *addr = 0L; } /* strlcat but passes a known length */ size_t strappend(char *str, size_t str_size, size_t str_len, char *append) { if (str_len >= str_size - 1) return str_len + strlen(append); while (*append != '\0') { if (str_len < str_size - 1) { str[str_len] = *append; append++; } str_len++; } if (str_len < str_size - 1) str[str_len] = '\0'; else str[str_size - 1] = '\0'; return str_len; } bool pushover(char *api_token, char *user_key, char *options, char *title, char *msg) { static char http_body[1024], param[64]; struct http_request *http; char *curopt; ssize_t len, n, lastn, blen, param_len; char c; blen = strappend(http_body, sizeof(http_body), 0, "token="); blen = strappend(http_body, sizeof(http_body), blen, api_token); blen = strappend(http_body, sizeof(http_body), blen, "&user="); blen = strappend(http_body, sizeof(http_body), blen, user_key); if (title && title[0]) { blen = strappend(http_body, sizeof(http_body), blen, "&title="); len = url_encode((unsigned char *)title, 0, (unsigned char *)http_body + blen, sizeof(http_body) - blen); if (len == -1) return false; blen += len; } blen = strappend(http_body, sizeof(http_body), blen, "&message="); if (blen >= sizeof(http_body)) return false; len = url_encode((unsigned char *)msg, 0, (unsigned char *)http_body + blen, sizeof(http_body) - blen); if (len == -1) return false; blen += len; if (blen >= sizeof(http_body)) return false; param[0] = '\0'; for (n = 0, param_len = 0; options && options[0]; n++) { c = options[n]; if (c == '=' || c == ',' || c == '\0') { /* remove trailing space */ param[param_len] = '\0'; while (param_len > 0 && param[param_len - 1] == ' ') { param[param_len - 1] = '\0'; param_len--; } if (c == '=') blen = strappend(http_body, sizeof(http_body), blen, "&"); else if (c == ',' || c == '\0') blen = strappend(http_body, sizeof(http_body), blen, "="); if (param_len) { if (blen >= sizeof(http_body)) return false; len = url_encode((unsigned char *)param, param_len, (unsigned char *)http_body + blen, sizeof(http_body) - blen); if (len == -1) return false; blen += len; } if (c == '\0') break; param_len = 0; param[0] = '\0'; } else if (param_len < sizeof(param)) { if (c == ' ' && param[0] == '\0') continue; param[param_len++] = c; } else return false; } blen = strappend(http_body, sizeof(http_body), blen, "\r\n"); if (blen > sizeof(http_body)) return false; http = http_post("http://api.pushover.net/1/messages.json", "Content-type: application/x-www-form-urlencoded", http_body, blen); if (!http) return false; http_req_skip_headers(http); http_req_free(&http); return true; }