Replace jmdns submodule with checked in code

This commit is contained in:
Daniel Martí 2015-03-31 19:44:03 +02:00
parent 6deac28a8b
commit 4258ea1c40
63 changed files with 15751 additions and 5 deletions

4
.gitmodules vendored
View File

@ -6,10 +6,6 @@
path = extern/MemorizingTrustManager path = extern/MemorizingTrustManager
url = https://github.com/ge0rg/MemorizingTrustManager.git url = https://github.com/ge0rg/MemorizingTrustManager.git
ignore = dirty ignore = dirty
[submodule "extern/jmdns"]
path = extern/jmdns
url = https://gitlab.com/fdroid/jmdns.git
ignore = dirty
[submodule "extern/Support"] [submodule "extern/Support"]
path = extern/Support path = extern/Support
url = https://android.googlesource.com/platform/frameworks/support url = https://android.googlesource.com/platform/frameworks/support

1
extern/jmdns vendored

@ -1 +0,0 @@
Subproject commit a81b14c758809c9f3a0bf8177e9114f4eb9d40ff

10
extern/jmdns/.classpath vendored Normal file
View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java"/>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources"/>
<classpathentry kind="src" output="target/test-classes" path="src/test/java"/>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources"/>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="target/classes"/>
</classpath>

23
extern/jmdns/.project vendored Normal file
View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>JMDNS</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

202
extern/jmdns/LICENSE vendored Normal file
View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

459
extern/jmdns/LICENSE-LGPL.txt vendored Normal file
View File

@ -0,0 +1,459 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS

1
extern/jmdns/build.gradle vendored Normal file
View File

@ -0,0 +1 @@
apply plugin: 'java'

View File

@ -0,0 +1,433 @@
// /Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns;
import java.io.Closeable;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Collection;
import java.util.Map;
import javax.jmdns.impl.JmDNSImpl;
/**
* mDNS implementation in Java.
*
* @author Arthur van Hoff, Rick Blair, Jeff Sonstein, Werner Randelshofer, Pierre Frisch, Scott Lewis, Scott Cytacki
*/
public abstract class JmDNS implements Closeable {
/**
*
*/
public static interface Delegate {
/**
* This method is called if JmDNS cannot recover from an I/O error.
*
* @param dns
* target DNS
* @param infos
* service info registered with the DNS
*/
public void cannotRecoverFromIOError(JmDNS dns, Collection<ServiceInfo> infos);
}
/**
* The version of JmDNS.
*/
public static final String VERSION = "3.4.2";
/**
* <p>
* Create an instance of JmDNS.
* </p>
* <p>
* <b>Note:</b> This is a convenience method. The preferred constructor is {@link #create(InetAddress, String)}.<br/>
* Check that your platform correctly handle the default localhost IP address and the local hostname. In doubt use the explicit constructor.<br/>
* This call is equivalent to <code>create(null, null)</code>.
* </p>
*
* @see #create(InetAddress, String)
* @return jmDNS instance
* @exception IOException
* if an exception occurs during the socket creation
*/
public static JmDNS create() throws IOException {
return new JmDNSImpl(null, null);
}
/**
* <p>
* Create an instance of JmDNS and bind it to a specific network interface given its IP-address.
* </p>
* <p>
* <b>Note:</b> This is a convenience method. The preferred constructor is {@link #create(InetAddress, String)}.<br/>
* Check that your platform correctly handle the default localhost IP address and the local hostname. In doubt use the explicit constructor.<br/>
* This call is equivalent to <code>create(addr, null)</code>.
* </p>
*
* @see #create(InetAddress, String)
* @param addr
* IP address to bind to.
* @return jmDNS instance
* @exception IOException
* if an exception occurs during the socket creation
*/
public static JmDNS create(final InetAddress addr) throws IOException {
return new JmDNSImpl(addr, null);
}
/**
* <p>
* Create an instance of JmDNS.
* </p>
* <p>
* <b>Note:</b> This is a convenience method. The preferred constructor is {@link #create(InetAddress, String)}.<br/>
* Check that your platform correctly handle the default localhost IP address and the local hostname. In doubt use the explicit constructor.<br/>
* This call is equivalent to <code>create(null, name)</code>.
* </p>
*
* @see #create(InetAddress, String)
* @param name
* name of the newly created JmDNS
* @return jmDNS instance
* @exception IOException
* if an exception occurs during the socket creation
*/
public static JmDNS create(final String name) throws IOException {
return new JmDNSImpl(null, name);
}
/**
* <p>
* Create an instance of JmDNS and bind it to a specific network interface given its IP-address.
* </p>
* If <code>addr</code> parameter is null this method will try to resolve to a local IP address of the machine using a network discovery:
* <ol>
* <li>Check the system property <code>net.mdns.interface</code></li>
* <li>Check the JVM local host</li>
* <li>Use the {@link NetworkTopologyDiscovery} to find a valid network interface and IP.</li>
* <li>In the last resort bind to the loopback address. This is non functional in most cases.</li>
* </ol>
* If <code>name</code> parameter is null will use the hostname. The hostname is determined by the following algorithm:
* <ol>
* <li>Get the hostname from the InetAdress obtained before.</li>
* <li>If the hostname is a reverse lookup default to <code>JmDNS name</code> or <code>computer</code> if null.</li>
* <li>If the name contains <code>'.'</code> replace them by <code>'-'</code></li>
* <li>Add <code>.local.</code> at the end of the name.</li>
* </ol>
* <p>
* <b>Note:</b> If you need to use a custom {@link NetworkTopologyDiscovery} it must be setup before any call to this method. This is done by setting up a {@link NetworkTopologyDiscovery.Factory.ClassDelegate} and installing it using
* {@link NetworkTopologyDiscovery.Factory#setClassDelegate(NetworkTopologyDiscovery.Factory.ClassDelegate)}. This must be done before creating a {@link JmDNS} or {@link JmmDNS} instance.
* </p>
*
* @param addr
* IP address to bind to.
* @param name
* name of the newly created JmDNS
* @return jmDNS instance
* @exception IOException
* if an exception occurs during the socket creation
*/
public static JmDNS create(final InetAddress addr, final String name) throws IOException {
return new JmDNSImpl(addr, name);
}
/**
* Return the name of the JmDNS instance. This is an arbitrary string that is useful for distinguishing instances.
*
* @return name of the JmDNS
*/
public abstract String getName();
/**
* Return the HostName associated with this JmDNS instance. Note: May not be the same as what started. The host name is subject to negotiation.
*
* @return Host name
*/
public abstract String getHostName();
/**
* Return the address of the interface to which this instance of JmDNS is bound.
*
* @return Internet Address
* @exception IOException
* if there is an error in the underlying protocol, such as a TCP error.
*/
public abstract InetAddress getInetAddress() throws IOException;
/**
* Return the address of the interface to which this instance of JmDNS is bound.
*
* @return Internet Address
* @exception IOException
* if there is an error in the underlying protocol, such as a TCP error.
* @deprecated do not use this implementation yields unpredictable results use {@link #getInetAddress()}
*/
@Deprecated
public abstract InetAddress getInterface() throws IOException;
/**
* Get service information. If the information is not cached, the method will block until updated information is received.
* <p/>
* Usage note: Do not call this method from the AWT event dispatcher thread. You will make the user interface unresponsive.
*
* @param type
* fully qualified service type, such as <code>_http._tcp.local.</code> .
* @param name
* unqualified service name, such as <code>foobar</code> .
* @return null if the service information cannot be obtained
*/
public abstract ServiceInfo getServiceInfo(String type, String name);
/**
* Get service information. If the information is not cached, the method will block for the given timeout until updated information is received.
* <p/>
* Usage note: If you call this method from the AWT event dispatcher thread, use a small timeout, or you will make the user interface unresponsive.
*
* @param type
* full qualified service type, such as <code>_http._tcp.local.</code> .
* @param name
* unqualified service name, such as <code>foobar</code> .
* @param timeout
* timeout in milliseconds. Typical timeout should be 5s.
* @return null if the service information cannot be obtained
*/
public abstract ServiceInfo getServiceInfo(String type, String name, long timeout);
/**
* Get service information. If the information is not cached, the method will block until updated information is received.
* <p/>
* Usage note: Do not call this method from the AWT event dispatcher thread. You will make the user interface unresponsive.
*
* @param type
* fully qualified service type, such as <code>_http._tcp.local.</code> .
* @param name
* unqualified service name, such as <code>foobar</code> .
* @param persistent
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
* @return null if the service information cannot be obtained
*/
public abstract ServiceInfo getServiceInfo(String type, String name, boolean persistent);
/**
* Get service information. If the information is not cached, the method will block for the given timeout until updated information is received.
* <p/>
* Usage note: If you call this method from the AWT event dispatcher thread, use a small timeout, or you will make the user interface unresponsive.
*
* @param type
* full qualified service type, such as <code>_http._tcp.local.</code> .
* @param name
* unqualified service name, such as <code>foobar</code> .
* @param timeout
* timeout in milliseconds. Typical timeout should be 5s.
* @param persistent
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
* @return null if the service information cannot be obtained
*/
public abstract ServiceInfo getServiceInfo(String type, String name, boolean persistent, long timeout);
/**
* Request service information. The information about the service is requested and the ServiceListener.resolveService method is called as soon as it is available.
* <p/>
* Usage note: Do not call this method from the AWT event dispatcher thread. You will make the user interface unresponsive.
*
* @param type
* full qualified service type, such as <code>_http._tcp.local.</code> .
* @param name
* unqualified service name, such as <code>foobar</code> .
*/
public abstract void requestServiceInfo(String type, String name);
/**
* Request service information. The information about the service is requested and the ServiceListener.resolveService method is called as soon as it is available.
* <p/>
* Usage note: Do not call this method from the AWT event dispatcher thread. You will make the user interface unresponsive.
*
* @param type
* full qualified service type, such as <code>_http._tcp.local.</code> .
* @param name
* unqualified service name, such as <code>foobar</code> .
* @param persistent
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
*/
public abstract void requestServiceInfo(String type, String name, boolean persistent);
/**
* Request service information. The information about the service is requested and the ServiceListener.resolveService method is called as soon as it is available.
*
* @param type
* full qualified service type, such as <code>_http._tcp.local.</code> .
* @param name
* unqualified service name, such as <code>foobar</code> .
* @param timeout
* timeout in milliseconds
*/
public abstract void requestServiceInfo(String type, String name, long timeout);
/**
* Request service information. The information about the service is requested and the ServiceListener.resolveService method is called as soon as it is available.
*
* @param type
* full qualified service type, such as <code>_http._tcp.local.</code> .
* @param name
* unqualified service name, such as <code>foobar</code> .
* @param persistent
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
* @param timeout
* timeout in milliseconds
*/
public abstract void requestServiceInfo(String type, String name, boolean persistent, long timeout);
/**
* Listen for service types.
*
* @param listener
* listener for service types
* @exception IOException
* if there is an error in the underlying protocol, such as a TCP error.
*/
public abstract void addServiceTypeListener(ServiceTypeListener listener) throws IOException;
/**
* Remove listener for service types.
*
* @param listener
* listener for service types
*/
public abstract void removeServiceTypeListener(ServiceTypeListener listener);
/**
* Listen for services of a given type. The type has to be a fully qualified type name such as <code>_http._tcp.local.</code>.
*
* @param type
* full qualified service type, such as <code>_http._tcp.local.</code>.
* @param listener
* listener for service updates
*/
public abstract void addServiceListener(String type, ServiceListener listener);
/**
* Remove listener for services of a given type.
*
* @param type
* full qualified service type, such as <code>_http._tcp.local.</code>.
* @param listener
* listener for service updates
*/
public abstract void removeServiceListener(String type, ServiceListener listener);
/**
* Register a service. The service is registered for access by other jmdns clients. The name of the service may be changed to make it unique.<br>
* Note that the given {@code ServiceInfo} is bound to this {@code JmDNS} instance, and should not be reused for any other {@linkplain #registerService(ServiceInfo)}.
*
* @param info
* service info to register
* @exception IOException
* if there is an error in the underlying protocol, such as a TCP error.
*/
public abstract void registerService(ServiceInfo info) throws IOException;
/**
* Unregister a service. The service should have been registered.
* <p>
* <b>Note:</b> Unregistered services will not disappear form the list of services immediately. According to the specification, when unregistering services we send goodbye packets and then wait <b>1s</b> before purging the cache.<br/>
* This is support for shared records that can be rescued by some other cooperation DNS.
*
* <pre>
* Clients receiving a Multicast DNS Response with a TTL of zero SHOULD NOT immediately delete the record from the cache, but instead record a TTL of 1 and then delete the record one second later.
* </pre>
*
* </p>
*
* @param info
* service info to remove
*/
public abstract void unregisterService(ServiceInfo info);
/**
* Unregister all services.
*/
public abstract void unregisterAllServices();
/**
* Register a service type. If this service type was not already known, all service listeners will be notified of the new service type.
* <p>
* Service types are automatically registered as they are discovered.
* </p>
*
* @param type
* full qualified service type, such as <code>_http._tcp.local.</code>.
* @return <code>true</code> if the type or subtype was added, <code>false</code> if the type was already registered.
*/
public abstract boolean registerServiceType(String type);
/**
* List Services and serviceTypes. Debugging Only
*
* @deprecated since 3.2.2
*/
@Deprecated
public abstract void printServices();
/**
* Returns a list of service infos of the specified type.
*
* @param type
* Service type name, such as <code>_http._tcp.local.</code>.
* @return An array of service instance.
*/
public abstract ServiceInfo[] list(String type);
/**
* Returns a list of service infos of the specified type.
*
* @param type
* Service type name, such as <code>_http._tcp.local.</code>.
* @param timeout
* timeout in milliseconds. Typical timeout should be 6s.
* @return An array of service instance.
*/
public abstract ServiceInfo[] list(String type, long timeout);
/**
* Returns a list of service infos of the specified type sorted by subtype. Any service that do not register a subtype is listed in the empty subtype section.
*
* @param type
* Service type name, such as <code>_http._tcp.local.</code>.
* @return A dictionary of service info by subtypes.
*/
public abstract Map<String, ServiceInfo[]> listBySubtype(String type);
/**
* Returns a list of service infos of the specified type sorted by subtype. Any service that do not register a subtype is listed in the empty subtype section.
*
* @param type
* Service type name, such as <code>_http._tcp.local.</code>.
* @param timeout
* timeout in milliseconds. Typical timeout should be 6s.
* @return A dictionary of service info by subtypes.
*/
public abstract Map<String, ServiceInfo[]> listBySubtype(String type, long timeout);
/**
* Returns the instance delegate
*
* @return instance delegate
*/
public abstract Delegate getDelegate();
/**
* Sets the instance delegate
*
* @param value
* new instance delegate
* @return previous instance delegate
*/
public abstract Delegate setDelegate(Delegate value);
}

View File

@ -0,0 +1,426 @@
/**
*
*/
package javax.jmdns;
import java.io.Closeable;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import javax.jmdns.impl.JmmDNSImpl;
/**
* <p>
* Java Multihomed Multicast DNS
* </p>
* Uses an underlying {@link JmDNS} instance for each {@link InetAddress} found on this computer.<br/>
* This class will monitor network topology changes, and will create or destroy JmDNS instances as required. It is your responsibility to maintain services registration (hint: use a {@link NetworkTopologyListener}).<br/>
* Most of this class methods have no notion of transaction: if an Exception is raised in the middle of execution, you may be in an incoherent state.
* <p>
* <b>Note:</b> This API is experimental and may change in the future please let us know what work and what does not work in your application.
* </p>
*
* @author C&eacute;drik Lime, Pierre Frisch
*/
public interface JmmDNS extends Closeable {
/**
* JmmDNS.Factory enable the creation of new instance of JmmDNS.
*/
public static final class Factory {
private static volatile JmmDNS _instance;
/**
* This interface defines a delegate to the EOClassDescriptionRegister class to enable subclassing.
*/
public static interface ClassDelegate {
/**
* Allows the delegate the opportunity to construct and return a different JmmDNS.
*
* @return Should return a new JmmDNS.
* @see #classDelegate()
* @see #setClassDelegate(ClassDelegate anObject)
*/
public JmmDNS newJmmDNS();
}
private static final AtomicReference<ClassDelegate> _databaseClassDelegate = new AtomicReference<ClassDelegate>();
private Factory() {
super();
}
/**
* Assigns <code>delegate</code> as JmmDNS's class delegate. The class delegate is optional.
*
* @param delegate
* The object to set as JmmDNS's class delegate.
* @see #classDelegate()
* @see JmmDNS.Factory.ClassDelegate
*/
public static void setClassDelegate(ClassDelegate delegate) {
_databaseClassDelegate.set(delegate);
}
/**
* Returns JmmDNS's class delegate.
*
* @return JmmDNS's class delegate.
* @see #setClassDelegate(ClassDelegate anObject)
* @see JmmDNS.Factory.ClassDelegate
*/
public static ClassDelegate classDelegate() {
return _databaseClassDelegate.get();
}
/**
* Returns a new instance of JmmDNS using the class delegate if it exists.
*
* @return new instance of JmmDNS
*/
protected static JmmDNS newJmmDNS() {
JmmDNS dns = null;
ClassDelegate delegate = _databaseClassDelegate.get();
if (delegate != null) {
dns = delegate.newJmmDNS();
}
return (dns != null ? dns : new JmmDNSImpl());
}
/**
* Return the instance of the Multihomed Multicast DNS.
*
* @return the JmmDNS
*/
public static JmmDNS getInstance() {
if (_instance == null) {
synchronized (Factory.class) {
if (_instance == null) {
_instance = JmmDNS.Factory.newJmmDNS();
}
}
}
return _instance;
}
/**
* Closes the instance if still running and discard it.
*
* @throws IOException
*/
public static void close() throws IOException {
synchronized (Factory.class) {
_instance.close();
_instance = null;
}
}
}
/**
* Return the names of the JmDNS instances.
*
* @return list of name of the JmDNS
* @see javax.jmdns.JmDNS#getName()
*/
public abstract String[] getNames();
/**
* Return the list HostName associated with this JmmDNS instance.
*
* @return list of host names
* @see javax.jmdns.JmDNS#getHostName()
*/
public abstract String[] getHostNames();
/**
* Return the list of addresses of the interface to which this instance of JmmDNS is bound.
*
* @return list of Internet Address
* @exception IOException
* @see javax.jmdns.JmDNS#getInetAddress()
*/
public abstract InetAddress[] getInetAddresses() throws IOException;
/**
* Return the list of addresses of the interface to which this instance of JmmDNS is bound.
*
* @return list of Internet Address
* @exception IOException
* @see javax.jmdns.JmDNS#getInterface()
* @deprecated do not use this implementation yields unpredictable results use {@link #getInetAddresses()}
*/
@Deprecated
public abstract InetAddress[] getInterfaces() throws IOException;
/**
* Return a list of all the registered JmDNS instances
*
* @return list of JmDNS instances
*/
public abstract JmDNS[] getDNS();
/**
* Get service information. If the information is not cached, the method will block until updated information is received on all DNS.
* <p/>
* Usage note: Do not call this method from the AWT event dispatcher thread. You will make the user interface unresponsive.
*
* @param type
* fully qualified service type, such as <code>_http._tcp.local.</code> .
* @param name
* unqualified service name, such as <code>foobar</code> .
* @return list of service info. If no service info is found the list is empty.
* @see javax.jmdns.JmDNS#getServiceInfo(java.lang.String, java.lang.String)
*/
public abstract ServiceInfo[] getServiceInfos(String type, String name);
/**
* Get service information. If the information is not cached, the method will block until updated information is received on all DNS.
* <p/>
* Usage note: If you call this method from the AWT event dispatcher thread, use a small timeout, or you will make the user interface unresponsive.
*
* @param type
* full qualified service type, such as <code>_http._tcp.local.</code> .
* @param name
* unqualified service name, such as <code>foobar</code> .
* @param timeout
* timeout in milliseconds. Typical timeout should be 5s.
* @return list of service info. If no service info is found the list is empty.
* @see javax.jmdns.JmDNS#getServiceInfo(java.lang.String, java.lang.String, long)
*/
public abstract ServiceInfo[] getServiceInfos(String type, String name, long timeout);
/**
* Get service information. If the information is not cached, the method will block until updated information is received on all DNS.
* <p/>
* Usage note: If you call this method from the AWT event dispatcher thread, use a small timeout, or you will make the user interface unresponsive.
*
* @param type
* full qualified service type, such as <code>_http._tcp.local.</code> .
* @param name
* unqualified service name, such as <code>foobar</code> .
* @param persistent
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
* @return list of service info. If no service info is found the list is empty.
* @see javax.jmdns.JmDNS#getServiceInfo(java.lang.String, java.lang.String, boolean)
*/
public abstract ServiceInfo[] getServiceInfos(String type, String name, boolean persistent);
/**
* Get service information. If the information is not cached, the method will block until updated information is received on all DNS.
* <p/>
* Usage note: If you call this method from the AWT event dispatcher thread, use a small timeout, or you will make the user interface unresponsive.
*
* @param type
* full qualified service type, such as <code>_http._tcp.local.</code> .
* @param name
* unqualified service name, such as <code>foobar</code> .
* @param timeout
* timeout in milliseconds. Typical timeout should be 5s.
* @param persistent
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
* @return list of service info. If no service info is found the list is empty.
* @see javax.jmdns.JmDNS#getServiceInfo(java.lang.String, java.lang.String, boolean, long)
*/
public abstract ServiceInfo[] getServiceInfos(String type, String name, boolean persistent, long timeout);
/**
* Request service information. The information about the service is requested and the ServiceListener.resolveService method is called as soon as it is available.
*
* @param type
* full qualified service type, such as <code>_http._tcp.local.</code> .
* @param name
* unqualified service name, such as <code>foobar</code> .
* @see javax.jmdns.JmDNS#requestServiceInfo(java.lang.String, java.lang.String)
*/
public abstract void requestServiceInfo(String type, String name);
/**
* Request service information. The information about the service is requested and the ServiceListener.resolveService method is called as soon as it is available.
*
* @param type
* full qualified service type, such as <code>_http._tcp.local.</code> .
* @param name
* unqualified service name, such as <code>foobar</code> .
* @param persistent
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
* @see javax.jmdns.JmDNS#requestServiceInfo(java.lang.String, java.lang.String, boolean)
*/
public abstract void requestServiceInfo(String type, String name, boolean persistent);
/**
* Request service information. The information about the service is requested and the ServiceListener.resolveService method is called as soon as it is available.
*
* @param type
* full qualified service type, such as <code>_http._tcp.local.</code> .
* @param name
* unqualified service name, such as <code>foobar</code> .
* @param timeout
* timeout in milliseconds
* @see javax.jmdns.JmDNS#requestServiceInfo(java.lang.String, java.lang.String, long)
*/
public abstract void requestServiceInfo(String type, String name, long timeout);
/**
* Request service information. The information about the service is requested and the ServiceListener.resolveService method is called as soon as it is available.
*
* @param type
* full qualified service type, such as <code>_http._tcp.local.</code> .
* @param name
* unqualified service name, such as <code>foobar</code> .
* @param persistent
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
* @param timeout
* timeout in milliseconds
* @see javax.jmdns.JmDNS#requestServiceInfo(java.lang.String, java.lang.String, boolean, long)
*/
public abstract void requestServiceInfo(String type, String name, boolean persistent, long timeout);
/**
* Listen for service types.
*
* @param listener
* listener for service types
* @exception IOException
* @see javax.jmdns.JmDNS#addServiceTypeListener(javax.jmdns.ServiceTypeListener)
*/
public abstract void addServiceTypeListener(ServiceTypeListener listener) throws IOException;
/**
* Remove listener for service types.
*
* @param listener
* listener for service types
* @see javax.jmdns.JmDNS#removeServiceTypeListener(javax.jmdns.ServiceTypeListener)
*/
public abstract void removeServiceTypeListener(ServiceTypeListener listener);
/**
* Listen for services of a given type. The type has to be a fully qualified type name such as <code>_http._tcp.local.</code>.
*
* @param type
* full qualified service type, such as <code>_http._tcp.local.</code>.
* @param listener
* listener for service updates
* @see javax.jmdns.JmDNS#addServiceListener(java.lang.String, javax.jmdns.ServiceListener)
*/
public abstract void addServiceListener(String type, ServiceListener listener);
/**
* Remove listener for services of a given type.
*
* @param type
* full qualified service type, such as <code>_http._tcp.local.</code>.
* @param listener
* listener for service updates
* @see javax.jmdns.JmDNS#removeServiceListener(java.lang.String, javax.jmdns.ServiceListener)
*/
public abstract void removeServiceListener(String type, ServiceListener listener);
/**
* Register a service. The service is registered for access by other jmdns clients. The name of the service may be changed to make it unique.<br>
* <b>Note</b> the Service info is cloned for each network interface.
*
* @param info
* service info to register
* @exception IOException
* @see javax.jmdns.JmDNS#registerService(javax.jmdns.ServiceInfo)
*/
public abstract void registerService(ServiceInfo info) throws IOException;
/**
* Unregister a service. The service should have been registered.
*
* @param info
* service info to remove
* @see javax.jmdns.JmDNS#unregisterService(javax.jmdns.ServiceInfo)
*/
public abstract void unregisterService(ServiceInfo info);
/**
* Unregister all services.
*
* @see javax.jmdns.JmDNS#unregisterAllServices()
*/
public abstract void unregisterAllServices();
/**
* Register a service type. If this service type was not already known, all service listeners will be notified of the new service type. Service types are automatically registered as they are discovered.
*
* @param type
* full qualified service type, such as <code>_http._tcp.local.</code>.
* @see javax.jmdns.JmDNS#registerServiceType(java.lang.String)
*/
public abstract void registerServiceType(String type);
/**
* Returns a list of service infos of the specified type.
*
* @param type
* Service type name, such as <code>_http._tcp.local.</code>.
* @return An array of service instance.
* @see javax.jmdns.JmDNS#list(java.lang.String)
*/
public abstract ServiceInfo[] list(String type);
/**
* Returns a list of service infos of the specified type.
*
* @param type
* Service type name, such as <code>_http._tcp.local.</code>.
* @param timeout
* timeout in milliseconds. Typical timeout should be 6s.
* @return An array of service instance.
* @see javax.jmdns.JmDNS#list(java.lang.String, long)
*/
public abstract ServiceInfo[] list(String type, long timeout);
/**
* Returns a list of service infos of the specified type sorted by subtype. Any service that do not register a subtype is listed in the empty subtype section.
*
* @param type
* Service type name, such as <code>_http._tcp.local.</code>.
* @return A dictionary of service info by subtypes.
* @see javax.jmdns.JmDNS#listBySubtype(java.lang.String)
*/
public abstract Map<String, ServiceInfo[]> listBySubtype(String type);
/**
* Returns a list of service infos of the specified type sorted by subtype. Any service that do not register a subtype is listed in the empty subtype section.
*
* @param type
* Service type name, such as <code>_http._tcp.local.</code>.
* @param timeout
* timeout in milliseconds. Typical timeout should be 6s.
* @return A dictionary of service info by subtypes.
* @see javax.jmdns.JmDNS#listBySubtype(java.lang.String, long)
*/
public abstract Map<String, ServiceInfo[]> listBySubtype(String type, long timeout);
/**
* Listen to network changes.
*
* @param listener
* listener for network changes
*/
public abstract void addNetworkTopologyListener(NetworkTopologyListener listener);
/**
* Remove listener for network changes.
*
* @param listener
* listener for network changes
*/
public abstract void removeNetworkTopologyListener(NetworkTopologyListener listener);
/**
* Returns list of network change listeners
*
* @return list of network change listeners
*/
public abstract NetworkTopologyListener[] networkListeners();
}

View File

@ -0,0 +1,164 @@
package javax.jmdns;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.concurrent.atomic.AtomicReference;
import javax.jmdns.impl.NetworkTopologyDiscoveryImpl;
/**
* This class is used to resolve the list of Internet address to use when attaching JmDNS to the network.
* <p>
* To create you own filtering class for Internet Addresses you will need to implement the class and the factory delegate. These must be called before any other call to JmDNS.
*
* <pre>
* public static class MyNetworkTopologyDiscovery implements NetworkTopologyDiscovery {
*
* &#064;Override
* public InetAddress[] getInetAddresses() {
* // TODO Auto-generated method stub
* return null;
* }
*
* &#064;Override
* public boolean useInetAddress(NetworkInterface networkInterface, InetAddress interfaceAddress) {
* // TODO Auto-generated method stub
* return false;
* }
*
* }
*
* public static class MyClass implements NetworkTopologyDiscovery.Factory.ClassDelegate {
* public MyClass() {
* super();
* NetworkTopologyDiscovery.Factory.setClassDelegate(this);
*
* // Access JmDNS or JmmDNS
* }
*
* &#064;Override
* public NetworkTopologyDiscovery newNetworkTopologyDiscovery() {
* return new MyNetworkTopologyDiscovery();
* }
*
* }
* </pre>
*
* </p>
*
* @author Pierre Frisch
*/
public interface NetworkTopologyDiscovery {
/**
* NetworkTopologyDiscovery.Factory enable the creation of new instance of NetworkTopologyDiscovery.
*/
public static final class Factory {
private static volatile NetworkTopologyDiscovery _instance;
/**
* This interface defines a delegate to the NetworkTopologyDiscovery.Factory class to enable subclassing.
*/
public static interface ClassDelegate {
/**
* Allows the delegate the opportunity to construct and return a different NetworkTopologyDiscovery.
*
* @return Should return a new NetworkTopologyDiscovery Object.
* @see #classDelegate()
* @see #setClassDelegate(ClassDelegate anObject)
*/
public NetworkTopologyDiscovery newNetworkTopologyDiscovery();
}
private static final AtomicReference<Factory.ClassDelegate> _databaseClassDelegate = new AtomicReference<Factory.ClassDelegate>();
private Factory() {
super();
}
/**
* Assigns <code>delegate</code> as NetworkTopologyDiscovery's class delegate. The class delegate is optional.
*
* @param delegate
* The object to set as NetworkTopologyDiscovery's class delegate.
* @see #classDelegate()
* @see JmmDNS.Factory.ClassDelegate
*/
public static void setClassDelegate(Factory.ClassDelegate delegate) {
_databaseClassDelegate.set(delegate);
}
/**
* Returns NetworkTopologyDiscovery's class delegate.
*
* @return NetworkTopologyDiscovery's class delegate.
* @see #setClassDelegate(ClassDelegate anObject)
* @see JmmDNS.Factory.ClassDelegate
*/
public static Factory.ClassDelegate classDelegate() {
return _databaseClassDelegate.get();
}
/**
* Returns a new instance of NetworkTopologyDiscovery using the class delegate if it exists.
*
* @return new instance of NetworkTopologyDiscovery
*/
protected static NetworkTopologyDiscovery newNetworkTopologyDiscovery() {
NetworkTopologyDiscovery instance = null;
Factory.ClassDelegate delegate = _databaseClassDelegate.get();
if (delegate != null) {
instance = delegate.newNetworkTopologyDiscovery();
}
return (instance != null ? instance : new NetworkTopologyDiscoveryImpl());
}
/**
* Return the instance of the Multihomed Multicast DNS.
*
* @return the JmmDNS
*/
public static NetworkTopologyDiscovery getInstance() {
if (_instance == null) {
synchronized (NetworkTopologyDiscovery.Factory.class) {
if (_instance == null) {
_instance = NetworkTopologyDiscovery.Factory.newNetworkTopologyDiscovery();
}
}
}
return _instance;
}
}
/**
* Get all local Internet Addresses for the machine.
*
* @return Set of InetAddress
*/
public abstract InetAddress[] getInetAddresses();
/**
* Check if a given InetAddress should be used for mDNS
*
* @param networkInterface
* @param interfaceAddress
* @return <code>true</code> is the address is to be used, <code>false</code> otherwise.
*/
public boolean useInetAddress(NetworkInterface networkInterface, InetAddress interfaceAddress);
/**
* Locks the given InetAddress if the device requires it.
*
* @param interfaceAddress
*/
public void lockInetAddress(InetAddress interfaceAddress);
/**
* Locks the given InetAddress if the device requires it.
*
* @param interfaceAddress
*/
public void unlockInetAddress(InetAddress interfaceAddress);
}

View File

@ -0,0 +1,45 @@
/**
*
*/
package javax.jmdns;
import java.net.InetAddress;
import java.util.EventObject;
/**
* @author C&eacute;drik Lime, Pierre Frisch
*/
public abstract class NetworkTopologyEvent extends EventObject {
/**
*
*/
private static final long serialVersionUID = -8630033521752540987L;
/**
* Constructs a Service Event.
*
* @param eventSource
* The DNS on which the Event initially occurred.
* @exception IllegalArgumentException
* if source is null.
*/
protected NetworkTopologyEvent(final Object eventSource) {
super(eventSource);
}
/**
* Returns the JmDNS instance associated with the event or null if it is a generic event.
*
* @return JmDNS instance
*/
public abstract JmDNS getDNS();
/**
* The Internet address affected by this event.
*
* @return InetAddress
*/
public abstract InetAddress getInetAddress();
}

View File

@ -0,0 +1,30 @@
/**
*
*/
package javax.jmdns;
import java.util.EventListener;
/**
* Listener for network topology updates.
*
* @author C&eacute;drik Lime, Pierre Frisch
*/
public interface NetworkTopologyListener extends EventListener {
/**
* A network address has been added.<br/>
*
* @param event
* The NetworkTopologyEvent providing the name and fully qualified type of the service.
*/
void inetAddressAdded(NetworkTopologyEvent event);
/**
* A network address has been removed.
*
* @param event
* The NetworkTopologyEvent providing the name and fully qualified type of the service.
*/
void inetAddressRemoved(NetworkTopologyEvent event);
}

