dhcpc.c 58 KB

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