d6_dhcpc.c 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * DHCPv6 client.
  4. *
  5. * 2011-11.
  6. * WARNING: THIS CODE IS INCOMPLETE. IT IS NOWHERE NEAR
  7. * TO BE READY FOR PRODUCTION USE.
  8. *
  9. * Copyright (C) 2011 Denys Vlasenko.
  10. *
  11. * Licensed under GPLv2, see file LICENSE in this source tree.
  12. */
  13. //config:config UDHCPC6
  14. //config: bool "udhcp client for DHCPv6 (udhcpc6)"
  15. //config: default n # not yet ready
  16. //config: depends on FEATURE_IPV6
  17. //config: help
  18. //config: udhcpc6 is a DHCPv6 client
  19. //applet:IF_UDHCPC6(APPLET(udhcpc6, BB_DIR_USR_BIN, BB_SUID_DROP))
  20. //kbuild:lib-$(CONFIG_UDHCPC6) += d6_dhcpc.o d6_packet.o d6_socket.o common.o socket.o signalpipe.o
  21. #include <syslog.h>
  22. /* Override ENABLE_FEATURE_PIDFILE - ifupdown needs our pidfile to always exist */
  23. #define WANT_PIDFILE 1
  24. #include "common.h"
  25. #include "dhcpd.h"
  26. #include "dhcpc.h"
  27. #include "d6_common.h"
  28. #include <netinet/if_ether.h>
  29. #include <netpacket/packet.h>
  30. #include <linux/filter.h>
  31. /* "struct client_config_t client_config" is in bb_common_bufsiz1 */
  32. #if ENABLE_LONG_OPTS
  33. static const char udhcpc6_longopts[] ALIGN1 =
  34. "interface\0" Required_argument "i"
  35. "now\0" No_argument "n"
  36. "pidfile\0" Required_argument "p"
  37. "quit\0" No_argument "q"
  38. "release\0" No_argument "R"
  39. "request\0" Required_argument "r"
  40. "script\0" Required_argument "s"
  41. "timeout\0" Required_argument "T"
  42. "retries\0" Required_argument "t"
  43. "tryagain\0" Required_argument "A"
  44. "syslog\0" No_argument "S"
  45. "request-option\0" Required_argument "O"
  46. "no-default-options\0" No_argument "o"
  47. "foreground\0" No_argument "f"
  48. "background\0" No_argument "b"
  49. /// IF_FEATURE_UDHCPC_ARPING("arping\0" No_argument "a")
  50. IF_FEATURE_UDHCP_PORT("client-port\0" Required_argument "P")
  51. ;
  52. #endif
  53. /* Must match getopt32 option string order */
  54. enum {
  55. OPT_i = 1 << 0,
  56. OPT_n = 1 << 1,
  57. OPT_p = 1 << 2,
  58. OPT_q = 1 << 3,
  59. OPT_R = 1 << 4,
  60. OPT_r = 1 << 5,
  61. OPT_s = 1 << 6,
  62. OPT_T = 1 << 7,
  63. OPT_t = 1 << 8,
  64. OPT_S = 1 << 9,
  65. OPT_A = 1 << 10,
  66. OPT_O = 1 << 11,
  67. OPT_o = 1 << 12,
  68. OPT_x = 1 << 13,
  69. OPT_f = 1 << 14,
  70. /* The rest has variable bit positions, need to be clever */
  71. OPTBIT_f = 14,
  72. USE_FOR_MMU( OPTBIT_b,)
  73. ///IF_FEATURE_UDHCPC_ARPING(OPTBIT_a,)
  74. IF_FEATURE_UDHCP_PORT( OPTBIT_P,)
  75. USE_FOR_MMU( OPT_b = 1 << OPTBIT_b,)
  76. ///IF_FEATURE_UDHCPC_ARPING(OPT_a = 1 << OPTBIT_a,)
  77. IF_FEATURE_UDHCP_PORT( OPT_P = 1 << OPTBIT_P,)
  78. };
  79. /*** Utility functions ***/
  80. static void *d6_find_option(uint8_t *option, uint8_t *option_end, unsigned code)
  81. {
  82. /* "length minus 4" */
  83. int len_m4 = option_end - option - 4;
  84. while (len_m4 >= 0) {
  85. /* Next option's len is too big? */
  86. if (option[3] > len_m4)
  87. return NULL; /* yes. bogus packet! */
  88. /* So far we treat any opts with code >255
  89. * or len >255 as bogus, and stop at once.
  90. * This simplifies big-endian handling.
  91. */
  92. if (option[0] != 0 || option[2] != 0)
  93. return NULL;
  94. /* Option seems to be valid */
  95. /* Does its code match? */
  96. if (option[1] == code)
  97. return option; /* yes! */
  98. option += option[3] + 4;
  99. len_m4 -= option[3] + 4;
  100. }
  101. return NULL;
  102. }
  103. static void *d6_copy_option(uint8_t *option, uint8_t *option_end, unsigned code)
  104. {
  105. uint8_t *opt = d6_find_option(option, option_end, code);
  106. if (!opt)
  107. return opt;
  108. return xmemdup(opt, opt[3] + 4);
  109. }
  110. static void *d6_store_blob(void *dst, const void *src, unsigned len)
  111. {
  112. memcpy(dst, src, len);
  113. return dst + len;
  114. }
  115. /*** Script execution code ***/
  116. static char** new_env(void)
  117. {
  118. client6_data.env_ptr = xrealloc_vector(client6_data.env_ptr, 3, client6_data.env_idx);
  119. return &client6_data.env_ptr[client6_data.env_idx++];
  120. }
  121. /* put all the parameters into the environment */
  122. static void option_to_env(uint8_t *option, uint8_t *option_end)
  123. {
  124. /* "length minus 4" */
  125. int len_m4 = option_end - option - 4;
  126. while (len_m4 >= 0) {
  127. uint32_t v32;
  128. char ipv6str[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")];
  129. if (option[0] != 0 || option[2] != 0)
  130. break;
  131. switch (option[1]) {
  132. //case D6_OPT_CLIENTID:
  133. //case D6_OPT_SERVERID:
  134. case D6_OPT_IA_NA:
  135. case D6_OPT_IA_PD:
  136. option_to_env(option + 16, option + 4 + option[3]);
  137. break;
  138. //case D6_OPT_IA_TA:
  139. case D6_OPT_IAADDR:
  140. /* 0 1 2 3
  141. * 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
  142. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  143. * | OPTION_IAADDR | option-len |
  144. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  145. * | |
  146. * | IPv6 address |
  147. * | |
  148. * | |
  149. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  150. * | preferred-lifetime |
  151. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  152. * | valid-lifetime |
  153. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  154. */
  155. sprint_nip6(ipv6str, option + 4);
  156. *new_env() = xasprintf("ipv6=%s", ipv6str);
  157. move_from_unaligned32(v32, option + 4 + 16 + 4);
  158. *new_env() = xasprintf("lease=%u", (unsigned)v32);
  159. break;
  160. //case D6_OPT_ORO:
  161. //case D6_OPT_PREFERENCE:
  162. //case D6_OPT_ELAPSED_TIME:
  163. //case D6_OPT_RELAY_MSG:
  164. //case D6_OPT_AUTH:
  165. //case D6_OPT_UNICAST:
  166. //case D6_OPT_STATUS_CODE:
  167. //case D6_OPT_RAPID_COMMIT:
  168. //case D6_OPT_USER_CLASS:
  169. //case D6_OPT_VENDOR_CLASS:
  170. //case D6_OPT_VENDOR_OPTS:
  171. //case D6_OPT_INTERFACE_ID:
  172. //case D6_OPT_RECONF_MSG:
  173. //case D6_OPT_RECONF_ACCEPT:
  174. case D6_OPT_IAPREFIX:
  175. /* 0 1 2 3
  176. * 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
  177. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  178. * | OPTION_IAPREFIX | option-length |
  179. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  180. * | preferred-lifetime |
  181. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  182. * | valid-lifetime |
  183. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  184. * | prefix-length | |
  185. * +-+-+-+-+-+-+-+-+ IPv6 prefix |
  186. * | (16 octets) |
  187. * | |
  188. * | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  189. * | |
  190. * +-+-+-+-+-+-+-+-+
  191. */
  192. //move_from_unaligned32(v32, option + 4 + 4);
  193. //*new_env() = xasprintf("lease=%u", (unsigned)v32);
  194. sprint_nip6(ipv6str, option + 4 + 4 + 1);
  195. *new_env() = xasprintf("ipv6prefix=%s/%u", ipv6str, (unsigned)(option[4 + 4]));
  196. }
  197. option += 4 + option[3];
  198. len_m4 -= 4 + option[3];
  199. }
  200. }
  201. static char **fill_envp(struct d6_packet *packet)
  202. {
  203. char **envp, **curr;
  204. client6_data.env_ptr = NULL;
  205. client6_data.env_idx = 0;
  206. *new_env() = xasprintf("interface=%s", client_config.interface);
  207. if (packet)
  208. option_to_env(packet->d6_options, packet->d6_options + sizeof(packet->d6_options));
  209. envp = curr = client6_data.env_ptr;
  210. while (*curr)
  211. putenv(*curr++);
  212. return envp;
  213. }
  214. /* Call a script with a par file and env vars */
  215. static void d6_run_script(struct d6_packet *packet, const char *name)
  216. {
  217. char **envp, **curr;
  218. char *argv[3];
  219. envp = fill_envp(packet);
  220. /* call script */
  221. log1("executing %s %s", client_config.script, name);
  222. argv[0] = (char*) client_config.script;
  223. argv[1] = (char*) name;
  224. argv[2] = NULL;
  225. spawn_and_wait(argv);
  226. for (curr = envp; *curr; curr++) {
  227. log2(" %s", *curr);
  228. bb_unsetenv_and_free(*curr);
  229. }
  230. free(envp);
  231. }
  232. /*** Sending/receiving packets ***/
  233. static ALWAYS_INLINE uint32_t random_xid(void)
  234. {
  235. uint32_t t = rand() & htonl(0x00ffffff);
  236. return t;
  237. }
  238. /* Initialize the packet with the proper defaults */
  239. static uint8_t *init_d6_packet(struct d6_packet *packet, char type, uint32_t xid)
  240. {
  241. struct d6_option *clientid;
  242. memset(packet, 0, sizeof(*packet));
  243. packet->d6_xid32 = xid;
  244. packet->d6_msg_type = type;
  245. clientid = (void*)client_config.clientid;
  246. return d6_store_blob(packet->d6_options, clientid, clientid->len + 2+2);
  247. }
  248. static uint8_t *add_d6_client_options(uint8_t *ptr)
  249. {
  250. return ptr;
  251. //uint8_t c;
  252. //int i, end, len;
  253. /* Add a "param req" option with the list of options we'd like to have
  254. * from stubborn DHCP servers. Pull the data from the struct in common.c.
  255. * No bounds checking because it goes towards the head of the packet. */
  256. //...
  257. /* Add -x options if any */
  258. //...
  259. }
  260. static int d6_mcast_from_client_config_ifindex(struct d6_packet *packet, uint8_t *end)
  261. {
  262. static const uint8_t FF02__1_2[16] = {
  263. 0xFF, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  264. 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02,
  265. };
  266. return d6_send_raw_packet(
  267. packet, (end - (uint8_t*) packet),
  268. /*src*/ NULL, CLIENT_PORT6,
  269. /*dst*/ (struct in6_addr*)FF02__1_2, SERVER_PORT6, MAC_BCAST_ADDR,
  270. client_config.ifindex
  271. );
  272. }
  273. /* Milticast a DHCPv6 Solicit packet to the network, with an optionally requested IP.
  274. *
  275. * RFC 3315 17.1.1. Creation of Solicit Messages
  276. *
  277. * The client MUST include a Client Identifier option to identify itself
  278. * to the server. The client includes IA options for any IAs to which
  279. * it wants the server to assign addresses. The client MAY include
  280. * addresses in the IAs as a hint to the server about addresses for
  281. * which the client has a preference. ...
  282. *
  283. * The client uses IA_NA options to request the assignment of non-
  284. * temporary addresses and uses IA_TA options to request the assignment
  285. * of temporary addresses. Either IA_NA or IA_TA options, or a
  286. * combination of both, can be included in DHCP messages.
  287. *
  288. * The client SHOULD include an Option Request option (see section 22.7)
  289. * to indicate the options the client is interested in receiving. The
  290. * client MAY additionally include instances of those options that are
  291. * identified in the Option Request option, with data values as hints to
  292. * the server about parameter values the client would like to have
  293. * returned.
  294. *
  295. * The client includes a Reconfigure Accept option (see section 22.20)
  296. * if the client is willing to accept Reconfigure messages from the
  297. * server.
  298. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  299. | OPTION_CLIENTID | option-len |
  300. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  301. . .
  302. . DUID .
  303. . (variable length) .
  304. . .
  305. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  306. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  307. | OPTION_IA_NA | option-len |
  308. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  309. | IAID (4 octets) |
  310. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  311. | T1 |
  312. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  313. | T2 |
  314. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  315. | |
  316. . IA_NA-options .
  317. . .
  318. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  319. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  320. | OPTION_IAADDR | option-len |
  321. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  322. | |
  323. | IPv6 address |
  324. | |
  325. | |
  326. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  327. | preferred-lifetime |
  328. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  329. | valid-lifetime |
  330. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  331. . .
  332. . IAaddr-options .
  333. . .
  334. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  335. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  336. | OPTION_ORO | option-len |
  337. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  338. | requested-option-code-1 | requested-option-code-2 |
  339. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  340. | ... |
  341. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  342. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  343. | OPTION_RECONF_ACCEPT | 0 |
  344. +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  345. */
  346. /* NOINLINE: limit stack usage in caller */
  347. static NOINLINE int send_d6_discover(uint32_t xid, struct in6_addr *requested_ipv6)
  348. {
  349. struct d6_packet packet;
  350. uint8_t *opt_ptr;
  351. unsigned len;
  352. /* Fill in: msg type, client id */
  353. opt_ptr = init_d6_packet(&packet, D6_MSG_SOLICIT, xid);
  354. /* Create new IA_NA, optionally with included IAADDR with requested IP */
  355. free(client6_data.ia_na);
  356. len = requested_ipv6 ? 2+2+4+4+4 + 2+2+16+4+4 : 2+2+4+4+4;
  357. client6_data.ia_na = xzalloc(len);
  358. client6_data.ia_na->code = D6_OPT_IA_NA;
  359. client6_data.ia_na->len = len - 4;
  360. *(uint32_t*)client6_data.ia_na->data = rand(); /* IAID */
  361. if (requested_ipv6) {
  362. struct d6_option *iaaddr = (void*)(client6_data.ia_na->data + 4+4+4);
  363. iaaddr->code = D6_OPT_IAADDR;
  364. iaaddr->len = 16+4+4;
  365. memcpy(iaaddr->data, requested_ipv6, 16);
  366. }
  367. opt_ptr = d6_store_blob(opt_ptr, client6_data.ia_na, len);
  368. /* Add options:
  369. * "param req" option according to -O, options specified with -x
  370. */
  371. opt_ptr = add_d6_client_options(opt_ptr);
  372. bb_error_msg("sending %s", "discover");
  373. return d6_mcast_from_client_config_ifindex(&packet, opt_ptr);
  374. }
  375. /* Multicast a DHCPv6 request message
  376. *
  377. * RFC 3315 18.1.1. Creation and Transmission of Request Messages
  378. *
  379. * The client uses a Request message to populate IAs with addresses and
  380. * obtain other configuration information. The client includes one or
  381. * more IA options in the Request message. The server then returns
  382. * addresses and other information about the IAs to the client in IA
  383. * options in a Reply message.
  384. *
  385. * The client generates a transaction ID and inserts this value in the
  386. * "transaction-id" field.
  387. *
  388. * The client places the identifier of the destination server in a
  389. * Server Identifier option.
  390. *
  391. * The client MUST include a Client Identifier option to identify itself
  392. * to the server. The client adds any other appropriate options,
  393. * including one or more IA options (if the client is requesting that
  394. * the server assign it some network addresses).
  395. *
  396. * The client MUST include an Option Request option (see section 22.7)
  397. * to indicate the options the client is interested in receiving. The
  398. * client MAY include options with data values as hints to the server
  399. * about parameter values the client would like to have returned.
  400. *
  401. * The client includes a Reconfigure Accept option (see section 22.20)
  402. * indicating whether or not the client is willing to accept Reconfigure
  403. * messages from the server.
  404. */
  405. /* NOINLINE: limit stack usage in caller */
  406. static NOINLINE int send_d6_select(uint32_t xid)
  407. {
  408. struct d6_packet packet;
  409. uint8_t *opt_ptr;
  410. /* Fill in: msg type, client id */
  411. opt_ptr = init_d6_packet(&packet, D6_MSG_REQUEST, xid);
  412. /* server id */
  413. opt_ptr = d6_store_blob(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
  414. /* IA NA (contains requested IP) */
  415. opt_ptr = d6_store_blob(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
  416. /* Add options:
  417. * "param req" option according to -O, options specified with -x
  418. */
  419. opt_ptr = add_d6_client_options(opt_ptr);
  420. bb_error_msg("sending %s", "select");
  421. return d6_mcast_from_client_config_ifindex(&packet, opt_ptr);
  422. }
  423. /* Unicast or broadcast a DHCP renew message
  424. *
  425. * RFC 3315 18.1.3. Creation and Transmission of Renew Messages
  426. *
  427. * To extend the valid and preferred lifetimes for the addresses
  428. * associated with an IA, the client sends a Renew message to the server
  429. * from which the client obtained the addresses in the IA containing an
  430. * IA option for the IA. The client includes IA Address options in the
  431. * IA option for the addresses associated with the IA. The server
  432. * determines new lifetimes for the addresses in the IA according to the
  433. * administrative configuration of the server. The server may also add
  434. * new addresses to the IA. The server may remove addresses from the IA
  435. * by setting the preferred and valid lifetimes of those addresses to
  436. * zero.
  437. *
  438. * The server controls the time at which the client contacts the server
  439. * to extend the lifetimes on assigned addresses through the T1 and T2
  440. * parameters assigned to an IA.
  441. *
  442. * At time T1 for an IA, the client initiates a Renew/Reply message
  443. * exchange to extend the lifetimes on any addresses in the IA. The
  444. * client includes an IA option with all addresses currently assigned to
  445. * the IA in its Renew message.
  446. *
  447. * If T1 or T2 is set to 0 by the server (for an IA_NA) or there are no
  448. * T1 or T2 times (for an IA_TA), the client may send a Renew or Rebind
  449. * message, respectively, at the client's discretion.
  450. *
  451. * The client sets the "msg-type" field to RENEW. The client generates
  452. * a transaction ID and inserts this value in the "transaction-id"
  453. * field.
  454. *
  455. * The client places the identifier of the destination server in a
  456. * Server Identifier option.
  457. *
  458. * The client MUST include a Client Identifier option to identify itself
  459. * to the server. The client adds any appropriate options, including
  460. * one or more IA options. The client MUST include the list of
  461. * addresses the client currently has associated with the IAs in the
  462. * Renew message.
  463. *
  464. * The client MUST include an Option Request option (see section 22.7)
  465. * to indicate the options the client is interested in receiving. The
  466. * client MAY include options with data values as hints to the server
  467. * about parameter values the client would like to have returned.
  468. */
  469. /* NOINLINE: limit stack usage in caller */
  470. static NOINLINE int send_d6_renew(uint32_t xid, struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
  471. {
  472. struct d6_packet packet;
  473. uint8_t *opt_ptr;
  474. /* Fill in: msg type, client id */
  475. opt_ptr = init_d6_packet(&packet, DHCPREQUEST, xid);
  476. /* server id */
  477. opt_ptr = d6_store_blob(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
  478. /* IA NA (contains requested IP) */
  479. opt_ptr = d6_store_blob(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
  480. /* Add options:
  481. * "param req" option according to -O, options specified with -x
  482. */
  483. opt_ptr = add_d6_client_options(opt_ptr);
  484. bb_error_msg("sending %s", "renew");
  485. if (server_ipv6)
  486. return d6_send_kernel_packet(
  487. &packet, (opt_ptr - (uint8_t*) &packet),
  488. our_cur_ipv6, CLIENT_PORT6,
  489. server_ipv6, SERVER_PORT6
  490. );
  491. return d6_mcast_from_client_config_ifindex(&packet, opt_ptr);
  492. }
  493. /* Unicast a DHCP release message */
  494. static int send_d6_release(struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
  495. {
  496. struct d6_packet packet;
  497. uint8_t *opt_ptr;
  498. /* Fill in: msg type, client id */
  499. opt_ptr = init_d6_packet(&packet, D6_MSG_RELEASE, random_xid());
  500. /* server id */
  501. opt_ptr = d6_store_blob(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
  502. /* IA NA (contains our current IP) */
  503. opt_ptr = d6_store_blob(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
  504. bb_error_msg("sending %s", "release");
  505. return d6_send_kernel_packet(
  506. &packet, (opt_ptr - (uint8_t*) &packet),
  507. our_cur_ipv6, CLIENT_PORT6,
  508. server_ipv6, SERVER_PORT6
  509. );
  510. }
  511. /* Returns -1 on errors that are fatal for the socket, -2 for those that aren't */
  512. /* NOINLINE: limit stack usage in caller */
  513. static NOINLINE int d6_recv_raw_packet(struct in6_addr *peer_ipv6
  514. UNUSED_PARAM
  515. , struct d6_packet *d6_pkt, int fd)
  516. {
  517. int bytes;
  518. struct ip6_udp_d6_packet packet;
  519. bytes = safe_read(fd, &packet, sizeof(packet));
  520. if (bytes < 0) {
  521. log1("packet read error, ignoring");
  522. /* NB: possible down interface, etc. Caller should pause. */
  523. return bytes; /* returns -1 */
  524. }
  525. if (bytes < (int) (sizeof(packet.ip6) + sizeof(packet.udp))) {
  526. log1("packet is too short, ignoring");
  527. return -2;
  528. }
  529. if (bytes < sizeof(packet.ip6) + ntohs(packet.ip6.ip6_plen)) {
  530. /* packet is bigger than sizeof(packet), we did partial read */
  531. log1("oversized packet, ignoring");
  532. return -2;
  533. }
  534. /* ignore any extra garbage bytes */
  535. bytes = sizeof(packet.ip6) + ntohs(packet.ip6.ip6_plen);
  536. /* make sure its the right packet for us, and that it passes sanity checks */
  537. if (packet.ip6.ip6_nxt != IPPROTO_UDP
  538. || (packet.ip6.ip6_vfc >> 4) != 6
  539. || packet.udp.dest != htons(CLIENT_PORT6)
  540. /* || bytes > (int) sizeof(packet) - can't happen */
  541. || packet.udp.len != packet.ip6.ip6_plen
  542. ) {
  543. log1("unrelated/bogus packet, ignoring");
  544. return -2;
  545. }
  546. //How to do this for ipv6?
  547. // /* verify UDP checksum. IP header has to be modified for this */
  548. // memset(&packet.ip, 0, offsetof(struct iphdr, protocol));
  549. // /* ip.xx fields which are not memset: protocol, check, saddr, daddr */
  550. // packet.ip.tot_len = packet.udp.len; /* yes, this is needed */
  551. // check = packet.udp.check;
  552. // packet.udp.check = 0;
  553. // if (check && check != inet_cksum((uint16_t *)&packet, bytes)) {
  554. // log1("packet with bad UDP checksum received, ignoring");
  555. // return -2;
  556. // }
  557. log1("received %s", "a packet");
  558. d6_dump_packet(&packet.data);
  559. bytes -= sizeof(packet.ip6) + sizeof(packet.udp);
  560. memcpy(d6_pkt, &packet.data, bytes);
  561. return bytes;
  562. }
  563. /*** Main ***/
  564. static int sockfd = -1;
  565. #define LISTEN_NONE 0
  566. #define LISTEN_KERNEL 1
  567. #define LISTEN_RAW 2
  568. static smallint listen_mode;
  569. /* initial state: (re)start DHCP negotiation */
  570. #define INIT_SELECTING 0
  571. /* discover was sent, DHCPOFFER reply received */
  572. #define REQUESTING 1
  573. /* select/renew was sent, DHCPACK reply received */
  574. #define BOUND 2
  575. /* half of lease passed, want to renew it by sending unicast renew requests */
  576. #define RENEWING 3
  577. /* renew requests were not answered, lease is almost over, send broadcast renew */
  578. #define REBINDING 4
  579. /* manually requested renew (SIGUSR1) */
  580. #define RENEW_REQUESTED 5
  581. /* release, possibly manually requested (SIGUSR2) */
  582. #define RELEASED 6
  583. static smallint state;
  584. static int d6_raw_socket(int ifindex)
  585. {
  586. int fd;
  587. struct sockaddr_ll sock;
  588. /*
  589. * Comment:
  590. *
  591. * I've selected not to see LL header, so BPF doesn't see it, too.
  592. * The filter may also pass non-IP and non-ARP packets, but we do
  593. * a more complete check when receiving the message in userspace.
  594. *
  595. * and filter shamelessly stolen from:
  596. *
  597. * http://www.flamewarmaster.de/software/dhcpclient/
  598. *
  599. * There are a few other interesting ideas on that page (look under
  600. * "Motivation"). Use of netlink events is most interesting. Think
  601. * of various network servers listening for events and reconfiguring.
  602. * That would obsolete sending HUP signals and/or make use of restarts.
  603. *
  604. * Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
  605. * License: GPL v2.
  606. *
  607. * TODO: make conditional?
  608. */
  609. #if 0
  610. static const struct sock_filter filter_instr[] = {
  611. /* load 9th byte (protocol) */
  612. BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
  613. /* jump to L1 if it is IPPROTO_UDP, else to L4 */
  614. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 0, 6),
  615. /* L1: load halfword from offset 6 (flags and frag offset) */
  616. BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 6),
  617. /* jump to L4 if any bits in frag offset field are set, else to L2 */
  618. BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K, 0x1fff, 4, 0),
  619. /* L2: skip IP header (load index reg with header len) */
  620. BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0),
  621. /* load udp destination port from halfword[header_len + 2] */
  622. BPF_STMT(BPF_LD|BPF_H|BPF_IND, 2),
  623. /* jump to L3 if udp dport is CLIENT_PORT6, else to L4 */
  624. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 68, 0, 1),
  625. /* L3: accept packet */
  626. BPF_STMT(BPF_RET|BPF_K, 0x7fffffff),
  627. /* L4: discard packet */
  628. BPF_STMT(BPF_RET|BPF_K, 0),
  629. };
  630. static const struct sock_fprog filter_prog = {
  631. .len = sizeof(filter_instr) / sizeof(filter_instr[0]),
  632. /* casting const away: */
  633. .filter = (struct sock_filter *) filter_instr,
  634. };
  635. #endif
  636. log1("opening raw socket on ifindex %d", ifindex); //log2?
  637. fd = xsocket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IPV6));
  638. log1("got raw socket fd %d", fd); //log2?
  639. sock.sll_family = AF_PACKET;
  640. sock.sll_protocol = htons(ETH_P_IPV6);
  641. sock.sll_ifindex = ifindex;
  642. xbind(fd, (struct sockaddr *) &sock, sizeof(sock));
  643. #if 0
  644. if (CLIENT_PORT6 == 546) {
  645. /* Use only if standard port is in use */
  646. /* Ignoring error (kernel may lack support for this) */
  647. if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog,
  648. sizeof(filter_prog)) >= 0)
  649. log1("attached filter to raw socket fd %d", fd); // log?
  650. }
  651. #endif
  652. log1("created raw socket");
  653. return fd;
  654. }
  655. static void change_listen_mode(int new_mode)
  656. {
  657. log1("entering listen mode: %s",
  658. new_mode != LISTEN_NONE
  659. ? (new_mode == LISTEN_KERNEL ? "kernel" : "raw")
  660. : "none"
  661. );
  662. listen_mode = new_mode;
  663. if (sockfd >= 0) {
  664. close(sockfd);
  665. sockfd = -1;
  666. }
  667. if (new_mode == LISTEN_KERNEL)
  668. sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT6, client_config.interface);
  669. else if (new_mode != LISTEN_NONE)
  670. sockfd = d6_raw_socket(client_config.ifindex);
  671. /* else LISTEN_NONE: sockfd stays closed */
  672. }
  673. /* Called only on SIGUSR1 */
  674. static void perform_renew(void)
  675. {
  676. bb_error_msg("performing DHCP renew");
  677. switch (state) {
  678. case BOUND:
  679. change_listen_mode(LISTEN_KERNEL);
  680. case RENEWING:
  681. case REBINDING:
  682. state = RENEW_REQUESTED;
  683. break;
  684. case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
  685. d6_run_script(NULL, "deconfig");
  686. case REQUESTING:
  687. case RELEASED:
  688. change_listen_mode(LISTEN_RAW);
  689. state = INIT_SELECTING;
  690. break;
  691. case INIT_SELECTING:
  692. break;
  693. }
  694. }
  695. static void perform_d6_release(struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
  696. {
  697. /* send release packet */
  698. if (state == BOUND || state == RENEWING || state == REBINDING) {
  699. bb_error_msg("unicasting a release");
  700. send_d6_release(server_ipv6, our_cur_ipv6); /* unicast */
  701. d6_run_script(NULL, "deconfig");
  702. }
  703. bb_error_msg("entering released state");
  704. change_listen_mode(LISTEN_NONE);
  705. state = RELEASED;
  706. }
  707. ///static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
  708. ///{
  709. /// uint8_t *storage;
  710. /// int len = strnlen(str, 255);
  711. /// storage = xzalloc(len + extra + OPT_DATA);
  712. /// storage[OPT_CODE] = code;
  713. /// storage[OPT_LEN] = len + extra;
  714. /// memcpy(storage + extra + OPT_DATA, str, len);
  715. /// return storage;
  716. ///}
  717. #if BB_MMU
  718. static void client_background(void)
  719. {
  720. bb_daemonize(0);
  721. logmode &= ~LOGMODE_STDIO;
  722. /* rewrite pidfile, as our pid is different now */
  723. write_pidfile(client_config.pidfile);
  724. }
  725. #endif
  726. //usage:#if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
  727. //usage:# define IF_UDHCP_VERBOSE(...) __VA_ARGS__
  728. //usage:#else
  729. //usage:# define IF_UDHCP_VERBOSE(...)
  730. //usage:#endif
  731. //usage:#define udhcpc6_trivial_usage
  732. //usage: "[-fbnq"IF_UDHCP_VERBOSE("v")"oR] [-i IFACE] [-r IP] [-s PROG] [-p PIDFILE]\n"
  733. //usage: " [-x OPT:VAL]... [-O OPT]..." IF_FEATURE_UDHCP_PORT(" [-P N]")
  734. //usage:#define udhcpc6_full_usage "\n"
  735. //usage: IF_LONG_OPTS(
  736. //usage: "\n -i,--interface IFACE Interface to use (default eth0)"
  737. //usage: "\n -p,--pidfile FILE Create pidfile"
  738. //usage: "\n -s,--script PROG Run PROG at DHCP events (default "CONFIG_UDHCPC_DEFAULT_SCRIPT")"
  739. //usage: "\n -B,--broadcast Request broadcast replies"
  740. //usage: "\n -t,--retries N Send up to N discover packets"
  741. //usage: "\n -T,--timeout N Pause between packets (default 3 seconds)"
  742. //usage: "\n -A,--tryagain N Wait N seconds after failure (default 20)"
  743. //usage: "\n -f,--foreground Run in foreground"
  744. //usage: USE_FOR_MMU(
  745. //usage: "\n -b,--background Background if lease is not obtained"
  746. //usage: )
  747. //usage: "\n -n,--now Exit if lease is not obtained"
  748. //usage: "\n -q,--quit Exit after obtaining lease"
  749. //usage: "\n -R,--release Release IP on exit"
  750. //usage: "\n -S,--syslog Log to syslog too"
  751. //usage: IF_FEATURE_UDHCP_PORT(
  752. //usage: "\n -P,--client-port N Use port N (default 546)"
  753. //usage: )
  754. ////usage: IF_FEATURE_UDHCPC_ARPING(
  755. ////usage: "\n -a,--arping Use arping to validate offered address"
  756. ////usage: )
  757. //usage: "\n -O,--request-option OPT Request option OPT from server (cumulative)"
  758. //usage: "\n -o,--no-default-options Don't request any options (unless -O is given)"
  759. //usage: "\n -r,--request IP Request this IP address"
  760. //usage: "\n -x OPT:VAL Include option OPT in sent packets (cumulative)"
  761. //usage: "\n Examples of string, numeric, and hex byte opts:"
  762. //usage: "\n -x hostname:bbox - option 12"
  763. //usage: "\n -x lease:3600 - option 51 (lease time)"
  764. //usage: "\n -x 0x3d:0100BEEFC0FFEE - option 61 (client id)"
  765. //usage: IF_UDHCP_VERBOSE(
  766. //usage: "\n -v Verbose"
  767. //usage: )
  768. //usage: )
  769. //usage: IF_NOT_LONG_OPTS(
  770. //usage: "\n -i IFACE Interface to use (default eth0)"
  771. //usage: "\n -p FILE Create pidfile"
  772. //usage: "\n -s PROG Run PROG at DHCP events (default "CONFIG_UDHCPC_DEFAULT_SCRIPT")"
  773. //usage: "\n -B Request broadcast replies"
  774. //usage: "\n -t N Send up to N discover packets"
  775. //usage: "\n -T N Pause between packets (default 3 seconds)"
  776. //usage: "\n -A N Wait N seconds (default 20) after failure"
  777. //usage: "\n -f Run in foreground"
  778. //usage: USE_FOR_MMU(
  779. //usage: "\n -b Background if lease is not obtained"
  780. //usage: )
  781. //usage: "\n -n Exit if lease is not obtained"
  782. //usage: "\n -q Exit after obtaining lease"
  783. //usage: "\n -R Release IP on exit"
  784. //usage: "\n -S Log to syslog too"
  785. //usage: IF_FEATURE_UDHCP_PORT(
  786. //usage: "\n -P N Use port N (default 546)"
  787. //usage: )
  788. ////usage: IF_FEATURE_UDHCPC_ARPING(
  789. ////usage: "\n -a Use arping to validate offered address"
  790. ////usage: )
  791. //usage: "\n -O OPT Request option OPT from server (cumulative)"
  792. //usage: "\n -o Don't request any options (unless -O is given)"
  793. //usage: "\n -r IP Request this IP address"
  794. //usage: "\n -x OPT:VAL Include option OPT in sent packets (cumulative)"
  795. //usage: "\n Examples of string, numeric, and hex byte opts:"
  796. //usage: "\n -x hostname:bbox - option 12"
  797. //usage: "\n -x lease:3600 - option 51 (lease time)"
  798. //usage: "\n -x 0x3d:0100BEEFC0FFEE - option 61 (client id)"
  799. //usage: IF_UDHCP_VERBOSE(
  800. //usage: "\n -v Verbose"
  801. //usage: )
  802. //usage: )
  803. //usage: "\nSignals:"
  804. //usage: "\n USR1 Renew lease"
  805. //usage: "\n USR2 Release lease"
  806. int udhcpc6_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  807. int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
  808. {
  809. const char *str_r;
  810. IF_FEATURE_UDHCP_PORT(char *str_P;)
  811. void *clientid_mac_ptr;
  812. llist_t *list_O = NULL;
  813. llist_t *list_x = NULL;
  814. int tryagain_timeout = 20;
  815. int discover_timeout = 3;
  816. int discover_retries = 3;
  817. struct in6_addr srv6_buf;
  818. struct in6_addr ipv6_buf;
  819. struct in6_addr *requested_ipv6;
  820. uint32_t xid = 0;
  821. int packet_num;
  822. int timeout; /* must be signed */
  823. unsigned already_waited_sec;
  824. unsigned opt;
  825. int max_fd;
  826. int retval;
  827. fd_set rfds;
  828. setup_common_bufsiz();
  829. /* Default options */
  830. IF_FEATURE_UDHCP_PORT(SERVER_PORT6 = 547;)
  831. IF_FEATURE_UDHCP_PORT(CLIENT_PORT6 = 546;)
  832. client_config.interface = "eth0";
  833. client_config.script = CONFIG_UDHCPC_DEFAULT_SCRIPT;
  834. /* Parse command line */
  835. /* O,x: list; -T,-t,-A take numeric param */
  836. opt_complementary = "O::x::T+:t+:A+" IF_UDHCP_VERBOSE(":vv") ;
  837. IF_LONG_OPTS(applet_long_options = udhcpc6_longopts;)
  838. opt = getopt32(argv, "i:np:qRr:s:T:t:SA:O:ox:f"
  839. USE_FOR_MMU("b")
  840. ///IF_FEATURE_UDHCPC_ARPING("a")
  841. IF_FEATURE_UDHCP_PORT("P:")
  842. "v"
  843. , &client_config.interface, &client_config.pidfile, &str_r /* i,p */
  844. , &client_config.script /* s */
  845. , &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */
  846. , &list_O
  847. , &list_x
  848. IF_FEATURE_UDHCP_PORT(, &str_P)
  849. IF_UDHCP_VERBOSE(, &dhcp_verbose)
  850. );
  851. requested_ipv6 = NULL;
  852. if (opt & OPT_r) {
  853. if (inet_pton(AF_INET6, str_r, &ipv6_buf) <= 0)
  854. bb_error_msg_and_die("bad IPv6 address '%s'", str_r);
  855. requested_ipv6 = &ipv6_buf;
  856. }
  857. #if ENABLE_FEATURE_UDHCP_PORT
  858. if (opt & OPT_P) {
  859. CLIENT_PORT6 = xatou16(str_P);
  860. SERVER_PORT6 = CLIENT_PORT6 + 1;
  861. }
  862. #endif
  863. while (list_O) {
  864. char *optstr = llist_pop(&list_O);
  865. unsigned n = bb_strtou(optstr, NULL, 0);
  866. if (errno || n > 254) {
  867. n = udhcp_option_idx(optstr);
  868. n = dhcp_optflags[n].code;
  869. }
  870. client_config.opt_mask[n >> 3] |= 1 << (n & 7);
  871. }
  872. if (!(opt & OPT_o)) {
  873. /*
  874. unsigned i, n;
  875. for (i = 0; (n = dhcp_optflags[i].code) != 0; i++) {
  876. if (dhcp_optflags[i].flags & OPTION_REQ) {
  877. client_config.opt_mask[n >> 3] |= 1 << (n & 7);
  878. }
  879. }
  880. */
  881. }
  882. while (list_x) {
  883. char *optstr = llist_pop(&list_x);
  884. char *colon = strchr(optstr, ':');
  885. if (colon)
  886. *colon = ' ';
  887. /* now it looks similar to udhcpd's config file line:
  888. * "optname optval", using the common routine: */
  889. udhcp_str2optset(optstr, &client_config.options);
  890. }
  891. if (udhcp_read_interface(client_config.interface,
  892. &client_config.ifindex,
  893. NULL,
  894. client_config.client_mac)
  895. ) {
  896. return 1;
  897. }
  898. /* Create client ID based on mac, set clientid_mac_ptr */
  899. {
  900. struct d6_option *clientid;
  901. clientid = xzalloc(2+2+2+2+6);
  902. clientid->code = D6_OPT_CLIENTID;
  903. clientid->len = 2+2+6;
  904. clientid->data[1] = 3; /* DUID-LL */
  905. clientid->data[3] = 1; /* ethernet */
  906. clientid_mac_ptr = clientid->data + 2+2;
  907. memcpy(clientid_mac_ptr, client_config.client_mac, 6);
  908. client_config.clientid = (void*)clientid;
  909. }
  910. #if !BB_MMU
  911. /* on NOMMU reexec (i.e., background) early */
  912. if (!(opt & OPT_f)) {
  913. bb_daemonize_or_rexec(0 /* flags */, argv);
  914. logmode = LOGMODE_NONE;
  915. }
  916. #endif
  917. if (opt & OPT_S) {
  918. openlog(applet_name, LOG_PID, LOG_DAEMON);
  919. logmode |= LOGMODE_SYSLOG;
  920. }
  921. /* Make sure fd 0,1,2 are open */
  922. bb_sanitize_stdio();
  923. /* Equivalent of doing a fflush after every \n */
  924. setlinebuf(stdout);
  925. /* Create pidfile */
  926. write_pidfile(client_config.pidfile);
  927. /* Goes to stdout (unless NOMMU) and possibly syslog */
  928. bb_error_msg("started, v"BB_VER);
  929. /* Set up the signal pipe */
  930. udhcp_sp_setup();
  931. /* We want random_xid to be random... */
  932. srand(monotonic_us());
  933. state = INIT_SELECTING;
  934. d6_run_script(NULL, "deconfig");
  935. change_listen_mode(LISTEN_RAW);
  936. packet_num = 0;
  937. timeout = 0;
  938. already_waited_sec = 0;
  939. /* Main event loop. select() waits on signal pipe and possibly
  940. * on sockfd.
  941. * "continue" statements in code below jump to the top of the loop.
  942. */
  943. for (;;) {
  944. struct timeval tv;
  945. struct d6_packet packet;
  946. uint8_t *packet_end;
  947. /* silence "uninitialized!" warning */
  948. unsigned timestamp_before_wait = timestamp_before_wait;
  949. //bb_error_msg("sockfd:%d, listen_mode:%d", sockfd, listen_mode);
  950. /* Was opening raw or udp socket here
  951. * if (listen_mode != LISTEN_NONE && sockfd < 0),
  952. * but on fast network renew responses return faster
  953. * than we open sockets. Thus this code is moved
  954. * to change_listen_mode(). Thus we open listen socket
  955. * BEFORE we send renew request (see "case BOUND:"). */
  956. max_fd = udhcp_sp_fd_set(&rfds, sockfd);
  957. tv.tv_sec = timeout - already_waited_sec;
  958. tv.tv_usec = 0;
  959. retval = 0;
  960. /* If we already timed out, fall through with retval = 0, else... */
  961. if ((int)tv.tv_sec > 0) {
  962. log1("waiting on select %u seconds", (int)tv.tv_sec);
  963. timestamp_before_wait = (unsigned)monotonic_sec();
  964. retval = select(max_fd + 1, &rfds, NULL, NULL, &tv);
  965. if (retval < 0) {
  966. /* EINTR? A signal was caught, don't panic */
  967. if (errno == EINTR) {
  968. already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
  969. continue;
  970. }
  971. /* Else: an error occured, panic! */
  972. bb_perror_msg_and_die("select");
  973. }
  974. }
  975. /* If timeout dropped to zero, time to become active:
  976. * resend discover/renew/whatever
  977. */
  978. if (retval == 0) {
  979. /* When running on a bridge, the ifindex may have changed
  980. * (e.g. if member interfaces were added/removed
  981. * or if the status of the bridge changed).
  982. * Refresh ifindex and client_mac:
  983. */
  984. if (udhcp_read_interface(client_config.interface,
  985. &client_config.ifindex,
  986. NULL,
  987. client_config.client_mac)
  988. ) {
  989. goto ret0; /* iface is gone? */
  990. }
  991. memcpy(clientid_mac_ptr, client_config.client_mac, 6);
  992. /* We will restart the wait in any case */
  993. already_waited_sec = 0;
  994. switch (state) {
  995. case INIT_SELECTING:
  996. if (!discover_retries || packet_num < discover_retries) {
  997. if (packet_num == 0)
  998. xid = random_xid();
  999. /* multicast */
  1000. send_d6_discover(xid, requested_ipv6);
  1001. timeout = discover_timeout;
  1002. packet_num++;
  1003. continue;
  1004. }
  1005. leasefail:
  1006. d6_run_script(NULL, "leasefail");
  1007. #if BB_MMU /* -b is not supported on NOMMU */
  1008. if (opt & OPT_b) { /* background if no lease */
  1009. bb_error_msg("no lease, forking to background");
  1010. client_background();
  1011. /* do not background again! */
  1012. opt = ((opt & ~OPT_b) | OPT_f);
  1013. } else
  1014. #endif
  1015. if (opt & OPT_n) { /* abort if no lease */
  1016. bb_error_msg("no lease, failing");
  1017. retval = 1;
  1018. goto ret;
  1019. }
  1020. /* wait before trying again */
  1021. timeout = tryagain_timeout;
  1022. packet_num = 0;
  1023. continue;
  1024. case REQUESTING:
  1025. if (!discover_retries || packet_num < discover_retries) {
  1026. /* send multicast select packet */
  1027. send_d6_select(xid);
  1028. timeout = discover_timeout;
  1029. packet_num++;
  1030. continue;
  1031. }
  1032. /* Timed out, go back to init state.
  1033. * "discover...select...discover..." loops
  1034. * were seen in the wild. Treat them similarly
  1035. * to "no response to discover" case */
  1036. change_listen_mode(LISTEN_RAW);
  1037. state = INIT_SELECTING;
  1038. goto leasefail;
  1039. case BOUND:
  1040. /* 1/2 lease passed, enter renewing state */
  1041. state = RENEWING;
  1042. client_config.first_secs = 0; /* make secs field count from 0 */
  1043. change_listen_mode(LISTEN_KERNEL);
  1044. log1("entering renew state");
  1045. /* fall right through */
  1046. case RENEW_REQUESTED: /* manual (SIGUSR1) renew */
  1047. case_RENEW_REQUESTED:
  1048. case RENEWING:
  1049. if (timeout > 60) {
  1050. /* send an unicast renew request */
  1051. /* Sometimes observed to fail (EADDRNOTAVAIL) to bind
  1052. * a new UDP socket for sending inside send_renew.
  1053. * I hazard to guess existing listening socket
  1054. * is somehow conflicting with it, but why is it
  1055. * not deterministic then?! Strange.
  1056. * Anyway, it does recover by eventually failing through
  1057. * into INIT_SELECTING state.
  1058. */
  1059. send_d6_renew(xid, &srv6_buf, requested_ipv6);
  1060. timeout >>= 1;
  1061. continue;
  1062. }
  1063. /* Timed out, enter rebinding state */
  1064. log1("entering rebinding state");
  1065. state = REBINDING;
  1066. /* fall right through */
  1067. case REBINDING:
  1068. /* Switch to bcast receive */
  1069. change_listen_mode(LISTEN_RAW);
  1070. /* Lease is *really* about to run out,
  1071. * try to find DHCP server using broadcast */
  1072. if (timeout > 0) {
  1073. /* send a broadcast renew request */
  1074. send_d6_renew(xid, /*server_ipv6:*/ NULL, requested_ipv6);
  1075. timeout >>= 1;
  1076. continue;
  1077. }
  1078. /* Timed out, enter init state */
  1079. bb_error_msg("lease lost, entering init state");
  1080. d6_run_script(NULL, "deconfig");
  1081. state = INIT_SELECTING;
  1082. client_config.first_secs = 0; /* make secs field count from 0 */
  1083. /*timeout = 0; - already is */
  1084. packet_num = 0;
  1085. continue;
  1086. /* case RELEASED: */
  1087. }
  1088. /* yah, I know, *you* say it would never happen */
  1089. timeout = INT_MAX;
  1090. continue; /* back to main loop */
  1091. } /* if select timed out */
  1092. /* select() didn't timeout, something happened */
  1093. /* Is it a signal? */
  1094. /* note: udhcp_sp_read checks FD_ISSET before reading */
  1095. switch (udhcp_sp_read(&rfds)) {
  1096. case SIGUSR1:
  1097. client_config.first_secs = 0; /* make secs field count from 0 */
  1098. already_waited_sec = 0;
  1099. perform_renew();
  1100. if (state == RENEW_REQUESTED) {
  1101. /* We might be either on the same network
  1102. * (in which case renew might work),
  1103. * or we might be on a completely different one
  1104. * (in which case renew won't ever succeed).
  1105. * For the second case, must make sure timeout
  1106. * is not too big, or else we can send
  1107. * futile renew requests for hours.
  1108. * (Ab)use -A TIMEOUT value (usually 20 sec)
  1109. * as a cap on the timeout.
  1110. */
  1111. if (timeout > tryagain_timeout)
  1112. timeout = tryagain_timeout;
  1113. goto case_RENEW_REQUESTED;
  1114. }
  1115. /* Start things over */
  1116. packet_num = 0;
  1117. /* Kill any timeouts, user wants this to hurry along */
  1118. timeout = 0;
  1119. continue;
  1120. case SIGUSR2:
  1121. perform_d6_release(&srv6_buf, requested_ipv6);
  1122. timeout = INT_MAX;
  1123. continue;
  1124. case SIGTERM:
  1125. bb_error_msg("received %s", "SIGTERM");
  1126. goto ret0;
  1127. }
  1128. /* Is it a packet? */
  1129. if (listen_mode == LISTEN_NONE || !FD_ISSET(sockfd, &rfds))
  1130. continue; /* no */
  1131. {
  1132. int len;
  1133. /* A packet is ready, read it */
  1134. if (listen_mode == LISTEN_KERNEL)
  1135. len = d6_recv_kernel_packet(&srv6_buf, &packet, sockfd);
  1136. else
  1137. len = d6_recv_raw_packet(&srv6_buf, &packet, sockfd);
  1138. if (len == -1) {
  1139. /* Error is severe, reopen socket */
  1140. bb_error_msg("read error: %s, reopening socket", strerror(errno));
  1141. sleep(discover_timeout); /* 3 seconds by default */
  1142. change_listen_mode(listen_mode); /* just close and reopen */
  1143. }
  1144. /* If this packet will turn out to be unrelated/bogus,
  1145. * we will go back and wait for next one.
  1146. * Be sure timeout is properly decreased. */
  1147. already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
  1148. if (len < 0)
  1149. continue;
  1150. packet_end = (uint8_t*)&packet + len;
  1151. }
  1152. if ((packet.d6_xid32 & htonl(0x00ffffff)) != xid) {
  1153. log1("xid %x (our is %x), ignoring packet",
  1154. (unsigned)(packet.d6_xid32 & htonl(0x00ffffff)), (unsigned)xid);
  1155. continue;
  1156. }
  1157. switch (state) {
  1158. case INIT_SELECTING:
  1159. if (packet.d6_msg_type == D6_MSG_ADVERTISE)
  1160. goto type_is_ok;
  1161. /* DHCPv6 has "Rapid Commit", when instead of Advertise,
  1162. * server sends Reply right away.
  1163. * Fall through to check for this case.
  1164. */
  1165. case REQUESTING:
  1166. case RENEWING:
  1167. case RENEW_REQUESTED:
  1168. case REBINDING:
  1169. if (packet.d6_msg_type == D6_MSG_REPLY) {
  1170. uint32_t lease_seconds;
  1171. struct d6_option *option, *iaaddr;
  1172. type_is_ok:
  1173. option = d6_find_option(packet.d6_options, packet_end, D6_OPT_STATUS_CODE);
  1174. if (option && option->data[4] != 0) {
  1175. /* return to init state */
  1176. bb_error_msg("received DHCP NAK (%u)", option->data[4]);
  1177. d6_run_script(&packet, "nak");
  1178. if (state != REQUESTING)
  1179. d6_run_script(NULL, "deconfig");
  1180. change_listen_mode(LISTEN_RAW);
  1181. sleep(3); /* avoid excessive network traffic */
  1182. state = INIT_SELECTING;
  1183. client_config.first_secs = 0; /* make secs field count from 0 */
  1184. requested_ipv6 = NULL;
  1185. timeout = 0;
  1186. packet_num = 0;
  1187. already_waited_sec = 0;
  1188. continue;
  1189. }
  1190. option = d6_copy_option(packet.d6_options, packet_end, D6_OPT_SERVERID);
  1191. if (!option) {
  1192. bb_error_msg("no server ID, ignoring packet");
  1193. continue;
  1194. /* still selecting - this server looks bad */
  1195. }
  1196. //Note: we do not bother comparing server IDs in Advertise and Reply msgs.
  1197. //server_id variable is used solely for creation of proper server_id option
  1198. //in outgoing packets. (why DHCPv6 even introduced it is a mystery).
  1199. free(client6_data.server_id);
  1200. client6_data.server_id = option;
  1201. if (packet.d6_msg_type == D6_MSG_ADVERTISE) {
  1202. /* enter requesting state */
  1203. state = REQUESTING;
  1204. timeout = 0;
  1205. packet_num = 0;
  1206. already_waited_sec = 0;
  1207. continue;
  1208. }
  1209. /* It's a D6_MSG_REPLY */
  1210. /*
  1211. * RFC 3315 18.1.8. Receipt of Reply Messages
  1212. *
  1213. * Upon the receipt of a valid Reply message in response to a Solicit
  1214. * (with a Rapid Commit option), Request, Confirm, Renew, Rebind or
  1215. * Information-request message, the client extracts the configuration
  1216. * information contained in the Reply. The client MAY choose to report
  1217. * any status code or message from the status code option in the Reply
  1218. * message.
  1219. *
  1220. * The client SHOULD perform duplicate address detection [17] on each of
  1221. * the addresses in any IAs it receives in the Reply message before
  1222. * using that address for traffic. If any of the addresses are found to
  1223. * be in use on the link, the client sends a Decline message to the
  1224. * server as described in section 18.1.7.
  1225. *
  1226. * If the Reply was received in response to a Solicit (with a Rapid
  1227. * Commit option), Request, Renew or Rebind message, the client updates
  1228. * the information it has recorded about IAs from the IA options
  1229. * contained in the Reply message:
  1230. *
  1231. * - Record T1 and T2 times.
  1232. *
  1233. * - Add any new addresses in the IA option to the IA as recorded by
  1234. * the client.
  1235. *
  1236. * - Update lifetimes for any addresses in the IA option that the
  1237. * client already has recorded in the IA.
  1238. *
  1239. * - Discard any addresses from the IA, as recorded by the client, that
  1240. * have a valid lifetime of 0 in the IA Address option.
  1241. *
  1242. * - Leave unchanged any information about addresses the client has
  1243. * recorded in the IA but that were not included in the IA from the
  1244. * server.
  1245. *
  1246. * Management of the specific configuration information is detailed in
  1247. * the definition of each option in section 22.
  1248. *
  1249. * If the client receives a Reply message with a Status Code containing
  1250. * UnspecFail, the server is indicating that it was unable to process
  1251. * the message due to an unspecified failure condition. If the client
  1252. * retransmits the original message to the same server to retry the
  1253. * desired operation, the client MUST limit the rate at which it
  1254. * retransmits the message and limit the duration of the time during
  1255. * which it retransmits the message.
  1256. *
  1257. * When the client receives a Reply message with a Status Code option
  1258. * with the value UseMulticast, the client records the receipt of the
  1259. * message and sends subsequent messages to the server through the
  1260. * interface on which the message was received using multicast. The
  1261. * client resends the original message using multicast.
  1262. *
  1263. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1264. * | OPTION_IA_NA | option-len |
  1265. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1266. * | IAID (4 octets) |
  1267. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1268. * | T1 |
  1269. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1270. * | T2 |
  1271. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1272. * | |
  1273. * . IA_NA-options .
  1274. * . .
  1275. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1276. *
  1277. *
  1278. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1279. * | OPTION_IAADDR | option-len |
  1280. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1281. * | |
  1282. * | IPv6 address |
  1283. * | |
  1284. * | |
  1285. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1286. * | preferred-lifetime |
  1287. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1288. * | valid-lifetime |
  1289. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1290. * . .
  1291. * . IAaddr-options .
  1292. * . .
  1293. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1294. */
  1295. free(client6_data.ia_na);
  1296. client6_data.ia_na = d6_copy_option(packet.d6_options, packet_end, D6_OPT_IA_NA);
  1297. if (!client6_data.ia_na) {
  1298. bb_error_msg("no %s option, ignoring packet", "IA_NA");
  1299. continue;
  1300. }
  1301. if (client6_data.ia_na->len < (4 + 4 + 4) + (2 + 2 + 16 + 4 + 4)) {
  1302. bb_error_msg("IA_NA option is too short:%d bytes", client6_data.ia_na->len);
  1303. continue;
  1304. }
  1305. iaaddr = d6_find_option(client6_data.ia_na->data + 4 + 4 + 4,
  1306. client6_data.ia_na->data + client6_data.ia_na->len,
  1307. D6_OPT_IAADDR
  1308. );
  1309. if (!iaaddr) {
  1310. bb_error_msg("no %s option, ignoring packet", "IAADDR");
  1311. continue;
  1312. }
  1313. if (iaaddr->len < (16 + 4 + 4)) {
  1314. bb_error_msg("IAADDR option is too short:%d bytes", iaaddr->len);
  1315. continue;
  1316. }
  1317. /* Note: the address is sufficiently aligned for cast:
  1318. * we _copied_ IA-NA, and copy is always well-aligned.
  1319. */
  1320. requested_ipv6 = (struct in6_addr*) iaaddr->data;
  1321. move_from_unaligned32(lease_seconds, iaaddr->data + 16 + 4);
  1322. lease_seconds = ntohl(lease_seconds);
  1323. /* paranoia: must not be too small and not prone to overflows */
  1324. if (lease_seconds < 0x10)
  1325. lease_seconds = 0x10;
  1326. /// TODO: check for 0 lease time?
  1327. if (lease_seconds >= 0x10000000)
  1328. lease_seconds = 0x0fffffff;
  1329. /* enter bound state */
  1330. timeout = lease_seconds / 2;
  1331. bb_error_msg("lease obtained, lease time %u",
  1332. /*inet_ntoa(temp_addr),*/ (unsigned)lease_seconds);
  1333. d6_run_script(&packet, state == REQUESTING ? "bound" : "renew");
  1334. state = BOUND;
  1335. change_listen_mode(LISTEN_NONE);
  1336. if (opt & OPT_q) { /* quit after lease */
  1337. goto ret0;
  1338. }
  1339. /* future renew failures should not exit (JM) */
  1340. opt &= ~OPT_n;
  1341. #if BB_MMU /* NOMMU case backgrounded earlier */
  1342. if (!(opt & OPT_f)) {
  1343. client_background();
  1344. /* do not background again! */
  1345. opt = ((opt & ~OPT_b) | OPT_f);
  1346. }
  1347. #endif
  1348. already_waited_sec = 0;
  1349. continue; /* back to main loop */
  1350. }
  1351. continue;
  1352. /* case BOUND: - ignore all packets */
  1353. /* case RELEASED: - ignore all packets */
  1354. }
  1355. /* back to main loop */
  1356. } /* for (;;) - main loop ends */
  1357. ret0:
  1358. if (opt & OPT_R) /* release on quit */
  1359. perform_d6_release(&srv6_buf, requested_ipv6);
  1360. retval = 0;
  1361. ret:
  1362. /*if (client_config.pidfile) - remove_pidfile has its own check */
  1363. remove_pidfile(client_config.pidfile);
  1364. return retval;
  1365. }