ntp.c 13 KB

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