Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NTPClient: ignore invalid timestamps #2041

Merged
merged 1 commit into from
Feb 4, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 27 additions & 18 deletions Sming/Core/Network/NtpClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ void NtpClient::onReceive(pbuf* buf, IpAddress remoteIP, uint16_t remotePort)
debug_d("NtpClient::onReceive(%s:%u)", remoteIP.toString().c_str(), remotePort);

stopTimer();
auto retry = [this]() { startTimer(NTP_RESPONSE_TIMEOUT_MS); };

// We do some basic check to see if it really is a ntp packet we receive.
// NTP version should be set to same as we used to send, NTP_VERSION
Expand All @@ -132,28 +133,36 @@ void NtpClient::onReceive(pbuf* buf, IpAddress remoteIP, uint16_t remotePort)
uint8_t ver = (versionMode & 0b00111000) >> 3;
uint8_t mode = (versionMode & 0x07);

if(mode == NTP_MODE_SERVER && (ver == NTP_VERSION || ver == (NTP_VERSION - 1))) {
//Most likely a correct NTP packet received.
if(mode != NTP_MODE_SERVER) {
// Received response from another client - retry
return retry();
}

uint32_t timestamp;
pbuf_copy_partial(buf, &timestamp, sizeof(timestamp), 40); // Copy only timestamp.
timestamp = ntohl(timestamp);
if(ver != NTP_VERSION && ver != (NTP_VERSION - 1)) {
// Received an unsupported version - retry
return retry();
}

// Unix time starts on Jan 1 1970, subtract 70 years:
uint32_t epoch = timestamp - 0x83AA7E80;
uint32_t timestamp;
pbuf_copy_partial(buf, &timestamp, sizeof(timestamp), 40); // Copy only timestamp.
timestamp = ntohl(timestamp);

if(autoUpdateSystemClock) {
SystemClock.setTime(epoch, eTZ_UTC); // update systemclock utc value
}
if(timestamp == 0) {
// Timestamp is not valid
return retry();
}

if(delegateCompleted) {
delegateCompleted(*this, epoch);
}
// Unix time starts on Jan 1 1970, subtract 70 years:
uint32_t epoch = timestamp - 0x83AA7E80;

// If auto query is enabled, schedule the next check
setAutoQuery(autoQueryEnabled);
} else {
// Got a dodgy packet so treat it as we would a response failure
startTimer(NTP_RESPONSE_TIMEOUT_MS);
if(autoUpdateSystemClock) {
SystemClock.setTime(epoch, eTZ_UTC); // update systemclock utc value
}

if(delegateCompleted) {
delegateCompleted(*this, epoch);
}

// If auto query is enabled, schedule the next check
setAutoQuery(autoQueryEnabled);
}