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 <dlfcn.h>
20 #include <fcntl.h>
21 #include <sys/uio.h>
22 #include <unistd.h>
23
24 #include <cerrno>
25
26 #include "log.h"
27
28 namespace rootcanal {
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)},
41 {const_cast<uint8_t*>(data), length}};
42 ssize_t ret = 0;
43 do {
44 ret = writev(uart_fd_, iov, sizeof(iov) / sizeof(iov[0]));
45 } while (-1 == ret && (EINTR == errno || EAGAIN == errno));
46
47 if (ret == -1) {
48 LOG_ERROR("Error writing to UART (%s)", strerror(errno));
49 } else if (ret < static_cast<ssize_t>(length + 1)) {
50 LOG_ERROR("%d / %d bytes written - something went wrong...",
51 static_cast<int>(ret), static_cast<int>(length + 1));
52 }
53 return ret;
54 }
55
OnDataReady(int fd)56 void H4Packetizer::OnDataReady(int fd) {
57 if (disconnected_) {
58 return;
59 }
60 ssize_t bytes_to_read = h4_parser_.BytesRequested();
61 std::vector<uint8_t> buffer(bytes_to_read);
62
63 ssize_t bytes_read;
64 do {
65 bytes_read = read(fd, buffer.data(), bytes_to_read);
66 } while (bytes_read == -1 && errno == EINTR);
67
68 if (bytes_read == 0) {
69 LOG_INFO("remote disconnected!");
70 disconnected_ = true;
71 disconnect_cb_();
72 return;
73 }
74 if (bytes_read < 0) {
75 if (errno == EAGAIN) {
76 // No data, try again later.
77 return;
78 }
79 if (errno == ECONNRESET) {
80 // They probably rejected our packet
81 disconnected_ = true;
82 disconnect_cb_();
83 return;
84 }
85
86 LOG_ALWAYS_FATAL("Read error in %d: %s",
87 static_cast<int>(h4_parser_.CurrentState()),
88 strerror(errno));
89 }
90 h4_parser_.Consume(buffer.data(), bytes_read);
91 }
92
93 } // namespace rootcanal
94