1 /*
   2  * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 #include <stdlib.h>
  27 #include <stdio.h>
  28 #include <strings.h>
  29 #include <time.h>
  30 #include <limits.h>
  31 #include <errno.h>
  32 #include <stddef.h>
  33 #include <sys/stat.h>
  34 #include <sys/types.h>
  35 #include <string.h>
  36 #include <dirent.h>
  37 #include <unistd.h>
  38 #ifdef __solaris__
  39 #include <libscf.h>
  40 #endif
  41 
  42 #include "jvm.h"
  43 
  44 #define SKIP_SPACE(p)   while (*p == ' ' || *p == '\t') p++;
  45 
  46 #if !defined(__solaris__) || defined(__sparcv9) || defined(amd64)
  47 #define fileopen        fopen
  48 #define filegets        fgets
  49 #define fileclose       fclose
  50 #endif
  51 
  52 #if defined(__linux__) || defined(_ALLBSD_SOURCE)
  53 
  54 
  55 static const char *ETC_TIMEZONE_FILE = "/etc/timezone";
  56 static const char *ZONEINFO_DIR = "/usr/share/zoneinfo";
  57 static const char *DEFAULT_ZONEINFO_FILE = "/etc/localtime";
  58 #else
  59 static const char *SYS_INIT_FILE = "/etc/default/init";
  60 static const char *ZONEINFO_DIR = "/usr/share/lib/zoneinfo";
  61 static const char *DEFAULT_ZONEINFO_FILE = "/usr/share/lib/zoneinfo/localtime";
  62 #endif /*__linux__*/
  63 
  64 /*
  65  * Returns a pointer to the zone ID portion of the given zoneinfo file
  66  * name, or NULL if the given string doesn't contain "zoneinfo/".
  67  */
  68 static char *
  69 getZoneName(char *str)
  70 {
  71     static const char *zidir = "zoneinfo/";
  72 
  73     char *pos = strstr((const char *)str, zidir);
  74     if (pos == NULL) {
  75         return NULL;
  76     }
  77     return pos + strlen(zidir);
  78 }
  79 
  80 /*
  81  * Returns a path name created from the given 'dir' and 'name' under
  82  * UNIX. This function allocates memory for the pathname calling
  83  * malloc(). NULL is returned if malloc() fails.
  84  */
  85 static char *
  86 getPathName(const char *dir, const char *name) {
  87     char *path;
  88 
  89     path = (char *) malloc(strlen(dir) + strlen(name) + 2);
  90     if (path == NULL) {
  91         return NULL;
  92     }
  93     return strcat(strcat(strcpy(path, dir), "/"), name);
  94 }
  95 
  96 /*
  97  * Scans the specified directory and its subdirectories to find a
  98  * zoneinfo file which has the same content as /etc/localtime on Linux
  99  * or /usr/share/lib/zoneinfo/localtime on Solaris given in 'buf'.
 100  * If file is symbolic link, then the contents it points to are in buf.
 101  * Returns a zone ID if found, otherwise, NULL is returned.
 102  */
 103 static char *
 104 findZoneinfoFile(char *buf, size_t size, const char *dir)
 105 {
 106     DIR *dirp = NULL;
 107     struct stat statbuf;
 108     struct dirent *dp = NULL;
 109     struct dirent *entry = NULL;
 110     char *pathname = NULL;
 111     int fd = -1;
 112     char *dbuf = NULL;
 113     char *tz = NULL;
 114 
 115     dirp = opendir(dir);
 116     if (dirp == NULL) {
 117         return NULL;
 118     }
 119 
 120     entry = (struct dirent *) malloc((size_t) pathconf(dir, _PC_NAME_MAX));
 121     if (entry == NULL) {
 122         (void) closedir(dirp);
 123         return NULL;
 124     }
 125 
 126 #if defined(__linux__) || defined(MACOSX) || (defined(__solaris__) \
 127     && (defined(_POSIX_PTHREAD_SEMANTICS) || defined(_LP64)))
 128     while (readdir_r(dirp, entry, &dp) == 0 && dp != NULL) {
 129 #else
 130     while ((dp = readdir_r(dirp, entry)) != NULL) {
 131 #endif
 132 
 133         /*
 134          * Skip '.' and '..' (and possibly other .* files)
 135          */
 136         if (dp->d_name[0] == '.') {
 137             continue;
 138         }
 139 
 140         /*
 141          * Skip "ROC", "posixrules", and "localtime".
 142          */
 143         if ((strcmp(dp->d_name, "ROC") == 0)
 144             || (strcmp(dp->d_name, "posixrules") == 0)
 145 #ifdef __solaris__
 146             /*
 147              * Skip the "src" and "tab" directories on Solaris.
 148              */
 149             || (strcmp(dp->d_name, "src") == 0)
 150             || (strcmp(dp->d_name, "tab") == 0)
 151 #endif
 152             || (strcmp(dp->d_name, "localtime") == 0)) {
 153             continue;
 154         }
 155 
 156         pathname = getPathName(dir, dp->d_name);
 157         if (pathname == NULL) {
 158             break;
 159         }
 160         if (stat(pathname, &statbuf) == -1) {
 161             break;
 162         }
 163 
 164         if (S_ISDIR(statbuf.st_mode)) {
 165             tz = findZoneinfoFile(buf, size, pathname);
 166             if (tz != NULL) {
 167                 break;
 168             }
 169         } else if (S_ISREG(statbuf.st_mode) && (size_t)statbuf.st_size == size) {
 170             dbuf = (char *) malloc(size);
 171             if (dbuf == NULL) {
 172                 break;
 173             }
 174             if ((fd = open(pathname, O_RDONLY)) == -1) {
 175                 break;
 176             }
 177             if (read(fd, dbuf, size) != (ssize_t) size) {
 178                 break;
 179             }
 180             if (memcmp(buf, dbuf, size) == 0) {
 181                 tz = getZoneName(pathname);
 182                 if (tz != NULL) {
 183                     tz = strdup(tz);
 184                 }
 185                 break;
 186             }
 187             free((void *) dbuf);
 188             dbuf = NULL;
 189             (void) close(fd);
 190             fd = -1;
 191         }
 192         free((void *) pathname);
 193         pathname = NULL;
 194     }
 195 
 196     if (entry != NULL) {
 197         free((void *) entry);
 198     }
 199     if (dirp != NULL) {
 200         (void) closedir(dirp);
 201     }
 202     if (pathname != NULL) {
 203         free((void *) pathname);
 204     }
 205     if (fd != -1) {
 206         (void) close(fd);
 207     }
 208     if (dbuf != NULL) {
 209         free((void *) dbuf);
 210     }
 211     return tz;
 212 }
 213 
 214 #if defined(__linux__) || defined(MACOSX)
 215 
 216 /*
 217  * Performs Linux specific mapping and returns a zone ID
 218  * if found. Otherwise, NULL is returned.
 219  */
 220 static char *
 221 getPlatformTimeZoneID()
 222 {
 223     struct stat statbuf;
 224     char *tz = NULL;
 225     FILE *fp;
 226     int fd;
 227     char *buf;
 228     size_t size;
 229 
 230 #ifdef __linux__
 231     /*
 232      * Try reading the /etc/timezone file for Debian distros. There's
 233      * no spec of the file format available. This parsing assumes that
 234      * there's one line of an Olson tzid followed by a '\n', no
 235      * leading or trailing spaces, no comments.
 236      */
 237     if ((fp = fopen(ETC_TIMEZONE_FILE, "r")) != NULL) {
 238         char line[256];
 239 
 240         if (fgets(line, sizeof(line), fp) != NULL) {
 241             char *p = strchr(line, '\n');
 242             if (p != NULL) {
 243                 *p = '\0';
 244             }
 245             if (strlen(line) > 0) {
 246                 tz = strdup(line);
 247             }
 248         }
 249         (void) fclose(fp);
 250         if (tz != NULL) {
 251             return tz;
 252         }
 253     }
 254 #endif /* __linux__ */
 255 
 256     /*
 257      * Next, try /etc/localtime to find the zone ID.
 258      */
 259     if (lstat(DEFAULT_ZONEINFO_FILE, &statbuf) == -1) {
 260         return NULL;
 261     }
 262 
 263     /*
 264      * If it's a symlink, get the link name and its zone ID part. (The
 265      * older versions of timeconfig created a symlink as described in
 266      * the Red Hat man page. It was changed in 1999 to create a copy
 267      * of a zoneinfo file. It's no longer possible to get the zone ID
 268      * from /etc/localtime.)
 269      */
 270     if (S_ISLNK(statbuf.st_mode)) {
 271         char linkbuf[PATH_MAX+1];
 272         int len;
 273 
 274         if ((len = readlink(DEFAULT_ZONEINFO_FILE, linkbuf, sizeof(linkbuf)-1)) == -1) {
 275             jio_fprintf(stderr, (const char *) "can't get a symlink of %s\n",
 276                         DEFAULT_ZONEINFO_FILE);
 277             return NULL;
 278         }
 279         linkbuf[len] = '\0';
 280         tz = getZoneName(linkbuf);
 281         if (tz != NULL) {
 282             tz = strdup(tz);
 283             return tz;
 284         }
 285     }
 286 
 287     /*
 288      * If it's a regular file, we need to find out the same zoneinfo file
 289      * that has been copied as /etc/localtime.
 290      * If initial symbolic link resolution failed, we should treat target 
 291      * file as a regular file.
 292      */
 293     if ((fd = open(DEFAULT_ZONEINFO_FILE, O_RDONLY)) == -1) {
 294         return NULL;
 295     }
 296     if (fstat(fd, &statbuf) == -1) {
 297         return NULL;
 298     }
 299     size = (size_t) statbuf.st_size;
 300     buf = (char *) malloc(size);
 301     if (buf == NULL) {
 302         return NULL;
 303     }
 304 
 305     if (read(fd, buf, size) != (ssize_t) size) {
 306         (void) close(fd);
 307         free((void *) buf);
 308         return NULL;
 309     }
 310     (void) close(fd);
 311 
 312     tz = findZoneinfoFile(buf, size, ZONEINFO_DIR);
 313     free((void *) buf);
 314     return tz;
 315 }
 316 #else
 317 #ifdef __solaris__
 318 #if !defined(__sparcv9) && !defined(amd64)
 319 
 320 /*
 321  * Those file* functions mimic the UNIX stream io functions. This is
 322  * because of the limitation of the number of open files on Solaris
 323  * (32-bit mode only) due to the System V ABI.
 324  */
 325 
 326 #define BUFFER_SIZE     4096
 327 
 328 static struct iobuffer {
 329     int     magic;      /* -1 to distinguish from the real FILE */
 330     int     fd;         /* file descriptor */
 331     char    *buffer;    /* pointer to buffer */
 332     char    *ptr;       /* current read pointer */
 333     char    *endptr;    /* end pointer */
 334 };
 335 
 336 static int
 337 fileclose(FILE *stream)
 338 {
 339     struct iobuffer *iop = (struct iobuffer *) stream;
 340 
 341     if (iop->magic != -1) {
 342         return fclose(stream);
 343     }
 344 
 345     if (iop == NULL) {
 346         return 0;
 347     }
 348     close(iop->fd);
 349     free((void *)iop->buffer);
 350     free((void *)iop);
 351     return 0;
 352 }
 353 
 354 static FILE *
 355 fileopen(const char *fname, const char *fmode)
 356 {
 357     FILE *fp;
 358     int fd;
 359     struct iobuffer *iop;
 360 
 361     if ((fp = fopen(fname, fmode)) != NULL) {
 362         return fp;
 363     }
 364 
 365     /*
 366      * It assumes read open.
 367      */
 368     if ((fd = open(fname, O_RDONLY)) == -1) {
 369         return NULL;
 370     }
 371 
 372     /*
 373      * Allocate struct iobuffer and its buffer
 374      */
 375     iop = malloc(sizeof(struct iobuffer));
 376     if (iop == NULL) {
 377         (void) close(fd);
 378         errno = ENOMEM;
 379         return NULL;
 380     }
 381     iop->magic = -1;
 382     iop->fd = fd;
 383     iop->buffer = malloc(BUFFER_SIZE);
 384     if (iop->buffer == NULL) {
 385         (void) close(fd);
 386         free((void *) iop);
 387         errno = ENOMEM;
 388         return NULL;
 389     }
 390     iop->ptr = iop->buffer;
 391     iop->endptr = iop->buffer;
 392     return (FILE *)iop;
 393 }
 394 
 395 /*
 396  * This implementation assumes that n is large enough and the line
 397  * separator is '\n'.
 398  */
 399 static char *
 400 filegets(char *s, int n, FILE *stream)
 401 {
 402     struct iobuffer *iop = (struct iobuffer *) stream;
 403     char *p;
 404 
 405     if (iop->magic != -1) {
 406         return fgets(s, n, stream);
 407     }
 408 
 409     p = s;
 410     for (;;) {
 411         char c;
 412 
 413         if (iop->ptr == iop->endptr) {
 414             ssize_t len;
 415 
 416             if ((len = read(iop->fd, (void *)iop->buffer, BUFFER_SIZE)) == -1) {
 417                 return NULL;
 418             }
 419             if (len == 0) {
 420                 *p = 0;
 421                 if (s == p) {
 422                     return NULL;
 423                 }
 424                 return s;
 425             }
 426             iop->ptr = iop->buffer;
 427             iop->endptr = iop->buffer + len;
 428         }
 429         c = *iop->ptr++;
 430         *p++ = c;
 431         if ((p - s) == (n - 1)) {
 432             *p = 0;
 433             return s;
 434         }
 435         if (c == '\n') {
 436             *p = 0;
 437             return s;
 438         }
 439     }
 440     /*NOTREACHED*/
 441 }
 442 #endif /* not __sparcv9 */
 443 
 444 
 445 /*
 446  * Performs Solaris dependent mapping. Returns a zone ID if
 447  * found. Otherwise, NULL is returned.  Solaris libc looks up
 448  * "/etc/default/init" to get the default TZ value if TZ is not defined
 449  * as an environment variable.
 450  */
 451 static char *
 452 getPlatformTimeZoneID()
 453 {
 454     char *tz = NULL;
 455     FILE *fp;
 456 
 457     /*
 458      * Try the TZ entry in /etc/default/init.
 459      */
 460     if ((fp = fileopen(SYS_INIT_FILE, "r")) != NULL) {
 461         char line[256];
 462         char quote = '\0';
 463 
 464         while (filegets(line, sizeof(line), fp) != NULL) {
 465             char *p = line;
 466             char *s;
 467             char c;
 468 
 469             /* quick check for comment lines */
 470             if (*p == '#') {
 471                 continue;
 472             }
 473             if (strncmp(p, "TZ=", 3) == 0) {
 474                 p += 3;
 475                 SKIP_SPACE(p);
 476                 c = *p;
 477                 if (c == '"' || c == '\'') {
 478                     quote = c;
 479                     p++;
 480                 }
 481 
 482                 /*
 483                  * PSARC/2001/383: quoted string support
 484                  */
 485                 for (s = p; (c = *s) != '\0' && c != '\n'; s++) {
 486                     /* No '\\' is supported here. */
 487                     if (c == quote) {
 488                         quote = '\0';
 489                         break;
 490                     }
 491                     if (c == ' ' && quote == '\0') {
 492                         break;
 493                     }
 494                 }
 495                 if (quote != '\0') {
 496                     jio_fprintf(stderr, "ZoneInfo: unterminated time zone name in /etc/TIMEZONE\n");
 497                 }
 498                 *s = '\0';
 499                 tz = strdup(p);
 500                 break;
 501             }
 502         }
 503         (void) fileclose(fp);
 504     }
 505     return tz;
 506 }
 507 
 508 #define TIMEZONE_FMRI   "svc:/system/timezone:default"
 509 #define TIMEZONE_PG     "timezone"
 510 #define LOCALTIME_PROP  "localtime"
 511 
 512 static void
 513 cleanupScf(scf_handle_t *h,
 514            scf_snapshot_t *snap,
 515            scf_instance_t *inst,
 516            scf_propertygroup_t *pg,
 517            scf_property_t *prop,
 518            scf_value_t *val,
 519            char *buf) {
 520     if (buf != NULL) {
 521         free(buf);
 522     }
 523     if (snap != NULL) {
 524         scf_snapshot_destroy(snap);
 525     }
 526     if (val != NULL) {
 527         scf_value_destroy(val);
 528     }
 529     if (prop != NULL) {
 530         scf_property_destroy(prop);
 531     }
 532     if (pg != NULL) {
 533         scf_pg_destroy(pg);
 534     }
 535     if (inst != NULL) {
 536         scf_instance_destroy(inst);
 537     }
 538     if (h != NULL) {
 539         scf_handle_destroy(h);
 540     }
 541 }
 542 
 543 /*
 544  * Retruns a zone ID of Solaris when the TZ value is "localtime".
 545  * First, it tries scf. If scf fails, it looks for the same file as
 546  * /usr/share/lib/zoneinfo/localtime under /usr/share/lib/zoneinfo/.
 547  */
 548 static char *
 549 getSolarisDefaultZoneID() {
 550     char *tz = NULL;
 551     struct stat statbuf;
 552     size_t size;
 553     char *buf;
 554     int fd;
 555     /* scf specific variables */
 556     scf_handle_t *h = NULL;
 557     scf_snapshot_t *snap = NULL;
 558     scf_instance_t *inst = NULL;
 559     scf_propertygroup_t *pg = NULL;
 560     scf_property_t *prop = NULL;
 561     scf_value_t *val = NULL;
 562 
 563     if ((h = scf_handle_create(SCF_VERSION)) != NULL
 564         && scf_handle_bind(h) == 0
 565         && (inst = scf_instance_create(h)) != NULL
 566         && (snap = scf_snapshot_create(h)) != NULL
 567         && (pg = scf_pg_create(h)) != NULL
 568         && (prop = scf_property_create(h)) != NULL
 569         && (val = scf_value_create(h)) != NULL
 570         && scf_handle_decode_fmri(h, TIMEZONE_FMRI, NULL, NULL, inst,
 571                                   NULL, NULL, SCF_DECODE_FMRI_REQUIRE_INSTANCE) == 0
 572         && scf_instance_get_snapshot(inst, "running", snap) == 0
 573         && scf_instance_get_pg_composed(inst, snap, TIMEZONE_PG, pg) == 0
 574         && scf_pg_get_property(pg, LOCALTIME_PROP, prop) == 0
 575         && scf_property_get_value(prop, val) == 0) {
 576         ssize_t len;
 577 
 578         /* Gets the length of the zone ID string */
 579         len = scf_value_get_astring(val, NULL, 0);
 580         if (len != -1) {
 581             tz = malloc(++len); /* +1 for a null byte */
 582             if (tz != NULL && scf_value_get_astring(val, tz, len) != -1) {
 583                 cleanupScf(h, snap, inst, pg, prop, val, NULL);
 584                 return tz;
 585             }
 586         }
 587     }
 588     cleanupScf(h, snap, inst, pg, prop, val, tz);
 589 
 590     if (stat(DEFAULT_ZONEINFO_FILE, &statbuf) == -1) {
 591         return NULL;
 592     }
 593     size = (size_t) statbuf.st_size;
 594     buf = malloc(size);
 595     if (buf == NULL) {
 596         return NULL;
 597     }
 598     if ((fd = open(DEFAULT_ZONEINFO_FILE, O_RDONLY)) == -1) {
 599         free((void *) buf);
 600         return NULL;
 601     }
 602 
 603     if (read(fd, buf, size) != (ssize_t) size) {
 604         (void) close(fd);
 605         free((void *) buf);
 606         return NULL;
 607     }
 608     (void) close(fd);
 609     tz = findZoneinfoFile(buf, size, ZONEINFO_DIR);
 610     free((void *) buf);
 611     return tz;
 612 }
 613 #endif /*__solaris__*/
 614 #endif /*__linux__*/
 615 
 616 /*
 617  * findJavaTZ_md() maps platform time zone ID to Java time zone ID
 618  * using <java_home>/lib/tzmappings. If the TZ value is not found, it
 619  * trys some libc implementation dependent mappings. If it still
 620  * can't map to a Java time zone ID, it falls back to the GMT+/-hh:mm
 621  * form. `country', which can be null, is not used for UNIX platforms.
 622  */
 623 /*ARGSUSED1*/
 624 char *
 625 findJavaTZ_md(const char *java_home_dir, const char *country)
 626 {
 627     char *tz;
 628     char *javatz = NULL;
 629     char *freetz = NULL;
 630 
 631     tz = getenv("TZ");
 632 
 633 #if defined(__linux__) || defined(_ALLBSD_SOURCE)
 634     if (tz == NULL) {
 635 #else
 636 #ifdef __solaris__
 637     if (tz == NULL || *tz == '\0') {
 638 #endif
 639 #endif
 640         tz = getPlatformTimeZoneID();
 641         freetz = tz;
 642     }
 643 
 644     /*
 645      * Remove any preceding ':'
 646      */
 647     if (tz != NULL && *tz == ':') {
 648         tz++;
 649     }
 650 
 651 #ifdef __solaris__
 652     if (strcmp(tz, "localtime") == 0) {
 653         tz = getSolarisDefaultZoneID();
 654         freetz = tz;
 655     }
 656 #endif
 657 
 658     if (tz != NULL) {
 659 #ifdef __linux__
 660         /*
 661          * Ignore "posix/" prefix.
 662          */
 663         if (strncmp(tz, "posix/", 6) == 0) {
 664             tz += 6;
 665         }
 666 #endif
 667         javatz = strdup(tz);
 668         if (freetz != NULL) {
 669             free((void *) freetz);
 670         }
 671     }
 672     return javatz;
 673 }
 674 /**
 675  * Returns a GMT-offset-based zone ID. (e.g., "GMT-08:00")
 676  */
 677 
 678 #ifdef MACOSX
 679 
 680 char *
 681 getGMTOffsetID()
 682 {
 683     time_t offset;
 684     char sign, buf[32];
 685     struct tm *local_tm;
 686     time_t clock;
 687     time_t currenttime;
 688 
 689     clock = time(NULL);
 690     tzset();
 691     local_tm = localtime(&clock);
 692     if (local_tm->tm_gmtoff >= 0) {
 693         offset = (time_t) local_tm->tm_gmtoff;
 694         sign = "+";
 695     } else {
 696         offset = (time_t) -local_tm->tm_gmtoff;
 697         sign = "-";
 698     }
 699     sprintf(buf, (const char *)"GMT%c%02d:%02d",
 700             sign, (int)(offset/3600), (int)((offset%3600)/60));
 701     return strdup(buf);
 702 }
 703 #else
 704 
 705 char *
 706 getGMTOffsetID()
 707 {
 708     time_t offset;
 709     char sign, buf[32];
 710 #ifdef __solaris__
 711     struct tm localtm;
 712     time_t currenttime;
 713 
 714     currenttime = time(NULL);
 715     if (localtime_r(&currenttime, &localtm) == NULL) {
 716         return NULL;
 717     }
 718 
 719     offset = localtm.tm_isdst ? altzone : timezone;
 720 #else
 721     offset = timezone;
 722 #endif /*__linux__*/
 723 
 724     if (offset == 0) {
 725         return strdup("GMT");
 726     }
 727 
 728     /* Note that the time offset direction is opposite. */
 729     if (offset > 0) {
 730         sign = '-';
 731     } else {
 732         offset = -offset;
 733         sign = '+';
 734     }
 735     sprintf(buf, (const char *)"GMT%c%02d:%02d",
 736             sign, (int)(offset/3600), (int)((offset%3600)/60));
 737     return strdup(buf);
 738 }
 739 #endif /* MACOSX */