dhcpc.c 57 KB

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