You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@nuttx.apache.org by xi...@apache.org on 2021/02/10 06:47:30 UTC
[incubator-nuttx-apps] branch master updated: ntpclient.c: Avoid
integer overflows in offset calculation
This is an automated email from the ASF dual-hosted git repository.
xiaoxiang pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-nuttx-apps.git
The following commit(s) were added to refs/heads/master by this push:
new ca6907c ntpclient.c: Avoid integer overflows in offset calculation
ca6907c is described below
commit ca6907ccbe6ee732ba1c179d789fbfb2f8e5e6ae
Author: YAMAMOTO Takashi <ya...@midokura.com>
AuthorDate: Tue Feb 9 16:39:24 2021 +0900
ntpclient.c: Avoid integer overflows in offset calculation
The current calculation easily overflows if the local time is
around the unix epoch. I guess it isn't too unusual for
devices without RTC. Or, the battery is dead. Or, whatever.
This commit avoids the overflow by simply dividing everything by 2.
While more sophisticated and precise solutions are possible,
I feel that they are overkill for this simple implementation.
For example,
The unix epoch (1970) is 0x83aa7e8000000000 in
64-bit NTP timestamp. (1900-origin)
The timestamp now, as of writing this, is 0xe3cda16b00000000.
With the code before this commit, the offset will be:
(lldb) p (long long)((0xe3cda16b00000000 - 0x83aa7e8000000000) + (0xe3cda16b00000000 - 0x83aa7e8000000000)) / 2
(long long) $16 = -2295952992316162048
(lldb)
with the new code, it would be:
(lldb) p (long long)((0xe3cda16b00000000 / 2 - 0x83aa7e8000000000 / 2) + (0xe3cda16b00000 / 2 - 0x83aa7e8000000000 / 2))
(long long) $17 = 6927419044538613760
(lldb)
It's the correct offset from the unix epoch:
(lldb) p 6927419044538613760 >> 32
(long) $0 = 1612915435
(lldb)
spacetanuki% date -r 1612915435
Wed Feb 10 09:03:55 JST 2021
spacetanuki%
---
netutils/ntpclient/ntpclient.c | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/netutils/ntpclient/ntpclient.c b/netutils/ntpclient/ntpclient.c
index a7c72c1..db87b4d 100644
--- a/netutils/ntpclient/ntpclient.c
+++ b/netutils/ntpclient/ntpclient.c
@@ -529,8 +529,8 @@ static void ntpc_calculate_offset(FAR int64_t *offset, FAR int64_t *delay,
* http://nicolas.aimon.fr/2014/12/05/timesync/
*/
- *offset = (int64_t)((remote_recvtime - local_xmittime) +
- (remote_xmittime - local_recvtime)) / 2;
+ *offset = (int64_t)((remote_recvtime / 2 - local_xmittime / 2) +
+ (remote_xmittime / 2 - local_recvtime / 2));
/* Calculate roundtrip delay. */