Prevent crash when no URL is specified.
[wine] / dlls / ntdll / time.c
1 /*
2  * Nt time functions.
3  *
4  * RtlTimeToTimeFields, RtlTimeFieldsToTime and defines are taken from ReactOS and
5  * adapted to wine with special permissions of the author. This code is
6  * Copyright 2002 Rex Jolliff (rex@lvcablemodem.com)
7  *
8  * Copyright 1999 Juergen Schmied
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  */
24
25 #include "config.h"
26 #include "wine/port.h"
27
28 #include <stdarg.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <limits.h>
32 #include <time.h>
33 #ifdef HAVE_SYS_TIME_H
34 # include <sys/time.h>
35 #endif
36 #ifdef HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif
39
40 #define NONAMELESSUNION
41 #define NONAMELESSSTRUCT
42 #include "windef.h"
43 #include "winbase.h"
44 #include "winreg.h"
45 #include "winternl.h"
46 #include "wine/unicode.h"
47 #include "wine/debug.h"
48 #include "ntdll_misc.h"
49
50 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
51
52 static CRITICAL_SECTION TIME_GetBias_section;
53 static CRITICAL_SECTION_DEBUG critsect_debug =
54 {
55     0, 0, &TIME_GetBias_section,
56     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
57       0, 0, { 0, (DWORD)(__FILE__ ": TIME_GetBias_section") }
58 };
59 static CRITICAL_SECTION TIME_GetBias_section = { &critsect_debug, -1, 0, 0, 0, 0 };
60
61 /* TimeZone registry key values */
62 static const WCHAR TZInformationKeyW[] = { 'M','a','c','h','i','n','e','\\',
63  'S','Y','S','T','E','M','\\','C','u','r','r','e','n','t','C','o','n','t','r',
64  'o','l','S','e','t','\\','C','o','n','t','r','o','l','\\','T','i','m','e','z',
65  'o','n','e','I','n','f','o','r','m','a','t','i','o','n', 0};
66 static const WCHAR TZStandardStartW[] = {
67   'S','t','a','n','d','a','r','d','s','t','a','r','t', 0};
68 static const WCHAR TZDaylightStartW[] = {
69   'D','a','y','l','i','g','h','t','s','t','a','r','t', 0};
70 static const WCHAR TZDaylightBiasW[] = {
71     'D','a','y','l','i','g','h','t','B','i','a','s', 0};
72 static const WCHAR TZStandardBiasW[] = {
73     'S','t','a','n','d','a','r','d','B','i','a','s', 0};
74 static const WCHAR TZBiasW[] = {'B','i','a','s', 0};
75 static const WCHAR TZDaylightNameW[] = {
76     'D','a','y','l','i','g','h','t','N','a','m','e', 0};
77 static const WCHAR TZStandardNameW[] = {
78     'S','t','a','n','d','a','r','d','N','a','m','e', 0};
79
80
81 #define SETTIME_MAX_ADJUST 120
82
83 /* This structure is used to store strings that represent all of the time zones
84  * in the world. (This is used to help GetTimeZoneInformation)
85  */
86 struct tagTZ_INFO
87 {
88     const char *psTZFromUnix;
89     WCHAR psTZWindows[32];
90     int bias;
91     int dst;
92 };
93
94 static const struct tagTZ_INFO TZ_INFO[] =
95 {
96    {"MHT",
97     {'D','a','t','e','l','i','n','e',' ','S','t','a','n','d','a','r','d',' ',
98      'T','i','m','e','\0'}, -720, 0},
99    {"SST",
100     {'S','a','m','o','a',' ','S','t','a','n','d','a','r','d',' ','T','i','m',
101      'e','\0'}, 660, 0},
102    {"HST",
103     {'H','a','w','a','i','i','a','n',' ','S','t','a','n','d','a','r','d',' ',
104      'T','i','m','e','\0'}, 600, 0},
105    {"AKDT",
106     {'A','l','a','s','k','a','n',' ','S','t','a','n','d','a','r','d',' ','T',
107      'i','m','e','\0'}, 480, 1},
108    {"PST",
109     {'P','a','c','i','f','i','c',' ','S','t','a','n','d','a','r','d',' ','T',
110      'i','m','e','\0'}, 480, 0},
111    {"PDT",
112     {'P','a','c','i','f','i','c',' ','S','t','a','n','d','a','r','d',' ','T',
113      'i','m','e','\0'}, 420, 1},
114    {"MST",
115     {'U','S',' ','M','o','u','n','t','a','i','n',' ','S','t','a','n','d','a',
116      'r','d',' ','T','i','m','e','\0'}, 420, 0},
117    {"MDT",
118     {'M','o','u','n','t','a','i','n',' ','S','t','a','n','d','a','r','d',' ',
119      'T','i','m','e','\0'}, 360, 1},
120    {"CST",
121     {'C','e','n','t','r','a','l',' ','A','m','e','r','i','c','a',' ','S','t',
122      'a','n','d','a','r','d',' ','T','i','m','e','\0'}, 360, 0},
123    {"CDT",
124     {'C','e','n','t','r','a','l',' ','S','t','a','n','d','a','r','d',' ','T',
125      'i','m','e','\0'}, 300, 1},
126    {"COT",
127     {'S','A',' ','P','a','c','i','f','i','c',' ','S','t','a','n','d','a','r',
128      'd',' ','T','i','m','e','\0'}, 300, 0},
129    {"EDT",
130     {'E','a','s','t','e','r','n',' ','S','t','a','n','d','a','r','d',' ','T',
131      'i','m','e','\0'}, 240, 1},
132    {"EST",
133     {'U','S',' ','E','a','s','t','e','r','n',' ','S','t','a','n','d','a','r',
134      'd',' ','T','i','m','e','\0'}, 300, 0},
135    {"ECT",
136     {'E','a','s','t','e','r','n',' ','C','e','n','t','r','a','l',' ','S','t','a','n','d','a','r',
137      'd',' ','T','i','m','e','\0'}, 300, 0},
138    {"ADT",
139     {'A','t','l','a','n','t','i','c',' ','S','t','a','n','d','a','r','d',' ',
140      'T','i','m','e','\0'}, 180, 1},
141    {"VET",
142     {'S','A',' ','W','e','s','t','e','r','n',' ','S','t','a','n','d','a','r',
143      'd',' ','T','i','m','e','\0'}, 240, 0},
144    {"CLT",
145     {'P','a','c','i','f','i','c',' ','S','A',' ','S','t','a','n','d','a','r',
146      'd',' ','T','i','m','e','\0'}, 240, 0},
147    {"NDT",
148     {'N','e','w','f','o','u','n','d','l','a','n','d',' ','S','t','a','n','d',
149      'a','r','d',' ','T','i','m','e','\0'}, 150, 1},
150    {"BRT",
151     {'B','r','a','z','i','l','i','a','n',' ','S','t','a','n','d','a','r','d',
152      ' ','T','i','m','e','\0'}, 180, 0},
153    {"BRST",
154     {'B','r','a','z','i','l','i','a','n',' ','S','u','m','m','e','r',
155      ' ','T','i','m','e','\0'}, 120, 1},
156    {"ART",
157     {'S','A',' ','E','a','s','t','e','r','n',' ','S','t','a','n','d','a','r',
158      'd',' ','T','i','m','e','\0'}, 180, 0},
159    {"WGST",
160     {'G','r','e','e','n','l','a','n','d',' ','S','t','a','n','d','a','r','d',
161      ' ','T','i','m','e','\0'}, 120, 1},
162    {"GST",
163     {'M','i','d','-','A','t','l','a','n','t','i','c',' ','S','t','a','n','d',
164      'a','r','d',' ','T','i','m','e','\0'}, 120, 0},
165    {"AZOST",
166     {'A','z','o','r','e','s',' ','S','t','a','n','d','a','r','d',' ','T','i',
167      'm','e','\0'}, 0, 1},
168    {"CVT",
169     {'C','a','p','e',' ','V','e','r','d','e',' ','S','t','a','n','d','a','r',
170      'd',' ','T','i','m','e','\0'}, 60, 0},
171    {"WET",
172     {'G','r','e','e','n','w','i','c','h',' ','S','t','a','n','d','a','r','d',
173      ' ','T','i','m','e','\0'}, 0, 0},
174    {"BST",
175     {'G','M','T',' ','S','t','a','n','d','a','r','d',' ','T','i','m','e','\0'},
176     -60, 1},
177    {"GMT",
178     {'G','M','T',' ','S','t','a','n','d','a','r','d',' ','T','i','m','e','\0'},
179     0, 0},
180    {"UTC",
181     {'G','M','T',' ','S','t','a','n','d','a','r','d',' ','T','i','m','e','\0'},
182     0, 0},
183    {"CET",
184     {'C','e','n','t','r','a','l',' ','E','u','r','o','p','e','a','n',' ',
185      'T','i','m','e','\0'}, -60, 0},
186    {"CEST",
187     {'C','e','n','t','r','a','l',' ','E','u','r','o','p','e',' ','S','t','a',
188      'n','d','a','r','d',' ','T','i','m','e','\0'}, -120, 1},
189    {"MET",
190     {'C','e','n','t','r','a','l',' ','E','u','r','o','p','e',' ','S','t','a',
191      'n','d','a','r','d',' ','T','i','m','e','\0'}, -60, 0},
192    {"MEST",
193     {'C','e','n','t','r','a','l',' ','E','u','r','o','p','e',' ','D','a','y',
194      'l','i','g','h','t',' ','T','i','m','e','\0'}, -120, 1},
195    {"WAT",
196     {'W','.',' ','C','e','n','t','r','a','l',' ','A','f','r','i','c','a',' ',
197      'S','t','a','n','d','a','r','d',' ','T','i','m','e','\0'}, -60, 0},
198    {"EEST",
199     {'E','.',' ','E','u','r','o','p','e',' ','S','t','a','n','d','a','r','d',
200      ' ','T','i','m','e','\0'}, -180, 1},
201    {"EET",
202     {'E','g','y','p','t',' ','S','t','a','n','d','a','r','d',' ','T','i','m',
203      'e','\0'}, -120, 0},
204    {"CAT",
205     {'C','e','n','t','r','a','l',' ','A','f','r','i','c','a','n',' '
206     ,'T','i','m','e','\0'}, -120, 0},
207    {"SAST",
208     {'S','o','u','t','h',' ','A','f','r','i','c','a',' ','S','t','a','n','d',
209      'a','r','d',' ','T','i','m','e','\0'}, -120, 0},
210    {"IST",
211     {'I','s','r','a','e','l',' ','S','t','a','n','d','a','r','d',' ','T','i',
212      'm','e','\0'}, -120, 0},
213    {"MSK",
214     {'R','u','s','s','i','a','n',' ','S','t','a','n','d','a','r','d',' ','T',
215      'i','m','e','\0'}, -180, 0},
216    {"ADT",
217     {'A','r','a','b','i','c',' ','S','t','a','n','d','a','r','d',' ','T','i',
218      'm','e','\0'}, -240, 1},
219    {"AST",
220     {'A','r','a','b',' ','S','t','a','n','d','a','r','d',' ','T','i','m','e',
221      '\0'}, -180, 0},
222    {"MSD",
223     {'R','u','s','s','i','a','n',' ','S','t','a','n','d','a','r','d',' ','T',
224      'i','m','e','\0'}, -240, 1},
225    {"EAT",
226     {'E','.',' ','A','f','r','i','c','a',' ','S','t','a','n','d','a','r','d',
227      ' ','T','i','m','e','\0'}, -180, 0},
228    {"IRST",
229     {'I','r','a','n',' ','S','t','a','n','d','a','r','d',' ','T','i','m','e',
230      '\0'}, -270, 1},
231    {"GST",
232     {'A','r','a','b','i','a','n',' ','S','t','a','n','d','a','r','d',' ','T',
233      'i','m','e','\0'}, -240, 0},
234    {"AZST",
235     {'C','a','u','c','a','s','u','s',' ','S','t','a','n','d','a','r','d',' ',
236      'T','i','m','e','\0'}, -300, 1},
237    {"AFT",
238     {'A','f','g','h','a','n','i','s','t','a','n',' ','S','t','a','n','d','a',
239      'r','d',' ','T','i','m','e','\0'}, -270, 0},
240    {"SAMT",
241     {'S','a','m','a','r','a',' ','S','t','a','n','d','a','r','d',' ','T','i',
242      'm','e','\0'}, -270, 1},
243    {"YEKST",
244     {'E','k','a','t','e','r','i','n','b','u','r','g',' ','S','t','a','n','d',
245      'a','r','d',' ','T','i','m','e','\0'}, -360, 1},
246    {"PKT",
247     {'W','e','s','t',' ','A','s','i','a',' ','S','t','a','n','d','a','r','d',
248      ' ','T','i','m','e','\0'}, -300, 0},
249    {"IST",
250     {'I','n','d','i','a',' ','S','t','a','n','d','a','r','d',' ','T','i','m',
251      'e','\0'}, -330, 0},
252    {"NPT",
253     {'N','e','p','a','l',' ','S','t','a','n','d','a','r','d',' ','T','i','m',
254      'e','\0'}, -345, 0},
255    {"ALMST",
256     {'N','.',' ','C','e','n','t','r','a','l',' ','A','s','i','a',' ','S','t',
257      'a','n','d','a','r','d',' ','T','i','m','e','\0'}, -420, 1},
258    {"BDT",
259     {'C','e','n','t','r','a','l',' ','A','s','i','a',' ','S','t','a','n','d',
260      'a','r','d',' ','T','i','m','e','\0'}, -360, 0},
261    {"LKT",
262     {'S','r','i',' ','L','a','n','k','a',' ','S','t','a','n','d','a','r','d',
263      ' ','T','i','m','e','\0'}, -360, 0},
264    {"MMT",
265     {'M','y','a','n','m','a','r',' ','S','t','a','n','d','a','r','d',' ','T',
266      'i','m','e','\0'}, -390, 0},
267    {"ICT",
268     {'S','E',' ','A','s','i','a',' ','S','t','a','n','d','a','r','d',' ','T',
269      'i','m','e','\0'}, -420, 0},
270    {"KRAST",
271     {'N','o','r','t','h',' ','A','s','i','a',' ','S','t','a','n','d','a','r',
272      'd',' ','T','i','m','e','\0'}, -480, 1},
273    {"CST",
274     {'C','h','i','n','a',' ','S','t','a','n','d','a','r','d',' ','T','i','m',
275      'e','\0'}, -480, 0},
276    {"IRKST",
277     {'N','o','r','t','h',' ','A','s','i','a',' ','E','a','s','t',' ','S','t',
278      'a','n','d','a','r','d',' ','T','i','m','e','\0'}, -540, 1},
279    {"SGT",
280     {'M','a','l','a','y',' ','P','e','n','i','n','s','u','l','a',' ','S','t',
281      'a','n','d','a','r','d',' ','T','i','m','e','\0'}, -480, 0},
282    {"WST",
283     {'W','.',' ','A','u','s','t','r','a','l','i','a',' ','S','t','a','n','d',
284      'a','r','d',' ','T','i','m','e','\0'}, -480, 0},
285    {"JST",
286     {'T','o','k','y','o',' ','S','t','a','n','d','a','r','d',' ','T','i','m',
287      'e','\0'}, -540, 0},
288    {"KST",
289     {'K','o','r','e','a',' ','S','t','a','n','d','a','r','d',' ','T','i','m',
290      'e','\0'}, -540, 0},
291    {"YAKST",
292     {'Y','a','k','u','t','s','k',' ','S','t','a','n','d','a','r','d',' ','T',
293      'i','m','e','\0'}, -600, 1},
294    {"CST",
295     {'C','e','n','.',' ','A','u','s','t','r','a','l','i','a',' ','S','t','a',
296      'n','d','a','r','d',' ','T','i','m','e','\0'}, -570, 0},
297    {"EST",
298     {'E','.',' ','A','u','s','t','r','a','l','i','a',' ','S','t','a','n','d',
299      'a','r','d',' ','T','i','m','e','\0'}, -600, 0},
300    {"EST",
301     {'E','.',' ','A','u','s','t','r','a','l','i','a',' ','S','t','a','n','d',
302      'a','r','d',' ','T','i','m','e','\0'}, -660, 1},
303    {"GST",
304     {'W','e','s','t',' ','P','a','c','i','f','i','c',' ','S','t','a','n','d',
305      'a','r','d',' ','T','i','m','e','\0'}, -600, 0},
306    {"VLAST",
307     {'V','l','a','d','i','v','o','s','t','o','k',' ','S','t','a','n','d','a',
308      'r','d',' ','T','i','m','e','\0'}, -660, 1},
309    {"MAGST",
310     {'C','e','n','t','r','a','l',' ','P','a','c','i','f','i','c',' ','S','t',
311      'a','n','d','a','r','d',' ','T','i','m','e','\0'}, -720, 1},
312    {"NZST",
313     {'N','e','w',' ','Z','e','a','l','a','n','d',' ','S','t','a','n','d','a',
314      'r','d',' ','T','i','m','e','\0'}, -720, 0},
315    {"NZDT",
316     {'N','e','w',' ','Z','e','a','l','a','n','d',' ','D','a','y','l','i','g',
317      'h','t',' ','T','i','m','e','\0'}, -780, 1},
318    {"FJT",
319     {'F','i','j','i',' ','S','t','a','n','d','a','r','d',' ','T','i','m','e',
320      '\0'}, -720, 0},
321    {"TOT",
322     {'T','o','n','g','a',' ','S','t','a','n','d','a','r','d',' ','T','i','m',
323      'e','\0'}, -780, 0},
324    {"NOVT",
325     {'N','o','v','o','s','i','b','i','r','s','k',' ','S','t','a','n','d','a',
326      'r','d',' ','T','i','m','e','\0'}, -360, 1}
327 };
328
329 #define TICKSPERSEC        10000000
330 #define TICKSPERMSEC       10000
331 #define SECSPERDAY         86400
332 #define SECSPERHOUR        3600
333 #define SECSPERMIN         60
334 #define MINSPERHOUR        60
335 #define HOURSPERDAY        24
336 #define EPOCHWEEKDAY       1  /* Jan 1, 1601 was Monday */
337 #define DAYSPERWEEK        7
338 #define EPOCHYEAR          1601
339 #define DAYSPERNORMALYEAR  365
340 #define DAYSPERLEAPYEAR    366
341 #define MONSPERYEAR        12
342 #define DAYSPERQUADRICENTENNIUM (365 * 400 + 97)
343 #define DAYSPERNORMALCENTURY (365 * 100 + 24)
344 #define DAYSPERNORMALQUADRENNIUM (365 * 4 + 1)
345
346 /* 1601 to 1970 is 369 years plus 89 leap days */
347 #define SECS_1601_TO_1970  ((369 * 365 + 89) * (ULONGLONG)SECSPERDAY)
348 #define TICKS_1601_TO_1970 (SECS_1601_TO_1970 * TICKSPERSEC)
349 /* 1601 to 1980 is 379 years plus 91 leap days */
350 #define SECS_1601_TO_1980  ((379 * 365 + 91) * (ULONGLONG)SECSPERDAY)
351 #define TICKS_1601_TO_1980 (SECS_1601_TO_1980 * TICKSPERSEC)
352 /* max ticks that can be represented as Unix time */
353 #define TICKS_1601_TO_UNIX_MAX ((SECS_1601_TO_1970 + INT_MAX) * TICKSPERSEC)
354
355
356 static const int MonthLengths[2][MONSPERYEAR] =
357 {
358         { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
359         { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
360 };
361
362 static inline int IsLeapYear(int Year)
363 {
364         return Year % 4 == 0 && (Year % 100 != 0 || Year % 400 == 0) ? 1 : 0;
365 }
366
367 /***********************************************************************
368  *              NTDLL_get_server_timeout
369  *
370  * Convert a NTDLL timeout into a timeval struct to send to the server.
371  */
372 void NTDLL_get_server_timeout( abs_time_t *when, const LARGE_INTEGER *timeout )
373 {
374     UINT remainder;
375
376     if (!timeout)  /* infinite timeout */
377     {
378         when->sec = when->usec = 0;
379     }
380     else if (timeout->QuadPart <= 0)  /* relative timeout */
381     {
382         struct timeval tv;
383
384         if (-timeout->QuadPart > (LONGLONG)INT_MAX * TICKSPERSEC)
385             when->sec = when->usec = INT_MAX;
386         else
387         {
388             ULONG sec = RtlEnlargedUnsignedDivide( -timeout->QuadPart, TICKSPERSEC, &remainder );
389             gettimeofday( &tv, 0 );
390             when->sec = tv.tv_sec + sec;
391             if ((when->usec = tv.tv_usec + (remainder / 10)) >= 1000000)
392             {
393                 when->usec -= 1000000;
394                 when->sec++;
395             }
396             if (when->sec < tv.tv_sec)  /* overflow */
397                 when->sec = when->usec = INT_MAX;
398         }
399     }
400     else  /* absolute time */
401     {
402         if (timeout->QuadPart < TICKS_1601_TO_1970)
403             when->sec = when->usec = 0;
404         else if (timeout->QuadPart > TICKS_1601_TO_UNIX_MAX)
405             when->sec = when->usec = INT_MAX;
406         else
407         {
408             when->sec = RtlEnlargedUnsignedDivide( timeout->QuadPart - TICKS_1601_TO_1970,
409                                                    TICKSPERSEC, &remainder );
410             when->usec = remainder / 10;
411         }
412     }
413 }
414
415
416 /***********************************************************************
417  *              NTDLL_from_server_timeout
418  *
419  * Convert a timeval struct from the server into an NTDLL timeout.
420  */
421 void NTDLL_from_server_timeout( LARGE_INTEGER *timeout, const abs_time_t *when )
422 {
423     timeout->QuadPart = when->sec * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1970;
424     timeout->QuadPart += when->usec * 10;
425 }
426
427
428 /******************************************************************************
429  *       RtlTimeToTimeFields [NTDLL.@]
430  *
431  * Convert a time into a TIME_FIELDS structure.
432  *
433  * PARAMS
434  *   liTime     [I] Time to convert.
435  *   TimeFields [O] Destination for the converted time.
436  *
437  * RETURNS
438  *   Nothing.
439  */
440 VOID WINAPI RtlTimeToTimeFields(
441         const LARGE_INTEGER *liTime,
442         PTIME_FIELDS TimeFields)
443 {
444         int SecondsInDay;
445         long int cleaps, years, yearday, months;
446         long int Days;
447         LONGLONG Time;
448
449         /* Extract millisecond from time and convert time into seconds */
450         TimeFields->Milliseconds =
451             (CSHORT) (( liTime->QuadPart % TICKSPERSEC) / TICKSPERMSEC);
452         Time = liTime->QuadPart / TICKSPERSEC;
453
454         /* The native version of RtlTimeToTimeFields does not take leap seconds
455          * into account */
456
457         /* Split the time into days and seconds within the day */
458         Days = Time / SECSPERDAY;
459         SecondsInDay = Time % SECSPERDAY;
460
461         /* compute time of day */
462         TimeFields->Hour = (CSHORT) (SecondsInDay / SECSPERHOUR);
463         SecondsInDay = SecondsInDay % SECSPERHOUR;
464         TimeFields->Minute = (CSHORT) (SecondsInDay / SECSPERMIN);
465         TimeFields->Second = (CSHORT) (SecondsInDay % SECSPERMIN);
466
467         /* compute day of week */
468         TimeFields->Weekday = (CSHORT) ((EPOCHWEEKDAY + Days) % DAYSPERWEEK);
469
470         /* compute year, month and day of month. */
471         cleaps=( 3 * ((4 * Days + 1227) / DAYSPERQUADRICENTENNIUM) + 3 ) / 4;
472         Days += 28188 + cleaps;
473         years = (20 * Days - 2442) / (5 * DAYSPERNORMALQUADRENNIUM);
474         yearday = Days - (years * DAYSPERNORMALQUADRENNIUM)/4;
475         months = (64 * yearday) / 1959;
476         /* the result is based on a year starting on March.
477          * To convert take 12 from Januari and Februari and
478          * increase the year by one. */
479         if( months < 14 ) {
480             TimeFields->Month = months - 1;
481             TimeFields->Year = years + 1524;
482         } else {
483             TimeFields->Month = months - 13;
484             TimeFields->Year = years + 1525;
485         }
486         /* calculation of day of month is based on the wonderful
487          * sequence of INT( n * 30.6): it reproduces the 
488          * 31-30-31-30-31-31 month lengths exactly for small n's */
489         TimeFields->Day = yearday - (1959 * months) / 64 ;
490         return;
491 }
492
493 /******************************************************************************
494  *       RtlTimeFieldsToTime [NTDLL.@]
495  *
496  * Convert a TIME_FIELDS structure into a time.
497  *
498  * PARAMS
499  *   ftTimeFields [I] TIME_FIELDS structure to convert.
500  *   Time         [O] Destination for the converted time.
501  *
502  * RETURNS
503  *   Success: TRUE.
504  *   Failure: FALSE.
505  */
506 BOOLEAN WINAPI RtlTimeFieldsToTime(
507         PTIME_FIELDS tfTimeFields,
508         PLARGE_INTEGER Time)
509 {
510         int month, year, cleaps, day;
511
512         /* FIXME: normalize the TIME_FIELDS structure here */
513         /* No, native just returns 0 (error) if the fields are not */
514         if( tfTimeFields->Milliseconds< 0 || tfTimeFields->Milliseconds > 999 ||
515                 tfTimeFields->Second < 0 || tfTimeFields->Second > 59 ||
516                 tfTimeFields->Minute < 0 || tfTimeFields->Minute > 59 ||
517                 tfTimeFields->Hour < 0 || tfTimeFields->Hour > 23 ||
518                 tfTimeFields->Month < 1 || tfTimeFields->Month > 12 ||
519                 tfTimeFields->Day < 1 ||
520                 tfTimeFields->Day > MonthLengths
521                     [ tfTimeFields->Month ==2 || IsLeapYear(tfTimeFields->Year)]
522                     [ tfTimeFields->Month - 1] ||
523                 tfTimeFields->Year < 1601 )
524             return FALSE;
525
526         /* now calculate a day count from the date
527          * First start counting years from March. This way the leap days
528          * are added at the end of the year, not somewhere in the middle.
529          * Formula's become so much less complicate that way.
530          * To convert: add 12 to the month numbers of Jan and Feb, and 
531          * take 1 from the year */
532         if(tfTimeFields->Month < 3) {
533             month = tfTimeFields->Month + 13;
534             year = tfTimeFields->Year - 1;
535         } else {
536             month = tfTimeFields->Month + 1;
537             year = tfTimeFields->Year;
538         }
539         cleaps = (3 * (year / 100) + 3) / 4;   /* nr of "century leap years"*/
540         day =  (36525 * year) / 100 - cleaps + /* year * dayperyr, corrected */
541                  (1959 * month) / 64 +         /* months * daypermonth */
542                  tfTimeFields->Day -          /* day of the month */
543                  584817 ;                      /* zero that on 1601-01-01 */
544         /* done */
545         
546         Time->QuadPart = (((((LONGLONG) day * HOURSPERDAY +
547             tfTimeFields->Hour) * MINSPERHOUR +
548             tfTimeFields->Minute) * SECSPERMIN +
549             tfTimeFields->Second ) * 1000 +
550             tfTimeFields->Milliseconds ) * TICKSPERMSEC;
551
552         return TRUE;
553 }
554
555 /***********************************************************************
556  *       TIME_GetBias [internal]
557  *
558  * Helper function calculates delta local time from UTC. 
559  *
560  * PARAMS
561  *   utc [I] The current utc time.
562  *   pdaylight [I] Local daylight.
563  *
564  * RETURNS
565  *   The bias for the current timezone.
566  */
567 static int TIME_GetBias(time_t utc, int *pdaylight)
568 {
569     struct tm *ptm;
570     static time_t last_utc;
571     static int last_bias;
572     static int last_daylight;
573     int ret;
574
575     RtlEnterCriticalSection( &TIME_GetBias_section );
576     if(utc == last_utc)
577     {
578         *pdaylight = last_daylight;
579         ret = last_bias;        
580     } else
581     {
582         ptm = localtime(&utc);
583         *pdaylight = last_daylight =
584             ptm->tm_isdst; /* daylight for local timezone */
585         ptm = gmtime(&utc);
586         ptm->tm_isdst = *pdaylight; /* use local daylight, not that of Greenwich */
587         last_utc = utc;
588         ret = last_bias = (int)(utc-mktime(ptm));
589     }
590     RtlLeaveCriticalSection( &TIME_GetBias_section );
591     return ret;
592 }
593
594 /******************************************************************************
595  *        RtlLocalTimeToSystemTime [NTDLL.@]
596  *
597  * Convert a local time into system time.
598  *
599  * PARAMS
600  *   LocalTime  [I] Local time to convert.
601  *   SystemTime [O] Destination for the converted time.
602  *
603  * RETURNS
604  *   Success: STATUS_SUCCESS.
605  *   Failure: An NTSTATUS error code indicating the problem.
606  */
607 NTSTATUS WINAPI RtlLocalTimeToSystemTime( const LARGE_INTEGER *LocalTime,
608                                           PLARGE_INTEGER SystemTime)
609 {
610     time_t gmt;
611     int bias, daylight;
612
613     TRACE("(%p, %p)\n", LocalTime, SystemTime);
614
615     gmt = time(NULL);
616     bias = TIME_GetBias(gmt, &daylight);
617
618     SystemTime->QuadPart = LocalTime->QuadPart - bias * (LONGLONG)TICKSPERSEC;
619     return STATUS_SUCCESS;
620 }
621
622 /******************************************************************************
623  *       RtlSystemTimeToLocalTime [NTDLL.@]
624  *
625  * Convert a system time into a local time.
626  *
627  * PARAMS
628  *   SystemTime [I] System time to convert.
629  *   LocalTime  [O] Destination for the converted time.
630  *
631  * RETURNS
632  *   Success: STATUS_SUCCESS.
633  *   Failure: An NTSTATUS error code indicating the problem.
634  */
635 NTSTATUS WINAPI RtlSystemTimeToLocalTime( const LARGE_INTEGER *SystemTime,
636                                           PLARGE_INTEGER LocalTime )
637 {
638     time_t gmt;
639     int bias, daylight;
640
641     TRACE("(%p, %p)\n", SystemTime, LocalTime);
642
643     gmt = time(NULL);
644     bias = TIME_GetBias(gmt, &daylight);
645
646     LocalTime->QuadPart = SystemTime->QuadPart + bias * (LONGLONG)TICKSPERSEC;
647     return STATUS_SUCCESS;
648 }
649
650 /******************************************************************************
651  *       RtlTimeToSecondsSince1970 [NTDLL.@]
652  *
653  * Convert a time into a count of seconds since 1970.
654  *
655  * PARAMS
656  *   Time    [I] Time to convert.
657  *   Seconds [O] Destination for the converted time.
658  *
659  * RETURNS
660  *   Success: TRUE.
661  *   Failure: FALSE, if the resulting value will not fit in a DWORD.
662  */
663 BOOLEAN WINAPI RtlTimeToSecondsSince1970( const LARGE_INTEGER *Time, LPDWORD Seconds )
664 {
665     ULONGLONG tmp = ((ULONGLONG)Time->u.HighPart << 32) | Time->u.LowPart;
666     tmp = RtlLargeIntegerDivide( tmp, TICKSPERSEC, NULL );
667     tmp -= SECS_1601_TO_1970;
668     if (tmp > 0xffffffff) return FALSE;
669     *Seconds = (DWORD)tmp;
670     return TRUE;
671 }
672
673 /******************************************************************************
674  *       RtlTimeToSecondsSince1980 [NTDLL.@]
675  *
676  * Convert a time into a count of seconds since 1980.
677  *
678  * PARAMS
679  *   Time    [I] Time to convert.
680  *   Seconds [O] Destination for the converted time.
681  *
682  * RETURNS
683  *   Success: TRUE.
684  *   Failure: FALSE, if the resulting value will not fit in a DWORD.
685  */
686 BOOLEAN WINAPI RtlTimeToSecondsSince1980( const LARGE_INTEGER *Time, LPDWORD Seconds )
687 {
688     ULONGLONG tmp = ((ULONGLONG)Time->u.HighPart << 32) | Time->u.LowPart;
689     tmp = RtlLargeIntegerDivide( tmp, TICKSPERSEC, NULL );
690     tmp -= SECS_1601_TO_1980;
691     if (tmp > 0xffffffff) return FALSE;
692     *Seconds = (DWORD)tmp;
693     return TRUE;
694 }
695
696 /******************************************************************************
697  *       RtlSecondsSince1970ToTime [NTDLL.@]
698  *
699  * Convert a count of seconds since 1970 to a time.
700  *
701  * PARAMS
702  *   Seconds [I] Time to convert.
703  *   Time    [O] Destination for the converted time.
704  *
705  * RETURNS
706  *   Nothing.
707  */
708 void WINAPI RtlSecondsSince1970ToTime( DWORD Seconds, LARGE_INTEGER *Time )
709 {
710     ULONGLONG secs = Seconds * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1970;
711     Time->u.LowPart  = (DWORD)secs;
712     Time->u.HighPart = (DWORD)(secs >> 32);
713 }
714
715 /******************************************************************************
716  *       RtlSecondsSince1980ToTime [NTDLL.@]
717  *
718  * Convert a count of seconds since 1980 to a time.
719  *
720  * PARAMS
721  *   Seconds [I] Time to convert.
722  *   Time    [O] Destination for the converted time.
723  *
724  * RETURNS
725  *   Nothing.
726  */
727 void WINAPI RtlSecondsSince1980ToTime( DWORD Seconds, LARGE_INTEGER *Time )
728 {
729     ULONGLONG secs = Seconds * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1980;
730     Time->u.LowPart  = (DWORD)secs;
731     Time->u.HighPart = (DWORD)(secs >> 32);
732 }
733
734 /******************************************************************************
735  *       RtlTimeToElapsedTimeFields [NTDLL.@]
736  *
737  * Convert a time to a count of elapsed seconds.
738  *
739  * PARAMS
740  *   Time       [I] Time to convert.
741  *   TimeFields [O] Destination for the converted time.
742  *
743  * RETURNS
744  *   Nothing.
745  */
746 void WINAPI RtlTimeToElapsedTimeFields( const LARGE_INTEGER *Time, PTIME_FIELDS TimeFields )
747 {
748     LONGLONG time;
749     UINT rem;
750
751     time = RtlExtendedLargeIntegerDivide( Time->QuadPart, TICKSPERSEC, &rem );
752     TimeFields->Milliseconds = rem / TICKSPERMSEC;
753
754     /* time is now in seconds */
755     TimeFields->Year  = 0;
756     TimeFields->Month = 0;
757     TimeFields->Day   = RtlExtendedLargeIntegerDivide( time, SECSPERDAY, &rem );
758
759     /* rem is now the remaining seconds in the last day */
760     TimeFields->Second = rem % 60;
761     rem /= 60;
762     TimeFields->Minute = rem % 60;
763     TimeFields->Hour = rem / 60;
764 }
765
766 /***********************************************************************
767  *       NtQuerySystemTime [NTDLL.@]
768  *       ZwQuerySystemTime [NTDLL.@]
769  *
770  * Get the current system time.
771  *
772  * PARAMS
773  *   Time [O] Destination for the current system time.
774  *
775  * RETURNS
776  *   Success: STATUS_SUCCESS.
777  *   Failure: An NTSTATUS error code indicating the problem.
778  */
779 NTSTATUS WINAPI NtQuerySystemTime( PLARGE_INTEGER Time )
780 {
781     struct timeval now;
782
783     gettimeofday( &now, 0 );
784     Time->QuadPart = now.tv_sec * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1970;
785     Time->QuadPart += now.tv_usec * 10;
786     return STATUS_SUCCESS;
787 }
788
789 /***********************************************************************
790  *        TIME_GetTZAsStr [internal]
791  *
792  * Helper function that returns the given timezone as a string.
793  *
794  * PARAMS
795  *   utc [I] The current utc time.
796  *   bias [I] The bias of the current timezone.
797  *   dst [I] ??
798  *
799  * RETURNS
800  *   Timezone name.
801  *
802  * NOTES:
803  *   This could be done with a hash table instead of merely iterating through a
804  *   table, however with the small amount of entries (60 or so) I didn't think
805  *   it was worth it.
806  */
807 static const WCHAR* TIME_GetTZAsStr (time_t utc, int bias, int dst)
808 {
809    char psTZName[7];
810    struct tm *ptm = localtime(&utc);
811    unsigned int i;
812
813    if (!strftime (psTZName, 7, "%Z", ptm))
814       return (NULL);
815
816    for (i=0; i<(sizeof(TZ_INFO) / sizeof(struct tagTZ_INFO)); i++)
817    {
818       if ( strcmp(TZ_INFO[i].psTZFromUnix, psTZName) == 0 &&
819            TZ_INFO[i].bias == bias &&
820            TZ_INFO[i].dst == dst
821          )
822             return TZ_INFO[i].psTZWindows;
823    }
824    FIXME("Can't match system time zone name \"%s\", bias=%d and dst=%d "
825          "to an entry in TZ_INFO. Please add appropriate entry to "
826          "TZ_INFO and submit as patch to wine-patches\n",psTZName,bias,dst);
827    return NULL;
828 }
829
830 /***  TIME_GetTimeZoneInfoFromReg: helper for GetTimeZoneInformation ***/
831
832
833 static int TIME_GetTimeZoneInfoFromReg(LPTIME_ZONE_INFORMATION tzinfo)
834 {
835     BYTE buf[90];
836     KEY_VALUE_PARTIAL_INFORMATION * KpInfo =
837         (KEY_VALUE_PARTIAL_INFORMATION *) buf;
838     HKEY hkey;
839     DWORD size;
840     OBJECT_ATTRIBUTES attr;
841     UNICODE_STRING nameW;
842
843     attr.Length = sizeof(attr);
844     attr.RootDirectory = 0;
845     attr.ObjectName = &nameW;
846     attr.Attributes = 0;
847     attr.SecurityDescriptor = NULL;
848     attr.SecurityQualityOfService = NULL;
849     RtlInitUnicodeString( &nameW, TZInformationKeyW);
850     if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr )) {
851
852 #define GTZIFR_N( valkey, tofield) \
853         RtlInitUnicodeString( &nameW, valkey );\
854         if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, KpInfo,\
855                     sizeof(buf), &size )) { \
856             if( size >= (sizeof((tofield)) + \
857                     offsetof(KEY_VALUE_PARTIAL_INFORMATION,Data))); { \
858                 memcpy(&(tofield), \
859                         KpInfo->Data, sizeof(tofield)); \
860             } \
861         }
862 #define GTZIFR_S( valkey, tofield) \
863         RtlInitUnicodeString( &nameW, valkey );\
864         if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, KpInfo,\
865                     sizeof(buf), &size )) { \
866             strncpyW( tofield, (WCHAR*) KpInfo->Data, \
867                     sizeof( tofield) / sizeof(WCHAR) ); \
868         }
869         
870         GTZIFR_N( TZStandardStartW,  tzinfo->StandardDate)
871         GTZIFR_N( TZDaylightStartW,  tzinfo->DaylightDate)
872         GTZIFR_N( TZBiasW,          tzinfo->Bias)
873         GTZIFR_N( TZStandardBiasW,  tzinfo->StandardBias)
874         GTZIFR_N( TZDaylightBiasW,  tzinfo->DaylightBias)
875         GTZIFR_S( TZStandardNameW, tzinfo->StandardName)
876         GTZIFR_S( TZDaylightNameW, tzinfo->DaylightName)
877
878 #undef GTZIFR_N
879 #undef GTZIFR_S
880         NtClose( hkey );
881         return 1;
882     }
883     return 0;
884 }
885
886 /***********************************************************************
887  *      RtlQueryTimeZoneInformation [NTDLL.@]
888  *
889  * Get information about the current timezone.
890  *
891  * PARAMS
892  *   tzinfo [O] Destination for the retrieved timezone info.
893  *
894  * RETURNS
895  *   Success: STATUS_SUCCESS.
896  *   Failure: An NTSTATUS error code indicating the problem.
897  */
898 NTSTATUS WINAPI RtlQueryTimeZoneInformation(LPTIME_ZONE_INFORMATION tzinfo)
899 {
900     time_t gmt;
901     int bias, daylight;
902     const WCHAR *psTZ;
903
904     memset(tzinfo, 0, sizeof(TIME_ZONE_INFORMATION));
905
906     if( !TIME_GetTimeZoneInfoFromReg(tzinfo)) {
907
908         gmt = time(NULL);
909         bias = TIME_GetBias(gmt, &daylight);
910
911         tzinfo->Bias = -bias / 60;
912         tzinfo->StandardBias = 0;
913         tzinfo->DaylightBias = -60;
914         tzinfo->StandardName[0]='\0';
915         tzinfo->DaylightName[0]='\0';
916         psTZ = TIME_GetTZAsStr (gmt, (-bias/60), daylight);
917         if (psTZ) strcpyW( tzinfo->StandardName, psTZ );
918         }
919     return STATUS_SUCCESS;
920 }
921
922 /***********************************************************************
923  *       RtlSetTimeZoneInformation [NTDLL.@]
924  *
925  * Set the current time zone information.
926  *
927  * PARAMS
928  *   tzinfo [I] Timezone information to set.
929  *
930  * RETURNS
931  *   Success: STATUS_SUCCESS.
932  *   Failure: An NTSTATUS error code indicating the problem.
933  *
934  * BUGS
935  *   Uses the obsolete unix timezone structure and tz_dsttime member.
936  */
937 NTSTATUS WINAPI RtlSetTimeZoneInformation( const TIME_ZONE_INFORMATION *tzinfo )
938 {
939 #ifdef HAVE_SETTIMEOFDAY
940     struct timezone tz;
941
942     tz.tz_minuteswest = tzinfo->Bias;
943 #ifdef DST_NONE
944     tz.tz_dsttime = DST_NONE;
945 #else
946     tz.tz_dsttime = 0;
947 #endif
948     if(!settimeofday(NULL, &tz))
949         return STATUS_SUCCESS;
950 #endif
951     return STATUS_PRIVILEGE_NOT_HELD;
952 }
953
954 /***********************************************************************
955  *        NtSetSystemTime [NTDLL.@]
956  *        ZwSetSystemTime [NTDLL.@]
957  *
958  * Set the system time.
959  *
960  * PARAMS
961  *   NewTime [I] The time to set.
962  *   OldTime [O] Optional destination for the previous system time.
963  *
964  * RETURNS
965  *   Success: STATUS_SUCCESS.
966  *   Failure: An NTSTATUS error code indicating the problem.
967  */
968 NTSTATUS WINAPI NtSetSystemTime(const LARGE_INTEGER *NewTime, LARGE_INTEGER *OldTime)
969 {
970     TIME_FIELDS tf;
971     struct timeval tv;
972     struct timezone tz;
973     struct tm t;
974     time_t sec, oldsec;
975     int dst, bias;
976     int err;
977
978     /* Return the old time if necessary */
979     if(OldTime)
980         NtQuerySystemTime(OldTime);
981
982     RtlTimeToTimeFields(NewTime, &tf);
983
984     /* call gettimeofday to get the current timezone */
985     gettimeofday(&tv, &tz);
986     oldsec = tv.tv_sec;
987     /* get delta local time from utc */
988     bias = TIME_GetBias(oldsec, &dst);
989
990     /* get the number of seconds */
991     t.tm_sec = tf.Second;
992     t.tm_min = tf.Minute;
993     t.tm_hour = tf.Hour;
994     t.tm_mday = tf.Day;
995     t.tm_mon = tf.Month - 1;
996     t.tm_year = tf.Year - 1900;
997     t.tm_isdst = dst;
998     sec = mktime (&t);
999     /* correct for timezone and daylight */
1000     sec += bias;
1001
1002     /* set the new time */
1003     tv.tv_sec = sec;
1004     tv.tv_usec = tf.Milliseconds * 1000;
1005
1006     /* error and sanity check*/
1007     if(sec == (time_t)-1 || abs((int)(sec-oldsec)) > SETTIME_MAX_ADJUST) {
1008         err = 2;
1009     } else {
1010 #ifdef HAVE_SETTIMEOFDAY
1011         err = settimeofday(&tv, NULL); /* 0 is OK, -1 is error */
1012         if(err == 0)
1013             return STATUS_SUCCESS;
1014 #else
1015         err = 1;
1016 #endif
1017     }
1018
1019     ERR("Cannot set time to %d/%d/%d %d:%d:%d Time adjustment %ld %s\n",
1020             tf.Year, tf.Month, tf.Day, tf.Hour, tf.Minute, tf.Second,
1021             (long)(sec-oldsec),
1022             err == -1 ? "No Permission"
1023                       : sec == (time_t)-1 ? "" : "is too large." );
1024
1025     if(err == 2)
1026         return STATUS_INVALID_PARAMETER;
1027     else if(err == -1)
1028         return STATUS_PRIVILEGE_NOT_HELD;
1029     else
1030         return STATUS_NOT_IMPLEMENTED;
1031 }