blob: 5a23f7e3a5d06024e10eb9366d605fbecca39b16 [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
Jeff Sharkey5ba8bfc2021-04-16 09:53:23 -060019import android.annotation.SuppressLint;
Artur Satayevd8fe38c2019-12-10 17:47:52 +000020import android.compat.annotation.UnsupportedAppUsage;
Nick Pellyee1402d2009-10-02 20:34:18 -070021import android.os.Handler;
zzyfab62db2012-04-03 19:48:32 -070022import android.os.ParcelUuid;
Casper Bondec0a7c932015-04-09 09:24:48 +020023import android.util.Log;
Nick Pellyee1402d2009-10-02 20:34:18 -070024
Nick Pelly53f441b2009-05-26 19:13:43 -070025import java.io.Closeable;
26import java.io.IOException;
27
28/**
Nick Pelly753da532009-08-19 11:00:00 -070029 * A listening Bluetooth socket.
Nick Pelly53f441b2009-05-26 19:13:43 -070030 *
Nick Pelly753da532009-08-19 11:00:00 -070031 * <p>The interface for Bluetooth Sockets is similar to that of TCP sockets:
32 * {@link java.net.Socket} and {@link java.net.ServerSocket}. On the server
33 * side, use a {@link BluetoothServerSocket} to create a listening server
Scott Mainbeef8092009-11-03 18:17:59 -080034 * socket. When a connection is accepted by the {@link BluetoothServerSocket},
35 * it will return a new {@link BluetoothSocket} to manage the connection.
Jake Hamby04c71382010-09-21 13:39:53 -070036 * On the client side, use a single {@link BluetoothSocket} to both initiate
Scott Mainbeef8092009-11-03 18:17:59 -080037 * an outgoing connection and to manage the connection.
Nick Pelly53f441b2009-05-26 19:13:43 -070038 *
Stanley Tng3b285452019-04-19 14:27:09 -070039 * <p>For Bluetooth BR/EDR, the most common type of socket is RFCOMM, which is the type supported by
40 * the Android APIs. RFCOMM is a connection-oriented, streaming transport over Bluetooth BR/EDR. It
41 * is also known as the Serial Port Profile (SPP). To create a listening
42 * {@link BluetoothServerSocket} that's ready for incoming Bluetooth BR/EDR connections, use {@link
43 * BluetoothAdapter#listenUsingRfcommWithServiceRecord
44 * BluetoothAdapter.listenUsingRfcommWithServiceRecord()}.
Nick Pelly53f441b2009-05-26 19:13:43 -070045 *
Stanley Tng3b285452019-04-19 14:27:09 -070046 * <p>For Bluetooth LE, the socket uses LE Connection-oriented Channel (CoC). LE CoC is a
47 * connection-oriented, streaming transport over Bluetooth LE and has a credit-based flow control.
48 * Correspondingly, use {@link BluetoothAdapter#listenUsingL2capChannel
49 * BluetoothAdapter.listenUsingL2capChannel()} to create a listening {@link BluetoothServerSocket}
50 * that's ready for incoming Bluetooth LE CoC connections. For LE CoC, you can use {@link #getPsm()}
51 * to get the protocol/service multiplexer (PSM) value that the peer needs to use to connect to your
52 * socket.
53 *
54 * <p> After the listening {@link BluetoothServerSocket} is created, call {@link #accept()} to
55 * listen for incoming connection requests. This call will block until a connection is established,
56 * at which point, it will return a {@link BluetoothSocket} to manage the connection. Once the
57 * {@link BluetoothSocket} is acquired, it's a good idea to call {@link #close()} on the {@link
58 * BluetoothServerSocket} when it's no longer needed for accepting
59 * connections. Closing the {@link BluetoothServerSocket} will <em>not</em> close the returned
60 * {@link BluetoothSocket}.
Nick Pelly753da532009-08-19 11:00:00 -070061 *
Scott Mainbeef8092009-11-03 18:17:59 -080062 * <p>{@link BluetoothServerSocket} is thread
Nick Pelly753da532009-08-19 11:00:00 -070063 * safe. In particular, {@link #close} will always immediately abort ongoing
Scott Mainbeef8092009-11-03 18:17:59 -080064 * operations and close the server socket.
Nick Pellyed6f2ce2009-09-08 10:12:06 -070065 *
Joe Fernandezda4e2ab2011-12-20 10:38:34 -080066 * <div class="special reference">
67 * <h3>Developer Guides</h3>
68 * <p>For more information about using Bluetooth, read the
Marie Janssenf242df22016-06-20 10:26:31 -070069 * <a href="{@docRoot}guide/topics/connectivity/bluetooth.html">Bluetooth</a> developer guide.</p>
Joe Fernandezda4e2ab2011-12-20 10:38:34 -080070 * </div>
71 *
Scott Mainbeef8092009-11-03 18:17:59 -080072 * {@see BluetoothSocket}
Nick Pelly53f441b2009-05-26 19:13:43 -070073 */
Jeff Sharkey5ba8bfc2021-04-16 09:53:23 -060074@SuppressLint("AndroidFrameworkBluetoothPermission")
Nick Pelly53f441b2009-05-26 19:13:43 -070075public final class BluetoothServerSocket implements Closeable {
Nick Pelly4cd2cd92009-09-02 11:51:35 -070076
Casper Bondec0a7c932015-04-09 09:24:48 +020077 private static final String TAG = "BluetoothServerSocket";
Ugo Yub6dc15a2022-12-28 20:18:00 +080078 private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Andrei Onea147146f2019-06-17 11:26:14 +010079 @UnsupportedAppUsage(publicAlternatives = "Use public {@link BluetoothServerSocket} API "
80 + "instead.")
Nick Pelly2d664882009-08-14 18:33:38 -070081 /*package*/ final BluetoothSocket mSocket;
Nick Pellyee1402d2009-10-02 20:34:18 -070082 private Handler mHandler;
83 private int mMessage;
Casper Bondec0a7c932015-04-09 09:24:48 +020084 private int mChannel;
Nick Pelly53f441b2009-05-26 19:13:43 -070085
86 /**
87 * Construct a socket for incoming connections.
Jack He910201b2017-08-22 16:06:54 -070088 *
89 * @param type type of socket
90 * @param auth require the remote device to be authenticated
Nick Pellycb32d7c2009-06-02 15:57:18 -070091 * @param encrypt require the connection to be encrypted
Jack He910201b2017-08-22 16:06:54 -070092 * @param port remote port
93 * @throws IOException On error, for example Bluetooth not available, or insufficient
94 * privileges
Nick Pelly53f441b2009-05-26 19:13:43 -070095 */
Nick Pelly2d664882009-08-14 18:33:38 -070096 /*package*/ BluetoothServerSocket(int type, boolean auth, boolean encrypt, int port)
Nick Pellycb32d7c2009-06-02 15:57:18 -070097 throws IOException {
Ben Dodson48d0cca2011-07-08 14:36:42 -070098 mChannel = port;
Nick Pelly07b84cb2009-10-07 07:44:03 +020099 mSocket = new BluetoothSocket(type, -1, auth, encrypt, null, port, null);
Casper Bonde60d77c22015-04-21 13:12:05 +0200100 if (port == BluetoothAdapter.SOCKET_CHANNEL_AUTO_STATIC_NO_SDP) {
101 mSocket.setExcludeSdp(true);
102 }
103 }
104
105 /**
106 * Construct a socket for incoming connections.
Jack He910201b2017-08-22 16:06:54 -0700107 *
108 * @param type type of socket
109 * @param auth require the remote device to be authenticated
Casper Bonde60d77c22015-04-21 13:12:05 +0200110 * @param encrypt require the connection to be encrypted
Jack He910201b2017-08-22 16:06:54 -0700111 * @param port remote port
Jeff Sharkeyc5386af2020-09-11 14:57:21 -0600112 * @param mitm enforce person-in-the-middle protection for authentication.
Casper Bonde91276012015-05-08 14:32:24 +0200113 * @param min16DigitPin enforce a minimum length of 16 digits for a sec mode 2 connection
Jack He910201b2017-08-22 16:06:54 -0700114 * @throws IOException On error, for example Bluetooth not available, or insufficient
115 * privileges
Casper Bonde60d77c22015-04-21 13:12:05 +0200116 */
117 /*package*/ BluetoothServerSocket(int type, boolean auth, boolean encrypt, int port,
Casper Bonde91276012015-05-08 14:32:24 +0200118 boolean mitm, boolean min16DigitPin)
Casper Bonde60d77c22015-04-21 13:12:05 +0200119 throws IOException {
120 mChannel = port;
Casper Bonde91276012015-05-08 14:32:24 +0200121 mSocket = new BluetoothSocket(type, -1, auth, encrypt, null, port, null, mitm,
122 min16DigitPin);
Jack He910201b2017-08-22 16:06:54 -0700123 if (port == BluetoothAdapter.SOCKET_CHANNEL_AUTO_STATIC_NO_SDP) {
Casper Bondec0a7c932015-04-09 09:24:48 +0200124 mSocket.setExcludeSdp(true);
125 }
Nick Pelly53f441b2009-05-26 19:13:43 -0700126 }
127
128 /**
zzyfab62db2012-04-03 19:48:32 -0700129 * Construct a socket for incoming connections.
Jack He910201b2017-08-22 16:06:54 -0700130 *
131 * @param type type of socket
132 * @param auth require the remote device to be authenticated
zzyfab62db2012-04-03 19:48:32 -0700133 * @param encrypt require the connection to be encrypted
Jack He910201b2017-08-22 16:06:54 -0700134 * @param uuid uuid
135 * @throws IOException On error, for example Bluetooth not available, or insufficient
136 * privileges
zzyfab62db2012-04-03 19:48:32 -0700137 */
138 /*package*/ BluetoothServerSocket(int type, boolean auth, boolean encrypt, ParcelUuid uuid)
139 throws IOException {
140 mSocket = new BluetoothSocket(type, -1, auth, encrypt, null, -1, uuid);
Casper Bondec0a7c932015-04-09 09:24:48 +0200141 // TODO: This is the same as mChannel = -1 - is this intentional?
zzyfab62db2012-04-03 19:48:32 -0700142 mChannel = mSocket.getPort();
143 }
144
145
146 /**
Nick Pelly53f441b2009-05-26 19:13:43 -0700147 * Block until a connection is established.
Nick Pelly753da532009-08-19 11:00:00 -0700148 * <p>Returns a connected {@link BluetoothSocket} on successful connection.
149 * <p>Once this call returns, it can be called again to accept subsequent
150 * incoming connections.
151 * <p>{@link #close} can be used to abort this call from another thread.
Jack He910201b2017-08-22 16:06:54 -0700152 *
Nick Pelly753da532009-08-19 11:00:00 -0700153 * @return a connected {@link BluetoothSocket}
Jack He910201b2017-08-22 16:06:54 -0700154 * @throws IOException on error, for example this call was aborted, or timeout
Nick Pelly53f441b2009-05-26 19:13:43 -0700155 */
156 public BluetoothSocket accept() throws IOException {
157 return accept(-1);
158 }
159
160 /**
161 * Block until a connection is established, with timeout.
Nick Pelly753da532009-08-19 11:00:00 -0700162 * <p>Returns a connected {@link BluetoothSocket} on successful connection.
163 * <p>Once this call returns, it can be called again to accept subsequent
164 * incoming connections.
165 * <p>{@link #close} can be used to abort this call from another thread.
Jack He910201b2017-08-22 16:06:54 -0700166 *
Nick Pelly753da532009-08-19 11:00:00 -0700167 * @return a connected {@link BluetoothSocket}
Jack He910201b2017-08-22 16:06:54 -0700168 * @throws IOException on error, for example this call was aborted, or timeout
Nick Pelly53f441b2009-05-26 19:13:43 -0700169 */
170 public BluetoothSocket accept(int timeout) throws IOException {
Nick Pelly4cd2cd92009-09-02 11:51:35 -0700171 return mSocket.accept(timeout);
Nick Pelly53f441b2009-05-26 19:13:43 -0700172 }
173
174 /**
Nick Pelly753da532009-08-19 11:00:00 -0700175 * Immediately close this socket, and release all associated resources.
176 * <p>Causes blocked calls on this socket in other threads to immediately
Nick Pelly53f441b2009-05-26 19:13:43 -0700177 * throw an IOException.
Scott Maina7848ce2009-11-19 17:00:19 -0800178 * <p>Closing the {@link BluetoothServerSocket} will <em>not</em>
179 * close any {@link BluetoothSocket} received from {@link #accept()}.
Nick Pelly53f441b2009-05-26 19:13:43 -0700180 */
181 public void close() throws IOException {
Stanley Tngd67d5e42017-11-22 16:04:40 -0800182 if (DBG) Log.d(TAG, "BluetoothServerSocket:close() called. mChannel=" + mChannel);
Nick Pellyee1402d2009-10-02 20:34:18 -0700183 synchronized (this) {
184 if (mHandler != null) {
185 mHandler.obtainMessage(mMessage).sendToTarget();
186 }
187 }
Nick Pelly4cd2cd92009-09-02 11:51:35 -0700188 mSocket.close();
Nick Pelly53f441b2009-05-26 19:13:43 -0700189 }
Nick Pellyee1402d2009-10-02 20:34:18 -0700190
Jack He910201b2017-08-22 16:06:54 -0700191 /*package*/
192 synchronized void setCloseHandler(Handler handler, int message) {
Nick Pellyee1402d2009-10-02 20:34:18 -0700193 mHandler = handler;
194 mMessage = message;
195 }
Jack He910201b2017-08-22 16:06:54 -0700196
Jack He9e045d22017-08-22 21:21:23 -0700197 /*package*/ void setServiceName(String serviceName) {
198 mSocket.setServiceName(serviceName);
zzyfab62db2012-04-03 19:48:32 -0700199 }
Casper Bondec0a7c932015-04-09 09:24:48 +0200200
Ben Dodson48d0cca2011-07-08 14:36:42 -0700201 /**
202 * Returns the channel on which this socket is bound.
Jack He910201b2017-08-22 16:06:54 -0700203 *
Ben Dodson48d0cca2011-07-08 14:36:42 -0700204 * @hide
205 */
206 public int getChannel() {
207 return mChannel;
208 }
Casper Bondec0a7c932015-04-09 09:24:48 +0200209
210 /**
Stanley Tngd67d5e42017-11-22 16:04:40 -0800211 * Returns the assigned dynamic protocol/service multiplexer (PSM) value for the listening L2CAP
212 * Connection-oriented Channel (CoC) server socket. This server socket must be returned by the
Xin Li10802fb2019-02-13 22:36:25 -0800213 * {@link BluetoothAdapter#listenUsingL2capChannel()} or {@link
214 * BluetoothAdapter#listenUsingInsecureL2capChannel()}. The returned value is undefined if this
Stanley Tngd67d5e42017-11-22 16:04:40 -0800215 * method is called on non-L2CAP server sockets.
216 *
217 * @return the assigned PSM or LE_PSM value depending on transport
Stanley Tngd67d5e42017-11-22 16:04:40 -0800218 */
219 public int getPsm() {
220 return mChannel;
221 }
222
223 /**
Casper Bondec0a7c932015-04-09 09:24:48 +0200224 * Sets the channel on which future sockets are bound.
225 * Currently used only when a channel is auto generated.
226 */
227 /*package*/ void setChannel(int newChannel) {
228 /* TODO: From a design/architecture perspective this is wrong.
229 * The bind operation should be conducted through this class
230 * and the resulting port should be kept in mChannel, and
231 * not set from BluetoothAdapter. */
Jack He910201b2017-08-22 16:06:54 -0700232 if (mSocket != null) {
233 if (mSocket.getPort() != newChannel) {
234 Log.w(TAG, "The port set is different that the underlying port. mSocket.getPort(): "
235 + mSocket.getPort() + " requested newChannel: " + newChannel);
Casper Bondec0a7c932015-04-09 09:24:48 +0200236 }
237 }
238 mChannel = newChannel;
239 }
240
241 @Override
242 public String toString() {
243 StringBuilder sb = new StringBuilder();
244 sb.append("ServerSocket: Type: ");
Jack He910201b2017-08-22 16:06:54 -0700245 switch (mSocket.getConnectionType()) {
246 case BluetoothSocket.TYPE_RFCOMM: {
Casper Bondec0a7c932015-04-09 09:24:48 +0200247 sb.append("TYPE_RFCOMM");
248 break;
249 }
Jack He910201b2017-08-22 16:06:54 -0700250 case BluetoothSocket.TYPE_L2CAP: {
Casper Bondec0a7c932015-04-09 09:24:48 +0200251 sb.append("TYPE_L2CAP");
252 break;
253 }
Stanley Tngd67d5e42017-11-22 16:04:40 -0800254 case BluetoothSocket.TYPE_L2CAP_LE: {
255 sb.append("TYPE_L2CAP_LE");
256 break;
257 }
Jack He910201b2017-08-22 16:06:54 -0700258 case BluetoothSocket.TYPE_SCO: {
Casper Bondec0a7c932015-04-09 09:24:48 +0200259 sb.append("TYPE_SCO");
260 break;
261 }
262 }
263 sb.append(" Channel: ").append(mChannel);
264 return sb.toString();
265 }
Nick Pelly53f441b2009-05-26 19:13:43 -0700266}