synctime.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. /* <DESC>
  25. * Set your system time from a remote HTTP server's Date: header.
  26. * </DESC>
  27. */
  28. /* This example code only builds as-is on Windows.
  29. *
  30. * While Unix/Linux user, you do not need this software.
  31. * You can achieve the same result as synctime using curl, awk and date.
  32. * Set proxy as according to your network, but beware of proxy Cache-Control.
  33. *
  34. * To set your system clock, root access is required.
  35. * # date -s "`curl -sI https://nist.time.gov/timezone.cgi?UTC/s/0 \
  36. * | awk -F': ' '/Date: / {print $2}'`"
  37. *
  38. * To view remote webserver date and time.
  39. * $ curl -sI https://nist.time.gov/timezone.cgi?UTC/s/0 \
  40. * | awk -F': ' '/Date: / {print $2}'
  41. *
  42. * Synchronising your computer clock via Internet time server usually relies
  43. * on DAYTIME, TIME, or NTP protocols. These protocols provide good accurate
  44. * time synchronization but it does not work well through a
  45. * firewall/proxy. Some adjustment has to be made to the firewall/proxy for
  46. * these protocols to work properly.
  47. *
  48. * There is an indirect method. Since most webserver provide server time in
  49. * their HTTP header, therefore you could synchronise your computer clock
  50. * using HTTP protocol which has no problem with firewall/proxy.
  51. *
  52. * For this software to work, you should take note of these items.
  53. * 1. Your firewall/proxy must allow your computer to surf internet.
  54. * 2. Webserver system time must in sync with the NTP time server,
  55. * or at least provide an accurate time keeping.
  56. * 3. Webserver HTTP header does not provide the milliseconds units,
  57. * so there is no way to get an accurate time.
  58. * 4. This software could only provide an accuracy of +- a few seconds,
  59. * as Round-Trip delay time is not taken into consideration.
  60. * Compensation of network, firewall/proxy delay cannot be simply divide
  61. * the Round-Trip delay time by half.
  62. * 5. Win32 SetSystemTime() API will set your computer clock according to
  63. * GMT/UTC time. Therefore your computer timezone must be properly set.
  64. * 6. Webserver data should not be cached by the proxy server. Some
  65. * webserver provide Cache-Control to prevent caching.
  66. *
  67. * References:
  68. * https://web.archive.org/web/20100228012139/ \
  69. * tf.nist.gov/timefreq/service/its.htm
  70. * https://web.archive.org/web/20100409024302/ \
  71. * tf.nist.gov/timefreq/service/firewall.htm
  72. *
  73. * Usage:
  74. * This software will synchronise your computer clock only when you issue
  75. * it with --synctime. By default, it only display the webserver's clock.
  76. *
  77. * Written by: Frank (contributed to libcurl)
  78. *
  79. * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
  80. * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
  81. * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
  82. *
  83. * IN NO EVENT SHALL THE AUTHOR OF THIS SOFTWARE BE LIABLE FOR
  84. * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
  85. * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  86. * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
  87. * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  88. * OF THIS SOFTWARE.
  89. *
  90. */
  91. #include <stdio.h>
  92. #include <time.h>
  93. #include <curl/curl.h>
  94. #ifdef _WIN32
  95. #include <windows.h>
  96. #endif
  97. #define MAX_STRING 256
  98. #define MAX_STRING1 MAX_STRING + 1
  99. #define SYNCTIME_UA "synctime/1.0"
  100. typedef struct
  101. {
  102. char http_proxy[MAX_STRING1];
  103. char proxy_user[MAX_STRING1];
  104. char timeserver[MAX_STRING1];
  105. } conf_t;
  106. const char DefaultTimeServer[3][MAX_STRING1] =
  107. {
  108. "https://nist.time.gov/",
  109. "https://www.google.com/"
  110. };
  111. const char *DayStr[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
  112. const char *MthStr[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  113. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  114. int ShowAllHeader;
  115. int AutoSyncTime;
  116. SYSTEMTIME SYSTime;
  117. SYSTEMTIME LOCALTime;
  118. #define HTTP_COMMAND_HEAD 0
  119. #define HTTP_COMMAND_GET 1
  120. size_t SyncTime_CURL_WriteOutput(void *ptr, size_t size, size_t nmemb,
  121. void *stream)
  122. {
  123. fwrite(ptr, size, nmemb, stream);
  124. return (nmemb*size);
  125. }
  126. size_t SyncTime_CURL_WriteHeader(void *ptr, size_t size, size_t nmemb,
  127. void *stream)
  128. {
  129. char TmpStr1[26], TmpStr2[26];
  130. (void)stream;
  131. if(ShowAllHeader == 1)
  132. fprintf(stderr, "%s", (char *)(ptr));
  133. if(strncmp((char *)(ptr), "Date:", 5) == 0) {
  134. if(ShowAllHeader == 0)
  135. fprintf(stderr, "HTTP Server. %s", (char *)(ptr));
  136. if(AutoSyncTime == 1) {
  137. *TmpStr1 = 0;
  138. *TmpStr2 = 0;
  139. if(strlen((char *)(ptr)) > 50) /* Can prevent buffer overflow to
  140. TmpStr1 & 2? */
  141. AutoSyncTime = 0;
  142. else {
  143. int RetVal = sscanf((char *)(ptr), "Date: %25s %hu %s %hu %hu:%hu:%hu",
  144. TmpStr1, &SYSTime.wDay, TmpStr2, &SYSTime.wYear,
  145. &SYSTime.wHour, &SYSTime.wMinute,
  146. &SYSTime.wSecond);
  147. if(RetVal == 7) {
  148. int i;
  149. SYSTime.wMilliseconds = 500; /* adjust to midpoint, 0.5 sec */
  150. for(i = 0; i<12; i++) {
  151. if(strcmp(MthStr[i], TmpStr2) == 0) {
  152. SYSTime.wMonth = i + 1;
  153. break;
  154. }
  155. }
  156. AutoSyncTime = 3; /* Computer clock will be adjusted */
  157. }
  158. else {
  159. AutoSyncTime = 0; /* Error in sscanf() fields conversion */
  160. }
  161. }
  162. }
  163. }
  164. if(strncmp((char *)(ptr), "X-Cache: HIT", 12) == 0) {
  165. fprintf(stderr, "ERROR: HTTP Server data is cached."
  166. " Server Date is no longer valid.\n");
  167. AutoSyncTime = 0;
  168. }
  169. return (nmemb*size);
  170. }
  171. void SyncTime_CURL_Init(CURL *curl, char *proxy_port,
  172. char *proxy_user_password)
  173. {
  174. if(strlen(proxy_port) > 0)
  175. curl_easy_setopt(curl, CURLOPT_PROXY, proxy_port);
  176. if(strlen(proxy_user_password) > 0)
  177. curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD, proxy_user_password);
  178. #ifdef SYNCTIME_UA
  179. curl_easy_setopt(curl, CURLOPT_USERAGENT, SYNCTIME_UA);
  180. #endif
  181. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, SyncTime_CURL_WriteOutput);
  182. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, SyncTime_CURL_WriteHeader);
  183. }
  184. int SyncTime_CURL_Fetch(CURL *curl, char *URL_Str, char *OutFileName,
  185. int HttpGetBody)
  186. {
  187. FILE *outfile;
  188. CURLcode res;
  189. outfile = NULL;
  190. if(HttpGetBody == HTTP_COMMAND_HEAD)
  191. curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
  192. else {
  193. outfile = fopen(OutFileName, "wb");
  194. curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfile);
  195. }
  196. curl_easy_setopt(curl, CURLOPT_URL, URL_Str);
  197. res = curl_easy_perform(curl);
  198. if(outfile)
  199. fclose(outfile);
  200. return res; /* (CURLE_OK) */
  201. }
  202. void showUsage(void)
  203. {
  204. fprintf(stderr, "SYNCTIME: Synchronising computer clock with time server"
  205. " using HTTP protocol.\n");
  206. fprintf(stderr, "Usage : SYNCTIME [Option]\n");
  207. fprintf(stderr, "Options :\n");
  208. fprintf(stderr, " --server=WEBSERVER Use this time server instead"
  209. " of default.\n");
  210. fprintf(stderr, " --showall Show all HTTP header.\n");
  211. fprintf(stderr, " --synctime Synchronising computer clock"
  212. " with time server.\n");
  213. fprintf(stderr, " --proxy-user=USER[:PASS] Set proxy username and"
  214. " password.\n");
  215. fprintf(stderr, " --proxy=HOST[:PORT] Use HTTP proxy on given"
  216. " port.\n");
  217. fprintf(stderr, " --help Print this help.\n");
  218. fprintf(stderr, "\n");
  219. return;
  220. }
  221. int conf_init(conf_t *conf)
  222. {
  223. int i;
  224. *conf->http_proxy = 0;
  225. for(i = 0; i<MAX_STRING1; i++)
  226. conf->proxy_user[i] = 0; /* Clean up password from memory */
  227. *conf->timeserver = 0;
  228. return 1;
  229. }
  230. int main(int argc, char *argv[])
  231. {
  232. CURL *curl;
  233. conf_t conf[1];
  234. int RetValue;
  235. ShowAllHeader = 0; /* Do not show HTTP Header */
  236. AutoSyncTime = 0; /* Do not synchronise computer clock */
  237. RetValue = 0; /* Successful Exit */
  238. conf_init(conf);
  239. if(argc > 1) {
  240. int OptionIndex = 0;
  241. while(OptionIndex < argc) {
  242. if(strncmp(argv[OptionIndex], "--server=", 9) == 0)
  243. snprintf(conf->timeserver, MAX_STRING, "%s", &argv[OptionIndex][9]);
  244. if(strcmp(argv[OptionIndex], "--showall") == 0)
  245. ShowAllHeader = 1;
  246. if(strcmp(argv[OptionIndex], "--synctime") == 0)
  247. AutoSyncTime = 1;
  248. if(strncmp(argv[OptionIndex], "--proxy-user=", 13) == 0)
  249. snprintf(conf->proxy_user, MAX_STRING, "%s", &argv[OptionIndex][13]);
  250. if(strncmp(argv[OptionIndex], "--proxy=", 8) == 0)
  251. snprintf(conf->http_proxy, MAX_STRING, "%s", &argv[OptionIndex][8]);
  252. if((strcmp(argv[OptionIndex], "--help") == 0) ||
  253. (strcmp(argv[OptionIndex], "/?") == 0)) {
  254. showUsage();
  255. return 0;
  256. }
  257. OptionIndex++;
  258. }
  259. }
  260. if(*conf->timeserver == 0) /* Use default server for time information */
  261. snprintf(conf->timeserver, MAX_STRING, "%s", DefaultTimeServer[0]);
  262. /* Init CURL before usage */
  263. curl_global_init(CURL_GLOBAL_ALL);
  264. curl = curl_easy_init();
  265. if(curl) {
  266. struct tm *lt;
  267. struct tm *gmt;
  268. time_t tt;
  269. time_t tt_local;
  270. time_t tt_gmt;
  271. double tzonediffFloat;
  272. int tzonediffWord;
  273. char timeBuf[61];
  274. char tzoneBuf[16];
  275. SyncTime_CURL_Init(curl, conf->http_proxy, conf->proxy_user);
  276. /* Calculating time diff between GMT and localtime */
  277. tt = time(0);
  278. lt = localtime(&tt);
  279. tt_local = mktime(lt);
  280. gmt = gmtime(&tt);
  281. tt_gmt = mktime(gmt);
  282. tzonediffFloat = difftime(tt_local, tt_gmt);
  283. tzonediffWord = (int)(tzonediffFloat/3600.0);
  284. if((double)(tzonediffWord * 3600) == tzonediffFloat)
  285. snprintf(tzoneBuf, 15, "%+03d'00'", tzonediffWord);
  286. else
  287. snprintf(tzoneBuf, 15, "%+03d'30'", tzonediffWord);
  288. /* Get current system time and local time */
  289. GetSystemTime(&SYSTime);
  290. GetLocalTime(&LOCALTime);
  291. snprintf(timeBuf, 60, "%s, %02d %s %04d %02d:%02d:%02d.%03d, ",
  292. DayStr[LOCALTime.wDayOfWeek], LOCALTime.wDay,
  293. MthStr[LOCALTime.wMonth-1], LOCALTime.wYear,
  294. LOCALTime.wHour, LOCALTime.wMinute, LOCALTime.wSecond,
  295. LOCALTime.wMilliseconds);
  296. fprintf(stderr, "Fetch: %s\n\n", conf->timeserver);
  297. fprintf(stderr, "Before HTTP. Date: %s%s\n\n", timeBuf, tzoneBuf);
  298. /* HTTP HEAD command to the Webserver */
  299. SyncTime_CURL_Fetch(curl, conf->timeserver, "index.htm",
  300. HTTP_COMMAND_HEAD);
  301. GetLocalTime(&LOCALTime);
  302. snprintf(timeBuf, 60, "%s, %02d %s %04d %02d:%02d:%02d.%03d, ",
  303. DayStr[LOCALTime.wDayOfWeek], LOCALTime.wDay,
  304. MthStr[LOCALTime.wMonth-1], LOCALTime.wYear,
  305. LOCALTime.wHour, LOCALTime.wMinute, LOCALTime.wSecond,
  306. LOCALTime.wMilliseconds);
  307. fprintf(stderr, "\nAfter HTTP. Date: %s%s\n", timeBuf, tzoneBuf);
  308. if(AutoSyncTime == 3) {
  309. /* Synchronising computer clock */
  310. if(!SetSystemTime(&SYSTime)) { /* Set system time */
  311. fprintf(stderr, "ERROR: Unable to set system time.\n");
  312. RetValue = 1;
  313. }
  314. else {
  315. /* Successfully re-adjusted computer clock */
  316. GetLocalTime(&LOCALTime);
  317. snprintf(timeBuf, 60, "%s, %02d %s %04d %02d:%02d:%02d.%03d, ",
  318. DayStr[LOCALTime.wDayOfWeek], LOCALTime.wDay,
  319. MthStr[LOCALTime.wMonth-1], LOCALTime.wYear,
  320. LOCALTime.wHour, LOCALTime.wMinute, LOCALTime.wSecond,
  321. LOCALTime.wMilliseconds);
  322. fprintf(stderr, "\nNew System's Date: %s%s\n", timeBuf, tzoneBuf);
  323. }
  324. }
  325. /* Cleanup before exit */
  326. conf_init(conf);
  327. curl_easy_cleanup(curl);
  328. }
  329. return RetValue;
  330. }