1 // SPDX-License-Identifier: GPL-2.0+
2 /* Copyright (C) 2024 Linaro Ltd. */
3 
4 #include <command.h>
5 #include <console.h>
6 #include <display_options.h>
7 #include <efi_loader.h>
8 #include <env.h>
9 #include <linux/kconfig.h>
10 #include <lwip/apps/http_client.h>
11 #include "lwip/altcp_tls.h"
12 #include <lwip/errno.h>
13 #include <lwip/timeouts.h>
14 #include <rng.h>
15 #include <mapmem.h>
16 #include <net.h>
17 #include <time.h>
18 #include <dm/uclass.h>
19 
20 #define SERVER_NAME_SIZE 254
21 #define HTTP_PORT_DEFAULT 80
22 #define HTTPS_PORT_DEFAULT 443
23 #define PROGRESS_PRINT_STEP_BYTES (100 * 1024)
24 
25 enum done_state {
26 	NOT_DONE = 0,
27 	SUCCESS = 1,
28 	FAILURE = 2
29 };
30 
31 struct wget_ctx {
32 	char server_name[SERVER_NAME_SIZE];
33 	u16 port;
34 	char *path;
35 	ulong daddr;
36 	ulong saved_daddr;
37 	ulong size;
38 	ulong prevsize;
39 	ulong start_time;
40 	enum done_state done;
41 };
42 
wget_lwip_fill_info(struct pbuf * hdr,u16_t hdr_len,u32_t hdr_cont_len)43 static void wget_lwip_fill_info(struct pbuf *hdr, u16_t hdr_len, u32_t hdr_cont_len)
44 {
45 	if (wget_info->headers) {
46 		if (hdr_len < MAX_HTTP_HEADERS_SIZE)
47 			pbuf_copy_partial(hdr, (void *)wget_info->headers, hdr_len, 0);
48 		else
49 			hdr_len = 0;
50 		wget_info->headers[hdr_len] = 0;
51 	}
52 	wget_info->hdr_cont_len = (u32)hdr_cont_len;
53 }
54 
wget_lwip_set_file_size(u32_t rx_content_len)55 static void wget_lwip_set_file_size(u32_t rx_content_len)
56 {
57 	wget_info->file_size = (ulong)rx_content_len;
58 }
59 
60 bool wget_validate_uri(char *uri);
61 
mbedtls_hardware_poll(void * data,unsigned char * output,size_t len,size_t * olen)62 int mbedtls_hardware_poll(void *data, unsigned char *output, size_t len,
63 			  size_t *olen)
64 {
65 	struct udevice *dev;
66 	int ret;
67 
68 	*olen = 0;
69 
70 	ret = uclass_get_device(UCLASS_RNG, 0, &dev);
71 	if (ret) {
72 		log_err("Failed to get an rng: %d\n", ret);
73 		return ret;
74 	}
75 	ret = dm_rng_read(dev, output, len);
76 	if (ret)
77 		return ret;
78 
79 	*olen = len;
80 
81 	return 0;
82 }
83 
parse_url(char * url,char * host,u16 * port,char ** path,bool * is_https)84 static int parse_url(char *url, char *host, u16 *port, char **path,
85 		     bool *is_https)
86 {
87 	char *p, *pp;
88 	long lport;
89 	size_t prefix_len = 0;
90 
91 	if (!wget_validate_uri(url)) {
92 		log_err("Invalid URL. Use http(s)://\n");
93 		return -EINVAL;
94 	}
95 
96 	*is_https = false;
97 	*port = HTTP_PORT_DEFAULT;
98 	prefix_len = strlen("http://");
99 	p = strstr(url, "http://");
100 	if (!p) {
101 		p = strstr(url, "https://");
102 		prefix_len = strlen("https://");
103 		*port = HTTPS_PORT_DEFAULT;
104 		*is_https = true;
105 	}
106 
107 	p += prefix_len;
108 
109 	/* Parse hostname */
110 	pp = strchr(p, ':');
111 	if (!pp)
112 		pp = strchr(p, '/');
113 	if (!pp)
114 		return -EINVAL;
115 
116 	if (p + SERVER_NAME_SIZE <= pp)
117 		return -EINVAL;
118 
119 	memcpy(host, p, pp - p);
120 	host[pp - p] = '\0';
121 
122 	if (*pp == ':') {
123 		/* Parse port number */
124 		p = pp + 1;
125 		lport = simple_strtol(p, &pp, 10);
126 		if (pp && *pp != '/')
127 			return -EINVAL;
128 		if (lport > 65535)
129 			return -EINVAL;
130 		*port = (u16)lport;
131 	}
132 
133 	if (*pp != '/')
134 		return -EINVAL;
135 	*path = pp;
136 
137 	return 0;
138 }
139 
140 /**
141  * store_block() - copy received data
142  *
143  * This function is called by the receive callback to copy a block of data
144  * into its final location (ctx->daddr). Before doing so, it checks if the copy
145  * is allowed.
146  *
147  * @ctx: the context for the current transfer
148  * @src: the data received from the TCP stack
149  * @len: the length of the data
150  */
store_block(struct wget_ctx * ctx,void * src,u16_t len)151 static int store_block(struct wget_ctx *ctx, void *src, u16_t len)
152 {
153 	ulong store_addr = ctx->daddr;
154 	uchar *ptr;
155 
156 	/* Avoid overflow */
157 	if (wget_info->buffer_size && wget_info->buffer_size < ctx->size + len)
158 		return -1;
159 
160 	if (CONFIG_IS_ENABLED(LMB) && wget_info->set_bootdev) {
161 		if (store_addr + len < store_addr ||
162 		    lmb_read_check(store_addr, len)) {
163 			if (!wget_info->silent) {
164 				printf("\nwget error: ");
165 				printf("trying to overwrite reserved memory\n");
166 			}
167 			return -1;
168 		}
169 	}
170 
171 	ptr = map_sysmem(store_addr, len);
172 	memcpy(ptr, src, len);
173 	unmap_sysmem(ptr);
174 
175 	ctx->daddr += len;
176 	ctx->size += len;
177 	if (ctx->size - ctx->prevsize > PROGRESS_PRINT_STEP_BYTES) {
178 		if (!wget_info->silent)
179 			printf("#");
180 		ctx->prevsize = ctx->size;
181 	}
182 
183 	return 0;
184 }
185 
httpc_recv_cb(void * arg,struct altcp_pcb * pcb,struct pbuf * pbuf,err_t err)186 static err_t httpc_recv_cb(void *arg, struct altcp_pcb *pcb, struct pbuf *pbuf,
187 			   err_t err)
188 {
189 	struct wget_ctx *ctx = arg;
190 	struct pbuf *buf;
191 	err_t ret;
192 
193 	if (!pbuf)
194 		return ERR_BUF;
195 
196 	if (!ctx->start_time)
197 		ctx->start_time = get_timer(0);
198 
199 	for (buf = pbuf; buf; buf = buf->next) {
200 		if (store_block(ctx, buf->payload, buf->len) < 0) {
201 			altcp_abort(pcb);
202 			ret = ERR_BUF;
203 			goto out;
204 		}
205 	}
206 	altcp_recved(pcb, pbuf->tot_len);
207 	ret = ERR_OK;
208 out:
209 	pbuf_free(pbuf);
210 	return ret;
211 }
212 
httpc_result_cb(void * arg,httpc_result_t httpc_result,u32_t rx_content_len,u32_t srv_res,err_t err)213 static void httpc_result_cb(void *arg, httpc_result_t httpc_result,
214 			    u32_t rx_content_len, u32_t srv_res, err_t err)
215 {
216 	struct wget_ctx *ctx = arg;
217 	ulong elapsed;
218 
219 	wget_info->status_code = (u32)srv_res;
220 
221 	if (err == ERR_BUF) {
222 		ctx->done = FAILURE;
223 		return;
224 	}
225 
226 	if (httpc_result != HTTPC_RESULT_OK) {
227 		log_err("\nHTTP client error %d\n", httpc_result);
228 		ctx->done = FAILURE;
229 		return;
230 	}
231 	if (srv_res != 200) {
232 		log_err("\nHTTP server error %d\n", srv_res);
233 		ctx->done = FAILURE;
234 		return;
235 	}
236 
237 	elapsed = get_timer(ctx->start_time);
238 	if (!elapsed)
239 		elapsed = 1;
240 	if (!wget_info->silent) {
241 		if (rx_content_len > PROGRESS_PRINT_STEP_BYTES)
242 			printf("\n");
243 		printf("%u bytes transferred in %lu ms (", rx_content_len,
244 		       elapsed);
245 		print_size(rx_content_len / elapsed * 1000, "/s)\n");
246 		printf("Bytes transferred = %lu (%lx hex)\n", ctx->size,
247 		       ctx->size);
248 	}
249 	if (wget_info->set_bootdev)
250 		efi_set_bootdev("Http", ctx->server_name, ctx->path, map_sysmem(ctx->saved_daddr, 0),
251 				rx_content_len);
252 	wget_lwip_set_file_size(rx_content_len);
253 	if (env_set_hex("filesize", rx_content_len) ||
254 	    env_set_hex("fileaddr", ctx->saved_daddr)) {
255 		log_err("Could not set filesize or fileaddr\n");
256 		ctx->done = FAILURE;
257 		return;
258 	}
259 
260 	ctx->done = SUCCESS;
261 }
262 
httpc_headers_done_cb(httpc_state_t * connection,void * arg,struct pbuf * hdr,u16_t hdr_len,u32_t content_len)263 static err_t httpc_headers_done_cb(httpc_state_t *connection, void *arg, struct pbuf *hdr,
264 				   u16_t hdr_len, u32_t content_len)
265 {
266 	wget_lwip_fill_info(hdr, hdr_len, content_len);
267 
268 	if (wget_info->check_buffer_size && (ulong)content_len > wget_info->buffer_size)
269 		return ERR_BUF;
270 
271 	return ERR_OK;
272 }
273 
274 
275 #if CONFIG_IS_ENABLED(WGET_CACERT)
276 #endif
277 
wget_do_request(ulong dst_addr,char * uri)278 int wget_do_request(ulong dst_addr, char *uri)
279 {
280 #if CONFIG_IS_ENABLED(WGET_HTTPS)
281 	altcp_allocator_t tls_allocator;
282 #endif
283 	httpc_connection_t conn;
284 	httpc_state_t *state;
285 	struct udevice *udev;
286 	struct netif *netif;
287 	struct wget_ctx ctx;
288 	char *path;
289 	bool is_https;
290 
291 	ctx.daddr = dst_addr;
292 	ctx.saved_daddr = dst_addr;
293 	ctx.done = NOT_DONE;
294 	ctx.size = 0;
295 	ctx.prevsize = 0;
296 	ctx.start_time = 0;
297 
298 	if (parse_url(uri, ctx.server_name, &ctx.port, &path, &is_https))
299 		return CMD_RET_USAGE;
300 
301 	if (net_lwip_eth_start() < 0)
302 		return CMD_RET_FAILURE;
303 
304 	if (!wget_info)
305 		wget_info = &default_wget_info;
306 
307 	udev = eth_get_dev();
308 
309 	netif = net_lwip_new_netif(udev);
310 	if (!netif)
311 		return -1;
312 
313 	/* if URL with hostname init dns */
314 	if (!ipaddr_aton(ctx.server_name, NULL) && net_lwip_dns_init())
315 		return CMD_RET_FAILURE;
316 
317 	memset(&conn, 0, sizeof(conn));
318 #if CONFIG_IS_ENABLED(WGET_HTTPS)
319 	if (is_https) {
320 		char *ca;
321 		size_t ca_sz;
322 
323 #if CONFIG_IS_ENABLED(WGET_CACERT) || CONFIG_IS_ENABLED(WGET_BUILTIN_CACERT)
324 #if CONFIG_IS_ENABLED(WGET_BUILTIN_CACERT)
325 		if (!cacert_initialized)
326 			set_cacert_builtin();
327 #endif
328 		ca = cacert;
329 		ca_sz = cacert_size;
330 
331 		if (cacert_auth_mode == AUTH_REQUIRED) {
332 			if (!ca || !ca_sz) {
333 				if (!wget_info->silent)
334 					printf("Error: cacert authentication "
335 					       "mode is 'required' but no CA "
336 					       "certificates given\n");
337 				return CMD_RET_FAILURE;
338 		       }
339 		} else if (cacert_auth_mode == AUTH_NONE) {
340 			ca = NULL;
341 			ca_sz = 0;
342 		} else if (cacert_auth_mode == AUTH_OPTIONAL) {
343 			/*
344 			 * Nothing to do, this is the default behavior of
345 			 * altcp_tls to check server certificates against CA
346 			 * certificates when the latter are provided and proceed
347 			 * with no verification if not.
348 			 */
349 		}
350 #endif
351 		if (!ca && !wget_info->silent) {
352 			printf("WARNING: no CA certificates, ");
353 			printf("HTTPS connections not authenticated\n");
354 		}
355 		tls_allocator.alloc = &altcp_tls_alloc;
356 		tls_allocator.arg =
357 			altcp_tls_create_config_client(ca, ca_sz,
358 						       ctx.server_name);
359 
360 		if (!tls_allocator.arg) {
361 			log_err("error: Cannot create a TLS connection\n");
362 			net_lwip_remove_netif(netif);
363 			return -1;
364 		}
365 
366 		conn.altcp_allocator = &tls_allocator;
367 	}
368 #endif
369 
370 	conn.result_fn = httpc_result_cb;
371 	conn.headers_done_fn = httpc_headers_done_cb;
372 	ctx.path = path;
373 	if (httpc_get_file_dns(ctx.server_name, ctx.port, path, &conn, httpc_recv_cb,
374 			       &ctx, &state)) {
375 		net_lwip_remove_netif(netif);
376 		return CMD_RET_FAILURE;
377 	}
378 
379 	errno = 0;
380 
381 	while (!ctx.done) {
382 		net_lwip_rx(udev, netif);
383 		if (ctrlc())
384 			break;
385 	}
386 
387 	net_lwip_remove_netif(netif);
388 
389 	if (ctx.done == SUCCESS)
390 		return 0;
391 
392 	if (errno == EPERM && !wget_info->silent)
393 		printf("Certificate verification failed\n");
394 
395 	return -1;
396 }
397 
398 /**
399  * wget_validate_uri() - validate the uri for wget
400  *
401  * @uri:	uri string
402  *
403  * This function follows the current U-Boot wget implementation.
404  * scheme: only "http:" is supported
405  * authority:
406  *   - user information: not supported
407  *   - host: supported
408  *   - port: not supported(always use the default port)
409  *
410  * Uri is expected to be correctly percent encoded.
411  * This is the minimum check, control codes(0x1-0x19, 0x7F, except '\0')
412  * and space character(0x20) are not allowed.
413  *
414  * TODO: stricter uri conformance check
415  *
416  * Return:	true on success, false on failure
417  */
wget_validate_uri(char * uri)418 bool wget_validate_uri(char *uri)
419 {
420 	char c;
421 	bool ret = true;
422 	char *str_copy, *s, *authority;
423 	size_t prefix_len = 0;
424 
425 	for (c = 0x1; c < 0x21; c++) {
426 		if (strchr(uri, c)) {
427 			log_err("invalid character is used\n");
428 			return false;
429 		}
430 	}
431 
432 	if (strchr(uri, 0x7f)) {
433 		log_err("invalid character is used\n");
434 		return false;
435 	}
436 
437 	if (!strncmp(uri, "http://", strlen("http://"))) {
438 		prefix_len = strlen("http://");
439 	} else if (CONFIG_IS_ENABLED(WGET_HTTPS)) {
440 		if (!strncmp(uri, "https://", strlen("https://"))) {
441 			prefix_len = strlen("https://");
442 		} else {
443 			log_err("only http(s):// is supported\n");
444 			return false;
445 		}
446 	} else {
447 		log_err("only http:// is supported\n");
448 		return false;
449 	}
450 
451 	str_copy = strdup(uri);
452 	if (!str_copy)
453 		return false;
454 
455 	s = str_copy + strlen("http://");
456 	authority = strsep(&s, "/");
457 	if (!s) {
458 		log_err("invalid uri, no file path\n");
459 		ret = false;
460 		goto out;
461 	}
462 	s = strchr(authority, '@');
463 	if (s) {
464 		log_err("user information is not supported\n");
465 		ret = false;
466 		goto out;
467 	}
468 
469 out:
470 	free(str_copy);
471 
472 	return ret;
473 }
474