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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
|
/*
* Author: Sven Gothel <sgothel@jausoft.com>
* Copyright (c) 2020 Gothel Software e.K.
* Copyright (c) 2020 ZAFENA AB
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <cstring>
#include <string>
#include <memory>
#include <cstdint>
#include <vector>
#include <cstdio>
#include <algorithm>
// #define PERF_PRINT_ON 1
#include <jau/debug.hpp>
#include "BTIoctl.hpp"
#include "HCIIoctl.hpp"
#include "L2CAPIoctl.hpp"
#include "HCIComm.hpp"
#include "L2CAPComm.hpp"
#include "BTAdapter.hpp"
extern "C" {
#include <unistd.h>
#include <sys/socket.h>
#include <poll.h>
#include <signal.h>
}
using namespace direct_bt;
L2CAPEnv::L2CAPEnv() noexcept
: exploding( jau::environment::getExplodingProperties("direct_bt.l2cap") ),
L2CAP_READER_POLL_TIMEOUT( jau::environment::getInt32Property("direct_bt.l2cap.reader.timeout", 10000, 1500 /* min */, INT32_MAX /* max */) ),
L2CAP_RESTART_COUNT_ON_ERROR( jau::environment::getInt32Property("direct_bt.l2cap.restart.count", 5, INT32_MIN /* min */, INT32_MAX /* max */) ), // FIXME: Move to L2CAPComm
DEBUG_DATA( jau::environment::getBooleanProperty("direct_bt.debug.l2cap.data", false) )
{
}
int L2CAPComm::l2cap_open_dev(const BDAddressAndType & adapterAddressAndType, const L2CAP_PSM psm, const L2CAP_CID cid) {
sockaddr_l2 a;
int fd, err;
// Create a loose L2CAP socket
fd = ::socket(AF_BLUETOOTH, // AF_BLUETOOTH == PF_BLUETOOTH
SOCK_SEQPACKET, BTPROTO_L2CAP);
if( 0 > fd ) {
ERR_PRINT("L2CAPComm::l2cap_open_dev: socket failed");
return fd;
}
// Bind socket to the L2CAP adapter
// BT Core Spec v5.2: Vol 3, Part A: L2CAP_CONNECTION_REQ
bzero((void *)&a, sizeof(a));
a.l2_family=AF_BLUETOOTH;
a.l2_psm = jau::cpu_to_le(direct_bt::number(psm));
a.l2_bdaddr = adapterAddressAndType.address;
a.l2_cid = jau::cpu_to_le(direct_bt::number(cid));
a.l2_bdaddr_type = ::number(adapterAddressAndType.type);
if ( ::bind(fd, (struct sockaddr *) &a, sizeof(a)) < 0 ) {
ERR_PRINT("L2CAPComm::l2cap_open_dev: bind failed");
goto failed;
}
return fd;
failed:
err = errno;
::close(fd);
errno = err;
return -1;
}
int L2CAPComm::l2cap_close_dev(int dd)
{
return ::close(dd);
}
// *************************************************
// *************************************************
// *************************************************
L2CAPComm::L2CAPComm(const BDAddressAndType& adapterAddressAndType_, const L2CAP_PSM psm_, const L2CAP_CID cid_)
: env(L2CAPEnv::get()),
adapterAddressAndType(adapterAddressAndType_),
psm(psm_), cid(cid_),
deviceAddressAndType(BDAddressAndType::ANY_BREDR_DEVICE),
socket_descriptor(-1),
is_open(false), has_ioerror(false), interrupt_flag(false), tid_connect(0), tid_read(0)
{ }
/**
* Setting BT_SECURITY within open() after bind() and before connect()
* causes BlueZ/Kernel to immediately process SMP, leading to a potential deadlock.
*
* Here we experience, setting security level before connect()
* will block the thread within connect(), potentially a mutex used in the SMP procedure.
*
* Hence we set BT_SECURITY after connect() within open().
*/
#define SET_BT_SECURITY_POST_CONNECT 1
bool L2CAPComm::open(const BTDevice& device, const BTSecurityLevel sec_level) {
bool expOpen = false; // C++11, exp as value since C++20
if( !is_open.compare_exchange_strong(expOpen, true) ) {
DBG_PRINT("L2CAPComm::open: Already open: %s, dd %d, %s, psm %s, cid %s",
getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(),
to_string(psm).c_str(), to_string(cid).c_str());
return false;
}
const std::lock_guard<std::recursive_mutex> lock(mtx_write); // RAII-style acquire and relinquish via destructor
has_ioerror = false; // always clear last ioerror flag (should be redundant)
/**
* bt_io_connect ( create_io ) with source address
* - fd = socket(.._)
* - bind(fd, ..)
* - l2cap_set
* -- set imtu, omtu, mode
* -- l2cap_set_master
* -- l2cap_set_flushable
* -- set_priority
* -- set_sec_level
* --- setsockopt(.. BT_SECURITY ..)
*
* - l2cap_connect with destination address
* -- connect(fd, ..)
*/
deviceAddressAndType = device.getAddressAndType();
/** BT Core Spec v5.2: Vol 3, Part A: L2CAP_CONNECTION_REQ */
sockaddr_l2 req;
int res;
int to_retry_count=0; // ETIMEDOUT retry count
DBG_PRINT("L2CAPComm::open: Start Connect: %s, dd %d, %s, psm %s, cid %s",
getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(),
to_string(psm).c_str(), to_string(cid).c_str());
socket_descriptor = l2cap_open_dev(adapterAddressAndType, psm, cid);
if( 0 > socket_descriptor ) {
goto failure; // open failed
}
#if !SET_BT_SECURITY_POST_CONNECT
#if USE_LINUX_BT_SECURITY
if( BTSecurityLevel::UNSET < sec_level ) {
if( !setBTSecurityLevelImpl(sec_level) ) {
goto failure; // sec_level failed
}
}
#endif
#endif
tid_connect = pthread_self(); // temporary safe tid to allow interruption
// actual request to connect to remote device
bzero((void *)&req, sizeof(req));
req.l2_family = AF_BLUETOOTH;
req.l2_psm = jau::cpu_to_le(direct_bt::number(psm));
req.l2_bdaddr = deviceAddressAndType.address;
req.l2_cid = jau::cpu_to_le(direct_bt::number(cid));
req.l2_bdaddr_type = ::number(deviceAddressAndType.type);
while( !interrupt_flag ) {
// blocking
res = ::connect(socket_descriptor, (struct sockaddr*)&req, sizeof(req));
DBG_PRINT("L2CAPComm::open: Connect Result %d, errno 0%X %s, %s", res, errno, strerror(errno), deviceAddressAndType.toString().c_str());
if( !res )
{
break; // done
} else if( ETIMEDOUT == errno ) {
to_retry_count++;
if( to_retry_count < number(Defaults::L2CAP_CONNECT_MAX_RETRY) ) {
WORDY_PRINT("L2CAPComm::open: Connect timeout, retry %d", to_retry_count);
continue;
} else {
ERR_PRINT("L2CAPComm::open: Connect timeout, retried %d", to_retry_count);
goto failure; // exit
}
} else {
// EALREADY == errno || ENETUNREACH == errno || EHOSTUNREACH == errno || ..
ERR_PRINT("L2CAPComm::open: Connect failed");
goto failure; // exit
}
}
// success
tid_connect = 0;
#if SET_BT_SECURITY_POST_CONNECT
#if USE_LINUX_BT_SECURITY
if( BTSecurityLevel::UNSET < sec_level ) {
if( !setBTSecurityLevelImpl(sec_level) ) {
goto failure; // sec_level failed
}
}
#endif
#endif
return true;
failure:
const int err = errno;
close();
errno = err;
return false;
}
bool L2CAPComm::close() noexcept {
bool expOpen = true; // C++11, exp as value since C++20
if( !is_open.compare_exchange_strong(expOpen, false) ) {
DBG_PRINT("L2CAPComm::close: Not connected: %s, dd %d, %s, psm %s, cid %s",
getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(),
to_string(psm).c_str(), to_string(cid).c_str());
has_ioerror = false; // always clear last ioerror flag (should be redundant)
return true;
}
const std::lock_guard<std::recursive_mutex> lock(mtx_write); // RAII-style acquire and relinquish via destructor
has_ioerror = false;
DBG_PRINT("L2CAPComm::close: Start: %s, dd %d, %s, psm %u, cid %u",
getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(), psm, cid);
PERF_TS_T0();
interrupt_flag = true;
{
pthread_t tid_self = pthread_self();
pthread_t _tid_connect = tid_connect;
pthread_t _tid_read = tid_read;
tid_read = 0;
tid_connect = 0;
// interrupt read(..) and , avoiding prolonged hang
if( 0 != _tid_read && tid_self != _tid_read ) {
int kerr;
if( 0 != ( kerr = pthread_kill(_tid_read, SIGALRM) ) ) {
ERR_PRINT("L2CAPComm::close: pthread_kill read %p FAILED: %d", (void*)_tid_read, kerr);
}
}
// interrupt connect(..) and , avoiding prolonged hang
interrupt_flag = true;
if( 0 != _tid_connect && _tid_read != _tid_connect && tid_self != _tid_connect ) {
int kerr;
if( 0 != ( kerr = pthread_kill(_tid_connect, SIGALRM) ) ) {
ERR_PRINT("L2CAPComm::close: pthread_kill connect %p FAILED: %d", (void*)_tid_connect, kerr);
}
}
}
l2cap_close_dev(socket_descriptor);
socket_descriptor = -1;
interrupt_flag = false;
PERF_TS_TD("L2CAPComm::close");
DBG_PRINT("L2CAPComm::close: End: dd %d", socket_descriptor.load());
return true;
}
bool L2CAPComm::setBTSecurityLevel(const BTSecurityLevel sec_level) {
if( !is_open ) {
DBG_PRINT("L2CAPComm::setBTSecurityLevel: Not connected: %s, dd %d, %s, psm %s, cid %s",
getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(),
to_string(psm).c_str(), to_string(cid).c_str());
return false;
}
const std::lock_guard<std::recursive_mutex> lock(mtx_write); // RAII-style acquire and relinquish via destructor
return setBTSecurityLevelImpl(sec_level);
}
bool L2CAPComm::setBTSecurityLevelImpl(const BTSecurityLevel sec_level) {
if( BTSecurityLevel::NONE > sec_level ) {
DBG_PRINT("L2CAPComm::setBTSecurityLevel: sec_level %s, not set", to_string(sec_level).c_str());
return false;
}
#if USE_LINUX_BT_SECURITY
struct bt_security bt_sec;
int result;
BTSecurityLevel old_sec_level = getBTSecurityLevelImpl();
if( old_sec_level != sec_level ) {
bzero(&bt_sec, sizeof(bt_sec));
bt_sec.level = direct_bt::number(sec_level);
result = setsockopt(socket_descriptor, SOL_BLUETOOTH, BT_SECURITY, &bt_sec, sizeof(bt_sec));
if ( 0 == result ) {
DBG_PRINT("L2CAPComm::setBTSecurityLevel: sec_level %s -> %s, success",
to_string(old_sec_level).c_str(), to_string(sec_level).c_str());
return true;
} else {
ERR_PRINT("L2CAPComm::setBTSecurityLevel: sec_level %s -> %s, failed",
to_string(old_sec_level).c_str(), to_string(sec_level).c_str());
return false;
}
} else {
DBG_PRINT("L2CAPComm::setBTSecurityLevel: sec_level %s == %s, success (ignored)",
to_string(old_sec_level).c_str(), to_string(sec_level).c_str());
return true;
}
#else
DBG_PRINT("L2CAPComm::setBTSecurityLevel: sec_level %s, not implemented", to_string(sec_level).c_str());
return false;
#endif
}
BTSecurityLevel L2CAPComm::getBTSecurityLevel() {
if( !is_open ) {
DBG_PRINT("L2CAPComm::getBTSecurityLevel: Not connected: %s, dd %d, %s, psm %s, cid %s",
getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(),
to_string(psm).c_str(), to_string(cid).c_str());
return BTSecurityLevel::UNSET;
}
const std::lock_guard<std::recursive_mutex> lock(mtx_write); // RAII-style acquire and relinquish via destructor
return getBTSecurityLevelImpl();
}
BTSecurityLevel L2CAPComm::getBTSecurityLevelImpl() {
BTSecurityLevel sec_level = BTSecurityLevel::UNSET;
#if USE_LINUX_BT_SECURITY
struct bt_security bt_sec;
socklen_t optlen = sizeof(bt_sec);
int result;
bzero(&bt_sec, sizeof(bt_sec));
result = getsockopt(socket_descriptor, SOL_BLUETOOTH, BT_SECURITY, &bt_sec, &optlen);
if ( 0 == result ) {
if( optlen == sizeof(bt_sec) ) {
sec_level = static_cast<BTSecurityLevel>(bt_sec.level);
DBG_PRINT("L2CAPComm::getBTSecurityLevel: sec_level %s, success", to_string(sec_level).c_str());
} else {
ERR_PRINT("L2CAPComm::getBTSecurityLevel: sec_level %s, failed. Returned size %zd != %zd ",
to_string(sec_level).c_str(), optlen, sizeof(bt_sec));
}
} else {
ERR_PRINT("L2CAPComm::getBTSecurityLevel: sec_level %s, failed. Result %d", to_string(sec_level).c_str(), result);
}
#else
DBG_PRINT("L2CAPComm::setBTSecurityLevel: sec_level %s, not implemented", to_string(sec_level).c_str());
#endif
return sec_level;
}
#define EXITCODE_ENUM(X) \
X(ExitCode, SUCCESS) \
X(ExitCode, NOT_OPEN) \
X(ExitCode, INTERRUPTED) \
X(ExitCode, INVALID_SOCKET_DD) \
X(ExitCode, POLL_ERROR) \
X(ExitCode, POLL_TIMEOUT) \
X(ExitCode, READ_ERROR) \
X(ExitCode, WRITE_ERROR)
#define CASE2_TO_STRING(U,V) case U::V: return #V;
std::string L2CAPComm::getExitCodeString(const ExitCode ec) noexcept {
if( number(ec) >= 0 ) {
return "SUCCESS";
}
switch(ec) {
EXITCODE_ENUM(CASE2_TO_STRING)
default: ; // fall through intended
}
return "Unknown ExitCode";
}
jau::snsize_t L2CAPComm::read(uint8_t* buffer, const jau::nsize_t capacity) {
const int32_t timeoutMS = env.L2CAP_READER_POLL_TIMEOUT;
jau::snsize_t len = 0;
jau::snsize_t err_res = 0;
if( !is_open ) {
err_res = number(ExitCode::NOT_OPEN);
goto errout;
}
if( interrupt_flag ) {
err_res = number(ExitCode::INTERRUPTED);
goto errout;
}
if( 0 > socket_descriptor ) {
err_res = number(ExitCode::INVALID_SOCKET_DD);
goto errout;
}
if( 0 == capacity ) {
goto done;
}
tid_read = pthread_self(); // temporary safe tid to allow interruption
if( timeoutMS ) {
struct pollfd p;
int n;
p.fd = socket_descriptor; p.events = POLLIN;
while ( is_open && !interrupt_flag && ( n = poll( &p, 1, timeoutMS ) ) < 0 ) {
if( !is_open ) {
err_res = number(ExitCode::NOT_OPEN);
goto errout;
}
if( interrupt_flag ) {
err_res = number(ExitCode::INTERRUPTED);
goto errout;
}
if ( errno == EAGAIN || errno == EINTR ) {
// cont temp unavail or interruption
continue;
}
err_res = number(ExitCode::POLL_ERROR);
goto errout;
}
if (!n) {
err_res = number(ExitCode::POLL_TIMEOUT);
errno = ETIMEDOUT;
goto errout;
}
}
while ( is_open && !interrupt_flag && ( len = ::read(socket_descriptor, buffer, capacity) ) < 0 ) {
if( !is_open ) {
err_res = number(ExitCode::NOT_OPEN);
goto errout;
}
if( interrupt_flag ) {
err_res = number(ExitCode::INTERRUPTED);
goto errout;
}
if ( errno == EAGAIN || errno == EINTR ) {
// cont temp unavail or interruption
continue;
}
err_res = number(ExitCode::READ_ERROR);
goto errout;
}
done:
tid_read = 0;
return len;
errout:
tid_read = 0;
if( is_open && !interrupt_flag && errno != ETIMEDOUT ) {
// Only report as ioerror if open, not intentionally interrupted and no timeout!
has_ioerror = true;
if( env.L2CAP_RESTART_COUNT_ON_ERROR < 0 ) {
ABORT("L2CAPComm::read: Error res %d (%s); %s, dd %d, %s, psm %s, cid %s",
err_res, getExitCodeString(err_res).c_str(),
getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(),
to_string(psm).c_str(), to_string(cid).c_str());
} else {
IRQ_PRINT("L2CAPComm::read: Error res %d (%s); %s, dd %d, %s, psm %s, cid %s",
err_res, getExitCodeString(err_res).c_str(),
getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(),
to_string(psm).c_str(), to_string(cid).c_str());
}
} else {
DBG_PRINT("L2CAPComm::read: Failed res %d (%s); %s, dd %d, %s, psm %s, cid %s",
err_res, getExitCodeString(err_res).c_str(),
getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(),
to_string(psm).c_str(), to_string(cid).c_str());
}
return err_res;
}
jau::snsize_t L2CAPComm::write(const uint8_t * buffer, const jau::nsize_t length) {
const std::lock_guard<std::recursive_mutex> lock(mtx_write); // RAII-style acquire and relinquish via destructor
jau::snsize_t len = 0;
jau::snsize_t err_res = 0;
if( !is_open ) {
err_res = number(ExitCode::NOT_OPEN);
goto errout;
}
if( interrupt_flag ) {
err_res = number(ExitCode::INTERRUPTED);
goto errout;
}
if( 0 > socket_descriptor ) {
err_res = number(ExitCode::INVALID_SOCKET_DD);
goto errout;
}
if( 0 == length ) {
goto done;
}
while ( is_open && !interrupt_flag && ( len = ::write(socket_descriptor, buffer, length) ) < 0 ) {
if( !is_open ) {
err_res = number(ExitCode::NOT_OPEN);
goto errout;
}
if( interrupt_flag ) {
err_res = number(ExitCode::INTERRUPTED);
goto errout;
}
if( EAGAIN == errno || EINTR == errno ) {
// cont temp unavail or interruption
continue;
}
err_res = number(ExitCode::WRITE_ERROR);
goto errout;
}
done:
return len;
errout:
if( is_open && !interrupt_flag ) {
// Only report as ioerror if open and not intentionally interrupted!
has_ioerror = true;
if( env.L2CAP_RESTART_COUNT_ON_ERROR < 0 ) {
ABORT("L2CAPComm::write: Error res %d (%s); %s, dd %d, %s, psm %s, cid %s",
err_res, getExitCodeString(err_res).c_str(),
getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(),
to_string(psm).c_str(), to_string(cid).c_str());
} else {
IRQ_PRINT("L2CAPComm::write: Error res %d (%s); %s, dd %d, %s, psm %s, cid %s",
err_res, getExitCodeString(err_res).c_str(),
getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(),
to_string(psm).c_str(), to_string(cid).c_str());
}
} else {
DBG_PRINT("L2CAPComm::write: Failed res %d (%s); %s, dd %d, %s, psm %s, cid %s",
err_res, getExitCodeString(err_res).c_str(),
getStateString().c_str(), socket_descriptor.load(), deviceAddressAndType.toString().c_str(),
to_string(psm).c_str(), to_string(cid).c_str());
}
return err_res;
}
|