2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * JDWP TCP socket network code.
19 #include "jdwp/JdwpPriv.h"
20 #include "jdwp/JdwpHandler.h"
28 #include <sys/types.h>
29 #include <sys/socket.h>
30 #include <netinet/in.h>
31 #include <netinet/tcp.h>
32 #include <arpa/inet.h>
35 #define kBasePort 8000
38 #define kInputBufferSize 8192
40 #define kMagicHandshake "JDWP-Handshake"
41 #define kMagicHandshakeLen (sizeof(kMagicHandshake)-1)
44 static void netShutdown(JdwpNetState* state);
45 static void netFree(JdwpNetState* state);
51 * We only talk to one debugger at a time.
53 struct JdwpNetState : public JdwpNetStateBase {
55 int listenSock; /* listen for connection from debugger */
56 int wakePipe[2]; /* break out of select */
58 struct in_addr remoteAddr;
59 unsigned short remotePort;
61 bool awaitingHandshake; /* waiting for "JDWP-Handshake" */
63 /* pending data from the network; would be more efficient as circular buf */
64 unsigned char inputBuffer[kInputBufferSize];
74 awaitingHandshake = false;
80 static JdwpNetState* netStartup(short port);
83 * Set up some stuff for transport=dt_socket.
85 static bool prepareSocket(JdwpState* state, const JdwpStartupParams* pParams)
89 if (pParams->server) {
90 if (pParams->port != 0) {
91 /* try only the specified port */
93 state->netState = netStartup(port);
95 /* scan through a range of ports, binding to the first available */
96 for (port = kBasePort; port <= kMaxPort; port++) {
97 state->netState = netStartup(port);
98 if (state->netState != NULL)
102 if (state->netState == NULL) {
103 ALOGE("JDWP net startup failed (req port=%d)", pParams->port);
107 port = pParams->port; // used in a debug msg later
108 state->netState = netStartup(-1);
111 if (pParams->suspend)
112 ALOGI("JDWP will wait for debugger on port %d", port);
114 ALOGD("JDWP will %s on port %d",
115 pParams->server ? "listen" : "connect", port);
122 * Are we still waiting for the handshake string?
124 static bool awaitingHandshake(JdwpState* state)
126 return state->netState->awaitingHandshake;
130 * Initialize JDWP stuff.
132 * Allocates a new state structure. If "port" is non-negative, this also
133 * tries to bind to a listen port. If "port" is less than zero, we assume
134 * we're preparing for an outbound connection, and return without binding
137 * This may be called several times if we're probing for a port.
139 * Returns 0 on success.
141 static JdwpNetState* netStartup(short port)
144 JdwpNetState* netState = new JdwpNetState;
151 netState->listenSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
152 if (netState->listenSock < 0) {
153 ALOGE("Socket create failed: %s", strerror(errno));
157 /* allow immediate re-use */
158 if (setsockopt(netState->listenSock, SOL_SOCKET, SO_REUSEADDR, &one,
161 ALOGE("setsockopt(SO_REUSEADDR) failed: %s", strerror(errno));
166 struct sockaddr_in addrInet;
167 struct sockaddr addrPlain;
169 addr.addrInet.sin_family = AF_INET;
170 addr.addrInet.sin_port = htons(port);
171 inet_aton("127.0.0.1", &addr.addrInet.sin_addr);
173 if (bind(netState->listenSock, &addr.addrPlain, sizeof(addr)) != 0) {
174 ALOGV("attempt to bind to port %u failed: %s", port, strerror(errno));
178 netState->listenPort = port;
179 LOGVV("+++ bound to port %d", netState->listenPort);
181 if (listen(netState->listenSock, 5) != 0) {
182 ALOGE("Listen failed: %s", strerror(errno));
189 netShutdown(netState);
195 * Shut down JDWP listener. Don't free state.
197 * Note that "netState" may be partially initialized if "startup" failed.
199 * This may be called from a non-JDWP thread as part of shutting the
202 * (This is currently called several times during startup as we probe
205 static void netShutdown(JdwpNetState* netState)
207 if (netState == NULL)
210 int listenSock = netState->listenSock;
211 int clientSock = netState->clientSock;
213 /* clear these out so it doesn't wake up and try to reuse them */
214 netState->listenSock = netState->clientSock = -1;
216 /* "shutdown" dislodges blocking read() and accept() calls */
217 if (listenSock >= 0) {
218 shutdown(listenSock, SHUT_RDWR);
221 if (clientSock >= 0) {
222 shutdown(clientSock, SHUT_RDWR);
226 /* if we might be sitting in select, kick us loose */
227 if (netState->wakePipe[1] >= 0) {
228 ALOGV("+++ writing to wakePipe");
229 TEMP_FAILURE_RETRY(write(netState->wakePipe[1], "", 1));
232 static void netShutdownExtern(JdwpState* state)
234 netShutdown(state->netState);
240 * Call this after shutting the network down with netShutdown().
242 static void netFree(JdwpNetState* netState)
244 if (netState == NULL)
246 assert(netState->listenSock == -1);
247 assert(netState->clientSock == -1);
249 if (netState->wakePipe[0] >= 0) {
250 close(netState->wakePipe[0]);
251 netState->wakePipe[0] = -1;
253 if (netState->wakePipe[1] >= 0) {
254 close(netState->wakePipe[1]);
255 netState->wakePipe[1] = -1;
260 static void netFreeExtern(JdwpState* state)
262 netFree(state->netState);
266 * Returns "true" if we're connected to a debugger.
268 static bool isConnected(JdwpState* state)
270 return (state->netState != NULL &&
271 state->netState->clientSock >= 0);
275 * Returns "true" if the fd is ready, "false" if not.
278 static bool isFdReadable(int sock)
285 FD_SET(sock, &readfds);
289 count = select(sock+1, &readfds, NULL, NULL, &tv);
293 if (FD_ISSET(sock, &readfds)) /* make sure it's our fd */
296 ALOGE("WEIRD: odd behavior in select (count=%d)", count);
303 * Check to see if we have a pending connection from the debugger.
305 * Returns true on success (meaning a connection is available).
307 static bool checkConnection(JdwpState* state)
309 JdwpNetState* netState = state->netState;
311 assert(netState->listenSock >= 0);
312 /* not expecting to be called when debugger is actively connected */
313 assert(netState->clientSock < 0);
315 if (!isFdReadable(netState->listenSock))
322 * Disable the TCP Nagle algorithm, which delays transmission of outbound
323 * packets until the previous transmissions have been acked. JDWP does a
324 * lot of back-and-forth with small packets, so this may help.
326 static int setNoDelay(int fd)
330 cc = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
336 * Accept a connection. This will block waiting for somebody to show up.
337 * If that's not desirable, use checkConnection() to make sure something
340 static bool acceptConnection(JdwpState* state)
342 JdwpNetState* netState = state->netState;
344 struct sockaddr_in addrInet;
345 struct sockaddr addrPlain;
350 if (netState->listenSock < 0)
351 return false; /* you're not listening! */
353 assert(netState->clientSock < 0); /* must not already be talking */
355 addrlen = sizeof(addr);
357 sock = accept(netState->listenSock, &addr.addrPlain, &addrlen);
358 if (sock < 0 && errno != EINTR) {
359 // When we call shutdown() on the socket, accept() returns with
360 // EINVAL. Don't gripe about it.
362 LOGVV("accept failed: %s", strerror(errno));
364 ALOGE("accept failed: %s", strerror(errno));
369 netState->remoteAddr = addr.addrInet.sin_addr;
370 netState->remotePort = ntohs(addr.addrInet.sin_port);
371 ALOGV("+++ accepted connection from %s:%u",
372 inet_ntoa(netState->remoteAddr), netState->remotePort);
374 netState->clientSock = sock;
375 netState->awaitingHandshake = true;
376 netState->inputCount = 0;
378 ALOGV("Setting TCP_NODELAY on accepted socket");
379 setNoDelay(netState->clientSock);
381 if (pipe(netState->wakePipe) < 0) {
382 ALOGE("pipe failed");
390 * Create a connection to a waiting debugger.
392 static bool establishConnection(JdwpState* state)
395 struct sockaddr_in addrInet;
396 struct sockaddr addrPlain;
398 struct hostent* pEntry;
401 assert(state != NULL && state->netState != NULL);
402 assert(!state->params.server);
403 assert(state->params.host[0] != '\0');
404 assert(state->params.port != 0);
407 * Start by resolving the host name.
409 //#undef HAVE_GETHOSTBYNAME_R
410 //#warning "forcing non-R"
411 #ifdef HAVE_GETHOSTBYNAME_R
414 int cc = gethostbyname_r(state->params.host, &he, auxBuf, sizeof(auxBuf),
417 ALOGW("gethostbyname_r('%s') failed: %s",
418 state->params.host, strerror(errno));
424 pEntry = gethostbyname(state->params.host);
425 if (pEntry == NULL) {
426 ALOGW("gethostbyname('%s') failed: %s",
427 state->params.host, strerror(h_errno));
432 /* copy it out ASAP to minimize risk of multithreaded annoyances */
433 memcpy(&addr.addrInet.sin_addr, pEntry->h_addr, pEntry->h_length);
434 addr.addrInet.sin_family = pEntry->h_addrtype;
436 addr.addrInet.sin_port = htons(state->params.port);
438 ALOGI("Connecting out to '%s' %d",
439 inet_ntoa(addr.addrInet.sin_addr), ntohs(addr.addrInet.sin_port));
444 JdwpNetState* netState;
445 netState = state->netState;
446 netState->clientSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
447 if (netState->clientSock < 0) {
448 ALOGE("Unable to create socket: %s", strerror(errno));
455 if (connect(netState->clientSock, &addr.addrPlain, sizeof(addr)) != 0) {
456 ALOGE("Unable to connect to %s:%d: %s",
457 inet_ntoa(addr.addrInet.sin_addr), ntohs(addr.addrInet.sin_port),
459 close(netState->clientSock);
460 netState->clientSock = -1;
464 ALOGI("Connection established to %s (%s:%d)",
465 state->params.host, inet_ntoa(addr.addrInet.sin_addr),
466 ntohs(addr.addrInet.sin_port));
467 netState->awaitingHandshake = true;
468 netState->inputCount = 0;
470 setNoDelay(netState->clientSock);
472 if (pipe(netState->wakePipe) < 0) {
473 ALOGE("pipe failed");
481 * Close the connection to the debugger.
483 * Reset the state so we're ready to receive a new connection.
485 static void closeConnection(JdwpState* state)
487 JdwpNetState* netState;
489 assert(state != NULL && state->netState != NULL);
491 netState = state->netState;
492 if (netState->clientSock < 0)
495 ALOGV("+++ closed connection to %s:%u",
496 inet_ntoa(netState->remoteAddr), netState->remotePort);
498 close(netState->clientSock);
499 netState->clientSock = -1;
505 * Figure out if we have a full packet in the buffer.
507 static bool haveFullPacket(JdwpNetState* netState)
511 if (netState->awaitingHandshake)
512 return (netState->inputCount >= (int) kMagicHandshakeLen);
514 if (netState->inputCount < 4)
517 length = get4BE(netState->inputBuffer);
518 return (netState->inputCount >= length);
522 * Consume bytes from the buffer.
524 * This would be more efficient with a circular buffer. However, we're
525 * usually only going to find one packet, which is trivial to handle.
527 static void consumeBytes(JdwpNetState* netState, int count)
530 assert(count <= netState->inputCount);
532 if (count == netState->inputCount) {
533 netState->inputCount = 0;
537 memmove(netState->inputBuffer, netState->inputBuffer + count,
538 netState->inputCount - count);
539 netState->inputCount -= count;
543 * Dump the contents of a packet to stdout.
546 static void dumpPacket(const unsigned char* packetBuf)
548 const unsigned char* buf = packetBuf;
550 u1 flags, cmdSet, cmd;
557 length = read4BE(&buf);
560 if ((flags & kJDWPFlagReply) != 0) {
562 error = read2BE(&buf);
565 cmdSet = read1(&buf);
569 dataLen = length - (buf - packetBuf);
571 ALOGV("--- %s: dataLen=%u id=0x%08x flags=0x%02x cmd=%d/%d",
572 reply ? "reply" : "req",
573 dataLen, id, flags, cmdSet, cmd);
575 dvmPrintHexDumpDbg(buf, dataLen, LOG_TAG);
580 * Handle a packet. Returns "false" if we encounter a connection-fatal error.
582 static bool handlePacket(JdwpState* state)
584 JdwpNetState* netState = state->netState;
585 const unsigned char* buf = netState->inputBuffer;
588 u1 flags, cmdSet, cmd;
593 cmd = cmdSet = 0; // shut up gcc
595 /*dumpPacket(netState->inputBuffer);*/
597 length = read4BE(&buf);
600 if ((flags & kJDWPFlagReply) != 0) {
602 error = read2BE(&buf);
605 cmdSet = read1(&buf);
609 assert((int) length <= netState->inputCount);
610 dataLen = length - (buf - netState->inputBuffer);
613 ExpandBuf* pReply = expandBufAlloc();
619 dvmJdwpProcessRequest(state, &hdr, buf, dataLen, pReply);
620 if (expandBufGetLength(pReply) > 0) {
621 ssize_t cc = netState->writePacket(pReply);
623 if (cc != (ssize_t) expandBufGetLength(pReply)) {
624 ALOGE("Failed sending reply to debugger: %s", strerror(errno));
625 expandBufFree(pReply);
629 ALOGW("No reply created for set=%d cmd=%d", cmdSet, cmd);
631 expandBufFree(pReply);
639 consumeBytes(netState, length);
644 * Process incoming data. If no data is available, this will block until
647 * If we get a full packet, handle it.
649 * To take some of the mystery out of life, we want to reject incoming
650 * connections if we already have a debugger attached. If we don't, the
651 * debugger will just mysteriously hang until it times out. We could just
652 * close the listen socket, but there's a good chance we won't be able to
653 * bind to the same port again, which would confuse utilities.
655 * Returns "false" on error (indicating that the connection has been severed),
656 * "true" if things are still okay.
658 static bool processIncoming(JdwpState* state)
660 JdwpNetState* netState = state->netState;
663 assert(netState->clientSock >= 0);
665 if (!haveFullPacket(netState)) {
666 /* read some more, looping until we have data */
674 maxfd = netState->listenSock;
675 if (netState->clientSock > maxfd)
676 maxfd = netState->clientSock;
677 if (netState->wakePipe[0] > maxfd)
678 maxfd = netState->wakePipe[0];
681 ALOGV("+++ all fds are closed");
687 /* configure fds; note these may get zapped by another thread */
688 fd = netState->listenSock;
690 FD_SET(fd, &readfds);
691 fd = netState->clientSock;
693 FD_SET(fd, &readfds);
694 fd = netState->wakePipe[0];
696 FD_SET(fd, &readfds);
698 ALOGI("NOTE: entering select w/o wakepipe");
702 * Select blocks until it sees activity on the file descriptors.
703 * Closing the local file descriptor does not count as activity,
704 * so we can't rely on that to wake us up (it works for read()
705 * and accept(), but not select()).
707 * We can do one of three things: (1) send a signal and catch
708 * EINTR, (2) open an additional fd ("wakePipe") and write to
709 * it when it's time to exit, or (3) time out periodically and
710 * re-issue the select. We're currently using #2, as it's more
711 * reliable than #1 and generally better than #3. Wastes two fds.
713 selCount = select(maxfd+1, &readfds, NULL, NULL, NULL);
717 ALOGE("select failed: %s", strerror(errno));
721 if (netState->wakePipe[0] >= 0 &&
722 FD_ISSET(netState->wakePipe[0], &readfds))
724 if (netState->listenSock >= 0)
725 ALOGE("Exit wake set, but not exiting?");
727 ALOGD("Got wake-up signal, bailing out of select");
730 if (netState->listenSock >= 0 &&
731 FD_ISSET(netState->listenSock, &readfds))
733 ALOGI("Ignoring second debugger -- accepting and dropping");
735 struct sockaddr_in addrInet;
736 struct sockaddr addrPlain;
740 tmpSock = accept(netState->listenSock, &addr.addrPlain,
743 ALOGI("Weird -- accept failed");
747 if (netState->clientSock >= 0 &&
748 FD_ISSET(netState->clientSock, &readfds))
750 readCount = read(netState->clientSock,
751 netState->inputBuffer + netState->inputCount,
752 sizeof(netState->inputBuffer) - netState->inputCount);
757 ALOGD("+++ EINTR hit");
759 } else if (readCount == 0) {
760 /* EOF hit -- far end went away */
761 ALOGD("+++ peer disconnected");
768 netState->inputCount += readCount;
769 if (!haveFullPacket(netState))
770 return true; /* still not there yet */
774 * Special-case the initial handshake. For some bizarre reason we're
775 * expected to emulate bad tty settings by echoing the request back
776 * exactly as it was sent. Note the handshake is always initiated by
777 * the debugger, no matter who connects to whom.
779 * Other than this one case, the protocol [claims to be] stateless.
781 if (netState->awaitingHandshake) {
784 if (memcmp(netState->inputBuffer,
785 kMagicHandshake, kMagicHandshakeLen) != 0)
787 ALOGE("ERROR: bad handshake '%.14s'", netState->inputBuffer);
792 cc = TEMP_FAILURE_RETRY(write(netState->clientSock, netState->inputBuffer,
793 kMagicHandshakeLen));
794 if (cc != kMagicHandshakeLen) {
795 ALOGE("Failed writing handshake bytes: %s (%d of %d)",
796 strerror(errno), cc, (int) kMagicHandshakeLen);
800 consumeBytes(netState, kMagicHandshakeLen);
801 netState->awaitingHandshake = false;
802 ALOGV("+++ handshake complete");
807 * Handle this packet.
809 return handlePacket(state);
812 closeConnection(state);
819 * The entire packet must be sent with a single write() call to avoid
822 * Returns "true" if it was sent successfully.
824 static bool sendRequest(JdwpState* state, ExpandBuf* pReq)
826 JdwpNetState* netState = state->netState;
828 /*dumpPacket(expandBufGetBuffer(pReq));*/
829 if (netState->clientSock < 0) {
830 /* can happen with some DDMS events */
831 ALOGV("NOT sending request -- no debugger is attached");
836 ssize_t cc = netState->writePacket(pReq);
838 if (cc != (ssize_t) expandBufGetLength(pReq)) {
839 ALOGE("Failed sending req to debugger: %s (%d of %d)",
840 strerror(errno), (int) cc, (int) expandBufGetLength(pReq));
848 * Send a request that was split into multiple buffers.
850 * The entire packet must be sent with a single writev() call to avoid
853 * Returns "true" if it was sent successfully.
855 static bool sendBufferedRequest(JdwpState* state, const struct iovec* iov,
858 JdwpNetState* netState = state->netState;
860 if (netState->clientSock < 0) {
861 /* can happen with some DDMS events */
862 ALOGV("NOT sending request -- no debugger is attached");
868 for (i = 0; i < iovcnt; i++)
869 expected += iov[i].iov_len;
871 ssize_t actual = netState->writeBufferedPacket(iov, iovcnt);
873 if ((size_t)actual != expected) {
874 ALOGE("Failed sending b-req to debugger: %s (%d of %zu)",
875 strerror(errno), (int) actual, expected);
886 * We can't generally share the implementations with other transports,
887 * even if they're also socket-based, because our JdwpNetState will be
888 * different from theirs.
890 static const JdwpTransport socketTransport = {
907 const JdwpTransport* dvmJdwpSocketTransport()
909 return &socketTransport;