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