dhcpc.c 57 KB

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