dhcpc.c 59 KB

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