1 /*
   2  * Copyright (c) 1999, 2011, 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 (most likely a symbolic link)
 100  * on Solaris given in 'buf'. Returns a zone ID if found, otherwise,
 101  * 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         }
 284         return tz;
 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      */
 291     size = (size_t) statbuf.st_size;
 292     buf = (char *) malloc(size);
 293     if (buf == NULL) {
 294         return NULL;
 295     }
 296     if ((fd = open(DEFAULT_ZONEINFO_FILE, O_RDONLY)) == -1) {
 297         free((void *) buf);
 298         return NULL;
 299     }
 300 
 301     if (read(fd, buf, size) != (ssize_t) size) {
 302         (void) close(fd);
 303         free((void *) buf);
 304         return NULL;
 305     }
 306     (void) close(fd);
 307 
 308     tz = findZoneinfoFile(buf, size, ZONEINFO_DIR);
 309     free((void *) buf);
 310     return tz;
 311 }
 312 #else
 313 #ifdef __solaris__
 314 #if !defined(__sparcv9) && !defined(amd64)
 315 
 316 /*
 317  * Those file* functions mimic the UNIX stream io functions. This is
 318  * because of the limitation of the number of open files on Solaris
 319  * (32-bit mode only) due to the System V ABI.
 320  */
 321 
 322 #define BUFFER_SIZE     4096
 323 
 324 static struct iobuffer {
 325     int     magic;      /* -1 to distinguish from the real FILE */
 326     int     fd;         /* file descriptor */
 327     char    *buffer;    /* pointer to buffer */
 328     char    *ptr;       /* current read pointer */
 329     char    *endptr;    /* end pointer */
 330 };
 331 
 332 static int
 333 fileclose(FILE *stream)
 334 {
 335     struct iobuffer *iop = (struct iobuffer *) stream;
 336 
 337     if (iop->magic != -1) {
 338         return fclose(stream);
 339     }
 340 
 341     if (iop == NULL) {
 342         return 0;
 343     }
 344     close(iop->fd);
 345     free((void *)iop->buffer);
 346     free((void *)iop);
 347     return 0;
 348 }
 349 
 350 static FILE *
 351 fileopen(const char *fname, const char *fmode)
 352 {
 353     FILE *fp;
 354     int fd;
 355     struct iobuffer *iop;
 356 
 357     if ((fp = fopen(fname, fmode)) != NULL) {
 358         return fp;
 359     }
 360 
 361     /*
 362      * It assumes read open.
 363      */
 364     if ((fd = open(fname, O_RDONLY)) == -1) {
 365         return NULL;
 366     }
 367 
 368     /*
 369      * Allocate struct iobuffer and its buffer
 370      */
 371     iop = malloc(sizeof(struct iobuffer));
 372     if (iop == NULL) {
 373         (void) close(fd);
 374         errno = ENOMEM;
 375         return NULL;
 376     }
 377     iop->magic = -1;
 378     iop->fd = fd;
 379     iop->buffer = malloc(BUFFER_SIZE);
 380     if (iop->buffer == NULL) {
 381         (void) close(fd);
 382         free((void *) iop);
 383         errno = ENOMEM;
 384         return NULL;
 385     }
 386     iop->ptr = iop->buffer;
 387     iop->endptr = iop->buffer;
 388     return (FILE *)iop;
 389 }
 390 
 391 /*
 392  * This implementation assumes that n is large enough and the line
 393  * separator is '\n'.
 394  */
 395 static char *
 396 filegets(char *s, int n, FILE *stream)
 397 {
 398     struct iobuffer *iop = (struct iobuffer *) stream;
 399     char *p;
 400 
 401     if (iop->magic != -1) {
 402         return fgets(s, n, stream);
 403     }
 404 
 405     p = s;
 406     for (;;) {
 407         char c;
 408 
 409         if (iop->ptr == iop->endptr) {
 410             ssize_t len;
 411 
 412             if ((len = read(iop->fd, (void *)iop->buffer, BUFFER_SIZE)) == -1) {
 413                 return NULL;
 414             }
 415             if (len == 0) {
 416                 *p = 0;
 417                 if (s == p) {
 418                     return NULL;
 419                 }
 420                 return s;
 421             }
 422             iop->ptr = iop->buffer;
 423             iop->endptr = iop->buffer + len;
 424         }
 425         c = *iop->ptr++;
 426         *p++ = c;
 427         if ((p - s) == (n - 1)) {
 428             *p = 0;
 429             return s;
 430         }
 431         if (c == '\n') {
 432             *p = 0;
 433             return s;
 434         }
 435     }
 436     /*NOTREACHED*/
 437 }
 438 #endif /* not __sparcv9 */
 439 
 440 
 441 /*
 442  * Performs Solaris dependent mapping. Returns a zone ID if
 443  * found. Otherwise, NULL is returned.  Solaris libc looks up
 444  * "/etc/default/init" to get the default TZ value if TZ is not defined
 445  * as an environment variable.
 446  */
 447 static char *
 448 getPlatformTimeZoneID()
 449 {
 450     char *tz = NULL;
 451     FILE *fp;
 452 
 453     /*
 454      * Try the TZ entry in /etc/default/init.
 455      */
 456     if ((fp = fileopen(SYS_INIT_FILE, "r")) != NULL) {
 457         char line[256];
 458         char quote = '\0';
 459 
 460         while (filegets(line, sizeof(line), fp) != NULL) {
 461             char *p = line;
 462             char *s;
 463             char c;
 464 
 465             /* quick check for comment lines */
 466             if (*p == '#') {
 467                 continue;
 468             }
 469             if (strncmp(p, "TZ=", 3) == 0) {
 470                 p += 3;
 471                 SKIP_SPACE(p);
 472                 c = *p;
 473                 if (c == '"' || c == '\'') {
 474                     quote = c;
 475                     p++;
 476                 }
 477 
 478                 /*
 479                  * PSARC/2001/383: quoted string support
 480                  */
 481                 for (s = p; (c = *s) != '\0' && c != '\n'; s++) {
 482                     /* No '\\' is supported here. */
 483                     if (c == quote) {
 484                         quote = '\0';
 485                         break;
 486                     }
 487                     if (c == ' ' && quote == '\0') {
 488                         break;
 489                     }
 490                 }
 491                 if (quote != '\0') {
 492                     jio_fprintf(stderr, "ZoneInfo: unterminated time zone name in /etc/TIMEZONE\n");
 493                 }
 494                 *s = '\0';
 495                 tz = strdup(p);
 496                 break;
 497             }
 498         }
 499         (void) fileclose(fp);
 500     }
 501     return tz;
 502 }
 503 
 504 #define TIMEZONE_FMRI   "svc:/system/timezone:default"
 505 #define TIMEZONE_PG     "timezone"
 506 #define LOCALTIME_PROP  "localtime"
 507 
 508 static void
 509 cleanupScf(scf_handle_t *h,
 510            scf_snapshot_t *snap,
 511            scf_instance_t *inst,
 512            scf_propertygroup_t *pg,
 513            scf_property_t *prop,
 514            scf_value_t *val,
 515            char *buf) {
 516     if (buf != NULL) {
 517         free(buf);
 518     }
 519     if (snap != NULL) {
 520         scf_snapshot_destroy(snap);
 521     }
 522     if (val != NULL) {
 523         scf_value_destroy(val);
 524     }
 525     if (prop != NULL) {
 526         scf_property_destroy(prop);
 527     }
 528     if (pg != NULL) {
 529         scf_pg_destroy(pg);
 530     }
 531     if (inst != NULL) {
 532         scf_instance_destroy(inst);
 533     }
 534     if (h != NULL) {
 535         scf_handle_destroy(h);
 536     }
 537 }
 538 
 539 /*
 540  * Retruns a zone ID of Solaris when the TZ value is "localtime".
 541  * First, it tries scf. If scf fails, it looks for the same file as
 542  * /usr/share/lib/zoneinfo/localtime under /usr/share/lib/zoneinfo/.
 543  */
 544 static char *
 545 getSolarisDefaultZoneID() {
 546     char *tz = NULL;
 547     struct stat statbuf;
 548     size_t size;
 549     char *buf;
 550     int fd;
 551     /* scf specific variables */
 552     scf_handle_t *h = NULL;
 553     scf_snapshot_t *snap = NULL;
 554     scf_instance_t *inst = NULL;
 555     scf_propertygroup_t *pg = NULL;
 556     scf_property_t *prop = NULL;
 557     scf_value_t *val = NULL;
 558 
 559     if ((h = scf_handle_create(SCF_VERSION)) != NULL
 560         && scf_handle_bind(h) == 0
 561         && (inst = scf_instance_create(h)) != NULL
 562         && (snap = scf_snapshot_create(h)) != NULL
 563         && (pg = scf_pg_create(h)) != NULL
 564         && (prop = scf_property_create(h)) != NULL
 565         && (val = scf_value_create(h)) != NULL
 566         && scf_handle_decode_fmri(h, TIMEZONE_FMRI, NULL, NULL, inst,
 567                                   NULL, NULL, SCF_DECODE_FMRI_REQUIRE_INSTANCE) == 0
 568         && scf_instance_get_snapshot(inst, "running", snap) == 0
 569         && scf_instance_get_pg_composed(inst, snap, TIMEZONE_PG, pg) == 0
 570         && scf_pg_get_property(pg, LOCALTIME_PROP, prop) == 0
 571         && scf_property_get_value(prop, val) == 0) {
 572         ssize_t len;
 573 
 574         /* Gets the length of the zone ID string */
 575         len = scf_value_get_astring(val, NULL, 0);
 576         if (len != -1) {
 577             tz = malloc(++len); /* +1 for a null byte */
 578             if (tz != NULL && scf_value_get_astring(val, tz, len) != -1) {
 579                 cleanupScf(h, snap, inst, pg, prop, val, NULL);
 580                 return tz;
 581             }
 582         }
 583     }
 584     cleanupScf(h, snap, inst, pg, prop, val, tz);
 585 
 586     if (stat(DEFAULT_ZONEINFO_FILE, &statbuf) == -1) {
 587         return NULL;
 588     }
 589     size = (size_t) statbuf.st_size;
 590     buf = malloc(size);
 591     if (buf == NULL) {
 592         return NULL;
 593     }
 594     if ((fd = open(DEFAULT_ZONEINFO_FILE, O_RDONLY)) == -1) {
 595         free((void *) buf);
 596         return NULL;
 597     }
 598 
 599     if (read(fd, buf, size) != (ssize_t) size) {
 600         (void) close(fd);
 601         free((void *) buf);
 602         return NULL;
 603     }
 604     (void) close(fd);
 605     tz = findZoneinfoFile(buf, size, ZONEINFO_DIR);
 606     free((void *) buf);
 607     return tz;
 608 }
 609 #endif /*__solaris__*/
 610 #endif /*__linux__*/
 611 
 612 /*
 613  * findJavaTZ_md() maps platform time zone ID to Java time zone ID
 614  * using <java_home>/lib/tzmappings. If the TZ value is not found, it
 615  * trys some libc implementation dependent mappings. If it still
 616  * can't map to a Java time zone ID, it falls back to the GMT+/-hh:mm
 617  * form. `country', which can be null, is not used for UNIX platforms.
 618  */
 619 /*ARGSUSED1*/
 620 char *
 621 findJavaTZ_md(const char *java_home_dir, const char *country)
 622 {
 623     char *tz;
 624     char *javatz = NULL;
 625     char *freetz = NULL;
 626 
 627     tz = getenv("TZ");
 628 
 629 #if defined(__linux__) || defined(_ALLBSD_SOURCE)
 630     if (tz == NULL) {
 631 #else
 632 #ifdef __solaris__
 633     if (tz == NULL || *tz == '\0') {
 634 #endif
 635 #endif
 636         tz = getPlatformTimeZoneID();
 637         freetz = tz;
 638     }
 639 
 640     /*
 641      * Remove any preceding ':'
 642      */
 643     if (tz != NULL && *tz == ':') {
 644         tz++;
 645     }
 646 
 647 #ifdef __solaris__
 648     if (strcmp(tz, "localtime") == 0) {
 649         tz = getSolarisDefaultZoneID();
 650         freetz = tz;
 651     }
 652 #endif
 653 
 654     if (tz != NULL) {
 655 #ifdef __linux__
 656         /*
 657          * Ignore "posix/" prefix.
 658          */
 659         if (strncmp(tz, "posix/", 6) == 0) {
 660             tz += 6;
 661         }
 662 #endif
 663         javatz = strdup(tz);
 664         if (freetz != NULL) {
 665             free((void *) freetz);
 666         }
 667     }
 668     return javatz;
 669 }
 670 /**
 671  * Returns a GMT-offset-based zone ID. (e.g., "GMT-08:00")
 672  */
 673 
 674 #ifdef MACOSX
 675 
 676 char *
 677 getGMTOffsetID()
 678 {
 679     time_t offset;
 680     char sign, buf[32];
 681     struct tm *local_tm;
 682     time_t clock;
 683     time_t currenttime;
 684 
 685     clock = time(NULL);
 686     tzset();
 687     local_tm = localtime(&clock);
 688     if (local_tm->tm_gmtoff >= 0) {
 689         offset = (time_t) local_tm->tm_gmtoff;
 690         sign = "+";
 691     } else {
 692         offset = (time_t) -local_tm->tm_gmtoff;
 693         sign = "-";
 694     }
 695     sprintf(buf, (const char *)"GMT%c%02d:%02d",
 696             sign, (int)(offset/3600), (int)((offset%3600)/60));
 697     return strdup(buf);
 698 }
 699 #else
 700 
 701 char *
 702 getGMTOffsetID()
 703 {
 704     time_t offset;
 705     char sign, buf[32];
 706 #ifdef __solaris__
 707     struct tm localtm;
 708     time_t currenttime;
 709 
 710     currenttime = time(NULL);
 711     if (localtime_r(&currenttime, &localtm) == NULL) {
 712         return NULL;
 713     }
 714 
 715     offset = localtm.tm_isdst ? altzone : timezone;
 716 #else
 717     offset = timezone;
 718 #endif /*__linux__*/
 719 
 720     if (offset == 0) {
 721         return strdup("GMT");
 722     }
 723 
 724     /* Note that the time offset direction is opposite. */
 725     if (offset > 0) {
 726         sign = '-';
 727     } else {
 728         offset = -offset;
 729         sign = '+';
 730     }
 731     sprintf(buf, (const char *)"GMT%c%02d:%02d",
 732             sign, (int)(offset/3600), (int)((offset%3600)/60));
 733     return strdup(buf);
 734 }
 735 #endif /* MACOSX */