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