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