Line data Source code
1 : /*
2 : ________________________________________________________________________
3 : | |
4 : | _ _ _ _ |
5 : | | (_) | | | | |
6 : | __| |_ __ _ _ __ ___ ___| |_ ___ _ __ ___ ___ __| | ___ ___ |
7 : | / _` | |/ _` | '_ ` _ \ / _ \ __/ _ \ '__/ __/ _ \ / _` |/ _ \/ __| |
8 : | | (_| | | (_| | | | | | | __/ || __/ | | (_| (_) | (_| | __/ (__ |
9 : | \__,_|_|\__,_|_| |_| |_|\___|\__\___|_| \___\___/ \__,_|\___|\___| |
10 : | |
11 : |________________________________________________________________________|
12 :
13 : C++ CODEC FOR DIAMETER PROTOCOL (RFC 6733)
14 : Version 0.0.z
15 : https://github.com/testillano/diametercodec
16 :
17 : Licensed under the MIT License <http://opensource.org/licenses/MIT>.
18 : SPDX-License-Identifier: MIT
19 : Copyright (c) 2021 Eduardo Ramos
20 :
21 : Permission is hereby granted, free of charge, to any person obtaining a copy
22 : of this software and associated documentation files (the "Software"), to deal
23 : in the Software without restriction, including without limitation the rights
24 : to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
25 : copies of the Software, and to permit persons to whom the Software is
26 : furnished to do so, subject to the following conditions:
27 :
28 : The above copyright notice and this permission notice shall be included in all
29 : copies or substantial portions of the Software.
30 :
31 : THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
32 : IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
33 : FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
34 : AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
35 : LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
36 : OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
37 : SOFTWARE.
38 : */
39 :
40 : // Standard
41 : #include <stdexcept>
42 :
43 : // Project
44 : #include <ert/diametercodec/codec/Message.hpp>
45 : #include <ert/diametercodec/stack/Dictionary.hpp>
46 :
47 : namespace ert {
48 : namespace diametercodec {
49 : namespace codec {
50 :
51 : // ============================================================================
52 : // Helpers (same encode/decode helpers as Avp.cpp, duplicated to keep files independent)
53 : // ============================================================================
54 :
55 : namespace {
56 :
57 21 : inline uint32_t decode4(const uint8_t* b) {
58 21 : return (uint32_t(b[0]) << 24) | (uint32_t(b[1]) << 16) | (uint32_t(b[2]) << 8) | uint32_t(b[3]);
59 : }
60 :
61 14 : inline uint32_t decode3(const uint8_t* b) { return (uint32_t(b[0]) << 16) | (uint32_t(b[1]) << 8) | uint32_t(b[2]); }
62 :
63 30 : inline void encode4(core::Buffer& out, uint32_t v) {
64 30 : out.push_back(static_cast<uint8_t>(v >> 24));
65 30 : out.push_back(static_cast<uint8_t>(v >> 16));
66 30 : out.push_back(static_cast<uint8_t>(v >> 8));
67 30 : out.push_back(static_cast<uint8_t>(v));
68 30 : }
69 :
70 10 : inline void encode3(core::Buffer& out, uint32_t v) {
71 10 : out.push_back(static_cast<uint8_t>(v >> 16));
72 10 : out.push_back(static_cast<uint8_t>(v >> 8));
73 10 : out.push_back(static_cast<uint8_t>(v));
74 10 : }
75 :
76 : } // anonymous namespace
77 :
78 : // ============================================================================
79 : // Message::decode
80 : // ============================================================================
81 9 : void Message::decode(const uint8_t* buf, size_t len, const stack::Dictionary& dict) {
82 9 : if (len < static_cast<size_t>(core::MessageHeaderLen))
83 2 : throw std::runtime_error("Not enough bytes for message header (20 bytes)");
84 :
85 : // 0 1 2 3
86 : // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
87 : // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
88 : // | Version | Message Length |
89 : // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
90 : // | command flags | Command-Code |
91 : // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
92 : // | Application-ID |
93 : // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
94 : // | Hop-by-Hop Identifier |
95 : // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
96 : // | End-to-End Identifier |
97 : // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
98 : // | AVPs ...
99 : // +-+-+-+-+-+-+-+-+-+-+-+-+-
100 :
101 7 : version_ = buf[0];
102 7 : uint32_t msgLen = decode3(buf + 1);
103 7 : flags_ = buf[4];
104 7 : uint32_t code = decode3(buf + 5);
105 7 : id_ = core::CommandId(static_cast<core::U24>(code), isRequest());
106 7 : applicationId_ = decode4(buf + 8);
107 7 : hopByHop_ = decode4(buf + 12);
108 7 : endToEnd_ = decode4(buf + 16);
109 :
110 7 : if (len < msgLen) throw std::runtime_error("Not enough bytes to cover message length");
111 :
112 : // Decode AVPs
113 6 : avps_.clear();
114 6 : size_t pos = core::MessageHeaderLen;
115 31 : while (pos < msgLen) {
116 25 : Avp avp;
117 25 : size_t consumed = avp.decode(buf + pos, msgLen - pos, dict);
118 25 : avps_.push_back(std::move(avp));
119 25 : pos += consumed;
120 25 : }
121 6 : }
122 :
123 : // ============================================================================
124 : // Message::encode
125 : // ============================================================================
126 10 : core::Buffer Message::encode(const stack::Dictionary& dict) const {
127 10 : core::Buffer out;
128 10 : out.reserve(256); // reasonable initial capacity
129 :
130 : // Version
131 10 : out.push_back(version_);
132 :
133 : // Message Length placeholder (3 bytes)
134 10 : size_t lenPos = out.size();
135 10 : out.push_back(0);
136 10 : out.push_back(0);
137 10 : out.push_back(0);
138 :
139 : // Command Flags
140 10 : out.push_back(flags_);
141 :
142 : // Command-Code (3 bytes)
143 10 : encode3(out, id_.first);
144 :
145 : // Application-ID
146 10 : encode4(out, applicationId_);
147 :
148 : // Hop-by-Hop
149 10 : encode4(out, hopByHop_);
150 :
151 : // End-to-End
152 10 : encode4(out, endToEnd_);
153 :
154 : // AVPs
155 54 : for (const auto& avp : avps_) avp.encode(out, dict);
156 :
157 : // Write message length
158 10 : uint32_t msgLen = static_cast<uint32_t>(out.size());
159 10 : out[lenPos] = static_cast<uint8_t>(msgLen >> 16);
160 10 : out[lenPos + 1] = static_cast<uint8_t>(msgLen >> 8);
161 10 : out[lenPos + 2] = static_cast<uint8_t>(msgLen);
162 :
163 10 : return out;
164 0 : }
165 :
166 : // ============================================================================
167 : // Message::getLength
168 : // ============================================================================
169 2 : size_t Message::getLength(const stack::Dictionary& dict) const {
170 2 : size_t total = core::MessageHeaderLen;
171 7 : for (const auto& avp : avps_) total += 4 * REQUIRED_WORDS(avp.getLength(dict));
172 2 : return total;
173 : }
174 :
175 : // ============================================================================
176 : // Message::setHeaderToAnswer
177 : // ============================================================================
178 1 : void Message::setHeaderToAnswer(const Message& request) {
179 1 : version_ = request.version_;
180 1 : flags_ = request.flags_ & ~core::MsgFlagRequest; // clear R flag
181 1 : id_ = core::CommandId(request.id_.first, false);
182 1 : applicationId_ = request.applicationId_;
183 1 : hopByHop_ = request.hopByHop_;
184 1 : endToEnd_ = request.endToEnd_;
185 1 : }
186 :
187 : // ============================================================================
188 : // Message::getAvp (by id)
189 : // ============================================================================
190 4 : const Avp* Message::getAvp(const core::AvpId& id) const {
191 10 : for (const auto& avp : avps_)
192 9 : if (avp.getId() == id) return &avp;
193 1 : return nullptr;
194 : }
195 :
196 : // ============================================================================
197 : // Message::getAvp (by name)
198 : // ============================================================================
199 3 : const Avp* Message::getAvp(const std::string& name, const stack::Dictionary& dict) const {
200 3 : const stack::Avp* sa = dict.getAvp(name);
201 3 : if (!sa) return nullptr;
202 2 : return getAvp(sa->getId());
203 : }
204 :
205 : // ============================================================================
206 : // Message::toJson
207 : // ============================================================================
208 5 : nlohmann::json Message::toJson(const stack::Dictionary& dict) const { return toJson(dict, DecodeOptions{}); }
209 :
210 6 : nlohmann::json Message::toJson(const stack::Dictionary& dict, const DecodeOptions& options) const {
211 6 : nlohmann::json result = nlohmann::json::object();
212 :
213 : // Header metadata
214 6 : result["_header"] = {{"version", version_},
215 6 : {"flags", flags_},
216 6 : {"command-code", id_.first},
217 0 : {"request", isRequest()},
218 6 : {"application-id", applicationId_},
219 6 : {"hop-by-hop-id", hopByHop_},
220 132 : {"end-to-end-id", endToEnd_}};
221 :
222 : // AVPs as flat JSON object (same as Grouped AVP logic)
223 40 : for (const auto& avp : avps_) {
224 34 : std::string name = avp.getName(dict);
225 34 : nlohmann::json val = avp.toJson(dict, options); // empty options: the plain path
226 34 : if (result.contains(name)) {
227 1 : if (!result[name].is_array()) {
228 1 : nlohmann::json arr = nlohmann::json::array();
229 1 : arr.push_back(std::move(result[name]));
230 1 : result[name] = std::move(arr);
231 1 : }
232 1 : result[name].push_back(std::move(val));
233 : } else {
234 33 : result[name] = std::move(val);
235 : }
236 34 : }
237 :
238 6 : return result;
239 96 : }
240 :
241 : // ============================================================================
242 : // Message::fromJson
243 : // ============================================================================
244 19 : Message Message::fromJson(const nlohmann::json& j, const stack::Dictionary& dict) {
245 19 : Message msg;
246 :
247 : // Parse header if present
248 19 : if (j.contains("_header")) {
249 19 : const auto& h = j["_header"];
250 19 : if (h.contains("version")) msg.version_ = h["version"].get<uint8_t>();
251 19 : if (h.contains("flags")) msg.flags_ = h["flags"].get<uint8_t>();
252 19 : if (h.contains("command-code")) {
253 19 : uint32_t code = h["command-code"].get<uint32_t>();
254 19 : bool req = h.value("request", false);
255 19 : msg.id_ = core::CommandId(static_cast<core::U24>(code), req);
256 : // Set R flag accordingly
257 19 : if (req)
258 18 : msg.flags_ |= core::MsgFlagRequest;
259 : else
260 1 : msg.flags_ &= ~core::MsgFlagRequest;
261 : }
262 19 : if (h.contains("application-id")) msg.applicationId_ = h["application-id"].get<uint32_t>();
263 19 : if (h.contains("hop-by-hop-id")) msg.hopByHop_ = h["hop-by-hop-id"].get<uint32_t>();
264 19 : if (h.contains("end-to-end-id")) msg.endToEnd_ = h["end-to-end-id"].get<uint32_t>();
265 : }
266 :
267 : // Parse AVPs (all keys except _header)
268 243 : for (auto& [key, val] : j.items()) {
269 112 : if (key == "_header") continue;
270 93 : if (val.is_array()) {
271 7 : for (const auto& elem : val) msg.avps_.push_back(Avp::fromJson(key, elem, dict));
272 : } else {
273 91 : msg.avps_.push_back(Avp::fromJson(key, val, dict));
274 : }
275 19 : }
276 :
277 : // JSON objects carry no order (keys are sorted): use the command ABNF
278 : // order from the dictionary so fixed AVPs (e.g. < Session-Id >) go first.
279 19 : const stack::Command* cmd = dict.getCommand(msg.id_);
280 19 : if (cmd) Avp::sortByRules(msg.avps_, cmd->avprules());
281 :
282 19 : return msg;
283 0 : }
284 :
285 : } // namespace codec
286 : } // namespace diametercodec
287 : } // namespace ert
|