3
0

d6_dhcpc.c 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492
  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 memcpy(xmalloc(opt[3] + 4), 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_PORT,
  269. /*dst*/ (struct in6_addr*)FF02__1_2, SERVER_PORT, 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_info_msg("Sending 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_info_msg("Sending 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_info_msg("Sending renew...");
  485. if (server_ipv6)
  486. return d6_send_kernel_packet(
  487. &packet, (opt_ptr - (uint8_t*) &packet),
  488. our_cur_ipv6, CLIENT_PORT,
  489. server_ipv6, SERVER_PORT
  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_info_msg("Sending release...");
  505. return d6_send_kernel_packet(
  506. &packet, (opt_ptr - (uint8_t*) &packet),
  507. our_cur_ipv6, CLIENT_PORT,
  508. server_ipv6, SERVER_PORT
  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_PORT)
  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 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_PORT, 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, 0xffffffff),
  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_PORT == 68) {
  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_PORT, 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_info_msg("Performing a 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_info_msg("Unicasting a release");
  700. send_d6_release(server_ipv6, our_cur_ipv6); /* unicast */
  701. d6_run_script(NULL, "deconfig");
  702. }
  703. bb_info_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. /* Default options */
  829. IF_FEATURE_UDHCP_PORT(SERVER_PORT = 547;)
  830. IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 546;)
  831. client_config.interface = "eth0";
  832. client_config.script = CONFIG_UDHCPC_DEFAULT_SCRIPT;
  833. /* Parse command line */
  834. /* O,x: list; -T,-t,-A take numeric param */
  835. opt_complementary = "O::x::T+:t+:A+" IF_UDHCP_VERBOSE(":vv") ;
  836. IF_LONG_OPTS(applet_long_options = udhcpc6_longopts;)
  837. opt = getopt32(argv, "i:np:qRr:s:T:t:SA:O:ox:f"
  838. USE_FOR_MMU("b")
  839. ///IF_FEATURE_UDHCPC_ARPING("a")
  840. IF_FEATURE_UDHCP_PORT("P:")
  841. "v"
  842. , &client_config.interface, &client_config.pidfile, &str_r /* i,p */
  843. , &client_config.script /* s */
  844. , &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */
  845. , &list_O
  846. , &list_x
  847. IF_FEATURE_UDHCP_PORT(, &str_P)
  848. IF_UDHCP_VERBOSE(, &dhcp_verbose)
  849. );
  850. requested_ipv6 = NULL;
  851. if (opt & OPT_r) {
  852. if (inet_pton(AF_INET6, str_r, &ipv6_buf) <= 0)
  853. bb_error_msg_and_die("bad IPv6 address '%s'", str_r);
  854. requested_ipv6 = &ipv6_buf;
  855. }
  856. #if ENABLE_FEATURE_UDHCP_PORT
  857. if (opt & OPT_P) {
  858. CLIENT_PORT = xatou16(str_P);
  859. SERVER_PORT = CLIENT_PORT - 1;
  860. }
  861. #endif
  862. while (list_O) {
  863. char *optstr = llist_pop(&list_O);
  864. unsigned n = bb_strtou(optstr, NULL, 0);
  865. if (errno || n > 254) {
  866. n = udhcp_option_idx(optstr);
  867. n = dhcp_optflags[n].code;
  868. }
  869. client_config.opt_mask[n >> 3] |= 1 << (n & 7);
  870. }
  871. if (!(opt & OPT_o)) {
  872. /*
  873. unsigned i, n;
  874. for (i = 0; (n = dhcp_optflags[i].code) != 0; i++) {
  875. if (dhcp_optflags[i].flags & OPTION_REQ) {
  876. client_config.opt_mask[n >> 3] |= 1 << (n & 7);
  877. }
  878. }
  879. */
  880. }
  881. while (list_x) {
  882. char *optstr = llist_pop(&list_x);
  883. char *colon = strchr(optstr, ':');
  884. if (colon)
  885. *colon = ' ';
  886. /* now it looks similar to udhcpd's config file line:
  887. * "optname optval", using the common routine: */
  888. udhcp_str2optset(optstr, &client_config.options);
  889. }
  890. if (udhcp_read_interface(client_config.interface,
  891. &client_config.ifindex,
  892. NULL,
  893. client_config.client_mac)
  894. ) {
  895. return 1;
  896. }
  897. /* Create client ID based on mac, set clientid_mac_ptr */
  898. {
  899. struct d6_option *clientid;
  900. clientid = xzalloc(2+2+2+2+6);
  901. clientid->code = D6_OPT_CLIENTID;
  902. clientid->len = 2+2+6;
  903. clientid->data[1] = 3; /* DUID-LL */
  904. clientid->data[3] = 1; /* ethernet */
  905. clientid_mac_ptr = clientid->data + 2+2;
  906. memcpy(clientid_mac_ptr, client_config.client_mac, 6);
  907. client_config.clientid = (void*)clientid;
  908. }
  909. #if !BB_MMU
  910. /* on NOMMU reexec (i.e., background) early */
  911. if (!(opt & OPT_f)) {
  912. bb_daemonize_or_rexec(0 /* flags */, argv);
  913. logmode = LOGMODE_NONE;
  914. }
  915. #endif
  916. if (opt & OPT_S) {
  917. openlog(applet_name, LOG_PID, LOG_DAEMON);
  918. logmode |= LOGMODE_SYSLOG;
  919. }
  920. /* Make sure fd 0,1,2 are open */
  921. bb_sanitize_stdio();
  922. /* Equivalent of doing a fflush after every \n */
  923. setlinebuf(stdout);
  924. /* Create pidfile */
  925. write_pidfile(client_config.pidfile);
  926. /* Goes to stdout (unless NOMMU) and possibly syslog */
  927. bb_info_msg("%s (v"BB_VER") started", applet_name);
  928. /* Set up the signal pipe */
  929. udhcp_sp_setup();
  930. /* We want random_xid to be random... */
  931. srand(monotonic_us());
  932. state = INIT_SELECTING;
  933. d6_run_script(NULL, "deconfig");
  934. change_listen_mode(LISTEN_RAW);
  935. packet_num = 0;
  936. timeout = 0;
  937. already_waited_sec = 0;
  938. /* Main event loop. select() waits on signal pipe and possibly
  939. * on sockfd.
  940. * "continue" statements in code below jump to the top of the loop.
  941. */
  942. for (;;) {
  943. struct timeval tv;
  944. struct d6_packet packet;
  945. uint8_t *packet_end;
  946. /* silence "uninitialized!" warning */
  947. unsigned timestamp_before_wait = timestamp_before_wait;
  948. //bb_error_msg("sockfd:%d, listen_mode:%d", sockfd, listen_mode);
  949. /* Was opening raw or udp socket here
  950. * if (listen_mode != LISTEN_NONE && sockfd < 0),
  951. * but on fast network renew responses return faster
  952. * than we open sockets. Thus this code is moved
  953. * to change_listen_mode(). Thus we open listen socket
  954. * BEFORE we send renew request (see "case BOUND:"). */
  955. max_fd = udhcp_sp_fd_set(&rfds, sockfd);
  956. tv.tv_sec = timeout - already_waited_sec;
  957. tv.tv_usec = 0;
  958. retval = 0;
  959. /* If we already timed out, fall through with retval = 0, else... */
  960. if ((int)tv.tv_sec > 0) {
  961. log1("Waiting on select %u seconds", (int)tv.tv_sec);
  962. timestamp_before_wait = (unsigned)monotonic_sec();
  963. retval = select(max_fd + 1, &rfds, NULL, NULL, &tv);
  964. if (retval < 0) {
  965. /* EINTR? A signal was caught, don't panic */
  966. if (errno == EINTR) {
  967. already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
  968. continue;
  969. }
  970. /* Else: an error occured, panic! */
  971. bb_perror_msg_and_die("select");
  972. }
  973. }
  974. /* If timeout dropped to zero, time to become active:
  975. * resend discover/renew/whatever
  976. */
  977. if (retval == 0) {
  978. /* When running on a bridge, the ifindex may have changed
  979. * (e.g. if member interfaces were added/removed
  980. * or if the status of the bridge changed).
  981. * Refresh ifindex and client_mac:
  982. */
  983. if (udhcp_read_interface(client_config.interface,
  984. &client_config.ifindex,
  985. NULL,
  986. client_config.client_mac)
  987. ) {
  988. goto ret0; /* iface is gone? */
  989. }
  990. memcpy(clientid_mac_ptr, client_config.client_mac, 6);
  991. /* We will restart the wait in any case */
  992. already_waited_sec = 0;
  993. switch (state) {
  994. case INIT_SELECTING:
  995. if (!discover_retries || packet_num < discover_retries) {
  996. if (packet_num == 0)
  997. xid = random_xid();
  998. /* multicast */
  999. send_d6_discover(xid, requested_ipv6);
  1000. timeout = discover_timeout;
  1001. packet_num++;
  1002. continue;
  1003. }
  1004. leasefail:
  1005. d6_run_script(NULL, "leasefail");
  1006. #if BB_MMU /* -b is not supported on NOMMU */
  1007. if (opt & OPT_b) { /* background if no lease */
  1008. bb_info_msg("No lease, forking to background");
  1009. client_background();
  1010. /* do not background again! */
  1011. opt = ((opt & ~OPT_b) | OPT_f);
  1012. } else
  1013. #endif
  1014. if (opt & OPT_n) { /* abort if no lease */
  1015. bb_info_msg("No lease, failing");
  1016. retval = 1;
  1017. goto ret;
  1018. }
  1019. /* wait before trying again */
  1020. timeout = tryagain_timeout;
  1021. packet_num = 0;
  1022. continue;
  1023. case REQUESTING:
  1024. if (!discover_retries || packet_num < discover_retries) {
  1025. /* send multicast select packet */
  1026. send_d6_select(xid);
  1027. timeout = discover_timeout;
  1028. packet_num++;
  1029. continue;
  1030. }
  1031. /* Timed out, go back to init state.
  1032. * "discover...select...discover..." loops
  1033. * were seen in the wild. Treat them similarly
  1034. * to "no response to discover" case */
  1035. change_listen_mode(LISTEN_RAW);
  1036. state = INIT_SELECTING;
  1037. goto leasefail;
  1038. case BOUND:
  1039. /* 1/2 lease passed, enter renewing state */
  1040. state = RENEWING;
  1041. client_config.first_secs = 0; /* make secs field count from 0 */
  1042. change_listen_mode(LISTEN_KERNEL);
  1043. log1("Entering renew state");
  1044. /* fall right through */
  1045. case RENEW_REQUESTED: /* manual (SIGUSR1) renew */
  1046. case_RENEW_REQUESTED:
  1047. case RENEWING:
  1048. if (timeout > 60) {
  1049. /* send an unicast renew request */
  1050. /* Sometimes observed to fail (EADDRNOTAVAIL) to bind
  1051. * a new UDP socket for sending inside send_renew.
  1052. * I hazard to guess existing listening socket
  1053. * is somehow conflicting with it, but why is it
  1054. * not deterministic then?! Strange.
  1055. * Anyway, it does recover by eventually failing through
  1056. * into INIT_SELECTING state.
  1057. */
  1058. send_d6_renew(xid, &srv6_buf, requested_ipv6);
  1059. timeout >>= 1;
  1060. continue;
  1061. }
  1062. /* Timed out, enter rebinding state */
  1063. log1("Entering rebinding state");
  1064. state = REBINDING;
  1065. /* fall right through */
  1066. case REBINDING:
  1067. /* Switch to bcast receive */
  1068. change_listen_mode(LISTEN_RAW);
  1069. /* Lease is *really* about to run out,
  1070. * try to find DHCP server using broadcast */
  1071. if (timeout > 0) {
  1072. /* send a broadcast renew request */
  1073. send_d6_renew(xid, /*server_ipv6:*/ NULL, requested_ipv6);
  1074. timeout >>= 1;
  1075. continue;
  1076. }
  1077. /* Timed out, enter init state */
  1078. bb_info_msg("Lease lost, entering init state");
  1079. d6_run_script(NULL, "deconfig");
  1080. state = INIT_SELECTING;
  1081. client_config.first_secs = 0; /* make secs field count from 0 */
  1082. /*timeout = 0; - already is */
  1083. packet_num = 0;
  1084. continue;
  1085. /* case RELEASED: */
  1086. }
  1087. /* yah, I know, *you* say it would never happen */
  1088. timeout = INT_MAX;
  1089. continue; /* back to main loop */
  1090. } /* if select timed out */
  1091. /* select() didn't timeout, something happened */
  1092. /* Is it a signal? */
  1093. /* note: udhcp_sp_read checks FD_ISSET before reading */
  1094. switch (udhcp_sp_read(&rfds)) {
  1095. case SIGUSR1:
  1096. client_config.first_secs = 0; /* make secs field count from 0 */
  1097. already_waited_sec = 0;
  1098. perform_renew();
  1099. if (state == RENEW_REQUESTED) {
  1100. /* We might be either on the same network
  1101. * (in which case renew might work),
  1102. * or we might be on a completely different one
  1103. * (in which case renew won't ever succeed).
  1104. * For the second case, must make sure timeout
  1105. * is not too big, or else we can send
  1106. * futile renew requests for hours.
  1107. * (Ab)use -A TIMEOUT value (usually 20 sec)
  1108. * as a cap on the timeout.
  1109. */
  1110. if (timeout > tryagain_timeout)
  1111. timeout = tryagain_timeout;
  1112. goto case_RENEW_REQUESTED;
  1113. }
  1114. /* Start things over */
  1115. packet_num = 0;
  1116. /* Kill any timeouts, user wants this to hurry along */
  1117. timeout = 0;
  1118. continue;
  1119. case SIGUSR2:
  1120. perform_d6_release(&srv6_buf, requested_ipv6);
  1121. timeout = INT_MAX;
  1122. continue;
  1123. case SIGTERM:
  1124. bb_info_msg("Received SIGTERM");
  1125. goto ret0;
  1126. }
  1127. /* Is it a packet? */
  1128. if (listen_mode == LISTEN_NONE || !FD_ISSET(sockfd, &rfds))
  1129. continue; /* no */
  1130. {
  1131. int len;
  1132. /* A packet is ready, read it */
  1133. if (listen_mode == LISTEN_KERNEL)
  1134. len = d6_recv_kernel_packet(&srv6_buf, &packet, sockfd);
  1135. else
  1136. len = d6_recv_raw_packet(&srv6_buf, &packet, sockfd);
  1137. if (len == -1) {
  1138. /* Error is severe, reopen socket */
  1139. bb_info_msg("Read error: %s, reopening socket", strerror(errno));
  1140. sleep(discover_timeout); /* 3 seconds by default */
  1141. change_listen_mode(listen_mode); /* just close and reopen */
  1142. }
  1143. /* If this packet will turn out to be unrelated/bogus,
  1144. * we will go back and wait for next one.
  1145. * Be sure timeout is properly decreased. */
  1146. already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
  1147. if (len < 0)
  1148. continue;
  1149. packet_end = (uint8_t*)&packet + len;
  1150. }
  1151. if ((packet.d6_xid32 & htonl(0x00ffffff)) != xid) {
  1152. log1("xid %x (our is %x), ignoring packet",
  1153. (unsigned)(packet.d6_xid32 & htonl(0x00ffffff)), (unsigned)xid);
  1154. continue;
  1155. }
  1156. switch (state) {
  1157. case INIT_SELECTING:
  1158. if (packet.d6_msg_type == D6_MSG_ADVERTISE)
  1159. goto type_is_ok;
  1160. /* DHCPv6 has "Rapid Commit", when instead of Advertise,
  1161. * server sends Reply right away.
  1162. * Fall through to check for this case.
  1163. */
  1164. case REQUESTING:
  1165. case RENEWING:
  1166. case RENEW_REQUESTED:
  1167. case REBINDING:
  1168. if (packet.d6_msg_type == D6_MSG_REPLY) {
  1169. uint32_t lease_seconds;
  1170. struct d6_option *option, *iaaddr;
  1171. type_is_ok:
  1172. option = d6_find_option(packet.d6_options, packet_end, D6_OPT_STATUS_CODE);
  1173. if (option && option->data[4] != 0) {
  1174. /* return to init state */
  1175. bb_info_msg("Received DHCP NAK (%u)", option->data[4]);
  1176. d6_run_script(&packet, "nak");
  1177. if (state != REQUESTING)
  1178. d6_run_script(NULL, "deconfig");
  1179. change_listen_mode(LISTEN_RAW);
  1180. sleep(3); /* avoid excessive network traffic */
  1181. state = INIT_SELECTING;
  1182. client_config.first_secs = 0; /* make secs field count from 0 */
  1183. requested_ipv6 = NULL;
  1184. timeout = 0;
  1185. packet_num = 0;
  1186. already_waited_sec = 0;
  1187. continue;
  1188. }
  1189. option = d6_copy_option(packet.d6_options, packet_end, D6_OPT_SERVERID);
  1190. if (!option) {
  1191. bb_error_msg("no server ID, ignoring packet");
  1192. continue;
  1193. /* still selecting - this server looks bad */
  1194. }
  1195. //Note: we do not bother comparing server IDs in Advertise and Reply msgs.
  1196. //server_id variable is used solely for creation of proper server_id option
  1197. //in outgoing packets. (why DHCPv6 even introduced it is a mystery).
  1198. free(client6_data.server_id);
  1199. client6_data.server_id = option;
  1200. if (packet.d6_msg_type == D6_MSG_ADVERTISE) {
  1201. /* enter requesting state */
  1202. state = REQUESTING;
  1203. timeout = 0;
  1204. packet_num = 0;
  1205. already_waited_sec = 0;
  1206. continue;
  1207. }
  1208. /* It's a D6_MSG_REPLY */
  1209. /*
  1210. * RFC 3315 18.1.8. Receipt of Reply Messages
  1211. *
  1212. * Upon the receipt of a valid Reply message in response to a Solicit
  1213. * (with a Rapid Commit option), Request, Confirm, Renew, Rebind or
  1214. * Information-request message, the client extracts the configuration
  1215. * information contained in the Reply. The client MAY choose to report
  1216. * any status code or message from the status code option in the Reply
  1217. * message.
  1218. *
  1219. * The client SHOULD perform duplicate address detection [17] on each of
  1220. * the addresses in any IAs it receives in the Reply message before
  1221. * using that address for traffic. If any of the addresses are found to
  1222. * be in use on the link, the client sends a Decline message to the
  1223. * server as described in section 18.1.7.
  1224. *
  1225. * If the Reply was received in response to a Solicit (with a Rapid
  1226. * Commit option), Request, Renew or Rebind message, the client updates
  1227. * the information it has recorded about IAs from the IA options
  1228. * contained in the Reply message:
  1229. *
  1230. * - Record T1 and T2 times.
  1231. *
  1232. * - Add any new addresses in the IA option to the IA as recorded by
  1233. * the client.
  1234. *
  1235. * - Update lifetimes for any addresses in the IA option that the
  1236. * client already has recorded in the IA.
  1237. *
  1238. * - Discard any addresses from the IA, as recorded by the client, that
  1239. * have a valid lifetime of 0 in the IA Address option.
  1240. *
  1241. * - Leave unchanged any information about addresses the client has
  1242. * recorded in the IA but that were not included in the IA from the
  1243. * server.
  1244. *
  1245. * Management of the specific configuration information is detailed in
  1246. * the definition of each option in section 22.
  1247. *
  1248. * If the client receives a Reply message with a Status Code containing
  1249. * UnspecFail, the server is indicating that it was unable to process
  1250. * the message due to an unspecified failure condition. If the client
  1251. * retransmits the original message to the same server to retry the
  1252. * desired operation, the client MUST limit the rate at which it
  1253. * retransmits the message and limit the duration of the time during
  1254. * which it retransmits the message.
  1255. *
  1256. * When the client receives a Reply message with a Status Code option
  1257. * with the value UseMulticast, the client records the receipt of the
  1258. * message and sends subsequent messages to the server through the
  1259. * interface on which the message was received using multicast. The
  1260. * client resends the original message using multicast.
  1261. *
  1262. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1263. * | OPTION_IA_NA | option-len |
  1264. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1265. * | IAID (4 octets) |
  1266. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1267. * | T1 |
  1268. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1269. * | T2 |
  1270. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1271. * | |
  1272. * . IA_NA-options .
  1273. * . .
  1274. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1275. *
  1276. *
  1277. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1278. * | OPTION_IAADDR | option-len |
  1279. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1280. * | |
  1281. * | IPv6 address |
  1282. * | |
  1283. * | |
  1284. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1285. * | preferred-lifetime |
  1286. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1287. * | valid-lifetime |
  1288. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1289. * . .
  1290. * . IAaddr-options .
  1291. * . .
  1292. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  1293. */
  1294. free(client6_data.ia_na);
  1295. client6_data.ia_na = d6_copy_option(packet.d6_options, packet_end, D6_OPT_IA_NA);
  1296. if (!client6_data.ia_na) {
  1297. bb_error_msg("no %s option, ignoring packet", "IA_NA");
  1298. continue;
  1299. }
  1300. if (client6_data.ia_na->len < (4 + 4 + 4) + (2 + 2 + 16 + 4 + 4)) {
  1301. bb_error_msg("IA_NA option is too short:%d bytes", client6_data.ia_na->len);
  1302. continue;
  1303. }
  1304. iaaddr = d6_find_option(client6_data.ia_na->data + 4 + 4 + 4,
  1305. client6_data.ia_na->data + client6_data.ia_na->len,
  1306. D6_OPT_IAADDR
  1307. );
  1308. if (!iaaddr) {
  1309. bb_error_msg("no %s option, ignoring packet", "IAADDR");
  1310. continue;
  1311. }
  1312. if (iaaddr->len < (16 + 4 + 4)) {
  1313. bb_error_msg("IAADDR option is too short:%d bytes", iaaddr->len);
  1314. continue;
  1315. }
  1316. /* Note: the address is sufficiently aligned for cast:
  1317. * we _copied_ IA-NA, and copy is always well-aligned.
  1318. */
  1319. requested_ipv6 = (struct in6_addr*) iaaddr->data;
  1320. move_from_unaligned32(lease_seconds, iaaddr->data + 16 + 4);
  1321. lease_seconds = ntohl(lease_seconds);
  1322. /* paranoia: must not be too small and not prone to overflows */
  1323. if (lease_seconds < 0x10)
  1324. lease_seconds = 0x10;
  1325. /// TODO: check for 0 lease time?
  1326. if (lease_seconds >= 0x10000000)
  1327. lease_seconds = 0x0fffffff;
  1328. /* enter bound state */
  1329. timeout = lease_seconds / 2;
  1330. bb_info_msg("Lease obtained, lease time %u",
  1331. /*inet_ntoa(temp_addr),*/ (unsigned)lease_seconds);
  1332. d6_run_script(&packet, state == REQUESTING ? "bound" : "renew");
  1333. state = BOUND;
  1334. change_listen_mode(LISTEN_NONE);
  1335. if (opt & OPT_q) { /* quit after lease */
  1336. goto ret0;
  1337. }
  1338. /* future renew failures should not exit (JM) */
  1339. opt &= ~OPT_n;
  1340. #if BB_MMU /* NOMMU case backgrounded earlier */
  1341. if (!(opt & OPT_f)) {
  1342. client_background();
  1343. /* do not background again! */
  1344. opt = ((opt & ~OPT_b) | OPT_f);
  1345. }
  1346. #endif
  1347. already_waited_sec = 0;
  1348. continue; /* back to main loop */
  1349. }
  1350. continue;
  1351. /* case BOUND: - ignore all packets */
  1352. /* case RELEASED: - ignore all packets */
  1353. }
  1354. /* back to main loop */
  1355. } /* for (;;) - main loop ends */
  1356. ret0:
  1357. if (opt & OPT_R) /* release on quit */
  1358. perform_d6_release(&srv6_buf, requested_ipv6);
  1359. retval = 0;
  1360. ret:
  1361. /*if (client_config.pidfile) - remove_pidfile has its own check */
  1362. remove_pidfile(client_config.pidfile);
  1363. return retval;
  1364. }