ntdll: Reimplement TIME_GetBias using new time zone code.
[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  * Copyright 2007 Dmitry Timoshkov
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this library; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24  */
25
26 #include "config.h"
27 #include "wine/port.h"
28
29 #include <stdarg.h>
30 #include <stdlib.h>
31 #include <errno.h>
32 #include <string.h>
33 #include <limits.h>
34 #include <time.h>
35 #ifdef HAVE_SYS_TIME_H
36 # include <sys/time.h>
37 #endif
38 #ifdef HAVE_UNISTD_H
39 # include <unistd.h>
40 #endif
41
42 #define NONAMELESSUNION
43 #define NONAMELESSSTRUCT
44 #include "ntstatus.h"
45 #define WIN32_NO_STATUS
46 #include "windef.h"
47 #include "winternl.h"
48 #include "wine/unicode.h"
49 #include "wine/debug.h"
50 #include "ntdll_misc.h"
51
52 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
53
54 static int init_tz_info(RTL_TIME_ZONE_INFORMATION *tzi);
55
56 static RTL_CRITICAL_SECTION TIME_tz_section;
57 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
58 {
59     0, 0, &TIME_tz_section,
60     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
61       0, 0, { (DWORD_PTR)(__FILE__ ": TIME_tz_section") }
62 };
63 static RTL_CRITICAL_SECTION TIME_tz_section = { &critsect_debug, -1, 0, 0, 0, 0 };
64
65 #define SETTIME_MAX_ADJUST 120
66
67 #define TICKSPERSEC        10000000
68 #define TICKSPERMSEC       10000
69 #define SECSPERDAY         86400
70 #define SECSPERHOUR        3600
71 #define SECSPERMIN         60
72 #define MINSPERHOUR        60
73 #define HOURSPERDAY        24
74 #define EPOCHWEEKDAY       1  /* Jan 1, 1601 was Monday */
75 #define DAYSPERWEEK        7
76 #define EPOCHYEAR          1601
77 #define DAYSPERNORMALYEAR  365
78 #define DAYSPERLEAPYEAR    366
79 #define MONSPERYEAR        12
80 #define DAYSPERQUADRICENTENNIUM (365 * 400 + 97)
81 #define DAYSPERNORMALCENTURY (365 * 100 + 24)
82 #define DAYSPERNORMALQUADRENNIUM (365 * 4 + 1)
83
84 /* 1601 to 1970 is 369 years plus 89 leap days */
85 #define SECS_1601_TO_1970  ((369 * 365 + 89) * (ULONGLONG)SECSPERDAY)
86 #define TICKS_1601_TO_1970 (SECS_1601_TO_1970 * TICKSPERSEC)
87 /* 1601 to 1980 is 379 years plus 91 leap days */
88 #define SECS_1601_TO_1980  ((379 * 365 + 91) * (ULONGLONG)SECSPERDAY)
89 #define TICKS_1601_TO_1980 (SECS_1601_TO_1980 * TICKSPERSEC)
90 /* max ticks that can be represented as Unix time */
91 #define TICKS_1601_TO_UNIX_MAX ((SECS_1601_TO_1970 + INT_MAX) * TICKSPERSEC)
92
93
94 static const int MonthLengths[2][MONSPERYEAR] =
95 {
96         { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
97         { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
98 };
99
100 static inline int IsLeapYear(int Year)
101 {
102         return Year % 4 == 0 && (Year % 100 != 0 || Year % 400 == 0) ? 1 : 0;
103 }
104
105 /******************************************************************************
106  *       RtlTimeToTimeFields [NTDLL.@]
107  *
108  * Convert a time into a TIME_FIELDS structure.
109  *
110  * PARAMS
111  *   liTime     [I] Time to convert.
112  *   TimeFields [O] Destination for the converted time.
113  *
114  * RETURNS
115  *   Nothing.
116  */
117 VOID WINAPI RtlTimeToTimeFields(
118         const LARGE_INTEGER *liTime,
119         PTIME_FIELDS TimeFields)
120 {
121         int SecondsInDay;
122         long int cleaps, years, yearday, months;
123         long int Days;
124         LONGLONG Time;
125
126         /* Extract millisecond from time and convert time into seconds */
127         TimeFields->Milliseconds =
128             (CSHORT) (( liTime->QuadPart % TICKSPERSEC) / TICKSPERMSEC);
129         Time = liTime->QuadPart / TICKSPERSEC;
130
131         /* The native version of RtlTimeToTimeFields does not take leap seconds
132          * into account */
133
134         /* Split the time into days and seconds within the day */
135         Days = Time / SECSPERDAY;
136         SecondsInDay = Time % SECSPERDAY;
137
138         /* compute time of day */
139         TimeFields->Hour = (CSHORT) (SecondsInDay / SECSPERHOUR);
140         SecondsInDay = SecondsInDay % SECSPERHOUR;
141         TimeFields->Minute = (CSHORT) (SecondsInDay / SECSPERMIN);
142         TimeFields->Second = (CSHORT) (SecondsInDay % SECSPERMIN);
143
144         /* compute day of week */
145         TimeFields->Weekday = (CSHORT) ((EPOCHWEEKDAY + Days) % DAYSPERWEEK);
146
147         /* compute year, month and day of month. */
148         cleaps=( 3 * ((4 * Days + 1227) / DAYSPERQUADRICENTENNIUM) + 3 ) / 4;
149         Days += 28188 + cleaps;
150         years = (20 * Days - 2442) / (5 * DAYSPERNORMALQUADRENNIUM);
151         yearday = Days - (years * DAYSPERNORMALQUADRENNIUM)/4;
152         months = (64 * yearday) / 1959;
153         /* the result is based on a year starting on March.
154          * To convert take 12 from Januari and Februari and
155          * increase the year by one. */
156         if( months < 14 ) {
157             TimeFields->Month = months - 1;
158             TimeFields->Year = years + 1524;
159         } else {
160             TimeFields->Month = months - 13;
161             TimeFields->Year = years + 1525;
162         }
163         /* calculation of day of month is based on the wonderful
164          * sequence of INT( n * 30.6): it reproduces the 
165          * 31-30-31-30-31-31 month lengths exactly for small n's */
166         TimeFields->Day = yearday - (1959 * months) / 64 ;
167         return;
168 }
169
170 /******************************************************************************
171  *       RtlTimeFieldsToTime [NTDLL.@]
172  *
173  * Convert a TIME_FIELDS structure into a time.
174  *
175  * PARAMS
176  *   ftTimeFields [I] TIME_FIELDS structure to convert.
177  *   Time         [O] Destination for the converted time.
178  *
179  * RETURNS
180  *   Success: TRUE.
181  *   Failure: FALSE.
182  */
183 BOOLEAN WINAPI RtlTimeFieldsToTime(
184         PTIME_FIELDS tfTimeFields,
185         PLARGE_INTEGER Time)
186 {
187         int month, year, cleaps, day;
188
189         /* FIXME: normalize the TIME_FIELDS structure here */
190         /* No, native just returns 0 (error) if the fields are not */
191         if( tfTimeFields->Milliseconds< 0 || tfTimeFields->Milliseconds > 999 ||
192                 tfTimeFields->Second < 0 || tfTimeFields->Second > 59 ||
193                 tfTimeFields->Minute < 0 || tfTimeFields->Minute > 59 ||
194                 tfTimeFields->Hour < 0 || tfTimeFields->Hour > 23 ||
195                 tfTimeFields->Month < 1 || tfTimeFields->Month > 12 ||
196                 tfTimeFields->Day < 1 ||
197                 tfTimeFields->Day > MonthLengths
198                     [ tfTimeFields->Month ==2 || IsLeapYear(tfTimeFields->Year)]
199                     [ tfTimeFields->Month - 1] ||
200                 tfTimeFields->Year < 1601 )
201             return FALSE;
202
203         /* now calculate a day count from the date
204          * First start counting years from March. This way the leap days
205          * are added at the end of the year, not somewhere in the middle.
206          * Formula's become so much less complicate that way.
207          * To convert: add 12 to the month numbers of Jan and Feb, and 
208          * take 1 from the year */
209         if(tfTimeFields->Month < 3) {
210             month = tfTimeFields->Month + 13;
211             year = tfTimeFields->Year - 1;
212         } else {
213             month = tfTimeFields->Month + 1;
214             year = tfTimeFields->Year;
215         }
216         cleaps = (3 * (year / 100) + 3) / 4;   /* nr of "century leap years"*/
217         day =  (36525 * year) / 100 - cleaps + /* year * dayperyr, corrected */
218                  (1959 * month) / 64 +         /* months * daypermonth */
219                  tfTimeFields->Day -          /* day of the month */
220                  584817 ;                      /* zero that on 1601-01-01 */
221         /* done */
222         
223         Time->QuadPart = (((((LONGLONG) day * HOURSPERDAY +
224             tfTimeFields->Hour) * MINSPERHOUR +
225             tfTimeFields->Minute) * SECSPERMIN +
226             tfTimeFields->Second ) * 1000 +
227             tfTimeFields->Milliseconds ) * TICKSPERMSEC;
228
229         return TRUE;
230 }
231
232 /***********************************************************************
233  *       TIME_GetBias [internal]
234  *
235  * Helper function calculates delta local time from UTC. 
236  *
237  * PARAMS
238  *   utc [I] The current utc time.
239  *   pdaylight [I] Local daylight.
240  *
241  * RETURNS
242  *   The bias for the current timezone.
243  */
244 static LONG TIME_GetBias(void)
245 {
246     static time_t last_utc;
247     static LONG last_bias;
248     LONG ret;
249     time_t utc;
250
251     utc = time( NULL );
252
253     RtlEnterCriticalSection( &TIME_tz_section );
254     if (utc != last_utc)
255     {
256         RTL_TIME_ZONE_INFORMATION tzi;
257         int is_dst = init_tz_info( &tzi );
258
259         last_utc = utc;
260         last_bias = tzi.Bias;
261         last_bias += is_dst ? tzi.DaylightBias : tzi.StandardBias;
262         last_bias *= SECSPERMIN;
263     }
264
265     ret = last_bias;
266
267     RtlLeaveCriticalSection( &TIME_tz_section );
268     return ret;
269 }
270
271 /******************************************************************************
272  *        RtlLocalTimeToSystemTime [NTDLL.@]
273  *
274  * Convert a local time into system time.
275  *
276  * PARAMS
277  *   LocalTime  [I] Local time to convert.
278  *   SystemTime [O] Destination for the converted time.
279  *
280  * RETURNS
281  *   Success: STATUS_SUCCESS.
282  *   Failure: An NTSTATUS error code indicating the problem.
283  */
284 NTSTATUS WINAPI RtlLocalTimeToSystemTime( const LARGE_INTEGER *LocalTime,
285                                           PLARGE_INTEGER SystemTime)
286 {
287     LONG bias;
288
289     TRACE("(%p, %p)\n", LocalTime, SystemTime);
290
291     bias = TIME_GetBias();
292     SystemTime->QuadPart = LocalTime->QuadPart + bias * (LONGLONG)TICKSPERSEC;
293     return STATUS_SUCCESS;
294 }
295
296 /******************************************************************************
297  *       RtlSystemTimeToLocalTime [NTDLL.@]
298  *
299  * Convert a system time into a local time.
300  *
301  * PARAMS
302  *   SystemTime [I] System time to convert.
303  *   LocalTime  [O] Destination for the converted time.
304  *
305  * RETURNS
306  *   Success: STATUS_SUCCESS.
307  *   Failure: An NTSTATUS error code indicating the problem.
308  */
309 NTSTATUS WINAPI RtlSystemTimeToLocalTime( const LARGE_INTEGER *SystemTime,
310                                           PLARGE_INTEGER LocalTime )
311 {
312     LONG bias;
313
314     TRACE("(%p, %p)\n", SystemTime, LocalTime);
315
316     bias = TIME_GetBias();
317     LocalTime->QuadPart = SystemTime->QuadPart - bias * (LONGLONG)TICKSPERSEC;
318     return STATUS_SUCCESS;
319 }
320
321 /******************************************************************************
322  *       RtlTimeToSecondsSince1970 [NTDLL.@]
323  *
324  * Convert a time into a count of seconds since 1970.
325  *
326  * PARAMS
327  *   Time    [I] Time to convert.
328  *   Seconds [O] Destination for the converted time.
329  *
330  * RETURNS
331  *   Success: TRUE.
332  *   Failure: FALSE, if the resulting value will not fit in a DWORD.
333  */
334 BOOLEAN WINAPI RtlTimeToSecondsSince1970( const LARGE_INTEGER *Time, LPDWORD Seconds )
335 {
336     ULONGLONG tmp = ((ULONGLONG)Time->u.HighPart << 32) | Time->u.LowPart;
337     tmp = RtlLargeIntegerDivide( tmp, TICKSPERSEC, NULL );
338     tmp -= SECS_1601_TO_1970;
339     if (tmp > 0xffffffff) return FALSE;
340     *Seconds = (DWORD)tmp;
341     return TRUE;
342 }
343
344 /******************************************************************************
345  *       RtlTimeToSecondsSince1980 [NTDLL.@]
346  *
347  * Convert a time into a count of seconds since 1980.
348  *
349  * PARAMS
350  *   Time    [I] Time to convert.
351  *   Seconds [O] Destination for the converted time.
352  *
353  * RETURNS
354  *   Success: TRUE.
355  *   Failure: FALSE, if the resulting value will not fit in a DWORD.
356  */
357 BOOLEAN WINAPI RtlTimeToSecondsSince1980( const LARGE_INTEGER *Time, LPDWORD Seconds )
358 {
359     ULONGLONG tmp = ((ULONGLONG)Time->u.HighPart << 32) | Time->u.LowPart;
360     tmp = RtlLargeIntegerDivide( tmp, TICKSPERSEC, NULL );
361     tmp -= SECS_1601_TO_1980;
362     if (tmp > 0xffffffff) return FALSE;
363     *Seconds = (DWORD)tmp;
364     return TRUE;
365 }
366
367 /******************************************************************************
368  *       RtlSecondsSince1970ToTime [NTDLL.@]
369  *
370  * Convert a count of seconds since 1970 to a time.
371  *
372  * PARAMS
373  *   Seconds [I] Time to convert.
374  *   Time    [O] Destination for the converted time.
375  *
376  * RETURNS
377  *   Nothing.
378  */
379 void WINAPI RtlSecondsSince1970ToTime( DWORD Seconds, LARGE_INTEGER *Time )
380 {
381     ULONGLONG secs = Seconds * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1970;
382     Time->u.LowPart  = (DWORD)secs;
383     Time->u.HighPart = (DWORD)(secs >> 32);
384 }
385
386 /******************************************************************************
387  *       RtlSecondsSince1980ToTime [NTDLL.@]
388  *
389  * Convert a count of seconds since 1980 to a time.
390  *
391  * PARAMS
392  *   Seconds [I] Time to convert.
393  *   Time    [O] Destination for the converted time.
394  *
395  * RETURNS
396  *   Nothing.
397  */
398 void WINAPI RtlSecondsSince1980ToTime( DWORD Seconds, LARGE_INTEGER *Time )
399 {
400     ULONGLONG secs = Seconds * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1980;
401     Time->u.LowPart  = (DWORD)secs;
402     Time->u.HighPart = (DWORD)(secs >> 32);
403 }
404
405 /******************************************************************************
406  *       RtlTimeToElapsedTimeFields [NTDLL.@]
407  *
408  * Convert a time to a count of elapsed seconds.
409  *
410  * PARAMS
411  *   Time       [I] Time to convert.
412  *   TimeFields [O] Destination for the converted time.
413  *
414  * RETURNS
415  *   Nothing.
416  */
417 void WINAPI RtlTimeToElapsedTimeFields( const LARGE_INTEGER *Time, PTIME_FIELDS TimeFields )
418 {
419     LONGLONG time;
420     INT rem;
421
422     time = RtlExtendedLargeIntegerDivide( Time->QuadPart, TICKSPERSEC, &rem );
423     TimeFields->Milliseconds = rem / TICKSPERMSEC;
424
425     /* time is now in seconds */
426     TimeFields->Year  = 0;
427     TimeFields->Month = 0;
428     TimeFields->Day   = RtlExtendedLargeIntegerDivide( time, SECSPERDAY, &rem );
429
430     /* rem is now the remaining seconds in the last day */
431     TimeFields->Second = rem % 60;
432     rem /= 60;
433     TimeFields->Minute = rem % 60;
434     TimeFields->Hour = rem / 60;
435 }
436
437 /***********************************************************************
438  *       NtQuerySystemTime [NTDLL.@]
439  *       ZwQuerySystemTime [NTDLL.@]
440  *
441  * Get the current system time.
442  *
443  * PARAMS
444  *   Time [O] Destination for the current system time.
445  *
446  * RETURNS
447  *   Success: STATUS_SUCCESS.
448  *   Failure: An NTSTATUS error code indicating the problem.
449  */
450 NTSTATUS WINAPI NtQuerySystemTime( PLARGE_INTEGER Time )
451 {
452     struct timeval now;
453
454     gettimeofday( &now, 0 );
455     Time->QuadPart = now.tv_sec * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1970;
456     Time->QuadPart += now.tv_usec * 10;
457     return STATUS_SUCCESS;
458 }
459
460 /******************************************************************************
461  *  NtQueryPerformanceCounter   [NTDLL.@]
462  *
463  *  Note: Windows uses a timer clocked at a multiple of 1193182 Hz. There is a
464  *  good number of applications that crash when the returned frequency is either
465  *  lower or higher than what Windows gives. Also too high counter values are
466  *  reported to give problems.
467  */
468 NTSTATUS WINAPI NtQueryPerformanceCounter( PLARGE_INTEGER Counter, PLARGE_INTEGER Frequency )
469 {
470     LARGE_INTEGER now;
471
472     if (!Counter) return STATUS_ACCESS_VIOLATION;
473
474     /* convert a counter that increments at a rate of 10 MHz
475      * to one of 1.193182 MHz, with some care for arithmetic
476      * overflow and good accuracy (21/176 = 0.11931818) */
477     NtQuerySystemTime( &now );
478     Counter->QuadPart = ((now.QuadPart - server_start_time) * 21) / 176;
479     if (Frequency) Frequency->QuadPart = 1193182;
480     return STATUS_SUCCESS;
481 }
482
483
484 /******************************************************************************
485  * NtGetTickCount   (NTDLL.@)
486  * ZwGetTickCount   (NTDLL.@)
487  */
488 ULONG WINAPI NtGetTickCount(void)
489 {
490     LARGE_INTEGER now;
491
492     NtQuerySystemTime( &now );
493     return (now.QuadPart - server_start_time) / 10000;
494 }
495
496 /* calculate the mday of dst change date, so that for instance Sun 5 Oct 2007
497  * (last Sunday in October of 2007) becomes Sun Oct 28 2007
498  *
499  * Note: year, day and month must be in unix format.
500  */
501 static int weekday_to_mday(int year, int day, int mon, int day_of_week)
502 {
503     struct tm date;
504     time_t tmp;
505     int wday, mday;
506
507     /* find first day in the month matching week day of the date */
508     memset(&date, 0, sizeof(date));
509     date.tm_year = year;
510     date.tm_mon = mon;
511     date.tm_mday = -1;
512     date.tm_wday = -1;
513     do
514     {
515         date.tm_mday++;
516         tmp = mktime(&date);
517     } while (date.tm_wday != day_of_week || date.tm_mon != mon);
518
519     mday = date.tm_mday;
520
521     /* find number of week days in the month matching week day of the date */
522     wday = 1; /* 1 - 1st, ...., 5 - last */
523     while (wday < day)
524     {
525         struct tm *tm;
526
527         date.tm_mday += 7;
528         tmp = mktime(&date);
529         tm = localtime(&tmp);
530         if (tm->tm_mon != mon)
531             break;
532         mday = tm->tm_mday;
533         wday++;
534     }
535
536     return mday;
537 }
538
539 static BOOL match_tz_date(const RTL_SYSTEM_TIME *st, const RTL_SYSTEM_TIME *reg_st)
540 {
541     WORD wDay;
542
543     if (st->wMonth != reg_st->wMonth) return FALSE;
544
545     if (!st->wMonth) return TRUE; /* no transition dates */
546
547     wDay = reg_st->wDay;
548     if (!reg_st->wYear) /* date in a day-of-week format */
549         wDay = weekday_to_mday(st->wYear - 1900, reg_st->wDay, reg_st->wMonth - 1, reg_st->wDayOfWeek);
550
551     if (st->wDay != wDay ||
552         st->wHour != reg_st->wHour ||
553         st->wMinute != reg_st->wMinute ||
554         st->wSecond != reg_st->wSecond ||
555         st->wMilliseconds != reg_st->wMilliseconds) return FALSE;
556
557     return TRUE;
558 }
559
560 static BOOL match_tz_info(const RTL_TIME_ZONE_INFORMATION *tzi, const RTL_TIME_ZONE_INFORMATION *reg_tzi)
561 {
562     if (tzi->Bias == reg_tzi->Bias &&
563         match_tz_date(&tzi->StandardDate, &reg_tzi->StandardDate) &&
564         match_tz_date(&tzi->DaylightDate, &reg_tzi->DaylightDate))
565         return TRUE;
566
567     return FALSE;
568 }
569
570 static BOOL reg_query_value(HKEY hkey, LPCWSTR name, DWORD type, void *data, DWORD count)
571 {
572     UNICODE_STRING nameW;
573     char buf[256];
574     KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buf;
575
576     if (count > sizeof(buf) - sizeof(KEY_VALUE_PARTIAL_INFORMATION))
577         return FALSE;
578
579     RtlInitUnicodeString(&nameW, name);
580
581     if (NtQueryValueKey(hkey, &nameW, KeyValuePartialInformation,
582                         buf, sizeof(buf), &count))
583         return FALSE;
584
585     if (info->Type != type) return FALSE;
586
587     memcpy(data, info->Data, info->DataLength);
588     return TRUE;
589 }
590
591 static void find_reg_tz_info(RTL_TIME_ZONE_INFORMATION *tzi)
592 {
593     static const WCHAR Time_ZonesW[] = { 'M','a','c','h','i','n','e','\\',
594         'S','o','f','t','w','a','r','e','\\',
595         'M','i','c','r','o','s','o','f','t','\\',
596         'W','i','n','d','o','w','s',' ','N','T','\\',
597         'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
598         'T','i','m','e',' ','Z','o','n','e','s',0 };
599     HANDLE hkey;
600     ULONG idx;
601     OBJECT_ATTRIBUTES attr;
602     UNICODE_STRING nameW;
603     WCHAR buf[128];
604
605     attr.Length = sizeof(attr);
606     attr.RootDirectory = 0;
607     attr.ObjectName = &nameW;
608     attr.Attributes = 0;
609     attr.SecurityDescriptor = NULL;
610     attr.SecurityQualityOfService = NULL;
611     RtlInitUnicodeString(&nameW, Time_ZonesW);
612     if (NtOpenKey(&hkey, KEY_READ, &attr))
613     {
614         WARN("Unable to open the time zones key\n");
615         return;
616     }
617
618     idx = 0;
619     nameW.Buffer = buf;
620     nameW.Length = sizeof(buf);
621     nameW.MaximumLength = sizeof(buf);
622
623     while (!RtlpNtEnumerateSubKey(hkey, &nameW, idx++))
624     {
625         static const WCHAR stdW[] = { 'S','t','d',0 };
626         static const WCHAR dltW[] = { 'D','l','t',0 };
627         static const WCHAR tziW[] = { 'T','Z','I',0 };
628         RTL_TIME_ZONE_INFORMATION reg_tzi;
629         HANDLE hSubkey;
630         struct tz_reg_data
631         {
632             LONG bias;
633             LONG std_bias;
634             LONG dlt_bias;
635             RTL_SYSTEM_TIME std_date;
636             RTL_SYSTEM_TIME dlt_date;
637         } tz_data;
638
639         attr.Length = sizeof(attr);
640         attr.RootDirectory = hkey;
641         attr.ObjectName = &nameW;
642         attr.Attributes = 0;
643         attr.SecurityDescriptor = NULL;
644         attr.SecurityQualityOfService = NULL;
645         if (NtOpenKey(&hSubkey, KEY_READ, &attr))
646         {
647             WARN("Unable to open subkey %s\n", debugstr_wn(nameW.Buffer, nameW.Length/sizeof(WCHAR)));
648             continue;
649         }
650
651 #define get_value(hkey, name, type, data, len) \
652     if (!reg_query_value(hkey, name, type, data, len)) \
653     { \
654         WARN("can't read data from %s\n", debugstr_w(name)); \
655         NtClose(hkey); \
656         continue; \
657     }
658
659         get_value(hSubkey, stdW, REG_SZ, reg_tzi.StandardName, sizeof(reg_tzi.StandardName));
660         get_value(hSubkey, dltW, REG_SZ, reg_tzi.DaylightName, sizeof(reg_tzi.DaylightName));
661         get_value(hSubkey, tziW, REG_BINARY, &tz_data, sizeof(tz_data));
662
663 #undef get_value
664
665         reg_tzi.Bias = tz_data.bias;
666         reg_tzi.StandardBias = tz_data.std_bias;
667         reg_tzi.DaylightBias = tz_data.dlt_bias;
668         reg_tzi.StandardDate = tz_data.std_date;
669         reg_tzi.DaylightDate = tz_data.dlt_date;
670
671         TRACE("%s: bias %d\n", debugstr_wn(nameW.Buffer, nameW.Length/sizeof(WCHAR)), reg_tzi.Bias);
672         TRACE("std (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
673             reg_tzi.StandardDate.wDay, reg_tzi.StandardDate.wMonth,
674             reg_tzi.StandardDate.wYear, reg_tzi.StandardDate.wDayOfWeek,
675             reg_tzi.StandardDate.wHour, reg_tzi.StandardDate.wMinute,
676             reg_tzi.StandardDate.wSecond, reg_tzi.StandardDate.wMilliseconds,
677             reg_tzi.StandardBias);
678         TRACE("dst (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
679             reg_tzi.DaylightDate.wDay, reg_tzi.DaylightDate.wMonth,
680             reg_tzi.DaylightDate.wYear, reg_tzi.DaylightDate.wDayOfWeek,
681             reg_tzi.DaylightDate.wHour, reg_tzi.DaylightDate.wMinute,
682             reg_tzi.DaylightDate.wSecond, reg_tzi.DaylightDate.wMilliseconds,
683             reg_tzi.DaylightBias);
684
685         NtClose(hSubkey);
686
687         if (match_tz_info(tzi, &reg_tzi))
688         {
689             memcpy(tzi, &reg_tzi, sizeof(*tzi));
690             NtClose(hkey);
691             return;
692         }
693
694         /* reset len */
695         nameW.Length = sizeof(buf);
696         nameW.MaximumLength = sizeof(buf);
697     }
698
699     NtClose(hkey);
700
701     FIXME("Can't find matching timezone information in the registry for "
702           "bias %d, std (d/m/y): %u/%02u/%04u, dlt (d/m/y): %u/%02u/%04u\n",
703           tzi->Bias,
704           tzi->StandardDate.wDay, tzi->StandardDate.wMonth, tzi->StandardDate.wYear,
705           tzi->DaylightDate.wDay, tzi->DaylightDate.wMonth, tzi->DaylightDate.wYear);
706 }
707
708 static time_t find_dst_change(unsigned long min, unsigned long max, int *is_dst)
709 {
710     time_t start;
711     struct tm *tm;
712
713     start = min;
714     tm = localtime(&start);
715     *is_dst = !tm->tm_isdst;
716     TRACE("starting date isdst %d, %s", !*is_dst, ctime(&start));
717
718     while (min <= max)
719     {
720         time_t pos = (min + max) / 2;
721         tm = localtime(&pos);
722
723         if (tm->tm_isdst != *is_dst)
724             min = pos + 1;
725         else
726             max = pos - 1;
727     }
728     return min;
729 }
730
731 static int init_tz_info(RTL_TIME_ZONE_INFORMATION *tzi)
732 {
733     static RTL_TIME_ZONE_INFORMATION cached_tzi;
734     static int current_year = -1;
735     struct tm *tm;
736     time_t year_start, year_end, tmp, dlt = 0, std = 0;
737     int is_dst, current_is_dst;
738
739     RtlEnterCriticalSection( &TIME_tz_section );
740
741     year_start = time(NULL);
742     tm = localtime(&year_start);
743
744     current_is_dst = tm->tm_isdst;
745     if (current_year == tm->tm_year)
746     {
747         *tzi = cached_tzi;
748         RtlLeaveCriticalSection( &TIME_tz_section );
749         return current_is_dst;
750     }
751
752     memset(tzi, 0, sizeof(*tzi));
753
754     TRACE("tz data will be valid through year %d\n", tm->tm_year + 1900);
755     current_year = tm->tm_year;
756
757     tm->tm_isdst = 0;
758     tm->tm_mday = 1;
759     tm->tm_mon = tm->tm_hour = tm->tm_min = tm->tm_sec = tm->tm_wday = tm->tm_yday = 0;
760     year_start = mktime(tm);
761     TRACE("year_start: %s", ctime(&year_start));
762
763     tm->tm_mday = tm->tm_wday = tm->tm_yday = 0;
764     tm->tm_mon = 12;
765     tm->tm_hour = 23;
766     tm->tm_min = tm->tm_sec = 59;
767     year_end = mktime(tm);
768     TRACE("year_end: %s", ctime(&year_end));
769
770     tm = gmtime(&year_start);
771     tzi->Bias = (LONG)(mktime(tm) - year_start) / 60;
772     TRACE("bias: %d\n", tzi->Bias);
773
774     tmp = find_dst_change(year_start, year_end, &is_dst);
775     if (is_dst)
776         dlt = tmp;
777     else
778         std = tmp;
779
780     tmp = find_dst_change(tmp, year_end, &is_dst);
781     if (is_dst)
782         dlt = tmp;
783     else
784         std = tmp;
785
786     TRACE("std: %s", ctime(&std));
787     TRACE("dlt: %s", ctime(&dlt));
788
789     if (dlt == std || !dlt || !std)
790     {
791         RtlLeaveCriticalSection( &TIME_tz_section );
792         TRACE("there is no daylight saving rules in this time zone\n");
793         return 0;
794     }
795
796     tmp = dlt - tzi->Bias * 60;
797     tm = gmtime(&tmp);
798     TRACE("dlt gmtime: %s", asctime(tm));
799
800     tzi->DaylightBias = -60;
801     tzi->DaylightDate.wYear = tm->tm_year + 1900;
802     tzi->DaylightDate.wMonth = tm->tm_mon + 1;
803     tzi->DaylightDate.wDayOfWeek = tm->tm_wday;
804     tzi->DaylightDate.wDay = tm->tm_mday;
805     tzi->DaylightDate.wHour = tm->tm_hour;
806     tzi->DaylightDate.wMinute = tm->tm_min;
807     tzi->DaylightDate.wSecond = tm->tm_sec;
808     tzi->DaylightDate.wMilliseconds = 0;
809
810     TRACE("daylight (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
811         tzi->DaylightDate.wDay, tzi->DaylightDate.wMonth,
812         tzi->DaylightDate.wYear, tzi->DaylightDate.wDayOfWeek,
813         tzi->DaylightDate.wHour, tzi->DaylightDate.wMinute,
814         tzi->DaylightDate.wSecond, tzi->DaylightDate.wMilliseconds,
815         tzi->DaylightBias);
816
817     tmp = std - tzi->Bias * 60 - tzi->DaylightBias * 60;
818     tm = gmtime(&tmp);
819     TRACE("std gmtime: %s", asctime(tm));
820
821     tzi->StandardBias = 0;
822     tzi->StandardDate.wYear = tm->tm_year + 1900;
823     tzi->StandardDate.wMonth = tm->tm_mon + 1;
824     tzi->StandardDate.wDayOfWeek = tm->tm_wday;
825     tzi->StandardDate.wDay = tm->tm_mday;
826     tzi->StandardDate.wHour = tm->tm_hour;
827     tzi->StandardDate.wMinute = tm->tm_min;
828     tzi->StandardDate.wSecond = tm->tm_sec;
829     tzi->StandardDate.wMilliseconds = 0;
830
831     TRACE("standard (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
832         tzi->StandardDate.wDay, tzi->StandardDate.wMonth,
833         tzi->StandardDate.wYear, tzi->StandardDate.wDayOfWeek,
834         tzi->StandardDate.wHour, tzi->StandardDate.wMinute,
835         tzi->StandardDate.wSecond, tzi->StandardDate.wMilliseconds,
836         tzi->StandardBias);
837
838     find_reg_tz_info(tzi);
839     cached_tzi = *tzi;
840
841     RtlLeaveCriticalSection( &TIME_tz_section );
842
843     return current_is_dst;
844 }
845
846 /***********************************************************************
847  *      RtlQueryTimeZoneInformation [NTDLL.@]
848  *
849  * Get information about the current timezone.
850  *
851  * PARAMS
852  *   tzinfo [O] Destination for the retrieved timezone info.
853  *
854  * RETURNS
855  *   Success: STATUS_SUCCESS.
856  *   Failure: An NTSTATUS error code indicating the problem.
857  */
858 NTSTATUS WINAPI RtlQueryTimeZoneInformation(RTL_TIME_ZONE_INFORMATION *tzinfo)
859 {
860     init_tz_info( tzinfo );
861
862     return STATUS_SUCCESS;
863 }
864
865 /***********************************************************************
866  *       RtlSetTimeZoneInformation [NTDLL.@]
867  *
868  * Set the current time zone information.
869  *
870  * PARAMS
871  *   tzinfo [I] Timezone information to set.
872  *
873  * RETURNS
874  *   Success: STATUS_SUCCESS.
875  *   Failure: An NTSTATUS error code indicating the problem.
876  *
877  */
878 NTSTATUS WINAPI RtlSetTimeZoneInformation( const RTL_TIME_ZONE_INFORMATION *tzinfo )
879 {
880     return STATUS_PRIVILEGE_NOT_HELD;
881 }
882
883 /***********************************************************************
884  *        NtSetSystemTime [NTDLL.@]
885  *        ZwSetSystemTime [NTDLL.@]
886  *
887  * Set the system time.
888  *
889  * PARAMS
890  *   NewTime [I] The time to set.
891  *   OldTime [O] Optional destination for the previous system time.
892  *
893  * RETURNS
894  *   Success: STATUS_SUCCESS.
895  *   Failure: An NTSTATUS error code indicating the problem.
896  */
897 NTSTATUS WINAPI NtSetSystemTime(const LARGE_INTEGER *NewTime, LARGE_INTEGER *OldTime)
898 {
899     struct timeval tv;
900     time_t tm_t;
901     DWORD sec, oldsec;
902     LARGE_INTEGER tm;
903     int err;
904
905     /* Return the old time if necessary */
906     if (!OldTime) OldTime = &tm;
907
908     NtQuerySystemTime( OldTime );
909     RtlTimeToSecondsSince1970( OldTime, &oldsec );
910
911     RtlTimeToSecondsSince1970( NewTime, &sec );
912
913     /* set the new time */
914     tv.tv_sec = sec;
915     tv.tv_usec = 0;
916
917     /* error and sanity check*/
918     if(sec == (time_t)-1 || abs((int)(sec-oldsec)) > SETTIME_MAX_ADJUST) {
919         err = 2;
920     } else {
921 #ifdef HAVE_SETTIMEOFDAY
922         err = settimeofday(&tv, NULL); /* 0 is OK, -1 is error */
923         if(err == 0)
924             return STATUS_SUCCESS;
925 #else
926         err = 1;
927 #endif
928     }
929
930     tm_t = sec;
931     ERR("Cannot set time to %s Time adjustment %ld %s\n",
932         ctime( &tm_t ),
933             (long)(sec-oldsec),
934             err == -1 ? "No Permission"
935                       : sec == (time_t)-1 ? "" : "is too large." );
936
937     if(err == 2)
938         return STATUS_INVALID_PARAMETER;
939     else if(err == -1)
940         return STATUS_PRIVILEGE_NOT_HELD;
941     else
942         return STATUS_NOT_IMPLEMENTED;
943 }