synctime.c 12 KB

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