TimeZone_md.c 23.4 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27 28 29 30 31 32 33 34
 */

#include <stdlib.h>
#include <stdio.h>
#include <strings.h>
#include <time.h>
#include <limits.h>
#include <errno.h>
#include <stddef.h>
#include <sys/stat.h>
#include <sys/types.h>
35 36
#include <string.h>
#include <dirent.h>
D
duke 已提交
37
#include <unistd.h>
S
simonis 已提交
38
#if defined(__solaris__)
39
#include <libscf.h>
D
duke 已提交
40 41 42
#endif

#include "jvm.h"
S
simonis 已提交
43
#include "TimeZone_md.h"
D
duke 已提交
44

45 46
static char *isFileIdentical(char* buf, size_t size, char *pathname);

D
duke 已提交
47 48
#define SKIP_SPACE(p)   while (*p == ' ' || *p == '\t') p++;

S
simonis 已提交
49 50 51 52 53
#if defined(_ALLBSD_SOURCE)
#define dirent64 dirent
#define readdir64_r readdir_r
#endif

D
duke 已提交
54 55 56 57 58 59
#if !defined(__solaris__) || defined(__sparcv9) || defined(amd64)
#define fileopen        fopen
#define filegets        fgets
#define fileclose       fclose
#endif

60
#if defined(__linux__) || defined(_ALLBSD_SOURCE)
61 62 63
static const char *ETC_TIMEZONE_FILE = "/etc/timezone";
static const char *ZONEINFO_DIR = "/usr/share/zoneinfo";
static const char *DEFAULT_ZONEINFO_FILE = "/etc/localtime";
64 65 66 67
#else
static const char *SYS_INIT_FILE = "/etc/default/init";
static const char *ZONEINFO_DIR = "/usr/share/lib/zoneinfo";
static const char *DEFAULT_ZONEINFO_FILE = "/usr/share/lib/zoneinfo/localtime";
S
simonis 已提交
68 69
#endif /* defined(__linux__) || defined(_ALLBSD_SOURCE) */

70 71
static const char popularZones[][4] = {"UTC", "GMT"};

S
simonis 已提交
72 73 74 75 76
#if defined(_AIX)
static const char *ETC_ENVIRONMENT_FILE = "/etc/environment";
#endif

#if defined(__linux__) || defined(MACOSX) || defined(__solaris__)
D
duke 已提交
77 78

/*
79 80
 * Returns a pointer to the zone ID portion of the given zoneinfo file
 * name, or NULL if the given string doesn't contain "zoneinfo/".
D
duke 已提交
81 82 83 84 85 86
 */
static char *
getZoneName(char *str)
{
    static const char *zidir = "zoneinfo/";

87
    char *pos = strstr((const char *)str, zidir);
D
duke 已提交
88 89 90 91 92 93 94 95 96
    if (pos == NULL) {
        return NULL;
    }
    return pos + strlen(zidir);
}

/*
 * Returns a path name created from the given 'dir' and 'name' under
 * UNIX. This function allocates memory for the pathname calling
97
 * malloc(). NULL is returned if malloc() fails.
D
duke 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111
 */
static char *
getPathName(const char *dir, const char *name) {
    char *path;

    path = (char *) malloc(strlen(dir) + strlen(name) + 2);
    if (path == NULL) {
        return NULL;
    }
    return strcat(strcat(strcpy(path, dir), "/"), name);
}

/*
 * Scans the specified directory and its subdirectories to find a
112
 * zoneinfo file which has the same content as /etc/localtime on Linux
113 114 115
 * or /usr/share/lib/zoneinfo/localtime on Solaris given in 'buf'.
 * If file is symbolic link, then the contents it points to are in buf.
 * Returns a zone ID if found, otherwise, NULL is returned.
D
duke 已提交
116 117 118 119 120
 */
