3
0

dhcpc.c 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * udhcp client
  4. *
  5. * Russ Dill <Russ.Dill@asu.edu> July 2001
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  20. */
  21. #include <syslog.h>
  22. /* Override ENABLE_FEATURE_PIDFILE - ifupdown needs our pidfile to always exist */
  23. #define WANT_PIDFILE 1
  24. #include "common.h"
  25. #include "dhcpd.h"
  26. #include "dhcpc.h"
  27. #include <netinet/if_ether.h>
  28. #include <netpacket/packet.h>
  29. #include <linux/filter.h>
  30. /* "struct client_config_t client_config" is in bb_common_bufsiz1 */
  31. #if ENABLE_LONG_OPTS
  32. static const char udhcpc_longopts[] ALIGN1 =
  33. "clientid-none\0" No_argument "C"
  34. "vendorclass\0" Required_argument "V"
  35. "hostname\0" Required_argument "H"
  36. "fqdn\0" Required_argument "F"
  37. "interface\0" Required_argument "i"
  38. "now\0" No_argument "n"
  39. "pidfile\0" Required_argument "p"
  40. "quit\0" No_argument "q"
  41. "release\0" No_argument "R"
  42. "request\0" Required_argument "r"
  43. "script\0" Required_argument "s"
  44. "timeout\0" Required_argument "T"
  45. "retries\0" Required_argument "t"
  46. "tryagain\0" Required_argument "A"
  47. "syslog\0" No_argument "S"
  48. "request-option\0" Required_argument "O"
  49. "no-default-options\0" No_argument "o"
  50. "foreground\0" No_argument "f"
  51. "background\0" No_argument "b"
  52. "broadcast\0" No_argument "B"
  53. IF_FEATURE_UDHCPC_ARPING("arping\0" No_argument "a")
  54. IF_FEATURE_UDHCP_PORT("client-port\0" Required_argument "P")
  55. ;
  56. #endif
  57. /* Must match getopt32 option string order */
  58. enum {
  59. OPT_C = 1 << 0,
  60. OPT_V = 1 << 1,
  61. OPT_H = 1 << 2,
  62. OPT_h = 1 << 3,
  63. OPT_F = 1 << 4,
  64. OPT_i = 1 << 5,
  65. OPT_n = 1 << 6,
  66. OPT_p = 1 << 7,
  67. OPT_q = 1 << 8,
  68. OPT_R = 1 << 9,
  69. OPT_r = 1 << 10,
  70. OPT_s = 1 << 11,
  71. OPT_T = 1 << 12,
  72. OPT_t = 1 << 13,
  73. OPT_S = 1 << 14,
  74. OPT_A = 1 << 15,
  75. OPT_O = 1 << 16,
  76. OPT_o = 1 << 17,
  77. OPT_x = 1 << 18,
  78. OPT_f = 1 << 19,
  79. OPT_B = 1 << 20,
  80. /* The rest has variable bit positions, need to be clever */
  81. OPTBIT_B = 20,
  82. USE_FOR_MMU( OPTBIT_b,)
  83. IF_FEATURE_UDHCPC_ARPING(OPTBIT_a,)
  84. IF_FEATURE_UDHCP_PORT( OPTBIT_P,)
  85. USE_FOR_MMU( OPT_b = 1 << OPTBIT_b,)
  86. IF_FEATURE_UDHCPC_ARPING(OPT_a = 1 << OPTBIT_a,)
  87. IF_FEATURE_UDHCP_PORT( OPT_P = 1 << OPTBIT_P,)
  88. };
  89. /*** Script execution code ***/
  90. /* get a rough idea of how long an option will be (rounding up...) */
  91. static const uint8_t len_of_option_as_string[] = {
  92. [OPTION_IP ] = sizeof("255.255.255.255 "),
  93. [OPTION_IP_PAIR ] = sizeof("255.255.255.255 ") * 2,
  94. [OPTION_STATIC_ROUTES ] = sizeof("255.255.255.255/32 255.255.255.255 "),
  95. [OPTION_6RD ] = sizeof("32 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
  96. [OPTION_STRING ] = 1,
  97. [OPTION_STRING_HOST ] = 1,
  98. #if ENABLE_FEATURE_UDHCP_RFC3397
  99. [OPTION_DNS_STRING ] = 1, /* unused */
  100. /* Hmmm, this severely overestimates size if SIP_SERVERS option
  101. * is in domain name form: N-byte option in binary form
  102. * mallocs ~16*N bytes. But it is freed almost at once.
  103. */
  104. [OPTION_SIP_SERVERS ] = sizeof("255.255.255.255 "),
  105. #endif
  106. // [OPTION_BOOLEAN ] = sizeof("yes "),
  107. [OPTION_U8 ] = sizeof("255 "),
  108. [OPTION_U16 ] = sizeof("65535 "),
  109. // [OPTION_S16 ] = sizeof("-32768 "),
  110. [OPTION_U32 ] = sizeof("4294967295 "),
  111. [OPTION_S32 ] = sizeof("-2147483684 "),
  112. };
  113. /* note: ip is a pointer to an IP in network order, possibly misaliged */
  114. static int sprint_nip(char *dest, const char *pre, const uint8_t *ip)
  115. {
  116. return sprintf(dest, "%s%u.%u.%u.%u", pre, ip[0], ip[1], ip[2], ip[3]);
  117. }
  118. /* really simple implementation, just count the bits */
  119. static int mton(uint32_t mask)
  120. {
  121. int i = 0;
  122. mask = ntohl(mask); /* 111110000-like bit pattern */
  123. while (mask) {
  124. i++;
  125. mask <<= 1;
  126. }
  127. return i;
  128. }
  129. /* Check if a given label represents a valid DNS label
  130. * Return pointer to the first character after the label upon success,
  131. * NULL otherwise.
  132. * See RFC1035, 2.3.1
  133. */
  134. /* We don't need to be particularly anal. For example, allowing _, hyphen
  135. * at the end, or leading and trailing dots would be ok, since it
  136. * can't be used for attacks. (Leading hyphen can be, if someone uses
  137. * cmd "$hostname"
  138. * in the script: then hostname may be treated as an option)
  139. */
  140. static const char *valid_domain_label(const char *label)
  141. {
  142. unsigned char ch;
  143. unsigned pos = 0;
  144. for (;;) {
  145. ch = *label;
  146. if ((ch|0x20) < 'a' || (ch|0x20) > 'z') {
  147. if (pos == 0) {
  148. /* label must begin with letter */
  149. return NULL;
  150. }
  151. if (ch < '0' || ch > '9') {
  152. if (ch == '\0' || ch == '.')
  153. return label;
  154. /* DNS allows only '-', but we are more permissive */
  155. if (ch != '-' && ch != '_')
  156. return NULL;
  157. }
  158. }
  159. label++;
  160. pos++;
  161. //Do we want this?
  162. //if (pos > 63) /* NS_MAXLABEL; labels must be 63 chars or less */
  163. // return NULL;
  164. }
  165. }
  166. /* Check if a given name represents a valid DNS name */
  167. /* See RFC1035, 2.3.1 */
  168. static int good_hostname(const char *name)
  169. {
  170. //const char *start = name;
  171. for (;;) {
  172. name = valid_domain_label(name);
  173. if (!name)
  174. return 0;
  175. if (!name[0])
  176. return 1;
  177. //Do we want this?
  178. //return ((name - start) < 1025); /* NS_MAXDNAME */
  179. name++;
  180. }
  181. }
  182. /* Create "opt_name=opt_value" string */
  183. static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_optflag *optflag, const char *opt_name)
  184. {
  185. unsigned upper_length;
  186. int len, type, optlen;
  187. char *dest, *ret;
  188. /* option points to OPT_DATA, need to go back to get OPT_LEN */
  189. len = option[-OPT_DATA + OPT_LEN];
  190. type = optflag->flags & OPTION_TYPE_MASK;
  191. optlen = dhcp_option_lengths[type];
  192. upper_length = len_of_option_as_string[type]
  193. * ((unsigned)(len + optlen - 1) / (unsigned)optlen);
  194. dest = ret = xmalloc(upper_length + strlen(opt_name) + 2);
  195. dest += sprintf(ret, "%s=", opt_name);
  196. while (len >= optlen) {
  197. switch (type) {
  198. case OPTION_IP:
  199. case OPTION_IP_PAIR:
  200. dest += sprint_nip(dest, "", option);
  201. if (type == OPTION_IP)
  202. break;
  203. dest += sprint_nip(dest, "/", option + 4);
  204. break;
  205. // case OPTION_BOOLEAN:
  206. // dest += sprintf(dest, *option ? "yes" : "no");
  207. // break;
  208. case OPTION_U8:
  209. dest += sprintf(dest, "%u", *option);
  210. break;
  211. // case OPTION_S16:
  212. case OPTION_U16: {
  213. uint16_t val_u16;
  214. move_from_unaligned16(val_u16, option);
  215. dest += sprintf(dest, "%u", ntohs(val_u16));
  216. break;
  217. }
  218. case OPTION_S32:
  219. case OPTION_U32: {
  220. uint32_t val_u32;
  221. move_from_unaligned32(val_u32, option);
  222. dest += sprintf(dest, type == OPTION_U32 ? "%lu" : "%ld", (unsigned long) ntohl(val_u32));
  223. break;
  224. }
  225. /* Note: options which use 'return' instead of 'break'
  226. * (for example, OPTION_STRING) skip the code which handles
  227. * the case of list of options.
  228. */
  229. case OPTION_STRING:
  230. case OPTION_STRING_HOST:
  231. memcpy(dest, option, len);
  232. dest[len] = '\0';
  233. if (type == OPTION_STRING_HOST && !good_hostname(dest))
  234. safe_strncpy(dest, "bad", len);
  235. return ret;
  236. case OPTION_STATIC_ROUTES: {
  237. /* Option binary format:
  238. * mask [one byte, 0..32]
  239. * ip [big endian, 0..4 bytes depending on mask]
  240. * router [big endian, 4 bytes]
  241. * may be repeated
  242. *
  243. * We convert it to a string "IP/MASK ROUTER IP2/MASK2 ROUTER2"
  244. */
  245. const char *pfx = "";
  246. while (len >= 1 + 4) { /* mask + 0-byte ip + router */
  247. uint32_t nip;
  248. uint8_t *p;
  249. unsigned mask;
  250. int bytes;
  251. mask = *option++;
  252. if (mask > 32)
  253. break;
  254. len--;
  255. nip = 0;
  256. p = (void*) &nip;
  257. bytes = (mask + 7) / 8; /* 0 -> 0, 1..8 -> 1, 9..16 -> 2 etc */
  258. while (--bytes >= 0) {
  259. *p++ = *option++;
  260. len--;
  261. }
  262. if (len < 4)
  263. break;
  264. /* print ip/mask */
  265. dest += sprint_nip(dest, pfx, (void*) &nip);
  266. pfx = " ";
  267. dest += sprintf(dest, "/%u ", mask);
  268. /* print router */
  269. dest += sprint_nip(dest, "", option);
  270. option += 4;
  271. len -= 4;
  272. }
  273. return ret;
  274. }
  275. case OPTION_6RD:
  276. /* Option binary format (see RFC 5969):
  277. * 0 1 2 3
  278. * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
  279. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  280. * | OPTION_6RD | option-length | IPv4MaskLen | 6rdPrefixLen |
  281. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  282. * | 6rdPrefix |
  283. * ... (16 octets) ...
  284. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  285. * ... 6rdBRIPv4Address(es) ...
  286. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  287. * We convert it to a string
  288. * "IPv4MaskLen 6rdPrefixLen 6rdPrefix 6rdBRIPv4Address..."
  289. *
  290. * Sanity check: ensure that our length is at least 22 bytes, that
  291. * IPv4MaskLen <= 32,
  292. * 6rdPrefixLen <= 128,
  293. * 6rdPrefixLen + (32 - IPv4MaskLen) <= 128
  294. * (2nd condition need no check - it follows from 1st and 3rd).
  295. * Else, return envvar with empty value ("optname=")
  296. */
  297. if (len >= (1 + 1 + 16 + 4)
  298. && option[0] <= 32
  299. && (option[1] + 32 - option[0]) <= 128
  300. ) {
  301. /* IPv4MaskLen */
  302. dest += sprintf(dest, "%u ", *option++);
  303. /* 6rdPrefixLen */
  304. dest += sprintf(dest, "%u ", *option++);
  305. /* 6rdPrefix */
  306. dest += sprint_nip6(dest, /* "", */ option);
  307. option += 16;
  308. len -= 1 + 1 + 16 + 4;
  309. /* "+ 4" above corresponds to the length of IPv4 addr
  310. * we consume in the loop below */
  311. while (1) {
  312. /* 6rdBRIPv4Address(es) */
  313. dest += sprint_nip(dest, " ", option);
  314. option += 4;
  315. len -= 4; /* do we have yet another 4+ bytes? */
  316. if (len < 0)
  317. break; /* no */
  318. }
  319. }
  320. return ret;
  321. #if ENABLE_FEATURE_UDHCP_RFC3397
  322. case OPTION_DNS_STRING:
  323. /* unpack option into dest; use ret for prefix (i.e., "optname=") */
  324. dest = dname_dec(option, len, ret);
  325. if (dest) {
  326. free(ret);
  327. return dest;
  328. }
  329. /* error. return "optname=" string */
  330. return ret;
  331. case OPTION_SIP_SERVERS:
  332. /* Option binary format:
  333. * type: byte
  334. * type=0: domain names, dns-compressed
  335. * type=1: IP addrs
  336. */
  337. option++;
  338. len--;
  339. if (option[-1] == 0) {
  340. dest = dname_dec(option, len, ret);
  341. if (dest) {
  342. free(ret);
  343. return dest;
  344. }
  345. } else
  346. if (option[-1] == 1) {
  347. const char *pfx = "";
  348. while (1) {
  349. len -= 4;
  350. if (len < 0)
  351. break;
  352. dest += sprint_nip(dest, pfx, option);
  353. pfx = " ";
  354. option += 4;
  355. }
  356. }
  357. return ret;
  358. #endif
  359. } /* switch */
  360. /* If we are here, try to format any remaining data
  361. * in the option as another, similarly-formatted option
  362. */
  363. option += optlen;
  364. len -= optlen;
  365. // TODO: it can be a list only if (optflag->flags & OPTION_LIST).
  366. // Should we bail out/warn if we see multi-ip option which is
  367. // not allowed to be such (for example, DHCP_BROADCAST)? -
  368. if (len < optlen /* || !(optflag->flags & OPTION_LIST) */)
  369. break;
  370. *dest++ = ' ';
  371. *dest = '\0';
  372. } /* while */
  373. return ret;
  374. }
  375. /* put all the parameters into the environment */
  376. static char **fill_envp(struct dhcp_packet *packet)
  377. {
  378. int envc;
  379. int i;
  380. char **envp, **curr;
  381. const char *opt_name;
  382. uint8_t *temp;
  383. uint8_t overload = 0;
  384. #define BITMAP unsigned
  385. #define BBITS (sizeof(BITMAP) * 8)
  386. #define BMASK(i) (1 << (i & (sizeof(BITMAP) * 8 - 1)))
  387. #define FOUND_OPTS(i) (found_opts[(unsigned)i / BBITS])
  388. BITMAP found_opts[256 / BBITS];
  389. memset(found_opts, 0, sizeof(found_opts));
  390. /* We need 6 elements for:
  391. * "interface=IFACE"
  392. * "ip=N.N.N.N" from packet->yiaddr
  393. * "siaddr=IP" from packet->siaddr_nip (unless 0)
  394. * "boot_file=FILE" from packet->file (unless overloaded)
  395. * "sname=SERVER_HOSTNAME" from packet->sname (unless overloaded)
  396. * terminating NULL
  397. */
  398. envc = 6;
  399. /* +1 element for each option, +2 for subnet option: */
  400. if (packet) {
  401. /* note: do not search for "pad" (0) and "end" (255) options */
  402. //TODO: change logic to scan packet _once_
  403. for (i = 1; i < 255; i++) {
  404. temp = udhcp_get_option(packet, i);
  405. if (temp) {
  406. if (i == DHCP_OPTION_OVERLOAD)
  407. overload = *temp;
  408. else if (i == DHCP_SUBNET)
  409. envc++; /* for $mask */
  410. envc++;
  411. /*if (i != DHCP_MESSAGE_TYPE)*/
  412. FOUND_OPTS(i) |= BMASK(i);
  413. }
  414. }
  415. }
  416. curr = envp = xzalloc(sizeof(envp[0]) * envc);
  417. *curr = xasprintf("interface=%s", client_config.interface);
  418. putenv(*curr++);
  419. if (!packet)
  420. return envp;
  421. /* Export BOOTP fields. Fields we don't (yet?) export:
  422. * uint8_t op; // always BOOTREPLY
  423. * uint8_t htype; // hardware address type. 1 = 10mb ethernet
  424. * uint8_t hlen; // hardware address length
  425. * uint8_t hops; // used by relay agents only
  426. * uint32_t xid;
  427. * uint16_t secs; // elapsed since client began acquisition/renewal
  428. * uint16_t flags; // only one flag so far: bcast. Never set by server
  429. * uint32_t ciaddr; // client IP (usually == yiaddr. can it be different
  430. * // if during renew server wants to give us differn IP?)
  431. * uint32_t gateway_nip; // relay agent IP address
  432. * uint8_t chaddr[16]; // link-layer client hardware address (MAC)
  433. * TODO: export gateway_nip as $giaddr?
  434. */
  435. /* Most important one: yiaddr as $ip */
  436. *curr = xmalloc(sizeof("ip=255.255.255.255"));
  437. sprint_nip(*curr, "ip=", (uint8_t *) &packet->yiaddr);
  438. putenv(*curr++);
  439. if (packet->siaddr_nip) {
  440. /* IP address of next server to use in bootstrap */
  441. *curr = xmalloc(sizeof("siaddr=255.255.255.255"));
  442. sprint_nip(*curr, "siaddr=", (uint8_t *) &packet->siaddr_nip);
  443. putenv(*curr++);
  444. }
  445. if (!(overload & FILE_FIELD) && packet->file[0]) {
  446. /* watch out for invalid packets */
  447. *curr = xasprintf("boot_file=%."DHCP_PKT_FILE_LEN_STR"s", packet->file);
  448. putenv(*curr++);
  449. }
  450. if (!(overload & SNAME_FIELD) && packet->sname[0]) {
  451. /* watch out for invalid packets */
  452. *curr = xasprintf("sname=%."DHCP_PKT_SNAME_LEN_STR"s", packet->sname);
  453. putenv(*curr++);
  454. }
  455. /* Export known DHCP options */
  456. opt_name = dhcp_option_strings;
  457. i = 0;
  458. while (*opt_name) {
  459. uint8_t code = dhcp_optflags[i].code;
  460. BITMAP *found_ptr = &FOUND_OPTS(code);
  461. BITMAP found_mask = BMASK(code);
  462. if (!(*found_ptr & found_mask))
  463. goto next;
  464. *found_ptr &= ~found_mask; /* leave only unknown options */
  465. temp = udhcp_get_option(packet, code);
  466. *curr = xmalloc_optname_optval(temp, &dhcp_optflags[i], opt_name);
  467. putenv(*curr++);
  468. if (code == DHCP_SUBNET) {
  469. /* Subnet option: make things like "$ip/$mask" possible */
  470. uint32_t subnet;
  471. move_from_unaligned32(subnet, temp);
  472. *curr = xasprintf("mask=%u", mton(subnet));
  473. putenv(*curr++);
  474. }
  475. next:
  476. opt_name += strlen(opt_name) + 1;
  477. i++;
  478. }
  479. /* Export unknown options */
  480. for (i = 0; i < 256;) {
  481. BITMAP bitmap = FOUND_OPTS(i);
  482. if (!bitmap) {
  483. i += BBITS;
  484. continue;
  485. }
  486. if (bitmap & BMASK(i)) {
  487. unsigned len, ofs;
  488. temp = udhcp_get_option(packet, i);
  489. /* udhcp_get_option returns ptr to data portion,
  490. * need to go back to get len
  491. */
  492. len = temp[-OPT_DATA + OPT_LEN];
  493. *curr = xmalloc(sizeof("optNNN=") + 1 + len*2);
  494. ofs = sprintf(*curr, "opt%u=", i);
  495. *bin2hex(*curr + ofs, (void*) temp, len) = '\0';
  496. putenv(*curr++);
  497. }
  498. i++;
  499. }
  500. return envp;
  501. }
  502. /* Call a script with a par file and env vars */
  503. static void udhcp_run_script(struct dhcp_packet *packet, const char *name)
  504. {
  505. char **envp, **curr;
  506. char *argv[3];
  507. envp = fill_envp(packet);
  508. /* call script */
  509. log1("Executing %s %s", client_config.script, name);
  510. argv[0] = (char*) client_config.script;
  511. argv[1] = (char*) name;
  512. argv[2] = NULL;
  513. spawn_and_wait(argv);
  514. for (curr = envp; *curr; curr++) {
  515. log2(" %s", *curr);
  516. bb_unsetenv_and_free(*curr);
  517. }
  518. free(envp);
  519. }
  520. /*** Sending/receiving packets ***/
  521. static ALWAYS_INLINE uint32_t random_xid(void)
  522. {
  523. return rand();
  524. }
  525. /* Initialize the packet with the proper defaults */
  526. static void init_packet(struct dhcp_packet *packet, char type)
  527. {
  528. uint16_t secs;
  529. /* Fill in: op, htype, hlen, cookie fields; message type option: */
  530. udhcp_init_header(packet, type);
  531. packet->xid = random_xid();
  532. client_config.last_secs = monotonic_sec();
  533. if (client_config.first_secs == 0)
  534. client_config.first_secs = client_config.last_secs;
  535. secs = client_config.last_secs - client_config.first_secs;
  536. packet->secs = htons(secs);
  537. memcpy(packet->chaddr, client_config.client_mac, 6);
  538. if (client_config.clientid)
  539. udhcp_add_binary_option(packet, client_config.clientid);
  540. }
  541. static void add_client_options(struct dhcp_packet *packet)
  542. {
  543. uint8_t c;
  544. int i, end, len;
  545. udhcp_add_simple_option(packet, DHCP_MAX_SIZE, htons(IP_UDP_DHCP_SIZE));
  546. /* Add a "param req" option with the list of options we'd like to have
  547. * from stubborn DHCP servers. Pull the data from the struct in common.c.
  548. * No bounds checking because it goes towards the head of the packet. */
  549. end = udhcp_end_option(packet->options);
  550. len = 0;
  551. for (i = 0; (c = dhcp_optflags[i].code) != 0; i++) {
  552. if (( (dhcp_optflags[i].flags & OPTION_REQ)
  553. && !client_config.no_default_options
  554. )
  555. || (client_config.opt_mask[c >> 3] & (1 << (c & 7)))
  556. ) {
  557. packet->options[end + OPT_DATA + len] = c;
  558. len++;
  559. }
  560. }
  561. if (len) {
  562. packet->options[end + OPT_CODE] = DHCP_PARAM_REQ;
  563. packet->options[end + OPT_LEN] = len;
  564. packet->options[end + OPT_DATA + len] = DHCP_END;
  565. }
  566. if (client_config.vendorclass)
  567. udhcp_add_binary_option(packet, client_config.vendorclass);
  568. if (client_config.hostname)
  569. udhcp_add_binary_option(packet, client_config.hostname);
  570. if (client_config.fqdn)
  571. udhcp_add_binary_option(packet, client_config.fqdn);
  572. /* Request broadcast replies if we have no IP addr */
  573. if ((option_mask32 & OPT_B) && packet->ciaddr == 0)
  574. packet->flags |= htons(BROADCAST_FLAG);
  575. /* Add -x options if any */
  576. {
  577. struct option_set *curr = client_config.options;
  578. while (curr) {
  579. udhcp_add_binary_option(packet, curr->data);
  580. curr = curr->next;
  581. }
  582. // if (client_config.sname)
  583. // strncpy((char*)packet->sname, client_config.sname, sizeof(packet->sname) - 1);
  584. // if (client_config.boot_file)
  585. // strncpy((char*)packet->file, client_config.boot_file, sizeof(packet->file) - 1);
  586. }
  587. // This will be needed if we remove -V VENDOR_STR in favor of
  588. // -x vendor:VENDOR_STR
  589. //if (!udhcp_find_option(packet.options, DHCP_VENDOR))
  590. // /* not set, set the default vendor ID */
  591. // ...add (DHCP_VENDOR, "udhcp "BB_VER) opt...
  592. }
  593. /* RFC 2131
  594. * 4.4.4 Use of broadcast and unicast
  595. *
  596. * The DHCP client broadcasts DHCPDISCOVER, DHCPREQUEST and DHCPINFORM
  597. * messages, unless the client knows the address of a DHCP server.
  598. * The client unicasts DHCPRELEASE messages to the server. Because
  599. * the client is declining the use of the IP address supplied by the server,
  600. * the client broadcasts DHCPDECLINE messages.
  601. *
  602. * When the DHCP client knows the address of a DHCP server, in either
  603. * INIT or REBOOTING state, the client may use that address
  604. * in the DHCPDISCOVER or DHCPREQUEST rather than the IP broadcast address.
  605. * The client may also use unicast to send DHCPINFORM messages
  606. * to a known DHCP server. If the client receives no response to DHCP
  607. * messages sent to the IP address of a known DHCP server, the DHCP
  608. * client reverts to using the IP broadcast address.
  609. */
  610. static int raw_bcast_from_client_config_ifindex(struct dhcp_packet *packet)
  611. {
  612. return udhcp_send_raw_packet(packet,
  613. /*src*/ INADDR_ANY, CLIENT_PORT,
  614. /*dst*/ INADDR_BROADCAST, SERVER_PORT, MAC_BCAST_ADDR,
  615. client_config.ifindex);
  616. }
  617. /* Broadcast a DHCP discover packet to the network, with an optionally requested IP */
  618. /* NOINLINE: limit stack usage in caller */
  619. static NOINLINE int send_discover(uint32_t xid, uint32_t requested)
  620. {
  621. struct dhcp_packet packet;
  622. /* Fill in: op, htype, hlen, cookie, chaddr fields,
  623. * random xid field (we override it below),
  624. * client-id option (unless -C), message type option:
  625. */
  626. init_packet(&packet, DHCPDISCOVER);
  627. packet.xid = xid;
  628. if (requested)
  629. udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
  630. /* Add options: maxsize,
  631. * optionally: hostname, fqdn, vendorclass,
  632. * "param req" option according to -O, options specified with -x
  633. */
  634. add_client_options(&packet);
  635. bb_info_msg("Sending discover...");
  636. return raw_bcast_from_client_config_ifindex(&packet);
  637. }
  638. /* Broadcast a DHCP request message */
  639. /* RFC 2131 3.1 paragraph 3:
  640. * "The client _broadcasts_ a DHCPREQUEST message..."
  641. */
  642. /* NOINLINE: limit stack usage in caller */
  643. static NOINLINE int send_select(uint32_t xid, uint32_t server, uint32_t requested)
  644. {
  645. struct dhcp_packet packet;
  646. struct in_addr addr;
  647. /*
  648. * RFC 2131 4.3.2 DHCPREQUEST message
  649. * ...
  650. * If the DHCPREQUEST message contains a 'server identifier'
  651. * option, the message is in response to a DHCPOFFER message.
  652. * Otherwise, the message is a request to verify or extend an
  653. * existing lease. If the client uses a 'client identifier'
  654. * in a DHCPREQUEST message, it MUST use that same 'client identifier'
  655. * in all subsequent messages. If the client included a list
  656. * of requested parameters in a DHCPDISCOVER message, it MUST
  657. * include that list in all subsequent messages.
  658. */
  659. /* Fill in: op, htype, hlen, cookie, chaddr fields,
  660. * random xid field (we override it below),
  661. * client-id option (unless -C), message type option:
  662. */
  663. init_packet(&packet, DHCPREQUEST);
  664. packet.xid = xid;
  665. udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
  666. udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
  667. /* Add options: maxsize,
  668. * optionally: hostname, fqdn, vendorclass,
  669. * "param req" option according to -O, and options specified with -x
  670. */
  671. add_client_options(&packet);
  672. addr.s_addr = requested;
  673. bb_info_msg("Sending select for %s...", inet_ntoa(addr));
  674. return raw_bcast_from_client_config_ifindex(&packet);
  675. }
  676. /* Unicast or broadcast a DHCP renew message */
  677. /* NOINLINE: limit stack usage in caller */
  678. static NOINLINE int send_renew(uint32_t xid, uint32_t server, uint32_t ciaddr)
  679. {
  680. struct dhcp_packet packet;
  681. /*
  682. * RFC 2131 4.3.2 DHCPREQUEST message
  683. * ...
  684. * DHCPREQUEST generated during RENEWING state:
  685. *
  686. * 'server identifier' MUST NOT be filled in, 'requested IP address'
  687. * option MUST NOT be filled in, 'ciaddr' MUST be filled in with
  688. * client's IP address. In this situation, the client is completely
  689. * configured, and is trying to extend its lease. This message will
  690. * be unicast, so no relay agents will be involved in its
  691. * transmission. Because 'giaddr' is therefore not filled in, the
  692. * DHCP server will trust the value in 'ciaddr', and use it when
  693. * replying to the client.
  694. */
  695. /* Fill in: op, htype, hlen, cookie, chaddr fields,
  696. * random xid field (we override it below),
  697. * client-id option (unless -C), message type option:
  698. */
  699. init_packet(&packet, DHCPREQUEST);
  700. packet.xid = xid;
  701. packet.ciaddr = ciaddr;
  702. /* Add options: maxsize,
  703. * optionally: hostname, fqdn, vendorclass,
  704. * "param req" option according to -O, and options specified with -x
  705. */
  706. add_client_options(&packet);
  707. bb_info_msg("Sending renew...");
  708. if (server)
  709. return udhcp_send_kernel_packet(&packet,
  710. ciaddr, CLIENT_PORT,
  711. server, SERVER_PORT);
  712. return raw_bcast_from_client_config_ifindex(&packet);
  713. }
  714. #if ENABLE_FEATURE_UDHCPC_ARPING
  715. /* Broadcast a DHCP decline message */
  716. /* NOINLINE: limit stack usage in caller */
  717. static NOINLINE int send_decline(/*uint32_t xid,*/ uint32_t server, uint32_t requested)
  718. {
  719. struct dhcp_packet packet;
  720. /* Fill in: op, htype, hlen, cookie, chaddr, random xid fields,
  721. * client-id option (unless -C), message type option:
  722. */
  723. init_packet(&packet, DHCPDECLINE);
  724. #if 0
  725. /* RFC 2131 says DHCPDECLINE's xid is randomly selected by client,
  726. * but in case the server is buggy and wants DHCPDECLINE's xid
  727. * to match the xid which started entire handshake,
  728. * we use the same xid we used in initial DHCPDISCOVER:
  729. */
  730. packet.xid = xid;
  731. #endif
  732. /* DHCPDECLINE uses "requested ip", not ciaddr, to store offered IP */
  733. udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
  734. udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
  735. bb_info_msg("Sending decline...");
  736. return raw_bcast_from_client_config_ifindex(&packet);
  737. }
  738. #endif
  739. /* Unicast a DHCP release message */
  740. static int send_release(uint32_t server, uint32_t ciaddr)
  741. {
  742. struct dhcp_packet packet;
  743. /* Fill in: op, htype, hlen, cookie, chaddr, random xid fields,
  744. * client-id option (unless -C), message type option:
  745. */
  746. init_packet(&packet, DHCPRELEASE);
  747. /* DHCPRELEASE uses ciaddr, not "requested ip", to store IP being released */
  748. packet.ciaddr = ciaddr;
  749. udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
  750. bb_info_msg("Sending release...");
  751. return udhcp_send_kernel_packet(&packet, ciaddr, CLIENT_PORT, server, SERVER_PORT);
  752. }
  753. /* Returns -1 on errors that are fatal for the socket, -2 for those that aren't */
  754. /* NOINLINE: limit stack usage in caller */
  755. static NOINLINE int udhcp_recv_raw_packet(struct dhcp_packet *dhcp_pkt, int fd)
  756. {
  757. int bytes;
  758. struct ip_udp_dhcp_packet packet;
  759. uint16_t check;
  760. bytes = safe_read(fd, &packet, sizeof(packet));
  761. if (bytes < 0) {
  762. log1("Packet read error, ignoring");
  763. /* NB: possible down interface, etc. Caller should pause. */
  764. return bytes; /* returns -1 */
  765. }
  766. if (bytes < (int) (sizeof(packet.ip) + sizeof(packet.udp))) {
  767. log1("Packet is too short, ignoring");
  768. return -2;
  769. }
  770. if (bytes < ntohs(packet.ip.tot_len)) {
  771. /* packet is bigger than sizeof(packet), we did partial read */
  772. log1("Oversized packet, ignoring");
  773. return -2;
  774. }
  775. /* ignore any extra garbage bytes */
  776. bytes = ntohs(packet.ip.tot_len);
  777. /* make sure its the right packet for us, and that it passes sanity checks */
  778. if (packet.ip.protocol != IPPROTO_UDP
  779. || packet.ip.version != IPVERSION
  780. || packet.ip.ihl != (sizeof(packet.ip) >> 2)
  781. || packet.udp.dest != htons(CLIENT_PORT)
  782. /* || bytes > (int) sizeof(packet) - can't happen */
  783. || ntohs(packet.udp.len) != (uint16_t)(bytes - sizeof(packet.ip))
  784. ) {
  785. log1("Unrelated/bogus packet, ignoring");
  786. return -2;
  787. }
  788. /* verify IP checksum */
  789. check = packet.ip.check;
  790. packet.ip.check = 0;
  791. if (check != inet_cksum((uint16_t *)&packet.ip, sizeof(packet.ip))) {
  792. log1("Bad IP header checksum, ignoring");
  793. return -2;
  794. }
  795. /* verify UDP checksum. IP header has to be modified for this */
  796. memset(&packet.ip, 0, offsetof(struct iphdr, protocol));
  797. /* ip.xx fields which are not memset: protocol, check, saddr, daddr */
  798. packet.ip.tot_len = packet.udp.len; /* yes, this is needed */
  799. check = packet.udp.check;
  800. packet.udp.check = 0;
  801. if (check && check != inet_cksum((uint16_t *)&packet, bytes)) {
  802. log1("Packet with bad UDP checksum received, ignoring");
  803. return -2;
  804. }
  805. if (packet.data.cookie != htonl(DHCP_MAGIC)) {
  806. bb_info_msg("Packet with bad magic, ignoring");
  807. return -2;
  808. }
  809. log1("Received a packet");
  810. udhcp_dump_packet(&packet.data);
  811. bytes -= sizeof(packet.ip) + sizeof(packet.udp);
  812. memcpy(dhcp_pkt, &packet.data, bytes);
  813. return bytes;
  814. }
  815. /*** Main ***/
  816. static int sockfd = -1;
  817. #define LISTEN_NONE 0
  818. #define LISTEN_KERNEL 1
  819. #define LISTEN_RAW 2
  820. static smallint listen_mode;
  821. /* initial state: (re)start DHCP negotiation */
  822. #define INIT_SELECTING 0
  823. /* discover was sent, DHCPOFFER reply received */
  824. #define REQUESTING 1
  825. /* select/renew was sent, DHCPACK reply received */
  826. #define BOUND 2
  827. /* half of lease passed, want to renew it by sending unicast renew requests */
  828. #define RENEWING 3
  829. /* renew requests were not answered, lease is almost over, send broadcast renew */
  830. #define REBINDING 4
  831. /* manually requested renew (SIGUSR1) */
  832. #define RENEW_REQUESTED 5
  833. /* release, possibly manually requested (SIGUSR2) */
  834. #define RELEASED 6
  835. static smallint state;
  836. static int udhcp_raw_socket(int ifindex)
  837. {
  838. int fd;
  839. struct sockaddr_ll sock;
  840. /*
  841. * Comment:
  842. *
  843. * I've selected not to see LL header, so BPF doesn't see it, too.
  844. * The filter may also pass non-IP and non-ARP packets, but we do
  845. * a more complete check when receiving the message in userspace.
  846. *
  847. * and filter shamelessly stolen from:
  848. *
  849. * http://www.flamewarmaster.de/software/dhcpclient/
  850. *
  851. * There are a few other interesting ideas on that page (look under
  852. * "Motivation"). Use of netlink events is most interesting. Think
  853. * of various network servers listening for events and reconfiguring.
  854. * That would obsolete sending HUP signals and/or make use of restarts.
  855. *
  856. * Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
  857. * License: GPL v2.
  858. *
  859. * TODO: make conditional?
  860. */
  861. static const struct sock_filter filter_instr[] = {
  862. /* load 9th byte (protocol) */
  863. BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
  864. /* jump to L1 if it is IPPROTO_UDP, else to L4 */
  865. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 0, 6),
  866. /* L1: load halfword from offset 6 (flags and frag offset) */
  867. BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 6),
  868. /* jump to L4 if any bits in frag offset field are set, else to L2 */
  869. BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K, 0x1fff, 4, 0),
  870. /* L2: skip IP header (load index reg with header len) */
  871. BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0),
  872. /* load udp destination port from halfword[header_len + 2] */
  873. BPF_STMT(BPF_LD|BPF_H|BPF_IND, 2),
  874. /* jump to L3 if udp dport is CLIENT_PORT, else to L4 */
  875. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 68, 0, 1),
  876. /* L3: accept packet */
  877. BPF_STMT(BPF_RET|BPF_K, 0xffffffff),
  878. /* L4: discard packet */
  879. BPF_STMT(BPF_RET|BPF_K, 0),
  880. };
  881. static const struct sock_fprog filter_prog = {
  882. .len = sizeof(filter_instr) / sizeof(filter_instr[0]),
  883. /* casting const away: */
  884. .filter = (struct sock_filter *) filter_instr,
  885. };
  886. log1("Opening raw socket on ifindex %d", ifindex); //log2?
  887. fd = xsocket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP));
  888. log1("Got raw socket fd %d", fd); //log2?
  889. sock.sll_family = AF_PACKET;
  890. sock.sll_protocol = htons(ETH_P_IP);
  891. sock.sll_ifindex = ifindex;
  892. xbind(fd, (struct sockaddr *) &sock, sizeof(sock));
  893. if (CLIENT_PORT == 68) {
  894. /* Use only if standard port is in use */
  895. /* Ignoring error (kernel may lack support for this) */
  896. if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog,
  897. sizeof(filter_prog)) >= 0)
  898. log1("Attached filter to raw socket fd %d", fd); // log?
  899. }
  900. log1("Created raw socket");
  901. return fd;
  902. }
  903. static void change_listen_mode(int new_mode)
  904. {
  905. log1("Entering listen mode: %s",
  906. new_mode != LISTEN_NONE
  907. ? (new_mode == LISTEN_KERNEL ? "kernel" : "raw")
  908. : "none"
  909. );
  910. listen_mode = new_mode;
  911. if (sockfd >= 0) {
  912. close(sockfd);
  913. sockfd = -1;
  914. }
  915. if (new_mode == LISTEN_KERNEL)
  916. sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT, client_config.interface);
  917. else if (new_mode != LISTEN_NONE)
  918. sockfd = udhcp_raw_socket(client_config.ifindex);
  919. /* else LISTEN_NONE: sockfd stays closed */
  920. }
  921. /* Called only on SIGUSR1 */
  922. static void perform_renew(void)
  923. {
  924. bb_info_msg("Performing a DHCP renew");
  925. switch (state) {
  926. case BOUND:
  927. change_listen_mode(LISTEN_KERNEL);
  928. case RENEWING:
  929. case REBINDING:
  930. state = RENEW_REQUESTED;
  931. break;
  932. case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
  933. udhcp_run_script(NULL, "deconfig");
  934. case REQUESTING:
  935. case RELEASED:
  936. change_listen_mode(LISTEN_RAW);
  937. state = INIT_SELECTING;
  938. break;
  939. case INIT_SELECTING:
  940. break;
  941. }
  942. }
  943. static void perform_release(uint32_t server_addr, uint32_t requested_ip)
  944. {
  945. char buffer[sizeof("255.255.255.255")];
  946. struct in_addr temp_addr;
  947. /* send release packet */
  948. if (state == BOUND || state == RENEWING || state == REBINDING) {
  949. temp_addr.s_addr = server_addr;
  950. strcpy(buffer, inet_ntoa(temp_addr));
  951. temp_addr.s_addr = requested_ip;
  952. bb_info_msg("Unicasting a release of %s to %s",
  953. inet_ntoa(temp_addr), buffer);
  954. send_release(server_addr, requested_ip); /* unicast */
  955. udhcp_run_script(NULL, "deconfig");
  956. }
  957. bb_info_msg("Entering released state");
  958. change_listen_mode(LISTEN_NONE);
  959. state = RELEASED;
  960. }
  961. static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
  962. {
  963. uint8_t *storage;
  964. int len = strnlen(str, 255);
  965. storage = xzalloc(len + extra + OPT_DATA);
  966. storage[OPT_CODE] = code;
  967. storage[OPT_LEN] = len + extra;
  968. memcpy(storage + extra + OPT_DATA, str, len);
  969. return storage;
  970. }
  971. #if BB_MMU
  972. static void client_background(void)
  973. {
  974. bb_daemonize(0);
  975. logmode &= ~LOGMODE_STDIO;
  976. /* rewrite pidfile, as our pid is different now */
  977. write_pidfile(client_config.pidfile);
  978. }
  979. #endif
  980. //usage:#if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
  981. //usage:# define IF_UDHCP_VERBOSE(...) __VA_ARGS__
  982. //usage:#else
  983. //usage:# define IF_UDHCP_VERBOSE(...)
  984. //usage:#endif
  985. //usage:#define udhcpc_trivial_usage
  986. //usage: "[-fbnq"IF_UDHCP_VERBOSE("v")"oCRB] [-i IFACE] [-r IP] [-s PROG] [-p PIDFILE]\n"
  987. //usage: " [-V VENDOR] [-x OPT:VAL]... [-O OPT]..." IF_FEATURE_UDHCP_PORT(" [-P N]")
  988. //usage:#define udhcpc_full_usage "\n"
  989. //usage: IF_LONG_OPTS(
  990. //usage: "\n -i,--interface IFACE Interface to use (default eth0)"
  991. //usage: "\n -p,--pidfile FILE Create pidfile"
  992. //usage: "\n -s,--script PROG Run PROG at DHCP events (default "CONFIG_UDHCPC_DEFAULT_SCRIPT")"
  993. //usage: "\n -B,--broadcast Request broadcast replies"
  994. //usage: "\n -t,--retries N Send up to N discover packets"
  995. //usage: "\n -T,--timeout N Pause between packets (default 3 seconds)"
  996. //usage: "\n -A,--tryagain N Wait N seconds after failure (default 20)"
  997. //usage: "\n -f,--foreground Run in foreground"
  998. //usage: USE_FOR_MMU(
  999. //usage: "\n -b,--background Background if lease is not obtained"
  1000. //usage: )
  1001. //usage: "\n -n,--now Exit if lease is not obtained"
  1002. //usage: "\n -q,--quit Exit after obtaining lease"
  1003. //usage: "\n -R,--release Release IP on exit"
  1004. //usage: "\n -S,--syslog Log to syslog too"
  1005. //usage: IF_FEATURE_UDHCP_PORT(
  1006. //usage: "\n -P,--client-port N Use port N (default 68)"
  1007. //usage: )
  1008. //usage: IF_FEATURE_UDHCPC_ARPING(
  1009. //usage: "\n -a,--arping Use arping to validate offered address"
  1010. //usage: )
  1011. //usage: "\n -O,--request-option OPT Request option OPT from server (cumulative)"
  1012. //usage: "\n -o,--no-default-options Don't request any options (unless -O is given)"
  1013. //usage: "\n -r,--request IP Request this IP address"
  1014. //usage: "\n -x OPT:VAL Include option OPT in sent packets (cumulative)"
  1015. //usage: "\n Examples of string, numeric, and hex byte opts:"
  1016. //usage: "\n -x hostname:bbox - option 12"
  1017. //usage: "\n -x lease:3600 - option 51 (lease time)"
  1018. //usage: "\n -x 0x3d:0100BEEFC0FFEE - option 61 (client id)"
  1019. //usage: "\n -F,--fqdn NAME Ask server to update DNS mapping for NAME"
  1020. //usage: "\n -V,--vendorclass VENDOR Vendor identifier (default 'udhcp VERSION')"
  1021. //usage: "\n -C,--clientid-none Don't send MAC as client identifier"
  1022. //usage: IF_UDHCP_VERBOSE(
  1023. //usage: "\n -v Verbose"
  1024. //usage: )
  1025. //usage: )
  1026. //usage: IF_NOT_LONG_OPTS(
  1027. //usage: "\n -i IFACE Interface to use (default eth0)"
  1028. //usage: "\n -p FILE Create pidfile"
  1029. //usage: "\n -s PROG Run PROG at DHCP events (default "CONFIG_UDHCPC_DEFAULT_SCRIPT")"
  1030. //usage: "\n -B Request broadcast replies"
  1031. //usage: "\n -t N Send up to N discover packets"
  1032. //usage: "\n -T N Pause between packets (default 3 seconds)"
  1033. //usage: "\n -A N Wait N seconds (default 20) after failure"
  1034. //usage: "\n -f Run in foreground"
  1035. //usage: USE_FOR_MMU(
  1036. //usage: "\n -b Background if lease is not obtained"
  1037. //usage: )
  1038. //usage: "\n -n Exit if lease is not obtained"
  1039. //usage: "\n -q Exit after obtaining lease"
  1040. //usage: "\n -R Release IP on exit"
  1041. //usage: "\n -S Log to syslog too"
  1042. //usage: IF_FEATURE_UDHCP_PORT(
  1043. //usage: "\n -P N Use port N (default 68)"
  1044. //usage: )
  1045. //usage: IF_FEATURE_UDHCPC_ARPING(
  1046. //usage: "\n -a Use arping to validate offered address"
  1047. //usage: )
  1048. //usage: "\n -O OPT Request option OPT from server (cumulative)"
  1049. //usage: "\n -o Don't request any options (unless -O is given)"
  1050. //usage: "\n -r IP Request this IP address"
  1051. //usage: "\n -x OPT:VAL Include option OPT in sent packets (cumulative)"
  1052. //usage: "\n Examples of string, numeric, and hex byte opts:"
  1053. //usage: "\n -x hostname:bbox - option 12"
  1054. //usage: "\n -x lease:3600 - option 51 (lease time)"
  1055. //usage: "\n -x 0x3d:0100BEEFC0FFEE - option 61 (client id)"
  1056. //usage: "\n -F NAME Ask server to update DNS mapping for NAME"
  1057. //usage: "\n -V VENDOR Vendor identifier (default 'udhcp VERSION')"
  1058. //usage: "\n -C Don't send MAC as client identifier"
  1059. //usage: IF_UDHCP_VERBOSE(
  1060. //usage: "\n -v Verbose"
  1061. //usage: )
  1062. //usage: )
  1063. //usage: "\nSignals:"
  1064. //usage: "\n USR1 Renew lease"
  1065. //usage: "\n USR2 Release lease"
  1066. int udhcpc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1067. int udhcpc_main(int argc UNUSED_PARAM, char **argv)
  1068. {
  1069. uint8_t *temp, *message;
  1070. const char *str_V, *str_h, *str_F, *str_r;
  1071. IF_FEATURE_UDHCP_PORT(char *str_P;)
  1072. void *clientid_mac_ptr;
  1073. llist_t *list_O = NULL;
  1074. llist_t *list_x = NULL;
  1075. int tryagain_timeout = 20;
  1076. int discover_timeout = 3;
  1077. int discover_retries = 3;
  1078. uint32_t server_addr = server_addr; /* for compiler */
  1079. uint32_t requested_ip = 0;
  1080. uint32_t xid = xid; /* for compiler */
  1081. int packet_num;
  1082. int timeout; /* must be signed */
  1083. unsigned already_waited_sec;
  1084. unsigned opt;
  1085. int max_fd;
  1086. int retval;
  1087. fd_set rfds;
  1088. /* Default options */
  1089. IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;)
  1090. IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;)
  1091. client_config.interface = "eth0";
  1092. client_config.script = CONFIG_UDHCPC_DEFAULT_SCRIPT;
  1093. str_V = "udhcp "BB_VER;
  1094. /* Parse command line */
  1095. /* O,x: list; -T,-t,-A take numeric param */
  1096. opt_complementary = "O::x::T+:t+:A+" IF_UDHCP_VERBOSE(":vv") ;
  1097. IF_LONG_OPTS(applet_long_options = udhcpc_longopts;)
  1098. opt = getopt32(argv, "CV:H:h:F:i:np:qRr:s:T:t:SA:O:ox:fB"
  1099. USE_FOR_MMU("b")
  1100. IF_FEATURE_UDHCPC_ARPING("a")
  1101. IF_FEATURE_UDHCP_PORT("P:")
  1102. "v"
  1103. , &str_V, &str_h, &str_h, &str_F
  1104. , &client_config.interface, &client_config.pidfile, &str_r /* i,p */
  1105. , &client_config.script /* s */
  1106. , &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */
  1107. , &list_O
  1108. , &list_x
  1109. IF_FEATURE_UDHCP_PORT(, &str_P)
  1110. IF_UDHCP_VERBOSE(, &dhcp_verbose)
  1111. );
  1112. if (opt & (OPT_h|OPT_H)) {
  1113. //msg added 2011-11
  1114. bb_error_msg("option -h NAME is deprecated, use -x hostname:NAME");
  1115. client_config.hostname = alloc_dhcp_option(DHCP_HOST_NAME, str_h, 0);
  1116. }
  1117. if (opt & OPT_F) {
  1118. /* FQDN option format: [0x51][len][flags][0][0]<fqdn> */
  1119. client_config.fqdn = alloc_dhcp_option(DHCP_FQDN, str_F, 3);
  1120. /* Flag bits: 0000NEOS
  1121. * S: 1 = Client requests server to update A RR in DNS as well as PTR
  1122. * O: 1 = Server indicates to client that DNS has been updated regardless
  1123. * E: 1 = Name is in DNS format, i.e. <4>host<6>domain<3>com<0>,
  1124. * not "host.domain.com". Format 0 is obsolete.
  1125. * N: 1 = Client requests server to not update DNS (S must be 0 then)
  1126. * Two [0] bytes which follow are deprecated and must be 0.
  1127. */
  1128. client_config.fqdn[OPT_DATA + 0] = 0x1;
  1129. /*client_config.fqdn[OPT_DATA + 1] = 0; - xzalloc did it */
  1130. /*client_config.fqdn[OPT_DATA + 2] = 0; */
  1131. }
  1132. if (opt & OPT_r)
  1133. requested_ip = inet_addr(str_r);
  1134. #if ENABLE_FEATURE_UDHCP_PORT
  1135. if (opt & OPT_P) {
  1136. CLIENT_PORT = xatou16(str_P);
  1137. SERVER_PORT = CLIENT_PORT - 1;
  1138. }
  1139. #endif
  1140. if (opt & OPT_o)
  1141. client_config.no_default_options = 1;
  1142. while (list_O) {
  1143. char *optstr = llist_pop(&list_O);
  1144. unsigned n = bb_strtou(optstr, NULL, 0);
  1145. if (errno || n > 254) {
  1146. n = udhcp_option_idx(optstr);
  1147. n = dhcp_optflags[n].code;
  1148. }
  1149. client_config.opt_mask[n >> 3] |= 1 << (n & 7);
  1150. }
  1151. while (list_x) {
  1152. char *optstr = llist_pop(&list_x);
  1153. char *colon = strchr(optstr, ':');
  1154. if (colon)
  1155. *colon = ' ';
  1156. /* now it looks similar to udhcpd's config file line:
  1157. * "optname optval", using the common routine: */
  1158. udhcp_str2optset(optstr, &client_config.options);
  1159. }
  1160. if (udhcp_read_interface(client_config.interface,
  1161. &client_config.ifindex,
  1162. NULL,
  1163. client_config.client_mac)
  1164. ) {
  1165. return 1;
  1166. }
  1167. clientid_mac_ptr = NULL;
  1168. if (!(opt & OPT_C) && !udhcp_find_option(client_config.options, DHCP_CLIENT_ID)) {
  1169. /* not suppressed and not set, set the default client ID */
  1170. client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, "", 7);
  1171. client_config.clientid[OPT_DATA] = 1; /* type: ethernet */
  1172. clientid_mac_ptr = client_config.clientid + OPT_DATA+1;
  1173. memcpy(clientid_mac_ptr, client_config.client_mac, 6);
  1174. }
  1175. if (str_V[0] != '\0') {
  1176. // can drop -V, str_V, client_config.vendorclass,
  1177. // but need to add "vendor" to the list of recognized
  1178. // string opts for this to work;
  1179. // and need to tweak add_client_options() too...
  1180. // ...so the question is, should we?
  1181. //bb_error_msg("option -V VENDOR is deprecated, use -x vendor:VENDOR");
  1182. client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, str_V, 0);
  1183. }
  1184. #if !BB_MMU
  1185. /* on NOMMU reexec (i.e., background) early */
  1186. if (!(opt & OPT_f)) {
  1187. bb_daemonize_or_rexec(0 /* flags */, argv);
  1188. logmode = LOGMODE_NONE;
  1189. }
  1190. #endif
  1191. if (opt & OPT_S) {
  1192. openlog(applet_name, LOG_PID, LOG_DAEMON);
  1193. logmode |= LOGMODE_SYSLOG;
  1194. }
  1195. /* Make sure fd 0,1,2 are open */
  1196. bb_sanitize_stdio();
  1197. /* Equivalent of doing a fflush after every \n */
  1198. setlinebuf(stdout);
  1199. /* Create pidfile */
  1200. write_pidfile(client_config.pidfile);
  1201. /* Goes to stdout (unless NOMMU) and possibly syslog */
  1202. bb_info_msg("%s (v"BB_VER") started", applet_name);
  1203. /* Set up the signal pipe */
  1204. udhcp_sp_setup();
  1205. /* We want random_xid to be random... */
  1206. srand(monotonic_us());
  1207. state = INIT_SELECTING;
  1208. udhcp_run_script(NULL, "deconfig");
  1209. change_listen_mode(LISTEN_RAW);
  1210. packet_num = 0;
  1211. timeout = 0;
  1212. already_waited_sec = 0;
  1213. /* Main event loop. select() waits on signal pipe and possibly
  1214. * on sockfd.
  1215. * "continue" statements in code below jump to the top of the loop.
  1216. */
  1217. for (;;) {
  1218. struct timeval tv;
  1219. struct dhcp_packet packet;
  1220. /* silence "uninitialized!" warning */
  1221. unsigned timestamp_before_wait = timestamp_before_wait;
  1222. //bb_error_msg("sockfd:%d, listen_mode:%d", sockfd, listen_mode);
  1223. /* Was opening raw or udp socket here
  1224. * if (listen_mode != LISTEN_NONE && sockfd < 0),
  1225. * but on fast network renew responses return faster
  1226. * than we open sockets. Thus this code is moved
  1227. * to change_listen_mode(). Thus we open listen socket
  1228. * BEFORE we send renew request (see "case BOUND:"). */
  1229. max_fd = udhcp_sp_fd_set(&rfds, sockfd);
  1230. tv.tv_sec = timeout - already_waited_sec;
  1231. tv.tv_usec = 0;
  1232. retval = 0;
  1233. /* If we already timed out, fall through with retval = 0, else... */
  1234. if ((int)tv.tv_sec > 0) {
  1235. timestamp_before_wait = (unsigned)monotonic_sec();
  1236. log1("Waiting on select...");
  1237. retval = select(max_fd + 1, &rfds, NULL, NULL, &tv);
  1238. if (retval < 0) {
  1239. /* EINTR? A signal was caught, don't panic */
  1240. if (errno == EINTR) {
  1241. already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
  1242. continue;
  1243. }
  1244. /* Else: an error occured, panic! */
  1245. bb_perror_msg_and_die("select");
  1246. }
  1247. }
  1248. /* If timeout dropped to zero, time to become active:
  1249. * resend discover/renew/whatever
  1250. */
  1251. if (retval == 0) {
  1252. /* When running on a bridge, the ifindex may have changed
  1253. * (e.g. if member interfaces were added/removed
  1254. * or if the status of the bridge changed).
  1255. * Refresh ifindex and client_mac:
  1256. */
  1257. if (udhcp_read_interface(client_config.interface,
  1258. &client_config.ifindex,
  1259. NULL,
  1260. client_config.client_mac)
  1261. ) {
  1262. goto ret0; /* iface is gone? */
  1263. }
  1264. if (clientid_mac_ptr)
  1265. memcpy(clientid_mac_ptr, client_config.client_mac, 6);
  1266. /* We will restart the wait in any case */
  1267. already_waited_sec = 0;
  1268. switch (state) {
  1269. case INIT_SELECTING:
  1270. if (packet_num < discover_retries) {
  1271. if (packet_num == 0)
  1272. xid = random_xid();
  1273. /* broadcast */
  1274. send_discover(xid, requested_ip);
  1275. timeout = discover_timeout;
  1276. packet_num++;
  1277. continue;
  1278. }
  1279. leasefail:
  1280. udhcp_run_script(NULL, "leasefail");
  1281. #if BB_MMU /* -b is not supported on NOMMU */
  1282. if (opt & OPT_b) { /* background if no lease */
  1283. bb_info_msg("No lease, forking to background");
  1284. client_background();
  1285. /* do not background again! */
  1286. opt = ((opt & ~OPT_b) | OPT_f);
  1287. } else
  1288. #endif
  1289. if (opt & OPT_n) { /* abort if no lease */
  1290. bb_info_msg("No lease, failing");
  1291. retval = 1;
  1292. goto ret;
  1293. }
  1294. /* wait before trying again */
  1295. timeout = tryagain_timeout;
  1296. packet_num = 0;
  1297. continue;
  1298. case REQUESTING:
  1299. if (packet_num < discover_retries) {
  1300. /* send broadcast select packet */
  1301. send_select(xid, server_addr, requested_ip);
  1302. timeout = discover_timeout;
  1303. packet_num++;
  1304. continue;
  1305. }
  1306. /* Timed out, go back to init state.
  1307. * "discover...select...discover..." loops
  1308. * were seen in the wild. Treat them similarly
  1309. * to "no response to discover" case */
  1310. change_listen_mode(LISTEN_RAW);
  1311. state = INIT_SELECTING;
  1312. goto leasefail;
  1313. case BOUND:
  1314. /* 1/2 lease passed, enter renewing state */
  1315. state = RENEWING;
  1316. client_config.first_secs = 0; /* make secs field count from 0 */
  1317. change_listen_mode(LISTEN_KERNEL);
  1318. log1("Entering renew state");
  1319. /* fall right through */
  1320. case RENEW_REQUESTED: /* manual (SIGUSR1) renew */
  1321. case_RENEW_REQUESTED:
  1322. case RENEWING:
  1323. if (timeout > 60) {
  1324. /* send an unicast renew request */
  1325. /* Sometimes observed to fail (EADDRNOTAVAIL) to bind
  1326. * a new UDP socket for sending inside send_renew.
  1327. * I hazard to guess existing listening socket
  1328. * is somehow conflicting with it, but why is it
  1329. * not deterministic then?! Strange.
  1330. * Anyway, it does recover by eventually failing through
  1331. * into INIT_SELECTING state.
  1332. */
  1333. send_renew(xid, server_addr, requested_ip);
  1334. timeout >>= 1;
  1335. continue;
  1336. }
  1337. /* Timed out, enter rebinding state */
  1338. log1("Entering rebinding state");
  1339. state = REBINDING;
  1340. /* fall right through */
  1341. case REBINDING:
  1342. /* Switch to bcast receive */
  1343. change_listen_mode(LISTEN_RAW);
  1344. /* Lease is *really* about to run out,
  1345. * try to find DHCP server using broadcast */
  1346. if (timeout > 0) {
  1347. /* send a broadcast renew request */
  1348. send_renew(xid, 0 /*INADDR_ANY*/, requested_ip);
  1349. timeout >>= 1;
  1350. continue;
  1351. }
  1352. /* Timed out, enter init state */
  1353. bb_info_msg("Lease lost, entering init state");
  1354. udhcp_run_script(NULL, "deconfig");
  1355. state = INIT_SELECTING;
  1356. client_config.first_secs = 0; /* make secs field count from 0 */
  1357. /*timeout = 0; - already is */
  1358. packet_num = 0;
  1359. continue;
  1360. /* case RELEASED: */
  1361. }
  1362. /* yah, I know, *you* say it would never happen */
  1363. timeout = INT_MAX;
  1364. continue; /* back to main loop */
  1365. } /* if select timed out */
  1366. /* select() didn't timeout, something happened */
  1367. /* Is it a signal? */
  1368. /* note: udhcp_sp_read checks FD_ISSET before reading */
  1369. switch (udhcp_sp_read(&rfds)) {
  1370. case SIGUSR1:
  1371. client_config.first_secs = 0; /* make secs field count from 0 */
  1372. already_waited_sec = 0;
  1373. perform_renew();
  1374. if (state == RENEW_REQUESTED) {
  1375. /* We might be either on the same network
  1376. * (in which case renew might work),
  1377. * or we might be on a completely different one
  1378. * (in which case renew won't ever succeed).
  1379. * For the second case, must make sure timeout
  1380. * is not too big, or else we can send
  1381. * futile renew requests for hours.
  1382. * (Ab)use -A TIMEOUT value (usually 20 sec)
  1383. * as a cap on the timeout.
  1384. */
  1385. if (timeout > tryagain_timeout)
  1386. timeout = tryagain_timeout;
  1387. goto case_RENEW_REQUESTED;
  1388. }
  1389. /* Start things over */
  1390. packet_num = 0;
  1391. /* Kill any timeouts, user wants this to hurry along */
  1392. timeout = 0;
  1393. continue;
  1394. case SIGUSR2:
  1395. perform_release(server_addr, requested_ip);
  1396. timeout = INT_MAX;
  1397. continue;
  1398. case SIGTERM:
  1399. bb_info_msg("Received SIGTERM");
  1400. goto ret0;
  1401. }
  1402. /* Is it a packet? */
  1403. if (listen_mode == LISTEN_NONE || !FD_ISSET(sockfd, &rfds))
  1404. continue; /* no */
  1405. {
  1406. int len;
  1407. /* A packet is ready, read it */
  1408. if (listen_mode == LISTEN_KERNEL)
  1409. len = udhcp_recv_kernel_packet(&packet, sockfd);
  1410. else
  1411. len = udhcp_recv_raw_packet(&packet, sockfd);
  1412. if (len == -1) {
  1413. /* Error is severe, reopen socket */
  1414. bb_info_msg("Read error: %s, reopening socket", strerror(errno));
  1415. sleep(discover_timeout); /* 3 seconds by default */
  1416. change_listen_mode(listen_mode); /* just close and reopen */
  1417. }
  1418. /* If this packet will turn out to be unrelated/bogus,
  1419. * we will go back and wait for next one.
  1420. * Be sure timeout is properly decreased. */
  1421. already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
  1422. if (len < 0)
  1423. continue;
  1424. }
  1425. if (packet.xid != xid) {
  1426. log1("xid %x (our is %x), ignoring packet",
  1427. (unsigned)packet.xid, (unsigned)xid);
  1428. continue;
  1429. }
  1430. /* Ignore packets that aren't for us */
  1431. if (packet.hlen != 6
  1432. || memcmp(packet.chaddr, client_config.client_mac, 6) != 0
  1433. ) {
  1434. //FIXME: need to also check that last 10 bytes are zero
  1435. log1("chaddr does not match, ignoring packet"); // log2?
  1436. continue;
  1437. }
  1438. message = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
  1439. if (message == NULL) {
  1440. bb_error_msg("no message type option, ignoring packet");
  1441. continue;
  1442. }
  1443. switch (state) {
  1444. case INIT_SELECTING:
  1445. /* Must be a DHCPOFFER */
  1446. if (*message == DHCPOFFER) {
  1447. /* What exactly is server's IP? There are several values.
  1448. * Example DHCP offer captured with tchdump:
  1449. *
  1450. * 10.34.25.254:67 > 10.34.25.202:68 // IP header's src
  1451. * BOOTP fields:
  1452. * Your-IP 10.34.25.202
  1453. * Server-IP 10.34.32.125 // "next server" IP
  1454. * Gateway-IP 10.34.25.254 // relay's address (if DHCP relays are in use)
  1455. * DHCP options:
  1456. * DHCP-Message Option 53, length 1: Offer
  1457. * Server-ID Option 54, length 4: 10.34.255.7 // "server ID"
  1458. * Default-Gateway Option 3, length 4: 10.34.25.254 // router
  1459. *
  1460. * We think that real server IP (one to use in renew/release)
  1461. * is one in Server-ID option. But I am not 100% sure.
  1462. * IP header's src and Gateway-IP (same in this example)
  1463. * might work too.
  1464. * "Next server" and router are definitely wrong ones to use, though...
  1465. */
  1466. temp = udhcp_get_option(&packet, DHCP_SERVER_ID);
  1467. if (!temp) {
  1468. bb_error_msg("no server ID, ignoring packet");
  1469. continue;
  1470. /* still selecting - this server looks bad */
  1471. }
  1472. /* it IS unaligned sometimes, don't "optimize" */
  1473. move_from_unaligned32(server_addr, temp);
  1474. /*xid = packet.xid; - already is */
  1475. requested_ip = packet.yiaddr;
  1476. /* enter requesting state */
  1477. state = REQUESTING;
  1478. timeout = 0;
  1479. packet_num = 0;
  1480. already_waited_sec = 0;
  1481. }
  1482. continue;
  1483. case REQUESTING:
  1484. case RENEWING:
  1485. case RENEW_REQUESTED:
  1486. case REBINDING:
  1487. if (*message == DHCPACK) {
  1488. uint32_t lease_seconds;
  1489. struct in_addr temp_addr;
  1490. temp = udhcp_get_option(&packet, DHCP_LEASE_TIME);
  1491. if (!temp) {
  1492. bb_error_msg("no lease time with ACK, using 1 hour lease");
  1493. lease_seconds = 60 * 60;
  1494. } else {
  1495. /* it IS unaligned sometimes, don't "optimize" */
  1496. move_from_unaligned32(lease_seconds, temp);
  1497. lease_seconds = ntohl(lease_seconds);
  1498. /* paranoia: must not be too small and not prone to overflows */
  1499. if (lease_seconds < 0x10)
  1500. lease_seconds = 0x10;
  1501. if (lease_seconds >= 0x10000000)
  1502. lease_seconds = 0x0fffffff;
  1503. }
  1504. #if ENABLE_FEATURE_UDHCPC_ARPING
  1505. if (opt & OPT_a) {
  1506. /* RFC 2131 3.1 paragraph 5:
  1507. * "The client receives the DHCPACK message with configuration
  1508. * parameters. The client SHOULD perform a final check on the
  1509. * parameters (e.g., ARP for allocated network address), and notes
  1510. * the duration of the lease specified in the DHCPACK message. At this
  1511. * point, the client is configured. If the client detects that the
  1512. * address is already in use (e.g., through the use of ARP),
  1513. * the client MUST send a DHCPDECLINE message to the server and restarts
  1514. * the configuration process..." */
  1515. if (!arpping(packet.yiaddr,
  1516. NULL,
  1517. (uint32_t) 0,
  1518. client_config.client_mac,
  1519. client_config.interface)
  1520. ) {
  1521. bb_info_msg("Offered address is in use "
  1522. "(got ARP reply), declining");
  1523. send_decline(/*xid,*/ server_addr, packet.yiaddr);
  1524. if (state != REQUESTING)
  1525. udhcp_run_script(NULL, "deconfig");
  1526. change_listen_mode(LISTEN_RAW);
  1527. state = INIT_SELECTING;
  1528. client_config.first_secs = 0; /* make secs field count from 0 */
  1529. requested_ip = 0;
  1530. timeout = tryagain_timeout;
  1531. packet_num = 0;
  1532. already_waited_sec = 0;
  1533. continue; /* back to main loop */
  1534. }
  1535. }
  1536. #endif
  1537. /* enter bound state */
  1538. timeout = lease_seconds / 2;
  1539. temp_addr.s_addr = packet.yiaddr;
  1540. bb_info_msg("Lease of %s obtained, lease time %u",
  1541. inet_ntoa(temp_addr), (unsigned)lease_seconds);
  1542. requested_ip = packet.yiaddr;
  1543. udhcp_run_script(&packet, state == REQUESTING ? "bound" : "renew");
  1544. state = BOUND;
  1545. change_listen_mode(LISTEN_NONE);
  1546. if (opt & OPT_q) { /* quit after lease */
  1547. goto ret0;
  1548. }
  1549. /* future renew failures should not exit (JM) */
  1550. opt &= ~OPT_n;
  1551. #if BB_MMU /* NOMMU case backgrounded earlier */
  1552. if (!(opt & OPT_f)) {
  1553. client_background();
  1554. /* do not background again! */
  1555. opt = ((opt & ~OPT_b) | OPT_f);
  1556. }
  1557. #endif
  1558. /* make future renew packets use different xid */
  1559. /* xid = random_xid(); ...but why bother? */
  1560. already_waited_sec = 0;
  1561. continue; /* back to main loop */
  1562. }
  1563. if (*message == DHCPNAK) {
  1564. /* return to init state */
  1565. bb_info_msg("Received DHCP NAK");
  1566. udhcp_run_script(&packet, "nak");
  1567. if (state != REQUESTING)
  1568. udhcp_run_script(NULL, "deconfig");
  1569. change_listen_mode(LISTEN_RAW);
  1570. sleep(3); /* avoid excessive network traffic */
  1571. state = INIT_SELECTING;
  1572. client_config.first_secs = 0; /* make secs field count from 0 */
  1573. requested_ip = 0;
  1574. timeout = 0;
  1575. packet_num = 0;
  1576. already_waited_sec = 0;
  1577. }
  1578. continue;
  1579. /* case BOUND: - ignore all packets */
  1580. /* case RELEASED: - ignore all packets */
  1581. }
  1582. /* back to main loop */
  1583. } /* for (;;) - main loop ends */
  1584. ret0:
  1585. if (opt & OPT_R) /* release on quit */
  1586. perform_release(server_addr, requested_ip);
  1587. retval = 0;
  1588. ret:
  1589. /*if (client_config.pidfile) - remove_pidfile has its own check */
  1590. remove_pidfile(client_config.pidfile);
  1591. return retval;
  1592. }