synctime.c 13 KB

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