1 /*
   2  * Copyright (c) 2005, 2019, 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.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "logging/log.hpp"
  27 #include "runtime/interfaceSupport.inline.hpp"
  28 #include "runtime/os.inline.hpp"
  29 #include "services/attachListener.hpp"
  30 #include "services/dtraceAttacher.hpp"
  31 
  32 #include <unistd.h>
  33 #include <signal.h>
  34 #include <sys/types.h>
  35 #include <sys/socket.h>
  36 #include <sys/un.h>
  37 #include <sys/stat.h>
  38 
  39 #ifndef UNIX_PATH_MAX
  40 #define UNIX_PATH_MAX   sizeof(((struct sockaddr_un *)0)->sun_path)
  41 #endif
  42 
  43 // The attach mechanism on Bsd uses a UNIX domain socket. An attach listener
  44 // thread is created at startup or is created on-demand via a signal from
  45 // the client tool. The attach listener creates a socket and binds it to a file
  46 // in the filesystem. The attach listener then acts as a simple (single-
  47 // threaded) server - it waits for a client to connect, reads the request,
  48 // executes it, and returns the response to the client via the socket
  49 // connection.
  50 //
  51 // As the socket is a UNIX domain socket it means that only clients on the
  52 // local machine can connect. In addition there are two other aspects to
  53 // the security:
  54 // 1. The well known file that the socket is bound to has permission 400
  55 // 2. When a client connect, the SO_PEERCRED socket option is used to
  56 //    obtain the credentials of client. We check that the effective uid
  57 //    of the client matches this process.
  58 
  59 // forward reference
  60 class BsdAttachOperation;
  61 
  62 class BsdAttachListener: AllStatic {
  63  private:
  64   // the path to which we bind the UNIX domain socket
  65   static char _path[UNIX_PATH_MAX];
  66   static bool _has_path;
  67 
  68   // the file descriptor for the listening socket
  69   static int _listener;
  70 
  71   static bool _atexit_registered;
  72 
  73   // reads a request from the given connected socket
  74   static BsdAttachOperation* read_request(int s);
  75 
  76  public:
  77   enum {
  78     ATTACH_PROTOCOL_VER = 1                     // protocol version
  79   };
  80   enum {
  81     ATTACH_ERROR_BADVERSION     = 101           // error codes
  82   };
  83 
  84   static void set_path(char* path) {
  85     if (path == NULL) {
  86       _path[0] = '\0';
  87       _has_path = false;
  88     } else {
  89       strncpy(_path, path, UNIX_PATH_MAX);
  90       _path[UNIX_PATH_MAX-1] = '\0';
  91       _has_path = true;
  92     }
  93   }
  94 
  95   static void set_listener(int s)               { _listener = s; }
  96 
  97   // initialize the listener, returns 0 if okay
  98   static int init();
  99 
 100   static char* path()                   { return _path; }
 101   static bool has_path()                { return _has_path; }
 102   static int listener()                 { return _listener; }
 103 
 104   // write the given buffer to a socket
 105   static int write_fully(int s, char* buf, int len);
 106 
 107   static BsdAttachOperation* dequeue();
 108 };
 109 
 110 class BsdAttachOperation: public AttachOperation {
 111  private:
 112   // the connection to the client
 113   int _socket;
 114 
 115  public:
 116   void complete(jint res, bufferedStream* st);
 117 
 118   void set_socket(int s)                                { _socket = s; }
 119   int socket() const                                    { return _socket; }
 120 
 121   BsdAttachOperation(char* name) : AttachOperation(name) {
 122     set_socket(-1);
 123   }
 124 };
 125 
 126 // statics
 127 char BsdAttachListener::_path[UNIX_PATH_MAX];
 128 bool BsdAttachListener::_has_path;
 129 int BsdAttachListener::_listener = -1;
 130 bool BsdAttachListener::_atexit_registered = false;
 131 
 132 // Supporting class to help split a buffer into individual components
 133 class ArgumentIterator : public StackObj {
 134  private:
 135   char* _pos;
 136   char* _end;
 137  public:
 138   ArgumentIterator(char* arg_buffer, size_t arg_size) {
 139     _pos = arg_buffer;
 140     _end = _pos + arg_size - 1;
 141   }
 142   char* next() {
 143     if (*_pos == '\0') {
 144       // advance the iterator if possible (null arguments)
 145       if (_pos < _end) {
 146         _pos += 1;
 147       }
 148       return NULL;
 149     }
 150     char* res = _pos;
 151     char* next_pos = strchr(_pos, '\0');
 152     if (next_pos < _end)  {
 153       next_pos++;
 154     }
 155     _pos = next_pos;
 156     return res;
 157   }
 158 };
 159 
 160 
 161 // atexit hook to stop listener and unlink the file that it is
 162 // bound too.
 163 extern "C" {
 164   static void listener_cleanup() {
 165     int s = BsdAttachListener::listener();
 166     if (s != -1) {
 167       BsdAttachListener::set_listener(-1);
 168       ::shutdown(s, SHUT_RDWR);
 169       ::close(s);
 170     }
 171     if (BsdAttachListener::has_path()) {
 172       ::unlink(BsdAttachListener::path());
 173       BsdAttachListener::set_path(NULL);
 174     }
 175   }
 176 }
 177 
 178 // Initialization - create a listener socket and bind it to a file
 179 
 180 int BsdAttachListener::init() {
 181   char path[UNIX_PATH_MAX];          // socket file
 182   char initial_path[UNIX_PATH_MAX];  // socket file during setup
 183   int listener;                      // listener socket (file descriptor)
 184 
 185   // register function to cleanup
 186   if (!_atexit_registered) {
 187     _atexit_registered = true;
 188     ::atexit(listener_cleanup);
 189   }
 190 
 191   int n = snprintf(path, UNIX_PATH_MAX, "%s/.java_pid%d",
 192                    os::get_temp_directory(), os::current_process_id());
 193   if (n < (int)UNIX_PATH_MAX) {
 194     n = snprintf(initial_path, UNIX_PATH_MAX, "%s.tmp", path);
 195   }
 196   if (n >= (int)UNIX_PATH_MAX) {
 197     return -1;
 198   }
 199 
 200   // create the listener socket
 201   listener = ::socket(PF_UNIX, SOCK_STREAM, 0);
 202   if (listener == -1) {
 203     return -1;
 204   }
 205 
 206   // bind socket
 207   struct sockaddr_un addr;
 208   memset((void *)&addr, 0, sizeof(addr));
 209   addr.sun_family = AF_UNIX;
 210   strcpy(addr.sun_path, initial_path);
 211   ::unlink(initial_path);
 212   int res = ::bind(listener, (struct sockaddr*)&addr, sizeof(addr));
 213   if (res == -1) {
 214     ::close(listener);
 215     return -1;
 216   }
 217 
 218   // put in listen mode, set permissions, and rename into place
 219   res = ::listen(listener, 5);
 220   if (res == 0) {
 221     RESTARTABLE(::chmod(initial_path, S_IREAD|S_IWRITE), res);
 222     if (res == 0) {
 223       // make sure the file is owned by the effective user and effective group
 224       // e.g. default behavior on mac is that new files inherit the group of
 225       // the directory that they are created in
 226       RESTARTABLE(::chown(initial_path, geteuid(), getegid()), res);
 227       if (res == 0) {
 228         res = ::rename(initial_path, path);
 229       }
 230     }
 231   }
 232   if (res == -1) {
 233     ::close(listener);
 234     ::unlink(initial_path);
 235     return -1;
 236   }
 237   set_path(path);
 238   set_listener(listener);
 239 
 240   return 0;
 241 }
 242 
 243 // Given a socket that is connected to a peer we read the request and
 244 // create an AttachOperation. As the socket is blocking there is potential
 245 // for a denial-of-service if the peer does not response. However this happens
 246 // after the peer credentials have been checked and in the worst case it just
 247 // means that the attach listener thread is blocked.
 248 //
 249 BsdAttachOperation* BsdAttachListener::read_request(int s) {
 250   char ver_str[8];
 251   sprintf(ver_str, "%d", ATTACH_PROTOCOL_VER);
 252 
 253   // The request is a sequence of strings so we first figure out the
 254   // expected count and the maximum possible length of the request.
 255   // The request is:
 256   //   <ver>0<cmd>0<arg>0<arg>0<arg>0
 257   // where <ver> is the protocol version (1), <cmd> is the command
 258   // name ("load", "datadump", ...), and <arg> is an argument
 259   int expected_str_count = 2 + AttachOperation::arg_count_max;
 260   const int max_len = (sizeof(ver_str) + 1) + (AttachOperation::name_length_max + 1) +
 261     AttachOperation::arg_count_max*(AttachOperation::arg_length_max + 1);
 262 
 263   char buf[max_len];
 264   int str_count = 0;
 265 
 266   // Read until all (expected) strings have been read, the buffer is
 267   // full, or EOF.
 268 
 269   int off = 0;
 270   int left = max_len;
 271 
 272   do {
 273     int n;
 274     RESTARTABLE(read(s, buf+off, left), n);
 275     assert(n <= left, "buffer was too small, impossible!");
 276     buf[max_len - 1] = '\0';
 277     if (n == -1) {
 278       return NULL;      // reset by peer or other error
 279     }
 280     if (n == 0) {
 281       break;
 282     }
 283     for (int i=0; i<n; i++) {
 284       if (buf[off+i] == 0) {
 285         // EOS found
 286         str_count++;
 287 
 288         // The first string is <ver> so check it now to
 289         // check for protocol mis-match
 290         if (str_count == 1) {
 291           if ((strlen(buf) != strlen(ver_str)) ||
 292               (atoi(buf) != ATTACH_PROTOCOL_VER)) {
 293             char msg[32];
 294             sprintf(msg, "%d\n", ATTACH_ERROR_BADVERSION);
 295             write_fully(s, msg, strlen(msg));
 296             return NULL;
 297           }
 298         }
 299       }
 300     }
 301     off += n;
 302     left -= n;
 303   } while (left > 0 && str_count < expected_str_count);
 304 
 305   if (str_count != expected_str_count) {
 306     return NULL;        // incomplete request
 307   }
 308 
 309   // parse request
 310 
 311   ArgumentIterator args(buf, (max_len)-left);
 312 
 313   // version already checked
 314   char* v = args.next();
 315 
 316   char* name = args.next();
 317   if (name == NULL || strlen(name) > AttachOperation::name_length_max) {
 318     return NULL;
 319   }
 320 
 321   BsdAttachOperation* op = new BsdAttachOperation(name);
 322 
 323   for (int i=0; i<AttachOperation::arg_count_max; i++) {
 324     char* arg = args.next();
 325     if (arg == NULL) {
 326       op->set_arg(i, NULL);
 327     } else {
 328       if (strlen(arg) > AttachOperation::arg_length_max) {
 329         delete op;
 330         return NULL;
 331       }
 332       op->set_arg(i, arg);
 333     }
 334   }
 335 
 336   op->set_socket(s);
 337   return op;
 338 }
 339 
 340 
 341 // Dequeue an operation
 342 //
 343 // In the Bsd implementation there is only a single operation and clients
 344 // cannot queue commands (except at the socket level).
 345 //
 346 BsdAttachOperation* BsdAttachListener::dequeue() {
 347   for (;;) {
 348     int s;
 349 
 350     // wait for client to connect
 351     struct sockaddr addr;
 352     socklen_t len = sizeof(addr);
 353     RESTARTABLE(::accept(listener(), &addr, &len), s);
 354     if (s == -1) {
 355       return NULL;      // log a warning?
 356     }
 357 
 358     // get the credentials of the peer and check the effective uid/guid
 359     uid_t puid;
 360     gid_t pgid;
 361     if (::getpeereid(s, &puid, &pgid) != 0) {
 362       log_debug(attach)("Failed to get peer id");
 363       ::close(s);
 364       continue;
 365     }
 366 
 367     if (!os::Posix::matches_effective_uid_and_gid_or_root(puid, pgid)) {
 368       log_debug(attach)("euid/egid check failed (%d/%d vs %d/%d)", puid, pgid,
 369               geteuid(), getegid());
 370       ::close(s);
 371       continue;
 372     }
 373 
 374     // peer credential look okay so we read the request
 375     BsdAttachOperation* op = read_request(s);
 376     if (op == NULL) {
 377       ::close(s);
 378       continue;
 379     } else {
 380       return op;
 381     }
 382   }
 383 }
 384 
 385 // write the given buffer to the socket
 386 int BsdAttachListener::write_fully(int s, char* buf, int len) {
 387   do {
 388     int n = ::write(s, buf, len);
 389     if (n == -1) {
 390       if (errno != EINTR) return -1;
 391     } else {
 392       buf += n;
 393       len -= n;
 394     }
 395   }
 396   while (len > 0);
 397   return 0;
 398 }
 399 
 400 // Complete an operation by sending the operation result and any result
 401 // output to the client. At this time the socket is in blocking mode so
 402 // potentially we can block if there is a lot of data and the client is
 403 // non-responsive. For most operations this is a non-issue because the
 404 // default send buffer is sufficient to buffer everything. In the future
 405 // if there are operations that involves a very big reply then it the
 406 // socket could be made non-blocking and a timeout could be used.
 407 
 408 void BsdAttachOperation::complete(jint result, bufferedStream* st) {
 409   JavaThread* thread = JavaThread::current();
 410   ThreadBlockInVM tbivm(thread);
 411 
 412   thread->set_suspend_equivalent();
 413   // cleared by handle_special_suspend_equivalent_condition() or
 414   // java_suspend_self() via check_and_wait_while_suspended()
 415 
 416   // write operation result
 417   char msg[32];
 418   sprintf(msg, "%d\n", result);
 419   int rc = BsdAttachListener::write_fully(this->socket(), msg, strlen(msg));
 420 
 421   // write any result data
 422   if (rc == 0) {
 423     BsdAttachListener::write_fully(this->socket(), (char*) st->base(), st->size());
 424     ::shutdown(this->socket(), 2);
 425   }
 426 
 427   // done
 428   ::close(this->socket());
 429 
 430   // were we externally suspended while we were waiting?
 431   thread->check_and_wait_while_suspended();
 432 
 433   delete this;
 434 }
 435 
 436 
 437 // AttachListener functions
 438 
 439 AttachOperation* AttachListener::dequeue() {
 440   JavaThread* thread = JavaThread::current();
 441   ThreadBlockInVM tbivm(thread);
 442 
 443   thread->set_suspend_equivalent();
 444   // cleared by handle_special_suspend_equivalent_condition() or
 445   // java_suspend_self() via check_and_wait_while_suspended()
 446 
 447   AttachOperation* op = BsdAttachListener::dequeue();
 448 
 449   // were we externally suspended while we were waiting?
 450   thread->check_and_wait_while_suspended();
 451 
 452   return op;
 453 }
 454 
 455 // Performs initialization at vm startup
 456 // For BSD we remove any stale .java_pid file which could cause
 457 // an attaching process to think we are ready to receive on the
 458 // domain socket before we are properly initialized
 459 
 460 void AttachListener::vm_start() {
 461   char fn[UNIX_PATH_MAX];
 462   struct stat st;
 463   int ret;
 464 
 465   int n = snprintf(fn, UNIX_PATH_MAX, "%s/.java_pid%d",
 466            os::get_temp_directory(), os::current_process_id());
 467   assert(n < (int)UNIX_PATH_MAX, "java_pid file name buffer overflow");
 468 
 469   RESTARTABLE(::stat(fn, &st), ret);
 470   if (ret == 0) {
 471     ret = ::unlink(fn);
 472     if (ret == -1) {
 473       log_debug(attach)("Failed to remove stale attach pid file at %s", fn);
 474     }
 475   }
 476 }
 477 
 478 int AttachListener::pd_init() {
 479   JavaThread* thread = JavaThread::current();
 480   ThreadBlockInVM tbivm(thread);
 481 
 482   thread->set_suspend_equivalent();
 483   // cleared by handle_special_suspend_equivalent_condition() or
 484   // java_suspend_self() via check_and_wait_while_suspended()
 485 
 486   int ret_code = BsdAttachListener::init();
 487 
 488   // were we externally suspended while we were waiting?
 489   thread->check_and_wait_while_suspended();
 490 
 491   return ret_code;
 492 }
 493 
 494 bool AttachListener::check_socket_file() {
 495   int ret;
 496   struct stat st;
 497   ret = stat(BsdAttachListener::path(), &st);
 498   if (ret == -1) { // need to restart attach listener.
 499     log_debug(attach)("Socket file %s does not exist - Restart Attach Listener",
 500                       BsdAttachListener::path());
 501 
 502     listener_cleanup();
 503 
 504     // wait to terminate current attach listener instance...
 505 
 506     while (AttachListener::transit_state(AL_INITIALIZING,
 507 
 508                                          AL_NOT_INITIALIZED) != AL_NOT_INITIALIZED) {
 509       os::naked_yield();
 510     }
 511     return is_init_trigger();
 512   }
 513   return false;
 514 }
 515 
 516 // Attach Listener is started lazily except in the case when
 517 // +ReduseSignalUsage is used
 518 bool AttachListener::init_at_startup() {
 519   if (ReduceSignalUsage) {
 520     return true;
 521   } else {
 522     return false;
 523   }
 524 }
 525 
 526 // If the file .attach_pid<pid> exists in the working directory
 527 // or /tmp then this is the trigger to start the attach mechanism
 528 bool AttachListener::is_init_trigger() {
 529   if (init_at_startup() || is_initialized()) {
 530     return false;               // initialized at startup or already initialized
 531   }
 532   char fn[PATH_MAX + 1];
 533   int ret;
 534   struct stat st;
 535   snprintf(fn, PATH_MAX + 1, "%s/.attach_pid%d",
 536            os::get_temp_directory(), os::current_process_id());
 537   RESTARTABLE(::stat(fn, &st), ret);
 538   if (ret == -1) {
 539     log_debug(attach)("Failed to find attach file: %s", fn);
 540   }
 541   if (ret == 0) {
 542     // simple check to avoid starting the attach mechanism when
 543     // a bogus non-root user creates the file
 544     if (os::Posix::matches_effective_uid_or_root(st.st_uid)) {
 545       init();
 546       log_trace(attach)("Attach triggered by %s", fn);
 547       return true;
 548     } else {
 549       log_debug(attach)("File %s has wrong user id %d (vs %d). Attach is not triggered", fn, st.st_uid, geteuid());
 550     }
 551   }
 552   return false;
 553 }
 554 
 555 // if VM aborts then remove listener
 556 void AttachListener::abort() {
 557   listener_cleanup();
 558 }
 559 
 560 void AttachListener::pd_data_dump() {
 561   os::signal_notify(SIGQUIT);
 562 }
 563 
 564 AttachOperationFunctionInfo* AttachListener::pd_find_operation(const char* n) {
 565   return NULL;
 566 }
 567 
 568 jint AttachListener::pd_set_flag(AttachOperation* op, outputStream* out) {
 569   out->print_cr("flag '%s' cannot be changed", op->arg(0));
 570   return JNI_ERR;
 571 }
 572 
 573 void AttachListener::pd_detachall() {
 574   // do nothing for now
 575 }