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