dhcpc.c 57 KB

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