-
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
-
381
-
382
-
383
-
384
-
385
-
386
-
387
-
388
-
389
-
390
-
391
-
392
-
393
-
394
// 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 Server = @import("./Server.zig").Server;
const allocator = std.heap.c_allocator;
pub const ScanOptions = extern struct {
/// How many times a scanner sends request UDP message?
count: c_uint,
/// How long will a scanner wait for response UDP message?
receive_window_ms: c_uint,
/// Set default option values.
pub fn init(ptr: ?*ScanOptions) callconv(.C) void {
if (ptr) |opts| {
opts.count = 1;
opts.receive_window_ms = 1_000;
}
}
};
pub const ScanResultCode = enum(c_int) {
ok = 0,
unknown_error = 1,
out_of_memory = 2,
socket_setup_error = 3,
udp_send_error = 4,
udp_recv_error = 5,
null_pointer_args = 6,
socket_permission_error = 7,
too_many_socket_error = 8,
invalid_receive_window = 9,
network_unavailable = 10,
pub fn fromScanError(err: ServerScanner.ScanError) ScanResultCode {
return switch (err) {
ServerScanner.ScanError.Unknown => .unknown_error,
ServerScanner.ScanError.OutOfMemory => .out_of_memory,
ServerScanner.ScanError.SocketSetupError => .socket_setup_error,
ServerScanner.ScanError.UDPSendError => .udp_send_error,
ServerScanner.ScanError.UDPRecvError => .udp_recv_error,
ServerScanner.ScanError.SocketPermissionDenied => .socket_permission_error,
ServerScanner.ScanError.TooManySocketError => .too_many_socket_error,
ServerScanner.ScanError.InvalidReceiveWindow => .invalid_receive_window,
ServerScanner.ScanError.NetworkUnavailable => .network_unavailable,
};
}
};
pub const ScanResult = extern struct {
code: ScanResultCode,
servers: ?*const []*Server = null,
i: usize = 0,
/// Returns `null` when the first argument is `null`, `code` field is
/// not "ok", or iterator reaches to the end.
/// Caller owns the returned `Server`.
/// Call `.free()` after use.
pub fn next(self_ptr: ?*ScanResult) callconv(.C) ?*Server {
const self = self_ptr orelse return null;
const servers = self.servers orelse return null;
if (self.i >= servers.len) {
return null;
}
const found = servers.*[self.i];
self.i += 1;
return found.dupe();
}
/// Reset internal iterator.
pub fn reset(self_ptr: ?*ScanResult) callconv(.C) void {
if (self_ptr) |self| {
self.i = 0;
}
}
/// Call to this function does NOT invalidate "Servers" previously returned by `next()`.
pub fn free(self_ptr: ?*ScanResult) callconv(.C) void {
if (self_ptr) |self| {
if (self.servers) |servers| {
for (servers.*) |server| {
server.free();
}
allocator.free(servers.*);
allocator.destroy(servers);
}
allocator.destroy(self);
}
}
};
pub const FindResult = extern struct {
code: ScanResultCode,
server: ?*Server = null,
pub fn free(self_ptr: ?*FindResult) callconv(.C) void {
if (self_ptr) |self| {
if (self.server) |server| {
server.free();
}
allocator.destroy(self);
}
}
};
pub const ServerScanner = extern struct {
sockfd: ?*std.posix.socket_t = null,
/// Returns `null` on OOM.
pub fn make() callconv(.C) ?*ServerScanner {
const scanner = allocator.create(ServerScanner) catch return null;
scanner.* = .{};
return scanner;
}
pub fn free(self_ptr: ?*ServerScanner) callconv(.C) void {
ServerScanner.close(self_ptr);
if (self_ptr) |self| {
allocator.destroy(self);
}
}
const udp_dst = std.net.Address.initIp4(
sood.discovery.multicast_ipv4_address,
sood.discovery.udp_port,
);
const ScanError = error{
Unknown,
SocketSetupError,
UDPSendError,
UDPRecvError,
SocketPermissionDenied,
TooManySocketError,
InvalidReceiveWindow,
NetworkUnavailable,
} || std.mem.Allocator.Error;
fn setupSocket(self: *ServerScanner) ScanError!*std.posix.socket_t {
if (self.sockfd) |sockfd| {
return sockfd;
}
const fd = try allocator.create(std.posix.socket_t);
errdefer allocator.destroy(fd);
fd.* = std.posix.socket(std.posix.AF.INET, std.posix.SOCK.DGRAM, 0) catch |err| {
return switch (err) {
std.posix.SocketError.PermissionDenied => ScanError.SocketPermissionDenied,
std.posix.SocketError.SystemFdQuotaExceeded, std.posix.SocketError.ProcessFdQuotaExceeded => ScanError.TooManySocketError,
std.posix.SocketError.SystemResources => ScanError.OutOfMemory,
else => ScanError.SocketSetupError,
};
};
errdefer std.posix.close(fd.*);
std.posix.setsockopt(
fd.*,
std.posix.SOL.SOCKET,
std.posix.SO.REUSEADDR,
&std.mem.toBytes(@as(c_int, 1)),
) catch |err| return switch (err) {
std.posix.SetSockOptError.PermissionDenied => ScanError.SocketPermissionDenied,
std.posix.SetSockOptError.SystemResources => ScanError.OutOfMemory,
else => ScanError.SocketSetupError,
};
self.sockfd = fd;
return fd;
}
inline fn setSocketReceiveTimeout(sockfd: *std.posix.socket_t, timeout_ms: u32) ScanError!void {
const sec = std.math.divFloor(u32, timeout_ms, 1_000) catch {
return ScanError.InvalidReceiveWindow;
};
const usec = @min(std.math.maxInt(i32), 1_000 * (std.math.rem(u32, timeout_ms, 1_000) catch {
return ScanError.InvalidReceiveWindow;
}));
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 => ScanError.SocketPermissionDenied,
std.posix.SetSockOptError.SystemResources => ScanError.OutOfMemory,
else => ScanError.SocketSetupError,
};
}
inline fn sendDiscoveryQuery(sockfd: *std.posix.socket_t) ScanError!void {
_ = std.posix.sendto(
sockfd.*,
sood.discovery.Query.prebuilt,
0,
&udp_dst.any,
udp_dst.getOsSockLen(),
) catch |err| return switch (err) {
std.posix.SendToError.NetworkSubsystemFailed, std.posix.SendToError.NetworkUnreachable => ScanError.NetworkUnavailable,
else => ScanError.UDPSendError,
};
}
/// Returns `null` on OOM or when an argument is a null pointer.
pub fn scan(
self_ptr: ?*ServerScanner,
opts_ptr: ?*const ScanOptions,
) callconv(.C) ?*ScanResult {
const self = self_ptr orelse return null;
const result = allocator.create(ScanResult) catch return null;
const opts = opts_ptr orelse {
result.* = .{
.code = .null_pointer_args,
};
return result;
};
self.scan_internal(opts, result) catch |err| {
result.* = .{
.code = ScanResultCode.fromScanError(err),
};
};
return result;
}
fn scan_internal(self: *ServerScanner, opts: *const ScanOptions, result: *ScanResult) ScanError!void {
const sockfd = try self.setupSocket();
try setSocketReceiveTimeout(sockfd, opts.receive_window_ms);
var servers = std.StringHashMap(*Server).init(allocator);
defer servers.deinit();
for (0..opts.count) |_| {
try sendDiscoveryQuery(sockfd);
while (true) {
// 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 => break,
std.posix.RecvFromError.MessageTooBig => continue,
else => return ScanError.UDPRecvError,
};
const response = sood.discovery.Response.parse(received[0..size]) catch {
// Non-SOOD message. Unlikely but technically possible.
continue;
};
const stale = servers.get(response.unique_id);
defer if (stale) |server| {
server.free();
};
try servers.put(response.unique_id, try Server.fromSoodResponse(src, &response));
}
}
const servers_slice = try allocator.create([]*Server);
errdefer allocator.destroy(servers_slice);
servers_slice.* = try allocator.alloc(*Server, servers.count());
errdefer allocator.free(servers_slice.*);
var i: usize = 0;
var iter = servers.valueIterator();
while (iter.next()) |server| {
servers_slice.*[i] = server.*;
i += 1;
}
result.* = .{
.code = .ok,
.servers = servers_slice,
};
}
/// Returns `null` on OOM or when an argument is a null pointer.
pub fn find(self_ptr: ?*ServerScanner, unique_id: [*:0]const u8, unique_id_len: usize) callconv(.C) ?*FindResult {
const self = self_ptr orelse return null;
const unique_id_slice = unique_id[0..unique_id_len];
const result = allocator.create(FindResult) catch return null;
self.findInternal(unique_id_slice, result) catch |err| {
result.* = .{
.code = ScanResultCode.fromScanError(err),
};
};
return result;
}
fn findInternal(self: *ServerScanner, unique_id: []const u8, result: *FindResult) ScanError!void {
const sockfd = try self.setupSocket();
try setSocketReceiveTimeout(sockfd, 1_000);
// Roon Server throttles discovery response to 3~5 secs.
for (0..10) |_| {
try sendDiscoveryQuery(sockfd);
while (true) {
// 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 => break,
std.posix.RecvFromError.MessageTooBig => continue,
else => return ScanError.UDPRecvError,
};
const response = sood.discovery.Response.parse(received[0..size]) catch {
// Non-SOOD message. Unlikely but technically possible.
continue;
};
if (!std.mem.eql(u8, response.unique_id, unique_id)) {
continue;
}
result.* = .{
.code = .ok,
.server = try Server.fromSoodResponse(src, &response),
};
return;
}
}
result.* = .{
.code = .ok,
};
}
pub fn close(self_ptr: ?*ServerScanner) callconv(.C) void {
if (self_ptr) |self| {
if (self.sockfd) |sockfd| {
std.posix.close(sockfd.*);
allocator.destroy(sockfd);
}
}
}
};