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