d6_dhcpc.c 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * DHCPv6 client.
  4. *
  5. * Copyright (C) 2011-2017 Denys Vlasenko.
  6. *
  7. * Licensed under GPLv2, see file LICENSE in this source tree.
  8. */
  9. //config:config UDHCPC6
  10. //config: bool "udhcpc6 (21 kb)"
  11. //config: default y
  12. //config: depends on FEATURE_IPV6
  13. //config: help
  14. //config: udhcpc6 is a DHCPv6 client
  15. //config:
  16. //config:config FEATURE_UDHCPC6_RFC3646
  17. //config: bool "Support RFC 3646 (DNS server and search list)"
  18. //config: default y
  19. //config: depends on UDHCPC6
  20. //config: help
  21. //config: List of DNS servers and domain search list can be requested with
  22. //config: "-O dns" and "-O search". If server gives these values,
  23. //config: they will be set in environment variables "dns" and "search".
  24. //config:
  25. //config:config FEATURE_UDHCPC6_RFC4704
  26. //config: bool "Support RFC 4704 (Client FQDN)"
  27. //config: default y
  28. //config: depends on UDHCPC6
  29. //config: help
  30. //config: You can request FQDN to be given by server using "-O fqdn".
  31. //config:
  32. //config:config FEATURE_UDHCPC6_RFC4833
  33. //config: bool "Support RFC 4833 (Timezones)"
  34. //config: default y
  35. //config: depends on UDHCPC6
  36. //config: help
  37. //config: You can request POSIX timezone with "-O tz" and timezone name
  38. //config: with "-O timezone".
  39. //config:
  40. //config:config FEATURE_UDHCPC6_RFC5970
  41. //config: bool "Support RFC 5970 (Network Boot)"
  42. //config: default y
  43. //config: depends on UDHCPC6
  44. //config: help
  45. //config: You can request bootfile-url with "-O bootfile_url" and
  46. //config: bootfile-params with "-O bootfile_params".
  47. //applet:IF_UDHCPC6(APPLET(udhcpc6, BB_DIR_USR_BIN, BB_SUID_DROP))
  48. //kbuild:lib-$(CONFIG_UDHCPC6) += d6_dhcpc.o d6_packet.o d6_socket.o common.o socket.o signalpipe.o
  49. //kbuild:lib-$(CONFIG_FEATURE_UDHCPC6_RFC3646) += domain_codec.o
  50. //kbuild:lib-$(CONFIG_FEATURE_UDHCPC6_RFC4704) += domain_codec.o
  51. #include <syslog.h>
  52. /* Override ENABLE_FEATURE_PIDFILE - ifupdown needs our pidfile to always exist */
  53. #define WANT_PIDFILE 1
  54. #include "common.h"
  55. #include "dhcpd.h"
  56. #include "dhcpc.h"
  57. #include "d6_common.h"
  58. #include <netinet/if_ether.h>
  59. #include <netpacket/packet.h>
  60. #include <linux/filter.h>
  61. /* "struct client_data_t client_data" is in bb_common_bufsiz1 */
  62. static const struct dhcp_optflag d6_optflags[] = {
  63. #if ENABLE_FEATURE_UDHCPC6_RFC3646
  64. { OPTION_6RD | OPTION_LIST | OPTION_REQ, D6_OPT_DNS_SERVERS },
  65. { OPTION_DNS_STRING | OPTION_LIST | OPTION_REQ, D6_OPT_DOMAIN_LIST },
  66. #endif
  67. #if ENABLE_FEATURE_UDHCPC6_RFC4704
  68. { OPTION_DNS_STRING, D6_OPT_CLIENT_FQDN },
  69. #endif
  70. #if ENABLE_FEATURE_UDHCPC6_RFC4833
  71. { OPTION_STRING, D6_OPT_TZ_POSIX },
  72. { OPTION_STRING, D6_OPT_TZ_NAME },
  73. #endif
  74. #if ENABLE_FEATURE_UDHCPC6_RFC5970
  75. { OPTION_STRING, D6_OPT_BOOT_URL },
  76. { OPTION_STRING, D6_OPT_BOOT_PARAM },
  77. #endif
  78. { OPTION_STRING, 0xd1 }, /* DHCP_PXE_CONF_FILE */
  79. { OPTION_STRING, 0xd2 }, /* DHCP_PXE_PATH_PREFIX */
  80. { 0, 0 }
  81. };
  82. /* Must match d6_optflags[] order */
  83. static const char d6_option_strings[] ALIGN1 =
  84. #if ENABLE_FEATURE_UDHCPC6_RFC3646
  85. "dns" "\0" /* D6_OPT_DNS_SERVERS */
  86. "search" "\0" /* D6_OPT_DOMAIN_LIST */
  87. #endif
  88. #if ENABLE_FEATURE_UDHCPC6_RFC4704
  89. "fqdn" "\0" /* D6_OPT_CLIENT_FQDN */
  90. #endif
  91. #if ENABLE_FEATURE_UDHCPC6_RFC4833
  92. "tz" "\0" /* D6_OPT_TZ_POSIX */
  93. "timezone" "\0" /* D6_OPT_TZ_NAME */
  94. #endif
  95. #if ENABLE_FEATURE_UDHCPC6_RFC5970
  96. "bootfile_url" "\0" /* D6_OPT_BOOT_URL */
  97. "bootfile_param" "\0" /* D6_OPT_BOOT_PARAM */
  98. #endif
  99. "pxeconffile" "\0" /* DHCP_PXE_CONF_FILE */
  100. "pxepathprefix" "\0" /* DHCP_PXE_PATH_PREFIX */
  101. "\0";
  102. #if ENABLE_LONG_OPTS
  103. static const char udhcpc6_longopts[] ALIGN1 =
  104. "interface\0" Required_argument "i"
  105. "now\0" No_argument "n"
  106. "pidfile\0" Required_argument "p"
  107. "quit\0" No_argument "q"
  108. "release\0" No_argument "R"
  109. "request\0" Required_argument "r"
  110. "requestprefix\0" No_argument "d"
  111. "script\0" Required_argument "s"
  112. "timeout\0" Required_argument "T"
  113. "retries\0" Required_argument "t"
  114. "tryagain\0" Required_argument "A"
  115. "syslog\0" No_argument "S"
  116. "request-option\0" Required_argument "O"
  117. "no-default-options\0" No_argument "o"
  118. "foreground\0" No_argument "f"
  119. "stateless\0" No_argument "l"
  120. USE_FOR_MMU(
  121. "background\0" No_argument "b"
  122. )
  123. /// IF_FEATURE_UDHCPC_ARPING("arping\0" No_argument "a")
  124. IF_FEATURE_UDHCP_PORT("client-port\0" Required_argument "P")
  125. ;
  126. #endif
  127. /* Must match getopt32 option string order */
  128. enum {
  129. OPT_i = 1 << 0,
  130. OPT_n = 1 << 1,
  131. OPT_p = 1 << 2,
  132. OPT_q = 1 << 3,
  133. OPT_R = 1 << 4,
  134. OPT_r = 1 << 5,
  135. OPT_s = 1 << 6,
  136. OPT_T = 1 << 7,
  137. OPT_t = 1 << 8,
  138. OPT_S = 1 << 9,
  139. OPT_A = 1 << 10,
  140. OPT_O = 1 << 11,
  141. OPT_o = 1 << 12,
  142. OPT_x = 1 << 13,
  143. OPT_f = 1 << 14,
  144. OPT_l = 1 << 15,
  145. OPT_d = 1 << 16,
  146. /* The rest has variable bit positions, need to be clever */
  147. OPTBIT_d = 16,
  148. USE_FOR_MMU( OPTBIT_b,)
  149. ///IF_FEATURE_UDHCPC_ARPING(OPTBIT_a,)
  150. IF_FEATURE_UDHCP_PORT( OPTBIT_P,)
  151. USE_FOR_MMU( OPT_b = 1 << OPTBIT_b,)
  152. ///IF_FEATURE_UDHCPC_ARPING(OPT_a = 1 << OPTBIT_a,)
  153. IF_FEATURE_UDHCP_PORT( OPT_P = 1 << OPTBIT_P,)
  154. };
  155. #if ENABLE_FEATURE_UDHCPC6_RFC4704
  156. static const char opt_fqdn_req[] = {
  157. (D6_OPT_CLIENT_FQDN >> 8), (D6_OPT_CLIENT_FQDN & 0xff),
  158. 0, 2, /* optlen */
  159. 0, /* flags: */
  160. /* S=0: server SHOULD NOT perform AAAA RR updates */
  161. /* O=0: client MUST set this bit to 0 */
  162. /* N=0: server SHOULD perform updates (PTR RR only in our case, since S=0) */
  163. 0 /* empty DNS-encoded name */
  164. };
  165. #endif
  166. /*** Utility functions ***/
  167. static void *d6_find_option(uint8_t *option, uint8_t *option_end, unsigned code)
  168. {
  169. /* "length minus 4" */
  170. int len_m4 = option_end - option - 4;
  171. while (len_m4 >= 0) {
  172. /* Next option's len is too big? */
  173. if (option[3] > len_m4)
  174. return NULL; /* yes. bogus packet! */
  175. /* So far we treat any opts with code >255
  176. * or len >255 as bogus, and stop at once.
  177. * This simplifies big-endian handling.
  178. */
  179. if (option[0] != 0 || option[2] != 0)
  180. return NULL;
  181. /* Option seems to be valid */
  182. /* Does its code match? */
  183. if (option[1] == code)
  184. return option; /* yes! */
  185. len_m4 -= option[3] + 4;
  186. option += option[3] + 4;
  187. }
  188. return NULL;
  189. }
  190. static void *d6_copy_option(uint8_t *option, uint8_t *option_end, unsigned code)
  191. {
  192. uint8_t *opt = d6_find_option(option, option_end, code);
  193. if (!opt)
  194. return opt;
  195. return xmemdup(opt, opt[3] + 4);
  196. }
  197. /*** Script execution code ***/
  198. static char** new_env(void)
  199. {
  200. client6_data.env_ptr = xrealloc_vector(client6_data.env_ptr, 3, client6_data.env_idx);
  201. return &client6_data.env_ptr[client6_data.env_idx++];
  202. }
  203. static char *string_option_to_env(const uint8_t *option,
  204. const uint8_t *option_end)
  205. {
  206. const char *ptr, *name = NULL;
  207. unsigned val_len;
  208. int i;
  209. ptr = d6_option_strings;
  210. i = 0;
  211. while (*ptr) {
  212. if (d6_optflags[i].code == option[1]) {
  213. name = ptr;
  214. goto found;
  215. }
  216. ptr += strlen(ptr) + 1;
  217. i++;
  218. }
  219. bb_error_msg("can't find option name for 0x%x, skipping", option[1]);
  220. return NULL;
  221. found:
  222. val_len = (option[2] << 8) | option[3];
  223. if (val_len + &option[D6_OPT_DATA] > option_end) {
  224. bb_simple_error_msg("option data exceeds option length");
  225. return NULL;
  226. }
  227. return xasprintf("%s=%.*s", name, val_len, (char*)option + 4);
  228. }
  229. /* put all the parameters into the environment */
  230. static void option_to_env(const uint8_t *option, const uint8_t *option_end)
  231. {
  232. #if ENABLE_FEATURE_UDHCPC6_RFC3646
  233. int addrs, option_offset;
  234. #endif
  235. /* "length minus 4" */
  236. int len_m4 = option_end - option - 4;
  237. while (len_m4 >= 0) {
  238. uint32_t v32;
  239. char ipv6str[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")];
  240. if (option[0] != 0 || option[2] != 0)
  241. break;
  242. /* Check if option-length exceeds size of option */
  243. if (option[3] > len_m4)
  244. break;
  245. switch (option[1]) {
  246. //case D6_OPT_CLIENTID:
  247. //case D6_OPT_SERVERID:
  248. case D6_OPT_IA_NA:
  249. case D6_OPT_IA_PD:
  250. option_to_env(option + 16, option + 4 + option[3]);
  251. break;
  252. //case D6_OPT_IA_TA:
  253. case D6_OPT_IAADDR:
  254. /* 0 1 2 3
  255. * 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
  256. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  257. * | OPTION_IAADDR | option-len |
  258. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  259. * | |
  260. * | IPv6 address |
  261. * | |
  262. * | |
  263. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  264. * | preferred-lifetime |
  265. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  266. * | valid-lifetime |
  267. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  268. */
  269. /* Make sure payload contains an address */
  270. if (option[3] < 24)
  271. break;
  272. sprint_nip6(ipv6str, option + 4);
  273. *new_env() = xasprintf("ipv6=%s", ipv6str);
  274. move_from_unaligned32(v32, option + 4 + 16 + 4);
  275. *new_env() = xasprintf("lease=%u", (unsigned)v32);
  276. break;
  277. //case D6_OPT_ORO:
  278. //case D6_OPT_PREFERENCE:
  279. //case D6_OPT_ELAPSED_TIME:
  280. //case D6_OPT_RELAY_MSG:
  281. //case D6_OPT_AUTH:
  282. //case D6_OPT_UNICAST:
  283. //case D6_OPT_STATUS_CODE:
  284. //case D6_OPT_RAPID_COMMIT:
  285. //case D6_OPT_USER_CLASS:
  286. //case D6_OPT_VENDOR_CLASS:
  287. //case D6_OPT_VENDOR_OPTS:
  288. //case D6_OPT_INTERFACE_ID:
  289. //case D6_OPT_RECONF_MSG:
  290. //case D6_OPT_RECONF_ACCEPT:
  291. case D6_OPT_IAPREFIX:
  292. /* 0 1 2 3
  293. * 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
  294. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  295. * | OPTION_IAPREFIX | option-length |
  296. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  297. * | preferred-lifetime |
  298. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  299. * | valid-lifetime |
  300. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  301. * | prefix-length | |
  302. * +-+-+-+-+-+-+-+-+ IPv6 prefix |
  303. * | (16 octets) |
  304. * | |
  305. * | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  306. * | |
  307. * +-+-+-+-+-+-+-+-+
  308. */
  309. move_from_unaligned32(v32, option + 4 + 4);
  310. *new_env() = xasprintf("ipv6prefix_lease=%u", (unsigned)v32);
  311. sprint_nip6(ipv6str, option + 4 + 4 + 4 + 1);
  312. *new_env() = xasprintf("ipv6prefix=%s/%u", ipv6str, (unsigned)(option[4 + 4 + 4]));
  313. break;
  314. #if ENABLE_FEATURE_UDHCPC6_RFC3646
  315. case D6_OPT_DNS_SERVERS: {
  316. char *dlist;
  317. /* Make sure payload-size is a multiple of 16 */
  318. if ((option[3] & 0x0f) != 0)
  319. break;
  320. /* Get the number of addresses on the option */
  321. addrs = option[3] >> 4;
  322. /* Setup environment variable */
  323. *new_env() = dlist = xmalloc(4 + addrs * 40 - 1);
  324. dlist = stpcpy(dlist, "dns=");
  325. option_offset = 0;
  326. while (addrs--) {
  327. sprint_nip6(dlist, option + 4 + option_offset);
  328. dlist += 39;
  329. option_offset += 16;
  330. if (addrs)
  331. *dlist++ = ' ';
  332. }
  333. break;
  334. }
  335. case D6_OPT_DOMAIN_LIST: {
  336. char *dlist;
  337. dlist = dname_dec(option + 4, (option[2] << 8) | option[3], "search=");
  338. if (!dlist)
  339. break;
  340. *new_env() = dlist;
  341. break;
  342. }
  343. #endif
  344. #if ENABLE_FEATURE_UDHCPC6_RFC4704
  345. case D6_OPT_CLIENT_FQDN: {
  346. char *dlist;
  347. if (option[3] == 0)
  348. break;
  349. /* Work around broken ISC DHCPD6.
  350. * ISC DHCPD6 does not implement RFC 4704 correctly: It says the first
  351. * byte of option-payload should contain flags where the bits 7-3 are
  352. * reserved for future use and MUST be zero. Instead ISC DHCPD6 just
  353. * writes the entire FQDN as string to option-payload. We assume a
  354. * broken server here if any of the reserved bits are set.
  355. */
  356. if (option[4] & 0xf8) {
  357. *new_env() = xasprintf("fqdn=%.*s", (int)option[3], (char*)option + 4);
  358. break;
  359. }
  360. dlist = dname_dec(option + 5, (/*(option[2] << 8) |*/ option[3]) - 1, "fqdn=");
  361. if (!dlist)
  362. break;
  363. *new_env() = dlist;
  364. break;
  365. }
  366. #endif
  367. #if ENABLE_FEATURE_UDHCPC6_RFC4833
  368. /* RFC 4833 Timezones */
  369. case D6_OPT_TZ_POSIX:
  370. *new_env() = xasprintf("tz=%.*s", (int)option[3], (char*)option + 4);
  371. break;
  372. case D6_OPT_TZ_NAME:
  373. *new_env() = xasprintf("tz_name=%.*s", (int)option[3], (char*)option + 4);
  374. break;
  375. #endif
  376. case D6_OPT_BOOT_URL:
  377. case D6_OPT_BOOT_PARAM:
  378. case 0xd1: /* DHCP_PXE_CONF_FILE */
  379. case 0xd2: /* DHCP_PXE_PATH_PREFIX */
  380. {
  381. char *tmp = string_option_to_env(option, option_end);
  382. if (tmp)
  383. *new_env() = tmp;
  384. break;
  385. }
  386. }
  387. len_m4 -= 4 + option[3];
  388. option += 4 + option[3];
  389. }
  390. }
  391. static char **fill_envp(const uint8_t *option, const uint8_t *option_end)
  392. {
  393. char **envp, **curr;
  394. client6_data.env_ptr = NULL;
  395. client6_data.env_idx = 0;
  396. *new_env() = xasprintf("interface=%s", client_data.interface);
  397. if (option)
  398. option_to_env(option, option_end);
  399. envp = curr = client6_data.env_ptr;
  400. while (*curr)
  401. putenv(*curr++);
  402. return envp;
  403. }
  404. /* Call a script with a par file and env vars */
  405. static void d6_run_script(const uint8_t *option, const uint8_t *option_end,
  406. const char *name)
  407. {
  408. char **envp, **curr;
  409. char *argv[3];
  410. envp = fill_envp(option, option_end);
  411. /* call script */
  412. log1("executing %s %s", client_data.script, name);
  413. argv[0] = (char*) client_data.script;
  414. argv[1] = (char*) name;
  415. argv[2] = NULL;
  416. spawn_and_wait(argv);
  417. for (curr = envp; *curr; curr++) {
  418. log2(" %s", *curr);
  419. bb_unsetenv_and_free(*curr);
  420. }
  421. free(envp);
  422. }
  423. /* Call a script with a par file and no env var */
  424. static void d6_run_script_no_option(const char *name)
  425. {
  426. d6_run_script(NULL, NULL, name);
  427. }
  428. /*** Sending/receiving packets ***/
  429. static ALWAYS_INLINE uint32_t random_xid(void)
  430. {
  431. uint32_t t = rand() & htonl(0x00ffffff);
  432. return t;
  433. }
  434. /* Initialize the packet with the proper defaults */
  435. static uint8_t *init_d6_packet(struct d6_packet *packet, char type, uint32_t xid)
  436. {
  437. uint8_t *ptr;
  438. struct d6_option *clientid;
  439. unsigned secs;
  440. memset(packet, 0, sizeof(*packet));
  441. packet->d6_xid32 = xid;
  442. packet->d6_msg_type = type;
  443. /* ELAPSED_TIME option is required to be present by the RFC,
  444. * and some servers do check for its presense. [which?]
  445. */
  446. ptr = packet->d6_options; /* NB: it is 32-bit aligned */
  447. *((uint32_t*)ptr) = htonl((D6_OPT_ELAPSED_TIME << 16) + 2);
  448. ptr += 4;
  449. client_data.last_secs = monotonic_sec();
  450. if (client_data.first_secs == 0)
  451. client_data.first_secs = client_data.last_secs;
  452. secs = client_data.last_secs - client_data.first_secs;
  453. *((uint16_t*)ptr) = (secs < 0xffff) ? htons(secs) : 0xffff;
  454. ptr += 2;
  455. /* add CLIENTID option */
  456. clientid = (void*)client_data.clientid;
  457. return mempcpy(ptr, clientid, clientid->len + 2+2);
  458. }
  459. static uint8_t *add_d6_client_options(uint8_t *ptr)
  460. {
  461. struct option_set *curr;
  462. uint8_t *start = ptr;
  463. unsigned option;
  464. uint16_t len;
  465. ptr += 4;
  466. for (option = 1; option < 256; option++) {
  467. if (client_data.opt_mask[option >> 3] & (1 << (option & 7))) {
  468. ptr[0] = (option >> 8);
  469. ptr[1] = option;
  470. ptr += 2;
  471. }
  472. }
  473. if ((ptr - start - 4) != 0) {
  474. start[0] = (D6_OPT_ORO >> 8);
  475. start[1] = D6_OPT_ORO;
  476. start[2] = ((ptr - start - 4) >> 8);
  477. start[3] = (ptr - start - 4);
  478. } else
  479. ptr = start;
  480. #if ENABLE_FEATURE_UDHCPC6_RFC4704
  481. ptr = mempcpy(ptr, &opt_fqdn_req, sizeof(opt_fqdn_req));
  482. #endif
  483. /* Add -x options if any */
  484. curr = client_data.options;
  485. while (curr) {
  486. len = (curr->data[D6_OPT_LEN] << 8) | curr->data[D6_OPT_LEN + 1];
  487. ptr = mempcpy(ptr, curr->data, D6_OPT_DATA + len);
  488. curr = curr->next;
  489. }
  490. return ptr;
  491. }
  492. static int d6_mcast_from_client_data_ifindex(struct d6_packet *packet, uint8_t *end)
  493. {
  494. /* FF02::1:2 is "All_DHCP_Relay_Agents_and_Servers" address */
  495. static const uint8_t FF02__1_2[16] = {
  496. 0xFF, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  497. 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02,
  498. };
  499. /* IPv6 requires different multicast contents in Ethernet Frame (RFC 2464) */
  500. static const uint8_t MAC_DHCP6MCAST_ADDR[6] ALIGN2 = {
  501. 0x33, 0x33, 0x00, 0x01, 0x00, 0x02,
  502. };
  503. return d6_send_raw_packet(
  504. packet, (end - (uint8_t*) packet),
  505. /*src*/ &client6_data.ll_ip6, CLIENT_PORT6,
  506. /*dst*/ (struct in6_addr*)FF02__1_2, SERVER_PORT6, MAC_DHCP6MCAST_ADDR,
  507. client_data.ifindex
  508. );
  509. }
  510. /* RFC 3315 18.1.5. Creation and Transmission of Information-request Messages
  511. *
  512. * The client uses an Information-request message to obtain
  513. * configuration information without having addresses assigned to it.
  514. *
  515. * The client sets the "msg-type" field to INFORMATION-REQUEST. The
  516. * client generates a transaction ID and inserts this value in the
  517. * "transaction-id" field.
  518. *
  519. * The client SHOULD include a Client Identifier option to identify
  520. * itself to the server. If the client does not include a Client
  521. * Identifier option, the server will not be able to return any client-
  522. * specific options to the client, or the server may choose not to
  523. * respond to the message at all. The client MUST include a Client
  524. * Identifier option if the Information-Request message will be
  525. * authenticated.
  526. *
  527. * The client MUST include an Option Request option (see section 22.7)
  528. * to indicate the options the client is interested in receiving. The
  529. * client MAY include options with data values as hints to the server
  530. * about parameter values the client would like to have returned.
  531. */
  532. /* NOINLINE: limit stack usage in caller */
  533. static NOINLINE int send_d6_info_request(uint32_t xid)
  534. {
  535. struct d6_packet packet;
  536. uint8_t *opt_ptr;
  537. /* Fill in: msg type, client id */
  538. opt_ptr = init_d6_packet(&packet, D6_MSG_INFORMATION_REQUEST, xid);
  539. /* Add options:
  540. * "param req" option according to -O, options specified with -x
  541. */
  542. opt_ptr = add_d6_client_options(opt_ptr);
  543. bb_error_msg("sending %s", "info request");
  544. return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
  545. }
  546. /* Milticast a DHCPv6 Solicit packet to the network, with an optionally requested IP.
  547. *
  548. * RFC 3315 17.1.1. Creation of Solicit Messages
  549. *
  550. * The client MUST include a Client Identifier option to identify itself
  551. * to the server. The client includes IA options for any IAs to which
  552. * it wants the server to assign addresses. The client MAY include
  553. * addresses in the IAs as a hint to the server about addresses for
  554. * which the client has a preference. ...
  555. *
  556. * The client uses IA_NA options to request the assignment of non-
  557. * temporary addresses and uses IA_TA options to request the assignment
  558. * of temporary addresses. Either IA_NA or IA_TA options, or a
  559. * combination of both, can be included in DHCP messages.
  560. *
  561. * The client SHOULD include an Option Request option (see section 22.7)
  562. * to indicate the options the client is interested in receiving. The
  563. * client MAY additionally include instances of those options that are
  564. * identified in the Option Request option, with data values as hints to
  565. * the server about parameter values the client would like to have
  566. * returned.
  567. *
  568. * The client includes a Reconfigure Accept option (see section 22.20)
  569. * if the client is willing to accept Reconfigure messages from the
  570. * server.
  571. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  572. | OPTION_CLIENTID | option-len |
  573. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  574. . .
  575. . DUID .
  576. . (variable length) .
  577. . .
  578. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  579. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  580. | OPTION_IA_NA | option-len |
  581. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  582. | IAID (4 octets) |
  583. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  584. | T1 |
  585. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  586. | T2 |
  587. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  588. | |
  589. . IA_NA-options .
  590. . .
  591. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  592. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  593. | OPTION_IAADDR | option-len |
  594. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  595. | |
  596. | IPv6 address |
  597. | |
  598. | |
  599. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  600. | preferred-lifetime |
  601. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  602. | valid-lifetime |
  603. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  604. . .
  605. . IAaddr-options .
  606. . .
  607. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  608. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  609. | OPTION_ORO | option-len |
  610. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  611. | requested-option-code-1 | requested-option-code-2 |
  612. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  613. | ... |
  614. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  615. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  616. | OPTION_RECONF_ACCEPT | 0 |
  617. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  618. */
  619. /* NOINLINE: limit stack usage in caller */
  620. static NOINLINE int send_d6_discover(uint32_t xid, struct in6_addr *requested_ipv6)
  621. {
  622. struct d6_packet packet;
  623. uint8_t *opt_ptr;
  624. unsigned len;
  625. /* Fill in: msg type, client id */
  626. opt_ptr = init_d6_packet(&packet, D6_MSG_SOLICIT, xid);
  627. /* Create new IA_NA, optionally with included IAADDR with requested IP */
  628. free(client6_data.ia_na);
  629. client6_data.ia_na = NULL;
  630. if (option_mask32 & OPT_r) {
  631. len = requested_ipv6 ? 2+2+4+4+4 + 2+2+16+4+4 : 2+2+4+4+4;
  632. client6_data.ia_na = xzalloc(len);
  633. client6_data.ia_na->code = D6_OPT_IA_NA;
  634. client6_data.ia_na->len = len - 4;
  635. *(bb__aliased_uint32_t*)client6_data.ia_na->data = rand(); /* IAID */
  636. if (requested_ipv6) {
  637. struct d6_option *iaaddr = (void*)(client6_data.ia_na->data + 4+4+4);
  638. iaaddr->code = D6_OPT_IAADDR;
  639. iaaddr->len = 16+4+4;
  640. memcpy(iaaddr->data, requested_ipv6, 16);
  641. }
  642. opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, len);
  643. }
  644. /* IA_PD */
  645. free(client6_data.ia_pd);
  646. client6_data.ia_pd = NULL;
  647. if (option_mask32 & OPT_d) {
  648. len = 2+2+4+4+4;
  649. client6_data.ia_pd = xzalloc(len);
  650. client6_data.ia_pd->code = D6_OPT_IA_PD;
  651. client6_data.ia_pd->len = len - 4;
  652. *(bb__aliased_uint32_t*)client6_data.ia_pd->data = rand(); /* IAID */
  653. opt_ptr = mempcpy(opt_ptr, client6_data.ia_pd, len);
  654. }
  655. /* Add options:
  656. * "param req" option according to -O, options specified with -x
  657. */
  658. opt_ptr = add_d6_client_options(opt_ptr);
  659. bb_info_msg("sending %s", "discover");
  660. return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
  661. }
  662. /* Multicast a DHCPv6 request message
  663. *
  664. * RFC 3315 18.1.1. Creation and Transmission of Request Messages
  665. *
  666. * The client uses a Request message to populate IAs with addresses and
  667. * obtain other configuration information. The client includes one or
  668. * more IA options in the Request message. The server then returns
  669. * addresses and other information about the IAs to the client in IA
  670. * options in a Reply message.
  671. *
  672. * The client generates a transaction ID and inserts this value in the
  673. * "transaction-id" field.
  674. *
  675. * The client places the identifier of the destination server in a
  676. * Server Identifier option.
  677. *
  678. * The client MUST include a Client Identifier option to identify itself
  679. * to the server. The client adds any other appropriate options,
  680. * including one or more IA options (if the client is requesting that
  681. * the server assign it some network addresses).
  682. *
  683. * The client MUST include an Option Request option (see section 22.7)
  684. * to indicate the options the client is interested in receiving. The
  685. * client MAY include options with data values as hints to the server
  686. * about parameter values the client would like to have returned.
  687. *
  688. * The client includes a Reconfigure Accept option (see section 22.20)
  689. * indicating whether or not the client is willing to accept Reconfigure
  690. * messages from the server.
  691. */
  692. /* NOINLINE: limit stack usage in caller */
  693. static NOINLINE int send_d6_select(uint32_t xid)
  694. {
  695. struct d6_packet packet;
  696. uint8_t *opt_ptr;
  697. /* Fill in: msg type, client id */
  698. opt_ptr = init_d6_packet(&packet, D6_MSG_REQUEST, xid);
  699. /* server id */
  700. opt_ptr = mempcpy(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
  701. /* IA NA (contains requested IP) */
  702. if (client6_data.ia_na)
  703. opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
  704. /* IA PD */
  705. if (client6_data.ia_pd)
  706. opt_ptr = mempcpy(opt_ptr, client6_data.ia_pd, client6_data.ia_pd->len + 2+2);
  707. /* Add options:
  708. * "param req" option according to -O, options specified with -x
  709. */
  710. opt_ptr = add_d6_client_options(opt_ptr);
  711. bb_info_msg("sending %s", "select");
  712. return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
  713. }
  714. /* Unicast or broadcast a DHCP renew message
  715. *
  716. * RFC 3315 18.1.3. Creation and Transmission of Renew Messages
  717. *
  718. * To extend the valid and preferred lifetimes for the addresses
  719. * associated with an IA, the client sends a Renew message to the server
  720. * from which the client obtained the addresses in the IA containing an
  721. * IA option for the IA. The client includes IA Address options in the
  722. * IA option for the addresses associated with the IA. The server
  723. * determines new lifetimes for the addresses in the IA according to the
  724. * administrative configuration of the server. The server may also add
  725. * new addresses to the IA. The server may remove addresses from the IA
  726. * by setting the preferred and valid lifetimes of those addresses to
  727. * zero.
  728. *
  729. * The server controls the time at which the client contacts the server
  730. * to extend the lifetimes on assigned addresses through the T1 and T2
  731. * parameters assigned to an IA.
  732. *
  733. * At time T1 for an IA, the client initiates a Renew/Reply message
  734. * exchange to extend the lifetimes on any addresses in the IA. The
  735. * client includes an IA option with all addresses currently assigned to
  736. * the IA in its Renew message.
  737. *
  738. * If T1 or T2 is set to 0 by the server (for an IA_NA) or there are no
  739. * T1 or T2 times (for an IA_TA), the client may send a Renew or Rebind
  740. * message, respectively, at the client's discretion.
  741. *
  742. * The client sets the "msg-type" field to RENEW. The client generates
  743. * a transaction ID and inserts this value in the "transaction-id"
  744. * field.
  745. *
  746. * The client places the identifier of the destination server in a
  747. * Server Identifier option.
  748. *
  749. * The client MUST include a Client Identifier option to identify itself
  750. * to the server. The client adds any appropriate options, including
  751. * one or more IA options. The client MUST include the list of
  752. * addresses the client currently has associated with the IAs in the
  753. * Renew message.
  754. *
  755. * The client MUST include an Option Request option (see section 22.7)
  756. * to indicate the options the client is interested in receiving. The
  757. * client MAY include options with data values as hints to the server
  758. * about parameter values the client would like to have returned.
  759. */
  760. /* NOINLINE: limit stack usage in caller */
  761. static NOINLINE int send_d6_renew(uint32_t xid, struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
  762. {
  763. struct d6_packet packet;
  764. uint8_t *opt_ptr;
  765. /* Fill in: msg type, client id */
  766. opt_ptr = init_d6_packet(&packet, DHCPREQUEST, xid);
  767. /* server id */
  768. opt_ptr = mempcpy(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
  769. /* IA NA (contains requested IP) */
  770. if (client6_data.ia_na)
  771. opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
  772. /* IA PD */
  773. if (client6_data.ia_pd)
  774. opt_ptr = mempcpy(opt_ptr, client6_data.ia_pd, client6_data.ia_pd->len + 2+2);
  775. /* Add options:
  776. * "param req" option according to -O, options specified with -x
  777. */
  778. opt_ptr = add_d6_client_options(opt_ptr);
  779. bb_info_msg("sending %s", "renew");
  780. if (server_ipv6)
  781. return d6_send_kernel_packet(
  782. &packet, (opt_ptr - (uint8_t*) &packet),
  783. our_cur_ipv6, CLIENT_PORT6,
  784. server_ipv6, SERVER_PORT6,
  785. client_data.ifindex
  786. );
  787. return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
  788. }
  789. /* Unicast a DHCP release message */
  790. static
  791. ALWAYS_INLINE /* one caller, help compiler to use this fact */
  792. int send_d6_release(struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
  793. {
  794. struct d6_packet packet;
  795. uint8_t *opt_ptr;
  796. /* Fill in: msg type, client id */
  797. opt_ptr = init_d6_packet(&packet, D6_MSG_RELEASE, random_xid());
  798. /* server id */
  799. opt_ptr = mempcpy(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
  800. /* IA NA (contains our current IP) */
  801. if (client6_data.ia_na)
  802. opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
  803. /* IA PD */
  804. if (client6_data.ia_pd)
  805. opt_ptr = mempcpy(opt_ptr, client6_data.ia_pd, client6_data.ia_pd->len + 2+2);
  806. bb_info_msg("sending %s", "release");
  807. return d6_send_kernel_packet(
  808. &packet, (opt_ptr - (uint8_t*) &packet),
  809. our_cur_ipv6, CLIENT_PORT6,
  810. server_ipv6, SERVER_PORT6,
  811. client_data.ifindex
  812. );
  813. }
  814. /* Returns -1 on errors that are fatal for the socket, -2 for those that aren't */
  815. /* NOINLINE: limit stack usage in caller */
  816. static NOINLINE int d6_recv_raw_packet(struct in6_addr *peer_ipv6, struct d6_packet *d6_pkt, int fd)
  817. {
  818. int bytes;
  819. struct ip6_udp_d6_packet packet;
  820. bytes = safe_read(fd, &packet, sizeof(packet));
  821. if (bytes < 0) {
  822. log1s("packet read error, ignoring");
  823. /* NB: possible down interface, etc. Caller should pause. */
  824. return bytes; /* returns -1 */
  825. }
  826. if (bytes < (int) (sizeof(packet.ip6) + sizeof(packet.udp))) {
  827. log1s("packet is too short, ignoring");
  828. return -2;
  829. }
  830. if (bytes < sizeof(packet.ip6) + ntohs(packet.ip6.ip6_plen)) {
  831. /* packet is bigger than sizeof(packet), we did partial read */
  832. log1s("oversized packet, ignoring");
  833. return -2;
  834. }
  835. /* ignore any extra garbage bytes */
  836. bytes = sizeof(packet.ip6) + ntohs(packet.ip6.ip6_plen);
  837. /* make sure its the right packet for us, and that it passes sanity checks */
  838. if (packet.ip6.ip6_nxt != IPPROTO_UDP
  839. || (packet.ip6.ip6_vfc >> 4) != 6
  840. || packet.udp.dest != htons(CLIENT_PORT6)
  841. /* || bytes > (int) sizeof(packet) - can't happen */
  842. || packet.udp.len != packet.ip6.ip6_plen
  843. ) {
  844. log1s("unrelated/bogus packet, ignoring");
  845. return -2;
  846. }
  847. //How to do this for ipv6?
  848. // /* verify UDP checksum. IP header has to be modified for this */
  849. // memset(&packet.ip, 0, offsetof(struct iphdr, protocol));
  850. // /* ip.xx fields which are not memset: protocol, check, saddr, daddr */
  851. // packet.ip.tot_len = packet.udp.len; /* yes, this is needed */
  852. // check = packet.udp.check;
  853. // packet.udp.check = 0;
  854. // if (check && check != inet_cksum((uint16_t *)&packet, bytes)) {
  855. // log1("packet with bad UDP checksum received, ignoring");
  856. // return -2;
  857. // }
  858. if (peer_ipv6)
  859. *peer_ipv6 = packet.ip6.ip6_src; /* struct copy */
  860. log1("received %s", "a packet");
  861. d6_dump_packet(&packet.data);
  862. bytes -= sizeof(packet.ip6) + sizeof(packet.udp);
  863. memcpy(d6_pkt, &packet.data, bytes);
  864. return bytes;
  865. }
  866. /*** Main ***/
  867. /* Values for client_data.listen_mode */
  868. #define LISTEN_NONE 0
  869. #define LISTEN_KERNEL 1
  870. #define LISTEN_RAW 2
  871. /* Values for client_data.state */
  872. /* initial state: (re)start DHCP negotiation */
  873. #define INIT_SELECTING 0
  874. /* discover was sent, DHCPOFFER reply received */
  875. #define REQUESTING 1
  876. /* select/renew was sent, DHCPACK reply received */
  877. #define BOUND 2
  878. /* half of lease passed, want to renew it by sending unicast renew requests */
  879. #define RENEWING 3
  880. /* renew requests were not answered, lease is almost over, send broadcast renew */
  881. #define REBINDING 4
  882. /* manually requested renew (SIGUSR1) */
  883. #define RENEW_REQUESTED 5
  884. /* release, possibly manually requested (SIGUSR2) */
  885. #define RELEASED 6
  886. static int d6_raw_socket(int ifindex)
  887. {
  888. int fd;
  889. struct sockaddr_ll sock;
  890. /*
  891. * Comment:
  892. *
  893. * I've selected not to see LL header, so BPF doesn't see it, too.
  894. * The filter may also pass non-IP and non-ARP packets, but we do
  895. * a more complete check when receiving the message in userspace.
  896. *
  897. * and filter shamelessly stolen from:
  898. *
  899. * http://www.flamewarmaster.de/software/dhcpclient/
  900. *
  901. * There are a few other interesting ideas on that page (look under
  902. * "Motivation"). Use of netlink events is most interesting. Think
  903. * of various network servers listening for events and reconfiguring.
  904. * That would obsolete sending HUP signals and/or make use of restarts.
  905. *
  906. * Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
  907. * License: GPL v2.
  908. *
  909. * TODO: make conditional?
  910. */
  911. #if 0
  912. static const struct sock_filter filter_instr[] = {
  913. /* load 9th byte (protocol) */
  914. BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
  915. /* jump to L1 if it is IPPROTO_UDP, else to L4 */
  916. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 0, 6),
  917. /* L1: load halfword from offset 6 (flags and frag offset) */
  918. BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 6),
  919. /* jump to L4 if any bits in frag offset field are set, else to L2 */
  920. BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K, 0x1fff, 4, 0),
  921. /* L2: skip IP header (load index reg with header len) */
  922. BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0),
  923. /* load udp destination port from halfword[header_len + 2] */
  924. BPF_STMT(BPF_LD|BPF_H|BPF_IND, 2),
  925. /* jump to L3 if udp dport is CLIENT_PORT6, else to L4 */
  926. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 68, 0, 1),
  927. /* L3: accept packet */
  928. BPF_STMT(BPF_RET|BPF_K, 0x7fffffff),
  929. /* L4: discard packet */
  930. BPF_STMT(BPF_RET|BPF_K, 0),
  931. };
  932. static const struct sock_fprog filter_prog = {
  933. .len = sizeof(filter_instr) / sizeof(filter_instr[0]),
  934. /* casting const away: */
  935. .filter = (struct sock_filter *) filter_instr,
  936. };
  937. #endif
  938. log2("opening raw socket on ifindex %d", ifindex);
  939. fd = xsocket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IPV6));
  940. log3("got raw socket fd %d", fd);
  941. memset(&sock, 0, sizeof(sock)); /* let's be deterministic */
  942. sock.sll_family = AF_PACKET;
  943. sock.sll_protocol = htons(ETH_P_IPV6);
  944. sock.sll_ifindex = ifindex;
  945. /*sock.sll_hatype = ARPHRD_???;*/
  946. /*sock.sll_pkttype = PACKET_???;*/
  947. /*sock.sll_halen = ???;*/
  948. /*sock.sll_addr[8] = ???;*/
  949. xbind(fd, (struct sockaddr *) &sock, sizeof(sock));
  950. #if 0
  951. if (CLIENT_PORT6 == 546) {
  952. /* Use only if standard port is in use */
  953. /* Ignoring error (kernel may lack support for this) */
  954. if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog,
  955. sizeof(filter_prog)) >= 0)
  956. log1("attached filter to raw socket fd %d", fd); // log?
  957. }
  958. #endif
  959. log1s("created raw socket");
  960. return fd;
  961. }
  962. static void change_listen_mode(int new_mode)
  963. {
  964. log1("entering listen mode: %s",
  965. new_mode != LISTEN_NONE
  966. ? (new_mode == LISTEN_KERNEL ? "kernel" : "raw")
  967. : "none"
  968. );
  969. client_data.listen_mode = new_mode;
  970. if (client_data.sockfd >= 0) {
  971. close(client_data.sockfd);
  972. client_data.sockfd = -1;
  973. }
  974. if (new_mode == LISTEN_KERNEL)
  975. client_data.sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT6, client_data.interface);
  976. else if (new_mode != LISTEN_NONE)
  977. client_data.sockfd = d6_raw_socket(client_data.ifindex);
  978. /* else LISTEN_NONE: client_data.sockfd stays closed */
  979. }
  980. /* Called only on SIGUSR1 */
  981. static void perform_renew(void)
  982. {
  983. bb_simple_info_msg("performing DHCP renew");
  984. switch (client_data.state) {
  985. case BOUND:
  986. change_listen_mode(LISTEN_KERNEL);
  987. case RENEWING:
  988. case REBINDING:
  989. client_data.state = RENEW_REQUESTED;
  990. break;
  991. case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
  992. d6_run_script_no_option("deconfig");
  993. case REQUESTING:
  994. case RELEASED:
  995. change_listen_mode(LISTEN_RAW);
  996. client_data.state = INIT_SELECTING;
  997. break;
  998. case INIT_SELECTING:
  999. break;
  1000. }
  1001. }
  1002. static void perform_d6_release(struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
  1003. {
  1004. /* send release packet */
  1005. if (client_data.state == BOUND
  1006. || client_data.state == RENEWING
  1007. || client_data.state == REBINDING
  1008. || client_data.state == RENEW_REQUESTED
  1009. ) {
  1010. bb_simple_info_msg("unicasting a release");
  1011. send_d6_release(server_ipv6, our_cur_ipv6); /* 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. d6_run_script_no_option("deconfig");
  1021. change_listen_mode(LISTEN_NONE);
  1022. client_data.state = RELEASED;
  1023. }
  1024. ///static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
  1025. ///{
  1026. /// uint8_t *storage;
  1027. /// int len = strnlen(str, 255);
  1028. /// storage = xzalloc(len + extra + OPT_DATA);
  1029. /// storage[OPT_CODE] = code;
  1030. /// storage[OPT_LEN] = len + extra;
  1031. /// memcpy(storage + extra + OPT_DATA, str, len);
  1032. /// return storage;
  1033. ///}
  1034. #if BB_MMU
  1035. static void client_background(void)
  1036. {
  1037. bb_daemonize(0);
  1038. logmode &= ~LOGMODE_STDIO;
  1039. /* rewrite pidfile, as our pid is different now */
  1040. write_pidfile(client_data.pidfile);
  1041. }
  1042. #endif
  1043. //usage:#if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
  1044. //usage:# define IF_UDHCP_VERBOSE(...) __VA_ARGS__
  1045. //usage:#else
  1046. //usage:# define IF_UDHCP_VERBOSE(...)
  1047. //usage:#endif
  1048. //usage:#define udhcpc6_trivial_usage
  1049. //usage: "[-fbnq"IF_UDHCP_VERBOSE("v")"odR] [-i IFACE] [-r IPv6] [-s PROG] [-p PIDFILE]\n"
  1050. //usage: " [-x OPT:VAL]... [-O OPT]..." IF_FEATURE_UDHCP_PORT(" [-P N]")
  1051. //usage:#define udhcpc6_full_usage "\n"
  1052. //usage: "\n -i IFACE Interface to use (default eth0)"
  1053. //usage: "\n -p FILE Create pidfile"
  1054. //usage: "\n -s PROG Run PROG at DHCP events (default "CONFIG_UDHCPC_DEFAULT_SCRIPT")"
  1055. //usage: "\n -B Request broadcast replies"
  1056. //usage: "\n -t N Send up to N discover packets"
  1057. //usage: "\n -T N Pause between packets (default 3 seconds)"
  1058. //usage: "\n -A N Wait N seconds (default 20) after failure"
  1059. //usage: "\n -f Run in foreground"
  1060. //usage: USE_FOR_MMU(
  1061. //usage: "\n -b Background if lease is not obtained"
  1062. //usage: )
  1063. //usage: "\n -n Exit if lease is not obtained"
  1064. //usage: "\n -q Exit after obtaining lease"
  1065. //usage: "\n -R Release IP on exit"
  1066. //usage: "\n -S Log to syslog too"
  1067. //usage: IF_FEATURE_UDHCP_PORT(
  1068. //usage: "\n -P N Use port N (default 546)"
  1069. //usage: )
  1070. ////usage: IF_FEATURE_UDHCPC_ARPING(
  1071. ////usage: "\n -a Use arping to validate offered address"
  1072. ////usage: )
  1073. //usage: "\n -O OPT Request option OPT from server (cumulative)"
  1074. //usage: "\n -o Don't request any options (unless -O is given)"
  1075. //usage: "\n -r IPv6 Request this address ('no' to not request any IP)"
  1076. //usage: "\n -d Request prefix"
  1077. //usage: "\n -l Send 'information request' instead of 'solicit'"
  1078. //usage: "\n (used for servers which do not assign IPv6 addresses)"
  1079. //usage: "\n -x OPT:VAL Include option OPT in sent packets (cumulative)"
  1080. //usage: "\n Examples of string, numeric, and hex byte opts:"
  1081. //usage: "\n -x hostname:bbox - option 12"
  1082. //usage: "\n -x lease:3600 - option 51 (lease time)"
  1083. //usage: "\n -x 0x3d:0100BEEFC0FFEE - option 61 (client id)"
  1084. //usage: "\n -x 14:'\"dumpfile\"' - option 14 (shell-quoted)"
  1085. //usage: IF_UDHCP_VERBOSE(
  1086. //usage: "\n -v Verbose"
  1087. //usage: )
  1088. //usage: "\nSignals:"
  1089. //usage: "\n USR1 Renew lease"
  1090. //usage: "\n USR2 Release lease"
  1091. int udhcpc6_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1092. int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
  1093. {
  1094. const char *str_r;
  1095. IF_FEATURE_UDHCP_PORT(char *str_P;)
  1096. void *clientid_mac_ptr;
  1097. llist_t *list_O = NULL;
  1098. llist_t *list_x = NULL;
  1099. int tryagain_timeout = 20;
  1100. int discover_timeout = 3;
  1101. int discover_retries = 3;
  1102. struct in6_addr srv6_buf;
  1103. struct in6_addr ipv6_buf;
  1104. struct in6_addr *requested_ipv6;
  1105. uint32_t xid = 0;
  1106. int packet_num;
  1107. int timeout; /* must be signed */
  1108. unsigned already_waited_sec;
  1109. unsigned opt;
  1110. int retval;
  1111. setup_common_bufsiz();
  1112. /* We want random_xid to be random */
  1113. srand(monotonic_us());
  1114. /* Default options */
  1115. IF_FEATURE_UDHCP_PORT(SERVER_PORT6 = 547;)
  1116. IF_FEATURE_UDHCP_PORT(CLIENT_PORT6 = 546;)
  1117. client_data.interface = "eth0";
  1118. client_data.script = CONFIG_UDHCPC_DEFAULT_SCRIPT;
  1119. client_data.sockfd = -1;
  1120. /* Make sure fd 0,1,2 are open */
  1121. /* Set up the signal pipe on fds 3,4 - must be before openlog() */
  1122. udhcp_sp_setup();
  1123. /* Parse command line */
  1124. opt = getopt32long(argv, "^"
  1125. /* O,x: list; -T,-t,-A take numeric param */
  1126. "i:np:qRr:s:T:+t:+SA:+O:*ox:*fld"
  1127. USE_FOR_MMU("b")
  1128. ///IF_FEATURE_UDHCPC_ARPING("a")
  1129. IF_FEATURE_UDHCP_PORT("P:")
  1130. "v"
  1131. "\0" IF_UDHCP_VERBOSE("vv") /* -v is a counter */
  1132. , udhcpc6_longopts
  1133. , &client_data.interface, &client_data.pidfile, &str_r /* i,p */
  1134. , &client_data.script /* s */
  1135. , &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */
  1136. , &list_O
  1137. , &list_x
  1138. IF_FEATURE_UDHCP_PORT(, &str_P)
  1139. IF_UDHCP_VERBOSE(, &dhcp_verbose)
  1140. );
  1141. requested_ipv6 = NULL;
  1142. option_mask32 |= OPT_r;
  1143. if (opt & OPT_l) {
  1144. /* for -l, do not require IPv6 assignment from server */
  1145. option_mask32 &= ~OPT_r;
  1146. } else if (opt & OPT_r) {
  1147. /* explicit "-r ARG" given */
  1148. if (strcmp(str_r, "no") == 0) {
  1149. option_mask32 &= ~OPT_r;
  1150. } else {
  1151. if (inet_pton(AF_INET6, str_r, &ipv6_buf) <= 0)
  1152. bb_error_msg_and_die("bad IPv6 address '%s'", str_r);
  1153. requested_ipv6 = &ipv6_buf;
  1154. }
  1155. }
  1156. #if ENABLE_FEATURE_UDHCP_PORT
  1157. if (opt & OPT_P) {
  1158. CLIENT_PORT6 = xatou16(str_P);
  1159. SERVER_PORT6 = CLIENT_PORT6 + 1;
  1160. }
  1161. #endif
  1162. while (list_O) {
  1163. char *optstr = llist_pop(&list_O);
  1164. unsigned n = bb_strtou(optstr, NULL, 0);
  1165. if (errno || n > 254) {
  1166. n = udhcp_option_idx(optstr, d6_option_strings);
  1167. n = d6_optflags[n].code;
  1168. }
  1169. client_data.opt_mask[n >> 3] |= 1 << (n & 7);
  1170. }
  1171. if (!(opt & OPT_o)) {
  1172. unsigned i, n;
  1173. for (i = 0; (n = d6_optflags[i].code) != 0; i++) {
  1174. if (d6_optflags[i].flags & OPTION_REQ) {
  1175. client_data.opt_mask[n >> 3] |= 1 << (n & 7);
  1176. }
  1177. }
  1178. }
  1179. while (list_x) {
  1180. char *optstr = xstrdup(llist_pop(&list_x));
  1181. udhcp_str2optset(optstr, &client_data.options,
  1182. d6_optflags, d6_option_strings,
  1183. /*dhcpv6:*/ 1
  1184. );
  1185. free(optstr);
  1186. }
  1187. if (d6_read_interface(client_data.interface,
  1188. &client_data.ifindex,
  1189. &client6_data.ll_ip6,
  1190. client_data.client_mac)
  1191. ) {
  1192. return 1;
  1193. }
  1194. /* Create client ID based on mac, set clientid_mac_ptr */
  1195. {
  1196. struct d6_option *clientid;
  1197. clientid = xzalloc(2+2+2+2+6);
  1198. clientid->code = D6_OPT_CLIENTID;
  1199. clientid->len = 2+2+6;
  1200. clientid->data[1] = 3; /* DUID-LL */
  1201. clientid->data[3] = 1; /* ethernet */
  1202. clientid_mac_ptr = clientid->data + 2+2;
  1203. memcpy(clientid_mac_ptr, client_data.client_mac, 6);
  1204. client_data.clientid = (void*)clientid;
  1205. }
  1206. #if !BB_MMU
  1207. /* on NOMMU reexec (i.e., background) early */
  1208. if (!(opt & OPT_f)) {
  1209. bb_daemonize_or_rexec(0 /* flags */, argv);
  1210. logmode = LOGMODE_NONE;
  1211. }
  1212. #endif
  1213. if (opt & OPT_S) {
  1214. openlog(applet_name, LOG_PID, LOG_DAEMON);
  1215. logmode |= LOGMODE_SYSLOG;
  1216. }
  1217. /* Create pidfile */
  1218. write_pidfile(client_data.pidfile);
  1219. /* Goes to stdout (unless NOMMU) and possibly syslog */
  1220. bb_simple_info_msg("started, v"BB_VER);
  1221. client_data.state = INIT_SELECTING;
  1222. d6_run_script_no_option("deconfig");
  1223. change_listen_mode(LISTEN_RAW);
  1224. packet_num = 0;
  1225. timeout = 0;
  1226. already_waited_sec = 0;
  1227. /* Main event loop. select() waits on signal pipe and possibly
  1228. * on sockfd.
  1229. * "continue" statements in code below jump to the top of the loop.
  1230. */
  1231. for (;;) {
  1232. int tv;
  1233. struct pollfd pfds[2];
  1234. struct d6_packet packet;
  1235. uint8_t *packet_end;
  1236. /* silence "uninitialized!" warning */
  1237. unsigned timestamp_before_wait = timestamp_before_wait;
  1238. //bb_error_msg("sockfd:%d, listen_mode:%d", client_data.sockfd, client_data.listen_mode);
  1239. /* Was opening raw or udp socket here
  1240. * if (client_data.listen_mode != LISTEN_NONE && client_data.sockfd < 0),
  1241. * but on fast network renew responses return faster
  1242. * than we open sockets. Thus this code is moved
  1243. * to change_listen_mode(). Thus we open listen socket
  1244. * BEFORE we send renew request (see "case BOUND:"). */
  1245. udhcp_sp_fd_set(pfds, client_data.sockfd);
  1246. tv = timeout - already_waited_sec;
  1247. retval = 0;
  1248. /* If we already timed out, fall through with retval = 0, else... */
  1249. if (tv > 0) {
  1250. log1("waiting %u seconds", tv);
  1251. timestamp_before_wait = (unsigned)monotonic_sec();
  1252. retval = poll(pfds, 2, tv < INT_MAX/1000 ? tv * 1000 : INT_MAX);
  1253. if (retval < 0) {
  1254. /* EINTR? A signal was caught, don't panic */
  1255. if (errno == EINTR) {
  1256. already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
  1257. continue;
  1258. }
  1259. /* Else: an error occured, panic! */
  1260. bb_simple_perror_msg_and_die("poll");
  1261. }
  1262. }
  1263. /* If timeout dropped to zero, time to become active:
  1264. * resend discover/renew/whatever
  1265. */
  1266. if (retval == 0) {
  1267. /* When running on a bridge, the ifindex may have changed
  1268. * (e.g. if member interfaces were added/removed
  1269. * or if the status of the bridge changed).
  1270. * Refresh ifindex and client_mac:
  1271. */
  1272. if (d6_read_interface(client_data.interface,
  1273. &client_data.ifindex,
  1274. &client6_data.ll_ip6,
  1275. client_data.client_mac)
  1276. ) {
  1277. goto ret0; /* iface is gone? */
  1278. }
  1279. memcpy(clientid_mac_ptr, client_data.client_mac, 6);
  1280. /* We will restart the wait in any case */
  1281. already_waited_sec = 0;
  1282. switch (client_data.state) {
  1283. case INIT_SELECTING:
  1284. if (!discover_retries || packet_num < discover_retries) {
  1285. if (packet_num == 0)
  1286. xid = random_xid();
  1287. /* multicast */
  1288. if (opt & OPT_l)
  1289. send_d6_info_request(xid);
  1290. else
  1291. send_d6_discover(xid, requested_ipv6);
  1292. timeout = discover_timeout;
  1293. packet_num++;
  1294. continue;
  1295. }
  1296. leasefail:
  1297. d6_run_script_no_option("leasefail");
  1298. #if BB_MMU /* -b is not supported on NOMMU */
  1299. if (opt & OPT_b) { /* background if no lease */
  1300. bb_simple_info_msg("no lease, forking to background");
  1301. client_background();
  1302. /* do not background again! */
  1303. opt = ((opt & ~(OPT_b|OPT_n)) | OPT_f);
  1304. /* ^^^ also disables -n (-b takes priority over -n):
  1305. * ifup's default udhcpc options are -R -n,
  1306. * and users want to be able to add -b
  1307. * (in a config file) to make it background
  1308. * _and not exit_.
  1309. */
  1310. } else
  1311. #endif
  1312. if (opt & OPT_n) { /* abort if no lease */
  1313. bb_simple_info_msg("no lease, failing");
  1314. retval = 1;
  1315. goto ret;
  1316. }
  1317. /* wait before trying again */
  1318. timeout = tryagain_timeout;
  1319. packet_num = 0;
  1320. continue;
  1321. case REQUESTING:
  1322. if (!discover_retries || packet_num < discover_retries) {
  1323. /* send multicast select packet */
  1324. send_d6_select(xid);
  1325. timeout = discover_timeout;
  1326. packet_num++;
  1327. continue;
  1328. }
  1329. /* Timed out, go back to init state.
  1330. * "discover...select...discover..." loops
  1331. * were seen in the wild. Treat them similarly
  1332. * to "no response to discover" case */
  1333. change_listen_mode(LISTEN_RAW);
  1334. client_data.state = INIT_SELECTING;
  1335. goto leasefail;
  1336. case BOUND:
  1337. /* 1/2 lease passed, enter renewing state */
  1338. client_data.state = RENEWING;
  1339. client_data.first_secs = 0; /* make secs field count from 0 */
  1340. change_listen_mode(LISTEN_KERNEL);
  1341. log1s("entering renew state");
  1342. /* fall right through */
  1343. case RENEW_REQUESTED: /* manual (SIGUSR1) renew */
  1344. case_RENEW_REQUESTED:
  1345. case RENEWING:
  1346. if (timeout >= 60) {
  1347. /* send an unicast renew request */
  1348. /* Sometimes observed to fail (EADDRNOTAVAIL) to bind
  1349. * a new UDP socket for sending inside send_renew.
  1350. * I hazard to guess existing listening socket
  1351. * is somehow conflicting with it, but why is it
  1352. * not deterministic then?! Strange.
  1353. * Anyway, it does recover by eventually failing through
  1354. * into INIT_SELECTING state.
  1355. */
  1356. if (opt & OPT_l)
  1357. send_d6_info_request(xid);
  1358. else
  1359. send_d6_renew(xid, &srv6_buf, requested_ipv6);
  1360. timeout >>= 1;
  1361. continue;
  1362. }
  1363. /* Timed out, enter rebinding state */
  1364. log1s("entering rebinding state");
  1365. client_data.state = REBINDING;
  1366. /* fall right through */
  1367. case REBINDING:
  1368. /* Switch to bcast receive */
  1369. change_listen_mode(LISTEN_RAW);
  1370. /* Lease is *really* about to run out,
  1371. * try to find DHCP server using broadcast */
  1372. if (timeout > 0) {
  1373. if (opt & OPT_l)
  1374. send_d6_info_request(xid);
  1375. else /* send a broadcast renew request */
  1376. send_d6_renew(xid, /*server_ipv6:*/ NULL, requested_ipv6);
  1377. timeout >>= 1;
  1378. continue;
  1379. }
  1380. /* Timed out, enter init state */
  1381. bb_simple_info_msg("lease lost, entering init state");
  1382. d6_run_script_no_option("deconfig");
  1383. client_data.state = INIT_SELECTING;
  1384. client_data.first_secs = 0; /* make secs field count from 0 */
  1385. /*timeout = 0; - already is */
  1386. packet_num = 0;
  1387. continue;
  1388. /* case RELEASED: */
  1389. }
  1390. /* yah, I know, *you* say it would never happen */
  1391. timeout = INT_MAX;
  1392. continue; /* back to main loop */
  1393. } /* if poll timed out */
  1394. /* poll() didn't timeout, something happened */
  1395. /* Is it a signal? */
  1396. switch (udhcp_sp_read()) {
  1397. case SIGUSR1:
  1398. client_data.first_secs = 0; /* make secs field count from 0 */
  1399. already_waited_sec = 0;
  1400. perform_renew();
  1401. if (client_data.state == RENEW_REQUESTED) {
  1402. /* We might be either on the same network
  1403. * (in which case renew might work),
  1404. * or we might be on a completely different one
  1405. * (in which case renew won't ever succeed).
  1406. * For the second case, must make sure timeout
  1407. * is not too big, or else we can send
  1408. * futile renew requests for hours.
  1409. */
  1410. if (timeout > 60)
  1411. timeout = 60;
  1412. goto case_RENEW_REQUESTED;
  1413. }
  1414. /* Start things over */
  1415. packet_num = 0;
  1416. /* Kill any timeouts, user wants this to hurry along */
  1417. timeout = 0;
  1418. continue;
  1419. case SIGUSR2:
  1420. perform_d6_release(&srv6_buf, requested_ipv6);
  1421. timeout = INT_MAX;
  1422. continue;
  1423. case SIGTERM:
  1424. bb_info_msg("received %s", "SIGTERM");
  1425. goto ret0;
  1426. }
  1427. /* Is it a packet? */
  1428. if (!pfds[1].revents)
  1429. continue; /* no */
  1430. {
  1431. int len;
  1432. /* A packet is ready, read it */
  1433. if (client_data.listen_mode == LISTEN_KERNEL)
  1434. len = d6_recv_kernel_packet(&srv6_buf, &packet, client_data.sockfd);
  1435. else
  1436. len = d6_recv_raw_packet(&srv6_buf, &packet, client_data.sockfd);
  1437. if (len == -1) {
  1438. /* Error is severe, reopen socket */
  1439. bb_error_msg("read error: "STRERROR_FMT", reopening socket" STRERROR_ERRNO);
  1440. sleep(discover_timeout); /* 3 seconds by default */
  1441. change_listen_mode(client_data.listen_mode); /* just close and reopen */
  1442. }
  1443. /* If this packet will turn out to be unrelated/bogus,
  1444. * we will go back and wait for next one.
  1445. * Be sure timeout is properly decreased. */
  1446. already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
  1447. if (len < 0)
  1448. continue;
  1449. packet_end = (uint8_t*)&packet + len;
  1450. }
  1451. if ((packet.d6_xid32 & htonl(0x00ffffff)) != xid) {
  1452. log1("xid %x (our is %x), ignoring packet",
  1453. (unsigned)(packet.d6_xid32 & htonl(0x00ffffff)), (unsigned)xid);
  1454. continue;
  1455. }
  1456. switch (client_data.state) {
  1457. case INIT_SELECTING:
  1458. if (packet.d6_msg_type == D6_MSG_ADVERTISE)
  1459. goto type_is_ok;
  1460. /* DHCPv6 has "Rapid Commit", when instead of Advertise,
  1461. * server sends Reply right away.
  1462. * Fall through to check for this case.
  1463. */
  1464. case REQUESTING:
  1465. case RENEWING:
  1466. case RENEW_REQUESTED:
  1467. case REBINDING:
  1468. if (packet.d6_msg_type == D6_MSG_REPLY) {
  1469. uint32_t lease_seconds;
  1470. struct d6_option *option;
  1471. unsigned address_timeout;
  1472. unsigned prefix_timeout;
  1473. type_is_ok:
  1474. address_timeout = 0;
  1475. prefix_timeout = 0;
  1476. option = d6_find_option(packet.d6_options, packet_end, D6_OPT_STATUS_CODE);
  1477. if (option && (option->data[0] | option->data[1]) != 0) {
  1478. /* return to init state */
  1479. bb_info_msg("received DHCP NAK (%u)", option->data[4]);
  1480. d6_run_script(packet.d6_options,
  1481. packet_end, "nak");
  1482. if (client_data.state != REQUESTING)
  1483. d6_run_script_no_option("deconfig");
  1484. change_listen_mode(LISTEN_RAW);
  1485. sleep(3); /* avoid excessive network traffic */
  1486. client_data.state = INIT_SELECTING;
  1487. client_data.first_secs = 0; /* make secs field count from 0 */
  1488. requested_ipv6 = NULL;
  1489. timeout = 0;
  1490. packet_num = 0;
  1491. already_waited_sec = 0;
  1492. continue;
  1493. }
  1494. option = d6_copy_option(packet.d6_options, packet_end, D6_OPT_SERVERID);
  1495. if (!option) {
  1496. bb_simple_info_msg("no server ID, ignoring packet");
  1497. continue;
  1498. /* still selecting - this server looks bad */
  1499. }
  1500. //Note: we do not bother comparing server IDs in Advertise and Reply msgs.
  1501. //server_id variable is used solely for creation of proper server_id option
  1502. //in outgoing packets. (why DHCPv6 even introduced it is a mystery).
  1503. free(client6_data.server_id);
  1504. client6_data.server_id = option;
  1505. if (packet.d6_msg_type == D6_MSG_ADVERTISE) {
  1506. /* enter requesting state */
  1507. client_data.state = REQUESTING;
  1508. timeout = 0;
  1509. packet_num = 0;
  1510. already_waited_sec = 0;
  1511. continue;
  1512. }
  1513. /* It's a D6_MSG_REPLY */
  1514. /*
  1515. * RFC 3315 18.1.8. Receipt of Reply Messages
  1516. *
  1517. * Upon the receipt of a valid Reply message in response to a Solicit
  1518. * (with a Rapid Commit option), Request, Confirm, Renew, Rebind or
  1519. * Information-request message, the client extracts the configuration
  1520. * information contained in the Reply. The client MAY choose to report
  1521. * any status code or message from the status code option in the Reply
  1522. * message.
  1523. *
  1524. * The client SHOULD perform duplicate address detection [17] on each of
  1525. * the addresses in any IAs it receives in the Reply message before
  1526. * using that address for traffic. If any of the addresses are found to
  1527. * be in use on the link, the client sends a Decline message to the
  1528. * server as described in section 18.1.7.
  1529. *
  1530. * If the Reply was received in response to a Solicit (with a Rapid
  1531. * Commit option), Request, Renew or Rebind message, the client updates
  1532. * the information it has recorded about IAs from the IA options
  1533. * contained in the Reply message:
  1534. *
  1535. * - Record T1 and T2 times.
  1536. *
  1537. * - Add any new addresses in the IA option to the IA as recorded by
  1538. * the client.
  1539. *
  1540. * - Update lifetimes for any addresses in the IA option that the
  1541. * client already has recorded in the IA.
  1542. *
  1543. * - Discard any addresses from the IA, as recorded by the client, that
  1544. * have a valid lifetime of 0 in the IA Address option.
  1545. *
  1546. * - Leave unchanged any information about addresses the client has
  1547. * recorded in the IA but that were not included in the IA from the
  1548. * server.
  1549. *
  1550. * Management of the specific configuration information is detailed in
  1551. * the definition of each option in section 22.
  1552. *
  1553. * If the client receives a Reply message with a Status Code containing
  1554. * UnspecFail, the server is indicating that it was unable to process
  1555. * the message due to an unspecified failure condition. If the client
  1556. * retransmits the original message to the same server to retry the
  1557. * desired operation, the client MUST limit the rate at which it
  1558. * retransmits the message and limit the duration of the time during
  1559. * which it retransmits the message.
  1560. *
  1561. * When the client receives a Reply message with a Status Code option
  1562. * with the value UseMulticast, the client records the receipt of the
  1563. * message and sends subsequent messages to the server through the
  1564. * interface on which the message was received using multicast. The
  1565. * client resends the original message using multicast.
  1566. *
  1567. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1568. * | OPTION_IA_NA | option-len |
  1569. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1570. * | IAID (4 octets) |
  1571. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1572. * | T1 |
  1573. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1574. * | T2 |
  1575. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1576. * | |
  1577. * . IA_NA-options .
  1578. * . .
  1579. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1580. *
  1581. *
  1582. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1583. * | OPTION_IAADDR | option-len |
  1584. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1585. * | |
  1586. * | IPv6 address |
  1587. * | |
  1588. * | |
  1589. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1590. * | preferred-lifetime |
  1591. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1592. * | valid-lifetime |
  1593. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1594. * . .
  1595. * . IAaddr-options .
  1596. * . .
  1597. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1598. */
  1599. if (option_mask32 & OPT_r) {
  1600. struct d6_option *iaaddr;
  1601. free(client6_data.ia_na);
  1602. client6_data.ia_na = d6_copy_option(packet.d6_options, packet_end, D6_OPT_IA_NA);
  1603. if (!client6_data.ia_na) {
  1604. bb_info_msg("no %s option, ignoring packet", "IA_NA");
  1605. continue;
  1606. }
  1607. if (client6_data.ia_na->len < (4 + 4 + 4) + (2 + 2 + 16 + 4 + 4)) {
  1608. bb_info_msg("%s option is too short:%d bytes",
  1609. "IA_NA", client6_data.ia_na->len);
  1610. continue;
  1611. }
  1612. iaaddr = d6_find_option(client6_data.ia_na->data + 4 + 4 + 4,
  1613. client6_data.ia_na->data + client6_data.ia_na->len,
  1614. D6_OPT_IAADDR
  1615. );
  1616. if (!iaaddr) {
  1617. bb_info_msg("no %s option, ignoring packet", "IAADDR");
  1618. continue;
  1619. }
  1620. if (iaaddr->len < (16 + 4 + 4)) {
  1621. bb_info_msg("%s option is too short:%d bytes",
  1622. "IAADDR", iaaddr->len);
  1623. continue;
  1624. }
  1625. /* Note: the address is sufficiently aligned for cast:
  1626. * we _copied_ IA-NA, and copy is always well-aligned.
  1627. */
  1628. requested_ipv6 = (struct in6_addr*) iaaddr->data;
  1629. move_from_unaligned32(lease_seconds, iaaddr->data + 16 + 4);
  1630. lease_seconds = ntohl(lease_seconds);
  1631. /// TODO: check for 0 lease time?
  1632. bb_info_msg("%s obtained, lease time %u",
  1633. "IPv6", /*inet_ntoa(temp_addr),*/ (unsigned)lease_seconds);
  1634. address_timeout = lease_seconds;
  1635. }
  1636. if (option_mask32 & OPT_d) {
  1637. struct d6_option *iaprefix;
  1638. free(client6_data.ia_pd);
  1639. client6_data.ia_pd = d6_copy_option(packet.d6_options, packet_end, D6_OPT_IA_PD);
  1640. if (!client6_data.ia_pd) {
  1641. bb_info_msg("no %s option, ignoring packet", "IA_PD");
  1642. continue;
  1643. }
  1644. if (client6_data.ia_pd->len < (4 + 4 + 4) + (2 + 2 + 4 + 4 + 1 + 16)) {
  1645. bb_info_msg("%s option is too short:%d bytes",
  1646. "IA_PD", client6_data.ia_pd->len);
  1647. continue;
  1648. }
  1649. iaprefix = d6_find_option(client6_data.ia_pd->data + 4 + 4 + 4,
  1650. client6_data.ia_pd->data + client6_data.ia_pd->len,
  1651. D6_OPT_IAPREFIX
  1652. );
  1653. if (!iaprefix) {
  1654. bb_info_msg("no %s option, ignoring packet", "IAPREFIX");
  1655. continue;
  1656. }
  1657. if (iaprefix->len < (4 + 4 + 1 + 16)) {
  1658. bb_info_msg("%s option is too short:%d bytes",
  1659. "IAPREFIX", iaprefix->len);
  1660. continue;
  1661. }
  1662. move_from_unaligned32(lease_seconds, iaprefix->data + 4);
  1663. lease_seconds = ntohl(lease_seconds);
  1664. bb_info_msg("%s obtained, lease time %u",
  1665. "prefix", /*inet_ntoa(temp_addr),*/ (unsigned)lease_seconds);
  1666. prefix_timeout = lease_seconds;
  1667. }
  1668. if (!address_timeout)
  1669. address_timeout = prefix_timeout;
  1670. if (!prefix_timeout)
  1671. prefix_timeout = address_timeout;
  1672. /* note: "int timeout" will not overflow even with 0xffffffff inputs here: */
  1673. timeout = (prefix_timeout < address_timeout ? prefix_timeout : address_timeout) / 2;
  1674. if (opt & OPT_l) {
  1675. /* TODO: request OPTION_INFORMATION_REFRESH_TIME (32)
  1676. * and use its value instead of the default 1 day.
  1677. */
  1678. timeout = 24 * 60 * 60;
  1679. }
  1680. /* paranoia: must not be too small */
  1681. /* timeout > 60 - ensures at least one unicast renew attempt */
  1682. if (timeout < 61)
  1683. timeout = 61;
  1684. /* enter bound state */
  1685. d6_run_script(packet.d6_options, packet_end,
  1686. (client_data.state == REQUESTING ? "bound" : "renew"));
  1687. client_data.state = BOUND;
  1688. change_listen_mode(LISTEN_NONE);
  1689. if (opt & OPT_q) { /* quit after lease */
  1690. goto ret0;
  1691. }
  1692. /* future renew failures should not exit (JM) */
  1693. opt &= ~OPT_n;
  1694. #if BB_MMU /* NOMMU case backgrounded earlier */
  1695. if (!(opt & OPT_f)) {
  1696. client_background();
  1697. /* do not background again! */
  1698. opt = ((opt & ~OPT_b) | OPT_f);
  1699. }
  1700. #endif
  1701. already_waited_sec = 0;
  1702. continue; /* back to main loop */
  1703. }
  1704. continue;
  1705. /* case BOUND: - ignore all packets */
  1706. /* case RELEASED: - ignore all packets */
  1707. }
  1708. /* back to main loop */
  1709. } /* for (;;) - main loop ends */
  1710. ret0:
  1711. if (opt & OPT_R) /* release on quit */
  1712. perform_d6_release(&srv6_buf, requested_ipv6);
  1713. retval = 0;
  1714. ret:
  1715. /*if (client_data.pidfile) - remove_pidfile has its own check */
  1716. remove_pidfile(client_data.pidfile);
  1717. return retval;
  1718. }