summaryrefslogtreecommitdiffstats
path: root/device/bluetooth/bluetooth_socket_mac.mm
blob: cee05a53f48a8b38067f7d7a7d27e632422dca57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "device/bluetooth/bluetooth_socket_mac.h"

#import <IOBluetooth/objc/IOBluetoothDevice.h>
#import <IOBluetooth/objc/IOBluetoothRFCOMMChannel.h>
#import <IOBluetooth/objc/IOBluetoothSDPServiceRecord.h>

#include <limits>
#include <sstream>
#include <string>

#include "base/basictypes.h"
#include "base/callback_helpers.h"
#include "base/memory/ref_counted.h"
#include "base/strings/stringprintf.h"
#include "base/strings/sys_string_conversions.h"
#include "base/threading/thread_restrictions.h"
#include "device/bluetooth/bluetooth_service_record.h"
#include "device/bluetooth/bluetooth_service_record_mac.h"
#include "net/base/io_buffer.h"

// Replicate specific 10.7 SDK declarations for building with prior SDKs.
#if !defined(MAC_OS_X_VERSION_10_7) || \
    MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7

@interface IOBluetoothDevice (LionSDKDeclarations)
- (NSString*)addressString;
@end

#endif  // MAC_OS_X_VERSION_10_7

@interface BluetoothRFCOMMChannelDelegate
    : NSObject <IOBluetoothRFCOMMChannelDelegate> {
 @private
  device::BluetoothSocketMac* socket_;  // weak
}

- (id)initWithSocket:(device::BluetoothSocketMac*)socket;

@end

@implementation BluetoothRFCOMMChannelDelegate

- (id)initWithSocket:(device::BluetoothSocketMac*)socket {
  if ((self = [super init]))
    socket_ = socket;

  return self;
}

- (void)rfcommChannelOpenComplete:(IOBluetoothRFCOMMChannel*)rfcommChannel
                           status:(IOReturn)error {
  socket_->OnChannelOpened(rfcommChannel, error);
}

- (void)rfcommChannelWriteComplete:(IOBluetoothRFCOMMChannel*)rfcommChannel
                            refcon:(void*)refcon
                            status:(IOReturn)error {
  socket_->OnChannelWriteComplete(rfcommChannel, refcon, error);
}

- (void)rfcommChannelData:(IOBluetoothRFCOMMChannel*)rfcommChannel
                     data:(void*)dataPointer
                   length:(size_t)dataLength {
  socket_->OnChannelDataReceived(rfcommChannel, dataPointer, dataLength);
}

- (void)rfcommChannelClosed:(IOBluetoothRFCOMMChannel*)rfcommChannel {
  socket_->OnChannelClosed(rfcommChannel);
}

@end

namespace {

const char kL2CAPNotSupported[] = "Bluetooth L2CAP protocol is not supported";
const char kSocketConnecting[] = "The socket is currently connecting";
const char kSocketAlreadyConnected[] = "The socket is already connected";
const char kSocketNotConnected[] = "The socket is not connected";
const char kReceivePending[] = "A Receive operation is pending";

template <class T>
void empty_queue(std::queue<T>& queue) {
  std::queue<T> empty;
  std::swap(queue, empty);
}

}  // namespace

namespace device {

BluetoothSocketMac::SendRequest::SendRequest()
    : status(kIOReturnSuccess), active_async_writes(0), error_signaled(false) {}

BluetoothSocketMac::SendRequest::~SendRequest() {}

BluetoothSocketMac::ReceiveCallbacks::ReceiveCallbacks() {}

BluetoothSocketMac::ReceiveCallbacks::~ReceiveCallbacks() {}

BluetoothSocketMac::ConnectCallbacks::ConnectCallbacks() {}

BluetoothSocketMac::ConnectCallbacks::~ConnectCallbacks() {}

// static
scoped_refptr<BluetoothSocketMac> BluetoothSocketMac::CreateBluetoothSocket(
    const scoped_refptr<base::SequencedTaskRunner>& ui_task_runner,
    IOBluetoothSDPServiceRecord* record) {
  return new BluetoothSocketMac(ui_task_runner, record);
}

BluetoothSocketMac::BluetoothSocketMac(
    const scoped_refptr<base::SequencedTaskRunner>& ui_task_runner,
    IOBluetoothSDPServiceRecord* record)
    : ui_task_runner_(ui_task_runner),
      record_(record),
      delegate_([[BluetoothRFCOMMChannelDelegate alloc] initWithSocket:this]),
      rfcomm_channel_(nil) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());
  [record_ retain];
}

