3
0

dhcpc.c 57 KB

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