View File

@ -0,0 +1,74 @@
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns;
import java.util.EventObject;
/**
*
*/
public abstract class ServiceEvent extends EventObject implements Cloneable {
/**
*
*/
private static final long serialVersionUID = -8558445644541006271L;
/**
* Constructs a Service Event.
*
* @param eventSource
* The object on which the Event initially occurred.
* @exception IllegalArgumentException
* if source is null.
*/
public ServiceEvent(final Object eventSource) {
super(eventSource);
}
/**
* Returns the JmDNS instance which originated the event.
*
* @return JmDNS instance
*/
public abstract JmDNS getDNS();
/**
* Returns the fully qualified type of the service.
*
* @return type of the service.
*/
public abstract String getType();
/**
* Returns the instance name of the service. Always returns null, if the event is sent to a service type listener.
*
* @return name of the service
*/
public abstract String getName();
/**
* Returns the service info record, or null if the service could not be resolved. Always returns null, if the event is sent to a service type listener.
*
* @return service info record
* @see javax.jmdns.ServiceEvent#getInfo()
*/
public abstract ServiceInfo getInfo();
/*
* (non-Javadoc)
* @see java.lang.Object#clone()
*/
@Override
public ServiceEvent clone() {
try {
return (ServiceEvent) super.clone();
} catch (CloneNotSupportedException exception) {
// clone is supported
return null;
}
}
}

View File

@ -0,0 +1,727 @@
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.util.Enumeration;
import java.util.Map;
import javax.jmdns.impl.ServiceInfoImpl;
/**
* <p>
* The fully qualified service name is build using up to 5 components with the following structure:
*
* <pre>
* &lt;app&gt;.&lt;protocol&gt;.&lt;servicedomain&gt;.&lt;parentdomain&gt;.<br/>
* &lt;Instance&gt;.&lt;app&gt;.&lt;protocol&gt;.&lt;servicedomain&gt;.&lt;parentdomain&gt;.<br/>
* &lt;sub&gt;._sub.&lt;app&gt;.&lt;protocol&gt;.&lt;servicedomain&gt;.&lt;parentdomain&gt;.
* </pre>
*
* <ol>
* <li>&lt;servicedomain&gt;.&lt;parentdomain&gt;: This is the domain scope of the service typically "local.", but this can also be something similar to "in-addr.arpa." or "ip6.arpa."</li>
* <li>&lt;protocol&gt;: This is either "_tcp" or "_udp"</li>
* <li>&lt;app&gt;: This define the application protocol. Typical example are "_http", "_ftp", etc.</li>
* <li>&lt;Instance&gt;: This is the service name</li>
* <li>&lt;sub&gt;: This is the subtype for the application protocol</li>
* </ol>
* </p>
*/
public abstract class ServiceInfo implements Cloneable {
/**
* This is the no value text byte. According top the specification it is one byte with 0 value.
*/
public static final byte[] NO_VALUE = new byte[0];
/**
* Fields for the fully qualified map.
*/
public enum Fields {
/**
* Domain Field.
*/
Domain,
/**
* Protocol Field.
*/
Protocol,
/**
* Application Field.
*/
Application,
/**
* Instance Field.
*/
Instance,
/**
* Subtype Field.
*/
Subtype
}
/**
* Construct a service description for registering with JmDNS.
*
* @param type
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
* @param name
* unqualified service instance name, such as <code>foobar</code>
* @param port
* the local port on which the service runs
* @param text
* string describing the service
* @return new service info
*/
public static ServiceInfo create(final String type, final String name, final int port, final String text) {
return new ServiceInfoImpl(type, name, "", port, 0, 0, false, text);
}
/**
* Construct a service description for registering with JmDNS.
*
* @param type
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
* @param name
* unqualified service instance name, such as <code>foobar</code>
* @param subtype
* service subtype see draft-cheshire-dnsext-dns-sd-06.txt chapter 7.1 Selective Instance Enumeration
* @param port
* the local port on which the service runs
* @param text
* string describing the service
* @return new service info
*/
public static ServiceInfo create(final String type, final String name, final String subtype, final int port, final String text) {
return new ServiceInfoImpl(type, name, subtype, port, 0, 0, false, text);
}
/**
* Construct a service description for registering with JmDNS.
*
* @param type
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
* @param name
* unqualified service instance name, such as <code>foobar</code>
* @param port
* the local port on which the service runs
* @param weight
* weight of the service
* @param priority
* priority of the service
* @param text
* string describing the service
* @return new service info
*/
public static ServiceInfo create(final String type, final String name, final int port, final int weight, final int priority, final String text) {
return new ServiceInfoImpl(type, name, "", port, weight, priority, false, text);
}
/**
* Construct a service description for registering with JmDNS.
*
* @param type
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
* @param name
* unqualified service instance name, such as <code>foobar</code>
* @param subtype
* service subtype see draft-cheshire-dnsext-dns-sd-06.txt chapter 7.1 Selective Instance Enumeration
* @param port
* the local port on which the service runs
* @param weight
* weight of the service
* @param priority
* priority of the service
* @param text
* string describing the service
* @return new service info
*/
public static ServiceInfo create(final String type, final String name, final String subtype, final int port, final int weight, final int priority, final String text) {
return new ServiceInfoImpl(type, name, subtype, port, weight, priority, false, text);
}
/**
* Construct a service description for registering with JmDNS. The properties hashtable must map property names to either Strings or byte arrays describing the property values.
*
* @param type
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
* @param name
* unqualified service instance name, such as <code>foobar</code>
* @param port
* the local port on which the service runs
* @param weight
* weight of the service
* @param priority
* priority of the service
* @param props
* properties describing the service
* @return new service info
*/
public static ServiceInfo create(final String type, final String name, final int port, final int weight, final int priority, final Map<String, ?> props) {
return new ServiceInfoImpl(type, name, "", port, weight, priority, false, props);
}
/**
* Construct a service description for registering with JmDNS. The properties hashtable must map property names to either Strings or byte arrays describing the property values.
*
* @param type
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
* @param name
* unqualified service instance name, such as <code>foobar</code>
* @param subtype
* service subtype see draft-cheshire-dnsext-dns-sd-06.txt chapter 7.1 Selective Instance Enumeration
* @param port
* the local port on which the service runs
* @param weight
* weight of the service
* @param priority
* priority of the service
* @param props
* properties describing the service
* @return new service info
*/
public static ServiceInfo create(final String type, final String name, final String subtype, final int port, final int weight, final int priority, final Map<String, ?> props) {
return new ServiceInfoImpl(type, name, subtype, port, weight, priority, false, props);
}
/**
* Construct a service description for registering with JmDNS.
*
* @param type
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
* @param name
* unqualified service instance name, such as <code>foobar</code>
* @param port
* the local port on which the service runs
* @param weight
* weight of the service
* @param priority
* priority of the service
* @param text
* bytes describing the service
* @return new service info
*/
public static ServiceInfo create(final String type, final String name, final int port, final int weight, final int priority, final byte[] text) {
return new ServiceInfoImpl(type, name, "", port, weight, priority, false, text);
}
/**
* Construct a service description for registering with JmDNS.
*
* @param type
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
* @param name
* unqualified service instance name, such as <code>foobar</code>
* @param subtype
* service subtype see draft-cheshire-dnsext-dns-sd-06.txt chapter 7.1 Selective Instance Enumeration
* @param port
* the local port on which the service runs
* @param weight
* weight of the service
* @param priority
* priority of the service
* @param text
* bytes describing the service
* @return new service info
*/
public static ServiceInfo create(final String type, final String name, final String subtype, final int port, final int weight, final int priority, final byte[] text) {
return new ServiceInfoImpl(type, name, subtype, port, weight, priority, false, text);
}
/**
* Construct a service description for registering with JmDNS.
*
* @param type
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
* @param name
* unqualified service instance name, such as <code>foobar</code>
* @param port
* the local port on which the service runs
* @param weight
* weight of the service
* @param priority
* priority of the service
* @param persistent
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
* @param text
* string describing the service
* @return new service info
*/
public static ServiceInfo create(final String type, final String name, final int port, final int weight, final int priority, final boolean persistent, final String text) {
return new ServiceInfoImpl(type, name, "", port, weight, priority, persistent, text);
}
/**
* Construct a service description for registering with JmDNS.
*
* @param type
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
* @param name
* unqualified service instance name, such as <code>foobar</code>
* @param subtype
* service subtype see draft-cheshire-dnsext-dns-sd-06.txt chapter 7.1 Selective Instance Enumeration
* @param port
* the local port on which the service runs
* @param weight
* weight of the service
* @param priority
* priority of the service
* @param persistent
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
* @param text
* string describing the service
* @return new service info
*/
public static ServiceInfo create(final String type, final String name, final String subtype, final int port, final int weight, final int priority, final boolean persistent, final String text) {
return new ServiceInfoImpl(type, name, subtype, port, weight, priority, persistent, text);
}
/**
* Construct a service description for registering with JmDNS. The properties hashtable must map property names to either Strings or byte arrays describing the property values.
*
* @param type
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
* @param name
* unqualified service instance name, such as <code>foobar</code>
* @param port
* the local port on which the service runs
* @param weight
* weight of the service
* @param priority
* priority of the service
* @param persistent
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
* @param props
* properties describing the service
* @return new service info
*/
public static ServiceInfo create(final String type, final String name, final int port, final int weight, final int priority, final boolean persistent, final Map<String, ?> props) {
return new ServiceInfoImpl(type, name, "", port, weight, priority, persistent, props);
}
/**
* Construct a service description for registering with JmDNS. The properties hashtable must map property names to either Strings or byte arrays describing the property values.
*
* @param type
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
* @param name
* unqualified service instance name, such as <code>foobar</code>
* @param subtype
* service subtype see draft-cheshire-dnsext-dns-sd-06.txt chapter 7.1 Selective Instance Enumeration
* @param port
* the local port on which the service runs
* @param weight
* weight of the service
* @param priority
* priority of the service
* @param persistent
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
* @param props
* properties describing the service
* @return new service info
*/
public static ServiceInfo create(final String type, final String name, final String subtype, final int port, final int weight, final int priority, final boolean persistent, final Map<String, ?> props) {
return new ServiceInfoImpl(type, name, subtype, port, weight, priority, persistent, props);
}
/**
* Construct a service description for registering with JmDNS.
*
* @param type
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
* @param name
* unqualified service instance name, such as <code>foobar</code>
* @param port
* the local port on which the service runs
* @param weight
* weight of the service
* @param priority
* priority of the service
* @param persistent
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
* @param text
* bytes describing the service
* @return new service info
*/
public static ServiceInfo create(final String type, final String name, final int port, final int weight, final int priority, final boolean persistent, final byte[] text) {
return new ServiceInfoImpl(type, name, "", port, weight, priority, persistent, text);
}
/**
* Construct a service description for registering with JmDNS.
*
* @param type
* fully qualified service type name, such as <code>_http._tcp.local.</code>.
* @param name
* unqualified service instance name, such as <code>foobar</code>
* @param subtype
* service subtype see draft-cheshire-dnsext-dns-sd-06.txt chapter 7.1 Selective Instance Enumeration
* @param port
* the local port on which the service runs
* @param weight
* weight of the service
* @param priority
* priority of the service
* @param persistent
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
* @param text
* bytes describing the service
* @return new service info
*/
public static ServiceInfo create(final String type, final String name, final String subtype, final int port, final int weight, final int priority, final boolean persistent, final byte[] text) {
return new ServiceInfoImpl(type, name, subtype, port, weight, priority, persistent, text);
}
/**
* Construct a service description for registering with JmDNS. The properties hashtable must map property names to either Strings or byte arrays describing the property values.
*
* @param qualifiedNameMap
* dictionary of values to build the fully qualified service name. Mandatory keys are Application and Instance. The Domain default is local, the Protocol default is tcp and the subtype default is none.
* @param port
* the local port on which the service runs
* @param weight
* weight of the service
* @param priority
* priority of the service
* @param persistent
* if <code>true</code> ServiceListener.resolveService will be called whenever new new information is received.
* @param props
* properties describing the service
* @return new service info
*/
public static ServiceInfo create(final Map<Fields, String> qualifiedNameMap, final int port, final int weight, final int priority, final boolean persistent, final Map<String, ?> props) {
return new ServiceInfoImpl(qualifiedNameMap, port, weight, priority, persistent, props);
}
/**
* Returns true if the service info is filled with data.
*
* @return <code>true</code> if the service info has data, <code>false</code> otherwise.
*/
public abstract boolean hasData();
/**
* Fully qualified service type name, such as <code>_http._tcp.local.</code>
*
* @return service type name
*/
public abstract String getType();
/**
* Fully qualified service type name with the subtype if appropriate, such as <code>_printer._sub._http._tcp.local.</code>
*
* @return service type name
*/
public abstract String getTypeWithSubtype();
/**
* Unqualified service instance name, such as <code>foobar</code> .
*
* @return service name
*/
public abstract String getName();
/**
* The key is used to retrieve service info in hash tables.<br/>
* The key is the lower case qualified name.
*
* @return the key
*/
public abstract String getKey();
/**
* Fully qualified service name, such as <code>foobar._http._tcp.local.</code> .
*
* @return qualified service name
*/
public abstract String getQualifiedName();
/**
* Get the name of the server.
*
* @return server name
*/
public abstract String getServer();
/**
* Returns the host IP address string in textual presentation.<br/>
* <b>Note:</b> This can be either an IPv4 or an IPv6 representation.
*
* @return the host raw IP address in a string format.
* @deprecated since 3.2.3
* @see #getHostAddresses()
*/
@Deprecated
public abstract String getHostAddress();
/**
* Returns the host IP addresses string in textual presentation.
*
* @return list of host raw IP address in a string format.
*/
public abstract String[] getHostAddresses();
/**
* Get the host address of the service.<br/>
*
* @return host Internet address
* @deprecated since 3.1.8
* @see #getInetAddresses()
*/
@Deprecated
public abstract InetAddress getAddress();
/**
* Get the InetAddress of the service. This will return the IPv4 if it exist, otherwise it return the IPv6 if set.<br/>
* <b>Note:</b> This return null if the service IP address cannot be resolved.
*
* @return Internet address
* @deprecated since 3.2.3
* @see #getInetAddresses()
*/
@Deprecated
public abstract InetAddress getInetAddress();
/**
* Get the IPv4 InetAddress of the service.<br/>
* <b>Note:</b> This return null if the service IPv4 address cannot be resolved.
*
* @return Internet address
* @deprecated since 3.2.3
* @see #getInet4Addresses()
*/
@Deprecated
public abstract Inet4Address getInet4Address();
/**
* Get the IPv6 InetAddress of the service.<br/>
* <b>Note:</b> This return null if the service IPv6 address cannot be resolved.
*
* @return Internet address
* @deprecated since 3.2.3
* @see #getInet6Addresses()
*/
@Deprecated
public abstract Inet6Address getInet6Address();
/**
* Returns a list of all InetAddresses that can be used for this service.
* <p>
* In a multi-homed environment service info can be associated with more than one address.
* </p>
*
* @return list of InetAddress objects
*/
public abstract InetAddress[] getInetAddresses();
/**
* Returns a list of all IPv4 InetAddresses that can be used for this service.
* <p>
* In a multi-homed environment service info can be associated with more than one address.
* </p>
*
* @return list of InetAddress objects
*/
public abstract Inet4Address[] getInet4Addresses();
/**
* Returns a list of all IPv6 InetAddresses that can be used for this service.
* <p>
* In a multi-homed environment service info can be associated with more than one address.
* </p>
*
* @return list of InetAddress objects
*/
public abstract Inet6Address[] getInet6Addresses();
/**
* Get the port for the service.
*
* @return service port
*/
public abstract int getPort();
/**
* Get the priority of the service.
*
* @return service priority
*/
public abstract int getPriority();
/**
* Get the weight of the service.
*
* @return service weight
*/
public abstract int getWeight();
/**
* Get the text for the service as raw bytes.
*
* @return raw service text
*/
public abstract byte[] getTextBytes();
/**
* Get the text for the service. This will interpret the text bytes as a UTF8 encoded string. Will return null if the bytes are not a valid UTF8 encoded string.<br/>
* <b>Note:</b> Do not use. This method make the assumption that the TXT record is one string. This is false. The TXT record is a series of key value pairs.
*
* @return service text
* @see #getPropertyNames()
* @see #getPropertyBytes(String)
* @see #getPropertyString(String)
* @deprecated since 3.1.7
*/
@Deprecated
public abstract String getTextString();
/**
* Get the URL for this service. An http URL is created by combining the address, port, and path properties.
*
* @return service URL
* @deprecated since 3.2.3
* @see #getURLs()
*/
@Deprecated
public abstract String getURL();
/**
* Get the list of URL for this service. An http URL is created by combining the address, port, and path properties.
*
* @return list of service URL
*/
public abstract String[] getURLs();
/**
* Get the URL for this service. An URL is created by combining the protocol, address, port, and path properties.
*
* @param protocol
* requested protocol
* @return service URL
* @deprecated since 3.2.3
* @see #getURLs()
*/
@Deprecated
public abstract String getURL(String protocol);
/**
* Get the list of URL for this service. An URL is created by combining the protocol, address, port, and path properties.
*
* @param protocol
* requested protocol
* @return list of service URL
*/
public abstract String[] getURLs(String protocol);
/**
* Get a property of the service. This involves decoding the text bytes into a property list. Returns null if the property is not found or the text data could not be decoded correctly.
*
* @param name
* property name
* @return raw property text
*/
public abstract byte[] getPropertyBytes(final String name);
/**
* Get a property of the service. This involves decoding the text bytes into a property list. Returns null if the property is not found, the text data could not be decoded correctly, or the resulting bytes are not a valid UTF8 string.
*
* @param name
* property name
* @return property text
*/
public abstract String getPropertyString(final String name);
/**
* Enumeration of the property names.
*
* @return property name enumeration
*/
public abstract Enumeration<String> getPropertyNames();
/**
* Returns a description of the service info suitable for printing.
*
* @return service info description
*/
public abstract String getNiceTextString();
/**
* Set the text for the service. Setting the text will fore a re-announce of the service.
*
* @param text
* the raw byte representation of the text field.
* @exception IllegalStateException
* if attempting to set the text for a non persistent service info.
*/
public abstract void setText(final byte[] text) throws IllegalStateException;
/**
* Set the text for the service. Setting the text will fore a re-announce of the service.
*
* @param props
* a key=value map that will be encoded into raw bytes.
* @exception IllegalStateException
* if attempting to set the text for a non persistent service info.
*/
public abstract void setText(final Map<String, ?> props) throws IllegalStateException;
/**
* Returns <code>true</code> if ServiceListener.resolveService will be called whenever new new information is received.
*
* @return the persistent
*/
public abstract boolean isPersistent();
/**
* Returns the domain of the service info suitable for printing.
*
* @return service domain
*/
public abstract String getDomain();
/**
* Returns the protocol of the service info suitable for printing.
*
* @return service protocol
*/
public abstract String getProtocol();
/**
* Returns the application of the service info suitable for printing.
*
* @return service application
*/
public abstract String getApplication();
/**
* Returns the sub type of the service info suitable for printing.
*
* @return service sub type
*/
public abstract String getSubtype();
/**
* Returns a dictionary of the fully qualified name component of this service.
*
* @return dictionary of the fully qualified name components
*/
public abstract Map<Fields, String> getQualifiedNameMap();
/*
* (non-Javadoc)
* @see java.lang.Object#clone()
*/
@Override
public ServiceInfo clone() {
try {
return (ServiceInfo) super.clone();
} catch (CloneNotSupportedException exception) {
// clone is supported
return null;
}
}
}

View File

@ -0,0 +1,49 @@
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns;
import java.util.EventListener;
/**
* Listener for service updates.
*
* @author Arthur van Hoff, Werner Randelshofer, Pierre Frisch
*/
public interface ServiceListener extends EventListener {
/**
* A service has been added.<br/>
* <b>Note:</b>This event is only the service added event. The service info associated with this event does not include resolution information.<br/>
* To get the full resolved information you need to listen to {@link #serviceResolved(ServiceEvent)} or call {@link JmDNS#getServiceInfo(String, String, long)}
*
* <pre>
* ServiceInfo info = event.getDNS().getServiceInfo(event.getType(), event.getName())
* </pre>
* <p>
* Please note that service resolution may take a few second to resolve.
* </p>
*
* @param event
* The ServiceEvent providing the name and fully qualified type of the service.
*/
void serviceAdded(ServiceEvent event);
/**
* A service has been removed.
*
* @param event
* The ServiceEvent providing the name and fully qualified type of the service.
*/
void serviceRemoved(ServiceEvent event);
/**
* A service has been resolved. Its details are now available in the ServiceInfo record.<br/>
* <b>Note:</b>This call back will never be called if the service does not resolve.<br/>
*
* @param event
* The ServiceEvent providing the name, the fully qualified type of the service, and the service info record.
*/
void serviceResolved(ServiceEvent event);
}

View File

@ -0,0 +1,35 @@
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns;
import java.util.EventListener;
/**
* Listener for service types.
*
* @author Arthur van Hoff, Werner Randelshofer
*/
public interface ServiceTypeListener extends EventListener {
/**
* A new service type was discovered.
*
* @param event
* The service event providing the fully qualified type of the service.
*/
void serviceTypeAdded(ServiceEvent event);
/**
* A new subtype for the service type was discovered.
*
* <pre>
* &lt;sub&gt;._sub.&lt;app&gt;.&lt;protocol&gt;.&lt;servicedomain&gt;.&lt;parentdomain&gt;.
* </pre>
*
* @param event
* The service event providing the fully qualified type of the service with subtype.
* @since 3.2.0
*/
void subTypeForServiceTypeAdded(ServiceEvent event);
}

View File

