AmendHub

Download

jcs

/

wallops

/

http.c

 

(View History)

jcs   http: Minor safety fixes Latest amendment: 141 on 2025-12-17

1 /*
2 * Copyright (c) 2020-2022 joshua stein <jcs@jcs.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 */
16
17 #include <stdio.h>
18 #include <string.h>
19 #include "dnr.h"
20 #include "http.h"
21 #include "util.h"
22
23 char * http_user_agent(void);
24 struct http_request * http_init_req(const char *verb, const char *surl,
25 const char *headers, const char *body, size_t body_len);
26 ssize_t http_req_ingest(struct http_request *req);
27 size_t strappend(char *str, size_t str_size, size_t str_len, char *append);
28
29 struct url *
30 url_parse(const char *str)
31 {
32 struct url *url = NULL;
33 char *buf, *scheme, *host, *path;
34 unsigned short port;
35 short ret, pos;
36 size_t len, schemelen, hostlen, pathlen;
37
38 len = strlen(str);
39 scheme = xmalloc(len + 1);
40 if (scheme == NULL) {
41 warn("http: Failed allocating %ld", len + 1);
42 return NULL;
43 }
44 host = xmalloc(len + 1);
45 if (host == NULL) {
46 warn("http: Failed allocating %ld", len + 1);
47 xfree(&scheme);
48 return NULL;
49 }
50 path = xmalloc(len + 1);
51 if (path == NULL) {
52 warn("http: Failed allocating %ld", len + 1);
53 xfree(&host);
54 xfree(&scheme);
55 return NULL;
56 }
57
58 /* scheme://host:port/path */
59 ret = sscanf(str, "%[^:]://%[^:]:%d%s%n", scheme, host, &port, path,
60 &pos);
61 if (ret == 4) {
62 if (pos > len)
63 panic("url_parse sscanf overflow");
64 goto consolidate;
65 }
66
67 /* scheme://host/path */
68 ret = sscanf(str, "%[^:]://%[^/]%s%n", scheme, host, path, &pos);
69 if (ret == 3) {
70 if (pos > len)
71 panic("url_parse sscanf overflow");
72 if (strcmp(scheme, "http") == 0)
73 port = 80;
74 else if (strcmp(scheme, "https") == 0)
75 port = 443;
76 else
77 goto cleanup;
78 goto consolidate;
79 }
80
81 goto cleanup;
82
83 consolidate:
84 schemelen = strlen(scheme);
85 hostlen = strlen(host);
86 pathlen = strlen(path);
87
88 /*
89 * Put everything in a single chunk of memory so the caller can just
90 * free(url)
91 */
92 len = sizeof(struct url) + schemelen + 1 + hostlen + 1 + pathlen + 1;
93 url = xmalloc(len);
94 if (url == NULL) {
95 warn("http: Failed allocating %ld for URL", len);
96 goto cleanup;
97 }
98
99 url->scheme = (char *)url + sizeof(struct url);
100 len = strlcpy(url->scheme, scheme, schemelen + 1);
101
102 url->host = url->scheme + len + 1;
103 len = strlcpy(url->host, host, hostlen + 1);
104
105 url->path = url->host + len + 1;
106 len = strlcpy(url->path, path, pathlen + 1);
107
108 url->port = port;
109
110 cleanup:
111 xfree(&scheme);
112 xfree(&host);
113 xfree(&path);
114
115 return url;
116 }
117
118 ssize_t
119 url_encode(unsigned char *str, size_t strlimit, unsigned char *dst,
120 size_t dstsize)
121 {
122 size_t len, n;
123 bool encode = false;
124 char a, b;
125 unsigned char c;
126
127 encode:
128 for (n = 0, len = 0; str[n] != '\0' && (strlimit ? n < strlimit : 1);
129 n++) {
130 c = str[n];
131
132 if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
133 (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' ||
134 c == '~' || c == ' ') {
135 if (len >= dstsize)
136 return -1;
137 if (c == ' ')
138 c = '+';
139 dst[len] = c;
140 len++;
141 } else {
142 if (len + 3 >= dstsize)
143 return -1;
144 snprintf((char *)dst + len, dstsize - len, "%%%02X", c);
145 len += 3;
146 }
147 }
148
149 dst[len] = '\0';
150 return len;
151 }
152
153 char *
154 http_user_agent(void)
155 {
156 static char agent[32] = { 0 };
157
158 if (agent[0] == '\0')
159 snprintf(agent, sizeof(agent), "Amend/%s", get_version(false));
160
161 return agent;
162 }
163
164 struct http_request *
165 http_init_req(const char *verb, const char *surl, const char *headers,
166 const char *body, size_t body_len)
167 {
168 struct url *url;
169 struct http_request *req;
170 size_t len, alen, hlen;
171 short err;
172 char ip_s[16], trail[2], clength[30];
173 char *oheaders = NULL, *mheaders = NULL;
174 ip_addr local_ip;
175 tcp_port local_port;
176
177 _TCPInit();
178
179 url = url_parse(surl);
180 if (url == NULL)
181 return NULL;
182
183 req = xmalloczero(sizeof(struct http_request));
184 if (req == NULL) {
185 warn("http: Failed allocating http_request");
186 return NULL;
187 }
188 req->url = url;
189 req->tcp_buf_size = (4 * 1500) + sizeof(req->chunk);
190 req->tcp_buf = xmalloc(req->tcp_buf_size);
191 if (req->tcp_buf == NULL) {
192 warn("http: Failed allocating tcp_buf");
193 xfree(&req);
194 return NULL;
195 }
196
197 err = _TCPCreate(&req->tcp_iopb, &req->tcp_stream, (Ptr)req->tcp_buf,
198 req->tcp_buf_size, nil, nil, nil, false);
199 if (err)
200 goto error;
201
202 err = DNSResolveName(req->url->host, &req->host_ip, NULL);
203 if (err)
204 goto error;
205
206 long2ip(req->host_ip, (char *)&ip_s);
207
208 alen = 256 + strlen(req->url->host);
209 oheaders = xmalloc(alen);
210 if (oheaders == NULL) {
211 warn("http: Failed allocating headers");
212 goto error;
213 }
214
215 if (body_len)
216 snprintf(clength, sizeof(clength),
217 "Content-Length: %lu\r\n", body_len);
218 else
219 clength[0] = '\0';
220
221 hlen = snprintf(oheaders, alen,
222 "Host: %s\r\n"
223 "User-Agent: %s\r\n"
224 "Accept: */*\r\n"
225 "%s",
226 req->url->host, http_user_agent(), clength);
227 if (hlen > alen) {
228 warn("http: Truncated headers");
229 goto error;
230 }
231
232 if (headers != NULL) {
233 hlen = http_merge_headers(oheaders, headers, &mheaders);
234 xfree(&oheaders);
235 oheaders = mheaders;
236 mheaders = NULL;
237 }
238
239 alen = 64 + strlen(req->url->path) + hlen;
240 req->message = xmalloc(alen);
241 if (req->message == NULL) {
242 warn("http: Failed allocating message");
243 goto error;
244 }
245
246 len = snprintf(req->message, alen,
247 "%s %s HTTP/1.0\r\n"
248 "%s"
249 "\r\n%s", verb, req->url->path, oheaders, body_len ? "\r\n" : "");
250 xfree(&oheaders);
251 if (len > alen) {
252 warn("http: Truncated message");
253 goto error;
254 }
255
256 err = _TCPActiveOpen(&req->tcp_iopb, req->tcp_stream, req->host_ip,
257 req->url->port, &local_ip, &local_port, nil, nil, false);
258 if (err)
259 goto error;
260
261 memset(&req->tcp_wds, 0, sizeof(req->tcp_wds));
262 req->tcp_wds[0].ptr = req->message;
263 req->tcp_wds[0].length = len;
264
265 if (body_len) {
266 req->tcp_wds[1].ptr = (char *)body;
267 req->tcp_wds[1].length = body_len;
268 }
269
270 err = _TCPSend(&req->tcp_iopb, req->tcp_stream, req->tcp_wds, nil, nil,
271 false);
272 if (err)
273 goto error;
274
275 return req;
276
277 error:
278 http_req_free(&req);
279 return NULL;
280 }
281
282 struct http_request *
283 http_get(const char *surl, const char *headers)
284 {
285 return http_init_req("GET", surl, headers, NULL, 0);
286 }
287
288 struct http_request *
289 http_post(const char *surl, const char *headers, const char *body,
290 size_t body_len)
291 {
292 return http_init_req("POST", surl, headers, body, body_len);
293 }
294
295 size_t
296 http_merge_headers(const char *lheaders, const char *rheaders,
297 char **mheaders)
298 {
299 /* rheaders take precedence */
300 size_t lhlen, rhlen, mhlen;
301 size_t l, r, lastl, lastr;
302 char *h;
303 bool found;
304
305 lhlen = strlen(lheaders);
306 rhlen = strlen(rheaders);
307
308 h = *mheaders = xmalloczero(lhlen + rhlen + 1);
309 if (*mheaders == NULL)
310 panic("http: Failed allocating space for new headers");
311
312 /* add each in lheaders, unless it's in rheaders */
313 mhlen = 0;
314 for (l = 0, lastl = 0; l < lhlen; l++) {
315 *h++ = lheaders[l];
316 mhlen++;
317
318 if (lheaders[l] != ':')
319 continue;
320
321 found = false;
322 for (r = 0, lastr = 0; r < rhlen; r++) {
323 if (rheaders[r] == '\n') {
324 lastr = r + 1;
325 continue;
326 }
327
328 if (rheaders[r] != ':')
329 continue;
330
331 if (strncasecmp(lheaders + lastl, rheaders + lastr,
332 r - lastr + 1) == 0) {
333 /* take rvalue */
334 found = true;
335 for (r = r + 1; r < rhlen; r++) {
336 *h++ = rheaders[r];
337 mhlen++;
338 if (rheaders[r] == '\n')
339 break;
340 }
341 break;
342 }
343 }
344
345 for (l = l + 1; l < lhlen; l++) {
346 if (!found) {
347 *h++ = lheaders[l];
348 mhlen++;
349 }
350 if (lheaders[l] == '\n')
351 break;
352 }
353 lastl = l + 1;
354 }
355
356 (*mheaders)[mhlen] = '\0';
357
358 /* now add each in rheaders, unless it's in lheaders */
359 for (r = 0, lastr = 0; r < rhlen; r++) {
360 if (rheaders[r] != ':')
361 continue;
362
363 found = false;
364 for (l = 0, lastl = 0; l < lhlen; l++) {
365 if (lheaders[l] == '\n') {
366 lastl = l + 1;
367 continue;
368 }
369 if (lheaders[l] != ':')
370 continue;
371
372 if (strncasecmp(lheaders + lastl, rheaders + lastr,
373 l - lastl + 1) == 0) {
374 found = true;
375 break;
376 }
377 }
378
379 for (r = lastr; r < rhlen; r++) {
380 if (!found) {
381 *h++ = rheaders[r];
382 mhlen++;
383 }
384 if (rheaders[r] == '\n')
385 break;
386 }
387 lastr = r + 1;
388 }
389
390 (*mheaders)[mhlen] = '\0';
391
392 return mhlen;
393 }
394
395 ssize_t
396 http_req_ingest(struct http_request *req)
397 {
398 short err;
399 unsigned short rlen;
400
401 if (!req)
402 return -1;
403
404 err = _TCPStatus(&req->tcp_iopb, req->tcp_stream, &req->tcp_status_pb,
405 nil, nil, false);
406 if (err ||
407 req->tcp_status_pb.connectionState != ConnectionStateEstablished)
408 return -1;
409
410 if (req->tcp_status_pb.amtUnreadData == 0)
411 return 0;
412 if (req->chunk_len == sizeof(req->chunk))
413 return 0;
414
415 rlen = MIN(req->tcp_status_pb.amtUnreadData,
416 sizeof(req->chunk) - req->chunk_len);
417
418 err = _TCPRcv(&req->tcp_iopb, req->tcp_stream,
419 req->chunk + req->chunk_len, &rlen, nil, nil, false);
420 if (err)
421 return -1;
422
423 req->chunk_len += rlen;
424
425 return rlen;
426 }
427
428 ssize_t
429 http_req_read_line(struct http_request *req, char *ret, size_t len)
430 {
431 ssize_t n, copy = -1, skip = 0;
432 bool dead = false;
433
434 for (;;) {
435 if (!dead && http_req_ingest(req) < 0)
436 dead = true;
437
438 for (n = 1; n < req->chunk_len; n++) {
439 if (req->chunk[n - 1] == '\r' && req->chunk[n] == '\n') {
440 copy = n - 1;
441 skip = 2;
442 break;
443 } else if (n + 1 == len) {
444 copy = n + 1;
445 break;
446 }
447 }
448
449 if (copy == -1 && dead && req->chunk_len < len) {
450 copy = req->chunk_len;
451 break;
452 }
453 if (copy >= 0)
454 break;
455 }
456
457 if (ret != NULL && copy > 0)
458 memcpy(ret, req->chunk, copy);
459
460 if (req->chunk_len <= copy + skip)
461 req->chunk_len = 0;
462 else {
463 memmove(req->chunk, req->chunk + copy + skip,
464 req->chunk_len - copy - skip);
465 req->chunk_len -= copy + skip;
466 }
467
468 return copy;
469 }
470
471 bool
472 http_req_skip_headers(struct http_request *req)
473 {
474 ssize_t size;
475 size_t length;
476 char header[128];
477
478 for (;;) {
479 size = http_req_read_line(req, (char *)&header, sizeof(header));
480 if (size < 0)
481 return false;
482 if (size == 0)
483 return true;
484
485 if (size >= sizeof(header))
486 size = sizeof(header) - 1;
487 header[size] = '\0';
488
489 if (strncmp(header, "Content-Length: ", 16) == 0) {
490 if (sscanf(header, "Content-Length: %ld", &length) == 1)
491 req->content_len = length;
492 }
493 }
494
495 return false;
496 }
497
498 void
499 http_req_free(void *reqptr)
500 {
501 unsigned long *addr = (unsigned long *)reqptr;
502 void *ptr = (void *)*addr;
503 struct http_request *req = (struct http_request *)ptr;
504
505 if (req == NULL)
506 return;
507
508 _TCPRelease(&req->tcp_iopb, req->tcp_stream, nil, nil, false);
509
510 if (req->message != NULL)
511 xfree(&req->message);
512 xfree(&req->tcp_buf);
513 xfree(&req->url);
514 xfree(&req);
515
516 *addr = 0L;
517 }
518
519 /* strlcat but passes a known length */
520 size_t
521 strappend(char *str, size_t str_size, size_t str_len, char *append)
522 {
523 if (str_len >= str_size - 1)
524 return str_len + strlen(append);
525
526 while (*append != '\0') {
527 if (str_len < str_size - 1) {
528 str[str_len] = *append;
529 append++;
530 }
531 str_len++;
532 }
533 if (str_len < str_size - 1)
534 str[str_len] = '\0';
535 else
536 str[str_size - 1] = '\0';
537
538 return str_len;
539 }
540
541 bool
542 pushover(char *api_token, char *user_key, char *options, char *title,
543 char *msg)
544 {
545 static char http_body[1024], param[64];
546 struct http_request *http;
547 char *curopt;
548 ssize_t len, n, lastn, blen, param_len;
549 char c;
550
551 blen = strappend(http_body, sizeof(http_body), 0, "token=");
552 blen = strappend(http_body, sizeof(http_body), blen, api_token);
553 blen = strappend(http_body, sizeof(http_body), blen, "&user=");
554 blen = strappend(http_body, sizeof(http_body), blen, user_key);
555
556 if (title && title[0]) {
557 blen = strappend(http_body, sizeof(http_body), blen, "&title=");
558 len = url_encode((unsigned char *)title, 0,
559 (unsigned char *)http_body + blen, sizeof(http_body) - blen);
560 if (len == -1)
561 return false;
562 blen += len;
563 }
564
565 blen = strappend(http_body, sizeof(http_body), blen, "&message=");
566
567 if (blen >= sizeof(http_body))
568 return false;
569
570 len = url_encode((unsigned char *)msg, 0,
571 (unsigned char *)http_body + blen, sizeof(http_body) - blen);
572 if (len == -1)
573 return false;
574 blen += len;
575
576 if (blen >= sizeof(http_body))
577 return false;
578
579 param[0] = '\0';
580
581 for (n = 0, param_len = 0; options && options[0]; n++) {
582 c = options[n];
583
584 if (c == '=' || c == ',' || c == '\0') {
585 /* remove trailing space */
586 param[param_len] = '\0';
587 while (param_len > 0 && param[param_len - 1] == ' ') {
588 param[param_len - 1] = '\0';
589 param_len--;
590 }
591
592 if (c == '=')
593 blen = strappend(http_body, sizeof(http_body), blen,
594 "&");
595 else if (c == ',' || c == '\0')
596 blen = strappend(http_body, sizeof(http_body), blen,
597 "=");
598
599 if (param_len) {
600 if (blen >= sizeof(http_body))
601 return false;
602 len = url_encode((unsigned char *)param, param_len,
603 (unsigned char *)http_body + blen,
604 sizeof(http_body) - blen);
605 if (len == -1)
606 return false;
607 blen += len;
608 }
609
610 if (c == '\0')
611 break;
612
613 param_len = 0;
614 param[0] = '\0';
615 } else if (param_len < sizeof(param)) {
616 if (c == ' ' && param[0] == '\0')
617 continue;
618 param[param_len++] = c;
619 } else
620 return false;
621 }
622
623 blen = strappend(http_body, sizeof(http_body), blen, "\r\n");
624 if (blen > sizeof(http_body))
625 return false;
626
627 http = http_post("http://api.pushover.net/1/messages.json",
628 "Content-type: application/x-www-form-urlencoded", http_body,
629 blen);
630 if (!http)
631 return false;
632 http_req_skip_headers(http);
633 http_req_free(&http);
634
635 return true;
636 }