BluetoothSocketMac::~BluetoothSocketMac() {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());
  ReleaseChannel();
  [delegate_ release];
  [record_ release];
}

void BluetoothSocketMac::ReleaseChannel() {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());
  if (rfcomm_channel_ != nil) {
    [rfcomm_channel_ setDelegate:nil];
    [rfcomm_channel_ closeChannel];
    [rfcomm_channel_ release];
    rfcomm_channel_ = nil;
  }

  // Closing the channel above prevents the callback delegate from being called
  // so it is now safe to release all callback state.
  connect_callbacks_.reset(NULL);
  receive_callbacks_.reset(NULL);
  empty_queue(receive_queue_);
  empty_queue(send_queue_);
}

void BluetoothSocketMac::Connect(
    const base::Closure& success_callback,
    const ErrorCompletionCallback& error_callback) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());

  if (connecting()) {
    error_callback.Run(kSocketConnecting);
    return;
  }

  if (rfcomm_channel_ != nil) {
    error_callback.Run(kSocketAlreadyConnected);
    return;
  }

  uint8 rfcomm_channel_id;
  IOReturn status = [record_ getRFCOMMChannelID:&rfcomm_channel_id];
  if (status != kIOReturnSuccess) {
    // TODO(youngki) add support for L2CAP sockets as well.
    error_callback.Run(kL2CAPNotSupported);
    return;
  }

  IOBluetoothDevice* device = [record_ device];
  IOBluetoothRFCOMMChannel* rfcomm_channel;
  status = [device openRFCOMMChannelAsync:&rfcomm_channel
                            withChannelID:rfcomm_channel_id
                                 delegate:delegate_];
  if (status != kIOReturnSuccess) {
    std::stringstream error;
    error << std::string("Failed to connect bluetooth socket (")
          << base::SysNSStringToUTF8([device addressString]) << "): (" << status
          << std::string(")");
    error_callback.Run(error.str());
    return;
  }

  connect_callbacks_.reset(new ConnectCallbacks());
  connect_callbacks_->success_callback = success_callback;
  connect_callbacks_->error_callback = error_callback;
  rfcomm_channel_ = rfcomm_channel;
  [rfcomm_channel_ setDelegate:delegate_];
}

void BluetoothSocketMac::OnChannelOpened(
    IOBluetoothRFCOMMChannel* rfcomm_channel,
    IOReturn status) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());
  DCHECK(rfcomm_channel_ == rfcomm_channel);
  DCHECK(connecting());

  scoped_ptr<ConnectCallbacks> temp = connect_callbacks_.Pass();
  if (status != kIOReturnSuccess) {
    ReleaseChannel();
    std::stringstream error;
    error << "Failed to connect bluetooth socket ("
          << base::SysNSStringToUTF8([[record_ device] addressString]) << "): ("
          << status << ")";
    temp->error_callback.Run(error.str());
    return;
  }

  temp->success_callback.Run();
}

void BluetoothSocketMac::Close() {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());

  ReleaseChannel();
}

void BluetoothSocketMac::Disconnect(const base::Closure& callback) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());

  ReleaseChannel();
  callback.Run();
}

void BluetoothSocketMac::Receive(
    int count,
    const ReceiveCompletionCallback& success_callback,
    const ReceiveErrorCompletionCallback& error_callback) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());

  if (connecting()) {
    error_callback.Run(BluetoothSocket::kSystemError, kSocketConnecting);
    return;
  }

  if (rfcomm_channel_ == nil) {
    error_callback.Run(BluetoothSocket::kDisconnected, kSocketNotConnected);
    return;
  }

  // Only one pending read at a time
  if (receive_callbacks_) {
    error_callback.Run(BluetoothSocket::kIOPending, kReceivePending);
    return;
  }

  // If there is at least one packet, consume it and succeed right away.
  if (!receive_queue_.empty()) {
    scoped_refptr<net::IOBufferWithSize> buffer = receive_queue_.front();
    receive_queue_.pop();
    success_callback.Run(buffer->size(), buffer);
    return;
  }

  // Set the receive callback to use when data is received.
  receive_callbacks_.reset(new ReceiveCallbacks());
  receive_callbacks_->success_callback = success_callback;
  receive_callbacks_->error_callback = error_callback;
}