@ -0,0 +1,386 @@
// Copyright 2003-2005 Arthur van Hoff Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.jmdns.impl.constants.DNSRecordClass;
import javax.jmdns.impl.constants.DNSRecordType;
/**
* A table of DNS entries. This is a map table which can handle multiple entries with the same name.
* <p/>
* Storing multiple entries with the same name is implemented using a linked list. This is hidden from the user and can change in later implementation.
* <p/>
* Here's how to iterate over all entries:
*
* <pre>
* for (Iterator i=dnscache.allValues().iterator(); i.hasNext(); ) {
* DNSEntry entry = i.next();
* ...do something with entry...
* }
* </pre>
* <p/>
* And here's how to iterate over all entries having a given name:
*
* <pre>
* for (Iterator i=dnscache.getDNSEntryList(name).iterator(); i.hasNext(); ) {
* DNSEntry entry = i.next();
* ...do something with entry...
* }
* </pre>
*
* @author Arthur van Hoff, Werner Randelshofer, Rick Blair, Pierre Frisch
*/
public class DNSCache extends ConcurrentHashMap<String, List<DNSEntry>> {
// private static Logger logger = Logger.getLogger(DNSCache.class.getName());
private static final long serialVersionUID = 3024739453186759259L;
/**
*
*/
public static final DNSCache EmptyCache = new _EmptyCache();
static final class _EmptyCache extends DNSCache {
private static final long serialVersionUID = 8487377323074567224L;
/**
* {@inheritDoc}
*/
@Override
public int size() {
return 0;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isEmpty() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean containsKey(Object key) {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public boolean containsValue(Object value) {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public List<DNSEntry> get(Object key) {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public Set<String> keySet() {
return Collections.emptySet();
}
/**
* {@inheritDoc}
*/
@Override
public Collection<List<DNSEntry>> values() {
return Collections.emptySet();
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object o) {
return (o instanceof Map) && ((Map<?, ?>) o).size() == 0;
}
/**
* {@inheritDoc}
*/
@Override
public List<DNSEntry> put(String key, List<DNSEntry> value) {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return 0;
}
}
/**
*
*/
public DNSCache() {
this(1024);
}
/**
* @param map
*/
public DNSCache(DNSCache map) {
this(map != null ? map.size() : 1024);
if (map != null) {
this.putAll(map);
}
}
/**
* Create a table with a given initial size.
*
* @param initialCapacity
*/
public DNSCache(int initialCapacity) {
super(initialCapacity);
}
// ====================================================================
// Map
/**
* {@inheritDoc}
*/
@Override
protected Object clone() throws CloneNotSupportedException {
return new DNSCache(this);
}
// ====================================================================
/**
* Returns all entries in the cache
*
* @return all entries in the cache
*/
public Collection<DNSEntry> allValues() {
List<DNSEntry> allValues = new ArrayList<DNSEntry>();
for (List<? extends DNSEntry> entry : this.values()) {
if (entry != null) {
allValues.addAll(entry);
}
}
return allValues;
}
/**
* Iterate only over items with matching name. Returns an list of DNSEntry or null. To retrieve all entries, one must iterate over this linked list.
*
* @param name
* @return list of DNSEntries
*/
public Collection<? extends DNSEntry> getDNSEntryList(String name) {
Collection<? extends DNSEntry> entryList = this._getDNSEntryList(name);
if (entryList != null) {
synchronized (entryList) {
entryList = new ArrayList<DNSEntry>(entryList);
}
} else {
entryList = Collections.emptyList();
}
return entryList;
}
private Collection<? extends DNSEntry> _getDNSEntryList(String name) {
return this.get(name != null ? name.toLowerCase() : null);
}
/**
* Get a matching DNS entry from the table (using isSameEntry). Returns the entry that was found.
*
* @param dnsEntry
* @return DNSEntry
*/
public DNSEntry getDNSEntry(DNSEntry dnsEntry) {
DNSEntry result = null;
if (dnsEntry != null) {
Collection<? extends DNSEntry> entryList = this._getDNSEntryList(dnsEntry.getKey());
if (entryList != null) {
synchronized (entryList) {
for (DNSEntry testDNSEntry : entryList) {
if (testDNSEntry.isSameEntry(dnsEntry)) {
result = testDNSEntry;
break;
}
}
}
}
}
return result;
}
/**
* Get a matching DNS entry from the table.
*
* @param name
* @param type
* @param recordClass
* @return DNSEntry
*/
public DNSEntry getDNSEntry(String name, DNSRecordType type, DNSRecordClass recordClass) {
DNSEntry result = null;
Collection<? extends DNSEntry> entryList = this._getDNSEntryList(name);
if (entryList != null) {
synchronized (entryList) {
for (DNSEntry testDNSEntry : entryList) {
if (testDNSEntry.matchRecordType(type) && testDNSEntry.matchRecordClass(recordClass)) {
result = testDNSEntry;
break;
}
}
}
}
return result;
}
/**
* Get all matching DNS entries from the table.
*
* @param name
* @param type
* @param recordClass
* @return list of entries
*/
public Collection<? extends DNSEntry> getDNSEntryList(String name, DNSRecordType type, DNSRecordClass recordClass) {
Collection<? extends DNSEntry> entryList = this._getDNSEntryList(name);
if (entryList != null) {
synchronized (entryList) {
entryList = new ArrayList<DNSEntry>(entryList);
for (Iterator<? extends DNSEntry> i = entryList.iterator(); i.hasNext();) {
DNSEntry testDNSEntry = i.next();
if (!testDNSEntry.matchRecordType(type) || (!testDNSEntry.matchRecordClass(recordClass))) {
i.remove();
}
}
}
} else {
entryList = Collections.emptyList();
}
return entryList;
}
/**
* Adds an entry to the table.
*
* @param dnsEntry
* @return true if the entry was added
*/
public boolean addDNSEntry(final DNSEntry dnsEntry) {
boolean result = false;
if (dnsEntry != null) {
List<DNSEntry> entryList = this.get(dnsEntry.getKey());
if (entryList == null) {
this.putIfAbsent(dnsEntry.getKey(), new ArrayList<DNSEntry>());
entryList = this.get(dnsEntry.getKey());
}
synchronized (entryList) {
entryList.add(dnsEntry);
}
// This is probably not very informative
result = true;
}
return result;
}
/**
* Removes a specific entry from the table. Returns true if the entry was found.
*
* @param dnsEntry
* @return true if the entry was removed
*/
public boolean removeDNSEntry(DNSEntry dnsEntry) {
boolean result = false;
if (dnsEntry != null) {
List<DNSEntry> entryList = this.get(dnsEntry.getKey());
if (entryList != null) {
synchronized (entryList) {
entryList.remove(dnsEntry);
}
}
}
return result;
}
/**
* Replace an existing entry by a new one.<br/>
* <b>Note:</b> the 2 entries must have the same key.
*
* @param newDNSEntry
* @param existingDNSEntry
* @return <code>true</code> if the entry has been replace, <code>false</code> otherwise.
*/
public boolean replaceDNSEntry(DNSEntry newDNSEntry, DNSEntry existingDNSEntry) {
boolean result = false;
if ((newDNSEntry != null) && (existingDNSEntry != null) && (newDNSEntry.getKey().equals(existingDNSEntry.getKey()))) {
List<DNSEntry> entryList = this.get(newDNSEntry.getKey());
if (entryList == null) {
this.putIfAbsent(newDNSEntry.getKey(), new ArrayList<DNSEntry>());
entryList = this.get(newDNSEntry.getKey());
}
synchronized (entryList) {
entryList.remove(existingDNSEntry);
entryList.add(newDNSEntry);
}
// This is probably not very informative
result = true;
}
return result;
}
/**
* {@inheritDoc}
*/
@Override
public synchronized String toString() {
StringBuffer aLog = new StringBuffer(2000);
aLog.append("\t---- cache ----");
for (String key : this.keySet()) {
aLog.append("\n\t\t");
aLog.append("\n\t\tname '");
aLog.append(key);
aLog.append("' ");
List<? extends DNSEntry> entryList = this.get(key);
if ((entryList != null) && (!entryList.isEmpty())) {
synchronized (entryList) {
for (DNSEntry entry : entryList) {
aLog.append("\n\t\t\t");
aLog.append(entry.toString());
}
}
} else {
aLog.append(" no entries");
}
}
return aLog.toString();
}
}

View File

@ -0,0 +1,316 @@
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import javax.jmdns.ServiceInfo.Fields;
import javax.jmdns.impl.constants.DNSRecordClass;
import javax.jmdns.impl.constants.DNSRecordType;
/**
* DNS entry with a name, type, and class. This is the base class for questions and records.
*
* @author Arthur van Hoff, Pierre Frisch, Rick Blair
*/
public abstract class DNSEntry {
// private static Logger logger = Logger.getLogger(DNSEntry.class.getName());
private final String _key;
private final String _name;
private final String _type;
private final DNSRecordType _recordType;
private final DNSRecordClass _dnsClass;
private final boolean _unique;
final Map<Fields, String> _qualifiedNameMap;
/**
* Create an entry.
*/
DNSEntry(String name, DNSRecordType type, DNSRecordClass recordClass, boolean unique) {
_name = name;
// _key = (name != null ? name.trim().toLowerCase() : null);
_recordType = type;
_dnsClass = recordClass;
_unique = unique;
_qualifiedNameMap = ServiceInfoImpl.decodeQualifiedNameMapForType(this.getName());
String domain = _qualifiedNameMap.get(Fields.Domain);
String protocol = _qualifiedNameMap.get(Fields.Protocol);
String application = _qualifiedNameMap.get(Fields.Application);
String instance = _qualifiedNameMap.get(Fields.Instance).toLowerCase();
_type = (application.length() > 0 ? "_" + application + "." : "") + (protocol.length() > 0 ? "_" + protocol + "." : "") + domain + ".";
_key = ((instance.length() > 0 ? instance + "." : "") + _type).toLowerCase();
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
boolean result = false;
if (obj instanceof DNSEntry) {
DNSEntry other = (DNSEntry) obj;
result = this.getKey().equals(other.getKey()) && this.getRecordType().equals(other.getRecordType()) && this.getRecordClass() == other.getRecordClass();
}
return result;
}
/**
* Check if two entries have exactly the same name, type, and class.
*
* @param entry
* @return <code>true</code> if the two entries have are for the same record, <code>false</code> otherwise
*/
public boolean isSameEntry(DNSEntry entry) {
return this.getKey().equals(entry.getKey()) && this.matchRecordType(entry.getRecordType()) && this.matchRecordClass(entry.getRecordClass());
}
/**
* Check if two entries have the same subtype.
*
* @param other
* @return <code>true</code> if the two entries have are for the same subtype, <code>false</code> otherwise
*/
public boolean sameSubtype(DNSEntry other) {
return this.getSubtype().equals(other.getSubtype());
}
/**
* Check if the requested record class match the current record class
*
* @param recordClass
* @return <code>true</code> if the two entries have compatible class, <code>false</code> otherwise
*/
public boolean matchRecordClass(DNSRecordClass recordClass) {
return (DNSRecordClass.CLASS_ANY == recordClass) || (DNSRecordClass.CLASS_ANY == this.getRecordClass()) || this.getRecordClass().equals(recordClass);
}
/**
* Check if the requested record tyep match the current record type
*
* @param recordType
* @return <code>true</code> if the two entries have compatible type, <code>false</code> otherwise
*/
public boolean matchRecordType(DNSRecordType recordType) {
return this.getRecordType().equals(recordType);
}
/**
* Returns the subtype of this entry
*
* @return subtype of this entry
*/
public String getSubtype() {
String subtype = this.getQualifiedNameMap().get(Fields.Subtype);
return (subtype != null ? subtype : "");
}
/**
* Returns the name of this entry
*
* @return name of this entry
*/
public String getName() {
return (_name != null ? _name : "");
}
/**
* @return the type
*/
public String getType() {
return (_type != null ? _type : "");
}
/**
* Returns the key for this entry. The key is the lower case name.
*
* @return key for this entry
*/
public String getKey() {
return (_key != null ? _key : "");
}
/**
* @return record type
*/
public DNSRecordType getRecordType() {
return (_recordType != null ? _recordType : DNSRecordType.TYPE_IGNORE);
}
/**
* @return record class
*/
public DNSRecordClass getRecordClass() {
return (_dnsClass != null ? _dnsClass : DNSRecordClass.CLASS_UNKNOWN);
}
/**
* @return true if unique
*/
public boolean isUnique() {
return _unique;
}
public Map<Fields, String> getQualifiedNameMap() {
return Collections.unmodifiableMap(_qualifiedNameMap);
}
public boolean isServicesDiscoveryMetaQuery() {
return _qualifiedNameMap.get(Fields.Application).equals("dns-sd") && _qualifiedNameMap.get(Fields.Instance).equals("_services");
}
public boolean isDomainDiscoveryQuery() {
// b._dns-sd._udp.<domain>.
// db._dns-sd._udp.<domain>.
// r._dns-sd._udp.<domain>.
// dr._dns-sd._udp.<domain>.
// lb._dns-sd._udp.<domain>.
if (_qualifiedNameMap.get(Fields.Application).equals("dns-sd")) {
String name = _qualifiedNameMap.get(Fields.Instance);
return "b".equals(name) || "db".equals(name) || "r".equals(name) || "dr".equals(name) || "lb".equals(name);
}
return false;
}
public boolean isReverseLookup() {
return this.isV4ReverseLookup() || this.isV6ReverseLookup();
}
public boolean isV4ReverseLookup() {
return _qualifiedNameMap.get(Fields.Domain).endsWith("in-addr.arpa");
}
public boolean isV6ReverseLookup() {
return _qualifiedNameMap.get(Fields.Domain).endsWith("ip6.arpa");
}
/**
* Check if the record is stale, i.e. it has outlived more than half of its TTL.
*
* @param now
* update date
* @return <code>true</code> is the record is stale, <code>false</code> otherwise.
*/
public abstract boolean isStale(long now);
/**
* Check if the record is expired.
*
* @param now
* update date
* @return <code>true</code> is the record is expired, <code>false</code> otherwise.
*/
public abstract boolean isExpired(long now);
/**
* Check that 2 entries are of the same class.
*
* @param entry
* @return <code>true</code> is the two class are the same, <code>false</code> otherwise.
*/
public boolean isSameRecordClass(DNSEntry entry) {
return (entry != null) && (entry.getRecordClass() == this.getRecordClass());
}
/**
* Check that 2 entries are of the same type.
*
* @param entry
* @return <code>true</code> is the two type are the same, <code>false</code> otherwise.
*/
public boolean isSameType(DNSEntry entry) {
return (entry != null) && (entry.getRecordType() == this.getRecordType());
}
/**
* @param dout
* @exception IOException
*/
protected void toByteArray(DataOutputStream dout) throws IOException {
dout.write(this.getName().getBytes("UTF8"));
dout.writeShort(this.getRecordType().indexValue());
dout.writeShort(this.getRecordClass().indexValue());
}
/**
* Creates a byte array representation of this record. This is needed for tie-break tests according to draft-cheshire-dnsext-multicastdns-04.txt chapter 9.2.
*
* @return byte array representation
*/
protected byte[] toByteArray() {
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
this.toByteArray(dout);
dout.close();
return bout.toByteArray();
} catch (IOException e) {
throw new InternalError();
}
}
/**
* Does a lexicographic comparison of the byte array representation of this record and that record. This is needed for tie-break tests according to draft-cheshire-dnsext-multicastdns-04.txt chapter 9.2.
*
* @param that
* @return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
*/
public int compareTo(DNSEntry that) {
byte[] thisBytes = this.toByteArray();
byte[] thatBytes = that.toByteArray();
for (int i = 0, n = Math.min(thisBytes.length, thatBytes.length); i < n; i++) {
if (thisBytes[i] > thatBytes[i]) {
return 1;
} else if (thisBytes[i] < thatBytes[i]) {
return -1;
}
}
return thisBytes.length - thatBytes.length;
}
/**
* Overriden, to return a value which is consistent with the value returned by equals(Object).
*/
@Override
public int hashCode() {
return this.getKey().hashCode() + this.getRecordType().indexValue() + this.getRecordClass().indexValue();
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder aLog = new StringBuilder(200);
aLog.append("[" + this.getClass().getSimpleName() + "@" + System.identityHashCode(this));
aLog.append(" type: " + this.getRecordType());
aLog.append(", class: " + this.getRecordClass());
aLog.append((_unique ? "-unique," : ","));
aLog.append(" name: " + _name);
this.toString(aLog);
aLog.append("]");
return aLog.toString();
}
/**
* @param aLog
*/
protected void toString(StringBuilder aLog) {
// Stub
}
}

View File

@ -0,0 +1,597 @@
// /Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jmdns.impl.constants.DNSConstants;
import javax.jmdns.impl.constants.DNSLabel;
import javax.jmdns.impl.constants.DNSOptionCode;
import javax.jmdns.impl.constants.DNSRecordClass;
import javax.jmdns.impl.constants.DNSRecordType;
import javax.jmdns.impl.constants.DNSResultCode;
/**
* Parse an incoming DNS message into its components.
*
* @author Arthur van Hoff, Werner Randelshofer, Pierre Frisch, Daniel Bobbert
*/
public final class DNSIncoming extends DNSMessage {
private static Logger logger = Logger.getLogger(DNSIncoming.class.getName());
// This is a hack to handle a bug in the BonjourConformanceTest
// It is sending out target strings that don't follow the "domain name" format.
public static boolean USE_DOMAIN_NAME_FORMAT_FOR_SRV_TARGET = true;
public static class MessageInputStream extends ByteArrayInputStream {
private static Logger logger1 = Logger.getLogger(MessageInputStream.class.getName());
final Map<Integer, String> _names;
public MessageInputStream(byte[] buffer, int length) {
this(buffer, 0, length);
}
/**
* @param buffer
* @param offset
* @param length
*/
public MessageInputStream(byte[] buffer, int offset, int length) {
super(buffer, offset, length);
_names = new HashMap<Integer, String>();
}
public int readByte() {
return this.read();
}
public int readUnsignedByte() {
return (this.read() & 0xFF);
}
public int readUnsignedShort() {
return (this.readUnsignedByte() << 8) | this.readUnsignedByte();
}
public int readInt() {
return (this.readUnsignedShort() << 16) | this.readUnsignedShort();
}
public byte[] readBytes(int len) {
byte bytes[] = new byte[len];
this.read(bytes, 0, len);
return bytes;
}
public String readUTF(int len) {
StringBuilder buffer = new StringBuilder(len);
for (int index = 0; index < len; index++) {
int ch = this.readUnsignedByte();
switch (ch >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
// 0xxxxxxx
break;
case 12:
case 13:
// 110x xxxx 10xx xxxx
ch = ((ch & 0x1F) << 6) | (this.readUnsignedByte() & 0x3F);
index++;
break;
case 14:
// 1110 xxxx 10xx xxxx 10xx xxxx
ch = ((ch & 0x0f) << 12) | ((this.readUnsignedByte() & 0x3F) << 6) | (this.readUnsignedByte() & 0x3F);
index++;
index++;
break;
default:
// 10xx xxxx, 1111 xxxx
ch = ((ch & 0x3F) << 4) | (this.readUnsignedByte() & 0x0f);
index++;
break;
}
buffer.append((char) ch);
}
return buffer.toString();
}
protected synchronized int peek() {
return (pos < count) ? (buf[pos] & 0xff) : -1;
}
public String readName() {
Map<Integer, StringBuilder> names = new HashMap<Integer, StringBuilder>();
StringBuilder buffer = new StringBuilder();
boolean finished = false;
while (!finished) {
int len = this.readUnsignedByte();
if (len == 0) {
finished = true;
break;
}
switch (DNSLabel.labelForByte(len)) {
case Standard:
int offset = pos - 1;
String label = this.readUTF(len) + ".";
buffer.append(label);
for (StringBuilder previousLabel : names.values()) {
previousLabel.append(label);
}
names.put(Integer.valueOf(offset), new StringBuilder(label));
break;
case Compressed:
int index = (DNSLabel.labelValue(len) << 8) | this.readUnsignedByte();
String compressedLabel = _names.get(Integer.valueOf(index));
if (compressedLabel == null) {
logger1.severe("bad domain name: possible circular name detected. Bad offset: 0x" + Integer.toHexString(index) + " at 0x" + Integer.toHexString(pos - 2));
compressedLabel = "";
}
buffer.append(compressedLabel);
for (StringBuilder previousLabel : names.values()) {
previousLabel.append(compressedLabel);
}
finished = true;
break;
case Extended:
// int extendedLabelClass = DNSLabel.labelValue(len);
logger1.severe("Extended label are not currently supported.");
break;
case Unknown:
default:
logger1.severe("unsupported dns label type: '" + Integer.toHexString(len & 0xC0) + "'");
}
}
for (Integer index : names.keySet()) {
_names.put(index, names.get(index).toString());
}
return buffer.toString();
}
public String readNonNameString() {
int len = this.readUnsignedByte();
return this.readUTF(len);
}
}
private final DatagramPacket _packet;
private final long _receivedTime;
private final MessageInputStream _messageInputStream;
private int _senderUDPPayload;
/**
* Parse a message from a datagram packet.
*
* @param packet
* @exception IOException
*/
public DNSIncoming(DatagramPacket packet) throws IOException {
super(0, 0, packet.getPort() == DNSConstants.MDNS_PORT);
this._packet = packet;
InetAddress source = packet.getAddress();
this._messageInputStream = new MessageInputStream(packet.getData(), packet.getLength());
this._receivedTime = System.currentTimeMillis();
this._senderUDPPayload = DNSConstants.MAX_MSG_TYPICAL;
try {
this.setId(_messageInputStream.readUnsignedShort());
this.setFlags(_messageInputStream.readUnsignedShort());
if (this.getOperationCode() > 0) {
throw new IOException("Received a message with a non standard operation code. Currently unsupported in the specification.");
}
int numQuestions = _messageInputStream.readUnsignedShort();
int numAnswers = _messageInputStream.readUnsignedShort();
int numAuthorities = _messageInputStream.readUnsignedShort();
int numAdditionals = _messageInputStream.readUnsignedShort();
if (logger.isLoggable(Level.FINER)) {
logger.finer("DNSIncoming() questions:" + numQuestions + " answers:" + numAnswers + " authorities:" + numAuthorities + " additionals:" + numAdditionals);
}
// We need some sanity checks
// A question is at least 5 bytes and answer 11 so check what we have
if ((numQuestions * 5 + (numAnswers + numAuthorities + numAdditionals) * 11) > packet.getLength()) {
throw new IOException("questions:" + numQuestions + " answers:" + numAnswers + " authorities:" + numAuthorities + " additionals:" + numAdditionals);
}
// parse questions
if (numQuestions > 0) {
for (int i = 0; i < numQuestions; i++) {
_questions.add(this.readQuestion());
}
}
// parse answers
if (numAnswers > 0) {
for (int i = 0; i < numAnswers; i++) {
DNSRecord rec = this.readAnswer(source);
if (rec != null) {
// Add a record, if we were able to create one.
_answers.add(rec);
}
}
}
if (numAuthorities > 0) {
for (int i = 0; i < numAuthorities; i++) {
DNSRecord rec = this.readAnswer(source);
if (rec != null) {
// Add a record, if we were able to create one.
_authoritativeAnswers.add(rec);
}
}
}
if (numAdditionals > 0) {
for (int i = 0; i < numAdditionals; i++) {
DNSRecord rec = this.readAnswer(source);
if (rec != null) {
// Add a record, if we were able to create one.
_additionals.add(rec);
}
}
}
// We should have drained the entire stream by now
if (_messageInputStream.available() > 0) {
throw new IOException("Received a message with the wrong length.");
}
} catch (Exception e) {
logger.log(Level.WARNING, "DNSIncoming() dump " + print(true) + "\n exception ", e);
// This ugly but some JVM don't implement the cause on IOException
IOException ioe = new IOException("DNSIncoming corrupted message");
ioe.initCause(e);
throw ioe;
}
}
private DNSIncoming(int flags, int id, boolean multicast, DatagramPacket packet, long receivedTime) {
super(flags, id, multicast);
this._packet = packet;
this._messageInputStream = new MessageInputStream(packet.getData(), packet.getLength());
this._receivedTime = receivedTime;
}
/*
* (non-Javadoc)
* @see java.lang.Object#clone()
*/
@Override
public DNSIncoming clone() {
DNSIncoming in = new DNSIncoming(this.getFlags(), this.getId(), this.isMulticast(), this._packet, this._receivedTime);
in._senderUDPPayload = this._senderUDPPayload;
in._questions.addAll(this._questions);
in._answers.addAll(this._answers);
in._authoritativeAnswers.addAll(this._authoritativeAnswers);
in._additionals.addAll(this._additionals);
return in;
}
private DNSQuestion readQuestion() {
String domain = _messageInputStream.readName();
DNSRecordType type = DNSRecordType.typeForIndex(_messageInputStream.readUnsignedShort());
if (type == DNSRecordType.TYPE_IGNORE) {
logger.log(Level.SEVERE, "Could not find record type: " + this.print(true));
}
int recordClassIndex = _messageInputStream.readUnsignedShort();
DNSRecordClass recordClass = DNSRecordClass.classForIndex(recordClassIndex);
boolean unique = recordClass.isUnique(recordClassIndex);
return DNSQuestion.newQuestion(domain, type, recordClass, unique);
}
private DNSRecord readAnswer(InetAddress source) {
String domain = _messageInputStream.readName();
DNSRecordType type = DNSRecordType.typeForIndex(_messageInputStream.readUnsignedShort());
if (type == DNSRecordType.TYPE_IGNORE) {
logger.log(Level.SEVERE, "Could not find record type. domain: " + domain + "\n" + this.print(true));
}
int recordClassIndex = _messageInputStream.readUnsignedShort();
DNSRecordClass recordClass = (type == DNSRecordType.TYPE_OPT ? DNSRecordClass.CLASS_UNKNOWN : DNSRecordClass.classForIndex(recordClassIndex));
if ((recordClass == DNSRecordClass.CLASS_UNKNOWN) && (type != DNSRecordType.TYPE_OPT)) {
logger.log(Level.SEVERE, "Could not find record class. domain: " + domain + " type: " + type + "\n" + this.print(true));
}
boolean unique = recordClass.isUnique(recordClassIndex);
int ttl = _messageInputStream.readInt();
int len = _messageInputStream.readUnsignedShort();
DNSRecord rec = null;
switch (type) {
case TYPE_A: // IPv4
rec = new DNSRecord.IPv4Address(domain, recordClass, unique, ttl, _messageInputStream.readBytes(len));
break;
case TYPE_AAAA: // IPv6
rec = new DNSRecord.IPv6Address(domain, recordClass, unique, ttl, _messageInputStream.readBytes(len));
break;
case TYPE_CNAME:
case TYPE_PTR:
String service = "";
service = _messageInputStream.readName();
if (service.length() > 0) {
rec = new DNSRecord.Pointer(domain, recordClass, unique, ttl, service);
} else {
logger.log(Level.WARNING, "PTR record of class: " + recordClass + ", there was a problem reading the service name of the answer for domain:" + domain);
}
break;
case TYPE_TXT:
rec = new DNSRecord.Text(domain, recordClass, unique, ttl, _messageInputStream.readBytes(len));
break;
case TYPE_SRV:
int priority = _messageInputStream.readUnsignedShort();
int weight = _messageInputStream.readUnsignedShort();
int port = _messageInputStream.readUnsignedShort();
String target = "";
// This is a hack to handle a bug in the BonjourConformanceTest
// It is sending out target strings that don't follow the "domain name" format.
if (USE_DOMAIN_NAME_FORMAT_FOR_SRV_TARGET) {
target = _messageInputStream.readName();
} else {
// [PJYF Nov 13 2010] Do we still need this? This looks really bad. All label are supposed to start by a length.
target = _messageInputStream.readNonNameString();
}
rec = new DNSRecord.Service(domain, recordClass, unique, ttl, priority, weight, port, target);
break;
case TYPE_HINFO:
StringBuilder buf = new StringBuilder();
buf.append(_messageInputStream.readUTF(len));
int index = buf.indexOf(" ");
String cpu = (index > 0 ? buf.substring(0, index) : buf.toString()).trim();
String os = (index > 0 ? buf.substring(index + 1) : "").trim();
rec = new DNSRecord.HostInformation(domain, recordClass, unique, ttl, cpu, os);
break;
case TYPE_OPT:
DNSResultCode extendedResultCode = DNSResultCode.resultCodeForFlags(this.getFlags(), ttl);
int version = (ttl & 0x00ff0000) >> 16;
if (version == 0) {
_senderUDPPayload = recordClassIndex;
while (_messageInputStream.available() > 0) {
// Read RDData
int optionCodeInt = 0;
DNSOptionCode optionCode = null;
if (_messageInputStream.available() >= 2) {
optionCodeInt = _messageInputStream.readUnsignedShort();
optionCode = DNSOptionCode.resultCodeForFlags(optionCodeInt);
} else {
logger.log(Level.WARNING, "There was a problem reading the OPT record. Ignoring.");
break;
}
int optionLength = 0;
if (_messageInputStream.available() >= 2) {
optionLength = _messageInputStream.readUnsignedShort();
} else {
logger.log(Level.WARNING, "There was a problem reading the OPT record. Ignoring.");
break;
}
byte[] optiondata = new byte[0];
if (_messageInputStream.available() >= optionLength) {
optiondata = _messageInputStream.readBytes(optionLength);
}
//
// We should really do something with those options.
switch (optionCode) {
case Owner:
// Valid length values are 8, 14, 18 and 20
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |Opt|Len|V|S|Primary MAC|Wakeup MAC | Password |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
int ownerVersion = 0;
int ownerSequence = 0;
byte[] ownerPrimaryMacAddress = null;
byte[] ownerWakeupMacAddress = null;
byte[] ownerPassword = null;
try {
ownerVersion = optiondata[0];
ownerSequence = optiondata[1];
ownerPrimaryMacAddress = new byte[] { optiondata[2], optiondata[3], optiondata[4], optiondata[5], optiondata[6], optiondata[7] };
ownerWakeupMacAddress = ownerPrimaryMacAddress;
if (optiondata.length > 8) {
// We have a wakeupMacAddress.
ownerWakeupMacAddress = new byte[] { optiondata[8], optiondata[9], optiondata[10], optiondata[11], optiondata[12], optiondata[13] };
}
if (optiondata.length == 18) {
// We have a short password.
ownerPassword = new byte[] { optiondata[14], optiondata[15], optiondata[16], optiondata[17] };
}
if (optiondata.length == 22) {
// We have a long password.
ownerPassword = new byte[] { optiondata[14], optiondata[15], optiondata[16], optiondata[17], optiondata[18], optiondata[19], optiondata[20], optiondata[21] };
}
} catch (Exception exception) {
logger.warning("Malformed OPT answer. Option code: Owner data: " + this._hexString(optiondata));
}
if (logger.isLoggable(Level.FINE)) {
logger.fine("Unhandled Owner OPT version: " + ownerVersion + " sequence: " + ownerSequence + " MAC address: " + this._hexString(ownerPrimaryMacAddress)
+ (ownerWakeupMacAddress != ownerPrimaryMacAddress ? " wakeup MAC address: " + this._hexString(ownerWakeupMacAddress) : "") + (ownerPassword != null ? " password: " + this._hexString(ownerPassword) : ""));
}
break;
case LLQ:
case NSID:
case UL:
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, "There was an OPT answer. Option code: " + optionCode + " data: " + this._hexString(optiondata));
}
break;
case Unknown:
logger.log(Level.WARNING, "There was an OPT answer. Not currently handled. Option code: " + optionCodeInt + " data: " + this._hexString(optiondata));
break;
default:
// This is to keep the compiler happy.
break;
}
}
} else {
logger.log(Level.WARNING, "There was an OPT answer. Wrong version number: " + version + " result code: " + extendedResultCode);
}
break;
default:
if (logger.isLoggable(Level.FINER)) {
logger.finer("DNSIncoming() unknown type:" + type);
}
_messageInputStream.skip(len);
break;
}
if (rec != null) {
rec.setRecordSource(source);
}
return rec;
}
/**
* Debugging.
*/
String print(boolean dump) {
StringBuilder buf = new StringBuilder();
buf.append(this.print());
if (dump) {
byte[] data = new byte[_packet.getLength()];
System.arraycopy(_packet.getData(), 0, data, 0, data.length);
buf.append(this.print(data));
}
return buf.toString();
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append(isQuery() ? "dns[query," : "dns[response,");
if (_packet.getAddress() != null) {
buf.append(_packet.getAddress().getHostAddress());
}
buf.append(':');
buf.append(_packet.getPort());
buf.append(", length=");
buf.append(_packet.getLength());
buf.append(", id=0x");
buf.append(Integer.toHexString(this.getId()));
if (this.getFlags() != 0) {
buf.append(", flags=0x");
buf.append(Integer.toHexString(this.getFlags()));
if ((this.getFlags() & DNSConstants.FLAGS_QR_RESPONSE) != 0) {
buf.append(":r");
}
if ((this.getFlags() & DNSConstants.FLAGS_AA) != 0) {
buf.append(":aa");
}
if ((this.getFlags() & DNSConstants.FLAGS_TC) != 0) {
buf.append(":tc");
}
}
if (this.getNumberOfQuestions() > 0) {
buf.append(", questions=");
buf.append(this.getNumberOfQuestions());
}
if (this.getNumberOfAnswers() > 0) {
buf.append(", answers=");
buf.append(this.getNumberOfAnswers());
}
if (this.getNumberOfAuthorities() > 0) {
buf.append(", authorities=");
buf.append(this.getNumberOfAuthorities());
}
if (this.getNumberOfAdditionals() > 0) {
buf.append(", additionals=");
buf.append(this.getNumberOfAdditionals());
}
if (this.getNumberOfQuestions() > 0) {
buf.append("\nquestions:");
for (DNSQuestion question : _questions) {
buf.append("\n\t");
buf.append(question);
}
}
if (this.getNumberOfAnswers() > 0) {
buf.append("\nanswers:");
for (DNSRecord record : _answers) {
buf.append("\n\t");
buf.append(record);
}
}
if (this.getNumberOfAuthorities() > 0) {
buf.append("\nauthorities:");
for (DNSRecord record : _authoritativeAnswers) {
buf.append("\n\t");
buf.append(record);
}
}
if (this.getNumberOfAdditionals() > 0) {
buf.append("\nadditionals:");
for (DNSRecord record : _additionals) {
buf.append("\n\t");
buf.append(record);
}
}
buf.append("]");
return buf.toString();
}
/**
* Appends answers to this Incoming.
*
* @exception IllegalArgumentException
* If not a query or if Truncated.
*/
void append(DNSIncoming that) {
if (this.isQuery() && this.isTruncated() && that.isQuery()) {
this._questions.addAll(that.getQuestions());
this._answers.addAll(that.getAnswers());
this._authoritativeAnswers.addAll(that.getAuthorities());
this._additionals.addAll(that.getAdditionals());
} else {
throw new IllegalArgumentException();
}
}
public int elapseSinceArrival() {
return (int) (System.currentTimeMillis() - _receivedTime);
}
/**
* This will return the default UDP payload except if an OPT record was found with a different size.
*
* @return the senderUDPPayload
*/
public int getSenderUDPPayload() {
return this._senderUDPPayload;
}
private static final char[] _nibbleToHex = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
/**
* Returns a hex-string for printing
*
* @param bytes
* @return Returns a hex-string which can be used within a SQL expression
*/
private String _hexString(byte[] bytes) {
StringBuilder result = new StringBuilder(2 * bytes.length);
for (int i = 0; i < bytes.length; i++) {
int b = bytes[i] & 0xFF;
result.append(_nibbleToHex[b / 16]);
result.append(_nibbleToHex[b % 16]);
}
return result.toString();
}
}

View File

@ -0,0 +1,28 @@
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl;
// REMIND: Listener should follow Java idiom for listener or have a different
// name.
/**
* DNSListener. Listener for record updates.
*
* @author Werner Randelshofer, Rick Blair
* @version 1.0 May 22, 2004 Created.
*/
interface DNSListener {
/**
* Update a DNS record.
*
* @param dnsCache
* record cache
* @param now
* update date
* @param record
* DNS record
*/
void updateRecord(DNSCache dnsCache, long now, DNSEntry record);
}

View File

@ -0,0 +1,335 @@
/**
*
*/
package javax.jmdns.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import javax.jmdns.impl.constants.DNSConstants;
/**
* DNSMessage define a DNS message either incoming or outgoing.
*
* @author Werner Randelshofer, Rick Blair, Pierre Frisch
*/
public abstract class DNSMessage {
/**
*
*/
public static final boolean MULTICAST = true;
/**
*
*/
public static final boolean UNICAST = false;
// protected DatagramPacket _packet;
// protected int _off;
// protected int _len;
// protected byte[] _data;
private int _id;
boolean _multicast;
private int _flags;
protected final List<DNSQuestion> _questions;
protected final List<DNSRecord> _answers;
protected final List<DNSRecord> _authoritativeAnswers;
protected final List<DNSRecord> _additionals;
/**
* @param flags
* @param id
* @param multicast
*/
protected DNSMessage(int flags, int id, boolean multicast) {
super();
_flags = flags;
_id = id;
_multicast = multicast;
_questions = Collections.synchronizedList(new LinkedList<DNSQuestion>());
_answers = Collections.synchronizedList(new LinkedList<DNSRecord>());
_authoritativeAnswers = Collections.synchronizedList(new LinkedList<DNSRecord>());
_additionals = Collections.synchronizedList(new LinkedList<DNSRecord>());
}
// public DatagramPacket getPacket() {
// return _packet;
// }
//
// public int getOffset() {
// return _off;
// }
//
// public int getLength() {
// return _len;
// }
//
// public byte[] getData() {
// if ( _data == null ) _data = new byte[DNSConstants.MAX_MSG_TYPICAL];
// return _data;
// }
/**
* @return message id
*/
public int getId() {
return (_multicast ? 0 : _id);
}
/**
* @param id
* the id to set
*/
public void setId(int id) {
this._id = id;
}
/**
* @return message flags
*/
public int getFlags() {
return _flags;
}
/**
* @param flags
* the flags to set
*/
public void setFlags(int flags) {
this._flags = flags;
}
/**
* @return true if multicast
*/
public boolean isMulticast() {
return _multicast;
}
/**
* @return list of questions
*/
public Collection<? extends DNSQuestion> getQuestions() {
return _questions;
}
/**
* @return number of questions in the message
*/
public int getNumberOfQuestions() {
return this.getQuestions().size();
}
public Collection<? extends DNSRecord> getAllAnswers() {
List<DNSRecord> aList = new ArrayList<DNSRecord>(_answers.size() + _authoritativeAnswers.size() + _additionals.size());
aList.addAll(_answers);
aList.addAll(_authoritativeAnswers);
aList.addAll(_additionals);
return aList;
}
/**
* @return list of answers
*/
public Collection<? extends DNSRecord> getAnswers() {
return _answers;
}
/**
* @return number of answers in the message
*/
public int getNumberOfAnswers() {
return this.getAnswers().size();
}
/**
* @return list of authorities
*/
public Collection<? extends DNSRecord> getAuthorities() {
return _authoritativeAnswers;
}
/**
* @return number of authorities in the message
*/
public int getNumberOfAuthorities() {
return this.getAuthorities().size();
}
/**
* @return list of additional answers
*/
public Collection<? extends DNSRecord> getAdditionals() {
return _additionals;
}
/**
* @return number of additional in the message
*/
public int getNumberOfAdditionals() {
return this.getAdditionals().size();
}
/**
* Check is the response code is valid<br/>
* The only valid value is zero all other values signify an error and the message must be ignored.
*
* @return true if the message has a valid response code.
*/
public boolean isValidResponseCode() {
return (_flags & DNSConstants.FLAGS_RCODE) == 0;
}
/**
* Returns the operation code value. Currently only standard query 0 is valid.
*
* @return The operation code value.
*/
public int getOperationCode() {
return (_flags & DNSConstants.FLAGS_OPCODE) >> 11;
}
/**
* Check if the message is truncated.
*
* @return true if the message was truncated
*/
public boolean isTruncated() {
return (_flags & DNSConstants.FLAGS_TC) != 0;
}
/**
* Check if the message is an authoritative answer.
*
* @return true if the message is an authoritative answer
*/
public boolean isAuthoritativeAnswer() {
return (_flags & DNSConstants.FLAGS_AA) != 0;
}
/**
* Check if the message is a query.
*
* @return true is the message is a query
*/
public boolean isQuery() {
return (_flags & DNSConstants.FLAGS_QR_MASK) == DNSConstants.FLAGS_QR_QUERY;
}
/**
* Check if the message is a response.
*
* @return true is the message is a response
*/
public boolean isResponse() {
return (_flags & DNSConstants.FLAGS_QR_MASK) == DNSConstants.FLAGS_QR_RESPONSE;
}
/**
* Check if the message is empty
*
* @return true is the message is empty
*/
public boolean isEmpty() {
return (this.getNumberOfQuestions() + this.getNumberOfAnswers() + this.getNumberOfAuthorities() + this.getNumberOfAdditionals()) == 0;
}
/**
* Debugging.
*/
String print() {
StringBuffer buf = new StringBuffer(200);
buf.append(this.toString());
buf.append("\n");
for (DNSQuestion question : _questions) {
buf.append("\tquestion: ");
buf.append(question);
buf.append("\n");
}
for (DNSRecord answer : _answers) {
buf.append("\tanswer: ");
buf.append(answer);
buf.append("\n");
}
for (DNSRecord answer : _authoritativeAnswers) {
buf.append("\tauthoritative: ");
buf.append(answer);
buf.append("\n");
}
for (DNSRecord answer : _additionals) {
buf.append("\tadditional: ");
buf.append(answer);
buf.append("\n");
}
return buf.toString();
}
/**
* Debugging.
*
* @param data
* @return data dump
*/
protected String print(byte[] data) {
StringBuilder buf = new StringBuilder(4000);
for (int off = 0, len = data.length; off < len; off += 32) {
int n = Math.min(32, len - off);
if (off < 0x10) {
buf.append(' ');
}
if (off < 0x100) {
buf.append(' ');
}
if (off < 0x1000) {
buf.append(' ');
}
buf.append(Integer.toHexString(off));
buf.append(':');
int index = 0;
for (index = 0; index < n; index++) {
if ((index % 8) == 0) {
buf.append(' ');
}
buf.append(Integer.toHexString((data[off + index] & 0xF0) >> 4));
buf.append(Integer.toHexString((data[off + index] & 0x0F) >> 0));
}
// for incomplete lines
if (index < 32) {
for (int i = index; i < 32; i++) {
if ((i % 8) == 0) {
buf.append(' ');
}
buf.append(" ");
}
}
buf.append(" ");
for (index = 0; index < n; index++) {
if ((index % 8) == 0) {
buf.append(' ');
}
int ch = data[off + index] & 0xFF;
buf.append(((ch > ' ') && (ch < 127)) ? (char) ch : '.');
}
buf.append("\n");
// limit message size
if (off + 32 >= 2048) {
buf.append("....\n");
break;
}
}
return buf.toString();
}
}

View File

@ -0,0 +1,446 @@
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.jmdns.impl.constants.DNSConstants;
import javax.jmdns.impl.constants.DNSRecordClass;
/**
* An outgoing DNS message.
*
* @author Arthur van Hoff, Rick Blair, Werner Randelshofer
*/
public final class DNSOutgoing extends DNSMessage {
public static class MessageOutputStream extends ByteArrayOutputStream {
private final DNSOutgoing _out;
private final int _offset;
/**
* Creates a new message stream, with a buffer capacity of the specified size, in bytes.
*
* @param size
* the initial size.
* @exception IllegalArgumentException
* if size is negative.
*/
MessageOutputStream(int size, DNSOutgoing out) {
this(size, out, 0);
}
MessageOutputStream(int size, DNSOutgoing out, int offset) {
super(size);
_out = out;
_offset = offset;
}
void writeByte(int value) {
this.write(value & 0xFF);
}
void writeBytes(String str, int off, int len) {
for (int i = 0; i < len; i++) {
writeByte(str.charAt(off + i));
}
}
void writeBytes(byte data[]) {
if (data != null) {
writeBytes(data, 0, data.length);
}
}
void writeBytes(byte data[], int off, int len) {
for (int i = 0; i < len; i++) {
writeByte(data[off + i]);
}
}
void writeShort(int value) {
writeByte(value >> 8);
writeByte(value);
}
void writeInt(int value) {
writeShort(value >> 16);
writeShort(value);
}
void writeUTF(String str, int off, int len) {
// compute utf length
int utflen = 0;
for (int i = 0; i < len; i++) {
int ch = str.charAt(off + i);
if ((ch >= 0x0001) && (ch <= 0x007F)) {
utflen += 1;
} else {
if (ch > 0x07FF) {
utflen += 3;
} else {
utflen += 2;
}
}
}
// write utf length
writeByte(utflen);
// write utf data
for (int i = 0; i < len; i++) {
int ch = str.charAt(off + i);
if ((ch >= 0x0001) && (ch <= 0x007F)) {
writeByte(ch);
} else {
if (ch > 0x07FF) {
writeByte(0xE0 | ((ch >> 12) & 0x0F));
writeByte(0x80 | ((ch >> 6) & 0x3F));
writeByte(0x80 | ((ch >> 0) & 0x3F));
} else {
writeByte(0xC0 | ((ch >> 6) & 0x1F));
writeByte(0x80 | ((ch >> 0) & 0x3F));
}
}
}
}
void writeName(String name) {
writeName(name, true);
}
void writeName(String name, boolean useCompression) {
String aName = name;
while (true) {
int n = aName.indexOf('.');
if (n < 0) {
n = aName.length();
}
if (n <= 0) {
writeByte(0);
return;
}
String label = aName.substring(0, n);
if (useCompression && USE_DOMAIN_NAME_COMPRESSION) {
Integer offset = _out._names.get(aName);
if (offset != null) {
int val = offset.intValue();
writeByte((val >> 8) | 0xC0);
writeByte(val & 0xFF);
return;
}
_out._names.put(aName, Integer.valueOf(this.size() + _offset));
writeUTF(label, 0, label.length());
} else {
writeUTF(label, 0, label.length());
}
aName = aName.substring(n);
if (aName.startsWith(".")) {
aName = aName.substring(1);
}
}
}
void writeQuestion(DNSQuestion question) {
writeName(question.getName());
writeShort(question.getRecordType().indexValue());
writeShort(question.getRecordClass().indexValue());
}
void writeRecord(DNSRecord rec, long now) {
writeName(rec.getName());
writeShort(rec.getRecordType().indexValue());
writeShort(rec.getRecordClass().indexValue() | ((rec.isUnique() && _out.isMulticast()) ? DNSRecordClass.CLASS_UNIQUE : 0));
writeInt((now == 0) ? rec.getTTL() : rec.getRemainingTTL(now));
// We need to take into account the 2 size bytes
MessageOutputStream record = new MessageOutputStream(512, _out, _offset + this.size() + 2);
rec.write(record);
byte[] byteArray = record.toByteArray();
writeShort(byteArray.length);
write(byteArray, 0, byteArray.length);
}
}
/**
* This can be used to turn off domain name compression. This was helpful for tracking problems interacting with other mdns implementations.
*/
public static boolean USE_DOMAIN_NAME_COMPRESSION = true;
Map<String, Integer> _names;
private int _maxUDPPayload;
private final MessageOutputStream _questionsBytes;
private final MessageOutputStream _answersBytes;
private final MessageOutputStream _authoritativeAnswersBytes;
private final MessageOutputStream _additionalsAnswersBytes;
private final static int HEADER_SIZE = 12;
/**
* Create an outgoing multicast query or response.
*
* @param flags
*/
public DNSOutgoing(int flags) {
this(flags, true, DNSConstants.MAX_MSG_TYPICAL);
}
/**
* Create an outgoing query or response.
*
* @param flags
* @param multicast
*/
public DNSOutgoing(int flags, boolean multicast) {
this(flags, multicast, DNSConstants.MAX_MSG_TYPICAL);
}
/**
* Create an outgoing query or response.
*
* @param flags
* @param multicast
* @param senderUDPPayload
* The sender's UDP payload size is the number of bytes of the largest UDP payload that can be reassembled and delivered in the sender's network stack.
*/
public DNSOutgoing(int flags, boolean multicast, int senderUDPPayload) {
super(flags, 0, multicast);
_names = new HashMap<String, Integer>();
_maxUDPPayload = (senderUDPPayload > 0 ? senderUDPPayload : DNSConstants.MAX_MSG_TYPICAL);
_questionsBytes = new MessageOutputStream(senderUDPPayload, this);
_answersBytes = new MessageOutputStream(senderUDPPayload, this);
_authoritativeAnswersBytes = new MessageOutputStream(senderUDPPayload, this);
_additionalsAnswersBytes = new MessageOutputStream(senderUDPPayload, this);
}
/**
* Return the number of byte available in the message.
*
* @return available space
*/
public int availableSpace() {
return _maxUDPPayload - HEADER_SIZE - _questionsBytes.size() - _answersBytes.size() - _authoritativeAnswersBytes.size() - _additionalsAnswersBytes.size();
}
/**
* Add a question to the message.
*
* @param rec
* @exception IOException
*/
public void addQuestion(DNSQuestion rec) throws IOException {
MessageOutputStream record = new MessageOutputStream(512, this);
record.writeQuestion(rec);
byte[] byteArray = record.toByteArray();
if (byteArray.length < this.availableSpace()) {
_questions.add(rec);
_questionsBytes.write(byteArray, 0, byteArray.length);
} else {
throw new IOException("message full");
}
}
/**
* Add an answer if it is not suppressed.
*
* @param in
* @param rec
* @exception IOException
*/
public void addAnswer(DNSIncoming in, DNSRecord rec) throws IOException {
if ((in == null) || !rec.suppressedBy(in)) {
this.addAnswer(rec, 0);
}
}
/**
* Add an answer to the message.
*
* @param rec
* @param now
* @exception IOException
*/
public void addAnswer(DNSRecord rec, long now) throws IOException {
if (rec != null) {
if ((now == 0) || !rec.isExpired(now)) {
MessageOutputStream record = new MessageOutputStream(512, this);
record.writeRecord(rec, now);
byte[] byteArray = record.toByteArray();
if (byteArray.length < this.availableSpace()) {
_answers.add(rec);
_answersBytes.write(byteArray, 0, byteArray.length);
} else {
throw new IOException("message full");
}
}
}
}
/**
* Add an authoritative answer to the message.
*
* @param rec
* @exception IOException
*/
public void addAuthorativeAnswer(DNSRecord rec) throws IOException {
MessageOutputStream record = new MessageOutputStream(512, this);
record.writeRecord(rec, 0);
byte[] byteArray = record.toByteArray();
if (byteArray.length < this.availableSpace()) {
_authoritativeAnswers.add(rec);
_authoritativeAnswersBytes.write(byteArray, 0, byteArray.length);
} else {
throw new IOException("message full");
}
}
/**
* Add an additional answer to the record. Omit if there is no room.
*
* @param in
* @param rec
* @exception IOException
*/
public void addAdditionalAnswer(DNSIncoming in, DNSRecord rec) throws IOException {
MessageOutputStream record = new MessageOutputStream(512, this);
record.writeRecord(rec, 0);
byte[] byteArray = record.toByteArray();
if (byteArray.length < this.availableSpace()) {
_additionals.add(rec);
_additionalsAnswersBytes.write(byteArray, 0, byteArray.length);
} else {
throw new IOException("message full");
}
}
/**
* Builds the final message buffer to be send and returns it.
*
* @return bytes to send.
*/
public byte[] data() {
long now = System.currentTimeMillis(); // System.currentTimeMillis()
_names.clear();
MessageOutputStream message = new MessageOutputStream(_maxUDPPayload, this);
message.writeShort(_multicast ? 0 : this.getId());
message.writeShort(this.getFlags());
message.writeShort(this.getNumberOfQuestions());
message.writeShort(this.getNumberOfAnswers());
message.writeShort(this.getNumberOfAuthorities());
message.writeShort(this.getNumberOfAdditionals());
for (DNSQuestion question : _questions) {
message.writeQuestion(question);
}
for (DNSRecord record : _answers) {
message.writeRecord(record, now);
}
for (DNSRecord record : _authoritativeAnswers) {
message.writeRecord(record, now);
}
for (DNSRecord record : _additionals) {
message.writeRecord(record, now);
}
return message.toByteArray();
}
/**
* Debugging.
*/
String print(boolean dump) {
StringBuilder buf = new StringBuilder();
buf.append(this.print());
if (dump) {
buf.append(this.print(this.data()));
}
return buf.toString();
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append(isQuery() ? "dns[query:" : "dns[response:");
buf.append(" id=0x");
buf.append(Integer.toHexString(this.getId()));
if (this.getFlags() != 0) {
buf.append(", flags=0x");
buf.append(Integer.toHexString(this.getFlags()));
if (this.isResponse()) {
buf.append(":r");
}
if (this.isAuthoritativeAnswer()) {
buf.append(":aa");
}
if (this.isTruncated()) {
buf.append(":tc");
}
}
if (this.getNumberOfQuestions() > 0) {
buf.append(", questions=");
buf.append(this.getNumberOfQuestions());
}
if (this.getNumberOfAnswers() > 0) {
buf.append(", answers=");
buf.append(this.getNumberOfAnswers());
}
if (this.getNumberOfAuthorities() > 0) {
buf.append(", authorities=");
buf.append(this.getNumberOfAuthorities());
}
if (this.getNumberOfAdditionals() > 0) {
buf.append(", additionals=");
buf.append(this.getNumberOfAdditionals());
}
if (this.getNumberOfQuestions() > 0) {
buf.append("\nquestions:");
for (DNSQuestion question : _questions) {
buf.append("\n\t");
buf.append(question);
}
}
if (this.getNumberOfAnswers() > 0) {
buf.append("\nanswers:");
for (DNSRecord record : _answers) {
buf.append("\n\t");
buf.append(record);
}
}
if (this.getNumberOfAuthorities() > 0) {
buf.append("\nauthorities:");
for (DNSRecord record : _authoritativeAnswers) {
buf.append("\n\t");
buf.append(record);
}
}
if (this.getNumberOfAdditionals() > 0) {
buf.append("\nadditionals:");
for (DNSRecord record : _additionals) {
buf.append("\n\t");
buf.append(record);
}
}
buf.append("\nnames=");
buf.append(_names);
buf.append("]");
return buf.toString();
}
/**
* @return the maxUDPPayload
*/
public int getMaxUDPPayload() {
return this._maxUDPPayload;
}
}

View File

@ -0,0 +1,328 @@
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl;
import java.net.InetAddress;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jmdns.ServiceInfo;
import javax.jmdns.ServiceInfo.Fields;
import javax.jmdns.impl.JmDNSImpl.ServiceTypeEntry;
import javax.jmdns.impl.constants.DNSConstants;
import javax.jmdns.impl.constants.DNSRecordClass;
import javax.jmdns.impl.constants.DNSRecordType;
/**
* A DNS question.
*
* @author Arthur van Hoff, Pierre Frisch
*/
public class DNSQuestion extends DNSEntry {
private static Logger logger = Logger.getLogger(DNSQuestion.class.getName());
/**
* Address question.
*/
private static class DNS4Address extends DNSQuestion {
DNS4Address(String name, DNSRecordType type, DNSRecordClass recordClass, boolean unique) {
super(name, type, recordClass, unique);
}
@Override
public void addAnswers(JmDNSImpl jmDNSImpl, Set<DNSRecord> answers) {
DNSRecord answer = jmDNSImpl.getLocalHost().getDNSAddressRecord(this.getRecordType(), DNSRecordClass.UNIQUE, DNSConstants.DNS_TTL);
if (answer != null) {
answers.add(answer);
}
}
@Override
public boolean iAmTheOnlyOne(JmDNSImpl jmDNSImpl) {
String name = this.getName().toLowerCase();
return jmDNSImpl.getLocalHost().getName().equals(name) || jmDNSImpl.getServices().keySet().contains(name);
}
}
/**
* Address question.
*/
private static class DNS6Address extends DNSQuestion {
DNS6Address(String name, DNSRecordType type, DNSRecordClass recordClass, boolean unique) {
super(name, type, recordClass, unique);
}
@Override
public void addAnswers(JmDNSImpl jmDNSImpl, Set<DNSRecord> answers) {
DNSRecord answer = jmDNSImpl.getLocalHost().getDNSAddressRecord(this.getRecordType(), DNSRecordClass.UNIQUE, DNSConstants.DNS_TTL);
if (answer != null) {
answers.add(answer);
}
}
@Override
public boolean iAmTheOnlyOne(JmDNSImpl jmDNSImpl) {
String name = this.getName().toLowerCase();
return jmDNSImpl.getLocalHost().getName().equals(name) || jmDNSImpl.getServices().keySet().contains(name);
}
}
/**
* Host Information question.
*/
private static class HostInformation extends DNSQuestion {
HostInformation(String name, DNSRecordType type, DNSRecordClass recordClass, boolean unique) {
super(name, type, recordClass, unique);
}
}
/**
* Pointer question.
*/
private static class Pointer extends DNSQuestion {
Pointer(String name, DNSRecordType type, DNSRecordClass recordClass, boolean unique) {
super(name, type, recordClass, unique);
}
@Override
public void addAnswers(JmDNSImpl jmDNSImpl, Set<DNSRecord> answers) {
// find matching services
for (ServiceInfo serviceInfo : jmDNSImpl.getServices().values()) {
this.addAnswersForServiceInfo(jmDNSImpl, answers, (ServiceInfoImpl) serviceInfo);
}
if (this.isServicesDiscoveryMetaQuery()) {
for (String serviceType : jmDNSImpl.getServiceTypes().keySet()) {
ServiceTypeEntry typeEntry = jmDNSImpl.getServiceTypes().get(serviceType);
answers.add(new DNSRecord.Pointer("_services._dns-sd._udp.local.", DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE, DNSConstants.DNS_TTL, typeEntry.getType()));
}
} else if (this.isReverseLookup()) {
String ipValue = this.getQualifiedNameMap().get(Fields.Instance);
if ((ipValue != null) && (ipValue.length() > 0)) {
InetAddress address = jmDNSImpl.getLocalHost().getInetAddress();
String hostIPAddress = (address != null ? address.getHostAddress() : "");
if (ipValue.equalsIgnoreCase(hostIPAddress)) {
if (this.isV4ReverseLookup()) {
answers.add(jmDNSImpl.getLocalHost().getDNSReverseAddressRecord(DNSRecordType.TYPE_A, DNSRecordClass.NOT_UNIQUE, DNSConstants.DNS_TTL));
}
if (this.isV6ReverseLookup()) {
answers.add(jmDNSImpl.getLocalHost().getDNSReverseAddressRecord(DNSRecordType.TYPE_AAAA, DNSRecordClass.NOT_UNIQUE, DNSConstants.DNS_TTL));
}
}
}
} else if (this.isDomainDiscoveryQuery()) {
// FIXME [PJYF Nov 16 2010] We do not currently support domain discovery
}
}
}
/**
* Service question.
*/
private static class Service extends DNSQuestion {
Service(String name, DNSRecordType type, DNSRecordClass recordClass, boolean unique) {
super(name, type, recordClass, unique);
}
@Override
public void addAnswers(JmDNSImpl jmDNSImpl, Set<DNSRecord> answers) {
String loname = this.getName().toLowerCase();
if (jmDNSImpl.getLocalHost().getName().equalsIgnoreCase(loname)) {
// type = DNSConstants.TYPE_A;
answers.addAll(jmDNSImpl.getLocalHost().answers(this.getRecordClass(), this.isUnique(), DNSConstants.DNS_TTL));
return;
}
// Service type request
if (jmDNSImpl.getServiceTypes().containsKey(loname)) {
DNSQuestion question = new Pointer(this.getName(), DNSRecordType.TYPE_PTR, this.getRecordClass(), this.isUnique());
question.addAnswers(jmDNSImpl, answers);
return;
}
this.addAnswersForServiceInfo(jmDNSImpl, answers, (ServiceInfoImpl) jmDNSImpl.getServices().get(loname));
}
@Override
public boolean iAmTheOnlyOne(JmDNSImpl jmDNSImpl) {
String name = this.getName().toLowerCase();
return jmDNSImpl.getLocalHost().getName().equals(name) || jmDNSImpl.getServices().keySet().contains(name);
}
}
/**
* Text question.
*/
private static class Text extends DNSQuestion {
Text(String name, DNSRecordType type, DNSRecordClass recordClass, boolean unique) {
super(name, type, recordClass, unique);
}
@Override
public void addAnswers(JmDNSImpl jmDNSImpl, Set<DNSRecord> answers) {
this.addAnswersForServiceInfo(jmDNSImpl, answers, (ServiceInfoImpl) jmDNSImpl.getServices().get(this.getName().toLowerCase()));
}
@Override
public boolean iAmTheOnlyOne(JmDNSImpl jmDNSImpl) {
String name = this.getName().toLowerCase();
return jmDNSImpl.getLocalHost().getName().equals(name) || jmDNSImpl.getServices().keySet().contains(name);
}
}
/**
* AllRecords question.
*/
private static class AllRecords extends DNSQuestion {
AllRecords(String name, DNSRecordType type, DNSRecordClass recordClass, boolean unique) {
super(name, type, recordClass, unique);
}
@Override
public boolean isSameType(DNSEntry entry) {
// We match all non null entry
return (entry != null);
}
@Override
public void addAnswers(JmDNSImpl jmDNSImpl, Set<DNSRecord> answers) {
String loname = this.getName().toLowerCase();
if (jmDNSImpl.getLocalHost().getName().equalsIgnoreCase(loname)) {
// type = DNSConstants.TYPE_A;
answers.addAll(jmDNSImpl.getLocalHost().answers(this.getRecordClass(), this.isUnique(), DNSConstants.DNS_TTL));
return;
}
// Service type request
if (jmDNSImpl.getServiceTypes().containsKey(loname)) {
DNSQuestion question = new Pointer(this.getName(), DNSRecordType.TYPE_PTR, this.getRecordClass(), this.isUnique());
question.addAnswers(jmDNSImpl, answers);
return;
}
this.addAnswersForServiceInfo(jmDNSImpl, answers, (ServiceInfoImpl) jmDNSImpl.getServices().get(loname));
}
@Override
public boolean iAmTheOnlyOne(JmDNSImpl jmDNSImpl) {
String name = this.getName().toLowerCase();
return jmDNSImpl.getLocalHost().getName().equals(name) || jmDNSImpl.getServices().keySet().contains(name);
}
}
DNSQuestion(String name, DNSRecordType type, DNSRecordClass recordClass, boolean unique) {
super(name, type, recordClass, unique);
}
/**
* Create a question.
*
* @param name
* DNS name to be resolved
* @param type
* Record type to resolve
* @param recordClass
* Record class to resolve
* @param unique
* Request unicast response (Currently not supported in this implementation)
* @return new question
*/
public static DNSQuestion newQuestion(String name, DNSRecordType type, DNSRecordClass recordClass, boolean unique) {
switch (type) {
case TYPE_A:
return new DNS4Address(name, type, recordClass, unique);
case TYPE_A6:
return new DNS6Address(name, type, recordClass, unique);
case TYPE_AAAA:
return new DNS6Address(name, type, recordClass, unique);
case TYPE_ANY:
return new AllRecords(name, type, recordClass, unique);
case TYPE_HINFO:
return new HostInformation(name, type, recordClass, unique);
case TYPE_PTR:
return new Pointer(name, type, recordClass, unique);
case TYPE_SRV:
return new Service(name, type, recordClass, unique);
case TYPE_TXT:
return new Text(name, type, recordClass, unique);
default:
return new DNSQuestion(name, type, recordClass, unique);
}
}
/**
* Check if this question is answered by a given DNS record.
*/
boolean answeredBy(DNSEntry rec) {
return this.isSameRecordClass(rec) && this.isSameType(rec) && this.getName().equals(rec.getName());
}
/**
* Adds answers to the list for our question.
*
* @param jmDNSImpl
* DNS holding the records
* @param answers
* List of previous answer to append.
*/
public void addAnswers(JmDNSImpl jmDNSImpl, Set<DNSRecord> answers) {
// By default we do nothing
}
protected void addAnswersForServiceInfo(JmDNSImpl jmDNSImpl, Set<DNSRecord> answers, ServiceInfoImpl info) {
if ((info != null) && info.isAnnounced()) {
if (this.getName().equalsIgnoreCase(info.getQualifiedName()) || this.getName().equalsIgnoreCase(info.getType()) || this.getName().equalsIgnoreCase(info.getTypeWithSubtype())) {
answers.addAll(jmDNSImpl.getLocalHost().answers(this.getRecordClass(), DNSRecordClass.UNIQUE, DNSConstants.DNS_TTL));
answers.addAll(info.answers(this.getRecordClass(), DNSRecordClass.UNIQUE, DNSConstants.DNS_TTL, jmDNSImpl.getLocalHost()));
}
if (logger.isLoggable(Level.FINER)) {
logger.finer(jmDNSImpl.getName() + " DNSQuestion(" + this.getName() + ").addAnswersForServiceInfo(): info: " + info + "\n" + answers);
}
}
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSEntry#isStale(long)
*/
@Override
public boolean isStale(long now) {
return false;
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSEntry#isExpired(long)
*/
@Override
public boolean isExpired(long now) {
return false;
}
/**
* Checks if we are the only to be able to answer that question.
*
* @param jmDNSImpl
* DNS holding the records
* @return <code>true</code> if we are the only one with the answer to the question, <code>false</code> otherwise.
*/
public boolean iAmTheOnlyOne(JmDNSImpl jmDNSImpl) {
return false;
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSEntry#toString(java.lang.StringBuilder)
*/
@Override
public void toString(StringBuilder aLog) {
// do nothing
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,572 @@
// Licensed under Apache License version 2.0
package javax.jmdns.impl;
import java.io.IOException;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jmdns.impl.constants.DNSState;
import javax.jmdns.impl.tasks.DNSTask;
/**
* Sets of methods to manage the state machine.<br/>
* <b>Implementation note:</b> This interface is accessed from multiple threads. The implementation must be thread safe.
*
* @author Pierre Frisch
*/
public interface DNSStatefulObject {
/**
* This class define a semaphore. On this multiple threads can wait the arrival of one event. Thread wait for a maximum defined by the timeout.
* <p>
* Implementation note: this class is based on {@link java.util.concurrent.Semaphore} so that they can be released by the timeout timer.
* </p>
*
* @author Pierre Frisch
*/
public static final class DNSStatefulObjectSemaphore {
private static Logger logger = Logger.getLogger(DNSStatefulObjectSemaphore.class.getName());
private final String _name;
private final ConcurrentMap<Thread, Semaphore> _semaphores;
/**
* @param name
* Semaphore name for debugging purposes.
*/
public DNSStatefulObjectSemaphore(String name) {
super();
_name = name;
_semaphores = new ConcurrentHashMap<Thread, Semaphore>(50);
}
/**
* Blocks the current thread until the event arrives or the timeout expires.
*
* @param timeout
* wait period for the event
*/
public void waitForEvent(long timeout) {
Thread thread = Thread.currentThread();
Semaphore semaphore = _semaphores.get(thread);
if (semaphore == null) {
semaphore = new Semaphore(1, true);
semaphore.drainPermits();
_semaphores.putIfAbsent(thread, semaphore);
}
semaphore = _semaphores.get(thread);
try {
semaphore.tryAcquire(timeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException exception) {
logger.log(Level.FINER, "Exception ", exception);
}
}
/**
* Signals the semaphore when the event arrives.
*/
public void signalEvent() {
Collection<Semaphore> semaphores = _semaphores.values();
for (Semaphore semaphore : semaphores) {
semaphore.release();
semaphores.remove(semaphore);
}
}
@Override
public String toString() {
StringBuilder aLog = new StringBuilder(1000);
aLog.append("Semaphore: ");
aLog.append(this._name);
if (_semaphores.size() == 0) {
aLog.append(" no semaphores.");
} else {
aLog.append(" semaphores:\n");
for (Thread thread : _semaphores.keySet()) {
aLog.append("\tThread: ");
aLog.append(thread.getName());
aLog.append(' ');
aLog.append(_semaphores.get(thread));
aLog.append('\n');
}
}
return aLog.toString();
}
}
public static class DefaultImplementation extends ReentrantLock implements DNSStatefulObject {
private static Logger logger = Logger.getLogger(DefaultImplementation.class.getName());
private static final long serialVersionUID = -3264781576883412227L;
private volatile JmDNSImpl _dns;
protected volatile DNSTask _task;
protected volatile DNSState _state;
private final DNSStatefulObjectSemaphore _announcing;
private final DNSStatefulObjectSemaphore _canceling;
public DefaultImplementation() {
super();
_dns = null;
_task = null;
_state = DNSState.PROBING_1;
_announcing = new DNSStatefulObjectSemaphore("Announce");
_canceling = new DNSStatefulObjectSemaphore("Cancel");
}
/**
* {@inheritDoc}
*/
@Override
public JmDNSImpl getDns() {
return this._dns;
}
protected void setDns(JmDNSImpl dns) {
this._dns = dns;
}
/**
* {@inheritDoc}
*/
@Override
public void associateWithTask(DNSTask task, DNSState state) {
if (this._task == null && this._state == state) {
this.lock();
try {
if (this._task == null && this._state == state) {
this.setTask(task);
}
} finally {
this.unlock();
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void removeAssociationWithTask(DNSTask task) {
if (this._task == task) {
this.lock();
try {
if (this._task == task) {
this.setTask(null);
}
} finally {
this.unlock();
}
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAssociatedWithTask(DNSTask task, DNSState state) {
this.lock();
try {
return this._task == task && this._state == state;
} finally {
this.unlock();
}
}
protected void setTask(DNSTask task) {
this._task = task;
}
/**
* @param state
* the state to set
*/
protected void setState(DNSState state) {
this.lock();
try {
this._state = state;
if (this.isAnnounced()) {
_announcing.signalEvent();
}
if (this.isCanceled()) {
_canceling.signalEvent();
// clear any waiting announcing
_announcing.signalEvent();
}
} finally {
this.unlock();
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean advanceState(DNSTask task) {
boolean result = true;
if (this._task == task) {
this.lock();
try {
if (this._task == task) {
this.setState(this._state.advance());
} else {
logger.warning("Trying to advance state whhen not the owner. owner: " + this._task + " perpetrator: " + task);
}
} finally {
this.unlock();
}
}
return result;
}
/**
* {@inheritDoc}
*/
@Override
public boolean revertState() {
boolean result = true;
if (!this.willCancel()) {
this.lock();
try {
if (!this.willCancel()) {
this.setState(this._state.revert());
this.setTask(null);
}
} finally {
this.unlock();
}
}
return result;
}
/**
* {@inheritDoc}
*/
@Override
public boolean cancelState() {
boolean result = false;
if (!this.willCancel()) {
this.lock();
try {
if (!this.willCancel()) {
this.setState(DNSState.CANCELING_1);
this.setTask(null);
result = true;
}
} finally {
this.unlock();
}
}
return result;
}
/**
* {@inheritDoc}
*/
@Override
public boolean closeState() {
boolean result = false;
if (!this.willClose()) {
this.lock();
try {
if (!this.willClose()) {
this.setState(DNSState.CLOSING);
this.setTask(null);
result = true;
}
} finally {
this.unlock();
}
}
return result;
}
/**
* {@inheritDoc}
*/
@Override
public boolean recoverState() {
boolean result = false;
this.lock();
try {
this.setState(DNSState.PROBING_1);
this.setTask(null);
} finally {
this.unlock();
}
return result;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isProbing() {
return this._state.isProbing();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAnnouncing() {
return this._state.isAnnouncing();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAnnounced() {
return this._state.isAnnounced();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isCanceling() {
return this._state.isCanceling();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isCanceled() {
return this._state.isCanceled();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isClosing() {
return this._state.isClosing();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isClosed() {
return this._state.isClosed();
}
private boolean willCancel() {
return this._state.isCanceled() || this._state.isCanceling();
}
private boolean willClose() {
return this._state.isClosed() || this._state.isClosing();
}
/**
* {@inheritDoc}
*/
@Override
public boolean waitForAnnounced(long timeout) {
if (!this.isAnnounced() && !this.willCancel()) {
_announcing.waitForEvent(timeout + 10);
}
if (!this.isAnnounced()) {
// When we run multihomed we need to check twice
_announcing.waitForEvent(10);
if (!this.isAnnounced()) {
if (this.willCancel() || this.willClose()) {
logger.fine("Wait for announced cancelled: " + this);
} else {
logger.warning("Wait for announced timed out: " + this);
}
}
}
return this.isAnnounced();
}
/**
* {@inheritDoc}
*/
@Override
public boolean waitForCanceled(long timeout) {
if (!this.isCanceled()) {
_canceling.waitForEvent(timeout);
}
if (!this.isCanceled()) {
// When we run multihomed we need to check twice
_canceling.waitForEvent(10);
if (!this.isCanceled() && !this.willClose()) {
logger.warning("Wait for canceled timed out: " + this);
}
}
return this.isCanceled();
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
try {
return (_dns != null ? "DNS: " + _dns.getName() + " [" + _dns.getInetAddress() + "]" : "NO DNS") + " state: " + _state + " task: " + _task;
} catch (IOException exception) {
return (_dns != null ? "DNS: " + _dns.getName() : "NO DNS") + " state: " + _state + " task: " + _task;
}
}
}
/**
* Returns the DNS associated with this object.
*
* @return DNS resolver
*/
public JmDNSImpl getDns();
/**
* Sets the task associated with this Object.
*
* @param task
* associated task
* @param state
* state of the task
*/
public void associateWithTask(DNSTask task, DNSState state);
/**
* Remove the association of the task with this Object.
*
* @param task
* associated task
*/
public void removeAssociationWithTask(DNSTask task);
/**
* Checks if this object is associated with the task and in the same state.
*
* @param task
* associated task
* @param state
* state of the task
* @return <code>true</code> is the task is associated with this object, <code>false</code> otherwise.
*/
public boolean isAssociatedWithTask(DNSTask task, DNSState state);
/**
* Sets the state and notifies all objects that wait on the ServiceInfo.
*
* @param task
* associated task
* @return <code>true</code if the state was changed by this thread, <code>false</code> otherwise.
* @see DNSState#advance()
*/
public boolean advanceState(DNSTask task);
/**
* Sets the state and notifies all objects that wait on the ServiceInfo.
*
* @return <code>true</code if the state was changed by this thread, <code>false</code> otherwise.
* @see DNSState#revert()
*/
public boolean revertState();
/**
* Sets the state and notifies all objects that wait on the ServiceInfo.
*
* @return <code>true</code if the state was changed by this thread, <code>false</code> otherwise.
*/
public boolean cancelState();
/**
* Sets the state and notifies all objects that wait on the ServiceInfo.
*
* @return <code>true</code if the state was changed by this thread, <code>false</code> otherwise.
*/
public boolean closeState();
/**
* Sets the state and notifies all objects that wait on the ServiceInfo.
*
* @return <code>true</code if the state was changed by this thread, <code>false</code> otherwise.
*/
public boolean recoverState();
/**
* Returns true, if this is a probing state.
*
* @return <code>true</code> if probing state, <code>false</code> otherwise
*/
public boolean isProbing();
/**
* Returns true, if this is an announcing state.
*
* @return <code>true</code> if announcing state, <code>false</code> otherwise
*/
public boolean isAnnouncing();
/**
* Returns true, if this is an announced state.
*
* @return <code>true</code> if announced state, <code>false</code> otherwise
*/
public boolean isAnnounced();
/**
* Returns true, if this is a canceling state.
*
* @return <code>true</code> if canceling state, <code>false</code> otherwise
*/
public boolean isCanceling();
/**
* Returns true, if this is a canceled state.
*
* @return <code>true</code> if canceled state, <code>false</code> otherwise
*/
public boolean isCanceled();
/**
* Returns true, if this is a closing state.
*
* @return <code>true</code> if closing state, <code>false</code> otherwise
*/
public boolean isClosing();
/**
* Returns true, if this is a closed state.
*
* @return <code>true</code> if closed state, <code>false</code> otherwise
*/
public boolean isClosed();
/**
* Waits for the object to be announced.
*
* @param timeout
* the maximum time to wait in milliseconds.
* @return <code>true</code> if the object is announced, <code>false</code> otherwise
*/
public boolean waitForAnnounced(long timeout);
/**
* Waits for the object to be canceled.
*
* @param timeout
* the maximum time to wait in milliseconds.
* @return <code>true</code> if the object is canceled, <code>false</code> otherwise
*/
public boolean waitForCanceled(long timeout);
}

View File

@ -0,0 +1,474 @@
/**
*
*/
package javax.jmdns.impl;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicReference;
import javax.jmdns.impl.tasks.RecordReaper;
import javax.jmdns.impl.tasks.Responder;
import javax.jmdns.impl.tasks.resolver.ServiceInfoResolver;
import javax.jmdns.impl.tasks.resolver.ServiceResolver;
import javax.jmdns.impl.tasks.resolver.TypeResolver;
import javax.jmdns.impl.tasks.state.Announcer;
import javax.jmdns.impl.tasks.state.Canceler;
import javax.jmdns.impl.tasks.state.Prober;
import javax.jmdns.impl.tasks.state.Renewer;
/**
* This class is used by JmDNS to start the various task required to run the DNS discovery. This interface is only there in order to support MANET modifications.
* <p>
* <b>Note: </b> This is not considered as part of the general public API of JmDNS.
* </p>
*
* @author Pierre Frisch
*/
public interface DNSTaskStarter {
/**
* DNSTaskStarter.Factory enable the creation of new instance of DNSTaskStarter.
*/
public static final class Factory {
private static volatile Factory _instance;
private final ConcurrentMap<JmDNSImpl, DNSTaskStarter> _instances;
/**
* This interface defines a delegate to the DNSTaskStarter class to enable subclassing.
*/
public static interface ClassDelegate {
/**
* Allows the delegate the opportunity to construct and return a different DNSTaskStarter.
*
* @param jmDNSImpl
* jmDNS instance
* @return Should return a new DNSTaskStarter Object.
* @see #classDelegate()
* @see #setClassDelegate(ClassDelegate anObject)
*/
public DNSTaskStarter newDNSTaskStarter(JmDNSImpl jmDNSImpl);
}
private static final AtomicReference<Factory.ClassDelegate> _databaseClassDelegate = new AtomicReference<Factory.ClassDelegate>();
private Factory() {
super();
_instances = new ConcurrentHashMap<JmDNSImpl, DNSTaskStarter>(20);
}
/**
* Assigns <code>delegate</code> as DNSTaskStarter's class delegate. The class delegate is optional.
*
* @param delegate
* The object to set as DNSTaskStarter's class delegate.
* @see #classDelegate()
* @see DNSTaskStarter.Factory.ClassDelegate
*/
public static void setClassDelegate(Factory.ClassDelegate delegate) {
_databaseClassDelegate.set(delegate);
}
/**
* Returns DNSTaskStarter's class delegate.
*
* @return DNSTaskStarter's class delegate.
* @see #setClassDelegate(ClassDelegate anObject)
* @see DNSTaskStarter.Factory.ClassDelegate
*/
public static Factory.ClassDelegate classDelegate() {
return _databaseClassDelegate.get();
}
/**
* Returns a new instance of DNSTaskStarter using the class delegate if it exists.
*
* @param jmDNSImpl
* jmDNS instance
* @return new instance of DNSTaskStarter
*/
protected static DNSTaskStarter newDNSTaskStarter(JmDNSImpl jmDNSImpl) {
DNSTaskStarter instance = null;
Factory.ClassDelegate delegate = _databaseClassDelegate.get();
if (delegate != null) {
instance = delegate.newDNSTaskStarter(jmDNSImpl);
}
return (instance != null ? instance : new DNSTaskStarterImpl(jmDNSImpl));
}
/**
* Return the instance of the DNSTaskStarter Factory.
*
* @return DNSTaskStarter Factory
*/
public static Factory getInstance() {
if (_instance == null) {
synchronized (DNSTaskStarter.Factory.class) {
if (_instance == null) {
_instance = new Factory();
}
}
}
return _instance;
}
/**
* Return the instance of the DNSTaskStarter for the JmDNS.
*
* @param jmDNSImpl
* jmDNS instance
* @return the DNSTaskStarter
*/
public DNSTaskStarter getStarter(JmDNSImpl jmDNSImpl) {
DNSTaskStarter starter = _instances.get(jmDNSImpl);
if (starter == null) {
_instances.putIfAbsent(jmDNSImpl, newDNSTaskStarter(jmDNSImpl));
starter = _instances.get(jmDNSImpl);
}
return starter;
}
/**
* Dispose of the DNSTaskStarter instance associated with this JmDNS.
*
* @param jmDNSImpl
* jmDNS instance
*/
public void disposeStarter(JmDNSImpl jmDNSImpl) {
_instances.remove(jmDNSImpl);
}
}
public static final class DNSTaskStarterImpl implements DNSTaskStarter {
private final JmDNSImpl _jmDNSImpl;
/**
* The timer is used to dispatch all outgoing messages of JmDNS. It is also used to dispatch maintenance tasks for the DNS cache.
*/
private final Timer _timer;
/**
* The timer is used to dispatch maintenance tasks for the DNS cache.
*/
private final Timer _stateTimer;
public static class StarterTimer extends Timer {
// This is needed because in some case we cancel the timers before all the task have finished running and in some case they will try to reschedule
private volatile boolean _cancelled;
/**
*
*/
public StarterTimer() {
super();
_cancelled = false;
}
/**
* @param isDaemon
*/
public StarterTimer(boolean isDaemon) {
super(isDaemon);
_cancelled = false;
}
/**
* @param name
* @param isDaemon
*/
public StarterTimer(String name, boolean isDaemon) {
super(name, isDaemon);
_cancelled = false;
}
/**
* @param name
*/
public StarterTimer(String name) {
super(name);
_cancelled = false;
}
/*
* (non-Javadoc)
* @see java.util.Timer#cancel()
*/
@Override
public synchronized void cancel() {
if (_cancelled) return;
_cancelled = true;
super.cancel();
}
/*
* (non-Javadoc)
* @see java.util.Timer#schedule(java.util.TimerTask, long)
*/
@Override
public synchronized void schedule(TimerTask task, long delay) {
if (_cancelled) return;
super.schedule(task, delay);
}
/*
* (non-Javadoc)
* @see java.util.Timer#schedule(java.util.TimerTask, java.util.Date)
*/
@Override
public synchronized void schedule(TimerTask task, Date time) {
if (_cancelled) return;
super.schedule(task, time);
}
/*
* (non-Javadoc)
* @see java.util.Timer#schedule(java.util.TimerTask, long, long)
*/
@Override
public synchronized void schedule(TimerTask task, long delay, long period) {
if (_cancelled) return;
super.schedule(task, delay, period);
}
/*
* (non-Javadoc)
* @see java.util.Timer#schedule(java.util.TimerTask, java.util.Date, long)
*/
@Override
public synchronized void schedule(TimerTask task, Date firstTime, long period) {
if (_cancelled) return;
super.schedule(task, firstTime, period);
}
/*
* (non-Javadoc)
* @see java.util.Timer#scheduleAtFixedRate(java.util.TimerTask, long, long)
*/
@Override
public synchronized void scheduleAtFixedRate(TimerTask task, long delay, long period) {
if (_cancelled) return;
super.scheduleAtFixedRate(task, delay, period);
}
/*
* (non-Javadoc)
* @see java.util.Timer#scheduleAtFixedRate(java.util.TimerTask, java.util.Date, long)
*/
@Override
public synchronized void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) {
if (_cancelled) return;
super.scheduleAtFixedRate(task, firstTime, period);
}
}
public DNSTaskStarterImpl(JmDNSImpl jmDNSImpl) {
super();
_jmDNSImpl = jmDNSImpl;
_timer = new StarterTimer("JmDNS(" + _jmDNSImpl.getName() + ").Timer", true);
_stateTimer = new StarterTimer("JmDNS(" + _jmDNSImpl.getName() + ").State.Timer", true);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#purgeTimer()
*/
@Override
public void purgeTimer() {
_timer.purge();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#purgeStateTimer()
*/
@Override
public void purgeStateTimer() {
_stateTimer.purge();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#cancelTimer()
*/
@Override
public void cancelTimer() {
_timer.cancel();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#cancelStateTimer()
*/
@Override
public void cancelStateTimer() {
_stateTimer.cancel();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startProber()
*/
@Override
public void startProber() {
new Prober(_jmDNSImpl).start(_stateTimer);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startAnnouncer()
*/
@Override
public void startAnnouncer() {
new Announcer(_jmDNSImpl).start(_stateTimer);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startRenewer()
*/
@Override
public void startRenewer() {
new Renewer(_jmDNSImpl).start(_stateTimer);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startCanceler()
*/
@Override
public void startCanceler() {
new Canceler(_jmDNSImpl).start(_stateTimer);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startReaper()
*/
@Override
public void startReaper() {
new RecordReaper(_jmDNSImpl).start(_timer);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startServiceInfoResolver(javax.jmdns.impl.ServiceInfoImpl)
*/
@Override
public void startServiceInfoResolver(ServiceInfoImpl info) {
new ServiceInfoResolver(_jmDNSImpl, info).start(_timer);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startTypeResolver()
*/
@Override
public void startTypeResolver() {
new TypeResolver(_jmDNSImpl).start(_timer);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startServiceResolver(java.lang.String)
*/
@Override
public void startServiceResolver(String type) {
new ServiceResolver(_jmDNSImpl, type).start(_timer);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.DNSTaskStarter#startResponder(javax.jmdns.impl.DNSIncoming, int)
*/
@Override
public void startResponder(DNSIncoming in, int port) {
new Responder(_jmDNSImpl, in, port).start(_timer);
}
}
/**
* Purge the general task timer
*/
public void purgeTimer();
/**
* Purge the state task timer
*/
public void purgeStateTimer();
/**
* Cancel the generals task timer
*/
public void cancelTimer();
/**
* Cancel the state task timer
*/
public void cancelStateTimer();
/**
* Start a new prober task
*/
public void startProber();
/**
* Start a new announcer task
*/
public void startAnnouncer();
/**
* Start a new renewer task
*/
public void startRenewer();
/**
* Start a new canceler task
*/
public void startCanceler();
/**
* Start a new reaper task. There is only supposed to be one reaper running at a time.
*/
public void startReaper();
/**
* Start a new service info resolver task
*
* @param info
* service info to resolve
*/
public void startServiceInfoResolver(ServiceInfoImpl info);
/**
* Start a new service type resolver task
*/
public void startTypeResolver();
/**
* Start a new service resolver task
*
* @param type
* service type to resolve
*/
public void startServiceResolver(String type);
/**
* Start a new responder task
*
* @param in
* incoming message
* @param port
* incoming port
*/
public void startResponder(DNSIncoming in, int port);
}

View File

@ -0,0 +1,434 @@
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jmdns.NetworkTopologyDiscovery;
import javax.jmdns.impl.constants.DNSConstants;
import javax.jmdns.impl.constants.DNSRecordClass;
import javax.jmdns.impl.constants.DNSRecordType;
import javax.jmdns.impl.constants.DNSState;
import javax.jmdns.impl.tasks.DNSTask;
/**
* HostInfo information on the local host to be able to cope with change of addresses.
*
* @author Pierre Frisch, Werner Randelshofer
*/
public class HostInfo implements DNSStatefulObject {
private static Logger logger = Logger.getLogger(HostInfo.class.getName());
protected String _name;
protected InetAddress _address;
protected NetworkInterface _interfaze;
private final HostInfoState _state;
private final static class HostInfoState extends DNSStatefulObject.DefaultImplementation {
private static final long serialVersionUID = -8191476803620402088L;
/**
* @param dns
*/
public HostInfoState(JmDNSImpl dns) {
super();
this.setDns(dns);
}
}
/**
* @param address
* IP address to bind
* @param dns
* JmDNS instance
* @param jmdnsName
* JmDNS name
* @return new HostInfo
*/
public static HostInfo newHostInfo(InetAddress address, JmDNSImpl dns, String jmdnsName) {
HostInfo localhost = null;
String aName = (jmdnsName != null ? jmdnsName : "");
InetAddress addr = address;
try {
if (addr == null) {
String ip = System.getProperty("net.mdns.interface");
if (ip != null) {
addr = InetAddress.getByName(ip);
} else {
addr = InetAddress.getLocalHost();
if (addr.isLoopbackAddress()) {
// Find local address that isn't a loopback address
InetAddress[] addresses = NetworkTopologyDiscovery.Factory.getInstance().getInetAddresses();
if (addresses.length > 0) {
addr = addresses[0];
}
}
}
if (addr.isLoopbackAddress()) {
logger.warning("Could not find any address beside the loopback.");
}
}
if (aName.length() == 0) {
aName = addr.getHostName();
}
if (aName.contains("in-addr.arpa") || (aName.equals(addr.getHostAddress()))) {
aName = ((jmdnsName != null) && (jmdnsName.length() > 0) ? jmdnsName : addr.getHostAddress());
}
} catch (final IOException e) {
logger.log(Level.WARNING, "Could not intialize the host network interface on " + address + "because of an error: " + e.getMessage(), e);
// This is only used for running unit test on Debian / Ubuntu
addr = loopbackAddress();
aName = ((jmdnsName != null) && (jmdnsName.length() > 0) ? jmdnsName : "computer");
}
// A host name with "." is illegal. so strip off everything and append .local.
// We also need to be carefull that the .local may already be there
int index = aName.indexOf(".local");
if (index > 0) {
aName = aName.substring(0, index);
}
aName = aName.replace('.', '-');
aName += ".local.";
localhost = new HostInfo(addr, aName, dns);
return localhost;
}
private static InetAddress loopbackAddress() {
try {
return InetAddress.getByName(null);
} catch (UnknownHostException exception) {
return null;
}
}
private HostInfo(final InetAddress address, final String name, final JmDNSImpl dns) {
super();
this._state = new HostInfoState(dns);
this._address = address;
this._name = name;
if (address != null) {
try {
_interfaze = NetworkInterface.getByInetAddress(address);
} catch (Exception exception) {
logger.log(Level.SEVERE, "LocalHostInfo() exception ", exception);
}
}
}
public String getName() {
return _name;
}
public InetAddress getInetAddress() {
return _address;
}
Inet4Address getInet4Address() {
if (this.getInetAddress() instanceof Inet4Address) {
return (Inet4Address) _address;
}
return null;
}
Inet6Address getInet6Address() {
if (this.getInetAddress() instanceof Inet6Address) {
return (Inet6Address) _address;
}
return null;
}
public NetworkInterface getInterface() {
return _interfaze;
}
public boolean conflictWithRecord(DNSRecord.Address record) {
DNSRecord.Address hostAddress = this.getDNSAddressRecord(record.getRecordType(), record.isUnique(), DNSConstants.DNS_TTL);
if (hostAddress != null) {
return hostAddress.sameType(record) && hostAddress.sameName(record) && (!hostAddress.sameValue(record));
}
return false;
}
synchronized String incrementHostName() {
_name = NameRegister.Factory.getRegistry().incrementName(this.getInetAddress(), _name, NameRegister.NameType.HOST);
return _name;
}
boolean shouldIgnorePacket(DatagramPacket packet) {
boolean result = false;
if (this.getInetAddress() != null) {
InetAddress from = packet.getAddress();
if (from != null) {
if ((this.getInetAddress().isLinkLocalAddress() || this.getInetAddress().isMCLinkLocal()) && (!from.isLinkLocalAddress())) {
// A host sending Multicast DNS queries to a link-local destination
// address (including the 224.0.0.251 and FF02::FB link-local multicast
// addresses) MUST only accept responses to that query that originate
// from the local link, and silently discard any other response packets.
// Without this check, it could be possible for remote rogue hosts to
// send spoof answer packets (perhaps unicast to the victim host) which
// the receiving machine could misinterpret as having originated on the
// local link.
result = true;
}
// if (from.isLinkLocalAddress() && (!this.getInetAddress().isLinkLocalAddress())) {
// // Ignore linklocal packets on regular interfaces, unless this is
// // also a linklocal interface. This is to avoid duplicates. This is
// // a terrible hack caused by the lack of an API to get the address
// // of the interface on which the packet was received.
// result = true;
// }
if (from.isLoopbackAddress() && (!this.getInetAddress().isLoopbackAddress())) {
// Ignore loopback packets on a regular interface unless this is also a loopback interface.
result = true;
}
}
}
return result;
}
DNSRecord.Address getDNSAddressRecord(DNSRecordType type, boolean unique, int ttl) {
switch (type) {
case TYPE_A:
return this.getDNS4AddressRecord(unique, ttl);
case TYPE_A6:
case TYPE_AAAA:
return this.getDNS6AddressRecord(unique, ttl);
default:
}
return null;
}
private DNSRecord.Address getDNS4AddressRecord(boolean unique, int ttl) {
if (this.getInetAddress() instanceof Inet4Address) {
return new DNSRecord.IPv4Address(this.getName(), DNSRecordClass.CLASS_IN, unique, ttl, this.getInetAddress());
}
return null;
}
private DNSRecord.Address getDNS6AddressRecord(boolean unique, int ttl) {
if (this.getInetAddress() instanceof Inet6Address) {
return new DNSRecord.IPv6Address(this.getName(), DNSRecordClass.CLASS_IN, unique, ttl, this.getInetAddress());
}
return null;
}
DNSRecord.Pointer getDNSReverseAddressRecord(DNSRecordType type, boolean unique, int ttl) {
switch (type) {
case TYPE_A:
return this.getDNS4ReverseAddressRecord(unique, ttl);
case TYPE_A6:
case TYPE_AAAA:
return this.getDNS6ReverseAddressRecord(unique, ttl);
default:
}
return null;
}
private DNSRecord.Pointer getDNS4ReverseAddressRecord(boolean unique, int ttl) {
if (this.getInetAddress() instanceof Inet4Address) {
return new DNSRecord.Pointer(this.getInetAddress().getHostAddress() + ".in-addr.arpa.", DNSRecordClass.CLASS_IN, unique, ttl, this.getName());
}
return null;
}
private DNSRecord.Pointer getDNS6ReverseAddressRecord(boolean unique, int ttl) {
if (this.getInetAddress() instanceof Inet6Address) {
return new DNSRecord.Pointer(this.getInetAddress().getHostAddress() + ".ip6.arpa.", DNSRecordClass.CLASS_IN, unique, ttl, this.getName());
}
return null;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(1024);
buf.append("local host info[");
buf.append(getName() != null ? getName() : "no name");
buf.append(", ");
buf.append(getInterface() != null ? getInterface().getDisplayName() : "???");
buf.append(":");
buf.append(getInetAddress() != null ? getInetAddress().getHostAddress() : "no address");
buf.append(", ");
buf.append(_state);
buf.append("]");
return buf.toString();
}
public Collection<DNSRecord> answers(DNSRecordClass recordClass, boolean unique, int ttl) {
List<DNSRecord> list = new ArrayList<DNSRecord>();
DNSRecord answer = this.getDNS4AddressRecord(unique, ttl);
if ((answer != null) && answer.matchRecordClass(recordClass)) {
list.add(answer);
}
answer = this.getDNS6AddressRecord(unique, ttl);
if ((answer != null) && answer.matchRecordClass(recordClass)) {
list.add(answer);
}
return list;
}
/**
* {@inheritDoc}
*/
@Override
public JmDNSImpl getDns() {
return this._state.getDns();
}
/**
* {@inheritDoc}
*/
@Override
public boolean advanceState(DNSTask task) {
return this._state.advanceState(task);
}
/**
* {@inheritDoc}
*/
@Override
public void removeAssociationWithTask(DNSTask task) {
this._state.removeAssociationWithTask(task);
}
/**
* {@inheritDoc}
*/
@Override
public boolean revertState() {
return this._state.revertState();
}
/**
* {@inheritDoc}
*/
@Override
public void associateWithTask(DNSTask task, DNSState state) {
this._state.associateWithTask(task, state);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAssociatedWithTask(DNSTask task, DNSState state) {
return this._state.isAssociatedWithTask(task, state);
}
/**
* {@inheritDoc}
*/
@Override
public boolean cancelState() {
return this._state.cancelState();
}
/**
* {@inheritDoc}
*/
@Override
public boolean closeState() {
return this._state.closeState();
}
/**
* {@inheritDoc}
*/
@Override
public boolean recoverState() {
return this._state.recoverState();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isProbing() {
return this._state.isProbing();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAnnouncing() {
return this._state.isAnnouncing();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isAnnounced() {
return this._state.isAnnounced();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isCanceling() {
return this._state.isCanceling();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isCanceled() {
return this._state.isCanceled();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isClosing() {
return this._state.isClosing();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isClosed() {
return this._state.isClosed();
}
/**
* {@inheritDoc}
*/
@Override
public boolean waitForAnnounced(long timeout) {
return _state.waitForAnnounced(timeout);
}
/**
* {@inheritDoc}
*/
@Override
public boolean waitForCanceled(long timeout) {
if (_address == null) {
// No need to wait this was never announced.
return true;
}
return _state.waitForCanceled(timeout);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,788 @@
/**
*
*/
package javax.jmdns.impl;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jmdns.JmDNS;
import javax.jmdns.JmmDNS;
import javax.jmdns.NetworkTopologyDiscovery;
import javax.jmdns.NetworkTopologyEvent;
import javax.jmdns.NetworkTopologyListener;
import javax.jmdns.ServiceInfo;
import javax.jmdns.ServiceListener;
import javax.jmdns.ServiceTypeListener;
import javax.jmdns.impl.constants.DNSConstants;
import javax.jmdns.impl.util.NamedThreadFactory;
/**
* This class enable multihoming mDNS. It will open a mDNS per IP address of the machine.
*
* @author C&eacute;drik Lime, Pierre Frisch
*/
public class JmmDNSImpl implements JmmDNS, NetworkTopologyListener, ServiceInfoImpl.Delegate {
private static Logger logger = Logger.getLogger(JmmDNSImpl.class.getName());
private final Set<NetworkTopologyListener> _networkListeners;
/**
* Every JmDNS created.
*/
private final ConcurrentMap<InetAddress, JmDNS> _knownMDNS;
/**
* This enable the service info text update.
*/
private final ConcurrentMap<String, ServiceInfo> _services;
/**
* List of registered services
*/
private final Set<String> _serviceTypes;
/**
* Holds instances of ServiceListener's. Keys are Strings holding a fully qualified service type. Values are LinkedList's of ServiceListener's.
*/
private final ConcurrentMap<String, List<ServiceListener>> _serviceListeners;
/**
* Holds instances of ServiceTypeListener's.
*/
private final Set<ServiceTypeListener> _typeListeners;
private final ExecutorService _listenerExecutor;
private final ExecutorService _jmDNSExecutor;
private final Timer _timer;
private final AtomicBoolean _isClosing;
private final AtomicBoolean _closed;
/**
*
*/
public JmmDNSImpl() {
super();
_networkListeners = Collections.synchronizedSet(new HashSet<NetworkTopologyListener>());
_knownMDNS = new ConcurrentHashMap<InetAddress, JmDNS>();
_services = new ConcurrentHashMap<String, ServiceInfo>(20);
_listenerExecutor = Executors.newSingleThreadExecutor(new NamedThreadFactory("JmmDNS Listeners"));
_jmDNSExecutor = Executors.newCachedThreadPool(new NamedThreadFactory("JmmDNS"));
_timer = new Timer("Multihomed mDNS.Timer", true);
_serviceListeners = new ConcurrentHashMap<String, List<ServiceListener>>();
_typeListeners = Collections.synchronizedSet(new HashSet<ServiceTypeListener>());
_serviceTypes = Collections.synchronizedSet(new HashSet<String>());
(new NetworkChecker(this, NetworkTopologyDiscovery.Factory.getInstance())).start(_timer);
_isClosing = new AtomicBoolean(false);
_closed = new AtomicBoolean(false);
}
/*
* (non-Javadoc)
* @see java.io.Closeable#close()
*/
@Override
public void close() throws IOException {
if (_isClosing.compareAndSet(false, true)) {
if (logger.isLoggable(Level.FINER)) {
logger.finer("Cancelling JmmDNS: " + this);
}
_timer.cancel();
_listenerExecutor.shutdown();
_jmDNSExecutor.shutdown();
// We need to cancel all the DNS
ExecutorService executor = Executors.newCachedThreadPool(new NamedThreadFactory("JmmDNS.close"));
try {
for (final JmDNS mDNS : this.getDNS()) {
executor.submit(new Runnable() {
/**
* {@inheritDoc}
*/
@Override
public void run() {
try {
mDNS.close();
} catch (IOException exception) {
// JmDNS never throws this is only because of the closeable interface
}
}
});
}
} finally {
executor.shutdown();
}
try {
executor.awaitTermination(DNSConstants.CLOSE_TIMEOUT, TimeUnit.MILLISECONDS);
} catch (InterruptedException exception) {
logger.log(Level.WARNING, "Exception ", exception);
}
_knownMDNS.clear();
_services.clear();
_serviceListeners.clear();
_typeListeners.clear();
_serviceTypes.clear();
_closed.set(true);
JmmDNS.Factory.close();
}
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#getNames()
*/
@Override
public String[] getNames() {
Set<String> result = new HashSet<String>();
for (JmDNS mDNS : this.getDNS()) {
result.add(mDNS.getName());
}
return result.toArray(new String[result.size()]);
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#getHostNames()
*/
@Override
public String[] getHostNames() {
Set<String> result = new HashSet<String>();
for (JmDNS mDNS : this.getDNS()) {
result.add(mDNS.getHostName());
}
return result.toArray(new String[result.size()]);
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#getInetAddresses()
*/
@Override
public InetAddress[] getInetAddresses() throws IOException {
Set<InetAddress> result = new HashSet<InetAddress>();
for (JmDNS mDNS : this.getDNS()) {
result.add(mDNS.getInetAddress());
}
return result.toArray(new InetAddress[result.size()]);
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#getDNS()
*/
@Override
public JmDNS[] getDNS() {
synchronized (_knownMDNS) {
return _knownMDNS.values().toArray(new JmDNS[_knownMDNS.size()]);
}
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#getInterfaces()
*/
@Override
@Deprecated
public InetAddress[] getInterfaces() throws IOException {
Set<InetAddress> result = new HashSet<InetAddress>();
for (JmDNS mDNS : this.getDNS()) {
result.add(mDNS.getInterface());
}
return result.toArray(new InetAddress[result.size()]);
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#getServiceInfos(java.lang.String, java.lang.String)
*/
@Override
public ServiceInfo[] getServiceInfos(String type, String name) {
return this.getServiceInfos(type, name, false, DNSConstants.SERVICE_INFO_TIMEOUT);
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#getServiceInfos(java.lang.String, java.lang.String, long)
*/
@Override
public ServiceInfo[] getServiceInfos(String type, String name, long timeout) {
return this.getServiceInfos(type, name, false, timeout);
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#getServiceInfos(java.lang.String, java.lang.String, boolean)
*/
@Override
public ServiceInfo[] getServiceInfos(String type, String name, boolean persistent) {
return this.getServiceInfos(type, name, persistent, DNSConstants.SERVICE_INFO_TIMEOUT);
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#getServiceInfos(java.lang.String, java.lang.String, boolean, long)
*/
@Override
public ServiceInfo[] getServiceInfos(final String type, final String name, final boolean persistent, final long timeout) {
// We need to run this in parallel to respect the timeout.
final JmDNS[] dnsArray = this.getDNS();
final Set<ServiceInfo> result = new HashSet<ServiceInfo>(dnsArray.length);
if (dnsArray.length > 0) {
List<Callable<ServiceInfo>> tasks = new ArrayList<Callable<ServiceInfo>>(dnsArray.length);
for (final JmDNS mDNS : dnsArray) {
tasks.add(new Callable<ServiceInfo>() {
@Override
public ServiceInfo call() throws Exception {
return mDNS.getServiceInfo(type, name, persistent, timeout);
}
});
}
ExecutorService executor = Executors.newFixedThreadPool(tasks.size(), new NamedThreadFactory("JmmDNS.getServiceInfos"));
try {
List<Future<ServiceInfo>> results = Collections.emptyList();
try {
results = executor.invokeAll(tasks, timeout + 100, TimeUnit.MILLISECONDS);
} catch (InterruptedException exception) {
logger.log(Level.FINE, "Interrupted ", exception);
Thread.currentThread().interrupt();
// Will terminate next loop early.
}
for (Future<ServiceInfo> future : results) {
if (future.isCancelled()) {
continue;
}
try {
ServiceInfo info = future.get();
if (info != null) {
result.add(info);
}
} catch (InterruptedException exception) {
logger.log(Level.FINE, "Interrupted ", exception);
Thread.currentThread().interrupt();
} catch (ExecutionException exception) {
logger.log(Level.WARNING, "Exception ", exception);
}
}
} finally {
executor.shutdown();
}
}
return result.toArray(new ServiceInfo[result.size()]);
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#requestServiceInfo(java.lang.String, java.lang.String)
*/
@Override
public void requestServiceInfo(String type, String name) {
this.requestServiceInfo(type, name, false, DNSConstants.SERVICE_INFO_TIMEOUT);
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#requestServiceInfo(java.lang.String, java.lang.String, boolean)
*/
@Override
public void requestServiceInfo(String type, String name, boolean persistent) {
this.requestServiceInfo(type, name, persistent, DNSConstants.SERVICE_INFO_TIMEOUT);
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#requestServiceInfo(java.lang.String, java.lang.String, long)
*/
@Override
public void requestServiceInfo(String type, String name, long timeout) {
this.requestServiceInfo(type, name, false, timeout);
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#requestServiceInfo(java.lang.String, java.lang.String, boolean, long)
*/
@Override
public void requestServiceInfo(final String type, final String name, final boolean persistent, final long timeout) {
// We need to run this in parallel to respect the timeout.
for (final JmDNS mDNS : this.getDNS()) {
_jmDNSExecutor.submit(new Runnable() {
/**
* {@inheritDoc}
*/
@Override
public void run() {
mDNS.requestServiceInfo(type, name, persistent, timeout);
}
});
}
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#addServiceTypeListener(javax.jmdns.ServiceTypeListener)
*/
@Override
public void addServiceTypeListener(ServiceTypeListener listener) throws IOException {
_typeListeners.add(listener);
for (JmDNS mDNS : this.getDNS()) {
mDNS.addServiceTypeListener(listener);
}
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#removeServiceTypeListener(javax.jmdns.ServiceTypeListener)
*/
@Override
public void removeServiceTypeListener(ServiceTypeListener listener) {
_typeListeners.remove(listener);
for (JmDNS mDNS : this.getDNS()) {
mDNS.removeServiceTypeListener(listener);
}
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#addServiceListener(java.lang.String, javax.jmdns.ServiceListener)
*/
@Override
public void addServiceListener(String type, ServiceListener listener) {
final String loType = type.toLowerCase();
List<ServiceListener> list = _serviceListeners.get(loType);
if (list == null) {
_serviceListeners.putIfAbsent(loType, new LinkedList<ServiceListener>());
list = _serviceListeners.get(loType);
}
if (list != null) {
synchronized (list) {
if (!list.contains(listener)) {
list.add(listener);
}
}
}
for (JmDNS mDNS : this.getDNS()) {
mDNS.addServiceListener(type, listener);
}
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#removeServiceListener(java.lang.String, javax.jmdns.ServiceListener)
*/
@Override
public void removeServiceListener(String type, ServiceListener listener) {
String loType = type.toLowerCase();
List<ServiceListener> list = _serviceListeners.get(loType);
if (list != null) {
synchronized (list) {
list.remove(listener);
if (list.isEmpty()) {
_serviceListeners.remove(loType, list);
}
}
}
for (JmDNS mDNS : this.getDNS()) {
mDNS.removeServiceListener(type, listener);
}
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.ServiceInfoImpl.Delegate#textValueUpdated(javax.jmdns.ServiceInfo, byte[])
*/
@Override
public void textValueUpdated(ServiceInfo target, byte[] value) {
// We need to get the list out of the synchronized block to prevent dead locks
final JmDNS[] dnsArray = this.getDNS();
synchronized (_services) {
for (JmDNS mDNS : dnsArray) {
ServiceInfo info = ((JmDNSImpl) mDNS).getServices().get(target.getQualifiedName());
if (info != null) {
info.setText(value);
} else {
logger.warning("We have a mDNS that does not know about the service info being updated.");
}
}
}
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#registerService(javax.jmdns.ServiceInfo)
*/
@Override
public void registerService(ServiceInfo info) throws IOException {
// We need to get the list out of the synchronized block to prevent dead locks
final JmDNS[] dnsArray = this.getDNS();
// This is really complex. We need to clone the service info for each DNS but then we loose the ability to update it.
synchronized (_services) {
for (JmDNS mDNS : dnsArray) {
mDNS.registerService(info.clone());
}
((ServiceInfoImpl) info).setDelegate(this);
_services.put(info.getQualifiedName(), info);
}
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#unregisterService(javax.jmdns.ServiceInfo)
*/
@Override
public void unregisterService(ServiceInfo info) {
// We need to get the list out of the synchronized block to prevent dead locks
final JmDNS[] dnsArray = this.getDNS();
synchronized (_services) {
_services.remove(info.getQualifiedName());
for (JmDNS mDNS : dnsArray) {
mDNS.unregisterService(info);
}
((ServiceInfoImpl) info).setDelegate(null);
}
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#unregisterAllServices()
*/
@Override
public void unregisterAllServices() {
// We need to get the list out of the synchronized block to prevent dead locks
final JmDNS[] dnsArray = this.getDNS();
synchronized (_services) {
_services.clear();
for (JmDNS mDNS : dnsArray) {
mDNS.unregisterAllServices();
}
}
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#registerServiceType(java.lang.String)
*/
@Override
public void registerServiceType(String type) {
_serviceTypes.add(type);
for (JmDNS mDNS : this.getDNS()) {
mDNS.registerServiceType(type);
}
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#list(java.lang.String)
*/
@Override
public ServiceInfo[] list(String type) {
return this.list(type, DNSConstants.SERVICE_INFO_TIMEOUT);
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#list(java.lang.String, long)
*/
@Override
public ServiceInfo[] list(final String type, final long timeout) {
final JmDNS[] dnsArray = this.getDNS();
// We need to run this in parallel to respect the timeout.
final Set<ServiceInfo> result = new HashSet<ServiceInfo>(dnsArray.length * 5);
if (dnsArray.length > 0) {
List<Callable<List<ServiceInfo>>> tasks = new ArrayList<Callable<List<ServiceInfo>>>(dnsArray.length);
for (final JmDNS mDNS : dnsArray) {
tasks.add(new Callable<List<ServiceInfo>>() {
@Override
public List<ServiceInfo> call() throws Exception {
return Arrays.asList(mDNS.list(type, timeout));
}
});
}
ExecutorService executor = Executors.newFixedThreadPool(tasks.size(), new NamedThreadFactory("JmmDNS.list"));
try {
List<Future<List<ServiceInfo>>> results = Collections.emptyList();
try {
results = executor.invokeAll(tasks, timeout + 100, TimeUnit.MILLISECONDS);
} catch (InterruptedException exception) {
logger.log(Level.FINE, "Interrupted ", exception);
Thread.currentThread().interrupt();
// Will terminate next loop early.
}
for (Future<List<ServiceInfo>> future : results) {
if (future.isCancelled()) {
continue;
}
try {
result.addAll(future.get());
} catch (InterruptedException exception) {
logger.log(Level.FINE, "Interrupted ", exception);
Thread.currentThread().interrupt();
} catch (ExecutionException exception) {
logger.log(Level.WARNING, "Exception ", exception);
}
}
} finally {
executor.shutdown();
}
}
return result.toArray(new ServiceInfo[result.size()]);
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#listBySubtype(java.lang.String)
*/
@Override
public Map<String, ServiceInfo[]> listBySubtype(String type) {
return this.listBySubtype(type, DNSConstants.SERVICE_INFO_TIMEOUT);
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#listBySubtype(java.lang.String, long)
*/
@Override
public Map<String, ServiceInfo[]> listBySubtype(final String type, final long timeout) {
Map<String, List<ServiceInfo>> map = new HashMap<String, List<ServiceInfo>>(5);
for (ServiceInfo info : this.list(type, timeout)) {
String subtype = info.getSubtype();
if (!map.containsKey(subtype)) {
map.put(subtype, new ArrayList<ServiceInfo>(10));
}
map.get(subtype).add(info);
}
Map<String, ServiceInfo[]> result = new HashMap<String, ServiceInfo[]>(map.size());
for (String subtype : map.keySet()) {
List<ServiceInfo> infoForSubType = map.get(subtype);
result.put(subtype, infoForSubType.toArray(new ServiceInfo[infoForSubType.size()]));
}
return result;
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#addNetworkTopologyListener(javax.jmdns.NetworkTopologyListener)
*/
@Override
public void addNetworkTopologyListener(NetworkTopologyListener listener) {
_networkListeners.add(listener);
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#removeNetworkTopologyListener(javax.jmdns.NetworkTopologyListener)
*/
@Override
public void removeNetworkTopologyListener(NetworkTopologyListener listener) {
_networkListeners.remove(listener);
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS#networkListeners()
*/
@Override
public NetworkTopologyListener[] networkListeners() {
return _networkListeners.toArray(new NetworkTopologyListener[_networkListeners.size()]);
}
/*
* (non-Javadoc)
* @see javax.jmdns.NetworkTopologyListener#inetAddressAdded(javax.jmdns.NetworkTopologyEvent)
*/
@Override
public void inetAddressAdded(NetworkTopologyEvent event) {
InetAddress address = event.getInetAddress();
try {
if (!_knownMDNS.containsKey(address)) {
synchronized (_knownMDNS) {
if (!_knownMDNS.containsKey(address)) {
final JmDNS dns = JmDNS.create(address);
if (_knownMDNS.putIfAbsent(address, dns) == null) {
// We need to register the services and listeners with the new JmDNS
final Collection<String> types = _serviceTypes;
final Collection<ServiceInfo> infos = _services.values();
final Collection<ServiceTypeListener> typeListeners = _typeListeners;
final Map<String, List<ServiceListener>> serviceListeners = _serviceListeners;
_jmDNSExecutor.submit(new Runnable() {
/**
* {@inheritDoc}
*/
@Override
public void run() {
// Register Types
for (String type : types) {
dns.registerServiceType(type);
}
// Register services
for (ServiceInfo info : infos) {
try {
dns.registerService(info.clone());
} catch (IOException exception) {
// logger.warning("Unexpected unhandled exception: " + exception);
}
}
// Add ServiceType Listeners
for (ServiceTypeListener listener : typeListeners) {
try {
dns.addServiceTypeListener(listener);
} catch (IOException exception) {
// logger.warning("Unexpected unhandled exception: " + exception);
}
}
// Add Service Listeners
for (String type : serviceListeners.keySet()) {
List<ServiceListener> listeners = serviceListeners.get(type);
synchronized (listeners) {
for (ServiceListener listener : listeners) {
dns.addServiceListener(type, listener);
}
}
}
}
});
final NetworkTopologyEvent jmdnsEvent = new NetworkTopologyEventImpl(dns, address);
for (final NetworkTopologyListener listener : this.networkListeners()) {
_listenerExecutor.submit(new Runnable() {
/**
* {@inheritDoc}
*/
@Override
public void run() {
listener.inetAddressAdded(jmdnsEvent);
}
});
}
} else {
dns.close();
}
}
}
}
} catch (Exception e) {
logger.warning("Unexpected unhandled exception: " + e);
}
}
/*
* (non-Javadoc)
* @see javax.jmdns.NetworkTopologyListener#inetAddressRemoved(javax.jmdns.NetworkTopologyEvent)
*/
@Override
public void inetAddressRemoved(NetworkTopologyEvent event) {
InetAddress address = event.getInetAddress();
try {
if (_knownMDNS.containsKey(address)) {
synchronized (_knownMDNS) {
if (_knownMDNS.containsKey(address)) {
JmDNS mDNS = _knownMDNS.remove(address);
mDNS.close();
final NetworkTopologyEvent jmdnsEvent = new NetworkTopologyEventImpl(mDNS, address);
for (final NetworkTopologyListener listener : this.networkListeners()) {
_listenerExecutor.submit(new Runnable() {
/**
* {@inheritDoc}
*/
@Override
public void run() {
listener.inetAddressRemoved(jmdnsEvent);
}
});
}
}
}
}
} catch (Exception e) {
logger.warning("Unexpected unhandled exception: " + e);
}
}
/**
* Checks the network state.<br/>
* If the network change, this class will reconfigure the list of DNS do adapt to the new configuration.
*/
static class NetworkChecker extends TimerTask {
private static Logger logger1 = Logger.getLogger(NetworkChecker.class.getName());
private final NetworkTopologyListener _mmDNS;
private final NetworkTopologyDiscovery _topology;
private Set<InetAddress> _knownAddresses;
public NetworkChecker(NetworkTopologyListener mmDNS, NetworkTopologyDiscovery topology) {
super();
this._mmDNS = mmDNS;
this._topology = topology;
_knownAddresses = Collections.synchronizedSet(new HashSet<InetAddress>());
}
public void start(Timer timer) {
// Run once up-front otherwise the list of servers will only appear after a delay.
run();
timer.schedule(this, DNSConstants.NETWORK_CHECK_INTERVAL, DNSConstants.NETWORK_CHECK_INTERVAL);
}
/**
* {@inheritDoc}
*/
@Override
public void run() {
try {
InetAddress[] curentAddresses = _topology.getInetAddresses();
Set<InetAddress> current = new HashSet<InetAddress>(curentAddresses.length);
for (InetAddress address : curentAddresses) {
current.add(address);
if (!_knownAddresses.contains(address)) {
final NetworkTopologyEvent event = new NetworkTopologyEventImpl(_mmDNS, address);
_mmDNS.inetAddressAdded(event);
}
}
for (InetAddress address : _knownAddresses) {
if (!current.contains(address)) {
final NetworkTopologyEvent event = new NetworkTopologyEventImpl(_mmDNS, address);
_mmDNS.inetAddressRemoved(event);
}
}
_knownAddresses = current;
} catch (Exception e) {
logger1.warning("Unexpected unhandled exception: " + e);
}
}
}
}

View File

@ -0,0 +1,286 @@
/**
*
*/
package javax.jmdns.impl;
import java.util.EventListener;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.logging.Logger;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceInfo;
import javax.jmdns.ServiceListener;
import javax.jmdns.ServiceTypeListener;
/**
* This class track the status of listener.<br/>
* The main purpose of this class is to collapse consecutive events so that we can guarantee the correct call back sequence.
*
* @param <T>
* listener type
*/
public class ListenerStatus<T extends EventListener> {
public static class ServiceListenerStatus extends ListenerStatus<ServiceListener> {
private static Logger logger = Logger.getLogger(ServiceListenerStatus.class.getName());
private final ConcurrentMap<String, ServiceInfo> _addedServices;
/**
* @param listener
* listener being tracked.
* @param synch
* true if that listener can be called asynchronously
*/
public ServiceListenerStatus(ServiceListener listener, boolean synch) {
super(listener, synch);
_addedServices = new ConcurrentHashMap<String, ServiceInfo>(32);
}
/**
* A service has been added.<br/>
* <b>Note:</b>This event is only the service added event. The service info associated with this event does not include resolution information.<br/>
* To get the full resolved information you need to listen to {@link #serviceResolved(ServiceEvent)} or call {@link JmDNS#getServiceInfo(String, String, long)}
*
* <pre>
* ServiceInfo info = event.getDNS().getServiceInfo(event.getType(), event.getName())
* </pre>
* <p>
* Please note that service resolution may take a few second to resolve.
* </p>
*
* @param event
* The ServiceEvent providing the name and fully qualified type of the service.
*/
void serviceAdded(ServiceEvent event) {
String qualifiedName = event.getName() + "." + event.getType();
if (null == _addedServices.putIfAbsent(qualifiedName, event.getInfo().clone())) {
this.getListener().serviceAdded(event);
ServiceInfo info = event.getInfo();
if ((info != null) && (info.hasData())) {
this.getListener().serviceResolved(event);
}
} else {
logger.finer("Service Added called for a service already added: " + event);
}
}
/**
* A service has been removed.
*
* @param event
* The ServiceEvent providing the name and fully qualified type of the service.
*/
void serviceRemoved(ServiceEvent event) {
String qualifiedName = event.getName() + "." + event.getType();
if (_addedServices.remove(qualifiedName, _addedServices.get(qualifiedName))) {
this.getListener().serviceRemoved(event);
} else {
logger.finer("Service Removed called for a service already removed: " + event);
}
}
/**
* A service has been resolved. Its details are now available in the ServiceInfo record.<br/>
* <b>Note:</b>This call back will never be called if the service does not resolve.<br/>
*
* @param event
* The ServiceEvent providing the name, the fully qualified type of the service, and the service info record.
*/
synchronized void serviceResolved(ServiceEvent event) {
ServiceInfo info = event.getInfo();
if ((info != null) && (info.hasData())) {
String qualifiedName = event.getName() + "." + event.getType();
ServiceInfo previousServiceInfo = _addedServices.get(qualifiedName);
if (!_sameInfo(info, previousServiceInfo)) {
if (null == previousServiceInfo) {
if (null == _addedServices.putIfAbsent(qualifiedName, info.clone())) {
this.getListener().serviceResolved(event);
}
} else {
if (_addedServices.replace(qualifiedName, previousServiceInfo, info.clone())) {
this.getListener().serviceResolved(event);
}
}
} else {
logger.finer("Service Resolved called for a service already resolved: " + event);
}
} else {
logger.warning("Service Resolved called for an unresolved event: " + event);
}
}
private static final boolean _sameInfo(ServiceInfo info, ServiceInfo lastInfo) {
if (info == null) return false;
if (lastInfo == null) return false;
if (!info.equals(lastInfo)) return false;
byte[] text = info.getTextBytes();
byte[] lastText = lastInfo.getTextBytes();
if (text.length != lastText.length) return false;
for (int i = 0; i < text.length; i++) {
if (text[i] != lastText[i]) return false;
}
return true;
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder aLog = new StringBuilder(2048);
aLog.append("[Status for ");
aLog.append(this.getListener().toString());
if (_addedServices.isEmpty()) {
aLog.append(" no type event ");
} else {
aLog.append(" (");
for (String service : _addedServices.keySet()) {
aLog.append(service + ", ");
}
aLog.append(") ");
}
aLog.append("]");
return aLog.toString();
}
}
public static class ServiceTypeListenerStatus extends ListenerStatus<ServiceTypeListener> {
private static Logger logger = Logger.getLogger(ServiceTypeListenerStatus.class.getName());
private final ConcurrentMap<String, String> _addedTypes;
/**
* @param listener
* listener being tracked.
* @param synch
* true if that listener can be called asynchronously
*/
public ServiceTypeListenerStatus(ServiceTypeListener listener, boolean synch) {
super(listener, synch);
_addedTypes = new ConcurrentHashMap<String, String>(32);
}
/**
* A new service type was discovered.
*
* @param event
* The service event providing the fully qualified type of the service.
*/
void serviceTypeAdded(ServiceEvent event) {
if (null == _addedTypes.putIfAbsent(event.getType(), event.getType())) {
this.getListener().serviceTypeAdded(event);
} else {
logger.finest("Service Type Added called for a service type already added: " + event);
}
}
/**
* A new subtype for the service type was discovered.
*
* <pre>
* &lt;sub&gt;._sub.&lt;app&gt;.&lt;protocol&gt;.&lt;servicedomain&gt;.&lt;parentdomain&gt;.
* </pre>
*
* @param event
* The service event providing the fully qualified type of the service with subtype.
*/
void subTypeForServiceTypeAdded(ServiceEvent event) {
if (null == _addedTypes.putIfAbsent(event.getType(), event.getType())) {
this.getListener().subTypeForServiceTypeAdded(event);
} else {
logger.finest("Service Sub Type Added called for a service sub type already added: " + event);
}
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder aLog = new StringBuilder(2048);
aLog.append("[Status for ");
aLog.append(this.getListener().toString());
if (_addedTypes.isEmpty()) {
aLog.append(" no type event ");
} else {
aLog.append(" (");
for (String type : _addedTypes.keySet()) {
aLog.append(type + ", ");
}
aLog.append(") ");
}
aLog.append("]");
return aLog.toString();
}
}
public final static boolean SYNCHONEOUS = true;
public final static boolean ASYNCHONEOUS = false;
private final T _listener;
private final boolean _synch;
/**
* @param listener
* listener being tracked.
* @param synch
* true if that listener can be called asynchronously
*/
public ListenerStatus(T listener, boolean synch) {
super();
_listener = listener;
_synch = synch;
}
/**
* @return the listener
*/
public T getListener() {
return _listener;
}
/**
* Return <cod>true</code> if the listener must be called synchronously.
*
* @return the synch
*/
public boolean isSynchronous() {
return _synch;
}
/*
* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return this.getListener().hashCode();
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
return (obj instanceof ListenerStatus) && this.getListener().equals(((ListenerStatus<?>) obj).getListener());
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "[Status for " + this.getListener().toString() + "]";
}
}

View File

@ -0,0 +1,274 @@
/**
*
*/
package javax.jmdns.impl;
import java.net.InetAddress;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
*
*/
public interface NameRegister {
/**
*
*/
public enum NameType {
/**
* This name represents a host name
*/
HOST,
/**
* This name represents a service name
*/
SERVICE,
}
public static abstract class BaseRegister implements NameRegister {
protected String incrementNameWithDash(String name) {
StringBuilder givenName = new StringBuilder(name.length() + 5);
int hostNameCount = 0;
int plocal = name.indexOf(".local.");
int punder = name.lastIndexOf('-');
if (punder < 0) {
// This is the first increment
hostNameCount = 1;
givenName.append(name.substring(0, plocal));
} else {
try {
int value = Integer.parseInt(name.substring(punder + 1, plocal));
hostNameCount = value + 1;
givenName.append(name.substring(0, punder));
} catch (Exception e) {
// If we got an exception this means that we have a name with a "-"
hostNameCount = 1;
givenName.append(name.substring(0, plocal));
}
}
givenName.append('-');
givenName.append(hostNameCount);
givenName.append(".local.");
return givenName.toString();
}
protected String incrementNameWithParentesis(String name) {
StringBuilder givenName = new StringBuilder(name.length() + 5);
final int l = name.lastIndexOf('(');
final int r = name.lastIndexOf(')');
if ((l >= 0) && (l < r)) {
try {
givenName.append(name.substring(0, l));
givenName.append('(');
givenName.append(Integer.parseInt(name.substring(l + 1, r)) + 1);
givenName.append(')');
} catch (final NumberFormatException e) {
givenName.setLength(0);
givenName.append(name);
givenName.append(" (2)");
}
} else {
givenName.append(name);
givenName.append(" (2)");
}
return givenName.toString();
}
}
public static class UniqueNamePerInterface extends BaseRegister {
private final ConcurrentMap<InetAddress, String> _hostNames;
private final ConcurrentMap<InetAddress, Set<String>> _serviceNames;
public UniqueNamePerInterface() {
super();
_hostNames = new ConcurrentHashMap<InetAddress, String>();
_serviceNames = new ConcurrentHashMap<InetAddress, Set<String>>();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.NameRegister#register(java.net.InetAddress, java.lang.String, javax.jmdns.impl.NameRegister.NameType)
*/
@Override
public void register(InetAddress networkInterface, String name, NameType type) {
switch (type) {
case HOST:
break;
case SERVICE:
break;
default:
// this is trash to keep the compiler happy
}
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.NameRegister#checkName(java.net.InetAddress, java.lang.String, javax.jmdns.impl.NameRegister.NameType)
*/
@Override
public boolean checkName(InetAddress networkInterface, String name, NameType type) {
switch (type) {
case HOST:
String hostname = _hostNames.get(networkInterface);
return hostname != null && hostname.equals(name);
case SERVICE:
Set<String> names = _serviceNames.get(networkInterface);
return names != null && names.contains(names);
default:
// this is trash to keep the compiler happy
return false;
}
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.NameRegister#incrementHostName(java.net.InetAddress, java.lang.String, javax.jmdns.impl.NameRegister.NameType)
*/
@Override
public String incrementName(InetAddress networkInterface, String name, NameType type) {
switch (type) {
case HOST:
return this.incrementNameWithDash(name);
case SERVICE:
return this.incrementNameWithParentesis(name);
default:
// this is trash to keep the compiler happy
return name;
}
}
}
public static class UniqueNameAcrossInterface extends BaseRegister {
/*
* (non-Javadoc)
* @see javax.jmdns.impl.NameRegister#register(java.net.InetAddress, java.lang.String, javax.jmdns.impl.NameRegister.NameType)
*/
@Override
public void register(InetAddress networkInterface, String name, NameType type) {
switch (type) {
case HOST:
break;
case SERVICE:
break;
default:
// this is trash to keep the compiler happy
}
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.NameRegister#checkName(java.net.InetAddress, java.lang.String, javax.jmdns.impl.NameRegister.NameType)
*/
@Override
public boolean checkName(InetAddress networkInterface, String name, NameType type) {
switch (type) {
case HOST:
return false;
case SERVICE:
return false;
default:
// this is trash to keep the compiler happy
return false;
}
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.NameRegister#incrementHostName(java.net.InetAddress, java.lang.String, javax.jmdns.impl.NameRegister.NameType)
*/
@Override
public String incrementName(InetAddress networkInterface, String name, NameType type) {
switch (type) {
case HOST:
return this.incrementNameWithDash(name);
case SERVICE:
return this.incrementNameWithParentesis(name);
default:
// this is trash to keep the compiler happy
return name;
}
}
}
public static class Factory {
private static volatile NameRegister _register;
/**
* Register a Name register.
*
* @param register
* new register
* @throws IllegalStateException
* the register can only be set once
*/
public static void setRegistry(NameRegister register) throws IllegalStateException {
if (_register != null) {
throw new IllegalStateException("The register can only be set once.");
}
if (register != null) {
_register = register;
}
}
/**
* Returns the name register.
*
* @return name register
*/
public static NameRegister getRegistry() {
if (_register == null) {
_register = new UniqueNamePerInterface();
}
return _register;
}
}
/**
* Registers a name that is defended by this group of mDNS.
*
* @param networkInterface
* IP address to handle
* @param name
* name to register
* @param type
* name type to register
*/
public abstract void register(InetAddress networkInterface, String name, NameType type);
/**
* Checks a name that is defended by this group of mDNS.
*
* @param networkInterface
* IP address to handle
* @param name
* name to check
* @param type
* name type to check
* @return <code>true</code> if the name is not in conflict, <code>flase</code> otherwise.
*/
public abstract boolean checkName(InetAddress networkInterface, String name, NameType type);
/**
* Increments a name that is defended by this group of mDNS after it has been found in conflict.
*
* @param networkInterface
* IP address to handle
* @param name
* name to increment
* @param type
* name type to increments
* @return new name
*/
public abstract String incrementName(InetAddress networkInterface, String name, NameType type);
}

View File

@ -0,0 +1,129 @@
/**
*
*/
package javax.jmdns.impl;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jmdns.NetworkTopologyDiscovery;
/**
* This class implements NetworkTopologyDiscovery.
*
* @author Pierre Frisch
*/
public class NetworkTopologyDiscoveryImpl implements NetworkTopologyDiscovery {
private final static Logger logger = Logger.getLogger(NetworkTopologyDiscoveryImpl.class.getName());
private final Method _isUp;
private final Method _supportsMulticast;
/**
*
*/
public NetworkTopologyDiscoveryImpl() {
super();
Method isUp;
try {
isUp = NetworkInterface.class.getMethod("isUp", (Class<?>[]) null);
} catch (Exception exception) {
// We do not want to throw anything if the method does not exist.
isUp = null;
}
_isUp = isUp;
Method supportsMulticast;
try {
supportsMulticast = NetworkInterface.class.getMethod("supportsMulticast", (Class<?>[]) null);
} catch (Exception exception) {
// We do not want to throw anything if the method does not exist.
supportsMulticast = null;
}
_supportsMulticast = supportsMulticast;
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS.NetworkTopologyDiscovery#getInetAddresses()
*/
@Override
public InetAddress[] getInetAddresses() {
Set<InetAddress> result = new HashSet<InetAddress>();
try {
for (Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces(); nifs.hasMoreElements();) {
NetworkInterface nif = nifs.nextElement();
for (Enumeration<InetAddress> iaenum = nif.getInetAddresses(); iaenum.hasMoreElements();) {
InetAddress interfaceAddress = iaenum.nextElement();
if (logger.isLoggable(Level.FINEST)) {
logger.finest("Found NetworkInterface/InetAddress: " + nif + " -- " + interfaceAddress);
}
if (this.useInetAddress(nif, interfaceAddress)) {
result.add(interfaceAddress);
}
}
}
} catch (SocketException se) {
logger.warning("Error while fetching network interfaces addresses: " + se);
}
return result.toArray(new InetAddress[result.size()]);
}
/*
* (non-Javadoc)
* @see javax.jmdns.JmmDNS.NetworkTopologyDiscovery#useInetAddress(java.net.NetworkInterface, java.net.InetAddress)
*/
@Override
public boolean useInetAddress(NetworkInterface networkInterface, InetAddress interfaceAddress) {
try {
if (_isUp != null) {
try {
if (!((Boolean) _isUp.invoke(networkInterface, (Object[]) null)).booleanValue()) {
return false;
}
} catch (Exception exception) {
// We should hide that exception.
}
}
if (_supportsMulticast != null) {
try {
if (!((Boolean) _supportsMulticast.invoke(networkInterface, (Object[]) null)).booleanValue()) {
return false;
}
} catch (Exception exception) {
// We should hide that exception.
}
}
return true;
} catch (Exception exception) {
return false;
}
}
/*
* (non-Javadoc)
* @see javax.jmdns.NetworkTopologyDiscovery#lockInetAddress(java.net.InetAddress)
*/
@Override
public void lockInetAddress(InetAddress interfaceAddress) {
// Default implementation does nothing.
}
/*
* (non-Javadoc)
* @see javax.jmdns.NetworkTopologyDiscovery#unlockInetAddress(java.net.InetAddress)
*/
@Override
public void unlockInetAddress(InetAddress interfaceAddress) {
// Default implementation does nothing.
}
}

View File

@ -0,0 +1,82 @@
/**
*
*/
package javax.jmdns.impl;
import java.net.InetAddress;
import javax.jmdns.JmDNS;
import javax.jmdns.NetworkTopologyEvent;
import javax.jmdns.NetworkTopologyListener;
/**
* @author C&eacute;drik Lime, Pierre Frisch
*/
public class NetworkTopologyEventImpl extends NetworkTopologyEvent implements Cloneable {
/**
*
*/
private static final long serialVersionUID = 1445606146153550463L;
private final InetAddress _inetAddress;
/**
* Constructs a Network Topology Event.
*
* @param jmDNS
* @param inetAddress
* @exception IllegalArgumentException
* if source is null.
*/
public NetworkTopologyEventImpl(JmDNS jmDNS, InetAddress inetAddress) {
super(jmDNS);
this._inetAddress = inetAddress;
}
NetworkTopologyEventImpl(NetworkTopologyListener jmmDNS, InetAddress inetAddress) {
super(jmmDNS);
this._inetAddress = inetAddress;
}
/*
* (non-Javadoc)
* @see javax.jmdns.NetworkTopologyEvent#getDNS()
*/
@Override
public JmDNS getDNS() {
return (this.getSource() instanceof JmDNS ? (JmDNS) getSource() : null);
}
/*
* (non-Javadoc)
* @see javax.jmdns.NetworkTopologyEvent#getInetAddress()
*/
@Override
public InetAddress getInetAddress() {
return _inetAddress;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append("[" + this.getClass().getSimpleName() + "@" + System.identityHashCode(this) + " ");
buf.append("\n\tinetAddress: '");
buf.append(this.getInetAddress());
buf.append("']");
// buf.append("' source: ");
// buf.append("\n\t" + source + "");
// buf.append("\n]");
return buf.toString();
}
/*
* (non-Javadoc)
* @see java.lang.Object#clone()
*/
@Override
public NetworkTopologyEventImpl clone() throws CloneNotSupportedException {
return new NetworkTopologyEventImpl(getDNS(), getInetAddress());
}
}

View File

@ -0,0 +1,124 @@
// /Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl;
import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceInfo;
/**
* ServiceEvent.
*
* @author Werner Randelshofer, Rick Blair
*/
/**
*
*/
public class ServiceEventImpl extends ServiceEvent {
/**
*
*/
private static final long serialVersionUID = 7107973622016897488L;
// private static Logger logger = Logger.getLogger(ServiceEvent.class.getName());
/**
* The type name of the service.
*/
private final String _type;
/**
* The instance name of the service. Or null, if the event was fired to a service type listener.
*/
private final String _name;
/**
* The service info record, or null if the service could be be resolved. This is also null, if the event was fired to a service type listener.
*/
private final ServiceInfo _info;
/**
* Creates a new instance.
*
* @param jmDNS
* the JmDNS instance which originated the event.
* @param type
* the type name of the service.
* @param name
* the instance name of the service.
* @param info
* the service info record, or null if the service could be be resolved.
*/
public ServiceEventImpl(JmDNSImpl jmDNS, String type, String name, ServiceInfo info) {
super(jmDNS);
this._type = type;
this._name = name;
this._info = info;
}
/*
* (non-Javadoc)
* @see javax.jmdns.ServiceEvent#getDNS()
*/
@Override
public JmDNS getDNS() {
return (JmDNS) getSource();
}
/*
* (non-Javadoc)
* @see javax.jmdns.ServiceEvent#getType()
*/
@Override
public String getType() {
return _type;
}
/*
* (non-Javadoc)
* @see javax.jmdns.ServiceEvent#getName()
*/
@Override
public String getName() {
return _name;
}
/*
* (non-Javadoc)
* @see java.util.EventObject#toString()
*/
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append("[" + this.getClass().getSimpleName() + "@" + System.identityHashCode(this) + " ");
buf.append("\n\tname: '");
buf.append(this.getName());
buf.append("' type: '");
buf.append(this.getType());
buf.append("' info: '");
buf.append(this.getInfo());
buf.append("']");
// buf.append("' source: ");
// buf.append("\n\t" + source + "");
// buf.append("\n]");
return buf.toString();
}
/*
* (non-Javadoc)
* @see javax.jmdns.ServiceEvent#getInfo()
*/
@Override
public ServiceInfo getInfo() {
return _info;
}
/*
* (non-Javadoc)
* @see javax.jmdns.ServiceEvent#clone()
*/
@Override
public ServiceEventImpl clone() {
ServiceInfoImpl newInfo = new ServiceInfoImpl(this.getInfo());
return new ServiceEventImpl((JmDNSImpl) this.getDNS(), this.getType(), this.getName(), newInfo);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,87 @@
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl;
import java.io.IOException;
import java.net.DatagramPacket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jmdns.impl.constants.DNSConstants;
/**
* Listen for multicast packets.
*/
class SocketListener extends Thread {
static Logger logger = Logger.getLogger(SocketListener.class.getName());
/**
*
*/
private final JmDNSImpl _jmDNSImpl;
/**
* @param jmDNSImpl
*/
SocketListener(JmDNSImpl jmDNSImpl) {
super("SocketListener(" + (jmDNSImpl != null ? jmDNSImpl.getName() : "") + ")");
this.setDaemon(true);
this._jmDNSImpl = jmDNSImpl;
}
@Override
public void run() {
try {
byte buf[] = new byte[DNSConstants.MAX_MSG_ABSOLUTE];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
while (!this._jmDNSImpl.isCanceling() && !this._jmDNSImpl.isCanceled()) {
packet.setLength(buf.length);
this._jmDNSImpl.getSocket().receive(packet);
if (this._jmDNSImpl.isCanceling() || this._jmDNSImpl.isCanceled() || this._jmDNSImpl.isClosing() || this._jmDNSImpl.isClosed()) {
break;
}
try {
if (this._jmDNSImpl.getLocalHost().shouldIgnorePacket(packet)) {
continue;
}
DNSIncoming msg = new DNSIncoming(packet);
if (msg.isValidResponseCode()) {
if (logger.isLoggable(Level.FINEST)) {
logger.finest(this.getName() + ".run() JmDNS in:" + msg.print(true));
}
if (msg.isQuery()) {
if (packet.getPort() != DNSConstants.MDNS_PORT) {
this._jmDNSImpl.handleQuery(msg, packet.getAddress(), packet.getPort());
}
this._jmDNSImpl.handleQuery(msg, this._jmDNSImpl.getGroup(), DNSConstants.MDNS_PORT);
} else {
this._jmDNSImpl.handleResponse(msg);
}
} else {
if (logger.isLoggable(Level.FINE)) {
logger.fine(this.getName() + ".run() JmDNS in message with error code:" + msg.print(true));
}
}
} catch (IOException e) {
logger.log(Level.WARNING, this.getName() + ".run() exception ", e);
}
}
} catch (IOException e) {
if (!this._jmDNSImpl.isCanceling() && !this._jmDNSImpl.isCanceled() && !this._jmDNSImpl.isClosing() && !this._jmDNSImpl.isClosed()) {
logger.log(Level.WARNING, this.getName() + ".run() exception ", e);
this._jmDNSImpl.recover();
}
}
if (logger.isLoggable(Level.FINEST)) {
logger.finest(this.getName() + ".run() exiting.");
}
}
public JmDNSImpl getDns() {
return _jmDNSImpl;
}
}

View File

@ -0,0 +1,62 @@
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl.constants;
/**
* DNS constants.
*
* @author Arthur van Hoff, Jeff Sonstein, Werner Randelshofer, Pierre Frisch, Rick Blair
*/
public final class DNSConstants {
// http://www.iana.org/assignments/dns-parameters
// changed to final class - jeffs
public static final String MDNS_GROUP = "224.0.0.251";
public static final String MDNS_GROUP_IPV6 = "FF02::FB";
public static final int MDNS_PORT = Integer.parseInt(System.getProperty("net.mdns.port", "5353"));
public static final int DNS_PORT = 53;
public static final int DNS_TTL = 60 * 60; // default one hour TTL
// public static final int DNS_TTL = 120 * 60; // two hour TTL (draft-cheshire-dnsext-multicastdns.txt ch 13)
public static final int MAX_MSG_TYPICAL = 1460;
public static final int MAX_MSG_ABSOLUTE = 8972;
public static final int FLAGS_QR_MASK = 0x8000; // Query response mask
public static final int FLAGS_QR_QUERY = 0x0000; // Query
public static final int FLAGS_QR_RESPONSE = 0x8000; // Response
public static final int FLAGS_OPCODE = 0x7800; // Operation code
public static final int FLAGS_AA = 0x0400; // Authorative answer
public static final int FLAGS_TC = 0x0200; // Truncated
public static final int FLAGS_RD = 0x0100; // Recursion desired
public static final int FLAGS_RA = 0x8000; // Recursion available
public static final int FLAGS_Z = 0x0040; // Zero
public static final int FLAGS_AD = 0x0020; // Authentic data
public static final int FLAGS_CD = 0x0010; // Checking disabled
public static final int FLAGS_RCODE = 0x000F; // Response code
// Time Intervals for various functions
public static final int SHARED_QUERY_TIME = 20; // milliseconds before send shared query
public static final int QUERY_WAIT_INTERVAL = 225; // milliseconds between query loops.
public static final int PROBE_WAIT_INTERVAL = 250; // milliseconds between probe loops.
public static final int RESPONSE_MIN_WAIT_INTERVAL = 20; // minimal wait interval for response.
public static final int RESPONSE_MAX_WAIT_INTERVAL = 115; // maximal wait interval for response
public static final int PROBE_CONFLICT_INTERVAL = 1000; // milliseconds to wait after conflict.
public static final int PROBE_THROTTLE_COUNT = 10; // After x tries go 1 time a sec. on probes.
public static final int PROBE_THROTTLE_COUNT_INTERVAL = 5000; // We only increment the throttle count, if the previous increment is inside this interval.
public static final int ANNOUNCE_WAIT_INTERVAL = 1000; // milliseconds between Announce loops.
public static final int RECORD_REAPER_INTERVAL = 10000; // milliseconds between cache cleanups.
public static final int RECORD_EXPIRY_DELAY = 1; // This is 1s delay used in ttl and therefore in seconds
public static final int KNOWN_ANSWER_TTL = 120;
public static final int ANNOUNCED_RENEWAL_TTL_INTERVAL = DNS_TTL * 500; // 50% of the TTL in milliseconds
public static final long CLOSE_TIMEOUT = ANNOUNCE_WAIT_INTERVAL * 5L;
public static final long SERVICE_INFO_TIMEOUT = ANNOUNCE_WAIT_INTERVAL * 6L;
public static final int NETWORK_CHECK_INTERVAL = 10 * 1000; // 10 secondes
}

View File

@ -0,0 +1,87 @@
/**
*
*/
package javax.jmdns.impl.constants;
/**
* DNS label.
*
* @author Arthur van Hoff, Jeff Sonstein, Werner Randelshofer, Pierre Frisch, Rick Blair
*/
public enum DNSLabel {
/**
* This is unallocated.
*/
Unknown("", 0x80),
/**
* Standard label [RFC 1035]
*/
Standard("standard label", 0x00),
/**
* Compressed label [RFC 1035]
*/
Compressed("compressed label", 0xC0),
/**
* Extended label [RFC 2671]
*/
Extended("extended label", 0x40);
/**
* DNS label types are encoded on the first 2 bits
*/
static final int LABEL_MASK = 0xC0;
static final int LABEL_NOT_MASK = 0x3F;
private final String _externalName;
private final int _index;
DNSLabel(String name, int index) {
_externalName = name;
_index = index;
}
/**
* Return the string representation of this type
*
* @return String
*/
public String externalName() {
return _externalName;
}
/**
* Return the numeric value of this type
*
* @return String
*/
public int indexValue() {
return _index;
}
/**
* @param index
* @return label
*/
public static DNSLabel labelForByte(int index) {
int maskedIndex = index & LABEL_MASK;
for (DNSLabel aLabel : DNSLabel.values()) {
if (aLabel._index == maskedIndex) return aLabel;
}
return Unknown;
}
/**
* @param index
* @return masked value
*/
public static int labelValue(int index) {
return index & LABEL_NOT_MASK;
}
@Override
public String toString() {
return this.name() + " index " + this.indexValue();
}
}

View File

@ -0,0 +1,86 @@
/**
*
*/
package javax.jmdns.impl.constants;
/**
* DNS operation code.
*
* @author Arthur van Hoff, Jeff Sonstein, Werner Randelshofer, Pierre Frisch, Rick Blair
*/
public enum DNSOperationCode {
/**
* Query [RFC1035]
*/
Query("Query", 0),
/**
* IQuery (Inverse Query, Obsolete) [RFC3425]
*/
IQuery("Inverse Query", 1),
/**
* Status [RFC1035]
*/
Status("Status", 2),
/**
* Unassigned
*/
Unassigned("Unassigned", 3),
/**
* Notify [RFC1996]
*/
Notify("Notify", 4),
/**
* Update [RFC2136]
*/
Update("Update", 5);
/**
* DNS RCode types are encoded on the last 4 bits
*/
static final int OpCode_MASK = 0x7800;
private final String _externalName;
private final int _index;
DNSOperationCode(String name, int index) {
_externalName = name;
_index = index;
}
/**
* Return the string representation of this type
*
* @return String
*/
public String externalName() {
return _externalName;
}
/**
* Return the numeric value of this type
*
* @return String
*/
public int indexValue() {
return _index;
}
/**
* @param flags
* @return label
*/
public static DNSOperationCode operationCodeForFlags(int flags) {
int maskedIndex = (flags & OpCode_MASK) >> 11;
for (DNSOperationCode aCode : DNSOperationCode.values()) {
if (aCode._index == maskedIndex) return aCode;
}
return Unassigned;
}
@Override
public String toString() {
return this.name() + " index " + this.indexValue();
}
}

View File

@ -0,0 +1,78 @@
/**
*
*/
package javax.jmdns.impl.constants;
/**
* DNS option code.
*
* @author Arthur van Hoff, Pierre Frisch, Rick Blair
*/
public enum DNSOptionCode {
/**
* Token
*/
Unknown("Unknown", 65535),
/**
* Long-Lived Queries Option [http://files.dns-sd.org/draft-sekar-dns-llq.txt]
*/
LLQ("LLQ", 1),
/**
* Update Leases Option [http://files.dns-sd.org/draft-sekar-dns-ul.txt]
*/
UL("UL", 2),
/**
* Name Server Identifier Option [RFC5001]
*/
NSID("NSID", 3),
/**
* Owner Option [draft-cheshire-edns0-owner-option]
*/
Owner("Owner", 4);
private final String _externalName;
private final int _index;
DNSOptionCode(String name, int index) {
_externalName = name;
_index = index;
}
/**
* Return the string representation of this type
*
* @return String
*/
public String externalName() {
return _externalName;
}
/**
* Return the numeric value of this type
*
* @return String
*/
public int indexValue() {
return _index;
}
/**
* @param optioncode
* @return label
*/
public static DNSOptionCode resultCodeForFlags(int optioncode) {
int maskedIndex = optioncode;
for (DNSOptionCode aCode : DNSOptionCode.values()) {
if (aCode._index == maskedIndex) return aCode;
}
return Unknown;
}
@Override
public String toString() {
return this.name() + " index " + this.indexValue();
}
}

View File

@ -0,0 +1,138 @@
/**
*
*/
package javax.jmdns.impl.constants;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* DNS Record Class
*
* @author Arthur van Hoff, Jeff Sonstein, Werner Randelshofer, Pierre Frisch, Rick Blair
*/
public enum DNSRecordClass {
/**
*
*/
CLASS_UNKNOWN("?", 0),
/**
* static final Internet
*/
CLASS_IN("in", 1),
/**
* CSNET
*/
CLASS_CS("cs", 2),
/**
* CHAOS
*/
CLASS_CH("ch", 3),
/**
* Hesiod
*/
CLASS_HS("hs", 4),
/**
* Used in DNS UPDATE [RFC 2136]
*/
CLASS_NONE("none", 254),
/**
* Not a DNS class, but a DNS query class, meaning "all classes"
*/
CLASS_ANY("any", 255);
private static Logger logger = Logger.getLogger(DNSRecordClass.class.getName());
/**
* Multicast DNS uses the bottom 15 bits to identify the record class...<br/>
* Except for pseudo records like OPT.
*/
public static final int CLASS_MASK = 0x7FFF;
/**
* For answers the top bit indicates that all other cached records are now invalid.<br/>
* For questions it indicates that we should send a unicast response.
*/
public static final int CLASS_UNIQUE = 0x8000;
/**
*
*/
public static final boolean UNIQUE = true;
/**
*
*/
public static final boolean NOT_UNIQUE = false;
private final String _externalName;
private final int _index;
DNSRecordClass(String name, int index) {
_externalName = name;
_index = index;
}
/**
* Return the string representation of this type
*
* @return String
*/
public String externalName() {
return _externalName;
}
/**
* Return the numeric value of this type
*
* @return String
*/
public int indexValue() {
return _index;
}
/**
* Checks if the class is unique
*
* @param index
* @return <code>true</code> is the class is unique, <code>false</code> otherwise.
*/
public boolean isUnique(int index) {
return (this != CLASS_UNKNOWN) && ((index & CLASS_UNIQUE) != 0);
}
/**
* @param name
* @return class for name
*/
public static DNSRecordClass classForName(String name) {
if (name != null) {
String aName = name.toLowerCase();
for (DNSRecordClass aClass : DNSRecordClass.values()) {
if (aClass._externalName.equals(aName)) return aClass;
}
}
logger.log(Level.WARNING, "Could not find record class for name: " + name);
return CLASS_UNKNOWN;
}
/**
* @param index
* @return class for name
*/
public static DNSRecordClass classForIndex(int index) {
int maskedIndex = index & CLASS_MASK;
for (DNSRecordClass aClass : DNSRecordClass.values()) {
if (aClass._index == maskedIndex) return aClass;
}
logger.log(Level.WARNING, "Could not find record class for index: " + index);
return CLASS_UNKNOWN;
}
@Override
public String toString() {
return this.name() + " index " + this.indexValue();
}
}

View File

@ -0,0 +1,312 @@
/**
*
*/
package javax.jmdns.impl.constants;
import java.util.logging.Logger;
/**
* DNS Record Type
*
* @author Arthur van Hoff, Jeff Sonstein, Werner Randelshofer, Pierre Frisch, Rick Blair
*/
public enum DNSRecordType {
/**
* Address
*/
TYPE_IGNORE("ignore", 0),
/**
* Address
*/
TYPE_A("a", 1),
/**
* Name Server
*/
TYPE_NS("ns", 2),
/**
* Mail Destination
*/
TYPE_MD("md", 3),
/**
* Mail Forwarder
*/
TYPE_MF("mf", 4),
/**
* Canonical Name
*/
TYPE_CNAME("cname", 5),
/**
* Start of Authority
*/
TYPE_SOA("soa", 6),
/**
* Mailbox
*/
TYPE_MB("mb", 7),
/**
* Mail Group
*/
TYPE_MG("mg", 8),
/**
* Mail Rename
*/
TYPE_MR("mr", 9),
/**
* NULL RR
*/
TYPE_NULL("null", 10),
/**
* Well-known-service
*/
TYPE_WKS("wks", 11),
/**
* Domain Name pointer
*/
TYPE_PTR("ptr", 12),
/**
* Host information
*/
TYPE_HINFO("hinfo", 13),
/**
* Mailbox information
*/
TYPE_MINFO("minfo", 14),
/**
* Mail exchanger
*/
TYPE_MX("mx", 15),
/**
* Arbitrary text string
*/
TYPE_TXT("txt", 16),
/**
* for Responsible Person [RFC1183]
*/
TYPE_RP("rp", 17),
/**
* for AFS Data Base location [RFC1183]
*/
TYPE_AFSDB("afsdb", 18),
/**
* for X.25 PSDN address [RFC1183]
*/
TYPE_X25("x25", 19),
/**
* for ISDN address [RFC1183]
*/
TYPE_ISDN("isdn", 20),
/**
* for Route Through [RFC1183]
*/
TYPE_RT("rt", 21),
/**
* for NSAP address, NSAP style A record [RFC1706]
*/
TYPE_NSAP("nsap", 22),
/**
*
*/
TYPE_NSAP_PTR("nsap-otr", 23),
/**
* for security signature [RFC2931]
*/
TYPE_SIG("sig", 24),
/**
* for security key [RFC2535]
*/
TYPE_KEY("key", 25),
/**
* X.400 mail mapping information [RFC2163]
*/
TYPE_PX("px", 26),
/**
* Geographical Position [RFC1712]
*/
TYPE_GPOS("gpos", 27),
/**
* IP6 Address [Thomson]
*/
TYPE_AAAA("aaaa", 28),
/**
* Location Information [Vixie]
*/
TYPE_LOC("loc", 29),
/**
* Next Domain - OBSOLETE [RFC2535, RFC3755]
*/
TYPE_NXT("nxt", 30),
/**
* Endpoint Identifier [Patton]
*/
TYPE_EID("eid", 31),
/**
* Nimrod Locator [Patton]
*/
TYPE_NIMLOC("nimloc", 32),
/**
* Server Selection [RFC2782]
*/
TYPE_SRV("srv", 33),
/**
* ATM Address [Dobrowski]
*/
TYPE_ATMA("atma", 34),
/**
* Naming Authority Pointer [RFC2168, RFC2915]
*/
TYPE_NAPTR("naptr", 35),
/**
* Key Exchanger [RFC2230]
*/
TYPE_KX("kx", 36),
/**
* CERT [RFC2538]
*/
TYPE_CERT("cert", 37),
/**
* A6 [RFC2874]
*/
TYPE_A6("a6", 38),
/**
* DNAME [RFC2672]
*/
TYPE_DNAME("dname", 39),
/**
* SINK [Eastlake]
*/
TYPE_SINK("sink", 40),
/**
* OPT [RFC2671]
*/
TYPE_OPT("opt", 41),
/**
* APL [RFC3123]
*/
TYPE_APL("apl", 42),
/**
* Delegation Signer [RFC3658]
*/
TYPE_DS("ds", 43),
/**
* SSH Key Fingerprint [RFC-ietf-secsh-dns-05.txt]
*/
TYPE_SSHFP("sshfp", 44),
/**
* RRSIG [RFC3755]
*/
TYPE_RRSIG("rrsig", 46),
/**
* NSEC [RFC3755]
*/
TYPE_NSEC("nsec", 47),
/**
* DNSKEY [RFC3755]
*/
TYPE_DNSKEY("dnskey", 48),
/**
* [IANA-Reserved]
*/
TYPE_UINFO("uinfo", 100),
/**
* [IANA-Reserved]
*/
TYPE_UID("uid", 101),
/**
* [IANA-Reserved]
*/
TYPE_GID("gid", 102),
/**
* [IANA-Reserved]
*/
TYPE_UNSPEC("unspec", 103),
/**
* Transaction Key [RFC2930]
*/
TYPE_TKEY("tkey", 249),
/**
* Transaction Signature [RFC2845]
*/
TYPE_TSIG("tsig", 250),
/**
* Incremental transfer [RFC1995]
*/
TYPE_IXFR("ixfr", 251),
/**
* Transfer of an entire zone [RFC1035]
*/
TYPE_AXFR("axfr", 252),
/**
* Mailbox-related records (MB, MG or MR) [RFC1035]
*/
TYPE_MAILA("mails", 253),
/**
* Mail agent RRs (Obsolete - see MX) [RFC1035]
*/
TYPE_MAILB("mailb", 254),
/**
* Request for all records [RFC1035]
*/
TYPE_ANY("any", 255);
private static Logger logger = Logger.getLogger(DNSRecordType.class.getName());
private final String _externalName;
private final int _index;
DNSRecordType(String name, int index) {
_externalName = name;
_index = index;
}
/**
* Return the string representation of this type
*
* @return String
*/
public String externalName() {
return _externalName;
}
/**
* Return the numeric value of this type
*
* @return String
*/
public int indexValue() {
return _index;
}
/**
* @param name
* @return type for name
*/
public static DNSRecordType typeForName(String name) {
if (name != null) {
String aName = name.toLowerCase();
for (DNSRecordType aType : DNSRecordType.values()) {
if (aType._externalName.equals(aName)) return aType;
}
}
logger.severe("Could not find record type for name: " + name);
return TYPE_IGNORE;
}
/**
* @param index
* @return type for name
*/
public static DNSRecordType typeForIndex(int index) {
for (DNSRecordType aType : DNSRecordType.values()) {
if (aType._index == index) return aType;
}
logger.severe("Could not find record type for index: " + index);
return TYPE_IGNORE;
}
@Override
public String toString() {
return this.name() + " index " + this.indexValue();
}
}

View File

@ -0,0 +1,149 @@
/**
*
*/
package javax.jmdns.impl.constants;
/**
* DNS result code.
*
* @author Arthur van Hoff, Jeff Sonstein, Werner Randelshofer, Pierre Frisch, Rick Blair
*/
public enum DNSResultCode {
/**
* Token
*/
Unknown("Unknown", 65535),
/**
* No Error [RFC1035]
*/
NoError("No Error", 0),
/**
* Format Error [RFC1035]
*/
FormErr("Format Error", 1),
/**
* Server Failure [RFC1035]
*/
ServFail("Server Failure", 2),
/**
* Non-Existent Domain [RFC1035]
*/
NXDomain("Non-Existent Domain", 3),
/**
* Not Implemented [RFC1035]
*/
NotImp("Not Implemented", 4),
/**
* Query Refused [RFC1035]
*/
Refused("Query Refused", 5),
/**
* Name Exists when it should not [RFC2136]
*/
YXDomain("Name Exists when it should not", 6),
/**
* RR Set Exists when it should not [RFC2136]
*/
YXRRSet("RR Set Exists when it should not", 7),
/**
* RR Set that should exist does not [RFC2136]
*/
NXRRSet("RR Set that should exist does not", 8),
/**
* Server Not Authoritative for zone [RFC2136]]
*/
NotAuth("Server Not Authoritative for zone", 9),
/**
* Name not contained in zone [RFC2136]
*/
NotZone("NotZone Name not contained in zone", 10),
;
// 0 NoError No Error [RFC1035]
// 1 FormErr Format Error [RFC1035]
// 2 ServFail Server Failure [RFC1035]
// 3 NXDomain Non-Existent Domain [RFC1035]
// 4 NotImp Not Implemented [RFC1035]
// 5 Refused Query Refused [RFC1035]
// 6 YXDomain Name Exists when it should not [RFC2136]
// 7 YXRRSet RR Set Exists when it should not [RFC2136]
// 8 NXRRSet RR Set that should exist does not [RFC2136]
// 9 NotAuth Server Not Authoritative for zone [RFC2136]
// 10 NotZone Name not contained in zone [RFC2136]
// 11-15 Unassigned
// 16 BADVERS Bad OPT Version [RFC2671]
// 16 BADSIG TSIG Signature Failure [RFC2845]
// 17 BADKEY Key not recognized [RFC2845]
// 18 BADTIME Signature out of time window [RFC2845]
// 19 BADMODE Bad TKEY Mode [RFC2930]
// 20 BADNAME Duplicate key name [RFC2930]
// 21 BADALG Algorithm not supported [RFC2930]
// 22 BADTRUNC Bad Truncation [RFC4635]
// 23-3840 Unassigned
// 3841-4095 Reserved for Private Use [RFC5395]
// 4096-65534 Unassigned
// 65535 Reserved, can be allocated by Standards Action [RFC5395]
/**
* DNS Result Code types are encoded on the last 4 bits
*/
final static int RCode_MASK = 0x0F;
/**
* DNS Extended Result Code types are encoded on the first 8 bits
*/
final static int ExtendedRCode_MASK = 0xFF;
private final String _externalName;
private final int _index;
DNSResultCode(String name, int index) {
_externalName = name;
_index = index;
}
/**
* Return the string representation of this type
*
* @return String
*/
public String externalName() {
return _externalName;
}
/**
* Return the numeric value of this type
*
* @return String
*/
public int indexValue() {
return _index;
}
/**
* @param flags
* @return label
*/
public static DNSResultCode resultCodeForFlags(int flags) {
int maskedIndex = flags & RCode_MASK;
for (DNSResultCode aCode : DNSResultCode.values()) {
if (aCode._index == maskedIndex) return aCode;
}
return Unknown;
}
public static DNSResultCode resultCodeForFlags(int flags, int extendedRCode) {
int maskedIndex = ((extendedRCode >> 28) & ExtendedRCode_MASK) | (flags & RCode_MASK);
for (DNSResultCode aCode : DNSResultCode.values()) {
if (aCode._index == maskedIndex) return aCode;
}
return Unknown;
}
@Override
public String toString() {
return this.name() + " index " + this.indexValue();
}
}

View File

@ -0,0 +1,215 @@
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl.constants;
/**
* DNSState defines the possible states for services registered with JmDNS.
*
* @author Werner Randelshofer, Rick Blair, Pierre Frisch
*/
public enum DNSState {
/**
*
*/
PROBING_1("probing 1", StateClass.probing),
/**
*
*/
PROBING_2("probing 2", StateClass.probing),
/**
*
*/
PROBING_3("probing 3", StateClass.probing),
/**
*
*/
ANNOUNCING_1("announcing 1", StateClass.announcing),
/**
*
*/
ANNOUNCING_2("announcing 2", StateClass.announcing),
/**
*
*/
ANNOUNCED("announced", StateClass.announced),
/**
*
*/
CANCELING_1("canceling 1", StateClass.canceling),
/**
*
*/
CANCELING_2("canceling 2", StateClass.canceling),
/**
*
*/
CANCELING_3("canceling 3", StateClass.canceling),
/**
*
*/
CANCELED("canceled", StateClass.canceled),
/**
*
*/
CLOSING("closing", StateClass.closing),
/**
*
*/
CLOSED("closed", StateClass.closed);
private enum StateClass {
probing, announcing, announced, canceling, canceled, closing, closed
}
// private static Logger logger = Logger.getLogger(DNSState.class.getName());
private final String _name;
private final StateClass _state;
private DNSState(String name, StateClass state) {
_name = name;
_state = state;
}
@Override
public final String toString() {
return _name;
}
/**
* Returns the next advanced state.<br/>
* In general, this advances one step in the following sequence: PROBING_1, PROBING_2, PROBING_3, ANNOUNCING_1, ANNOUNCING_2, ANNOUNCED.<br/>
* or CANCELING_1, CANCELING_2, CANCELING_3, CANCELED Does not advance for ANNOUNCED and CANCELED state.
*
* @return next state
*/
public final DNSState advance() {
switch (this) {
case PROBING_1:
return PROBING_2;
case PROBING_2:
return PROBING_3;
case PROBING_3:
return ANNOUNCING_1;
case ANNOUNCING_1:
return ANNOUNCING_2;
case ANNOUNCING_2:
return ANNOUNCED;
case ANNOUNCED:
return ANNOUNCED;
case CANCELING_1:
return CANCELING_2;
case CANCELING_2:
return CANCELING_3;
case CANCELING_3:
return CANCELED;
case CANCELED:
return CANCELED;
case CLOSING:
return CLOSED;
case CLOSED:
return CLOSED;
default:
// This is just to keep the compiler happy as we have covered all cases before.
return this;
}
}
/**
* Returns to the next reverted state. All states except CANCELED revert to PROBING_1. Status CANCELED does not revert.
*
* @return reverted state
*/
public final DNSState revert() {
switch (this) {
case PROBING_1:
case PROBING_2:
case PROBING_3:
case ANNOUNCING_1:
case ANNOUNCING_2:
case ANNOUNCED:
return PROBING_1;
case CANCELING_1:
case CANCELING_2:
case CANCELING_3:
return CANCELING_1;
case CANCELED:
return CANCELED;
case CLOSING:
return CLOSING;
case CLOSED:
return CLOSED;
default:
// This is just to keep the compiler happy as we have covered all cases before.
return this;
}
}
/**
* Returns true, if this is a probing state.
*
* @return <code>true</code> if probing state, <code>false</code> otherwise
*/
public final boolean isProbing() {
return _state == StateClass.probing;
}
/**
* Returns true, if this is an announcing state.
*
* @return <code>true</code> if announcing state, <code>false</code> otherwise
*/
public final boolean isAnnouncing() {
return _state == StateClass.announcing;
}
/**
* Returns true, if this is an announced state.
*
* @return <code>true</code> if announced state, <code>false</code> otherwise
*/
public final boolean isAnnounced() {
return _state == StateClass.announced;
}
/**
* Returns true, if this is a canceling state.
*
* @return <code>true</code> if canceling state, <code>false</code> otherwise
*/
public final boolean isCanceling() {
return _state == StateClass.canceling;
}
/**
* Returns true, if this is a canceled state.
*
* @return <code>true</code> if canceled state, <code>false</code> otherwise
*/
public final boolean isCanceled() {
return _state == StateClass.canceled;
}
/**
* Returns true, if this is a closing state.
*
* @return <code>true</code> if closing state, <code>false</code> otherwise
*/
public final boolean isClosing() {
return _state == StateClass.closing;
}
/**
* Returns true, if this is a closing state.
*
* @return <code>true</code> if closed state, <code>false</code> otherwise
*/
public final boolean isClosed() {
return _state == StateClass.closed;
}
}

View File

@ -0,0 +1,2 @@
package javax.jmdns.impl.constants;

View File

@ -0,0 +1,2 @@
package javax.jmdns.impl;

View File

@ -0,0 +1,223 @@
// Licensed under Apache License version 2.0
package javax.jmdns.impl.tasks;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import javax.jmdns.impl.DNSIncoming;
import javax.jmdns.impl.DNSOutgoing;
import javax.jmdns.impl.DNSQuestion;
import javax.jmdns.impl.DNSRecord;
import javax.jmdns.impl.JmDNSImpl;
import javax.jmdns.impl.constants.DNSConstants;
/**
* This is the root class for all task scheduled by the timer in JmDNS.
*
* @author Pierre Frisch
*/
public abstract class DNSTask extends TimerTask {
/**
*
*/
private final JmDNSImpl _jmDNSImpl;
/**
* @param jmDNSImpl
*/
protected DNSTask(JmDNSImpl jmDNSImpl) {
super();
this._jmDNSImpl = jmDNSImpl;
}
/**
* Return the DNS associated with this task.
*
* @return associated DNS
*/
public JmDNSImpl getDns() {
return _jmDNSImpl;
}
/**
* Start this task.
*
* @param timer
* task timer.
*/
public abstract void start(Timer timer);
/**
* Return this task name.
*
* @return task name
*/
public abstract String getName();
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return this.getName();
}
/**
* Add a question to the message.
*
* @param out
* outgoing message
* @param rec
* DNS question
* @return outgoing message for the next question
* @exception IOException
*/
public DNSOutgoing addQuestion(DNSOutgoing out, DNSQuestion rec) throws IOException {
DNSOutgoing newOut = out;
try {
newOut.addQuestion(rec);
} catch (final IOException e) {
int flags = newOut.getFlags();
boolean multicast = newOut.isMulticast();
int maxUDPPayload = newOut.getMaxUDPPayload();
int id = newOut.getId();
newOut.setFlags(flags | DNSConstants.FLAGS_TC);
newOut.setId(id);
this._jmDNSImpl.send(newOut);
newOut = new DNSOutgoing(flags, multicast, maxUDPPayload);
newOut.addQuestion(rec);
}
return newOut;
}
/**
* Add an answer if it is not suppressed.
*
* @param out
* outgoing message
* @param in
* incoming request
* @param rec
* DNS record answer
* @return outgoing message for the next answer
* @exception IOException
*/
public DNSOutgoing addAnswer(DNSOutgoing out, DNSIncoming in, DNSRecord rec) throws IOException {
DNSOutgoing newOut = out;
try {
newOut.addAnswer(in, rec);
} catch (final IOException e) {
int flags = newOut.getFlags();
boolean multicast = newOut.isMulticast();
int maxUDPPayload = newOut.getMaxUDPPayload();
int id = newOut.getId();
newOut.setFlags(flags | DNSConstants.FLAGS_TC);
newOut.setId(id);
this._jmDNSImpl.send(newOut);
newOut = new DNSOutgoing(flags, multicast, maxUDPPayload);
newOut.addAnswer(in, rec);
}
return newOut;
}
/**
* Add an answer to the message.
*
* @param out
* outgoing message
* @param rec
* DNS record answer
* @param now
* @return outgoing message for the next answer
* @exception IOException
*/
public DNSOutgoing addAnswer(DNSOutgoing out, DNSRecord rec, long now) throws IOException {
DNSOutgoing newOut = out;
try {
newOut.addAnswer(rec, now);
} catch (final IOException e) {
int flags = newOut.getFlags();
boolean multicast = newOut.isMulticast();
int maxUDPPayload = newOut.getMaxUDPPayload();
int id = newOut.getId();
newOut.setFlags(flags | DNSConstants.FLAGS_TC);
newOut.setId(id);
this._jmDNSImpl.send(newOut);
newOut = new DNSOutgoing(flags, multicast, maxUDPPayload);
newOut.addAnswer(rec, now);
}
return newOut;
}
/**
* Add an authoritative answer to the message.
*
* @param out
* outgoing message
* @param rec
* DNS record answer
* @return outgoing message for the next answer
* @exception IOException
*/
public DNSOutgoing addAuthoritativeAnswer(DNSOutgoing out, DNSRecord rec) throws IOException {
DNSOutgoing newOut = out;
try {
newOut.addAuthorativeAnswer(rec);
} catch (final IOException e) {
int flags = newOut.getFlags();
boolean multicast = newOut.isMulticast();
int maxUDPPayload = newOut.getMaxUDPPayload();
int id = newOut.getId();
newOut.setFlags(flags | DNSConstants.FLAGS_TC);
newOut.setId(id);
this._jmDNSImpl.send(newOut);
newOut = new DNSOutgoing(flags, multicast, maxUDPPayload);
newOut.addAuthorativeAnswer(rec);
}
return newOut;
}
/**
* Add an additional answer to the record. Omit if there is no room.
*
* @param out
* outgoing message
* @param in
* incoming request
* @param rec
* DNS record answer
* @return outgoing message for the next answer
* @exception IOException
*/
public DNSOutgoing addAdditionalAnswer(DNSOutgoing out, DNSIncoming in, DNSRecord rec) throws IOException {
DNSOutgoing newOut = out;
try {
newOut.addAdditionalAnswer(in, rec);
} catch (final IOException e) {
int flags = newOut.getFlags();
boolean multicast = newOut.isMulticast();
int maxUDPPayload = newOut.getMaxUDPPayload();
int id = newOut.getId();
newOut.setFlags(flags | DNSConstants.FLAGS_TC);
newOut.setId(id);
this._jmDNSImpl.send(newOut);
newOut = new DNSOutgoing(flags, multicast, maxUDPPayload);
newOut.addAdditionalAnswer(in, rec);
}
return newOut;
}
}

View File

@ -0,0 +1,61 @@
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl.tasks;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jmdns.impl.JmDNSImpl;
import javax.jmdns.impl.constants.DNSConstants;
/**
* Periodically removes expired entries from the cache.
*/
public class RecordReaper extends DNSTask {
static Logger logger = Logger.getLogger(RecordReaper.class.getName());
/**
* @param jmDNSImpl
*/
public RecordReaper(JmDNSImpl jmDNSImpl) {
super(jmDNSImpl);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.DNSTask#getName()
*/
@Override
public String getName() {
return "RecordReaper(" + (this.getDns() != null ? this.getDns().getName() : "") + ")";
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.DNSTask#start(java.util.Timer)
*/
@Override
public void start(Timer timer) {
if (!this.getDns().isCanceling() && !this.getDns().isCanceled()) {
timer.schedule(this, DNSConstants.RECORD_REAPER_INTERVAL, DNSConstants.RECORD_REAPER_INTERVAL);
}
}
@Override
public void run() {
if (this.getDns().isCanceling() || this.getDns().isCanceled()) {
return;
}
if (logger.isLoggable(Level.FINEST)) {
logger.finest(this.getName() + ".run() JmDNS reaping cache");
}
// Remove expired answers from the cache
// -------------------------------------
this.getDns().cleanCache();
}
}

View File

@ -0,0 +1,157 @@
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl.tasks;
import java.util.HashSet;
import java.util.Set;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jmdns.impl.DNSIncoming;
import javax.jmdns.impl.DNSOutgoing;
import javax.jmdns.impl.DNSQuestion;
import javax.jmdns.impl.DNSRecord;
import javax.jmdns.impl.JmDNSImpl;
import javax.jmdns.impl.constants.DNSConstants;
/**
* The Responder sends a single answer for the specified service infos and for the host name.
*/
public class Responder extends DNSTask {
static Logger logger = Logger.getLogger(Responder.class.getName());
/**
*
*/
private final DNSIncoming _in;
/**
*
*/
private final boolean _unicast;
public Responder(JmDNSImpl jmDNSImpl, DNSIncoming in, int port) {
super(jmDNSImpl);
this._in = in;
this._unicast = (port != DNSConstants.MDNS_PORT);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.DNSTask#getName()
*/
@Override
public String getName() {
return "Responder(" + (this.getDns() != null ? this.getDns().getName() : "") + ")";
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return super.toString() + " incomming: " + _in;
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.DNSTask#start(java.util.Timer)
*/
@Override
public void start(Timer timer) {
// According to draft-cheshire-dnsext-multicastdns.txt chapter "7 Responding":
// We respond immediately if we know for sure, that we are the only one who can respond to the query.
// In all other cases, we respond within 20-120 ms.
//
// According to draft-cheshire-dnsext-multicastdns.txt chapter "6.2 Multi-Packet Known Answer Suppression":
// We respond after 20-120 ms if the query is truncated.
boolean iAmTheOnlyOne = true;
for (DNSQuestion question : _in.getQuestions()) {
if (logger.isLoggable(Level.FINEST)) {
logger.finest(this.getName() + "start() question=" + question);
}
iAmTheOnlyOne = question.iAmTheOnlyOne(this.getDns());
if (!iAmTheOnlyOne) {
break;
}
}
int delay = (iAmTheOnlyOne && !_in.isTruncated()) ? 0 : DNSConstants.RESPONSE_MIN_WAIT_INTERVAL + JmDNSImpl.getRandom().nextInt(DNSConstants.RESPONSE_MAX_WAIT_INTERVAL - DNSConstants.RESPONSE_MIN_WAIT_INTERVAL + 1) - _in.elapseSinceArrival();
if (delay < 0) {
delay = 0;
}
if (logger.isLoggable(Level.FINEST)) {
logger.finest(this.getName() + "start() Responder chosen delay=" + delay);
}
if (!this.getDns().isCanceling() && !this.getDns().isCanceled()) {
timer.schedule(this, delay);
}
}
@Override
public void run() {
this.getDns().respondToQuery(_in);
// We use these sets to prevent duplicate records
Set<DNSQuestion> questions = new HashSet<DNSQuestion>();
Set<DNSRecord> answers = new HashSet<DNSRecord>();
if (this.getDns().isAnnounced()) {
try {
// Answer questions
for (DNSQuestion question : _in.getQuestions()) {
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.getName() + "run() JmDNS responding to: " + question);
}
// for unicast responses the question must be included
if (_unicast) {
// out.addQuestion(q);
questions.add(question);
}
question.addAnswers(this.getDns(), answers);
}
// remove known answers, if the ttl is at least half of the correct value. (See Draft Cheshire chapter 7.1.).
long now = System.currentTimeMillis();
for (DNSRecord knownAnswer : _in.getAnswers()) {
if (knownAnswer.isStale(now)) {
answers.remove(knownAnswer);
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.getName() + "JmDNS Responder Known Answer Removed");
}
}
}
// respond if we have answers
if (!answers.isEmpty()) {
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.getName() + "run() JmDNS responding");
}
DNSOutgoing out = new DNSOutgoing(DNSConstants.FLAGS_QR_RESPONSE | DNSConstants.FLAGS_AA, !_unicast, _in.getSenderUDPPayload());
out.setId(_in.getId());
for (DNSQuestion question : questions) {
if (question != null) {
out = this.addQuestion(out, question);
}
}
for (DNSRecord answer : answers) {
if (answer != null) {
out = this.addAnswer(out, _in, answer);
}
}
if (!out.isEmpty()) this.getDns().send(out);
}
// this.cancel();
} catch (Throwable e) {
logger.log(Level.WARNING, this.getName() + "run() exception ", e);
this.getDns().close();
}
}
}
}

View File

@ -0,0 +1,2 @@
package javax.jmdns.impl.tasks;

View File

@ -0,0 +1,116 @@
// Licensed under Apache License version 2.0
package javax.jmdns.impl.tasks.resolver;
import java.io.IOException;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jmdns.impl.DNSOutgoing;
import javax.jmdns.impl.JmDNSImpl;
import javax.jmdns.impl.constants.DNSConstants;
import javax.jmdns.impl.tasks.DNSTask;
/**
* This is the root class for all resolver tasks.
*
* @author Pierre Frisch
*/
public abstract class DNSResolverTask extends DNSTask {
private static Logger logger = Logger.getLogger(DNSResolverTask.class.getName());
/**
* Counts the number of queries being sent.
*/
protected int _count = 0;
/**
* @param jmDNSImpl
*/
public DNSResolverTask(JmDNSImpl jmDNSImpl) {
super(jmDNSImpl);
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return super.toString() + " count: " + _count;
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.DNSTask#start(java.util.Timer)
*/
@Override
public void start(Timer timer) {
if (!this.getDns().isCanceling() && !this.getDns().isCanceled()) {
timer.schedule(this, DNSConstants.QUERY_WAIT_INTERVAL, DNSConstants.QUERY_WAIT_INTERVAL);
}
}
/*
* (non-Javadoc)
* @see java.util.TimerTask#run()
*/
@Override
public void run() {
try {
if (this.getDns().isCanceling() || this.getDns().isCanceled()) {
this.cancel();
} else {
if (_count++ < 3) {
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.getName() + ".run() JmDNS " + this.description());
}
DNSOutgoing out = new DNSOutgoing(DNSConstants.FLAGS_QR_QUERY);
out = this.addQuestions(out);
if (this.getDns().isAnnounced()) {
out = this.addAnswers(out);
}
if (!out.isEmpty()) {
this.getDns().send(out);
}
} else {
// After three queries, we can quit.
this.cancel();
}
}
} catch (Throwable e) {
logger.log(Level.WARNING, this.getName() + ".run() exception ", e);
this.getDns().recover();
}
}
/**
* Overridden by subclasses to add questions to the message.<br/>
* <b>Note:</b> Because of message size limitation the returned message may be different than the message parameter.
*
* @param out
* outgoing message
* @return the outgoing message.
* @exception IOException
*/
protected abstract DNSOutgoing addQuestions(DNSOutgoing out) throws IOException;
/**
* Overridden by subclasses to add questions to the message.<br/>
* <b>Note:</b> Because of message size limitation the returned message may be different than the message parameter.
*
* @param out
* outgoing message
* @return the outgoing message.
* @exception IOException
*/
protected abstract DNSOutgoing addAnswers(DNSOutgoing out) throws IOException;
/**
* Returns a description of the resolver for debugging
*
* @return resolver description
*/
protected abstract String description();
}

View File

@ -0,0 +1,107 @@
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl.tasks.resolver;
import java.io.IOException;
import javax.jmdns.impl.DNSEntry;
import javax.jmdns.impl.DNSOutgoing;
import javax.jmdns.impl.DNSQuestion;
import javax.jmdns.impl.DNSRecord;
import javax.jmdns.impl.JmDNSImpl;
import javax.jmdns.impl.ServiceInfoImpl;
import javax.jmdns.impl.constants.DNSRecordClass;
import javax.jmdns.impl.constants.DNSRecordType;
/**
* The ServiceInfoResolver queries up to three times consecutively for a service info, and then removes itself from the timer.
* <p/>
* The ServiceInfoResolver will run only if JmDNS is in state ANNOUNCED. REMIND: Prevent having multiple service resolvers for the same info in the timer queue.
*/
public class ServiceInfoResolver extends DNSResolverTask {
private final ServiceInfoImpl _info;
public ServiceInfoResolver(JmDNSImpl jmDNSImpl, ServiceInfoImpl info) {
super(jmDNSImpl);
this._info = info;
info.setDns(this.getDns());
this.getDns().addListener(info, DNSQuestion.newQuestion(info.getQualifiedName(), DNSRecordType.TYPE_ANY, DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE));
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.DNSTask#getName()
*/
@Override
public String getName() {
return "ServiceInfoResolver(" + (this.getDns() != null ? this.getDns().getName() : "") + ")";
}
/*
* (non-Javadoc)
* @see java.util.TimerTask#cancel()
*/
@Override
public boolean cancel() {
// We should not forget to remove the listener
boolean result = super.cancel();
if (!_info.isPersistent()) {
this.getDns().removeListener(_info);
}
return result;
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.Resolver#addAnswers(javax.jmdns.impl.DNSOutgoing)
*/
@Override
protected DNSOutgoing addAnswers(DNSOutgoing out) throws IOException {
DNSOutgoing newOut = out;
if (!_info.hasData()) {
long now = System.currentTimeMillis();
newOut = this.addAnswer(newOut, (DNSRecord) this.getDns().getCache().getDNSEntry(_info.getQualifiedName(), DNSRecordType.TYPE_SRV, DNSRecordClass.CLASS_IN), now);
newOut = this.addAnswer(newOut, (DNSRecord) this.getDns().getCache().getDNSEntry(_info.getQualifiedName(), DNSRecordType.TYPE_TXT, DNSRecordClass.CLASS_IN), now);
if (_info.getServer().length() > 0) {
for (DNSEntry addressEntry : this.getDns().getCache().getDNSEntryList(_info.getServer(), DNSRecordType.TYPE_A, DNSRecordClass.CLASS_IN)) {
newOut = this.addAnswer(newOut, (DNSRecord) addressEntry, now);
}
for (DNSEntry addressEntry : this.getDns().getCache().getDNSEntryList(_info.getServer(), DNSRecordType.TYPE_AAAA, DNSRecordClass.CLASS_IN)) {
newOut = this.addAnswer(newOut, (DNSRecord) addressEntry, now);
}
}
}
return newOut;
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.Resolver#addQuestions(javax.jmdns.impl.DNSOutgoing)
*/
@Override
protected DNSOutgoing addQuestions(DNSOutgoing out) throws IOException {
DNSOutgoing newOut = out;
if (!_info.hasData()) {
newOut = this.addQuestion(newOut, DNSQuestion.newQuestion(_info.getQualifiedName(), DNSRecordType.TYPE_SRV, DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE));
newOut = this.addQuestion(newOut, DNSQuestion.newQuestion(_info.getQualifiedName(), DNSRecordType.TYPE_TXT, DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE));
if (_info.getServer().length() > 0) {
newOut = this.addQuestion(newOut, DNSQuestion.newQuestion(_info.getServer(), DNSRecordType.TYPE_A, DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE));
newOut = this.addQuestion(newOut, DNSQuestion.newQuestion(_info.getServer(), DNSRecordType.TYPE_AAAA, DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE));
}
}
return newOut;
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.Resolver#description()
*/
@Override
protected String description() {
return "querying service info: " + (_info != null ? _info.getQualifiedName() : "null");
}
}

View File

@ -0,0 +1,77 @@
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl.tasks.resolver;
import java.io.IOException;
import javax.jmdns.ServiceInfo;
import javax.jmdns.impl.DNSOutgoing;
import javax.jmdns.impl.DNSQuestion;
import javax.jmdns.impl.DNSRecord;
import javax.jmdns.impl.JmDNSImpl;
import javax.jmdns.impl.constants.DNSConstants;
import javax.jmdns.impl.constants.DNSRecordClass;
import javax.jmdns.impl.constants.DNSRecordType;
/**
* The ServiceResolver queries three times consecutively for services of a given type, and then removes itself from the timer.
* <p/>
* The ServiceResolver will run only if JmDNS is in state ANNOUNCED. REMIND: Prevent having multiple service resolvers for the same type in the timer queue.
*/
public class ServiceResolver extends DNSResolverTask {
private final String _type;
public ServiceResolver(JmDNSImpl jmDNSImpl, String type) {
super(jmDNSImpl);
this._type = type;
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.DNSTask#getName()
*/
@Override
public String getName() {
return "ServiceResolver(" + (this.getDns() != null ? this.getDns().getName() : "") + ")";
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.Resolver#addAnswers(javax.jmdns.impl.DNSOutgoing)
*/
@Override
protected DNSOutgoing addAnswers(DNSOutgoing out) throws IOException {
DNSOutgoing newOut = out;
long now = System.currentTimeMillis();
for (ServiceInfo info : this.getDns().getServices().values()) {
newOut = this.addAnswer(newOut, new DNSRecord.Pointer(info.getType(), DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE, DNSConstants.DNS_TTL, info.getQualifiedName()), now);
// newOut = this.addAnswer(newOut, new DNSRecord.Service(info.getQualifiedName(), DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE, DNSConstants.DNS_TTL, info.getPriority(), info.getWeight(), info.getPort(),
// this.getDns().getLocalHost().getName()), now);
}
return newOut;
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.Resolver#addQuestions(javax.jmdns.impl.DNSOutgoing)
*/
@Override
protected DNSOutgoing addQuestions(DNSOutgoing out) throws IOException {
DNSOutgoing newOut = out;
newOut = this.addQuestion(newOut, DNSQuestion.newQuestion(_type, DNSRecordType.TYPE_PTR, DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE));
// newOut = this.addQuestion(newOut, DNSQuestion.newQuestion(_type, DNSRecordType.TYPE_SRV, DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE));
return newOut;
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.Resolver#description()
*/
@Override
protected String description() {
return "querying service";
}
}

View File

@ -0,0 +1,75 @@
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl.tasks.resolver;
import java.io.IOException;
import javax.jmdns.impl.DNSOutgoing;
import javax.jmdns.impl.DNSQuestion;
import javax.jmdns.impl.DNSRecord;
import javax.jmdns.impl.JmDNSImpl;
import javax.jmdns.impl.JmDNSImpl.ServiceTypeEntry;
import javax.jmdns.impl.constants.DNSConstants;
import javax.jmdns.impl.constants.DNSRecordClass;
import javax.jmdns.impl.constants.DNSRecordType;
/**
* Helper class to resolve service types.
* <p/>
* The TypeResolver queries three times consecutively for service types, and then removes itself from the timer.
* <p/>
* The TypeResolver will run only if JmDNS is in state ANNOUNCED.
*/
public class TypeResolver extends DNSResolverTask {
/**
* @param jmDNSImpl
*/
public TypeResolver(JmDNSImpl jmDNSImpl) {
super(jmDNSImpl);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.DNSTask#getName()
*/
@Override
public String getName() {
return "TypeResolver(" + (this.getDns() != null ? this.getDns().getName() : "") + ")";
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.Resolver#addAnswers(javax.jmdns.impl.DNSOutgoing)
*/
@Override
protected DNSOutgoing addAnswers(DNSOutgoing out) throws IOException {
DNSOutgoing newOut = out;
long now = System.currentTimeMillis();
for (String type : this.getDns().getServiceTypes().keySet()) {
ServiceTypeEntry typeEntry = this.getDns().getServiceTypes().get(type);
newOut = this.addAnswer(newOut, new DNSRecord.Pointer("_services._dns-sd._udp.local.", DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE, DNSConstants.DNS_TTL, typeEntry.getType()), now);
}
return newOut;
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.Resolver#addQuestions(javax.jmdns.impl.DNSOutgoing)
*/
@Override
protected DNSOutgoing addQuestions(DNSOutgoing out) throws IOException {
return this.addQuestion(out, DNSQuestion.newQuestion("_services._dns-sd._udp.local.", DNSRecordType.TYPE_PTR, DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE));
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.Resolver#description()
*/
@Override
protected String description() {
return "querying type";
}
}

View File

@ -0,0 +1,2 @@
package javax.jmdns.impl.tasks.resolver;

View File

@ -0,0 +1,146 @@
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl.tasks.state;
import java.io.IOException;
import java.util.Timer;
import java.util.logging.Logger;
import javax.jmdns.impl.DNSOutgoing;
import javax.jmdns.impl.DNSRecord;
import javax.jmdns.impl.JmDNSImpl;
import javax.jmdns.impl.ServiceInfoImpl;
import javax.jmdns.impl.constants.DNSConstants;
import javax.jmdns.impl.constants.DNSRecordClass;
import javax.jmdns.impl.constants.DNSState;
/**
* The Announcer sends an accumulated query of all announces, and advances the state of all serviceInfos, for which it has sent an announce. The Announcer also sends announcements and advances the state of JmDNS itself.
* <p/>
* When the announcer has run two times, it finishes.
*/
public class Announcer extends DNSStateTask {
static Logger logger = Logger.getLogger(Announcer.class.getName());
public Announcer(JmDNSImpl jmDNSImpl) {
super(jmDNSImpl, defaultTTL());
this.setTaskState(DNSState.ANNOUNCING_1);
this.associate(DNSState.ANNOUNCING_1);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.DNSTask#getName()
*/
@Override
public String getName() {
return "Announcer(" + (this.getDns() != null ? this.getDns().getName() : "") + ")";
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return super.toString() + " state: " + this.getTaskState();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.DNSTask#start(java.util.Timer)
*/
@Override
public void start(Timer timer) {
if (!this.getDns().isCanceling() && !this.getDns().isCanceled()) {
timer.schedule(this, DNSConstants.ANNOUNCE_WAIT_INTERVAL, DNSConstants.ANNOUNCE_WAIT_INTERVAL);
}
}
@Override
public boolean cancel() {
this.removeAssociation();
return super.cancel();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#getTaskDescription()
*/
@Override
public String getTaskDescription() {
return "announcing";
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#checkRunCondition()
*/
@Override
protected boolean checkRunCondition() {
return !this.getDns().isCanceling() && !this.getDns().isCanceled();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#createOugoing()
*/
@Override
protected DNSOutgoing createOugoing() {
return new DNSOutgoing(DNSConstants.FLAGS_QR_RESPONSE | DNSConstants.FLAGS_AA);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#buildOutgoingForDNS(javax.jmdns.impl.DNSOutgoing)
*/
@Override
protected DNSOutgoing buildOutgoingForDNS(DNSOutgoing out) throws IOException {
DNSOutgoing newOut = out;
for (DNSRecord answer : this.getDns().getLocalHost().answers(DNSRecordClass.CLASS_ANY, DNSRecordClass.UNIQUE, this.getTTL())) {
newOut = this.addAnswer(newOut, null, answer);
}
return newOut;
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#buildOutgoingForInfo(javax.jmdns.impl.ServiceInfoImpl, javax.jmdns.impl.DNSOutgoing)
*/
@Override
protected DNSOutgoing buildOutgoingForInfo(ServiceInfoImpl info, DNSOutgoing out) throws IOException {
DNSOutgoing newOut = out;
for (DNSRecord answer : info.answers(DNSRecordClass.CLASS_ANY, DNSRecordClass.UNIQUE, this.getTTL(), this.getDns().getLocalHost())) {
newOut = this.addAnswer(newOut, null, answer);
}
return newOut;
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#recoverTask(java.lang.Throwable)
*/
@Override
protected void recoverTask(Throwable e) {
this.getDns().recover();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#advanceTask()
*/
@Override
protected void advanceTask() {
this.setTaskState(this.getTaskState().advance());
if (!this.getTaskState().isAnnouncing()) {
this.cancel();
this.getDns().startRenewer();
}
}
}

View File

@ -0,0 +1,143 @@
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl.tasks.state;
import java.io.IOException;
import java.util.Timer;
import java.util.logging.Logger;
import javax.jmdns.impl.DNSOutgoing;
import javax.jmdns.impl.DNSRecord;
import javax.jmdns.impl.JmDNSImpl;
import javax.jmdns.impl.ServiceInfoImpl;
import javax.jmdns.impl.constants.DNSConstants;
import javax.jmdns.impl.constants.DNSRecordClass;
import javax.jmdns.impl.constants.DNSState;
/**
* The Canceler sends two announces with TTL=0 for the specified services.
*/
public class Canceler extends DNSStateTask {
static Logger logger = Logger.getLogger(Canceler.class.getName());
public Canceler(JmDNSImpl jmDNSImpl) {
super(jmDNSImpl, 0);
this.setTaskState(DNSState.CANCELING_1);
this.associate(DNSState.CANCELING_1);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.DNSTask#getName()
*/
@Override
public String getName() {
return "Canceler(" + (this.getDns() != null ? this.getDns().getName() : "") + ")";
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return super.toString() + " state: " + this.getTaskState();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.DNSTask#start(java.util.Timer)
*/
@Override
public void start(Timer timer) {
timer.schedule(this, 0, DNSConstants.ANNOUNCE_WAIT_INTERVAL);
}
/*
* (non-Javadoc)
* @see java.util.TimerTask#cancel()
*/
@Override
public boolean cancel() {
this.removeAssociation();
return super.cancel();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#getTaskDescription()
*/
@Override
public String getTaskDescription() {
return "canceling";
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#checkRunCondition()
*/
@Override
protected boolean checkRunCondition() {
return true;
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#createOugoing()
*/
@Override
protected DNSOutgoing createOugoing() {
return new DNSOutgoing(DNSConstants.FLAGS_QR_RESPONSE | DNSConstants.FLAGS_AA);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#buildOutgoingForDNS(javax.jmdns.impl.DNSOutgoing)
*/
@Override
protected DNSOutgoing buildOutgoingForDNS(DNSOutgoing out) throws IOException {
DNSOutgoing newOut = out;
for (DNSRecord answer : this.getDns().getLocalHost().answers(DNSRecordClass.CLASS_ANY, DNSRecordClass.UNIQUE, this.getTTL())) {
newOut = this.addAnswer(newOut, null, answer);
}
return newOut;
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#buildOutgoingForInfo(javax.jmdns.impl.ServiceInfoImpl, javax.jmdns.impl.DNSOutgoing)
*/
@Override
protected DNSOutgoing buildOutgoingForInfo(ServiceInfoImpl info, DNSOutgoing out) throws IOException {
DNSOutgoing newOut = out;
for (DNSRecord answer : info.answers(DNSRecordClass.CLASS_ANY, DNSRecordClass.UNIQUE, this.getTTL(), this.getDns().getLocalHost())) {
newOut = this.addAnswer(newOut, null, answer);
}
return newOut;
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#recoverTask(java.lang.Throwable)
*/
@Override
protected void recoverTask(Throwable e) {
this.getDns().recover();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#advanceTask()
*/
@Override
protected void advanceTask() {
this.setTaskState(this.getTaskState().advance());
if (!this.getTaskState().isCanceling()) {
cancel();
}
}
}

View File

@ -0,0 +1,188 @@
// Licensed under Apache License version 2.0
package javax.jmdns.impl.tasks.state;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jmdns.ServiceInfo;
import javax.jmdns.impl.DNSOutgoing;
import javax.jmdns.impl.DNSStatefulObject;
import javax.jmdns.impl.JmDNSImpl;
import javax.jmdns.impl.ServiceInfoImpl;
import javax.jmdns.impl.constants.DNSConstants;
import javax.jmdns.impl.constants.DNSState;
import javax.jmdns.impl.tasks.DNSTask;
/**
* This is the root class for all state tasks. These tasks work with objects that implements the {@link javax.jmdns.impl.DNSStatefulObject} interface and therefore participate in the state machine.
*
* @author Pierre Frisch
*/
public abstract class DNSStateTask extends DNSTask {
static Logger logger1 = Logger.getLogger(DNSStateTask.class.getName());
/**
* By setting a 0 ttl we effectively expire the record.
*/
private final int _ttl;
private static int _defaultTTL = DNSConstants.DNS_TTL;
/**
* The state of the task.
*/
private DNSState _taskState = null;
public abstract String getTaskDescription();
public static int defaultTTL() {
return _defaultTTL;
}
/**
* For testing only do not use in production.
*
* @param value
*/
public static void setDefaultTTL(int value) {
_defaultTTL = value;
}
/**
* @param jmDNSImpl
* @param ttl
*/
public DNSStateTask(JmDNSImpl jmDNSImpl, int ttl) {
super(jmDNSImpl);
_ttl = ttl;
}
/**
* @return the ttl
*/
public int getTTL() {
return _ttl;
}
/**
* Associate the DNS host and the service infos with this task if not already associated and in the same state.
*
* @param state
* target state
*/
protected void associate(DNSState state) {
synchronized (this.getDns()) {
this.getDns().associateWithTask(this, state);
}
for (ServiceInfo serviceInfo : this.getDns().getServices().values()) {
((ServiceInfoImpl) serviceInfo).associateWithTask(this, state);
}
}
/**
* Remove the DNS host and service info association with this task.
*/
protected void removeAssociation() {
// Remove association from host to this
synchronized (this.getDns()) {
this.getDns().removeAssociationWithTask(this);
}
// Remove associations from services to this
for (ServiceInfo serviceInfo : this.getDns().getServices().values()) {
((ServiceInfoImpl) serviceInfo).removeAssociationWithTask(this);
}
}
@Override
public void run() {
DNSOutgoing out = this.createOugoing();
try {
if (!this.checkRunCondition()) {
this.cancel();
return;
}
List<DNSStatefulObject> stateObjects = new ArrayList<DNSStatefulObject>();
// send probes for JmDNS itself
synchronized (this.getDns()) {
if (this.getDns().isAssociatedWithTask(this, this.getTaskState())) {
logger1.finer(this.getName() + ".run() JmDNS " + this.getTaskDescription() + " " + this.getDns().getName());
stateObjects.add(this.getDns());
out = this.buildOutgoingForDNS(out);
}
}
// send probes for services
for (ServiceInfo serviceInfo : this.getDns().getServices().values()) {
ServiceInfoImpl info = (ServiceInfoImpl) serviceInfo;
synchronized (info) {
if (info.isAssociatedWithTask(this, this.getTaskState())) {
logger1.fine(this.getName() + ".run() JmDNS " + this.getTaskDescription() + " " + info.getQualifiedName());
stateObjects.add(info);
out = this.buildOutgoingForInfo(info, out);
}
}
}
if (!out.isEmpty()) {
logger1.finer(this.getName() + ".run() JmDNS " + this.getTaskDescription() + " #" + this.getTaskState());
this.getDns().send(out);
// Advance the state of objects.
this.advanceObjectsState(stateObjects);
} else {
// Advance the state of objects.
this.advanceObjectsState(stateObjects);
// If we have nothing to send, another timer taskState ahead of us has done the job for us. We can cancel.
cancel();
return;
}
} catch (Throwable e) {
logger1.log(Level.WARNING, this.getName() + ".run() exception ", e);
this.recoverTask(e);
}
this.advanceTask();
}
protected abstract boolean checkRunCondition();
protected abstract DNSOutgoing buildOutgoingForDNS(DNSOutgoing out) throws IOException;
protected abstract DNSOutgoing buildOutgoingForInfo(ServiceInfoImpl info, DNSOutgoing out) throws IOException;
protected abstract DNSOutgoing createOugoing();
protected void advanceObjectsState(List<DNSStatefulObject> list) {
if (list != null) {
for (DNSStatefulObject object : list) {
synchronized (object) {
object.advanceState(this);
}
}
}
}
protected abstract void recoverTask(Throwable e);
protected abstract void advanceTask();
/**
* @return the taskState
*/
protected DNSState getTaskState() {
return this._taskState;
}
/**
* @param taskState
* the taskState to set
*/
protected void setTaskState(DNSState taskState) {
this._taskState = taskState;
}
}

View File

@ -0,0 +1,161 @@
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl.tasks.state;
import java.io.IOException;
import java.util.Timer;
import java.util.logging.Logger;
import javax.jmdns.impl.DNSOutgoing;
import javax.jmdns.impl.DNSQuestion;
import javax.jmdns.impl.DNSRecord;
import javax.jmdns.impl.JmDNSImpl;
import javax.jmdns.impl.ServiceInfoImpl;
import javax.jmdns.impl.constants.DNSConstants;
import javax.jmdns.impl.constants.DNSRecordClass;
import javax.jmdns.impl.constants.DNSRecordType;
import javax.jmdns.impl.constants.DNSState;
/**
* The Prober sends three consecutive probes for all service infos that needs probing as well as for the host name. The state of each service info of the host name is advanced, when a probe has been sent for it. When the prober has run three times,
* it launches an Announcer.
* <p/>
* If a conflict during probes occurs, the affected service infos (and affected host name) are taken away from the prober. This eventually causes the prober to cancel itself.
*/
public class Prober extends DNSStateTask {
static Logger logger = Logger.getLogger(Prober.class.getName());
public Prober(JmDNSImpl jmDNSImpl) {
super(jmDNSImpl, defaultTTL());
this.setTaskState(DNSState.PROBING_1);
this.associate(DNSState.PROBING_1);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.DNSTask#getName()
*/
@Override
public String getName() {
return "Prober(" + (this.getDns() != null ? this.getDns().getName() : "") + ")";
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return super.toString() + " state: " + this.getTaskState();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.DNSTask#start(java.util.Timer)
*/
@Override
public void start(Timer timer) {
long now = System.currentTimeMillis();
if (now - this.getDns().getLastThrottleIncrement() < DNSConstants.PROBE_THROTTLE_COUNT_INTERVAL) {
this.getDns().setThrottle(this.getDns().getThrottle() + 1);
} else {
this.getDns().setThrottle(1);
}
this.getDns().setLastThrottleIncrement(now);
if (this.getDns().isAnnounced() && this.getDns().getThrottle() < DNSConstants.PROBE_THROTTLE_COUNT) {
timer.schedule(this, JmDNSImpl.getRandom().nextInt(1 + DNSConstants.PROBE_WAIT_INTERVAL), DNSConstants.PROBE_WAIT_INTERVAL);
} else if (!this.getDns().isCanceling() && !this.getDns().isCanceled()) {
timer.schedule(this, DNSConstants.PROBE_CONFLICT_INTERVAL, DNSConstants.PROBE_CONFLICT_INTERVAL);
}
}
@Override
public boolean cancel() {
this.removeAssociation();
return super.cancel();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#getTaskDescription()
*/
@Override
public String getTaskDescription() {
return "probing";
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#checkRunCondition()
*/
@Override
protected boolean checkRunCondition() {
return !this.getDns().isCanceling() && !this.getDns().isCanceled();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#createOugoing()
*/
@Override
protected DNSOutgoing createOugoing() {
return new DNSOutgoing(DNSConstants.FLAGS_QR_QUERY);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#buildOutgoingForDNS(javax.jmdns.impl.DNSOutgoing)
*/
@Override
protected DNSOutgoing buildOutgoingForDNS(DNSOutgoing out) throws IOException {
DNSOutgoing newOut = out;
newOut.addQuestion(DNSQuestion.newQuestion(this.getDns().getLocalHost().getName(), DNSRecordType.TYPE_ANY, DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE));
for (DNSRecord answer : this.getDns().getLocalHost().answers(DNSRecordClass.CLASS_ANY, DNSRecordClass.NOT_UNIQUE, this.getTTL())) {
newOut = this.addAuthoritativeAnswer(newOut, answer);
}
return newOut;
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#buildOutgoingForInfo(javax.jmdns.impl.ServiceInfoImpl, javax.jmdns.impl.DNSOutgoing)
*/
@Override
protected DNSOutgoing buildOutgoingForInfo(ServiceInfoImpl info, DNSOutgoing out) throws IOException {
DNSOutgoing newOut = out;
newOut = this.addQuestion(newOut, DNSQuestion.newQuestion(info.getQualifiedName(), DNSRecordType.TYPE_ANY, DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE));
// the "unique" flag should be not set here because these answers haven't been proven unique yet this means the record will not exactly match the announcement record
newOut = this.addAuthoritativeAnswer(newOut, new DNSRecord.Service(info.getQualifiedName(), DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE, this.getTTL(), info.getPriority(), info.getWeight(), info.getPort(), this.getDns().getLocalHost()
.getName()));
return newOut;
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#recoverTask(java.lang.Throwable)
*/
@Override
protected void recoverTask(Throwable e) {
this.getDns().recover();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#advanceTask()
*/
@Override
protected void advanceTask() {
this.setTaskState(this.getTaskState().advance());
if (!this.getTaskState().isProbing()) {
cancel();
this.getDns().startAnnouncer();
}
}
}

View File

@ -0,0 +1,141 @@
// Copyright 2003-2005 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl.tasks.state;
import java.io.IOException;
import java.util.Timer;
import java.util.logging.Logger;
import javax.jmdns.impl.DNSOutgoing;
import javax.jmdns.impl.DNSRecord;
import javax.jmdns.impl.JmDNSImpl;
import javax.jmdns.impl.ServiceInfoImpl;
import javax.jmdns.impl.constants.DNSConstants;
import javax.jmdns.impl.constants.DNSRecordClass;
import javax.jmdns.impl.constants.DNSState;
/**
* The Renewer is there to send renewal announcement when the record expire for ours infos.
*/
public class Renewer extends DNSStateTask {
static Logger logger = Logger.getLogger(Renewer.class.getName());
public Renewer(JmDNSImpl jmDNSImpl) {
super(jmDNSImpl, defaultTTL());
this.setTaskState(DNSState.ANNOUNCED);
this.associate(DNSState.ANNOUNCED);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.DNSTask#getName()
*/
@Override
public String getName() {
return "Renewer(" + (this.getDns() != null ? this.getDns().getName() : "") + ")";
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return super.toString() + " state: " + this.getTaskState();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.DNSTask#start(java.util.Timer)
*/
@Override
public void start(Timer timer) {
if (!this.getDns().isCanceling() && !this.getDns().isCanceled()) {
timer.schedule(this, DNSConstants.ANNOUNCED_RENEWAL_TTL_INTERVAL, DNSConstants.ANNOUNCED_RENEWAL_TTL_INTERVAL);
}
}
@Override
public boolean cancel() {
this.removeAssociation();
return super.cancel();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#getTaskDescription()
*/
@Override
public String getTaskDescription() {
return "renewing";
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#checkRunCondition()
*/
@Override
protected boolean checkRunCondition() {
return !this.getDns().isCanceling() && !this.getDns().isCanceled();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#createOugoing()
*/
@Override
protected DNSOutgoing createOugoing() {
return new DNSOutgoing(DNSConstants.FLAGS_QR_RESPONSE | DNSConstants.FLAGS_AA);
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#buildOutgoingForDNS(javax.jmdns.impl.DNSOutgoing)
*/
@Override
protected DNSOutgoing buildOutgoingForDNS(DNSOutgoing out) throws IOException {
DNSOutgoing newOut = out;
for (DNSRecord answer : this.getDns().getLocalHost().answers(DNSRecordClass.CLASS_ANY, DNSRecordClass.UNIQUE, this.getTTL())) {
newOut = this.addAnswer(newOut, null, answer);
}
return newOut;
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#buildOutgoingForInfo(javax.jmdns.impl.ServiceInfoImpl, javax.jmdns.impl.DNSOutgoing)
*/
@Override
protected DNSOutgoing buildOutgoingForInfo(ServiceInfoImpl info, DNSOutgoing out) throws IOException {
DNSOutgoing newOut = out;
for (DNSRecord answer : info.answers(DNSRecordClass.CLASS_ANY, DNSRecordClass.UNIQUE, this.getTTL(), this.getDns().getLocalHost())) {
newOut = this.addAnswer(newOut, null, answer);
}
return newOut;
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#recoverTask(java.lang.Throwable)
*/
@Override
protected void recoverTask(Throwable e) {
this.getDns().recover();
}
/*
* (non-Javadoc)
* @see javax.jmdns.impl.tasks.state.DNSStateTask#advanceTask()
*/
@Override
protected void advanceTask() {
this.setTaskState(this.getTaskState().advance());
if (!this.getTaskState().isAnnounced()) {
cancel();
}
}
}

View File

@ -0,0 +1,2 @@
package javax.jmdns.impl.tasks.state;

View File

@ -0,0 +1,35 @@
// Copyright 2003-2012 Arthur van Hoff, Rick Blair
// Licensed under Apache License version 2.0
// Original license LGPL
package javax.jmdns.impl.util;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/**
* Custom thread factory which sets the name to make it easier to identify where the pooled threads were created.
*
* @author Trejkaz, Pierre Frisch
*/
public class NamedThreadFactory implements ThreadFactory {
private final ThreadFactory _delegate;
private final String _namePrefix;
/**
* Constructs the thread factory.
*
* @param namePrefix a prefix to append to thread names (will be separated from the default thread name by a space.)
*/
public NamedThreadFactory(String namePrefix) {
this._namePrefix = namePrefix;
_delegate = Executors.defaultThreadFactory();
}
@Override
public Thread newThread(Runnable runnable) {
Thread thread = _delegate.newThread(runnable);
thread.setName(_namePrefix + ' ' + thread.getName());
return thread;
}
}

View File

@ -0,0 +1,9 @@
package javax.jmdns;
/**
* JmDNS is a Java implementation of multi-cast DNS and can be used for service registration and discovery in local area networks. JmDNS is fully compatible with Apple's Bonjour. The project was originally started in December 2002 by Arthur van Hoff
* at Strangeberry. In November 2003 the project was moved to SourceForge, and the name was changed from JRendezvous to JmDNS for legal reasons. Many thanks to Stuart Cheshire for help and moral support.
* <p>
* <a href="http://jmdns.sourceforge.net/">http://jmdns.sourceforge.net/<a>
* </p>
**/