blob: e68a9082f05dc5ebd740c312b9b91505abc1e40a [file] [log] [blame]
Nick Pelly53f441b2009-05-26 19:13:43 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.bluetooth;
18
Chen Chen874e7b02023-03-07 17:37:43 -080019import static android.bluetooth.BluetoothUtils.getSyncTimeout;
20
Jeff Sharkey5ba8bfc2021-04-16 09:53:23 -060021import android.annotation.SuppressLint;
Artur Satayevd8fe38c2019-12-10 17:47:52 +000022import android.compat.annotation.UnsupportedAppUsage;
Nick Pellyee1402d2009-10-02 20:34:18 -070023import android.os.Handler;
zzyfab62db2012-04-03 19:48:32 -070024import android.os.ParcelUuid;
Chen Chen874e7b02023-03-07 17:37:43 -080025import android.os.RemoteException;
Casper Bondec0a7c932015-04-09 09:24:48 +020026import android.util.Log;
Nick Pellyee1402d2009-10-02 20:34:18 -070027
Chen Chen874e7b02023-03-07 17:37:43 -080028import com.android.modules.utils.SynchronousResultReceiver;
29
Nick Pelly53f441b2009-05-26 19:13:43 -070030import java.io.Closeable;
31import java.io.IOException;
Chen Chen874e7b02023-03-07 17:37:43 -080032import java.util.concurrent.TimeoutException;
Nick Pelly53f441b2009-05-26 19:13:43 -070033
34/**
Nick Pelly753da532009-08-19 11:00:00 -070035 * A listening Bluetooth socket.
Nick Pelly53f441b2009-05-26 19:13:43 -070036 *
Nick Pelly753da532009-08-19 11:00:00 -070037 * <p>The interface for Bluetooth Sockets is similar to that of TCP sockets:
38 * {@link java.net.Socket} and {@link java.net.ServerSocket}. On the server
39 * side, use a {@link BluetoothServerSocket} to create a listening server
Scott Mainbeef8092009-11-03 18:17:59 -080040 * socket. When a connection is accepted by the {@link BluetoothServerSocket},
41 * it will return a new {@link BluetoothSocket} to manage the connection.
Jake Hamby04c71382010-09-21 13:39:53 -070042 * On the client side, use a single {@link BluetoothSocket} to both initiate
Scott Mainbeef8092009-11-03 18:17:59 -080043 * an outgoing connection and to manage the connection.
Nick Pelly53f441b2009-05-26 19:13:43 -070044 *
Stanley Tng3b285452019-04-19 14:27:09 -070045 * <p>For Bluetooth BR/EDR, the most common type of socket is RFCOMM, which is the type supported by
46 * the Android APIs. RFCOMM is a connection-oriented, streaming transport over Bluetooth BR/EDR. It
47 * is also known as the Serial Port Profile (SPP). To create a listening
48 * {@link BluetoothServerSocket} that's ready for incoming Bluetooth BR/EDR connections, use {@link
49 * BluetoothAdapter#listenUsingRfcommWithServiceRecord
50 * BluetoothAdapter.listenUsingRfcommWithServiceRecord()}.
Nick Pelly53f441b2009-05-26 19:13:43 -070051 *
Stanley Tng3b285452019-04-19 14:27:09 -070052 * <p>For Bluetooth LE, the socket uses LE Connection-oriented Channel (CoC). LE CoC is a
53 * connection-oriented, streaming transport over Bluetooth LE and has a credit-based flow control.
54 * Correspondingly, use {@link BluetoothAdapter#listenUsingL2capChannel
55 * BluetoothAdapter.listenUsingL2capChannel()} to create a listening {@link BluetoothServerSocket}
56 * that's ready for incoming Bluetooth LE CoC connections. For LE CoC, you can use {@link #getPsm()}
57 * to get the protocol/service multiplexer (PSM) value that the peer needs to use to connect to your
58 * socket.
59 *
60 * <p> After the listening {@link BluetoothServerSocket} is created, call {@link #accept()} to
61 * listen for incoming connection requests. This call will block until a connection is established,
62 * at which point, it will return a {@link BluetoothSocket} to manage the connection. Once the
63 * {@link BluetoothSocket} is acquired, it's a good idea to call {@link #close()} on the {@link
64 * BluetoothServerSocket} when it's no longer needed for accepting
65 * connections. Closing the {@link BluetoothServerSocket} will <em>not</em> close the returned
66 * {@link BluetoothSocket}.
Nick Pelly753da532009-08-19 11:00:00 -070067 *
Scott Mainbeef8092009-11-03 18:17:59 -080068 * <p>{@link BluetoothServerSocket} is thread
Nick Pelly753da532009-08-19 11:00:00 -070069 * safe. In particular, {@link #close} will always immediately abort ongoing
Scott Mainbeef8092009-11-03 18:17:59 -080070 * operations and close the server socket.
Nick Pellyed6f2ce2009-09-08 10:12:06 -070071 *
Joe Fernandezda4e2ab2011-12-20 10:38:34 -080072 * <div class="special reference">
73 * <h3>Developer Guides</h3>
74 * <p>For more information about using Bluetooth, read the
Marie Janssenf242df22016-06-20 10:26:31 -070075 * <a href="{@docRoot}guide/topics/connectivity/bluetooth.html">Bluetooth</a> developer guide.</p>
Joe Fernandezda4e2ab2011-12-20 10:38:34 -080076 * </div>
77 *
Scott Mainbeef8092009-11-03 18:17:59 -080078 * {@see BluetoothSocket}
Nick Pelly53f441b2009-05-26 19:13:43 -070079 */
Jeff Sharkey5ba8bfc2021-04-16 09:53:23 -060080@SuppressLint("AndroidFrameworkBluetoothPermission")
Nick Pelly53f441b2009-05-26 19:13:43 -070081public final class BluetoothServerSocket implements Closeable {
Nick Pelly4cd2cd92009-09-02 11:51:35 -070082
Casper Bondec0a7c932015-04-09 09:24:48 +020083 private static final String TAG = "BluetoothServerSocket";
Ugo Yub6dc15a2022-12-28 20:18:00 +080084 private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Andrei Onea147146f2019-06-17 11:26:14 +010085 @UnsupportedAppUsage(publicAlternatives = "Use public {@link BluetoothServerSocket} API "
86 + "instead.")
Nick Pelly2d664882009-08-14 18:33:38 -070087 /*package*/ final BluetoothSocket mSocket;
Nick Pellyee1402d2009-10-02 20:34:18 -070088 private Handler mHandler;
89 private int mMessage;
Casper Bondec0a7c932015-04-09 09:24:48 +020090 private int mChannel;
Chen Chen874e7b02023-03-07 17:37:43 -080091 private long mSocketCreationTime = 0;
92
93 // BluetoothSocket.getConnectionType() will hide L2CAP_LE.
94 // Therefore a new variable need to be maintained here.
95 private int mType;
Nick Pelly53f441b2009-05-26 19:13:43 -070096
97 /**
98 * Construct a socket for incoming connections.
Jack He910201b2017-08-22 16:06:54 -070099 *
100 * @param type type of socket
101 * @param auth require the remote device to be authenticated
Nick Pellycb32d7c2009-06-02 15:57:18 -0700102 * @param encrypt require the connection to be encrypted
Jack He910201b2017-08-22 16:06:54 -0700103 * @param port remote port
104 * @throws IOException On error, for example Bluetooth not available, or insufficient
105 * privileges
Nick Pelly53f441b2009-05-26 19:13:43 -0700106 */
Nick Pelly2d664882009-08-14 18:33:38 -0700107 /*package*/ BluetoothServerSocket(int type, boolean auth, boolean encrypt, int port)
Nick Pellycb32d7c2009-06-02 15:57:18 -0700108 throws IOException {
Chen Chen874e7b02023-03-07 17:37:43 -0800109 mType = type;
Ben Dodson48d0cca2011-07-08 14:36:42 -0700110 mChannel = port;
Chen Chen874e7b02023-03-07 17:37:43 -0800111 mSocketCreationTime = System.currentTimeMillis();
Nick Pelly07b84cb2009-10-07 07:44:03 +0200112 mSocket = new BluetoothSocket(type, -1, auth, encrypt, null, port, null);
Casper Bonde60d77c22015-04-21 13:12:05 +0200113 if (port == BluetoothAdapter.SOCKET_CHANNEL_AUTO_STATIC_NO_SDP) {
114 mSocket.setExcludeSdp(true);
115 }
116 }
117
118 /**
119 * Construct a socket for incoming connections.
Jack He910201b2017-08-22 16:06:54 -0700120 *
121 * @param type type of socket
122 * @param auth require the remote device to be authenticated
Casper Bonde60d77c22015-04-21 13:12:05 +0200123 * @param encrypt require the connection to be encrypted
Jack He910201b2017-08-22 16:06:54 -0700124 * @param port remote port
Jeff Sharkeyc5386af2020-09-11 14:57:21 -0600125 * @param mitm enforce person-in-the-middle protection for authentication.
Casper Bonde91276012015-05-08 14:32:24 +0200126 * @param min16DigitPin enforce a minimum length of 16 digits for a sec mode 2 connection
Jack He910201b2017-08-22 16:06:54 -0700127 * @throws IOException On error, for example Bluetooth not available, or insufficient
128 * privileges
Casper Bonde60d77c22015-04-21 13:12:05 +0200129 */
130 /*package*/ BluetoothServerSocket(int type, boolean auth, boolean encrypt, int port,
Casper Bonde91276012015-05-08 14:32:24 +0200131 boolean mitm, boolean min16DigitPin)
Casper Bonde60d77c22015-04-21 13:12:05 +0200132 throws IOException {
Chen Chen874e7b02023-03-07 17:37:43 -0800133 mType = type;
Casper Bonde60d77c22015-04-21 13:12:05 +0200134 mChannel = port;
Chen Chen874e7b02023-03-07 17:37:43 -0800135 mSocketCreationTime = System.currentTimeMillis();
Casper Bonde91276012015-05-08 14:32:24 +0200136 mSocket = new BluetoothSocket(type, -1, auth, encrypt, null, port, null, mitm,
137 min16DigitPin);
Jack He910201b2017-08-22 16:06:54 -0700138 if (port == BluetoothAdapter.SOCKET_CHANNEL_AUTO_STATIC_NO_SDP) {
Casper Bondec0a7c932015-04-09 09:24:48 +0200139 mSocket.setExcludeSdp(true);
140 }
Nick Pelly53f441b2009-05-26 19:13:43 -0700141 }
142
143 /**
zzyfab62db2012-04-03 19:48:32 -0700144 * Construct a socket for incoming connections.
Jack He910201b2017-08-22 16:06:54 -0700145 *
146 * @param type type of socket
147 * @param auth require the remote device to be authenticated
zzyfab62db2012-04-03 19:48:32 -0700148 * @param encrypt require the connection to be encrypted
Jack He910201b2017-08-22 16:06:54 -0700149 * @param uuid uuid
150 * @throws IOException On error, for example Bluetooth not available, or insufficient
151 * privileges
zzyfab62db2012-04-03 19:48:32 -0700152 */
153 /*package*/ BluetoothServerSocket(int type, boolean auth, boolean encrypt, ParcelUuid uuid)
154 throws IOException {
Chen Chen874e7b02023-03-07 17:37:43 -0800155 mType = type;
156 mSocketCreationTime = System.currentTimeMillis();
zzyfab62db2012-04-03 19:48:32 -0700157 mSocket = new BluetoothSocket(type, -1, auth, encrypt, null, -1, uuid);
Casper Bondec0a7c932015-04-09 09:24:48 +0200158 // TODO: This is the same as mChannel = -1 - is this intentional?
zzyfab62db2012-04-03 19:48:32 -0700159 mChannel = mSocket.getPort();
160 }
161
162
163 /**
Nick Pelly53f441b2009-05-26 19:13:43 -0700164 * Block until a connection is established.
Nick Pelly753da532009-08-19 11:00:00 -0700165 * <p>Returns a connected {@link BluetoothSocket} on successful connection.
166 * <p>Once this call returns, it can be called again to accept subsequent
167 * incoming connections.
168 * <p>{@link #close} can be used to abort this call from another thread.
Jack He910201b2017-08-22 16:06:54 -0700169 *
Nick Pelly753da532009-08-19 11:00:00 -0700170 * @return a connected {@link BluetoothSocket}
Jack He910201b2017-08-22 16:06:54 -0700171 * @throws IOException on error, for example this call was aborted, or timeout
Nick Pelly53f441b2009-05-26 19:13:43 -0700172 */
173 public BluetoothSocket accept() throws IOException {
174 return accept(-1);
175 }
176
177 /**
178 * Block until a connection is established, with timeout.
Nick Pelly753da532009-08-19 11:00:00 -0700179 * <p>Returns a connected {@link BluetoothSocket} on successful connection.
180 * <p>Once this call returns, it can be called again to accept subsequent
181 * incoming connections.
182 * <p>{@link #close} can be used to abort this call from another thread.
Jack He910201b2017-08-22 16:06:54 -0700183 *
Nick Pelly753da532009-08-19 11:00:00 -0700184 * @return a connected {@link BluetoothSocket}
Jack He910201b2017-08-22 16:06:54 -0700185 * @throws IOException on error, for example this call was aborted, or timeout
Nick Pelly53f441b2009-05-26 19:13:43 -0700186 */
187 public BluetoothSocket accept(int timeout) throws IOException {
Chen Chen874e7b02023-03-07 17:37:43 -0800188 BluetoothSocket acceptedSocket = null;
189 try {
190 acceptedSocket = mSocket.accept(timeout);
191 logL2capcocServerConnection(
192 acceptedSocket, timeout, BluetoothSocket.RESULT_L2CAP_CONN_SUCCESS);
193 return acceptedSocket;
194 } catch (IOException e) {
195 logL2capcocServerConnection(
196 acceptedSocket, timeout, BluetoothSocket.RESULT_L2CAP_CONN_SERVER_FAILURE);
197 throw e;
198 }
Nick Pelly53f441b2009-05-26 19:13:43 -0700199 }
200
Chen Chen874e7b02023-03-07 17:37:43 -0800201 private void logL2capcocServerConnection(
202 BluetoothSocket acceptedSocket, int timeout, int result) {
203 if (mType != BluetoothSocket.TYPE_L2CAP_LE) {
204 return;
205 }
206 IBluetooth bluetoothProxy =
207 BluetoothAdapter.getDefaultAdapter().getBluetoothService();
208 if (bluetoothProxy == null) {
209 Log.w(TAG,
210 "bluetoothProxy is null while trying to log l2cap soc server connection");
211 return;
212 }
213 try {
214 final SynchronousResultReceiver recv = SynchronousResultReceiver.get();
215 bluetoothProxy.logL2capcocServerConnection(
216 acceptedSocket == null ? null : acceptedSocket.getRemoteDevice(),
217 getPsm(),
218 mSocket.isAuth(),
219 result,
220 System.currentTimeMillis() - mSocketCreationTime,
221 timeout,
222 recv);
223 recv.awaitResultNoInterrupt(getSyncTimeout()).getValue(null);
224
225 } catch (RemoteException | TimeoutException e) {
226 Log.w(TAG, "logL2capcocServerConnection failed due to remote exception");
227 }
228 }
Nick Pelly53f441b2009-05-26 19:13:43 -0700229 /**
Nick Pelly753da532009-08-19 11:00:00 -0700230 * Immediately close this socket, and release all associated resources.
231 * <p>Causes blocked calls on this socket in other threads to immediately
Nick Pelly53f441b2009-05-26 19:13:43 -0700232 * throw an IOException.
Scott Maina7848ce2009-11-19 17:00:19 -0800233 * <p>Closing the {@link BluetoothServerSocket} will <em>not</em>
234 * close any {@link BluetoothSocket} received from {@link #accept()}.
Nick Pelly53f441b2009-05-26 19:13:43 -0700235 */
236 public void close() throws IOException {
Stanley Tngd67d5e42017-11-22 16:04:40 -0800237 if (DBG) Log.d(TAG, "BluetoothServerSocket:close() called. mChannel=" + mChannel);
Nick Pellyee1402d2009-10-02 20:34:18 -0700238 synchronized (this) {
239 if (mHandler != null) {
240 mHandler.obtainMessage(mMessage).sendToTarget();
241 }
242 }
Nick Pelly4cd2cd92009-09-02 11:51:35 -0700243 mSocket.close();
Nick Pelly53f441b2009-05-26 19:13:43 -0700244 }
Nick Pellyee1402d2009-10-02 20:34:18 -0700245
Jack He910201b2017-08-22 16:06:54 -0700246 /*package*/
247 synchronized void setCloseHandler(Handler handler, int message) {
Nick Pellyee1402d2009-10-02 20:34:18 -0700248 mHandler = handler;
249 mMessage = message;
250 }
Jack He910201b2017-08-22 16:06:54 -0700251
Jack He9e045d22017-08-22 21:21:23 -0700252 /*package*/ void setServiceName(String serviceName) {
253 mSocket.setServiceName(serviceName);
zzyfab62db2012-04-03 19:48:32 -0700254 }
Casper Bondec0a7c932015-04-09 09:24:48 +0200255
Ben Dodson48d0cca2011-07-08 14:36:42 -0700256 /**
257 * Returns the channel on which this socket is bound.
Jack He910201b2017-08-22 16:06:54 -0700258 *
Ben Dodson48d0cca2011-07-08 14:36:42 -0700259 * @hide
260 */
261 public int getChannel() {
262 return mChannel;
263 }
Casper Bondec0a7c932015-04-09 09:24:48 +0200264
265 /**
Stanley Tngd67d5e42017-11-22 16:04:40 -0800266 * Returns the assigned dynamic protocol/service multiplexer (PSM) value for the listening L2CAP
267 * Connection-oriented Channel (CoC) server socket. This server socket must be returned by the
Xin Li10802fb2019-02-13 22:36:25 -0800268 * {@link BluetoothAdapter#listenUsingL2capChannel()} or {@link
269 * BluetoothAdapter#listenUsingInsecureL2capChannel()}. The returned value is undefined if this
Stanley Tngd67d5e42017-11-22 16:04:40 -0800270 * method is called on non-L2CAP server sockets.
271 *
272 * @return the assigned PSM or LE_PSM value depending on transport
Stanley Tngd67d5e42017-11-22 16:04:40 -0800273 */
274 public int getPsm() {
275 return mChannel;
276 }
277
278 /**
Casper Bondec0a7c932015-04-09 09:24:48 +0200279 * Sets the channel on which future sockets are bound.
280 * Currently used only when a channel is auto generated.
281 */
282 /*package*/ void setChannel(int newChannel) {
283 /* TODO: From a design/architecture perspective this is wrong.
284 * The bind operation should be conducted through this class
285 * and the resulting port should be kept in mChannel, and
286 * not set from BluetoothAdapter. */
Jack He910201b2017-08-22 16:06:54 -0700287 if (mSocket != null) {
288 if (mSocket.getPort() != newChannel) {
289 Log.w(TAG, "The port set is different that the underlying port. mSocket.getPort(): "
290 + mSocket.getPort() + " requested newChannel: " + newChannel);
Casper Bondec0a7c932015-04-09 09:24:48 +0200291 }
292 }
293 mChannel = newChannel;
294 }
295
296 @Override
297 public String toString() {
298 StringBuilder sb = new StringBuilder();
299 sb.append("ServerSocket: Type: ");
Jack He910201b2017-08-22 16:06:54 -0700300 switch (mSocket.getConnectionType()) {
301 case BluetoothSocket.TYPE_RFCOMM: {
Casper Bondec0a7c932015-04-09 09:24:48 +0200302 sb.append("TYPE_RFCOMM");
303 break;
304 }
Jack He910201b2017-08-22 16:06:54 -0700305 case BluetoothSocket.TYPE_L2CAP: {
Casper Bondec0a7c932015-04-09 09:24:48 +0200306 sb.append("TYPE_L2CAP");
307 break;
308 }
Stanley Tngd67d5e42017-11-22 16:04:40 -0800309 case BluetoothSocket.TYPE_L2CAP_LE: {
310 sb.append("TYPE_L2CAP_LE");
311 break;
312 }
Jack He910201b2017-08-22 16:06:54 -0700313 case BluetoothSocket.TYPE_SCO: {
Casper Bondec0a7c932015-04-09 09:24:48 +0200314 sb.append("TYPE_SCO");
315 break;
316 }
317 }
318 sb.append(" Channel: ").append(mChannel);
319 return sb.toString();
320 }
Nick Pelly53f441b2009-05-26 19:13:43 -0700321}