3
0

dhcpd.c 39 KB

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