static char *
findZoneinfoFile(char *buf, size_t size, const char *dir)
{
    DIR *dirp = NULL;
S
simonis 已提交
121 122
    struct dirent64 *dp = NULL;
    struct dirent64 *entry = NULL;
D
duke 已提交
123 124 125
    char *pathname = NULL;
    char *tz = NULL;

126 127
    if (strcmp(dir, ZONEINFO_DIR) == 0) {
        /* fast path for 1st iteration */
128 129
        unsigned int i;
        for (i = 0; i < sizeof (popularZones) / sizeof (popularZones[0]); i++) {
130 131 132 133 134 135 136 137 138 139 140 141 142
            pathname = getPathName(dir, popularZones[i]);
            if (pathname == NULL) {
                continue;
            }
            tz = isFileIdentical(buf, size, pathname);
            free((void *) pathname);
            pathname = NULL;
            if (tz != NULL) {
                return tz;
            }
        }
    }

143 144 145 146 147 148 149 150 151 152 153
    dirp = opendir(dir);
    if (dirp == NULL) {
        return NULL;
    }

    entry = (struct dirent64 *) malloc((size_t) pathconf(dir, _PC_NAME_MAX));
    if (entry == NULL) {
        (void) closedir(dirp);
        return NULL;
    }

S
simonis 已提交
154
    while (readdir64_r(dirp, entry, &dp) == 0 && dp != NULL) {
D
duke 已提交
155 156 157 158 159 160 161 162
        /*
         * Skip '.' and '..' (and possibly other .* files)
         */
        if (dp->d_name[0] == '.') {
            continue;
        }

        /*
163
         * Skip "ROC", "posixrules", and "localtime".
D
duke 已提交
164 165 166
         */
        if ((strcmp(dp->d_name, "ROC") == 0)
            || (strcmp(dp->d_name, "posixrules") == 0)
S
simonis 已提交
167
#if defined(__solaris__)
168 169 170 171 172 173
            /*
             * Skip the "src" and "tab" directories on Solaris.
             */
            || (strcmp(dp->d_name, "src") == 0)
            || (strcmp(dp->d_name, "tab") == 0)
#endif
D
duke 已提交
174 175 176 177 178 179 180 181 182
            || (strcmp(dp->d_name, "localtime") == 0)) {
            continue;
        }

        pathname = getPathName(dir, dp->d_name);
        if (pathname == NULL) {
            break;
        }

183 184
        tz = isFileIdentical(buf, size, pathname);

D
duke 已提交
185 186
        free((void *) pathname);
        pathname = NULL;
187 188 189
        if (tz != NULL) {
            break;
        }
D
duke 已提交
190 191
    }

192 193 194
    if (entry != NULL) {
        free((void *) entry);
    }
D
duke 已提交
195 196 197
    if (dirp != NULL) {
        (void) closedir(dirp);
    }
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    return tz;
}

/*
 * Checks if the file pointed to by pathname matches
 * the data contents in buf.
 * Returns a representation of the timezone file name
 * if file match is found, otherwise NULL.
 */
static char *
isFileIdentical(char *buf, size_t size, char *pathname)
{
    char *possibleMatch = NULL;
    struct stat statbuf;
    char *dbuf = NULL;
    int fd = -1;
    int res;

    if (stat(pathname, &statbuf) == -1) {
        return NULL;
D
duke 已提交
218
    }
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239

    if (S_ISDIR(statbuf.st_mode)) {
        possibleMatch  = findZoneinfoFile(buf, size, pathname);
    } else if (S_ISREG(statbuf.st_mode) && (size_t)statbuf.st_size == size) {
        dbuf = (char *) malloc(size);
        if (dbuf == NULL) {
            return NULL;
        }
        if ((fd = open(pathname, O_RDONLY)) == -1) {
            goto freedata;
        }
        if (read(fd, dbuf, size) != (ssize_t) size) {
            goto freedata;
        }
        if (memcmp(buf, dbuf, size) == 0) {
            possibleMatch = getZoneName(pathname);
            if (possibleMatch != NULL) {
                possibleMatch = strdup(possibleMatch);
            }
        }
        freedata:
D
duke 已提交
240
        free((void *) dbuf);
241 242
        dbuf = NULL;
        (void) close(fd);
D
duke 已提交
243
    }
244
    return possibleMatch;
D
duke 已提交
245 246
}

247
#if defined(__linux__) || defined(MACOSX)
248

