dhcpc.c 57 KB

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