dhcpc.c 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * udhcp client
  4. * Russ Dill <Russ.Dill@asu.edu> July 2001
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  19. */
  20. //applet:IF_UDHCPC(APPLET(udhcpc, BB_DIR_SBIN, BB_SUID_DROP))
  21. //kbuild:lib-$(CONFIG_UDHCPC) += common.o packet.o signalpipe.o socket.o
  22. //kbuild:lib-$(CONFIG_UDHCPC) += dhcpc.o
  23. //kbuild:lib-$(CONFIG_FEATURE_UDHCPC_ARPING) += arpping.o
  24. //kbuild:lib-$(CONFIG_FEATURE_UDHCP_RFC3397) += domain_codec.o
  25. #include <syslog.h>
  26. /* Override ENABLE_FEATURE_PIDFILE - ifupdown needs our pidfile to always exist */
  27. #define WANT_PIDFILE 1
  28. #include "common.h"
  29. #include "dhcpd.h"
  30. #include "dhcpc.h"
  31. #include <netinet/if_ether.h>
  32. #include <linux/filter.h>
  33. #include <linux/if_packet.h>
  34. #ifndef PACKET_AUXDATA
  35. # define PACKET_AUXDATA 8
  36. struct tpacket_auxdata {
  37. uint32_t tp_status;
  38. uint32_t tp_len;
  39. uint32_t tp_snaplen;
  40. uint16_t tp_mac;
  41. uint16_t tp_net;
  42. uint16_t tp_vlan_tci;
  43. uint16_t tp_padding;
  44. };
  45. #endif
  46. /* "struct client_data_t client_data" is in bb_common_bufsiz1 */
  47. #if ENABLE_LONG_OPTS
  48. static const char udhcpc_longopts[] ALIGN1 =
  49. "clientid-none\0" No_argument "C"
  50. "vendorclass\0" Required_argument "V"
  51. "hostname\0" Required_argument "H"
  52. "fqdn\0" Required_argument "F"
  53. "interface\0" Required_argument "i"
  54. "now\0" No_argument "n"
  55. "pidfile\0" Required_argument "p"
  56. "quit\0" No_argument "q"
  57. "release\0" No_argument "R"
  58. "request\0" Required_argument "r"
  59. "script\0" Required_argument "s"
  60. "timeout\0" Required_argument "T"
  61. "retries\0" Required_argument "t"
  62. "tryagain\0" Required_argument "A"
  63. "syslog\0" No_argument "S"
  64. "request-option\0" Required_argument "O"
  65. "no-default-options\0" No_argument "o"
  66. "foreground\0" No_argument "f"
  67. USE_FOR_MMU(
  68. "background\0" No_argument "b"
  69. )
  70. "broadcast\0" No_argument "B"
  71. IF_FEATURE_UDHCPC_ARPING("arping\0" Optional_argument "a")
  72. IF_FEATURE_UDHCP_PORT("client-port\0" Required_argument "P")
  73. ;
  74. #endif
  75. /* Must match getopt32 option string order */
  76. enum {
  77. OPT_C = 1 << 0,
  78. OPT_V = 1 << 1,
  79. OPT_H = 1 << 2,
  80. OPT_h = 1 << 3,
  81. OPT_F = 1 << 4,
  82. OPT_i = 1 << 5,
  83. OPT_n = 1 << 6,
  84. OPT_p = 1 << 7,
  85. OPT_q = 1 << 8,
  86. OPT_R = 1 << 9,
  87. OPT_r = 1 << 10,
  88. OPT_s = 1 << 11,
  89. OPT_T = 1 << 12,
  90. OPT_t = 1 << 13,
  91. OPT_S = 1 << 14,
  92. OPT_A = 1 << 15,
  93. OPT_O = 1 << 16,
  94. OPT_o = 1 << 17,
  95. OPT_x = 1 << 18,
  96. OPT_f = 1 << 19,
  97. OPT_B = 1 << 20,
  98. /* The rest has variable bit positions, need to be clever */
  99. OPTBIT_B = 20,
  100. USE_FOR_MMU( OPTBIT_b,)
  101. IF_FEATURE_UDHCPC_ARPING(OPTBIT_a,)
  102. IF_FEATURE_UDHCP_PORT( OPTBIT_P,)
  103. USE_FOR_MMU( OPT_b = 1 << OPTBIT_b,)
  104. IF_FEATURE_UDHCPC_ARPING(OPT_a = 1 << OPTBIT_a,)
  105. IF_FEATURE_UDHCP_PORT( OPT_P = 1 << OPTBIT_P,)
  106. };
  107. /*** Script execution code ***/
  108. struct dhcp_optitem {
  109. unsigned len;
  110. uint8_t code;
  111. uint8_t malloced;
  112. uint8_t *data;
  113. char *env;
  114. };
  115. /* get a rough idea of how long an option will be (rounding up...) */
  116. static const uint8_t len_of_option_as_string[] ALIGN1 = {
  117. [OPTION_IP ] = sizeof("255.255.255.255 "),
  118. [OPTION_IP_PAIR ] = sizeof("255.255.255.255 ") * 2,
  119. [OPTION_STATIC_ROUTES ] = sizeof("255.255.255.255/32 255.255.255.255 "),
  120. [OPTION_6RD ] = sizeof("132 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 "),
  121. [OPTION_STRING ] = 1,
  122. [OPTION_STRING_HOST ] = 1,
  123. #if ENABLE_FEATURE_UDHCP_RFC3397
  124. [OPTION_DNS_STRING ] = 1, /* unused */
  125. /* Hmmm, this severely overestimates size if SIP_SERVERS option
  126. * is in domain name form: N-byte option in binary form
  127. * mallocs ~16*N bytes. But it is freed almost at once.
  128. */
  129. [OPTION_SIP_SERVERS ] = sizeof("255.255.255.255 "),
  130. #endif
  131. // [OPTION_BOOLEAN ] = sizeof("yes "),
  132. [OPTION_U8 ] = sizeof("255 "),
  133. [OPTION_U16 ] = sizeof("65535 "),
  134. // [OPTION_S16 ] = sizeof("-32768 "),
  135. [OPTION_U32 ] = sizeof("4294967295 "),
  136. [OPTION_S32 ] = sizeof("-2147483684 "),
  137. };
  138. /* note: ip is a pointer to an IP in network order, possibly misaliged */
  139. static int sprint_nip(char *dest, const char *pre, const uint8_t *ip)
  140. {
  141. return sprintf(dest, "%s%u.%u.%u.%u", pre, ip[0], ip[1], ip[2], ip[3]);
  142. }
  143. /* really simple implementation, just count the bits */
  144. static int mton(uint32_t mask)
  145. {
  146. int i = 0;
  147. mask = ntohl(mask); /* 111110000-like bit pattern */
  148. while (mask) {
  149. i++;
  150. mask <<= 1;
  151. }
  152. return i;
  153. }
  154. #if ENABLE_FEATURE_UDHCPC_SANITIZEOPT
  155. /* Check if a given name represents a valid DNS name */
  156. /* See RFC1035, 2.3.1 */
  157. /* We don't need to be particularly anal. For example, allowing _, hyphen
  158. * at the end, or leading and trailing dots would be ok, since it
  159. * can't be used for attacks. (Leading hyphen can be, if someone uses cmd "$hostname"
  160. * in the script: then hostname may be treated as an option)
  161. */
  162. static int good_hostname(const char *name)
  163. {
  164. if (*name == '-') /* Can't start with '-' */
  165. return 0;
  166. while (*name) {
  167. unsigned char ch = *name++;
  168. if (!isalnum(ch))
  169. /* DNS allows only '-', but we are more permissive */
  170. if (ch != '-' && ch != '_' && ch != '.')
  171. return 0;
  172. // TODO: do we want to validate lengths against NS_MAXLABEL and NS_MAXDNAME?
  173. }
  174. return 1;
  175. }
  176. #else
  177. # define good_hostname(name) 1
  178. #endif
  179. /* Create "opt_name=opt_value" string */
  180. static NOINLINE char *xmalloc_optname_optval(const struct dhcp_optitem *opt_item, const struct dhcp_optflag *optflag, const char *opt_name)
  181. {
  182. unsigned upper_length;
  183. int len, type, optlen;
  184. char *dest, *ret;
  185. uint8_t *option;
  186. option = opt_item->data;
  187. len = opt_item->len;
  188. type = optflag->flags & OPTION_TYPE_MASK;
  189. optlen = dhcp_option_lengths[type];
  190. upper_length = len_of_option_as_string[type]
  191. * ((unsigned)(len + optlen) / (unsigned)optlen);
  192. dest = ret = xmalloc(upper_length + strlen(opt_name) + 2);
  193. dest += sprintf(ret, "%s=", opt_name);
  194. while (len >= optlen) {
  195. switch (type) {
  196. case OPTION_IP:
  197. case OPTION_IP_PAIR:
  198. dest += sprint_nip(dest, "", option);
  199. if (type == OPTION_IP_PAIR)
  200. dest += sprint_nip(dest, "/", option + 4);
  201. break;
  202. // case OPTION_BOOLEAN:
  203. // dest += sprintf(dest, *option ? "yes" : "no");
  204. // break;
  205. case OPTION_U8:
  206. dest += sprintf(dest, "%u", *option);
  207. break;
  208. // case OPTION_S16:
  209. case OPTION_U16: {
  210. uint16_t val_u16;
  211. move_from_unaligned16(val_u16, option);
  212. dest += sprintf(dest, "%u", ntohs(val_u16));
  213. break;
  214. }
  215. case OPTION_S32:
  216. case OPTION_U32: {
  217. uint32_t val_u32;
  218. move_from_unaligned32(val_u32, option);
  219. dest += sprintf(dest, type == OPTION_U32 ? "%lu" : "%ld", (unsigned long) ntohl(val_u32));
  220. break;
  221. }
  222. /* Note: options which use 'return' instead of 'break'
  223. * (for example, OPTION_STRING) skip the code which handles
  224. * the case of list of options.
  225. */
  226. case OPTION_STRING:
  227. case OPTION_STRING_HOST:
  228. memcpy(dest, option, len);
  229. dest[len] = '\0';
  230. //TODO: it appears option 15 DHCP_DOMAIN_NAME is often abused
  231. //by DHCP admins to contain a space-separated list of domains,
  232. //not one domain name (presumably, to work as list of search domains,
  233. //instead of using proper option 119 DHCP_DOMAIN_SEARCH).
  234. //Currently, good_hostname() balks on strings containing spaces.
  235. //Do we need to allow it? Only for DHCP_DOMAIN_NAME option?
  236. if (type == OPTION_STRING_HOST && !good_hostname(dest))
  237. safe_strncpy(dest, "bad", len);
  238. return ret;
  239. case OPTION_STATIC_ROUTES: {
  240. /* Option binary format:
  241. * mask [one byte, 0..32]
  242. * ip [big endian, 0..4 bytes depending on mask]
  243. * router [big endian, 4 bytes]
  244. * may be repeated
  245. *
  246. * We convert it to a string "IP/MASK ROUTER IP2/MASK2 ROUTER2"
  247. */
  248. const char *pfx = "";
  249. while (len >= 1 + 4) { /* mask + 0-byte ip + router */
  250. uint32_t nip;
  251. uint8_t *p;
  252. unsigned mask;
  253. int bytes;
  254. mask = *option++;
  255. if (mask > 32)
  256. break;
  257. len--;
  258. nip = 0;
  259. p = (void*) &nip;
  260. bytes = (mask + 7) / 8; /* 0 -> 0, 1..8 -> 1, 9..16 -> 2 etc */
  261. while (--bytes >= 0) {
  262. *p++ = *option++;
  263. len--;
  264. }
  265. if (len < 4)
  266. break;
  267. /* print ip/mask */
  268. dest += sprint_nip(dest, pfx, (void*) &nip);
  269. pfx = " ";
  270. dest += sprintf(dest, "/%u ", mask);
  271. /* print router */
  272. dest += sprint_nip(dest, "", option);
  273. option += 4;
  274. len -= 4;
  275. }
  276. return ret;
  277. }
  278. case OPTION_6RD:
  279. /* Option binary format (see RFC 5969):
  280. * 0 1 2 3
  281. * 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
  282. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  283. * | OPTION_6RD | option-length | IPv4MaskLen | 6rdPrefixLen |
  284. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  285. * | 6rdPrefix |
  286. * ... (16 octets) ...
  287. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  288. * ... 6rdBRIPv4Address(es) ...
  289. * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  290. * We convert it to a string
  291. * "IPv4MaskLen 6rdPrefixLen 6rdPrefix 6rdBRIPv4Address..."
  292. *
  293. * Sanity check: ensure that our length is at least 22 bytes, that
  294. * IPv4MaskLen <= 32,
  295. * 6rdPrefixLen <= 128,
  296. * 6rdPrefixLen + (32 - IPv4MaskLen) <= 128
  297. * (2nd condition needs no check - it follows from 1st and 3rd).
  298. * Else, return envvar with empty value ("optname=")
  299. */
  300. if (len >= (1 + 1 + 16 + 4)
  301. && option[0] <= 32
  302. && (option[1] + 32 - option[0]) <= 128
  303. ) {
  304. /* IPv4MaskLen */
  305. dest += sprintf(dest, "%u ", *option++);
  306. /* 6rdPrefixLen */
  307. dest += sprintf(dest, "%u ", *option++);
  308. /* 6rdPrefix */
  309. dest += sprint_nip6(dest, /* "", */ option);
  310. option += 16;
  311. len -= 1 + 1 + 16;
  312. *dest++ = ' ';
  313. /* 6rdBRIPv4Address(es), use common IPv4 logic to process them */
  314. type = OPTION_IP;
  315. optlen = 4;
  316. continue;
  317. }
  318. return ret;
  319. #if ENABLE_FEATURE_UDHCP_RFC3397
  320. case OPTION_DNS_STRING:
  321. /* unpack option into dest; use ret for prefix (i.e., "optname=") */
  322. dest = dname_dec(option, len, ret);
  323. if (dest) {
  324. free(ret);
  325. return dest;
  326. }
  327. /* error. return "optname=" string */
  328. return ret;
  329. case OPTION_SIP_SERVERS:
  330. /* Option binary format:
  331. * type: byte
  332. * type=0: domain names, dns-compressed
  333. * type=1: IP addrs
  334. */
  335. option++;
  336. len--;
  337. if (option[-1] == 1) {
  338. /* use common IPv4 logic to process IP addrs */
  339. type = OPTION_IP;
  340. optlen = 4;
  341. continue;
  342. }
  343. if (option[-1] == 0) {
  344. dest = dname_dec(option, len, ret);
  345. if (dest) {
  346. free(ret);
  347. return dest;
  348. }
  349. }
  350. return ret;
  351. #endif
  352. } /* switch */
  353. /* If we are here, try to format any remaining data
  354. * in the option as another, similarly-formatted option
  355. */
  356. option += optlen;
  357. len -= optlen;
  358. // TODO: it can be a list only if (optflag->flags & OPTION_LIST).
  359. // Should we bail out/warn if we see multi-ip option which is
  360. // not allowed to be such (for example, DHCP_BROADCAST)? -
  361. if (len < optlen /* || !(optflag->flags & OPTION_LIST) */)
  362. break;
  363. *dest++ = ' ';
  364. *dest = '\0';
  365. } /* while */
  366. return ret;
  367. }
  368. static void optitem_unset_env_and_free(void *item)
  369. {
  370. struct dhcp_optitem *opt_item = item;
  371. bb_unsetenv_and_free(opt_item->env);
  372. if (opt_item->malloced)
  373. free(opt_item->data);
  374. free(opt_item);
  375. }
  376. /* Used by static options (interface, siaddr, etc) */
  377. static void putenvp(char *new_opt)
  378. {
  379. struct dhcp_optitem *opt_item;
  380. opt_item = xzalloc(sizeof(*opt_item));
  381. /* opt_item->code = 0, so it won't appear in concat_option's lookup */
  382. /* opt_item->malloced = 0 */
  383. /* opt_item->data = NULL */
  384. opt_item->env = new_opt;
  385. llist_add_to(&client_data.envp, opt_item);
  386. log2(" %s", new_opt);
  387. putenv(new_opt);
  388. }
  389. /* Support RFC3396 Long Encoded Options */
  390. static struct dhcp_optitem *concat_option(uint8_t *data, uint8_t len, uint8_t code)
  391. {
  392. llist_t *item;
  393. struct dhcp_optitem *opt_item;
  394. /* Check if an option with the code already exists.
  395. * A possible optimization is to create a bitmap of all existing options in the packet,
  396. * and iterate over the option list only if they exist.
  397. * This will result in bigger code, and because dhcp packets don't have too many options it
  398. * shouldn't have a big impact on performance.
  399. */
  400. for (item = client_data.envp; item != NULL; item = item->link) {
  401. opt_item = (struct dhcp_optitem *)item->data;
  402. if (opt_item->code == code) {
  403. /* This option was seen already, concatenate */
  404. uint8_t *new_data;
  405. new_data = xmalloc(len + opt_item->len);
  406. memcpy(
  407. mempcpy(new_data, opt_item->data, opt_item->len),
  408. data, len
  409. );
  410. opt_item->len += len;
  411. if (opt_item->malloced)
  412. free(opt_item->data);
  413. opt_item->malloced = 1;
  414. opt_item->data = new_data;
  415. return opt_item;
  416. }
  417. }
  418. /* This is a new option, add a new dhcp_optitem to the list */
  419. opt_item = xzalloc(sizeof(*opt_item));
  420. opt_item->code = code;
  421. /* opt_item->malloced = 0 */
  422. opt_item->data = data;
  423. opt_item->len = len;
  424. llist_add_to(&client_data.envp, opt_item);
  425. return opt_item;
  426. }
  427. static const char* get_optname(uint8_t code, const struct dhcp_optflag **dh)
  428. {
  429. /* Find the option:
  430. * dhcp_optflags is sorted so we stop searching when dh->code >= code, which is faster
  431. * than iterating over the entire array.
  432. * Options which don't have a match in dhcp_option_strings[], e.g DHCP_REQUESTED_IP,
  433. * are located after the sorted array, so these entries will never be reached
  434. * and they'll count as unknown options.
  435. */
  436. for (*dh = dhcp_optflags; (*dh)->code && (*dh)->code < code; (*dh)++)
  437. continue;
  438. if ((*dh)->code == code)
  439. return nth_string(dhcp_option_strings, (*dh - dhcp_optflags));
  440. return NULL;
  441. }
  442. /* put all the parameters into the environment */
  443. static void fill_envp(struct dhcp_packet *packet)
  444. {
  445. uint8_t *optptr;
  446. struct dhcp_scan_state scan_state;
  447. char *new_opt;
  448. putenvp(xasprintf("interface=%s", client_data.interface));
  449. if (!packet)
  450. return;
  451. init_scan_state(packet, &scan_state);
  452. /* Iterate over the packet options.
  453. * Handle each option based on whether it's an unknown / known option.
  454. * Long options are supported in compliance with RFC 3396.
  455. */
  456. while ((optptr = udhcp_scan_options(packet, &scan_state)) != NULL) {
  457. const struct dhcp_optflag *dh;
  458. const char *opt_name;
  459. struct dhcp_optitem *opt_item;
  460. uint8_t code = optptr[OPT_CODE];
  461. uint8_t len = optptr[OPT_LEN];
  462. uint8_t *data = optptr + OPT_DATA;
  463. opt_item = concat_option(data, len, code);
  464. opt_name = get_optname(code, &dh);
  465. if (opt_name) {
  466. new_opt = xmalloc_optname_optval(opt_item, dh, opt_name);
  467. if (opt_item->code == DHCP_SUBNET && opt_item->len == 4) {
  468. /* Generate extra envvar for DHCP_SUBNET, $mask */
  469. uint32_t subnet;
  470. move_from_unaligned32(subnet, opt_item->data);
  471. putenvp(xasprintf("mask=%u", mton(subnet)));
  472. }
  473. } else {
  474. unsigned ofs;
  475. new_opt = xmalloc(sizeof("optNNN=") + 1 + opt_item->len*2);
  476. ofs = sprintf(new_opt, "opt%u=", opt_item->code);
  477. bin2hex(new_opt + ofs, (char *)opt_item->data, opt_item->len)[0] = '\0';
  478. }
  479. log2(" %s", new_opt);
  480. putenv(new_opt);
  481. /* putenv will replace the existing environment variable in case of a duplicate.
  482. * Free the previous occurrence (NULL if it's the first one).
  483. */
  484. free(opt_item->env);
  485. opt_item->env = new_opt;
  486. }
  487. /* Export BOOTP fields. Fields we don't (yet?) export:
  488. * uint8_t op; // always BOOTREPLY
  489. * uint8_t htype; // hardware address type. 1 = 10mb ethernet
  490. * uint8_t hlen; // hardware address length
  491. * uint8_t hops; // used by relay agents only
  492. * uint32_t xid;
  493. * uint16_t secs; // elapsed since client began acquisition/renewal
  494. * uint16_t flags; // only one flag so far: bcast. Never set by server
  495. * uint32_t ciaddr; // client IP (usually == yiaddr. can it be different
  496. * // if during renew server wants to give us different IP?)
  497. * uint8_t chaddr[16]; // link-layer client hardware address (MAC)
  498. */
  499. /* Most important one: yiaddr as $ip */
  500. new_opt = xmalloc(sizeof("ip=255.255.255.255"));
  501. sprint_nip(new_opt, "ip=", (uint8_t *) &packet->yiaddr);
  502. putenvp(new_opt);
  503. if (packet->siaddr_nip) {
  504. /* IP address of next server to use in bootstrap */
  505. new_opt = xmalloc(sizeof("siaddr=255.255.255.255"));
  506. sprint_nip(new_opt, "siaddr=", (uint8_t *) &packet->siaddr_nip);
  507. putenvp(new_opt);
  508. }
  509. if (packet->gateway_nip) {
  510. /* IP address of DHCP relay agent */
  511. new_opt = xmalloc(sizeof("giaddr=255.255.255.255"));
  512. sprint_nip(new_opt, "giaddr=", (uint8_t *) &packet->gateway_nip);
  513. putenvp(new_opt);
  514. }
  515. if (!(scan_state.overload & FILE_FIELD) && packet->file[0]) {
  516. /* watch out for invalid packets */
  517. new_opt = xasprintf("boot_file=%."DHCP_PKT_FILE_LEN_STR"s", packet->file);
  518. putenvp(new_opt);
  519. }
  520. if (!(scan_state.overload & SNAME_FIELD) && packet->sname[0]) {
  521. /* watch out for invalid packets */
  522. new_opt = xasprintf("sname=%."DHCP_PKT_SNAME_LEN_STR"s", packet->sname);
  523. putenvp(new_opt);
  524. }
  525. }
  526. /* Call a script with a par file and env vars */
  527. static void udhcp_run_script(struct dhcp_packet *packet, const char *name)
  528. {
  529. char *argv[3];
  530. fill_envp(packet);
  531. /* call script */
  532. log1("executing %s %s", client_data.script, name);
  533. argv[0] = (char*) client_data.script;
  534. argv[1] = (char*) name;
  535. argv[2] = NULL;
  536. spawn_and_wait(argv);
  537. /* Free all allocated environment variables */
  538. llist_free(client_data.envp, optitem_unset_env_and_free);
  539. client_data.envp = NULL;
  540. }
  541. /*** Sending/receiving packets ***/
  542. static ALWAYS_INLINE uint32_t random_xid(void)
  543. {
  544. return rand();
  545. }
  546. /* Initialize the packet with the proper defaults */
  547. static void init_packet(struct dhcp_packet *packet, char type)
  548. {
  549. unsigned secs;
  550. /* Fill in: op, htype, hlen, cookie fields; message type option: */
  551. udhcp_init_header(packet, type);
  552. packet->xid = random_xid();
  553. client_data.last_secs = monotonic_sec();
  554. if (client_data.first_secs == 0)
  555. client_data.first_secs = client_data.last_secs;
  556. secs = client_data.last_secs - client_data.first_secs;
  557. packet->secs = (secs < 0xffff) ? htons(secs) : 0xffff;
  558. memcpy(packet->chaddr, client_data.client_mac, 6);
  559. if (client_data.clientid)
  560. udhcp_add_binary_option(packet, client_data.clientid);
  561. }
  562. static void add_client_options(struct dhcp_packet *packet)
  563. {
  564. int i, end, len;
  565. udhcp_add_simple_option(packet, DHCP_MAX_SIZE, htons(IP_UDP_DHCP_SIZE));
  566. /* Add a "param req" option with the list of options we'd like to have
  567. * from stubborn DHCP servers. Pull the data from the struct in common.c.
  568. * No bounds checking because it goes towards the head of the packet. */
  569. end = udhcp_end_option(packet->options);
  570. len = 0;
  571. for (i = 1; i < DHCP_END; i++) {
  572. if (client_data.opt_mask[i >> 3] & (1 << (i & 7))) {
  573. packet->options[end + OPT_DATA + len] = i;
  574. len++;
  575. }
  576. }
  577. if (len) {
  578. packet->options[end + OPT_CODE] = DHCP_PARAM_REQ;
  579. packet->options[end + OPT_LEN] = len;
  580. packet->options[end + OPT_DATA + len] = DHCP_END;
  581. }
  582. if (client_data.vendorclass)
  583. udhcp_add_binary_option(packet, client_data.vendorclass);
  584. if (client_data.hostname)
  585. udhcp_add_binary_option(packet, client_data.hostname);
  586. if (client_data.fqdn)
  587. udhcp_add_binary_option(packet, client_data.fqdn);
  588. /* Request broadcast replies if we have no IP addr */
  589. if ((option_mask32 & OPT_B) && packet->ciaddr == 0)
  590. packet->flags |= htons(BROADCAST_FLAG);
  591. /* Add -x options if any */
  592. {
  593. struct option_set *curr = client_data.options;
  594. while (curr) {
  595. udhcp_add_binary_option(packet, curr->data);
  596. curr = curr->next;
  597. }
  598. // if (client_data.sname)
  599. // strncpy((char*)packet->sname, client_data.sname, sizeof(packet->sname) - 1);
  600. // if (client_data.boot_file)
  601. // strncpy((char*)packet->file, client_data.boot_file, sizeof(packet->file) - 1);
  602. }
  603. // This will be needed if we remove -V VENDOR_STR in favor of
  604. // -x vendor:VENDOR_STR
  605. //if (!udhcp_find_option(packet.options, DHCP_VENDOR))
  606. // /* not set, set the default vendor ID */
  607. // ...add (DHCP_VENDOR, "udhcp "BB_VER) opt...
  608. }
  609. /* RFC 2131
  610. * 4.4.4 Use of broadcast and unicast
  611. *
  612. * The DHCP client broadcasts DHCPDISCOVER, DHCPREQUEST and DHCPINFORM
  613. * messages, unless the client knows the address of a DHCP server.
  614. * The client unicasts DHCPRELEASE messages to the server. Because
  615. * the client is declining the use of the IP address supplied by the server,
  616. * the client broadcasts DHCPDECLINE messages.
  617. *
  618. * When the DHCP client knows the address of a DHCP server, in either
  619. * INIT or REBOOTING state, the client may use that address
  620. * in the DHCPDISCOVER or DHCPREQUEST rather than the IP broadcast address.
  621. * The client may also use unicast to send DHCPINFORM messages
  622. * to a known DHCP server. If the client receives no response to DHCP
  623. * messages sent to the IP address of a known DHCP server, the DHCP
  624. * client reverts to using the IP broadcast address.
  625. */
  626. static int raw_bcast_from_client_data_ifindex(struct dhcp_packet *packet, uint32_t src_nip)
  627. {
  628. return udhcp_send_raw_packet(packet,
  629. /*src*/ src_nip, CLIENT_PORT,
  630. /*dst*/ INADDR_BROADCAST, SERVER_PORT, MAC_BCAST_ADDR,
  631. client_data.ifindex);
  632. }
  633. static int bcast_or_ucast(struct dhcp_packet *packet, uint32_t ciaddr, uint32_t server)
  634. {
  635. if (server)
  636. return udhcp_send_kernel_packet(packet,
  637. ciaddr, CLIENT_PORT,
  638. server, SERVER_PORT,
  639. client_data.interface);
  640. return raw_bcast_from_client_data_ifindex(packet, ciaddr);
  641. }
  642. /* Broadcast a DHCP discover packet to the network, with an optionally requested IP */
  643. /* NOINLINE: limit stack usage in caller */
  644. static NOINLINE int send_discover(uint32_t xid, uint32_t requested)
  645. {
  646. struct dhcp_packet packet;
  647. /* Fill in: op, htype, hlen, cookie, chaddr fields,
  648. * random xid field (we override it below),
  649. * client-id option (unless -C), message type option:
  650. */
  651. init_packet(&packet, DHCPDISCOVER);
  652. packet.xid = xid;
  653. if (requested)
  654. udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
  655. /* Add options: maxsize,
  656. * optionally: hostname, fqdn, vendorclass,
  657. * "param req" option according to -O, options specified with -x
  658. */
  659. add_client_options(&packet);
  660. bb_simple_info_msg("broadcasting discover");
  661. return raw_bcast_from_client_data_ifindex(&packet, INADDR_ANY);
  662. }
  663. /* Broadcast a DHCP request message */
  664. /* RFC 2131 3.1 paragraph 3:
  665. * "The client _broadcasts_ a DHCPREQUEST message..."
  666. */
  667. /* NOINLINE: limit stack usage in caller */
  668. static NOINLINE int send_select(uint32_t xid, uint32_t server, uint32_t requested)
  669. {
  670. struct dhcp_packet packet;
  671. struct in_addr temp_addr;
  672. char server_str[sizeof("255.255.255.255")];
  673. /*
  674. * RFC 2131 4.3.2 DHCPREQUEST message
  675. * ...
  676. * If the DHCPREQUEST message contains a 'server identifier'
  677. * option, the message is in response to a DHCPOFFER message.
  678. * Otherwise, the message is a request to verify or extend an
  679. * existing lease. If the client uses a 'client identifier'
  680. * in a DHCPREQUEST message, it MUST use that same 'client identifier'
  681. * in all subsequent messages. If the client included a list
  682. * of requested parameters in a DHCPDISCOVER message, it MUST
  683. * include that list in all subsequent messages.
  684. */
  685. /* Fill in: op, htype, hlen, cookie, chaddr fields,
  686. * random xid field (we override it below),
  687. * client-id option (unless -C), message type option:
  688. */
  689. init_packet(&packet, DHCPREQUEST);
  690. packet.xid = xid;
  691. udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
  692. udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
  693. /* Add options: maxsize,
  694. * optionally: hostname, fqdn, vendorclass,
  695. * "param req" option according to -O, and options specified with -x
  696. */
  697. add_client_options(&packet);
  698. temp_addr.s_addr = server;
  699. strcpy(server_str, inet_ntoa(temp_addr));
  700. temp_addr.s_addr = requested;
  701. bb_info_msg("broadcasting select for %s, server %s",
  702. inet_ntoa(temp_addr),
  703. server_str
  704. );
  705. return raw_bcast_from_client_data_ifindex(&packet, INADDR_ANY);
  706. }
  707. /* Unicast or broadcast a DHCP renew message */
  708. /* NOINLINE: limit stack usage in caller */
  709. static NOINLINE int send_renew(uint32_t xid, uint32_t server, uint32_t ciaddr)
  710. {
  711. struct dhcp_packet packet;
  712. /*
  713. * RFC 2131 4.3.2 DHCPREQUEST message
  714. * ...
  715. * DHCPREQUEST generated during RENEWING state:
  716. *
  717. * 'server identifier' MUST NOT be filled in, 'requested IP address'
  718. * option MUST NOT be filled in, 'ciaddr' MUST be filled in with
  719. * client's IP address. In this situation, the client is completely
  720. * configured, and is trying to extend its lease. This message will
  721. * be unicast, so no relay agents will be involved in its
  722. * transmission. Because 'giaddr' is therefore not filled in, the
  723. * DHCP server will trust the value in 'ciaddr', and use it when
  724. * replying to the client.
  725. */
  726. /* Fill in: op, htype, hlen, cookie, chaddr fields,
  727. * random xid field (we override it below),
  728. * client-id option (unless -C), message type option:
  729. */
  730. init_packet(&packet, DHCPREQUEST);
  731. packet.xid = xid;
  732. packet.ciaddr = ciaddr;
  733. /* Add options: maxsize,
  734. * optionally: hostname, fqdn, vendorclass,
  735. * "param req" option according to -O, and options specified with -x
  736. */
  737. add_client_options(&packet);
  738. if (server) {
  739. struct in_addr temp_addr;
  740. temp_addr.s_addr = server;
  741. bb_info_msg("sending renew to server %s", inet_ntoa(temp_addr));
  742. } else {
  743. bb_simple_info_msg("broadcasting renew");
  744. }
  745. return bcast_or_ucast(&packet, ciaddr, server);
  746. }
  747. #if ENABLE_FEATURE_UDHCPC_ARPING
  748. /* Broadcast a DHCP decline message */
  749. /* NOINLINE: limit stack usage in caller */
  750. static NOINLINE int send_decline(/*uint32_t xid,*/ uint32_t server, uint32_t requested)
  751. {
  752. struct dhcp_packet packet;
  753. /* Fill in: op, htype, hlen, cookie, chaddr, random xid fields,
  754. * client-id option (unless -C), message type option:
  755. */
  756. init_packet(&packet, DHCPDECLINE);
  757. #if 0
  758. /* RFC 2131 says DHCPDECLINE's xid is randomly selected by client,
  759. * but in case the server is buggy and wants DHCPDECLINE's xid
  760. * to match the xid which started entire handshake,
  761. * we use the same xid we used in initial DHCPDISCOVER:
  762. */
  763. packet.xid = xid;
  764. #endif
  765. /* DHCPDECLINE uses "requested ip", not ciaddr, to store offered IP */
  766. udhcp_add_simple_option(&packet, DHCP_REQUESTED_IP, requested);
  767. udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
  768. bb_simple_info_msg("broadcasting decline");
  769. return raw_bcast_from_client_data_ifindex(&packet, INADDR_ANY);
  770. }
  771. #endif
  772. /* Unicast a DHCP release message */
  773. static
  774. ALWAYS_INLINE /* one caller, help compiler to use this fact */
  775. int send_release(uint32_t server, uint32_t ciaddr)
  776. {
  777. struct dhcp_packet packet;
  778. /* Fill in: op, htype, hlen, cookie, chaddr, random xid fields,
  779. * client-id option (unless -C), message type option:
  780. */
  781. init_packet(&packet, DHCPRELEASE);
  782. /* DHCPRELEASE uses ciaddr, not "requested ip", to store IP being released */
  783. packet.ciaddr = ciaddr;
  784. udhcp_add_simple_option(&packet, DHCP_SERVER_ID, server);
  785. bb_info_msg("sending %s", "release");
  786. /* Note: normally we unicast here since "server" is not zero.
  787. * However, there _are_ people who run "address-less" DHCP servers,
  788. * and reportedly ISC dhcp client and Windows allow that.
  789. */
  790. return bcast_or_ucast(&packet, ciaddr, server);
  791. }
  792. /* Returns -1 on errors that are fatal for the socket, -2 for those that aren't */
  793. /* NOINLINE: limit stack usage in caller */
  794. static NOINLINE int udhcp_recv_raw_packet(struct dhcp_packet *dhcp_pkt, int fd)
  795. {
  796. int bytes;
  797. struct ip_udp_dhcp_packet packet;
  798. uint16_t check;
  799. unsigned char cmsgbuf[CMSG_LEN(sizeof(struct tpacket_auxdata))];
  800. struct iovec iov;
  801. struct msghdr msg;
  802. struct cmsghdr *cmsg;
  803. /* used to use just safe_read(fd, &packet, sizeof(packet))
  804. * but we need to check for TP_STATUS_CSUMNOTREADY :(
  805. */
  806. iov.iov_base = &packet;
  807. iov.iov_len = sizeof(packet);
  808. memset(&msg, 0, sizeof(msg));
  809. msg.msg_iov = &iov;
  810. msg.msg_iovlen = 1;
  811. msg.msg_control = cmsgbuf;
  812. msg.msg_controllen = sizeof(cmsgbuf);
  813. for (;;) {
  814. bytes = recvmsg(fd, &msg, 0);
  815. if (bytes < 0) {
  816. if (errno == EINTR)
  817. continue;
  818. log1s("packet read error, ignoring");
  819. /* NB: possible down interface, etc. Caller should pause. */
  820. return bytes; /* returns -1 */
  821. }
  822. break;
  823. }
  824. if (bytes < (int) (sizeof(packet.ip) + sizeof(packet.udp))) {
  825. log1s("packet is too short, ignoring");
  826. return -2;
  827. }
  828. if (bytes < ntohs(packet.ip.tot_len)) {
  829. /* packet is bigger than sizeof(packet), we did partial read */
  830. log1s("oversized packet, ignoring");
  831. return -2;
  832. }
  833. /* ignore any extra garbage bytes */
  834. bytes = ntohs(packet.ip.tot_len);
  835. /* make sure its the right packet for us, and that it passes sanity checks */
  836. if (packet.ip.protocol != IPPROTO_UDP
  837. || packet.ip.version != IPVERSION
  838. || packet.ip.ihl != (sizeof(packet.ip) >> 2)
  839. || packet.udp.dest != htons(CLIENT_PORT)
  840. /* || bytes > (int) sizeof(packet) - can't happen */
  841. || ntohs(packet.udp.len) != (uint16_t)(bytes - sizeof(packet.ip))
  842. ) {
  843. log1s("unrelated/bogus packet, ignoring");
  844. return -2;
  845. }
  846. /* verify IP checksum */
  847. check = packet.ip.check;
  848. packet.ip.check = 0;
  849. if (check != inet_cksum(&packet.ip, sizeof(packet.ip))) {
  850. log1s("bad IP header checksum, ignoring");
  851. return -2;
  852. }
  853. for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
  854. if (cmsg->cmsg_level == SOL_PACKET
  855. && cmsg->cmsg_type == PACKET_AUXDATA
  856. ) {
  857. /* some VMs don't checksum UDP and TCP data
  858. * they send to the same physical machine,
  859. * here we detect this case:
  860. */
  861. struct tpacket_auxdata *aux = (void *)CMSG_DATA(cmsg);
  862. if (aux->tp_status & TP_STATUS_CSUMNOTREADY)
  863. goto skip_udp_sum_check;
  864. }
  865. }
  866. /* verify UDP checksum. IP header has to be modified for this */
  867. memset(&packet.ip, 0, offsetof(struct iphdr, protocol));
  868. /* ip.xx fields which are not memset: protocol, check, saddr, daddr */
  869. packet.ip.tot_len = packet.udp.len; /* yes, this is needed */
  870. check = packet.udp.check;
  871. packet.udp.check = 0;
  872. if (check && check != inet_cksum(&packet, bytes)) {
  873. log1s("packet with bad UDP checksum received, ignoring");
  874. return -2;
  875. }
  876. skip_udp_sum_check:
  877. if (packet.data.cookie != htonl(DHCP_MAGIC)) {
  878. bb_simple_info_msg("packet with bad magic, ignoring");
  879. return -2;
  880. }
  881. log1("received %s", "a packet");
  882. udhcp_dump_packet(&packet.data);
  883. bytes -= sizeof(packet.ip) + sizeof(packet.udp);
  884. memcpy(dhcp_pkt, &packet.data, bytes);
  885. return bytes;
  886. }
  887. /*** Main ***/
  888. /* Values for client_data.listen_mode */
  889. #define LISTEN_NONE 0
  890. #define LISTEN_KERNEL 1
  891. #define LISTEN_RAW 2
  892. /* Values for client_data.state */
  893. /* initial state: (re)start DHCP negotiation */
  894. #define INIT_SELECTING 0
  895. /* discover was sent, DHCPOFFER reply received */
  896. #define REQUESTING 1
  897. /* select/renew was sent, DHCPACK reply received */
  898. #define BOUND 2
  899. /* half of lease passed, want to renew it by sending unicast renew requests */
  900. #define RENEWING 3
  901. /* renew requests were not answered, lease is almost over, send broadcast renew */
  902. #define REBINDING 4
  903. /* manually requested renew (SIGUSR1) */
  904. #define RENEW_REQUESTED 5
  905. /* release, possibly manually requested (SIGUSR2) */
  906. #define RELEASED 6
  907. static int udhcp_raw_socket(int ifindex)
  908. {
  909. int fd;
  910. struct sockaddr_ll sock;
  911. log2("opening raw socket on ifindex %d", ifindex);
  912. fd = xsocket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP));
  913. /* ^^^^^
  914. * SOCK_DGRAM: remove link-layer headers on input (SOCK_RAW keeps them)
  915. * ETH_P_IP: want to receive only packets with IPv4 eth type
  916. */
  917. log3("got raw socket fd %d", fd);
  918. memset(&sock, 0, sizeof(sock)); /* let's be deterministic */
  919. sock.sll_family = AF_PACKET;
  920. sock.sll_protocol = htons(ETH_P_IP);
  921. sock.sll_ifindex = ifindex;
  922. /*sock.sll_hatype = ARPHRD_???;*/
  923. /*sock.sll_pkttype = PACKET_???;*/
  924. /*sock.sll_halen = ???;*/
  925. /*sock.sll_addr[8] = ???;*/
  926. xbind(fd, (struct sockaddr *) &sock, sizeof(sock));
  927. #if 0 /* Several users reported breakage when BPF filter is used */
  928. if (CLIENT_PORT == 68) {
  929. /* Use only if standard port is in use */
  930. /*
  931. * I've selected not to see LL header, so BPF doesn't see it, too.
  932. * The filter may also pass non-IP and non-ARP packets, but we do
  933. * a more complete check when receiving the message in userspace.
  934. *
  935. * and filter shamelessly stolen from:
  936. *
  937. * http://www.flamewarmaster.de/software/dhcpclient/
  938. *
  939. * There are a few other interesting ideas on that page (look under
  940. * "Motivation"). Use of netlink events is most interesting. Think
  941. * of various network servers listening for events and reconfiguring.
  942. * That would obsolete sending HUP signals and/or make use of restarts.
  943. *
  944. * Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
  945. * License: GPL v2.
  946. */
  947. static const struct sock_filter filter_instr[] = {
  948. /* load 9th byte (protocol) */
  949. BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
  950. /* jump to L1 if it is IPPROTO_UDP, else to L4 */
  951. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 0, 6),
  952. /* L1: load halfword from offset 6 (flags and frag offset) */
  953. BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 6),
  954. /* jump to L4 if any bits in frag offset field are set, else to L2 */
  955. BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K, 0x1fff, 4, 0),
  956. /* L2: skip IP header (load index reg with header len) */
  957. BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0),
  958. /* load udp destination port from halfword[header_len + 2] */
  959. BPF_STMT(BPF_LD|BPF_H|BPF_IND, 2),
  960. /* jump to L3 if udp dport is CLIENT_PORT, else to L4 */
  961. BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 68, 0, 1),
  962. /* L3: accept packet ("accept 0x7fffffff bytes") */
  963. /* Accepting 0xffffffff works too but kernel 2.6.19 is buggy */
  964. BPF_STMT(BPF_RET|BPF_K, 0x7fffffff),
  965. /* L4: discard packet ("accept zero bytes") */
  966. BPF_STMT(BPF_RET|BPF_K, 0),
  967. };
  968. static const struct sock_fprog filter_prog = {
  969. .len = sizeof(filter_instr) / sizeof(filter_instr[0]),
  970. /* casting const away: */
  971. .filter = (struct sock_filter *) filter_instr,
  972. };
  973. /* Ignoring error (kernel may lack support for this) */
  974. if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog,
  975. sizeof(filter_prog)) >= 0)
  976. log1("attached filter to raw socket fd"); // log?
  977. }
  978. #endif
  979. if (setsockopt_1(fd, SOL_PACKET, PACKET_AUXDATA) != 0) {
  980. if (errno != ENOPROTOOPT)
  981. log1s("can't set PACKET_AUXDATA on raw socket");
  982. }
  983. log1s("created raw socket");
  984. return fd;
  985. }
  986. static void change_listen_mode(int new_mode)
  987. {
  988. log1("entering listen mode: %s",
  989. new_mode != LISTEN_NONE
  990. ? (new_mode == LISTEN_KERNEL ? "kernel" : "raw")
  991. : "none"
  992. );
  993. client_data.listen_mode = new_mode;
  994. if (client_data.sockfd >= 0) {
  995. close(client_data.sockfd);
  996. client_data.sockfd = -1;
  997. }
  998. if (new_mode == LISTEN_KERNEL)
  999. client_data.sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT, client_data.interface);
  1000. else if (new_mode != LISTEN_NONE)
  1001. client_data.sockfd = udhcp_raw_socket(client_data.ifindex);
  1002. /* else LISTEN_NONE: client_data.sockfd stays closed */
  1003. }
  1004. /* Called only on SIGUSR1 */
  1005. static void perform_renew(void)
  1006. {
  1007. bb_simple_info_msg("performing DHCP renew");
  1008. switch (client_data.state) {
  1009. case BOUND:
  1010. change_listen_mode(LISTEN_KERNEL);
  1011. case RENEWING:
  1012. case REBINDING:
  1013. client_data.state = RENEW_REQUESTED;
  1014. break;
  1015. case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
  1016. udhcp_run_script(NULL, "deconfig");
  1017. case REQUESTING:
  1018. case RELEASED:
  1019. change_listen_mode(LISTEN_RAW);
  1020. client_data.state = INIT_SELECTING;
  1021. break;
  1022. case INIT_SELECTING:
  1023. break;
  1024. }
  1025. }
  1026. static void perform_release(uint32_t server_addr, uint32_t requested_ip)
  1027. {
  1028. char buffer[sizeof("255.255.255.255")];
  1029. struct in_addr temp_addr;
  1030. /* send release packet */
  1031. if (client_data.state == BOUND
  1032. || client_data.state == RENEWING
  1033. || client_data.state == REBINDING
  1034. || client_data.state == RENEW_REQUESTED
  1035. ) {
  1036. temp_addr.s_addr = server_addr;
  1037. strcpy(buffer, inet_ntoa(temp_addr));
  1038. temp_addr.s_addr = requested_ip;
  1039. bb_info_msg("unicasting a release of %s to %s",
  1040. inet_ntoa(temp_addr), buffer);
  1041. send_release(server_addr, requested_ip); /* unicast */
  1042. }
  1043. bb_simple_info_msg("entering released state");
  1044. /*
  1045. * We can be here on: SIGUSR2,
  1046. * or on exit (SIGTERM) and -R "release on quit" is specified.
  1047. * Users requested to be notified in all cases, even if not in one
  1048. * of the states above.
  1049. */
  1050. udhcp_run_script(NULL, "deconfig");
  1051. change_listen_mode(LISTEN_NONE);
  1052. client_data.state = RELEASED;
  1053. }
  1054. static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
  1055. {
  1056. uint8_t *storage;
  1057. int len = strnlen(str, 255);
  1058. storage = xzalloc(len + extra + OPT_DATA);
  1059. storage[OPT_CODE] = code;
  1060. storage[OPT_LEN] = len + extra;
  1061. memcpy(storage + extra + OPT_DATA, str, len);
  1062. return storage;
  1063. }
  1064. #if BB_MMU
  1065. static void client_background(void)
  1066. {
  1067. bb_daemonize(0);
  1068. logmode &= ~LOGMODE_STDIO;
  1069. /* rewrite pidfile, as our pid is different now */
  1070. write_pidfile(client_data.pidfile);
  1071. }
  1072. #endif
  1073. //usage:#if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
  1074. //usage:# define IF_UDHCP_VERBOSE(...) __VA_ARGS__
  1075. //usage:#else
  1076. //usage:# define IF_UDHCP_VERBOSE(...)
  1077. //usage:#endif
  1078. //usage:#define udhcpc_trivial_usage
  1079. //usage: "[-fbq"IF_UDHCP_VERBOSE("v")"RB]"IF_FEATURE_UDHCPC_ARPING(" [-a[MSEC]]")" [-t N] [-T SEC] [-A SEC/-n]\n"
  1080. //usage: " [-i IFACE]"IF_FEATURE_UDHCP_PORT(" [-P PORT]")" [-s PROG] [-p PIDFILE]\n"
  1081. //usage: " [-oC] [-r IP] [-V VENDOR] [-F NAME] [-x OPT:VAL]... [-O OPT]..."
  1082. //usage:#define udhcpc_full_usage "\n"
  1083. //usage: "\n -i IFACE Interface to use (default "CONFIG_UDHCPC_DEFAULT_INTERFACE")"
  1084. //usage: IF_FEATURE_UDHCP_PORT(
  1085. //usage: "\n -P PORT Use PORT (default 68)"
  1086. //usage: )
  1087. //usage: "\n -s PROG Run PROG at DHCP events (default "CONFIG_UDHCPC_DEFAULT_SCRIPT")"
  1088. //usage: "\n -p FILE Create pidfile"
  1089. //usage: "\n -B Request broadcast replies"
  1090. //usage: "\n -t N Send up to N discover packets (default 3)"
  1091. //usage: "\n -T SEC Pause between packets (default 3)"
  1092. //usage: "\n -A SEC Wait if lease is not obtained (default 20)"
  1093. //usage: USE_FOR_MMU(
  1094. //usage: "\n -b Background if lease is not obtained"
  1095. //usage: )
  1096. //usage: "\n -n Exit if lease is not obtained"
  1097. //usage: "\n -q Exit after obtaining lease"
  1098. //usage: "\n -R Release IP on exit"
  1099. //usage: "\n -f Run in foreground"
  1100. //usage: "\n -S Log to syslog too"
  1101. //usage: IF_FEATURE_UDHCPC_ARPING(
  1102. //usage: "\n -a[MSEC] Validate offered address with ARP ping"
  1103. //usage: )
  1104. //usage: "\n -r IP Request this IP address"
  1105. //usage: "\n -o Don't request any options (unless -O is given)"
  1106. //usage: "\n -O OPT Request option OPT from server (cumulative)"
  1107. //usage: "\n -x OPT:VAL Include option OPT in sent packets (cumulative)"
  1108. //usage: "\n Examples of string, numeric, and hex byte opts:"
  1109. //usage: "\n -x hostname:bbox - option 12"
  1110. //usage: "\n -x lease:3600 - option 51 (lease time)"
  1111. //usage: "\n -x 0x3d:0100BEEFC0FFEE - option 61 (client id)"
  1112. //usage: "\n -x 14:'\"dumpfile\"' - option 14 (shell-quoted)"
  1113. //usage: "\n -F NAME Ask server to update DNS mapping for NAME"
  1114. //usage: "\n -V VENDOR Vendor identifier (default 'udhcp VERSION')"
  1115. //usage: "\n -C Don't send MAC as client identifier"
  1116. //usage: IF_UDHCP_VERBOSE(
  1117. //usage: "\n -v Verbose"
  1118. //usage: )
  1119. //usage: "\nSignals:"
  1120. //usage: "\n USR1 Renew lease"
  1121. //usage: "\n USR2 Release lease"
  1122. int udhcpc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1123. int udhcpc_main(int argc UNUSED_PARAM, char **argv)
  1124. {
  1125. uint8_t *message;
  1126. const char *str_V, *str_h, *str_F, *str_r;
  1127. IF_FEATURE_UDHCPC_ARPING(const char *str_a = "2000";)
  1128. IF_FEATURE_UDHCP_PORT(char *str_P;)
  1129. void *clientid_mac_ptr;
  1130. llist_t *list_O = NULL;
  1131. llist_t *list_x = NULL;
  1132. int tryagain_timeout = 20;
  1133. int discover_timeout = 3;
  1134. int discover_retries = 3;
  1135. uint32_t server_addr = server_addr; /* for compiler */
  1136. uint32_t requested_ip = 0;
  1137. uint32_t xid = xid; /* for compiler */
  1138. int packet_num;
  1139. int timeout; /* must be signed */
  1140. unsigned already_waited_sec;
  1141. unsigned opt;
  1142. IF_FEATURE_UDHCPC_ARPING(unsigned arpping_ms;)
  1143. int retval;
  1144. setup_common_bufsiz();
  1145. /* Default options */
  1146. IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;)
  1147. IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;)
  1148. client_data.interface = CONFIG_UDHCPC_DEFAULT_INTERFACE;
  1149. client_data.script = CONFIG_UDHCPC_DEFAULT_SCRIPT;
  1150. client_data.sockfd = -1;
  1151. str_V = "udhcp "BB_VER;
  1152. /* Make sure fd 0,1,2 are open */
  1153. /* Set up the signal pipe on fds 3,4 - must be before openlog() */
  1154. udhcp_sp_setup();
  1155. /* Parse command line */
  1156. opt = getopt32long(argv, "^"
  1157. /* O,x: list; -T,-t,-A take numeric param */
  1158. "CV:H:h:F:i:np:qRr:s:T:+t:+SA:+O:*ox:*fB"
  1159. USE_FOR_MMU("b")
  1160. IF_FEATURE_UDHCPC_ARPING("a::")
  1161. IF_FEATURE_UDHCP_PORT("P:")
  1162. "v"
  1163. "\0" IF_UDHCP_VERBOSE("vv") /* -v is a counter */
  1164. , udhcpc_longopts
  1165. , &str_V, &str_h, &str_h, &str_F
  1166. , &client_data.interface, &client_data.pidfile /* i,p */
  1167. , &str_r /* r */
  1168. , &client_data.script /* s */
  1169. , &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */
  1170. , &list_O
  1171. , &list_x
  1172. IF_FEATURE_UDHCPC_ARPING(, &str_a)
  1173. IF_FEATURE_UDHCP_PORT(, &str_P)
  1174. IF_UDHCP_VERBOSE(, &dhcp_verbose)
  1175. );
  1176. if (opt & (OPT_h|OPT_H)) {
  1177. //msg added 2011-11
  1178. bb_simple_error_msg("option -h NAME is deprecated, use -x hostname:NAME");
  1179. client_data.hostname = alloc_dhcp_option(DHCP_HOST_NAME, str_h, 0);
  1180. }
  1181. if (opt & OPT_F) {
  1182. /* FQDN option format: [0x51][len][flags][0][0]<fqdn> */
  1183. client_data.fqdn = alloc_dhcp_option(DHCP_FQDN, str_F, 3);
  1184. /* Flag bits: 0000NEOS
  1185. * S: 1 = Client requests server to update A RR in DNS as well as PTR
  1186. * O: 1 = Server indicates to client that DNS has been updated regardless
  1187. * E: 1 = Name is in DNS format, i.e. <4>host<6>domain<3>com<0>,
  1188. * not "host.domain.com". Format 0 is obsolete.
  1189. * N: 1 = Client requests server to not update DNS (S must be 0 then)
  1190. * Two [0] bytes which follow are deprecated and must be 0.
  1191. */
  1192. client_data.fqdn[OPT_DATA + 0] = 0x1;
  1193. /*client_data.fqdn[OPT_DATA + 1] = 0; - xzalloc did it */
  1194. /*client_data.fqdn[OPT_DATA + 2] = 0; */
  1195. }
  1196. if (opt & OPT_r)
  1197. requested_ip = inet_addr(str_r);
  1198. #if ENABLE_FEATURE_UDHCP_PORT
  1199. if (opt & OPT_P) {
  1200. CLIENT_PORT = xatou16(str_P);
  1201. SERVER_PORT = CLIENT_PORT - 1;
  1202. }
  1203. #endif
  1204. IF_FEATURE_UDHCPC_ARPING(arpping_ms = xatou(str_a);)
  1205. while (list_O) {
  1206. char *optstr = llist_pop(&list_O);
  1207. unsigned n = bb_strtou(optstr, NULL, 0);
  1208. if (errno || n > 254) {
  1209. n = udhcp_option_idx(optstr, dhcp_option_strings);
  1210. n = dhcp_optflags[n].code;
  1211. }
  1212. client_data.opt_mask[n >> 3] |= 1 << (n & 7);
  1213. }
  1214. if (!(opt & OPT_o)) {
  1215. unsigned i, n;
  1216. for (i = 0; (n = dhcp_optflags[i].code) != 0; i++) {
  1217. if (dhcp_optflags[i].flags & OPTION_REQ) {
  1218. client_data.opt_mask[n >> 3] |= 1 << (n & 7);
  1219. }
  1220. }
  1221. }
  1222. while (list_x) {
  1223. char *optstr = xstrdup(llist_pop(&list_x));
  1224. udhcp_str2optset(optstr, &client_data.options,
  1225. dhcp_optflags, dhcp_option_strings,
  1226. /*dhcpv6:*/ 0
  1227. );
  1228. free(optstr);
  1229. }
  1230. if (udhcp_read_interface(client_data.interface,
  1231. &client_data.ifindex,
  1232. NULL,
  1233. client_data.client_mac)
  1234. ) {
  1235. return 1;
  1236. }
  1237. clientid_mac_ptr = NULL;
  1238. if (!(opt & OPT_C) && !udhcp_find_option(client_data.options, DHCP_CLIENT_ID)) {
  1239. /* not suppressed and not set, set the default client ID */
  1240. client_data.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, "", 7);
  1241. client_data.clientid[OPT_DATA] = 1; /* type: ethernet */
  1242. clientid_mac_ptr = client_data.clientid + OPT_DATA+1;
  1243. memcpy(clientid_mac_ptr, client_data.client_mac, 6);
  1244. }
  1245. if (str_V[0] != '\0') {
  1246. // can drop -V, str_V, client_data.vendorclass,
  1247. // but need to add "vendor" to the list of recognized
  1248. // string opts for this to work;
  1249. // and need to tweak add_client_options() too...
  1250. // ...so the question is, should we?
  1251. //bb_error_msg("option -V VENDOR is deprecated, use -x vendor:VENDOR");
  1252. client_data.vendorclass = alloc_dhcp_option(DHCP_VENDOR, str_V, 0);
  1253. }
  1254. #if !BB_MMU
  1255. /* on NOMMU reexec (i.e., background) early */
  1256. if (!(opt & OPT_f)) {
  1257. bb_daemonize_or_rexec(0 /* flags */, argv);
  1258. logmode = LOGMODE_NONE;
  1259. }
  1260. #endif
  1261. if (opt & OPT_S) {
  1262. openlog(applet_name, LOG_PID, LOG_DAEMON);
  1263. logmode |= LOGMODE_SYSLOG;
  1264. }
  1265. /* Create pidfile */
  1266. write_pidfile(client_data.pidfile);
  1267. /* Goes to stdout (unless NOMMU) and possibly syslog */
  1268. bb_simple_info_msg("started, v"BB_VER);
  1269. /* We want random_xid to be random... */
  1270. srand(monotonic_us());
  1271. client_data.state = INIT_SELECTING;
  1272. udhcp_run_script(NULL, "deconfig");
  1273. change_listen_mode(LISTEN_RAW);
  1274. packet_num = 0;
  1275. timeout = 0;
  1276. already_waited_sec = 0;
  1277. /* Main event loop. select() waits on signal pipe and possibly
  1278. * on sockfd.
  1279. * "continue" statements in code below jump to the top of the loop.
  1280. */
  1281. for (;;) {
  1282. int tv;
  1283. struct pollfd pfds[2];
  1284. struct dhcp_packet packet;
  1285. /* silence "uninitialized!" warning */
  1286. unsigned timestamp_before_wait = timestamp_before_wait;
  1287. //bb_error_msg("sockfd:%d, listen_mode:%d", client_data.sockfd, client_data.listen_mode);
  1288. /* Was opening raw or udp socket here
  1289. * if (client_data.listen_mode != LISTEN_NONE && client_data.sockfd < 0),
  1290. * but on fast network renew responses return faster
  1291. * than we open sockets. Thus this code is moved
  1292. * to change_listen_mode(). Thus we open listen socket
  1293. * BEFORE we send renew request (see "case BOUND:"). */
  1294. udhcp_sp_fd_set(pfds, client_data.sockfd);
  1295. tv = timeout - already_waited_sec;
  1296. retval = 0;
  1297. /* If we already timed out, fall through with retval = 0, else... */
  1298. if (tv > 0) {
  1299. log1("waiting %u seconds", tv);
  1300. timestamp_before_wait = (unsigned)monotonic_sec();
  1301. retval = poll(pfds, 2, tv < INT_MAX/1000 ? tv * 1000 : INT_MAX);
  1302. if (retval < 0) {
  1303. /* EINTR? A signal was caught, don't panic */
  1304. if (errno == EINTR) {
  1305. already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
  1306. continue;
  1307. }
  1308. /* Else: an error occurred, panic! */
  1309. bb_simple_perror_msg_and_die("poll");
  1310. }
  1311. }
  1312. /* If timeout dropped to zero, time to become active:
  1313. * resend discover/renew/whatever
  1314. */
  1315. if (retval == 0) {
  1316. /* When running on a bridge, the ifindex may have changed
  1317. * (e.g. if member interfaces were added/removed
  1318. * or if the status of the bridge changed).
  1319. * Refresh ifindex and client_mac:
  1320. */
  1321. if (udhcp_read_interface(client_data.interface,
  1322. &client_data.ifindex,
  1323. NULL,
  1324. client_data.client_mac)
  1325. ) {
  1326. goto ret0; /* iface is gone? */
  1327. }
  1328. if (clientid_mac_ptr)
  1329. memcpy(clientid_mac_ptr, client_data.client_mac, 6);
  1330. /* We will restart the wait in any case */
  1331. already_waited_sec = 0;
  1332. switch (client_data.state) {
  1333. case INIT_SELECTING:
  1334. if (!discover_retries || packet_num < discover_retries) {
  1335. if (packet_num == 0)
  1336. xid = random_xid();
  1337. /* broadcast */
  1338. send_discover(xid, requested_ip);
  1339. timeout = discover_timeout;
  1340. packet_num++;
  1341. continue;
  1342. }
  1343. leasefail:
  1344. udhcp_run_script(NULL, "leasefail");
  1345. #if BB_MMU /* -b is not supported on NOMMU */
  1346. if (opt & OPT_b) { /* background if no lease */
  1347. bb_simple_info_msg("no lease, forking to background");
  1348. client_background();
  1349. /* do not background again! */
  1350. opt = ((opt & ~(OPT_b|OPT_n)) | OPT_f);
  1351. /* ^^^ also disables -n (-b takes priority over -n):
  1352. * ifup's default udhcpc options are -R -n,
  1353. * and users want to be able to add -b
  1354. * (in a config file) to make it background
  1355. * _and not exit_.
  1356. */
  1357. } else
  1358. #endif
  1359. if (opt & OPT_n) { /* abort if no lease */
  1360. bb_simple_info_msg("no lease, failing");
  1361. retval = 1;
  1362. goto ret;
  1363. }
  1364. /* wait before trying again */
  1365. timeout = tryagain_timeout;
  1366. packet_num = 0;
  1367. continue;
  1368. case REQUESTING:
  1369. if (packet_num < 3) {
  1370. /* send broadcast select packet */
  1371. send_select(xid, server_addr, requested_ip);
  1372. timeout = discover_timeout;
  1373. packet_num++;
  1374. continue;
  1375. }
  1376. /* Timed out, go back to init state.
  1377. * "discover...select...discover..." loops
  1378. * were seen in the wild. Treat them similarly
  1379. * to "no response to discover" case */
  1380. change_listen_mode(LISTEN_RAW);
  1381. client_data.state = INIT_SELECTING;
  1382. goto leasefail;
  1383. case BOUND:
  1384. /* 1/2 lease passed, enter renewing state */
  1385. client_data.state = RENEWING;
  1386. client_data.first_secs = 0; /* make secs field count from 0 */
  1387. change_listen_mode(LISTEN_KERNEL);
  1388. log1s("entering renew state");
  1389. /* fall right through */
  1390. case RENEW_REQUESTED: /* manual (SIGUSR1) renew */
  1391. case_RENEW_REQUESTED:
  1392. case RENEWING:
  1393. if (timeout >= 60) {
  1394. /* send an unicast renew request */
  1395. /* Sometimes observed to fail (EADDRNOTAVAIL) to bind
  1396. * a new UDP socket for sending inside send_renew.
  1397. * I hazard to guess existing listening socket
  1398. * is somehow conflicting with it, but why is it
  1399. * not deterministic then?! Strange.
  1400. * Anyway, it does recover by eventually failing through
  1401. * into INIT_SELECTING state.
  1402. */
  1403. if (send_renew(xid, server_addr, requested_ip) >= 0) {
  1404. timeout >>= 1;
  1405. //TODO: the timeout to receive an answer for our renew should not be selected
  1406. //with "timeout = lease_seconds / 2; ...; timeout = timeout / 2": it is often huge.
  1407. //Waiting e.g. 4*3600 seconds for a reply does not make sense
  1408. //(if reply isn't coming, we keep an open socket for hours),
  1409. //it should be something like 10 seconds.
  1410. //Also, it's probably best to try sending renew in kernel mode a few (3-5) times
  1411. //and fall back to raw mode if it does not work.
  1412. continue;
  1413. }
  1414. /* else: error sending.
  1415. * example: ENETUNREACH seen with server
  1416. * which gave us bogus server ID 1.1.1.1
  1417. * which wasn't reachable (and probably did not exist).
  1418. */
  1419. }
  1420. /* Timed out or error, enter rebinding state */
  1421. log1s("entering rebinding state");
  1422. client_data.state = REBINDING;
  1423. /* fall right through */
  1424. case REBINDING:
  1425. /* Switch to bcast receive */
  1426. change_listen_mode(LISTEN_RAW);
  1427. /* Lease is *really* about to run out,
  1428. * try to find DHCP server using broadcast */
  1429. if (timeout > 0) {
  1430. /* send a broadcast renew request */
  1431. send_renew(xid, 0 /*INADDR_ANY*/, requested_ip);
  1432. timeout >>= 1;
  1433. continue;
  1434. }
  1435. /* Timed out, enter init state */
  1436. bb_simple_info_msg("lease lost, entering init state");
  1437. udhcp_run_script(NULL, "deconfig");
  1438. client_data.state = INIT_SELECTING;
  1439. client_data.first_secs = 0; /* make secs field count from 0 */
  1440. /*timeout = 0; - already is */
  1441. packet_num = 0;
  1442. continue;
  1443. /* case RELEASED: */
  1444. }
  1445. /* yah, I know, *you* say it would never happen */
  1446. timeout = INT_MAX;
  1447. continue; /* back to main loop */
  1448. } /* if poll timed out */
  1449. /* poll() didn't timeout, something happened */
  1450. /* Is it a signal? */
  1451. switch (udhcp_sp_read()) {
  1452. case SIGUSR1:
  1453. client_data.first_secs = 0; /* make secs field count from 0 */
  1454. already_waited_sec = 0;
  1455. perform_renew();
  1456. if (client_data.state == RENEW_REQUESTED) {
  1457. /* We might be either on the same network
  1458. * (in which case renew might work),
  1459. * or we might be on a completely different one
  1460. * (in which case renew won't ever succeed).
  1461. * For the second case, must make sure timeout
  1462. * is not too big, or else we can send
  1463. * futile renew requests for hours.
  1464. */
  1465. if (timeout > 60)
  1466. timeout = 60;
  1467. goto case_RENEW_REQUESTED;
  1468. }
  1469. /* Start things over */
  1470. packet_num = 0;
  1471. /* Kill any timeouts, user wants this to hurry along */
  1472. timeout = 0;
  1473. continue;
  1474. case SIGUSR2:
  1475. perform_release(server_addr, requested_ip);
  1476. timeout = INT_MAX;
  1477. continue;
  1478. case SIGTERM:
  1479. bb_info_msg("received %s", "SIGTERM");
  1480. goto ret0;
  1481. }
  1482. /* Is it a packet? */
  1483. if (!pfds[1].revents)
  1484. continue; /* no */
  1485. {
  1486. int len;
  1487. /* A packet is ready, read it */
  1488. if (client_data.listen_mode == LISTEN_KERNEL)
  1489. len = udhcp_recv_kernel_packet(&packet, client_data.sockfd);
  1490. else
  1491. len = udhcp_recv_raw_packet(&packet, client_data.sockfd);
  1492. if (len == -1) {
  1493. /* Error is severe, reopen socket */
  1494. bb_error_msg("read error: "STRERROR_FMT", reopening socket" STRERROR_ERRNO);
  1495. sleep(discover_timeout); /* 3 seconds by default */
  1496. change_listen_mode(client_data.listen_mode); /* just close and reopen */
  1497. }
  1498. /* If this packet will turn out to be unrelated/bogus,
  1499. * we will go back and wait for next one.
  1500. * Be sure timeout is properly decreased. */
  1501. already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
  1502. if (len < 0)
  1503. continue;
  1504. }
  1505. if (packet.xid != xid) {
  1506. log1("xid %x (our is %x)%s",
  1507. (unsigned)packet.xid, (unsigned)xid,
  1508. ", ignoring packet"
  1509. );
  1510. continue;
  1511. }
  1512. /* Ignore packets that aren't for us */
  1513. if (packet.hlen != 6
  1514. || memcmp(packet.chaddr, client_data.client_mac, 6) != 0
  1515. ) {
  1516. //FIXME: need to also check that last 10 bytes are zero
  1517. log1("chaddr does not match%s", ", ignoring packet"); // log2?
  1518. continue;
  1519. }
  1520. message = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
  1521. if (message == NULL) {
  1522. bb_info_msg("no message type option%s", ", ignoring packet");
  1523. continue;
  1524. }
  1525. switch (client_data.state) {
  1526. case INIT_SELECTING:
  1527. /* Must be a DHCPOFFER */
  1528. if (*message == DHCPOFFER) {
  1529. uint8_t *temp;
  1530. /* What exactly is server's IP? There are several values.
  1531. * Example DHCP offer captured with tchdump:
  1532. *
  1533. * 10.34.25.254:67 > 10.34.25.202:68 // IP header's src
  1534. * BOOTP fields:
  1535. * Your-IP 10.34.25.202
  1536. * Server-IP 10.34.32.125 // "next server" IP
  1537. * Gateway-IP 10.34.25.254 // relay's address (if DHCP relays are in use)
  1538. * DHCP options:
  1539. * DHCP-Message Option 53, length 1: Offer
  1540. * Server-ID Option 54, length 4: 10.34.255.7 // "server ID"
  1541. * Default-Gateway Option 3, length 4: 10.34.25.254 // router
  1542. *
  1543. * We think that real server IP (one to use in renew/release)
  1544. * is one in Server-ID option. But I am not 100% sure.
  1545. * IP header's src and Gateway-IP (same in this example)
  1546. * might work too.
  1547. * "Next server" and router are definitely wrong ones to use, though...
  1548. */
  1549. /* We used to ignore packets without DHCP_SERVER_ID.
  1550. * I've got user reports from people who run "address-less" servers.
  1551. * They either supply DHCP_SERVER_ID of 0.0.0.0 or don't supply it at all.
  1552. * They say ISC DHCP client supports this case.
  1553. */
  1554. server_addr = 0;
  1555. temp = udhcp_get_option32(&packet, DHCP_SERVER_ID);
  1556. if (!temp) {
  1557. bb_simple_info_msg("no server ID, using 0.0.0.0");
  1558. } else {
  1559. /* it IS unaligned sometimes, don't "optimize" */
  1560. move_from_unaligned32(server_addr, temp);
  1561. }
  1562. /*xid = packet.xid; - already is */
  1563. requested_ip = packet.yiaddr;
  1564. /* enter requesting state */
  1565. client_data.state = REQUESTING;
  1566. timeout = 0;
  1567. packet_num = 0;
  1568. already_waited_sec = 0;
  1569. }
  1570. continue;
  1571. case REQUESTING:
  1572. case RENEWING:
  1573. case RENEW_REQUESTED:
  1574. case REBINDING:
  1575. if (*message == DHCPACK) {
  1576. unsigned start;
  1577. uint32_t lease_seconds;
  1578. struct in_addr temp_addr;
  1579. char server_str[sizeof("255.255.255.255")];
  1580. uint8_t *temp;
  1581. temp = udhcp_get_option32(&packet, DHCP_LEASE_TIME);
  1582. if (!temp) {
  1583. bb_simple_info_msg("no lease time with ACK, using 1 hour lease");
  1584. lease_seconds = 60 * 60;
  1585. } else {
  1586. /* it IS unaligned sometimes, don't "optimize" */
  1587. move_from_unaligned32(lease_seconds, temp);
  1588. lease_seconds = ntohl(lease_seconds);
  1589. /* paranoia: must not be too small and not prone to overflows */
  1590. /* timeout > 60 - ensures at least one unicast renew attempt */
  1591. if (lease_seconds < 2 * 61)
  1592. lease_seconds = 2 * 61;
  1593. //if (lease_seconds > 0x7fffffff)
  1594. // lease_seconds = 0x7fffffff;
  1595. //^^^not necessary since "timeout = lease_seconds / 2"
  1596. //does not overflow even for 0xffffffff.
  1597. }
  1598. #if ENABLE_FEATURE_UDHCPC_ARPING
  1599. if (opt & OPT_a) {
  1600. /* RFC 2131 3.1 paragraph 5:
  1601. * "The client receives the DHCPACK message with configuration
  1602. * parameters. The client SHOULD perform a final check on the
  1603. * parameters (e.g., ARP for allocated network address), and notes
  1604. * the duration of the lease specified in the DHCPACK message. At this
  1605. * point, the client is configured. If the client detects that the
  1606. * address is already in use (e.g., through the use of ARP),
  1607. * the client MUST send a DHCPDECLINE message to the server and restarts
  1608. * the configuration process..." */
  1609. if (!arpping(packet.yiaddr,
  1610. NULL,
  1611. (uint32_t) 0,
  1612. client_data.client_mac,
  1613. client_data.interface,
  1614. arpping_ms)
  1615. ) {
  1616. bb_simple_info_msg("offered address is in use "
  1617. "(got ARP reply), declining");
  1618. send_decline(/*xid,*/ server_addr, packet.yiaddr);
  1619. if (client_data.state != REQUESTING)
  1620. udhcp_run_script(NULL, "deconfig");
  1621. change_listen_mode(LISTEN_RAW);
  1622. client_data.state = INIT_SELECTING;
  1623. client_data.first_secs = 0; /* make secs field count from 0 */
  1624. requested_ip = 0;
  1625. timeout = tryagain_timeout;
  1626. packet_num = 0;
  1627. already_waited_sec = 0;
  1628. continue; /* back to main loop */
  1629. }
  1630. }
  1631. #endif
  1632. /* enter bound state */
  1633. temp_addr.s_addr = server_addr;
  1634. strcpy(server_str, inet_ntoa(temp_addr));
  1635. temp_addr.s_addr = packet.yiaddr;
  1636. bb_info_msg("lease of %s obtained from %s, lease time %u",
  1637. inet_ntoa(temp_addr), server_str, (unsigned)lease_seconds);
  1638. requested_ip = packet.yiaddr;
  1639. start = monotonic_sec();
  1640. udhcp_run_script(&packet, client_data.state == REQUESTING ? "bound" : "renew");
  1641. already_waited_sec = (unsigned)monotonic_sec() - start;
  1642. timeout = lease_seconds / 2;
  1643. if ((unsigned)timeout < already_waited_sec) {
  1644. /* Something went wrong. Back to discover state */
  1645. timeout = already_waited_sec = 0;
  1646. }
  1647. client_data.state = BOUND;
  1648. change_listen_mode(LISTEN_NONE);
  1649. if (opt & OPT_q) { /* quit after lease */
  1650. goto ret0;
  1651. }
  1652. /* future renew failures should not exit (JM) */
  1653. opt &= ~OPT_n;
  1654. #if BB_MMU /* NOMMU case backgrounded earlier */
  1655. if (!(opt & OPT_f)) {
  1656. client_background();
  1657. /* do not background again! */
  1658. opt = ((opt & ~OPT_b) | OPT_f);
  1659. }
  1660. #endif
  1661. /* make future renew packets use different xid */
  1662. /* xid = random_xid(); ...but why bother? */
  1663. continue; /* back to main loop */
  1664. }
  1665. if (*message == DHCPNAK) {
  1666. /* If network has more than one DHCP server,
  1667. * "wrong" server can reply first, with a NAK.
  1668. * Do not interpret it as a NAK from "our" server.
  1669. */
  1670. if (server_addr != 0) {
  1671. uint32_t svid;
  1672. uint8_t *temp;
  1673. temp = udhcp_get_option32(&packet, DHCP_SERVER_ID);
  1674. if (!temp) {
  1675. non_matching_svid:
  1676. log1("received DHCP NAK with wrong"
  1677. " server ID%s", ", ignoring packet");
  1678. continue;
  1679. }
  1680. move_from_unaligned32(svid, temp);
  1681. if (svid != server_addr)
  1682. goto non_matching_svid;
  1683. }
  1684. /* return to init state */
  1685. bb_info_msg("received %s", "DHCP NAK");
  1686. udhcp_run_script(&packet, "nak");
  1687. if (client_data.state != REQUESTING)
  1688. udhcp_run_script(NULL, "deconfig");
  1689. change_listen_mode(LISTEN_RAW);
  1690. sleep(3); /* avoid excessive network traffic */
  1691. client_data.state = INIT_SELECTING;
  1692. client_data.first_secs = 0; /* make secs field count from 0 */
  1693. requested_ip = 0;
  1694. timeout = 0;
  1695. packet_num = 0;
  1696. already_waited_sec = 0;
  1697. }
  1698. continue;
  1699. /* case BOUND: - ignore all packets */
  1700. /* case RELEASED: - ignore all packets */
  1701. }
  1702. /* back to main loop */
  1703. } /* for (;;) - main loop ends */
  1704. ret0:
  1705. if (opt & OPT_R) /* release on quit */
  1706. perform_release(server_addr, requested_ip);
  1707. retval = 0;
  1708. ret:
  1709. /*if (client_data.pidfile) - remove_pidfile has its own check */
  1710. remove_pidfile(client_data.pidfile);
  1711. return retval;
  1712. }