dhcpc.c 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781
  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 <linux/filter.h>
  29. #include <linux/if_packet.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. int i, end, len;
  544. udhcp_add_simple_option(packet, DHCP_MAX_SIZE, htons(IP_UDP_DHCP_SIZE));
  545. /* Add a "param req" option with the list of options we'd like to have
  546. * from stubborn DHCP servers. Pull the data from the struct in common.c.
  547. * No bounds checking because it goes towards the head of the packet. */
  548. end = udhcp_end_option(packet->options);
  549. len = 0;
  550. for (i = 1; i < DHCP_END; i++) {
  551. if (client_config.opt_mask[i >> 3] & (1 << (i & 7))) {
  552. packet->options[end + OPT_DATA + len] = i;
  553. len++;
  554. }
  555. }
  556. if (len) {
  557. packet->options[end + OPT_CODE] = DHCP_PARAM_REQ;
  558. packet->options[end + OPT_LEN] = len;
  559. packet->options[end + OPT_DATA + len] = DHCP_END;
  560. }
  561. if (client_config.vendorclass)
  562. udhcp_add_binary_option(packet, client_config.vendorclass);
  563. if (client_config.hostname)
  564. udhcp_add_binary_option(packet, client_config.hostname);
  565. if (client_config.fqdn)
  566. udhcp_add_binary_option(packet, client_config.fqdn);
  567. /* Request broadcast replies if we have no IP addr */
  568. if ((option_mask32 & OPT_B) && packet->ciaddr == 0)
  569. packet->flags |= htons(BROADCAST_FLAG);
  570. /* Add -x options if any */
  571. {
  572. struct option_set *curr = client_config.options;
  573. while (curr) {
  574. udhcp_add_binary_option(packet, curr->data);
  575. curr = curr->next;
  576. }
  577. // if (client_config.sname)
  578. // strncpy((char*)packet->sname, client_config.sname, sizeof(packet->sname) - 1);
  579. // if (client_config.boot_file)
  580. // strncpy((char*)packet->file, client_config.boot_file, sizeof(packet->file) - 1);
  581. }
  582. // This will be needed if we remove -V VENDOR_STR in favor of
  583. // -x vendor:VENDOR_STR
  584. //if (!udhcp_find_option(packet.options, DHCP_VENDOR))
  585. // /* not set, set the default vendor ID */
  586. // ...add (DHCP_VENDOR, "udhcp "BB_VER) opt...
  587. }
  588. /* RFC 2131
  589. * 4.4.4 Use of broadcast and unicast
  590. *
  591. * The DHCP client broadcasts DHCPDISCOVER, DHCPREQUEST and DHCPINFORM
  592. * messages, unless the client knows the address of a DHCP server.
  593. * The client unicasts DHCPRELEASE messages to the server. Because
  594. * the client is declining the use of the IP address supplied by the server,
  595. * the client broadcasts DHCPDECLINE messages.
  596. *
  597. * When the DHCP client knows the address of a DHCP server, in either
  598. * INIT or REBOOTING state, the client may use that address
  599. * in the DHCPDISCOVER or DHCPREQUEST rather than the IP broadcast address.
  600. * The client may also use unicast to send DHCPINFORM messages
  601. * to a known DHCP server. If the client receives no response to DHCP
  602. * messages sent to the IP address of a known DHCP server, the DHCP
  603. * client reverts to using the IP broadcast address.
  604. */
  605. static int raw_bcast_from_client_config_ifindex(struct dhcp_packet *packet)
  606. {
  607. return udhcp_send_raw_packet(packet,
  608. /*src*/ INADDR_ANY, CLIENT_PORT,
  609. /*dst*/ INADDR_BROADCAST, SERVER_PORT, MAC_BCAST_ADDR,
  610. client_config.ifindex);
  611. }
  612. /* Broadcast a DHCP discover packet to the network, with an optionally requested IP */
  613. /* NOINLINE: limit stack usage in caller */
  614. static NOINLINE int send_discover(uint32_t xid, uint32_t requested)
  615. {
  616. struct dhcp_packet packet;
  617. /* Fill in: op, htype, hlen, cookie, chaddr fields,
  618. * random xid field (we override it below),
  619. * client-id option (unless -C), message type option:
  620. */
  621. init_packet(&packet, DHCPDISCOVER);
  622. packet.xid = xid;
  623. if (requested)
  624. udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
  625. /* Add options: maxsize,
  626. * optionally: hostname, fqdn, vendorclass,
  627. * "param req" option according to -O, options specified with -x
  628. */
  629. add_client_options(&packet);
  630. bb_info_msg("Sending discover...");
  631. return raw_bcast_from_client_config_ifindex(&packet);
  632. }
  633. /* Broadcast a DHCP request message */
  634. /* RFC 2131 3.1 paragraph 3:
  635. * "The client _broadcasts_ a DHCPREQUEST message..."
  636. */
  637. /* NOINLINE: limit stack usage in caller */
  638. static NOINLINE int send_select(uint32_t xid, uint32_t server, uint32_t requested)
  639. {
  640. struct dhcp_packet packet;
  641. struct in_addr addr;
  642. /*
  643. * RFC 2131 4.3.2 DHCPREQUEST message
  644. * ...
  645. * If the DHCPREQUEST message contains a 'server identifier'
  646. * option, the message is in response to a DHCPOFFER message.
  647. * Otherwise, the message is a request to verify or extend an
  648. * existing lease. If the client uses a 'client identifier'
  649. * in a DHCPREQUEST message, it MUST use that same 'client identifier'
  650. * in all subsequent messages. If the client included a list
  651. * of requested parameters in a DHCPDISCOVER message, it MUST
  652. * include that list in all subsequent messages.
  653. */
  654. /* Fill in: op, htype, hlen, cookie, chaddr fields,
  655. * random xid field (we override it below),
  656. * client-id option (unless -C), message type option:
  657. */
  658. init_packet(&packet, DHCPREQUEST);
  659. packet.xid = xid;
  660. udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
  661. udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
  662. /* Add options: maxsize,
  663. * optionally: hostname, fqdn, vendorclass,
  664. * "param req" option according to -O, and options specified with -x
  665. */
  666. add_client_options(&packet);
  667. addr.s_addr = requested;
  668. bb_info_msg("Sending select for %s...", inet_ntoa(addr));
  669. return raw_bcast_from_client_config_ifindex(&packet);
  670. }
  671. /* Unicast or broadcast a DHCP renew message */
  672. /* NOINLINE: limit stack usage in caller */
  673. static NOINLINE int send_renew(uint32_t xid, uint32_t server, uint32_t ciaddr)
  674. {
  675. struct dhcp_packet packet;
  676. /*
  677. * RFC 2131 4.3.2 DHCPREQUEST message
  678. * ...
  679. * DHCPREQUEST generated during RENEWING state:
  680. *
  681. * 'server identifier' MUST NOT be filled in, 'requested IP address'
  682. * option MUST NOT be filled in, 'ciaddr' MUST be filled in with
  683. * client's IP address. In this situation, the client is completely
  684. * configured, and is trying to extend its lease. This message will
  685. * be unicast, so no relay agents will be involved in its
  686. * transmission. Because 'giaddr' is therefore not filled in, the
  687. * DHCP server will trust the value in 'ciaddr', and use it when
  688. * replying to the client.
  689. */
  690. /* Fill in: op, htype, hlen, cookie, chaddr fields,
  691. * random xid field (we override it below),
  692. * client-id option (unless -C), message type option:
  693. */
  694. init_packet(&packet, DHCPREQUEST);
  695. packet.xid = xid;
  696. packet.ciaddr = ciaddr;
  697. /* Add options: maxsize,
  698. * optionally: hostname, fqdn, vendorclass,
  699. * "param req" option according to -O, and options specified with -x
  700. */
  701. add_client_options(&packet);
  702. bb_info_msg("Sending renew...");
  703. if (server)
  704. return udhcp_send_kernel_packet(&packet,
  705. ciaddr, CLIENT_PORT,
  706. server, SERVER_PORT);
  707. return raw_bcast_from_client_config_ifindex(&packet);
  708. }
  709. #if ENABLE_FEATURE_UDHCPC_ARPING
  710. /* Broadcast a DHCP decline message */
  711. /* NOINLINE: limit stack usage in caller */
  712. static NOINLINE int send_decline(/*uint32_t xid,*/ uint32_t server, uint32_t requested)
  713. {
  714. struct dhcp_packet packet;
  715. /* Fill in: op, htype, hlen, cookie, chaddr, random xid fields,
  716. * client-id option (unless -C), message type option:
  717. */
  718. init_packet(&packet, DHCPDECLINE);
  719. #if 0
  720. /* RFC 2131 says DHCPDECLINE's xid is randomly selected by client,
  721. * but in case the server is buggy and wants DHCPDECLINE's xid
  722. * to match the xid which started entire handshake,
  723. * we use the same xid we used in initial DHCPDISCOVER:
  724. */
  725. packet.xid = xid;
  726. #endif
  727. /* DHCPDECLINE uses "requested ip", not ciaddr, to store offered IP */
  728. udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
  729. udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
  730. bb_info_msg("Sending decline...");
  731. return raw_bcast_from_client_config_ifindex(&packet);
  732. }
  733. #endif
  734. /* Unicast a DHCP release message */
  735. static int send_release(uint32_t server, uint32_t ciaddr)
  736. {
  737. struct dhcp_packet packet;
  738. /* Fill in: op, htype, hlen, cookie, chaddr, random xid fields,
  739. * client-id option (unless -C), message type option:
  740. */
  741. init_packet(&packet, DHCPRELEASE);
  742. /* DHCPRELEASE uses ciaddr, not "requested ip", to store IP being released */
  743. packet.ciaddr = ciaddr;
  744. udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
  745. bb_info_msg("Sending release...");
  746. return udhcp_send_kernel_packet(&packet, ciaddr, CLIENT_PORT, server, SERVER_PORT);
  747. }
  748. /* Returns -1 on errors that are fatal for the socket, -2 for those that aren't */
  749. /* NOINLINE: limit stack usage in caller */
  750. static NOINLINE int udhcp_recv_raw_packet(struct dhcp_packet *dhcp_pkt, int fd)
  751. {
  752. int bytes;
  753. struct ip_udp_dhcp_packet packet;
  754. uint16_t check;
  755. unsigned char cmsgbuf[CMSG_LEN(sizeof(struct tpacket_auxdata))];
  756. struct iovec iov;
  757. struct msghdr msg;
  758. struct cmsghdr *cmsg;
  759. /* used to use just safe_read(fd, &packet, sizeof(packet))
  760. * but we need to check for TP_STATUS_CSUMNOTREADY :(
  761. */
  762. iov.iov_base = &packet;
  763. iov.iov_len = sizeof(packet);
  764. memset(&msg, 0, sizeof(msg));
  765. msg.msg_iov = &iov;
  766. msg.msg_iovlen = 1;
  767. msg.msg_control = cmsgbuf;
  768. msg.msg_controllen = sizeof(cmsgbuf);
  769. for (;;) {
  770. bytes = recvmsg(fd, &msg, 0);
  771. if (bytes < 0) {
  772. if (errno == EINTR)
  773. continue;
  774. log1("Packet read error, ignoring");
  775. /* NB: possible down interface, etc. Caller should pause. */
  776. return bytes; /* returns -1 */
  777. }
  778. break;
  779. }
  780. if (bytes < (int) (sizeof(packet.ip) + sizeof(packet.udp))) {
  781. log1("Packet is too short, ignoring");
  782. return -2;
  783. }
  784. if (bytes < ntohs(packet.ip.tot_len)) {
  785. /* packet is bigger than sizeof(packet), we did partial read */
  786. log1("Oversized packet, ignoring");
  787. return -2;
  788. }
  789. /* ignore any extra garbage bytes */
  790. bytes = ntohs(packet.ip.tot_len);
  791. /* make sure its the right packet for us, and that it passes sanity checks */
  792. if (packet.ip.protocol != IPPROTO_UDP
  793. || packet.ip.version != IPVERSION
  794. || packet.ip.ihl != (sizeof(packet.ip) >> 2)
  795. || packet.udp.dest != htons(CLIENT_PORT)
  796. /* || bytes > (int) sizeof(packet) - can't happen */
  797. || ntohs(packet.udp.len) != (uint16_t)(bytes - sizeof(packet.ip))
  798. ) {
  799. log1("Unrelated/bogus packet, ignoring");
  800. return -2;
  801. }
  802. /* verify IP checksum */
  803. check = packet.ip.check;
  804. packet.ip.check = 0;
  805. if (check != inet_cksum((uint16_t *)&packet.ip, sizeof(packet.ip))) {
  806. log1("Bad IP header checksum, ignoring");
  807. return -2;
  808. }
  809. for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
  810. if (cmsg->cmsg_level == SOL_PACKET
  811. && cmsg->cmsg_type == PACKET_AUXDATA
  812. ) {
  813. /* some VMs don't checksum UDP and TCP data
  814. * they send to the same physical machine,
  815. * here we detect this case:
  816. */
  817. struct tpacket_auxdata *aux = (void *)CMSG_DATA(cmsg);
  818. if (aux->tp_status & TP_STATUS_CSUMNOTREADY)
  819. goto skip_udp_sum_check;
  820. }
  821. }
  822. /* verify UDP checksum. IP header has to be modified for this */
  823. memset(&packet.ip, 0, offsetof(struct iphdr, protocol));
  824. /* ip.xx fields which are not memset: protocol, check, saddr, daddr */
  825. packet.ip.tot_len = packet.udp.len; /* yes, this is needed */
  826. check = packet.udp.check;
  827. packet.udp.check = 0;
  828. if (check && check != inet_cksum((uint16_t *)&packet, bytes)) {
  829. log1("Packet with bad UDP checksum received, ignoring");
  830. return -2;
  831. }
  832. skip_udp_sum_check:
  833. if (packet.data.cookie != htonl(DHCP_MAGIC)) {
  834. bb_info_msg("Packet with bad magic, ignoring");
  835. return -2;
  836. }
  837. log1("Received a packet");
  838. udhcp_dump_packet(&packet.data);
  839. bytes -= sizeof(packet.ip) + sizeof(packet.udp);
  840. memcpy(dhcp_pkt, &packet.data, bytes);
  841. return bytes;
  842. }
  843. /*** Main ***/
  844. static int sockfd = -1;
  845. #define LISTEN_NONE 0
  846. #define LISTEN_KERNEL 1
  847. #define LISTEN_RAW 2
  848. static smallint listen_mode;
  849. /* initial state: (re)start DHCP negotiation */
  850. #define INIT_SELECTING 0
  851. /* discover was sent, DHCPOFFER reply received */
  852. #define REQUESTING 1
  853. /* select/renew was sent, DHCPACK reply received */
  854. #define BOUND 2
  855. /* half of lease passed, want to renew it by sending unicast renew requests */
  856. #define RENEWING 3
  857. /* renew requests were not answered, lease is almost over, send broadcast renew */
  858. #define REBINDING 4
  859. /* manually requested renew (SIGUSR1) */
  860. #define RENEW_REQUESTED 5
  861. /* release, possibly manually requested (SIGUSR2) */
  862. #define RELEASED 6
  863. static smallint state;
  864. static int udhcp_raw_socket(int ifindex)
  865. {
  866. int fd;
  867. struct sockaddr_ll sock;
  868. /*
  869. * Comment:
  870. *
  871. * I've selected not to see LL header, so BPF doesn't see it, too.
  872. * The filter may also pass non-IP and non-ARP packets, but we do
  873. * a more complete check when receiving the message in userspace.
  874. *
  875. * and filter shamelessly stolen from:
  876. *
  877. * http://www.flamewarmaster.de/software/dhcpclient/
  878. *
  879. * There are a few other interesting ideas on that page (look under
  880. * "Motivation"). Use of netlink events is most interesting. Think
  881. * of various network servers listening for events and reconfiguring.
  882. * That would obsolete sending HUP signals and/or make use of restarts.
  883. *
  884. * Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
  885. * License: GPL v2.
  886. *
  887. * TODO: make conditional?
  888. */
  889. static const struct sock_filter filter_instr[] = {
  890. /* load 9th byte (protocol) */
  891. BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
  892. /* jump to L1 if it is IPPROTO_UDP, else to L4 */
  893. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 0, 6),
  894. /* L1: load halfword from offset 6 (flags and frag offset) */
  895. BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 6),
  896. /* jump to L4 if any bits in frag offset field are set, else to L2 */
  897. BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K, 0x1fff, 4, 0),
  898. /* L2: skip IP header (load index reg with header len) */
  899. BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0),
  900. /* load udp destination port from halfword[header_len + 2] */
  901. BPF_STMT(BPF_LD|BPF_H|BPF_IND, 2),
  902. /* jump to L3 if udp dport is CLIENT_PORT, else to L4 */
  903. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 68, 0, 1),
  904. /* L3: accept packet */
  905. BPF_STMT(BPF_RET|BPF_K, 0xffffffff),
  906. /* L4: discard packet */
  907. BPF_STMT(BPF_RET|BPF_K, 0),
  908. };
  909. static const struct sock_fprog filter_prog = {
  910. .len = sizeof(filter_instr) / sizeof(filter_instr[0]),
  911. /* casting const away: */
  912. .filter = (struct sock_filter *) filter_instr,
  913. };
  914. log1("Opening raw socket on ifindex %d", ifindex); //log2?
  915. fd = xsocket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP));
  916. log1("Got raw socket fd"); //log2?
  917. sock.sll_family = AF_PACKET;
  918. sock.sll_protocol = htons(ETH_P_IP);
  919. sock.sll_ifindex = ifindex;
  920. xbind(fd, (struct sockaddr *) &sock, sizeof(sock));
  921. if (CLIENT_PORT == 68) {
  922. /* Use only if standard port is in use */
  923. /* Ignoring error (kernel may lack support for this) */
  924. if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog,
  925. sizeof(filter_prog)) >= 0)
  926. log1("Attached filter to raw socket fd"); // log?
  927. }
  928. if (setsockopt(fd, SOL_PACKET, PACKET_AUXDATA,
  929. &const_int_1, sizeof(int)) < 0
  930. ) {
  931. if (errno != ENOPROTOOPT)
  932. log1("Can't set PACKET_AUXDATA on raw socket");
  933. }
  934. log1("Created raw socket");
  935. return fd;
  936. }
  937. static void change_listen_mode(int new_mode)
  938. {
  939. log1("Entering listen mode: %s",
  940. new_mode != LISTEN_NONE
  941. ? (new_mode == LISTEN_KERNEL ? "kernel" : "raw")
  942. : "none"
  943. );
  944. listen_mode = new_mode;
  945. if (sockfd >= 0) {
  946. close(sockfd);
  947. sockfd = -1;
  948. }
  949. if (new_mode == LISTEN_KERNEL)
  950. sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT, client_config.interface);
  951. else if (new_mode != LISTEN_NONE)
  952. sockfd = udhcp_raw_socket(client_config.ifindex);
  953. /* else LISTEN_NONE: sockfd stays closed */
  954. }
  955. /* Called only on SIGUSR1 */
  956. static void perform_renew(void)
  957. {
  958. bb_info_msg("Performing a DHCP renew");
  959. switch (state) {
  960. case BOUND:
  961. change_listen_mode(LISTEN_KERNEL);
  962. case RENEWING:
  963. case REBINDING:
  964. state = RENEW_REQUESTED;
  965. break;
  966. case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
  967. udhcp_run_script(NULL, "deconfig");
  968. case REQUESTING:
  969. case RELEASED:
  970. change_listen_mode(LISTEN_RAW);
  971. state = INIT_SELECTING;
  972. break;
  973. case INIT_SELECTING:
  974. break;
  975. }
  976. }
  977. static void perform_release(uint32_t server_addr, uint32_t requested_ip)
  978. {
  979. char buffer[sizeof("255.255.255.255")];
  980. struct in_addr temp_addr;
  981. /* send release packet */
  982. if (state == BOUND || state == RENEWING || state == REBINDING) {
  983. temp_addr.s_addr = server_addr;
  984. strcpy(buffer, inet_ntoa(temp_addr));
  985. temp_addr.s_addr = requested_ip;
  986. bb_info_msg("Unicasting a release of %s to %s",
  987. inet_ntoa(temp_addr), buffer);
  988. send_release(server_addr, requested_ip); /* unicast */
  989. udhcp_run_script(NULL, "deconfig");
  990. }
  991. bb_info_msg("Entering released state");
  992. change_listen_mode(LISTEN_NONE);
  993. state = RELEASED;
  994. }
  995. static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
  996. {
  997. uint8_t *storage;
  998. int len = strnlen(str, 255);
  999. storage = xzalloc(len + extra + OPT_DATA);
  1000. storage[OPT_CODE] = code;
  1001. storage[OPT_LEN] = len + extra;
  1002. memcpy(storage + extra + OPT_DATA, str, len);
  1003. return storage;
  1004. }
  1005. #if BB_MMU
  1006. static void client_background(void)
  1007. {
  1008. bb_daemonize(0);
  1009. logmode &= ~LOGMODE_STDIO;
  1010. /* rewrite pidfile, as our pid is different now */
  1011. write_pidfile(client_config.pidfile);
  1012. }
  1013. #endif
  1014. //usage:#if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
  1015. //usage:# define IF_UDHCP_VERBOSE(...) __VA_ARGS__
  1016. //usage:#else
  1017. //usage:# define IF_UDHCP_VERBOSE(...)
  1018. //usage:#endif
  1019. //usage:#define udhcpc_trivial_usage
  1020. //usage: "[-fbnq"IF_UDHCP_VERBOSE("v")"oCRB] [-i IFACE] [-r IP] [-s PROG] [-p PIDFILE]\n"
  1021. //usage: " [-V VENDOR] [-x OPT:VAL]... [-O OPT]..." IF_FEATURE_UDHCP_PORT(" [-P N]")
  1022. //usage:#define udhcpc_full_usage "\n"
  1023. //usage: IF_LONG_OPTS(
  1024. //usage: "\n -i,--interface IFACE Interface to use (default eth0)"
  1025. //usage: "\n -p,--pidfile FILE Create pidfile"
  1026. //usage: "\n -s,--script PROG Run PROG at DHCP events (default "CONFIG_UDHCPC_DEFAULT_SCRIPT")"
  1027. //usage: "\n -B,--broadcast Request broadcast replies"
  1028. //usage: "\n -t,--retries N Send up to N discover packets"
  1029. //usage: "\n -T,--timeout N Pause between packets (default 3 seconds)"
  1030. //usage: "\n -A,--tryagain N Wait N seconds after failure (default 20)"
  1031. //usage: "\n -f,--foreground Run in foreground"
  1032. //usage: USE_FOR_MMU(
  1033. //usage: "\n -b,--background Background if lease is not obtained"
  1034. //usage: )
  1035. //usage: "\n -n,--now Exit if lease is not obtained"
  1036. //usage: "\n -q,--quit Exit after obtaining lease"
  1037. //usage: "\n -R,--release Release IP on exit"
  1038. //usage: "\n -S,--syslog Log to syslog too"
  1039. //usage: IF_FEATURE_UDHCP_PORT(
  1040. //usage: "\n -P,--client-port N Use port N (default 68)"
  1041. //usage: )
  1042. //usage: IF_FEATURE_UDHCPC_ARPING(
  1043. //usage: "\n -a,--arping Use arping to validate offered address"
  1044. //usage: )
  1045. //usage: "\n -O,--request-option OPT Request option OPT from server (cumulative)"
  1046. //usage: "\n -o,--no-default-options Don't request any options (unless -O is given)"
  1047. //usage: "\n -r,--request IP Request this IP address"
  1048. //usage: "\n -x OPT:VAL Include option OPT in sent packets (cumulative)"
  1049. //usage: "\n Examples of string, numeric, and hex byte opts:"
  1050. //usage: "\n -x hostname:bbox - option 12"
  1051. //usage: "\n -x lease:3600 - option 51 (lease time)"
  1052. //usage: "\n -x 0x3d:0100BEEFC0FFEE - option 61 (client id)"
  1053. //usage: "\n -F,--fqdn NAME Ask server to update DNS mapping for NAME"
  1054. //usage: "\n -V,--vendorclass VENDOR Vendor identifier (default 'udhcp VERSION')"
  1055. //usage: "\n -C,--clientid-none Don't send MAC as client identifier"
  1056. //usage: IF_UDHCP_VERBOSE(
  1057. //usage: "\n -v Verbose"
  1058. //usage: )
  1059. //usage: )
  1060. //usage: IF_NOT_LONG_OPTS(
  1061. //usage: "\n -i IFACE Interface to use (default eth0)"
  1062. //usage: "\n -p FILE Create pidfile"
  1063. //usage: "\n -s PROG Run PROG at DHCP events (default "CONFIG_UDHCPC_DEFAULT_SCRIPT")"
  1064. //usage: "\n -B Request broadcast replies"
  1065. //usage: "\n -t N Send up to N discover packets"
  1066. //usage: "\n -T N Pause between packets (default 3 seconds)"
  1067. //usage: "\n -A N Wait N seconds (default 20) after failure"
  1068. //usage: "\n -f Run in foreground"
  1069. //usage: USE_FOR_MMU(
  1070. //usage: "\n -b Background if lease is not obtained"
  1071. //usage: )
  1072. //usage: "\n -n Exit if lease is not obtained"
  1073. //usage: "\n -q Exit after obtaining lease"
  1074. //usage: "\n -R Release IP on exit"
  1075. //usage: "\n -S Log to syslog too"
  1076. //usage: IF_FEATURE_UDHCP_PORT(
  1077. //usage: "\n -P N Use port N (default 68)"
  1078. //usage: )
  1079. //usage: IF_FEATURE_UDHCPC_ARPING(
  1080. //usage: "\n -a Use arping to validate offered address"
  1081. //usage: )
  1082. //usage: "\n -O OPT Request option OPT from server (cumulative)"
  1083. //usage: "\n -o Don't request any options (unless -O is given)"
  1084. //usage: "\n -r IP Request this IP address"
  1085. //usage: "\n -x OPT:VAL Include option OPT in sent packets (cumulative)"
  1086. //usage: "\n Examples of string, numeric, and hex byte opts:"
  1087. //usage: "\n -x hostname:bbox - option 12"
  1088. //usage: "\n -x lease:3600 - option 51 (lease time)"
  1089. //usage: "\n -x 0x3d:0100BEEFC0FFEE - option 61 (client id)"
  1090. //usage: "\n -F NAME Ask server to update DNS mapping for NAME"
  1091. //usage: "\n -V VENDOR Vendor identifier (default 'udhcp VERSION')"
  1092. //usage: "\n -C Don't send MAC as client identifier"
  1093. //usage: IF_UDHCP_VERBOSE(
  1094. //usage: "\n -v Verbose"
  1095. //usage: )
  1096. //usage: )
  1097. //usage: "\nSignals:"
  1098. //usage: "\n USR1 Renew lease"
  1099. //usage: "\n USR2 Release lease"
  1100. int udhcpc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1101. int udhcpc_main(int argc UNUSED_PARAM, char **argv)
  1102. {
  1103. uint8_t *temp, *message;
  1104. const char *str_V, *str_h, *str_F, *str_r;
  1105. IF_FEATURE_UDHCP_PORT(char *str_P;)
  1106. void *clientid_mac_ptr;
  1107. llist_t *list_O = NULL;
  1108. llist_t *list_x = NULL;
  1109. int tryagain_timeout = 20;
  1110. int discover_timeout = 3;
  1111. int discover_retries = 3;
  1112. uint32_t server_addr = server_addr; /* for compiler */
  1113. uint32_t requested_ip = 0;
  1114. uint32_t xid = xid; /* for compiler */
  1115. int packet_num;
  1116. int timeout; /* must be signed */
  1117. unsigned already_waited_sec;
  1118. unsigned opt;
  1119. int max_fd;
  1120. int retval;
  1121. fd_set rfds;
  1122. /* Default options */
  1123. IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;)
  1124. IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;)
  1125. client_config.interface = "eth0";
  1126. client_config.script = CONFIG_UDHCPC_DEFAULT_SCRIPT;
  1127. str_V = "udhcp "BB_VER;
  1128. /* Parse command line */
  1129. /* O,x: list; -T,-t,-A take numeric param */
  1130. opt_complementary = "O::x::T+:t+:A+" IF_UDHCP_VERBOSE(":vv") ;
  1131. IF_LONG_OPTS(applet_long_options = udhcpc_longopts;)
  1132. opt = getopt32(argv, "CV:H:h:F:i:np:qRr:s:T:t:SA:O:ox:fB"
  1133. USE_FOR_MMU("b")
  1134. IF_FEATURE_UDHCPC_ARPING("a")
  1135. IF_FEATURE_UDHCP_PORT("P:")
  1136. "v"
  1137. , &str_V, &str_h, &str_h, &str_F
  1138. , &client_config.interface, &client_config.pidfile, &str_r /* i,p */
  1139. , &client_config.script /* s */
  1140. , &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */
  1141. , &list_O
  1142. , &list_x
  1143. IF_FEATURE_UDHCP_PORT(, &str_P)
  1144. IF_UDHCP_VERBOSE(, &dhcp_verbose)
  1145. );
  1146. if (opt & (OPT_h|OPT_H)) {
  1147. //msg added 2011-11
  1148. bb_error_msg("option -h NAME is deprecated, use -x hostname:NAME");
  1149. client_config.hostname = alloc_dhcp_option(DHCP_HOST_NAME, str_h, 0);
  1150. }
  1151. if (opt & OPT_F) {
  1152. /* FQDN option format: [0x51][len][flags][0][0]<fqdn> */
  1153. client_config.fqdn = alloc_dhcp_option(DHCP_FQDN, str_F, 3);
  1154. /* Flag bits: 0000NEOS
  1155. * S: 1 = Client requests server to update A RR in DNS as well as PTR
  1156. * O: 1 = Server indicates to client that DNS has been updated regardless
  1157. * E: 1 = Name is in DNS format, i.e. <4>host<6>domain<3>com<0>,
  1158. * not "host.domain.com". Format 0 is obsolete.
  1159. * N: 1 = Client requests server to not update DNS (S must be 0 then)
  1160. * Two [0] bytes which follow are deprecated and must be 0.
  1161. */
  1162. client_config.fqdn[OPT_DATA + 0] = 0x1;
  1163. /*client_config.fqdn[OPT_DATA + 1] = 0; - xzalloc did it */
  1164. /*client_config.fqdn[OPT_DATA + 2] = 0; */
  1165. }
  1166. if (opt & OPT_r)
  1167. requested_ip = inet_addr(str_r);
  1168. #if ENABLE_FEATURE_UDHCP_PORT
  1169. if (opt & OPT_P) {
  1170. CLIENT_PORT = xatou16(str_P);
  1171. SERVER_PORT = CLIENT_PORT - 1;
  1172. }
  1173. #endif
  1174. while (list_O) {
  1175. char *optstr = llist_pop(&list_O);
  1176. unsigned n = bb_strtou(optstr, NULL, 0);
  1177. if (errno || n > 254) {
  1178. n = udhcp_option_idx(optstr);
  1179. n = dhcp_optflags[n].code;
  1180. }
  1181. client_config.opt_mask[n >> 3] |= 1 << (n & 7);
  1182. }
  1183. if (!(opt & OPT_o)) {
  1184. unsigned i, n;
  1185. for (i = 0; (n = dhcp_optflags[i].code) != 0; i++) {
  1186. if (dhcp_optflags[i].flags & OPTION_REQ) {
  1187. client_config.opt_mask[n >> 3] |= 1 << (n & 7);
  1188. }
  1189. }
  1190. }
  1191. while (list_x) {
  1192. char *optstr = llist_pop(&list_x);
  1193. char *colon = strchr(optstr, ':');
  1194. if (colon)
  1195. *colon = ' ';
  1196. /* now it looks similar to udhcpd's config file line:
  1197. * "optname optval", using the common routine: */
  1198. udhcp_str2optset(optstr, &client_config.options);
  1199. }
  1200. if (udhcp_read_interface(client_config.interface,
  1201. &client_config.ifindex,
  1202. NULL,
  1203. client_config.client_mac)
  1204. ) {
  1205. return 1;
  1206. }
  1207. clientid_mac_ptr = NULL;
  1208. if (!(opt & OPT_C) && !udhcp_find_option(client_config.options, DHCP_CLIENT_ID)) {
  1209. /* not suppressed and not set, set the default client ID */
  1210. client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, "", 7);
  1211. client_config.clientid[OPT_DATA] = 1; /* type: ethernet */
  1212. clientid_mac_ptr = client_config.clientid + OPT_DATA+1;
  1213. memcpy(clientid_mac_ptr, client_config.client_mac, 6);
  1214. }
  1215. if (str_V[0] != '\0') {
  1216. // can drop -V, str_V, client_config.vendorclass,
  1217. // but need to add "vendor" to the list of recognized
  1218. // string opts for this to work;
  1219. // and need to tweak add_client_options() too...
  1220. // ...so the question is, should we?
  1221. //bb_error_msg("option -V VENDOR is deprecated, use -x vendor:VENDOR");
  1222. client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, str_V, 0);
  1223. }
  1224. #if !BB_MMU
  1225. /* on NOMMU reexec (i.e., background) early */
  1226. if (!(opt & OPT_f)) {
  1227. bb_daemonize_or_rexec(0 /* flags */, argv);
  1228. logmode = LOGMODE_NONE;
  1229. }
  1230. #endif
  1231. if (opt & OPT_S) {
  1232. openlog(applet_name, LOG_PID, LOG_DAEMON);
  1233. logmode |= LOGMODE_SYSLOG;
  1234. }
  1235. /* Make sure fd 0,1,2 are open */
  1236. bb_sanitize_stdio();
  1237. /* Equivalent of doing a fflush after every \n */
  1238. setlinebuf(stdout);
  1239. /* Create pidfile */
  1240. write_pidfile(client_config.pidfile);
  1241. /* Goes to stdout (unless NOMMU) and possibly syslog */
  1242. bb_info_msg("%s (v"BB_VER") started", applet_name);
  1243. /* Set up the signal pipe */
  1244. udhcp_sp_setup();
  1245. /* We want random_xid to be random... */
  1246. srand(monotonic_us());
  1247. state = INIT_SELECTING;
  1248. udhcp_run_script(NULL, "deconfig");
  1249. change_listen_mode(LISTEN_RAW);
  1250. packet_num = 0;
  1251. timeout = 0;
  1252. already_waited_sec = 0;
  1253. /* Main event loop. select() waits on signal pipe and possibly
  1254. * on sockfd.
  1255. * "continue" statements in code below jump to the top of the loop.
  1256. */
  1257. for (;;) {
  1258. struct timeval tv;
  1259. struct dhcp_packet packet;
  1260. /* silence "uninitialized!" warning */
  1261. unsigned timestamp_before_wait = timestamp_before_wait;
  1262. //bb_error_msg("sockfd:%d, listen_mode:%d", sockfd, listen_mode);
  1263. /* Was opening raw or udp socket here
  1264. * if (listen_mode != LISTEN_NONE && sockfd < 0),
  1265. * but on fast network renew responses return faster
  1266. * than we open sockets. Thus this code is moved
  1267. * to change_listen_mode(). Thus we open listen socket
  1268. * BEFORE we send renew request (see "case BOUND:"). */
  1269. max_fd = udhcp_sp_fd_set(&rfds, sockfd);
  1270. tv.tv_sec = timeout - already_waited_sec;
  1271. tv.tv_usec = 0;
  1272. retval = 0;
  1273. /* If we already timed out, fall through with retval = 0, else... */
  1274. if ((int)tv.tv_sec > 0) {
  1275. log1("Waiting on select %u seconds", (int)tv.tv_sec);
  1276. timestamp_before_wait = (unsigned)monotonic_sec();
  1277. retval = select(max_fd + 1, &rfds, NULL, NULL, &tv);
  1278. if (retval < 0) {
  1279. /* EINTR? A signal was caught, don't panic */
  1280. if (errno == EINTR) {
  1281. already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
  1282. continue;
  1283. }
  1284. /* Else: an error occured, panic! */
  1285. bb_perror_msg_and_die("select");
  1286. }
  1287. }
  1288. /* If timeout dropped to zero, time to become active:
  1289. * resend discover/renew/whatever
  1290. */
  1291. if (retval == 0) {
  1292. /* When running on a bridge, the ifindex may have changed
  1293. * (e.g. if member interfaces were added/removed
  1294. * or if the status of the bridge changed).
  1295. * Refresh ifindex and client_mac:
  1296. */
  1297. if (udhcp_read_interface(client_config.interface,
  1298. &client_config.ifindex,
  1299. NULL,
  1300. client_config.client_mac)
  1301. ) {
  1302. goto ret0; /* iface is gone? */
  1303. }
  1304. if (clientid_mac_ptr)
  1305. memcpy(clientid_mac_ptr, client_config.client_mac, 6);
  1306. /* We will restart the wait in any case */
  1307. already_waited_sec = 0;
  1308. switch (state) {
  1309. case INIT_SELECTING:
  1310. if (!discover_retries || packet_num < discover_retries) {
  1311. if (packet_num == 0)
  1312. xid = random_xid();
  1313. /* broadcast */
  1314. send_discover(xid, requested_ip);
  1315. timeout = discover_timeout;
  1316. packet_num++;
  1317. continue;
  1318. }
  1319. leasefail:
  1320. udhcp_run_script(NULL, "leasefail");
  1321. #if BB_MMU /* -b is not supported on NOMMU */
  1322. if (opt & OPT_b) { /* background if no lease */
  1323. bb_info_msg("No lease, forking to background");
  1324. client_background();
  1325. /* do not background again! */
  1326. opt = ((opt & ~OPT_b) | OPT_f);
  1327. } else
  1328. #endif
  1329. if (opt & OPT_n) { /* abort if no lease */
  1330. bb_info_msg("No lease, failing");
  1331. retval = 1;
  1332. goto ret;
  1333. }
  1334. /* wait before trying again */
  1335. timeout = tryagain_timeout;
  1336. packet_num = 0;
  1337. continue;
  1338. case REQUESTING:
  1339. if (!discover_retries || packet_num < discover_retries) {
  1340. /* send broadcast select packet */
  1341. send_select(xid, server_addr, requested_ip);
  1342. timeout = discover_timeout;
  1343. packet_num++;
  1344. continue;
  1345. }
  1346. /* Timed out, go back to init state.
  1347. * "discover...select...discover..." loops
  1348. * were seen in the wild. Treat them similarly
  1349. * to "no response to discover" case */
  1350. change_listen_mode(LISTEN_RAW);
  1351. state = INIT_SELECTING;
  1352. goto leasefail;
  1353. case BOUND:
  1354. /* 1/2 lease passed, enter renewing state */
  1355. state = RENEWING;
  1356. client_config.first_secs = 0; /* make secs field count from 0 */
  1357. change_listen_mode(LISTEN_KERNEL);
  1358. log1("Entering renew state");
  1359. /* fall right through */
  1360. case RENEW_REQUESTED: /* manual (SIGUSR1) renew */
  1361. case_RENEW_REQUESTED:
  1362. case RENEWING:
  1363. if (timeout > 60) {
  1364. /* send an unicast renew request */
  1365. /* Sometimes observed to fail (EADDRNOTAVAIL) to bind
  1366. * a new UDP socket for sending inside send_renew.
  1367. * I hazard to guess existing listening socket
  1368. * is somehow conflicting with it, but why is it
  1369. * not deterministic then?! Strange.
  1370. * Anyway, it does recover by eventually failing through
  1371. * into INIT_SELECTING state.
  1372. */
  1373. send_renew(xid, server_addr, requested_ip);
  1374. timeout >>= 1;
  1375. continue;
  1376. }
  1377. /* Timed out, enter rebinding state */
  1378. log1("Entering rebinding state");
  1379. state = REBINDING;
  1380. /* fall right through */
  1381. case REBINDING:
  1382. /* Switch to bcast receive */
  1383. change_listen_mode(LISTEN_RAW);
  1384. /* Lease is *really* about to run out,
  1385. * try to find DHCP server using broadcast */
  1386. if (timeout > 0) {
  1387. /* send a broadcast renew request */
  1388. send_renew(xid, 0 /*INADDR_ANY*/, requested_ip);
  1389. timeout >>= 1;
  1390. continue;
  1391. }
  1392. /* Timed out, enter init state */
  1393. bb_info_msg("Lease lost, entering init state");
  1394. udhcp_run_script(NULL, "deconfig");
  1395. state = INIT_SELECTING;
  1396. client_config.first_secs = 0; /* make secs field count from 0 */
  1397. /*timeout = 0; - already is */
  1398. packet_num = 0;
  1399. continue;
  1400. /* case RELEASED: */
  1401. }
  1402. /* yah, I know, *you* say it would never happen */
  1403. timeout = INT_MAX;
  1404. continue; /* back to main loop */
  1405. } /* if select timed out */
  1406. /* select() didn't timeout, something happened */
  1407. /* Is it a signal? */
  1408. /* note: udhcp_sp_read checks FD_ISSET before reading */
  1409. switch (udhcp_sp_read(&rfds)) {
  1410. case SIGUSR1:
  1411. client_config.first_secs = 0; /* make secs field count from 0 */
  1412. already_waited_sec = 0;
  1413. perform_renew();
  1414. if (state == RENEW_REQUESTED) {
  1415. /* We might be either on the same network
  1416. * (in which case renew might work),
  1417. * or we might be on a completely different one
  1418. * (in which case renew won't ever succeed).
  1419. * For the second case, must make sure timeout
  1420. * is not too big, or else we can send
  1421. * futile renew requests for hours.
  1422. * (Ab)use -A TIMEOUT value (usually 20 sec)
  1423. * as a cap on the timeout.
  1424. */
  1425. if (timeout > tryagain_timeout)
  1426. timeout = tryagain_timeout;
  1427. goto case_RENEW_REQUESTED;
  1428. }
  1429. /* Start things over */
  1430. packet_num = 0;
  1431. /* Kill any timeouts, user wants this to hurry along */
  1432. timeout = 0;
  1433. continue;
  1434. case SIGUSR2:
  1435. perform_release(server_addr, requested_ip);
  1436. timeout = INT_MAX;
  1437. continue;
  1438. case SIGTERM:
  1439. bb_info_msg("Received SIGTERM");
  1440. goto ret0;
  1441. }
  1442. /* Is it a packet? */
  1443. if (listen_mode == LISTEN_NONE || !FD_ISSET(sockfd, &rfds))
  1444. continue; /* no */
  1445. {
  1446. int len;
  1447. /* A packet is ready, read it */
  1448. if (listen_mode == LISTEN_KERNEL)
  1449. len = udhcp_recv_kernel_packet(&packet, sockfd);
  1450. else
  1451. len = udhcp_recv_raw_packet(&packet, sockfd);
  1452. if (len == -1) {
  1453. /* Error is severe, reopen socket */
  1454. bb_info_msg("Read error: %s, reopening socket", strerror(errno));
  1455. sleep(discover_timeout); /* 3 seconds by default */
  1456. change_listen_mode(listen_mode); /* just close and reopen */
  1457. }
  1458. /* If this packet will turn out to be unrelated/bogus,
  1459. * we will go back and wait for next one.
  1460. * Be sure timeout is properly decreased. */
  1461. already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
  1462. if (len < 0)
  1463. continue;
  1464. }
  1465. if (packet.xid != xid) {
  1466. log1("xid %x (our is %x), ignoring packet",
  1467. (unsigned)packet.xid, (unsigned)xid);
  1468. continue;
  1469. }
  1470. /* Ignore packets that aren't for us */
  1471. if (packet.hlen != 6
  1472. || memcmp(packet.chaddr, client_config.client_mac, 6) != 0
  1473. ) {
  1474. //FIXME: need to also check that last 10 bytes are zero
  1475. log1("chaddr does not match, ignoring packet"); // log2?
  1476. continue;
  1477. }
  1478. message = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
  1479. if (message == NULL) {
  1480. bb_error_msg("no message type option, ignoring packet");
  1481. continue;
  1482. }
  1483. switch (state) {
  1484. case INIT_SELECTING:
  1485. /* Must be a DHCPOFFER */
  1486. if (*message == DHCPOFFER) {
  1487. /* What exactly is server's IP? There are several values.
  1488. * Example DHCP offer captured with tchdump:
  1489. *
  1490. * 10.34.25.254:67 > 10.34.25.202:68 // IP header's src
  1491. * BOOTP fields:
  1492. * Your-IP 10.34.25.202
  1493. * Server-IP 10.34.32.125 // "next server" IP
  1494. * Gateway-IP 10.34.25.254 // relay's address (if DHCP relays are in use)
  1495. * DHCP options:
  1496. * DHCP-Message Option 53, length 1: Offer
  1497. * Server-ID Option 54, length 4: 10.34.255.7 // "server ID"
  1498. * Default-Gateway Option 3, length 4: 10.34.25.254 // router
  1499. *
  1500. * We think that real server IP (one to use in renew/release)
  1501. * is one in Server-ID option. But I am not 100% sure.
  1502. * IP header's src and Gateway-IP (same in this example)
  1503. * might work too.
  1504. * "Next server" and router are definitely wrong ones to use, though...
  1505. */
  1506. temp = udhcp_get_option(&packet, DHCP_SERVER_ID);
  1507. if (!temp) {
  1508. bb_error_msg("no server ID, ignoring packet");
  1509. continue;
  1510. /* still selecting - this server looks bad */
  1511. }
  1512. /* it IS unaligned sometimes, don't "optimize" */
  1513. move_from_unaligned32(server_addr, temp);
  1514. /*xid = packet.xid; - already is */
  1515. requested_ip = packet.yiaddr;
  1516. /* enter requesting state */
  1517. state = REQUESTING;
  1518. timeout = 0;
  1519. packet_num = 0;
  1520. already_waited_sec = 0;
  1521. }
  1522. continue;
  1523. case REQUESTING:
  1524. case RENEWING:
  1525. case RENEW_REQUESTED:
  1526. case REBINDING:
  1527. if (*message == DHCPACK) {
  1528. uint32_t lease_seconds;
  1529. struct in_addr temp_addr;
  1530. temp = udhcp_get_option(&packet, DHCP_LEASE_TIME);
  1531. if (!temp) {
  1532. bb_error_msg("no lease time with ACK, using 1 hour lease");
  1533. lease_seconds = 60 * 60;
  1534. } else {
  1535. /* it IS unaligned sometimes, don't "optimize" */
  1536. move_from_unaligned32(lease_seconds, temp);
  1537. lease_seconds = ntohl(lease_seconds);
  1538. /* paranoia: must not be too small and not prone to overflows */
  1539. if (lease_seconds < 0x10)
  1540. lease_seconds = 0x10;
  1541. if (lease_seconds >= 0x10000000)
  1542. lease_seconds = 0x0fffffff;
  1543. }
  1544. #if ENABLE_FEATURE_UDHCPC_ARPING
  1545. if (opt & OPT_a) {
  1546. /* RFC 2131 3.1 paragraph 5:
  1547. * "The client receives the DHCPACK message with configuration
  1548. * parameters. The client SHOULD perform a final check on the
  1549. * parameters (e.g., ARP for allocated network address), and notes
  1550. * the duration of the lease specified in the DHCPACK message. At this
  1551. * point, the client is configured. If the client detects that the
  1552. * address is already in use (e.g., through the use of ARP),
  1553. * the client MUST send a DHCPDECLINE message to the server and restarts
  1554. * the configuration process..." */
  1555. if (!arpping(packet.yiaddr,
  1556. NULL,
  1557. (uint32_t) 0,
  1558. client_config.client_mac,
  1559. client_config.interface)
  1560. ) {
  1561. bb_info_msg("Offered address is in use "
  1562. "(got ARP reply), declining");
  1563. send_decline(/*xid,*/ server_addr, packet.yiaddr);
  1564. if (state != REQUESTING)
  1565. udhcp_run_script(NULL, "deconfig");
  1566. change_listen_mode(LISTEN_RAW);
  1567. state = INIT_SELECTING;
  1568. client_config.first_secs = 0; /* make secs field count from 0 */
  1569. requested_ip = 0;
  1570. timeout = tryagain_timeout;
  1571. packet_num = 0;
  1572. already_waited_sec = 0;
  1573. continue; /* back to main loop */
  1574. }
  1575. }
  1576. #endif
  1577. /* enter bound state */
  1578. timeout = lease_seconds / 2;
  1579. temp_addr.s_addr = packet.yiaddr;
  1580. bb_info_msg("Lease of %s obtained, lease time %u",
  1581. inet_ntoa(temp_addr), (unsigned)lease_seconds);
  1582. requested_ip = packet.yiaddr;
  1583. udhcp_run_script(&packet, state == REQUESTING ? "bound" : "renew");
  1584. state = BOUND;
  1585. change_listen_mode(LISTEN_NONE);
  1586. if (opt & OPT_q) { /* quit after lease */
  1587. goto ret0;
  1588. }
  1589. /* future renew failures should not exit (JM) */
  1590. opt &= ~OPT_n;
  1591. #if BB_MMU /* NOMMU case backgrounded earlier */
  1592. if (!(opt & OPT_f)) {
  1593. client_background();
  1594. /* do not background again! */
  1595. opt = ((opt & ~OPT_b) | OPT_f);
  1596. }
  1597. #endif
  1598. /* make future renew packets use different xid */
  1599. /* xid = random_xid(); ...but why bother? */
  1600. already_waited_sec = 0;
  1601. continue; /* back to main loop */
  1602. }
  1603. if (*message == DHCPNAK) {
  1604. /* return to init state */
  1605. bb_info_msg("Received DHCP NAK");
  1606. udhcp_run_script(&packet, "nak");
  1607. if (state != REQUESTING)
  1608. udhcp_run_script(NULL, "deconfig");
  1609. change_listen_mode(LISTEN_RAW);
  1610. sleep(3); /* avoid excessive network traffic */
  1611. state = INIT_SELECTING;
  1612. client_config.first_secs = 0; /* make secs field count from 0 */
  1613. requested_ip = 0;
  1614. timeout = 0;
  1615. packet_num = 0;
  1616. already_waited_sec = 0;
  1617. }
  1618. continue;
  1619. /* case BOUND: - ignore all packets */
  1620. /* case RELEASED: - ignore all packets */
  1621. }
  1622. /* back to main loop */
  1623. } /* for (;;) - main loop ends */
  1624. ret0:
  1625. if (opt & OPT_R) /* release on quit */
  1626. perform_release(server_addr, requested_ip);
  1627. retval = 0;
  1628. ret:
  1629. /*if (client_config.pidfile) - remove_pidfile has its own check */
  1630. remove_pidfile(client_config.pidfile);
  1631. return retval;
  1632. }