blob: 0da17796d61314d5016347dd3297eac2f9ebd15f [file] [log] [blame]
Vernon Mauerye7329c72018-10-08 12:05:16 -07001/**
2 * Copyright © 2018 Intel Corporation
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#pragma once
17
18#include <algorithm>
19#include <boost/asio/spawn.hpp>
20#include <cstdint>
William A. Kennington IIIf2fd17a2019-04-24 01:53:52 -070021#include <exception>
Vernon Mauerye08fbff2019-04-03 09:19:34 -070022#include <ipmid/api-types.hpp>
Vernon Mauerye7329c72018-10-08 12:05:16 -070023#include <ipmid/message/types.hpp>
24#include <memory>
25#include <phosphor-logging/log.hpp>
Vernon Mauery33298af2019-05-13 15:32:37 -070026#include <sdbusplus/asio/connection.hpp>
Vernon Mauerye7329c72018-10-08 12:05:16 -070027#include <tuple>
28#include <utility>
29#include <vector>
30
31namespace ipmi
32{
33
34struct Context
35{
36 using ptr = std::shared_ptr<Context>;
37
Vernon Mauery33298af2019-05-13 15:32:37 -070038 Context() = delete;
39 Context(const Context&) = default;
40 Context& operator=(const Context&) = default;
41 Context(Context&&) = delete;
42 Context& operator=(Context&&) = delete;
Vernon Mauerye7329c72018-10-08 12:05:16 -070043
Vernon Mauery33298af2019-05-13 15:32:37 -070044 Context(std::shared_ptr<sdbusplus::asio::connection> bus, NetFn netFn,
Johnathan Manteyc11cc5c2020-07-22 13:52:33 -070045 uint8_t lun, Cmd cmd, int channel, int userId, uint32_t sessionId,
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +053046 Privilege priv, int rqSA, boost::asio::yield_context& yield) :
Vernon Mauery33298af2019-05-13 15:32:37 -070047 bus(bus),
Johnathan Manteyc11cc5c2020-07-22 13:52:33 -070048 netFn(netFn), lun(lun), cmd(cmd), channel(channel), userId(userId),
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +053049 sessionId(sessionId), priv(priv), rqSA(rqSA), yield(yield)
Vernon Mauerye7329c72018-10-08 12:05:16 -070050 {
51 }
52
Vernon Mauery33298af2019-05-13 15:32:37 -070053 std::shared_ptr<sdbusplus::asio::connection> bus;
Vernon Mauerye7329c72018-10-08 12:05:16 -070054 // normal IPMI context (what call is this, from whence it came...)
Vernon Mauery33298af2019-05-13 15:32:37 -070055 NetFn netFn;
Johnathan Manteyc11cc5c2020-07-22 13:52:33 -070056 uint8_t lun;
Vernon Mauery33298af2019-05-13 15:32:37 -070057 Cmd cmd;
58 int channel;
59 int userId;
Rajashekar Gade Reddy4d226402019-11-13 17:13:05 +053060 uint32_t sessionId;
Vernon Mauery33298af2019-05-13 15:32:37 -070061 Privilege priv;
Vernon Maueryd6a2da02019-04-09 16:00:46 -070062 // srcAddr is only set on IPMB requests because
63 // Platform Event Message needs it to determine the incoming format
Vernon Mauery33298af2019-05-13 15:32:37 -070064 int rqSA;
James Feistcb09aa02019-09-06 13:41:59 -070065 boost::asio::yield_context yield;
Vernon Mauerye7329c72018-10-08 12:05:16 -070066};
67
68namespace message
69{
70
71namespace details
72{
73
74template <typename A>
75struct UnpackSingle;
76
77template <typename T>
78using UnpackSingle_t = UnpackSingle<utility::TypeIdDowncast_t<T>>;
79
80template <typename A>
81struct PackSingle;
82
83template <typename T>
84using PackSingle_t = PackSingle<utility::TypeIdDowncast_t<T>>;
85
86// size to hold 64 bits plus one (possibly-)partial byte
87static constexpr size_t bitStreamSize = ((sizeof(uint64_t) + 1) * CHAR_BIT);
88
89} // namespace details
90
91/**
92 * @brief a payload class that provides a mechanism to pack and unpack data
93 *
94 * When a new request is being executed, the Payload class is responsible for
95 * attempting to unpack all the required arguments from the incoming blob. For
96 * variable-length functions, it is possible to have function signature have a
97 * Payload object, which will then allow the remaining data to be extracted as
98 * needed.
99 *
100 * When creating a response, the parameters returned from the callback use a
101 * newly created payload object to pack all the parameters into a buffer that is
102 * then returned to the requester.
103 *
104 * These interfaces make calls into the message/pack.hpp and message/unpack.hpp
105 * functions.
106 */
107struct Payload
108{
109 Payload() = default;
110 Payload(const Payload&) = default;
111 Payload& operator=(const Payload&) = default;
112 Payload(Payload&&) = default;
113 Payload& operator=(Payload&&) = default;
114
William A. Kennington III51694c22019-04-24 01:44:44 -0700115 explicit Payload(std::vector<uint8_t>&& data) : raw(std::move(data))
Vernon Mauerye7329c72018-10-08 12:05:16 -0700116 {
117 }
118
119 ~Payload()
120 {
121 using namespace phosphor::logging;
William A. Kennington IIIf2fd17a2019-04-24 01:53:52 -0700122 if (raw.size() != 0 && std::uncaught_exceptions() == 0 && !trailingOk &&
123 !unpackCheck && !unpackError)
Vernon Mauerye7329c72018-10-08 12:05:16 -0700124 {
125 log<level::ERR>("Failed to check request for full unpack");
126 }
127 }
128
129 /******************************************************************
130 * raw vector access
131 *****************************************************************/
132 /**
133 * @brief return the size of the underlying raw buffer
134 */
135 size_t size() const
136 {
137 return raw.size();
138 }
139 /**
140 * @brief resize the underlying raw buffer to a new size
141 *
142 * @param sz - new size for the buffer
143 */
144 void resize(size_t sz)
145 {
146 raw.resize(sz);
147 }
148 /**
149 * @brief return a pointer to the underlying raw buffer
150 */
151 uint8_t* data()
152 {
153 return raw.data();
154 }
155 /**
156 * @brief return a const pointer to the underlying raw buffer
157 */
158 const uint8_t* data() const
159 {
160 return raw.data();
161 }
162
163 /******************************************************************
164 * Response operations
165 *****************************************************************/
166 /**
167 * @brief append a series of bytes to the buffer
168 *
169 * @tparam T - the type pointer to return; must be compatible to a byte
170 *
171 * @param begin - a pointer to the beginning of the series
172 * @param end - a pointer to the end of the series
173 */
174 template <typename T>
175 void append(T* begin, T* end)
176 {
177 static_assert(
178 std::is_same_v<utility::TypeIdDowncast_t<T>, int8_t> ||
179 std::is_same_v<utility::TypeIdDowncast_t<T>, uint8_t> ||
180 std::is_same_v<utility::TypeIdDowncast_t<T>, char>,
181 "begin and end must be signed or unsigned byte pointers");
182 // this interface only allows full-byte access; pack in partial bytes
183 drain();
184 raw.insert(raw.end(), reinterpret_cast<const uint8_t*>(begin),
185 reinterpret_cast<const uint8_t*>(end));
186 }
187
188 /**
189 * @brief append a series of bits to the buffer
190 *
191 * Only the lowest @count order of bits will be appended, with the most
192 * significant of those bits getting appended first.
193 *
194 * @param count - number of bits to append
195 * @param bits - a byte with count significant bits to append
196 */
197 void appendBits(size_t count, uint8_t bits)
198 {
199 // drain whole bytes out
200 drain(true);
201
202 // add in the new bits as the higher-order bits, filling LSBit first
203 fixed_uint_t<details::bitStreamSize> tmp = bits;
204 tmp <<= bitCount;
205 bitStream |= tmp;
206 bitCount += count;
207
208 // drain any whole bytes we have appended
209 drain(true);
210 }
211
212 /**
213 * @brief empty out the bucket and pack it as bytes LSB-first
214 *
215 * @param wholeBytesOnly - if true, only the whole bytes will be drained
216 */
217 void drain(bool wholeBytesOnly = false)
218 {
219 while (bitCount > 0)
220 {
221 uint8_t retVal;
222 if (bitCount < CHAR_BIT)
223 {
224 if (wholeBytesOnly)
225 {
226 break;
227 }
228 }
229 size_t bitsOut = std::min(static_cast<size_t>(CHAR_BIT), bitCount);
230 retVal = static_cast<uint8_t>(bitStream);
231 raw.push_back(retVal);
232 bitStream >>= bitsOut;
233 bitCount -= bitsOut;
234 }
235 }
236
237 // base empty pack
238 int pack()
239 {
240 return 0;
241 }
242
243 /**
244 * @brief pack arbitrary values (of any supported type) into the buffer
245 *
246 * @tparam Arg - the type of the first argument
247 * @tparam Args - the type of the optional remaining arguments
248 *
249 * @param arg - the first argument to pack
250 * @param args... - the optional remaining arguments to pack
251 *
252 * @return int - non-zero on pack errors
253 */
254 template <typename Arg, typename... Args>
255 int pack(Arg&& arg, Args&&... args)
256 {
257 int packRet =
258 details::PackSingle_t<Arg>::op(*this, std::forward<Arg>(arg));
259 if (packRet)
260 {
261 return packRet;
262 }
263 packRet = pack(std::forward<Args>(args)...);
264 drain();
265 return packRet;
266 }
267
William A. Kennington III92476a82019-04-25 01:32:30 -0700268 /**
269 * @brief Prepends another payload to this one
270 *
271 * Avoid using this unless absolutely required since it inserts into the
272 * front of the response payload.
273 *
274 * @param p - The payload to prepend
275 *
276 * @retunr int - non-zero on prepend errors
277 */
278 int prepend(const ipmi::message::Payload& p)
279 {
280 if (bitCount != 0 || p.bitCount != 0)
281 {
282 return 1;
283 }
284 raw.reserve(raw.size() + p.raw.size());
285 raw.insert(raw.begin(), p.raw.begin(), p.raw.end());
286 return 0;
287 }
288
Vernon Mauerye7329c72018-10-08 12:05:16 -0700289 /******************************************************************
290 * Request operations
291 *****************************************************************/
292 /**
293 * @brief pop a series of bytes from the raw buffer
294 *
295 * @tparam T - the type pointer to return; must be compatible to a byte
296 *
297 * @param count - the number of bytes to return
298 *
299 * @return - a tuple of pointers (begin,begin+count)
300 */
301 template <typename T>
302 auto pop(size_t count)
303 {
304 static_assert(
305 std::is_same_v<utility::TypeIdDowncast_t<T>, int8_t> ||
306 std::is_same_v<utility::TypeIdDowncast_t<T>, uint8_t> ||
307 std::is_same_v<utility::TypeIdDowncast_t<T>, char>,
308 "T* must be signed or unsigned byte pointers");
309 // this interface only allows full-byte access; skip partial bits
310 if (bitCount)
311 {
312 // WARN on unused bits?
313 discardBits();
314 }
315 if (count <= (raw.size() - rawIndex))
316 {
317 auto range = std::make_tuple(
318 reinterpret_cast<T*>(raw.data() + rawIndex),
319 reinterpret_cast<T*>(raw.data() + rawIndex + count));
320 rawIndex += count;
321 return range;
322 }
323 unpackError = true;
324 return std::make_tuple(reinterpret_cast<T*>(NULL),
325 reinterpret_cast<T*>(NULL));
326 }
327
328 /**
329 * @brief fill bit stream with at least count bits for consumption
330 *
331 * @param count - number of bit needed
332 *
333 * @return - unpackError
334 */
335 bool fillBits(size_t count)
336 {
337 // add more bits to the top end of the bitstream
338 // so we consume bits least-significant first
339 if (count > (details::bitStreamSize - CHAR_BIT))
340 {
341 unpackError = true;
342 return unpackError;
343 }
344 while (bitCount < count)
345 {
346 if (rawIndex < raw.size())
347 {
348 fixed_uint_t<details::bitStreamSize> tmp = raw[rawIndex++];
349 tmp <<= bitCount;
350 bitStream |= tmp;
351 bitCount += CHAR_BIT;
352 }
353 else
354 {
355 // raw has run out of bytes to pop
356 unpackError = true;
357 return unpackError;
358 }
359 }
360 return false;
361 }
362
363 /**
364 * @brief consume count bits from bitstream (must call fillBits first)
365 *
366 * @param count - number of bit needed
367 *
368 * @return - count bits from stream
369 */
370 uint8_t popBits(size_t count)
371 {
372 if (bitCount < count)
373 {
374 unpackError = true;
375 return 0;
376 }
377 // consume bits low-order bits first
378 auto bits = bitStream.convert_to<uint8_t>();
379 bits &= ((1 << count) - 1);
380 bitStream >>= count;
381 bitCount -= count;
382 return bits;
383 }
384
385 /**
386 * @brief discard all partial bits
387 */
388 void discardBits()
389 {
390 bitStream = 0;
391 bitCount = 0;
392 }
393
394 /**
395 * @brief fully reset the unpack stream
396 */
397 void reset()
398 {
399 discardBits();
400 rawIndex = 0;
401 unpackError = false;
402 }
403
404 /**
405 * @brief check to see if the stream has been fully unpacked
406 *
407 * @return bool - true if the stream has been unpacked and has no errors
408 */
409 bool fullyUnpacked()
410 {
411 unpackCheck = true;
412 return raw.size() == rawIndex && bitCount == 0 && !unpackError;
413 }
414
415 // base empty unpack
416 int unpack()
417 {
418 return 0;
419 }
420
421 /**
422 * @brief unpack arbitrary values (of any supported type) from the buffer
423 *
424 * @tparam Arg - the type of the first argument
425 * @tparam Args - the type of the optional remaining arguments
426 *
427 * @param arg - the first argument to unpack
428 * @param args... - the optional remaining arguments to unpack
429 *
430 * @return int - non-zero for unpack error
431 */
432 template <typename Arg, typename... Args>
433 int unpack(Arg&& arg, Args&&... args)
434 {
435 int unpackRet =
436 details::UnpackSingle_t<Arg>::op(*this, std::forward<Arg>(arg));
437 if (unpackRet)
438 {
439 unpackError = true;
440 return unpackRet;
441 }
442 return unpack(std::forward<Args>(args)...);
443 }
444
445 /**
446 * @brief unpack a tuple of values (of any supported type) from the buffer
447 *
448 * This will unpack the elements of the tuple as if each one was passed in
449 * individually, as if passed into the above variadic function.
450 *
451 * @tparam Types - the implicitly declared list of the tuple element types
452 *
453 * @param t - the tuple of values to unpack
454 *
455 * @return int - non-zero on unpack error
456 */
457 template <typename... Types>
458 int unpack(std::tuple<Types...>& t)
459 {
460 // roll back checkpoint so that unpacking a tuple is atomic
461 size_t priorBitCount = bitCount;
462 size_t priorIndex = rawIndex;
463 fixed_uint_t<details::bitStreamSize> priorBits = bitStream;
464
465 int ret =
466 std::apply([this](Types&... args) { return unpack(args...); }, t);
467 if (ret)
468 {
469 bitCount = priorBitCount;
470 bitStream = priorBits;
471 rawIndex = priorIndex;
472 }
473
474 return ret;
475 }
476
477 // partial bytes in the form of bits
478 fixed_uint_t<details::bitStreamSize> bitStream;
479 size_t bitCount = 0;
480 std::vector<uint8_t> raw;
481 size_t rawIndex = 0;
William A. Kennington III51694c22019-04-24 01:44:44 -0700482 bool trailingOk = true;
483 bool unpackCheck = false;
Vernon Mauerye7329c72018-10-08 12:05:16 -0700484 bool unpackError = false;
485};
486
487/**
488 * @brief high-level interface to an IPMI response
489 *
490 * Make it easy to just pack in the response args from the callback into a
491 * buffer that goes back to the requester.
492 */
493struct Response
494{
495 /* Define all of the basic class operations:
496 * Not allowed:
497 * - Default constructor to avoid nullptrs.
498 * Allowed:
499 * - Copy operations.
500 * - Move operations.
501 * - Destructor.
502 */
503 Response() = delete;
504 Response(const Response&) = default;
505 Response& operator=(const Response&) = default;
506 Response(Response&&) = default;
507 Response& operator=(Response&&) = default;
508 ~Response() = default;
509
510 using ptr = std::shared_ptr<Response>;
511
512 explicit Response(Context::ptr& context) :
513 payload(), ctx(context), cc(ccSuccess)
514 {
515 }
516
517 /**
518 * @brief pack arbitrary values (of any supported type) into the payload
519 *
520 * @tparam Args - the type of the optional arguments
521 *
522 * @param args... - the optional arguments to pack
523 *
524 * @return int - non-zero on pack errors
525 */
526 template <typename... Args>
527 int pack(Args&&... args)
528 {
529 return payload.pack(std::forward<Args>(args)...);
530 }
531
532 /**
533 * @brief pack a tuple of values (of any supported type) into the payload
534 *
535 * This will pack the elements of the tuple as if each one was passed in
536 * individually, as if passed into the above variadic function.
537 *
538 * @tparam Types - the implicitly declared list of the tuple element types
539 *
540 * @param t - the tuple of values to pack
541 *
542 * @return int - non-zero on pack errors
543 */
544 template <typename... Types>
545 int pack(std::tuple<Types...>& t)
546 {
547 return payload.pack(t);
548 }
549
William A. Kennington III92476a82019-04-25 01:32:30 -0700550 /**
551 * @brief Prepends another payload to this one
552 *
553 * Avoid using this unless absolutely required since it inserts into the
554 * front of the response payload.
555 *
556 * @param p - The payload to prepend
557 *
558 * @retunr int - non-zero on prepend errors
559 */
560 int prepend(const ipmi::message::Payload& p)
561 {
562 return payload.prepend(p);
563 }
564
Vernon Mauerye7329c72018-10-08 12:05:16 -0700565 Payload payload;
566 Context::ptr ctx;
567 Cc cc;
568};
569
570/**
571 * @brief high-level interface to an IPMI request
572 *
573 * Make it easy to unpack the buffer into the request args for the callback.
574 */
575struct Request
576{
577 /* Define all of the basic class operations:
578 * Not allowed:
579 * - Default constructor to avoid nullptrs.
580 * Allowed:
581 * - Copy operations.
582 * - Move operations.
583 * - Destructor.
584 */
585 Request() = delete;
586 Request(const Request&) = default;
587 Request& operator=(const Request&) = default;
588 Request(Request&&) = default;
589 Request& operator=(Request&&) = default;
590 ~Request() = default;
591
592 using ptr = std::shared_ptr<Request>;
593
594 explicit Request(Context::ptr context, std::vector<uint8_t>&& d) :
595 payload(std::forward<std::vector<uint8_t>>(d)), ctx(context)
596 {
597 }
598
599 /**
600 * @brief unpack arbitrary values (of any supported type) from the payload
601 *
602 * @tparam Args - the type of the optional arguments
603 *
604 * @param args... - the optional arguments to unpack
605 *
606 * @return int - non-zero for unpack error
607 */
608 template <typename... Args>
609 int unpack(Args&&... args)
610 {
611 int unpackRet = payload.unpack(std::forward<Args>(args)...);
Vernon Maueryf865dea2019-05-03 13:29:40 -0700612 if (unpackRet != ipmi::ccSuccess)
Vernon Mauerye7329c72018-10-08 12:05:16 -0700613 {
Vernon Maueryf865dea2019-05-03 13:29:40 -0700614 // not all bits were consumed by requested parameters
615 return ipmi::ccReqDataLenInvalid;
616 }
617 if (!payload.trailingOk)
618 {
619 if (!payload.fullyUnpacked())
Vernon Mauerye7329c72018-10-08 12:05:16 -0700620 {
Vernon Maueryf865dea2019-05-03 13:29:40 -0700621 // not all bits were consumed by requested parameters
622 return ipmi::ccReqDataLenInvalid;
Vernon Mauerye7329c72018-10-08 12:05:16 -0700623 }
624 }
Vernon Maueryf865dea2019-05-03 13:29:40 -0700625 return ipmi::ccSuccess;
Vernon Mauerye7329c72018-10-08 12:05:16 -0700626 }
627
628 /**
629 * @brief unpack a tuple of values (of any supported type) from the payload
630 *
631 * This will unpack the elements of the tuple as if each one was passed in
632 * individually, as if passed into the above variadic function.
633 *
634 * @tparam Types - the implicitly declared list of the tuple element types
635 *
636 * @param t - the tuple of values to unpack
637 *
638 * @return int - non-zero on unpack error
639 */
640 template <typename... Types>
641 int unpack(std::tuple<Types...>& t)
642 {
643 return std::apply([this](Types&... args) { return unpack(args...); },
644 t);
645 }
646
647 /** @brief Create a response message that corresponds to this request
648 *
649 * @return A shared_ptr to the response message created
650 */
651 Response::ptr makeResponse()
652 {
653 return std::make_shared<Response>(ctx);
654 }
655
656 Payload payload;
657 Context::ptr ctx;
658};
659
660} // namespace message
661
662} // namespace ipmi
663
664// include packing and unpacking of types
665#include <ipmid/message/pack.hpp>
666#include <ipmid/message/unpack.hpp>