D
duke 已提交
249
/*
250
 * Performs Linux specific mapping and returns a zone ID
D
duke 已提交
251 252 253 254 255 256 257 258 259 260 261 262
 * if found. Otherwise, NULL is returned.
 */
static char *
getPlatformTimeZoneID()
{
    struct stat statbuf;
    char *tz = NULL;
    FILE *fp;
    int fd;
    char *buf;
    size_t size;

S
simonis 已提交
263
#if defined(__linux__)
D
duke 已提交
264
    /*
265 266 267 268
     * Try reading the /etc/timezone file for Debian distros. There's
     * no spec of the file format available. This parsing assumes that
     * there's one line of an Olson tzid followed by a '\n', no
     * leading or trailing spaces, no comments.
D
duke 已提交
269
     */
270
    if ((fp = fopen(ETC_TIMEZONE_FILE, "r")) != NULL) {
D
duke 已提交
271 272
        char line[256];

273 274 275 276
        if (fgets(line, sizeof(line), fp) != NULL) {
            char *p = strchr(line, '\n');
            if (p != NULL) {
                *p = '\0';
D
duke 已提交
277
            }
278 279
            if (strlen(line) > 0) {
                tz = strdup(line);
D
duke 已提交
280 281 282 283 284 285 286
            }
        }
        (void) fclose(fp);
        if (tz != NULL) {
            return tz;
        }
    }
S
simonis 已提交
287
#endif /* defined(__linux__) */
D
duke 已提交
288 289 290 291

    /*
     * Next, try /etc/localtime to find the zone ID.
     */
292
    if (lstat(DEFAULT_ZONEINFO_FILE, &statbuf) == -1) {
D
duke 已提交
293 294 295 296 297 298 299 300 301 302 303 304 305 306
        return NULL;
    }

    /*
     * If it's a symlink, get the link name and its zone ID part. (The
     * older versions of timeconfig created a symlink as described in
     * the Red Hat man page. It was changed in 1999 to create a copy
     * of a zoneinfo file. It's no longer possible to get the zone ID
     * from /etc/localtime.)
     */
    if (S_ISLNK(statbuf.st_mode)) {
        char linkbuf[PATH_MAX+1];
        int len;

307
        if ((len = readlink(DEFAULT_ZONEINFO_FILE, linkbuf, sizeof(linkbuf)-1)) == -1) {
D
duke 已提交
308
            jio_fprintf(stderr, (const char *) "can't get a symlink of %s\n",
309
                        DEFAULT_ZONEINFO_FILE);
D
duke 已提交
310 311 312 313 314 315
            return NULL;
        }
        linkbuf[len] = '\0';
        tz = getZoneName(linkbuf);
        if (tz != NULL) {
            tz = strdup(tz);
316
            return tz;
D
duke 已提交
317 318 319 320 321 322
        }
    }

    /*
     * If it's a regular file, we need to find out the same zoneinfo file
     * that has been copied as /etc/localtime.
323 324
     * If initial symbolic link resolution failed, we should treat target
     * file as a regular file.
D
duke 已提交
325
     */
326 327 328 329 330 331 332
    if ((fd = open(DEFAULT_ZONEINFO_FILE, O_RDONLY)) == -1) {
        return NULL;
    }
    if (fstat(fd, &statbuf) == -1) {
        (void) close(fd);
        return NULL;
    }
D
duke 已提交
333 334 335
    size = (size_t) statbuf.st_size;
    buf = (char *) malloc(size);
    if (buf == NULL) {
336
        (void) close(fd);
D
duke 已提交
337 338 339 340 341 342 343 344 345 346
        return NULL;
    }

    if (read(fd, buf, size) != (ssize_t) size) {
        (void) close(fd);
        free((void *) buf);
        return NULL;
    }
    (void) close(fd);

347
    tz = findZoneinfoFile(buf, size, ZONEINFO_DIR);
D
duke 已提交
348 349 350
    free((void *) buf);
    return tz;
}
S
simonis 已提交
351 352 353

#elif defined(__solaris__)

D
duke 已提交
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
#if !defined(__sparcv9) && !defined(amd64)

