1 #include <libubox/ustream-ssl.h>
3 #include "uclient-utils.h"
4 #include "uclient-backend.h"
6 static struct uclient_url *uclient_get_url(const char *url_str)
8 static const struct uclient_backend *backends[] = {
12 const struct uclient_backend *backend;
13 const char * const *prefix = NULL;
14 struct uclient_url *url;
16 char *host_buf, *uri_buf, *next;
19 for (i = 0; i < ARRAY_SIZE(backends); i++) {
22 for (prefix = backends[i]->prefix; *prefix; prefix++) {
23 prefix_len = strlen(*prefix);
25 if (!strncmp(url_str, *prefix, prefix_len))
32 url_str += prefix_len;
33 backend = backends[i];
40 next = strchr(url_str, '/');
43 host_len = next - url_str;
46 host_len = strlen(url_str);
49 url = calloc_a(sizeof(*url),
50 &host_buf, host_len + 1,
51 &uri_buf, strlen(location) + 1);
53 url->backend = backend;
54 url->location = strcpy(uri_buf, location);
56 url->host = strncpy(host_buf, url_str, host_len);
58 next = strchr(host_buf, '@');
63 if (uclient_urldecode(host_buf, host_buf, false) < 0)
69 /* Literal IPv6 address */
70 if (*url->host == '[') {
72 next = strrchr(url->host, ']');
80 next = strrchr(url->host, ':');
92 struct uclient *uclient_new(const char *url_str, const struct uclient_cb *cb)
95 struct uclient_url *url;
97 url = uclient_get_url(url_str);
101 cl = url->backend->alloc();
105 cl->backend = url->backend;
112 int uclient_connect_url(struct uclient *cl, const char *url_str)
114 struct uclient_url *url = cl->url;
115 const struct uclient_backend *backend = cl->backend;
118 url = uclient_get_url(url_str);
122 if (url->backend != cl->backend)
128 if (backend->update_url)
129 backend->update_url(cl);
132 return backend->connect(cl);
135 void uclient_free(struct uclient *cl)
137 struct uclient_url *url = cl->url;
139 if (cl->backend->free)
140 cl->backend->free(cl);
147 int uclient_write(struct uclient *cl, char *buf, int len)
149 if (!cl->backend->write)
152 return cl->backend->write(cl, buf, len);
155 int uclient_request(struct uclient *cl)
157 if (!cl->backend->request)
160 return cl->backend->request(cl);
163 int uclient_read(struct uclient *cl, char *buf, int len)
165 if (!cl->backend->read)
168 return cl->backend->read(cl, buf, len);
171 static void __uclient_backend_change_state(struct uloop_timeout *timeout)
173 struct uclient *cl = container_of(timeout, struct uclient, timeout);
175 if (cl->error && cl->cb->error)
177 else if (cl->eof && cl->cb->data_eof)
178 cl->cb->data_eof(cl);
181 static void uclient_backend_change_state(struct uclient *cl)
183 cl->timeout.cb = __uclient_backend_change_state;
184 uloop_timeout_set(&cl->timeout, 1);
187 void uclient_backend_set_error(struct uclient *cl)
193 uclient_backend_change_state(cl);
196 void __hidden uclient_backend_set_eof(struct uclient *cl)
198 if (cl->eof || cl->error)
202 uclient_backend_change_state(cl);
205 void __hidden uclient_backend_reset_state(struct uclient *cl)
209 uloop_timeout_cancel(&cl->timeout);