Start of unit tests for *Info* functions.
[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    {"ANAT",
328     {'A','n','a','d','y','r',' ','S','t','a','n','d','a','r','d',' ','T','i',
329      'm','e','\0'}, -720, 1}
330 };
331
332 #define TICKSPERSEC        10000000
333 #define TICKSPERMSEC       10000
334 #define SECSPERDAY         86400
335 #define SECSPERHOUR        3600
336 #define SECSPERMIN         60
337 #define MINSPERHOUR        60
338 #define HOURSPERDAY        24
339 #define EPOCHWEEKDAY       1  /* Jan 1, 1601 was Monday */
340 #define DAYSPERWEEK        7
341 #define EPOCHYEAR          1601
342 #define DAYSPERNORMALYEAR  365
343 #define DAYSPERLEAPYEAR    366
344 #define MONSPERYEAR        12
345 #define DAYSPERQUADRICENTENNIUM (365 * 400 + 97)
346 #define DAYSPERNORMALCENTURY (365 * 100 + 24)
347 #define DAYSPERNORMALQUADRENNIUM (365 * 4 + 1)
348
349 /* 1601 to 1970 is 369 years plus 89 leap days */
350 #define SECS_1601_TO_1970  ((369 * 365 + 89) * (ULONGLONG)SECSPERDAY)
351 #define TICKS_1601_TO_1970 (SECS_1601_TO_1970 * TICKSPERSEC)
352 /* 1601 to 1980 is 379 years plus 91 leap days */
353 #define SECS_1601_TO_1980  ((379 * 365 + 91) * (ULONGLONG)SECSPERDAY)
354 #define TICKS_1601_TO_1980 (SECS_1601_TO_1980 * TICKSPERSEC)
355 /* max ticks that can be represented as Unix time */
356 #define TICKS_1601_TO_UNIX_MAX ((SECS_1601_TO_1970 + INT_MAX) * TICKSPERSEC)
357
358
359 static const int MonthLengths[2][MONSPERYEAR] =
360 {
361         { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
362         { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
363 };
364
365 static inline int IsLeapYear(int Year)
366 {
367         return Year % 4 == 0 && (Year % 100 != 0 || Year % 400 == 0) ? 1 : 0;
368 }
369
370 /***********************************************************************
371  *              NTDLL_get_server_timeout
372  *
373  * Convert a NTDLL timeout into a timeval struct to send to the server.
374  */
375 void NTDLL_get_server_timeout( abs_time_t *when, const LARGE_INTEGER *timeout )
376 {
377     UINT remainder;
378
379     if (!timeout)  /* infinite timeout */
380     {
381         when->sec = when->usec = 0;
382     }
383     else if (timeout->QuadPart <= 0)  /* relative timeout */
384     {
385         struct timeval tv;
386
387         if (-timeout->QuadPart > (LONGLONG)INT_MAX * TICKSPERSEC)
388             when->sec = when->usec = INT_MAX;
389         else
390         {
391             ULONG sec = RtlEnlargedUnsignedDivide( -timeout->QuadPart, TICKSPERSEC, &remainder );
392             gettimeofday( &tv, 0 );
393             when->sec = tv.tv_sec + sec;
394             if ((when->usec = tv.tv_usec + (remainder / 10)) >= 1000000)
395             {
396                 when->usec -= 1000000;
397                 when->sec++;
398             }
399             if (when->sec < tv.tv_sec)  /* overflow */
400                 when->sec = when->usec = INT_MAX;
401         }
402     }
403     else  /* absolute time */
404     {
405         if (timeout->QuadPart < TICKS_1601_TO_1970)
406             when->sec = when->usec = 0;
407         else if (timeout->QuadPart > TICKS_1601_TO_UNIX_MAX)
408             when->sec = when->usec = INT_MAX;
409         else
410         {
411             when->sec = RtlEnlargedUnsignedDivide( timeout->QuadPart - TICKS_1601_TO_1970,
412                                                    TICKSPERSEC, &remainder );
413             when->usec = remainder / 10;
414         }
415     }
416 }
417
418
419 /***********************************************************************
420  *              NTDLL_from_server_timeout
421  *
422  * Convert a timeval struct from the server into an NTDLL timeout.
423  */
424 void NTDLL_from_server_timeout( LARGE_INTEGER *timeout, const abs_time_t *when )
425 {
426     timeout->QuadPart = when->sec * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1970;
427     timeout->QuadPart += when->usec * 10;
428 }
429
430
431 /******************************************************************************
432  *       RtlTimeToTimeFields [NTDLL.@]
433  *
434  * Convert a time into a TIME_FIELDS structure.
435  *
436  * PARAMS
437  *   liTime     [I] Time to convert.
438  *   TimeFields [O] Destination for the converted time.
439  *
440  * RETURNS
441  *   Nothing.
442  */
443 VOID WINAPI RtlTimeToTimeFields(
444         const LARGE_INTEGER *liTime,
445         PTIME_FIELDS TimeFields)
446 {
447         int SecondsInDay;
448         long int cleaps, years, yearday, months;
449         long int Days;
450         LONGLONG Time;
451
452         /* Extract millisecond from time and convert time into seconds */
453         TimeFields->Milliseconds =
454             (CSHORT) (( liTime->QuadPart % TICKSPERSEC) / TICKSPERMSEC);
455         Time = liTime->QuadPart / TICKSPERSEC;
456
457         /* The native version of RtlTimeToTimeFields does not take leap seconds
458          * into account */
459
460         /* Split the time into days and seconds within the day */
461         Days = Time / SECSPERDAY;
462         SecondsInDay = Time % SECSPERDAY;
463
464         /* compute time of day */
465         TimeFields->Hour = (CSHORT) (SecondsInDay / SECSPERHOUR);
466         SecondsInDay = SecondsInDay % SECSPERHOUR;
467         TimeFields->Minute = (CSHORT) (SecondsInDay / SECSPERMIN);
468         TimeFields->Second = (CSHORT) (SecondsInDay % SECSPERMIN);
469
470         /* compute day of week */
471         TimeFields->Weekday = (CSHORT) ((EPOCHWEEKDAY + Days) % DAYSPERWEEK);
472
473         /* compute year, month and day of month. */
474         cleaps=( 3 * ((4 * Days + 1227) / DAYSPERQUADRICENTENNIUM) + 3 ) / 4;
475         Days += 28188 + cleaps;
476         years = (20 * Days - 2442) / (5 * DAYSPERNORMALQUADRENNIUM);
477         yearday = Days - (years * DAYSPERNORMALQUADRENNIUM)/4;
478         months = (64 * yearday) / 1959;
479         /* the result is based on a year starting on March.
480          * To convert take 12 from Januari and Februari and
481          * increase the year by one. */
482         if( months < 14 ) {
483             TimeFields->Month = months - 1;
484             TimeFields->Year = years + 1524;
485         } else {
486             TimeFields->Month = months - 13;
487             TimeFields->Year = years + 1525;
488         }
489         /* calculation of day of month is based on the wonderful
490          * sequence of INT( n * 30.6): it reproduces the 
491          * 31-30-31-30-31-31 month lengths exactly for small n's */
492         TimeFields->Day = yearday - (1959 * months) / 64 ;
493         return;
494 }
495
496 /******************************************************************************
497  *       RtlTimeFieldsToTime [NTDLL.@]
498  *
499  * Convert a TIME_FIELDS structure into a time.
500  *
501  * PARAMS
502  *   ftTimeFields [I] TIME_FIELDS structure to convert.
503  *   Time         [O] Destination for the converted time.
504  *
505  * RETURNS
506  *   Success: TRUE.
507  *   Failure: FALSE.
508  */
509 BOOLEAN WINAPI RtlTimeFieldsToTime(
510         PTIME_FIELDS tfTimeFields,
511         PLARGE_INTEGER Time)
512 {
513         int month, year, cleaps, day;
514
515         /* FIXME: normalize the TIME_FIELDS structure here */
516         /* No, native just returns 0 (error) if the fields are not */
517         if( tfTimeFields->Milliseconds< 0 || tfTimeFields->Milliseconds > 999 ||
518                 tfTimeFields->Second < 0 || tfTimeFields->Second > 59 ||
519                 tfTimeFields->Minute < 0 || tfTimeFields->Minute > 59 ||
520                 tfTimeFields->Hour < 0 || tfTimeFields->Hour > 23 ||
521                 tfTimeFields->Month < 1 || tfTimeFields->Month > 12 ||
522                 tfTimeFields->Day < 1 ||
523                 tfTimeFields->Day > MonthLengths
524                     [ tfTimeFields->Month ==2 || IsLeapYear(tfTimeFields->Year)]
525                     [ tfTimeFields->Month - 1] ||
526                 tfTimeFields->Year < 1601 )
527             return FALSE;
528
529         /* now calculate a day count from the date
530          * First start counting years from March. This way the leap days
531          * are added at the end of the year, not somewhere in the middle.
532          * Formula's become so much less complicate that way.
533          * To convert: add 12 to the month numbers of Jan and Feb, and 
534          * take 1 from the year */
535         if(tfTimeFields->Month < 3) {
536             month = tfTimeFields->Month + 13;
537             year = tfTimeFields->Year - 1;
538         } else {
539             month = tfTimeFields->Month + 1;
540             year = tfTimeFields->Year;
541         }
542         cleaps = (3 * (year / 100) + 3) / 4;   /* nr of "century leap years"*/
543         day =  (36525 * year) / 100 - cleaps + /* year * dayperyr, corrected */
544                  (1959 * month) / 64 +         /* months * daypermonth */
545                  tfTimeFields->Day -          /* day of the month */
546                  584817 ;                      /* zero that on 1601-01-01 */
547         /* done */
548         
549         Time->QuadPart = (((((LONGLONG) day * HOURSPERDAY +
550             tfTimeFields->Hour) * MINSPERHOUR +
551             tfTimeFields->Minute) * SECSPERMIN +
552             tfTimeFields->Second ) * 1000 +
553             tfTimeFields->Milliseconds ) * TICKSPERMSEC;
554
555         return TRUE;
556 }
557
558 /***********************************************************************
559  *       TIME_GetBias [internal]
560  *
561  * Helper function calculates delta local time from UTC. 
562  *
563  * PARAMS
564  *   utc [I] The current utc time.
565  *   pdaylight [I] Local daylight.
566  *
567  * RETURNS
568  *   The bias for the current timezone.
569  */
570 static int TIME_GetBias(time_t utc, int *pdaylight)
571 {
572     struct tm *ptm;
573     static time_t last_utc;
574     static int last_bias;
575     static int last_daylight;
576     int ret;
577
578     RtlEnterCriticalSection( &TIME_GetBias_section );
579     if(utc == last_utc)
580     {
581         *pdaylight = last_daylight;
582         ret = last_bias;        
583     } else
584     {
585         ptm = localtime(&utc);
586         *pdaylight = last_daylight =
587             ptm->tm_isdst; /* daylight for local timezone */
588         ptm = gmtime(&utc);
589         ptm->tm_isdst = *pdaylight; /* use local daylight, not that of Greenwich */
590         last_utc = utc;
591         ret = last_bias = (int)(utc-mktime(ptm));
592     }
593     RtlLeaveCriticalSection( &TIME_GetBias_section );
594     return ret;
595 }
596
597 /******************************************************************************
598  *        RtlLocalTimeToSystemTime [NTDLL.@]
599  *
600  * Convert a local time into system time.
601  *
602  * PARAMS
603  *   LocalTime  [I] Local time to convert.
604  *   SystemTime [O] Destination for the converted time.
605  *
606  * RETURNS
607  *   Success: STATUS_SUCCESS.
608  *   Failure: An NTSTATUS error code indicating the problem.
609  */
610 NTSTATUS WINAPI RtlLocalTimeToSystemTime( const LARGE_INTEGER *LocalTime,
611                                           PLARGE_INTEGER SystemTime)
612 {
613     time_t gmt;
614     int bias, daylight;
615
616     TRACE("(%p, %p)\n", LocalTime, SystemTime);
617
618     gmt = time(NULL);
619     bias = TIME_GetBias(gmt, &daylight);
620
621     SystemTime->QuadPart = LocalTime->QuadPart - bias * (LONGLONG)TICKSPERSEC;
622     return STATUS_SUCCESS;
623 }
624
625 /******************************************************************************
626  *       RtlSystemTimeToLocalTime [NTDLL.@]
627  *
628  * Convert a system time into a local time.
629  *
630  * PARAMS
631  *   SystemTime [I] System time to convert.
632  *   LocalTime  [O] Destination for the converted time.
633  *
634  * RETURNS
635  *   Success: STATUS_SUCCESS.
636  *   Failure: An NTSTATUS error code indicating the problem.
637  */
638 NTSTATUS WINAPI RtlSystemTimeToLocalTime( const LARGE_INTEGER *SystemTime,
639                                           PLARGE_INTEGER LocalTime )
640 {
641     time_t gmt;
642     int bias, daylight;
643
644     TRACE("(%p, %p)\n", SystemTime, LocalTime);
645
646     gmt = time(NULL);
647     bias = TIME_GetBias(gmt, &daylight);
648
649     LocalTime->QuadPart = SystemTime->QuadPart + bias * (LONGLONG)TICKSPERSEC;
650     return STATUS_SUCCESS;
651 }
652
653 /******************************************************************************
654  *       RtlTimeToSecondsSince1970 [NTDLL.@]
655  *
656  * Convert a time into a count of seconds since 1970.
657  *
658  * PARAMS
659  *   Time    [I] Time to convert.
660  *   Seconds [O] Destination for the converted time.
661  *
662  * RETURNS
663  *   Success: TRUE.
664  *   Failure: FALSE, if the resulting value will not fit in a DWORD.
665  */
666 BOOLEAN WINAPI RtlTimeToSecondsSince1970( const LARGE_INTEGER *Time, LPDWORD Seconds )
667 {
668     ULONGLONG tmp = ((ULONGLONG)Time->u.HighPart << 32) | Time->u.LowPart;
669     tmp = RtlLargeIntegerDivide( tmp, TICKSPERSEC, NULL );
670     tmp -= SECS_1601_TO_1970;
671     if (tmp > 0xffffffff) return FALSE;
672     *Seconds = (DWORD)tmp;
673     return TRUE;
674 }
675
676 /******************************************************************************
677  *       RtlTimeToSecondsSince1980 [NTDLL.@]
678  *
679  * Convert a time into a count of seconds since 1980.
680  *
681  * PARAMS
682  *   Time    [I] Time to convert.
683  *   Seconds [O] Destination for the converted time.
684  *
685  * RETURNS
686  *   Success: TRUE.
687  *   Failure: FALSE, if the resulting value will not fit in a DWORD.
688  */
689 BOOLEAN WINAPI RtlTimeToSecondsSince1980( const LARGE_INTEGER *Time, LPDWORD Seconds )
690 {
691     ULONGLONG tmp = ((ULONGLONG)Time->u.HighPart << 32) | Time->u.LowPart;
692     tmp = RtlLargeIntegerDivide( tmp, TICKSPERSEC, NULL );
693     tmp -= SECS_1601_TO_1980;
694     if (tmp > 0xffffffff) return FALSE;
695     *Seconds = (DWORD)tmp;
696     return TRUE;
697 }
698
699 /******************************************************************************
700  *       RtlSecondsSince1970ToTime [NTDLL.@]
701  *
702  * Convert a count of seconds since 1970 to a time.
703  *
704  * PARAMS
705  *   Seconds [I] Time to convert.
706  *   Time    [O] Destination for the converted time.
707  *
708  * RETURNS
709  *   Nothing.
710  */
711 void WINAPI RtlSecondsSince1970ToTime( DWORD Seconds, LARGE_INTEGER *Time )
712 {
713     ULONGLONG secs = Seconds * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1970;
714     Time->u.LowPart  = (DWORD)secs;
715     Time->u.HighPart = (DWORD)(secs >> 32);
716 }
717
718 /******************************************************************************
719  *       RtlSecondsSince1980ToTime [NTDLL.@]
720  *
721  * Convert a count of seconds since 1980 to a time.
722  *
723  * PARAMS
724  *   Seconds [I] Time to convert.
725  *   Time    [O] Destination for the converted time.
726  *
727  * RETURNS
728  *   Nothing.
729  */
730 void WINAPI RtlSecondsSince1980ToTime( DWORD Seconds, LARGE_INTEGER *Time )
731 {
732     ULONGLONG secs = Seconds * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1980;
733     Time->u.LowPart  = (DWORD)secs;
734     Time->u.HighPart = (DWORD)(secs >> 32);
735 }
736
737 /******************************************************************************
738  *       RtlTimeToElapsedTimeFields [NTDLL.@]
739  *
740  * Convert a time to a count of elapsed seconds.
741  *
742  * PARAMS
743  *   Time       [I] Time to convert.
744  *   TimeFields [O] Destination for the converted time.
745  *
746  * RETURNS
747  *   Nothing.
748  */
749 void WINAPI RtlTimeToElapsedTimeFields( const LARGE_INTEGER *Time, PTIME_FIELDS TimeFields )
750 {
751     LONGLONG time;
752     UINT rem;
753
754     time = RtlExtendedLargeIntegerDivide( Time->QuadPart, TICKSPERSEC, &rem );
755     TimeFields->Milliseconds = rem / TICKSPERMSEC;
756
757     /* time is now in seconds */
758     TimeFields->Year  = 0;
759     TimeFields->Month = 0;
760     TimeFields->Day   = RtlExtendedLargeIntegerDivide( time, SECSPERDAY, &rem );
761
762     /* rem is now the remaining seconds in the last day */
763     TimeFields->Second = rem % 60;
764     rem /= 60;
765     TimeFields->Minute = rem % 60;
766     TimeFields->Hour = rem / 60;
767 }
768
769 /***********************************************************************
770  *       NtQuerySystemTime [NTDLL.@]
771  *       ZwQuerySystemTime [NTDLL.@]
772  *
773  * Get the current system time.
774  *
775  * PARAMS
776  *   Time [O] Destination for the current system time.
777  *
778  * RETURNS
779  *   Success: STATUS_SUCCESS.
780  *   Failure: An NTSTATUS error code indicating the problem.
781  */
782 NTSTATUS WINAPI NtQuerySystemTime( PLARGE_INTEGER Time )
783 {
784     struct timeval now;
785
786     gettimeofday( &now, 0 );
787     Time->QuadPart = now.tv_sec * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1970;
788     Time->QuadPart += now.tv_usec * 10;
789     return STATUS_SUCCESS;
790 }
791
792 /***********************************************************************
793  *        TIME_GetTZAsStr [internal]
794  *
795  * Helper function that returns the given timezone as a string.
796  *
797  * PARAMS
798  *   utc [I] The current utc time.
799  *   bias [I] The bias of the current timezone.
800  *   dst [I] ??
801  *
802  * RETURNS
803  *   Timezone name.
804  *
805  * NOTES:
806  *   This could be done with a hash table instead of merely iterating through a
807  *   table, however with the small amount of entries (60 or so) I didn't think
808  *   it was worth it.
809  */
810 static const WCHAR* TIME_GetTZAsStr (time_t utc, int bias, int dst)
811 {
812    char psTZName[7];
813    struct tm *ptm = localtime(&utc);
814    unsigned int i;
815
816    if (!strftime (psTZName, 7, "%Z", ptm))
817       return (NULL);
818
819    for (i=0; i<(sizeof(TZ_INFO) / sizeof(struct tagTZ_INFO)); i++)
820    {
821       if ( strcmp(TZ_INFO[i].psTZFromUnix, psTZName) == 0 &&
822            TZ_INFO[i].bias == bias &&
823            TZ_INFO[i].dst == dst
824          )
825             return TZ_INFO[i].psTZWindows;
826    }
827    FIXME("Can't match system time zone name \"%s\", bias=%d and dst=%d "
828          "to an entry in TZ_INFO. Please add appropriate entry to "
829          "TZ_INFO and submit as patch to wine-patches\n",psTZName,bias,dst);
830    return NULL;
831 }
832
833 /***  TIME_GetTimeZoneInfoFromReg: helper for GetTimeZoneInformation ***/
834
835
836 static int TIME_GetTimeZoneInfoFromReg(LPTIME_ZONE_INFORMATION tzinfo)
837 {
838     BYTE buf[90];
839     KEY_VALUE_PARTIAL_INFORMATION * KpInfo =
840         (KEY_VALUE_PARTIAL_INFORMATION *) buf;
841     HKEY hkey;
842     DWORD size;
843     OBJECT_ATTRIBUTES attr;
844     UNICODE_STRING nameW;
845
846     attr.Length = sizeof(attr);
847     attr.RootDirectory = 0;
848     attr.ObjectName = &nameW;
849     attr.Attributes = 0;
850     attr.SecurityDescriptor = NULL;
851     attr.SecurityQualityOfService = NULL;
852     RtlInitUnicodeString( &nameW, TZInformationKeyW);
853     if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr )) {
854
855 #define GTZIFR_N( valkey, tofield) \
856         RtlInitUnicodeString( &nameW, valkey );\
857         if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, KpInfo,\
858                     sizeof(buf), &size )) { \
859             if( size >= (sizeof((tofield)) + \
860                     offsetof(KEY_VALUE_PARTIAL_INFORMATION,Data))); { \
861                 memcpy(&(tofield), \
862                         KpInfo->Data, sizeof(tofield)); \
863             } \
864         }
865 #define GTZIFR_S( valkey, tofield) \
866         RtlInitUnicodeString( &nameW, valkey );\
867         if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, KpInfo,\
868                     sizeof(buf), &size )) { \
869             strncpyW( tofield, (WCHAR*) KpInfo->Data, \
870                     sizeof( tofield) / sizeof(WCHAR) ); \
871         }
872         
873         GTZIFR_N( TZStandardStartW,  tzinfo->StandardDate)
874         GTZIFR_N( TZDaylightStartW,  tzinfo->DaylightDate)
875         GTZIFR_N( TZBiasW,          tzinfo->Bias)
876         GTZIFR_N( TZStandardBiasW,  tzinfo->StandardBias)
877         GTZIFR_N( TZDaylightBiasW,  tzinfo->DaylightBias)
878         GTZIFR_S( TZStandardNameW, tzinfo->StandardName)
879         GTZIFR_S( TZDaylightNameW, tzinfo->DaylightName)
880
881 #undef GTZIFR_N
882 #undef GTZIFR_S
883         NtClose( hkey );
884         return 1;
885     }
886     return 0;
887 }
888
889 /***********************************************************************
890  *      RtlQueryTimeZoneInformation [NTDLL.@]
891  *
892  * Get information about the current timezone.
893  *
894  * PARAMS
895  *   tzinfo [O] Destination for the retrieved timezone info.
896  *
897  * RETURNS
898  *   Success: STATUS_SUCCESS.
899  *   Failure: An NTSTATUS error code indicating the problem.
900  */
901 NTSTATUS WINAPI RtlQueryTimeZoneInformation(LPTIME_ZONE_INFORMATION tzinfo)
902 {
903     time_t gmt;
904     int bias, daylight;
905     const WCHAR *psTZ;
906
907     memset(tzinfo, 0, sizeof(TIME_ZONE_INFORMATION));
908
909     if( !TIME_GetTimeZoneInfoFromReg(tzinfo)) {
910
911         gmt = time(NULL);
912         bias = TIME_GetBias(gmt, &daylight);
913
914         tzinfo->Bias = -bias / 60;
915         tzinfo->StandardBias = 0;
916         tzinfo->DaylightBias = -60;
917         tzinfo->StandardName[0]='\0';
918         tzinfo->DaylightName[0]='\0';
919         psTZ = TIME_GetTZAsStr (gmt, (-bias/60), daylight);
920         if (psTZ) strcpyW( tzinfo->StandardName, psTZ );
921         }
922     return STATUS_SUCCESS;
923 }
924
925 /***********************************************************************
926  *       RtlSetTimeZoneInformation [NTDLL.@]
927  *
928  * Set the current time zone information.
929  *
930  * PARAMS
931  *   tzinfo [I] Timezone information to set.
932  *
933  * RETURNS
934  *   Success: STATUS_SUCCESS.
935  *   Failure: An NTSTATUS error code indicating the problem.
936  *
937  * BUGS
938  *   Uses the obsolete unix timezone structure and tz_dsttime member.
939  */
940 NTSTATUS WINAPI RtlSetTimeZoneInformation( const TIME_ZONE_INFORMATION *tzinfo )
941 {
942 #ifdef HAVE_SETTIMEOFDAY
943     struct timezone tz;
944
945     tz.tz_minuteswest = tzinfo->Bias;
946 #ifdef DST_NONE
947     tz.tz_dsttime = DST_NONE;
948 #else
949     tz.tz_dsttime = 0;
950 #endif
951     if(!settimeofday(NULL, &tz))
952         return STATUS_SUCCESS;
953 #endif
954     return STATUS_PRIVILEGE_NOT_HELD;
955 }
956
957 /***********************************************************************
958  *        NtSetSystemTime [NTDLL.@]
959  *        ZwSetSystemTime [NTDLL.@]
960  *
961  * Set the system time.
962  *
963  * PARAMS
964  *   NewTime [I] The time to set.
965  *   OldTime [O] Optional destination for the previous system time.
966  *
967  * RETURNS
968  *   Success: STATUS_SUCCESS.
969  *   Failure: An NTSTATUS error code indicating the problem.
970  */
971 NTSTATUS WINAPI NtSetSystemTime(const LARGE_INTEGER *NewTime, LARGE_INTEGER *OldTime)
972 {
973     TIME_FIELDS tf;
974     struct timeval tv;
975     struct timezone tz;
976     struct tm t;
977     time_t sec, oldsec;
978     int dst, bias;
979     int err;
980
981     /* Return the old time if necessary */
982     if(OldTime)
983         NtQuerySystemTime(OldTime);
984
985     RtlTimeToTimeFields(NewTime, &tf);
986
987     /* call gettimeofday to get the current timezone */
988     gettimeofday(&tv, &tz);
989     oldsec = tv.tv_sec;
990     /* get delta local time from utc */
991     bias = TIME_GetBias(oldsec, &dst);
992
993     /* get the number of seconds */
994     t.tm_sec = tf.Second;
995     t.tm_min = tf.Minute;
996     t.tm_hour = tf.Hour;
997     t.tm_mday = tf.Day;
998     t.tm_mon = tf.Month - 1;
999     t.tm_year = tf.Year - 1900;
1000     t.tm_isdst = dst;
1001     sec = mktime (&t);
1002     /* correct for timezone and daylight */
1003     sec += bias;
1004
1005     /* set the new time */
1006     tv.tv_sec = sec;
1007     tv.tv_usec = tf.Milliseconds * 1000;
1008
1009     /* error and sanity check*/
1010     if(sec == (time_t)-1 || abs((int)(sec-oldsec)) > SETTIME_MAX_ADJUST) {
1011         err = 2;
1012     } else {
1013 #ifdef HAVE_SETTIMEOFDAY
1014         err = settimeofday(&tv, NULL); /* 0 is OK, -1 is error */
1015         if(err == 0)
1016             return STATUS_SUCCESS;
1017 #else
1018         err = 1;
1019 #endif
1020     }
1021
1022     ERR("Cannot set time to %d/%d/%d %d:%d:%d Time adjustment %ld %s\n",
1023             tf.Year, tf.Month, tf.Day, tf.Hour, tf.Minute, tf.Second,
1024             (long)(sec-oldsec),
1025             err == -1 ? "No Permission"
1026                       : sec == (time_t)-1 ? "" : "is too large." );
1027
1028     if(err == 2)
1029         return STATUS_INVALID_PARAMETER;
1030     else if(err == -1)
1031         return STATUS_PRIVILEGE_NOT_HELD;
1032     else
1033         return STATUS_NOT_IMPLEMENTED;
1034 }