1 /*
2  * Copyright 2018, 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 "poller.h"
18 
19 #include "log.h"
20 
21 #include <errno.h>
22 #include <poll.h>
23 #include <signal.h>
24 #include <stdio.h>
25 #include <string.h>
26 
27 #include <unordered_map>
28 #include <vector>
29 
30 using std::chrono::duration_cast;
31 
calculateTimeout(Pollable::Timestamp deadline,struct timespec * ts)32 static struct timespec* calculateTimeout(Pollable::Timestamp deadline,
33                                          struct timespec* ts) {
34     Pollable::Timestamp now = Pollable::Clock::now();
35     if (deadline < Pollable::Timestamp::max()) {
36         if (deadline <= now) {
37             ts->tv_sec = 0;
38             ts->tv_nsec = 0;
39             return ts;
40         }
41 
42         auto timeout = deadline - now;
43         // Convert and round down to seconds
44         auto seconds = duration_cast<std::chrono::seconds>(timeout);
45         // Then subtract the seconds from the timeout and convert the remainder
46         auto nanos = duration_cast<std::chrono::nanoseconds>(timeout - seconds);
47 
48         ts->tv_sec = seconds.count();
49         ts->tv_nsec = nanos.count();
50 
51         return ts;
52     }
53     return nullptr;
54 }
55 
Poller()56 Poller::Poller() {
57 }
58 
addPollable(Pollable * pollable)59 void Poller::addPollable(Pollable* pollable) {
60     mPollables.push_back(pollable);
61 }
62 
run()63 int Poller::run() {
64     // Block all signals while we're running. This way we don't have to deal
65     // with things like EINTR. We then uses ppoll to set the original mask while
66     // polling. This way polling can be interrupted but socket writing, reading
67     // and ioctl remain interrupt free. If a signal arrives while we're blocking
68     // it it will be placed in the signal queue and handled once ppoll sets the
69     // original mask. This way no signals are lost.
70     sigset_t blockMask, mask;
71     int status = ::sigfillset(&blockMask);
72     if (status != 0) {
73         ALOGE("Unable to fill signal set: %s", strerror(errno));
74         return errno;
75     }
76     status = ::sigprocmask(SIG_SETMASK, &blockMask, &mask);
77     if (status != 0) {
78         ALOGE("Unable to set signal mask: %s", strerror(errno));
79         return errno;
80     }
81 
82     std::vector<struct pollfd> fds;
83     std::unordered_map<int, Pollable*> pollables;
84     while (true) {
85         fds.clear();
86         pollables.clear();
87         Pollable::Timestamp deadline = Pollable::Timestamp::max();
88         for (auto& pollable : mPollables) {
89             size_t start = fds.size();
90             pollable->getPollData(&fds);
91             Pollable::Timestamp pollableDeadline = pollable->getTimeout();
92             // Create a map from each fd to the pollable
93             for (size_t i = start; i < fds.size(); ++i) {
94                 pollables[fds[i].fd] = pollable;
95             }
96             if (pollableDeadline < deadline) {
97                 deadline = pollableDeadline;
98             }
99         }
100 
101         struct timespec ts = { 0, 0 };
102         struct timespec* tsPtr = calculateTimeout(deadline, &ts);
103         status = ::ppoll(fds.data(), fds.size(), tsPtr, &mask);
104         if (status < 0) {
105             if (errno == EINTR) {
106                 // Interrupted, just keep going
107                 continue;
108             }
109             // Actual error, time to quit
110             ALOGE("Polling failed: %s", strerror(errno));
111             return errno;
112         } else if (status > 0) {
113             // Check for read or close events
114             for (const auto& fd : fds) {
115                 if ((fd.revents & (POLLIN | POLLHUP)) == 0) {
116                     // Neither POLLIN nor POLLHUP, not interested
117                     continue;
118                 }
119                 auto pollable = pollables.find(fd.fd);
120                 if (pollable == pollables.end()) {
121                     // No matching fd, weird and unexpected
122                     ALOGE("Poller could not find fd matching %d", fd.fd);
123                     continue;
124                 }
125                 if (fd.revents & POLLIN) {
126                     // This pollable has data available for reading
127                     int status = 0;
128                     if (!pollable->second->onReadAvailable(fd.fd, &status)) {
129                         // The onReadAvailable handler signaled an exit
130                         return status;
131                     }
132                 }
133                 if (fd.revents & POLLHUP) {
134                     // The fd was closed from the other end
135                     int status = 0;
136                     if (!pollable->second->onClose(fd.fd, &status)) {
137                         // The onClose handler signaled an exit
138                         return status;
139                     }
140                 }
141             }
142         }
143         // Check for timeouts
144         Pollable::Timestamp now = Pollable::Clock::now();
145         for (const auto& pollable : mPollables) {
146             if (pollable->getTimeout() <= now) {
147                 int status = 0;
148                 if (!pollable->onTimeout(now, &status)) {
149                     // The onTimeout handler signaled an exit
150                     return status;
151                 }
152             }
153         }
154     }
155 
156     return 0;
157 }
158