3
0

d6_dhcpc.c 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863
  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_from_client_data_ifindex(
  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. );
  508. }
  509. /* RFC 3315 18.1.5. Creation and Transmission of Information-request Messages
  510. *
  511. * The client uses an Information-request message to obtain
  512. * configuration information without having addresses assigned to it.
  513. *
  514. * The client sets the "msg-type" field to INFORMATION-REQUEST. The
  515. * client generates a transaction ID and inserts this value in the
  516. * "transaction-id" field.
  517. *
  518. * The client SHOULD include a Client Identifier option to identify
  519. * itself to the server. If the client does not include a Client
  520. * Identifier option, the server will not be able to return any client-
  521. * specific options to the client, or the server may choose not to
  522. * respond to the message at all. The client MUST include a Client
  523. * Identifier option if the Information-Request message will be
  524. * authenticated.
  525. *
  526. * The client MUST include an Option Request option (see section 22.7)
  527. * to indicate the options the client is interested in receiving. The
  528. * client MAY include options with data values as hints to the server
  529. * about parameter values the client would like to have returned.
  530. */
  531. /* NOINLINE: limit stack usage in caller */
  532. static NOINLINE int send_d6_info_request(uint32_t xid)
  533. {
  534. struct d6_packet packet;
  535. uint8_t *opt_ptr;
  536. /* Fill in: msg type, client id */
  537. opt_ptr = init_d6_packet(&packet, D6_MSG_INFORMATION_REQUEST, xid);
  538. /* Add options:
  539. * "param req" option according to -O, options specified with -x
  540. */
  541. opt_ptr = add_d6_client_options(opt_ptr);
  542. bb_error_msg("sending %s", "info request");
  543. return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
  544. }
  545. /* Milticast a DHCPv6 Solicit packet to the network, with an optionally requested IP.
  546. *
  547. * RFC 3315 17.1.1. Creation of Solicit Messages
  548. *
  549. * The client MUST include a Client Identifier option to identify itself
  550. * to the server. The client includes IA options for any IAs to which
  551. * it wants the server to assign addresses. The client MAY include
  552. * addresses in the IAs as a hint to the server about addresses for
  553. * which the client has a preference. ...
  554. *
  555. * The client uses IA_NA options to request the assignment of non-
  556. * temporary addresses and uses IA_TA options to request the assignment
  557. * of temporary addresses. Either IA_NA or IA_TA options, or a
  558. * combination of both, can be included in DHCP messages.
  559. *
  560. * The client SHOULD include an Option Request option (see section 22.7)
  561. * to indicate the options the client is interested in receiving. The
  562. * client MAY additionally include instances of those options that are
  563. * identified in the Option Request option, with data values as hints to
  564. * the server about parameter values the client would like to have
  565. * returned.
  566. *
  567. * The client includes a Reconfigure Accept option (see section 22.20)
  568. * if the client is willing to accept Reconfigure messages from the
  569. * server.
  570. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  571. | OPTION_CLIENTID | option-len |
  572. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  573. . .
  574. . DUID .
  575. . (variable length) .
  576. . .
  577. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  578. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  579. | OPTION_IA_NA | option-len |
  580. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  581. | IAID (4 octets) |
  582. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  583. | T1 |
  584. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  585. | T2 |
  586. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  587. | |
  588. . IA_NA-options .
  589. . .
  590. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  591. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  592. | OPTION_IAADDR | option-len |
  593. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  594. | |
  595. | IPv6 address |
  596. | |
  597. | |
  598. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  599. | preferred-lifetime |
  600. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  601. | valid-lifetime |
  602. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  603. . .
  604. . IAaddr-options .
  605. . .
  606. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  607. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  608. | OPTION_ORO | option-len |
  609. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  610. | requested-option-code-1 | requested-option-code-2 |
  611. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  612. | ... |
  613. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  614. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  615. | OPTION_RECONF_ACCEPT | 0 |
  616. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  617. */
  618. /* NOINLINE: limit stack usage in caller */
  619. static NOINLINE int send_d6_discover(uint32_t xid, struct in6_addr *requested_ipv6)
  620. {
  621. struct d6_packet packet;
  622. uint8_t *opt_ptr;
  623. unsigned len;
  624. /* Fill in: msg type, client id */
  625. opt_ptr = init_d6_packet(&packet, D6_MSG_SOLICIT, xid);
  626. /* Create new IA_NA, optionally with included IAADDR with requested IP */
  627. free(client6_data.ia_na);
  628. client6_data.ia_na = NULL;
  629. if (option_mask32 & OPT_r) {
  630. len = requested_ipv6 ? 2+2+4+4+4 + 2+2+16+4+4 : 2+2+4+4+4;
  631. client6_data.ia_na = xzalloc(len);
  632. client6_data.ia_na->code = D6_OPT_IA_NA;
  633. client6_data.ia_na->len = len - 4;
  634. *(bb__aliased_uint32_t*)client6_data.ia_na->data = rand(); /* IAID */
  635. if (requested_ipv6) {
  636. struct d6_option *iaaddr = (void*)(client6_data.ia_na->data + 4+4+4);
  637. iaaddr->code = D6_OPT_IAADDR;
  638. iaaddr->len = 16+4+4;
  639. memcpy(iaaddr->data, requested_ipv6, 16);
  640. }
  641. opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, len);
  642. }
  643. /* IA_PD */
  644. free(client6_data.ia_pd);
  645. client6_data.ia_pd = NULL;
  646. if (option_mask32 & OPT_d) {
  647. len = 2+2+4+4+4;
  648. client6_data.ia_pd = xzalloc(len);
  649. client6_data.ia_pd->code = D6_OPT_IA_PD;
  650. client6_data.ia_pd->len = len - 4;
  651. *(bb__aliased_uint32_t*)client6_data.ia_pd->data = rand(); /* IAID */
  652. opt_ptr = mempcpy(opt_ptr, client6_data.ia_pd, len);
  653. }
  654. /* Add options:
  655. * "param req" option according to -O, options specified with -x
  656. */
  657. opt_ptr = add_d6_client_options(opt_ptr);
  658. bb_info_msg("sending %s", "discover");
  659. return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
  660. }
  661. /* Multicast a DHCPv6 request message
  662. *
  663. * RFC 3315 18.1.1. Creation and Transmission of Request Messages
  664. *
  665. * The client uses a Request message to populate IAs with addresses and
  666. * obtain other configuration information. The client includes one or
  667. * more IA options in the Request message. The server then returns
  668. * addresses and other information about the IAs to the client in IA
  669. * options in a Reply message.
  670. *
  671. * The client generates a transaction ID and inserts this value in the
  672. * "transaction-id" field.
  673. *
  674. * The client places the identifier of the destination server in a
  675. * Server Identifier option.
  676. *
  677. * The client MUST include a Client Identifier option to identify itself
  678. * to the server. The client adds any other appropriate options,
  679. * including one or more IA options (if the client is requesting that
  680. * the server assign it some network addresses).
  681. *
  682. * The client MUST include an Option Request option (see section 22.7)
  683. * to indicate the options the client is interested in receiving. The
  684. * client MAY include options with data values as hints to the server
  685. * about parameter values the client would like to have returned.
  686. *
  687. * The client includes a Reconfigure Accept option (see section 22.20)
  688. * indicating whether or not the client is willing to accept Reconfigure
  689. * messages from the server.
  690. */
  691. /* NOINLINE: limit stack usage in caller */
  692. static NOINLINE int send_d6_select(uint32_t xid)
  693. {
  694. struct d6_packet packet;
  695. uint8_t *opt_ptr;
  696. /* Fill in: msg type, client id */
  697. opt_ptr = init_d6_packet(&packet, D6_MSG_REQUEST, xid);
  698. /* server id */
  699. opt_ptr = mempcpy(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
  700. /* IA NA (contains requested IP) */
  701. if (client6_data.ia_na)
  702. opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
  703. /* IA PD */
  704. if (client6_data.ia_pd)
  705. opt_ptr = mempcpy(opt_ptr, client6_data.ia_pd, client6_data.ia_pd->len + 2+2);
  706. /* Add options:
  707. * "param req" option according to -O, options specified with -x
  708. */
  709. opt_ptr = add_d6_client_options(opt_ptr);
  710. bb_info_msg("sending %s", "select");
  711. return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
  712. }
  713. /* Unicast or broadcast a DHCP renew message
  714. *
  715. * RFC 3315 18.1.3. Creation and Transmission of Renew Messages
  716. *
  717. * To extend the valid and preferred lifetimes for the addresses
  718. * associated with an IA, the client sends a Renew message to the server
  719. * from which the client obtained the addresses in the IA containing an
  720. * IA option for the IA. The client includes IA Address options in the
  721. * IA option for the addresses associated with the IA. The server
  722. * determines new lifetimes for the addresses in the IA according to the
  723. * administrative configuration of the server. The server may also add
  724. * new addresses to the IA. The server may remove addresses from the IA
  725. * by setting the preferred and valid lifetimes of those addresses to
  726. * zero.
  727. *
  728. * The server controls the time at which the client contacts the server
  729. * to extend the lifetimes on assigned addresses through the T1 and T2
  730. * parameters assigned to an IA.
  731. *
  732. * At time T1 for an IA, the client initiates a Renew/Reply message
  733. * exchange to extend the lifetimes on any addresses in the IA. The
  734. * client includes an IA option with all addresses currently assigned to
  735. * the IA in its Renew message.
  736. *
  737. * If T1 or T2 is set to 0 by the server (for an IA_NA) or there are no
  738. * T1 or T2 times (for an IA_TA), the client may send a Renew or Rebind
  739. * message, respectively, at the client's discretion.
  740. *
  741. * The client sets the "msg-type" field to RENEW. The client generates
  742. * a transaction ID and inserts this value in the "transaction-id"
  743. * field.
  744. *
  745. * The client places the identifier of the destination server in a
  746. * Server Identifier option.
  747. *
  748. * The client MUST include a Client Identifier option to identify itself
  749. * to the server. The client adds any appropriate options, including
  750. * one or more IA options. The client MUST include the list of
  751. * addresses the client currently has associated with the IAs in the
  752. * Renew message.
  753. *
  754. * The client MUST include an Option Request option (see section 22.7)
  755. * to indicate the options the client is interested in receiving. The
  756. * client MAY include options with data values as hints to the server
  757. * about parameter values the client would like to have returned.
  758. */
  759. /* NOINLINE: limit stack usage in caller */
  760. static NOINLINE int send_d6_renew(uint32_t xid, struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
  761. {
  762. struct d6_packet packet;
  763. uint8_t *opt_ptr;
  764. /* Fill in: msg type, client id */
  765. opt_ptr = init_d6_packet(&packet, DHCPREQUEST, xid);
  766. /* server id */
  767. opt_ptr = mempcpy(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
  768. /* IA NA (contains requested IP) */
  769. if (client6_data.ia_na)
  770. opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
  771. /* IA PD */
  772. if (client6_data.ia_pd)
  773. opt_ptr = mempcpy(opt_ptr, client6_data.ia_pd, client6_data.ia_pd->len + 2+2);
  774. /* Add options:
  775. * "param req" option according to -O, options specified with -x
  776. */
  777. opt_ptr = add_d6_client_options(opt_ptr);
  778. bb_info_msg("sending %s", "renew");
  779. if (server_ipv6)
  780. return d6_send_kernel_packet_from_client_data_ifindex(
  781. &packet, (opt_ptr - (uint8_t*) &packet),
  782. our_cur_ipv6, CLIENT_PORT6,
  783. server_ipv6, SERVER_PORT6
  784. );
  785. return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
  786. }
  787. /* Unicast a DHCP release message */
  788. static
  789. ALWAYS_INLINE /* one caller, help compiler to use this fact */
  790. int send_d6_release(struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
  791. {
  792. struct d6_packet packet;
  793. uint8_t *opt_ptr;
  794. /* Fill in: msg type, client id */
  795. opt_ptr = init_d6_packet(&packet, D6_MSG_RELEASE, random_xid());
  796. /* server id */
  797. opt_ptr = mempcpy(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
  798. /* IA NA (contains our current IP) */
  799. if (client6_data.ia_na)
  800. opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
  801. /* IA PD */
  802. if (client6_data.ia_pd)
  803. opt_ptr = mempcpy(opt_ptr, client6_data.ia_pd, client6_data.ia_pd->len + 2+2);
  804. bb_info_msg("sending %s", "release");
  805. return d6_send_kernel_packet_from_client_data_ifindex(
  806. &packet, (opt_ptr - (uint8_t*) &packet),
  807. our_cur_ipv6, CLIENT_PORT6,
  808. server_ipv6, SERVER_PORT6
  809. );
  810. }
  811. /* Returns -1 on errors that are fatal for the socket, -2 for those that aren't */
  812. /* NOINLINE: limit stack usage in caller */
  813. static NOINLINE int d6_recv_raw_packet(struct in6_addr *peer_ipv6, struct d6_packet *d6_pkt, int fd)
  814. {
  815. int bytes;
  816. struct ip6_udp_d6_packet packet;
  817. bytes = safe_read(fd, &packet, sizeof(packet));
  818. if (bytes < 0) {
  819. log1s("packet read error, ignoring");
  820. /* NB: possible down interface, etc. Caller should pause. */
  821. return bytes; /* returns -1 */
  822. }
  823. if (bytes < (int) (sizeof(packet.ip6) + sizeof(packet.udp))) {
  824. log1s("packet is too short, ignoring");
  825. return -2;
  826. }
  827. if (bytes < sizeof(packet.ip6) + ntohs(packet.ip6.ip6_plen)) {
  828. /* packet is bigger than sizeof(packet), we did partial read */
  829. log1s("oversized packet, ignoring");
  830. return -2;
  831. }
  832. /* ignore any extra garbage bytes */
  833. bytes = sizeof(packet.ip6) + ntohs(packet.ip6.ip6_plen);
  834. /* make sure its the right packet for us, and that it passes sanity checks */
  835. if (packet.ip6.ip6_nxt != IPPROTO_UDP
  836. || (packet.ip6.ip6_vfc >> 4) != 6
  837. || packet.udp.dest != htons(CLIENT_PORT6)
  838. /* || bytes > (int) sizeof(packet) - can't happen */
  839. || packet.udp.len != packet.ip6.ip6_plen
  840. ) {
  841. log1s("unrelated/bogus packet, ignoring");
  842. return -2;
  843. }
  844. //How to do this for ipv6?
  845. // /* verify UDP checksum. IP header has to be modified for this */
  846. // memset(&packet.ip, 0, offsetof(struct iphdr, protocol));
  847. // /* ip.xx fields which are not memset: protocol, check, saddr, daddr */
  848. // packet.ip.tot_len = packet.udp.len; /* yes, this is needed */
  849. // check = packet.udp.check;
  850. // packet.udp.check = 0;
  851. // if (check && check != inet_cksum(&packet, bytes)) {
  852. // log1("packet with bad UDP checksum received, ignoring");
  853. // return -2;
  854. // }
  855. if (peer_ipv6)
  856. *peer_ipv6 = packet.ip6.ip6_src; /* struct copy */
  857. log1("received %s", "a packet");
  858. d6_dump_packet(&packet.data);
  859. bytes -= sizeof(packet.ip6) + sizeof(packet.udp);
  860. memcpy(d6_pkt, &packet.data, bytes);
  861. return bytes;
  862. }
  863. /*** Main ***/
  864. /* Values for client_data.listen_mode */
  865. #define LISTEN_NONE 0
  866. #define LISTEN_KERNEL 1
  867. #define LISTEN_RAW 2
  868. /* Values for client_data.state */
  869. /* initial state: (re)start DHCP negotiation */
  870. #define INIT_SELECTING 0
  871. /* discover was sent, DHCPOFFER reply received */
  872. #define REQUESTING 1
  873. /* select/renew was sent, DHCPACK reply received */
  874. #define BOUND 2
  875. /* half of lease passed, want to renew it by sending unicast renew requests */
  876. #define RENEWING 3
  877. /* renew requests were not answered, lease is almost over, send broadcast renew */
  878. #define REBINDING 4
  879. /* manually requested renew (SIGUSR1) */
  880. #define RENEW_REQUESTED 5
  881. /* release, possibly manually requested (SIGUSR2) */
  882. #define RELEASED 6
  883. static int d6_raw_socket(int ifindex)
  884. {
  885. int fd;
  886. struct sockaddr_ll sock;
  887. /*
  888. * Comment:
  889. *
  890. * I've selected not to see LL header, so BPF doesn't see it, too.
  891. * The filter may also pass non-IP and non-ARP packets, but we do
  892. * a more complete check when receiving the message in userspace.
  893. *
  894. * and filter shamelessly stolen from:
  895. *
  896. * http://www.flamewarmaster.de/software/dhcpclient/
  897. *
  898. * There are a few other interesting ideas on that page (look under
  899. * "Motivation"). Use of netlink events is most interesting. Think
  900. * of various network servers listening for events and reconfiguring.
  901. * That would obsolete sending HUP signals and/or make use of restarts.
  902. *
  903. * Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
  904. * License: GPL v2.
  905. *
  906. * TODO: make conditional?
  907. */
  908. #if 0
  909. static const struct sock_filter filter_instr[] = {
  910. /* load 9th byte (protocol) */
  911. BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
  912. /* jump to L1 if it is IPPROTO_UDP, else to L4 */
  913. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 0, 6),
  914. /* L1: load halfword from offset 6 (flags and frag offset) */
  915. BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 6),
  916. /* jump to L4 if any bits in frag offset field are set, else to L2 */
  917. BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K, 0x1fff, 4, 0),
  918. /* L2: skip IP header (load index reg with header len) */
  919. BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0),
  920. /* load udp destination port from halfword[header_len + 2] */
  921. BPF_STMT(BPF_LD|BPF_H|BPF_IND, 2),
  922. /* jump to L3 if udp dport is CLIENT_PORT6, else to L4 */
  923. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 68, 0, 1),
  924. /* L3: accept packet */
  925. BPF_STMT(BPF_RET|BPF_K, 0x7fffffff),
  926. /* L4: discard packet */
  927. BPF_STMT(BPF_RET|BPF_K, 0),
  928. };
  929. static const struct sock_fprog filter_prog = {
  930. .len = sizeof(filter_instr) / sizeof(filter_instr[0]),
  931. /* casting const away: */
  932. .filter = (struct sock_filter *) filter_instr,
  933. };
  934. #endif
  935. log2("opening raw socket on ifindex %d", ifindex);
  936. fd = xsocket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IPV6));
  937. log3("got raw socket fd %d", fd);
  938. memset(&sock, 0, sizeof(sock)); /* let's be deterministic */
  939. sock.sll_family = AF_PACKET;
  940. sock.sll_protocol = htons(ETH_P_IPV6);
  941. sock.sll_ifindex = ifindex;
  942. /*sock.sll_hatype = ARPHRD_???;*/
  943. /*sock.sll_pkttype = PACKET_???;*/
  944. /*sock.sll_halen = ???;*/
  945. /*sock.sll_addr[8] = ???;*/
  946. xbind(fd, (struct sockaddr *) &sock, sizeof(sock));
  947. #if 0
  948. if (CLIENT_PORT6 == 546) {
  949. /* Use only if standard port is in use */
  950. /* Ignoring error (kernel may lack support for this) */
  951. if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog,
  952. sizeof(filter_prog)) >= 0)
  953. log1("attached filter to raw socket fd %d", fd); // log?
  954. }
  955. #endif
  956. log1s("created raw socket");
  957. return fd;
  958. }
  959. static void change_listen_mode(int new_mode)
  960. {
  961. log1("entering listen mode: %s",
  962. new_mode != LISTEN_NONE
  963. ? (new_mode == LISTEN_KERNEL ? "kernel" : "raw")
  964. : "none"
  965. );
  966. client_data.listen_mode = new_mode;
  967. if (client_data.sockfd >= 0) {
  968. close(client_data.sockfd);
  969. client_data.sockfd = -1;
  970. }
  971. if (new_mode == LISTEN_KERNEL)
  972. client_data.sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT6, client_data.interface);
  973. else if (new_mode != LISTEN_NONE)
  974. client_data.sockfd = d6_raw_socket(client_data.ifindex);
  975. /* else LISTEN_NONE: client_data.sockfd stays closed */
  976. }
  977. /* Called only on SIGUSR1 */
  978. static void perform_renew(void)
  979. {
  980. bb_simple_info_msg("performing DHCP renew");
  981. switch (client_data.state) {
  982. case BOUND:
  983. change_listen_mode(LISTEN_KERNEL);
  984. case RENEWING:
  985. case REBINDING:
  986. client_data.state = RENEW_REQUESTED;
  987. break;
  988. case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
  989. d6_run_script_no_option("deconfig");
  990. case REQUESTING:
  991. case RELEASED:
  992. change_listen_mode(LISTEN_RAW);
  993. client_data.state = INIT_SELECTING;
  994. break;
  995. case INIT_SELECTING:
  996. break;
  997. }
  998. }
  999. static void perform_d6_release(struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
  1000. {
  1001. /* send release packet */
  1002. if (client_data.state == BOUND
  1003. || client_data.state == RENEWING
  1004. || client_data.state == REBINDING
  1005. || client_data.state == RENEW_REQUESTED
  1006. ) {
  1007. bb_simple_info_msg("unicasting a release");
  1008. send_d6_release(server_ipv6, our_cur_ipv6); /* unicast */
  1009. }
  1010. bb_simple_info_msg("entering released state");
  1011. /*
  1012. * We can be here on: SIGUSR2,
  1013. * or on exit (SIGTERM) and -R "release on quit" is specified.
  1014. * Users requested to be notified in all cases, even if not in one
  1015. * of the states above.
  1016. */
  1017. d6_run_script_no_option("deconfig");
  1018. change_listen_mode(LISTEN_NONE);
  1019. client_data.state = RELEASED;
  1020. }
  1021. ///static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
  1022. ///{
  1023. /// uint8_t *storage;
  1024. /// int len = strnlen(str, 255);
  1025. /// storage = xzalloc(len + extra + OPT_DATA);
  1026. /// storage[OPT_CODE] = code;
  1027. /// storage[OPT_LEN] = len + extra;
  1028. /// memcpy(storage + extra + OPT_DATA, str, len);
  1029. /// return storage;
  1030. ///}
  1031. #if BB_MMU
  1032. static void client_background(void)
  1033. {
  1034. bb_daemonize(0);
  1035. logmode &= ~LOGMODE_STDIO;
  1036. /* rewrite pidfile, as our pid is different now */
  1037. write_pidfile(client_data.pidfile);
  1038. }
  1039. #endif
  1040. //usage:#if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
  1041. //usage:# define IF_UDHCP_VERBOSE(...) __VA_ARGS__
  1042. //usage:#else
  1043. //usage:# define IF_UDHCP_VERBOSE(...)
  1044. //usage:#endif
  1045. //usage:#define udhcpc6_trivial_usage
  1046. //usage: "[-fbnq"IF_UDHCP_VERBOSE("v")"odR] [-i IFACE] [-r IPv6] [-s PROG] [-p PIDFILE]\n"
  1047. //usage: " [-x OPT:VAL]... [-O OPT]..." IF_FEATURE_UDHCP_PORT(" [-P PORT]")
  1048. //usage:#define udhcpc6_full_usage "\n"
  1049. //usage: "\n -i IFACE Interface to use (default eth0)"
  1050. //usage: "\n -p FILE Create pidfile"
  1051. //usage: "\n -s PROG Run PROG at DHCP events (default "CONFIG_UDHCPC_DEFAULT_SCRIPT")"
  1052. //usage: "\n -B Request broadcast replies"
  1053. //usage: "\n -t N Send up to N discover packets"
  1054. //usage: "\n -T N Pause between packets (default 3 seconds)"
  1055. //usage: "\n -A N Wait N seconds (default 20) after failure"
  1056. //usage: "\n -f Run in foreground"
  1057. //usage: USE_FOR_MMU(
  1058. //usage: "\n -b Background if lease is not obtained"
  1059. //usage: )
  1060. //usage: "\n -n Exit if lease is not obtained"
  1061. //usage: "\n -q Exit after obtaining lease"
  1062. //usage: "\n -R Release IP on exit"
  1063. //usage: "\n -S Log to syslog too"
  1064. //usage: IF_FEATURE_UDHCP_PORT(
  1065. //usage: "\n -P PORT Use PORT (default 546)"
  1066. //usage: )
  1067. ////usage: IF_FEATURE_UDHCPC_ARPING(
  1068. ////usage: "\n -a Use arping to validate offered address"
  1069. ////usage: )
  1070. //usage: "\n -O OPT Request option OPT from server (cumulative)"
  1071. //usage: "\n -o Don't request any options (unless -O is given)"
  1072. //usage: "\n -r IPv6 Request this address ('no' to not request any IP)"
  1073. //usage: "\n -d Request prefix"
  1074. //usage: "\n -l Send 'information request' instead of 'solicit'"
  1075. //usage: "\n (used for servers which do not assign IPv6 addresses)"
  1076. //usage: "\n -x OPT:VAL Include option OPT in sent packets (cumulative)"
  1077. //usage: "\n Examples of string, numeric, and hex byte opts:"
  1078. //usage: "\n -x hostname:bbox - option 12"
  1079. //usage: "\n -x lease:3600 - option 51 (lease time)"
  1080. //usage: "\n -x 0x3d:0100BEEFC0FFEE - option 61 (client id)"
  1081. //usage: "\n -x 14:'\"dumpfile\"' - option 14 (shell-quoted)"
  1082. //usage: IF_UDHCP_VERBOSE(
  1083. //usage: "\n -v Verbose"
  1084. //usage: )
  1085. //usage: "\nSignals:"
  1086. //usage: "\n USR1 Renew lease"
  1087. //usage: "\n USR2 Release lease"
  1088. int udhcpc6_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1089. int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
  1090. {
  1091. const char *str_r;
  1092. IF_FEATURE_UDHCP_PORT(char *str_P;)
  1093. void *clientid_mac_ptr;
  1094. llist_t *list_O = NULL;
  1095. llist_t *list_x = NULL;
  1096. int tryagain_timeout = 20;
  1097. int discover_timeout = 3;
  1098. int discover_retries = 3;
  1099. struct in6_addr srv6_buf;
  1100. struct in6_addr ipv6_buf;
  1101. struct in6_addr *requested_ipv6;
  1102. uint32_t xid = 0;
  1103. int packet_num;
  1104. int timeout; /* must be signed */
  1105. unsigned already_waited_sec;
  1106. unsigned opt;
  1107. int retval;
  1108. setup_common_bufsiz();
  1109. /* We want random_xid to be random */
  1110. srand(monotonic_us());
  1111. /* Default options */
  1112. IF_FEATURE_UDHCP_PORT(SERVER_PORT6 = 547;)
  1113. IF_FEATURE_UDHCP_PORT(CLIENT_PORT6 = 546;)
  1114. client_data.interface = "eth0";
  1115. client_data.script = CONFIG_UDHCPC_DEFAULT_SCRIPT;
  1116. client_data.sockfd = -1;
  1117. /* Make sure fd 0,1,2 are open */
  1118. /* Set up the signal pipe on fds 3,4 - must be before openlog() */
  1119. udhcp_sp_setup();
  1120. /* Parse command line */
  1121. opt = getopt32long(argv, "^"
  1122. /* O,x: list; -T,-t,-A take numeric param */
  1123. "i:np:qRr:s:T:+t:+SA:+O:*ox:*fld"
  1124. USE_FOR_MMU("b")
  1125. ///IF_FEATURE_UDHCPC_ARPING("a")
  1126. IF_FEATURE_UDHCP_PORT("P:")
  1127. "v"
  1128. "\0" IF_UDHCP_VERBOSE("vv") /* -v is a counter */
  1129. , udhcpc6_longopts
  1130. , &client_data.interface, &client_data.pidfile, &str_r /* i,p */
  1131. , &client_data.script /* s */
  1132. , &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */
  1133. , &list_O
  1134. , &list_x
  1135. IF_FEATURE_UDHCP_PORT(, &str_P)
  1136. IF_UDHCP_VERBOSE(, &dhcp_verbose)
  1137. );
  1138. requested_ipv6 = NULL;
  1139. option_mask32 |= OPT_r;
  1140. if (opt & OPT_l) {
  1141. /* for -l, do not require IPv6 assignment from server */
  1142. option_mask32 &= ~OPT_r;
  1143. } else if (opt & OPT_r) {
  1144. /* explicit "-r ARG" given */
  1145. if (strcmp(str_r, "no") == 0) {
  1146. option_mask32 &= ~OPT_r;
  1147. } else {
  1148. if (inet_pton(AF_INET6, str_r, &ipv6_buf) <= 0)
  1149. bb_error_msg_and_die("bad IPv6 address '%s'", str_r);
  1150. requested_ipv6 = &ipv6_buf;
  1151. }
  1152. }
  1153. #if ENABLE_FEATURE_UDHCP_PORT
  1154. if (opt & OPT_P) {
  1155. CLIENT_PORT6 = xatou16(str_P);
  1156. SERVER_PORT6 = CLIENT_PORT6 + 1;
  1157. }
  1158. #endif
  1159. while (list_O) {
  1160. char *optstr = llist_pop(&list_O);
  1161. unsigned n = bb_strtou(optstr, NULL, 0);
  1162. if (errno || n > 254) {
  1163. n = udhcp_option_idx(optstr, d6_option_strings);
  1164. n = d6_optflags[n].code;
  1165. }
  1166. client_data.opt_mask[n >> 3] |= 1 << (n & 7);
  1167. }
  1168. if (!(opt & OPT_o)) {
  1169. unsigned i, n;
  1170. for (i = 0; (n = d6_optflags[i].code) != 0; i++) {
  1171. if (d6_optflags[i].flags & OPTION_REQ) {
  1172. client_data.opt_mask[n >> 3] |= 1 << (n & 7);
  1173. }
  1174. }
  1175. }
  1176. while (list_x) {
  1177. char *optstr = xstrdup(llist_pop(&list_x));
  1178. udhcp_str2optset(optstr, &client_data.options,
  1179. d6_optflags, d6_option_strings,
  1180. /*dhcpv6:*/ 1
  1181. );
  1182. free(optstr);
  1183. }
  1184. if (d6_read_interface(client_data.interface,
  1185. &client_data.ifindex,
  1186. &client6_data.ll_ip6,
  1187. client_data.client_mac)
  1188. ) {
  1189. return 1;
  1190. }
  1191. /* Create client ID based on mac, set clientid_mac_ptr */
  1192. {
  1193. struct d6_option *clientid;
  1194. clientid = xzalloc(2+2+2+2+6);
  1195. clientid->code = D6_OPT_CLIENTID;
  1196. clientid->len = 2+2+6;
  1197. clientid->data[1] = 3; /* DUID-LL */
  1198. clientid->data[3] = 1; /* ethernet */
  1199. clientid_mac_ptr = clientid->data + 2+2;
  1200. memcpy(clientid_mac_ptr, client_data.client_mac, 6);
  1201. client_data.clientid = (void*)clientid;
  1202. }
  1203. #if !BB_MMU
  1204. /* on NOMMU reexec (i.e., background) early */
  1205. if (!(opt & OPT_f)) {
  1206. bb_daemonize_or_rexec(0 /* flags */, argv);
  1207. logmode = LOGMODE_NONE;
  1208. }
  1209. #endif
  1210. if (opt & OPT_S) {
  1211. openlog(applet_name, LOG_PID, LOG_DAEMON);
  1212. logmode |= LOGMODE_SYSLOG;
  1213. }
  1214. /* Create pidfile */
  1215. write_pidfile(client_data.pidfile);
  1216. /* Goes to stdout (unless NOMMU) and possibly syslog */
  1217. bb_simple_info_msg("started, v"BB_VER);
  1218. client_data.state = INIT_SELECTING;
  1219. d6_run_script_no_option("deconfig");
  1220. change_listen_mode(LISTEN_RAW);
  1221. packet_num = 0;
  1222. timeout = 0;
  1223. already_waited_sec = 0;
  1224. /* Main event loop. select() waits on signal pipe and possibly
  1225. * on sockfd.
  1226. * "continue" statements in code below jump to the top of the loop.
  1227. */
  1228. for (;;) {
  1229. int tv;
  1230. struct pollfd pfds[2];
  1231. struct d6_packet packet;
  1232. uint8_t *packet_end;
  1233. /* silence "uninitialized!" warning */
  1234. unsigned timestamp_before_wait = timestamp_before_wait;
  1235. //bb_error_msg("sockfd:%d, listen_mode:%d", client_data.sockfd, client_data.listen_mode);
  1236. /* Was opening raw or udp socket here
  1237. * if (client_data.listen_mode != LISTEN_NONE && client_data.sockfd < 0),
  1238. * but on fast network renew responses return faster
  1239. * than we open sockets. Thus this code is moved
  1240. * to change_listen_mode(). Thus we open listen socket
  1241. * BEFORE we send renew request (see "case BOUND:"). */
  1242. udhcp_sp_fd_set(pfds, client_data.sockfd);
  1243. tv = timeout - already_waited_sec;
  1244. retval = 0;
  1245. /* If we already timed out, fall through with retval = 0, else... */
  1246. if (tv > 0) {
  1247. log1("waiting %u seconds", tv);
  1248. timestamp_before_wait = (unsigned)monotonic_sec();
  1249. retval = poll(pfds, 2, tv < INT_MAX/1000 ? tv * 1000 : INT_MAX);
  1250. if (retval < 0) {
  1251. /* EINTR? A signal was caught, don't panic */
  1252. if (errno == EINTR) {
  1253. already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
  1254. continue;
  1255. }
  1256. /* Else: an error occured, panic! */
  1257. bb_simple_perror_msg_and_die("poll");
  1258. }
  1259. }
  1260. /* If timeout dropped to zero, time to become active:
  1261. * resend discover/renew/whatever
  1262. */
  1263. if (retval == 0) {
  1264. /* When running on a bridge, the ifindex may have changed
  1265. * (e.g. if member interfaces were added/removed
  1266. * or if the status of the bridge changed).
  1267. * Refresh ifindex and client_mac:
  1268. */
  1269. if (d6_read_interface(client_data.interface,
  1270. &client_data.ifindex,
  1271. &client6_data.ll_ip6,
  1272. client_data.client_mac)
  1273. ) {
  1274. goto ret0; /* iface is gone? */
  1275. }
  1276. memcpy(clientid_mac_ptr, client_data.client_mac, 6);
  1277. /* We will restart the wait in any case */
  1278. already_waited_sec = 0;
  1279. switch (client_data.state) {
  1280. case INIT_SELECTING:
  1281. if (!discover_retries || packet_num < discover_retries) {
  1282. if (packet_num == 0)
  1283. xid = random_xid();
  1284. /* multicast */
  1285. if (opt & OPT_l)
  1286. send_d6_info_request(xid);
  1287. else
  1288. send_d6_discover(xid, requested_ipv6);
  1289. timeout = discover_timeout;
  1290. packet_num++;
  1291. continue;
  1292. }
  1293. leasefail:
  1294. d6_run_script_no_option("leasefail");
  1295. #if BB_MMU /* -b is not supported on NOMMU */
  1296. if (opt & OPT_b) { /* background if no lease */
  1297. bb_simple_info_msg("no lease, forking to background");
  1298. client_background();
  1299. /* do not background again! */
  1300. opt = ((opt & ~(OPT_b|OPT_n)) | OPT_f);
  1301. /* ^^^ also disables -n (-b takes priority over -n):
  1302. * ifup's default udhcpc options are -R -n,
  1303. * and users want to be able to add -b
  1304. * (in a config file) to make it background
  1305. * _and not exit_.
  1306. */
  1307. } else
  1308. #endif
  1309. if (opt & OPT_n) { /* abort if no lease */
  1310. bb_simple_info_msg("no lease, failing");
  1311. retval = 1;
  1312. goto ret;
  1313. }
  1314. /* wait before trying again */
  1315. timeout = tryagain_timeout;
  1316. packet_num = 0;
  1317. continue;
  1318. case REQUESTING:
  1319. if (!discover_retries || packet_num < discover_retries) {
  1320. /* send multicast select packet */
  1321. send_d6_select(xid);
  1322. timeout = discover_timeout;
  1323. packet_num++;
  1324. continue;
  1325. }
  1326. /* Timed out, go back to init state.
  1327. * "discover...select...discover..." loops
  1328. * were seen in the wild. Treat them similarly
  1329. * to "no response to discover" case */
  1330. change_listen_mode(LISTEN_RAW);
  1331. client_data.state = INIT_SELECTING;
  1332. goto leasefail;
  1333. case BOUND:
  1334. /* 1/2 lease passed, enter renewing state */
  1335. client_data.state = RENEWING;
  1336. client_data.first_secs = 0; /* make secs field count from 0 */
  1337. change_listen_mode(LISTEN_KERNEL);
  1338. log1s("entering renew state");
  1339. /* fall right through */
  1340. case RENEW_REQUESTED: /* manual (SIGUSR1) renew */
  1341. case_RENEW_REQUESTED:
  1342. case RENEWING:
  1343. if (timeout >= 60) {
  1344. /* send an unicast renew request */
  1345. /* Sometimes observed to fail (EADDRNOTAVAIL) to bind
  1346. * a new UDP socket for sending inside send_renew.
  1347. * I hazard to guess existing listening socket
  1348. * is somehow conflicting with it, but why is it
  1349. * not deterministic then?! Strange.
  1350. * Anyway, it does recover by eventually failing through
  1351. * into INIT_SELECTING state.
  1352. */
  1353. if (opt & OPT_l)
  1354. send_d6_info_request(xid);
  1355. else
  1356. send_d6_renew(xid, &srv6_buf, requested_ipv6);
  1357. timeout >>= 1;
  1358. continue;
  1359. }
  1360. /* Timed out, enter rebinding state */
  1361. log1s("entering rebinding state");
  1362. client_data.state = REBINDING;
  1363. /* fall right through */
  1364. case REBINDING:
  1365. /* Switch to bcast receive */
  1366. change_listen_mode(LISTEN_RAW);
  1367. /* Lease is *really* about to run out,
  1368. * try to find DHCP server using broadcast */
  1369. if (timeout > 0) {
  1370. if (opt & OPT_l)
  1371. send_d6_info_request(xid);
  1372. else /* send a broadcast renew request */
  1373. send_d6_renew(xid, /*server_ipv6:*/ NULL, requested_ipv6);
  1374. timeout >>= 1;
  1375. continue;
  1376. }
  1377. /* Timed out, enter init state */
  1378. bb_simple_info_msg("lease lost, entering init state");
  1379. d6_run_script_no_option("deconfig");
  1380. client_data.state = INIT_SELECTING;
  1381. client_data.first_secs = 0; /* make secs field count from 0 */
  1382. /*timeout = 0; - already is */
  1383. packet_num = 0;
  1384. continue;
  1385. /* case RELEASED: */
  1386. }
  1387. /* yah, I know, *you* say it would never happen */
  1388. timeout = INT_MAX;
  1389. continue; /* back to main loop */
  1390. } /* if poll timed out */
  1391. /* poll() didn't timeout, something happened */
  1392. /* Is it a signal? */
  1393. switch (udhcp_sp_read()) {
  1394. case SIGUSR1:
  1395. client_data.first_secs = 0; /* make secs field count from 0 */
  1396. already_waited_sec = 0;
  1397. perform_renew();
  1398. if (client_data.state == RENEW_REQUESTED) {
  1399. /* We might be either on the same network
  1400. * (in which case renew might work),
  1401. * or we might be on a completely different one
  1402. * (in which case renew won't ever succeed).
  1403. * For the second case, must make sure timeout
  1404. * is not too big, or else we can send
  1405. * futile renew requests for hours.
  1406. */
  1407. if (timeout > 60)
  1408. timeout = 60;
  1409. goto case_RENEW_REQUESTED;
  1410. }
  1411. /* Start things over */
  1412. packet_num = 0;
  1413. /* Kill any timeouts, user wants this to hurry along */
  1414. timeout = 0;
  1415. continue;
  1416. case SIGUSR2:
  1417. perform_d6_release(&srv6_buf, requested_ipv6);
  1418. timeout = INT_MAX;
  1419. continue;
  1420. case SIGTERM:
  1421. bb_info_msg("received %s", "SIGTERM");
  1422. goto ret0;
  1423. }
  1424. /* Is it a packet? */
  1425. if (!pfds[1].revents)
  1426. continue; /* no */
  1427. {
  1428. int len;
  1429. /* A packet is ready, read it */
  1430. if (client_data.listen_mode == LISTEN_KERNEL)
  1431. len = d6_recv_kernel_packet(&srv6_buf, &packet, client_data.sockfd);
  1432. else
  1433. len = d6_recv_raw_packet(&srv6_buf, &packet, client_data.sockfd);
  1434. if (len == -1) {
  1435. /* Error is severe, reopen socket */
  1436. bb_error_msg("read error: "STRERROR_FMT", reopening socket" STRERROR_ERRNO);
  1437. sleep(discover_timeout); /* 3 seconds by default */
  1438. change_listen_mode(client_data.listen_mode); /* just close and reopen */
  1439. }
  1440. /* If this packet will turn out to be unrelated/bogus,
  1441. * we will go back and wait for next one.
  1442. * Be sure timeout is properly decreased. */
  1443. already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
  1444. if (len < 0)
  1445. continue;
  1446. packet_end = (uint8_t*)&packet + len;
  1447. }
  1448. if ((packet.d6_xid32 & htonl(0x00ffffff)) != xid) {
  1449. log1("xid %x (our is %x), ignoring packet",
  1450. (unsigned)(packet.d6_xid32 & htonl(0x00ffffff)), (unsigned)xid);
  1451. continue;
  1452. }
  1453. switch (client_data.state) {
  1454. case INIT_SELECTING:
  1455. if (packet.d6_msg_type == D6_MSG_ADVERTISE)
  1456. goto type_is_ok;
  1457. /* DHCPv6 has "Rapid Commit", when instead of Advertise,
  1458. * server sends Reply right away.
  1459. * Fall through to check for this case.
  1460. */
  1461. case REQUESTING:
  1462. case RENEWING:
  1463. case RENEW_REQUESTED:
  1464. case REBINDING:
  1465. if (packet.d6_msg_type == D6_MSG_REPLY) {
  1466. uint32_t lease_seconds;
  1467. struct d6_option *option;
  1468. unsigned address_timeout;
  1469. unsigned prefix_timeout;
  1470. type_is_ok:
  1471. address_timeout = 0;
  1472. prefix_timeout = 0;
  1473. option = d6_find_option(packet.d6_options, packet_end, D6_OPT_STATUS_CODE);
  1474. if (option && (option->data[0] | option->data[1]) != 0) {
  1475. /* return to init state */
  1476. bb_info_msg("received DHCP NAK (%u)", option->data[4]);
  1477. d6_run_script(packet.d6_options,
  1478. packet_end, "nak");
  1479. if (client_data.state != REQUESTING)
  1480. d6_run_script_no_option("deconfig");
  1481. change_listen_mode(LISTEN_RAW);
  1482. sleep(3); /* avoid excessive network traffic */
  1483. client_data.state = INIT_SELECTING;
  1484. client_data.first_secs = 0; /* make secs field count from 0 */
  1485. requested_ipv6 = NULL;
  1486. timeout = 0;
  1487. packet_num = 0;
  1488. already_waited_sec = 0;
  1489. continue;
  1490. }
  1491. option = d6_copy_option(packet.d6_options, packet_end, D6_OPT_SERVERID);
  1492. if (!option) {
  1493. bb_simple_info_msg("no server ID, ignoring packet");
  1494. continue;
  1495. /* still selecting - this server looks bad */
  1496. }
  1497. //Note: we do not bother comparing server IDs in Advertise and Reply msgs.
  1498. //server_id variable is used solely for creation of proper server_id option
  1499. //in outgoing packets. (why DHCPv6 even introduced it is a mystery).
  1500. free(client6_data.server_id);
  1501. client6_data.server_id = option;
  1502. if (packet.d6_msg_type == D6_MSG_ADVERTISE) {
  1503. /* enter requesting state */
  1504. client_data.state = REQUESTING;
  1505. timeout = 0;
  1506. packet_num = 0;
  1507. already_waited_sec = 0;
  1508. continue;
  1509. }
  1510. /* It's a D6_MSG_REPLY */
  1511. /*
  1512. * RFC 3315 18.1.8. Receipt of Reply Messages
  1513. *
  1514. * Upon the receipt of a valid Reply message in response to a Solicit
  1515. * (with a Rapid Commit option), Request, Confirm, Renew, Rebind or
  1516. * Information-request message, the client extracts the configuration
  1517. * information contained in the Reply. The client MAY choose to report
  1518. * any status code or message from the status code option in the Reply
  1519. * message.
  1520. *
  1521. * The client SHOULD perform duplicate address detection [17] on each of
  1522. * the addresses in any IAs it receives in the Reply message before
  1523. * using that address for traffic. If any of the addresses are found to
  1524. * be in use on the link, the client sends a Decline message to the
  1525. * server as described in section 18.1.7.
  1526. *
  1527. * If the Reply was received in response to a Solicit (with a Rapid
  1528. * Commit option), Request, Renew or Rebind message, the client updates
  1529. * the information it has recorded about IAs from the IA options
  1530. * contained in the Reply message:
  1531. *
  1532. * - Record T1 and T2 times.
  1533. *
  1534. * - Add any new addresses in the IA option to the IA as recorded by
  1535. * the client.
  1536. *
  1537. * - Update lifetimes for any addresses in the IA option that the
  1538. * client already has recorded in the IA.
  1539. *
  1540. * - Discard any addresses from the IA, as recorded by the client, that
  1541. * have a valid lifetime of 0 in the IA Address option.
  1542. *
  1543. * - Leave unchanged any information about addresses the client has
  1544. * recorded in the IA but that were not included in the IA from the
  1545. * server.
  1546. *
  1547. * Management of the specific configuration information is detailed in
  1548. * the definition of each option in section 22.
  1549. *
  1550. * If the client receives a Reply message with a Status Code containing
  1551. * UnspecFail, the server is indicating that it was unable to process
  1552. * the message due to an unspecified failure condition. If the client
  1553. * retransmits the original message to the same server to retry the
  1554. * desired operation, the client MUST limit the rate at which it
  1555. * retransmits the message and limit the duration of the time during
  1556. * which it retransmits the message.
  1557. *
  1558. * When the client receives a Reply message with a Status Code option
  1559. * with the value UseMulticast, the client records the receipt of the
  1560. * message and sends subsequent messages to the server through the
  1561. * interface on which the message was received using multicast. The
  1562. * client resends the original message using multicast.
  1563. *
  1564. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1565. * | OPTION_IA_NA | option-len |
  1566. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1567. * | IAID (4 octets) |
  1568. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1569. * | T1 |
  1570. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1571. * | T2 |
  1572. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1573. * | |
  1574. * . IA_NA-options .
  1575. * . .
  1576. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1577. *
  1578. *
  1579. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1580. * | OPTION_IAADDR | option-len |
  1581. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1582. * | |
  1583. * | IPv6 address |
  1584. * | |
  1585. * | |
  1586. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1587. * | preferred-lifetime |
  1588. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1589. * | valid-lifetime |
  1590. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1591. * . .
  1592. * . IAaddr-options .
  1593. * . .
  1594. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1595. */
  1596. if (option_mask32 & OPT_r) {
  1597. struct d6_option *iaaddr;
  1598. free(client6_data.ia_na);
  1599. client6_data.ia_na = d6_copy_option(packet.d6_options, packet_end, D6_OPT_IA_NA);
  1600. if (!client6_data.ia_na) {
  1601. bb_info_msg("no %s option, ignoring packet", "IA_NA");
  1602. continue;
  1603. }
  1604. if (client6_data.ia_na->len < (4 + 4 + 4) + (2 + 2 + 16 + 4 + 4)) {
  1605. bb_info_msg("%s option is too short:%d bytes",
  1606. "IA_NA", client6_data.ia_na->len);
  1607. continue;
  1608. }
  1609. iaaddr = d6_find_option(client6_data.ia_na->data + 4 + 4 + 4,
  1610. client6_data.ia_na->data + client6_data.ia_na->len,
  1611. D6_OPT_IAADDR
  1612. );
  1613. if (!iaaddr) {
  1614. bb_info_msg("no %s option, ignoring packet", "IAADDR");
  1615. continue;
  1616. }
  1617. if (iaaddr->len < (16 + 4 + 4)) {
  1618. bb_info_msg("%s option is too short:%d bytes",
  1619. "IAADDR", iaaddr->len);
  1620. continue;
  1621. }
  1622. /* Note: the address is sufficiently aligned for cast:
  1623. * we _copied_ IA-NA, and copy is always well-aligned.
  1624. */
  1625. requested_ipv6 = (struct in6_addr*) iaaddr->data;
  1626. move_from_unaligned32(lease_seconds, iaaddr->data + 16 + 4);
  1627. lease_seconds = ntohl(lease_seconds);
  1628. /// TODO: check for 0 lease time?
  1629. bb_info_msg("%s obtained, lease time %u",
  1630. "IPv6", /*inet_ntoa(temp_addr),*/ (unsigned)lease_seconds);
  1631. address_timeout = lease_seconds;
  1632. }
  1633. if (option_mask32 & OPT_d) {
  1634. struct d6_option *iaprefix;
  1635. free(client6_data.ia_pd);
  1636. client6_data.ia_pd = d6_copy_option(packet.d6_options, packet_end, D6_OPT_IA_PD);
  1637. if (!client6_data.ia_pd) {
  1638. bb_info_msg("no %s option, ignoring packet", "IA_PD");
  1639. continue;
  1640. }
  1641. if (client6_data.ia_pd->len < (4 + 4 + 4) + (2 + 2 + 4 + 4 + 1 + 16)) {
  1642. bb_info_msg("%s option is too short:%d bytes",
  1643. "IA_PD", client6_data.ia_pd->len);
  1644. continue;
  1645. }
  1646. iaprefix = d6_find_option(client6_data.ia_pd->data + 4 + 4 + 4,
  1647. client6_data.ia_pd->data + client6_data.ia_pd->len,
  1648. D6_OPT_IAPREFIX
  1649. );
  1650. if (!iaprefix) {
  1651. bb_info_msg("no %s option, ignoring packet", "IAPREFIX");
  1652. continue;
  1653. }
  1654. if (iaprefix->len < (4 + 4 + 1 + 16)) {
  1655. bb_info_msg("%s option is too short:%d bytes",
  1656. "IAPREFIX", iaprefix->len);
  1657. continue;
  1658. }
  1659. move_from_unaligned32(lease_seconds, iaprefix->data + 4);
  1660. lease_seconds = ntohl(lease_seconds);
  1661. bb_info_msg("%s obtained, lease time %u",
  1662. "prefix", /*inet_ntoa(temp_addr),*/ (unsigned)lease_seconds);
  1663. prefix_timeout = lease_seconds;
  1664. }
  1665. if (!address_timeout)
  1666. address_timeout = prefix_timeout;
  1667. if (!prefix_timeout)
  1668. prefix_timeout = address_timeout;
  1669. /* note: "int timeout" will not overflow even with 0xffffffff inputs here: */
  1670. timeout = (prefix_timeout < address_timeout ? prefix_timeout : address_timeout) / 2;
  1671. if (opt & OPT_l) {
  1672. /* TODO: request OPTION_INFORMATION_REFRESH_TIME (32)
  1673. * and use its value instead of the default 1 day.
  1674. */
  1675. timeout = 24 * 60 * 60;
  1676. }
  1677. /* paranoia: must not be too small */
  1678. /* timeout > 60 - ensures at least one unicast renew attempt */
  1679. if (timeout < 61)
  1680. timeout = 61;
  1681. /* enter bound state */
  1682. d6_run_script(packet.d6_options, packet_end,
  1683. (client_data.state == REQUESTING ? "bound" : "renew"));
  1684. client_data.state = BOUND;
  1685. change_listen_mode(LISTEN_NONE);
  1686. if (opt & OPT_q) { /* quit after lease */
  1687. goto ret0;
  1688. }
  1689. /* future renew failures should not exit (JM) */
  1690. opt &= ~OPT_n;
  1691. #if BB_MMU /* NOMMU case backgrounded earlier */
  1692. if (!(opt & OPT_f)) {
  1693. client_background();
  1694. /* do not background again! */
  1695. opt = ((opt & ~OPT_b) | OPT_f);
  1696. }
  1697. #endif
  1698. already_waited_sec = 0;
  1699. continue; /* back to main loop */
  1700. }
  1701. continue;
  1702. /* case BOUND: - ignore all packets */
  1703. /* case RELEASED: - ignore all packets */
  1704. }
  1705. /* back to main loop */
  1706. } /* for (;;) - main loop ends */
  1707. ret0:
  1708. if (opt & OPT_R) /* release on quit */
  1709. perform_d6_release(&srv6_buf, requested_ipv6);
  1710. retval = 0;
  1711. ret:
  1712. /*if (client_data.pidfile) - remove_pidfile has its own check */
  1713. remove_pidfile(client_data.pidfile);
  1714. return retval;
  1715. }