Skip to content

Commit df4cdba

Browse files
yangguangcai1xiaoxiang781216
authored andcommitted
ntp:fix parameter is negative numbers.
Signed-off-by: yangguangcai <[email protected]>
1 parent fb37ef3 commit df4cdba

File tree

1 file changed

+28
-11
lines changed

1 file changed

+28
-11
lines changed

netutils/ntpclient/ntpclient.c

Lines changed: 28 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -409,7 +409,7 @@ static inline void ntpc_setuint64(FAR uint8_t *ptr, uint64_t value)
409409
* Name: ntp_secpart
410410
****************************************************************************/
411411

412-
static uint32_t ntp_secpart(uint64_t time)
412+
static int32_t ntp_secpart(int64_t time)
413413
{
414414
/* NTP timestamps are represented as a 64-bit fixed-point number, in
415415
* seconds relative to 0000 UT on 1 January 1900. The integer part is
@@ -434,11 +434,11 @@ static uint32_t ntp_secpart(uint64_t time)
434434
* Name: ntp_nsecpart
435435
****************************************************************************/
436436

437-
static uint32_t ntp_nsecpart(uint64_t time)
437+
static int32_t ntp_nsecpart(int64_t time)
438438
{
439439
/* Get fraction part converted to nanoseconds. */
440440

441-
return ((time & 0xffffffffu) * NSEC_PER_SEC) >> 32;
441+
return (((int64_t)((uint64_t)time << 32) >> 32) * NSEC_PER_SEC) >> 32;
442442
}
443443

444444
/****************************************************************************
@@ -527,6 +527,30 @@ static void ntpc_calculate_offset(FAR int64_t *offset, FAR int64_t *delay,
527527
(remote_xmittime - remote_recvtime);
528528
}
529529

530+
/****************************************************************************
531+
* Name: ntpc_apply_offset
532+
****************************************************************************/
533+
534+
static void ntpc_apply_offset(FAR struct timespec *tp,
535+
FAR struct timespec *src,
536+
int64_t offset)
537+
{
538+
tp->tv_sec = src->tv_sec + ntp_secpart(offset);
539+
tp->tv_nsec = src->tv_nsec + ntp_nsecpart(offset);
540+
541+
while (tp->tv_nsec < 0)
542+
{
543+
tp->tv_nsec += NSEC_PER_SEC;
544+
tp->tv_sec--;
545+
}
546+
547+
while (tp->tv_nsec >= NSEC_PER_SEC)
548+
{
549+
tp->tv_nsec -= NSEC_PER_SEC;
550+
tp->tv_sec++;
551+
}
552+
}
553+
530554
/****************************************************************************
531555
* Name: ntpc_settime
532556
*
@@ -580,14 +604,7 @@ static void ntpc_settime(int64_t offset, FAR struct timespec *start_realtime,
580604

581605
/* Apply offset */
582606

583-
tp = curr_realtime;
584-
tp.tv_sec += ntp_secpart(offset);
585-
tp.tv_nsec += ntp_nsecpart(offset);
586-
while (tp.tv_nsec >= NSEC_PER_SEC)
587-
{
588-
tp.tv_nsec -= NSEC_PER_SEC;
589-
tp.tv_sec++;
590-
}
607+
ntpc_apply_offset(&tp, &curr_realtime, offset);
591608

592609
/* Set the system time */
593610

0 commit comments

Comments
 (0)