Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

dhcpserver.c 9.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2018-2019 Damien P. George
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. // For DHCP specs see:
  27. // https://www.ietf.org/rfc/rfc2131.txt
  28. // https://tools.ietf.org/html/rfc2132 -- DHCP Options and BOOTP Vendor Extensions
  29. #include <stdio.h>
  30. #include <string.h>
  31. #include <errno.h>
  32. #include "cyw43_config.h"
  33. #include "dhcpserver.h"
  34. #include "lwip/udp.h"
  35. #define DHCPDISCOVER (1)
  36. #define DHCPOFFER (2)
  37. #define DHCPREQUEST (3)
  38. #define DHCPDECLINE (4)
  39. #define DHCPACK (5)
  40. #define DHCPNACK (6)
  41. #define DHCPRELEASE (7)
  42. #define DHCPINFORM (8)
  43. #define DHCP_OPT_PAD (0)
  44. #define DHCP_OPT_SUBNET_MASK (1)
  45. #define DHCP_OPT_ROUTER (3)
  46. #define DHCP_OPT_DNS (6)
  47. #define DHCP_OPT_HOST_NAME (12)
  48. #define DHCP_OPT_REQUESTED_IP (50)
  49. #define DHCP_OPT_IP_LEASE_TIME (51)
  50. #define DHCP_OPT_MSG_TYPE (53)
  51. #define DHCP_OPT_SERVER_ID (54)
  52. #define DHCP_OPT_PARAM_REQUEST_LIST (55)
  53. #define DHCP_OPT_MAX_MSG_SIZE (57)
  54. #define DHCP_OPT_VENDOR_CLASS_ID (60)
  55. #define DHCP_OPT_CLIENT_ID (61)
  56. #define DHCP_OPT_END (255)
  57. #define PORT_DHCP_SERVER (67)
  58. #define PORT_DHCP_CLIENT (68)
  59. #define DEFAULT_DNS MAKE_IP4(8, 8, 8, 8)
  60. #define DEFAULT_LEASE_TIME_S (24 * 60 * 60) // in seconds
  61. #define MAC_LEN (6)
  62. #define MAKE_IP4(a, b, c, d) ((a) << 24 | (b) << 16 | (c) << 8 | (d))
  63. typedef struct {
  64. uint8_t op; // message opcode
  65. uint8_t htype; // hardware address type
  66. uint8_t hlen; // hardware address length
  67. uint8_t hops;
  68. uint32_t xid; // transaction id, chosen by client
  69. uint16_t secs; // client seconds elapsed
  70. uint16_t flags;
  71. uint8_t ciaddr[4]; // client IP address
  72. uint8_t yiaddr[4]; // your IP address
  73. uint8_t siaddr[4]; // next server IP address
  74. uint8_t giaddr[4]; // relay agent IP address
  75. uint8_t chaddr[16]; // client hardware address
  76. uint8_t sname[64]; // server host name
  77. uint8_t file[128]; // boot file name
  78. uint8_t options[312]; // optional parameters, variable, starts with magic
  79. } dhcp_msg_t;
  80. static int dhcp_socket_new_dgram(struct udp_pcb **udp, void *cb_data, udp_recv_fn cb_udp_recv) {
  81. // family is AF_INET
  82. // type is SOCK_DGRAM
  83. *udp = udp_new();
  84. if (*udp == NULL) {
  85. return -ENOMEM;
  86. }
  87. // Register callback
  88. udp_recv(*udp, cb_udp_recv, (void *)cb_data);
  89. return 0; // success
  90. }
  91. static void dhcp_socket_free(struct udp_pcb **udp) {
  92. if (*udp != NULL) {
  93. udp_remove(*udp);
  94. *udp = NULL;
  95. }
  96. }
  97. static int dhcp_socket_bind(struct udp_pcb **udp, uint32_t ip, uint16_t port) {
  98. ip_addr_t addr;
  99. IP4_ADDR(&addr, ip >> 24 & 0xff, ip >> 16 & 0xff, ip >> 8 & 0xff, ip & 0xff);
  100. // TODO convert lwIP errors to errno
  101. return udp_bind(*udp, &addr, port);
  102. }
  103. static int dhcp_socket_sendto(struct udp_pcb **udp, const void *buf, size_t len, uint32_t ip, uint16_t port) {
  104. if (len > 0xffff) {
  105. len = 0xffff;
  106. }
  107. struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM);
  108. if (p == NULL) {
  109. return -ENOMEM;
  110. }
  111. memcpy(p->payload, buf, len);
  112. ip_addr_t dest;
  113. IP4_ADDR(&dest, ip >> 24 & 0xff, ip >> 16 & 0xff, ip >> 8 & 0xff, ip & 0xff);
  114. err_t err = udp_sendto(*udp, p, &dest, port);
  115. pbuf_free(p);
  116. if (err != ERR_OK) {
  117. return err;
  118. }
  119. return len;
  120. }
  121. static uint8_t *opt_find(uint8_t *opt, uint8_t cmd) {
  122. for (int i = 0; i < 308 && opt[i] != DHCP_OPT_END;) {
  123. if (opt[i] == cmd) {
  124. return &opt[i];
  125. }
  126. i += 2 + opt[i + 1];
  127. }
  128. return NULL;
  129. }
  130. static void opt_write_n(uint8_t **opt, uint8_t cmd, size_t n, void *data) {
  131. uint8_t *o = *opt;
  132. *o++ = cmd;
  133. *o++ = n;
  134. memcpy(o, data, n);
  135. *opt = o + n;
  136. }
  137. static void opt_write_u8(uint8_t **opt, uint8_t cmd, uint8_t val) {
  138. uint8_t *o = *opt;
  139. *o++ = cmd;
  140. *o++ = 1;
  141. *o++ = val;
  142. *opt = o;
  143. }
  144. static void opt_write_u32(uint8_t **opt, uint8_t cmd, uint32_t val) {
  145. uint8_t *o = *opt;
  146. *o++ = cmd;
  147. *o++ = 4;
  148. *o++ = val >> 24;
  149. *o++ = val >> 16;
  150. *o++ = val >> 8;
  151. *o++ = val;
  152. *opt = o;
  153. }
  154. static void dhcp_server_process(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_addr_t *src_addr, u16_t src_port) {
  155. dhcp_server_t *d = arg;
  156. (void)upcb;
  157. (void)src_addr;
  158. (void)src_port;
  159. // This is around 548 bytes
  160. dhcp_msg_t dhcp_msg;
  161. #define DHCP_MIN_SIZE (240 + 3)
  162. if (p->tot_len < DHCP_MIN_SIZE) {
  163. goto ignore_request;
  164. }
  165. size_t len = pbuf_copy_partial(p, &dhcp_msg, sizeof(dhcp_msg), 0);
  166. if (len < DHCP_MIN_SIZE) {
  167. goto ignore_request;
  168. }
  169. dhcp_msg.op = DHCPOFFER;
  170. memcpy(&dhcp_msg.yiaddr, &d->ip.addr, 4);
  171. uint8_t *opt = (uint8_t *)&dhcp_msg.options;
  172. opt += 4; // assume magic cookie: 99, 130, 83, 99
  173. switch (opt[2]) {
  174. case DHCPDISCOVER: {
  175. int yi = DHCPS_MAX_IP;
  176. for (int i = 0; i < DHCPS_MAX_IP; ++i) {
  177. if (memcmp(d->lease[i].mac, dhcp_msg.chaddr, MAC_LEN) == 0) {
  178. // MAC match, use this IP address
  179. yi = i;
  180. break;
  181. }
  182. if (yi == DHCPS_MAX_IP) {
  183. // Look for a free IP address
  184. if (memcmp(d->lease[i].mac, "\x00\x00\x00\x00\x00\x00", MAC_LEN) == 0) {
  185. // IP available
  186. yi = i;
  187. }
  188. uint32_t expiry = d->lease[i].expiry << 16 | 0xffff;
  189. if ((int32_t)(expiry - cyw43_hal_ticks_ms()) < 0) {
  190. // IP expired, reuse it
  191. memset(d->lease[i].mac, 0, MAC_LEN);
  192. yi = i;
  193. }
  194. }
  195. }
  196. if (yi == DHCPS_MAX_IP) {
  197. // No more IP addresses left
  198. goto ignore_request;
  199. }
  200. dhcp_msg.yiaddr[3] = DHCPS_BASE_IP + yi;
  201. opt_write_u8(&opt, DHCP_OPT_MSG_TYPE, DHCPOFFER);
  202. break;
  203. }
  204. case DHCPREQUEST: {
  205. uint8_t *o = opt_find(opt, DHCP_OPT_REQUESTED_IP);
  206. if (o == NULL) {
  207. // Should be NACK
  208. goto ignore_request;
  209. }
  210. if (memcmp(o + 2, &d->ip.addr, 3) != 0) {
  211. // Should be NACK
  212. goto ignore_request;
  213. }
  214. uint8_t yi = o[5] - DHCPS_BASE_IP;
  215. if (yi >= DHCPS_MAX_IP) {
  216. // Should be NACK
  217. goto ignore_request;
  218. }
  219. if (memcmp(d->lease[yi].mac, dhcp_msg.chaddr, MAC_LEN) == 0) {
  220. // MAC match, ok to use this IP address
  221. } else if (memcmp(d->lease[yi].mac, "\x00\x00\x00\x00\x00\x00", MAC_LEN) == 0) {
  222. // IP unused, ok to use this IP address
  223. memcpy(d->lease[yi].mac, dhcp_msg.chaddr, MAC_LEN);
  224. } else {
  225. // IP already in use
  226. // Should be NACK
  227. goto ignore_request;
  228. }
  229. d->lease[yi].expiry = (cyw43_hal_ticks_ms() + DEFAULT_LEASE_TIME_S * 1000) >> 16;
  230. dhcp_msg.yiaddr[3] = DHCPS_BASE_IP + yi;
  231. opt_write_u8(&opt, DHCP_OPT_MSG_TYPE, DHCPACK);
  232. printf("DHCPS: client connected: MAC=%02x:%02x:%02x:%02x:%02x:%02x IP=%u.%u.%u.%u\n",
  233. dhcp_msg.chaddr[0], dhcp_msg.chaddr[1], dhcp_msg.chaddr[2], dhcp_msg.chaddr[3], dhcp_msg.chaddr[4], dhcp_msg.chaddr[5],
  234. dhcp_msg.yiaddr[0], dhcp_msg.yiaddr[1], dhcp_msg.yiaddr[2], dhcp_msg.yiaddr[3]);
  235. break;
  236. }
  237. default:
  238. goto ignore_request;
  239. }
  240. opt_write_n(&opt, DHCP_OPT_SERVER_ID, 4, &d->ip.addr);
  241. opt_write_n(&opt, DHCP_OPT_SUBNET_MASK, 4, &d->nm.addr);
  242. opt_write_n(&opt, DHCP_OPT_ROUTER, 4, &d->ip.addr); // aka gateway; can have mulitple addresses
  243. opt_write_u32(&opt, DHCP_OPT_DNS, DEFAULT_DNS); // can have mulitple addresses
  244. opt_write_u32(&opt, DHCP_OPT_IP_LEASE_TIME, DEFAULT_LEASE_TIME_S);
  245. *opt++ = DHCP_OPT_END;
  246. dhcp_socket_sendto(&d->udp, &dhcp_msg, opt - (uint8_t *)&dhcp_msg, 0xffffffff, PORT_DHCP_CLIENT);
  247. ignore_request:
  248. pbuf_free(p);
  249. }
  250. void dhcp_server_init(dhcp_server_t *d, ip_addr_t *ip, ip_addr_t *nm) {
  251. ip_addr_copy(d->ip, *ip);
  252. ip_addr_copy(d->nm, *nm);
  253. memset(d->lease, 0, sizeof(d->lease));
  254. if (dhcp_socket_new_dgram(&d->udp, d, dhcp_server_process) != 0) {
  255. return;
  256. }
  257. dhcp_socket_bind(&d->udp, 0, PORT_DHCP_SERVER);
  258. }
  259. void dhcp_server_deinit(dhcp_server_t *d) {
  260. dhcp_socket_free(&d->udp);
  261. }