📄 sntp.c
字号:
//=============================================================================
//
// sntp.c
//
// Simple Network Time Protocol
//
//=============================================================================
//####ECOSGPLCOPYRIGHTBEGIN####
// -------------------------------------------
// This file is part of eCos, the Embedded Configurable Operating System.
// Copyright (C) 2003 Andrew Lunn
//
// eCos is free software; you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 or (at your option) any later version.
//
// eCos is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with eCos; if not, write to the Free Software Foundation, Inc.,
// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
//
// As a special exception, if other files instantiate templates or use macros
// or inline functions from this file, or you compile this file and link it
// with other works to produce a work based on this file, this file does not
// by itself cause the resulting work to be covered by the GNU General Public
// License. However the source code for this file must still be made available
// in accordance with section (3) of the GNU General Public License.
//
// This exception does not invalidate any other reasons why a work based on
// this file might be covered by the GNU General Public License.
//
// Alternative licenses for eCos may be arranged by contacting Red Hat, Inc.
// at http://sources.redhat.com/ecos/ecos-license/
// -------------------------------------------
//####ECOSGPLCOPYRIGHTEND####
//=============================================================================
//#####DESCRIPTIONBEGIN####
//
// Author(s): andrew.lunn
// Contributors:
// Date: 2003-02-12
// Description: Provides a Simple Network Time Protocol Client
//####DESCRIPTIONEND####
//
//=============================================================================
#include <pkgconf/system.h>
#include <pkgconf/net_sntp.h>
#include <network.h>
#include <cyg/infra/cyg_type.h>
#include <cyg/infra/cyg_ass.h>
#include <cyg/infra/cyg_trac.h>
#include <cyg/sntp/sntp.h>
#include <time.h>
/* NTP/SNTPv4 Packet Format (RFC2030) */
typedef struct
{
cyg_uint32 Seconds; /* Since 00:00:00 Jan 01 1900 */
cyg_uint32 Fraction;
} NTP_TIMESTAMP;
typedef struct
{
/* Control combines LeapIndicator, Version, and Mode */
cyg_uint8 Control;
cyg_uint8 Stratum;
cyg_uint8 Poll;
cyg_uint8 Precision;
cyg_uint32 RootDelay;
cyg_uint32 RootDispersion;
cyg_uint32 ReferenceIdentifier;
NTP_TIMESTAMP ReferenceTimestamp;
NTP_TIMESTAMP OriginateTimestamp;
NTP_TIMESTAMP ReceiveTimestamp;
NTP_TIMESTAMP TransmitTimestamp;
cyg_uint32 KeyIdentifier; /* Optional */
cyg_uint8 MessageDigest[16]; /* Optional */
} NTP_PACKET;
#define NTP_PACKET_MINLEN 48 /* Packet size - optional fields */
/* Leap Indicator Field [Bits 7:6] */
#define NTP_LI_NOLEAP 0x00
#define NTP_LI_61SECS 0x40
#define NTP_LI_59SECS 0x80
#define NTP_LI_ALARM 0xC0
/* Version Field [Bits 5:3] */
#define NTP_VERSION_GET(pkt) ((((pkt)->Control)>>3)&0x7)
#define NTP_VERSION_SET(ver) (((ver)&0x7)<<3)
/* Mode Field [Bits 2:0] */
#define NTP_MODE_RESERVED 0
#define NTP_MODE_SYMACTIVE 1 /* Symmetric Active */
#define NTP_MODE_SYMPASSIVE 2 /* Symmetric Passive */
#define NTP_MODE_CLIENT 3
#define NTP_MODE_SERVER 4
#define NTP_MODE_BROADCAST 5
#define NTP_MODE_NTPCTRL 6 /* Reserved for NTP control message */
#define NTP_MODE_PRIVATE 7 /* Reserved for private use */
#define NTP_MODE_GET(pkt) (((pkt)->Control)&0x7)
#define NTP_MODE_SET(mode) ((mode)&0x7)
/* Time Base Conversion Macros
*
* The NTP timebase is 00:00 Jan 1 1900. The local
* time base is 00:00 Jan 1 1970. Convert between
* these two by added or substracting 70 years
* worth of time. Note that 17 of these years were
* leap years.
*/
#define TIME_BASEDIFF ((((cyg_uint32)70*365 + 17) * 24*3600))
#define TIME_NTP_TO_LOCAL(t) ((t)-TIME_BASEDIFF)
#define TIME_LOCAL_TO_NTP(t) ((t)+TIME_BASEDIFF)
struct sntp_srv_s {
struct sockaddr addr;
int stratum;
int version;
cyg_uint32 timestamp;
};
static int sntp_initialized = 0;
#ifdef CYGPKG_NET_SNTP_UNICAST
/* When using SNTP unicast mode, sntp_servers
* points to an array of char pointers that
* specify NTP server addresses to send
* requests to. sntp_num_servers specifies
* the number of hostnames in the array.
*/
static struct sockaddr *sntp_servers = NULL;
static cyg_uint32 sntp_num_servers = 0;
static cyg_mutex_t sntp_mutex;
static time_t NextTimeUpdate = 0;
/* SNTP Timeouts
*
* SNTP_WAITPERIOD is the number of seconds to wait
* before retransmitting unanswered NTP requests
* whenever we are due for an update.
*
* SNTP_UPDATEPERIOD is the number of seconds to wait
* after we get a good time update before we feel
* like we should re-synchronize again with the
* time server.
*/
#define SNTP_WAITPERIOD 10 /* Wait period in seconds */
#define SNTP_UPDATEPERIOD (30*60) /* Update period in seconds */
#endif /* CYKPKG_NET_SNTP_UNICAST */
#ifndef CYGNUM_SNTP_STACK_SIZE
/* Use a stack size of at least CYGNUM_SNTP_STACK_SIZE_MIN, but not less than
* CYGNUM_HAL_STACK_SIZE_TYPICAL.
*/
#define CYGNUM_SNTP_STACK_SIZE_MIN 4096
#if (CYGNUM_HAL_STACK_SIZE_TYPICAL < CYGNUM_SNTP_STACK_SIZE_MIN)
#define CYGNUM_SNTP_STACK_SIZE CYGNUM_SNTP_STACK_SIZE_MIN
#else
#define CYGNUM_SNTP_STACK_SIZE CYGNUM_HAL_STACK_SIZE_TYPICAL
#endif
#endif /* CYGNUM_SNTP_STACK_SIZE */
/* Is the new server better than the current one? If its the same as
the current, its always better. If the stratum is lower its better.
If we have not heard from the old server for more than 10 minutes,
the new server is better. */
static int is_better(struct sntp_srv_s *newer, struct sntp_srv_s *old) {
time_t last_time, diff;
if (!memcmp(&newer->addr, &old->addr, newer->addr.sa_len)) return 1;
if (newer->stratum < old->stratum) return 1;
if (old->timestamp != 0xffffffff) {
last_time = TIME_NTP_TO_LOCAL(old->timestamp);
diff = time(NULL) - last_time;
if (diff > 600) return 1;
return 0;
}
return 1;
}
const struct in6_addr in6addr_ntp_multicast = IN6ADDR_NTP_MULTICAST;
static void sntp_fn(cyg_addrword_t data)
{
int fd;
int ret;
struct sockaddr_in local;
struct servent *serv;
NTP_PACKET ntp_pkt;
struct sntp_srv_s new_srv;
struct sntp_srv_s best_srv;
int mode;
int len;
time_t new_time, current_time, diff;
fd_set readfds;
int n;
#ifdef CYGPKG_NET_INET6
int fd6 = -1;
struct ipv6_mreq mreq;
struct sockaddr_in6 local6;
#endif
#ifdef CYGPKG_NET_SNTP_UNICAST
int i;
struct timeval timeout;
#endif /* CYGPKG_NET_SNTP_UNICAST */
struct timeval *ptimeout = NULL;
memset(&best_srv,0xff,sizeof(best_srv));
fd = socket(AF_INET,SOCK_DGRAM,0);
CYG_ASSERT(-1 != fd,"Failed to open socket");
serv = getservbyname("ntp","udp");
CYG_ASSERT(serv,"getservbyname(sntp,udp)");
memset(&local,0,sizeof(local));
local.sin_family = AF_INET;
local.sin_len = sizeof(local);
local.sin_port = serv->s_port;
local.sin_addr.s_addr = INADDR_ANY;
ret=bind(fd,(struct sockaddr *)&local,sizeof(local));
CYG_ASSERT(0 == ret, "Bind failed");
n = fd;
#ifdef CYGPKG_NET_INET6
fd6 = socket(AF_INET6, SOCK_DGRAM,0);
CYG_ASSERT(-1 != fd,"Failed to open socket");
mreq.ipv6mr_multiaddr = in6addr_ntp_multicast;
mreq.ipv6mr_interface = 0;
/* Join the well-known NTP multicast groups. We will
* try to join the link-local, site-local, and global
* unicast groups.
*
* Note that we skip the node-local group since it
* doesn't make any sense to join that group. If we
* had an NTP server running on the local node, we
* wouldn't need to have an NTP client get the time
* from it!
*/
#ifdef CYGHWR_NET_DRIVER_ETH0
// Link-Local
mreq.ipv6mr_multiaddr.s6_addr[1]=0x02;
mreq.ipv6mr_interface = if_nametoindex("eth0");
if (mreq.ipv6mr_interface != 0 ) {
ret = setsockopt(fd6, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof(mreq));
CYG_ASSERT(0 == ret, "setsockopt(IPV6_JOIN_GROUP) Link-Local eth0");
}
#endif
#ifdef CYGHWR_NET_DRIVER_ETH1
// Link-Local
mreq.ipv6mr_multiaddr.s6_addr[1]=0x02;
mreq.ipv6mr_interface = if_nametoindex("eth1");
if (mreq.ipv6mr_interface != 0 ) {
ret = setsockopt(fd6, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof(mreq));
CYG_ASSERT(0 == ret, "setsockopt(IPV6_JOIN_GROUP) Link-Local eth1");
}
#endif
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -