dhcpd.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * udhcp server
  4. * Copyright (C) 1999 Matthew Ramsay <matthewr@moreton.com.au>
  5. * Chris Trew <ctrew@moreton.com.au>
  6. *
  7. * Rewrite by Russ Dill <Russ.Dill@asu.edu> July 2001
  8. *
  9. * This program is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 2 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program; if not, write to the Free Software
  21. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  22. */
  23. //applet:IF_UDHCPD(APPLET(udhcpd, BB_DIR_USR_SBIN, BB_SUID_DROP))
  24. //kbuild:lib-$(CONFIG_UDHCPD) += common.o packet.o signalpipe.o socket.o
  25. //kbuild:lib-$(CONFIG_UDHCPD) += dhcpd.o arpping.o
  26. //kbuild:lib-$(CONFIG_FEATURE_UDHCP_RFC3397) += domain_codec.o
  27. //usage:#define udhcpd_trivial_usage
  28. //usage: "[-fS] [-I ADDR]" IF_FEATURE_UDHCP_PORT(" [-P N]") " [CONFFILE]"
  29. //usage:#define udhcpd_full_usage "\n\n"
  30. //usage: "DHCP server\n"
  31. //usage: "\n -f Run in foreground"
  32. //usage: "\n -S Log to syslog too"
  33. //usage: "\n -I ADDR Local address"
  34. //usage: "\n -a MSEC Timeout for ARP ping (default 2000)"
  35. //usage: IF_FEATURE_UDHCP_PORT(
  36. //usage: "\n -P N Use port N (default 67)"
  37. //usage: )
  38. #include <netinet/ether.h>
  39. #include <syslog.h>
  40. #include "common.h"
  41. #include "dhcpc.h"
  42. #include "dhcpd.h"
  43. /* globals */
  44. struct dyn_lease *g_leases;
  45. /* struct server_config_t server_config is in bb_common_bufsiz1 */
  46. /* Takes the address of the pointer to the static_leases linked list,
  47. * address to a 6 byte mac address,
  48. * 4 byte IP address */
  49. static void add_static_lease(struct static_lease **st_lease_pp,
  50. uint8_t *mac,
  51. uint32_t nip)
  52. {
  53. struct static_lease *st_lease;
  54. /* Find the tail of the list */
  55. while ((st_lease = *st_lease_pp) != NULL) {
  56. st_lease_pp = &st_lease->next;
  57. }
  58. /* Add new node */
  59. *st_lease_pp = st_lease = xzalloc(sizeof(*st_lease));
  60. memcpy(st_lease->mac, mac, 6);
  61. st_lease->nip = nip;
  62. /*st_lease->next = NULL;*/
  63. }
  64. /* Find static lease IP by mac */
  65. static uint32_t get_static_nip_by_mac(struct static_lease *st_lease, void *mac)
  66. {
  67. while (st_lease) {
  68. if (memcmp(st_lease->mac, mac, 6) == 0)
  69. return st_lease->nip;
  70. st_lease = st_lease->next;
  71. }
  72. return 0;
  73. }
  74. static int is_nip_reserved(struct static_lease *st_lease, uint32_t nip)
  75. {
  76. while (st_lease) {
  77. if (st_lease->nip == nip)
  78. return 1;
  79. st_lease = st_lease->next;
  80. }
  81. return 0;
  82. }
  83. #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 2
  84. /* Print out static leases just to check what's going on */
  85. /* Takes the address of the pointer to the static_leases linked list */
  86. static void log_static_leases(struct static_lease **st_lease_pp)
  87. {
  88. struct static_lease *cur;
  89. if (dhcp_verbose < 2)
  90. return;
  91. cur = *st_lease_pp;
  92. while (cur) {
  93. bb_error_msg("static lease: mac:%02x:%02x:%02x:%02x:%02x:%02x nip:%x",
  94. cur->mac[0], cur->mac[1], cur->mac[2],
  95. cur->mac[3], cur->mac[4], cur->mac[5],
  96. cur->nip
  97. );
  98. cur = cur->next;
  99. }
  100. }
  101. #else
  102. # define log_static_leases(st_lease_pp) ((void)0)
  103. #endif
  104. /* Find the oldest expired lease, NULL if there are no expired leases */
  105. static struct dyn_lease *oldest_expired_lease(void)
  106. {
  107. struct dyn_lease *oldest_lease = NULL;
  108. leasetime_t oldest_time = time(NULL);
  109. unsigned i;
  110. /* Unexpired leases have g_leases[i].expires >= current time
  111. * and therefore can't ever match */
  112. for (i = 0; i < server_config.max_leases; i++) {
  113. if (g_leases[i].expires == 0 /* empty entry */
  114. || g_leases[i].expires < oldest_time
  115. ) {
  116. oldest_time = g_leases[i].expires;
  117. oldest_lease = &g_leases[i];
  118. }
  119. }
  120. return oldest_lease;
  121. }
  122. /* Clear out all leases with matching nonzero chaddr OR yiaddr.
  123. * If chaddr == NULL, this is a conflict lease.
  124. */
  125. static void clear_leases(const uint8_t *chaddr, uint32_t yiaddr)
  126. {
  127. unsigned i;
  128. for (i = 0; i < server_config.max_leases; i++) {
  129. if ((chaddr && memcmp(g_leases[i].lease_mac, chaddr, 6) == 0)
  130. || (yiaddr && g_leases[i].lease_nip == yiaddr)
  131. ) {
  132. memset(&g_leases[i], 0, sizeof(g_leases[i]));
  133. }
  134. }
  135. }
  136. /* Add a lease into the table, clearing out any old ones.
  137. * If chaddr == NULL, this is a conflict lease.
  138. */
  139. static struct dyn_lease *add_lease(
  140. const uint8_t *chaddr, uint32_t yiaddr,
  141. leasetime_t leasetime,
  142. const char *hostname, int hostname_len)
  143. {
  144. struct dyn_lease *oldest;
  145. /* clean out any old ones */
  146. clear_leases(chaddr, yiaddr);
  147. oldest = oldest_expired_lease();
  148. if (oldest) {
  149. memset(oldest, 0, sizeof(*oldest));
  150. if (hostname) {
  151. char *p;
  152. hostname_len++; /* include NUL */
  153. if (hostname_len > sizeof(oldest->hostname))
  154. hostname_len = sizeof(oldest->hostname);
  155. p = safe_strncpy(oldest->hostname, hostname, hostname_len);
  156. /*
  157. * Sanitization (s/bad_char/./g).
  158. * The intent is not to allow only "DNS-valid" hostnames,
  159. * but merely make dumpleases output safe for shells to use.
  160. * We accept "0-9A-Za-z._-", all other chars turn to dots.
  161. */
  162. while (*p) {
  163. if (!isalnum(*p) && *p != '-' && *p != '_')
  164. *p = '.';
  165. p++;
  166. }
  167. }
  168. if (chaddr)
  169. memcpy(oldest->lease_mac, chaddr, 6);
  170. oldest->lease_nip = yiaddr;
  171. oldest->expires = time(NULL) + leasetime;
  172. }
  173. return oldest;
  174. }
  175. /* True if a lease has expired */
  176. static int is_expired_lease(struct dyn_lease *lease)
  177. {
  178. return (lease->expires < (leasetime_t) time(NULL));
  179. }
  180. /* Find the first lease that matches MAC, NULL if no match */
  181. static struct dyn_lease *find_lease_by_mac(const uint8_t *mac)
  182. {
  183. unsigned i;
  184. for (i = 0; i < server_config.max_leases; i++)
  185. if (memcmp(g_leases[i].lease_mac, mac, 6) == 0)
  186. return &g_leases[i];
  187. return NULL;
  188. }
  189. /* Find the first lease that matches IP, NULL is no match */
  190. static struct dyn_lease *find_lease_by_nip(uint32_t nip)
  191. {
  192. unsigned i;
  193. for (i = 0; i < server_config.max_leases; i++)
  194. if (g_leases[i].lease_nip == nip)
  195. return &g_leases[i];
  196. return NULL;
  197. }
  198. /* Check if the IP is taken; if it is, add it to the lease table */
  199. static int nobody_responds_to_arp(uint32_t nip, const uint8_t *safe_mac, unsigned arpping_ms)
  200. {
  201. struct in_addr temp;
  202. int r;
  203. r = arpping(nip, safe_mac,
  204. server_config.server_nip,
  205. server_config.server_mac,
  206. server_config.interface,
  207. arpping_ms);
  208. if (r)
  209. return r;
  210. temp.s_addr = nip;
  211. bb_error_msg("%s belongs to someone, reserving it for %u seconds",
  212. inet_ntoa(temp), (unsigned)server_config.conflict_time);
  213. add_lease(NULL, nip, server_config.conflict_time, NULL, 0);
  214. return 0;
  215. }
  216. /* Find a new usable (we think) address */
  217. static uint32_t find_free_or_expired_nip(const uint8_t *safe_mac, unsigned arpping_ms)
  218. {
  219. uint32_t addr;
  220. struct dyn_lease *oldest_lease = NULL;
  221. #if ENABLE_FEATURE_UDHCPD_BASE_IP_ON_MAC
  222. uint32_t stop;
  223. unsigned i, hash;
  224. /* hash hwaddr: use the SDBM hashing algorithm. Seems to give good
  225. * dispersal even with similarly-valued "strings".
  226. */
  227. hash = 0;
  228. for (i = 0; i < 6; i++)
  229. hash += safe_mac[i] + (hash << 6) + (hash << 16) - hash;
  230. /* pick a seed based on hwaddr then iterate until we find a free address. */
  231. addr = server_config.start_ip
  232. + (hash % (1 + server_config.end_ip - server_config.start_ip));
  233. stop = addr;
  234. #else
  235. addr = server_config.start_ip;
  236. #define stop (server_config.end_ip + 1)
  237. #endif
  238. do {
  239. uint32_t nip;
  240. struct dyn_lease *lease;
  241. /* ie, 192.168.55.0 */
  242. if ((addr & 0xff) == 0)
  243. goto next_addr;
  244. /* ie, 192.168.55.255 */
  245. if ((addr & 0xff) == 0xff)
  246. goto next_addr;
  247. nip = htonl(addr);
  248. /* skip our own address */
  249. if (nip == server_config.server_nip)
  250. goto next_addr;
  251. /* is this a static lease addr? */
  252. if (is_nip_reserved(server_config.static_leases, nip))
  253. goto next_addr;
  254. lease = find_lease_by_nip(nip);
  255. if (!lease) {
  256. //TODO: DHCP servers do not always sit on the same subnet as clients: should *ping*, not arp-ping!
  257. if (nobody_responds_to_arp(nip, safe_mac, arpping_ms))
  258. return nip;
  259. } else {
  260. if (!oldest_lease || lease->expires < oldest_lease->expires)
  261. oldest_lease = lease;
  262. }
  263. next_addr:
  264. addr++;
  265. #if ENABLE_FEATURE_UDHCPD_BASE_IP_ON_MAC
  266. if (addr > server_config.end_ip)
  267. addr = server_config.start_ip;
  268. #endif
  269. } while (addr != stop);
  270. if (oldest_lease
  271. && is_expired_lease(oldest_lease)
  272. && nobody_responds_to_arp(oldest_lease->lease_nip, safe_mac, arpping_ms)
  273. ) {
  274. return oldest_lease->lease_nip;
  275. }
  276. return 0;
  277. }
  278. /* On these functions, make sure your datatype matches */
  279. static int FAST_FUNC read_str(const char *line, void *arg)
  280. {
  281. char **dest = arg;
  282. free(*dest);
  283. *dest = xstrdup(line);
  284. return 1;
  285. }
  286. static int FAST_FUNC read_u32(const char *line, void *arg)
  287. {
  288. *(uint32_t*)arg = bb_strtou32(line, NULL, 10);
  289. return errno == 0;
  290. }
  291. static int FAST_FUNC read_staticlease(const char *const_line, void *arg)
  292. {
  293. char *line;
  294. char *mac_string;
  295. char *ip_string;
  296. struct ether_addr mac_bytes; /* it's "struct { uint8_t mac[6]; }" */
  297. uint32_t nip;
  298. /* Read mac */
  299. line = (char *) const_line;
  300. mac_string = strtok_r(line, " \t", &line);
  301. if (!mac_string || !ether_aton_r(mac_string, &mac_bytes))
  302. return 0;
  303. /* Read ip */
  304. ip_string = strtok_r(NULL, " \t", &line);
  305. if (!ip_string || !udhcp_str2nip(ip_string, &nip))
  306. return 0;
  307. add_static_lease(arg, (uint8_t*) &mac_bytes, nip);
  308. log_static_leases(arg);
  309. return 1;
  310. }
  311. static int FAST_FUNC read_optset(const char *line, void *arg) {
  312. return udhcp_str2optset(line, arg, dhcp_optflags, dhcp_option_strings);
  313. }
  314. struct config_keyword {
  315. const char *keyword;
  316. int (*handler)(const char *line, void *var) FAST_FUNC;
  317. unsigned ofs;
  318. const char *def;
  319. };
  320. #define OFS(field) offsetof(struct server_config_t, field)
  321. static const struct config_keyword keywords[] = {
  322. /* keyword handler variable address default */
  323. {"start" , udhcp_str2nip , OFS(start_ip ), "192.168.0.20"},
  324. {"end" , udhcp_str2nip , OFS(end_ip ), "192.168.0.254"},
  325. {"interface" , read_str , OFS(interface ), "eth0"},
  326. /* Avoid "max_leases value not sane" warning by setting default
  327. * to default_end_ip - default_start_ip + 1: */
  328. {"max_leases" , read_u32 , OFS(max_leases ), "235"},
  329. {"auto_time" , read_u32 , OFS(auto_time ), "7200"},
  330. {"decline_time" , read_u32 , OFS(decline_time ), "3600"},
  331. {"conflict_time", read_u32 , OFS(conflict_time), "3600"},
  332. {"offer_time" , read_u32 , OFS(offer_time ), "60"},
  333. {"min_lease" , read_u32 , OFS(min_lease_sec), "60"},
  334. {"lease_file" , read_str , OFS(lease_file ), LEASES_FILE},
  335. {"pidfile" , read_str , OFS(pidfile ), "/var/run/udhcpd.pid"},
  336. {"siaddr" , udhcp_str2nip , OFS(siaddr_nip ), "0.0.0.0"},
  337. /* keywords with no defaults must be last! */
  338. {"option" , read_optset , OFS(options ), ""},
  339. {"opt" , read_optset , OFS(options ), ""},
  340. {"notify_file" , read_str , OFS(notify_file ), NULL},
  341. {"sname" , read_str , OFS(sname ), NULL},
  342. {"boot_file" , read_str , OFS(boot_file ), NULL},
  343. {"static_lease" , read_staticlease, OFS(static_leases), ""},
  344. };
  345. enum { KWS_WITH_DEFAULTS = ARRAY_SIZE(keywords) - 6 };
  346. static NOINLINE void read_config(const char *file)
  347. {
  348. parser_t *parser;
  349. const struct config_keyword *k;
  350. unsigned i;
  351. char *token[2];
  352. for (i = 0; i < KWS_WITH_DEFAULTS; i++)
  353. keywords[i].handler(keywords[i].def, (char*)&server_config + keywords[i].ofs);
  354. parser = config_open(file);
  355. while (config_read(parser, token, 2, 2, "# \t", PARSE_NORMAL)) {
  356. for (k = keywords, i = 0; i < ARRAY_SIZE(keywords); k++, i++) {
  357. if (strcasecmp(token[0], k->keyword) == 0) {
  358. if (!k->handler(token[1], (char*)&server_config + k->ofs)) {
  359. bb_error_msg("can't parse line %u in %s",
  360. parser->lineno, file);
  361. /* reset back to the default value */
  362. k->handler(k->def, (char*)&server_config + k->ofs);
  363. }
  364. break;
  365. }
  366. }
  367. }
  368. config_close(parser);
  369. server_config.start_ip = ntohl(server_config.start_ip);
  370. server_config.end_ip = ntohl(server_config.end_ip);
  371. }
  372. static void write_leases(void)
  373. {
  374. int fd;
  375. unsigned i;
  376. leasetime_t curr;
  377. int64_t written_at;
  378. fd = open_or_warn(server_config.lease_file, O_WRONLY|O_CREAT|O_TRUNC);
  379. if (fd < 0)
  380. return;
  381. curr = written_at = time(NULL);
  382. written_at = SWAP_BE64(written_at);
  383. full_write(fd, &written_at, sizeof(written_at));
  384. for (i = 0; i < server_config.max_leases; i++) {
  385. leasetime_t tmp_time;
  386. if (g_leases[i].lease_nip == 0)
  387. continue;
  388. /* Screw with the time in the struct, for easier writing */
  389. tmp_time = g_leases[i].expires;
  390. g_leases[i].expires -= curr;
  391. if ((signed_leasetime_t) g_leases[i].expires < 0)
  392. g_leases[i].expires = 0;
  393. g_leases[i].expires = htonl(g_leases[i].expires);
  394. /* No error check. If the file gets truncated,
  395. * we lose some leases on restart. Oh well. */
  396. full_write(fd, &g_leases[i], sizeof(g_leases[i]));
  397. /* Then restore it when done */
  398. g_leases[i].expires = tmp_time;
  399. }
  400. close(fd);
  401. if (server_config.notify_file) {
  402. char *argv[3];
  403. argv[0] = server_config.notify_file;
  404. argv[1] = server_config.lease_file;
  405. argv[2] = NULL;
  406. spawn_and_wait(argv);
  407. }
  408. }
  409. static NOINLINE void read_leases(const char *file)
  410. {
  411. struct dyn_lease lease;
  412. int64_t written_at, time_passed;
  413. int fd;
  414. #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
  415. unsigned i = 0;
  416. #endif
  417. fd = open_or_warn(file, O_RDONLY);
  418. if (fd < 0)
  419. return;
  420. if (full_read(fd, &written_at, sizeof(written_at)) != sizeof(written_at))
  421. goto ret;
  422. written_at = SWAP_BE64(written_at);
  423. time_passed = time(NULL) - written_at;
  424. /* Strange written_at, or lease file from old version of udhcpd
  425. * which had no "written_at" field? */
  426. if ((uint64_t)time_passed > 12 * 60 * 60)
  427. goto ret;
  428. while (full_read(fd, &lease, sizeof(lease)) == sizeof(lease)) {
  429. uint32_t y = ntohl(lease.lease_nip);
  430. if (y >= server_config.start_ip && y <= server_config.end_ip) {
  431. signed_leasetime_t expires = ntohl(lease.expires) - (signed_leasetime_t)time_passed;
  432. uint32_t static_nip;
  433. if (expires <= 0)
  434. /* We keep expired leases: add_lease() will add
  435. * a lease with 0 seconds remaining.
  436. * Fewer IP address changes this way for mass reboot scenario.
  437. */
  438. expires = 0;
  439. /* Check if there is a different static lease for this IP or MAC */
  440. static_nip = get_static_nip_by_mac(server_config.static_leases, lease.lease_mac);
  441. if (static_nip) {
  442. /* NB: we do not add lease even if static_nip == lease.lease_nip.
  443. */
  444. continue;
  445. }
  446. if (is_nip_reserved(server_config.static_leases, lease.lease_nip))
  447. continue;
  448. /* NB: add_lease takes "relative time", IOW,
  449. * lease duration, not lease deadline. */
  450. if (add_lease(lease.lease_mac, lease.lease_nip,
  451. expires,
  452. lease.hostname, sizeof(lease.hostname)
  453. ) == 0
  454. ) {
  455. bb_error_msg("too many leases while loading %s", file);
  456. break;
  457. }
  458. #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
  459. i++;
  460. #endif
  461. }
  462. }
  463. log1("read %d leases", i);
  464. ret:
  465. close(fd);
  466. }
  467. /* Send a packet to a specific mac address and ip address by creating our own ip packet */
  468. static void send_packet_to_client(struct dhcp_packet *dhcp_pkt, int force_broadcast)
  469. {
  470. const uint8_t *chaddr;
  471. uint32_t ciaddr;
  472. // Was:
  473. //if (force_broadcast) { /* broadcast */ }
  474. //else if (dhcp_pkt->ciaddr) { /* unicast to dhcp_pkt->ciaddr */ }
  475. //else if (dhcp_pkt->flags & htons(BROADCAST_FLAG)) { /* broadcast */ }
  476. //else { /* unicast to dhcp_pkt->yiaddr */ }
  477. // But this is wrong: yiaddr is _our_ idea what client's IP is
  478. // (for example, from lease file). Client may not know that,
  479. // and may not have UDP socket listening on that IP!
  480. // We should never unicast to dhcp_pkt->yiaddr!
  481. // dhcp_pkt->ciaddr, OTOH, comes from client's request packet,
  482. // and can be used.
  483. if (force_broadcast
  484. || (dhcp_pkt->flags & htons(BROADCAST_FLAG))
  485. || dhcp_pkt->ciaddr == 0
  486. ) {
  487. log1("broadcasting packet to client");
  488. ciaddr = INADDR_BROADCAST;
  489. chaddr = MAC_BCAST_ADDR;
  490. } else {
  491. log1("unicasting packet to client ciaddr");
  492. ciaddr = dhcp_pkt->ciaddr;
  493. chaddr = dhcp_pkt->chaddr;
  494. }
  495. udhcp_send_raw_packet(dhcp_pkt,
  496. /*src*/ server_config.server_nip, SERVER_PORT,
  497. /*dst*/ ciaddr, CLIENT_PORT, chaddr,
  498. server_config.ifindex);
  499. }
  500. /* Send a packet to gateway_nip using the kernel ip stack */
  501. static void send_packet_to_relay(struct dhcp_packet *dhcp_pkt)
  502. {
  503. log1("forwarding packet to relay");
  504. udhcp_send_kernel_packet(dhcp_pkt,
  505. server_config.server_nip, SERVER_PORT,
  506. dhcp_pkt->gateway_nip, SERVER_PORT);
  507. }
  508. static void send_packet(struct dhcp_packet *dhcp_pkt, int force_broadcast)
  509. {
  510. if (dhcp_pkt->gateway_nip)
  511. send_packet_to_relay(dhcp_pkt);
  512. else
  513. send_packet_to_client(dhcp_pkt, force_broadcast);
  514. }
  515. static void init_packet(struct dhcp_packet *packet, struct dhcp_packet *oldpacket, char type)
  516. {
  517. /* Sets op, htype, hlen, cookie fields
  518. * and adds DHCP_MESSAGE_TYPE option */
  519. udhcp_init_header(packet, type);
  520. packet->xid = oldpacket->xid;
  521. memcpy(packet->chaddr, oldpacket->chaddr, sizeof(oldpacket->chaddr));
  522. packet->flags = oldpacket->flags;
  523. packet->gateway_nip = oldpacket->gateway_nip;
  524. packet->ciaddr = oldpacket->ciaddr;
  525. udhcp_add_simple_option(packet, DHCP_SERVER_ID, server_config.server_nip);
  526. }
  527. /* Fill options field, siaddr_nip, and sname and boot_file fields.
  528. * TODO: teach this code to use overload option.
  529. */
  530. static void add_server_options(struct dhcp_packet *packet)
  531. {
  532. struct option_set *curr = server_config.options;
  533. while (curr) {
  534. if (curr->data[OPT_CODE] != DHCP_LEASE_TIME)
  535. udhcp_add_binary_option(packet, curr->data);
  536. curr = curr->next;
  537. }
  538. packet->siaddr_nip = server_config.siaddr_nip;
  539. if (server_config.sname)
  540. strncpy((char*)packet->sname, server_config.sname, sizeof(packet->sname) - 1);
  541. if (server_config.boot_file)
  542. strncpy((char*)packet->file, server_config.boot_file, sizeof(packet->file) - 1);
  543. }
  544. static uint32_t select_lease_time(struct dhcp_packet *packet)
  545. {
  546. uint32_t lease_time_sec = server_config.max_lease_sec;
  547. uint8_t *lease_time_opt = udhcp_get_option(packet, DHCP_LEASE_TIME);
  548. if (lease_time_opt) {
  549. move_from_unaligned32(lease_time_sec, lease_time_opt);
  550. lease_time_sec = ntohl(lease_time_sec);
  551. if (lease_time_sec > server_config.max_lease_sec)
  552. lease_time_sec = server_config.max_lease_sec;
  553. if (lease_time_sec < server_config.min_lease_sec)
  554. lease_time_sec = server_config.min_lease_sec;
  555. }
  556. return lease_time_sec;
  557. }
  558. /* We got a DHCP DISCOVER. Send an OFFER. */
  559. /* NOINLINE: limit stack usage in caller */
  560. static NOINLINE void send_offer(struct dhcp_packet *oldpacket,
  561. uint32_t static_lease_nip,
  562. struct dyn_lease *lease,
  563. uint8_t *requested_ip_opt,
  564. unsigned arpping_ms)
  565. {
  566. struct dhcp_packet packet;
  567. uint32_t lease_time_sec;
  568. struct in_addr addr;
  569. init_packet(&packet, oldpacket, DHCPOFFER);
  570. /* If it is a static lease, use its IP */
  571. packet.yiaddr = static_lease_nip;
  572. /* Else: */
  573. if (!static_lease_nip) {
  574. /* We have no static lease for client's chaddr */
  575. uint32_t req_nip;
  576. const char *p_host_name;
  577. if (lease) {
  578. /* We have a dynamic lease for client's chaddr.
  579. * Reuse its IP (even if lease is expired).
  580. * Note that we ignore requested IP in this case.
  581. */
  582. packet.yiaddr = lease->lease_nip;
  583. }
  584. /* Or: if client has requested an IP */
  585. else if (requested_ip_opt != NULL
  586. /* (read IP) */
  587. && (move_from_unaligned32(req_nip, requested_ip_opt), 1)
  588. /* and the IP is in the lease range */
  589. && ntohl(req_nip) >= server_config.start_ip
  590. && ntohl(req_nip) <= server_config.end_ip
  591. /* and */
  592. && ( !(lease = find_lease_by_nip(req_nip)) /* is not already taken */
  593. || is_expired_lease(lease) /* or is taken, but expired */
  594. )
  595. ) {
  596. packet.yiaddr = req_nip;
  597. }
  598. else {
  599. /* Otherwise, find a free IP */
  600. packet.yiaddr = find_free_or_expired_nip(oldpacket->chaddr, arpping_ms);
  601. }
  602. if (!packet.yiaddr) {
  603. bb_error_msg("no free IP addresses. OFFER abandoned");
  604. return;
  605. }
  606. /* Reserve the IP for a short time hoping to get DHCPREQUEST soon */
  607. p_host_name = (const char*) udhcp_get_option(oldpacket, DHCP_HOST_NAME);
  608. lease = add_lease(packet.chaddr, packet.yiaddr,
  609. server_config.offer_time,
  610. p_host_name,
  611. p_host_name ? (unsigned char)p_host_name[OPT_LEN - OPT_DATA] : 0
  612. );
  613. if (!lease) {
  614. bb_error_msg("no free IP addresses. OFFER abandoned");
  615. return;
  616. }
  617. }
  618. lease_time_sec = select_lease_time(oldpacket);
  619. udhcp_add_simple_option(&packet, DHCP_LEASE_TIME, htonl(lease_time_sec));
  620. add_server_options(&packet);
  621. addr.s_addr = packet.yiaddr;
  622. bb_error_msg("sending OFFER of %s", inet_ntoa(addr));
  623. /* send_packet emits error message itself if it detects failure */
  624. send_packet(&packet, /*force_bcast:*/ 0);
  625. }
  626. /* NOINLINE: limit stack usage in caller */
  627. static NOINLINE void send_NAK(struct dhcp_packet *oldpacket)
  628. {
  629. struct dhcp_packet packet;
  630. init_packet(&packet, oldpacket, DHCPNAK);
  631. log1("sending %s", "NAK");
  632. send_packet(&packet, /*force_bcast:*/ 1);
  633. }
  634. /* NOINLINE: limit stack usage in caller */
  635. static NOINLINE void send_ACK(struct dhcp_packet *oldpacket, uint32_t yiaddr)
  636. {
  637. struct dhcp_packet packet;
  638. uint32_t lease_time_sec;
  639. struct in_addr addr;
  640. const char *p_host_name;
  641. init_packet(&packet, oldpacket, DHCPACK);
  642. packet.yiaddr = yiaddr;
  643. lease_time_sec = select_lease_time(oldpacket);
  644. udhcp_add_simple_option(&packet, DHCP_LEASE_TIME, htonl(lease_time_sec));
  645. add_server_options(&packet);
  646. addr.s_addr = yiaddr;
  647. bb_error_msg("sending ACK to %s", inet_ntoa(addr));
  648. send_packet(&packet, /*force_bcast:*/ 0);
  649. p_host_name = (const char*) udhcp_get_option(oldpacket, DHCP_HOST_NAME);
  650. add_lease(packet.chaddr, packet.yiaddr,
  651. lease_time_sec,
  652. p_host_name,
  653. p_host_name ? (unsigned char)p_host_name[OPT_LEN - OPT_DATA] : 0
  654. );
  655. if (ENABLE_FEATURE_UDHCPD_WRITE_LEASES_EARLY) {
  656. /* rewrite the file with leases at every new acceptance */
  657. write_leases();
  658. }
  659. }
  660. /* NOINLINE: limit stack usage in caller */
  661. static NOINLINE void send_inform(struct dhcp_packet *oldpacket)
  662. {
  663. struct dhcp_packet packet;
  664. /* "If a client has obtained a network address through some other means
  665. * (e.g., manual configuration), it may use a DHCPINFORM request message
  666. * to obtain other local configuration parameters. Servers receiving a
  667. * DHCPINFORM message construct a DHCPACK message with any local
  668. * configuration parameters appropriate for the client without:
  669. * allocating a new address, checking for an existing binding, filling
  670. * in 'yiaddr' or including lease time parameters. The servers SHOULD
  671. * unicast the DHCPACK reply to the address given in the 'ciaddr' field
  672. * of the DHCPINFORM message.
  673. * ...
  674. * The server responds to a DHCPINFORM message by sending a DHCPACK
  675. * message directly to the address given in the 'ciaddr' field
  676. * of the DHCPINFORM message. The server MUST NOT send a lease
  677. * expiration time to the client and SHOULD NOT fill in 'yiaddr'."
  678. */
  679. //TODO: do a few sanity checks: is ciaddr set?
  680. //Better yet: is ciaddr == IP source addr?
  681. init_packet(&packet, oldpacket, DHCPACK);
  682. add_server_options(&packet);
  683. send_packet(&packet, /*force_bcast:*/ 0);
  684. }
  685. int udhcpd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  686. int udhcpd_main(int argc UNUSED_PARAM, char **argv)
  687. {
  688. int server_socket = -1, retval;
  689. uint8_t *state;
  690. unsigned timeout_end;
  691. unsigned num_ips;
  692. unsigned opt;
  693. struct option_set *option;
  694. char *str_I = str_I;
  695. const char *str_a = "2000";
  696. unsigned arpping_ms;
  697. IF_FEATURE_UDHCP_PORT(char *str_P;)
  698. setup_common_bufsiz();
  699. IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;)
  700. IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;)
  701. #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
  702. opt_complementary = "vv";
  703. #endif
  704. opt = getopt32(argv, "fSI:va:"
  705. IF_FEATURE_UDHCP_PORT("P:")
  706. , &str_I
  707. , &str_a
  708. IF_FEATURE_UDHCP_PORT(, &str_P)
  709. IF_UDHCP_VERBOSE(, &dhcp_verbose)
  710. );
  711. if (!(opt & 1)) { /* no -f */
  712. bb_daemonize_or_rexec(0, argv);
  713. logmode = LOGMODE_NONE;
  714. }
  715. /* update argv after the possible vfork+exec in daemonize */
  716. argv += optind;
  717. if (opt & 2) { /* -S */
  718. openlog(applet_name, LOG_PID, LOG_DAEMON);
  719. logmode |= LOGMODE_SYSLOG;
  720. }
  721. if (opt & 4) { /* -I */
  722. len_and_sockaddr *lsa = xhost_and_af2sockaddr(str_I, 0, AF_INET);
  723. server_config.server_nip = lsa->u.sin.sin_addr.s_addr;
  724. free(lsa);
  725. }
  726. #if ENABLE_FEATURE_UDHCP_PORT
  727. if (opt & 32) { /* -P */
  728. SERVER_PORT = xatou16(str_P);
  729. CLIENT_PORT = SERVER_PORT + 1;
  730. }
  731. #endif
  732. arpping_ms = xatou(str_a);
  733. /* Would rather not do read_config before daemonization -
  734. * otherwise NOMMU machines will parse config twice */
  735. read_config(argv[0] ? argv[0] : DHCPD_CONF_FILE);
  736. /* Make sure fd 0,1,2 are open */
  737. bb_sanitize_stdio();
  738. /* Equivalent of doing a fflush after every \n */
  739. setlinebuf(stdout);
  740. /* Create pidfile */
  741. write_pidfile(server_config.pidfile);
  742. /* if (!..) bb_perror_msg("can't create pidfile %s", pidfile); */
  743. bb_error_msg("started, v"BB_VER);
  744. option = udhcp_find_option(server_config.options, DHCP_LEASE_TIME);
  745. server_config.max_lease_sec = DEFAULT_LEASE_TIME;
  746. if (option) {
  747. move_from_unaligned32(server_config.max_lease_sec, option->data + OPT_DATA);
  748. server_config.max_lease_sec = ntohl(server_config.max_lease_sec);
  749. }
  750. /* Sanity check */
  751. num_ips = server_config.end_ip - server_config.start_ip + 1;
  752. if (server_config.max_leases > num_ips) {
  753. bb_error_msg("max_leases=%u is too big, setting to %u",
  754. (unsigned)server_config.max_leases, num_ips);
  755. server_config.max_leases = num_ips;
  756. }
  757. g_leases = xzalloc(server_config.max_leases * sizeof(g_leases[0]));
  758. read_leases(server_config.lease_file);
  759. if (udhcp_read_interface(server_config.interface,
  760. &server_config.ifindex,
  761. (server_config.server_nip == 0 ? &server_config.server_nip : NULL),
  762. server_config.server_mac)
  763. ) {
  764. retval = 1;
  765. goto ret;
  766. }
  767. /* Setup the signal pipe */
  768. udhcp_sp_setup();
  769. continue_with_autotime:
  770. timeout_end = monotonic_sec() + server_config.auto_time;
  771. while (1) { /* loop until universe collapses */
  772. struct pollfd pfds[2];
  773. struct dhcp_packet packet;
  774. int bytes;
  775. int tv;
  776. uint8_t *server_id_opt;
  777. uint8_t *requested_ip_opt;
  778. uint32_t requested_nip = requested_nip; /* for compiler */
  779. uint32_t static_lease_nip;
  780. struct dyn_lease *lease, fake_lease;
  781. if (server_socket < 0) {
  782. server_socket = udhcp_listen_socket(/*INADDR_ANY,*/ SERVER_PORT,
  783. server_config.interface);
  784. }
  785. udhcp_sp_fd_set(pfds, server_socket);
  786. tv = timeout_end - monotonic_sec();
  787. retval = 0;
  788. if (!server_config.auto_time || tv > 0) {
  789. retval = poll(pfds, 2, server_config.auto_time ? tv * 1000 : -1);
  790. }
  791. if (retval == 0) {
  792. write_leases();
  793. goto continue_with_autotime;
  794. }
  795. if (retval < 0 && errno != EINTR) {
  796. log1("error on select");
  797. continue;
  798. }
  799. switch (udhcp_sp_read(pfds)) {
  800. case SIGUSR1:
  801. bb_error_msg("received %s", "SIGUSR1");
  802. write_leases();
  803. /* why not just reset the timeout, eh */
  804. goto continue_with_autotime;
  805. case SIGTERM:
  806. bb_error_msg("received %s", "SIGTERM");
  807. write_leases();
  808. goto ret0;
  809. case 0: /* no signal: read a packet */
  810. break;
  811. default: /* signal or error (probably EINTR): back to select */
  812. continue;
  813. }
  814. bytes = udhcp_recv_kernel_packet(&packet, server_socket);
  815. if (bytes < 0) {
  816. /* bytes can also be -2 ("bad packet data") */
  817. if (bytes == -1 && errno != EINTR) {
  818. log1("read error: %s, reopening socket", strerror(errno));
  819. close(server_socket);
  820. server_socket = -1;
  821. }
  822. continue;
  823. }
  824. if (packet.hlen != 6) {
  825. bb_error_msg("MAC length != 6, ignoring packet");
  826. continue;
  827. }
  828. if (packet.op != BOOTREQUEST) {
  829. bb_error_msg("not a REQUEST, ignoring packet");
  830. continue;
  831. }
  832. state = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
  833. if (state == NULL || state[0] < DHCP_MINTYPE || state[0] > DHCP_MAXTYPE) {
  834. bb_error_msg("no or bad message type option, ignoring packet");
  835. continue;
  836. }
  837. /* Get SERVER_ID if present */
  838. server_id_opt = udhcp_get_option(&packet, DHCP_SERVER_ID);
  839. if (server_id_opt) {
  840. uint32_t server_id_network_order;
  841. move_from_unaligned32(server_id_network_order, server_id_opt);
  842. if (server_id_network_order != server_config.server_nip) {
  843. /* client talks to somebody else */
  844. log1("server ID doesn't match, ignoring");
  845. continue;
  846. }
  847. }
  848. /* Look for a static/dynamic lease */
  849. static_lease_nip = get_static_nip_by_mac(server_config.static_leases, &packet.chaddr);
  850. if (static_lease_nip) {
  851. bb_error_msg("found static lease: %x", static_lease_nip);
  852. memcpy(&fake_lease.lease_mac, &packet.chaddr, 6);
  853. fake_lease.lease_nip = static_lease_nip;
  854. fake_lease.expires = 0;
  855. lease = &fake_lease;
  856. } else {
  857. lease = find_lease_by_mac(packet.chaddr);
  858. }
  859. /* Get REQUESTED_IP if present */
  860. requested_ip_opt = udhcp_get_option(&packet, DHCP_REQUESTED_IP);
  861. if (requested_ip_opt) {
  862. move_from_unaligned32(requested_nip, requested_ip_opt);
  863. }
  864. switch (state[0]) {
  865. case DHCPDISCOVER:
  866. log1("received %s", "DISCOVER");
  867. send_offer(&packet, static_lease_nip, lease, requested_ip_opt, arpping_ms);
  868. break;
  869. case DHCPREQUEST:
  870. log1("received %s", "REQUEST");
  871. /* RFC 2131:
  872. o DHCPREQUEST generated during SELECTING state:
  873. Client inserts the address of the selected server in 'server
  874. identifier', 'ciaddr' MUST be zero, 'requested IP address' MUST be
  875. filled in with the yiaddr value from the chosen DHCPOFFER.
  876. Note that the client may choose to collect several DHCPOFFER
  877. messages and select the "best" offer. The client indicates its
  878. selection by identifying the offering server in the DHCPREQUEST
  879. message. If the client receives no acceptable offers, the client
  880. may choose to try another DHCPDISCOVER message. Therefore, the
  881. servers may not receive a specific DHCPREQUEST from which they can
  882. decide whether or not the client has accepted the offer.
  883. o DHCPREQUEST generated during INIT-REBOOT state:
  884. 'server identifier' MUST NOT be filled in, 'requested IP address'
  885. option MUST be filled in with client's notion of its previously
  886. assigned address. 'ciaddr' MUST be zero. The client is seeking to
  887. verify a previously allocated, cached configuration. Server SHOULD
  888. send a DHCPNAK message to the client if the 'requested IP address'
  889. is incorrect, or is on the wrong network.
  890. Determining whether a client in the INIT-REBOOT state is on the
  891. correct network is done by examining the contents of 'giaddr', the
  892. 'requested IP address' option, and a database lookup. If the DHCP
  893. server detects that the client is on the wrong net (i.e., the
  894. result of applying the local subnet mask or remote subnet mask (if
  895. 'giaddr' is not zero) to 'requested IP address' option value
  896. doesn't match reality), then the server SHOULD send a DHCPNAK
  897. message to the client.
  898. If the network is correct, then the DHCP server should check if
  899. the client's notion of its IP address is correct. If not, then the
  900. server SHOULD send a DHCPNAK message to the client. If the DHCP
  901. server has no record of this client, then it MUST remain silent,
  902. and MAY output a warning to the network administrator. This
  903. behavior is necessary for peaceful coexistence of non-
  904. communicating DHCP servers on the same wire.
  905. If 'giaddr' is 0x0 in the DHCPREQUEST message, the client is on
  906. the same subnet as the server. The server MUST broadcast the
  907. DHCPNAK message to the 0xffffffff broadcast address because the
  908. client may not have a correct network address or subnet mask, and
  909. the client may not be answering ARP requests.
  910. If 'giaddr' is set in the DHCPREQUEST message, the client is on a
  911. different subnet. The server MUST set the broadcast bit in the
  912. DHCPNAK, so that the relay agent will broadcast the DHCPNAK to the
  913. client, because the client may not have a correct network address
  914. or subnet mask, and the client may not be answering ARP requests.
  915. o DHCPREQUEST generated during RENEWING state:
  916. 'server identifier' MUST NOT be filled in, 'requested IP address'
  917. option MUST NOT be filled in, 'ciaddr' MUST be filled in with
  918. client's IP address. In this situation, the client is completely
  919. configured, and is trying to extend its lease. This message will
  920. be unicast, so no relay agents will be involved in its
  921. transmission. Because 'giaddr' is therefore not filled in, the
  922. DHCP server will trust the value in 'ciaddr', and use it when
  923. replying to the client.
  924. A client MAY choose to renew or extend its lease prior to T1. The
  925. server may choose not to extend the lease (as a policy decision by
  926. the network administrator), but should return a DHCPACK message
  927. regardless.
  928. o DHCPREQUEST generated during REBINDING state:
  929. 'server identifier' MUST NOT be filled in, 'requested IP address'
  930. option MUST NOT be filled in, 'ciaddr' MUST be filled in with
  931. client's IP address. In this situation, the client is completely
  932. configured, and is trying to extend its lease. This message MUST
  933. be broadcast to the 0xffffffff IP broadcast address. The DHCP
  934. server SHOULD check 'ciaddr' for correctness before replying to
  935. the DHCPREQUEST.
  936. The DHCPREQUEST from a REBINDING client is intended to accommodate
  937. sites that have multiple DHCP servers and a mechanism for
  938. maintaining consistency among leases managed by multiple servers.
  939. A DHCP server MAY extend a client's lease only if it has local
  940. administrative authority to do so.
  941. */
  942. if (!requested_ip_opt) {
  943. requested_nip = packet.ciaddr;
  944. if (requested_nip == 0) {
  945. log1("no requested IP and no ciaddr, ignoring");
  946. break;
  947. }
  948. }
  949. if (lease && requested_nip == lease->lease_nip) {
  950. /* client requested or configured IP matches the lease.
  951. * ACK it, and bump lease expiration time. */
  952. send_ACK(&packet, lease->lease_nip);
  953. break;
  954. }
  955. /* No lease for this MAC, or lease IP != requested IP */
  956. if (server_id_opt /* client is in SELECTING state */
  957. || requested_ip_opt /* client is in INIT-REBOOT state */
  958. ) {
  959. /* "No, we don't have this IP for you" */
  960. send_NAK(&packet);
  961. } /* else: client is in RENEWING or REBINDING, do not answer */
  962. break;
  963. case DHCPDECLINE:
  964. /* RFC 2131:
  965. * "If the server receives a DHCPDECLINE message,
  966. * the client has discovered through some other means
  967. * that the suggested network address is already
  968. * in use. The server MUST mark the network address
  969. * as not available and SHOULD notify the local
  970. * sysadmin of a possible configuration problem."
  971. *
  972. * SERVER_ID must be present,
  973. * REQUESTED_IP must be present,
  974. * chaddr must be filled in,
  975. * ciaddr must be 0 (we do not check this)
  976. */
  977. log1("received %s", "DECLINE");
  978. if (server_id_opt
  979. && requested_ip_opt
  980. && lease /* chaddr matches this lease */
  981. && requested_nip == lease->lease_nip
  982. ) {
  983. memset(lease->lease_mac, 0, sizeof(lease->lease_mac));
  984. lease->expires = time(NULL) + server_config.decline_time;
  985. }
  986. break;
  987. case DHCPRELEASE:
  988. /* "Upon receipt of a DHCPRELEASE message, the server
  989. * marks the network address as not allocated."
  990. *
  991. * SERVER_ID must be present,
  992. * REQUESTED_IP must not be present (we do not check this),
  993. * chaddr must be filled in,
  994. * ciaddr must be filled in
  995. */
  996. log1("received %s", "RELEASE");
  997. if (server_id_opt
  998. && lease /* chaddr matches this lease */
  999. && packet.ciaddr == lease->lease_nip
  1000. ) {
  1001. lease->expires = time(NULL);
  1002. }
  1003. break;
  1004. case DHCPINFORM:
  1005. log1("received %s", "INFORM");
  1006. send_inform(&packet);
  1007. break;
  1008. }
  1009. }
  1010. ret0:
  1011. retval = 0;
  1012. ret:
  1013. /*if (server_config.pidfile) - server_config.pidfile is never NULL */
  1014. remove_pidfile(server_config.pidfile);
  1015. return retval;
  1016. }