aboutsummaryrefslogtreecommitdiff
path: root/networking
diff options
context:
space:
mode:
authorRon Yorston <rmy@pobox.com>2015-03-14 20:33:00 +0000
committerRon Yorston <rmy@pobox.com>2015-03-14 20:33:00 +0000
commita4f58436b78fe59e57620c6e0301f213ee25f273 (patch)
tree8355f724926e605280af2d6f2b1ccc6b1bd02dee /networking
parentba0c36cfcf84efbac6f89e27238e04bb57e9cd45 (diff)
parent49acc1a7618a28d34381cbb7661d7c981fcb238f (diff)
downloadbusybox-w32-a4f58436b78fe59e57620c6e0301f213ee25f273.tar.gz
busybox-w32-a4f58436b78fe59e57620c6e0301f213ee25f273.tar.bz2
busybox-w32-a4f58436b78fe59e57620c6e0301f213ee25f273.zip
Merge branch 'busybox' into merge
Conflicts: coreutils/od_bloaty.c libbb/lineedit.c
Diffstat (limited to 'networking')
-rw-r--r--networking/Config.src3
-rw-r--r--networking/arping.c3
-rw-r--r--networking/dnsd.c2
-rw-r--r--networking/ftpd.c9
-rw-r--r--networking/httpd.c8
-rw-r--r--networking/ifupdown.c10
-rw-r--r--networking/inetd.c12
-rw-r--r--networking/interface.c4
-rw-r--r--networking/libiproute/ipaddress.c2
-rw-r--r--networking/nameif.c8
-rw-r--r--networking/netstat.c6
-rw-r--r--networking/ntpd.c69
-rw-r--r--networking/ntpd_simple.c1005
-rw-r--r--networking/route.c48
-rw-r--r--networking/telnetd.c12
-rw-r--r--networking/udhcp/dhcpc.c6
-rw-r--r--networking/udhcp/dhcpd.c3
-rw-r--r--networking/wget.c98
18 files changed, 189 insertions, 1119 deletions
diff --git a/networking/Config.src b/networking/Config.src
index 15a696876..da36e8627 100644
--- a/networking/Config.src
+++ b/networking/Config.src
@@ -750,8 +750,7 @@ config TELNETD
750 750
751 Note that for busybox telnetd to work you need several things: 751 Note that for busybox telnetd to work you need several things:
752 First of all, your kernel needs: 752 First of all, your kernel needs:
753 UNIX98_PTYS=y 753 CONFIG_UNIX98_PTYS=y
754 DEVPTS_FS=y
755 754
756 Next, you need a /dev/pts directory on your root filesystem: 755 Next, you need a /dev/pts directory on your root filesystem:
757 756
diff --git a/networking/arping.c b/networking/arping.c
index a4421edcb..dbfd75ef5 100644
--- a/networking/arping.c
+++ b/networking/arping.c
@@ -284,7 +284,6 @@ int arping_main(int argc UNUSED_PARAM, char **argv)
284 // Need to remove SUID_NEVER from applets.h for this to work 284 // Need to remove SUID_NEVER from applets.h for this to work
285 //xsetuid(getuid()); 285 //xsetuid(getuid());
286 286
287 err_str = xasprintf("interface %s %%s", device);
288 { 287 {
289 unsigned opt; 288 unsigned opt;
290 char *str_timeout; 289 char *str_timeout;
@@ -302,7 +301,7 @@ int arping_main(int argc UNUSED_PARAM, char **argv)
302 } 301 }
303 302
304 target = argv[optind]; 303 target = argv[optind];
305 304 err_str = xasprintf("interface %s %%s", device);
306 xfunc_error_retval = 2; 305 xfunc_error_retval = 2;
307 306
308 { 307 {
diff --git a/networking/dnsd.c b/networking/dnsd.c
index fe98400f7..923ad6bc6 100644
--- a/networking/dnsd.c
+++ b/networking/dnsd.c
@@ -194,7 +194,7 @@ static char *table_lookup(struct dns_entry *d,
194 if ((len != 1 || d->name[1] != '*') 194 if ((len != 1 || d->name[1] != '*')
195 /* we assume (do not check) that query_string 195 /* we assume (do not check) that query_string
196 * ends in ".in-addr.arpa" */ 196 * ends in ".in-addr.arpa" */
197 && strncmp(d->rip, query_string, strlen(d->rip)) == 0 197 && is_prefixed_with(query_string, d->rip)
198 ) { 198 ) {
199#if DEBUG 199#if DEBUG
200 fprintf(stderr, "Found name:%s\n", d->name); 200 fprintf(stderr, "Found name:%s\n", d->name);
diff --git a/networking/ftpd.c b/networking/ftpd.c
index 6adcb1dee..0c10e1f25 100644
--- a/networking/ftpd.c
+++ b/networking/ftpd.c
@@ -1174,8 +1174,13 @@ int ftpd_main(int argc UNUSED_PARAM, char **argv)
1174 1174
1175 //umask(077); - admin can set umask before starting us 1175 //umask(077); - admin can set umask before starting us
1176 1176
1177 /* Signals. We'll always take -EPIPE rather than a rude signal, thanks */ 1177 /* Signals */
1178 signal(SIGPIPE, SIG_IGN); 1178 bb_signals(0
1179 /* We'll always take EPIPE rather than a rude signal, thanks */
1180 + (1 << SIGPIPE)
1181 /* LIST command spawns chilren. Prevent zombies */
1182 + (1 << SIGCHLD)
1183 , SIG_IGN);
1179 1184
1180 /* Set up options on the command socket (do we need these all? why?) */ 1185 /* Set up options on the command socket (do we need these all? why?) */
1181 setsockopt(STDIN_FILENO, IPPROTO_TCP, TCP_NODELAY, &const_int_1, sizeof(const_int_1)); 1186 setsockopt(STDIN_FILENO, IPPROTO_TCP, TCP_NODELAY, &const_int_1, sizeof(const_int_1));
diff --git a/networking/httpd.c b/networking/httpd.c
index 9cf080401..7a9065fcc 100644
--- a/networking/httpd.c
+++ b/networking/httpd.c
@@ -697,7 +697,7 @@ static void parse_conf(const char *path, int flag)
697 goto config_error; 697 goto config_error;
698 } 698 }
699 *host_port++ = '\0'; 699 *host_port++ = '\0';
700 if (strncmp(host_port, "http://", 7) == 0) 700 if (is_prefixed_with(host_port, "http://"))
701 host_port += 7; 701 host_port += 7;
702 if (*host_port == '\0') { 702 if (*host_port == '\0') {
703 goto config_error; 703 goto config_error;
@@ -1894,7 +1894,7 @@ static Htaccess_Proxy *find_proxy_entry(const char *url)
1894{ 1894{
1895 Htaccess_Proxy *p; 1895 Htaccess_Proxy *p;
1896 for (p = proxy; p; p = p->next) { 1896 for (p = proxy; p; p = p->next) {
1897 if (strncmp(url, p->url_from, strlen(p->url_from)) == 0) 1897 if (is_prefixed_with(url, p->url_from))
1898 return p; 1898 return p;
1899 } 1899 }
1900 return NULL; 1900 return NULL;
@@ -2183,7 +2183,7 @@ static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
2183 if (STRNCASECMP(iobuf, "Range:") == 0) { 2183 if (STRNCASECMP(iobuf, "Range:") == 0) {
2184 /* We know only bytes=NNN-[MMM] */ 2184 /* We know only bytes=NNN-[MMM] */
2185 char *s = skip_whitespace(iobuf + sizeof("Range:")-1); 2185 char *s = skip_whitespace(iobuf + sizeof("Range:")-1);
2186 if (strncmp(s, "bytes=", 6) == 0) { 2186 if (is_prefixed_with(s, "bytes=") == 0) {
2187 s += sizeof("bytes=")-1; 2187 s += sizeof("bytes=")-1;
2188 range_start = BB_STRTOOFF(s, &s, 10); 2188 range_start = BB_STRTOOFF(s, &s, 10);
2189 if (s[0] != '-' || range_start < 0) { 2189 if (s[0] != '-' || range_start < 0) {
@@ -2269,7 +2269,7 @@ static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
2269 tptr = urlcopy + 1; /* skip first '/' */ 2269 tptr = urlcopy + 1; /* skip first '/' */
2270 2270
2271#if ENABLE_FEATURE_HTTPD_CGI 2271#if ENABLE_FEATURE_HTTPD_CGI
2272 if (strncmp(tptr, "cgi-bin/", 8) == 0) { 2272 if (is_prefixed_with(tptr, "cgi-bin/")) {
2273 if (tptr[8] == '\0') { 2273 if (tptr[8] == '\0') {
2274 /* protect listing "cgi-bin/" */ 2274 /* protect listing "cgi-bin/" */
2275 send_headers_and_exit(HTTP_FORBIDDEN); 2275 send_headers_and_exit(HTTP_FORBIDDEN);
diff --git a/networking/ifupdown.c b/networking/ifupdown.c
index c35d97a1a..daabeec0c 100644
--- a/networking/ifupdown.c
+++ b/networking/ifupdown.c
@@ -289,7 +289,7 @@ static char *parse(const char *command, struct interface_defn_t *ifd)
289 /* "hwaddress <class> <address>": 289 /* "hwaddress <class> <address>":
290 * unlike ifconfig, ip doesnt want <class> 290 * unlike ifconfig, ip doesnt want <class>
291 * (usually "ether" keyword). Skip it. */ 291 * (usually "ether" keyword). Skip it. */
292 if (strncmp(command, "hwaddress", 9) == 0) { 292 if (is_prefixed_with(command, "hwaddress")) {
293 varvalue = skip_whitespace(skip_non_whitespace(varvalue)); 293 varvalue = skip_whitespace(skip_non_whitespace(varvalue));
294 } 294 }
295# endif 295# endif
@@ -298,7 +298,7 @@ static char *parse(const char *command, struct interface_defn_t *ifd)
298# if ENABLE_FEATURE_IFUPDOWN_IP 298# if ENABLE_FEATURE_IFUPDOWN_IP
299 /* Sigh... Add a special case for 'ip' to convert from 299 /* Sigh... Add a special case for 'ip' to convert from
300 * dotted quad to bit count style netmasks. */ 300 * dotted quad to bit count style netmasks. */
301 if (strncmp(command, "bnmask", 6) == 0) { 301 if (is_prefixed_with(command, "bnmask")) {
302 unsigned res; 302 unsigned res;
303 varvalue = get_var("netmask", 7, ifd); 303 varvalue = get_var("netmask", 7, ifd);
304 if (varvalue) { 304 if (varvalue) {
@@ -1159,12 +1159,12 @@ static char *run_mapping(char *physical, struct mapping_defn_t *map)
1159 1159
1160static llist_t *find_iface_state(llist_t *state_list, const char *iface) 1160static llist_t *find_iface_state(llist_t *state_list, const char *iface)
1161{ 1161{
1162 unsigned iface_len = strlen(iface);
1163 llist_t *search = state_list; 1162 llist_t *search = state_list;
1164 1163
1165 while (search) { 1164 while (search) {
1166 if ((strncmp(search->data, iface, iface_len) == 0) 1165 char *after_iface = is_prefixed_with(search->data, iface);
1167 && (search->data[iface_len] == '=') 1166 if (after_iface
1167 && *after_iface == '='
1168 ) { 1168 ) {
1169 return search; 1169 return search;
1170 } 1170 }
diff --git a/networking/inetd.c b/networking/inetd.c
index 584c5e5e4..dce5a0885 100644
--- a/networking/inetd.c
+++ b/networking/inetd.c
@@ -645,7 +645,7 @@ static servtab_t *dup_servtab(servtab_t *sep)
645} 645}
646 646
647/* gcc generates much more code if this is inlined */ 647/* gcc generates much more code if this is inlined */
648static servtab_t *parse_one_line(void) 648static NOINLINE servtab_t *parse_one_line(void)
649{ 649{
650 int argc; 650 int argc;
651 char *token[6+MAXARGV]; 651 char *token[6+MAXARGV];
@@ -675,6 +675,8 @@ static servtab_t *parse_one_line(void)
675 * default host for the following lines. */ 675 * default host for the following lines. */
676 free(default_local_hostname); 676 free(default_local_hostname);
677 default_local_hostname = sep->se_local_hostname; 677 default_local_hostname = sep->se_local_hostname;
678 /*sep->se_local_hostname = NULL; - redundant */
679 /* (we'll overwrite this field anyway) */
678 goto more; 680 goto more;
679 } 681 }
680 } else 682 } else
@@ -688,10 +690,10 @@ static servtab_t *parse_one_line(void)
688 parse_err: 690 parse_err:
689 bb_error_msg("parse error on line %u, line is ignored", 691 bb_error_msg("parse error on line %u, line is ignored",
690 parser->lineno); 692 parser->lineno);
691 free_servtab_strings(sep);
692 /* Just "goto more" can make sep to carry over e.g. 693 /* Just "goto more" can make sep to carry over e.g.
693 * "rpc"-ness (by having se_rpcver_lo != 0). 694 * "rpc"-ness (by having se_rpcver_lo != 0).
694 * We will be more paranoid: */ 695 * We will be more paranoid: */
696 free_servtab_strings(sep);
695 free(sep); 697 free(sep);
696 goto new; 698 goto new;
697 } 699 }
@@ -725,7 +727,7 @@ static servtab_t *parse_one_line(void)
725 goto parse_err; 727 goto parse_err;
726#endif 728#endif
727 } 729 }
728 if (strncmp(arg, "rpc/", 4) == 0) { 730 if (is_prefixed_with(arg, "rpc/")) {
729#if ENABLE_FEATURE_INETD_RPC 731#if ENABLE_FEATURE_INETD_RPC
730 unsigned n; 732 unsigned n;
731 arg += 4; 733 arg += 4;
@@ -815,7 +817,7 @@ static servtab_t *parse_one_line(void)
815 } 817 }
816#endif 818#endif
817 argc = 0; 819 argc = 0;
818 while ((arg = token[6+argc]) != NULL && argc < MAXARGV) 820 while (argc < MAXARGV && (arg = token[6+argc]) != NULL)
819 sep->se_argv[argc++] = xstrdup(arg); 821 sep->se_argv[argc++] = xstrdup(arg);
820 /* Some inetd.conf files have no argv's, not even argv[0]. 822 /* Some inetd.conf files have no argv's, not even argv[0].
821 * Fix them up. 823 * Fix them up.
@@ -1654,7 +1656,7 @@ static void FAST_FUNC daytime_stream(int s, servtab_t *sep UNUSED_PARAM)
1654{ 1656{
1655 time_t t; 1657 time_t t;
1656 1658
1657 t = time(NULL); 1659 time(&t);
1658 fdprintf(s, "%.24s\r\n", ctime(&t)); 1660 fdprintf(s, "%.24s\r\n", ctime(&t));
1659} 1661}
1660static void FAST_FUNC daytime_dg(int s, servtab_t *sep) 1662static void FAST_FUNC daytime_dg(int s, servtab_t *sep)
diff --git a/networking/interface.c b/networking/interface.c
index bf7d2b1b4..b0572d04e 100644
--- a/networking/interface.c
+++ b/networking/interface.c
@@ -91,9 +91,9 @@ static const char* FAST_FUNC INET_sprint(struct sockaddr *sap, int numeric)
91{ 91{
92 static char *buff; /* defaults to NULL */ 92 static char *buff; /* defaults to NULL */
93 93
94 free(buff);
95 if (sap->sa_family == 0xFFFF || sap->sa_family == 0) 94 if (sap->sa_family == 0xFFFF || sap->sa_family == 0)
96 return "[NONE SET]"; 95 return "[NONE SET]";
96 free(buff);
97 buff = INET_rresolve((struct sockaddr_in *) sap, numeric, 0xffffff00); 97 buff = INET_rresolve((struct sockaddr_in *) sap, numeric, 0xffffff00);
98 return buff; 98 return buff;
99} 99}
@@ -173,9 +173,9 @@ static const char* FAST_FUNC INET6_sprint(struct sockaddr *sap, int numeric)
173{ 173{
174 static char *buff; 174 static char *buff;
175 175
176 free(buff);
177 if (sap->sa_family == 0xFFFF || sap->sa_family == 0) 176 if (sap->sa_family == 0xFFFF || sap->sa_family == 0)
178 return "[NONE SET]"; 177 return "[NONE SET]";
178 free(buff);
179 buff = INET6_rresolve((struct sockaddr_in6 *) sap, numeric); 179 buff = INET6_rresolve((struct sockaddr_in6 *) sap, numeric);
180 return buff; 180 return buff;
181} 181}
diff --git a/networking/libiproute/ipaddress.c b/networking/libiproute/ipaddress.c
index aa4779ad1..4072d0626 100644
--- a/networking/libiproute/ipaddress.c
+++ b/networking/libiproute/ipaddress.c
@@ -701,7 +701,7 @@ static int ipaddr_modify(int cmd, char **argv)
701 /* There was no "dev IFACE", but we need that */ 701 /* There was no "dev IFACE", but we need that */
702 bb_error_msg_and_die("need \"dev IFACE\""); 702 bb_error_msg_and_die("need \"dev IFACE\"");
703 } 703 }
704 if (l && strncmp(d, l, strlen(d)) != 0) { 704 if (l && !is_prefixed_with(l, d)) {
705 bb_error_msg_and_die("\"dev\" (%s) must match \"label\" (%s)", d, l); 705 bb_error_msg_and_die("\"dev\" (%s) must match \"label\" (%s)", d, l);
706 } 706 }
707 707
diff --git a/networking/nameif.c b/networking/nameif.c
index 9a8846dc0..9b18a6d16 100644
--- a/networking/nameif.c
+++ b/networking/nameif.c
@@ -161,19 +161,19 @@ static void nameif_parse_selector(ethtable_t *ch, char *selector)
161 if (*next) 161 if (*next)
162 *next++ = '\0'; 162 *next++ = '\0';
163 /* Check for selectors, mac= is assumed */ 163 /* Check for selectors, mac= is assumed */
164 if (strncmp(selector, "bus=", 4) == 0) { 164 if (is_prefixed_with(selector, "bus=")) {
165 ch->bus_info = xstrdup(selector + 4); 165 ch->bus_info = xstrdup(selector + 4);
166 found_selector++; 166 found_selector++;
167 } else if (strncmp(selector, "driver=", 7) == 0) { 167 } else if (is_prefixed_with(selector, "driver=")) {
168 ch->driver = xstrdup(selector + 7); 168 ch->driver = xstrdup(selector + 7);
169 found_selector++; 169 found_selector++;
170 } else if (strncmp(selector, "phyaddr=", 8) == 0) { 170 } else if (is_prefixed_with(selector, "phyaddr=")) {
171 ch->phy_address = xatoi_positive(selector + 8); 171 ch->phy_address = xatoi_positive(selector + 8);
172 found_selector++; 172 found_selector++;
173 } else { 173 } else {
174#endif 174#endif
175 lmac = xmalloc(ETH_ALEN); 175 lmac = xmalloc(ETH_ALEN);
176 ch->mac = ether_aton_r(selector + (strncmp(selector, "mac=", 4) != 0 ? 0 : 4), lmac); 176 ch->mac = ether_aton_r(selector + (is_prefixed_with(selector, "mac=") ? 4 : 0), lmac);
177 if (ch->mac == NULL) 177 if (ch->mac == NULL)
178 bb_error_msg_and_die("can't parse %s", selector); 178 bb_error_msg_and_die("can't parse %s", selector);
179#if ENABLE_FEATURE_NAMEIF_EXTENDED 179#if ENABLE_FEATURE_NAMEIF_EXTENDED
diff --git a/networking/netstat.c b/networking/netstat.c
index f80b845bc..1303d3f3d 100644
--- a/networking/netstat.c
+++ b/networking/netstat.c
@@ -228,12 +228,12 @@ static long extract_socket_inode(const char *lname)
228{ 228{
229 long inode = -1; 229 long inode = -1;
230 230
231 if (strncmp(lname, "socket:[", sizeof("socket:[")-1) == 0) { 231 if (is_prefixed_with(lname, "socket:[")) {
232 /* "socket:[12345]", extract the "12345" as inode */ 232 /* "socket:[12345]", extract the "12345" as inode */
233 inode = bb_strtoul(lname + sizeof("socket:[")-1, (char**)&lname, 0); 233 inode = bb_strtoul(lname + sizeof("socket:[")-1, (char**)&lname, 0);
234 if (*lname != ']') 234 if (*lname != ']')
235 inode = -1; 235 inode = -1;
236 } else if (strncmp(lname, "[0000]:", sizeof("[0000]:")-1) == 0) { 236 } else if (is_prefixed_with(lname, "[0000]:")) {
237 /* "[0000]:12345", extract the "12345" as inode */ 237 /* "[0000]:12345", extract the "12345" as inode */
238 inode = bb_strtoul(lname + sizeof("[0000]:")-1, NULL, 0); 238 inode = bb_strtoul(lname + sizeof("[0000]:")-1, NULL, 0);
239 if (errno) /* not NUL terminated? */ 239 if (errno) /* not NUL terminated? */
@@ -622,7 +622,7 @@ static int FAST_FUNC unix_do_one(char *line)
622 622
623 /* TODO: currently we stop at first NUL byte. Is it a problem? */ 623 /* TODO: currently we stop at first NUL byte. Is it a problem? */
624 line += path_ofs; 624 line += path_ofs;
625 *strchrnul(line, '\n') = '\0'; 625 chomp(line);
626 while (*line) 626 while (*line)
627 fputc_printable(*line++, stdout); 627 fputc_printable(*line++, stdout);
628 bb_putchar('\n'); 628 bb_putchar('\n');
diff --git a/networking/ntpd.c b/networking/ntpd.c
index 2d4f076d9..0233ed82c 100644
--- a/networking/ntpd.c
+++ b/networking/ntpd.c
@@ -1,30 +1,43 @@
1/* 1/*
2 * NTP client/server, based on OpenNTPD 3.9p1 2 * NTP client/server, based on OpenNTPD 3.9p1
3 * 3 *
4 * Author: Adam Tkac <vonsch@gmail.com> 4 * Busybox port author: Adam Tkac (C) 2009 <vonsch@gmail.com>
5 * 5 *
6 * Licensed under GPLv2, see file LICENSE in this source tree. 6 * OpenNTPd 3.9p1 copyright holders:
7 * Copyright (c) 2003, 2004 Henning Brauer <henning@openbsd.org>
8 * Copyright (c) 2004 Alexander Guy <alexander.guy@andern.org>
9 *
10 * OpenNTPd code is licensed under ISC-style licence:
11 *
12 * Permission to use, copy, modify, and distribute this software for any
13 * purpose with or without fee is hereby granted, provided that the above
14 * copyright notice and this permission notice appear in all copies.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
17 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
19 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
20 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
21 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
22 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
23 ***********************************************************************
7 * 24 *
8 * Parts of OpenNTPD clock syncronization code is replaced by 25 * Parts of OpenNTPD clock syncronization code is replaced by
9 * code which is based on ntp-4.2.6, whuch carries the following 26 * code which is based on ntp-4.2.6, which carries the following
10 * copyright notice: 27 * copyright notice:
11 * 28 *
12 *********************************************************************** 29 * Copyright (c) University of Delaware 1992-2009
13 * * 30 *
14 * Copyright (c) University of Delaware 1992-2009 * 31 * Permission to use, copy, modify, and distribute this software and
15 * * 32 * its documentation for any purpose with or without fee is hereby
16 * Permission to use, copy, modify, and distribute this software and * 33 * granted, provided that the above copyright notice appears in all
17 * its documentation for any purpose with or without fee is hereby * 34 * copies and that both the copyright notice and this permission
18 * granted, provided that the above copyright notice appears in all * 35 * notice appear in supporting documentation, and that the name
19 * copies and that both the copyright notice and this permission * 36 * University of Delaware not be used in advertising or publicity
20 * notice appear in supporting documentation, and that the name * 37 * pertaining to distribution of the software without specific,
21 * University of Delaware not be used in advertising or publicity * 38 * written prior permission. The University of Delaware makes no
22 * pertaining to distribution of the software without specific, * 39 * representations about the suitability this software for any
23 * written prior permission. The University of Delaware makes no * 40 * purpose. It is provided "as is" without express or implied warranty.
24 * representations about the suitability this software for any *
25 * purpose. It is provided "as is" without express or implied *
26 * warranty. *
27 * *
28 *********************************************************************** 41 ***********************************************************************
29 */ 42 */
30 43
@@ -37,14 +50,15 @@
37//usage: "\n -q Quit after clock is set" 50//usage: "\n -q Quit after clock is set"
38//usage: "\n -N Run at high priority" 51//usage: "\n -N Run at high priority"
39//usage: "\n -w Do not set time (only query peers), implies -n" 52//usage: "\n -w Do not set time (only query peers), implies -n"
40//usage: IF_FEATURE_NTPD_SERVER(
41//usage: "\n -l Run as server on port 123"
42//usage: "\n -I IFACE Bind server to IFACE, implies -l"
43//usage: )
44//usage: "\n -S PROG Run PROG after stepping time, stratum change, and every 11 mins" 53//usage: "\n -S PROG Run PROG after stepping time, stratum change, and every 11 mins"
45//usage: "\n -p PEER Obtain time from PEER (may be repeated)" 54//usage: "\n -p PEER Obtain time from PEER (may be repeated)"
46//usage: IF_FEATURE_NTPD_CONF( 55//usage: IF_FEATURE_NTPD_CONF(
47//usage: "\n If -p is not given, read /etc/ntp.conf" 56//usage: "\n If -p is not given, 'server HOST' lines"
57//usage: "\n from /etc/ntp.conf are used"
58//usage: )
59//usage: IF_FEATURE_NTPD_SERVER(
60//usage: "\n -l Also run as server on port 123"
61//usage: "\n -I IFACE Bind server to IFACE, implies -l"
48//usage: ) 62//usage: )
49 63
50// -l and -p options are not compatible with "standard" ntpd: 64// -l and -p options are not compatible with "standard" ntpd:
@@ -363,8 +377,6 @@ struct globals {
363 */ 377 */
364#define G_precision_sec 0.002 378#define G_precision_sec 0.002
365 uint8_t stratum; 379 uint8_t stratum;
366 /* Bool. After set to 1, never goes back to 0: */
367 smallint initial_poll_complete;
368 380
369#define STATE_NSET 0 /* initial state, "nothing is set" */ 381#define STATE_NSET 0 /* initial state, "nothing is set" */
370//#define STATE_FSET 1 /* frequency set from file */ 382//#define STATE_FSET 1 /* frequency set from file */
@@ -1071,7 +1083,7 @@ select_and_cluster(void)
1071 1083
1072 num_points = 0; 1084 num_points = 0;
1073 item = G.ntp_peers; 1085 item = G.ntp_peers;
1074 if (G.initial_poll_complete) while (item != NULL) { 1086 while (item != NULL) {
1075 double rd, offset; 1087 double rd, offset;
1076 1088
1077 p = (peer_t *) item->data; 1089 p = (peer_t *) item->data;
@@ -1636,7 +1648,7 @@ update_local_clock(peer_t *p)
1636 if (G.ntp_status & LI_MINUSSEC) 1648 if (G.ntp_status & LI_MINUSSEC)
1637 tmx.status |= STA_DEL; 1649 tmx.status |= STA_DEL;
1638 1650
1639 tmx.constant = G.poll_exp - 4; 1651 tmx.constant = (int)G.poll_exp - 4 > 0 ? (int)G.poll_exp - 4 : 0;
1640 /* EXPERIMENTAL. 1652 /* EXPERIMENTAL.
1641 * The below if statement should be unnecessary, but... 1653 * The below if statement should be unnecessary, but...
1642 * It looks like Linux kernel's PLL is far too gentle in changing 1654 * It looks like Linux kernel's PLL is far too gentle in changing
@@ -2272,7 +2284,6 @@ int ntpd_main(int argc UNUSED_PARAM, char **argv)
2272 VERB4 bb_error_msg("disabling burst mode"); 2284 VERB4 bb_error_msg("disabling burst mode");
2273 G.polladj_count = 0; 2285 G.polladj_count = 0;
2274 G.poll_exp = MINPOLL; 2286 G.poll_exp = MINPOLL;
2275 G.initial_poll_complete = 1;
2276 } 2287 }
2277 send_query_to_peer(p); 2288 send_query_to_peer(p);
2278 } else { 2289 } else {
diff --git a/networking/ntpd_simple.c b/networking/ntpd_simple.c
deleted file mode 100644
index 2cfbd55d4..000000000
--- a/networking/ntpd_simple.c
+++ /dev/null
@@ -1,1005 +0,0 @@
1/*
2 * NTP client/server, based on OpenNTPD 3.9p1
3 *
4 * Author: Adam Tkac <vonsch@gmail.com>
5 *
6 * Licensed under GPLv2, see file LICENSE in this source tree.
7 */
8#include "libbb.h"
9#include <netinet/ip.h> /* For IPTOS_LOWDELAY definition */
10#include <sys/resource.h> /* setpriority */
11#ifndef IPTOS_LOWDELAY
12# define IPTOS_LOWDELAY 0x10
13#endif
14
15
16/* Sync to peers every N secs */
17#define INTERVAL_QUERY_NORMAL 30
18#define INTERVAL_QUERY_PATHETIC 60
19#define INTERVAL_QUERY_AGRESSIVE 5
20
21/* Bad if *less than* TRUSTLEVEL_BADPEER */
22#define TRUSTLEVEL_BADPEER 6
23#define TRUSTLEVEL_PATHETIC 2
24#define TRUSTLEVEL_AGRESSIVE 8
25#define TRUSTLEVEL_MAX 10
26
27#define QSCALE_OFF_MIN 0.05
28#define QSCALE_OFF_MAX 0.50
29
30/* Single query might take N secs max */
31#define QUERYTIME_MAX 15
32/* Min offset for settime at start. "man ntpd" says it's 128 ms */
33#define STEPTIME_MIN_OFFSET 0.128
34
35typedef struct {
36 uint32_t int_partl;
37 uint32_t fractionl;
38} l_fixedpt_t;
39
40typedef struct {
41 uint16_t int_parts;
42 uint16_t fractions;
43} s_fixedpt_t;
44
45enum {
46 NTP_DIGESTSIZE = 16,
47 NTP_MSGSIZE_NOAUTH = 48,
48 NTP_MSGSIZE = (NTP_MSGSIZE_NOAUTH + 4 + NTP_DIGESTSIZE),
49};
50
51typedef struct {
52 uint8_t m_status; /* status of local clock and leap info */
53 uint8_t m_stratum; /* stratum level */
54 uint8_t m_ppoll; /* poll value */
55 int8_t m_precision_exp;
56 s_fixedpt_t m_rootdelay;
57 s_fixedpt_t m_dispersion;
58 uint32_t m_refid;
59 l_fixedpt_t m_reftime;
60 l_fixedpt_t m_orgtime;
61 l_fixedpt_t m_rectime;
62 l_fixedpt_t m_xmttime;
63 uint32_t m_keyid;
64 uint8_t m_digest[NTP_DIGESTSIZE];
65} msg_t;
66
67enum {
68 NTP_VERSION = 4,
69 NTP_MAXSTRATUM = 15,
70
71 /* Status Masks */
72 MODE_MASK = (7 << 0),
73 VERSION_MASK = (7 << 3),
74 VERSION_SHIFT = 3,
75 LI_MASK = (3 << 6),
76
77 /* Leap Second Codes (high order two bits of m_status) */
78 LI_NOWARNING = (0 << 6), /* no warning */
79 LI_PLUSSEC = (1 << 6), /* add a second (61 seconds) */
80 LI_MINUSSEC = (2 << 6), /* minus a second (59 seconds) */
81 LI_ALARM = (3 << 6), /* alarm condition */
82
83 /* Mode values */
84 MODE_RES0 = 0, /* reserved */
85 MODE_SYM_ACT = 1, /* symmetric active */
86 MODE_SYM_PAS = 2, /* symmetric passive */
87 MODE_CLIENT = 3, /* client */
88 MODE_SERVER = 4, /* server */
89 MODE_BROADCAST = 5, /* broadcast */
90 MODE_RES1 = 6, /* reserved for NTP control message */
91 MODE_RES2 = 7, /* reserved for private use */
92};
93
94#define OFFSET_1900_1970 2208988800UL /* 1970 - 1900 in seconds */
95
96typedef struct {
97 double d_offset;
98 double d_delay;
99 //UNUSED: double d_error;
100 time_t d_rcv_time;
101 uint32_t d_refid4;
102 uint8_t d_leap;
103 uint8_t d_stratum;
104 uint8_t d_good;
105} datapoint_t;
106
107#define NUM_DATAPOINTS 8
108typedef struct {
109 len_and_sockaddr *p_lsa;
110 char *p_dotted;
111 /* When to send new query (if p_fd == -1)
112 * or when receive times out (if p_fd >= 0): */
113 time_t next_action_time;
114 int p_fd;
115 uint8_t p_datapoint_idx;
116 uint8_t p_trustlevel;
117 double p_xmttime;
118 datapoint_t update;
119 datapoint_t p_datapoint[NUM_DATAPOINTS];
120 msg_t p_xmt_msg;
121} peer_t;
122
123enum {
124 OPT_n = (1 << 0),
125 OPT_q = (1 << 1),
126 OPT_N = (1 << 2),
127 OPT_x = (1 << 3),
128 /* Insert new options above this line. */
129 /* Non-compat options: */
130 OPT_p = (1 << 4),
131 OPT_l = (1 << 5) * ENABLE_FEATURE_NTPD_SERVER,
132};
133
134
135struct globals {
136 /* total round trip delay to currently selected reference clock */
137 double rootdelay;
138 /* reference timestamp: time when the system clock was last set or corrected */
139 double reftime;
140 llist_t *ntp_peers;
141#if ENABLE_FEATURE_NTPD_SERVER
142 int listen_fd;
143#endif
144 unsigned verbose;
145 unsigned peer_cnt;
146 unsigned scale;
147 uint32_t refid;
148 uint32_t refid4;
149 uint8_t synced;
150 uint8_t leap;
151#define G_precision_exp -6
152// int8_t precision_exp;
153 uint8_t stratum;
154 uint8_t time_was_stepped;
155 uint8_t first_adj_done;
156};
157#define G (*ptr_to_globals)
158
159static const int const_IPTOS_LOWDELAY = IPTOS_LOWDELAY;
160
161
162static void
163set_next(peer_t *p, unsigned t)
164{
165 p->next_action_time = time(NULL) + t;
166}
167
168static void
169add_peers(char *s)
170{
171 peer_t *p;
172
173 p = xzalloc(sizeof(*p));
174 p->p_lsa = xhost2sockaddr(s, 123);
175 p->p_dotted = xmalloc_sockaddr2dotted_noport(&p->p_lsa->u.sa);
176 p->p_fd = -1;
177 p->p_xmt_msg.m_status = MODE_CLIENT | (NTP_VERSION << 3);
178 p->p_trustlevel = TRUSTLEVEL_PATHETIC;
179 p->next_action_time = time(NULL); /* = set_next(p, 0); */
180
181 llist_add_to(&G.ntp_peers, p);
182 G.peer_cnt++;
183}
184
185static double
186gettime1900d(void)
187{
188 struct timeval tv;
189 gettimeofday(&tv, NULL); /* never fails */
190 return (tv.tv_sec + 1.0e-6 * tv.tv_usec + OFFSET_1900_1970);
191}
192
193static void
194d_to_tv(double d, struct timeval *tv)
195{
196 tv->tv_sec = (long)d;
197 tv->tv_usec = (d - tv->tv_sec) * 1000000;
198}
199
200static double
201lfp_to_d(l_fixedpt_t lfp)
202{
203 double ret;
204 lfp.int_partl = ntohl(lfp.int_partl);
205 lfp.fractionl = ntohl(lfp.fractionl);
206 ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
207 return ret;
208}
209
210#if 0 //UNUSED
211static double
212sfp_to_d(s_fixedpt_t sfp)
213{
214 double ret;
215 sfp.int_parts = ntohs(sfp.int_parts);
216 sfp.fractions = ntohs(sfp.fractions);
217 ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
218 return ret;
219}
220#endif
221
222#if ENABLE_FEATURE_NTPD_SERVER
223static l_fixedpt_t
224d_to_lfp(double d)
225{
226 l_fixedpt_t lfp;
227 lfp.int_partl = (uint32_t)d;
228 lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
229 lfp.int_partl = htonl(lfp.int_partl);
230 lfp.fractionl = htonl(lfp.fractionl);
231 return lfp;
232}
233
234static s_fixedpt_t
235d_to_sfp(double d)
236{
237 s_fixedpt_t sfp;
238 sfp.int_parts = (uint16_t)d;
239 sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
240 sfp.int_parts = htons(sfp.int_parts);
241 sfp.fractions = htons(sfp.fractions);
242 return sfp;
243}
244#endif
245
246static unsigned
247error_interval(void)
248{
249 unsigned interval, r;
250 interval = INTERVAL_QUERY_PATHETIC * QSCALE_OFF_MAX / QSCALE_OFF_MIN;
251 r = (unsigned)rand() % (unsigned)(interval / 10);
252 return (interval + r);
253}
254
255static int
256do_sendto(int fd,
257 const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
258 msg_t *msg, ssize_t len)
259{
260 ssize_t ret;
261
262 errno = 0;
263 if (!from) {
264 ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
265 } else {
266 ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
267 }
268 if (ret != len) {
269 bb_perror_msg("send failed");
270 return -1;
271 }
272 return 0;
273}
274
275static int
276send_query_to_peer(peer_t *p)
277{
278 // Why do we need to bind()?
279 // See what happens when we don't bind:
280 //
281 // socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
282 // setsockopt(3, SOL_IP, IP_TOS, [16], 4) = 0
283 // gettimeofday({1259071266, 327885}, NULL) = 0
284 // sendto(3, "xxx", 48, MSG_DONTWAIT, {sa_family=AF_INET, sin_port=htons(123), sin_addr=inet_addr("10.34.32.125")}, 16) = 48
285 // ^^^ we sent it from some source port picked by kernel.
286 // time(NULL) = 1259071266
287 // write(2, "ntpd: entering poll 15 secs\n", 28) = 28
288 // poll([{fd=3, events=POLLIN}], 1, 15000) = 1 ([{fd=3, revents=POLLIN}])
289 // recv(3, "yyy", 68, MSG_DONTWAIT) = 48
290 // ^^^ this recv will receive packets to any local port!
291 //
292 // Uncomment this and use strace to see it in action:
293#define PROBE_LOCAL_ADDR // { len_and_sockaddr lsa; lsa.len = LSA_SIZEOF_SA; getsockname(p->query.fd, &lsa.u.sa, &lsa.len); }
294
295 if (p->p_fd == -1) {
296 int fd, family;
297 len_and_sockaddr *local_lsa;
298
299 family = p->p_lsa->u.sa.sa_family;
300 p->p_fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
301 /* local_lsa has "null" address and port 0 now.
302 * bind() ensures we have a *particular port* selected by kernel
303 * and remembered in p->p_fd, thus later recv(p->p_fd)
304 * receives only packets sent to this port.
305 */
306 PROBE_LOCAL_ADDR
307 xbind(fd, &local_lsa->u.sa, local_lsa->len);
308 PROBE_LOCAL_ADDR
309#if ENABLE_FEATURE_IPV6
310 if (family == AF_INET)
311#endif
312 setsockopt(fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
313 free(local_lsa);
314 }
315
316 /*
317 * Send out a random 64-bit number as our transmit time. The NTP
318 * server will copy said number into the originate field on the
319 * response that it sends us. This is totally legal per the SNTP spec.
320 *
321 * The impact of this is two fold: we no longer send out the current
322 * system time for the world to see (which may aid an attacker), and
323 * it gives us a (not very secure) way of knowing that we're not
324 * getting spoofed by an attacker that can't capture our traffic
325 * but can spoof packets from the NTP server we're communicating with.
326 *
327 * Save the real transmit timestamp locally.
328 */
329 p->p_xmt_msg.m_xmttime.int_partl = rand();
330 p->p_xmt_msg.m_xmttime.fractionl = rand();
331 p->p_xmttime = gettime1900d();
332
333 if (do_sendto(p->p_fd, /*from:*/ NULL, /*to:*/ &p->p_lsa->u.sa, /*addrlen:*/ p->p_lsa->len,
334 &p->p_xmt_msg, NTP_MSGSIZE_NOAUTH) == -1
335 ) {
336 close(p->p_fd);
337 p->p_fd = -1;
338 set_next(p, INTERVAL_QUERY_PATHETIC);
339 return -1;
340 }
341
342 if (G.verbose)
343 bb_error_msg("sent query to %s", p->p_dotted);
344 set_next(p, QUERYTIME_MAX);
345
346 return 0;
347}
348
349
350/* Time is stepped only once, when the first packet from a peer is received.
351 */
352static void
353step_time_once(double offset)
354{
355 double dtime;
356 llist_t *item;
357 struct timeval tv;
358 char buf[80];
359 time_t tval;
360
361 if (G.time_was_stepped)
362 goto bail;
363 G.time_was_stepped = 1;
364
365 /* if the offset is small, don't step, slew (later) */
366 if (offset < STEPTIME_MIN_OFFSET && offset > -STEPTIME_MIN_OFFSET)
367 goto bail;
368
369 gettimeofday(&tv, NULL); /* never fails */
370 dtime = offset + tv.tv_sec;
371 dtime += 1.0e-6 * tv.tv_usec;
372 d_to_tv(dtime, &tv);
373
374 if (settimeofday(&tv, NULL) == -1)
375 bb_perror_msg_and_die("settimeofday");
376
377 tval = tv.tv_sec;
378 strftime_YYYYMMDDHHMMSS(buf, sizeof(buf), &tval);
379
380 bb_error_msg("setting clock to %s (offset %fs)", buf, offset);
381
382 for (item = G.ntp_peers; item != NULL; item = item->link) {
383 peer_t *p = (peer_t *) item->data;
384 p->next_action_time -= (time_t)offset;
385 }
386
387 bail:
388 if (option_mask32 & OPT_q)
389 exit(0);
390}
391
392
393/* Time is periodically slewed when we collect enough
394 * good data points.
395 */
396static int
397compare_offsets(const void *aa, const void *bb)
398{
399 const peer_t *const *a = aa;
400 const peer_t *const *b = bb;
401 if ((*a)->update.d_offset < (*b)->update.d_offset)
402 return -1;
403 return ((*a)->update.d_offset > (*b)->update.d_offset);
404}
405static unsigned
406updated_scale(double offset)
407{
408 if (offset < 0)
409 offset = -offset;
410 if (offset > QSCALE_OFF_MAX)
411 return 1;
412 if (offset < QSCALE_OFF_MIN)
413 return QSCALE_OFF_MAX / QSCALE_OFF_MIN;
414 return QSCALE_OFF_MAX / offset;
415}
416static void
417slew_time(void)
418{
419 llist_t *item;
420 double offset_median;
421 struct timeval tv;
422
423 {
424 peer_t **peers = xzalloc(sizeof(peers[0]) * G.peer_cnt);
425 unsigned goodpeer_cnt = 0;
426 unsigned middle;
427
428 for (item = G.ntp_peers; item != NULL; item = item->link) {
429 peer_t *p = (peer_t *) item->data;
430 if (p->p_trustlevel < TRUSTLEVEL_BADPEER)
431 continue;
432 if (!p->update.d_good) {
433 free(peers);
434 return;
435 }
436 peers[goodpeer_cnt++] = p;
437 }
438
439 if (goodpeer_cnt == 0) {
440 free(peers);
441 goto clear_good;
442 }
443
444 qsort(peers, goodpeer_cnt, sizeof(peers[0]), compare_offsets);
445
446 middle = goodpeer_cnt / 2;
447 if (middle != 0 && (goodpeer_cnt & 1) == 0) {
448 offset_median = (peers[middle-1]->update.d_offset + peers[middle]->update.d_offset) / 2;
449 G.rootdelay = (peers[middle-1]->update.d_delay + peers[middle]->update.d_delay) / 2;
450 G.stratum = 1 + MAX(peers[middle-1]->update.d_stratum, peers[middle]->update.d_stratum);
451 } else {
452 offset_median = peers[middle]->update.d_offset;
453 G.rootdelay = peers[middle]->update.d_delay;
454 G.stratum = 1 + peers[middle]->update.d_stratum;
455 }
456 G.leap = peers[middle]->update.d_leap;
457 G.refid4 = peers[middle]->update.d_refid4;
458 G.refid =
459#if ENABLE_FEATURE_IPV6
460 peers[middle]->p_lsa->u.sa.sa_family != AF_INET ?
461 G.refid4 :
462#endif
463 peers[middle]->p_lsa->u.sin.sin_addr.s_addr;
464 free(peers);
465 }
466//TODO: if (offset_median > BIG) step_time(offset_median)?
467
468 G.scale = updated_scale(offset_median);
469
470 bb_error_msg("adjusting clock by %fs, our stratum is %u, time scale %u",
471 offset_median, G.stratum, G.scale);
472
473 errno = 0;
474 d_to_tv(offset_median, &tv);
475 if (adjtime(&tv, &tv) == -1)
476 bb_perror_msg_and_die("adjtime failed");
477 if (G.verbose >= 2)
478 bb_error_msg("old adjust: %d.%06u", (int)tv.tv_sec, (unsigned)tv.tv_usec);
479
480 if (G.first_adj_done) {
481 uint8_t synced = (tv.tv_sec == 0 && tv.tv_usec == 0);
482 if (synced != G.synced) {
483 G.synced = synced;
484 bb_error_msg("clock is %ssynced", synced ? "" : "un");
485 }
486 }
487 G.first_adj_done = 1;
488
489 G.reftime = gettime1900d();
490
491 clear_good:
492 for (item = G.ntp_peers; item != NULL; item = item->link) {
493 peer_t *p = (peer_t *) item->data;
494 p->update.d_good = 0;
495 }
496}
497
498static void
499update_peer_data(peer_t *p)
500{
501 /* Clock filter.
502 * Find the datapoint with the lowest delay.
503 * Use that as the peer update.
504 * Invalidate it and all older ones.
505 */
506 int i;
507 int best = -1;
508 int good = 0;
509
510 for (i = 0; i < NUM_DATAPOINTS; i++) {
511 if (p->p_datapoint[i].d_good) {
512 good++;
513 if (best < 0 || p->p_datapoint[i].d_delay < p->p_datapoint[best].d_delay)
514 best = i;
515 }
516 }
517
518 if (good < 8) //FIXME: was it meant to be NUM_DATAPOINTS, not 8?
519 return;
520
521 p->update = p->p_datapoint[best]; /* struct copy */
522 slew_time();
523
524 for (i = 0; i < NUM_DATAPOINTS; i++)
525 if (p->p_datapoint[i].d_rcv_time <= p->p_datapoint[best].d_rcv_time)
526 p->p_datapoint[i].d_good = 0;
527}
528
529static unsigned
530scale_interval(unsigned requested)
531{
532 unsigned interval, r;
533 interval = requested * G.scale;
534 r = (unsigned)rand() % (unsigned)(MAX(5, interval / 10));
535 return (interval + r);
536}
537static void
538recv_and_process_peer_pkt(peer_t *p)
539{
540 ssize_t size;
541 msg_t msg;
542 double T1, T2, T3, T4;
543 unsigned interval;
544 datapoint_t *datapoint;
545
546 /* We can recvfrom here and check from.IP, but some multihomed
547 * ntp servers reply from their *other IP*.
548 * TODO: maybe we should check at least what we can: from.port == 123?
549 */
550 size = recv(p->p_fd, &msg, sizeof(msg), MSG_DONTWAIT);
551 if (size == -1) {
552 bb_perror_msg("recv(%s) error", p->p_dotted);
553 if (errno == EHOSTUNREACH || errno == EHOSTDOWN
554 || errno == ENETUNREACH || errno == ENETDOWN
555 || errno == ECONNREFUSED || errno == EADDRNOTAVAIL
556 || errno == EAGAIN
557 ) {
558//TODO: always do this?
559 set_next(p, error_interval());
560 goto close_sock;
561 }
562 xfunc_die();
563 }
564
565 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
566 bb_error_msg("malformed packet received from %s", p->p_dotted);
567 goto bail;
568 }
569
570 if (msg.m_orgtime.int_partl != p->p_xmt_msg.m_xmttime.int_partl
571 || msg.m_orgtime.fractionl != p->p_xmt_msg.m_xmttime.fractionl
572 ) {
573 goto bail;
574 }
575
576 if ((msg.m_status & LI_ALARM) == LI_ALARM
577 || msg.m_stratum == 0
578 || msg.m_stratum > NTP_MAXSTRATUM
579 ) {
580// TODO: stratum 0 responses may have commands in 32-bit m_refid field:
581// "DENY", "RSTR" - peer does not like us at all
582// "RATE" - peer is overloaded, reduce polling freq
583 interval = error_interval();
584 bb_error_msg("reply from %s: not synced, next query in %us", p->p_dotted, interval);
585 goto close_sock;
586 }
587
588 /*
589 * From RFC 2030 (with a correction to the delay math):
590 *
591 * Timestamp Name ID When Generated
592 * ------------------------------------------------------------
593 * Originate Timestamp T1 time request sent by client
594 * Receive Timestamp T2 time request received by server
595 * Transmit Timestamp T3 time reply sent by server
596 * Destination Timestamp T4 time reply received by client
597 *
598 * The roundtrip delay and local clock offset are defined as
599 *
600 * delay = (T4 - T1) - (T3 - T2); offset = ((T2 - T1) + (T3 - T4)) / 2
601 */
602 T1 = p->p_xmttime;
603 T2 = lfp_to_d(msg.m_rectime);
604 T3 = lfp_to_d(msg.m_xmttime);
605 T4 = gettime1900d();
606
607 datapoint = &p->p_datapoint[p->p_datapoint_idx];
608
609 datapoint->d_offset = ((T2 - T1) + (T3 - T4)) / 2;
610 datapoint->d_delay = (T4 - T1) - (T3 - T2);
611 if (datapoint->d_delay < 0) {
612 bb_error_msg("reply from %s: negative delay %f", p->p_dotted, datapoint->d_delay);
613 interval = error_interval();
614 set_next(p, interval);
615 goto close_sock;
616 }
617 //UNUSED: datapoint->d_error = (T2 - T1) - (T3 - T4);
618 datapoint->d_rcv_time = (time_t)(T4 - OFFSET_1900_1970); /* = time(NULL); */
619 datapoint->d_good = 1;
620
621 datapoint->d_leap = (msg.m_status & LI_MASK);
622 //UNUSED: datapoint->o_precision = msg.m_precision_exp;
623 //UNUSED: datapoint->o_rootdelay = sfp_to_d(msg.m_rootdelay);
624 //UNUSED: datapoint->o_rootdispersion = sfp_to_d(msg.m_dispersion);
625 //UNUSED: datapoint->d_refid = ntohl(msg.m_refid);
626 datapoint->d_refid4 = msg.m_xmttime.fractionl;
627 //UNUSED: datapoint->o_reftime = lfp_to_d(msg.m_reftime);
628 //UNUSED: datapoint->o_poll = msg.m_ppoll;
629 datapoint->d_stratum = msg.m_stratum;
630
631 if (p->p_trustlevel < TRUSTLEVEL_PATHETIC)
632 interval = scale_interval(INTERVAL_QUERY_PATHETIC);
633 else if (p->p_trustlevel < TRUSTLEVEL_AGRESSIVE)
634 interval = scale_interval(INTERVAL_QUERY_AGRESSIVE);
635 else
636 interval = scale_interval(INTERVAL_QUERY_NORMAL);
637
638 set_next(p, interval);
639
640 /* Every received reply which we do not discard increases trust */
641 if (p->p_trustlevel < TRUSTLEVEL_MAX) {
642 p->p_trustlevel++;
643 if (p->p_trustlevel == TRUSTLEVEL_BADPEER)
644 bb_error_msg("peer %s now valid", p->p_dotted);
645 }
646
647 if (G.verbose)
648 bb_error_msg("reply from %s: offset %f delay %f, next query in %us", p->p_dotted,
649 datapoint->d_offset, datapoint->d_delay, interval);
650
651 update_peer_data(p);
652//TODO: do it after all peers had a chance to return at least one reply?
653 step_time_once(datapoint->d_offset);
654
655 p->p_datapoint_idx++;
656 if (p->p_datapoint_idx >= NUM_DATAPOINTS)
657 p->p_datapoint_idx = 0;
658
659 close_sock:
660 /* We do not expect any more packets from this peer for now.
661 * Closing the socket informs kernel about it.
662 * We open a new socket when we send a new query.
663 */
664 close(p->p_fd);
665 p->p_fd = -1;
666 bail:
667 return;
668}
669
670#if ENABLE_FEATURE_NTPD_SERVER
671static void
672recv_and_process_client_pkt(void /*int fd*/)
673{
674 ssize_t size;
675 uint8_t version;
676 double rectime;
677 len_and_sockaddr *to;
678 struct sockaddr *from;
679 msg_t msg;
680 uint8_t query_status;
681 uint8_t query_ppoll;
682 l_fixedpt_t query_xmttime;
683
684 to = get_sock_lsa(G.listen_fd);
685 from = xzalloc(to->len);
686
687 size = recv_from_to(G.listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len);
688 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
689 char *addr;
690 if (size < 0) {
691 if (errno == EAGAIN)
692 goto bail;
693 bb_perror_msg_and_die("recv");
694 }
695 addr = xmalloc_sockaddr2dotted_noport(from);
696 bb_error_msg("malformed packet received from %s: size %u", addr, (int)size);
697 free(addr);
698 goto bail;
699 }
700
701 query_status = msg.m_status;
702 query_ppoll = msg.m_ppoll;
703 query_xmttime = msg.m_xmttime;
704
705 /* Build a reply packet */
706 memset(&msg, 0, sizeof(msg));
707 msg.m_status = G.synced ? G.leap : LI_ALARM;
708 msg.m_status |= (query_status & VERSION_MASK);
709 msg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
710 MODE_SERVER : MODE_SYM_PAS;
711 msg.m_stratum = G.stratum;
712 msg.m_ppoll = query_ppoll;
713 msg.m_precision_exp = G_precision_exp;
714 rectime = gettime1900d();
715 msg.m_xmttime = msg.m_rectime = d_to_lfp(rectime);
716 msg.m_reftime = d_to_lfp(G.reftime);
717 //msg.m_xmttime = d_to_lfp(gettime1900d()); // = msg.m_rectime
718 msg.m_orgtime = query_xmttime;
719 msg.m_rootdelay = d_to_sfp(G.rootdelay);
720 version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
721 msg.m_refid = (version > (3 << VERSION_SHIFT)) ? G.refid4 : G.refid;
722
723 /* We reply from the local address packet was sent to,
724 * this makes to/from look swapped here: */
725 do_sendto(G.listen_fd,
726 /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
727 &msg, size);
728
729 bail:
730 free(to);
731 free(from);
732}
733#endif
734
735/* Upstream ntpd's options:
736 *
737 * -4 Force DNS resolution of host names to the IPv4 namespace.
738 * -6 Force DNS resolution of host names to the IPv6 namespace.
739 * -a Require cryptographic authentication for broadcast client,
740 * multicast client and symmetric passive associations.
741 * This is the default.
742 * -A Do not require cryptographic authentication for broadcast client,
743 * multicast client and symmetric passive associations.
744 * This is almost never a good idea.
745 * -b Enable the client to synchronize to broadcast servers.
746 * -c conffile
747 * Specify the name and path of the configuration file,
748 * default /etc/ntp.conf
749 * -d Specify debugging mode. This option may occur more than once,
750 * with each occurrence indicating greater detail of display.
751 * -D level
752 * Specify debugging level directly.
753 * -f driftfile
754 * Specify the name and path of the frequency file.
755 * This is the same operation as the "driftfile FILE"
756 * configuration command.
757 * -g Normally, ntpd exits with a message to the system log
758 * if the offset exceeds the panic threshold, which is 1000 s
759 * by default. This option allows the time to be set to any value
760 * without restriction; however, this can happen only once.
761 * If the threshold is exceeded after that, ntpd will exit
762 * with a message to the system log. This option can be used
763 * with the -q and -x options. See the tinker command for other options.
764 * -i jaildir
765 * Chroot the server to the directory jaildir. This option also implies
766 * that the server attempts to drop root privileges at startup
767 * (otherwise, chroot gives very little additional security).
768 * You may need to also specify a -u option.
769 * -k keyfile
770 * Specify the name and path of the symmetric key file,
771 * default /etc/ntp/keys. This is the same operation
772 * as the "keys FILE" configuration command.
773 * -l logfile
774 * Specify the name and path of the log file. The default
775 * is the system log file. This is the same operation as
776 * the "logfile FILE" configuration command.
777 * -L Do not listen to virtual IPs. The default is to listen.
778 * -n Don't fork.
779 * -N To the extent permitted by the operating system,
780 * run the ntpd at the highest priority.
781 * -p pidfile
782 * Specify the name and path of the file used to record the ntpd
783 * process ID. This is the same operation as the "pidfile FILE"
784 * configuration command.
785 * -P priority
786 * To the extent permitted by the operating system,
787 * run the ntpd at the specified priority.
788 * -q Exit the ntpd just after the first time the clock is set.
789 * This behavior mimics that of the ntpdate program, which is
790 * to be retired. The -g and -x options can be used with this option.
791 * Note: The kernel time discipline is disabled with this option.
792 * -r broadcastdelay
793 * Specify the default propagation delay from the broadcast/multicast
794 * server to this client. This is necessary only if the delay
795 * cannot be computed automatically by the protocol.
796 * -s statsdir
797 * Specify the directory path for files created by the statistics
798 * facility. This is the same operation as the "statsdir DIR"
799 * configuration command.
800 * -t key
801 * Add a key number to the trusted key list. This option can occur
802 * more than once.
803 * -u user[:group]
804 * Specify a user, and optionally a group, to switch to.
805 * -v variable
806 * -V variable
807 * Add a system variable listed by default.
808 * -x Normally, the time is slewed if the offset is less than the step
809 * threshold, which is 128 ms by default, and stepped if above
810 * the threshold. This option sets the threshold to 600 s, which is
811 * well within the accuracy window to set the clock manually.
812 * Note: since the slew rate of typical Unix kernels is limited
813 * to 0.5 ms/s, each second of adjustment requires an amortization
814 * interval of 2000 s. Thus, an adjustment as much as 600 s
815 * will take almost 14 days to complete. This option can be used
816 * with the -g and -q options. See the tinker command for other options.
817 * Note: The kernel time discipline is disabled with this option.
818 */
819
820/* By doing init in a separate function we decrease stack usage
821 * in main loop.
822 */
823static NOINLINE void ntp_init(char **argv)
824{
825 unsigned opts;
826 llist_t *peers;
827
828 srand(getpid());
829
830 if (getuid())
831 bb_error_msg_and_die(bb_msg_you_must_be_root);
832
833 peers = NULL;
834 opt_complementary = "dd:p::"; /* d: counter, p: list */
835 opts = getopt32(argv,
836 "nqNx" /* compat */
837 "p:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
838 "d" /* compat */
839 "46aAbgL", /* compat, ignored */
840 &peers, &G.verbose);
841 if (!(opts & (OPT_p|OPT_l)))
842 bb_show_usage();
843 if (opts & OPT_x) /* disable stepping, only slew is allowed */
844 G.time_was_stepped = 1;
845 while (peers)
846 add_peers(llist_pop(&peers));
847 if (!(opts & OPT_n)) {
848 bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
849 logmode = LOGMODE_NONE;
850 }
851#if ENABLE_FEATURE_NTPD_SERVER
852 G.listen_fd = -1;
853 if (opts & OPT_l) {
854 G.listen_fd = create_and_bind_dgram_or_die(NULL, 123);
855 socket_want_pktinfo(G.listen_fd);
856 setsockopt(G.listen_fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
857 }
858#endif
859 /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
860 if (opts & OPT_N)
861 setpriority(PRIO_PROCESS, 0, -15);
862
863 /* Set some globals */
864#if 0
865 /* With constant b = 100, G.precision_exp is also constant -6.
866 * Uncomment this and you'll see */
867 {
868 int prec = 0;
869 int b;
870# if 0
871 struct timespec tp;
872 /* We can use sys_clock_getres but assuming 10ms tick should be fine */
873 clock_getres(CLOCK_REALTIME, &tp);
874 tp.tv_sec = 0;
875 tp.tv_nsec = 10000000;
876 b = 1000000000 / tp.tv_nsec; /* convert to Hz */
877# else
878 b = 100; /* b = 1000000000/10000000 = 100 */
879# endif
880 while (b > 1)
881 prec--, b >>= 1;
882 //G.precision_exp = prec;
883 bb_error_msg("G.precision_exp:%d", prec); /* -6 */
884 }
885#endif
886 G.scale = 1;
887
888 bb_signals((1 << SIGTERM) | (1 << SIGINT), record_signo);
889 bb_signals((1 << SIGPIPE) | (1 << SIGHUP), SIG_IGN);
890}
891
892int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
893int ntpd_main(int argc UNUSED_PARAM, char **argv)
894{
895 struct globals g;
896 struct pollfd *pfd;
897 peer_t **idx2peer;
898
899 memset(&g, 0, sizeof(g));
900 SET_PTR_TO_GLOBALS(&g);
901
902 ntp_init(argv);
903
904 {
905 /* if ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
906 unsigned cnt = g.peer_cnt + ENABLE_FEATURE_NTPD_SERVER;
907 idx2peer = xzalloc(sizeof(idx2peer[0]) * cnt);
908 pfd = xzalloc(sizeof(pfd[0]) * cnt);
909 }
910
911 while (!bb_got_signal) {
912 llist_t *item;
913 unsigned i, j;
914 unsigned sent_cnt, trial_cnt;
915 int nfds, timeout;
916 time_t cur_time, nextaction;
917
918 /* Nothing between here and poll() blocks for any significant time */
919
920 cur_time = time(NULL);
921 nextaction = cur_time + 3600;
922
923 i = 0;
924#if ENABLE_FEATURE_NTPD_SERVER
925 if (g.listen_fd != -1) {
926 pfd[0].fd = g.listen_fd;
927 pfd[0].events = POLLIN;
928 i++;
929 }
930#endif
931 /* Pass over peer list, send requests, time out on receives */
932 sent_cnt = trial_cnt = 0;
933 for (item = g.ntp_peers; item != NULL; item = item->link) {
934 peer_t *p = (peer_t *) item->data;
935
936 /* Overflow-safe "if (p->next_action_time <= cur_time) ..." */
937 if ((int)(cur_time - p->next_action_time) >= 0) {
938 if (p->p_fd == -1) {
939 /* Time to send new req */
940 trial_cnt++;
941 if (send_query_to_peer(p) == 0)
942 sent_cnt++;
943 } else {
944 /* Timed out waiting for reply */
945 close(p->p_fd);
946 p->p_fd = -1;
947 timeout = error_interval();
948 bb_error_msg("timed out waiting for %s, "
949 "next query in %us", p->p_dotted, timeout);
950 if (p->p_trustlevel >= TRUSTLEVEL_BADPEER) {
951 p->p_trustlevel /= 2;
952 if (p->p_trustlevel < TRUSTLEVEL_BADPEER)
953 bb_error_msg("peer %s now invalid", p->p_dotted);
954 }
955 set_next(p, timeout);
956 }
957 }
958
959 if (p->next_action_time < nextaction)
960 nextaction = p->next_action_time;
961
962 if (p->p_fd >= 0) {
963 /* Wait for reply from this peer */
964 pfd[i].fd = p->p_fd;
965 pfd[i].events = POLLIN;
966 idx2peer[i] = p;
967 i++;
968 }
969 }
970
971 if ((trial_cnt > 0 && sent_cnt == 0) || g.peer_cnt == 0)
972 step_time_once(0); /* no good peers, don't wait */
973
974 timeout = nextaction - cur_time;
975 if (timeout < 1)
976 timeout = 1;
977
978 /* Here we may block */
979 if (g.verbose >= 2)
980 bb_error_msg("poll %us, sockets:%u", timeout, i);
981 nfds = poll(pfd, i, timeout * 1000);
982 if (nfds <= 0)
983 continue;
984
985 /* Process any received packets */
986 j = 0;
987#if ENABLE_FEATURE_NTPD_SERVER
988 if (g.listen_fd != -1) {
989 if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
990 nfds--;
991 recv_and_process_client_pkt(/*g.listen_fd*/);
992 }
993 j = 1;
994 }
995#endif
996 for (; nfds != 0 && j < i; j++) {
997 if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
998 nfds--;
999 recv_and_process_peer_pkt(idx2peer[j]);
1000 }
1001 }
1002 } /* while (!bb_got_signal) */
1003
1004 kill_myself_with_sig(bb_got_signal);
1005}
diff --git a/networking/route.c b/networking/route.c
index 24cc2eb5a..65c2fb7c8 100644
--- a/networking/route.c
+++ b/networking/route.c
@@ -55,6 +55,7 @@
55#define RTF_WINDOW 0x0080 /* per route window clamping */ 55#define RTF_WINDOW 0x0080 /* per route window clamping */
56#define RTF_IRTT 0x0100 /* Initial round trip time */ 56#define RTF_IRTT 0x0100 /* Initial round trip time */
57#define RTF_REJECT 0x0200 /* Reject route */ 57#define RTF_REJECT 0x0200 /* Reject route */
58#define RTF_NONEXTHOP 0x00200000 /* route with no nexthop */
58#endif 59#endif
59 60
60#if defined(SIOCADDRTOLD) || defined(RTF_IRTT) /* route */ 61#if defined(SIOCADDRTOLD) || defined(RTF_IRTT) /* route */
@@ -128,7 +129,7 @@ static const char tbl_ipvx[] ALIGN1 =
128 "\013\043reinstate" /* Since last, we can save a byte. */ 129 "\013\043reinstate" /* Since last, we can save a byte. */
129; 130;
130 131
131static const int flags_ipvx[] = { /* MUST match tbl_ipvx[] values above. */ 132static const uint16_t flags_ipvx[] = { /* MUST match tbl_ipvx[] values above. */
132#ifdef RTF_REJECT 133#ifdef RTF_REJECT
133 RTF_REJECT, 134 RTF_REJECT,
134#endif 135#endif
@@ -449,7 +450,11 @@ static NOINLINE void INET6_setroute(int action, char **args)
449} 450}
450#endif 451#endif
451 452
452static const unsigned flagvals[] = { /* Must agree with flagchars[]. */ 453static const
454IF_NOT_FEATURE_IPV6(uint16_t)
455IF_FEATURE_IPV6(unsigned)
456flagvals[] = { /* Must agree with flagchars[]. */
457 RTF_UP,
453 RTF_GATEWAY, 458 RTF_GATEWAY,
454 RTF_HOST, 459 RTF_HOST,
455 RTF_REINSTATE, 460 RTF_REINSTATE,
@@ -458,27 +463,25 @@ static const unsigned flagvals[] = { /* Must agree with flagchars[]. */
458#if ENABLE_FEATURE_IPV6 463#if ENABLE_FEATURE_IPV6
459 RTF_DEFAULT, 464 RTF_DEFAULT,
460 RTF_ADDRCONF, 465 RTF_ADDRCONF,
461 RTF_CACHE 466 RTF_CACHE,
467 RTF_REJECT,
468 RTF_NONEXTHOP, /* this one doesn't fit into 16 bits */
462#endif 469#endif
463}; 470};
464
465#define IPV4_MASK (RTF_GATEWAY|RTF_HOST|RTF_REINSTATE|RTF_DYNAMIC|RTF_MODIFIED)
466#define IPV6_MASK (RTF_GATEWAY|RTF_HOST|RTF_DEFAULT|RTF_ADDRCONF|RTF_CACHE)
467
468/* Must agree with flagvals[]. */ 471/* Must agree with flagvals[]. */
469static const char flagchars[] ALIGN1 = 472static const char flagchars[] ALIGN1 =
470 "GHRDM" 473 "UGHRDM"
471#if ENABLE_FEATURE_IPV6 474#if ENABLE_FEATURE_IPV6
472 "DAC" 475 "DAC!n"
473#endif 476#endif
474; 477;
478#define IPV4_MASK (RTF_UP|RTF_GATEWAY|RTF_HOST|RTF_REINSTATE|RTF_DYNAMIC|RTF_MODIFIED)
479#define IPV6_MASK (RTF_UP|RTF_GATEWAY|RTF_HOST|RTF_DEFAULT|RTF_ADDRCONF|RTF_CACHE|RTF_REJECT|RTF_NONEXTHOP)
475 480
476static void set_flags(char *flagstr, int flags) 481static void set_flags(char *flagstr, int flags)
477{ 482{
478 int i; 483 int i;
479 484
480 *flagstr++ = 'U';
481
482 for (i = 0; (*flagstr = flagchars[i]) != 0; i++) { 485 for (i = 0; (*flagstr = flagchars[i]) != 0; i++) {
483 if (flags & flagvals[i]) { 486 if (flags & flagvals[i]) {
484 ++flagstr; 487 ++flagstr;
@@ -491,6 +494,7 @@ void FAST_FUNC bb_displayroutes(int noresolve, int netstatfmt)
491{ 494{
492 char devname[64], flags[16], *sdest, *sgw; 495 char devname[64], flags[16], *sdest, *sgw;
493 unsigned long d, g, m; 496 unsigned long d, g, m;
497 int r;
494 int flgs, ref, use, metric, mtu, win, ir; 498 int flgs, ref, use, metric, mtu, win, ir;
495 struct sockaddr_in s_addr; 499 struct sockaddr_in s_addr;
496 struct in_addr mask; 500 struct in_addr mask;
@@ -501,20 +505,24 @@ void FAST_FUNC bb_displayroutes(int noresolve, int netstatfmt)
501 "Destination Gateway Genmask Flags %s Iface\n", 505 "Destination Gateway Genmask Flags %s Iface\n",
502 netstatfmt ? " MSS Window irtt" : "Metric Ref Use"); 506 netstatfmt ? " MSS Window irtt" : "Metric Ref Use");
503 507
504 if (fscanf(fp, "%*[^\n]\n") < 0) { /* Skip the first line. */ 508 /* Skip the first line. */
505 goto ERROR; /* Empty or missing line, or read error. */ 509 r = fscanf(fp, "%*[^\n]\n");
510 if (r < 0) {
511 /* Empty line, read error, or EOF. Yes, if routing table
512 * is completely empty, /proc/net/route has no header.
513 */
514 goto ERROR;
506 } 515 }
507 while (1) { 516 while (1) {
508 int r;
509 r = fscanf(fp, "%63s%lx%lx%X%d%d%d%lx%d%d%d\n", 517 r = fscanf(fp, "%63s%lx%lx%X%d%d%d%lx%d%d%d\n",
510 devname, &d, &g, &flgs, &ref, &use, &metric, &m, 518 devname, &d, &g, &flgs, &ref, &use, &metric, &m,
511 &mtu, &win, &ir); 519 &mtu, &win, &ir);
512 if (r != 11) { 520 if (r != 11) {
521 ERROR:
513 if ((r < 0) && feof(fp)) { /* EOF with no (nonspace) chars read. */ 522 if ((r < 0) && feof(fp)) { /* EOF with no (nonspace) chars read. */
514 break; 523 break;
515 } 524 }
516 ERROR: 525 bb_perror_msg_and_die(bb_msg_read_error);
517 bb_error_msg_and_die("fscanf");
518 } 526 }
519 527
520 if (!(flgs & RTF_UP)) { /* Skip interfaces that are down. */ 528 if (!(flgs & RTF_UP)) { /* Skip interfaces that are down. */
@@ -574,13 +582,13 @@ static void INET6_displayroutes(void)
574 int r; 582 int r;
575 r = fscanf(fp, "%32s%x%*s%x%32s%x%x%x%x%s\n", 583 r = fscanf(fp, "%32s%x%*s%x%32s%x%x%x%x%s\n",
576 addr6x+14, &prefix_len, &slen, addr6x+40+7, 584 addr6x+14, &prefix_len, &slen, addr6x+40+7,
577 &metric, &use, &refcnt, &iflags, iface); 585 &metric, &refcnt, &use, &iflags, iface);
578 if (r != 9) { 586 if (r != 9) {
579 if ((r < 0) && feof(fp)) { /* EOF with no (nonspace) chars read. */ 587 if ((r < 0) && feof(fp)) { /* EOF with no (nonspace) chars read. */
580 break; 588 break;
581 } 589 }
582 ERROR: 590 ERROR:
583 bb_error_msg_and_die("fscanf"); 591 bb_perror_msg_and_die(bb_msg_read_error);
584 } 592 }
585 593
586 /* Do the addr6x shift-and-insert changes to ':'-delimit addresses. 594 /* Do the addr6x shift-and-insert changes to ':'-delimit addresses.
@@ -606,10 +614,6 @@ static void INET6_displayroutes(void)
606 } while (i < 40+28+7); 614 } while (i < 40+28+7);
607 } 615 }
608 616
609 if (!(iflags & RTF_UP)) { /* Skip interfaces that are down. */
610 continue;
611 }
612
613 set_flags(flags, (iflags & IPV6_MASK)); 617 set_flags(flags, (iflags & IPV6_MASK));
614 618
615 r = 0; 619 r = 0;
diff --git a/networking/telnetd.c b/networking/telnetd.c
index 9e7a84cce..6aee95871 100644
--- a/networking/telnetd.c
+++ b/networking/telnetd.c
@@ -462,15 +462,7 @@ static void handle_sigchld(int sig UNUSED_PARAM)
462 while (ts) { 462 while (ts) {
463 if (ts->shell_pid == pid) { 463 if (ts->shell_pid == pid) {
464 ts->shell_pid = -1; 464 ts->shell_pid = -1;
465// man utmp: 465 update_utmp_DEAD_PROCESS(pid);
466// When init(8) finds that a process has exited, it locates its utmp entry
467// by ut_pid, sets ut_type to DEAD_PROCESS, and clears ut_user, ut_host
468// and ut_time with null bytes.
469// [same applies to other processes which maintain utmp entries, like telnetd]
470//
471// We do not bother actually clearing fields:
472// it might be interesting to know who was logged in and from where
473 update_utmp(pid, DEAD_PROCESS, /*tty_name:*/ NULL, /*username:*/ NULL, /*hostname:*/ NULL);
474 break; 466 break;
475 } 467 }
476 ts = ts->next; 468 ts = ts->next;
@@ -739,7 +731,7 @@ int telnetd_main(int argc UNUSED_PARAM, char **argv)
739 continue; 731 continue;
740 kill_session: 732 kill_session:
741 if (ts->shell_pid > 0) 733 if (ts->shell_pid > 0)
742 update_utmp(ts->shell_pid, DEAD_PROCESS, /*tty_name:*/ NULL, /*username:*/ NULL, /*hostname:*/ NULL); 734 update_utmp_DEAD_PROCESS(ts->shell_pid);
743 free_session(ts); 735 free_session(ts);
744 ts = next; 736 ts = next;
745 } 737 }
diff --git a/networking/udhcp/dhcpc.c b/networking/udhcp/dhcpc.c
index a34829c3a..9d3d1a31c 100644
--- a/networking/udhcp/dhcpc.c
+++ b/networking/udhcp/dhcpc.c
@@ -1752,7 +1752,6 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
1752 } 1752 }
1753#endif 1753#endif
1754 /* enter bound state */ 1754 /* enter bound state */
1755 timeout = lease_seconds / 2;
1756 temp_addr.s_addr = packet.yiaddr; 1755 temp_addr.s_addr = packet.yiaddr;
1757 bb_info_msg("Lease of %s obtained, lease time %u", 1756 bb_info_msg("Lease of %s obtained, lease time %u",
1758 inet_ntoa(temp_addr), (unsigned)lease_seconds); 1757 inet_ntoa(temp_addr), (unsigned)lease_seconds);
@@ -1761,6 +1760,11 @@ int udhcpc_main(int argc UNUSED_PARAM, char **argv)
1761 start = monotonic_sec(); 1760 start = monotonic_sec();
1762 udhcp_run_script(&packet, state == REQUESTING ? "bound" : "renew"); 1761 udhcp_run_script(&packet, state == REQUESTING ? "bound" : "renew");
1763 already_waited_sec = (unsigned)monotonic_sec() - start; 1762 already_waited_sec = (unsigned)monotonic_sec() - start;
1763 timeout = lease_seconds / 2;
1764 if ((unsigned)timeout < already_waited_sec) {
1765 /* Something went wrong. Back to discover state */
1766 timeout = already_waited_sec = 0;
1767 }
1764 1768
1765 state = BOUND; 1769 state = BOUND;
1766 change_listen_mode(LISTEN_NONE); 1770 change_listen_mode(LISTEN_NONE);
diff --git a/networking/udhcp/dhcpd.c b/networking/udhcp/dhcpd.c
index 4b3ed240c..2de074f9b 100644
--- a/networking/udhcp/dhcpd.c
+++ b/networking/udhcp/dhcpd.c
@@ -413,7 +413,8 @@ int udhcpd_main(int argc UNUSED_PARAM, char **argv)
413 413
414 max_sock = udhcp_sp_fd_set(&rfds, server_socket); 414 max_sock = udhcp_sp_fd_set(&rfds, server_socket);
415 if (server_config.auto_time) { 415 if (server_config.auto_time) {
416 tv.tv_sec = timeout_end - monotonic_sec(); 416 /* cast to signed is essential if tv_sec is wider than int */
417 tv.tv_sec = (int)(timeout_end - monotonic_sec());
417 tv.tv_usec = 0; 418 tv.tv_usec = 0;
418 } 419 }
419 retval = 0; 420 retval = 0;
diff --git a/networking/wget.c b/networking/wget.c
index 774accf7a..42bfbb206 100644
--- a/networking/wget.c
+++ b/networking/wget.c
@@ -38,8 +38,14 @@
38 38
39#if 0 39#if 0
40# define log_io(...) bb_error_msg(__VA_ARGS__) 40# define log_io(...) bb_error_msg(__VA_ARGS__)
41# define SENDFMT(fp, fmt, ...) \
42 do { \
43 log_io("> " fmt, ##__VA_ARGS__); \
44 fprintf(fp, fmt, ##__VA_ARGS__); \
45 } while (0);
41#else 46#else
42# define log_io(...) ((void)0) 47# define log_io(...) ((void)0)
48# define SENDFMT(fp, fmt, ...) fprintf(fp, fmt, ##__VA_ARGS__)
43#endif 49#endif
44 50
45 51
@@ -55,6 +61,36 @@ static const char P_FTP[] = "ftp";
55static const char P_HTTP[] = "http"; 61static const char P_HTTP[] = "http";
56static const char P_HTTPS[] = "https"; 62static const char P_HTTPS[] = "https";
57 63
64#if ENABLE_FEATURE_WGET_LONG_OPTIONS
65/* User-specified headers prevent using our corresponding built-in headers. */
66enum {
67 HDR_HOST = (1<<0),
68 HDR_USER_AGENT = (1<<1),
69 HDR_RANGE = (1<<2),
70 HDR_AUTH = (1<<3) * ENABLE_FEATURE_WGET_AUTHENTICATION,
71 HDR_PROXY_AUTH = (1<<4) * ENABLE_FEATURE_WGET_AUTHENTICATION,
72};
73static const char wget_user_headers[] ALIGN1 =
74 "Host:\0"
75 "User-Agent:\0"
76 "Range:\0"
77# if ENABLE_FEATURE_WGET_AUTHENTICATION
78 "Authorization:\0"
79 "Proxy-Authorization:\0"
80# endif
81 ;
82# define USR_HEADER_HOST (G.user_headers & HDR_HOST)
83# define USR_HEADER_USER_AGENT (G.user_headers & HDR_USER_AGENT)
84# define USR_HEADER_RANGE (G.user_headers & HDR_RANGE)
85# define USR_HEADER_AUTH (G.user_headers & HDR_AUTH)
86# define USR_HEADER_PROXY_AUTH (G.user_headers & HDR_PROXY_AUTH)
87#else /* No long options, no user-headers :( */
88# define USR_HEADER_HOST 0
89# define USR_HEADER_USER_AGENT 0
90# define USR_HEADER_RANGE 0
91# define USR_HEADER_AUTH 0
92# define USR_HEADER_PROXY_AUTH 0
93#endif
58 94
59/* Globals */ 95/* Globals */
60struct globals { 96struct globals {
@@ -69,6 +105,7 @@ struct globals {
69#if ENABLE_FEATURE_WGET_LONG_OPTIONS 105#if ENABLE_FEATURE_WGET_LONG_OPTIONS
70 char *post_data; 106 char *post_data;
71 char *extra_headers; 107 char *extra_headers;
108 unsigned char user_headers; /* Headers mentioned by the user */
72#endif 109#endif
73 char *fname_out; /* where to direct output (-O) */ 110 char *fname_out; /* where to direct output (-O) */
74 const char *proxy_flag; /* Use proxies if env vars are set */ 111 const char *proxy_flag; /* Use proxies if env vars are set */
@@ -842,43 +879,46 @@ static void download_one_url(const char *url)
842#endif 879#endif
843 /* Send HTTP request */ 880 /* Send HTTP request */
844 if (use_proxy) { 881 if (use_proxy) {
845 fprintf(sfp, "GET %s://%s/%s HTTP/1.1\r\n", 882 SENDFMT(sfp, "GET %s://%s/%s HTTP/1.1\r\n",
846 target.protocol, target.host, 883 target.protocol, target.host,
847 target.path); 884 target.path);
848 } else { 885 } else {
849 fprintf(sfp, "%s /%s HTTP/1.1\r\n", 886 SENDFMT(sfp, "%s /%s HTTP/1.1\r\n",
850 (option_mask32 & WGET_OPT_POST_DATA) ? "POST" : "GET", 887 (option_mask32 & WGET_OPT_POST_DATA) ? "POST" : "GET",
851 target.path); 888 target.path);
852 } 889 }
853 890 if (!USR_HEADER_HOST)
854 fprintf(sfp, "Host: %s\r\nUser-Agent: %s\r\n", 891 SENDFMT(sfp, "Host: %s\r\n", target.host);
855 target.host, G.user_agent); 892 if (!USR_HEADER_USER_AGENT)
893 SENDFMT(sfp, "User-Agent: %s\r\n", G.user_agent);
856 894
857 /* Ask server to close the connection as soon as we are done 895 /* Ask server to close the connection as soon as we are done
858 * (IOW: we do not intend to send more requests) 896 * (IOW: we do not intend to send more requests)
859 */ 897 */
860 fprintf(sfp, "Connection: close\r\n"); 898 SENDFMT(sfp, "Connection: close\r\n");
861 899
862#if ENABLE_FEATURE_WGET_AUTHENTICATION 900#if ENABLE_FEATURE_WGET_AUTHENTICATION
863 if (target.user) { 901 if (target.user && !USR_HEADER_AUTH) {
864 fprintf(sfp, "Proxy-Authorization: Basic %s\r\n"+6, 902 SENDFMT(sfp, "Proxy-Authorization: Basic %s\r\n"+6,
865 base64enc(target.user)); 903 base64enc(target.user));
866 } 904 }
867 if (use_proxy && server.user) { 905 if (use_proxy && server.user && !USR_HEADER_PROXY_AUTH) {
868 fprintf(sfp, "Proxy-Authorization: Basic %s\r\n", 906 SENDFMT(sfp, "Proxy-Authorization: Basic %s\r\n",
869 base64enc(server.user)); 907 base64enc(server.user));
870 } 908 }
871#endif 909#endif
872 910
873 if (G.beg_range != 0) 911 if (G.beg_range != 0 && !USR_HEADER_RANGE)
874 fprintf(sfp, "Range: bytes=%"OFF_FMT"u-\r\n", G.beg_range); 912 SENDFMT(sfp, "Range: bytes=%"OFF_FMT"u-\r\n", G.beg_range);
875 913
876#if ENABLE_FEATURE_WGET_LONG_OPTIONS 914#if ENABLE_FEATURE_WGET_LONG_OPTIONS
877 if (G.extra_headers) 915 if (G.extra_headers) {
916 log_io(G.extra_headers);
878 fputs(G.extra_headers, sfp); 917 fputs(G.extra_headers, sfp);
918 }
879 919
880 if (option_mask32 & WGET_OPT_POST_DATA) { 920 if (option_mask32 & WGET_OPT_POST_DATA) {
881 fprintf(sfp, 921 SENDFMT(sfp,
882 "Content-Type: application/x-www-form-urlencoded\r\n" 922 "Content-Type: application/x-www-form-urlencoded\r\n"
883 "Content-Length: %u\r\n" 923 "Content-Length: %u\r\n"
884 "\r\n" 924 "\r\n"
@@ -888,7 +928,7 @@ static void download_one_url(const char *url)
888 } else 928 } else
889#endif 929#endif
890 { 930 {
891 fprintf(sfp, "\r\n"); 931 SENDFMT(sfp, "\r\n");
892 } 932 }
893 933
894 fflush(sfp); 934 fflush(sfp);
@@ -1105,7 +1145,9 @@ int wget_main(int argc UNUSED_PARAM, char **argv)
1105#if ENABLE_FEATURE_WGET_LONG_OPTIONS 1145#if ENABLE_FEATURE_WGET_LONG_OPTIONS
1106 applet_long_options = wget_longopts; 1146 applet_long_options = wget_longopts;
1107#endif 1147#endif
1108 opt_complementary = "-1" IF_FEATURE_WGET_TIMEOUT(":T+") IF_FEATURE_WGET_LONG_OPTIONS(":\xfe::"); 1148 opt_complementary = "-1"
1149 IF_FEATURE_WGET_TIMEOUT(":T+")
1150 IF_FEATURE_WGET_LONG_OPTIONS(":\xfe::");
1109 getopt32(argv, "csqO:P:Y:U:T:" /*ignored:*/ "t:", 1151 getopt32(argv, "csqO:P:Y:U:T:" /*ignored:*/ "t:",
1110 &G.fname_out, &G.dir_prefix, 1152 &G.fname_out, &G.dir_prefix,
1111 &G.proxy_flag, &G.user_agent, 1153 &G.proxy_flag, &G.user_agent,
@@ -1118,16 +1160,32 @@ int wget_main(int argc UNUSED_PARAM, char **argv)
1118 1160
1119#if ENABLE_FEATURE_WGET_LONG_OPTIONS 1161#if ENABLE_FEATURE_WGET_LONG_OPTIONS
1120 if (headers_llist) { 1162 if (headers_llist) {
1121 int size = 1; 1163 int size = 0;
1122 char *cp; 1164 char *hdr;
1123 llist_t *ll = headers_llist; 1165 llist_t *ll = headers_llist;
1124 while (ll) { 1166 while (ll) {
1125 size += strlen(ll->data) + 2; 1167 size += strlen(ll->data) + 2;
1126 ll = ll->link; 1168 ll = ll->link;
1127 } 1169 }
1128 G.extra_headers = cp = xmalloc(size); 1170 G.extra_headers = hdr = xmalloc(size + 1);
1129 while (headers_llist) { 1171 while (headers_llist) {
1130 cp += sprintf(cp, "%s\r\n", (char*)llist_pop(&headers_llist)); 1172 int bit;
1173 const char *words;
1174
1175 size = sprintf(hdr, "%s\r\n",
1176 (char*)llist_pop(&headers_llist));
1177 /* a bit like index_in_substrings but don't match full key */
1178 bit = 1;
1179 words = wget_user_headers;
1180 while (*words) {
1181 if (strstr(hdr, words) == hdr) {
1182 G.user_headers |= bit;
1183 break;
1184 }
1185 bit <<= 1;
1186 words += strlen(words) + 1;
1187 }
1188 hdr += size;
1131 } 1189 }
1132 } 1190 }
1133#endif 1191#endif