1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <errno.h>
18 #include <stdio.h>
19 #include <sys/socket.h>
20 #include <sys/un.h>
21 #include <unistd.h>
22 
23 #include "android-base/stringprintf.h"
24 
25 #include "base/logging.h"  // For VLOG.
26 #include "jdwp/jdwp_priv.h"
27 #include "thread-current-inl.h"
28 
29 #ifdef ART_TARGET_ANDROID
30 #include "cutils/sockets.h"
31 #endif
32 
33 /*
34  * The JDWP <-> ADB transport protocol is explained in detail
35  * in system/core/adb/jdwp_service.c. Here's a summary.
36  *
37  * 1/ when the JDWP thread starts, it tries to connect to a Unix
38  *    domain stream socket (@jdwp-control) that is opened by the
39  *    ADB daemon.
40  *
41  * 2/ it then sends the current process PID as an int32_t.
42  *
43  * 3/ then, it uses recvmsg to receive file descriptors from the
44  *    daemon. each incoming file descriptor is a pass-through to
45  *    a given JDWP debugger, that can be used to read the usual
46  *    JDWP-handshake, etc...
47  */
48 
49 static constexpr char kJdwpControlName[] = "\0jdwp-control";
50 static constexpr size_t kJdwpControlNameLen = sizeof(kJdwpControlName) - 1;
51 /* This timeout is for connect/send with control socket. In practice, the
52  * connect should never timeout since it's just connect to a local unix domain
53  * socket. But in case adb is buggy and doesn't respond to any connection, the
54  * connect will block. For send, actually it would never block since we only send
55  * several bytes and the kernel buffer is big enough to accept it. 10 seconds
56  * should be far enough.
57  */
58 static constexpr int kControlSockSendTimeout = 10;
59 
60 namespace art {
61 
62 namespace JDWP {
63 
64 using android::base::StringPrintf;
65 
66 struct JdwpAdbState : public JdwpNetStateBase {
67  public:
JdwpAdbStateart::JDWP::JdwpAdbState68   explicit JdwpAdbState(JdwpState* state)
69       : JdwpNetStateBase(state),
70         state_lock_("JdwpAdbState lock", kJdwpAdbStateLock) {
71     control_sock_ = -1;
72     shutting_down_ = false;
73 
74     control_addr_.controlAddrUn.sun_family = AF_UNIX;
75     control_addr_len_ = sizeof(control_addr_.controlAddrUn.sun_family) + kJdwpControlNameLen;
76     memcpy(control_addr_.controlAddrUn.sun_path, kJdwpControlName, kJdwpControlNameLen);
77   }
78 
~JdwpAdbStateart::JDWP::JdwpAdbState79   ~JdwpAdbState() {
80     if (clientSock != -1) {
81       shutdown(clientSock, SHUT_RDWR);
82       close(clientSock);
83     }
84     if (control_sock_ != -1) {
85       shutdown(control_sock_, SHUT_RDWR);
86       close(control_sock_);
87     }
88   }
89 
90   virtual bool Accept() REQUIRES(!state_lock_);
91 
Establishart::JDWP::JdwpAdbState92   virtual bool Establish(const JdwpOptions*) {
93     return false;
94   }
95 
Shutdownart::JDWP::JdwpAdbState96   virtual void Shutdown() REQUIRES(!state_lock_) {
97     int control_sock;
98     int local_clientSock;
99     {
100       MutexLock mu(Thread::Current(), state_lock_);
101       shutting_down_ = true;
102       control_sock = this->control_sock_;
103       local_clientSock = this->clientSock;
104       /* clear these out so it doesn't wake up and try to reuse them */
105       this->control_sock_ = this->clientSock = -1;
106     }
107 
108     if (local_clientSock != -1) {
109       shutdown(local_clientSock, SHUT_RDWR);
110     }
111 
112     if (control_sock != -1) {
113       shutdown(control_sock, SHUT_RDWR);
114     }
115 
116     WakePipe();
117   }
118 
119   virtual bool ProcessIncoming() REQUIRES(!state_lock_);
120 
121  private:
122   int ReceiveClientFd() REQUIRES(!state_lock_);
123 
IsDownart::JDWP::JdwpAdbState124   bool IsDown() REQUIRES(!state_lock_) {
125     MutexLock mu(Thread::Current(), state_lock_);
126     return shutting_down_;
127   }
128 
ControlSockart::JDWP::JdwpAdbState129   int ControlSock() REQUIRES(!state_lock_) {
130     MutexLock mu(Thread::Current(), state_lock_);
131     if (shutting_down_) {
132       CHECK_EQ(control_sock_, -1);
133     }
134     return control_sock_;
135   }
136 
137   int control_sock_ GUARDED_BY(state_lock_);
138   bool shutting_down_ GUARDED_BY(state_lock_);
139   Mutex state_lock_;
140 
141   socklen_t control_addr_len_;
142   union {
143     sockaddr_un controlAddrUn;
144     sockaddr controlAddrPlain;
145   } control_addr_;
146 };
147 
148 /*
149  * Do initial prep work, e.g. binding to ports and opening files.  This
150  * runs in the main thread, before the JDWP thread starts, so it shouldn't
151  * do anything that might block forever.
152  */
InitAdbTransport(JdwpState * state,const JdwpOptions *)153 bool InitAdbTransport(JdwpState* state, const JdwpOptions*) {
154   VLOG(jdwp) << "ADB transport startup";
155   state->netState = new JdwpAdbState(state);
156   return (state->netState != nullptr);
157 }
158 
159 /*
160  * Receive a file descriptor from ADB.  The fd can be used to communicate
161  * directly with a debugger or DDMS.
162  *
163  * Returns the file descriptor on success.  On failure, returns -1 and
164  * closes netState->control_sock_.
165  */
ReceiveClientFd()166 int JdwpAdbState::ReceiveClientFd() {
167   char dummy = '!';
168   union {
169     cmsghdr cm;
170     char buffer[CMSG_SPACE(sizeof(int))];
171   } cm_un;
172 
173   iovec iov;
174   iov.iov_base       = &dummy;
175   iov.iov_len        = 1;
176 
177   msghdr msg;
178   msg.msg_name       = nullptr;
179   msg.msg_namelen    = 0;
180   msg.msg_iov        = &iov;
181   msg.msg_iovlen     = 1;
182   msg.msg_flags      = 0;
183   msg.msg_control    = cm_un.buffer;
184   msg.msg_controllen = sizeof(cm_un.buffer);
185 
186   cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
187   cmsg->cmsg_len   = msg.msg_controllen;
188   cmsg->cmsg_level = SOL_SOCKET;
189   cmsg->cmsg_type  = SCM_RIGHTS;
190   (reinterpret_cast<int*>(CMSG_DATA(cmsg)))[0] = -1;
191 
192   int rc = TEMP_FAILURE_RETRY(recvmsg(ControlSock(), &msg, 0));
193 
194   if (rc <= 0) {
195     if (rc == -1) {
196       PLOG(WARNING) << "Receiving file descriptor from ADB failed (socket " << ControlSock() << ")";
197     }
198     MutexLock mu(Thread::Current(), state_lock_);
199     close(control_sock_);
200     control_sock_ = -1;
201     return -1;
202   }
203 
204   return (reinterpret_cast<int*>(CMSG_DATA(cmsg)))[0];
205 }
206 
207 /*
208  * Block forever, waiting for a debugger to connect to us.  Called from the
209  * JDWP thread.
210  *
211  * This needs to un-block and return "false" if the VM is shutting down.  It
212  * should return "true" when it successfully accepts a connection.
213  */
Accept()214 bool JdwpAdbState::Accept() {
215   int retryCount = 0;
216 
217   /* first, ensure that we get a connection to the ADB daemon */
218 
219  retry:
220   if (IsDown()) {
221     return false;
222   }
223 
224   if (ControlSock() == -1) {
225     int        sleep_ms     = 500;
226     const int  sleep_max_ms = 2*1000;
227 
228     int sock = socket(AF_UNIX, SOCK_SEQPACKET, 0);
229     if (sock < 0) {
230       PLOG(ERROR) << "Could not create ADB control socket";
231       return false;
232     }
233     struct timeval timeout;
234     timeout.tv_sec = kControlSockSendTimeout;
235     timeout.tv_usec = 0;
236     setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
237     {
238       MutexLock mu(Thread::Current(), state_lock_);
239       control_sock_ = sock;
240       if (shutting_down_) {
241         return false;
242       }
243       if (!MakePipe()) {
244         return false;
245       }
246     }
247 
248     int32_t pid = getpid();
249 
250     for (;;) {
251       /*
252        * If adbd isn't running, because USB debugging was disabled or
253        * perhaps the system is restarting it for "adb root", the
254        * connect() will fail.  We loop here forever waiting for it
255        * to come back.
256        *
257        * Waking up and polling every couple of seconds is generally a
258        * bad thing to do, but we only do this if the application is
259        * debuggable *and* adbd isn't running.  Still, for the sake
260        * of battery life, we should consider timing out and giving
261        * up after a few minutes in case somebody ships an app with
262        * the debuggable flag set.
263        */
264       int ret = connect(ControlSock(), &control_addr_.controlAddrPlain, control_addr_len_);
265       if (!ret) {
266         int control_sock = ControlSock();
267 #ifdef ART_TARGET_ANDROID
268         if (control_sock < 0 || !socket_peer_is_trusted(control_sock)) {
269           if (control_sock >= 0 && shutdown(control_sock, SHUT_RDWR)) {
270             PLOG(ERROR) << "trouble shutting down socket";
271           }
272           return false;
273         }
274 #endif
275 
276         /* now try to send our pid to the ADB daemon */
277         ret = TEMP_FAILURE_RETRY(send(control_sock, &pid, sizeof(pid), 0));
278         if (ret == sizeof(pid)) {
279           VLOG(jdwp) << "PID " << pid << " sent to ADB";
280           break;
281         }
282 
283         PLOG(ERROR) << "Weird, can't send JDWP process pid to ADB";
284         return false;
285       }
286       if (VLOG_IS_ON(jdwp)) {
287         PLOG(ERROR) << "Can't connect to ADB control socket";
288       }
289 
290       usleep(sleep_ms * 1000);
291 
292       sleep_ms += (sleep_ms >> 1);
293       if (sleep_ms > sleep_max_ms) {
294         sleep_ms = sleep_max_ms;
295       }
296       if (IsDown()) {
297         return false;
298       }
299     }
300   }
301 
302   VLOG(jdwp) << "trying to receive file descriptor from ADB";
303   /* now we can receive a client file descriptor */
304   int sock = ReceiveClientFd();
305   {
306     MutexLock mu(Thread::Current(), state_lock_);
307     clientSock = sock;
308     if (shutting_down_) {
309       return false;       // suppress logs and additional activity
310     }
311   }
312   if (clientSock == -1) {
313     if (++retryCount > 5) {
314       LOG(ERROR) << "adb connection max retries exceeded";
315       return false;
316     }
317     goto retry;
318   } else {
319     VLOG(jdwp) << "received file descriptor " << clientSock << " from ADB";
320     SetAwaitingHandshake(true);
321     input_count_ = 0;
322     return true;
323   }
324 }
325 
326 /*
327  * Process incoming data.  If no data is available, this will block until
328  * some arrives.
329  *
330  * If we get a full packet, handle it.
331  *
332  * To take some of the mystery out of life, we want to reject incoming
333  * connections if we already have a debugger attached.  If we don't, the
334  * debugger will just mysteriously hang until it times out.  We could just
335  * close the listen socket, but there's a good chance we won't be able to
336  * bind to the same port again, which would confuse utilities.
337  *
338  * Returns "false" on error (indicating that the connection has been severed),
339  * "true" if things are still okay.
340  */
ProcessIncoming()341 bool JdwpAdbState::ProcessIncoming() {
342   int readCount;
343 
344   CHECK_NE(clientSock, -1);
345 
346   if (!HaveFullPacket()) {
347     /* read some more, looping until we have data */
348     errno = 0;
349     while (1) {
350       int selCount;
351       fd_set readfds;
352       int maxfd = -1;
353       int fd;
354 
355       FD_ZERO(&readfds);
356 
357       /* configure fds; note these may get zapped by another thread */
358       fd = ControlSock();
359       if (fd >= 0) {
360         FD_SET(fd, &readfds);
361         if (maxfd < fd) {
362           maxfd = fd;
363         }
364       }
365       fd = clientSock;
366       if (fd >= 0) {
367         FD_SET(fd, &readfds);
368         if (maxfd < fd) {
369           maxfd = fd;
370         }
371       }
372       fd = wake_pipe_[0];
373       if (fd >= 0) {
374         FD_SET(fd, &readfds);
375         if (maxfd < fd) {
376           maxfd = fd;
377         }
378       } else {
379         LOG(INFO) << "NOTE: entering select w/o wakepipe";
380       }
381 
382       if (maxfd < 0) {
383         VLOG(jdwp) << "+++ all fds are closed";
384         return false;
385       }
386 
387       /*
388        * Select blocks until it sees activity on the file descriptors.
389        * Closing the local file descriptor does not count as activity,
390        * so we can't rely on that to wake us up (it works for read()
391        * and accept(), but not select()).
392        *
393        * We can do one of three things: (1) send a signal and catch
394        * EINTR, (2) open an additional fd ("wake pipe") and write to
395        * it when it's time to exit, or (3) time out periodically and
396        * re-issue the select.  We're currently using #2, as it's more
397        * reliable than #1 and generally better than #3.  Wastes two fds.
398        */
399       selCount = select(maxfd + 1, &readfds, nullptr, nullptr, nullptr);
400       if (selCount < 0) {
401         if (errno == EINTR) {
402           continue;
403         }
404         PLOG(ERROR) << "select failed";
405         goto fail;
406       }
407 
408       if (wake_pipe_[0] >= 0 && FD_ISSET(wake_pipe_[0], &readfds)) {
409         VLOG(jdwp) << "Got wake-up signal, bailing out of select";
410         goto fail;
411       }
412       int control_sock = ControlSock();
413       if (control_sock >= 0 && FD_ISSET(control_sock, &readfds)) {
414         int  sock = ReceiveClientFd();
415         if (sock >= 0) {
416           LOG(INFO) << "Ignoring second debugger -- accepting and dropping";
417           close(sock);
418         } else {
419           CHECK_EQ(ControlSock(), -1);
420           /*
421            * Remote side most likely went away, so our next read
422            * on clientSock will fail and throw us out of the loop.
423            */
424         }
425       }
426       if (clientSock >= 0 && FD_ISSET(clientSock, &readfds)) {
427         readCount = read(clientSock, input_buffer_ + input_count_, sizeof(input_buffer_) - input_count_);
428         if (readCount < 0) {
429           /* read failed */
430           if (errno != EINTR) {
431             goto fail;
432           }
433           VLOG(jdwp) << "+++ EINTR hit";
434           return true;
435         } else if (readCount == 0) {
436           /* EOF hit -- far end went away */
437           VLOG(jdwp) << "+++ peer disconnected";
438           goto fail;
439         } else {
440           break;
441         }
442       }
443     }
444 
445     input_count_ += readCount;
446     if (!HaveFullPacket()) {
447       return true;        /* still not there yet */
448     }
449   }
450 
451   /*
452    * Special-case the initial handshake.  For some bizarre reason we're
453    * expected to emulate bad tty settings by echoing the request back
454    * exactly as it was sent.  Note the handshake is always initiated by
455    * the debugger, no matter who connects to whom.
456    *
457    * Other than this one case, the protocol [claims to be] stateless.
458    */
459   if (IsAwaitingHandshake()) {
460     if (memcmp(input_buffer_, kMagicHandshake, kMagicHandshakeLen) != 0) {
461       LOG(ERROR) << StringPrintf("ERROR: bad handshake '%.14s'", input_buffer_);
462       goto fail;
463     }
464 
465     errno = 0;
466     int cc = TEMP_FAILURE_RETRY(write(clientSock, input_buffer_, kMagicHandshakeLen));
467     if (cc != kMagicHandshakeLen) {
468       PLOG(ERROR) << "Failed writing handshake bytes (" << cc << " of " << kMagicHandshakeLen << ")";
469       goto fail;
470     }
471 
472     ConsumeBytes(kMagicHandshakeLen);
473     SetAwaitingHandshake(false);
474     VLOG(jdwp) << "+++ handshake complete";
475     return true;
476   }
477 
478   /*
479    * Handle this packet.
480    */
481   return state_->HandlePacket();
482 
483  fail:
484   Close();
485   return false;
486 }
487 
488 }  // namespace JDWP
489 
490 }  // namespace art
491