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