3
0

dhcpc.c 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853
  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. /* Without MSG_DONTROUTE, the packet was seen routed over
  636. * _other interface_ if server ID is bogus (example: 1.1.1.1).
  637. */
  638. return udhcp_send_kernel_packet(packet,
  639. ciaddr, CLIENT_PORT,
  640. server, SERVER_PORT,
  641. /*send_flags: "to hosts only on directly connected networks" */ MSG_DONTROUTE
  642. );
  643. }
  644. return raw_bcast_from_client_config_ifindex(packet, ciaddr);
  645. }
  646. /* Broadcast a DHCP discover packet to the network, with an optionally requested IP */
  647. /* NOINLINE: limit stack usage in caller */
  648. static NOINLINE int send_discover(uint32_t xid, uint32_t requested)
  649. {
  650. struct dhcp_packet packet;
  651. /* Fill in: op, htype, hlen, cookie, chaddr fields,
  652. * random xid field (we override it below),
  653. * client-id option (unless -C), message type option:
  654. */
  655. init_packet(&packet, DHCPDISCOVER);
  656. packet.xid = xid;
  657. if (requested)
  658. udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
  659. /* Add options: maxsize,
  660. * optionally: hostname, fqdn, vendorclass,
  661. * "param req" option according to -O, options specified with -x
  662. */
  663. add_client_options(&packet);
  664. bb_error_msg("sending %s", "discover");
  665. return raw_bcast_from_client_config_ifindex(&packet, INADDR_ANY);
  666. }
  667. /* Broadcast a DHCP request message */
  668. /* RFC 2131 3.1 paragraph 3:
  669. * "The client _broadcasts_ a DHCPREQUEST message..."
  670. */
  671. /* NOINLINE: limit stack usage in caller */
  672. static NOINLINE int send_select(uint32_t xid, uint32_t server, uint32_t requested)
  673. {
  674. struct dhcp_packet packet;
  675. struct in_addr temp_addr;
  676. /*
  677. * RFC 2131 4.3.2 DHCPREQUEST message
  678. * ...
  679. * If the DHCPREQUEST message contains a 'server identifier'
  680. * option, the message is in response to a DHCPOFFER message.
  681. * Otherwise, the message is a request to verify or extend an
  682. * existing lease. If the client uses a 'client identifier'
  683. * in a DHCPREQUEST message, it MUST use that same 'client identifier'
  684. * in all subsequent messages. If the client included a list
  685. * of requested parameters in a DHCPDISCOVER message, it MUST
  686. * include that list in all subsequent messages.
  687. */
  688. /* Fill in: op, htype, hlen, cookie, chaddr fields,
  689. * random xid field (we override it below),
  690. * client-id option (unless -C), message type option:
  691. */
  692. init_packet(&packet, DHCPREQUEST);
  693. packet.xid = xid;
  694. udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
  695. udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
  696. /* Add options: maxsize,
  697. * optionally: hostname, fqdn, vendorclass,
  698. * "param req" option according to -O, and options specified with -x
  699. */
  700. add_client_options(&packet);
  701. temp_addr.s_addr = requested;
  702. bb_error_msg("sending select for %s", inet_ntoa(temp_addr));
  703. return raw_bcast_from_client_config_ifindex(&packet, INADDR_ANY);
  704. }
  705. /* Unicast or broadcast a DHCP renew message */
  706. /* NOINLINE: limit stack usage in caller */
  707. static NOINLINE int send_renew(uint32_t xid, uint32_t server, uint32_t ciaddr)
  708. {
  709. struct dhcp_packet packet;
  710. struct in_addr temp_addr;
  711. /*
  712. * RFC 2131 4.3.2 DHCPREQUEST message
  713. * ...
  714. * DHCPREQUEST generated during RENEWING state:
  715. *
  716. * 'server identifier' MUST NOT be filled in, 'requested IP address'
  717. * option MUST NOT be filled in, 'ciaddr' MUST be filled in with
  718. * client's IP address. In this situation, the client is completely
  719. * configured, and is trying to extend its lease. This message will
  720. * be unicast, so no relay agents will be involved in its
  721. * transmission. Because 'giaddr' is therefore not filled in, the
  722. * DHCP server will trust the value in 'ciaddr', and use it when
  723. * replying to the client.
  724. */
  725. /* Fill in: op, htype, hlen, cookie, chaddr fields,
  726. * random xid field (we override it below),
  727. * client-id option (unless -C), message type option:
  728. */
  729. init_packet(&packet, DHCPREQUEST);
  730. packet.xid = xid;
  731. packet.ciaddr = ciaddr;
  732. /* Add options: maxsize,
  733. * optionally: hostname, fqdn, vendorclass,
  734. * "param req" option according to -O, and options specified with -x
  735. */
  736. add_client_options(&packet);
  737. temp_addr.s_addr = server;
  738. bb_error_msg("sending renew to %s", inet_ntoa(temp_addr));
  739. return bcast_or_ucast(&packet, ciaddr, server);
  740. }
  741. #if ENABLE_FEATURE_UDHCPC_ARPING
  742. /* Broadcast a DHCP decline message */
  743. /* NOINLINE: limit stack usage in caller */
  744. static NOINLINE int send_decline(/*uint32_t xid,*/ uint32_t server, uint32_t requested)
  745. {
  746. struct dhcp_packet packet;
  747. /* Fill in: op, htype, hlen, cookie, chaddr, random xid fields,
  748. * client-id option (unless -C), message type option:
  749. */
  750. init_packet(&packet, DHCPDECLINE);
  751. #if 0
  752. /* RFC 2131 says DHCPDECLINE's xid is randomly selected by client,
  753. * but in case the server is buggy and wants DHCPDECLINE's xid
  754. * to match the xid which started entire handshake,
  755. * we use the same xid we used in initial DHCPDISCOVER:
  756. */
  757. packet.xid = xid;
  758. #endif
  759. /* DHCPDECLINE uses "requested ip", not ciaddr, to store offered IP */
  760. udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
  761. udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
  762. bb_error_msg("sending %s", "decline");
  763. return raw_bcast_from_client_config_ifindex(&packet, INADDR_ANY);
  764. }
  765. #endif
  766. /* Unicast a DHCP release message */
  767. static int send_release(uint32_t server, uint32_t ciaddr)
  768. {
  769. struct dhcp_packet packet;
  770. /* Fill in: op, htype, hlen, cookie, chaddr, random xid fields,
  771. * client-id option (unless -C), message type option:
  772. */
  773. init_packet(&packet, DHCPRELEASE);
  774. /* DHCPRELEASE uses ciaddr, not "requested ip", to store IP being released */
  775. packet.ciaddr = ciaddr;
  776. udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
  777. bb_error_msg("sending %s", "release");
  778. /* Note: normally we unicast here since "server" is not zero.
  779. * However, there _are_ people who run "address-less" DHCP servers,
  780. * and reportedly ISC dhcp client and Windows allow that.
  781. */
  782. return bcast_or_ucast(&packet, ciaddr, server);
  783. }
  784. /* Returns -1 on errors that are fatal for the socket, -2 for those that aren't */
  785. /* NOINLINE: limit stack usage in caller */
  786. static NOINLINE int udhcp_recv_raw_packet(struct dhcp_packet *dhcp_pkt, int fd)
  787. {
  788. int bytes;
  789. struct ip_udp_dhcp_packet packet;
  790. uint16_t check;
  791. unsigned char cmsgbuf[CMSG_LEN(sizeof(struct tpacket_auxdata))];
  792. struct iovec iov;
  793. struct msghdr msg;
  794. struct cmsghdr *cmsg;
  795. /* used to use just safe_read(fd, &packet, sizeof(packet))
  796. * but we need to check for TP_STATUS_CSUMNOTREADY :(
  797. */
  798. iov.iov_base = &packet;
  799. iov.iov_len = sizeof(packet);
  800. memset(&msg, 0, sizeof(msg));
  801. msg.msg_iov = &iov;
  802. msg.msg_iovlen = 1;
  803. msg.msg_control = cmsgbuf;
  804. msg.msg_controllen = sizeof(cmsgbuf);
  805. for (;;) {
  806. bytes = recvmsg(fd, &msg, 0);
  807. if (bytes < 0) {
  808. if (errno == EINTR)
  809. continue;
  810. log1("packet read error, ignoring");
  811. /* NB: possible down interface, etc. Caller should pause. */
  812. return bytes; /* returns -1 */
  813. }
  814. break;
  815. }
  816. if (bytes < (int) (sizeof(packet.ip) + sizeof(packet.udp))) {
  817. log1("packet is too short, ignoring");
  818. return -2;
  819. }
  820. if (bytes < ntohs(packet.ip.tot_len)) {
  821. /* packet is bigger than sizeof(packet), we did partial read */
  822. log1("oversized packet, ignoring");
  823. return -2;
  824. }
  825. /* ignore any extra garbage bytes */
  826. bytes = ntohs(packet.ip.tot_len);
  827. /* make sure its the right packet for us, and that it passes sanity checks */
  828. if (packet.ip.protocol != IPPROTO_UDP
  829. || packet.ip.version != IPVERSION
  830. || packet.ip.ihl != (sizeof(packet.ip) >> 2)
  831. || packet.udp.dest != htons(CLIENT_PORT)
  832. /* || bytes > (int) sizeof(packet) - can't happen */
  833. || ntohs(packet.udp.len) != (uint16_t)(bytes - sizeof(packet.ip))
  834. ) {
  835. log1("unrelated/bogus packet, ignoring");
  836. return -2;
  837. }
  838. /* verify IP checksum */
  839. check = packet.ip.check;
  840. packet.ip.check = 0;
  841. if (check != inet_cksum((uint16_t *)&packet.ip, sizeof(packet.ip))) {
  842. log1("bad IP header checksum, ignoring");
  843. return -2;
  844. }
  845. for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
  846. if (cmsg->cmsg_level == SOL_PACKET
  847. && cmsg->cmsg_type == PACKET_AUXDATA
  848. ) {
  849. /* some VMs don't checksum UDP and TCP data
  850. * they send to the same physical machine,
  851. * here we detect this case:
  852. */
  853. struct tpacket_auxdata *aux = (void *)CMSG_DATA(cmsg);
  854. if (aux->tp_status & TP_STATUS_CSUMNOTREADY)
  855. goto skip_udp_sum_check;
  856. }
  857. }
  858. /* verify UDP checksum. IP header has to be modified for this */
  859. memset(&packet.ip, 0, offsetof(struct iphdr, protocol));
  860. /* ip.xx fields which are not memset: protocol, check, saddr, daddr */
  861. packet.ip.tot_len = packet.udp.len; /* yes, this is needed */
  862. check = packet.udp.check;
  863. packet.udp.check = 0;
  864. if (check && check != inet_cksum((uint16_t *)&packet, bytes)) {
  865. log1("packet with bad UDP checksum received, ignoring");
  866. return -2;
  867. }
  868. skip_udp_sum_check:
  869. if (packet.data.cookie != htonl(DHCP_MAGIC)) {
  870. bb_error_msg("packet with bad magic, ignoring");
  871. return -2;
  872. }
  873. log1("received %s", "a packet");
  874. udhcp_dump_packet(&packet.data);
  875. bytes -= sizeof(packet.ip) + sizeof(packet.udp);
  876. memcpy(dhcp_pkt, &packet.data, bytes);
  877. return bytes;
  878. }
  879. /*** Main ***/
  880. static int sockfd = -1;
  881. #define LISTEN_NONE 0
  882. #define LISTEN_KERNEL 1
  883. #define LISTEN_RAW 2
  884. static smallint listen_mode;
  885. /* initial state: (re)start DHCP negotiation */
  886. #define INIT_SELECTING 0
  887. /* discover was sent, DHCPOFFER reply received */
  888. #define REQUESTING 1
  889. /* select/renew was sent, DHCPACK reply received */
  890. #define BOUND 2
  891. /* half of lease passed, want to renew it by sending unicast renew requests */
  892. #define RENEWING 3
  893. /* renew requests were not answered, lease is almost over, send broadcast renew */
  894. #define REBINDING 4
  895. /* manually requested renew (SIGUSR1) */
  896. #define RENEW_REQUESTED 5
  897. /* release, possibly manually requested (SIGUSR2) */
  898. #define RELEASED 6
  899. static smallint state;
  900. static int udhcp_raw_socket(int ifindex)
  901. {
  902. int fd;
  903. struct sockaddr_ll sock;
  904. log2("opening raw socket on ifindex %d", ifindex);
  905. fd = xsocket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP));
  906. /* ^^^^^
  907. * SOCK_DGRAM: remove link-layer headers on input (SOCK_RAW keeps them)
  908. * ETH_P_IP: want to receive only packets with IPv4 eth type
  909. */
  910. log2("got raw socket fd");
  911. memset(&sock, 0, sizeof(sock)); /* let's be deterministic */
  912. sock.sll_family = AF_PACKET;
  913. sock.sll_protocol = htons(ETH_P_IP);
  914. sock.sll_ifindex = ifindex;
  915. /*sock.sll_hatype = ARPHRD_???;*/
  916. /*sock.sll_pkttype = PACKET_???;*/
  917. /*sock.sll_halen = ???;*/
  918. /*sock.sll_addr[8] = ???;*/
  919. xbind(fd, (struct sockaddr *) &sock, sizeof(sock));
  920. #if 0 /* Several users reported breakage when BPF filter is used */
  921. if (CLIENT_PORT == 68) {
  922. /* Use only if standard port is in use */
  923. /*
  924. * I've selected not to see LL header, so BPF doesn't see it, too.
  925. * The filter may also pass non-IP and non-ARP packets, but we do
  926. * a more complete check when receiving the message in userspace.
  927. *
  928. * and filter shamelessly stolen from:
  929. *
  930. * http://www.flamewarmaster.de/software/dhcpclient/
  931. *
  932. * There are a few other interesting ideas on that page (look under
  933. * "Motivation"). Use of netlink events is most interesting. Think
  934. * of various network servers listening for events and reconfiguring.
  935. * That would obsolete sending HUP signals and/or make use of restarts.
  936. *
  937. * Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
  938. * License: GPL v2.
  939. */
  940. static const struct sock_filter filter_instr[] = {
  941. /* load 9th byte (protocol) */
  942. BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
  943. /* jump to L1 if it is IPPROTO_UDP, else to L4 */
  944. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 0, 6),
  945. /* L1: load halfword from offset 6 (flags and frag offset) */
  946. BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 6),
  947. /* jump to L4 if any bits in frag offset field are set, else to L2 */
  948. BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K, 0x1fff, 4, 0),
  949. /* L2: skip IP header (load index reg with header len) */
  950. BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0),
  951. /* load udp destination port from halfword[header_len + 2] */
  952. BPF_STMT(BPF_LD|BPF_H|BPF_IND, 2),
  953. /* jump to L3 if udp dport is CLIENT_PORT, else to L4 */
  954. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 68, 0, 1),
  955. /* L3: accept packet ("accept 0x7fffffff bytes") */
  956. /* Accepting 0xffffffff works too but kernel 2.6.19 is buggy */
  957. BPF_STMT(BPF_RET|BPF_K, 0x7fffffff),
  958. /* L4: discard packet ("accept zero bytes") */
  959. BPF_STMT(BPF_RET|BPF_K, 0),
  960. };
  961. static const struct sock_fprog filter_prog = {
  962. .len = sizeof(filter_instr) / sizeof(filter_instr[0]),
  963. /* casting const away: */
  964. .filter = (struct sock_filter *) filter_instr,
  965. };
  966. /* Ignoring error (kernel may lack support for this) */
  967. if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog,
  968. sizeof(filter_prog)) >= 0)
  969. log1("attached filter to raw socket fd"); // log?
  970. }
  971. #endif
  972. if (setsockopt_1(fd, SOL_PACKET, PACKET_AUXDATA) != 0) {
  973. if (errno != ENOPROTOOPT)
  974. log1("can't set PACKET_AUXDATA on raw socket");
  975. }
  976. log1("created raw socket");
  977. return fd;
  978. }
  979. static void change_listen_mode(int new_mode)
  980. {
  981. log1("entering listen mode: %s",
  982. new_mode != LISTEN_NONE
  983. ? (new_mode == LISTEN_KERNEL ? "kernel" : "raw")
  984. : "none"
  985. );
  986. listen_mode = new_mode;
  987. if (sockfd >= 0) {
  988. close(sockfd);
  989. sockfd = -1;
  990. }
  991. if (new_mode == LISTEN_KERNEL)
  992. sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT, client_config.interface);
  993. else if (new_mode != LISTEN_NONE)
  994. sockfd = udhcp_raw_socket(client_config.ifindex);
  995. /* else LISTEN_NONE: sockfd stays closed */
  996. }
  997. /* Called only on SIGUSR1 */
  998. static void perform_renew(void)
  999. {
  1000. bb_error_msg("performing DHCP renew");
  1001. switch (state) {
  1002. case BOUND:
  1003. change_listen_mode(LISTEN_KERNEL);
  1004. case RENEWING:
  1005. case REBINDING:
  1006. state = RENEW_REQUESTED;
  1007. break;
  1008. case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
  1009. udhcp_run_script(NULL, "deconfig");
  1010. case REQUESTING:
  1011. case RELEASED:
  1012. change_listen_mode(LISTEN_RAW);
  1013. state = INIT_SELECTING;
  1014. break;
  1015. case INIT_SELECTING:
  1016. break;
  1017. }
  1018. }
  1019. static void perform_release(uint32_t server_addr, uint32_t requested_ip)
  1020. {
  1021. char buffer[sizeof("255.255.255.255")];
  1022. struct in_addr temp_addr;
  1023. /* send release packet */
  1024. if (state == BOUND
  1025. || state == RENEWING
  1026. || state == REBINDING
  1027. || state == RENEW_REQUESTED
  1028. ) {
  1029. temp_addr.s_addr = server_addr;
  1030. strcpy(buffer, inet_ntoa(temp_addr));
  1031. temp_addr.s_addr = requested_ip;
  1032. bb_error_msg("unicasting a release of %s to %s",
  1033. inet_ntoa(temp_addr), buffer);
  1034. send_release(server_addr, requested_ip); /* unicast */
  1035. }
  1036. bb_error_msg("entering released state");
  1037. /*
  1038. * We can be here on: SIGUSR2,
  1039. * or on exit (SIGTERM) and -R "release on quit" is specified.
  1040. * Users requested to be notified in all cases, even if not in one
  1041. * of the states above.
  1042. */
  1043. udhcp_run_script(NULL, "deconfig");
  1044. change_listen_mode(LISTEN_NONE);
  1045. state = RELEASED;
  1046. }
  1047. static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
  1048. {
  1049. uint8_t *storage;
  1050. int len = strnlen(str, 255);
  1051. storage = xzalloc(len + extra + OPT_DATA);
  1052. storage[OPT_CODE] = code;
  1053. storage[OPT_LEN] = len + extra;
  1054. memcpy(storage + extra + OPT_DATA, str, len);
  1055. return storage;
  1056. }
  1057. #if BB_MMU
  1058. static void client_background(void)
  1059. {
  1060. bb_daemonize(0);
  1061. logmode &= ~LOGMODE_STDIO;
  1062. /* rewrite pidfile, as our pid is different now */
  1063. write_pidfile(client_config.pidfile);
  1064. }
  1065. #endif
  1066. //usage:#if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
  1067. //usage:# define IF_UDHCP_VERBOSE(...) __VA_ARGS__
  1068. //usage:#else
  1069. //usage:# define IF_UDHCP_VERBOSE(...)
  1070. //usage:#endif
  1071. //usage:#define udhcpc_trivial_usage
  1072. //usage: "[-fbq"IF_UDHCP_VERBOSE("v")"RB]"IF_FEATURE_UDHCPC_ARPING(" [-a[MSEC]]")" [-t N] [-T SEC] [-A SEC/-n]\n"
  1073. //usage: " [-i IFACE]"IF_FEATURE_UDHCP_PORT(" [-P PORT]")" [-s PROG] [-p PIDFILE]\n"
  1074. //usage: " [-oC] [-r IP] [-V VENDOR] [-F NAME] [-x OPT:VAL]... [-O OPT]..."
  1075. //usage:#define udhcpc_full_usage "\n"
  1076. //usage: "\n -i IFACE Interface to use (default eth0)"
  1077. //usage: IF_FEATURE_UDHCP_PORT(
  1078. //usage: "\n -P PORT Use PORT (default 68)"
  1079. //usage: )
  1080. //usage: "\n -s PROG Run PROG at DHCP events (default "CONFIG_UDHCPC_DEFAULT_SCRIPT")"
  1081. //usage: "\n -p FILE Create pidfile"
  1082. //usage: "\n -B Request broadcast replies"
  1083. //usage: "\n -t N Send up to N discover packets (default 3)"
  1084. //usage: "\n -T SEC Pause between packets (default 3)"
  1085. //usage: "\n -A SEC Wait if lease is not obtained (default 20)"
  1086. //usage: "\n -n Exit if lease is not obtained"
  1087. //usage: "\n -q Exit after obtaining lease"
  1088. //usage: "\n -R Release IP on exit"
  1089. //usage: "\n -f Run in foreground"
  1090. //usage: USE_FOR_MMU(
  1091. //usage: "\n -b Background if lease is not obtained"
  1092. //usage: )
  1093. //usage: "\n -S Log to syslog too"
  1094. //usage: IF_FEATURE_UDHCPC_ARPING(
  1095. //usage: "\n -a[MSEC] Validate offered address with ARP ping"
  1096. //usage: )
  1097. //usage: "\n -r IP Request this IP address"
  1098. //usage: "\n -o Don't request any options (unless -O is given)"
  1099. //usage: "\n -O OPT Request option OPT from server (cumulative)"
  1100. //usage: "\n -x OPT:VAL Include option OPT in sent packets (cumulative)"
  1101. //usage: "\n Examples of string, numeric, and hex byte opts:"
  1102. //usage: "\n -x hostname:bbox - option 12"
  1103. //usage: "\n -x lease:3600 - option 51 (lease time)"
  1104. //usage: "\n -x 0x3d:0100BEEFC0FFEE - option 61 (client id)"
  1105. //usage: "\n -x 14:'\"dumpfile\"' - option 14 (shell-quoted)"
  1106. //usage: "\n -F NAME Ask server to update DNS mapping for NAME"
  1107. //usage: "\n -V VENDOR Vendor identifier (default 'udhcp VERSION')"
  1108. //usage: "\n -C Don't send MAC as client identifier"
  1109. //usage: IF_UDHCP_VERBOSE(
  1110. //usage: "\n -v Verbose"
  1111. //usage: )
  1112. //usage: "\nSignals:"
  1113. //usage: "\n USR1 Renew lease"
  1114. //usage: "\n USR2 Release lease"
  1115. int udhcpc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1116. int udhcpc_main(int argc UNUSED_PARAM, char **argv)
  1117. {
  1118. uint8_t *message;
  1119. const char *str_V, *str_h, *str_F, *str_r;
  1120. IF_FEATURE_UDHCPC_ARPING(const char *str_a = "2000";)
  1121. IF_FEATURE_UDHCP_PORT(char *str_P;)
  1122. void *clientid_mac_ptr;
  1123. llist_t *list_O = NULL;
  1124. llist_t *list_x = NULL;
  1125. int tryagain_timeout = 20;
  1126. int discover_timeout = 3;
  1127. int discover_retries = 3;
  1128. uint32_t server_addr = server_addr; /* for compiler */
  1129. uint32_t requested_ip = 0;
  1130. uint32_t xid = xid; /* for compiler */
  1131. int packet_num;
  1132. int timeout; /* must be signed */
  1133. unsigned already_waited_sec;
  1134. unsigned opt;
  1135. IF_FEATURE_UDHCPC_ARPING(unsigned arpping_ms;)
  1136. int retval;
  1137. setup_common_bufsiz();
  1138. /* Default options */
  1139. IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;)
  1140. IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;)
  1141. client_config.interface = "eth0";
  1142. client_config.script = CONFIG_UDHCPC_DEFAULT_SCRIPT;
  1143. str_V = "udhcp "BB_VER;
  1144. /* Parse command line */
  1145. opt = getopt32long(argv, "^"
  1146. /* O,x: list; -T,-t,-A take numeric param */
  1147. "CV:H:h:F:i:np:qRr:s:T:+t:+SA:+O:*ox:*fB"
  1148. USE_FOR_MMU("b")
  1149. IF_FEATURE_UDHCPC_ARPING("a::")
  1150. IF_FEATURE_UDHCP_PORT("P:")
  1151. "v"
  1152. "\0" IF_UDHCP_VERBOSE("vv") /* -v is a counter */
  1153. , udhcpc_longopts
  1154. , &str_V, &str_h, &str_h, &str_F
  1155. , &client_config.interface, &client_config.pidfile /* i,p */
  1156. , &str_r /* r */
  1157. , &client_config.script /* s */
  1158. , &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */
  1159. , &list_O
  1160. , &list_x
  1161. IF_FEATURE_UDHCPC_ARPING(, &str_a)
  1162. IF_FEATURE_UDHCP_PORT(, &str_P)
  1163. IF_UDHCP_VERBOSE(, &dhcp_verbose)
  1164. );
  1165. if (opt & (OPT_h|OPT_H)) {
  1166. //msg added 2011-11
  1167. bb_error_msg("option -h NAME is deprecated, use -x hostname:NAME");
  1168. client_config.hostname = alloc_dhcp_option(DHCP_HOST_NAME, str_h, 0);
  1169. }
  1170. if (opt & OPT_F) {
  1171. /* FQDN option format: [0x51][len][flags][0][0]<fqdn> */
  1172. client_config.fqdn = alloc_dhcp_option(DHCP_FQDN, str_F, 3);
  1173. /* Flag bits: 0000NEOS
  1174. * S: 1 = Client requests server to update A RR in DNS as well as PTR
  1175. * O: 1 = Server indicates to client that DNS has been updated regardless
  1176. * E: 1 = Name is in DNS format, i.e. <4>host<6>domain<3>com<0>,
  1177. * not "host.domain.com". Format 0 is obsolete.
  1178. * N: 1 = Client requests server to not update DNS (S must be 0 then)
  1179. * Two [0] bytes which follow are deprecated and must be 0.
  1180. */
  1181. client_config.fqdn[OPT_DATA + 0] = 0x1;
  1182. /*client_config.fqdn[OPT_DATA + 1] = 0; - xzalloc did it */
  1183. /*client_config.fqdn[OPT_DATA + 2] = 0; */
  1184. }
  1185. if (opt & OPT_r)
  1186. requested_ip = inet_addr(str_r);
  1187. #if ENABLE_FEATURE_UDHCP_PORT
  1188. if (opt & OPT_P) {
  1189. CLIENT_PORT = xatou16(str_P);
  1190. SERVER_PORT = CLIENT_PORT - 1;
  1191. }
  1192. #endif
  1193. IF_FEATURE_UDHCPC_ARPING(arpping_ms = xatou(str_a);)
  1194. while (list_O) {
  1195. char *optstr = llist_pop(&list_O);
  1196. unsigned n = bb_strtou(optstr, NULL, 0);
  1197. if (errno || n > 254) {
  1198. n = udhcp_option_idx(optstr, dhcp_option_strings);
  1199. n = dhcp_optflags[n].code;
  1200. }
  1201. client_config.opt_mask[n >> 3] |= 1 << (n & 7);
  1202. }
  1203. if (!(opt & OPT_o)) {
  1204. unsigned i, n;
  1205. for (i = 0; (n = dhcp_optflags[i].code) != 0; i++) {
  1206. if (dhcp_optflags[i].flags & OPTION_REQ) {
  1207. client_config.opt_mask[n >> 3] |= 1 << (n & 7);
  1208. }
  1209. }
  1210. }
  1211. while (list_x) {
  1212. char *optstr = xstrdup(llist_pop(&list_x));
  1213. udhcp_str2optset(optstr, &client_config.options,
  1214. dhcp_optflags, dhcp_option_strings,
  1215. /*dhcpv6:*/ 0
  1216. );
  1217. free(optstr);
  1218. }
  1219. if (udhcp_read_interface(client_config.interface,
  1220. &client_config.ifindex,
  1221. NULL,
  1222. client_config.client_mac)
  1223. ) {
  1224. return 1;
  1225. }
  1226. clientid_mac_ptr = NULL;
  1227. if (!(opt & OPT_C) && !udhcp_find_option(client_config.options, DHCP_CLIENT_ID)) {
  1228. /* not suppressed and not set, set the default client ID */
  1229. client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, "", 7);
  1230. client_config.clientid[OPT_DATA] = 1; /* type: ethernet */
  1231. clientid_mac_ptr = client_config.clientid + OPT_DATA+1;
  1232. memcpy(clientid_mac_ptr, client_config.client_mac, 6);
  1233. }
  1234. if (str_V[0] != '\0') {
  1235. // can drop -V, str_V, client_config.vendorclass,
  1236. // but need to add "vendor" to the list of recognized
  1237. // string opts for this to work;
  1238. // and need to tweak add_client_options() too...
  1239. // ...so the question is, should we?
  1240. //bb_error_msg("option -V VENDOR is deprecated, use -x vendor:VENDOR");
  1241. client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, str_V, 0);
  1242. }
  1243. #if !BB_MMU
  1244. /* on NOMMU reexec (i.e., background) early */
  1245. if (!(opt & OPT_f)) {
  1246. bb_daemonize_or_rexec(0 /* flags */, argv);
  1247. logmode = LOGMODE_NONE;
  1248. }
  1249. #endif
  1250. if (opt & OPT_S) {
  1251. openlog(applet_name, LOG_PID, LOG_DAEMON);
  1252. logmode |= LOGMODE_SYSLOG;
  1253. }
  1254. /* Make sure fd 0,1,2 are open */
  1255. bb_sanitize_stdio();
  1256. /* Create pidfile */
  1257. write_pidfile(client_config.pidfile);
  1258. /* Goes to stdout (unless NOMMU) and possibly syslog */
  1259. bb_error_msg("started, v"BB_VER);
  1260. /* Set up the signal pipe */
  1261. udhcp_sp_setup();
  1262. /* We want random_xid to be random... */
  1263. srand(monotonic_us());
  1264. state = INIT_SELECTING;
  1265. udhcp_run_script(NULL, "deconfig");
  1266. change_listen_mode(LISTEN_RAW);
  1267. packet_num = 0;
  1268. timeout = 0;
  1269. already_waited_sec = 0;
  1270. /* Main event loop. select() waits on signal pipe and possibly
  1271. * on sockfd.
  1272. * "continue" statements in code below jump to the top of the loop.
  1273. */
  1274. for (;;) {
  1275. int tv;
  1276. struct pollfd pfds[2];
  1277. struct dhcp_packet packet;
  1278. /* silence "uninitialized!" warning */
  1279. unsigned timestamp_before_wait = timestamp_before_wait;
  1280. //bb_error_msg("sockfd:%d, listen_mode:%d", sockfd, listen_mode);
  1281. /* Was opening raw or udp socket here
  1282. * if (listen_mode != LISTEN_NONE && sockfd < 0),
  1283. * but on fast network renew responses return faster
  1284. * than we open sockets. Thus this code is moved
  1285. * to change_listen_mode(). Thus we open listen socket
  1286. * BEFORE we send renew request (see "case BOUND:"). */
  1287. udhcp_sp_fd_set(pfds, sockfd);
  1288. tv = timeout - already_waited_sec;
  1289. retval = 0;
  1290. /* If we already timed out, fall through with retval = 0, else... */
  1291. if (tv > 0) {
  1292. log1("waiting %u seconds", tv);
  1293. timestamp_before_wait = (unsigned)monotonic_sec();
  1294. retval = poll(pfds, 2, tv < INT_MAX/1000 ? tv * 1000 : INT_MAX);
  1295. if (retval < 0) {
  1296. /* EINTR? A signal was caught, don't panic */
  1297. if (errno == EINTR) {
  1298. already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
  1299. continue;
  1300. }
  1301. /* Else: an error occurred, panic! */
  1302. bb_perror_msg_and_die("poll");
  1303. }
  1304. }
  1305. /* If timeout dropped to zero, time to become active:
  1306. * resend discover/renew/whatever
  1307. */
  1308. if (retval == 0) {
  1309. /* When running on a bridge, the ifindex may have changed
  1310. * (e.g. if member interfaces were added/removed
  1311. * or if the status of the bridge changed).
  1312. * Refresh ifindex and client_mac:
  1313. */
  1314. if (udhcp_read_interface(client_config.interface,
  1315. &client_config.ifindex,
  1316. NULL,
  1317. client_config.client_mac)
  1318. ) {
  1319. goto ret0; /* iface is gone? */
  1320. }
  1321. if (clientid_mac_ptr)
  1322. memcpy(clientid_mac_ptr, client_config.client_mac, 6);
  1323. /* We will restart the wait in any case */
  1324. already_waited_sec = 0;
  1325. switch (state) {
  1326. case INIT_SELECTING:
  1327. if (!discover_retries || packet_num < discover_retries) {
  1328. if (packet_num == 0)
  1329. xid = random_xid();
  1330. /* broadcast */
  1331. send_discover(xid, requested_ip);
  1332. timeout = discover_timeout;
  1333. packet_num++;
  1334. continue;
  1335. }
  1336. leasefail:
  1337. udhcp_run_script(NULL, "leasefail");
  1338. #if BB_MMU /* -b is not supported on NOMMU */
  1339. if (opt & OPT_b) { /* background if no lease */
  1340. bb_error_msg("no lease, forking to background");
  1341. client_background();
  1342. /* do not background again! */
  1343. opt = ((opt & ~OPT_b) | OPT_f);
  1344. } else
  1345. #endif
  1346. if (opt & OPT_n) { /* abort if no lease */
  1347. bb_error_msg("no lease, failing");
  1348. retval = 1;
  1349. goto ret;
  1350. }
  1351. /* wait before trying again */
  1352. timeout = tryagain_timeout;
  1353. packet_num = 0;
  1354. continue;
  1355. case REQUESTING:
  1356. if (packet_num < 3) {
  1357. /* send broadcast select packet */
  1358. send_select(xid, server_addr, requested_ip);
  1359. timeout = discover_timeout;
  1360. packet_num++;
  1361. continue;
  1362. }
  1363. /* Timed out, go back to init state.
  1364. * "discover...select...discover..." loops
  1365. * were seen in the wild. Treat them similarly
  1366. * to "no response to discover" case */
  1367. change_listen_mode(LISTEN_RAW);
  1368. state = INIT_SELECTING;
  1369. goto leasefail;
  1370. case BOUND:
  1371. /* 1/2 lease passed, enter renewing state */
  1372. state = RENEWING;
  1373. client_config.first_secs = 0; /* make secs field count from 0 */
  1374. change_listen_mode(LISTEN_KERNEL);
  1375. log1("entering renew state");
  1376. /* fall right through */
  1377. case RENEW_REQUESTED: /* manual (SIGUSR1) renew */
  1378. case_RENEW_REQUESTED:
  1379. case RENEWING:
  1380. if (timeout > 60) {
  1381. /* send an unicast renew request */
  1382. /* Sometimes observed to fail (EADDRNOTAVAIL) to bind
  1383. * a new UDP socket for sending inside send_renew.
  1384. * I hazard to guess existing listening socket
  1385. * is somehow conflicting with it, but why is it
  1386. * not deterministic then?! Strange.
  1387. * Anyway, it does recover by eventually failing through
  1388. * into INIT_SELECTING state.
  1389. */
  1390. if (send_renew(xid, server_addr, requested_ip) >= 0) {
  1391. timeout >>= 1;
  1392. //TODO: the timeout to receive an answer for our renew should not be selected
  1393. //with "timeout = lease_seconds / 2; ...; timeout = timeout / 2": it is often huge.
  1394. //Waiting e.g. 4*3600 seconds for a reply does not make sense
  1395. //(if reply isn't coming, we keep an open socket for hours),
  1396. //it should be something like 10 seconds.
  1397. //Also, it's probably best to try sending renew in kernel mode a few (3-5) times
  1398. //and fall back to raw mode if it does not work.
  1399. continue;
  1400. }
  1401. /* else: error sending.
  1402. * example: ENETUNREACH seen with server
  1403. * which gave us bogus server ID 1.1.1.1
  1404. * which wasn't reachable (and probably did not exist).
  1405. */
  1406. }
  1407. /* Timed out or error, enter rebinding state */
  1408. log1("entering rebinding state");
  1409. state = REBINDING;
  1410. /* fall right through */
  1411. case REBINDING:
  1412. /* Switch to bcast receive */
  1413. change_listen_mode(LISTEN_RAW);
  1414. /* Lease is *really* about to run out,
  1415. * try to find DHCP server using broadcast */
  1416. if (timeout > 0) {
  1417. /* send a broadcast renew request */
  1418. send_renew(xid, 0 /*INADDR_ANY*/, requested_ip);
  1419. timeout >>= 1;
  1420. continue;
  1421. }
  1422. /* Timed out, enter init state */
  1423. bb_error_msg("lease lost, entering init state");
  1424. udhcp_run_script(NULL, "deconfig");
  1425. state = INIT_SELECTING;
  1426. client_config.first_secs = 0; /* make secs field count from 0 */
  1427. /*timeout = 0; - already is */
  1428. packet_num = 0;
  1429. continue;
  1430. /* case RELEASED: */
  1431. }
  1432. /* yah, I know, *you* say it would never happen */
  1433. timeout = INT_MAX;
  1434. continue; /* back to main loop */
  1435. } /* if poll timed out */
  1436. /* poll() didn't timeout, something happened */
  1437. /* Is it a signal? */
  1438. switch (udhcp_sp_read()) {
  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 (!pfds[1].revents)
  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: "STRERROR_FMT", 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 > 0x7fffffff)
  1579. // lease_seconds = 0x7fffffff;
  1580. //^^^not necessary since "timeout = lease_seconds / 2"
  1581. //does not overflow even for 0xffffffff.
  1582. }
  1583. #if ENABLE_FEATURE_UDHCPC_ARPING
  1584. if (opt & OPT_a) {
  1585. /* RFC 2131 3.1 paragraph 5:
  1586. * "The client receives the DHCPACK message with configuration
  1587. * parameters. The client SHOULD perform a final check on the
  1588. * parameters (e.g., ARP for allocated network address), and notes
  1589. * the duration of the lease specified in the DHCPACK message. At this
  1590. * point, the client is configured. If the client detects that the
  1591. * address is already in use (e.g., through the use of ARP),
  1592. * the client MUST send a DHCPDECLINE message to the server and restarts
  1593. * the configuration process..." */
  1594. if (!arpping(packet.yiaddr,
  1595. NULL,
  1596. (uint32_t) 0,
  1597. client_config.client_mac,
  1598. client_config.interface,
  1599. arpping_ms)
  1600. ) {
  1601. bb_error_msg("offered address is in use "
  1602. "(got ARP reply), declining");
  1603. send_decline(/*xid,*/ server_addr, packet.yiaddr);
  1604. if (state != REQUESTING)
  1605. udhcp_run_script(NULL, "deconfig");
  1606. change_listen_mode(LISTEN_RAW);
  1607. state = INIT_SELECTING;
  1608. client_config.first_secs = 0; /* make secs field count from 0 */
  1609. requested_ip = 0;
  1610. timeout = tryagain_timeout;
  1611. packet_num = 0;
  1612. already_waited_sec = 0;
  1613. continue; /* back to main loop */
  1614. }
  1615. }
  1616. #endif
  1617. /* enter bound state */
  1618. temp_addr.s_addr = packet.yiaddr;
  1619. bb_error_msg("lease of %s obtained, lease time %u",
  1620. inet_ntoa(temp_addr), (unsigned)lease_seconds);
  1621. requested_ip = packet.yiaddr;
  1622. start = monotonic_sec();
  1623. udhcp_run_script(&packet, state == REQUESTING ? "bound" : "renew");
  1624. already_waited_sec = (unsigned)monotonic_sec() - start;
  1625. timeout = lease_seconds / 2;
  1626. if ((unsigned)timeout < already_waited_sec) {
  1627. /* Something went wrong. Back to discover state */
  1628. timeout = already_waited_sec = 0;
  1629. }
  1630. state = BOUND;
  1631. change_listen_mode(LISTEN_NONE);
  1632. if (opt & OPT_q) { /* quit after lease */
  1633. goto ret0;
  1634. }
  1635. /* future renew failures should not exit (JM) */
  1636. opt &= ~OPT_n;
  1637. #if BB_MMU /* NOMMU case backgrounded earlier */
  1638. if (!(opt & OPT_f)) {
  1639. client_background();
  1640. /* do not background again! */
  1641. opt = ((opt & ~OPT_b) | OPT_f);
  1642. }
  1643. #endif
  1644. /* make future renew packets use different xid */
  1645. /* xid = random_xid(); ...but why bother? */
  1646. continue; /* back to main loop */
  1647. }
  1648. if (*message == DHCPNAK) {
  1649. /* If network has more than one DHCP server,
  1650. * "wrong" server can reply first, with a NAK.
  1651. * Do not interpret it as a NAK from "our" server.
  1652. */
  1653. if (server_addr != 0) {
  1654. uint32_t svid;
  1655. uint8_t *temp;
  1656. temp = udhcp_get_option(&packet, DHCP_SERVER_ID);
  1657. if (!temp) {
  1658. non_matching_svid:
  1659. log1("received DHCP NAK with wrong"
  1660. " server ID, ignoring packet");
  1661. continue;
  1662. }
  1663. move_from_unaligned32(svid, temp);
  1664. if (svid != server_addr)
  1665. goto non_matching_svid;
  1666. }
  1667. /* return to init state */
  1668. bb_error_msg("received %s", "DHCP NAK");
  1669. udhcp_run_script(&packet, "nak");
  1670. if (state != REQUESTING)
  1671. udhcp_run_script(NULL, "deconfig");
  1672. change_listen_mode(LISTEN_RAW);
  1673. sleep(3); /* avoid excessive network traffic */
  1674. state = INIT_SELECTING;
  1675. client_config.first_secs = 0; /* make secs field count from 0 */
  1676. requested_ip = 0;
  1677. timeout = 0;
  1678. packet_num = 0;
  1679. already_waited_sec = 0;
  1680. }
  1681. continue;
  1682. /* case BOUND: - ignore all packets */
  1683. /* case RELEASED: - ignore all packets */
  1684. }
  1685. /* back to main loop */
  1686. } /* for (;;) - main loop ends */
  1687. ret0:
  1688. if (opt & OPT_R) /* release on quit */
  1689. perform_release(server_addr, requested_ip);
  1690. retval = 0;
  1691. ret:
  1692. /*if (client_config.pidfile) - remove_pidfile has its own check */
  1693. remove_pidfile(client_config.pidfile);
  1694. return retval;
  1695. }