-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdnssd.java
More file actions
495 lines (450 loc) · 23.7 KB
/
dnssd.java
File metadata and controls
495 lines (450 loc) · 23.7 KB
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import org.xbill.DNS.DClass;
import org.xbill.DNS.Message;
import org.xbill.DNS.MulticastDNSUtils;
import org.xbill.DNS.Name;
import org.xbill.DNS.Record;
import org.xbill.DNS.Type;
import org.xbill.mDNS.Browse;
import org.xbill.mDNS.Constants;
import org.xbill.mDNS.DNSSDListener;
import org.xbill.mDNS.ExecutionTimer;
import org.xbill.mDNS.Lookup;
import org.xbill.mDNS.Lookup.Domain;
import org.xbill.mDNS.MulticastDNSService;
import org.xbill.mDNS.ServiceInstance;
import org.xbill.mDNS.ServiceName;
@SuppressWarnings({"unchecked", "rawtypes"})
public class dnssd
{
private static final String COMMAND_LINE =
"------------------------------------------------------------------------------\n" +
"| Command Line: dnssd <option> [parameters] |\n" +
"------------------------------------------------------------------------------\n" +
"dnssd -E (Enumerate recommended registration domains)\n" +
"dnssd -F (Enumerate recommended browsing domains)\n" +
"dnssd -B <Type> [<Domain>] (Browse for services instances)\n" +
"dnssd -L <Name> <Type> [<Domain>] (Look up a service instance)\n" +
"dnssd -R <Name> <Type> <Domain> <Port> <Host> [<TXT>...] (Register a service)\n" +
"dnssd -Q <FQDN> <rrtype> <rrclass> (Generic query for any record type)\n" +
"dnssd -G v4/v6/v4v6 <Hostname> (Get address information for hostname)\n" +
"dnssd -V (Get version of currently running daemon / system service)\n" +
"------------------------------------------------------------------------------";
protected dnssd()
throws UnknownHostException
{
}
/**
* Test program
* @param args The input parameters
*
* Command Line:
* dnssd -E (Enumerate recommended registration domains)
* dnssd -F (Enumerate recommended browsing domains)
* dnssd -B <Type> [<Domain>] (Browse for services instances)
* dnssd -L <Name> <Type> <Domain> (Look up a service instance)
* dnssd -R <Name> <Type> <Domain> <Port> <Host> [<TXT>...] (Register a service)
* dnssd -Z <Type> <Domain> (Output results in Zone File format)
* dnssd -Q <FQDN> <rrtype> <rrclass> (Generic query for any record type)
* dnssd -C <FQDN> <rrtype> <rrclass> (Query; reconfirming each result)
*/
public static void main(final String[] args)
throws Exception
{
/*
* TODO: Java has a bug were IPv6 doesn't work and another bug where the IP TTL does not
* get set on outbound packets if IPv6 is enabled. The following code works around
* this issue.
*
* Remove when IPv6 and Socket.setTimeToLive() are working.
*/
// Properties props = System.getProperties();
// props.setProperty("java.net.preferIPv4Stack","true");
// System.setProperties(props);
StringBuilder timingBuilder = new StringBuilder();
try
{
if (args.length > 0)
{
timingBuilder.append("Execution of \"dnssd ");
for (String arg : args)
{
timingBuilder.append(arg).append(" ");
}
timingBuilder.setLength(timingBuilder.length() - 1);
timingBuilder.append("\"");
String temp = args[0];
if ((temp != null) && ((temp.length() == 2) || (temp.length() == 3)) &&
(temp.startsWith("-") || temp.startsWith("--")))
{
Name[] browseDomains;
ArrayList domainNames;
Name[] serviceTypes;
Domain[] domains = null;
char option = temp.charAt(temp.length() - 1);
ExecutionTimer._start();
switch (option)
{
case 'E':
// Enumerate recommended registration domains
ExecutionTimer._start();
Lookup lookup = new Lookup(Constants.DEFAULT_REGISTRATION_DOMAIN_NAME, Constants.REGISTRATION_DOMAIN_NAME);
try
{
domains = lookup.lookupDomains();
} finally
{
lookup.close();
}
System.out.println("Registration Domains:");
printArray(domains, "\t%s\n");
System.out.println("\n" + timingBuilder.toString() + " - took " + ExecutionTimer._took(TimeUnit.SECONDS) + " seconds.");
break;
case 'F':
// Enumerate recommended browse domains
ExecutionTimer._start();
lookup = new Lookup(Constants.DEFAULT_BROWSE_DOMAIN_NAME, Constants.BROWSE_DOMAIN_NAME, Constants.LEGACY_BROWSE_DOMAIN_NAME);
try
{
domains = lookup.lookupDomains();
} finally
{
lookup.close();
}
System.out.println("Browse Domains:");
printArray(domains, "\t%s\n");
System.out.println("\n" + timingBuilder.toString() + " - took " + ExecutionTimer._took(TimeUnit.SECONDS) + " seconds.");
break;
case 'B':
// Browse for service instances
if ((args.length < 2) || (args[1] == null) || (args[1].length() == 0))
{
throw new IllegalArgumentException("Too few arguments for -B option");
}
ExecutionTimer._start();
if (args.length == 2)
{
domainNames = new ArrayList();
lookup = new Lookup(Constants.DEFAULT_BROWSE_DOMAIN_NAME, Constants.BROWSE_DOMAIN_NAME, Constants.LEGACY_BROWSE_DOMAIN_NAME);
try
{
domains = lookup.lookupDomains();
} finally
{
lookup.close();
}
if ((domains != null) && (domains.length > 0))
{
for (int index = 0; index < domains.length; index++)
{
if ((domains[index] != null) && !domainNames.contains(domains[index]))
{
domainNames.add(domains[index].getName());
}
}
}
browseDomains = (Name[]) domainNames.toArray(new Name[domainNames.size()]);
} else
{
browseDomains = new Name[] {new Name(args[2] + (args[2].endsWith(".") ? "" : "."))};
}
System.out.println("Searching for Browse Domains - took " + ExecutionTimer._took(TimeUnit.SECONDS) + " seconds.");
serviceTypes = new Name[browseDomains.length];
for (int i = 0; i < browseDomains.length; i++)
{
serviceTypes[i] = new Name(args[1], browseDomains[i]);
}
System.out.println("Browsing for Services of the following types:");
printArray(serviceTypes, "\t%s\n");
System.out.println();
System.out.println("Services Found:");
ExecutionTimer._start();
// ExecutionTimer.start();
MulticastDNSService mDNSService = new MulticastDNSService();
Object id = mDNSService.startServiceDiscovery(new Browse(serviceTypes), new DNSSDListener()
{
public void handleException(final Object id, final Exception e)
{
if (!((e instanceof IOException) && "no route to host".equalsIgnoreCase(e.getMessage())))
{
System.err.println("Exception: " + e.getMessage());
e.printStackTrace(System.err);
}
}
public void receiveMessage(final Object id, final Message m)
{
}
public void serviceDiscovered(final Object id, final ServiceInstance service)
{
System.out.println("Service Discovered - " + service);
}
public void serviceRemoved(final Object id, final ServiceInstance service)
{
System.out.println("Service Removed - " + service);
}
});
System.out.println("\nStarting Browse for " + timingBuilder.toString() + " - took " + ExecutionTimer._took(TimeUnit.SECONDS) + " seconds.");
while (true)
{
Thread.sleep(10);
if (System.in.read() == 'q')
{
break;
}
}
mDNSService.stopServiceDiscovery(id);
mDNSService.close();
System.out.println("\n" + timingBuilder.toString() + " - took " + ExecutionTimer._took(TimeUnit.SECONDS) + " seconds.");
break;
case 'L':
// Lookup a service
if ((args.length < 3) || (args[2] == null) || (args[2].length() == 0))
{
throw new IllegalArgumentException("Too few arguments for -L option");
}
ExecutionTimer._start();
if (args.length == 3)
{
domainNames = new ArrayList();
lookup = new Lookup(Constants.DEFAULT_BROWSE_DOMAIN_NAME, Constants.BROWSE_DOMAIN_NAME, Constants.LEGACY_BROWSE_DOMAIN_NAME);
try
{
domains = lookup.lookupDomains();
} finally
{
lookup.close();
}
if ((domains != null) && (domains.length > 0))
{
for (int index = 0; index < domains.length; index++)
{
if ((domains[index] != null) && !domainNames.contains(domains[index]))
{
domainNames.add(domains[index].getName());
}
}
}
browseDomains = (Name[]) domainNames.toArray(new Name[domainNames.size()]);
} else
{
browseDomains = new Name[] {new Name(args[3] + (args[3].endsWith(".") ? "" : "."))};
}
System.out.println("\nSearching for Browse Domains - took " + ExecutionTimer._took(TimeUnit.SECONDS) + " seconds.");
serviceTypes = new Name[browseDomains.length];
for (int i = 0; i < browseDomains.length; i++)
{
serviceTypes[i] = new Name(args[1] + "." + args[2], browseDomains[i]);
}
ExecutionTimer._start();
System.out.println("Lookup Service :");
printArray(serviceTypes, "\t%s\n");
System.out.println();
System.out.println("Services Found:");
lookup = new Lookup(serviceTypes);
try
{
printArray(lookup.lookupServices(), "\t%s\n");
} finally
{
lookup.close();
}
System.out.println("\n" + timingBuilder.toString() + " - took " + ExecutionTimer._took(TimeUnit.SECONDS) + " seconds.");
break;
case 'R':
// Register a Service
if (args.length < 5)
{
throw new IllegalArgumentException("Too few arguments for -R option");
}
String[] txtValues = new String[args.length - 6];
if (args.length > 6)
{
System.arraycopy(args, 6, txtValues, 0, txtValues.length);
}
ServiceName serviceName = new ServiceName(args[1] + "." + args[2] + "." + args[3]);
String host = args[5];
int port = Integer.parseInt(args[4]);
if ((host == null) || (host.length() == 0))
{
String machineName = MulticastDNSUtils.getMachineName();
if (machineName == null)
{
host = MulticastDNSUtils.getHostName();
} else
{
host = (machineName.endsWith(".") ? machineName : machineName + ".");
}
}
Name hostname = new Name(host);
InetAddress[] addresses = null;
try
{
addresses = InetAddress.getAllByName(hostname.toString());
} catch (UnknownHostException e)
{
}
if ((addresses == null) || (addresses.length == 0))
{
addresses = MulticastDNSUtils.getLocalAddresses();
}
ExecutionTimer._start();
mDNSService = new MulticastDNSService();
ServiceInstance service = new ServiceInstance(serviceName, 0, 0, port, hostname/*, MulticastDNSService.DEFAULT_SRV_TTL*/, addresses, txtValues);
ServiceInstance registeredService = mDNSService.register(service);
if (registeredService != null)
{
System.out.println("Services Successfully Registered: \n\t" + registeredService);
} else
{
System.err.println("Services Registration Failed!");
}
while (true)
{
Thread.sleep(10);
if (System.in.read() == 'q')
{
if (mDNSService.unregister(registeredService))
{
System.out.println("Services Successfully Unregistered: \n\t" + service);
} else
{
System.err.println("Services Unregistration Failed!");
}
break;
}
}
mDNSService.close();
System.out.println("\n" + timingBuilder.toString() + " - took " + ExecutionTimer._took(TimeUnit.SECONDS) + " seconds.");
break;
case 'Q':
// TODO: Fix Query Results! Add Additional "Known" Records. Why doesn't the SRV record return after expirey?
if (args.length < 4)
{
throw new IllegalArgumentException("Too few arguments for -" + option + " option");
}
int type = Type.value(args[2], true);
if (type < 0)
{
throw new IllegalArgumentException("Invalid Type \"" + args[2] + "\" specified.");
}
int dclass = DClass.value(args[3]);
if (dclass < 0)
{
throw new IllegalArgumentException("Invalid DClass \"" + args[3] + "\" specified.");
}
ExecutionTimer._start();
lookup = new Lookup(new Name[]{new Name(args[1])}, type, dclass);
try
{
Record[] records = lookup.lookupRecords();
System.out.println("Query Resource Records :\n\tName: " + args[1] + ", Type: " + Type.string(type) + ", DClass: " + DClass.string(dclass));
System.out.println();
System.out.println("Resource Records Found:");
printArray(records, "\t%s\n");
} finally
{
lookup.close();
}
System.out.println("\n" + timingBuilder.toString() + " - took " + ExecutionTimer._took(TimeUnit.SECONDS) + " seconds.");
break;
case 'C':
break;
default:
throw new IllegalArgumentException("Invalid option \"" + args[0] + "\" specified!");
}
} else
{
throw new IllegalArgumentException("Invalid option \"" + args[0] + "\" specified!");
}
} else
{
throw new IllegalArgumentException((String) null);
}
} catch (IllegalArgumentException e)
{
printHelp(e.getMessage());
} finally
{
System.out.println("\nTotal " + timingBuilder.toString() + " - took " + ExecutionTimer._took(TimeUnit.SECONDS) + " seconds.");
}
System.exit(0);
}
private static void printArray(final Object[] array, final String... format)
{
if ((array != null) && (format != null) && (array.length > 0) && (format.length > 0))
{
int startFormat = 0;
int endFormat = format.length - 1;
int lastElementFormat = -1;
// Process Headers
if (format.length > 1)
{
while ((startFormat < endFormat) && !format[startFormat].contains("%"))
{
System.out.print(format[startFormat++]);
}
}
// Process Footers
if (format.length > 1)
{
while ((endFormat > startFormat) && !format[endFormat].contains("%"))
{
endFormat--;
}
}
// Get Last Element Format (last format that is not a footer)
lastElementFormat = endFormat;
if ((endFormat - startFormat) > 0)
{
endFormat--;
}
int index = 0;
int fIndex = startFormat;
for (; index < (array.length - 1);)
{
while (!format[fIndex].contains("%"))
{
System.out.print(format[fIndex++]);
if (fIndex > endFormat)
{
fIndex = startFormat;
}
}
System.out.printf(format[fIndex++], array[index++]);
if (fIndex > endFormat)
{
fIndex = startFormat;
}
}
// Format last element
while (!format[fIndex].contains("%"))
{
System.out.print(format[fIndex++]);
if (fIndex > endFormat)
{
fIndex = startFormat;
}
}
if (index < array.length)
{
System.out.printf(format[lastElementFormat], array[index++]);
}
for (fIndex = lastElementFormat + 1; fIndex < format.length; fIndex++)
{
System.out.print(format[fIndex]);
}
}
}
private static void printHelp(final String message)
{
if ((message != null) && (message.length() > 0))
{
System.out.println("\n==>>" + message + "<<==\n");
}
System.out.println(COMMAND_LINE);
}
}