/*
 * Those file* functions mimic the UNIX stream io functions. This is
 * because of the limitation of the number of open files on Solaris
 * (32-bit mode only) due to the System V ABI.
 */

#define BUFFER_SIZE     4096

static struct iobuffer {
    int     magic;      /* -1 to distinguish from the real FILE */
    int     fd;         /* file descriptor */
    char    *buffer;    /* pointer to buffer */
    char    *ptr;       /* current read pointer */
    char    *endptr;    /* end pointer */
};

static int
fileclose(FILE *stream)
{
    struct iobuffer *iop = (struct iobuffer *) stream;

    if (iop->magic != -1) {
        return fclose(stream);
    }

    if (iop == NULL) {
        return 0;
    }
    close(iop->fd);
    free((void *)iop->buffer);
    free((void *)iop);
    return 0;
}

static FILE *
fileopen(const char *fname, const char *fmode)
{
    FILE *fp;
    int fd;
    struct iobuffer *iop;

    if ((fp = fopen(fname, fmode)) != NULL) {
        return fp;
    }

    /*
     * It assumes read open.
     */
    if ((fd = open(fname, O_RDONLY)) == -1) {
        return NULL;
    }

    /*
     * Allocate struct iobuffer and its buffer
     */
    iop = malloc(sizeof(struct iobuffer));
    if (iop == NULL) {
        (void) close(fd);
        errno = ENOMEM;
        return NULL;
    }
    iop->magic = -1;
    iop->fd = fd;
    iop->buffer = malloc(BUFFER_SIZE);
    if (iop->buffer == NULL) {
        (void) close(fd);
        free((void *) iop);
        errno = ENOMEM;
        return NULL;
    }
    iop->ptr = iop->buffer;
    iop->endptr = iop->buffer;
    return (FILE *)iop;
}

/*
 * This implementation assumes that n is large enough and the line
 * separator is '\n'.
 */
static char *
filegets(char *s, int n, FILE *stream)
{
    struct iobuffer *iop = (struct iobuffer *) stream;
    char *p;

    if (iop->magic != -1) {
        return fgets(s, n, stream);
    }

    p = s;
    for (;;) {
        char c;

        if (iop->ptr == iop->endptr) {
            ssize_t len;

            if ((len = read(iop->fd, (void *)iop->buffer, BUFFER_SIZE)) == -1) {
                return NULL;
            }
            if (len == 0) {
                *p = 0;
                if (s == p) {
                    return NULL;
                }
                return s;
            }
            iop->ptr = iop->buffer;
            iop->endptr = iop->buffer + len;
        }
        c = *iop->ptr++;
        *p++ = c;
        if ((p - s) == (n - 1)) {
            *p = 0;
            return s;
        }
        if (c == '\n') {
            *p = 0;
            return s;
        }
    }
    /*NOTREACHED*/
}
S
simonis 已提交
478
#endif /* !defined(__sparcv9) && !defined(amd64) */
D
duke 已提交
479 480

/*
481 482 483
 * Performs Solaris dependent mapping. Returns a zone ID if
 * found. Otherwise, NULL is returned.  Solaris libc looks up
 * "/etc/default/init" to get the default TZ value if TZ is not defined
D
duke 已提交
484 485 486 487 488 489 490 491 492 493 494
 * as an environment variable.
 */
static char *
getPlatformTimeZoneID()
{
    char *tz = NULL;
    FILE *fp;

    /*
     * Try the TZ entry in /etc/default/init.
     */
495
    if ((fp = fileopen(SYS_INIT_FILE, "r")) != NULL) {
D
duke 已提交
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
        char line[256];
        char quote = '\0';

        while (filegets(line, sizeof(line), fp) != NULL) {
            char *p = line;
            char *s;
            char c;

            /* quick check for comment lines */
            if (*p == '#') {
                continue;
            }
            if (strncmp(p, "TZ=", 3) == 0) {
                p += 3;
                SKIP_SPACE(p);
                c = *p;
                if (c == '"' || c == '\'') {
                    quote = c;
                    p++;
                }

                /*
                 * PSARC/2001/383: quoted string support
                 */
                for (s = p; (c = *s) != '\0' && c != '\n'; s++) {
                    /* No '\\' is supported here. */
                    if (c == quote) {
                        quote = '\0';
                        break;
                    }
                    if (c == ' ' && quote == '\0') {
                        break;
                    }
                }
                if (quote != '\0') {
                    jio_fprintf(stderr, "ZoneInfo: unterminated time zone name in /etc/TIMEZONE\n");
                }
                *s = '\0';
                tz = strdup(p);
                break;
            }
        }
        (void) fileclose(fp);
    }
    return tz;
}

