3
0

dhcpc.c 58 KB

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