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