blob: 4b937feaee1e1e5ae3313f69bc970a27a342a523 [file] [log] [blame]
Jerome Forissieraedcfec2024-10-16 12:04:07 +02001// SPDX-License-Identifier: GPL-2.0+
2/* Copyright (C) 2024 Linaro Ltd. */
3
4#include <command.h>
5#include <console.h>
6#include <lwip/dns.h>
7#include <lwip/timeouts.h>
8#include <net.h>
9#include <time.h>
10
11#define DNS_RESEND_MS 1000
12#define DNS_TIMEOUT_MS 10000
13
14struct dns_cb_arg {
15 ip_addr_t host_ipaddr;
16 const char *var;
17 bool done;
18};
19
20static void do_dns_tmr(void *arg)
21{
22 dns_tmr();
23}
24
25static void dns_cb(const char *name, const ip_addr_t *ipaddr, void *arg)
26{
27 struct dns_cb_arg *dns_cb_arg = arg;
28 char *ipstr = ip4addr_ntoa(ipaddr);
29
30 dns_cb_arg->done = true;
31
32 if (!ipaddr) {
33 printf("DNS: host not found\n");
34 dns_cb_arg->host_ipaddr.addr = 0;
35 return;
36 }
37
38 if (dns_cb_arg->var)
39 env_set(dns_cb_arg->var, ipstr);
40
41 printf("%s\n", ipstr);
42}
43
44static int dns_loop(struct udevice *udev, const char *name, const char *var)
45{
46 struct dns_cb_arg dns_cb_arg = { };
47 bool has_server = false;
48 struct netif *netif;
49 ip_addr_t ipaddr;
50 ip_addr_t ns;
51 ulong start;
52 char *nsenv;
53 int ret;
54
55 dns_cb_arg.var = var;
56
57 netif = net_lwip_new_netif(udev);
58 if (!netif)
59 return -1;
60
61 dns_init();
62
63 nsenv = env_get("dnsip");
64 if (nsenv && ipaddr_aton(nsenv, &ns)) {
65 dns_setserver(0, &ns);
66 has_server = true;
67 }
68
69 nsenv = env_get("dnsip2");
70 if (nsenv && ipaddr_aton(nsenv, &ns)) {
71 dns_setserver(1, &ns);
72 has_server = true;
73 }
74
75 if (!has_server) {
76 log_err("No valid name server (dnsip/dnsip2)\n");
77 net_lwip_remove_netif(netif);
78 return CMD_RET_FAILURE;
79 }
80
81 dns_cb_arg.done = false;
82
83 ret = dns_gethostbyname(name, &ipaddr, dns_cb, &dns_cb_arg);
84
85 if (ret == ERR_OK) {
86 dns_cb(name, &ipaddr, &dns_cb_arg);
87 } else if (ret == ERR_INPROGRESS) {
88 start = get_timer(0);
89 sys_timeout(DNS_RESEND_MS, do_dns_tmr, NULL);
90 do {
91 net_lwip_rx(udev, netif);
92 if (dns_cb_arg.done)
93 break;
94 sys_check_timeouts();
95 if (ctrlc()) {
96 printf("\nAbort\n");
97 break;
98 }
99 } while (get_timer(start) < DNS_TIMEOUT_MS);
100 sys_untimeout(do_dns_tmr, NULL);
101 }
102
103 net_lwip_remove_netif(netif);
104
105 if (dns_cb_arg.done && dns_cb_arg.host_ipaddr.addr != 0)
106 return CMD_RET_SUCCESS;
107
108 return CMD_RET_FAILURE;
109}
110
111int do_dns(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[])
112{
113 char *name;
114 char *var = NULL;
115
116 if (argc == 1 || argc > 3)
117 return CMD_RET_USAGE;
118
119 name = argv[1];
120
121 if (argc == 3)
122 var = argv[2];
123
124 eth_set_current();
125
126 return dns_loop(eth_get_dev(), name, var);
127}