dhcpc.c 57 KB

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