Merge pull request #11353 from kvuorine/fwknop-fixes
[feed/packages.git] / net / nginx-util / src / ubus-cxx.hpp
1 #ifndef _UBUS_CXX_HPP
2 #define _UBUS_CXX_HPP
3
4 #include <cassert>
5 #include <libubus.h>
6 #include <memory>
7 #include <mutex>
8 #include <string>
9 #include <utility>
10 #include <vector>
11
12 #ifndef NDEBUG
13 #include <iostream>
14 #endif
15
16
17 namespace ubus {
18
19 static constexpr int call_timeout = 500;
20
21 using msg_ptr = std::shared_ptr<const blob_attr>;
22
23 using strings = std::vector<std::string>;
24
25
26 inline auto concat(strings dest) { return dest; }
27
28
29 template<class ...Strings>
30 inline auto concat(strings dest, strings src, Strings ...more)
31 {
32 dest.reserve(dest.size() + src.size());
33 dest.insert(std::end(dest), std::make_move_iterator(std::begin(src)),
34 std::make_move_iterator(std::end(src)));
35 return concat(std::move(dest), std::move(more)...);
36 }
37
38
39 template<class S, class ...Strings>
40 inline auto concat(strings dest, S src, Strings ...more)
41 {
42 dest.emplace_back(std::move(src));
43 return concat(std::move(dest), std::move(more)...);
44 }
45
46
47
48 class iterator {
49
50 private:
51
52 const strings & keys;
53
54 const size_t n = 0;
55
56 size_t i = 0;
57
58 const blob_attr * pos = nullptr;
59
60 std::unique_ptr<iterator> cur{};
61
62 iterator * parent = nullptr;
63
64 size_t rem = 0;
65
66
67 [[nodiscard]] inline auto matches() const -> bool
68 {
69 return (keys[i].empty() || blobmsg_name(cur->pos)==keys[i]);
70 }
71
72
73 explicit iterator(iterator * par)
74 : keys{par->keys}, n{par->n}, pos{par->pos}, cur{this}, parent{par}
75 {
76 if (pos!=nullptr) {
77 rem = blobmsg_data_len(pos);
78 pos = static_cast<blob_attr *>(blobmsg_data(pos));
79 }
80 }
81
82
83 public:
84
85 explicit iterator(const blob_attr * msg, const strings & filter={""})
86 : keys{filter}, n{keys.size()-1}, pos{msg}, cur{this}
87 {
88 if (pos!=nullptr) {
89 rem = blobmsg_data_len(pos);
90 pos = static_cast<blob_attr *>(blobmsg_data(pos));
91
92 if (rem==0) { pos = nullptr; }
93 else if (i!=n || !matches()) { ++*this; }
94 }
95 }
96
97
98 inline iterator(iterator &&) noexcept = default;
99
100
101 inline iterator(const iterator &) = delete;
102
103
104 inline auto operator=(const iterator &) -> iterator & = delete;
105
106
107 inline auto operator=(iterator &&) -> iterator & = delete;
108
109
110 inline auto operator*() { return cur->pos; }
111
112
113 inline auto operator!=(const iterator & rhs)
114 { return (cur->rem!=rhs.cur->rem || cur->pos!=rhs.cur->pos); }
115
116
117 auto operator++() -> iterator &;
118
119
120 inline ~iterator()
121 { if (cur.get()==this) { static_cast<void>(cur.release()); } }
122
123 };
124
125
126
127 class message {
128
129 private:
130
131 const msg_ptr msg{}; // initialized by callback.
132
133 const strings keys{};
134
135
136 public:
137
138 inline explicit message(msg_ptr message_ptr, strings filter={""})
139 : msg{std::move(message_ptr)}, keys{std::move(filter)} {}
140
141
142 inline message(message &&) = default;
143
144
145 inline message(const message &) = delete;
146
147
148 inline auto operator=(message &&) -> message & = delete;
149
150
151 inline auto operator=(const message &) -> message & = delete;
152
153
154 [[nodiscard]] inline auto begin() const -> iterator
155 { return iterator{msg.get(), keys}; }
156
157
158 [[nodiscard]] inline auto end() const -> iterator
159 { return iterator{nullptr, keys}; }
160
161
162 inline explicit operator bool() const { return begin()!=end(); }
163
164
165 template<class ...Strings>
166 auto filter(Strings ...filter)
167 {
168 strings both{};
169 if (keys.size()!=1 || !keys[0].empty()) { both = keys; }
170 both = concat(std::move(both), std::move(filter)...);
171 return std::move(message{msg, std::move(both)});
172 }
173
174
175 inline ~message() = default;
176
177 };
178
179
180
181 class lock_shared_resources {
182
183 private:
184
185 static std::mutex inuse;
186
187
188 public:
189
190
191 inline lock_shared_resources() { inuse.lock(); }
192
193
194 inline lock_shared_resources(lock_shared_resources &&) noexcept = default;
195
196
197 inline lock_shared_resources(const lock_shared_resources &) = delete;
198
199
200 inline auto operator=(const lock_shared_resources &) -> auto & = delete;
201
202
203 inline auto operator=(lock_shared_resources &&) -> auto && = delete;
204
205
206 //NOLINTNEXTLINE(readability-convert-member-functions-to-static)
207 inline auto get_context() -> ubus_context * // is member to enforce inuse.
208 {
209 static auto ubus_freeing = [] (ubus_context * ctx) { ubus_free(ctx); };
210 static std::unique_ptr<ubus_context, decltype(ubus_freeing)>
211 lazy_ctx{ubus_connect(nullptr), ubus_freeing};
212
213 if (!lazy_ctx) { // it could be available on a later call:
214
215 lazy_ctx.reset(ubus_connect(nullptr));
216
217 if (!lazy_ctx) {
218 throw std::runtime_error("ubus error: cannot connect context");
219 }
220 }
221
222 return lazy_ctx.get();
223 }
224
225
226 //NOLINTNEXTLINE(readability-convert-member-functions-to-static)
227 inline auto get_blob_buf() -> blob_buf * // is member to enforce inuse.
228 {
229 static blob_buf buf;
230
231 static auto blob_buf_freeing = [] (blob_buf * b) { blob_buf_free(b); };
232 static std::unique_ptr<blob_buf, decltype(blob_buf_freeing)>
233 created_to_free_on_the_end_of_life{&buf, blob_buf_freeing};
234
235 blob_buf_init(&buf, 0);
236
237 return &buf;
238 }
239
240
241 inline ~lock_shared_resources() { inuse.unlock(); }
242
243 };
244
245
246 template<class F>
247 auto call(const char * path, const char * method, F set_arguments,
248 int timeout=call_timeout) -> message;
249
250
251 inline auto call(const char * path, const char * method,
252 int timeout=call_timeout) -> message
253 { return call(path, method, [](blob_buf * /*buf*/) { return 0; }, timeout); }
254
255
256 inline auto call(const char * path, int timeout=call_timeout) -> message
257 { return call(path, "", timeout); }
258
259
260
261
262 // ------------------------- implementation: ----------------------------------
263
264
265 std::mutex lock_shared_resources::inuse;
266
267
268 inline auto iterator::operator++() -> iterator &
269 {
270 for(;;) {
271 #ifndef NDEBUG
272 std::cout<<std::string(i,'>')<<" look for "<<keys[i]<<" at ";
273 std::cout<<blobmsg_name(cur->pos)<<std::endl;
274 #endif
275
276 auto id = blob_id(cur->pos);
277 if ( (id==BLOBMSG_TYPE_TABLE || id==BLOBMSG_TYPE_ARRAY)
278 && i<n
279 && matches()
280 && blobmsg_data_len(cur->pos)>0 )
281 { //immmerge:
282 ++i;
283
284 auto tmp = cur.release();
285
286 struct new_iterator : public iterator // use private constructor:
287 { explicit new_iterator(iterator * par) : iterator{par} {} };
288 cur = std::make_unique<new_iterator>(tmp);
289
290 } else {
291 while (true) {
292 cur->rem -= blob_pad_len(cur->pos);
293 cur->pos = blob_next(cur->pos);
294 auto len = blob_pad_len(cur->pos);
295
296 if (cur->rem>0 && len<=cur->rem && len>=sizeof(blob_attr))
297 { break; }
298
299 //emerge:
300 auto tmp = cur->parent;
301
302 if (tmp == nullptr) {
303 cur->pos = nullptr;
304 return *cur;
305 }
306
307 cur.reset(tmp);
308
309 --i;
310 }
311 }
312 if (i==n && matches()) { return *cur; }
313 }
314 }
315
316
317 template<class F>
318 inline auto call(const char * path, const char * method, F set_arguments,
319 int timeout) -> message
320 {
321
322 auto shared = lock_shared_resources{};
323
324 auto ctx = shared.get_context();
325
326 uint32_t id;
327 int err = ubus_lookup_id(ctx, path, &id);
328
329 if (err==0) { // call
330 ubus_request request{};
331
332 auto buf = shared.get_blob_buf();
333 err = set_arguments(buf);
334 if (err==0) {
335 err = ubus_invoke_async(ctx, id, method, buf->head, &request);
336 }
337
338 if (err==0) {
339
340 msg_ptr message_ptr;
341
342 /* Cannot capture message_ptr, the lambda would be another type.
343 * Pass a location where to save the message as priv pointer when
344 * invoking and get it back here:
345 */
346 request.priv = &message_ptr;
347
348 request.data_cb =
349 [](ubus_request * req, int /*type*/, blob_attr * msg)
350 {
351 if (req==nullptr || msg==nullptr) { return; }
352
353 auto saved = static_cast<msg_ptr *>(req->priv);
354 if (saved==nullptr || *saved) { return; }
355
356 saved->reset(blob_memdup(msg), free);
357 if (!*saved) { throw std::bad_alloc(); }
358 };
359
360 err = ubus_complete_request(ctx, &request, timeout);
361
362 if (err==0) { return message{message_ptr}; }
363 }
364 }
365
366 std::string errmsg = "ubus::call error: cannot invoke";
367 errmsg += " (" + std::to_string(err) + ") " + path + " " + method;
368 throw std::runtime_error(errmsg);
369 }
370
371
372 } // namespace ubus
373
374
375 #endif