/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.bluetooth; import android.annotation.FlaggedApi; import android.annotation.RequiresNoPermission; import android.annotation.RequiresPermission; import android.annotation.SystemApi; import android.bluetooth.annotations.RequiresBluetoothConnectPermission; import android.compat.annotation.UnsupportedAppUsage; import android.content.AttributionSource; import android.net.LocalSocket; import android.os.Build; import android.os.ParcelFileDescriptor; import android.os.ParcelUuid; import android.os.RemoteException; import android.util.Log; import com.android.bluetooth.flags.Flags; import java.io.Closeable; import java.io.FileDescriptor; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import java.util.Locale; import java.util.UUID; /** * A connected or connecting Bluetooth socket. * *
The interface for Bluetooth Sockets is similar to that of TCP sockets: {@link java.net.Socket} * and {@link java.net.ServerSocket}. On the server side, use a {@link BluetoothServerSocket} to * create a listening server socket. When a connection is accepted by the {@link * BluetoothServerSocket}, it will return a new {@link BluetoothSocket} to manage the connection. On * the client side, use a single {@link BluetoothSocket} to both initiate an outgoing connection and * to manage the connection. * *
The most common type of Bluetooth socket is RFCOMM, which is the type supported by the Android * APIs. RFCOMM is a connection-oriented, streaming transport over Bluetooth. It is also known as * the Serial Port Profile (SPP). * *
To create a {@link BluetoothSocket} for connecting to a known device, use {@link * BluetoothDevice#createRfcommSocketToServiceRecord * BluetoothDevice.createRfcommSocketToServiceRecord()}. Then call {@link #connect()} to attempt a * connection to the remote device. This call will block until a connection is established or the * connection fails. * *
To create a {@link BluetoothSocket} as a server (or "host"), see the {@link * BluetoothServerSocket} documentation. * *
Once the socket is connected, whether initiated as a client or accepted as a server, open the * IO streams by calling {@link #getInputStream} and {@link #getOutputStream} in order to retrieve * {@link java.io.InputStream} and {@link java.io.OutputStream} objects, respectively, which are * automatically connected to the socket. * *
{@link BluetoothSocket} is thread safe. In particular, {@link #close} will always immediately * abort ongoing operations and close the socket. * *
For more information about using Bluetooth, read the Bluetooth developer guide.
The socket should already be connected in this case, so {@link #connect()} should not be * called. * * @param pfd is the {@link ParcelFileDescriptor} for an already connected BluetoothSocket * @param device is the remote {@link BluetoothDevice} that this socket is connected to * @param uuid is the service ID that this RFCOMM connection is using * @throws IOException if socket creation fails. */ /*package*/ static BluetoothSocket createSocketFromOpenFd( ParcelFileDescriptor pfd, BluetoothDevice device, ParcelUuid uuid) throws IOException { BluetoothSocket bluetoothSocket = new BluetoothSocket(TYPE_RFCOMM, true, true, device, -1, uuid); bluetoothSocket.mPfd = pfd; bluetoothSocket.mSocket = new LocalSocket(pfd.getFileDescriptor()); bluetoothSocket.mSocketIS = bluetoothSocket.mSocket.getInputStream(); bluetoothSocket.mSocketOS = bluetoothSocket.mSocket.getOutputStream(); bluetoothSocket.mSocketState = SocketState.CONNECTED; return bluetoothSocket; } private BluetoothSocket(BluetoothSocket s) { if (VDBG) Log.d(TAG, "Creating new Private BluetoothSocket of type: " + s.mType); mUuid = s.mUuid; mType = s.mType; mAuth = s.mAuth; mEncrypt = s.mEncrypt; mPort = s.mPort; mInputStream = new BluetoothInputStream(this); mOutputStream = new BluetoothOutputStream(this); mMaxRxPacketSize = s.mMaxRxPacketSize; mMaxTxPacketSize = s.mMaxTxPacketSize; mConnectionUuid = s.mConnectionUuid; mServiceName = s.mServiceName; mExcludeSdp = s.mExcludeSdp; mAuthMitm = s.mAuthMitm; mMin16DigitPin = s.mMin16DigitPin; mSocketCreationTimeNanos = s.mSocketCreationTimeNanos; mSocketCreationLatencyNanos = s.mSocketCreationLatencyNanos; } private BluetoothSocket acceptSocket(String remoteAddr) throws IOException { BluetoothSocket as = new BluetoothSocket(this); as.mSocketState = SocketState.CONNECTED; FileDescriptor[] fds = mSocket.getAncillaryFileDescriptors(); if (DBG) Log.d(TAG, "acceptSocket: socket fd passed by stack fds:" + Arrays.toString(fds)); if (fds == null || fds.length != 1) { Log.e(TAG, "socket fd passed from stack failed, fds: " + Arrays.toString(fds)); as.close(); throw new IOException("bt socket accept failed"); } as.mPfd = ParcelFileDescriptor.dup(fds[0]); as.mSocket = new LocalSocket(fds[0]); as.mSocketIS = as.mSocket.getInputStream(); as.mSocketOS = as.mSocket.getOutputStream(); as.mAddress = remoteAddr; as.mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(remoteAddr); return as; } /** @hide */ @Override @SuppressWarnings("Finalize") // TODO(b/314811467) protected void finalize() throws Throwable { try { close(); } finally { super.finalize(); } } private int getSecurityFlags() { int flags = 0; if (mAuth) { flags |= SEC_FLAG_AUTH; } if (mEncrypt) { flags |= SEC_FLAG_ENCRYPT; } if (mExcludeSdp) { flags |= BTSOCK_FLAG_NO_SDP; } if (mAuthMitm) { flags |= SEC_FLAG_AUTH_MITM; } if (mMin16DigitPin) { flags |= SEC_FLAG_AUTH_16_DIGIT; } return flags; } /** * Get the remote device this socket is connecting, or connected, to. * * @return remote device */ @RequiresNoPermission public BluetoothDevice getRemoteDevice() { return mDevice; } /** * Get the input stream associated with this socket. * *
The input stream will be returned even if the socket is not yet connected, but operations * on that stream will throw IOException until the associated socket is connected. * * @return InputStream */ @RequiresNoPermission public InputStream getInputStream() throws IOException { return mInputStream; } /** * Get the output stream associated with this socket. * *
The output stream will be returned even if the socket is not yet connected, but operations * on that stream will throw IOException until the associated socket is connected. * * @return OutputStream */ @RequiresNoPermission public OutputStream getOutputStream() throws IOException { return mOutputStream; } /** * Get the connection status of this socket, ie, whether there is an active connection with * remote device. * * @return true if connected false if not connected */ @RequiresNoPermission public boolean isConnected() { return mSocketState == SocketState.CONNECTED; } /*package*/ void setServiceName(String name) { mServiceName = name; } /*package*/ boolean isAuth() { return mAuth; } /** * Attempt to connect to a remote device. * *
This method will block until a connection is made or the connection fails. If this method * returns without an exception then this socket is now connected. * *
Creating new connections to remote Bluetooth devices should not be attempted while device * discovery is in progress. Device discovery is a heavyweight procedure on the Bluetooth * adapter and will significantly slow a device connection. Use {@link * BluetoothAdapter#cancelDiscovery()} to cancel an ongoing discovery. Discovery is not managed * by the Activity, but is run as a system service, so an application should always call {@link * BluetoothAdapter#cancelDiscovery()} even if it did not directly request a discovery, just to * be sure. * *
{@link #close} can be used to abort this call from another thread. * * @throws BluetoothSocketException in case of failure, with the corresponding error code. * @throws IOException for other errors (eg: InputStream read failures etc.). */ @RequiresBluetoothConnectPermission @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) public void connect() throws IOException { IBluetooth bluetoothProxy = BluetoothAdapter.getDefaultAdapter().getBluetoothService(); long socketConnectionTimeNanos = System.nanoTime(); if (bluetoothProxy == null) { throw new BluetoothSocketException(BluetoothSocketException.BLUETOOTH_OFF_FAILURE); } try { if (mDevice == null) { throw new BluetoothSocketException(BluetoothSocketException.NULL_DEVICE); } if (mSocketState == SocketState.CLOSED) { throw new BluetoothSocketException(BluetoothSocketException.SOCKET_CLOSED); } IBluetoothSocketManager socketManager = bluetoothProxy.getSocketManager(); if (socketManager == null) { throw new BluetoothSocketException(BluetoothSocketException.SOCKET_MANAGER_FAILURE); } mPfd = socketManager.connectSocket(mDevice, mType, mUuid, mPort, getSecurityFlags()); synchronized (this) { Log.i(TAG, "connect(), SocketState: " + mSocketState + ", mPfd: " + mPfd); if (mSocketState == SocketState.CLOSED) { throw new BluetoothSocketException(BluetoothSocketException.SOCKET_CLOSED); } if (mPfd == null) { throw new BluetoothSocketException( BluetoothSocketException.UNIX_FILE_SOCKET_CREATION_FAILURE); } FileDescriptor fd = mPfd.getFileDescriptor(); mSocket = new LocalSocket(fd); mSocketIS = mSocket.getInputStream(); mSocketOS = mSocket.getOutputStream(); } int channel = readInt(mSocketIS); if (channel == 0) { int errCode = (int) mSocketIS.read(); throw new BluetoothSocketException(errCode); } if (channel < 0) { throw new BluetoothSocketException( BluetoothSocketException.SOCKET_CONNECTION_FAILURE); } mPort = channel; waitSocketSignal(mSocketIS); synchronized (this) { if (mSocketState == SocketState.CLOSED) { throw new BluetoothSocketException(BluetoothSocketException.SOCKET_CLOSED); } mSocketState = SocketState.CONNECTED; Log.i(TAG, "connect(), socket connected. mPort=" + mPort); } } catch (BluetoothSocketException e) { SocketMetrics.logSocketConnect( e.getErrorCode(), socketConnectionTimeNanos, mType, mDevice, mPort, mAuth, mSocketCreationTimeNanos, mSocketCreationLatencyNanos); throw e; } catch (RemoteException e) { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); SocketMetrics.logSocketConnect( BluetoothSocketException.RPC_FAILURE, socketConnectionTimeNanos, mType, mDevice, mPort, mAuth, mSocketCreationTimeNanos, mSocketCreationLatencyNanos); throw new BluetoothSocketException( BluetoothSocketException.RPC_FAILURE, "unable to send RPC: " + e.getMessage()); } SocketMetrics.logSocketConnect( SocketMetrics.SOCKET_NO_ERROR, socketConnectionTimeNanos, mType, mDevice, mPort, mAuth, mSocketCreationTimeNanos, mSocketCreationLatencyNanos); } /** * Currently returns unix errno instead of throwing IOException, so that BluetoothAdapter can * check the error code for EADDRINUSE */ @RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT) /*package*/ int bindListen() { int ret; if (mSocketState == SocketState.CLOSED) return EBADFD; IBluetooth bluetoothProxy = BluetoothAdapter.getDefaultAdapter().getBluetoothService(); if (bluetoothProxy == null) { Log.e(TAG, "bindListen fail, reason: bluetooth is off"); return -1; } try { if (DBG) Log.d(TAG, "bindListen(): mPort=" + mPort + ", mType=" + mType); IBluetoothSocketManager socketManager = bluetoothProxy.getSocketManager(); if (socketManager == null) { Log.e(TAG, "bindListen() bt get socket manager failed"); return -1; } mPfd = socketManager.createSocketChannel( mType, mServiceName, mUuid, mPort, getSecurityFlags()); } catch (RemoteException e) { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); return -1; } // read out port number try { synchronized (this) { if (DBG) { Log.d(TAG, "bindListen(), SocketState: " + mSocketState + ", mPfd: " + mPfd); } if (mSocketState != SocketState.INIT) return EBADFD; if (mPfd == null) return -1; FileDescriptor fd = mPfd.getFileDescriptor(); if (fd == null) { Log.e(TAG, "bindListen(), null file descriptor"); return -1; } if (DBG) Log.d(TAG, "bindListen(), Create LocalSocket"); mSocket = new LocalSocket(fd); if (DBG) Log.d(TAG, "bindListen(), new LocalSocket.getInputStream()"); mSocketIS = mSocket.getInputStream(); mSocketOS = mSocket.getOutputStream(); } if (DBG) Log.d(TAG, "bindListen(), readInt mSocketIS: " + mSocketIS); int channel = readInt(mSocketIS); synchronized (this) { if (mSocketState == SocketState.INIT) { mSocketState = SocketState.LISTENING; } } if (DBG) Log.d(TAG, "bindListen(): channel=" + channel + ", mPort=" + mPort); if (mPort <= -1) { mPort = channel; } // else ASSERT(mPort == channel) ret = 0; } catch (IOException e) { if (mPfd != null) { try { mPfd.close(); } catch (IOException e1) { Log.e(TAG, "bindListen, close mPfd: " + e1); } mPfd = null; } Log.e(TAG, "bindListen, fail to get port number, exception: " + e); return -1; } return ret; } /*package*/ BluetoothSocket accept(int timeout) throws IOException { BluetoothSocket acceptedSocket; if (mSocketState != SocketState.LISTENING) { throw new IOException("bt socket is not in listen state"); } Log.d(TAG, "accept(), timeout (ms):" + timeout); if (timeout > 0) { mSocket.setSoTimeout(timeout); } String RemoteAddr = waitSocketSignal(mSocketIS); if (timeout > 0) { mSocket.setSoTimeout(0); } synchronized (this) { if (mSocketState != SocketState.LISTENING) { throw new IOException("bt socket is not in listen state"); } acceptedSocket = acceptSocket(RemoteAddr); // quick drop the reference of the file handle } return acceptedSocket; } /*package*/ int available() throws IOException { if (VDBG) Log.d(TAG, "available: " + mSocketIS); return mSocketIS.available(); } /*package*/ int read(byte[] b, int offset, int length) throws IOException { int ret = 0; if (VDBG) Log.d(TAG, "read in: " + mSocketIS + " len: " + length); if ((mType == TYPE_L2CAP) || (mType == TYPE_L2CAP_LE)) { int bytesToRead = length; if (VDBG) { Log.v( TAG, "l2cap: read(): offset: " + offset + " length:" + length + "mL2capBuffer= " + mL2capBuffer); } if (mL2capBuffer == null) { createL2capRxBuffer(); } if (mL2capBuffer.remaining() == 0) { if (VDBG) Log.v(TAG, "l2cap buffer empty, refilling..."); if (fillL2capRxBuffer() == -1) { return -1; } } if (bytesToRead > mL2capBuffer.remaining()) { bytesToRead = mL2capBuffer.remaining(); } if (VDBG) { Log.v(TAG, "get(): offset: " + offset + " bytesToRead: " + bytesToRead); } mL2capBuffer.get(b, offset, bytesToRead); ret = bytesToRead; } else { if (VDBG) Log.v(TAG, "default: read(): offset: " + offset + " length:" + length); ret = mSocketIS.read(b, offset, length); } if (ret < 0) { throw new IOException("bt socket closed, read return: " + ret); } if (VDBG) Log.d(TAG, "read out: " + mSocketIS + " ret: " + ret); return ret; } /*package*/ int write(byte[] b, int offset, int length) throws IOException { // TODO: Since bindings can exist between the SDU size and the // protocol, we might need to throw an exception instead of just // splitting the write into multiple smaller writes. // Rfcomm uses dynamic allocation, and should not have any bindings // to the actual message length. if (VDBG) Log.d(TAG, "write: " + mSocketOS + " length: " + length); if ((mType == TYPE_L2CAP) || (mType == TYPE_L2CAP_LE)) { if (length <= mMaxTxPacketSize) { mSocketOS.write(b, offset, length); } else { if (DBG) { Log.w( TAG, "WARNING: Write buffer larger than L2CAP packet size!\n" + "Packet will be divided into SDU packets of size " + mMaxTxPacketSize); } int tmpOffset = offset; int bytesToWrite = length; while (bytesToWrite > 0) { int tmpLength = (bytesToWrite > mMaxTxPacketSize) ? mMaxTxPacketSize : bytesToWrite; mSocketOS.write(b, tmpOffset, tmpLength); tmpOffset += tmpLength; bytesToWrite -= tmpLength; } } } else { mSocketOS.write(b, offset, length); } // There is no good way to confirm since the entire process is asynchronous anyway if (VDBG) Log.d(TAG, "write out: " + mSocketOS + " length: " + length); return length; } @Override public void close() throws IOException { Log.d( TAG, "close() this: " + this + ", channel: " + mPort + ", mSocketIS: " + mSocketIS + ", mSocketOS: " + mSocketOS + ", mSocket: " + mSocket + ", mSocketState: " + mSocketState); if (mSocketState == SocketState.CLOSED) { return; } else { synchronized (this) { if (mSocketState == SocketState.CLOSED) { return; } mSocketState = SocketState.CLOSED; if (mSocket != null) { if (DBG) Log.d(TAG, "Closing mSocket: " + mSocket); mSocket.shutdownInput(); mSocket.shutdownOutput(); mSocket.close(); mSocket = null; } if (mPfd != null) { mPfd.close(); mPfd = null; } mConnectionUuid = null; } } } /*package */ void removeChannel() {} /*package */ int getPort() { return mPort; } /*package */ long getSocketCreationTime() { return mSocketCreationTimeNanos; } /** * Get the maximum supported Transmit packet size for the underlying transport. Use this to * optimize the writes done to the output socket, to avoid sending half full packets. * * @return the maximum supported Transmit packet size for the underlying transport. */ @RequiresNoPermission public int getMaxTransmitPacketSize() { return mMaxTxPacketSize; } /** * Get the maximum supported Receive packet size for the underlying transport. Use this to * optimize the reads done on the input stream, as any call to read will return a maximum of * this amount of bytes - or for some transports a multiple of this value. * * @return the maximum supported Receive packet size for the underlying transport. */ @RequiresNoPermission public int getMaxReceivePacketSize() { return mMaxRxPacketSize; } /** * Get the type of the underlying connection. * * @return one of {@link #TYPE_RFCOMM}, {@link #TYPE_SCO} or {@link #TYPE_L2CAP} */ @RequiresNoPermission public int getConnectionType() { if (mType == TYPE_L2CAP_LE) { // Treat the LE CoC to be the same type as L2CAP. return TYPE_L2CAP; } return mType; } /** * Change if a SDP entry should be automatically created. Must be called before calling .bind, * for the call to have any effect. * * @param excludeSdp *