ntp.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. /*
  2. *
  3. * (C) 2014 David Lettier.
  4. * (C) 2018 Armink (armink.ztl@gmail.com)
  5. *
  6. * http://www.lettier.com/
  7. *
  8. * NTP client.
  9. *
  10. * Compiled with gcc version 4.7.2 20121109 (Red Hat 4.7.2-8) (GCC).
  11. *
  12. * Tested on Linux 3.8.11-200.fc18.x86_64 #1 SMP Wed May 1 19:44:27 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux.
  13. * Tested on RT-Thread 3.0.0+
  14. *
  15. * To compile: $ gcc main.c -o ntpClient.out
  16. *
  17. * Usage: $ ./ntpClient.out
  18. *
  19. * Change Logs:
  20. * Date Author Notes
  21. * 2018-02-10 armink the first version
  22. * 2020-07-21 Chenxuan C++ support
  23. * 2021-05-09 Meco Man remove timezone function
  24. */
  25. #include <rtthread.h>
  26. #ifdef PKG_NETUTILS_NTP
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <sys/time.h>
  31. #include <sys/types.h>
  32. #include <rtdevice.h>
  33. #if defined(RT_USING_SAL)
  34. #include <arpa/inet.h>
  35. #include <sys/socket.h>
  36. #include <netdb.h>
  37. #elif defined(RT_USING_LWIP)
  38. #include <lwip/inet.h>
  39. #include <lwip/sockets.h>
  40. #include <lwip/netdb.h>
  41. extern struct hostent *gethostbyname(const char *name);
  42. extern int recvfrom(int s, void *mem, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen);
  43. extern int sendto(int s, const void *dataptr, size_t size, int flags, const struct sockaddr *to, socklen_t tolen);
  44. extern int socket(int domain, int type, int protocol);
  45. extern int closesocket(int s);
  46. #endif /* RT_USING_SAL */
  47. #if defined(RT_USING_NETDEV)
  48. #include <netdev.h>
  49. #elif defined(RT_USING_LWIP)
  50. #include <lwip/netif.h>
  51. #endif /* RT_USING_NETDEV */
  52. #define DBG_SECTION_NAME "ntp"
  53. #define DBG_LEVEL DBG_INFO
  54. #include <rtdbg.h>
  55. #if RT_VER_NUM <= 0x40003
  56. #ifndef NETUTILS_NTP_TIMEZONE
  57. #define NETUTILS_NTP_TIMEZONE 8
  58. #endif
  59. #endif
  60. #ifdef NETUTILS_NTP_HOSTNAME
  61. #define NTP_HOSTNAME1 NETUTILS_NTP_HOSTNAME
  62. #else
  63. #define NTP_HOSTNAME1 NULL
  64. #endif
  65. #ifdef NETUTILS_NTP_HOSTNAME2
  66. #define NTP_HOSTNAME2 NETUTILS_NTP_HOSTNAME2
  67. #else
  68. #define NTP_HOSTNAME2 NULL
  69. #endif
  70. #ifdef NETUTILS_NTP_HOSTNAME3
  71. #define NTP_HOSTNAME3 NETUTILS_NTP_HOSTNAME3
  72. #else
  73. #define NTP_HOSTNAME3 NULL
  74. #endif
  75. #define NTP_TIMESTAMP_DELTA 2208988800ull
  76. #define LI(packet) (uint8_t) ((packet.li_vn_mode & 0xC0) >> 6) // (li & 11 000 000) >> 6
  77. #define VN(packet) (uint8_t) ((packet.li_vn_mode & 0x38) >> 3) // (vn & 00 111 000) >> 3
  78. #define MODE(packet) (uint8_t) ((packet.li_vn_mode & 0x07) >> 0) // (mode & 00 000 111) >> 0
  79. // Structure that defines the 48 byte NTP packet protocol.
  80. typedef struct {
  81. uint8_t li_vn_mode; // Eight bits. li, vn, and mode.
  82. // li. Two bits. Leap indicator.
  83. // vn. Three bits. Version number of the protocol.
  84. // mode. Three bits. Client will pick mode 3 for client.
  85. uint8_t stratum; // Eight bits. Stratum level of the local clock.
  86. uint8_t poll; // Eight bits. Maximum interval between successive messages.
  87. uint8_t precision; // Eight bits. Precision of the local clock.
  88. uint32_t rootDelay; // 32 bits. Total round trip delay time.
  89. uint32_t rootDispersion; // 32 bits. Max error aloud from primary clock source.
  90. uint32_t refId; // 32 bits. Reference clock identifier.
  91. uint32_t refTm_s; // 32 bits. Reference time-stamp seconds.
  92. uint32_t refTm_f; // 32 bits. Reference time-stamp fraction of a second.
  93. uint32_t origTm_s; // 32 bits. Originate time-stamp seconds.
  94. uint32_t origTm_f; // 32 bits. Originate time-stamp fraction of a second.
  95. uint32_t rxTm_s; // 32 bits. Received time-stamp seconds.
  96. uint32_t rxTm_f; // 32 bits. Received time-stamp fraction of a second.
  97. uint32_t txTm_s; // 32 bits and the most important field the client cares about. Transmit time-stamp seconds.
  98. uint32_t txTm_f; // 32 bits. Transmit time-stamp fraction of a second.
  99. } ntp_packet; // Total: 384 bits or 48 bytes.
  100. static ntp_packet packet = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  101. static int sendto_ntp_server(int sockfd, const char *host_name, struct sockaddr_in *serv_addr)
  102. {
  103. struct hostent *server;
  104. socklen_t addr_len = sizeof(struct sockaddr_in);
  105. /* NTP UDP port number. */
  106. int portno = 123;
  107. server = gethostbyname(host_name);
  108. if (server == NULL)
  109. {
  110. LOG_D("No such host(%s)", host_name);
  111. return -RT_ERROR;
  112. }
  113. else
  114. {
  115. /* Zero out the server address structure. */
  116. rt_memset((char *)serv_addr, 0, addr_len);
  117. serv_addr->sin_family = AF_INET;
  118. /* Convert the port number integer to network big-endian style and save it to the server address structure. */
  119. serv_addr->sin_port = htons(portno);
  120. /* Copy the server's IP address to the server address structure. */
  121. rt_memcpy(&serv_addr->sin_addr.s_addr, (char *) server->h_addr, server->h_length);
  122. return sendto(sockfd, (char *) &packet, sizeof(ntp_packet), 0, (const struct sockaddr *)serv_addr, addr_len);
  123. }
  124. }
  125. /**
  126. * Get the UTC time from NTP server
  127. *
  128. * @param host_name NTP server host name, NULL: will using default host name
  129. *
  130. * @note this function is not reentrant
  131. *
  132. * @return >0: success, current GMT time
  133. * =0: get failed
  134. */
  135. time_t ntp_get_time(const char *host_name)
  136. {
  137. /* the delay(ms) between two receive */
  138. #define RECV_TIME_DELAY_MS 10
  139. /* NTP receive timeout(S) */
  140. #define NTP_GET_TIMEOUT 5
  141. /* number of NTP servers */
  142. #define NTP_SERVER_NUM 3
  143. int sockfd, n, i = 0, server_num = 0;
  144. struct sockaddr_in serv_addr[NTP_SERVER_NUM];
  145. rt_tick_t start = 0;
  146. time_t new_time = 0;
  147. socklen_t addr_len = sizeof(struct sockaddr_in);
  148. const char *const host_name_buf[NTP_SERVER_NUM] = {NTP_HOSTNAME1, NTP_HOSTNAME2, NTP_HOSTNAME3};
  149. /* Create and zero out the packet. All 48 bytes worth. */
  150. rt_memset(&packet, 0, sizeof(ntp_packet));
  151. /* Set the first byte's bits to 00,011,011 for li = 0, vn = 3, and mode = 3. The rest will be left set to zero.
  152. Represents 27 in base 10 or 00011011 in base 2. */
  153. *((char *) &packet + 0) = 0x1b;
  154. #if defined(RT_USING_NETDEV) || defined(RT_USING_LWIP)
  155. {
  156. #define NTP_INTERNET 0x02
  157. #define NTP_INTERNET_BUFF_LEN 18
  158. #define NTP_INTERNET_MONTH_LEN 4
  159. #define NTP_INTERNET_DATE_LEN 16
  160. #ifndef SW_VER_NUM
  161. #define SW_VER_NUM 0x00000000
  162. #endif
  163. const char month[][NTP_INTERNET_MONTH_LEN] =
  164. {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
  165. char date[NTP_INTERNET_DATE_LEN] = {0};
  166. uint8_t send_data[NTP_INTERNET_BUFF_LEN] = {0};
  167. uint8_t index, moth_num = 0;
  168. uint16_t check = 0;
  169. /* get build moth value*/
  170. rt_snprintf(date, NTP_INTERNET_DATE_LEN, "%s", __DATE__);
  171. for (index = 0; index < sizeof(month) / NTP_INTERNET_MONTH_LEN; index++)
  172. {
  173. if (rt_memcmp(date, month[index], NTP_INTERNET_MONTH_LEN - 1) == 0)
  174. {
  175. moth_num = index + 1;
  176. break;
  177. }
  178. }
  179. send_data[0] = NTP_INTERNET;
  180. /* get hardware address */
  181. {
  182. #if defined(RT_USING_LWIP) && !defined(RT_USING_NETDEV)
  183. #define netdev netif
  184. #define netdev_default netif_default
  185. #endif
  186. extern struct netdev *netdev_default;
  187. struct netdev *dev = netdev_default;
  188. for (index = 0; index < dev->hwaddr_len; index++)
  189. {
  190. send_data[index + 1] = dev->hwaddr[index] + moth_num;
  191. }
  192. }
  193. send_data[9] = RT_VERSION;
  194. send_data[10] = RT_SUBVERSION;
  195. send_data[11] = RT_REVISION;
  196. send_data[12] = (uint8_t)(SW_VER_NUM >> 24);
  197. send_data[13] = (uint8_t)(SW_VER_NUM >> 16);
  198. send_data[14] = (uint8_t)(SW_VER_NUM >> 8);
  199. send_data[15] = (uint8_t)(SW_VER_NUM & 0xFF);
  200. /* get the check value */
  201. for (index = 0; index < NTP_INTERNET_BUFF_LEN - sizeof(check); index++)
  202. {
  203. check += (uint8_t)send_data[index];
  204. }
  205. send_data[NTP_INTERNET_BUFF_LEN - 2] = check >> 8;
  206. send_data[NTP_INTERNET_BUFF_LEN - 1] = check & 0xFF;
  207. rt_memcpy(((char *)&packet + 4), send_data, NTP_INTERNET_BUFF_LEN);
  208. }
  209. #endif /* RT_USING_NETDEV || RT_USING_LWIP */
  210. /* Create a UDP socket. */
  211. sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  212. if (sockfd < 0)
  213. {
  214. LOG_E("Create socket failed");
  215. return 0;
  216. }
  217. if (host_name)
  218. {
  219. /* access the incoming host_name server */
  220. if (sendto_ntp_server(sockfd, host_name, serv_addr) >= 0)
  221. {
  222. server_num = 1;
  223. }
  224. }
  225. else
  226. {
  227. /* use the static default NTP server */
  228. for (i = 0; i < NTP_SERVER_NUM; i++)
  229. {
  230. if (host_name_buf[i] == NULL || strlen(host_name_buf[i]) == 0)
  231. continue;
  232. if (sendto_ntp_server(sockfd, host_name_buf[i], &serv_addr[server_num]) >= 0)
  233. {
  234. server_num ++;
  235. }
  236. }
  237. }
  238. if (server_num <= 0)
  239. {
  240. closesocket(sockfd);
  241. return 0;
  242. }
  243. start = rt_tick_get();
  244. while (rt_tick_get() <= start + NTP_GET_TIMEOUT * RT_TICK_PER_SECOND)
  245. {
  246. for (i = 0; i < server_num; i++)
  247. {
  248. /* non-blocking receive the packet back from the server. If n == -1, it failed. */
  249. n = recvfrom(sockfd, (char *) &packet, sizeof(ntp_packet), MSG_DONTWAIT, (struct sockaddr *)&serv_addr[i], &addr_len);
  250. if (n <= 0)
  251. {
  252. LOG_D("Reading from server %s error (%d).", inet_ntoa(serv_addr[i].sin_addr.s_addr), n);
  253. }
  254. else if (n > 0)
  255. {
  256. goto __exit;
  257. }
  258. }
  259. rt_thread_mdelay(RECV_TIME_DELAY_MS);
  260. }
  261. __exit:
  262. if (rt_tick_get() <= start + NTP_GET_TIMEOUT * RT_TICK_PER_SECOND)
  263. {
  264. /* These two fields contain the time-stamp seconds as the packet left the NTP server.
  265. The number of seconds correspond to the seconds passed since 1900.
  266. ntohl() converts the bit/byte order from the network's to host's "endianness". */
  267. packet.txTm_s = ntohl(packet.txTm_s); // Time-stamp seconds.
  268. packet.txTm_f = ntohl(packet.txTm_f); // Time-stamp fraction of a second.
  269. /* Extract the 32 bits that represent the time-stamp seconds (since NTP epoch) from when the packet left the server.
  270. Subtract 70 years worth of seconds from the seconds since 1900.
  271. This leaves the seconds since the UNIX epoch of 1970.
  272. (1900)------------------(1970)**************************************(Time Packet Left the Server) */
  273. new_time = (time_t)(packet.txTm_s - NTP_TIMESTAMP_DELTA);
  274. }
  275. else
  276. {
  277. LOG_E("Receive the socket from server timeout (%dS).", NTP_GET_TIMEOUT);
  278. }
  279. closesocket(sockfd);
  280. return new_time;
  281. }
  282. #if RT_VER_NUM <= 0x40003
  283. /**
  284. * Get the local time from NTP server
  285. *
  286. * @param host_name NTP server host name, NULL: will using default host name
  287. *
  288. * @return >0: success, current local time, offset timezone by NETUTILS_NTP_TIMEZONE
  289. * =0: get failed
  290. */
  291. time_t ntp_get_local_time(const char *host_name)
  292. {
  293. time_t cur_time = ntp_get_time(host_name);
  294. if (cur_time)
  295. {
  296. /* add the timezone offset for set_time/set_date */
  297. cur_time += NETUTILS_NTP_TIMEZONE * 3600;
  298. }
  299. return cur_time;
  300. }
  301. #endif
  302. /**
  303. * Sync current local time to RTC by NTP
  304. *
  305. * @param host_name NTP server host name, NULL: will using default host name
  306. *
  307. * @return >0: success
  308. * =0: sync failed
  309. */
  310. time_t ntp_sync_to_rtc(const char *host_name)
  311. {
  312. #if RT_VER_NUM <= 0x40003
  313. time_t cur_time = ntp_get_local_time(host_name);
  314. #else
  315. time_t cur_time = ntp_get_time(host_name); /*after v4.0.3, RT-Thread takes over the timezone management*/
  316. #endif
  317. if (cur_time)
  318. {
  319. #ifdef RT_USING_RTC
  320. #if RT_VER_NUM <= 0x40003
  321. struct tm *cur_tm;
  322. cur_tm = localtime(&cur_time);
  323. set_time(cur_tm->tm_hour, cur_tm->tm_min, cur_tm->tm_sec);
  324. set_date(cur_tm->tm_year + 1900, cur_tm->tm_mon + 1, cur_tm->tm_mday);
  325. #else
  326. rt_device_control(rt_device_find("rtc"), RT_DEVICE_CTRL_RTC_SET_TIME, &cur_time);
  327. #endif /*RT_VER_NUM <= 0x40003*/
  328. LOG_I("Get local time from NTP server: %s", ctime((const time_t *) &cur_time));
  329. #else
  330. LOG_E("The system time update failed. Please enable RT_USING_RTC.\n");
  331. cur_time = 0;
  332. #endif /* RT_USING_RTC */
  333. }
  334. return cur_time;
  335. }
  336. #if RT_VER_NUM > 0x40003
  337. /* NTP first sync delay time for network connect, unit: second */
  338. #ifndef RTC_NTP_FIRST_SYNC_DELAY
  339. #define RTC_NTP_FIRST_SYNC_DELAY (30)
  340. #endif
  341. /* NTP sync period, unit: second */
  342. #ifndef RTC_NTP_SYNC_PERIOD
  343. #define RTC_NTP_SYNC_PERIOD (1L*60L*60L)
  344. #endif
  345. static void ntp_sync_thread_enrty(void *param)
  346. {
  347. /* first sync delay for network connect */
  348. rt_thread_delay(RTC_NTP_FIRST_SYNC_DELAY * RT_TICK_PER_SECOND);
  349. while (1)
  350. {
  351. ntp_sync_to_rtc(NULL);
  352. rt_thread_delay(RTC_NTP_SYNC_PERIOD * RT_TICK_PER_SECOND);
  353. }
  354. }
  355. static int rt_rtc_ntp_sync_init(void)
  356. {
  357. static rt_bool_t init_ok = RT_FALSE;
  358. rt_thread_t thread;
  359. if (init_ok)
  360. {
  361. return 0;
  362. }
  363. thread = rt_thread_create("ntp_sync", ntp_sync_thread_enrty, RT_NULL, 1300, RT_THREAD_PRIORITY_MAX - 2, 20);
  364. if (thread)
  365. {
  366. rt_thread_startup(thread);
  367. }
  368. else
  369. {
  370. return -RT_ENOMEM;
  371. }
  372. init_ok = RT_TRUE;
  373. return RT_EOK;
  374. }
  375. INIT_COMPONENT_EXPORT(rt_rtc_ntp_sync_init);
  376. #endif
  377. #ifdef FINSH_USING_MSH
  378. #include <finsh.h>
  379. static void cmd_ntp_sync(int argc, char **argv)
  380. {
  381. char *host_name = NULL;
  382. if (argc > 1)
  383. {
  384. host_name = argv[1];
  385. }
  386. ntp_sync_to_rtc(host_name);
  387. }
  388. MSH_CMD_EXPORT_ALIAS(cmd_ntp_sync, ntp_sync, Update time by NTP(Network Time Protocol): ntp_sync [host_name]);
  389. #endif /* RT_USING_FINSH */
  390. #endif /* PKG_NETUTILS_NTP */