Skip to content

Commit

Permalink
Fix deserialization logic for several fields
Browse files Browse the repository at this point in the history
* leap indicator
* version number
* mode
* stratum
* poll
* precision

Fix version number deserialization logic

Fix deserialization logic for mode, stratum, poll and precision
  • Loading branch information
stoyicker committed Nov 7, 2023
1 parent 4356f9e commit 389976c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ internal class NtpExchanger(
NTP_PORT_NUMBER.toByte(),
)
val responseTime = referenceClock.referenceEpochTime - requestTime
NtpExchangeResult(responseTime, ntpPacketDeserializer(buffer))
ntpPacketDeserializer(buffer)?.let { NtpExchangeResult(responseTime, it) }
} catch (_: Throwable) {
null
} finally {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,24 @@ import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds

internal class NtpPacketDeserializer {
operator fun invoke(bytes: ByteArray): NtpPacket {
operator fun invoke(bytes: ByteArray): NtpPacket? {
var index = 0
val leapIndicator = (bytes[index].toInt() shr 6) and 0b11
if (leapIndicator == LEAP_INDICATOR_CLOCK_UNSYNCHRONIZED) {
return null
}
val versionNumber = (bytes[index].toInt() shr 3) and 0b111
val mode = bytes[index].toInt() and 0b111
if (mode != MODE_SERVER) {
return null
}
++index
val stratum = bytes[index++].asIntResolvingSign
if (stratum >= STRATUM_CLOCK_NOT_SYNCHRONIZED) {
return null
}
val poll = bytes[index++].asIntResolvingSign
val precision = bytes[index++].asIntResolvingSign
return NtpPacket(
(bytes[index++].toInt() shl 8) + bytes[index++],
(bytes[index++].toInt() shl 16) + (bytes[index++].toInt() shl 24) + bytes[index++],
Expand All @@ -31,6 +47,9 @@ internal class NtpPacketDeserializer {
)
}

private val Byte.asIntResolvingSign
get() = toUByte().toInt()

private val ByteArray.asNtpIntervalToInterval: Duration
get() {
var index = 0
Expand Down Expand Up @@ -70,4 +89,10 @@ internal class NtpPacketDeserializer {
NtpPacket.NTP_EPOCH_OFFSET_WITH_EPOCH +
fraction.milliseconds
}

companion object {
private const val LEAP_INDICATOR_CLOCK_UNSYNCHRONIZED = 0b11
private const val MODE_SERVER = 4
private const val STRATUM_CLOCK_NOT_SYNCHRONIZED = 16
}
}

0 comments on commit 389976c

Please sign in to comment.