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