-
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
// Copyright 2025 Shota FUJI
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
const std = @import("std");
const sood = @import("sood");
const udp_dst = std.net.Address.initIp4(
sood.discovery.multicast_ipv4_address,
sood.discovery.udp_port,
);
const Options = struct {
/// How many times will I send discovery query via UDP multicast?
/// As discovery is done via UDP, there is a chance of discovery query
/// will be lost. To accommodate the nature of UDP, this module sends
/// more than one query with timeouts (`receive_timeout_ms`) in-between.
///
/// Maximum of total discovery duration is `send_count * receive_timeout_ms`.
send_count: usize = 4,
/// How long should I wait for a response for discovery query?
///
/// Must be greater than 0.
///
/// Maximum of total discovery duration is `send_count * receive_timeout_ms`.
receive_timeout_ms: u32 = 1_300,
};
const StaticError = error{
/// Unexpected error happened.
Unknown,
/// The program has no permission for socket access.
/// Requires user to grant required permission for the program.
SocketPermissionDenied,
/// Unable to create or configure UDP socket.
/// Restarting the program or a system _may_ help.
/// It's also possible that the system does not support required socket features,
/// but this should be quite rare: I belive socket features this module uses are
/// supported in every modern POSIX-compliant OS.
SocketCreationError,
/// Unable to send discovery query.
/// Perhaps multicast is disallowed? User intervention is necessary in that case.
UDPSendError,
/// Unable to receive UDP message.
/// As UDP socket is connection-less, this should be extremely rare.
/// It could be kernel-level network or memory error.
UDPRecvError,
/// A value of `Options.receive_timeout_ms` being `0`.
InvalidReceiveWindow,
/// Network interface is down, kernel error, etc.
NetworkUnavailable,
} || std.mem.Allocator.Error;
pub fn Error(comptime Server: type) type {
return StaticError || Server.FromSoodResponseError;
}
/// List Roon Servers on a network.
pub fn scan(
comptime Server: type,
allocator: std.mem.Allocator,
opts: Options,
) Error(Server)!std.StringHashMap(Server) {
const sockfd = try createSocket(opts);
defer std.posix.close(sockfd);
var servers = std.StringHashMap(Server).init(allocator);
errdefer servers.deinit();
for (0..opts.send_count) |_| {
try sendDiscoveryQuery(sockfd);
while (true) {
std.log.debug("Waiting for UDP message...", .{});
// Discovery response from servers usually fits under 300 bytes.
// Extra bytes for safety.
var received: [512]u8 = undefined;
var src: std.net.Address = undefined;
var src_len: std.posix.socklen_t = udp_dst.getOsSockLen();
const size = std.posix.recvfrom(
sockfd,
&received,
0,
&src.any,
&src_len,
) catch |err| switch (err) {
std.posix.RecvFromError.WouldBlock => {
std.log.debug("UDP read timeout.", .{});
break;
},
std.posix.RecvFromError.MessageTooBig => {
std.log.warn("Unable to read UDP message (message too big)", .{});
continue;
},
else => return StaticError.UDPRecvError,
};
std.log.debug("Got UDP message.", .{});
const response = sood.discovery.Response.parse(received[0..size]) catch |err| {
std.log.warn(
"Unable to parse received UDP message as SOOD message: {s}",
.{@errorName(err)},
);
// Non-SOOD message. Unlikely but technically possible.
continue;
};
const stale = servers.getPtr(response.unique_id);
defer if (stale) |server| {
server.deinit();
};
var server = try Server.fromSoodResponse(allocator, src, &response);
errdefer server.deinit();
try servers.put(server.getKey(), server);
}
}
return servers;
}
pub fn resolve(
comptime Server: type,
allocator: std.mem.Allocator,
unique_id: []const u8,
opts: Options,
) Error(Server)!?Server {
const sockfd = try createSocket(opts);
defer std.posix.close(sockfd);
for (0..opts.send_count) |i| {
std.log.debug("Sending discovery query... ({d})", .{i});
try sendDiscoveryQuery(sockfd);
while (true) {
std.log.debug("Waiting for UDP message...", .{});
// Discovery response from servers usually fits under 300 bytes.
// Extra bytes for safety.
var received: [512]u8 = undefined;
var src: std.net.Address = undefined;
var src_len: std.posix.socklen_t = udp_dst.getOsSockLen();
const size = std.posix.recvfrom(
sockfd,
&received,
0,
&src.any,
&src_len,
) catch |err| switch (err) {
std.posix.RecvFromError.WouldBlock => {
std.log.debug("UDP read timeout.", .{});
break;
},
std.posix.RecvFromError.MessageTooBig => {
std.log.warn("Unable to read UDP message (message too big)", .{});
continue;
},
else => return StaticError.UDPRecvError,
};
std.log.debug("Got UDP message.", .{});
const response = sood.discovery.Response.parse(received[0..size]) catch |err| {
std.log.warn(
"Unable to parse received UDP message as SOOD message: {s}",
.{@errorName(err)},
);
// Non-SOOD message. Unlikely but technically possible.
continue;
};
if (std.mem.eql(u8, response.unique_id, unique_id)) {
return try Server.fromSoodResponse(allocator, src, &response);
}
}
}
return null;
}
fn createSocket(opts: Options) StaticError!std.posix.socket_t {
std.log.debug("Opening UDP socket...", .{});
const sockfd = std.posix.socket(std.posix.AF.INET, std.posix.SOCK.DGRAM, 0) catch |err| {
return switch (err) {
std.posix.SocketError.PermissionDenied => StaticError.SocketPermissionDenied,
std.posix.SocketError.SystemFdQuotaExceeded,
std.posix.SocketError.ProcessFdQuotaExceeded,
=> StaticError.SocketCreationError,
std.posix.SocketError.SystemResources => StaticError.OutOfMemory,
else => StaticError.SocketCreationError,
};
};
errdefer std.posix.close(sockfd);
std.posix.setsockopt(
sockfd,
std.posix.SOL.SOCKET,
std.posix.SO.REUSEADDR,
&std.mem.toBytes(@as(c_int, 1)),
) catch |err| return switch (err) {
std.posix.SetSockOptError.PermissionDenied => StaticError.SocketPermissionDenied,
std.posix.SetSockOptError.SystemResources => StaticError.OutOfMemory,
else => StaticError.SocketCreationError,
};
const sec = std.math.divFloor(u32, opts.receive_timeout_ms, 1_000) catch {
return StaticError.InvalidReceiveWindow;
};
const usec = @min(
std.math.maxInt(i32),
1_000 * (std.math.rem(u32, opts.receive_timeout_ms, 1_000) catch {
return StaticError.InvalidReceiveWindow;
}),
);
std.log.debug("Setting UDP read timeout to {d}ms ({d}sec, {d}usec)", .{
opts.receive_timeout_ms,
sec,
usec,
});
const timeout = std.posix.timeval{ .sec = sec, .usec = usec };
std.posix.setsockopt(
sockfd,
std.posix.SOL.SOCKET,
std.posix.SO.RCVTIMEO,
&std.mem.toBytes(timeout),
) catch |err| return switch (err) {
std.posix.SetSockOptError.PermissionDenied => StaticError.SocketPermissionDenied,
std.posix.SetSockOptError.SystemResources => StaticError.OutOfMemory,
else => StaticError.SocketCreationError,
};
return sockfd;
}
fn sendDiscoveryQuery(sockfd: std.posix.socket_t) StaticError!void {
std.log.debug("Sending server discovery message to {}", .{udp_dst});
_ = std.posix.sendto(
sockfd,
sood.discovery.Query.prebuilt,
0,
&udp_dst.any,
udp_dst.getOsSockLen(),
) catch |err| {
std.log.err("Failed to send discovery message: {s}", .{@errorName(err)});
return switch (err) {
std.posix.SendToError.NetworkSubsystemFailed,
std.posix.SendToError.NetworkUnreachable,
=> StaticError.NetworkUnavailable,
else => StaticError.UDPSendError,
};
};
}