1 //
2 // Copyright 2017 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
17 #include "h4_packetizer.h"
18
19 #include <cerrno>
20 #include <dlfcn.h>
21 #include <fcntl.h>
22 #include <sys/uio.h>
23 #include <unistd.h>
24
25 #include "os/log.h"
26 #include "osi/include/osi.h"
27
28 namespace test_vendor_lib {
29
H4Packetizer(int fd,PacketReadCallback command_cb,PacketReadCallback event_cb,PacketReadCallback acl_cb,PacketReadCallback sco_cb,PacketReadCallback iso_cb,ClientDisconnectCallback disconnect_cb)30 H4Packetizer::H4Packetizer(int fd, PacketReadCallback command_cb,
31 PacketReadCallback event_cb,
32 PacketReadCallback acl_cb, PacketReadCallback sco_cb,
33 PacketReadCallback iso_cb,
34 ClientDisconnectCallback disconnect_cb)
35 : uart_fd_(fd),
36 h4_parser_(command_cb, event_cb, acl_cb, sco_cb, iso_cb),
37 disconnect_cb_(std::move(disconnect_cb)) {}
38
Send(uint8_t type,const uint8_t * data,size_t length)39 size_t H4Packetizer::Send(uint8_t type, const uint8_t* data, size_t length) {
40 struct iovec iov[] = {{&type, sizeof(type)}, {const_cast<uint8_t*>(data), length}};
41 ssize_t ret = 0;
42 do {
43 OSI_NO_INTR(ret = writev(uart_fd_, iov, sizeof(iov) / sizeof(iov[0])));
44 } while (-1 == ret && EAGAIN == errno);
45
46 if (ret == -1) {
47 LOG_ERROR("Error writing to UART (%s)", strerror(errno));
48 } else if (ret < static_cast<ssize_t>(length + 1)) {
49 LOG_ERROR("%d / %d bytes written - something went wrong...",
50 static_cast<int>(ret), static_cast<int>(length + 1));
51 }
52 return ret;
53 }
54
55
OnDataReady(int fd)56 void H4Packetizer::OnDataReady(int fd) {
57 if (disconnected_) return;
58 ssize_t bytes_to_read = h4_parser_.BytesRequested();
59 std::vector<uint8_t> buffer(bytes_to_read);
60
61 ssize_t bytes_read;
62 OSI_NO_INTR(bytes_read = read(fd, buffer.data(), bytes_to_read));
63 if (bytes_read == 0) {
64 LOG_INFO("remote disconnected!");
65 disconnected_ = true;
66 disconnect_cb_();
67 return;
68 } else if (bytes_read < 0) {
69 if (errno == EAGAIN) {
70 // No data, try again later.
71 return;
72 } else if (errno == ECONNRESET) {
73 // They probably rejected our packet
74 disconnected_ = true;
75 disconnect_cb_();
76 return;
77 } else {
78 LOG_ALWAYS_FATAL("Read error in %d: %s", h4_parser_.CurrentState(),
79 strerror(errno));
80 }
81 }
82 h4_parser_.Consume(buffer.data(), bytes_read);
83 }
84
85 } // namespace test_vendor_lib
86