2
0

synctime.c 13 KB

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