blob: e5b6ea192639eb75c2f8c94d09d816ed10b70731 [file] [log] [blame]
Nick Pelly53f441b2009-05-26 19:13:43 -07001/*
Zhihai Xua9cc57d2012-10-23 17:31:56 -07002 * Copyright (C) 2012 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.
Nick Pelly53f441b2009-05-26 19:13:43 -070015 */
16
17package android.bluetooth;
18
William Escande4b414a82024-07-19 15:47:05 -070019import static android.Manifest.permission.BLUETOOTH_CONNECT;
20import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
William Escande3f7cbce2024-08-02 11:08:35 -070021import static android.Manifest.permission.LOCAL_MAC_ADDRESS;
William Escande4b414a82024-07-19 15:47:05 -070022
Jayden Kim34602a42024-02-21 18:47:40 +000023import android.annotation.FlaggedApi;
Bhakthavatsala Raghavendraaf3a0172024-10-18 21:33:33 +000024import android.annotation.IntDef;
Bhakthavatsala Raghavendradcaace52024-10-25 22:29:01 +000025import android.annotation.NonNull;
Jeff Sharkey5ba8bfc2021-04-16 09:53:23 -060026import android.annotation.RequiresNoPermission;
Jeff Sharkey8f80e4a2021-04-02 08:06:09 -060027import android.annotation.RequiresPermission;
Jayden Kim34602a42024-02-21 18:47:40 +000028import android.annotation.SystemApi;
Jeff Sharkey5ba8bfc2021-04-16 09:53:23 -060029import android.bluetooth.annotations.RequiresBluetoothConnectPermission;
Artur Satayevd8fe38c2019-12-10 17:47:52 +000030import android.compat.annotation.UnsupportedAppUsage;
Jayden Kim34602a42024-02-21 18:47:40 +000031import android.content.AttributionSource;
Jack He910201b2017-08-22 16:06:54 -070032import android.net.LocalSocket;
Mathew Inwoodcba870b2020-10-27 11:47:29 +000033import android.os.Build;
zzyfab62db2012-04-03 19:48:32 -070034import android.os.ParcelFileDescriptor;
Jack He910201b2017-08-22 16:06:54 -070035import android.os.ParcelUuid;
Nick Pelly07b84cb2009-10-07 07:44:03 +020036import android.os.RemoteException;
37import android.util.Log;
38
Jayden Kim34602a42024-02-21 18:47:40 +000039import com.android.bluetooth.flags.Flags;
40
Nick Pelly53f441b2009-05-26 19:13:43 -070041import java.io.Closeable;
zzyfab62db2012-04-03 19:48:32 -070042import java.io.FileDescriptor;
Nick Pelly53f441b2009-05-26 19:13:43 -070043import java.io.IOException;
44import java.io.InputStream;
45import java.io.OutputStream;
Bhakthavatsala Raghavendraaf3a0172024-10-18 21:33:33 +000046import java.lang.annotation.Retention;
47import java.lang.annotation.RetentionPolicy;
Jack He910201b2017-08-22 16:06:54 -070048import java.nio.ByteBuffer;
49import java.nio.ByteOrder;
Andreas Gampe7b1e7402015-12-11 18:00:38 -080050import java.util.Arrays;
Jeff Sharkeyc27359e2013-06-11 14:13:09 -070051import java.util.Locale;
zzy30495702012-10-11 14:52:43 -070052import java.util.UUID;
Casper Bondec0a7c932015-04-09 09:24:48 +020053
Nick Pelly53f441b2009-05-26 19:13:43 -070054/**
Nick Pelly753da532009-08-19 11:00:00 -070055 * A connected or connecting Bluetooth socket.
Nick Pelly53f441b2009-05-26 19:13:43 -070056 *
David Duarteee52b7e2023-12-02 01:32:11 +000057 * <p>The interface for Bluetooth Sockets is similar to that of TCP sockets: {@link java.net.Socket}
58 * and {@link java.net.ServerSocket}. On the server side, use a {@link BluetoothServerSocket} to
59 * create a listening server socket. When a connection is accepted by the {@link
60 * BluetoothServerSocket}, it will return a new {@link BluetoothSocket} to manage the connection. On
61 * the client side, use a single {@link BluetoothSocket} to both initiate an outgoing connection and
62 * to manage the connection.
Nick Pelly53f441b2009-05-26 19:13:43 -070063 *
David Duarteee52b7e2023-12-02 01:32:11 +000064 * <p>The most common type of Bluetooth socket is RFCOMM, which is the type supported by the Android
65 * APIs. RFCOMM is a connection-oriented, streaming transport over Bluetooth. It is also known as
66 * the Serial Port Profile (SPP).
Nick Pelly53f441b2009-05-26 19:13:43 -070067 *
David Duarteee52b7e2023-12-02 01:32:11 +000068 * <p>To create a {@link BluetoothSocket} for connecting to a known device, use {@link
69 * BluetoothDevice#createRfcommSocketToServiceRecord
70 * BluetoothDevice.createRfcommSocketToServiceRecord()}. Then call {@link #connect()} to attempt a
71 * connection to the remote device. This call will block until a connection is established or the
72 * connection fails.
Nick Pelly753da532009-08-19 11:00:00 -070073 *
David Duarteee52b7e2023-12-02 01:32:11 +000074 * <p>To create a {@link BluetoothSocket} as a server (or "host"), see the {@link
75 * BluetoothServerSocket} documentation.
Nick Pelly753da532009-08-19 11:00:00 -070076 *
David Duarteee52b7e2023-12-02 01:32:11 +000077 * <p>Once the socket is connected, whether initiated as a client or accepted as a server, open the
78 * IO streams by calling {@link #getInputStream} and {@link #getOutputStream} in order to retrieve
79 * {@link java.io.InputStream} and {@link java.io.OutputStream} objects, respectively, which are
Scott Mainbeef8092009-11-03 18:17:59 -080080 * automatically connected to the socket.
81 *
David Duarteee52b7e2023-12-02 01:32:11 +000082 * <p>{@link BluetoothSocket} is thread safe. In particular, {@link #close} will always immediately
83 * abort ongoing operations and close the socket.
Nick Pellyed6f2ce2009-09-08 10:12:06 -070084 *
David Duarteee52b7e2023-12-02 01:32:11 +000085 * <p><div class="special reference">
86 *
Joe Fernandezda4e2ab2011-12-20 10:38:34 -080087 * <h3>Developer Guides</h3>
Joe Fernandezda4e2ab2011-12-20 10:38:34 -080088 *
David Duarteee52b7e2023-12-02 01:32:11 +000089 * <p>For more information about using Bluetooth, read the <a
90 * href="{@docRoot}guide/topics/connectivity/bluetooth.html">Bluetooth</a> developer guide. </div>
91 *
David Duarte5a02bb42023-12-04 23:07:42 +000092 * @see BluetoothServerSocket
93 * @see java.io.InputStream
94 * @see java.io.OutputStream
Nick Pelly53f441b2009-05-26 19:13:43 -070095 */
96public final class BluetoothSocket implements Closeable {
Nick Pelly07b84cb2009-10-07 07:44:03 +020097 private static final String TAG = "BluetoothSocket";
Joe LaPennaa49d75d2014-05-13 18:17:46 -070098 private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
99 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
Nick Pelly07b84cb2009-10-07 07:44:03 +0200100
Nick Pellyee1402d2009-10-02 20:34:18 -0700101 /** @hide */
102 public static final int MAX_RFCOMM_CHANNEL = 30;
David Duarteee52b7e2023-12-02 01:32:11 +0000103
Casper Bondec0a7c932015-04-09 09:24:48 +0200104 /*package*/ static final int MAX_L2CAP_PACKAGE_SIZE = 0xFFFF;
Nick Pellyee1402d2009-10-02 20:34:18 -0700105
Andre Eisenbach660bff72015-05-04 13:48:50 -0700106 /** RFCOMM socket */
Casper Bondec0a7c932015-04-09 09:24:48 +0200107 public static final int TYPE_RFCOMM = 1;
Andre Eisenbach660bff72015-05-04 13:48:50 -0700108
109 /** SCO socket */
Casper Bondec0a7c932015-04-09 09:24:48 +0200110 public static final int TYPE_SCO = 2;
Andre Eisenbach660bff72015-05-04 13:48:50 -0700111
112 /** L2CAP socket */
Casper Bondec0a7c932015-04-09 09:24:48 +0200113 public static final int TYPE_L2CAP = 3;
Nick Pellycb32d7c2009-06-02 15:57:18 -0700114
David Duarteee52b7e2023-12-02 01:32:11 +0000115 /**
116 * L2CAP socket on BR/EDR transport
117 *
Bhakthavatsala Raghavendraaf3a0172024-10-18 21:33:33 +0000118 * <p>To be removed once Flags.FLAG_SOCKET_SETTINGS_API is removed
119 *
Stanley Tngd67d5e42017-11-22 16:04:40 -0800120 * @hide
121 */
122 public static final int TYPE_L2CAP_BREDR = TYPE_L2CAP;
123
David Duarteee52b7e2023-12-02 01:32:11 +0000124 /**
125 * L2CAP socket on LE transport
126 *
Bhakthavatsala Raghavendraaf3a0172024-10-18 21:33:33 +0000127 * <p>To be removed once Flags.FLAG_SOCKET_SETTINGS_API is removed
128 *
Stanley Tngd67d5e42017-11-22 16:04:40 -0800129 * @hide
130 */
131 public static final int TYPE_L2CAP_LE = 4;
132
Bhakthavatsala Raghavendraaf3a0172024-10-18 21:33:33 +0000133 /** L2CAP socket on LE transport */
134 @FlaggedApi(Flags.FLAG_SOCKET_SETTINGS_API)
135 public static final int TYPE_LE = 4;
136
137 /** @hide */
138 @IntDef(
139 prefix = {"BluetoothSocket.TYPE_"},
140 value = {
141 BluetoothSocket.TYPE_RFCOMM,
142 BluetoothSocket.TYPE_SCO,
143 BluetoothSocket.TYPE_L2CAP,
144 BluetoothSocket.TYPE_LE,
145 })
146 @Retention(RetentionPolicy.SOURCE)
147 public @interface SocketType {}
148
Nick Pellyee1402d2009-10-02 20:34:18 -0700149 /*package*/ static final int EBADFD = 77;
David Duarteee52b7e2023-12-02 01:32:11 +0000150
Mathew Inwoodcba870b2020-10-27 11:47:29 +0000151 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
Nick Pellyee1402d2009-10-02 20:34:18 -0700152 /*package*/ static final int EADDRINUSE = 98;
153
zzyfab62db2012-04-03 19:48:32 -0700154 /*package*/ static final int SEC_FLAG_ENCRYPT = 1;
155 /*package*/ static final int SEC_FLAG_AUTH = 1 << 1;
Jack He910201b2017-08-22 16:06:54 -0700156 /*package*/ static final int BTSOCK_FLAG_NO_SDP = 1 << 2;
Bhakthavatsala Raghavendradcaace52024-10-25 22:29:01 +0000157 /*package*/ static final int SEC_FLAG_AUTH_PITM = 1 << 3;
Jack He910201b2017-08-22 16:06:54 -0700158 /*package*/ static final int SEC_FLAG_AUTH_16_DIGIT = 1 << 4;
zzyfab62db2012-04-03 19:48:32 -0700159
Liang Li77fbb392024-11-14 07:24:14 +0000160 /*package*/ static final String DEFAULT_SOCKET_NAME = "default_name";
161
David Duarteee52b7e2023-12-02 01:32:11 +0000162 private final int mType; /* one of TYPE_RFCOMM etc */
163 private BluetoothDevice mDevice; /* remote device */
164 private String mAddress; /* remote address */
Nick Pelly53f441b2009-05-26 19:13:43 -0700165 private final boolean mAuth;
166 private final boolean mEncrypt;
167 private final BluetoothInputStream mInputStream;
168 private final BluetoothOutputStream mOutputStream;
zzyfab62db2012-04-03 19:48:32 -0700169 private final ParcelUuid mUuid;
Liang Li77fbb392024-11-14 07:24:14 +0000170 private final int mDataPath;
171 private final String mSocketName;
172 private final long mHubId;
173 private final long mEndpointId;
174 private final int mMaximumPacketSize;
David Duarteee52b7e2023-12-02 01:32:11 +0000175
Jeff Sharkeyc5386af2020-09-11 14:57:21 -0600176 /** when true no SPP SDP record will be created */
177 private boolean mExcludeSdp = false;
David Duarteee52b7e2023-12-02 01:32:11 +0000178
Jeff Sharkeyc5386af2020-09-11 14:57:21 -0600179 /** when true Person-in-the-middle protection will be enabled */
Bhakthavatsala Raghavendradcaace52024-10-25 22:29:01 +0000180 private boolean mAuthPitm = false;
David Duarteee52b7e2023-12-02 01:32:11 +0000181
Jeff Sharkeyc5386af2020-09-11 14:57:21 -0600182 /** Minimum 16 digit pin for sec mode 2 connections */
183 private boolean mMin16DigitPin = false;
David Duarteee52b7e2023-12-02 01:32:11 +0000184
Andrei Onea147146f2019-06-17 11:26:14 +0100185 @UnsupportedAppUsage(publicAlternatives = "Use {@link BluetoothSocket} public API instead.")
zzyfab62db2012-04-03 19:48:32 -0700186 private ParcelFileDescriptor mPfd;
David Duarteee52b7e2023-12-02 01:32:11 +0000187
188 @UnsupportedAppUsage private LocalSocket mSocket;
zzyfab62db2012-04-03 19:48:32 -0700189 private InputStream mSocketIS;
190 private OutputStream mSocketOS;
David Duarteee52b7e2023-12-02 01:32:11 +0000191 @UnsupportedAppUsage private int mPort; /* RFCOMM channel or L2CAP psm */
zzyfab62db2012-04-03 19:48:32 -0700192 private String mServiceName;
zzyfab62db2012-04-03 19:48:32 -0700193
Liang Li77fbb392024-11-14 07:24:14 +0000194 private static final int SOCK_CONNECTION_SIGNAL_SIZE = 44;
195 private static final long INVALID_SOCKET_ID = 0;
Liang Li88ba5e02024-11-14 19:07:45 +0000196 private static final int SOCK_ACCEPT_SIGNAL_SIZE = 4;
Casper Bondec0a7c932015-04-09 09:24:48 +0200197
198 private ByteBuffer mL2capBuffer = null;
199 private int mMaxTxPacketSize = 0; // The l2cap maximum packet size supported by the peer.
200 private int mMaxRxPacketSize = 0; // The l2cap maximum packet size that can be received.
Jayden Kim815a8c92024-03-17 07:48:36 +0000201 private ParcelUuid mConnectionUuid;
Liang Li77fbb392024-11-14 07:24:14 +0000202 private long mSocketId; // Socket ID in connected state.
Nick Pelly53f441b2009-05-26 19:13:43 -0700203
Pomai Ahlobc19c022023-11-13 16:37:06 -0800204 private long mSocketCreationTimeNanos = 0;
205 private long mSocketCreationLatencyNanos = 0;
Chen Chen696b3562023-02-23 14:27:08 -0800206
Matthew Xie638350f2011-05-03 19:50:20 -0700207 private enum SocketState {
208 INIT,
209 CONNECTED,
zzyfab62db2012-04-03 19:48:32 -0700210 LISTENING,
211 CLOSED,
Matthew Xie638350f2011-05-03 19:50:20 -0700212 }
Nick Pelly4cd2cd92009-09-02 11:51:35 -0700213
Matthew Xie638350f2011-05-03 19:50:20 -0700214 /** prevents all native calls after destroyNative() */
zzyfab62db2012-04-03 19:48:32 -0700215 private volatile SocketState mSocketState;
Matthew Xie638350f2011-05-03 19:50:20 -0700216
217 /** protects mSocketState */
David Duarteee52b7e2023-12-02 01:32:11 +0000218 // private final ReentrantReadWriteLock mLock;
Nick Pelly53f441b2009-05-26 19:13:43 -0700219
220 /**
Nick Pelly2d664882009-08-14 18:33:38 -0700221 * Construct a BluetoothSocket.
Jack He910201b2017-08-22 16:06:54 -0700222 *
223 * @param type type of socket
Jack He910201b2017-08-22 16:06:54 -0700224 * @param auth require the remote device to be authenticated
Nick Pelly53f441b2009-05-26 19:13:43 -0700225 * @param encrypt require the connection to be encrypted
Jack He910201b2017-08-22 16:06:54 -0700226 * @param port remote port
227 * @param uuid SDP uuid
David Duarteee52b7e2023-12-02 01:32:11 +0000228 * @throws IOException On error, for example Bluetooth not available, or insufficient privileges
Nick Pelly53f441b2009-05-26 19:13:43 -0700229 */
William Escande3f7cbce2024-08-02 11:08:35 -0700230 @RequiresPermission(allOf = {BLUETOOTH_CONNECT, LOCAL_MAC_ADDRESS})
Bhakthavatsala Raghavendraaf3a0172024-10-18 21:33:33 +0000231 /*package*/ BluetoothSocket(int type, boolean auth, boolean encrypt, int port, ParcelUuid uuid)
David Duarteee52b7e2023-12-02 01:32:11 +0000232 throws IOException {
Bhakthavatsala Raghavendradcaace52024-10-25 22:29:01 +0000233 this(type, auth, encrypt, port, uuid, false, false);
Casper Bonde60d77c22015-04-21 13:12:05 +0200234 }
235
236 /**
237 * Construct a BluetoothSocket.
Jack He910201b2017-08-22 16:06:54 -0700238 *
239 * @param type type of socket
Jack He910201b2017-08-22 16:06:54 -0700240 * @param auth require the remote device to be authenticated
Casper Bonde60d77c22015-04-21 13:12:05 +0200241 * @param encrypt require the connection to be encrypted
Jack He910201b2017-08-22 16:06:54 -0700242 * @param port remote port
243 * @param uuid SDP uuid
Bhakthavatsala Raghavendradcaace52024-10-25 22:29:01 +0000244 * @param pitm enforce person-in-the-middle protection.
Casper Bonde91276012015-05-08 14:32:24 +0200245 * @param min16DigitPin enforce a minimum length of 16 digits for a sec mode 2 connection
David Duarteee52b7e2023-12-02 01:32:11 +0000246 * @throws IOException On error, for example Bluetooth not available, or insufficient privileges
Casper Bonde60d77c22015-04-21 13:12:05 +0200247 */
William Escande3f7cbce2024-08-02 11:08:35 -0700248 @RequiresPermission(allOf = {BLUETOOTH_CONNECT, LOCAL_MAC_ADDRESS})
David Duarteee52b7e2023-12-02 01:32:11 +0000249 /*package*/ BluetoothSocket(
250 int type,
David Duarteee52b7e2023-12-02 01:32:11 +0000251 boolean auth,
252 boolean encrypt,
David Duarteee52b7e2023-12-02 01:32:11 +0000253 int port,
254 ParcelUuid uuid,
Bhakthavatsala Raghavendradcaace52024-10-25 22:29:01 +0000255 boolean pitm,
David Duarteee52b7e2023-12-02 01:32:11 +0000256 boolean min16DigitPin)
Jack He910201b2017-08-22 16:06:54 -0700257 throws IOException {
Liang Li77fbb392024-11-14 07:24:14 +0000258 this(type, auth, encrypt, port, uuid, pitm, min16DigitPin, 0, DEFAULT_SOCKET_NAME, 0, 0, 0);
259 }
260
261 /**
262 * Construct a BluetoothSocket.
263 *
264 * @param type type of socket
265 * @param auth require the remote device to be authenticated
266 * @param encrypt require the connection to be encrypted
267 * @param port remote port
268 * @param uuid SDP uuid
269 * @param pitm enforce person-in-the-middle protection.
270 * @param min16DigitPin enforce a minimum length of 16 digits for a sec mode 2 connection
271 * @param dataPath data path used for this socket
272 * @param socketName user-friendly name for this socket
273 * @param hubId ID of the hub to which the end point belongs
274 * @param endpointId ID of the endpoint within the hub that is associated with this socket
275 * @param maximumPacketSize The maximum size (in bytes) of a single data packet
276 * @throws IOException On error, for example Bluetooth not available, or insufficient privileges
277 */
278 @RequiresPermission(allOf = {BLUETOOTH_CONNECT, LOCAL_MAC_ADDRESS})
279 /*package*/ BluetoothSocket(
280 int type,
281 boolean auth,
282 boolean encrypt,
283 int port,
284 ParcelUuid uuid,
285 boolean pitm,
286 boolean min16DigitPin,
287 int dataPath,
288 @NonNull String socketName,
289 long hubId,
290 long endpointId,
291 int maximumPacketSize)
292 throws IOException {
Casper Bondec0a7c932015-04-09 09:24:48 +0200293 if (VDBG) Log.d(TAG, "Creating new BluetoothSocket of type: " + type);
Pomai Ahlobc19c022023-11-13 16:37:06 -0800294 mSocketCreationTimeNanos = System.nanoTime();
David Duarteee52b7e2023-12-02 01:32:11 +0000295 if (type == BluetoothSocket.TYPE_RFCOMM
296 && uuid == null
Casper Bondec0a7c932015-04-09 09:24:48 +0200297 && port != BluetoothAdapter.SOCKET_CHANNEL_AUTO_STATIC_NO_SDP) {
Nick Pellyee1402d2009-10-02 20:34:18 -0700298 if (port < 1 || port > MAX_RFCOMM_CHANNEL) {
299 throw new IOException("Invalid RFCOMM channel: " + port);
300 }
301 }
Jack He910201b2017-08-22 16:06:54 -0700302 if (uuid != null) {
zzy30495702012-10-11 14:52:43 -0700303 mUuid = uuid;
Jack He910201b2017-08-22 16:06:54 -0700304 } else {
305 mUuid = new ParcelUuid(new UUID(0, 0));
306 }
Nick Pellycb32d7c2009-06-02 15:57:18 -0700307 mType = type;
Nick Pelly53f441b2009-05-26 19:13:43 -0700308 mAuth = auth;
Bhakthavatsala Raghavendradcaace52024-10-25 22:29:01 +0000309 mAuthPitm = pitm;
310 mMin16DigitPin = min16DigitPin;
311 mEncrypt = encrypt;
312 mPort = port;
313 // this constructor to be called only from BluetoothServerSocket
314 mDevice = null;
Liang Li77fbb392024-11-14 07:24:14 +0000315 mDataPath = dataPath;
316 mSocketName = socketName;
317 mHubId = hubId;
318 mEndpointId = endpointId;
319 mMaximumPacketSize = maximumPacketSize;
Bhakthavatsala Raghavendradcaace52024-10-25 22:29:01 +0000320
321 mSocketState = SocketState.INIT;
322
323 mAddress = BluetoothAdapter.getDefaultAdapter().getAddress();
324
325 mInputStream = new BluetoothInputStream(this);
326 mOutputStream = new BluetoothOutputStream(this);
327 mSocketCreationLatencyNanos = System.nanoTime() - mSocketCreationTimeNanos;
328 }
329
330 /**
331 * Construct a BluetoothSocket.
332 *
333 * @param device remote device that this socket can connect to
334 * @param type type of socket
335 * @param auth require the remote device to be authenticated
336 * @param encrypt require the connection to be encrypted
337 * @param port remote port
338 * @param uuid SDP uuid
339 * @throws IOException On error, for example Bluetooth not available, or insufficient privileges
340 */
341 /*package*/ BluetoothSocket(
342 BluetoothDevice device,
343 int type,
344 boolean auth,
345 boolean encrypt,
346 int port,
347 ParcelUuid uuid)
348 throws IOException {
349 this(device, type, auth, encrypt, port, uuid, false, false);
350 }
351
352 /**
353 * Construct a BluetoothSocket.
354 *
355 * @param device remote device that this socket can connect to
356 * @param type type of socket
357 * @param auth require the remote device to be authenticated
358 * @param encrypt require the connection to be encrypted
359 * @param port remote port
360 * @param uuid SDP uuid
361 * @param pitm enforce person-in-the-middle protection.
362 * @param min16DigitPin enforce a minimum length of 16 digits for a sec mode 2 connection
363 * @throws IOException On error, for example Bluetooth not available, or insufficient privileges
364 */
365 /*package*/ BluetoothSocket(
366 @NonNull BluetoothDevice device,
367 int type,
368 boolean auth,
369 boolean encrypt,
370 int port,
371 ParcelUuid uuid,
372 boolean pitm,
373 boolean min16DigitPin)
374 throws IOException {
Liang Li77fbb392024-11-14 07:24:14 +0000375 this(
376 device,
377 type,
378 auth,
379 encrypt,
380 port,
381 uuid,
382 pitm,
383 min16DigitPin,
384 0,
385 DEFAULT_SOCKET_NAME,
386 0,
387 0,
388 0);
389 }
390
391 /**
392 * Construct a BluetoothSocket.
393 *
394 * @param device remote device that this socket can connect to
395 * @param type type of socket
396 * @param auth require the remote device to be authenticated
397 * @param encrypt require the connection to be encrypted
398 * @param port remote port
399 * @param uuid SDP uuid
400 * @param pitm enforce person-in-the-middle protection.
401 * @param min16DigitPin enforce a minimum length of 16 digits for a sec mode 2 connection
402 * @param dataPath data path used for this socket
403 * @param socketName user-friendly name for this socket
404 * @param hubId ID of the hub to which the end point belongs
405 * @param endpointId ID of the endpoint within the hub that is associated with this socket
406 * @param maximumPacketSize The maximum size (in bytes) of a single data packet
407 * @throws IOException On error, for example Bluetooth not available, or insufficient privileges
408 */
409 /*package*/ BluetoothSocket(
410 @NonNull BluetoothDevice device,
411 int type,
412 boolean auth,
413 boolean encrypt,
414 int port,
415 ParcelUuid uuid,
416 boolean pitm,
417 boolean min16DigitPin,
418 int dataPath,
419 @NonNull String socketName,
420 long hubId,
421 long endpointId,
422 int maximumPacketSize)
423 throws IOException {
Bhakthavatsala Raghavendradcaace52024-10-25 22:29:01 +0000424 if (VDBG) Log.d(TAG, "Creating new BluetoothSocket of type: " + type);
425 mSocketCreationTimeNanos = System.nanoTime();
426 if (type == BluetoothSocket.TYPE_RFCOMM
427 && uuid == null
428 && port != BluetoothAdapter.SOCKET_CHANNEL_AUTO_STATIC_NO_SDP) {
429 if (port < 1 || port > MAX_RFCOMM_CHANNEL) {
430 throw new IOException("Invalid RFCOMM channel: " + port);
431 }
432 }
433 if (uuid != null) {
434 mUuid = uuid;
435 } else {
436 mUuid = new ParcelUuid(new UUID(0, 0));
437 }
438 mType = type;
439 mAuth = auth;
440 mAuthPitm = pitm;
Casper Bonde91276012015-05-08 14:32:24 +0200441 mMin16DigitPin = min16DigitPin;
Nick Pelly53f441b2009-05-26 19:13:43 -0700442 mEncrypt = encrypt;
Nick Pelly2d664882009-08-14 18:33:38 -0700443 mDevice = device;
zzyfab62db2012-04-03 19:48:32 -0700444 mPort = port;
Liang Li77fbb392024-11-14 07:24:14 +0000445 mDataPath = dataPath;
446 mSocketName = socketName;
447 mHubId = hubId;
448 mEndpointId = endpointId;
449 mMaximumPacketSize = maximumPacketSize;
zzyfab62db2012-04-03 19:48:32 -0700450
451 mSocketState = SocketState.INIT;
452
Bhakthavatsala Raghavendradcaace52024-10-25 22:29:01 +0000453 // Remote socket
454 mAddress = device.getAddress();
455
Nick Pelly53f441b2009-05-26 19:13:43 -0700456 mInputStream = new BluetoothInputStream(this);
457 mOutputStream = new BluetoothOutputStream(this);
Pomai Ahlobc19c022023-11-13 16:37:06 -0800458 mSocketCreationLatencyNanos = System.nanoTime() - mSocketCreationTimeNanos;
zzyfab62db2012-04-03 19:48:32 -0700459 }
Jack He910201b2017-08-22 16:06:54 -0700460
tadvanae6718402022-01-26 10:35:38 -0800461 /**
462 * Creates a BluetoothSocket from a {@link ParcelFileDescriptor}. This is used for when the
463 * underlying mPfd is transferred to a separate process (e.g. over a binder), and the socket
464 * must be reconstructed.
David Duarteee52b7e2023-12-02 01:32:11 +0000465 *
466 * <p>The socket should already be connected in this case, so {@link #connect()} should not be
tadvanae6718402022-01-26 10:35:38 -0800467 * called.
468 *
469 * @param pfd is the {@link ParcelFileDescriptor} for an already connected BluetoothSocket
470 * @param device is the remote {@link BluetoothDevice} that this socket is connected to
471 * @param uuid is the service ID that this RFCOMM connection is using
472 * @throws IOException if socket creation fails.
473 */
474 /*package*/ static BluetoothSocket createSocketFromOpenFd(
475 ParcelFileDescriptor pfd, BluetoothDevice device, ParcelUuid uuid) throws IOException {
476 BluetoothSocket bluetoothSocket =
Bhakthavatsala Raghavendradcaace52024-10-25 22:29:01 +0000477 new BluetoothSocket(device, TYPE_RFCOMM, true, true, -1, uuid);
tadvanae6718402022-01-26 10:35:38 -0800478
479 bluetoothSocket.mPfd = pfd;
480 bluetoothSocket.mSocket = new LocalSocket(pfd.getFileDescriptor());
481 bluetoothSocket.mSocketIS = bluetoothSocket.mSocket.getInputStream();
482 bluetoothSocket.mSocketOS = bluetoothSocket.mSocket.getOutputStream();
483 bluetoothSocket.mSocketState = SocketState.CONNECTED;
484
485 return bluetoothSocket;
486 }
487
zzyfab62db2012-04-03 19:48:32 -0700488 private BluetoothSocket(BluetoothSocket s) {
Casper Bondec0a7c932015-04-09 09:24:48 +0200489 if (VDBG) Log.d(TAG, "Creating new Private BluetoothSocket of type: " + s.mType);
zzyfab62db2012-04-03 19:48:32 -0700490 mUuid = s.mUuid;
491 mType = s.mType;
492 mAuth = s.mAuth;
493 mEncrypt = s.mEncrypt;
494 mPort = s.mPort;
495 mInputStream = new BluetoothInputStream(this);
496 mOutputStream = new BluetoothOutputStream(this);
Casper Bondec0a7c932015-04-09 09:24:48 +0200497 mMaxRxPacketSize = s.mMaxRxPacketSize;
498 mMaxTxPacketSize = s.mMaxTxPacketSize;
Jayden Kim815a8c92024-03-17 07:48:36 +0000499 mConnectionUuid = s.mConnectionUuid;
Liang Li77fbb392024-11-14 07:24:14 +0000500 mSocketId = s.mSocketId;
Casper Bondec0a7c932015-04-09 09:24:48 +0200501
zzyfab62db2012-04-03 19:48:32 -0700502 mServiceName = s.mServiceName;
Casper Bondec0a7c932015-04-09 09:24:48 +0200503 mExcludeSdp = s.mExcludeSdp;
Bhakthavatsala Raghavendradcaace52024-10-25 22:29:01 +0000504 mAuthPitm = s.mAuthPitm;
Casper Bonde91276012015-05-08 14:32:24 +0200505 mMin16DigitPin = s.mMin16DigitPin;
Liang Li77fbb392024-11-14 07:24:14 +0000506 mDataPath = s.mDataPath;
507 mSocketName = s.mSocketName;
508 mHubId = s.mHubId;
509 mEndpointId = s.mEndpointId;
510 mMaximumPacketSize = s.mMaximumPacketSize;
Pomai Ahlobc19c022023-11-13 16:37:06 -0800511 mSocketCreationTimeNanos = s.mSocketCreationTimeNanos;
512 mSocketCreationLatencyNanos = s.mSocketCreationLatencyNanos;
zzyfab62db2012-04-03 19:48:32 -0700513 }
Jack He910201b2017-08-22 16:06:54 -0700514
Jack He9e045d22017-08-22 21:21:23 -0700515 private BluetoothSocket acceptSocket(String remoteAddr) throws IOException {
zzyfab62db2012-04-03 19:48:32 -0700516 BluetoothSocket as = new BluetoothSocket(this);
517 as.mSocketState = SocketState.CONNECTED;
518 FileDescriptor[] fds = mSocket.getAncillaryFileDescriptors();
Ugo Yub6dc15a2022-12-28 20:18:00 +0800519 if (DBG) Log.d(TAG, "acceptSocket: socket fd passed by stack fds:" + Arrays.toString(fds));
Jack He910201b2017-08-22 16:06:54 -0700520 if (fds == null || fds.length != 1) {
Andreas Gampe7b1e7402015-12-11 18:00:38 -0800521 Log.e(TAG, "socket fd passed from stack failed, fds: " + Arrays.toString(fds));
zzyf6fcd9b2013-04-16 17:17:37 -0700522 as.close();
David Duarte1c07fc72023-12-02 02:08:08 +0000523 throw new IOException("bt socket accept failed");
zzyfab62db2012-04-03 19:48:32 -0700524 }
Zach Johnsonc6242452015-07-13 18:00:35 -0700525
William Escande88eade52021-11-19 16:48:45 +0100526 as.mPfd = ParcelFileDescriptor.dup(fds[0]);
Lorenzo Colittiaa149022022-01-25 09:59:44 +0900527 as.mSocket = new LocalSocket(fds[0]);
zzyfab62db2012-04-03 19:48:32 -0700528 as.mSocketIS = as.mSocket.getInputStream();
529 as.mSocketOS = as.mSocket.getOutputStream();
Jack He9e045d22017-08-22 21:21:23 -0700530 as.mAddress = remoteAddr;
531 as.mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(remoteAddr);
zzyfab62db2012-04-03 19:48:32 -0700532 return as;
533 }
Jack He910201b2017-08-22 16:06:54 -0700534
Nick Pelly753da532009-08-19 11:00:00 -0700535 /** @hide */
Nick Pelly53f441b2009-05-26 19:13:43 -0700536 @Override
David Duarte5a02bb42023-12-04 23:07:42 +0000537 @SuppressWarnings("Finalize") // TODO(b/314811467)
Nick Pelly53f441b2009-05-26 19:13:43 -0700538 protected void finalize() throws Throwable {
539 try {
540 close();
541 } finally {
542 super.finalize();
543 }
544 }
Jack He910201b2017-08-22 16:06:54 -0700545
zzyfab62db2012-04-03 19:48:32 -0700546 private int getSecurityFlags() {
547 int flags = 0;
Jack He910201b2017-08-22 16:06:54 -0700548 if (mAuth) {
zzyfab62db2012-04-03 19:48:32 -0700549 flags |= SEC_FLAG_AUTH;
Jack He910201b2017-08-22 16:06:54 -0700550 }
551 if (mEncrypt) {
zzyfab62db2012-04-03 19:48:32 -0700552 flags |= SEC_FLAG_ENCRYPT;
Jack He910201b2017-08-22 16:06:54 -0700553 }
554 if (mExcludeSdp) {
Casper Bondec0a7c932015-04-09 09:24:48 +0200555 flags |= BTSOCK_FLAG_NO_SDP;
Jack He910201b2017-08-22 16:06:54 -0700556 }
Bhakthavatsala Raghavendradcaace52024-10-25 22:29:01 +0000557 if (mAuthPitm) {
558 flags |= SEC_FLAG_AUTH_PITM;
Jack He910201b2017-08-22 16:06:54 -0700559 }
560 if (mMin16DigitPin) {
Casper Bonde91276012015-05-08 14:32:24 +0200561 flags |= SEC_FLAG_AUTH_16_DIGIT;
Jack He910201b2017-08-22 16:06:54 -0700562 }
zzyfab62db2012-04-03 19:48:32 -0700563 return flags;
Nick Pelly53f441b2009-05-26 19:13:43 -0700564 }
565
566 /**
Nick Pelly753da532009-08-19 11:00:00 -0700567 * Get the remote device this socket is connecting, or connected, to.
Jack He910201b2017-08-22 16:06:54 -0700568 *
Nick Pelly753da532009-08-19 11:00:00 -0700569 * @return remote device
Nick Pelly53f441b2009-05-26 19:13:43 -0700570 */
Jeff Sharkey5ba8bfc2021-04-16 09:53:23 -0600571 @RequiresNoPermission
Nick Pelly2d664882009-08-14 18:33:38 -0700572 public BluetoothDevice getRemoteDevice() {
573 return mDevice;
Nick Pelly53f441b2009-05-26 19:13:43 -0700574 }
575
576 /**
577 * Get the input stream associated with this socket.
David Duarteee52b7e2023-12-02 01:32:11 +0000578 *
579 * <p>The input stream will be returned even if the socket is not yet connected, but operations
580 * on that stream will throw IOException until the associated socket is connected.
Jack He910201b2017-08-22 16:06:54 -0700581 *
Nick Pelly53f441b2009-05-26 19:13:43 -0700582 * @return InputStream
583 */
Jeff Sharkey5ba8bfc2021-04-16 09:53:23 -0600584 @RequiresNoPermission
Nick Pelly53f441b2009-05-26 19:13:43 -0700585 public InputStream getInputStream() throws IOException {
586 return mInputStream;
587 }
588
589 /**
590 * Get the output stream associated with this socket.
David Duarteee52b7e2023-12-02 01:32:11 +0000591 *
592 * <p>The output stream will be returned even if the socket is not yet connected, but operations
593 * on that stream will throw IOException until the associated socket is connected.
Jack He910201b2017-08-22 16:06:54 -0700594 *
Nick Pelly53f441b2009-05-26 19:13:43 -0700595 * @return OutputStream
596 */
Jeff Sharkey5ba8bfc2021-04-16 09:53:23 -0600597 @RequiresNoPermission
Nick Pelly53f441b2009-05-26 19:13:43 -0700598 public OutputStream getOutputStream() throws IOException {
599 return mOutputStream;
600 }
601
Nick Pellyee1402d2009-10-02 20:34:18 -0700602 /**
Matthew Xie638350f2011-05-03 19:50:20 -0700603 * Get the connection status of this socket, ie, whether there is an active connection with
604 * remote device.
Jack He910201b2017-08-22 16:06:54 -0700605 *
606 * @return true if connected false if not connected
Matthew Xie638350f2011-05-03 19:50:20 -0700607 */
Jeff Sharkey5ba8bfc2021-04-16 09:53:23 -0600608 @RequiresNoPermission
Matthew Xie638350f2011-05-03 19:50:20 -0700609 public boolean isConnected() {
zzyfab62db2012-04-03 19:48:32 -0700610 return mSocketState == SocketState.CONNECTED;
611 }
612
613 /*package*/ void setServiceName(String name) {
614 mServiceName = name;
615 }
616
Chen Chen874e7b02023-03-07 17:37:43 -0800617 /*package*/ boolean isAuth() {
618 return mAuth;
619 }
David Duarteee52b7e2023-12-02 01:32:11 +0000620
zzyfab62db2012-04-03 19:48:32 -0700621 /**
622 * Attempt to connect to a remote device.
Anton Hansson4c4d1252023-10-03 14:03:19 +0000623 *
Aritra Sen8134e952023-03-11 01:03:38 +0000624 * <p>This method will block until a connection is made or the connection fails. If this method
625 * returns without an exception then this socket is now connected.
Anton Hansson4c4d1252023-10-03 14:03:19 +0000626 *
Aritra Sen8134e952023-03-11 01:03:38 +0000627 * <p>Creating new connections to remote Bluetooth devices should not be attempted while device
628 * discovery is in progress. Device discovery is a heavyweight procedure on the Bluetooth
Anton Hansson4c4d1252023-10-03 14:03:19 +0000629 * adapter and will significantly slow a device connection. Use {@link
630 * BluetoothAdapter#cancelDiscovery()} to cancel an ongoing discovery. Discovery is not managed
631 * by the Activity, but is run as a system service, so an application should always call {@link
632 * BluetoothAdapter#cancelDiscovery()} even if it did not directly request a discovery, just to
633 * be sure.
634 *
zzyfab62db2012-04-03 19:48:32 -0700635 * <p>{@link #close} can be used to abort this call from another thread.
Jack He910201b2017-08-22 16:06:54 -0700636 *
Liang Li77fbb392024-11-14 07:24:14 +0000637 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_PRIVILEGED} permission only when
638 * {@code mDataPath} is different from {@link BluetoothSocketSettings#DATA_PATH_NO_OFFLOAD}.
639 *
Anton Hansson4c4d1252023-10-03 14:03:19 +0000640 * @throws BluetoothSocketException in case of failure, with the corresponding error code.
Aritra Sen8134e952023-03-11 01:03:38 +0000641 * @throws IOException for other errors (eg: InputStream read failures etc.).
zzyfab62db2012-04-03 19:48:32 -0700642 */
Liang Li77fbb392024-11-14 07:24:14 +0000643 @FlaggedApi(Flags.FLAG_SOCKET_SETTINGS_API)
Jeff Sharkey5ba8bfc2021-04-16 09:53:23 -0600644 @RequiresBluetoothConnectPermission
Liang Li77fbb392024-11-14 07:24:14 +0000645 @RequiresPermission(
646 allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED},
647 conditional = true)
zzyfab62db2012-04-03 19:48:32 -0700648 public void connect() throws IOException {
David Duarteee52b7e2023-12-02 01:32:11 +0000649 IBluetooth bluetoothProxy = BluetoothAdapter.getDefaultAdapter().getBluetoothService();
Pomai Ahlobc19c022023-11-13 16:37:06 -0800650 long socketConnectionTimeNanos = System.nanoTime();
Chen Chen696b3562023-02-23 14:27:08 -0800651 if (bluetoothProxy == null) {
Aritra Sen8134e952023-03-11 01:03:38 +0000652 throw new BluetoothSocketException(BluetoothSocketException.BLUETOOTH_OFF_FAILURE);
Chen Chen696b3562023-02-23 14:27:08 -0800653 }
zzyfab62db2012-04-03 19:48:32 -0700654 try {
Pomai Ahloe28d3cb2023-11-02 17:19:30 -0700655 if (mDevice == null) {
656 throw new BluetoothSocketException(BluetoothSocketException.NULL_DEVICE);
657 }
Chen Chen696b3562023-02-23 14:27:08 -0800658 if (mSocketState == SocketState.CLOSED) {
Aritra Sen8134e952023-03-11 01:03:38 +0000659 throw new BluetoothSocketException(BluetoothSocketException.SOCKET_CLOSED);
Chen Chen696b3562023-02-23 14:27:08 -0800660 }
661
William Escande0cef84c2022-01-10 19:13:28 +0100662 IBluetoothSocketManager socketManager = bluetoothProxy.getSocketManager();
Chen Chen696b3562023-02-23 14:27:08 -0800663 if (socketManager == null) {
Aritra Sen8134e952023-03-11 01:03:38 +0000664 throw new BluetoothSocketException(BluetoothSocketException.SOCKET_MANAGER_FAILURE);
Chen Chen696b3562023-02-23 14:27:08 -0800665 }
Liang Li77fbb392024-11-14 07:24:14 +0000666 if (Flags.socketSettingsApi()) {
667 if (mDataPath == BluetoothSocketSettings.DATA_PATH_NO_OFFLOAD) {
668 mPfd =
669 socketManager.connectSocket(
670 mDevice, mType, mUuid, mPort, getSecurityFlags());
671 } else {
672 mPfd =
673 socketManager.connectSocketwithOffload(
674 mDevice,
675 mType,
676 mUuid,
677 mPort,
678 getSecurityFlags(),
679 mDataPath,
680 mSocketName,
681 mHubId,
682 mEndpointId,
683 mMaximumPacketSize);
684 }
685 } else {
686 mPfd =
687 socketManager.connectSocket(
688 mDevice, mType, mUuid, mPort, getSecurityFlags());
689 }
Jack He910201b2017-08-22 16:06:54 -0700690 synchronized (this) {
Pomai Ahlo13444752024-03-21 11:24:46 -0700691 Log.i(TAG, "connect(), SocketState: " + mSocketState + ", mPfd: " + mPfd);
Chen Chen696b3562023-02-23 14:27:08 -0800692 if (mSocketState == SocketState.CLOSED) {
William Escande8d6dc6e2024-05-31 11:53:57 -0700693 throw new BluetoothSocketException(BluetoothSocketException.SOCKET_CLOSED);
Chen Chen696b3562023-02-23 14:27:08 -0800694 }
695 if (mPfd == null) {
Aritra Sen8134e952023-03-11 01:03:38 +0000696 throw new BluetoothSocketException(
William Escande8d6dc6e2024-05-31 11:53:57 -0700697 BluetoothSocketException.UNIX_FILE_SOCKET_CREATION_FAILURE);
Chen Chen696b3562023-02-23 14:27:08 -0800698 }
zzyfab62db2012-04-03 19:48:32 -0700699 FileDescriptor fd = mPfd.getFileDescriptor();
Lorenzo Colittiaa149022022-01-25 09:59:44 +0900700 mSocket = new LocalSocket(fd);
zzyfab62db2012-04-03 19:48:32 -0700701 mSocketIS = mSocket.getInputStream();
702 mSocketOS = mSocket.getOutputStream();
703 }
704 int channel = readInt(mSocketIS);
Aritra Sena23c9d42023-02-03 11:50:14 +0000705 if (channel == 0) {
706 int errCode = (int) mSocketIS.read();
Aritra Sen8134e952023-03-11 01:03:38 +0000707 throw new BluetoothSocketException(errCode);
Aritra Sena23c9d42023-02-03 11:50:14 +0000708 }
709 if (channel < 0) {
Aritra Sen8134e952023-03-11 01:03:38 +0000710 throw new BluetoothSocketException(
711 BluetoothSocketException.SOCKET_CONNECTION_FAILURE);
Jack He910201b2017-08-22 16:06:54 -0700712 }
zzyfab62db2012-04-03 19:48:32 -0700713 mPort = channel;
714 waitSocketSignal(mSocketIS);
Jack He910201b2017-08-22 16:06:54 -0700715 synchronized (this) {
716 if (mSocketState == SocketState.CLOSED) {
Aritra Sen8134e952023-03-11 01:03:38 +0000717 throw new BluetoothSocketException(BluetoothSocketException.SOCKET_CLOSED);
Jack He910201b2017-08-22 16:06:54 -0700718 }
zzyfab62db2012-04-03 19:48:32 -0700719 mSocketState = SocketState.CONNECTED;
Pomai Ahlo13444752024-03-21 11:24:46 -0700720 Log.i(TAG, "connect(), socket connected. mPort=" + mPort);
zzyfab62db2012-04-03 19:48:32 -0700721 }
Pomai Ahloe28d3cb2023-11-02 17:19:30 -0700722 } catch (BluetoothSocketException e) {
723 SocketMetrics.logSocketConnect(
724 e.getErrorCode(),
Pomai Ahlobc19c022023-11-13 16:37:06 -0800725 socketConnectionTimeNanos,
Pomai Ahloe28d3cb2023-11-02 17:19:30 -0700726 mType,
727 mDevice,
728 mPort,
729 mAuth,
Pomai Ahlobc19c022023-11-13 16:37:06 -0800730 mSocketCreationTimeNanos,
731 mSocketCreationLatencyNanos);
Pomai Ahloe28d3cb2023-11-02 17:19:30 -0700732 throw e;
zzyfab62db2012-04-03 19:48:32 -0700733 } catch (RemoteException e) {
William Escande0cef84c2022-01-10 19:13:28 +0100734 Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
Pomai Ahloe28d3cb2023-11-02 17:19:30 -0700735 SocketMetrics.logSocketConnect(
736 BluetoothSocketException.RPC_FAILURE,
Pomai Ahlobc19c022023-11-13 16:37:06 -0800737 socketConnectionTimeNanos,
Pomai Ahloe28d3cb2023-11-02 17:19:30 -0700738 mType,
739 mDevice,
740 mPort,
741 mAuth,
Pomai Ahlobc19c022023-11-13 16:37:06 -0800742 mSocketCreationTimeNanos,
743 mSocketCreationLatencyNanos);
744 throw new BluetoothSocketException(
745 BluetoothSocketException.RPC_FAILURE, "unable to send RPC: " + e.getMessage());
zzyfab62db2012-04-03 19:48:32 -0700746 }
Pomai Ahloe28d3cb2023-11-02 17:19:30 -0700747 SocketMetrics.logSocketConnect(
748 SocketMetrics.SOCKET_NO_ERROR,
Pomai Ahlobc19c022023-11-13 16:37:06 -0800749 socketConnectionTimeNanos,
Pomai Ahloe28d3cb2023-11-02 17:19:30 -0700750 mType,
751 mDevice,
752 mPort,
753 mAuth,
Pomai Ahlobc19c022023-11-13 16:37:06 -0800754 mSocketCreationTimeNanos,
755 mSocketCreationLatencyNanos);
Matthew Xie638350f2011-05-03 19:50:20 -0700756 }
757
758 /**
David Duarteee52b7e2023-12-02 01:32:11 +0000759 * Currently returns unix errno instead of throwing IOException, so that BluetoothAdapter can
760 * check the error code for EADDRINUSE
Nick Pellyee1402d2009-10-02 20:34:18 -0700761 */
William Escande8dd232d2024-08-19 18:48:11 -0700762 @RequiresBluetoothConnectPermission
William Escande4b414a82024-07-19 15:47:05 -0700763 @RequiresPermission(BLUETOOTH_CONNECT)
Nick Pellyee1402d2009-10-02 20:34:18 -0700764 /*package*/ int bindListen() {
zzyfab62db2012-04-03 19:48:32 -0700765 int ret;
766 if (mSocketState == SocketState.CLOSED) return EBADFD;
Jeff Sharkeya1157db2021-08-10 16:50:52 -0600767 IBluetooth bluetoothProxy = BluetoothAdapter.getDefaultAdapter().getBluetoothService();
fredc3c719642012-04-12 00:02:00 -0700768 if (bluetoothProxy == null) {
769 Log.e(TAG, "bindListen fail, reason: bluetooth is off");
770 return -1;
771 }
Nick Pelly4cd2cd92009-09-02 11:51:35 -0700772 try {
Stanley Tngd67d5e42017-11-22 16:04:40 -0800773 if (DBG) Log.d(TAG, "bindListen(): mPort=" + mPort + ", mType=" + mType);
William Escande0cef84c2022-01-10 19:13:28 +0100774 IBluetoothSocketManager socketManager = bluetoothProxy.getSocketManager();
775 if (socketManager == null) {
776 Log.e(TAG, "bindListen() bt get socket manager failed");
777 return -1;
778 }
David Duarteee52b7e2023-12-02 01:32:11 +0000779 mPfd =
780 socketManager.createSocketChannel(
781 mType, mServiceName, mUuid, mPort, getSecurityFlags());
zzyfab62db2012-04-03 19:48:32 -0700782 } catch (RemoteException e) {
William Escande0cef84c2022-01-10 19:13:28 +0100783 Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
zzyfab62db2012-04-03 19:48:32 -0700784 return -1;
785 }
786
787 // read out port number
788 try {
Jack He910201b2017-08-22 16:06:54 -0700789 synchronized (this) {
790 if (DBG) {
Jack He9e045d22017-08-22 21:21:23 -0700791 Log.d(TAG, "bindListen(), SocketState: " + mSocketState + ", mPfd: " + mPfd);
Jack He910201b2017-08-22 16:06:54 -0700792 }
793 if (mSocketState != SocketState.INIT) return EBADFD;
794 if (mPfd == null) return -1;
zzyfab62db2012-04-03 19:48:32 -0700795 FileDescriptor fd = mPfd.getFileDescriptor();
Ajay Panicker178b0282017-03-28 14:28:27 -0700796 if (fd == null) {
797 Log.e(TAG, "bindListen(), null file descriptor");
798 return -1;
799 }
800
Neil Fuller3dfe08b2017-01-06 11:29:15 +0000801 if (DBG) Log.d(TAG, "bindListen(), Create LocalSocket");
Lorenzo Colittiaa149022022-01-25 09:59:44 +0900802 mSocket = new LocalSocket(fd);
Neil Fuller3dfe08b2017-01-06 11:29:15 +0000803 if (DBG) Log.d(TAG, "bindListen(), new LocalSocket.getInputStream()");
zzyfab62db2012-04-03 19:48:32 -0700804 mSocketIS = mSocket.getInputStream();
805 mSocketOS = mSocket.getOutputStream();
806 }
Joe LaPennaa49d75d2014-05-13 18:17:46 -0700807 if (DBG) Log.d(TAG, "bindListen(), readInt mSocketIS: " + mSocketIS);
zzyfab62db2012-04-03 19:48:32 -0700808 int channel = readInt(mSocketIS);
Jack He910201b2017-08-22 16:06:54 -0700809 synchronized (this) {
810 if (mSocketState == SocketState.INIT) {
zzyfab62db2012-04-03 19:48:32 -0700811 mSocketState = SocketState.LISTENING;
Jack He910201b2017-08-22 16:06:54 -0700812 }
zzyfab62db2012-04-03 19:48:32 -0700813 }
Stanley Tngd67d5e42017-11-22 16:04:40 -0800814 if (DBG) Log.d(TAG, "bindListen(): channel=" + channel + ", mPort=" + mPort);
Casper Bondec0a7c932015-04-09 09:24:48 +0200815 if (mPort <= -1) {
zzyfab62db2012-04-03 19:48:32 -0700816 mPort = channel;
Liang Li77fbb392024-11-14 07:24:14 +0000817 }
zzyfab62db2012-04-03 19:48:32 -0700818 ret = 0;
819 } catch (IOException e) {
Matthew Xie6398bb32014-09-03 10:04:00 -0700820 if (mPfd != null) {
821 try {
822 mPfd.close();
823 } catch (IOException e1) {
824 Log.e(TAG, "bindListen, close mPfd: " + e1);
825 }
826 mPfd = null;
827 }
zzyfab62db2012-04-03 19:48:32 -0700828 Log.e(TAG, "bindListen, fail to get port number, exception: " + e);
829 return -1;
830 }
831 return ret;
Nick Pelly4cd2cd92009-09-02 11:51:35 -0700832 }
833
Liang Li77fbb392024-11-14 07:24:14 +0000834 /**
835 * Currently returns unix errno instead of throwing IOException, so that BluetoothAdapter can
836 * check the error code for EADDRINUSE
837 */
838 @RequiresBluetoothConnectPermission
839 @RequiresPermission(
840 allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED},
841 conditional = true)
842 /*package*/ int bindListenWithOffload() {
843 int ret;
844 if (mSocketState == SocketState.CLOSED) return EBADFD;
845 IBluetooth bluetoothProxy = BluetoothAdapter.getDefaultAdapter().getBluetoothService();
846 if (bluetoothProxy == null) {
847 Log.e(TAG, "bindListenWithOffload() fail, reason: bluetooth is off");
848 return -1;
849 }
850 try {
851 if (DBG) Log.d(TAG, "bindListenWithOffload(): mPort=" + mPort + ", mType=" + mType);
852 IBluetoothSocketManager socketManager = bluetoothProxy.getSocketManager();
853 if (socketManager == null) {
854 Log.e(TAG, "bindListenWithOffload() bt get socket manager failed");
855 return -1;
856 }
857 mPfd =
858 socketManager.createSocketChannelWithOffload(
859 mType,
860 mServiceName,
861 mUuid,
862 mPort,
863 getSecurityFlags(),
864 mDataPath,
865 mSocketName,
866 mHubId,
867 mEndpointId,
868 mMaximumPacketSize);
869 } catch (RemoteException e) {
870 Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
871 return -1;
872 }
873
874 // read out port number
875 try {
876 synchronized (this) {
877 if (DBG) {
878 Log.d(
879 TAG,
880 "bindListenWithOffload(), SocketState: "
881 + mSocketState
882 + ", mPfd: "
883 + mPfd);
884 }
885 if (mSocketState != SocketState.INIT) return EBADFD;
886 if (mPfd == null) return -1;
887 FileDescriptor fd = mPfd.getFileDescriptor();
888 if (fd == null) {
889 Log.e(TAG, "bindListenWithOffload(), null file descriptor");
890 return -1;
891 }
892
893 if (DBG) Log.d(TAG, "bindListenWithOffload(), Create LocalSocket");
894 mSocket = new LocalSocket(fd);
895 if (DBG) Log.d(TAG, "bindListenWithOffload(), new LocalSocket.getInputStream()");
896 mSocketIS = mSocket.getInputStream();
897 mSocketOS = mSocket.getOutputStream();
898 }
899 if (DBG) Log.d(TAG, "bindListenWithOffload(), readInt mSocketIS: " + mSocketIS);
900 int channel = readInt(mSocketIS);
901 synchronized (this) {
902 if (mSocketState == SocketState.INIT) {
903 mSocketState = SocketState.LISTENING;
904 }
905 }
906 if (DBG) Log.d(TAG, "bindListenWithOffload(): channel=" + channel + ", mPort=" + mPort);
907 if (mPort <= -1) {
908 mPort = channel;
909 }
910 ret = 0;
911 } catch (IOException e) {
912 if (mPfd != null) {
913 try {
914 mPfd.close();
915 } catch (IOException e1) {
916 Log.e(TAG, "bindListenWithOffload, close mPfd: " + e1);
917 }
918 mPfd = null;
919 }
920 Log.e(TAG, "bindListenWithOffload, fail to get port number, exception: " + e);
921 return -1;
922 }
923 return ret;
924 }
925
Nick Pelly4cd2cd92009-09-02 11:51:35 -0700926 /*package*/ BluetoothSocket accept(int timeout) throws IOException {
zzyfab62db2012-04-03 19:48:32 -0700927 BluetoothSocket acceptedSocket;
Jack He910201b2017-08-22 16:06:54 -0700928 if (mSocketState != SocketState.LISTENING) {
Casper Bondec0a7c932015-04-09 09:24:48 +0200929 throw new IOException("bt socket is not in listen state");
Jack He910201b2017-08-22 16:06:54 -0700930 }
Ugo Yub6dc15a2022-12-28 20:18:00 +0800931 Log.d(TAG, "accept(), timeout (ms):" + timeout);
Jack He910201b2017-08-22 16:06:54 -0700932 if (timeout > 0) {
Jack He910201b2017-08-22 16:06:54 -0700933 mSocket.setSoTimeout(timeout);
zzy2e650b32012-11-22 11:52:44 -0800934 }
Liang Li88ba5e02024-11-14 19:07:45 +0000935 sendSocketAcceptSignal(mSocketOS, true);
936 String RemoteAddr;
937 try {
938 RemoteAddr = waitSocketSignal(mSocketIS);
939 } finally {
940 sendSocketAcceptSignal(mSocketOS, false);
941 }
Jack He910201b2017-08-22 16:06:54 -0700942 if (timeout > 0) {
zzy2e650b32012-11-22 11:52:44 -0800943 mSocket.setSoTimeout(0);
Jack He910201b2017-08-22 16:06:54 -0700944 }
945 synchronized (this) {
946 if (mSocketState != SocketState.LISTENING) {
zzyfab62db2012-04-03 19:48:32 -0700947 throw new IOException("bt socket is not in listen state");
Jack He910201b2017-08-22 16:06:54 -0700948 }
zzyfab62db2012-04-03 19:48:32 -0700949 acceptedSocket = acceptSocket(RemoteAddr);
David Duarteee52b7e2023-12-02 01:32:11 +0000950 // quick drop the reference of the file handle
Nick Pelly4cd2cd92009-09-02 11:51:35 -0700951 }
zzyfab62db2012-04-03 19:48:32 -0700952 return acceptedSocket;
Nick Pelly4cd2cd92009-09-02 11:51:35 -0700953 }
954
955 /*package*/ int available() throws IOException {
Matthew Xief8035a72012-10-09 22:10:37 -0700956 if (VDBG) Log.d(TAG, "available: " + mSocketIS);
zzyfab62db2012-04-03 19:48:32 -0700957 return mSocketIS.available();
Nick Pelly4cd2cd92009-09-02 11:51:35 -0700958 }
Jack He910201b2017-08-22 16:06:54 -0700959
Nick Pelly4cd2cd92009-09-02 11:51:35 -0700960 /*package*/ int read(byte[] b, int offset, int length) throws IOException {
Casper Bondec0a7c932015-04-09 09:24:48 +0200961 int ret = 0;
Zhihai Xuf4f4b3b2013-12-17 11:39:20 -0800962 if (VDBG) Log.d(TAG, "read in: " + mSocketIS + " len: " + length);
Stanley Tngd67d5e42017-11-22 16:04:40 -0800963 if ((mType == TYPE_L2CAP) || (mType == TYPE_L2CAP_LE)) {
Casper Bondec0a7c932015-04-09 09:24:48 +0200964 int bytesToRead = length;
Jack He910201b2017-08-22 16:06:54 -0700965 if (VDBG) {
David Duarteee52b7e2023-12-02 01:32:11 +0000966 Log.v(
967 TAG,
968 "l2cap: read(): offset: "
969 + offset
970 + " length:"
971 + length
972 + "mL2capBuffer= "
973 + mL2capBuffer);
Jack He910201b2017-08-22 16:06:54 -0700974 }
Casper Bondec0a7c932015-04-09 09:24:48 +0200975 if (mL2capBuffer == null) {
976 createL2capRxBuffer();
977 }
978 if (mL2capBuffer.remaining() == 0) {
979 if (VDBG) Log.v(TAG, "l2cap buffer empty, refilling...");
980 if (fillL2capRxBuffer() == -1) {
Jack Hef59c8962025-01-09 15:26:42 -0800981 throw new IOException("bt socket closed, read return: " + ret);
Casper Bondec0a7c932015-04-09 09:24:48 +0200982 }
983 }
984 if (bytesToRead > mL2capBuffer.remaining()) {
985 bytesToRead = mL2capBuffer.remaining();
986 }
Jack He910201b2017-08-22 16:06:54 -0700987 if (VDBG) {
David Duarteee52b7e2023-12-02 01:32:11 +0000988 Log.v(TAG, "get(): offset: " + offset + " bytesToRead: " + bytesToRead);
Jack He910201b2017-08-22 16:06:54 -0700989 }
Casper Bondec0a7c932015-04-09 09:24:48 +0200990 mL2capBuffer.get(b, offset, bytesToRead);
991 ret = bytesToRead;
Jack He910201b2017-08-22 16:06:54 -0700992 } else {
Casper Bondec0a7c932015-04-09 09:24:48 +0200993 if (VDBG) Log.v(TAG, "default: read(): offset: " + offset + " length:" + length);
994 ret = mSocketIS.read(b, offset, length);
995 }
Jack He910201b2017-08-22 16:06:54 -0700996 if (ret < 0) {
Jack Hef59c8962025-01-09 15:26:42 -0800997 throw new IOException("bt socket closed, read return: " + ret);
Jack He910201b2017-08-22 16:06:54 -0700998 }
Zhihai Xuf4f4b3b2013-12-17 11:39:20 -0800999 if (VDBG) Log.d(TAG, "read out: " + mSocketIS + " ret: " + ret);
1000 return ret;
Nick Pelly4cd2cd92009-09-02 11:51:35 -07001001 }
1002
1003 /*package*/ int write(byte[] b, int offset, int length) throws IOException {
Casper Bondec0a7c932015-04-09 09:24:48 +02001004
David Duarteee52b7e2023-12-02 01:32:11 +00001005 // TODO: Since bindings can exist between the SDU size and the
Casper Bondec0a7c932015-04-09 09:24:48 +02001006 // protocol, we might need to throw an exception instead of just
1007 // splitting the write into multiple smaller writes.
1008 // Rfcomm uses dynamic allocation, and should not have any bindings
1009 // to the actual message length.
Jack He910201b2017-08-22 16:06:54 -07001010 if (VDBG) Log.d(TAG, "write: " + mSocketOS + " length: " + length);
Stanley Tngd67d5e42017-11-22 16:04:40 -08001011 if ((mType == TYPE_L2CAP) || (mType == TYPE_L2CAP_LE)) {
Jack He910201b2017-08-22 16:06:54 -07001012 if (length <= mMaxTxPacketSize) {
1013 mSocketOS.write(b, offset, length);
1014 } else {
1015 if (DBG) {
David Duarteee52b7e2023-12-02 01:32:11 +00001016 Log.w(
1017 TAG,
1018 "WARNING: Write buffer larger than L2CAP packet size!\n"
1019 + "Packet will be divided into SDU packets of size "
1020 + mMaxTxPacketSize);
Casper Bondec0a7c932015-04-09 09:24:48 +02001021 }
Jack He910201b2017-08-22 16:06:54 -07001022 int tmpOffset = offset;
1023 int bytesToWrite = length;
1024 while (bytesToWrite > 0) {
David Duarteee52b7e2023-12-02 01:32:11 +00001025 int tmpLength =
1026 (bytesToWrite > mMaxTxPacketSize) ? mMaxTxPacketSize : bytesToWrite;
Jack He910201b2017-08-22 16:06:54 -07001027 mSocketOS.write(b, tmpOffset, tmpLength);
1028 tmpOffset += tmpLength;
1029 bytesToWrite -= tmpLength;
1030 }
Casper Bondec0a7c932015-04-09 09:24:48 +02001031 }
Jack He910201b2017-08-22 16:06:54 -07001032 } else {
1033 mSocketOS.write(b, offset, length);
1034 }
1035 // There is no good way to confirm since the entire process is asynchronous anyway
1036 if (VDBG) Log.d(TAG, "write out: " + mSocketOS + " length: " + length);
1037 return length;
Nick Pelly4cd2cd92009-09-02 11:51:35 -07001038 }
1039
zzyfab62db2012-04-03 19:48:32 -07001040 @Override
1041 public void close() throws IOException {
David Duarteee52b7e2023-12-02 01:32:11 +00001042 Log.d(
1043 TAG,
1044 "close() this: "
1045 + this
1046 + ", channel: "
1047 + mPort
1048 + ", mSocketIS: "
1049 + mSocketIS
1050 + ", mSocketOS: "
1051 + mSocketOS
1052 + ", mSocket: "
1053 + mSocket
1054 + ", mSocketState: "
1055 + mSocketState);
Jack He910201b2017-08-22 16:06:54 -07001056 if (mSocketState == SocketState.CLOSED) {
zzyfab62db2012-04-03 19:48:32 -07001057 return;
Jack He910201b2017-08-22 16:06:54 -07001058 } else {
1059 synchronized (this) {
1060 if (mSocketState == SocketState.CLOSED) {
zzyfab62db2012-04-03 19:48:32 -07001061 return;
Jack He910201b2017-08-22 16:06:54 -07001062 }
1063 mSocketState = SocketState.CLOSED;
1064 if (mSocket != null) {
Joe LaPennaa49d75d2014-05-13 18:17:46 -07001065 if (DBG) Log.d(TAG, "Closing mSocket: " + mSocket);
zzyfab62db2012-04-03 19:48:32 -07001066 mSocket.shutdownInput();
1067 mSocket.shutdownOutput();
1068 mSocket.close();
1069 mSocket = null;
1070 }
Zhihai Xu0ad59162014-01-20 12:04:23 -08001071 if (mPfd != null) {
1072 mPfd.close();
1073 mPfd = null;
1074 }
Jayden Kim815a8c92024-03-17 07:48:36 +00001075 mConnectionUuid = null;
Liang Li77fbb392024-11-14 07:24:14 +00001076 mSocketId = INVALID_SOCKET_ID;
Jack He910201b2017-08-22 16:06:54 -07001077 }
Nick Pelly07b84cb2009-10-07 07:44:03 +02001078 }
zzyfab62db2012-04-03 19:48:32 -07001079 }
Nick Pelly07b84cb2009-10-07 07:44:03 +02001080
David Duarteee52b7e2023-12-02 01:32:11 +00001081 /*package */ void removeChannel() {}
Nick Pelly07b84cb2009-10-07 07:44:03 +02001082
zzyfab62db2012-04-03 19:48:32 -07001083 /*package */ int getPort() {
1084 return mPort;
1085 }
Casper Bondec0a7c932015-04-09 09:24:48 +02001086
Chen Chen696b3562023-02-23 14:27:08 -08001087 /*package */ long getSocketCreationTime() {
Pomai Ahlobc19c022023-11-13 16:37:06 -08001088 return mSocketCreationTimeNanos;
Chen Chen696b3562023-02-23 14:27:08 -08001089 }
1090
Casper Bondec0a7c932015-04-09 09:24:48 +02001091 /**
David Duarteee52b7e2023-12-02 01:32:11 +00001092 * Get the maximum supported Transmit packet size for the underlying transport. Use this to
1093 * optimize the writes done to the output socket, to avoid sending half full packets.
Jack He910201b2017-08-22 16:06:54 -07001094 *
Casper Bondec0a7c932015-04-09 09:24:48 +02001095 * @return the maximum supported Transmit packet size for the underlying transport.
1096 */
Jeff Sharkey5ba8bfc2021-04-16 09:53:23 -06001097 @RequiresNoPermission
Jack He910201b2017-08-22 16:06:54 -07001098 public int getMaxTransmitPacketSize() {
Casper Bondec0a7c932015-04-09 09:24:48 +02001099 return mMaxTxPacketSize;
1100 }
1101
1102 /**
David Duarteee52b7e2023-12-02 01:32:11 +00001103 * Get the maximum supported Receive packet size for the underlying transport. Use this to
1104 * optimize the reads done on the input stream, as any call to read will return a maximum of
1105 * this amount of bytes - or for some transports a multiple of this value.
Jack He910201b2017-08-22 16:06:54 -07001106 *
Casper Bondec0a7c932015-04-09 09:24:48 +02001107 * @return the maximum supported Receive packet size for the underlying transport.
1108 */
Jeff Sharkey5ba8bfc2021-04-16 09:53:23 -06001109 @RequiresNoPermission
Jack He910201b2017-08-22 16:06:54 -07001110 public int getMaxReceivePacketSize() {
Casper Bondec0a7c932015-04-09 09:24:48 +02001111 return mMaxRxPacketSize;
1112 }
1113
1114 /**
Andre Eisenbach660bff72015-05-04 13:48:50 -07001115 * Get the type of the underlying connection.
Jack He910201b2017-08-22 16:06:54 -07001116 *
Andre Eisenbach660bff72015-05-04 13:48:50 -07001117 * @return one of {@link #TYPE_RFCOMM}, {@link #TYPE_SCO} or {@link #TYPE_L2CAP}
Casper Bondec0a7c932015-04-09 09:24:48 +02001118 */
Jeff Sharkey5ba8bfc2021-04-16 09:53:23 -06001119 @RequiresNoPermission
Casper Bondec0a7c932015-04-09 09:24:48 +02001120 public int getConnectionType() {
Stanley Tng412cbec2018-06-29 14:05:04 -07001121 if (mType == TYPE_L2CAP_LE) {
1122 // Treat the LE CoC to be the same type as L2CAP.
1123 return TYPE_L2CAP;
1124 }
Casper Bondec0a7c932015-04-09 09:24:48 +02001125 return mType;
1126 }
1127
1128 /**
David Duarteee52b7e2023-12-02 01:32:11 +00001129 * Change if a SDP entry should be automatically created. Must be called before calling .bind,
1130 * for the call to have any effect.
Jack He910201b2017-08-22 16:06:54 -07001131 *
David Duarteee52b7e2023-12-02 01:32:11 +00001132 * @param excludeSdp
1133 * <li>TRUE - do not auto generate SDP record.
1134 * <li>FALSE - default - auto generate SPP SDP record.
Casper Bondec0a7c932015-04-09 09:24:48 +02001135 * @hide
1136 */
Jeff Sharkey5ba8bfc2021-04-16 09:53:23 -06001137 @RequiresNoPermission
Casper Bondec0a7c932015-04-09 09:24:48 +02001138 public void setExcludeSdp(boolean excludeSdp) {
Jack He9e045d22017-08-22 21:21:23 -07001139 mExcludeSdp = excludeSdp;
Casper Bondec0a7c932015-04-09 09:24:48 +02001140 }
1141
Stanley Tngcf3cfd32018-01-16 10:39:32 -08001142 /**
1143 * Set the LE Transmit Data Length to be the maximum that the BT Controller is capable of. This
1144 * parameter is used by the BT Controller to set the maximum transmission packet size on this
1145 * connection. This function is currently used for testing only.
David Duarteee52b7e2023-12-02 01:32:11 +00001146 *
Stanley Tngcf3cfd32018-01-16 10:39:32 -08001147 * @hide
1148 */
Jeff Sharkey5ba8bfc2021-04-16 09:53:23 -06001149 @RequiresBluetoothConnectPermission
William Escande4b414a82024-07-19 15:47:05 -07001150 @RequiresPermission(BLUETOOTH_CONNECT)
Stanley Tngcf3cfd32018-01-16 10:39:32 -08001151 public void requestMaximumTxDataLength() throws IOException {
1152 if (mDevice == null) {
1153 throw new IOException("requestMaximumTxDataLength is called on null device");
1154 }
1155
1156 try {
1157 if (mSocketState == SocketState.CLOSED) {
1158 throw new IOException("socket closed");
1159 }
David Duarteee52b7e2023-12-02 01:32:11 +00001160 IBluetooth bluetoothProxy = BluetoothAdapter.getDefaultAdapter().getBluetoothService();
Stanley Tngcf3cfd32018-01-16 10:39:32 -08001161 if (bluetoothProxy == null) {
1162 throw new IOException("Bluetooth is off");
1163 }
1164
1165 if (DBG) Log.d(TAG, "requestMaximumTxDataLength");
William Escande0cef84c2022-01-10 19:13:28 +01001166 IBluetoothSocketManager socketManager = bluetoothProxy.getSocketManager();
1167 if (socketManager == null) throw new IOException("bt get socket manager failed");
1168 socketManager.requestMaximumTxDataLength(mDevice);
Stanley Tngcf3cfd32018-01-16 10:39:32 -08001169 } catch (RemoteException e) {
William Escande0cef84c2022-01-10 19:13:28 +01001170 Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
Stanley Tngcf3cfd32018-01-16 10:39:32 -08001171 throw new IOException("unable to send RPC: " + e.getMessage());
1172 }
1173 }
1174
Jayden Kim34602a42024-02-21 18:47:40 +00001175 /**
1176 * Returns the L2CAP local channel ID associated with an open connection to this socket.
1177 *
1178 * @return the L2CAP local channel ID.
1179 * @throws BluetoothSocketException in case of failure, with the corresponding error code.
1180 * @hide
1181 */
1182 @SystemApi
1183 @FlaggedApi(Flags.FLAG_BT_SOCKET_API_L2CAP_CID)
William Escande8dd232d2024-08-19 18:48:11 -07001184 @RequiresBluetoothConnectPermission
1185 @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED})
Jayden Kim34602a42024-02-21 18:47:40 +00001186 public int getL2capLocalChannelId() throws IOException {
Jayden Kim815a8c92024-03-17 07:48:36 +00001187 if (mType != TYPE_L2CAP_LE) {
1188 throw new BluetoothSocketException(BluetoothSocketException.L2CAP_UNKNOWN);
1189 }
1190 if (mSocketState != SocketState.CONNECTED || mConnectionUuid == null) {
1191 throw new BluetoothSocketException(BluetoothSocketException.SOCKET_CLOSED);
1192 }
1193 int cid;
Jayden Kim34602a42024-02-21 18:47:40 +00001194 IBluetooth bluetoothProxy = BluetoothAdapter.getDefaultAdapter().getBluetoothService();
1195 if (bluetoothProxy == null) {
1196 throw new BluetoothSocketException(BluetoothSocketException.BLUETOOTH_OFF_FAILURE);
1197 }
1198 try {
1199 IBluetoothSocketManager socketManager = bluetoothProxy.getSocketManager();
1200 if (socketManager == null) {
1201 throw new BluetoothSocketException(BluetoothSocketException.SOCKET_MANAGER_FAILURE);
1202 }
Jayden Kim815a8c92024-03-17 07:48:36 +00001203 cid =
1204 socketManager.getL2capLocalChannelId(
1205 mConnectionUuid, AttributionSource.myAttributionSource());
Jayden Kim34602a42024-02-21 18:47:40 +00001206 } catch (RemoteException e) {
1207 Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
1208 throw new IOException("unable to send RPC: " + e.getMessage());
1209 }
Jayden Kim815a8c92024-03-17 07:48:36 +00001210 if (cid == -1) {
Jayden Kim34602a42024-02-21 18:47:40 +00001211 throw new BluetoothSocketException(BluetoothSocketException.SOCKET_CLOSED);
1212 }
Jayden Kim815a8c92024-03-17 07:48:36 +00001213 return cid;
Jayden Kim34602a42024-02-21 18:47:40 +00001214 }
1215
1216 /**
1217 * Returns the L2CAP remote channel ID associated with an open connection to this socket.
1218 *
1219 * @return the L2CAP remote channel ID.
1220 * @throws BluetoothSocketException in case of failure, with the corresponding error code.
1221 * @hide
1222 */
1223 @SystemApi
1224 @FlaggedApi(Flags.FLAG_BT_SOCKET_API_L2CAP_CID)
William Escande8dd232d2024-08-19 18:48:11 -07001225 @RequiresBluetoothConnectPermission
1226 @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED})
Jayden Kim34602a42024-02-21 18:47:40 +00001227 public int getL2capRemoteChannelId() throws IOException {
Jayden Kim815a8c92024-03-17 07:48:36 +00001228 if (mType != TYPE_L2CAP_LE) {
1229 throw new BluetoothSocketException(BluetoothSocketException.L2CAP_UNKNOWN);
1230 }
1231 if (mSocketState != SocketState.CONNECTED || mConnectionUuid == null) {
1232 throw new BluetoothSocketException(BluetoothSocketException.SOCKET_CLOSED);
1233 }
1234 int cid;
Jayden Kim34602a42024-02-21 18:47:40 +00001235 IBluetooth bluetoothProxy = BluetoothAdapter.getDefaultAdapter().getBluetoothService();
1236 if (bluetoothProxy == null) {
1237 throw new BluetoothSocketException(BluetoothSocketException.BLUETOOTH_OFF_FAILURE);
1238 }
1239 try {
1240 IBluetoothSocketManager socketManager = bluetoothProxy.getSocketManager();
1241 if (socketManager == null) {
1242 throw new BluetoothSocketException(BluetoothSocketException.SOCKET_MANAGER_FAILURE);
1243 }
Jayden Kim815a8c92024-03-17 07:48:36 +00001244 cid =
1245 socketManager.getL2capRemoteChannelId(
1246 mConnectionUuid, AttributionSource.myAttributionSource());
Jayden Kim34602a42024-02-21 18:47:40 +00001247 } catch (RemoteException e) {
1248 Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
1249 throw new IOException("unable to send RPC: " + e.getMessage());
1250 }
Jayden Kim815a8c92024-03-17 07:48:36 +00001251 if (cid == -1) {
Jayden Kim34602a42024-02-21 18:47:40 +00001252 throw new BluetoothSocketException(BluetoothSocketException.SOCKET_CLOSED);
1253 }
Jayden Kim815a8c92024-03-17 07:48:36 +00001254 return cid;
Jayden Kim34602a42024-02-21 18:47:40 +00001255 }
1256
Liang Li77fbb392024-11-14 07:24:14 +00001257 /**
1258 * Returns the socket ID assigned to the open connection on this BluetoothSocket. This socket ID
1259 * is a unique identifier for the socket. It is valid only while the socket is connected.
1260 *
1261 * @return The socket ID in connected state.
1262 * @throws BluetoothSocketException If the socket is not connected or an error occurs while
1263 * retrieving the socket ID.
1264 * @hide
1265 */
1266 @SystemApi
1267 @FlaggedApi(Flags.FLAG_SOCKET_SETTINGS_API)
1268 @RequiresNoPermission
1269 public long getSocketId() throws IOException {
1270 if (mSocketState != SocketState.CONNECTED || mSocketId == INVALID_SOCKET_ID) {
1271 throw new BluetoothSocketException(BluetoothSocketException.SOCKET_CLOSED);
1272 }
1273 return mSocketId;
1274 }
1275
tadvanae6718402022-01-26 10:35:38 -08001276 /** @hide */
William Escande8dd232d2024-08-19 18:48:11 -07001277 @RequiresNoPermission
tadvanae6718402022-01-26 10:35:38 -08001278 public ParcelFileDescriptor getParcelFileDescriptor() {
1279 return mPfd;
1280 }
1281
Jack He910201b2017-08-22 16:06:54 -07001282 private String convertAddr(final byte[] addr) {
David Duarteee52b7e2023-12-02 01:32:11 +00001283 return String.format(
1284 Locale.US,
1285 "%02X:%02X:%02X:%02X:%02X:%02X",
1286 addr[0],
1287 addr[1],
1288 addr[2],
1289 addr[3],
1290 addr[4],
1291 addr[5]);
zzyfab62db2012-04-03 19:48:32 -07001292 }
Jack He910201b2017-08-22 16:06:54 -07001293
Liang Li88ba5e02024-11-14 19:07:45 +00001294 /**
1295 * Sends a socket accept signal to the host stack.
1296 *
1297 * <p>This method is used to notify the host stack whether the host application is actively
1298 * accepting a new connection or not. It sends a signal containing the acceptance status to the
1299 * output stream associated with the socket.
1300 *
1301 * <p>This method is only effective when the data path is not {@link
1302 * BluetoothSocketSettings#DATA_PATH_NO_OFFLOAD}.
1303 *
1304 * @param os The output stream to write the signal to.
1305 * @param isAccepting {@code true} if the socket connection is being accepted, {@code false}
1306 * otherwise.
1307 * @throws IOException If an I/O error occurs while writing to the output stream.
1308 * @hide
1309 */
1310 private void sendSocketAcceptSignal(OutputStream os, boolean isAccepting) throws IOException {
1311 if (Flags.socketSettingsApi()) {
1312 if (mDataPath == BluetoothSocketSettings.DATA_PATH_NO_OFFLOAD) {
1313 return;
1314 }
1315 Log.d(TAG, "sendSocketAcceptSignal" + " isAccepting " + isAccepting);
1316 byte[] sig = new byte[SOCK_ACCEPT_SIGNAL_SIZE];
1317 ByteBuffer bb = ByteBuffer.wrap(sig);
1318 bb.order(ByteOrder.nativeOrder());
1319 bb.putShort((short) SOCK_ACCEPT_SIGNAL_SIZE);
1320 bb.putShort((short) (isAccepting ? 1 : 0));
1321 os.write(sig, 0, SOCK_ACCEPT_SIGNAL_SIZE);
1322 }
1323 }
1324
zzyfab62db2012-04-03 19:48:32 -07001325 private String waitSocketSignal(InputStream is) throws IOException {
Liang Li77fbb392024-11-14 07:24:14 +00001326 byte[] sig = new byte[SOCK_CONNECTION_SIGNAL_SIZE];
zzyfab62db2012-04-03 19:48:32 -07001327 int ret = readAll(is, sig);
Jack He910201b2017-08-22 16:06:54 -07001328 if (VDBG) {
Liang Li77fbb392024-11-14 07:24:14 +00001329 Log.d(
1330 TAG,
1331 "waitSocketSignal read "
1332 + SOCK_CONNECTION_SIGNAL_SIZE
1333 + " bytes signal ret: "
1334 + ret);
Jack He910201b2017-08-22 16:06:54 -07001335 }
zzyfab62db2012-04-03 19:48:32 -07001336 ByteBuffer bb = ByteBuffer.wrap(sig);
Casper Bondec0a7c932015-04-09 09:24:48 +02001337 /* the struct in native is decorated with __attribute__((packed)), hence this is possible */
zzyfab62db2012-04-03 19:48:32 -07001338 bb.order(ByteOrder.nativeOrder());
1339 int size = bb.getShort();
Liang Li77fbb392024-11-14 07:24:14 +00001340 if (size != SOCK_CONNECTION_SIGNAL_SIZE) {
zzy2e650b32012-11-22 11:52:44 -08001341 throw new IOException("Connection failure, wrong signal size: " + size);
Jack He910201b2017-08-22 16:06:54 -07001342 }
1343 byte[] addr = new byte[6];
zzyfab62db2012-04-03 19:48:32 -07001344 bb.get(addr);
1345 int channel = bb.getInt();
1346 int status = bb.getInt();
Casper Bondec0a7c932015-04-09 09:24:48 +02001347 mMaxTxPacketSize = (bb.getShort() & 0xffff); // Convert to unsigned value
1348 mMaxRxPacketSize = (bb.getShort() & 0xffff); // Convert to unsigned value
Jayden Kim815a8c92024-03-17 07:48:36 +00001349 long uuidLsb = bb.getLong();
1350 long uuidMsb = bb.getLong();
1351 mConnectionUuid = new ParcelUuid(new UUID(uuidMsb, uuidLsb));
Liang Li77fbb392024-11-14 07:24:14 +00001352 mSocketId = bb.getLong();
zzyfab62db2012-04-03 19:48:32 -07001353 String RemoteAddr = convertAddr(addr);
Jack He910201b2017-08-22 16:06:54 -07001354 if (VDBG) {
David Duarteee52b7e2023-12-02 01:32:11 +00001355 Log.d(
1356 TAG,
1357 "waitSocketSignal: sig size: "
1358 + size
1359 + ", remote addr: "
1360 + RemoteAddr
1361 + ", channel: "
1362 + channel
1363 + ", status: "
1364 + status
1365 + " MaxRxPktSize: "
1366 + mMaxRxPacketSize
1367 + " MaxTxPktSize: "
Jayden Kim34602a42024-02-21 18:47:40 +00001368 + mMaxTxPacketSize
Jayden Kim815a8c92024-03-17 07:48:36 +00001369 + " mConnectionUuid: "
Liang Li77fbb392024-11-14 07:24:14 +00001370 + mConnectionUuid.toString()
1371 + " mSocketId: "
1372 + mSocketId);
Jack He910201b2017-08-22 16:06:54 -07001373 }
1374 if (status != 0) {
zzyfab62db2012-04-03 19:48:32 -07001375 throw new IOException("Connection failure, status: " + status);
Jack He910201b2017-08-22 16:06:54 -07001376 }
zzyfab62db2012-04-03 19:48:32 -07001377 return RemoteAddr;
1378 }
Casper Bondec0a7c932015-04-09 09:24:48 +02001379
Jack He910201b2017-08-22 16:06:54 -07001380 private void createL2capRxBuffer() {
Stanley Tngd67d5e42017-11-22 16:04:40 -08001381 if ((mType == TYPE_L2CAP) || (mType == TYPE_L2CAP_LE)) {
Casper Bondec0a7c932015-04-09 09:24:48 +02001382 // Allocate the buffer to use for reads.
Jack He910201b2017-08-22 16:06:54 -07001383 if (VDBG) Log.v(TAG, " Creating mL2capBuffer: mMaxPacketSize: " + mMaxRxPacketSize);
Casper Bondec0a7c932015-04-09 09:24:48 +02001384 mL2capBuffer = ByteBuffer.wrap(new byte[mMaxRxPacketSize]);
Jack He910201b2017-08-22 16:06:54 -07001385 if (VDBG) Log.v(TAG, "mL2capBuffer.remaining()" + mL2capBuffer.remaining());
Casper Bondec0a7c932015-04-09 09:24:48 +02001386 mL2capBuffer.limit(0); // Ensure we do a real read at the first read-request
Jack He910201b2017-08-22 16:06:54 -07001387 if (VDBG) {
Jack He9e045d22017-08-22 21:21:23 -07001388 Log.v(TAG, "mL2capBuffer.remaining() after limit(0):" + mL2capBuffer.remaining());
Jack He910201b2017-08-22 16:06:54 -07001389 }
Casper Bondec0a7c932015-04-09 09:24:48 +02001390 }
1391 }
1392
zzyfab62db2012-04-03 19:48:32 -07001393 private int readAll(InputStream is, byte[] b) throws IOException {
1394 int left = b.length;
Jack He910201b2017-08-22 16:06:54 -07001395 while (left > 0) {
zzyfab62db2012-04-03 19:48:32 -07001396 int ret = is.read(b, b.length - left, left);
Jack He910201b2017-08-22 16:06:54 -07001397 if (ret <= 0) {
David Duarteee52b7e2023-12-02 01:32:11 +00001398 throw new IOException(
1399 "read failed, socket might closed or timeout, read ret: " + ret);
Jack He910201b2017-08-22 16:06:54 -07001400 }
zzyfab62db2012-04-03 19:48:32 -07001401 left -= ret;
Jack He910201b2017-08-22 16:06:54 -07001402 if (left != 0) {
David Duarteee52b7e2023-12-02 01:32:11 +00001403 Log.w(
1404 TAG,
1405 "readAll() looping, read partial size: "
1406 + (b.length - left)
1407 + ", expect size: "
1408 + b.length);
Jack He910201b2017-08-22 16:06:54 -07001409 }
Nick Pelly07b84cb2009-10-07 07:44:03 +02001410 }
zzyfab62db2012-04-03 19:48:32 -07001411 return b.length;
1412 }
1413
1414 private int readInt(InputStream is) throws IOException {
1415 byte[] ibytes = new byte[4];
1416 int ret = readAll(is, ibytes);
Matthew Xief8035a72012-10-09 22:10:37 -07001417 if (VDBG) Log.d(TAG, "inputStream.read ret: " + ret);
zzyfab62db2012-04-03 19:48:32 -07001418 ByteBuffer bb = ByteBuffer.wrap(ibytes);
1419 bb.order(ByteOrder.nativeOrder());
1420 return bb.getInt();
Nick Pelly07b84cb2009-10-07 07:44:03 +02001421 }
Casper Bondec0a7c932015-04-09 09:24:48 +02001422
1423 private int fillL2capRxBuffer() throws IOException {
1424 mL2capBuffer.rewind();
1425 int ret = mSocketIS.read(mL2capBuffer.array());
Jack He910201b2017-08-22 16:06:54 -07001426 if (ret == -1) {
Casper Bondec0a7c932015-04-09 09:24:48 +02001427 // reached end of stream - return -1
1428 mL2capBuffer.limit(0);
1429 return -1;
1430 }
1431 mL2capBuffer.limit(ret);
1432 return ret;
1433 }
1434
William Escandee5975fe2022-06-21 16:52:06 -07001435 @Override
1436 public String toString() {
1437 return BluetoothUtils.toAnonymizedAddress(mAddress);
1438 }
Nick Pelly53f441b2009-05-26 19:13:43 -07001439}