543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
#define TIMEZONE_FMRI   "svc:/system/timezone:default"
#define TIMEZONE_PG     "timezone"
#define LOCALTIME_PROP  "localtime"

static void
cleanupScf(scf_handle_t *h,
           scf_snapshot_t *snap,
           scf_instance_t *inst,
           scf_propertygroup_t *pg,
           scf_property_t *prop,
           scf_value_t *val,
           char *buf) {
    if (buf != NULL) {
        free(buf);
    }
    if (snap != NULL) {
        scf_snapshot_destroy(snap);
    }
    if (val != NULL) {
        scf_value_destroy(val);
    }
    if (prop != NULL) {
        scf_property_destroy(prop);
    }
    if (pg != NULL) {
        scf_pg_destroy(pg);
    }
    if (inst != NULL) {
        scf_instance_destroy(inst);
    }
    if (h != NULL) {
        scf_handle_destroy(h);
    }
}

/*
S
simonis 已提交
579
 * Returns a zone ID of Solaris when the TZ value is "localtime".
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
 * First, it tries scf. If scf fails, it looks for the same file as
 * /usr/share/lib/zoneinfo/localtime under /usr/share/lib/zoneinfo/.
 */
static char *
getSolarisDefaultZoneID() {
    char *tz = NULL;
    struct stat statbuf;
    size_t size;
    char *buf;
    int fd;
    /* scf specific variables */
    scf_handle_t *h = NULL;
    scf_snapshot_t *snap = NULL;
    scf_instance_t *inst = NULL;
    scf_propertygroup_t *pg = NULL;
    scf_property_t *prop = NULL;
    scf_value_t *val = NULL;

    if ((h = scf_handle_create(SCF_VERSION)) != NULL
        && scf_handle_bind(h) == 0
        && (inst = scf_instance_create(h)) != NULL
        && (snap = scf_snapshot_create(h)) != NULL
        && (pg = scf_pg_create(h)) != NULL
        && (prop = scf_property_create(h)) != NULL
        && (val = scf_value_create(h)) != NULL
        && scf_handle_decode_fmri(h, TIMEZONE_FMRI, NULL, NULL, inst,
                                  NULL, NULL, SCF_DECODE_FMRI_REQUIRE_INSTANCE) == 0
        && scf_instance_get_snapshot(inst, "running", snap) == 0
        && scf_instance_get_pg_composed(inst, snap, TIMEZONE_PG, pg) == 0
        && scf_pg_get_property(pg, LOCALTIME_PROP, prop) == 0
        && scf_property_get_value(prop, val) == 0) {
        ssize_t len;

        /* Gets the length of the zone ID string */
        len = scf_value_get_astring(val, NULL, 0);
        if (len != -1) {
            tz = malloc(++len); /* +1 for a null byte */
            if (tz != NULL && scf_value_get_astring(val, tz, len) != -1) {
                cleanupScf(h, snap, inst, pg, prop, val, NULL);
                return tz;
            }
        }
    }
    cleanupScf(h, snap, inst, pg, prop, val, tz);

    if (stat(DEFAULT_ZONEINFO_FILE, &statbuf) == -1) {
        return NULL;
    }
    size = (size_t) statbuf.st_size;
    buf = malloc(size);
    if (buf == NULL) {
        return NULL;
    }
    if ((fd = open(DEFAULT_ZONEINFO_FILE, O_RDONLY)) == -1) {
        free((void *) buf);
        return NULL;
    }

    if (read(fd, buf, size) != (ssize_t) size) {
        (void) close(fd);
        free((void *) buf);
        return NULL;
    }
    (void) close(fd);
    tz = findZoneinfoFile(buf, size, ZONEINFO_DIR);
    free((void *) buf);
    return tz;
}
D
duke 已提交
648

