d6_dhcpc.c 50 KB

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