xref: /kvmtool/net/uip/dhcp.c (revision bdcc9e40df201b98ba1b2e2fac1ecd8cc13ac9cc)
1 #include "kvm/uip.h"
2 
3 #include <arpa/inet.h>
4 
5 static inline bool uip_dhcp_is_discovery(struct uip_dhcp *dhcp)
6 {
7 	return (dhcp->option[2] == UIP_DHCP_DISCOVER &&
8 		dhcp->option[1] == UIP_DHCP_TAG_MSG_TYPE_LEN &&
9 		dhcp->option[0] == UIP_DHCP_TAG_MSG_TYPE);
10 }
11 
12 static inline bool uip_dhcp_is_request(struct uip_dhcp *dhcp)
13 {
14 	return (dhcp->option[2] == UIP_DHCP_REQUEST &&
15 		dhcp->option[1] == UIP_DHCP_TAG_MSG_TYPE_LEN &&
16 		dhcp->option[0] == UIP_DHCP_TAG_MSG_TYPE);
17 }
18 
19 bool uip_udp_is_dhcp(struct uip_udp *udp)
20 {
21 	struct uip_dhcp *dhcp;
22 
23 	if (ntohs(udp->sport) != UIP_DHCP_PORT_CLIENT ||
24 	    ntohs(udp->dport) != UIP_DHCP_PORT_SERVER)
25 		return false;
26 
27 	dhcp = (struct uip_dhcp *)udp;
28 
29 	if (ntohl(dhcp->magic_cookie) != UIP_DHCP_MAGIC_COOKIE)
30 		return false;
31 
32 	return true;
33 }
34 
35 int uip_dhcp_get_dns(struct uip_info *info)
36 {
37 	char key[256], val[256];
38 	struct in_addr addr;
39 	int ret = -1;
40 	int n = 0;
41 	FILE *fp;
42 	u32 ip;
43 
44 	fp = fopen("/etc/resolv.conf", "r");
45 	if (!fp)
46 		goto out;
47 
48 	while (!feof(fp)) {
49 		if (fscanf(fp, "%s %s\n", key, val) != 2)
50 			continue;
51 		if (strncmp("domain", key, 6) == 0)
52 			info->domain_name = strndup(val, UIP_DHCP_MAX_DOMAIN_NAME_LEN);
53 		else if (strncmp("nameserver", key, 10) == 0) {
54 			if (!inet_aton(val, &addr))
55 				continue;
56 			ip = ntohl(addr.s_addr);
57 			if (n < UIP_DHCP_MAX_DNS_SERVER_NR)
58 				info->dns_ip[n++] = ip;
59 			ret = 0;
60 		}
61 	}
62 
63 out:
64 	fclose(fp);
65 	return ret;
66 }
67