S
simonis 已提交
649 650 651 652
#endif /* defined(__solaris__) */

#elif defined(_AIX)

653 654 655
static char *
getPlatformTimeZoneID()
{
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
    FILE *fp;
    char *tz = NULL;
    char *tz_key = "TZ=";
    char line[256];
    size_t tz_key_len = strlen(tz_key);

    if ((fp = fopen(ETC_ENVIRONMENT_FILE, "r")) != NULL) {
        while (fgets(line, sizeof(line), fp) != NULL) {
            char *p = strchr(line, '\n');
            if (p != NULL) {
                *p = '\0';
            }
            if (0 == strncmp(line, tz_key, tz_key_len)) {
                tz = strdup(line + tz_key_len);
                break;
            }
        }
        (void) fclose(fp);
    }

    return tz;
677
}
S
simonis 已提交
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774

static char *
mapPlatformToJavaTimezone(const char *java_home_dir, const char *tz) {
    FILE *tzmapf;
    char mapfilename[PATH_MAX + 1];
    char line[256];
    int linecount = 0;
    char *tz_buf = NULL;
    char *temp_tz = NULL;
    char *javatz = NULL;
    size_t tz_len = 0;

    /* On AIX, the TZ environment variable may end with a comma
     * followed by modifier fields. These are ignored here. */
    temp_tz = strchr(tz, ',');
    tz_len = (temp_tz == NULL) ? strlen(tz) : temp_tz - tz;
    tz_buf = (char *)malloc(tz_len + 1);
    memcpy(tz_buf, tz, tz_len);
    tz_buf[tz_len] = 0;

    /* Open tzmappings file, with buffer overrun check */
    if ((strlen(java_home_dir) + 15) > PATH_MAX) {
        jio_fprintf(stderr, "Path %s/lib/tzmappings exceeds maximum path length\n", java_home_dir);
        goto tzerr;
    }
    strcpy(mapfilename, java_home_dir);
    strcat(mapfilename, "/lib/tzmappings");
    if ((tzmapf = fopen(mapfilename, "r")) == NULL) {
        jio_fprintf(stderr, "can't open %s\n", mapfilename);
        goto tzerr;
    }

    while (fgets(line, sizeof(line), tzmapf) != NULL) {
        char *p = line;
        char *sol = line;
        char *java;
        int result;

        linecount++;
        /*
         * Skip comments and blank lines
         */
        if (*p == '#' || *p == '\n') {
            continue;
        }

        /*
         * Get the first field, platform zone ID
         */
        while (*p != '\0' && *p != '\t') {
            p++;
        }
        if (*p == '\0') {
            /* mapping table is broken! */
            jio_fprintf(stderr, "tzmappings: Illegal format at near line %d.\n", linecount);
            break;
        }

        *p++ = '\0';
        if ((result = strncmp(tz_buf, sol, tz_len)) == 0) {
            /*
             * If this is the current platform zone ID,
             * take the Java time zone ID (2nd field).
             */
            java = p;
            while (*p != '\0' && *p != '\n') {
                p++;
            }

            if (*p == '\0') {
                /* mapping table is broken! */
                jio_fprintf(stderr, "tzmappings: Illegal format at line %d.\n", linecount);
                break;
            }

            *p = '\0';
            javatz = strdup(java);
            break;
        } else if (result < 0) {
            break;
        }
    }
    (void) fclose(tzmapf);

tzerr:
    if (tz_buf != NULL ) {
        free((void *) tz_buf);
    }

    if (javatz == NULL) {
        return getGMTOffsetID();
    }

    return javatz;
}

#endif /* defined(_AIX) */
775

D
duke 已提交
776 777 778 779 780
/*
 * findJavaTZ_md() maps platform time zone ID to Java time zone ID
 * using <java_home>/lib/tzmappings. If the TZ value is not found, it
 * trys some libc implementation dependent mappings. If it still
 * can't map to a Java time zone ID, it falls back to the GMT+/-hh:mm
781
 * form.
D
duke 已提交
782 783 784
 */
