Home | History | Annotate | Download | only in common
      1 /*
      2 ********************************************************************************
      3 *   Copyright (C) 2005-2013, International Business Machines
      4 *   Corporation and others.  All Rights Reserved.
      5 ********************************************************************************
      6 *
      7 * File WINTZ.CPP
      8 *
      9 ********************************************************************************
     10 */
     11 
     12 #include "unicode/utypes.h"
     13 
     14 #if U_PLATFORM_HAS_WIN32_API
     15 
     16 #include "wintz.h"
     17 #include "cmemory.h"
     18 #include "cstring.h"
     19 
     20 #include "unicode/ures.h"
     21 
     22 #   define WIN32_LEAN_AND_MEAN
     23 #   define VC_EXTRALEAN
     24 #   define NOUSER
     25 #   define NOSERVICE
     26 #   define NOIME
     27 #   define NOMCX
     28 #include <windows.h>
     29 
     30 #define MAX_LENGTH_ID 40
     31 
     32 /* The layout of the Tzi value in the registry */
     33 typedef struct
     34 {
     35     int32_t bias;
     36     int32_t standardBias;
     37     int32_t daylightBias;
     38     SYSTEMTIME standardDate;
     39     SYSTEMTIME daylightDate;
     40 } TZI;
     41 
     42 /**
     43  * Various registry keys and key fragments.
     44  */
     45 static const char CURRENT_ZONE_REGKEY[] = "SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation\\";
     46 static const char STANDARD_NAME_REGKEY[] = "StandardName";
     47 static const char STANDARD_TIME_REGKEY[] = " Standard Time";
     48 static const char TZI_REGKEY[] = "TZI";
     49 static const char STD_REGKEY[] = "Std";
     50 
     51 /**
     52  * HKLM subkeys used to probe for the flavor of Windows.  Note that we
     53  * specifically check for the "GMT" zone subkey; this is present on
     54  * NT, but on XP has become "GMT Standard Time".  We need to
     55  * discriminate between these cases.
     56  */
     57 static const char* const WIN_TYPE_PROBE_REGKEY[] = {
     58     /* WIN_9X_ME_TYPE */
     59     "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Time Zones",
     60 
     61     /* WIN_NT_TYPE */
     62     "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\GMT"
     63 
     64     /* otherwise: WIN_2K_XP_TYPE */
     65 };
     66 
     67 /**
     68  * The time zone root subkeys (under HKLM) for different flavors of
     69  * Windows.
     70  */
     71 static const char* const TZ_REGKEY[] = {
     72     /* WIN_9X_ME_TYPE */
     73     "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Time Zones\\",
     74 
     75     /* WIN_NT_TYPE | WIN_2K_XP_TYPE */
     76     "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\"
     77 };
     78 
     79 /**
     80  * Flavor of Windows, from our perspective.  Not a real OS version,
     81  * but rather the flavor of the layout of the time zone information in
     82  * the registry.
     83  */
     84 enum {
     85     WIN_9X_ME_TYPE = 1,
     86     WIN_NT_TYPE = 2,
     87     WIN_2K_XP_TYPE = 3
     88 };
     89 
     90 static int32_t gWinType = 0;
     91 
     92 static int32_t detectWindowsType()
     93 {
     94     int32_t winType;
     95     LONG result;
     96     HKEY hkey;
     97 
     98     /* Detect the version of windows by trying to open a sequence of
     99         probe keys.  We don't use the OS version API because what we
    100         really want to know is how the registry is laid out.
    101         Specifically, is it 9x/Me or not, and is it "GMT" or "GMT
    102         Standard Time". */
    103     for (winType = 0; winType < 2; winType++) {
    104         result = RegOpenKeyExA(HKEY_LOCAL_MACHINE,
    105                               WIN_TYPE_PROBE_REGKEY[winType],
    106                               0,
    107                               KEY_QUERY_VALUE,
    108                               &hkey);
    109         RegCloseKey(hkey);
    110 
    111         if (result == ERROR_SUCCESS) {
    112             break;
    113         }
    114     }
    115 
    116     return winType+1; /* +1 to bring it inline with the enum */
    117 }
    118 
    119 static LONG openTZRegKey(HKEY *hkey, const char *winid)
    120 {
    121     char subKeyName[110]; /* TODO: why 96?? */
    122     char *name;
    123     LONG result;
    124 
    125     /* This isn't thread safe, but it's good enough because the result should be constant per system. */
    126     if (gWinType <= 0) {
    127         gWinType = detectWindowsType();
    128     }
    129 
    130     uprv_strcpy(subKeyName, TZ_REGKEY[(gWinType != WIN_9X_ME_TYPE)]);
    131     name = &subKeyName[strlen(subKeyName)];
    132     uprv_strcat(subKeyName, winid);
    133 
    134     if (gWinType == WIN_9X_ME_TYPE) {
    135         /* Remove " Standard Time" */
    136         char *pStd = uprv_strstr(subKeyName, STANDARD_TIME_REGKEY);
    137         if (pStd) {
    138             *pStd = 0;
    139         }
    140     }
    141 
    142     result = RegOpenKeyExA(HKEY_LOCAL_MACHINE,
    143                             subKeyName,
    144                             0,
    145                             KEY_QUERY_VALUE,
    146                             hkey);
    147     return result;
    148 }
    149 
    150 static LONG getTZI(const char *winid, TZI *tzi)
    151 {
    152     DWORD cbData = sizeof(TZI);
    153     LONG result;
    154     HKEY hkey;
    155 
    156     result = openTZRegKey(&hkey, winid);
    157 
    158     if (result == ERROR_SUCCESS) {
    159         result = RegQueryValueExA(hkey,
    160                                     TZI_REGKEY,
    161                                     NULL,
    162                                     NULL,
    163                                     (LPBYTE)tzi,
    164                                     &cbData);
    165 
    166     }
    167 
    168     RegCloseKey(hkey);
    169 
    170     return result;
    171 }
    172 
    173 static LONG getSTDName(const char *winid, char *regStdName, int32_t length) {
    174     DWORD cbData = length;
    175     LONG result;
    176     HKEY hkey;
    177 
    178     result = openTZRegKey(&hkey, winid);
    179 
    180     if (result == ERROR_SUCCESS) {
    181         result = RegQueryValueExA(hkey,
    182                                     STD_REGKEY,
    183                                     NULL,
    184                                     NULL,
    185                                     (LPBYTE)regStdName,
    186                                     &cbData);
    187 
    188     }
    189 
    190     RegCloseKey(hkey);
    191 
    192     return result;
    193 }
    194 
    195 /*
    196   This code attempts to detect the Windows time zone, as set in the
    197   Windows Date and Time control panel.  It attempts to work on
    198   multiple flavors of Windows (9x, Me, NT, 2000, XP) and on localized
    199   installs.  It works by directly interrogating the registry and
    200   comparing the data there with the data returned by the
    201   GetTimeZoneInformation API, along with some other strategies.  The
    202   registry contains time zone data under one of two keys (depending on
    203   the flavor of Windows):
    204 
    205     HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Time Zones\
    206     HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\
    207 
    208   Under this key are several subkeys, one for each time zone.  These
    209   subkeys are named "Pacific" on Win9x/Me and "Pacific Standard Time"
    210   on WinNT/2k/XP.  There are some other wrinkles; see the code for
    211   details.  The subkey name is NOT LOCALIZED, allowing us to support
    212   localized installs.
    213 
    214   Under the subkey are data values.  We care about:
    215 
    216     Std   Standard time display name, localized
    217     TZI   Binary block of data
    218 
    219   The TZI data is of particular interest.  It contains the offset, two
    220   more offsets for standard and daylight time, and the start and end
    221   rules.  This is the same data returned by the GetTimeZoneInformation
    222   API.  The API may modify the data on the way out, so we have to be
    223   careful, but essentially we do a binary comparison against the TZI
    224   blocks of various registry keys.  When we find a match, we know what
    225   time zone Windows is set to.  Since the registry key is not
    226   localized, we can then translate the key through a simple table
    227   lookup into the corresponding ICU time zone.
    228 
    229   This strategy doesn't always work because there are zones which
    230   share an offset and rules, so more than one TZI block will match.
    231   For example, both Tokyo and Seoul are at GMT+9 with no DST rules;
    232   their TZI blocks are identical.  For these cases, we fall back to a
    233   name lookup.  We attempt to match the display name as stored in the
    234   registry for the current zone to the display name stored in the
    235   registry for various Windows zones.  By comparing the registry data
    236   directly we avoid conversion complications.
    237 
    238   Author: Alan Liu
    239   Since: ICU 2.6
    240   Based on original code by Carl Brown <cbrown (at) xnetinc.com>
    241 */
    242 
    243 /**
    244  * Main Windows time zone detection function.  Returns the Windows
    245  * time zone, translated to an ICU time zone, or NULL upon failure.
    246  */
    247 U_CFUNC const char* U_EXPORT2
    248 uprv_detectWindowsTimeZone() {
    249     UErrorCode status = U_ZERO_ERROR;
    250     UResourceBundle* bundle = NULL;
    251     char* icuid = NULL;
    252     char apiStdName[MAX_LENGTH_ID];
    253     char regStdName[MAX_LENGTH_ID];
    254     char tmpid[MAX_LENGTH_ID];
    255     int32_t len;
    256     int id;
    257     int errorCode;
    258     char ISOcode[3]; /* 2 letter iso code */
    259 
    260     LONG result;
    261     TZI tziKey;
    262     TZI tziReg;
    263     TIME_ZONE_INFORMATION apiTZI;
    264 
    265     /* Obtain TIME_ZONE_INFORMATION from the API, and then convert it
    266        to TZI.  We could also interrogate the registry directly; we do
    267        this below if needed. */
    268     uprv_memset(&apiTZI, 0, sizeof(apiTZI));
    269     uprv_memset(&tziKey, 0, sizeof(tziKey));
    270     uprv_memset(&tziReg, 0, sizeof(tziReg));
    271     GetTimeZoneInformation(&apiTZI);
    272     tziKey.bias = apiTZI.Bias;
    273     uprv_memcpy((char *)&tziKey.standardDate, (char*)&apiTZI.StandardDate,
    274            sizeof(apiTZI.StandardDate));
    275     uprv_memcpy((char *)&tziKey.daylightDate, (char*)&apiTZI.DaylightDate,
    276            sizeof(apiTZI.DaylightDate));
    277 
    278     /* Convert the wchar_t* standard name to char* */
    279     uprv_memset(apiStdName, 0, sizeof(apiStdName));
    280     wcstombs(apiStdName, apiTZI.StandardName, MAX_LENGTH_ID);
    281 
    282     tmpid[0] = 0;
    283 
    284     id = GetUserGeoID(GEOCLASS_NATION);
    285     errorCode = GetGeoInfo(id,GEO_ISO2,ISOcode,3,0);
    286 
    287     bundle = ures_openDirect(NULL, "windowsZones", &status);
    288     ures_getByKey(bundle, "mapTimezones", bundle, &status);
    289 
    290     /* Note: We get the winid not from static tables but from resource bundle. */
    291     while (U_SUCCESS(status) && ures_hasNext(bundle)) {
    292         UBool idFound = FALSE;
    293         const char* winid;
    294         UResourceBundle* winTZ = ures_getNextResource(bundle, NULL, &status);
    295         if (U_FAILURE(status)) {
    296             break;
    297         }
    298         winid = ures_getKey(winTZ);
    299         result = getTZI(winid, &tziReg);
    300 
    301         if (result == ERROR_SUCCESS) {
    302             /* Windows alters the DaylightBias in some situations.
    303                Using the bias and the rules suffices, so overwrite
    304                these unreliable fields. */
    305             tziKey.standardBias = tziReg.standardBias;
    306             tziKey.daylightBias = tziReg.daylightBias;
    307 
    308             if (uprv_memcmp((char *)&tziKey, (char*)&tziReg, sizeof(tziKey)) == 0) {
    309                 const UChar* icuTZ = NULL;
    310                 if (errorCode != 0) {
    311                     icuTZ = ures_getStringByKey(winTZ, ISOcode, &len, &status);
    312                 }
    313                 if (errorCode==0 || icuTZ==NULL) {
    314                     /* fallback to default "001" and reset status */
    315                     status = U_ZERO_ERROR;
    316                     icuTZ = ures_getStringByKey(winTZ, "001", &len, &status);
    317                 }
    318 
    319                 if (U_SUCCESS(status)) {
    320                     /* Get the standard name from the registry key to compare with
    321                        the one from Windows API call. */
    322                     uprv_memset(regStdName, 0, sizeof(regStdName));
    323                     result = getSTDName(winid, regStdName, sizeof(regStdName));
    324                     if (result == ERROR_SUCCESS) {
    325                         if (uprv_strcmp(apiStdName, regStdName) == 0) {
    326                             idFound = TRUE;
    327                         }
    328                     }
    329 
    330                     /* tmpid buffer holds the ICU timezone ID corresponding to the timezone ID from Windows.
    331                      * If none is found, tmpid buffer will contain a fallback ID (i.e. the time zone ID matching
    332                      * the current time zone information)
    333                      */
    334                     if (idFound || tmpid[0] == 0) {
    335                         /* if icuTZ has more than one city, take only the first (i.e. terminate icuTZ at first space) */
    336                         int index=0;
    337                         while (! (*icuTZ == '\0' || *icuTZ ==' ')) {
    338                             tmpid[index++]=(char)(*icuTZ++);  /* safe to assume 'char' is ASCII compatible on windows */
    339                         }
    340                         tmpid[index]='\0';
    341                     }
    342                 }
    343             }
    344         }
    345         ures_close(winTZ);
    346         if (idFound) {
    347             break;
    348         }
    349     }
    350 
    351     /*
    352      * Copy the timezone ID to icuid to be returned.
    353      */
    354     if (tmpid[0] != 0) {
    355         len = uprv_strlen(tmpid);
    356         icuid = (char*)uprv_calloc(len + 1, sizeof(char));
    357         if (icuid != NULL) {
    358             uprv_strcpy(icuid, tmpid);
    359         }
    360     }
    361 
    362     ures_close(bundle);
    363 
    364     return icuid;
    365 }
    366 
    367 #endif /* U_PLATFORM_HAS_WIN32_API */
    368