synctime.c 12 KB

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