summaryrefslogtreecommitdiffstats
path: root/mplexer.hh
blob: d85efe91fe54487b650221966a956cea8b0376bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/*
 * This file is part of PowerDNS or dnsdist.
 * Copyright -- PowerDNS.COM B.V. and its contributors
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of version 2 of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * In addition, for the avoidance of any doubt, permission is granted to
 * link this program with OpenSSL and to (re)distribute the binaries
 * produced as the result of such linking.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
#pragma once
#include <boost/function.hpp>
#include <boost/any.hpp>
#include <boost/shared_array.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_comparison.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/key_extractors.hpp>
#include <vector>
#include <map>
#include <stdexcept>
#include <string>
#include <sys/time.h>

using namespace ::boost::multi_index;

class FDMultiplexerException : public std::runtime_error
{
public:
  FDMultiplexerException(const std::string& str) :
    std::runtime_error(str)
  {}
};

/** Very simple FD multiplexer, based on callbacks and boost::any parameters
    As a special service, this parameter is kept around and can be modified, 
    allowing for state to be stored inside the multiplexer.

    It has some "interesting" semantics
*/

class FDMultiplexer
{
public:
  typedef boost::any funcparam_t;
  typedef boost::function<void(int, funcparam_t&)> callbackfunc_t;
  enum class EventKind : uint8_t
  {
    Read,
    Write,
    Both
  };

protected:
  struct Callback
  {
    callbackfunc_t d_callback;
    mutable funcparam_t d_parameter;
    struct timeval d_ttd;
    int d_fd;
  };

public:
  FDMultiplexer() :
    d_inrun(false)
  {}
  virtual ~FDMultiplexer()
  {}

  static FDMultiplexer* getMultiplexerSilent();

  /* tv will be updated to 'now' before run returns */
  /* timeout is in ms */
  /* returns 0 on timeout, -1 in case of error (but all implementations
     actually throw in that case) and the number of ready events otherwise.
     Note that We might have two events (read AND write) for the same descriptor */
  virtual int run(struct timeval* tv, int timeout = 500) = 0;

  /* timeout is in ms, 0 will return immediately, -1 will block until at least one FD is ready */
  virtual void getAvailableFDs(std::vector<int>& fds, int timeout) = 0;

  //! Add an fd to the read watch list - currently an fd can only be on one list at a time!
  void addReadFD(int fd, callbackfunc_t toDo, const funcparam_t& parameter = funcparam_t(), const struct timeval* ttd = nullptr)
  {
    bool alreadyWatched = d_writeCallbacks.count(fd) > 0;

    if (alreadyWatched) {
      this->alterFD(fd, EventKind::Write, EventKind::Both);
    }
    else {
      this->addFD(fd, EventKind::Read);
    }

    /* do the addition _after_ so the entry is not added if there is an error */
    accountingAddFD(d_readCallbacks, fd, toDo, parameter, ttd);
  }

  //! Add an fd to the write watch list - currently an fd can only be on one list at a time!
  void addWriteFD(int fd, callbackfunc_t toDo, const funcparam_t& parameter = funcparam_t(), const struct timeval* ttd = nullptr)
  {
    bool alreadyWatched = d_readCallbacks.count(fd) > 0;

    if (alreadyWatched) {
      this->alterFD(fd, EventKind::Read, EventKind::Both);
    }
    else {
      this->addFD(fd, EventKind::Write);
    }

    /* do the addition _after_ so the entry is not added if there is an error */
    accountingAddFD(d_writeCallbacks, fd, toDo, parameter, ttd);
  }

  //! Remove an fd from the read watch list. You can't call this function on an fd that is closed already!
  /** WARNING: references to 'parameter' become invalid after this function! */
  void removeReadFD(int fd)
  {
    const auto& iter = d_writeCallbacks.find(fd);
    accountingRemoveFD(d_readCallbacks, fd);

    if (iter != d_writeCallbacks.end()) {
      this->alterFD(fd, EventKind::Both, EventKind::Write);
    }
    else {
      this->removeFD(fd, EventKind::Read);
    }
  }

  //! Remove an fd from the write watch list. You can't call this function on an fd that is closed already!
  /** WARNING: references to 'parameter' become invalid after this function! */
  void removeWriteFD(int fd)
  {
    const auto& iter = d_readCallbacks.find(fd);
    accountingRemoveFD(d_writeCallbacks, fd);

    if (iter != d_readCallbacks.end()) {
      this->alterFD(fd, EventKind::Both, EventKind::Read);
    }
    else {
      this->removeFD(fd, EventKind::Write);
    }
  }

  void setReadTTD(int fd, struct timeval tv, int timeout)
  {
    const auto& it = d_readCallbacks.find(fd);
    if (it == d_readCallbacks.end()) {
      throw FDMultiplexerException("attempt to timestamp fd not in the multiplexer");
    }

    auto newEntry = *it;
    tv.tv_sec += timeout;
    newEntry.d_ttd = tv;
    d_readCallbacks.replace(it, newEntry);
  }

  void setWriteTTD(int fd, struct timeval tv, int timeout)
  {
    const auto& it = d_writeCallbacks.find(fd);
    if (it == d_writeCallbacks.end()) {
      throw FDMultiplexerException("attempt to timestamp fd not in the multiplexer");
    }

    auto newEntry = *it;
    tv.tv_sec += timeout;
    newEntry.d_ttd = tv;
    d_writeCallbacks.replace(it, newEntry);
  }

