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 
25 namespace shill {
26 
IOInputHandler(int fd,const InputCallback & input_callback,const ErrorCallback & error_callback)27 IOInputHandler::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 
~IOInputHandler()34 IOInputHandler::~IOInputHandler() {
35   Stop();
36 }
37 
Start()38 void 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 
Stop()46 void IOInputHandler::Stop() {
47   fd_watcher_.StopWatchingFileDescriptor();
48 }
49 
OnFileCanReadWithoutBlocking(int fd)50 void 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 
OnFileCanWriteWithoutBlocking(int fd)66 void IOInputHandler::OnFileCanWriteWithoutBlocking(int fd) {
67   NOTREACHED() << "Not watching file descriptor for write";
68 }
69 
70 }  // namespace shill
71