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