/*ARGSUSED1*/
char *
785
findJavaTZ_md(const char *java_home_dir)
D
duke 已提交
786 787 788 789 790 791 792 793 794 795 796 797 798
{
    char *tz;
    char *javatz = NULL;
    char *freetz = NULL;

    tz = getenv("TZ");

    if (tz == NULL || *tz == '\0') {
        tz = getPlatformTimeZoneID();
        freetz = tz;
    }

    if (tz != NULL) {
S
simonis 已提交
799 800 801 802 803 804
        /* Ignore preceding ':' */
        if (*tz == ':') {
            tz++;
        }
#if defined(__linux__)
        /* Ignore "posix/" prefix on Linux. */
D
duke 已提交
805 806 807 808
        if (strncmp(tz, "posix/", 6) == 0) {
            tz += 6;
        }
#endif
S
simonis 已提交
809 810 811 812

#if defined(_AIX)
        /* On AIX do the platform to Java mapping. */
        javatz = mapPlatformToJavaTimezone(java_home_dir, tz);
D
duke 已提交
813 814 815
        if (freetz != NULL) {
            free((void *) freetz);
        }
S
simonis 已提交
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
#else
#if defined(__solaris__)
        /* Solaris might use localtime, so handle it here. */
        if (strcmp(tz, "localtime") == 0) {
            javatz = getSolarisDefaultZoneID();
            if (freetz != NULL) {
                free((void *) freetz);
            }
        } else
#endif
        if (freetz == NULL) {
            /* strdup if we are still working on getenv result. */
            javatz = strdup(tz);
        } else if (freetz != tz) {
            /* strdup and free the old buffer, if we moved the pointer. */
            javatz = strdup(tz);
            free((void *) freetz);
        } else {
            /* we are good if we already work on a freshly allocated buffer. */
            javatz = tz;
836 837
        }
#endif
D
duke 已提交
838
    }
839

D
duke 已提交
840 841
    return javatz;
}
842

D
duke 已提交
843
/**
844
 * Returns a GMT-offset-based zone ID. (e.g., "GMT-08:00")
D
duke 已提交
845
 */
846

S
simonis 已提交
847
#if defined(MACOSX)
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862

char *
getGMTOffsetID()
{
    time_t offset;
    char sign, buf[32];
    struct tm *local_tm;
    time_t clock;
    time_t currenttime;

    clock = time(NULL);
    tzset();
    local_tm = localtime(&clock);
    if (local_tm->tm_gmtoff >= 0) {
        offset = (time_t) local_tm->tm_gmtoff;
S
simonis 已提交
863
        sign = '+';
864 865
    } else {
        offset = (time_t) -local_tm->tm_gmtoff;
S
simonis 已提交
866
        sign = '-';
867 868 869 870 871
    }
    sprintf(buf, (const char *)"GMT%c%02d:%02d",
            sign, (int)(offset/3600), (int)((offset%3600)/60));
    return strdup(buf);
}
S
simonis 已提交
872

873 874
#else

D
duke 已提交
875 876 877 878
char *
getGMTOffsetID()
{
    time_t offset;
879
    char sign, buf[32];
S
simonis 已提交
880
#if defined(__solaris__)
881 882 883 884 885 886 887 888 889 890 891
    struct tm localtm;
    time_t currenttime;

    currenttime = time(NULL);
    if (localtime_r(&currenttime, &localtm) == NULL) {
        return NULL;
    }

    offset = localtm.tm_isdst ? altzone : timezone;
#else
    offset = timezone;
S
simonis 已提交
892
#endif
D
duke 已提交
893

894
    if (offset == 0) {
D
duke 已提交
895 896 897 898
        return strdup("GMT");
    }

    /* Note that the time offset direction is opposite. */
899
    if (offset > 0) {
D
duke 已提交
900 901
        sign = '-';
    } else {
902
        offset = -offset;
D
duke 已提交
903 904 905 906 907 908
        sign = '+';
    }
    sprintf(buf, (const char *)"GMT%c%02d:%02d",
            sign, (int)(offset/3600), (int)((offset%3600)/60));
    return strdup(buf);
}
909
#endif /* MACOSX */