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