-
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
-
315
-
316
-
317
-
318
-
319
-
320
-
321
-
322
-
323
-
324
-
325
-
326
-
327
-
328
-
329
-
330
-
331
-
332
-
333
-
334
-
335
-
336
-
337
-
338
-
339
-
340
-
341
-
342
-
343
-
344
-
345
-
346
-
347
-
348
-
349
-
350
-
351
-
352
-
353
-
354
-
355
-
356
-
357
-
358
-
359
-
360
-
361
-
362
-
363
-
364
-
365
-
366
-
367
-
368
-
369
-
370
-
371
-
372
-
373
-
374
-
375
-
376
-
377
-
378
-
379
-
380
// Copyright 2025 Shota FUJI
//
// Licensed under the Zero-Clause BSD License or the Apache License, Version 2.0, at your option.
// You may not use, copy, modify, or distribute this file except according to those terms. You can
// find a copy of the Zero-Clause BSD License at LICENSES/0BSD.txt, and a copy of the Apache License,
// Version 2.0 at LICENSES/Apache-2.0.txt. You may also obtain a copy of the Apache License, Version
// 2.0 at <https://www.apache.org/licenses/LICENSE-2.0>
//
// SPDX-License-Identifier: 0BSD OR Apache-2.0
//! This module contains parsing of and serializing from SOOD message used by Roon Core and
//! discovery clients. References:
//! <https://github.com/RoonLabs/node-roon-api/blob/51258392f8bfae3fe218740dda5bc049a822872e/sood.js>
//! <https://github.com/pavoni/pyroon/blob/981a62b715c0bd31664342a7cff94a8624e18f79/roonapi/soodmessage.py>
//! Since there is no official documentation and the message format is flexible (key-value fields,)
//! this module does not add semantics or "static types" over it.
const std = @import("std");
const Self = @This();
const magic_string = "SOOD\x02";
header: Header,
body: Properties,
pub const Kind = enum {
/// A message has unsupported/unknown type field. Caller may reject a message of this kind.
/// This variant exists for forward compatibility.
unknown,
/// Query message. A client performing discovery sends a message of this kind.
query,
/// Response message. Roon Core received a Query sends a message of this kind.
response,
};
pub const Header = struct {
/// Message type. Using "kind" instead of "type" because the latter is keyword, and writing
/// `@"type"` everytime would be annoying.
kind: Kind = .unknown,
pub const byte_size: usize = magic_string.len + 1;
pub const ParseError = error{
/// A message header is incomplete.
InvalidHeaderSize,
/// A message does not have valid SOOD message signature: `['S', 'O', 'O', 'D', 0x2]`.
InvalidSignature,
};
/// Parse header part of the SOOD message bytes and populate struct fields,
/// then returns bytes count read.
pub fn parse(self: *Header, bytes: []const u8) ParseError!usize {
if (bytes.len < byte_size) {
return ParseError.InvalidHeaderSize;
}
if (!std.mem.startsWith(u8, bytes, magic_string)) {
return ParseError.InvalidSignature;
}
self.kind = switch (bytes[5]) {
'Q' => .query,
'R' => .response,
else => .unknown,
};
return byte_size;
}
pub const WriteError = error{
/// Target buffer does not have enough space for the header.
NoEnoughSpace,
/// Tried to write unknown type message.
UnknownKind,
};
};
/// A pair of key and value exist in a message.
pub const Property = struct {
key: []const u8,
value: []const u8,
};
pub const ReadPropertyError = error{
/// Value of key size field is 0.
EmptyKey,
/// Key is not long enough indicated by size field.
IncompleteKey,
/// Key is not valid UTF-8 string.
NonUTF8Key,
/// Value size field is missing, or lacking a byte.
InvalidValueSizeField,
/// Value is not long enough indicated by size field.
IncompleteValue,
/// Value is not valid UTF-8 string.
NonUTF8Value,
};
pub fn readProperty(bytes: []const u8, dst: *Property) ReadPropertyError!usize {
var i: usize = 0;
const key_size = bytes[i];
i += 1;
if (key_size == 0) {
return ReadPropertyError.EmptyKey;
}
const key_start = i;
i += key_size;
if (i > bytes.len) {
return ReadPropertyError.IncompleteKey;
}
const key = bytes[key_start..i];
if (!std.unicode.utf8ValidateSlice(key)) {
return ReadPropertyError.NonUTF8Key;
}
const value_size_start = i;
i += 2;
if (i > bytes.len) {
return ReadPropertyError.InvalidValueSizeField;
}
const value_size = std.mem.readInt(
u16,
&.{ bytes[value_size_start], bytes[value_size_start + 1] },
.big,
);
const value_start = i;
i += value_size;
if (i > bytes.len) {
return ReadPropertyError.IncompleteValue;
}
const value = bytes[value_start..i];
if (!std.unicode.utf8ValidateSlice(value)) {
return ReadPropertyError.NonUTF8Value;
}
dst.key = key;
dst.value = value;
return i;
}
pub const Properties = struct {
bytes: []const u8,
pub const ParseError = ReadPropertyError;
pub const Iterator = struct {
/// Position in the `bytes`.
i: usize = 0,
/// Reference to the Message.
props: *const Properties,
pub fn next(it: *Iterator) ReadPropertyError!?Property {
if (it.i >= it.props.bytes.len) {
return null;
}
const start_i = it.i;
errdefer {
it.i = start_i;
}
var p: Property = undefined;
it.i += try readProperty(it.props.bytes[it.i..], &p);
return p;
}
};
pub fn iterator(props: *const Properties) Iterator {
return .{ .props = props };
}
pub fn estimateByteSize(props: []const Property) usize {
var n: usize = 0;
for (props) |p| {
n += p.estimateByteSize();
}
return n;
}
};
/// Returns a parsed message. Created Message's fields refer to the `bytes`: freeing `bytes` then
/// accessing a Message's field would be use-after-free.
pub fn parse(bytes: []const u8) !Self {
var header = Header{};
const body_start = try header.parse(bytes);
return .{
.header = header,
.body = .{
.bytes = bytes[body_start..],
},
};
}
test parse {
const message = try parse("SOOD\x02R\x03foo\x00\x03bar");
var it = message.body.iterator();
const foo = try it.next();
try std.testing.expect(std.mem.eql(u8, foo.?.key, "foo"));
try std.testing.expect(std.mem.eql(u8, foo.?.value, "bar"));
try std.testing.expect(try it.next() == null);
}
test "Should not parse non-SOOD messages" {
{
// PNG file signature
const message = parse("\x89PNG\r\n\x1a\n");
try std.testing.expectError(Header.ParseError.InvalidSignature, message);
}
{
// No `0x02` after `SOOD`
const message = parse("SOODR\x02foo");
try std.testing.expectError(Header.ParseError.InvalidSignature, message);
}
{
// Too short
const message = parse("SOOD\x02");
try std.testing.expectError(Header.ParseError.InvalidHeaderSize, message);
}
}
test "Should parse unknown message type" {
{
const message = try parse("SOOD\x02r");
try std.testing.expectEqual(Kind.unknown, message.header.kind);
}
{
const message = try parse("SOOD\x02\x02");
try std.testing.expectEqual(Kind.unknown, message.header.kind);
}
}
pub const WriteError = error{
/// Tried to write unknown type message.
UnknownKind,
/// Size of property key is too large.
TooLargePropertyKey,
/// Size of property value is too large.
TooLargePropertyValue,
};
/// Generate SOOD message bytes. Caller is responsible for `free`-ing the returned data.
pub fn write(allocator: std.mem.Allocator, header: Header, props: []const Property) ![]u8 {
var props_size: usize = 0;
for (props) |p| {
props_size += 1 + p.key.len + 2 + p.value.len;
}
const buf = try allocator.alloc(u8, Header.byte_size + props_size);
errdefer allocator.free(buf);
std.mem.copyForwards(u8, buf, magic_string);
buf[magic_string.len] = switch (header.kind) {
.query => 'Q',
.response => 'R',
else => return WriteError.UnknownKind,
};
var i: usize = magic_string.len + 1;
for (props) |p| {
if (p.key.len > std.math.maxInt(u8)) {
return WriteError.TooLargePropertyKey;
}
buf[i] = @truncate(p.key.len);
i += 1;
std.mem.copyForwards(u8, buf[i..], p.key);
i += p.key.len;
if (p.value.len > std.math.maxInt(u16)) {
return WriteError.TooLargePropertyValue;
}
var value_size: [2]u8 = undefined;
std.mem.writeInt(u16, &value_size, @truncate(p.value.len), .big);
std.mem.copyForwards(u8, buf[i..], &value_size);
i += 2;
std.mem.copyForwards(u8, buf[i..], p.value);
i += p.value.len;
}
return buf;
}
test write {
const props = &[_]Property{
.{ .key = "foo", .value = "foo-foo" },
.{ .key = "bar", .value = "bar-bar" },
};
const bytes = try write(std.testing.allocator, .{ .kind = .query }, props);
defer std.testing.allocator.free(bytes);
try std.testing.expect(
std.mem.eql(u8, bytes, "SOOD\x02Q\x03foo\x00\x07foo-foo\x03bar\x00\x07bar-bar"),
);
}
test "Should not write unknown message type" {
const result = write(std.testing.allocator, .{ .kind = .unknown }, &.{});
try std.testing.expectError(WriteError.UnknownKind, result);
}
test "Should not write a key that its size exceeds MAX(u8)" {
const key = try std.testing.allocator.alloc(u8, std.math.maxInt(u8) + 1);
defer std.testing.allocator.free(key);
@memset(key, '?');
const props = &[_]Property{
.{ .key = key, .value = "!" },
};
const result = write(std.testing.allocator, .{ .kind = .query }, props);
try std.testing.expectError(WriteError.TooLargePropertyKey, result);
}
test "Should not write a value that its size exceeds MAX(u16)" {
const value = try std.testing.allocator.alloc(u8, std.math.maxInt(u16) + 1);
defer std.testing.allocator.free(value);
@memset(value, '?');
const props = &[_]Property{
.{ .key = "?", .value = value },
};
const result = write(std.testing.allocator, .{ .kind = .query }, props);
try std.testing.expectError(WriteError.TooLargePropertyValue, result);
}
test "Should write large property" {
const key = try std.testing.allocator.alloc(u8, std.math.maxInt(u8) - 1);
defer std.testing.allocator.free(key);
@memset(key, 'K');
const value = try std.testing.allocator.alloc(u8, std.math.maxInt(u16) - 1);
defer std.testing.allocator.free(value);
@memset(value, 'V');
const props = &[_]Property{
.{ .key = key, .value = value },
};
const bytes = try write(std.testing.allocator, .{ .kind = .query }, props);
defer std.testing.allocator.free(bytes);
try std.testing.expect(bytes.len > 0);
const message = try parse(bytes);
try std.testing.expectEqual(Kind.query, message.header.kind);
var it = message.body.iterator();
const prop = try it.next();
try std.testing.expectEqual(std.math.maxInt(u8) - 1, prop.?.key.len);
try std.testing.expectEqual(std.math.maxInt(u16) - 1, prop.?.value.len);
}