2
0

synctime.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2016, 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 http://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 http://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. * http://tf.nist.gov/timefreq/service/its.htm
  67. * http://tf.nist.gov/timefreq/service/firewall.htm
  68. *
  69. * Usage:
  70. * This software will synchronise your computer clock only when you issue
  71. * it with --synctime. By default, it only display the webserver's clock.
  72. *
  73. * Written by: Frank (contributed to libcurl)
  74. *
  75. * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
  76. * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
  77. * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
  78. *
  79. * IN NO EVENT SHALL THE AUTHOR OF THIS SOFTWARE BE LIABLE FOR
  80. * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
  81. * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  82. * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
  83. * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  84. * OF THIS SOFTWARE.
  85. *
  86. */
  87. #include <stdio.h>
  88. #include <time.h>
  89. #ifndef __CYGWIN__
  90. #include <windows.h>
  91. #endif
  92. #include <curl/curl.h>
  93. #define MAX_STRING 256
  94. #define MAX_STRING1 MAX_STRING+1
  95. #define SYNCTIME_UA "synctime/1.0"
  96. typedef struct
  97. {
  98. char http_proxy[MAX_STRING1];
  99. char proxy_user[MAX_STRING1];
  100. char timeserver[MAX_STRING1];
  101. } conf_t;
  102. const char DefaultTimeServer[3][MAX_STRING1] =
  103. {
  104. "http://pool.ntp.org/",
  105. "http://nist.time.gov/",
  106. "http://www.google.com/"
  107. };
  108. const char *DayStr[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
  109. const char *MthStr[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  110. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  111. int ShowAllHeader;
  112. int AutoSyncTime;
  113. SYSTEMTIME SYSTime;
  114. SYSTEMTIME LOCALTime;
  115. #define HTTP_COMMAND_HEAD 0
  116. #define HTTP_COMMAND_GET 1
  117. size_t SyncTime_CURL_WriteOutput(void *ptr, size_t size, size_t nmemb,
  118. void *stream)
  119. {
  120. fwrite(ptr, size, nmemb, stream);
  121. return (nmemb*size);
  122. }
  123. size_t SyncTime_CURL_WriteHeader(void *ptr, size_t size, size_t nmemb,
  124. void *stream)
  125. {
  126. int i, RetVal;
  127. char TmpStr1[26], TmpStr2[26];
  128. if(ShowAllHeader == 1)
  129. fprintf(stderr, "%s", (char *)(ptr));
  130. if(strncmp((char *)(ptr), "Date:", 5) == 0) {
  131. if(ShowAllHeader == 0)
  132. fprintf(stderr, "HTTP Server. %s", (char *)(ptr));
  133. if(AutoSyncTime == 1) {
  134. *TmpStr1 = 0;
  135. *TmpStr2 = 0;
  136. if(strlen((char *)(ptr)) > 50) /* Can prevent buffer overflow to
  137. TmpStr1 & 2? */
  138. AutoSyncTime = 0;
  139. else {
  140. RetVal = sscanf((char *)(ptr), "Date: %s %hu %s %hu %hu:%hu:%hu",
  141. TmpStr1, &SYSTime.wDay, TmpStr2, &SYSTime.wYear,
  142. &SYSTime.wHour, &SYSTime.wMinute, &SYSTime.wSecond);
  143. if(RetVal == 7) {
  144. SYSTime.wMilliseconds = 500; /* adjust to midpoint, 0.5 sec */
  145. for(i=0; i<12; i++) {
  146. if(strcmp(MthStr[i], TmpStr2) == 0) {
  147. SYSTime.wMonth = i+1;
  148. break;
  149. }
  150. }
  151. AutoSyncTime = 3; /* Computer clock will be adjusted */
  152. }
  153. else {
  154. AutoSyncTime = 0; /* Error in sscanf() fields conversion */
  155. }
  156. }
  157. }
  158. }
  159. if(strncmp((char *)(ptr), "X-Cache: HIT", 12) == 0) {
  160. fprintf(stderr, "ERROR: HTTP Server data is cached."
  161. " Server Date is no longer valid.\n");
  162. AutoSyncTime = 0;
  163. }
  164. return (nmemb*size);
  165. }
  166. void SyncTime_CURL_Init(CURL *curl, char *proxy_port,
  167. char *proxy_user_password)
  168. {
  169. if(strlen(proxy_port) > 0)
  170. curl_easy_setopt(curl, CURLOPT_PROXY, proxy_port);
  171. if(strlen(proxy_user_password) > 0)
  172. curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD, proxy_user_password);
  173. #ifdef SYNCTIME_UA
  174. curl_easy_setopt(curl, CURLOPT_USERAGENT, SYNCTIME_UA);
  175. #endif
  176. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, *SyncTime_CURL_WriteOutput);
  177. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, *SyncTime_CURL_WriteHeader);
  178. }
  179. int SyncTime_CURL_Fetch(CURL *curl, char *URL_Str, char *OutFileName,
  180. int HttpGetBody)
  181. {
  182. FILE *outfile;
  183. CURLcode res;
  184. outfile = NULL;
  185. if(HttpGetBody == HTTP_COMMAND_HEAD)
  186. curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
  187. else {
  188. outfile = fopen(OutFileName, "wb");
  189. curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfile);
  190. }
  191. curl_easy_setopt(curl, CURLOPT_URL, URL_Str);
  192. res = curl_easy_perform(curl);
  193. if(outfile != NULL)
  194. fclose(outfile);
  195. return res; /* (CURLE_OK) */
  196. }
  197. void showUsage(void)
  198. {
  199. fprintf(stderr, "SYNCTIME: Synchronising computer clock with time server"
  200. " using HTTP protocol.\n");
  201. fprintf(stderr, "Usage : SYNCTIME [Option]\n");
  202. fprintf(stderr, "Options :\n");
  203. fprintf(stderr, " --server=WEBSERVER Use this time server instead"
  204. " of default.\n");
  205. fprintf(stderr, " --showall Show all HTTP header.\n");
  206. fprintf(stderr, " --synctime Synchronising computer clock"
  207. " with time server.\n");
  208. fprintf(stderr, " --proxy-user=USER[:PASS] Set proxy username and"
  209. " password.\n");
  210. fprintf(stderr, " --proxy=HOST[:PORT] Use HTTP proxy on given"
  211. " port.\n");
  212. fprintf(stderr, " --help Print this help.\n");
  213. fprintf(stderr, "\n");
  214. return;
  215. }
  216. int conf_init(conf_t *conf)
  217. {
  218. int i;
  219. *conf->http_proxy = 0;
  220. for(i=0; i<MAX_STRING1; i++)
  221. conf->proxy_user[i] = 0; /* Clean up password from memory */
  222. *conf->timeserver = 0;
  223. return 1;
  224. }
  225. int main(int argc, char *argv[])
  226. {
  227. CURL *curl;
  228. conf_t conf[1];
  229. int OptionIndex;
  230. struct tm *lt;
  231. struct tm *gmt;
  232. time_t tt;
  233. time_t tt_local;
  234. time_t tt_gmt;
  235. double tzonediffFloat;
  236. int tzonediffWord;
  237. char timeBuf[61];
  238. char tzoneBuf[16];
  239. int RetValue;
  240. OptionIndex = 0;
  241. ShowAllHeader = 0; /* Do not show HTTP Header */
  242. AutoSyncTime = 0; /* Do not synchronise computer clock */
  243. RetValue = 0; /* Successful Exit */
  244. conf_init(conf);
  245. if(argc > 1) {
  246. while(OptionIndex < argc) {
  247. if(strncmp(argv[OptionIndex], "--server=", 9) == 0)
  248. snprintf(conf->timeserver, MAX_STRING, "%s", &argv[OptionIndex][9]);
  249. if(strcmp(argv[OptionIndex], "--showall") == 0)
  250. ShowAllHeader = 1;
  251. if(strcmp(argv[OptionIndex], "--synctime") == 0)
  252. AutoSyncTime = 1;
  253. if(strncmp(argv[OptionIndex], "--proxy-user=", 13) == 0)
  254. snprintf(conf->proxy_user, MAX_STRING, "%s", &argv[OptionIndex][13]);
  255. if(strncmp(argv[OptionIndex], "--proxy=", 8) == 0)
  256. snprintf(conf->http_proxy, MAX_STRING, "%s", &argv[OptionIndex][8]);
  257. if((strcmp(argv[OptionIndex], "--help") == 0) ||
  258. (strcmp(argv[OptionIndex], "/?") == 0)) {
  259. showUsage();
  260. return 0;
  261. }
  262. OptionIndex++;
  263. }
  264. }
  265. if(*conf->timeserver == 0) /* Use default server for time information */
  266. snprintf(conf->timeserver, MAX_STRING, "%s", DefaultTimeServer[0]);
  267. /* Init CURL before usage */
  268. curl_global_init(CURL_GLOBAL_ALL);
  269. curl = curl_easy_init();
  270. if(curl) {
  271. SyncTime_CURL_Init(curl, conf->http_proxy, conf->proxy_user);
  272. /* Calculating time diff between GMT and localtime */
  273. tt = time(0);
  274. lt = localtime(&tt);
  275. tt_local = mktime(lt);
  276. gmt = gmtime(&tt);
  277. tt_gmt = mktime(gmt);
  278. tzonediffFloat = difftime(tt_local, tt_gmt);
  279. tzonediffWord = (int)(tzonediffFloat/3600.0);
  280. if((double)(tzonediffWord * 3600) == tzonediffFloat)
  281. snprintf(tzoneBuf, 15, "%+03d'00'", tzonediffWord);
  282. else
  283. snprintf(tzoneBuf, 15, "%+03d'30'", tzonediffWord);
  284. /* Get current system time and local time */
  285. GetSystemTime(&SYSTime);
  286. GetLocalTime(&LOCALTime);
  287. snprintf(timeBuf, 60, "%s, %02d %s %04d %02d:%02d:%02d.%03d, ",
  288. DayStr[LOCALTime.wDayOfWeek], LOCALTime.wDay,
  289. MthStr[LOCALTime.wMonth-1], LOCALTime.wYear,
  290. LOCALTime.wHour, LOCALTime.wMinute, LOCALTime.wSecond,
  291. LOCALTime.wMilliseconds);
  292. fprintf(stderr, "Fetch: %s\n\n", conf->timeserver);
  293. fprintf(stderr, "Before HTTP. Date: %s%s\n\n", timeBuf, tzoneBuf);
  294. /* HTTP HEAD command to the Webserver */
  295. SyncTime_CURL_Fetch(curl, conf->timeserver, "index.htm",
  296. HTTP_COMMAND_HEAD);
  297. GetLocalTime(&LOCALTime);
  298. snprintf(timeBuf, 60, "%s, %02d %s %04d %02d:%02d:%02d.%03d, ",
  299. DayStr[LOCALTime.wDayOfWeek], LOCALTime.wDay,
  300. MthStr[LOCALTime.wMonth-1], LOCALTime.wYear,
  301. LOCALTime.wHour, LOCALTime.wMinute, LOCALTime.wSecond,
  302. LOCALTime.wMilliseconds);
  303. fprintf(stderr, "\nAfter HTTP. Date: %s%s\n", timeBuf, tzoneBuf);
  304. if(AutoSyncTime == 3) {
  305. /* Synchronising computer clock */
  306. if(!SetSystemTime(&SYSTime)) { /* Set system time */
  307. fprintf(stderr, "ERROR: Unable to set system time.\n");
  308. RetValue = 1;
  309. }
  310. else {
  311. /* Successfully re-adjusted computer clock */
  312. GetLocalTime(&LOCALTime);
  313. snprintf(timeBuf, 60, "%s, %02d %s %04d %02d:%02d:%02d.%03d, ",
  314. DayStr[LOCALTime.wDayOfWeek], LOCALTime.wDay,
  315. MthStr[LOCALTime.wMonth-1], LOCALTime.wYear,
  316. LOCALTime.wHour, LOCALTime.wMinute, LOCALTime.wSecond,
  317. LOCALTime.wMilliseconds);
  318. fprintf(stderr, "\nNew System's Date: %s%s\n", timeBuf, tzoneBuf);
  319. }
  320. }
  321. /* Cleanup before exit */
  322. conf_init(conf);
  323. curl_easy_cleanup(curl);
  324. }
  325. return RetValue;
  326. }