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