d6_dhcpc.c 62 KB

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