void BluetoothSocketMac::OnChannelDataReceived(
    IOBluetoothRFCOMMChannel* rfcomm_channel,
    void* data,
    size_t length) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());
  DCHECK(rfcomm_channel_ == rfcomm_channel);
  DCHECK(!connecting());
  CHECK_LT(length, static_cast<size_t>(std::numeric_limits<int>::max()));

  int data_size = static_cast<int>(length);
  scoped_refptr<net::IOBufferWithSize> buffer(
      new net::IOBufferWithSize(data_size));
  memcpy(buffer->data(), data, buffer->size());

  // If there is a pending read callback, call it now.
  if (receive_callbacks_) {
    scoped_ptr<ReceiveCallbacks> temp = receive_callbacks_.Pass();
    temp->success_callback.Run(buffer->size(), buffer);
    return;
  }

  // Otherwise, enqueue the buffer for later use
  receive_queue_.push(buffer);
}

void BluetoothSocketMac::Send(scoped_refptr<net::IOBuffer> buffer,
                              int buffer_size,
                              const SendCompletionCallback& success_callback,
                              const ErrorCompletionCallback& error_callback) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());

  if (connecting()) {
    error_callback.Run(kSocketConnecting);
    return;
  }

  if (rfcomm_channel_ == nil) {
    error_callback.Run(kSocketNotConnected);
    return;
  }

  // Create and enqueue request in preparation of async writes.
  linked_ptr<SendRequest> request(new SendRequest());
  request->buffer_size = buffer_size;
  request->success_callback = success_callback;
  request->error_callback = error_callback;
  send_queue_.push(request);

  // |writeAsync| accepts buffers of max. mtu bytes per call, so we need to emit
  // multiple write operations if buffer_size > mtu.
  BluetoothRFCOMMMTU mtu = [rfcomm_channel_ getMTU];
  scoped_refptr<net::DrainableIOBuffer> send_buffer(
      new net::DrainableIOBuffer(buffer, buffer_size));
  while (send_buffer->BytesRemaining() > 0) {
    int byte_count = send_buffer->BytesRemaining();
    if (byte_count > mtu)
      byte_count = mtu;
    IOReturn status = [rfcomm_channel_ writeAsync:send_buffer->data()
                                           length:byte_count
                                           refcon:request.get()];
    if (status != kIOReturnSuccess) {
      std::stringstream error;
      error << "Failed to connect bluetooth socket ("
            << base::SysNSStringToUTF8([[record_ device] addressString])
            << "): (" << status << ")";
      // Remember the first error only
      if (request->status == kIOReturnSuccess)
        request->status = status;
      request->error_signaled = true;
      request->error_callback.Run(error.str());
      // We may have failed to issue any write operation. In that case, there
      // will be no corresponding completion callback for this particular
      // request, so we must forget about it now.
      if (request->active_async_writes == 0) {
        send_queue_.pop();
      }
      return;
    }

    request->active_async_writes++;
    send_buffer->DidConsume(byte_count);
  }
}

void BluetoothSocketMac::OnChannelWriteComplete(
    IOBluetoothRFCOMMChannel* rfcomm_channel,
    void* refcon,
    IOReturn status) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());

  // Note: We use "CHECK" below to ensure we never run into unforeseen
  // occurrences of asynchronous callbacks, which could lead to data
  // corruption.
  CHECK(rfcomm_channel_ == rfcomm_channel);
  CHECK(static_cast<SendRequest*>(refcon) == send_queue_.front().get());

  // Keep a local linked_ptr to avoid releasing the request too early if we end
  // up removing it from the queue.
  linked_ptr<SendRequest> request = send_queue_.front();

  // Remember the first error only
  if (status != kIOReturnSuccess) {
    if (request->status == kIOReturnSuccess)
      request->status = status;
  }

  // Figure out if we are done with this async request
  request->active_async_writes--;
  if (request->active_async_writes > 0)
    return;

  // If this was the last active async write for this request, remove it from
  // the queue and call the appropriate callback associated to the request.
  send_queue_.pop();
  if (request->status != kIOReturnSuccess) {
    if (!request->error_signaled) {
      std::stringstream error;
      error << "Failed to connect bluetooth socket ("
            << base::SysNSStringToUTF8([[record_ device] addressString])
            << "): (" << status << ")";
      request->error_signaled = true;
      request->error_callback.Run(error.str());
    }
  } else {
    request->success_callback.Run(request->buffer_size);
  }
}

void BluetoothSocketMac::OnChannelClosed(
    IOBluetoothRFCOMMChannel* rfcomm_channel) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(ui_task_runner_->RunsTasksOnCurrentThread());
  DCHECK(rfcomm_channel_ == rfcomm_channel);

  if (receive_callbacks_) {
    scoped_ptr<ReceiveCallbacks> temp = receive_callbacks_.Pass();
    temp->error_callback.Run(BluetoothSocket::kDisconnected,
                             kSocketNotConnected);
  }

  ReleaseChannel();
}

}  // namespace device