attachListener_aix.cpp revision 10295:ad7a71500f4a
1129199Scognet/* 2129199Scognet * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved. 3129199Scognet * Copyright (c) 2012, 2016 SAP SE. All rights reserved. 4129199Scognet * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5129199Scognet * 6129199Scognet * This code is free software; you can redistribute it and/or modify it 7129199Scognet * under the terms of the GNU General Public License version 2 only, as 8129199Scognet * published by the Free Software Foundation. 9129199Scognet * 10129199Scognet * This code is distributed in the hope that it will be useful, but WITHOUT 11135670Scognet * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12129199Scognet * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13129199Scognet * version 2 for more details (a copy is included in the LICENSE file that 14129199Scognet * accompanied this code). 15135670Scognet * 16129199Scognet * You should have received a copy of the GNU General Public License version 17129199Scognet * 2 along with this work; if not, write to the Free Software Foundation, 18129199Scognet * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 19129199Scognet * 20169612Swkoszek * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 21129199Scognet * or visit www.oracle.com if you need additional information or have any 22129199Scognet * questions. 23129199Scognet * 24129199Scognet */ 25129199Scognet 26129199Scognet#include "precompiled.hpp" 27129199Scognet#include "runtime/interfaceSupport.hpp" 28129199Scognet#include "runtime/os.inline.hpp" 29129199Scognet#include "services/attachListener.hpp" 30129199Scognet#include "services/dtraceAttacher.hpp" 31129199Scognet 32129199Scognet#include <unistd.h> 33209131Sraj#include <signal.h> 34209131Sraj#include <sys/types.h> 35135670Scognet#include <sys/socket.h> 36135670Scognet#include <sys/un.h> 37140479Scognet#include <sys/stat.h> 38157165Scognet 39153112Scognet#ifndef UNIX_PATH_MAX 40147630Scognet#define UNIX_PATH_MAX sizeof(((struct sockaddr_un *)0)->sun_path) 41150862Scognet#endif 42248126Sandrew 43245838Sandrew// The attach mechanism on AIX uses a UNIX domain socket. An attach listener 44248126Sandrew// thread is created at startup or is created on-demand via a signal from 45245838Sandrew// the client tool. The attach listener creates a socket and binds it to a file 46160629Scognet// in the filesystem. The attach listener then acts as a simple (single- 47253396Sandrew// threaded) server - it waits for a client to connect, reads the request, 48160629Scognet// executes it, and returns the response to the client via the socket 49248365Sandrew// connection. 50253396Sandrew// 51245675Sandrew// As the socket is a UNIX domain socket it means that only clients on the 52248126Sandrew// local machine can connect. In addition there are two other aspects to 53248126Sandrew// the security: 54248126Sandrew// 1. The well known file that the socket is bound to has permission 400 55160629Scognet// 2. When a client connect, the SO_PEERID socket option is used to 56248126Sandrew// obtain the credentials of client. We check that the effective uid 57160629Scognet// of the client matches this process. 58243664Smarcel 59152742Scognet// forward reference 60152742Scognetclass AixAttachOperation; 61153549Scognet 62152742Scognetclass AixAttachListener: AllStatic { 63152742Scognet private: 64152742Scognet // the path to which we bind the UNIX domain socket 65152742Scognet static char _path[UNIX_PATH_MAX]; 66152742Scognet static bool _has_path; 67153566Scognet // Shutdown marker to prevent accept blocking during clean-up. 68175984Sraj static bool _shutdown; 69175984Sraj 70175984Sraj // the file descriptor for the listening socket 71175984Sraj static int _listener; 72159084Scognet 73159084Scognet static void set_path(char* path) { 74159084Scognet if (path == NULL) { 75171619Scognet _has_path = false; 76183840Sraj } else { 77239268Sgonzo strncpy(_path, path, UNIX_PATH_MAX); 78239268Sgonzo _path[UNIX_PATH_MAX-1] = '\0'; 79239268Sgonzo _has_path = true; 80177895Simp } 81177895Simp } 82153566Scognet 83159758Scognet static void set_listener(int s) { _listener = s; } 84153566Scognet 85153566Scognet // reads a request from the given connected socket 86153549Scognet static AixAttachOperation* read_request(int s); 87248362Sandrew 88171619Scognet public: 89171619Scognet enum { 90171619Scognet ATTACH_PROTOCOL_VER = 1 // protocol version 91153549Scognet }; 92248362Sandrew enum { 93159557Scognet ATTACH_ERROR_BADVERSION = 101 // error codes 94248362Sandrew }; 95181294Scognet 96248362Sandrew // initialize the listener, returns 0 if okay 97248362Sandrew static int init(); 98181294Scognet 99248362Sandrew static char* path() { return _path; } 100248362Sandrew static bool has_path() { return _has_path; } 101248363Sandrew static int listener() { return _listener; } 102248363Sandrew // Shutdown marker to prevent accept blocking during clean-up 103248362Sandrew static void set_shutdown(bool shutdown) { _shutdown = shutdown; } 104153566Scognet static bool is_shutdown() { return _shutdown; } 105248362Sandrew 106154561Scognet // write the given buffer to a socket 107248362Sandrew static int write_fully(int s, char* buf, int len); 108238464Simp 109153112Scognet static AixAttachOperation* dequeue(); 110248362Sandrew}; 111223116Scognet 112223116Scognetclass AixAttachOperation: public AttachOperation { 113181294Scognet private: 114248362Sandrew // the connection to the client 115248362Sandrew int _socket; 116181294Scognet 117248362Sandrew public: 118248362Sandrew void complete(jint res, bufferedStream* st); 119248362Sandrew 120153112Scognet void set_socket(int s) { _socket = s; } 121248363Sandrew int socket() const { return _socket; } 122153549Scognet 123248362Sandrew AixAttachOperation(char* name) : AttachOperation(name) { 124150862Scognet set_socket(-1); 125185478Ssam } 126185478Ssam}; 127129199Scognet 128129199Scognet// statics 129129199Scognetchar AixAttachListener::_path[UNIX_PATH_MAX]; 130129199Scognetbool AixAttachListener::_has_path; 131129199Scognetint AixAttachListener::_listener = -1; 132129199Scognet// Shutdown marker to prevent accept blocking during clean-up 133129199Scognetbool AixAttachListener::_shutdown = false; 134129199Scognet 135129199Scognet// Supporting class to help split a buffer into individual components 136129199Scognetclass ArgumentIterator : public StackObj { 137129199Scognet private: 138129199Scognet char* _pos; 139153549Scognet char* _end; 140153549Scognet public: 141153549Scognet ArgumentIterator(char* arg_buffer, size_t arg_size) { 142153549Scognet _pos = arg_buffer; 143153549Scognet _end = _pos + arg_size - 1; 144153549Scognet } 145135670Scognet char* next() { 146135670Scognet if (*_pos == '\0') { 147135670Scognet if (_pos < _end) { 148129199Scognet _pos += 1; 149129199Scognet } 150129199Scognet 151 return NULL; 152 } 153 char* res = _pos; 154 char* next_pos = strchr(_pos, '\0'); 155 if (next_pos < _end) { 156 next_pos++; 157 } 158 _pos = next_pos; 159 return res; 160 } 161}; 162 163// On AIX if sockets block until all data has been transmitted 164// successfully in some communication domains a socket "close" may 165// never complete. We have to take care that after the socket shutdown 166// the listener never enters accept state. 167 168// atexit hook to stop listener and unlink the file that it is 169// bound too. 170 171// Some modifications to the listener logic to prevent deadlocks on exit. 172// 1. We Shutdown the socket here instead. AixAttachOperation::complete() is not the right place 173// since more than one agent in a sequence in JPLIS live tests wouldn't work (Listener thread 174// would be dead after the first operation completion). 175// 2. close(s) may never return if the listener thread is in socket accept(). Unlinking the file 176// should be sufficient for cleanup. 177extern "C" { 178 static void listener_cleanup() { 179 static int cleanup_done; 180 if (!cleanup_done) { 181 cleanup_done = 1; 182 AixAttachListener::set_shutdown(true); 183 int s = AixAttachListener::listener(); 184 if (s != -1) { 185 ::shutdown(s, 2); 186 } 187 if (AixAttachListener::has_path()) { 188 ::unlink(AixAttachListener::path()); 189 } 190 } 191 } 192} 193 194// Initialization - create a listener socket and bind it to a file 195 196int AixAttachListener::init() { 197 char path[UNIX_PATH_MAX]; // socket file 198 char initial_path[UNIX_PATH_MAX]; // socket file during setup 199 int listener; // listener socket (file descriptor) 200 201 // register function to cleanup 202 ::atexit(listener_cleanup); 203 204 int n = snprintf(path, UNIX_PATH_MAX, "%s/.java_pid%d", 205 os::get_temp_directory(), os::current_process_id()); 206 if (n < (int)UNIX_PATH_MAX) { 207 n = snprintf(initial_path, UNIX_PATH_MAX, "%s.tmp", path); 208 } 209 if (n >= (int)UNIX_PATH_MAX) { 210 return -1; 211 } 212 213 // create the listener socket 214 listener = ::socket(PF_UNIX, SOCK_STREAM, 0); 215 if (listener == -1) { 216 return -1; 217 } 218 219 // bind socket 220 struct sockaddr_un addr; 221 memset((void *)&addr, 0, sizeof(addr)); 222 addr.sun_family = AF_UNIX; 223 strcpy(addr.sun_path, initial_path); 224 ::unlink(initial_path); 225 // We must call bind with the actual socketaddr length. This is obligatory for AS400. 226 int res = ::bind(listener, (struct sockaddr*)&addr, SUN_LEN(&addr)); 227 if (res == -1) { 228 ::close(listener); 229 return -1; 230 } 231 232 // put in listen mode, set permissions, and rename into place 233 res = ::listen(listener, 5); 234 if (res == 0) { 235 RESTARTABLE(::chmod(initial_path, (S_IREAD|S_IWRITE) & ~(S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)), res); 236 if (res == 0) { 237 res = ::rename(initial_path, path); 238 } 239 } 240 if (res == -1) { 241 ::close(listener); 242 ::unlink(initial_path); 243 return -1; 244 } 245 set_path(path); 246 set_listener(listener); 247 set_shutdown(false); 248 249 return 0; 250} 251 252// Given a socket that is connected to a peer we read the request and 253// create an AttachOperation. As the socket is blocking there is potential 254// for a denial-of-service if the peer does not response. However this happens 255// after the peer credentials have been checked and in the worst case it just 256// means that the attach listener thread is blocked. 257// 258AixAttachOperation* AixAttachListener::read_request(int s) { 259 char ver_str[8]; 260 sprintf(ver_str, "%d", ATTACH_PROTOCOL_VER); 261 262 // The request is a sequence of strings so we first figure out the 263 // expected count and the maximum possible length of the request. 264 // The request is: 265 // <ver>0<cmd>0<arg>0<arg>0<arg>0 266 // where <ver> is the protocol version (1), <cmd> is the command 267 // name ("load", "datadump", ...), and <arg> is an argument 268 int expected_str_count = 2 + AttachOperation::arg_count_max; 269 const int max_len = (sizeof(ver_str) + 1) + (AttachOperation::name_length_max + 1) + 270 AttachOperation::arg_count_max*(AttachOperation::arg_length_max + 1); 271 272 char buf[max_len]; 273 int str_count = 0; 274 275 // Read until all (expected) strings have been read, the buffer is 276 // full, or EOF. 277 278 int off = 0; 279 int left = max_len; 280 281 do { 282 int n; 283 // Don't block on interrupts because this will 284 // hang in the clean-up when shutting down. 285 n = read(s, buf+off, left); 286 if (n == -1) { 287 return NULL; // reset by peer or other error 288 } 289 if (n == 0) { // end of file reached 290 break; 291 } 292 for (int i=0; i<n; i++) { 293 if (buf[off+i] == 0) { 294 // EOS found 295 str_count++; 296 297 // The first string is <ver> so check it now to 298 // check for protocol mis-match 299 if (str_count == 1) { 300 if ((strlen(buf) != strlen(ver_str)) || 301 (atoi(buf) != ATTACH_PROTOCOL_VER)) { 302 char msg[32]; 303 sprintf(msg, "%d\n", ATTACH_ERROR_BADVERSION); 304 write_fully(s, msg, strlen(msg)); 305 return NULL; 306 } 307 } 308 } 309 } 310 off += n; 311 left -= n; 312 } while (left > 0 && str_count < expected_str_count); 313 314 if (str_count != expected_str_count) { 315 return NULL; // incomplete request 316 } 317 318 // parse request 319 320 ArgumentIterator args(buf, (max_len)-left); 321 322 // version already checked 323 char* v = args.next(); 324 325 char* name = args.next(); 326 if (name == NULL || strlen(name) > AttachOperation::name_length_max) { 327 return NULL; 328 } 329 330 AixAttachOperation* op = new AixAttachOperation(name); 331 332 for (int i=0; i<AttachOperation::arg_count_max; i++) { 333 char* arg = args.next(); 334 if (arg == NULL) { 335 op->set_arg(i, NULL); 336 } else { 337 if (strlen(arg) > AttachOperation::arg_length_max) { 338 delete op; 339 return NULL; 340 } 341 op->set_arg(i, arg); 342 } 343 } 344 345 op->set_socket(s); 346 return op; 347} 348 349 350// Dequeue an operation 351// 352// In the Aix implementation there is only a single operation and clients 353// cannot queue commands (except at the socket level). 354// 355AixAttachOperation* AixAttachListener::dequeue() { 356 for (;;) { 357 int s; 358 359 // wait for client to connect 360 struct sockaddr addr; 361 socklen_t len = sizeof(addr); 362 memset(&addr, 0, len); 363 // We must prevent accept blocking on the socket if it has been shut down. 364 // Therefore we allow interrups and check whether we have been shut down already. 365 if (AixAttachListener::is_shutdown()) { 366 return NULL; 367 } 368 s=::accept(listener(), &addr, &len); 369 if (s == -1) { 370 return NULL; // log a warning? 371 } 372 373 // Added timeouts for read and write. If we get no request within the 374 // next AttachListenerTimeout milliseconds we just finish the connection. 375 struct timeval tv; 376 tv.tv_sec = 0; 377 tv.tv_usec = AttachListenerTimeout * 1000; 378 ::setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(tv)); 379 ::setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (char*)&tv, sizeof(tv)); 380 381 // get the credentials of the peer and check the effective uid/guid 382 // - check with jeff on this. 383 struct peercred_struct cred_info; 384 socklen_t optlen = sizeof(cred_info); 385 if (::getsockopt(s, SOL_SOCKET, SO_PEERID, (void*)&cred_info, &optlen) == -1) { 386 int res; 387 RESTARTABLE(::close(s), res); 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 int res; 395 RESTARTABLE(::close(s), res); 396 continue; 397 } 398 399 // peer credential look okay so we read the request 400 AixAttachOperation* op = read_request(s); 401 if (op == NULL) { 402 int res; 403 ::close(s); 404 continue; 405 } else { 406 return op; 407 } 408 } 409} 410 411// write the given buffer to the socket 412int AixAttachListener::write_fully(int s, char* buf, int len) { 413 do { 414 int n = ::write(s, buf, len); 415 if (n == -1) { 416 if (errno != EINTR) return -1; 417 } else { 418 buf += n; 419 len -= n; 420 } 421 } 422 while (len > 0); 423 return 0; 424} 425 426// Complete an operation by sending the operation result and any result 427// output to the client. At this time the socket is in blocking mode so 428// potentially we can block if there is a lot of data and the client is 429// non-responsive. For most operations this is a non-issue because the 430// default send buffer is sufficient to buffer everything. In the future 431// if there are operations that involves a very big reply then it the 432// socket could be made non-blocking and a timeout could be used. 433 434void AixAttachOperation::complete(jint result, bufferedStream* st) { 435 JavaThread* thread = JavaThread::current(); 436 ThreadBlockInVM tbivm(thread); 437 438 thread->set_suspend_equivalent(); 439 // cleared by handle_special_suspend_equivalent_condition() or 440 // java_suspend_self() via check_and_wait_while_suspended() 441 442 // write operation result 443 char msg[32]; 444 sprintf(msg, "%d\n", result); 445 int rc = AixAttachListener::write_fully(this->socket(), msg, strlen(msg)); 446 447 // write any result data 448 if (rc == 0) { 449 // Shutdown the socket in the cleanup function to enable more than 450 // one agent attach in a sequence (see comments to listener_cleanup()). 451 AixAttachListener::write_fully(this->socket(), (char*) st->base(), st->size()); 452 } 453 454 // done 455 ::close(this->socket()); 456 457 // were we externally suspended while we were waiting? 458 thread->check_and_wait_while_suspended(); 459 460 delete this; 461} 462 463 464// AttachListener functions 465 466AttachOperation* AttachListener::dequeue() { 467 JavaThread* thread = JavaThread::current(); 468 ThreadBlockInVM tbivm(thread); 469 470 thread->set_suspend_equivalent(); 471 // cleared by handle_special_suspend_equivalent_condition() or 472 // java_suspend_self() via check_and_wait_while_suspended() 473 474 AttachOperation* op = AixAttachListener::dequeue(); 475 476 // were we externally suspended while we were waiting? 477 thread->check_and_wait_while_suspended(); 478 479 return op; 480} 481 482// Performs initialization at vm startup 483// For AIX we remove any stale .java_pid file which could cause 484// an attaching process to think we are ready to receive on the 485// domain socket before we are properly initialized 486 487void AttachListener::vm_start() { 488 char fn[UNIX_PATH_MAX]; 489 struct stat64 st; 490 int ret; 491 492 int n = snprintf(fn, UNIX_PATH_MAX, "%s/.java_pid%d", 493 os::get_temp_directory(), os::current_process_id()); 494 assert(n < (int)UNIX_PATH_MAX, "java_pid file name buffer overflow"); 495 496 RESTARTABLE(::stat64(fn, &st), ret); 497 if (ret == 0) { 498 ret = ::unlink(fn); 499 if (ret == -1) { 500 debug_only(warning("failed to remove stale attach pid file at %s", fn)); 501 } 502 } 503} 504 505int AttachListener::pd_init() { 506 JavaThread* thread = JavaThread::current(); 507 ThreadBlockInVM tbivm(thread); 508 509 thread->set_suspend_equivalent(); 510 // cleared by handle_special_suspend_equivalent_condition() or 511 // java_suspend_self() via check_and_wait_while_suspended() 512 513 int ret_code = AixAttachListener::init(); 514 515 // were we externally suspended while we were waiting? 516 thread->check_and_wait_while_suspended(); 517 518 return ret_code; 519} 520 521// Attach Listener is started lazily except in the case when 522// +ReduseSignalUsage is used 523bool AttachListener::init_at_startup() { 524 if (ReduceSignalUsage) { 525 return true; 526 } else { 527 return false; 528 } 529} 530 531// If the file .attach_pid<pid> exists in the working directory 532// or /tmp then this is the trigger to start the attach mechanism 533bool AttachListener::is_init_trigger() { 534 if (init_at_startup() || is_initialized()) { 535 return false; // initialized at startup or already initialized 536 } 537 char fn[PATH_MAX+1]; 538 sprintf(fn, ".attach_pid%d", os::current_process_id()); 539 int ret; 540 struct stat64 st; 541 RESTARTABLE(::stat64(fn, &st), ret); 542 if (ret == -1) { 543 snprintf(fn, sizeof(fn), "%s/.attach_pid%d", 544 os::get_temp_directory(), os::current_process_id()); 545 RESTARTABLE(::stat64(fn, &st), ret); 546 } 547 if (ret == 0) { 548 // simple check to avoid starting the attach mechanism when 549 // a bogus user creates the file 550 if (st.st_uid == geteuid()) { 551 init(); 552 return true; 553 } 554 } 555 return false; 556} 557 558// if VM aborts then remove listener 559void AttachListener::abort() { 560 listener_cleanup(); 561} 562 563void AttachListener::pd_data_dump() { 564 os::signal_notify(SIGQUIT); 565} 566 567AttachOperationFunctionInfo* AttachListener::pd_find_operation(const char* n) { 568 return NULL; 569} 570 571jint AttachListener::pd_set_flag(AttachOperation* op, outputStream* out) { 572 out->print_cr("flag '%s' cannot be changed", op->arg(0)); 573 return JNI_ERR; 574} 575 576void AttachListener::pd_detachall() { 577 // Cleanup server socket to detach clients. 578 listener_cleanup(); 579} 580