1//
2// Copyright (C) 2014 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 "shill/net/io_input_handler.h"
18
19#include <string>
20#include <unistd.h>
21
22#include <base/logging.h>
23#include <base/strings/stringprintf.h>
24
25namespace shill {
26
27IOInputHandler::IOInputHandler(int fd,
28                               const InputCallback& input_callback,
29                               const ErrorCallback& error_callback)
30    : fd_(fd),
31      input_callback_(input_callback),
32      error_callback_(error_callback) {}
33
34IOInputHandler::~IOInputHandler() {
35  Stop();
36}
37
38void IOInputHandler::Start() {
39  if (!base::MessageLoopForIO::current()->WatchFileDescriptor(
40          fd_, true, base::MessageLoopForIO::WATCH_READ,
41          &fd_watcher_, this)) {
42    LOG(ERROR) << "WatchFileDescriptor failed on read";
43  }
44}
45
46void IOInputHandler::Stop() {
47  fd_watcher_.StopWatchingFileDescriptor();
48}
49
50void IOInputHandler::OnFileCanReadWithoutBlocking(int fd) {
51  CHECK_EQ(fd_, fd);
52
53  unsigned char buf[IOHandler::kDataBufferSize];
54  int len = read(fd, buf, sizeof(buf));
55  if (len < 0) {
56    std::string condition = base::StringPrintf(
57        "File read error: %d", errno);
58    LOG(ERROR) << condition;
59    error_callback_.Run(condition);
60  }
61
62  InputData input_data(buf, len);
63  input_callback_.Run(&input_data);
64}
65
66void IOInputHandler::OnFileCanWriteWithoutBlocking(int fd) {
67  NOTREACHED() << "Not watching file descriptor for write";
68}
69
70}  // namespace shill
71