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