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