uclient-http: basic auth: Handle memory allocation failure
[project/uclient.git] / uclient-http.c
1 /*
2 * uclient - ustream based protocol client library
3 *
4 * Copyright (C) 2014 Felix Fietkau <nbd@openwrt.org>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18 #include <sys/socket.h>
19 #include <stdio.h>
20 #include <ctype.h>
21 #include <unistd.h>
22 #include <stdint.h>
23 #include <string.h>
24 #include <fcntl.h>
25
26 #include <libubox/ustream.h>
27 #include <libubox/ustream-ssl.h>
28 #include <libubox/usock.h>
29 #include <libubox/blobmsg.h>
30
31 #include "uclient.h"
32 #include "uclient-utils.h"
33 #include "uclient-backend.h"
34
35 enum auth_type {
36 AUTH_TYPE_UNKNOWN,
37 AUTH_TYPE_NONE,
38 AUTH_TYPE_BASIC,
39 AUTH_TYPE_DIGEST,
40 };
41
42 enum request_type {
43 REQ_GET,
44 REQ_HEAD,
45 REQ_POST,
46 REQ_PUT,
47 REQ_DELETE,
48 __REQ_MAX
49 };
50
51 enum http_state {
52 HTTP_STATE_INIT,
53 HTTP_STATE_HEADERS_SENT,
54 HTTP_STATE_REQUEST_DONE,
55 HTTP_STATE_RECV_HEADERS,
56 HTTP_STATE_RECV_DATA,
57 HTTP_STATE_ERROR,
58 };
59
60 static const char * const request_types[__REQ_MAX] = {
61 [REQ_GET] = "GET",
62 [REQ_HEAD] = "HEAD",
63 [REQ_POST] = "POST",
64 [REQ_PUT] = "PUT",
65 [REQ_DELETE] = "DELETE",
66 };
67
68 struct uclient_http {
69 struct uclient uc;
70
71 const struct ustream_ssl_ops *ssl_ops;
72 struct ustream_ssl_ctx *ssl_ctx;
73 struct ustream *us;
74
75 struct ustream_fd ufd;
76 struct ustream_ssl ussl;
77
78 struct uloop_timeout disconnect_t;
79 unsigned int seq;
80
81 bool ssl_require_validation;
82 bool ssl;
83 bool eof;
84 bool connection_close;
85 bool disconnect;
86 enum request_type req_type;
87 enum http_state state;
88
89 enum auth_type auth_type;
90 char *auth_str;
91
92 long read_chunked;
93 long content_length;
94
95 int usock_flags;
96
97 uint32_t nc;
98
99 struct blob_buf headers;
100 struct blob_buf meta;
101 };
102
103 enum {
104 PREFIX_HTTP,
105 PREFIX_HTTPS,
106 __PREFIX_MAX,
107 };
108
109 static const char * const uclient_http_prefix[] = {
110 [PREFIX_HTTP] = "http://",
111 [PREFIX_HTTPS] = "https://",
112 [__PREFIX_MAX] = NULL
113 };
114
115 static int uclient_http_connect(struct uclient *cl);
116
117 static int uclient_do_connect(struct uclient_http *uh, const char *port)
118 {
119 socklen_t sl;
120 int fd;
121
122 if (uh->uc.url->port)
123 port = uh->uc.url->port;
124
125 memset(&uh->uc.remote_addr, 0, sizeof(uh->uc.remote_addr));
126
127 fd = usock_inet_timeout(USOCK_TCP | USOCK_NONBLOCK | uh->usock_flags,
128 uh->uc.url->host, port, &uh->uc.remote_addr,
129 uh->uc.timeout_msecs);
130 if (fd < 0)
131 return -1;
132
133 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
134 ustream_fd_init(&uh->ufd, fd);
135
136 sl = sizeof(uh->uc.local_addr);
137 memset(&uh->uc.local_addr, 0, sl);
138 getsockname(fd, &uh->uc.local_addr.sa, &sl);
139
140 return 0;
141 }
142
143 static void uclient_http_disconnect(struct uclient_http *uh)
144 {
145 uloop_timeout_cancel(&uh->disconnect_t);
146 if (!uh->us)
147 return;
148
149 if (uh->ssl)
150 ustream_free(&uh->ussl.stream);
151 ustream_free(&uh->ufd.stream);
152 close(uh->ufd.fd.fd);
153 uh->us = NULL;
154 }
155
156 static void uclient_http_free_url_state(struct uclient *cl)
157 {
158 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
159
160 uh->auth_type = AUTH_TYPE_UNKNOWN;
161 free(uh->auth_str);
162 uh->auth_str = NULL;
163 uclient_http_disconnect(uh);
164 }
165
166 static void uclient_http_error(struct uclient_http *uh, int code)
167 {
168 uh->state = HTTP_STATE_ERROR;
169 uh->us->eof = true;
170 ustream_state_change(uh->us);
171 uclient_backend_set_error(&uh->uc, code);
172 }
173
174 static void uclient_http_request_disconnect(struct uclient *cl)
175 {
176 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
177
178 if (!uh->us)
179 return;
180
181 uh->eof = true;
182 uh->disconnect = true;
183 uloop_timeout_set(&uh->disconnect_t, 1);
184 }
185
186 static void uclient_notify_eof(struct uclient_http *uh)
187 {
188 struct ustream *us = uh->us;
189
190 if (uh->disconnect)
191 return;
192
193 if (!uh->eof) {
194 if (!us->eof && !us->write_error)
195 return;
196
197 if (ustream_pending_data(us, false))
198 return;
199 }
200
201 if (uh->content_length < 0 && uh->read_chunked >= 0)
202 uh->uc.data_eof = true;
203
204 uclient_backend_set_eof(&uh->uc);
205
206 if (uh->connection_close)
207 uclient_http_request_disconnect(&uh->uc);
208 }
209
210 static void uclient_http_reset_state(struct uclient_http *uh)
211 {
212 uh->seq++;
213 uclient_backend_reset_state(&uh->uc);
214 uh->read_chunked = -1;
215 uh->content_length = -1;
216 uh->eof = false;
217 uh->disconnect = false;
218 uh->connection_close = false;
219 uh->state = HTTP_STATE_INIT;
220
221 if (uh->auth_type == AUTH_TYPE_UNKNOWN && !uh->uc.url->auth)
222 uh->auth_type = AUTH_TYPE_NONE;
223 }
224
225 static void uclient_http_init_request(struct uclient_http *uh)
226 {
227 uh->seq++;
228 uclient_http_reset_state(uh);
229 blob_buf_init(&uh->meta, 0);
230 }
231
232 static enum auth_type
233 uclient_http_update_auth_type(struct uclient_http *uh)
234 {
235 if (!uh->auth_str)
236 return AUTH_TYPE_NONE;
237
238 if (!strncasecmp(uh->auth_str, "basic", 5))
239 return AUTH_TYPE_BASIC;
240
241 if (!strncasecmp(uh->auth_str, "digest", 6))
242 return AUTH_TYPE_DIGEST;
243
244 return AUTH_TYPE_NONE;
245 }
246
247 static void uclient_http_process_headers(struct uclient_http *uh)
248 {
249 enum {
250 HTTP_HDR_TRANSFER_ENCODING,
251 HTTP_HDR_CONNECTION,
252 HTTP_HDR_CONTENT_LENGTH,
253 HTTP_HDR_AUTH,
254 __HTTP_HDR_MAX,
255 };
256 static const struct blobmsg_policy hdr_policy[__HTTP_HDR_MAX] = {
257 #define hdr(_name) { .name = _name, .type = BLOBMSG_TYPE_STRING }
258 [HTTP_HDR_TRANSFER_ENCODING] = hdr("transfer-encoding"),
259 [HTTP_HDR_CONNECTION] = hdr("connection"),
260 [HTTP_HDR_CONTENT_LENGTH] = hdr("content-length"),
261 [HTTP_HDR_AUTH] = hdr("www-authenticate"),
262 #undef hdr
263 };
264 struct blob_attr *tb[__HTTP_HDR_MAX];
265 struct blob_attr *cur;
266
267 blobmsg_parse(hdr_policy, __HTTP_HDR_MAX, tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
268
269 cur = tb[HTTP_HDR_TRANSFER_ENCODING];
270 if (cur && strstr(blobmsg_data(cur), "chunked"))
271 uh->read_chunked = 0;
272
273 cur = tb[HTTP_HDR_CONNECTION];
274 if (cur && strstr(blobmsg_data(cur), "close"))
275 uh->connection_close = true;
276
277 cur = tb[HTTP_HDR_CONTENT_LENGTH];
278 if (cur)
279 uh->content_length = strtoul(blobmsg_data(cur), NULL, 10);
280
281 cur = tb[HTTP_HDR_AUTH];
282 if (cur) {
283 free(uh->auth_str);
284 uh->auth_str = strdup(blobmsg_data(cur));
285 }
286
287 uh->auth_type = uclient_http_update_auth_type(uh);
288 }
289
290 static bool uclient_request_supports_body(enum request_type req_type)
291 {
292 switch (req_type) {
293 case REQ_POST:
294 case REQ_PUT:
295 case REQ_DELETE:
296 return true;
297 default:
298 return false;
299 }
300 }
301
302 static int
303 uclient_http_add_auth_basic(struct uclient_http *uh)
304 {
305 struct uclient_url *url = uh->uc.url;
306 int auth_len = strlen(url->auth);
307 char *auth_buf;
308
309 if (auth_len > 512)
310 return -EINVAL;
311
312 auth_buf = alloca(base64_len(auth_len) + 1);
313 if (!auth_buf)
314 return -ENOMEM;
315
316 base64_encode(url->auth, auth_len, auth_buf);
317 ustream_printf(uh->us, "Authorization: Basic %s\r\n", auth_buf);
318
319 return 0;
320 }
321
322 static char *digest_unquote_sep(char **str)
323 {
324 char *cur = *str + 1;
325 char *start = cur;
326 char *out;
327
328 if (**str != '"')
329 return NULL;
330
331 out = cur;
332 while (1) {
333 if (!*cur)
334 return NULL;
335
336 if (*cur == '"') {
337 cur++;
338 break;
339 }
340
341 if (*cur == '\\')
342 cur++;
343
344 *(out++) = *(cur++);
345 }
346
347 if (*cur == ',')
348 cur++;
349
350 *out = 0;
351 *str = cur;
352
353 return start;
354 }
355
356 static char *digest_sep(char **str)
357 {
358 char *cur, *next;
359
360 cur = *str;
361 next = strchr(*str, ',');
362 if (next) {
363 *str = next + 1;
364 *next = 0;
365 } else {
366 *str += strlen(*str);
367 }
368
369 return cur;
370 }
371
372 static bool strmatch(char **str, const char *prefix)
373 {
374 int len = strlen(prefix);
375
376 if (strncmp(*str, prefix, len) != 0 || (*str)[len] != '=')
377 return false;
378
379 *str += len + 1;
380 return true;
381 }
382
383 static void
384 get_cnonce(char *dest)
385 {
386 uint32_t val = 0;
387 FILE *f;
388 size_t n;
389
390 f = fopen("/dev/urandom", "r");
391 if (f) {
392 n = fread(&val, sizeof(val), 1, f);
393 fclose(f);
394 if (n != 1)
395 return;
396 }
397
398 bin_to_hex(dest, &val, sizeof(val));
399 }
400
401 static void add_field(char **buf, int *ofs, int *len, const char *name, const char *val)
402 {
403 int available = *len - *ofs;
404 int required;
405 const char *next;
406 char *cur;
407
408 if (*len && !*buf)
409 return;
410
411 required = strlen(name) + 4 + strlen(val) * 2;
412 if (required > available)
413 *len += required - available + 64;
414
415 *buf = realloc(*buf, *len);
416 if (!*buf)
417 return;
418
419 cur = *buf + *ofs;
420 cur += sprintf(cur, ", %s=\"", name);
421
422 while ((next = strchr(val, '"'))) {
423 if (next > val) {
424 memcpy(cur, val, next - val);
425 cur += next - val;
426 }
427
428 cur += sprintf(cur, "\\\"");
429 val = next + 1;
430 }
431
432 cur += sprintf(cur, "%s\"", val);
433 *ofs = cur - *buf;
434 }
435
436 static void
437 uclient_http_add_auth_digest(struct uclient_http *uh)
438 {
439 struct uclient_url *url = uh->uc.url;
440 const char *realm = NULL, *opaque = NULL;
441 const char *user, *password;
442 char *buf, *next;
443 int len, ofs;
444
445 char cnonce_str[9];
446 char nc_str[9];
447 char ahash[33];
448 char hash[33];
449
450 struct http_digest_data data = {
451 .nc = nc_str,
452 .cnonce = cnonce_str,
453 .auth_hash = ahash,
454 };
455
456 len = strlen(uh->auth_str) + 1;
457 if (len > 512)
458 return;
459
460 buf = alloca(len);
461 strcpy(buf, uh->auth_str);
462
463 /* skip auth type */
464 strsep(&buf, " ");
465
466 next = buf;
467 while (*next) {
468 const char **dest = NULL;
469 const char *tmp;
470
471 while (*next && isspace(*next))
472 next++;
473
474 if (strmatch(&next, "realm"))
475 dest = &realm;
476 else if (strmatch(&next, "qop"))
477 dest = &data.qop;
478 else if (strmatch(&next, "nonce"))
479 dest = &data.nonce;
480 else if (strmatch(&next, "opaque"))
481 dest = &opaque;
482 else if (strmatch(&next, "stale") ||
483 strmatch(&next, "algorithm") ||
484 strmatch(&next, "auth-param")) {
485 digest_sep(&next);
486 continue;
487 } else if (strmatch(&next, "domain") ||
488 strmatch(&next, "qop-options"))
489 dest = &tmp;
490 else {
491 digest_sep(&next);
492 continue;
493 }
494
495 *dest = digest_unquote_sep(&next);
496 }
497
498 if (!realm || !data.qop || !data.nonce)
499 return;
500
501 sprintf(nc_str, "%08x", uh->nc++);
502 get_cnonce(cnonce_str);
503
504 data.qop = "auth";
505 data.uri = url->location;
506 data.method = request_types[uh->req_type];
507
508 password = strchr(url->auth, ':');
509 if (password) {
510 char *user_buf;
511
512 len = password - url->auth;
513 if (len > 256)
514 return;
515
516 user_buf = alloca(len + 1);
517 strncpy(user_buf, url->auth, len);
518 user_buf[len] = 0;
519 user = user_buf;
520 password++;
521 } else {
522 user = url->auth;
523 password = "";
524 }
525
526 http_digest_calculate_auth_hash(ahash, user, realm, password);
527 http_digest_calculate_response(hash, &data);
528
529 buf = NULL;
530 len = 0;
531 ofs = 0;
532
533 add_field(&buf, &ofs, &len, "username", user);
534 add_field(&buf, &ofs, &len, "realm", realm);
535 add_field(&buf, &ofs, &len, "nonce", data.nonce);
536 add_field(&buf, &ofs, &len, "uri", data.uri);
537 add_field(&buf, &ofs, &len, "cnonce", data.cnonce);
538 add_field(&buf, &ofs, &len, "response", hash);
539 if (opaque)
540 add_field(&buf, &ofs, &len, "opaque", opaque);
541
542 ustream_printf(uh->us, "Authorization: Digest nc=%s, qop=%s%s\r\n", data.nc, data.qop, buf);
543 free(buf);
544 }
545
546 static void
547 uclient_http_add_auth_header(struct uclient_http *uh)
548 {
549 if (!uh->uc.url->auth)
550 return;
551
552 switch (uh->auth_type) {
553 case AUTH_TYPE_UNKNOWN:
554 case AUTH_TYPE_NONE:
555 break;
556 case AUTH_TYPE_BASIC:
557 uclient_http_add_auth_basic(uh);
558 break;
559 case AUTH_TYPE_DIGEST:
560 uclient_http_add_auth_digest(uh);
561 break;
562 }
563 }
564
565 static void
566 uclient_http_send_headers(struct uclient_http *uh)
567 {
568 struct uclient_url *url = uh->uc.url;
569 struct blob_attr *cur;
570 enum request_type req_type = uh->req_type;
571 bool literal_ipv6;
572 int rem;
573
574 if (uh->state >= HTTP_STATE_HEADERS_SENT)
575 return;
576
577 if (uh->uc.proxy_url)
578 url = uh->uc.proxy_url;
579
580 literal_ipv6 = strchr(url->host, ':');
581
582 ustream_printf(uh->us,
583 "%s %s HTTP/1.1\r\n"
584 "Host: %s%s%s%s%s\r\n",
585 request_types[req_type], url->location,
586 literal_ipv6 ? "[" : "",
587 url->host,
588 literal_ipv6 ? "]" : "",
589 url->port ? ":" : "",
590 url->port ? url->port : "");
591
592 blobmsg_for_each_attr(cur, uh->headers.head, rem)
593 ustream_printf(uh->us, "%s: %s\r\n", blobmsg_name(cur), (char *) blobmsg_data(cur));
594
595 if (uclient_request_supports_body(uh->req_type))
596 ustream_printf(uh->us, "Transfer-Encoding: chunked\r\n");
597
598 uclient_http_add_auth_header(uh);
599
600 ustream_printf(uh->us, "\r\n");
601
602 uh->state = HTTP_STATE_HEADERS_SENT;
603 }
604
605 static void uclient_http_headers_complete(struct uclient_http *uh)
606 {
607 enum auth_type auth_type = uh->auth_type;
608 int seq = uh->uc.seq;
609
610 uh->state = HTTP_STATE_RECV_DATA;
611 uh->uc.meta = uh->meta.head;
612 uclient_http_process_headers(uh);
613
614 if (auth_type == AUTH_TYPE_UNKNOWN && uh->uc.status_code == 401 &&
615 (uh->req_type == REQ_HEAD || uh->req_type == REQ_GET)) {
616 uclient_http_connect(&uh->uc);
617 uclient_http_send_headers(uh);
618 uh->state = HTTP_STATE_REQUEST_DONE;
619 return;
620 }
621
622 if (uh->uc.cb->header_done)
623 uh->uc.cb->header_done(&uh->uc);
624
625 if (uh->eof || seq != uh->uc.seq)
626 return;
627
628 if (uh->req_type == REQ_HEAD || uh->uc.status_code == 204) {
629 uh->eof = true;
630 uclient_notify_eof(uh);
631 }
632 }
633
634 static void uclient_parse_http_line(struct uclient_http *uh, char *data)
635 {
636 char *name;
637 char *sep;
638
639 if (uh->state == HTTP_STATE_REQUEST_DONE) {
640 char *code;
641
642 if (!strlen(data))
643 return;
644
645 /* HTTP/1.1 */
646 strsep(&data, " ");
647
648 code = strsep(&data, " ");
649 if (!code)
650 goto error;
651
652 uh->uc.status_code = strtoul(code, &sep, 10);
653 if (sep && *sep)
654 goto error;
655
656 uh->state = HTTP_STATE_RECV_HEADERS;
657 return;
658 }
659
660 if (!*data) {
661 uclient_http_headers_complete(uh);
662 return;
663 }
664
665 sep = strchr(data, ':');
666 if (!sep)
667 return;
668
669 *(sep++) = 0;
670
671 for (name = data; *name; name++)
672 *name = tolower(*name);
673
674 name = data;
675 while (isspace(*sep))
676 sep++;
677
678 blobmsg_add_string(&uh->meta, name, sep);
679 return;
680
681 error:
682 uh->uc.status_code = 400;
683 uh->eof = true;
684 uclient_notify_eof(uh);
685 }
686
687 static void __uclient_notify_read(struct uclient_http *uh)
688 {
689 struct uclient *uc = &uh->uc;
690 unsigned int seq = uh->seq;
691 char *data;
692 int len;
693
694 if (uh->state < HTTP_STATE_REQUEST_DONE || uh->state == HTTP_STATE_ERROR)
695 return;
696
697 data = ustream_get_read_buf(uh->us, &len);
698 if (!data || !len)
699 return;
700
701 if (uh->state < HTTP_STATE_RECV_DATA) {
702 char *sep, *next;
703 int cur_len;
704
705 do {
706 sep = strchr(data, '\n');
707 if (!sep)
708 break;
709
710 next = sep + 1;
711 if (sep > data && sep[-1] == '\r')
712 sep--;
713
714 /* Check for multi-line HTTP headers */
715 if (sep > data) {
716 if (!*next)
717 return;
718
719 if (isspace(*next) && *next != '\r' && *next != '\n') {
720 sep[0] = ' ';
721 if (sep + 1 < next)
722 sep[1] = ' ';
723 continue;
724 }
725 }
726
727 *sep = 0;
728 cur_len = next - data;
729 uclient_parse_http_line(uh, data);
730 if (seq != uh->seq)
731 return;
732
733 ustream_consume(uh->us, cur_len);
734 len -= cur_len;
735
736 if (uh->eof)
737 return;
738
739 data = ustream_get_read_buf(uh->us, &len);
740 } while (data && uh->state < HTTP_STATE_RECV_DATA);
741
742 if (!len)
743 return;
744 }
745
746 if (uh->eof)
747 return;
748
749 if (uh->state == HTTP_STATE_RECV_DATA) {
750 /* Now it's uclient user turn to read some data */
751 uloop_timeout_cancel(&uc->connection_timeout);
752
753 if (uc->cb->data_read)
754 uc->cb->data_read(uc);
755 }
756 }
757
758 static void __uclient_notify_write(struct uclient_http *uh)
759 {
760 struct uclient *uc = &uh->uc;
761
762 if (uc->cb->data_sent)
763 uc->cb->data_sent(uc);
764 }
765
766 static void uclient_notify_read(struct ustream *us, int bytes)
767 {
768 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
769
770 __uclient_notify_read(uh);
771 }
772
773 static void uclient_notify_write(struct ustream *us, int bytes)
774 {
775 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
776
777 __uclient_notify_write(uh);
778 }
779
780 static void uclient_notify_state(struct ustream *us)
781 {
782 struct uclient_http *uh = container_of(us, struct uclient_http, ufd.stream);
783
784 if (uh->ufd.stream.write_error) {
785 uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
786 return;
787 }
788 uclient_notify_eof(uh);
789 }
790
791 static int uclient_setup_http(struct uclient_http *uh)
792 {
793 struct ustream *us = &uh->ufd.stream;
794 int ret;
795
796 uh->us = us;
797 uh->ssl = false;
798
799 us->string_data = true;
800 us->notify_state = uclient_notify_state;
801 us->notify_read = uclient_notify_read;
802 us->notify_write = uclient_notify_write;
803
804 ret = uclient_do_connect(uh, "80");
805 if (ret)
806 return UCLIENT_ERROR_CONNECT;
807
808 return 0;
809 }
810
811 static void uclient_ssl_notify_read(struct ustream *us, int bytes)
812 {
813 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
814
815 __uclient_notify_read(uh);
816 }
817
818 static void uclient_ssl_notify_write(struct ustream *us, int bytes)
819 {
820 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
821
822 __uclient_notify_write(uh);
823 }
824
825 static void uclient_ssl_notify_state(struct ustream *us)
826 {
827 struct uclient_http *uh = container_of(us, struct uclient_http, ussl.stream);
828
829 uclient_notify_eof(uh);
830 }
831
832 static void uclient_ssl_notify_error(struct ustream_ssl *ssl, int error, const char *str)
833 {
834 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
835
836 uclient_http_error(uh, UCLIENT_ERROR_CONNECT);
837 }
838
839 static void uclient_ssl_notify_verify_error(struct ustream_ssl *ssl, int error, const char *str)
840 {
841 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
842
843 if (!uh->ssl_require_validation)
844 return;
845
846 uclient_http_error(uh, UCLIENT_ERROR_SSL_INVALID_CERT);
847 }
848
849 static void uclient_ssl_notify_connected(struct ustream_ssl *ssl)
850 {
851 struct uclient_http *uh = container_of(ssl, struct uclient_http, ussl);
852
853 if (!uh->ssl_require_validation)
854 return;
855
856 if (!uh->ussl.valid_cn)
857 uclient_http_error(uh, UCLIENT_ERROR_SSL_CN_MISMATCH);
858 }
859
860 static int uclient_setup_https(struct uclient_http *uh)
861 {
862 struct ustream *us = &uh->ussl.stream;
863 int ret;
864
865 uh->ssl = true;
866 uh->us = us;
867
868 if (!uh->ssl_ctx)
869 return UCLIENT_ERROR_MISSING_SSL_CONTEXT;
870
871 ret = uclient_do_connect(uh, "443");
872 if (ret)
873 return UCLIENT_ERROR_CONNECT;
874
875 us->string_data = true;
876 us->notify_state = uclient_ssl_notify_state;
877 us->notify_read = uclient_ssl_notify_read;
878 us->notify_write = uclient_ssl_notify_write;
879 uh->ussl.notify_error = uclient_ssl_notify_error;
880 uh->ussl.notify_verify_error = uclient_ssl_notify_verify_error;
881 uh->ussl.notify_connected = uclient_ssl_notify_connected;
882 uh->ussl.server_name = uh->uc.url->host;
883 uh->ssl_ops->init(&uh->ussl, &uh->ufd.stream, uh->ssl_ctx, false);
884 uh->ssl_ops->set_peer_cn(&uh->ussl, uh->uc.url->host);
885
886 return 0;
887 }
888
889 static int uclient_http_connect(struct uclient *cl)
890 {
891 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
892 int ret;
893
894 if (!cl->eof || uh->disconnect || uh->connection_close)
895 uclient_http_disconnect(uh);
896
897 uclient_http_init_request(uh);
898
899 if (uh->us)
900 return 0;
901
902 uh->ssl = cl->url->prefix == PREFIX_HTTPS;
903
904 if (uh->ssl)
905 ret = uclient_setup_https(uh);
906 else
907 ret = uclient_setup_http(uh);
908
909 return ret;
910 }
911
912 static void uclient_http_disconnect_cb(struct uloop_timeout *timeout)
913 {
914 struct uclient_http *uh = container_of(timeout, struct uclient_http, disconnect_t);
915
916 uclient_http_disconnect(uh);
917 }
918
919 static struct uclient *uclient_http_alloc(void)
920 {
921 struct uclient_http *uh;
922
923 uh = calloc_a(sizeof(*uh));
924 uh->disconnect_t.cb = uclient_http_disconnect_cb;
925 blob_buf_init(&uh->headers, 0);
926
927 return &uh->uc;
928 }
929
930 static void uclient_http_free_ssl_ctx(struct uclient_http *uh)
931 {
932 uh->ssl_ops = NULL;
933 uh->ssl_ctx = NULL;
934 }
935
936 static void uclient_http_free(struct uclient *cl)
937 {
938 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
939
940 uclient_http_free_url_state(cl);
941 uclient_http_free_ssl_ctx(uh);
942 blob_buf_free(&uh->headers);
943 blob_buf_free(&uh->meta);
944 free(uh);
945 }
946
947 int
948 uclient_http_set_request_type(struct uclient *cl, const char *type)
949 {
950 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
951 int i;
952
953 if (cl->backend != &uclient_backend_http)
954 return -1;
955
956 if (uh->state > HTTP_STATE_INIT)
957 return -1;
958
959 for (i = 0; i < ARRAY_SIZE(request_types); i++) {
960 if (strcmp(request_types[i], type) != 0)
961 continue;
962
963 uh->req_type = i;
964 return 0;
965 }
966
967 return -1;
968 }
969
970 int
971 uclient_http_reset_headers(struct uclient *cl)
972 {
973 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
974
975 blob_buf_init(&uh->headers, 0);
976
977 return 0;
978 }
979
980 int
981 uclient_http_set_header(struct uclient *cl, const char *name, const char *value)
982 {
983 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
984
985 if (cl->backend != &uclient_backend_http)
986 return -1;
987
988 if (uh->state > HTTP_STATE_INIT)
989 return -1;
990
991 blobmsg_add_string(&uh->headers, name, value);
992 return 0;
993 }
994
995 static int
996 uclient_http_send_data(struct uclient *cl, const char *buf, unsigned int len)
997 {
998 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
999
1000 if (uh->state >= HTTP_STATE_REQUEST_DONE)
1001 return -1;
1002
1003 uclient_http_send_headers(uh);
1004
1005 if (len > 0) {
1006 ustream_printf(uh->us, "%X\r\n", len);
1007 ustream_write(uh->us, buf, len, false);
1008 ustream_printf(uh->us, "\r\n");
1009 }
1010
1011 return len;
1012 }
1013
1014 static int
1015 uclient_http_request_done(struct uclient *cl)
1016 {
1017 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1018
1019 if (uh->state >= HTTP_STATE_REQUEST_DONE)
1020 return -1;
1021
1022 uclient_http_send_headers(uh);
1023 if (uclient_request_supports_body(uh->req_type))
1024 ustream_printf(uh->us, "0\r\n\r\n");
1025 uh->state = HTTP_STATE_REQUEST_DONE;
1026
1027 return 0;
1028 }
1029
1030 static int
1031 uclient_http_read(struct uclient *cl, char *buf, unsigned int len)
1032 {
1033 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1034 int read_len = 0;
1035 char *data, *data_end;
1036
1037 if (uh->state < HTTP_STATE_RECV_DATA || !uh->us)
1038 return 0;
1039
1040 data = ustream_get_read_buf(uh->us, &read_len);
1041 if (!data || !read_len)
1042 return 0;
1043
1044 data_end = data + read_len;
1045 read_len = 0;
1046
1047 if (uh->read_chunked == 0) {
1048 char *sep;
1049
1050 if (data[0] == '\r' && data[1] == '\n') {
1051 data += 2;
1052 read_len += 2;
1053 }
1054
1055 sep = strstr(data, "\r\n");
1056 if (!sep)
1057 return 0;
1058
1059 *sep = 0;
1060 uh->read_chunked = strtoul(data, NULL, 16);
1061
1062 read_len += sep + 2 - data;
1063 data = sep + 2;
1064
1065 if (!uh->read_chunked) {
1066 uh->eof = true;
1067 uh->uc.data_eof = true;
1068 }
1069 }
1070
1071 if (len > data_end - data)
1072 len = data_end - data;
1073
1074 if (uh->read_chunked >= 0) {
1075 if (len > uh->read_chunked)
1076 len = uh->read_chunked;
1077
1078 uh->read_chunked -= len;
1079 } else if (uh->content_length >= 0) {
1080 if (len > uh->content_length)
1081 len = uh->content_length;
1082
1083 uh->content_length -= len;
1084 if (!uh->content_length) {
1085 uh->eof = true;
1086 uh->uc.data_eof = true;
1087 }
1088 }
1089
1090 if (len > 0) {
1091 read_len += len;
1092 memcpy(buf, data, len);
1093 }
1094
1095 if (read_len > 0)
1096 ustream_consume(uh->us, read_len);
1097
1098 uclient_notify_eof(uh);
1099
1100 /* Now that we consumed something and if this isn't EOF, start timer again */
1101 if (!uh->uc.eof && !cl->connection_timeout.pending)
1102 uloop_timeout_set(&cl->connection_timeout, cl->timeout_msecs);
1103
1104 return len;
1105 }
1106
1107 int uclient_http_redirect(struct uclient *cl)
1108 {
1109 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1110 struct blobmsg_policy location = {
1111 .name = "location",
1112 .type = BLOBMSG_TYPE_STRING,
1113 };
1114 struct uclient_url *url = cl->url;
1115 struct blob_attr *tb;
1116
1117 if (cl->backend != &uclient_backend_http)
1118 return false;
1119
1120 switch (cl->status_code) {
1121 case 301:
1122 case 302:
1123 case 307:
1124 break;
1125 default:
1126 return false;
1127 }
1128
1129 blobmsg_parse(&location, 1, &tb, blob_data(uh->meta.head), blob_len(uh->meta.head));
1130 if (!tb)
1131 return false;
1132
1133 url = uclient_get_url_location(url, blobmsg_data(tb));
1134 if (!url)
1135 return false;
1136
1137 free(cl->url);
1138 cl->url = url;
1139 if (uclient_http_connect(cl))
1140 return -1;
1141
1142 uclient_http_request_done(cl);
1143
1144 return true;
1145 }
1146
1147 int uclient_http_set_ssl_ctx(struct uclient *cl, const struct ustream_ssl_ops *ops,
1148 struct ustream_ssl_ctx *ctx, bool require_validation)
1149 {
1150 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1151
1152 if (cl->backend != &uclient_backend_http)
1153 return -1;
1154
1155 uclient_http_free_url_state(cl);
1156
1157 uclient_http_free_ssl_ctx(uh);
1158 uh->ssl_ops = ops;
1159 uh->ssl_ctx = ctx;
1160 uh->ssl_require_validation = !!ctx && require_validation;
1161
1162 return 0;
1163 }
1164
1165 int uclient_http_set_address_family(struct uclient *cl, int af)
1166 {
1167 struct uclient_http *uh = container_of(cl, struct uclient_http, uc);
1168
1169 if (cl->backend != &uclient_backend_http)
1170 return -1;
1171
1172 switch (af) {
1173 case AF_INET:
1174 uh->usock_flags = USOCK_IPV4ONLY;
1175 break;
1176 case AF_INET6:
1177 uh->usock_flags = USOCK_IPV6ONLY;
1178 break;
1179 default:
1180 uh->usock_flags = 0;
1181 break;
1182 }
1183
1184 return 0;
1185 }
1186
1187 const struct uclient_backend uclient_backend_http = {
1188 .prefix = uclient_http_prefix,
1189
1190 .alloc = uclient_http_alloc,
1191 .free = uclient_http_free,
1192 .connect = uclient_http_connect,
1193 .disconnect = uclient_http_request_disconnect,
1194 .update_url = uclient_http_free_url_state,
1195 .update_proxy_url = uclient_http_free_url_state,
1196
1197 .read = uclient_http_read,
1198 .write = uclient_http_send_data,
1199 .request = uclient_http_request_done,
1200 };