summaryrefslogtreecommitdiffstats
path: root/src/direct_bt/L2CAPComm.cpp
blob: b3493fc64a52db06ec3c9b50e01ed7c7de65b1f8 (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
/*
 * 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 "DBTAdapter.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 EUI48 & adapterAddress, const uint16_t psm, const uint16_t cid, const bool pubaddrAdapter) {
    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(psm);
    a.l2_bdaddr = adapterAddress;
    a.l2_cid = jau::cpu_to_le(cid);
    a.l2_bdaddr_type = pubaddrAdapter ? BDADDR_LE_PUBLIC : BDADDR_LE_RANDOM;
    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(std::shared_ptr<DBTDevice> device_, const uint16_t psm_, const uint16_t cid_)
: env(L2CAPEnv::get()),
  device(device_), deviceString(device_->getAddressString()), psm(psm_), cid(cid_),
  socket_descriptor( l2cap_open_dev(device_->getAdapter().getAddress(), psm_, cid_, true /* pubaddrAdptr */) ),
  is_connected(true), has_ioerror(false), interrupt_flag(false), tid_connect(0), tid_read(0)
{
    /** 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::ctor: Start Connect: %s, dd %d, %s, psm %u, cid %u, pubDevice %d",
              getStateString().c_str(), socket_descriptor.load(), deviceString.c_str(), psm_, cid_, true);

    if( 0 > socket_descriptor ) {
        goto failure; // open failed
    }
    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(psm_);
    req.l2_bdaddr = device_->getAddress();
    req.l2_cid = jau::cpu_to_le(cid_);
    req.l2_bdaddr_type = device_->getAddressType();

    while( !interrupt_flag ) {
        // blocking
        res = ::connect(socket_descriptor, (struct sockaddr*)&req, sizeof(req));

        DBG_PRINT("L2CAPComm::ctor: Connect Result %d, errno 0%X %s, %s", res, errno, strerror(errno), deviceString.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::ctor: Connect timeout, retry %d", to_retry_count);
                continue;
            } else {
                ERR_PRINT("L2CAPComm::ctor: Connect timeout, retried %d", to_retry_count);
                goto failure; // exit
            }

        } else  {
            // EALREADY == errno || ENETUNREACH == errno || EHOSTUNREACH == errno || ..
            ERR_PRINT("L2CAPComm::ctor: Connect failed");
            goto failure; // exit
        }
    }
    // success
    tid_connect = 0;
    return;

failure:
    const int err = errno;
    disconnect();
    errno = err;
}

bool L2CAPComm::disconnect() noexcept {
    bool expConn = true; // C++11, exp as value since C++20
    if( !is_connected.compare_exchange_strong(expConn, false) ) {
        DBG_PRINT("L2CAPComm::disconnect: Not connected: %s, dd %d, %s, psm %u, cid %u, pubDevice %d",
                  getStateString().c_str(), socket_descriptor.load(), deviceString.c_str(), psm, cid, true);
        return false;
    }
    const std::lock_guard<std::recursive_mutex> lock(mtx_write); // RAII-style acquire and relinquish via destructor

    has_ioerror = false;
    DBG_PRINT("L2CAPComm::disconnect: Start: %s, dd %d, %s, psm %u, cid %u, pubDevice %d",
              getStateString().c_str(), socket_descriptor.load(), deviceString.c_str(), psm, cid, true);
    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::disconnect: 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::disconnect: 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::disconnect");
    DBG_PRINT("L2CAPComm::disconnect: End: dd %d", socket_descriptor.load());
    return true;
}

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;

    tid_read = pthread_self(); // temporary safe tid to allow interruption

    if( 0 > socket_descriptor ) {
        err_res = -1; // invalid socket_descriptor or capacity
        goto errout;
    }
    if( 0 == capacity ) {
        goto done;
    }

    if( timeoutMS ) {
        struct pollfd p;
        int n;

        p.fd = socket_descriptor; p.events = POLLIN;
        while ( !interrupt_flag && (n = poll(&p, 1, timeoutMS)) < 0 ) {
            if ( !interrupt_flag && ( errno == EAGAIN || errno == EINTR ) ) {
                // cont temp unavail or interruption
                continue;
            }
            err_res = -10; // poll error !(ETIMEDOUT || EAGAIN || EINTR)
            goto errout;
        }
        if (!n) {
            err_res = -11; // poll error ETIMEDOUT
            errno = ETIMEDOUT;
            goto errout;
        }
    }

    while ((len = ::read(socket_descriptor, buffer, capacity)) < 0) {
        if (errno == EAGAIN || errno == EINTR ) {
            // cont temp unavail or interruption
            continue;
        }
        err_res = -20; // read error
        goto errout;
    }

done:
    tid_read = 0;
    return len;

errout:
    tid_read = 0;
    if( errno != ETIMEDOUT ) {
        has_ioerror = true;
        if( is_connected ) {
            if( env.L2CAP_RESTART_COUNT_ON_ERROR < 0 ) {
                ABORT("L2CAPComm::read: Error res %d; %s, dd %d, %s, psm %u, cid %u",
                      err_res, getStateString().c_str(), socket_descriptor.load(), deviceString.c_str(), psm, cid);
            } else {
                IRQ_PRINT("L2CAPComm::read: Error res %d; %s, dd %d, %s, psm %u, cid %u",
                      err_res, getStateString().c_str(), socket_descriptor.load(), deviceString.c_str(), psm, cid);
            }
        }
    }
    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( 0 > socket_descriptor ) {
        err_res = -1; // invalid socket_descriptor or capacity
        goto errout;
    }
    if( 0 == length ) {
        goto done;
    }

    while( ( len = ::write(socket_descriptor, buffer, length) ) < 0 ) {
        if( EAGAIN == errno || EINTR == errno ) {
            continue;
        }
        err_res = -10; // write error !(EAGAIN || EINTR)
        goto errout;
    }

done:
    return len;

errout:
    has_ioerror = true;
    if( is_connected ) {
        if( env.L2CAP_RESTART_COUNT_ON_ERROR < 0 ) {
            ABORT("L2CAPComm::write: Error res %d; %s, dd %d, %s, psm %u, cid %u",
                  err_res, getStateString().c_str(), socket_descriptor.load(), deviceString.c_str(), psm, cid);
        } else {
            IRQ_PRINT("L2CAPComm::write: Error res %d; %s, dd %d, %s, psm %u, cid %u",
                  err_res, getStateString().c_str(), socket_descriptor.load(), deviceString.c_str(), psm, cid);
        }
    }
    return err_res;
}