1 /*
   2  * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright 2012, 2013 SAP AG. 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 "runtime/interfaceSupport.hpp"
  28 #include "runtime/os.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 Linux 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_PEERID 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 AixAttachOperation;
  61 
  62 class AixAttachListener: 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   // Shutdown marker to prevent accept blocking during clean-up.
  68   static bool _shutdown;
  69 
  70   // the file descriptor for the listening socket
  71   static int _listener;
  72 
  73   static void set_path(char* path) {
  74     if (path == NULL) {
  75       _has_path = false;
  76     } else {
  77       strncpy(_path, path, UNIX_PATH_MAX);
  78       _path[UNIX_PATH_MAX-1] = '\0';
  79       _has_path = true;
  80     }
  81   }
  82 
  83   static void set_listener(int s)               { _listener = s; }
  84 
  85   // reads a request from the given connected socket
  86   static AixAttachOperation* read_request(int s);
  87 
  88  public:
  89   enum {
  90     ATTACH_PROTOCOL_VER = 1                     // protocol version
  91   };
  92   enum {
  93     ATTACH_ERROR_BADVERSION     = 101           // error codes
  94   };
  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   // Shutdown marker to prevent accept blocking during clean-up
 103   static void set_shutdown(bool shutdown) { _shutdown = shutdown; }
 104   static bool is_shutdown()     { return _shutdown; }
 105 
 106   // write the given buffer to a socket
 107   static int write_fully(int s, char* buf, int len);
 108 
 109   static AixAttachOperation* dequeue();
 110 };
 111 
 112 class AixAttachOperation: public AttachOperation {
 113  private:
 114   // the connection to the client
 115   int _socket;
 116 
 117  public:
 118   void complete(jint res, bufferedStream* st);
 119 
 120   void set_socket(int s)                                { _socket = s; }
 121   int socket() const                                    { return _socket; }
 122 
 123   AixAttachOperation(char* name) : AttachOperation(name) {
 124     set_socket(-1);
 125   }
 126 };
 127 
 128 // statics
 129 char AixAttachListener::_path[UNIX_PATH_MAX];
 130 bool AixAttachListener::_has_path;
 131 int AixAttachListener::_listener = -1;
 132 // Shutdown marker to prevent accept blocking during clean-up
 133 bool AixAttachListener::_shutdown = false;
 134 
 135 // Supporting class to help split a buffer into individual components
 136 class ArgumentIterator : public StackObj {
 137  private:
 138   char* _pos;
 139   char* _end;
 140  public:
 141   ArgumentIterator(char* arg_buffer, size_t arg_size) {
 142     _pos = arg_buffer;
 143     _end = _pos + arg_size - 1;
 144   }
 145   char* next() {
 146     if (*_pos == '\0') {
 147       return NULL;
 148     }
 149     char* res = _pos;
 150     char* next_pos = strchr(_pos, '\0');
 151     if (next_pos < _end)  {
 152       next_pos++;
 153     }
 154     _pos = next_pos;
 155     return res;
 156   }
 157 };
 158 
 159 // On AIX if sockets block until all data has been transmitted
 160 // successfully in some communication domains a socket "close" may
 161 // never complete. We have to take care that after the socket shutdown
 162 // the listener never enters accept state.
 163 
 164 // atexit hook to stop listener and unlink the file that it is
 165 // bound too.
 166 
 167 // Some modifications to the listener logic to prevent deadlocks on exit.
 168 // 1. We Shutdown the socket here instead. AixAttachOperation::complete() is not the right place
 169 //    since more than one agent in a sequence in JPLIS live tests wouldn't work (Listener thread
 170 //    would be dead after the first operation completion).
 171 // 2. close(s) may never return if the listener thread is in socket accept(). Unlinking the file
 172 //    should be sufficient for cleanup.
 173 extern "C" {
 174   static void listener_cleanup() {
 175     static int cleanup_done;
 176     if (!cleanup_done) {
 177       cleanup_done = 1;
 178       AixAttachListener::set_shutdown(true);
 179       int s = AixAttachListener::listener();
 180       if (s != -1) {
 181         ::shutdown(s, 2);
 182       }
 183       if (AixAttachListener::has_path()) {
 184         ::unlink(AixAttachListener::path());
 185       }
 186     }
 187   }
 188 }
 189 
 190 // Initialization - create a listener socket and bind it to a file
 191 
 192 int AixAttachListener::init() {
 193   char path[UNIX_PATH_MAX];          // socket file
 194   char initial_path[UNIX_PATH_MAX];  // socket file during setup
 195   int listener;                      // listener socket (file descriptor)
 196 
 197   // register function to cleanup
 198   ::atexit(listener_cleanup);
 199 
 200   int n = snprintf(path, UNIX_PATH_MAX, "%s/.java_pid%d",
 201                    os::get_temp_directory(), os::current_process_id());
 202   if (n < (int)UNIX_PATH_MAX) {
 203     n = snprintf(initial_path, UNIX_PATH_MAX, "%s.tmp", path);
 204   }
 205   if (n >= (int)UNIX_PATH_MAX) {
 206     return -1;
 207   }
 208 
 209   // create the listener socket
 210   listener = ::socket(PF_UNIX, SOCK_STREAM, 0);
 211   if (listener == -1) {
 212     return -1;
 213   }
 214 
 215   // bind socket
 216   struct sockaddr_un addr;
 217   addr.sun_family = AF_UNIX;
 218   strcpy(addr.sun_path, initial_path);
 219   ::unlink(initial_path);
 220   // We must call bind with the actual socketaddr length. This is obligatory for AS400.
 221   int res = ::bind(listener, (struct sockaddr*)&addr, SUN_LEN(&addr));
 222   if (res == -1) {
 223     RESTARTABLE(::close(listener), res);
 224     return -1;
 225   }
 226 
 227   // put in listen mode, set permissions, and rename into place
 228   res = ::listen(listener, 5);
 229   if (res == 0) {
 230       RESTARTABLE(::chmod(initial_path, (S_IREAD|S_IWRITE) & ~(S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)), res);
 231       if (res == 0) {
 232           res = ::rename(initial_path, path);
 233       }
 234   }
 235   if (res == -1) {
 236     RESTARTABLE(::close(listener), res);
 237     ::unlink(initial_path);
 238     return -1;
 239   }
 240   set_path(path);
 241   set_listener(listener);
 242   set_shutdown(false);
 243 
 244   return 0;
 245 }
 246 
 247 // Given a socket that is connected to a peer we read the request and
 248 // create an AttachOperation. As the socket is blocking there is potential
 249 // for a denial-of-service if the peer does not response. However this happens
 250 // after the peer credentials have been checked and in the worst case it just
 251 // means that the attach listener thread is blocked.
 252 //
 253 AixAttachOperation* AixAttachListener::read_request(int s) {
 254   char ver_str[8];
 255   sprintf(ver_str, "%d", ATTACH_PROTOCOL_VER);
 256 
 257   // The request is a sequence of strings so we first figure out the
 258   // expected count and the maximum possible length of the request.
 259   // The request is:
 260   //   <ver>0<cmd>0<arg>0<arg>0<arg>0
 261   // where <ver> is the protocol version (1), <cmd> is the command
 262   // name ("load", "datadump", ...), and <arg> is an argument
 263   int expected_str_count = 2 + AttachOperation::arg_count_max;
 264   const int max_len = (sizeof(ver_str) + 1) + (AttachOperation::name_length_max + 1) +
 265     AttachOperation::arg_count_max*(AttachOperation::arg_length_max + 1);
 266 
 267   char buf[max_len];
 268   int str_count = 0;
 269 
 270   // Read until all (expected) strings have been read, the buffer is
 271   // full, or EOF.
 272 
 273   int off = 0;
 274   int left = max_len;
 275 
 276   do {
 277     int n;
 278     // Don't block on interrupts because this will
 279     // hang in the clean-up when shutting down.
 280     n = read(s, buf+off, left);
 281     if (n == -1) {
 282       return NULL;      // reset by peer or other error
 283     }
 284     if (n == 0) {       // end of file reached
 285       break;
 286     }
 287     for (int i=0; i<n; i++) {
 288       if (buf[off+i] == 0) {
 289         // EOS found
 290         str_count++;
 291 
 292         // The first string is <ver> so check it now to
 293         // check for protocol mis-match
 294         if (str_count == 1) {
 295           if ((strlen(buf) != strlen(ver_str)) ||
 296               (atoi(buf) != ATTACH_PROTOCOL_VER)) {
 297             char msg[32];
 298             sprintf(msg, "%d\n", ATTACH_ERROR_BADVERSION);
 299             write_fully(s, msg, strlen(msg));
 300             return NULL;
 301           }
 302         }
 303       }
 304     }
 305     off += n;
 306     left -= n;
 307   } while (left > 0 && str_count < expected_str_count);
 308 
 309   if (str_count != expected_str_count) {
 310     return NULL;        // incomplete request
 311   }
 312 
 313   // parse request
 314 
 315   ArgumentIterator args(buf, (max_len)-left);
 316 
 317   // version already checked
 318   char* v = args.next();
 319 
 320   char* name = args.next();
 321   if (name == NULL || strlen(name) > AttachOperation::name_length_max) {
 322     return NULL;
 323   }
 324 
 325   AixAttachOperation* op = new AixAttachOperation(name);
 326 
 327   for (int i=0; i<AttachOperation::arg_count_max; i++) {
 328     char* arg = args.next();
 329     if (arg == NULL) {
 330       op->set_arg(i, NULL);
 331     } else {
 332       if (strlen(arg) > AttachOperation::arg_length_max) {
 333         delete op;
 334         return NULL;
 335       }
 336       op->set_arg(i, arg);
 337     }
 338   }
 339 
 340   op->set_socket(s);
 341   return op;
 342 }
 343 
 344 
 345 // Dequeue an operation
 346 //
 347 // In the Linux implementation there is only a single operation and clients
 348 // cannot queue commands (except at the socket level).
 349 //
 350 AixAttachOperation* AixAttachListener::dequeue() {
 351   for (;;) {
 352     int s;
 353 
 354     // wait for client to connect
 355     struct sockaddr addr;
 356     socklen_t len = sizeof(addr);
 357     memset(&addr, 0, len);
 358     // We must prevent accept blocking on the socket if it has been shut down.
 359     // Therefore we allow interrups and check whether we have been shut down already.
 360     if (AixAttachListener::is_shutdown()) {
 361       return NULL;
 362     }
 363     s=::accept(listener(), &addr, &len);
 364     if (s == -1) {
 365       return NULL;      // log a warning?
 366     }
 367 
 368     // Added timeouts for read and write.  If we get no request within the
 369     // next AttachListenerTimeout milliseconds we just finish the connection.
 370     struct timeval tv;
 371     tv.tv_sec = 0;
 372     tv.tv_usec = AttachListenerTimeout * 1000;
 373     ::setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(tv));
 374     ::setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (char*)&tv, sizeof(tv));
 375 
 376     // get the credentials of the peer and check the effective uid/guid
 377     // - check with jeff on this.
 378     struct peercred_struct cred_info;
 379     socklen_t optlen = sizeof(cred_info);
 380     if (::getsockopt(s, SOL_SOCKET, SO_PEERID, (void*)&cred_info, &optlen) == -1) {
 381       int res;
 382       RESTARTABLE(::close(s), res);
 383       continue;
 384     }
 385     uid_t euid = geteuid();
 386     gid_t egid = getegid();
 387 
 388     if (cred_info.euid != euid || cred_info.egid != egid) {
 389       int res;
 390       RESTARTABLE(::close(s), res);
 391       continue;
 392     }
 393 
 394     // peer credential look okay so we read the request
 395     AixAttachOperation* op = read_request(s);
 396     if (op == NULL) {
 397       int res;
 398       RESTARTABLE(::close(s), res);
 399       continue;
 400     } else {
 401       return op;
 402     }
 403   }
 404 }
 405 
 406 // write the given buffer to the socket
 407 int AixAttachListener::write_fully(int s, char* buf, int len) {
 408   do {
 409     int n = ::write(s, buf, len);
 410     if (n == -1) {
 411       if (errno != EINTR) return -1;
 412     } else {
 413       buf += n;
 414       len -= n;
 415     }
 416   }
 417   while (len > 0);
 418   return 0;
 419 }
 420 
 421 // Complete an operation by sending the operation result and any result
 422 // output to the client. At this time the socket is in blocking mode so
 423 // potentially we can block if there is a lot of data and the client is
 424 // non-responsive. For most operations this is a non-issue because the
 425 // default send buffer is sufficient to buffer everything. In the future
 426 // if there are operations that involves a very big reply then it the
 427 // socket could be made non-blocking and a timeout could be used.
 428 
 429 void AixAttachOperation::complete(jint result, bufferedStream* st) {
 430   JavaThread* thread = JavaThread::current();
 431   ThreadBlockInVM tbivm(thread);
 432 
 433   thread->set_suspend_equivalent();
 434   // cleared by handle_special_suspend_equivalent_condition() or
 435   // java_suspend_self() via check_and_wait_while_suspended()
 436 
 437   // write operation result
 438   char msg[32];
 439   sprintf(msg, "%d\n", result);
 440   int rc = AixAttachListener::write_fully(this->socket(), msg, strlen(msg));
 441 
 442   // write any result data
 443   if (rc == 0) {
 444     // Shutdown the socket in the cleanup function to enable more than
 445     // one agent attach in a sequence (see comments to listener_cleanup()).
 446     AixAttachListener::write_fully(this->socket(), (char*) st->base(), st->size());
 447   }
 448 
 449   // done
 450   RESTARTABLE(::close(this->socket()), rc);
 451 
 452   // were we externally suspended while we were waiting?
 453   thread->check_and_wait_while_suspended();
 454 
 455   delete this;
 456 }
 457 
 458 
 459 // AttachListener functions
 460 
 461 AttachOperation* AttachListener::dequeue() {
 462   JavaThread* thread = JavaThread::current();
 463   ThreadBlockInVM tbivm(thread);
 464 
 465   thread->set_suspend_equivalent();
 466   // cleared by handle_special_suspend_equivalent_condition() or
 467   // java_suspend_self() via check_and_wait_while_suspended()
 468 
 469   AttachOperation* op = AixAttachListener::dequeue();
 470 
 471   // were we externally suspended while we were waiting?
 472   thread->check_and_wait_while_suspended();
 473 
 474   return op;
 475 }
 476 
 477 // Performs initialization at vm startup
 478 // For AIX we remove any stale .java_pid file which could cause
 479 // an attaching process to think we are ready to receive on the
 480 // domain socket before we are properly initialized
 481 
 482 void AttachListener::vm_start() {
 483   char fn[UNIX_PATH_MAX];
 484   struct stat64 st;
 485   int ret;
 486 
 487   int n = snprintf(fn, UNIX_PATH_MAX, "%s/.java_pid%d",
 488            os::get_temp_directory(), os::current_process_id());
 489   assert(n < (int)UNIX_PATH_MAX, "java_pid file name buffer overflow");
 490 
 491   RESTARTABLE(::stat64(fn, &st), ret);
 492   if (ret == 0) {
 493     ret = ::unlink(fn);
 494     if (ret == -1) {
 495       debug_only(warning("failed to remove stale attach pid file at %s", fn));
 496     }
 497   }
 498 }
 499 
 500 int AttachListener::pd_init() {
 501   JavaThread* thread = JavaThread::current();
 502   ThreadBlockInVM tbivm(thread);
 503 
 504   thread->set_suspend_equivalent();
 505   // cleared by handle_special_suspend_equivalent_condition() or
 506   // java_suspend_self() via check_and_wait_while_suspended()
 507 
 508   int ret_code = AixAttachListener::init();
 509 
 510   // were we externally suspended while we were waiting?
 511   thread->check_and_wait_while_suspended();
 512 
 513   return ret_code;
 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   sprintf(fn, ".attach_pid%d", os::current_process_id());
 534   int ret;
 535   struct stat64 st;
 536   RESTARTABLE(::stat64(fn, &st), ret);
 537   if (ret == -1) {
 538     snprintf(fn, sizeof(fn), "%s/.attach_pid%d",
 539              os::get_temp_directory(), os::current_process_id());
 540     RESTARTABLE(::stat64(fn, &st), ret);
 541   }
 542   if (ret == 0) {
 543     // simple check to avoid starting the attach mechanism when
 544     // a bogus user creates the file
 545     if (st.st_uid == geteuid()) {
 546       init();
 547       return true;
 548     }
 549   }
 550   return false;
 551 }
 552 
 553 // if VM aborts then remove listener
 554 void AttachListener::abort() {
 555   listener_cleanup();
 556 }
 557 
 558 void AttachListener::pd_data_dump() {
 559   os::signal_notify(SIGQUIT);
 560 }
 561 
 562 AttachOperationFunctionInfo* AttachListener::pd_find_operation(const char* n) {
 563   return NULL;
 564 }
 565 
 566 jint AttachListener::pd_set_flag(AttachOperation* op, outputStream* out) {
 567   out->print_cr("flag '%s' cannot be changed", op->arg(0));
 568   return JNI_ERR;
 569 }
 570 
 571 void AttachListener::pd_detachall() {
 572   // Cleanup server socket to detach clients.
 573   listener_cleanup();
 574 }