  void alterFDToRead(int fd, callbackfunc_t toDo, const funcparam_t& parameter = funcparam_t(), const struct timeval* ttd = nullptr)
  {
    accountingRemoveFD(d_writeCallbacks, fd);
    this->alterFD(fd, EventKind::Write, EventKind::Read);
    accountingAddFD(d_readCallbacks, fd, toDo, parameter, ttd);
  }

  void alterFDToWrite(int fd, callbackfunc_t toDo, const funcparam_t& parameter = funcparam_t(), const struct timeval* ttd = nullptr)
  {
    accountingRemoveFD(d_readCallbacks, fd);
    this->alterFD(fd, EventKind::Read, EventKind::Write);
    accountingAddFD(d_writeCallbacks, fd, toDo, parameter, ttd);
  }

  std::vector<std::pair<int, funcparam_t>> getTimeouts(const struct timeval& tv, bool writes = false)
  {
    std::vector<std::pair<int, funcparam_t>> ret;
    const auto tied = boost::tie(tv.tv_sec, tv.tv_usec);
    auto& idx = writes ? d_writeCallbacks.get<TTDOrderedTag>() : d_readCallbacks.get<TTDOrderedTag>();

    for (auto it = idx.begin(); it != idx.end(); ++it) {
      if (it->d_ttd.tv_sec == 0 || tied <= boost::tie(it->d_ttd.tv_sec, it->d_ttd.tv_usec)) {
        break;
      }
      ret.emplace_back(it->d_fd, it->d_parameter);
    }

    return ret;
  }

  typedef FDMultiplexer* getMultiplexer_t();
  typedef std::multimap<int, getMultiplexer_t*> FDMultiplexermap_t;

  static FDMultiplexermap_t& getMultiplexerMap()
  {
    static FDMultiplexermap_t theMap;
    return theMap;
  }

  virtual std::string getName() const = 0;

  size_t getWatchedFDCount(bool writeFDs) const
  {
    return writeFDs ? d_writeCallbacks.size() : d_readCallbacks.size();
  }

  void runForAllWatchedFDs(void (*watcher)(bool isRead, int fd, const funcparam_t&, struct timeval))
  {
    for (const auto& entry : d_readCallbacks) {
      watcher(true, entry.d_fd, entry.d_parameter, entry.d_ttd);
    }
    for (const auto& entry : d_writeCallbacks) {
      watcher(false, entry.d_fd, entry.d_parameter, entry.d_ttd);
    }
  }

protected:
  struct FDBasedTag
  {
  };
  struct TTDOrderedTag
  {
  };
  struct ttd_compare
  {
    /* we want a 0 TTD (no timeout) to come _after_ everything else */
    bool operator()(const struct timeval& lhs, const struct timeval& rhs) const
    {
      /* special treatment if at least one of the TTD is 0,
         normal comparison otherwise */
      if (lhs.tv_sec == 0 && rhs.tv_sec == 0) {
        return false;
      }
      if (lhs.tv_sec == 0 && rhs.tv_sec != 0) {
        return false;
      }
      if (lhs.tv_sec != 0 && rhs.tv_sec == 0) {
        return true;
      }

      return std::tie(lhs.tv_sec, lhs.tv_usec) < std::tie(rhs.tv_sec, rhs.tv_usec);
    }
  };

  typedef multi_index_container<
    Callback,
    indexed_by<
      hashed_unique<tag<FDBasedTag>,
                    member<Callback, int, &Callback::d_fd>>,
      ordered_non_unique<tag<TTDOrderedTag>,
                         member<Callback, struct timeval, &Callback::d_ttd>,
                         ttd_compare>>>
    callbackmap_t;

  callbackmap_t d_readCallbacks, d_writeCallbacks;
  bool d_inrun;

  void accountingAddFD(callbackmap_t& cbmap, int fd, callbackfunc_t toDo, const funcparam_t& parameter, const struct timeval* ttd)
  {
    Callback cb;
    cb.d_fd = fd;
    cb.d_callback = toDo;
    cb.d_parameter = parameter;
    memset(&cb.d_ttd, 0, sizeof(cb.d_ttd));
    if (ttd) {
      cb.d_ttd = *ttd;
    }

    auto pair = cbmap.insert(std::move(cb));
    if (!pair.second) {
      throw FDMultiplexerException("Tried to add fd " + std::to_string(fd) + " to multiplexer twice");
    }
  }

  void accountingRemoveFD(callbackmap_t& cbmap, int fd)
  {
    if (!cbmap.erase(fd)) {
      throw FDMultiplexerException("Tried to remove unlisted fd " + std::to_string(fd) + " from multiplexer");
    }
  }

  virtual void addFD(int fd, EventKind kind) = 0;
  /* most implementations do not care about which event has to be removed, except for kqueue */
  virtual void removeFD(int fd, EventKind kind) = 0;
  /* most implementations do not care about which event has to be removed, except for kqueue */
  virtual void alterFD(int fd, EventKind from, EventKind to)
  {
    /* naive implementation */
    removeFD(fd, from);
    addFD(fd, to);
  }
};