Compare commits
16
Commits
v1.1.1
..
d160814ca1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d160814ca1 | ||
|
|
fa38806250 | ||
|
|
420eed64f7 | ||
|
|
1d35747b62 | ||
|
|
3e912d4d3c | ||
|
|
3776ece7a4 | ||
|
|
c1a60eef43 | ||
|
|
3a6356f4d9 | ||
|
|
4c6472a504 | ||
|
|
7cc4e042bd | ||
|
|
d5da03d91b | ||
|
|
6dcc2c4b89 | ||
|
|
bc39956b6c | ||
|
|
8ca2185c01 | ||
|
|
f0d8cd93e8 | ||
|
|
ef1c5b42ab |
No files matched your search
@@ -0,0 +1 @@
|
|||||||
|
server/packaging/start.bat text eol=crlf
|
||||||
@@ -0,0 +1,661 @@
|
|||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, 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
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If 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 convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero 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
|
||||||
|
Program specifies that a certain numbered version of the GNU Affero General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU Affero General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU Affero General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
@@ -63,7 +63,15 @@ flutter run -d linux
|
|||||||
3. 「目标」填要测的主机、端口和类型。合作反射的默认端口是 TCP `19090`、UDP `19091`。Minecraft Java 默认 `25565`,基岩版默认 `19132`。
|
3. 「目标」填要测的主机、端口和类型。合作反射的默认端口是 TCP `19090`、UDP `19091`。Minecraft Java 默认 `25565`,基岩版默认 `19132`。
|
||||||
4. 点「开始探测」。远程任务到设定的时长后节点会自己停,也可以提前点停止。停止或断开都会让节点结束这次任务。
|
4. 点「开始探测」。远程任务到设定的时长后节点会自己停,也可以提前点停止。停止或断开都会让节点结束这次任务。
|
||||||
|
|
||||||
本机的 UDP 探测会记下这次解析出的每个地址。结果上的「发往」是当前实际在用的地址。还没有哪个地址应答时,一个超时就换下一个;已经有应答之后,要连续三次没有应答才换,中途开关 VPN 不会把还在应答的地址丢掉。地址落在 `198.18.0.0/15` 时,界面会标明这是 VPN 假地址。
|
本机的 UDP 探测会记下这次解析出的每个地址。结果上的「实际地址」是真正发包或连通的地址,并注明 IPv4 或 IPv6。域名解析出来的地址单独标成「解析到」,不会被说成已经在用。还没有哪个地址应答时,一次失败就换下一个,这次失败不计入正式丢包,界面会说明回退;已经有应答之后,超时算正式结果,要连续三次没有应答才换。全部地址都失败时显示失败,不会显示 0% 成功。地址落在 `198.18.0.0/15` 时,界面会标明这是 VPN 假地址。
|
||||||
|
|
||||||
|
远程节点从 1.1.2 起会在每条结果里带上实际地址。更早的节点没有这个字段时,界面写明「节点没有报告实际使用的地址」,不会在手机上另做一次解析来冒充。1.1.1 的节点仍会把选址失败算进统计。
|
||||||
|
|
||||||
|
端口框写着当前类型的默认端口。合作反射 TCP 是 19090,UDP 是 19091。只有端口仍是上一种类型的默认值,或端口是空的,切换类型才会自动更换。
|
||||||
|
|
||||||
|
已有远程节点可以改名称、控制地址和口令。节点编号和当前选择不变。口令留空表示不改,界面不显示已经保存的口令。
|
||||||
|
|
||||||
|
手动停止后曲线还在,并给出这次的开始、结束、用时和最终指标。停止时还没完成的请求不算丢包。点曲线可以钉住该时刻,松手后仍然保留。指标的算法在应用里的「指标说明」,版本记录在「更新历史」。
|
||||||
|
|
||||||
节点口令保存在本机应用目录里,权限尽量收成只有自己能读,不会写进网址或日志。
|
节点口令保存在本机应用目录里,权限尽量收成只有自己能读,不会写进网址或日志。
|
||||||
|
|
||||||
@@ -71,12 +79,12 @@ flutter run -d linux
|
|||||||
|
|
||||||
步骤、公开/口令两种例子、防火墙和 HTTPS 在 [docs/server-linux.md](docs/server-linux.md)。不要把真实口令写进仓库或命令历史以外的公开地方。
|
步骤、公开/口令两种例子、防火墙和 HTTPS 在 [docs/server-linux.md](docs/server-linux.md)。不要把真实口令写进仓库或命令历史以外的公开地方。
|
||||||
|
|
||||||
只做反射,给本机或节点回显用:
|
只做反射,给本机或节点回显用。端口和口令写在 `server/.env`,不改就是 TCP `19090`、UDP `19091`:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd server
|
cd server
|
||||||
go build -o netquality-reflector .
|
go build -o netquality-reflector .
|
||||||
./netquality-reflector -bind 0.0.0.0 -tcp-port 19090 -udp-port 19091
|
./netquality-reflector
|
||||||
```
|
```
|
||||||
|
|
||||||
同一台机器既回显、又替手机探测别的目标:
|
同一台机器既回显、又替手机探测别的目标:
|
||||||
@@ -96,4 +104,12 @@ cd server && go test -race ./...
|
|||||||
cd client && flutter analyze && flutter test
|
cd client && flutter analyze && flutter test
|
||||||
```
|
```
|
||||||
|
|
||||||
Android 安装包是按 CPU 分开的 release 包,使用调试证书,只适合测试安装,不是应用商店签名。当前版本名 `1.1.1`。
|
Android 安装包是按 CPU 分开的 release 包,使用调试证书,只适合测试安装,不是应用商店签名。当前版本名 `1.1.2`,构建号 `5`。
|
||||||
|
|
||||||
|
这一版的说明在 [docs/release-notes/1.1.2.md](docs/release-notes/1.1.2.md)。
|
||||||
|
|
||||||
|
## 许可
|
||||||
|
|
||||||
|
Copyright (C) 2026 言灸
|
||||||
|
|
||||||
|
本项目以 GNU Affero General Public License v3.0 许可(SPDX 标识:AGPL-3.0-only)。你可以在遵守该许可的前提下使用、修改和分发。完整条款见仓库根目录的 [LICENSE](LICENSE)。
|
||||||
+1
-1
@@ -7,4 +7,4 @@ flutter pub get
|
|||||||
flutter run -d linux
|
flutter run -d linux
|
||||||
```
|
```
|
||||||
|
|
||||||
默认用本机去测 `127.0.0.1` 的合作反射 TCP `19090`。先在 `../server` 里启动反射服务,再点「开始探测」。要让另一台机器代测时,把来源改成「远程节点」。
|
默认用本机去测 `127.0.0.1` 的合作反射 TCP `19090`。合作反射 UDP 默认 `19091`。先在 `../server` 里启动反射服务,再点「开始探测」。要让另一台机器代测时,把来源改成「远程节点」。当前版本是 1.1.2。指标怎么读、这一版改了什么,在应用里的「指标说明」和「更新历史」。
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
/// Versions that exist as this release or as a real Git tag / GitHub Release.
|
||||||
|
/// Unpublished earlier behavior mentioned inside the 1.1.1 notes is not given
|
||||||
|
/// its own entry.
|
||||||
|
class ReleaseEntry {
|
||||||
|
const ReleaseEntry({
|
||||||
|
required this.version,
|
||||||
|
required this.title,
|
||||||
|
required this.source,
|
||||||
|
required this.points,
|
||||||
|
this.published,
|
||||||
|
});
|
||||||
|
|
||||||
|
final String version;
|
||||||
|
final String title;
|
||||||
|
final String source;
|
||||||
|
final String? published;
|
||||||
|
final List<String> points;
|
||||||
|
}
|
||||||
|
|
||||||
|
const releaseHistory = <ReleaseEntry>[
|
||||||
|
ReleaseEntry(
|
||||||
|
version: '1.1.2',
|
||||||
|
title: '网络质量探测 1.1.2',
|
||||||
|
source: '仓库 docs/release-notes/1.1.2.md。这一版的 Git 标签要等发布时才有,这里写的是即将发布的内容。',
|
||||||
|
points: [
|
||||||
|
'可以修改已有远程节点的名称、控制地址和口令。节点编号和当前选择保持不变。口令留空表示不改,界面不显示已经保存的口令。',
|
||||||
|
'端口框标明当前类型的默认端口。合作反射 TCP 是 19090,UDP 是 19091。只有端口仍是上一种类型的默认值,或端口是空的,切换类型才会自动更换。',
|
||||||
|
'本机和远程节点都显示实际连通或实际发包的地址,以及 IPv4 / IPv6。旧节点如果没有上报地址,会写明未报告,不会把域名解析的第一个地址当成已经使用的地址。',
|
||||||
|
'选址阶段失败的候选(例如 IPv6 没有应答后改用 IPv4)不再计入正式丢包,并单独说明回退。选定地址之后的失败仍然计入。全部候选都失败时显示失败,不会显示 0% 成功。',
|
||||||
|
'结果给出已发送、已收到、超时、比率、当前/最小/平均/中位/P95/最大延迟、抖动和用时。某种探测没有测量的量会标成不适用或 —。',
|
||||||
|
'手动停止后保留曲线,并给出开始、结束、用时、目标、来源、实际地址和最终指标。停止时还没完成的请求不计入丢包。',
|
||||||
|
'点曲线可以钉住该时刻的数值,松手后仍然保留;再点另一点会更换。新的一次探测,或该点滚出窗口后,不会沿用过期选择。',
|
||||||
|
'新增「指标说明」。',
|
||||||
|
],
|
||||||
|
),
|
||||||
|
ReleaseEntry(
|
||||||
|
version: '1.1.1',
|
||||||
|
title: '网络质量探测 1.1.1',
|
||||||
|
published: '2026-11-09',
|
||||||
|
source: 'Git 标签 v1.1.1,以及 GitHub Release「网络质量探测 1.1.1」(发布于 2026-11-09,之后补过桌面和节点压缩包)。',
|
||||||
|
points: [
|
||||||
|
'本机 UDP 会把解析出的地址逐个试过,停在第一个真正有应答的地址上。',
|
||||||
|
'还没有地址应答时,一次超时就换下一个。已经有应答之后,要连续 3 次没有应答才换。',
|
||||||
|
'结果里显示当时实际在用的地址。地址落在 198.18.0.0/15 时,会提示这是 VPN 假地址。',
|
||||||
|
'发布物包含 Android APK(arm64-v8a 与 armeabi-v7a,versionName 1.1.1,versionCode 分别为 2004 和 1004)、Linux 与 Windows 桌面客户端,以及 Linux amd64、Linux arm64、Windows amd64 的检测节点包。',
|
||||||
|
'标签 v1.1.1 没有因为后来补上的桌面和节点压缩包而移动。',
|
||||||
|
],
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
const releaseHistoryNote =
|
||||||
|
'仓库里目前公开的版本标签只有 v1.1.1。1.1.1 的发布说明提到过更早的发包行为,但没有单独的标签或 Release,所以这里不写成另一个版本。';
|
||||||
@@ -1,3 +1,6 @@
|
|||||||
|
// Copyright (C) 2026 灸 言
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
import 'ui/home_page.dart';
|
import 'ui/home_page.dart';
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
/// Latency over successful round-trips only.
|
||||||
|
///
|
||||||
|
/// * current: the latest successful sample, stored separately as `rttMs`
|
||||||
|
/// * min / max: smallest and largest successful sample
|
||||||
|
/// * mean: arithmetic mean
|
||||||
|
/// * median: the middle sample after sorting; when the count is even, the
|
||||||
|
/// mean of the two middle samples
|
||||||
|
/// * p95: nearest-rank. Rank is `ceil(0.95 * n)` computed as
|
||||||
|
/// `(95 * n + 99) ~/ 100` so binary floating point cannot move the rank.
|
||||||
|
/// Rank is 1-based and then clamped to the sample count.
|
||||||
|
class LatencyStats {
|
||||||
|
const LatencyStats({
|
||||||
|
required this.min,
|
||||||
|
required this.mean,
|
||||||
|
required this.median,
|
||||||
|
required this.p95,
|
||||||
|
required this.max,
|
||||||
|
});
|
||||||
|
|
||||||
|
final double min;
|
||||||
|
final double mean;
|
||||||
|
final double median;
|
||||||
|
final double p95;
|
||||||
|
final double max;
|
||||||
|
|
||||||
|
static LatencyStats? from(List<double> samples) {
|
||||||
|
if (samples.isEmpty) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
final sorted = [...samples]..sort();
|
||||||
|
var sum = 0.0;
|
||||||
|
for (final value in sorted) {
|
||||||
|
sum += value;
|
||||||
|
}
|
||||||
|
final count = sorted.length;
|
||||||
|
final median = count.isOdd
|
||||||
|
? sorted[count ~/ 2]
|
||||||
|
: (sorted[count ~/ 2 - 1] + sorted[count ~/ 2]) / 2;
|
||||||
|
final rank = nearestRank95(count);
|
||||||
|
return LatencyStats(
|
||||||
|
min: sorted.first,
|
||||||
|
mean: sum / count,
|
||||||
|
median: median,
|
||||||
|
p95: sorted[rank - 1],
|
||||||
|
max: sorted.last,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int nearestRank95(int count) {
|
||||||
|
if (count <= 1) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
final rank = (95 * count + 99) ~/ 100;
|
||||||
|
if (rank < 1) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (rank > count) {
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
return rank;
|
||||||
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import 'latency.dart';
|
||||||
|
|
||||||
class Outcome {
|
class Outcome {
|
||||||
const Outcome({
|
const Outcome({
|
||||||
required this.status,
|
required this.status,
|
||||||
@@ -6,6 +8,7 @@ class Outcome {
|
|||||||
this.note = '',
|
this.note = '',
|
||||||
this.detail = const {},
|
this.detail = const {},
|
||||||
this.reconnect = false,
|
this.reconnect = false,
|
||||||
|
this.selectionSkipped = 0,
|
||||||
});
|
});
|
||||||
|
|
||||||
final String status;
|
final String status;
|
||||||
@@ -15,6 +18,10 @@ class Outcome {
|
|||||||
final Map<String, String> detail;
|
final Map<String, String> detail;
|
||||||
final bool reconnect;
|
final bool reconnect;
|
||||||
|
|
||||||
|
/// Candidate failures folded into this measured attempt. They are not
|
||||||
|
/// themselves samples.
|
||||||
|
final int selectionSkipped;
|
||||||
|
|
||||||
static const ok = 'ok';
|
static const ok = 'ok';
|
||||||
static const timeout = 'timeout';
|
static const timeout = 'timeout';
|
||||||
static const unknown = 'unknown';
|
static const unknown = 'unknown';
|
||||||
@@ -48,6 +55,13 @@ class ProbeSummary {
|
|||||||
required this.unknownPct,
|
required this.unknownPct,
|
||||||
required this.lastNote,
|
required this.lastNote,
|
||||||
required this.detail,
|
required this.detail,
|
||||||
|
this.minRttMs,
|
||||||
|
this.meanRttMs,
|
||||||
|
this.medianRttMs,
|
||||||
|
this.p95RttMs,
|
||||||
|
this.maxRttMs,
|
||||||
|
this.selectionSkipped = 0,
|
||||||
|
this.latencyStats = false,
|
||||||
});
|
});
|
||||||
|
|
||||||
final int sent;
|
final int sent;
|
||||||
@@ -68,6 +82,15 @@ class ProbeSummary {
|
|||||||
final double? unknownPct;
|
final double? unknownPct;
|
||||||
final String lastNote;
|
final String lastNote;
|
||||||
final Map<String, String> detail;
|
final Map<String, String> detail;
|
||||||
|
final double? minRttMs;
|
||||||
|
final double? meanRttMs;
|
||||||
|
final double? medianRttMs;
|
||||||
|
final double? p95RttMs;
|
||||||
|
final double? maxRttMs;
|
||||||
|
final int selectionSkipped;
|
||||||
|
|
||||||
|
/// False when an older remote node omitted the latency distribution.
|
||||||
|
final bool latencyStats;
|
||||||
|
|
||||||
static const empty = ProbeSummary(
|
static const empty = ProbeSummary(
|
||||||
sent: 0,
|
sent: 0,
|
||||||
@@ -110,6 +133,16 @@ class ProbeSummary {
|
|||||||
unknownPct: _double(json['unknownPct']),
|
unknownPct: _double(json['unknownPct']),
|
||||||
lastNote: json['lastNote'] is String ? json['lastNote'] as String : '',
|
lastNote: json['lastNote'] is String ? json['lastNote'] as String : '',
|
||||||
detail: _detail(json['detail']),
|
detail: _detail(json['detail']),
|
||||||
|
minRttMs: _double(json['minRttMs']),
|
||||||
|
meanRttMs: _double(json['meanRttMs']),
|
||||||
|
medianRttMs: _double(json['medianRttMs']),
|
||||||
|
p95RttMs: _double(json['p95RttMs']),
|
||||||
|
maxRttMs: _double(json['maxRttMs']),
|
||||||
|
selectionSkipped: _int(json['selectionSkipped']),
|
||||||
|
latencyStats:
|
||||||
|
json.containsKey('minRttMs') ||
|
||||||
|
json.containsKey('medianRttMs') ||
|
||||||
|
json.containsKey('p95RttMs'),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -137,7 +170,9 @@ class ProbeSample {
|
|||||||
|
|
||||||
factory ProbeSample.fromJson(Map<String, dynamic> json) {
|
factory ProbeSample.fromJson(Map<String, dynamic> json) {
|
||||||
final summary = json['summary'] is Map
|
final summary = json['summary'] is Map
|
||||||
? ProbeSummary.fromJson(Map<String, dynamic>.from(json['summary'] as Map))
|
? ProbeSummary.fromJson(
|
||||||
|
Map<String, dynamic>.from(json['summary'] as Map),
|
||||||
|
)
|
||||||
: ProbeSummary.empty;
|
: ProbeSummary.empty;
|
||||||
return ProbeSample(
|
return ProbeSample(
|
||||||
seq: _int(json['seq']),
|
seq: _int(json['seq']),
|
||||||
@@ -171,12 +206,15 @@ class SampleBook {
|
|||||||
double jitterMs = 0;
|
double jitterMs = 0;
|
||||||
bool _hasJitter = false;
|
bool _hasJitter = false;
|
||||||
double _lastTransit = 0;
|
double _lastTransit = 0;
|
||||||
|
final List<double> _rtts = [];
|
||||||
|
int selectionSkipped = 0;
|
||||||
String lastNote = '';
|
String lastNote = '';
|
||||||
Map<String, String> detail = {};
|
Map<String, String> detail = {};
|
||||||
|
|
||||||
void add(Outcome outcome) {
|
void add(Outcome outcome) {
|
||||||
sent += 1;
|
sent += 1;
|
||||||
completed += 1;
|
completed += 1;
|
||||||
|
selectionSkipped += outcome.selectionSkipped;
|
||||||
if (outcome.reconnect) {
|
if (outcome.reconnect) {
|
||||||
reconnects += 1;
|
reconnects += 1;
|
||||||
}
|
}
|
||||||
@@ -193,6 +231,7 @@ class SampleBook {
|
|||||||
final rtt = outcome.rttMs;
|
final rtt = outcome.rttMs;
|
||||||
if (rtt != null) {
|
if (rtt != null) {
|
||||||
lastRttMs = rtt;
|
lastRttMs = rtt;
|
||||||
|
_rtts.add(rtt);
|
||||||
if (_hasJitter) {
|
if (_hasJitter) {
|
||||||
final delta = (rtt - _lastTransit).abs();
|
final delta = (rtt - _lastTransit).abs();
|
||||||
jitterMs += (delta - jitterMs) / 16;
|
jitterMs += (delta - jitterMs) / 16;
|
||||||
@@ -250,6 +289,7 @@ class SampleBook {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
final latency = LatencyStats.from(_rtts);
|
||||||
return ProbeSummary(
|
return ProbeSummary(
|
||||||
sent: sent,
|
sent: sent,
|
||||||
completed: completed,
|
completed: completed,
|
||||||
@@ -269,6 +309,13 @@ class SampleBook {
|
|||||||
unknownPct: unknownPct,
|
unknownPct: unknownPct,
|
||||||
lastNote: lastNote,
|
lastNote: lastNote,
|
||||||
detail: detail,
|
detail: detail,
|
||||||
|
minRttMs: latency?.min,
|
||||||
|
meanRttMs: latency?.mean,
|
||||||
|
medianRttMs: latency?.median,
|
||||||
|
p95RttMs: latency?.p95,
|
||||||
|
maxRttMs: latency?.max,
|
||||||
|
selectionSkipped: selectionSkipped,
|
||||||
|
latencyStats: true,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,120 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'sample_book.dart';
|
||||||
|
|
||||||
|
/// A candidate "responded" when the address itself answered: success, a
|
||||||
|
/// protocol mismatch, or an explicit refusal. Silence, timeout and a
|
||||||
|
/// connect error are not a response, so another address may be tried.
|
||||||
|
bool selectionResponded(Outcome outcome) {
|
||||||
|
switch (outcome.status) {
|
||||||
|
case Outcome.ok:
|
||||||
|
case Outcome.protocol:
|
||||||
|
case Outcome.refused:
|
||||||
|
return true;
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SelectionDecision {
|
||||||
|
const SelectionDecision({required this.commit, this.skipped = 0});
|
||||||
|
|
||||||
|
final List<Outcome> commit;
|
||||||
|
final int skipped;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Separates address selection from measured probes.
|
||||||
|
///
|
||||||
|
/// Before any candidate has responded, failures are held. A later response
|
||||||
|
/// drops those held failures: they are reported as a fallback diagnostic and
|
||||||
|
/// are not added to sent, timeout or loss. If every candidate fails in the
|
||||||
|
/// round, the held failures are committed, so the session cannot show a
|
||||||
|
/// false 0% success. After a response, further failures are committed
|
||||||
|
/// immediately. [endMeasurement] is called when the picker leaves the
|
||||||
|
/// address that was being measured; the failure that caused the leave has
|
||||||
|
/// already been committed.
|
||||||
|
class SelectionLedger {
|
||||||
|
SelectionLedger(this.candidateCount);
|
||||||
|
|
||||||
|
final int candidateCount;
|
||||||
|
bool measuring = false;
|
||||||
|
final List<Outcome> _held = [];
|
||||||
|
|
||||||
|
SelectionDecision take(Outcome outcome, {required bool responded}) {
|
||||||
|
if (candidateCount <= 1) {
|
||||||
|
if (responded) {
|
||||||
|
measuring = true;
|
||||||
|
}
|
||||||
|
return SelectionDecision(commit: [outcome]);
|
||||||
|
}
|
||||||
|
if (measuring) {
|
||||||
|
return SelectionDecision(commit: [outcome]);
|
||||||
|
}
|
||||||
|
if (responded) {
|
||||||
|
final skipped = _held.length;
|
||||||
|
final next = skipped == 0
|
||||||
|
? outcome
|
||||||
|
: _attach(outcome, _fallbackText(_held, outcome), skipped);
|
||||||
|
_held.clear();
|
||||||
|
measuring = true;
|
||||||
|
return SelectionDecision(commit: [next], skipped: skipped);
|
||||||
|
}
|
||||||
|
_held.add(outcome);
|
||||||
|
if (_held.length >= candidateCount) {
|
||||||
|
final commit = List<Outcome>.of(_held);
|
||||||
|
_held.clear();
|
||||||
|
return SelectionDecision(commit: commit);
|
||||||
|
}
|
||||||
|
return const SelectionDecision(commit: []);
|
||||||
|
}
|
||||||
|
|
||||||
|
void endMeasurement() {
|
||||||
|
measuring = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Outcome _attach(Outcome outcome, String fallback, int skipped) {
|
||||||
|
return Outcome(
|
||||||
|
status: outcome.status,
|
||||||
|
kind: outcome.kind,
|
||||||
|
rttMs: outcome.rttMs,
|
||||||
|
note: outcome.note,
|
||||||
|
reconnect: outcome.reconnect,
|
||||||
|
selectionSkipped: outcome.selectionSkipped + skipped,
|
||||||
|
detail: {...outcome.detail, 'fallback': fallback},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
String _fallbackText(List<Outcome> held, Outcome success) {
|
||||||
|
final failed = held
|
||||||
|
.map((outcome) {
|
||||||
|
final address = outcome.detail['address'];
|
||||||
|
final family = outcome.detail['family'];
|
||||||
|
final where = address == null || address.isEmpty
|
||||||
|
? '未知地址'
|
||||||
|
: (family == null || family.isEmpty)
|
||||||
|
? address
|
||||||
|
: '$address($family)';
|
||||||
|
final why = outcome.note.isEmpty ? '没有成功' : outcome.note;
|
||||||
|
return '$where:$why';
|
||||||
|
})
|
||||||
|
.join(';');
|
||||||
|
final used = success.detail['address'] ?? '';
|
||||||
|
final usedFamily = success.detail['family'] ?? '';
|
||||||
|
final usedText = used.isEmpty
|
||||||
|
? '另一个地址'
|
||||||
|
: usedFamily.isEmpty
|
||||||
|
? used
|
||||||
|
: '$used($usedFamily)';
|
||||||
|
return '候选未成功:$failed。已改用 $usedText。这些失败没有计入正式丢包或失败率。';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stop discards the attempt that was still in flight. A finished attempt
|
||||||
|
/// whose note says it was stopped is not a measured loss either.
|
||||||
|
bool countsAfterStop(Outcome? outcome, {required bool cancelled}) {
|
||||||
|
if (cancelled || outcome == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return outcome.note != '已停止';
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import '../storage/token_vault.dart';
|
||||||
|
import 'session_config.dart';
|
||||||
|
|
||||||
|
/// Blank means "keep the token already stored". A non-blank value replaces it.
|
||||||
|
/// The saved token is never returned here.
|
||||||
|
String? replacementNodeToken(String entered) {
|
||||||
|
final trimmed = entered.trim();
|
||||||
|
if (trimmed.isEmpty) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes a replacement token. Returns false when the existing secret is kept.
|
||||||
|
Future<bool> saveEditedNodeToken(
|
||||||
|
TokenVault vault,
|
||||||
|
String id,
|
||||||
|
String entered,
|
||||||
|
) async {
|
||||||
|
final next = replacementNodeToken(entered);
|
||||||
|
if (next == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
await vault.write(nodeTokenKey(id), next);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keeps [RemoteNode.id]. Changing the control URL clears a cached visibility
|
||||||
|
/// check because it may now be a different server. The token is not part of
|
||||||
|
/// this object.
|
||||||
|
RemoteNode applyNodeEdit(
|
||||||
|
RemoteNode node, {
|
||||||
|
required String name,
|
||||||
|
required String baseUrl,
|
||||||
|
}) {
|
||||||
|
final urlChanged = node.baseUrl != baseUrl;
|
||||||
|
return node.copyWith(
|
||||||
|
name: name,
|
||||||
|
baseUrl: baseUrl,
|
||||||
|
visibility: urlChanged ? '' : node.visibility,
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'probe_profile.dart';
|
||||||
|
|
||||||
|
/// Keeps a port the user typed. An empty field or a value that is still the
|
||||||
|
/// previous profile's default follows the newly selected profile.
|
||||||
|
String portAfterProfileChange({
|
||||||
|
required String current,
|
||||||
|
required int previousDefault,
|
||||||
|
required int nextDefault,
|
||||||
|
}) {
|
||||||
|
final trimmed = current.trim();
|
||||||
|
if (trimmed.isEmpty || int.tryParse(trimmed) == previousDefault) {
|
||||||
|
return '$nextDefault';
|
||||||
|
}
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
String portHint(ProbeProfile profile) {
|
||||||
|
switch (profile.id) {
|
||||||
|
case 'nq-tcp':
|
||||||
|
return '合作反射 TCP 默认 19090';
|
||||||
|
case 'nq-udp':
|
||||||
|
return '合作反射 UDP 默认 19091';
|
||||||
|
default:
|
||||||
|
return '${profile.label} 默认 ${profile.port}';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const portHelperText =
|
||||||
|
'合作反射 TCP 默认 19090,UDP 默认 19091。只有当前端口仍是上一种类型的默认值或为空时,切换类型才会自动更换。';
|
||||||
@@ -1,22 +1,67 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
|
|
||||||
import '../metrics/sample_book.dart';
|
import '../metrics/sample_book.dart';
|
||||||
import '../models/probe_profile.dart';
|
import '../models/probe_profile.dart';
|
||||||
import '../models/session_config.dart';
|
import '../models/session_config.dart';
|
||||||
|
import '../ui/address_text.dart';
|
||||||
import 'endpoint_picker.dart';
|
import 'endpoint_picker.dart';
|
||||||
import 'probe_loop.dart';
|
import 'probe_loop.dart';
|
||||||
import 'remote_client.dart';
|
import 'remote_client.dart';
|
||||||
|
|
||||||
class ChartSample {
|
class ChartSample {
|
||||||
const ChartSample({required this.sec, required this.rttMs, required this.ratePct});
|
const ChartSample({
|
||||||
|
required this.sec,
|
||||||
|
required this.rttMs,
|
||||||
|
required this.ratePct,
|
||||||
|
});
|
||||||
|
|
||||||
final double sec;
|
final double sec;
|
||||||
final double? rttMs;
|
final double? rttMs;
|
||||||
final double? ratePct;
|
final double? ratePct;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class SessionReport {
|
||||||
|
const SessionReport({
|
||||||
|
required this.startedAt,
|
||||||
|
required this.endedAt,
|
||||||
|
required this.elapsed,
|
||||||
|
required this.target,
|
||||||
|
required this.profileLabel,
|
||||||
|
required this.sourceLabel,
|
||||||
|
required this.profileId,
|
||||||
|
required this.summary,
|
||||||
|
required this.rateLabel,
|
||||||
|
required this.resolved,
|
||||||
|
required this.usedAddress,
|
||||||
|
required this.usedFamily,
|
||||||
|
required this.fallbackText,
|
||||||
|
required this.addressUnreported,
|
||||||
|
required this.usedIsFake,
|
||||||
|
});
|
||||||
|
|
||||||
|
final DateTime startedAt;
|
||||||
|
final DateTime endedAt;
|
||||||
|
final Duration elapsed;
|
||||||
|
final String target;
|
||||||
|
final String profileLabel;
|
||||||
|
final String sourceLabel;
|
||||||
|
final String profileId;
|
||||||
|
final ProbeSummary summary;
|
||||||
|
final String rateLabel;
|
||||||
|
final List<ResolvedAddress> resolved;
|
||||||
|
final String? usedAddress;
|
||||||
|
final String? usedFamily;
|
||||||
|
final String fallbackText;
|
||||||
|
final bool addressUnreported;
|
||||||
|
final bool usedIsFake;
|
||||||
|
}
|
||||||
|
|
||||||
class ProbeView {
|
class ProbeView {
|
||||||
const ProbeView({
|
const ProbeView({
|
||||||
required this.running,
|
required this.running,
|
||||||
@@ -28,8 +73,22 @@ class ProbeView {
|
|||||||
required this.samples,
|
required this.samples,
|
||||||
required this.rateLabel,
|
required this.rateLabel,
|
||||||
required this.sourceLabel,
|
required this.sourceLabel,
|
||||||
this.targetAddress,
|
required this.sessionId,
|
||||||
this.targetIsFake = false,
|
this.profileId = '',
|
||||||
|
required this.elapsed,
|
||||||
|
this.targetHost = '',
|
||||||
|
this.profileLabel = '',
|
||||||
|
this.tryingAddress,
|
||||||
|
this.tryingFamily,
|
||||||
|
this.usedAddress,
|
||||||
|
this.usedFamily,
|
||||||
|
this.usedIsFake = false,
|
||||||
|
this.resolved = const [],
|
||||||
|
this.fallbackText = '',
|
||||||
|
this.addressUnreported = false,
|
||||||
|
this.report,
|
||||||
|
this.startedAt,
|
||||||
|
this.endedAt,
|
||||||
});
|
});
|
||||||
|
|
||||||
static const initial = ProbeView(
|
static const initial = ProbeView(
|
||||||
@@ -42,6 +101,8 @@ class ProbeView {
|
|||||||
samples: [],
|
samples: [],
|
||||||
rateLabel: '探测无应答',
|
rateLabel: '探测无应答',
|
||||||
sourceLabel: '本机',
|
sourceLabel: '本机',
|
||||||
|
sessionId: 0,
|
||||||
|
elapsed: Duration.zero,
|
||||||
);
|
);
|
||||||
|
|
||||||
final bool running;
|
final bool running;
|
||||||
@@ -53,8 +114,22 @@ class ProbeView {
|
|||||||
final List<ChartSample> samples;
|
final List<ChartSample> samples;
|
||||||
final String rateLabel;
|
final String rateLabel;
|
||||||
final String sourceLabel;
|
final String sourceLabel;
|
||||||
final String? targetAddress;
|
final int sessionId;
|
||||||
final bool targetIsFake;
|
final String profileId;
|
||||||
|
final Duration elapsed;
|
||||||
|
final String targetHost;
|
||||||
|
final String profileLabel;
|
||||||
|
final String? tryingAddress;
|
||||||
|
final String? tryingFamily;
|
||||||
|
final String? usedAddress;
|
||||||
|
final String? usedFamily;
|
||||||
|
final bool usedIsFake;
|
||||||
|
final List<ResolvedAddress> resolved;
|
||||||
|
final String fallbackText;
|
||||||
|
final bool addressUnreported;
|
||||||
|
final SessionReport? report;
|
||||||
|
final DateTime? startedAt;
|
||||||
|
final DateTime? endedAt;
|
||||||
|
|
||||||
ProbeView copyWith({
|
ProbeView copyWith({
|
||||||
bool? running,
|
bool? running,
|
||||||
@@ -67,8 +142,24 @@ class ProbeView {
|
|||||||
List<ChartSample>? samples,
|
List<ChartSample>? samples,
|
||||||
String? rateLabel,
|
String? rateLabel,
|
||||||
String? sourceLabel,
|
String? sourceLabel,
|
||||||
String? targetAddress,
|
int? sessionId,
|
||||||
bool? targetIsFake,
|
String? profileId,
|
||||||
|
Duration? elapsed,
|
||||||
|
String? targetHost,
|
||||||
|
String? profileLabel,
|
||||||
|
String? tryingAddress,
|
||||||
|
String? tryingFamily,
|
||||||
|
bool clearTrying = false,
|
||||||
|
String? usedAddress,
|
||||||
|
String? usedFamily,
|
||||||
|
bool? usedIsFake,
|
||||||
|
List<ResolvedAddress>? resolved,
|
||||||
|
String? fallbackText,
|
||||||
|
bool? addressUnreported,
|
||||||
|
SessionReport? report,
|
||||||
|
bool clearReport = false,
|
||||||
|
DateTime? startedAt,
|
||||||
|
DateTime? endedAt,
|
||||||
}) {
|
}) {
|
||||||
return ProbeView(
|
return ProbeView(
|
||||||
running: running ?? this.running,
|
running: running ?? this.running,
|
||||||
@@ -80,8 +171,22 @@ class ProbeView {
|
|||||||
samples: samples ?? this.samples,
|
samples: samples ?? this.samples,
|
||||||
rateLabel: rateLabel ?? this.rateLabel,
|
rateLabel: rateLabel ?? this.rateLabel,
|
||||||
sourceLabel: sourceLabel ?? this.sourceLabel,
|
sourceLabel: sourceLabel ?? this.sourceLabel,
|
||||||
targetAddress: targetAddress ?? this.targetAddress,
|
sessionId: sessionId ?? this.sessionId,
|
||||||
targetIsFake: targetIsFake ?? this.targetIsFake,
|
profileId: profileId ?? this.profileId,
|
||||||
|
elapsed: elapsed ?? this.elapsed,
|
||||||
|
targetHost: targetHost ?? this.targetHost,
|
||||||
|
profileLabel: profileLabel ?? this.profileLabel,
|
||||||
|
tryingAddress: clearTrying ? null : tryingAddress ?? this.tryingAddress,
|
||||||
|
tryingFamily: clearTrying ? null : tryingFamily ?? this.tryingFamily,
|
||||||
|
usedAddress: usedAddress ?? this.usedAddress,
|
||||||
|
usedFamily: usedFamily ?? this.usedFamily,
|
||||||
|
usedIsFake: usedIsFake ?? this.usedIsFake,
|
||||||
|
resolved: resolved ?? this.resolved,
|
||||||
|
fallbackText: fallbackText ?? this.fallbackText,
|
||||||
|
addressUnreported: addressUnreported ?? this.addressUnreported,
|
||||||
|
report: clearReport ? null : report ?? this.report,
|
||||||
|
startedAt: startedAt ?? this.startedAt,
|
||||||
|
endedAt: endedAt ?? this.endedAt,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -93,113 +198,154 @@ class ProbeController extends ChangeNotifier {
|
|||||||
RemoteProbe? _remote;
|
RemoteProbe? _remote;
|
||||||
String _nodeToken = '';
|
String _nodeToken = '';
|
||||||
var _token = 0;
|
var _token = 0;
|
||||||
|
var _session = 0;
|
||||||
|
var _busy = false;
|
||||||
|
var _remoteMode = false;
|
||||||
|
DateTime? _startedAt;
|
||||||
|
Timer? _tick;
|
||||||
|
|
||||||
Future<void> start(SessionConfig config, {required String nodeToken, required String echoToken}) async {
|
Future<void> start(
|
||||||
final problem = config.validate();
|
SessionConfig config, {
|
||||||
if (problem != null) {
|
required String nodeToken,
|
||||||
view = view.copyWith(banner: problem, phase: '无法开始');
|
required String echoToken,
|
||||||
notifyListeners();
|
}) async {
|
||||||
|
if (_busy) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final echoProblem = _echoProblem(config.profileId, echoToken);
|
_busy = true;
|
||||||
if (echoProblem != null) {
|
|
||||||
view = view.copyWith(banner: echoProblem, phase: '无法开始');
|
|
||||||
notifyListeners();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await stop();
|
|
||||||
_nodeToken = nodeToken;
|
|
||||||
final generation = ++_token;
|
|
||||||
_clock
|
|
||||||
..reset()
|
|
||||||
..start();
|
|
||||||
final source = config.remote ? (config.node?.name ?? '远程节点') : '本机';
|
|
||||||
view = ProbeView(
|
|
||||||
running: true,
|
|
||||||
phase: '探测中',
|
|
||||||
banner: null,
|
|
||||||
note: config.remote ? '正在让节点向目标发包' : '正在从本机向目标发包',
|
|
||||||
detail: const {},
|
|
||||||
summary: ProbeSummary.empty,
|
|
||||||
samples: const [],
|
|
||||||
rateLabel: rateLabelFor(config.profileId),
|
|
||||||
sourceLabel: source,
|
|
||||||
);
|
|
||||||
notifyListeners();
|
|
||||||
bool cancelled() => generation != _token;
|
|
||||||
try {
|
try {
|
||||||
if (config.remote) {
|
final problem = config.validate();
|
||||||
final remote = RemoteProbe();
|
if (problem != null) {
|
||||||
_remote = remote;
|
view = view.copyWith(banner: problem, phase: '无法开始');
|
||||||
await remote.run(
|
|
||||||
baseUrl: config.node!.baseUrl,
|
|
||||||
nodeToken: nodeToken,
|
|
||||||
body: ProbeBody(
|
|
||||||
target: config.host.trim(),
|
|
||||||
port: config.port,
|
|
||||||
profile: config.profileId,
|
|
||||||
intervalMs: config.intervalMs,
|
|
||||||
timeoutMs: config.timeoutMs,
|
|
||||||
durationSec: config.durationSec,
|
|
||||||
packetSize: config.packetSize,
|
|
||||||
echoToken: echoToken,
|
|
||||||
dnsName: config.dnsName.trim(),
|
|
||||||
payloadHex: config.payloadHex.trim(),
|
|
||||||
expectHex: config.expectHex.trim(),
|
|
||||||
),
|
|
||||||
onSample: (sample) => _accept(generation, sample),
|
|
||||||
cancelled: cancelled,
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
final loop = ProbeLoop(
|
|
||||||
onEndpoint: (address) {
|
|
||||||
if (generation != _token) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
view = view.copyWith(
|
|
||||||
targetAddress: address.address,
|
|
||||||
targetIsFake: isClashFakeIp(address),
|
|
||||||
);
|
|
||||||
notifyListeners();
|
|
||||||
},
|
|
||||||
);
|
|
||||||
_local = loop;
|
|
||||||
await loop.run(
|
|
||||||
request: ProbeRequest(
|
|
||||||
host: config.host.trim(),
|
|
||||||
port: config.port,
|
|
||||||
profileId: config.profileId,
|
|
||||||
interval: Duration(milliseconds: config.intervalMs),
|
|
||||||
timeout: Duration(milliseconds: config.timeoutMs),
|
|
||||||
packetSize: config.packetSize,
|
|
||||||
echoToken: echoToken,
|
|
||||||
dnsName: config.dnsName.trim(),
|
|
||||||
payloadHex: config.payloadHex.trim(),
|
|
||||||
expectHex: config.expectHex.trim(),
|
|
||||||
),
|
|
||||||
onSample: (sample) => _accept(generation, sample),
|
|
||||||
cancelled: cancelled,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (generation == _token) {
|
|
||||||
view = view.copyWith(running: false, phase: '已停止');
|
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
} on RemoteException catch (error) {
|
final echoProblem = _echoProblem(config.profileId, echoToken);
|
||||||
if (generation == _token) {
|
if (echoProblem != null) {
|
||||||
view = view.copyWith(running: false, phase: '出错', banner: error.message);
|
view = view.copyWith(banner: echoProblem, phase: '无法开始');
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
} on Object {
|
await stop();
|
||||||
if (generation == _token) {
|
_nodeToken = nodeToken;
|
||||||
view = view.copyWith(running: false, phase: '出错', banner: '探测中断');
|
_remoteMode = config.remote;
|
||||||
notifyListeners();
|
final generation = ++_token;
|
||||||
|
final session = ++_session;
|
||||||
|
_startedAt = DateTime.now();
|
||||||
|
_clock
|
||||||
|
..reset()
|
||||||
|
..start();
|
||||||
|
final source = config.remote ? (config.node?.name ?? '远程节点') : '本机';
|
||||||
|
final profile = ProbeProfile.byId(config.profileId);
|
||||||
|
view = ProbeView(
|
||||||
|
running: true,
|
||||||
|
phase: '探测中',
|
||||||
|
banner: null,
|
||||||
|
note: config.remote ? '正在让节点向目标发包' : '正在从本机向目标发包',
|
||||||
|
detail: const {},
|
||||||
|
summary: ProbeSummary.empty,
|
||||||
|
samples: const [],
|
||||||
|
rateLabel: rateLabelFor(config.profileId),
|
||||||
|
sourceLabel: source,
|
||||||
|
sessionId: session,
|
||||||
|
profileId: config.profileId,
|
||||||
|
elapsed: Duration.zero,
|
||||||
|
targetHost: '${config.host.trim()}:${config.port}',
|
||||||
|
profileLabel: profile.label,
|
||||||
|
startedAt: _startedAt,
|
||||||
|
);
|
||||||
|
notifyListeners();
|
||||||
|
_armTick(generation);
|
||||||
|
bool cancelled() => generation != _token;
|
||||||
|
try {
|
||||||
|
if (config.remote) {
|
||||||
|
final remote = RemoteProbe();
|
||||||
|
_remote = remote;
|
||||||
|
await remote.run(
|
||||||
|
baseUrl: config.node!.baseUrl,
|
||||||
|
nodeToken: nodeToken,
|
||||||
|
body: ProbeBody(
|
||||||
|
target: config.host.trim(),
|
||||||
|
port: config.port,
|
||||||
|
profile: config.profileId,
|
||||||
|
intervalMs: config.intervalMs,
|
||||||
|
timeoutMs: config.timeoutMs,
|
||||||
|
durationSec: config.durationSec,
|
||||||
|
packetSize: config.packetSize,
|
||||||
|
echoToken: echoToken,
|
||||||
|
dnsName: config.dnsName.trim(),
|
||||||
|
payloadHex: config.payloadHex.trim(),
|
||||||
|
expectHex: config.expectHex.trim(),
|
||||||
|
),
|
||||||
|
onSample: (sample) => _accept(generation, sample),
|
||||||
|
onResolved: (resolved) {
|
||||||
|
if (generation != _token) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
view = view.copyWith(resolved: resolved);
|
||||||
|
notifyListeners();
|
||||||
|
},
|
||||||
|
cancelled: cancelled,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
final loop = ProbeLoop(
|
||||||
|
onEndpoint: (address) {
|
||||||
|
if (generation != _token) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
view = view.copyWith(
|
||||||
|
tryingAddress: address.address,
|
||||||
|
tryingFamily: addressFamily(address),
|
||||||
|
);
|
||||||
|
notifyListeners();
|
||||||
|
},
|
||||||
|
onResolved: (addresses) {
|
||||||
|
if (generation != _token) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
view = view.copyWith(
|
||||||
|
resolved: [
|
||||||
|
for (final address in addresses)
|
||||||
|
ResolvedAddress(
|
||||||
|
address: address.address,
|
||||||
|
family: addressFamily(address),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
notifyListeners();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
_local = loop;
|
||||||
|
await loop.run(
|
||||||
|
request: ProbeRequest(
|
||||||
|
host: config.host.trim(),
|
||||||
|
port: config.port,
|
||||||
|
profileId: config.profileId,
|
||||||
|
interval: Duration(milliseconds: config.intervalMs),
|
||||||
|
timeout: Duration(milliseconds: config.timeoutMs),
|
||||||
|
packetSize: config.packetSize,
|
||||||
|
echoToken: echoToken,
|
||||||
|
dnsName: config.dnsName.trim(),
|
||||||
|
payloadHex: config.payloadHex.trim(),
|
||||||
|
expectHex: config.expectHex.trim(),
|
||||||
|
),
|
||||||
|
onSample: (sample) => _accept(generation, sample),
|
||||||
|
cancelled: cancelled,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
_finish(generation, '已停止');
|
||||||
|
} on RemoteException catch (error) {
|
||||||
|
_finish(generation, '出错', banner: error.message);
|
||||||
|
} on Object {
|
||||||
|
_finish(generation, '出错', banner: '探测中断');
|
||||||
|
} finally {
|
||||||
|
if (generation == _token) {
|
||||||
|
_local = null;
|
||||||
|
_remote = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if (generation == _token) {
|
_busy = false;
|
||||||
_local = null;
|
|
||||||
_remote = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -217,11 +363,73 @@ class ProbeController extends ChangeNotifier {
|
|||||||
_nodeToken = '';
|
_nodeToken = '';
|
||||||
}
|
}
|
||||||
if (view.running) {
|
if (view.running) {
|
||||||
view = view.copyWith(running: false, phase: '已停止');
|
_clock.stop();
|
||||||
|
_tick?.cancel();
|
||||||
|
final ended = DateTime.now();
|
||||||
|
view = view.copyWith(
|
||||||
|
running: false,
|
||||||
|
phase: '已停止',
|
||||||
|
elapsed: _clock.elapsed,
|
||||||
|
endedAt: ended,
|
||||||
|
report: _snapshot(ended),
|
||||||
|
);
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void _finish(int generation, String phase, {String? banner}) {
|
||||||
|
if (generation != _token || !view.running) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
_clock.stop();
|
||||||
|
_tick?.cancel();
|
||||||
|
final ended = DateTime.now();
|
||||||
|
view = view.copyWith(
|
||||||
|
running: false,
|
||||||
|
phase: phase,
|
||||||
|
banner: banner,
|
||||||
|
elapsed: _clock.elapsed,
|
||||||
|
endedAt: ended,
|
||||||
|
report: _snapshot(ended),
|
||||||
|
);
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
SessionReport? _snapshot(DateTime ended) {
|
||||||
|
final started = _startedAt;
|
||||||
|
if (started == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return SessionReport(
|
||||||
|
startedAt: started,
|
||||||
|
endedAt: ended,
|
||||||
|
elapsed: _clock.elapsed,
|
||||||
|
target: view.targetHost,
|
||||||
|
profileLabel: view.profileLabel,
|
||||||
|
sourceLabel: view.sourceLabel,
|
||||||
|
profileId: view.profileId,
|
||||||
|
summary: view.summary,
|
||||||
|
rateLabel: view.rateLabel,
|
||||||
|
resolved: view.resolved,
|
||||||
|
usedAddress: view.usedAddress,
|
||||||
|
usedFamily: view.usedFamily,
|
||||||
|
fallbackText: view.fallbackText,
|
||||||
|
addressUnreported: view.addressUnreported,
|
||||||
|
usedIsFake: view.usedIsFake,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _armTick(int generation) {
|
||||||
|
_tick?.cancel();
|
||||||
|
_tick = Timer.periodic(const Duration(seconds: 1), (_) {
|
||||||
|
if (generation != _token || !view.running) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
view = view.copyWith(elapsed: _clock.elapsed);
|
||||||
|
notifyListeners();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
void _accept(int generation, ProbeSample sample) {
|
void _accept(int generation, ProbeSample sample) {
|
||||||
if (generation != _token) {
|
if (generation != _token) {
|
||||||
return;
|
return;
|
||||||
@@ -246,6 +454,16 @@ class ProbeController extends ChangeNotifier {
|
|||||||
ratePct: rate,
|
ratePct: rate,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
final reported = sample.detail['address'];
|
||||||
|
final hasAddress = reported != null && reported.isNotEmpty;
|
||||||
|
final fallback = sample.detail['fallback'];
|
||||||
|
final parsed = hasAddress ? InternetAddress.tryParse(reported) : null;
|
||||||
|
final family = hasAddress
|
||||||
|
? ((sample.detail['family'] != null &&
|
||||||
|
sample.detail['family']!.isNotEmpty)
|
||||||
|
? sample.detail['family']
|
||||||
|
: familyOfAddress(reported))
|
||||||
|
: null;
|
||||||
view = view.copyWith(
|
view = view.copyWith(
|
||||||
phase: phaseFor(sample.status),
|
phase: phaseFor(sample.status),
|
||||||
note: sample.note,
|
note: sample.note,
|
||||||
@@ -253,9 +471,24 @@ class ProbeController extends ChangeNotifier {
|
|||||||
summary: sample.summary,
|
summary: sample.summary,
|
||||||
samples: samples,
|
samples: samples,
|
||||||
clearBanner: true,
|
clearBanner: true,
|
||||||
|
elapsed: _clock.elapsed,
|
||||||
|
usedAddress: hasAddress ? reported : view.usedAddress,
|
||||||
|
usedFamily: hasAddress ? family : view.usedFamily,
|
||||||
|
usedIsFake: hasAddress
|
||||||
|
? parsed != null && isClashFakeIp(parsed)
|
||||||
|
: view.usedIsFake,
|
||||||
|
clearTrying: hasAddress || (fallback != null && fallback.isNotEmpty),
|
||||||
|
fallbackText: (fallback != null && fallback.isNotEmpty) ? fallback : null,
|
||||||
|
addressUnreported: _remoteMode && !hasAddress,
|
||||||
);
|
);
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_tick?.cancel();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
String? _echoProblem(String profileId, String echoToken) {
|
String? _echoProblem(String profileId, String echoToken) {
|
||||||
|
|||||||
@@ -3,7 +3,9 @@ import 'dart:io';
|
|||||||
import 'dart:typed_data';
|
import 'dart:typed_data';
|
||||||
|
|
||||||
import '../metrics/sample_book.dart';
|
import '../metrics/sample_book.dart';
|
||||||
|
import '../metrics/selection_ledger.dart';
|
||||||
import '../protocol/probe_packet.dart';
|
import '../protocol/probe_packet.dart';
|
||||||
|
import '../ui/address_text.dart';
|
||||||
import 'endpoint_picker.dart';
|
import 'endpoint_picker.dart';
|
||||||
import 'game_codec.dart';
|
import 'game_codec.dart';
|
||||||
|
|
||||||
@@ -36,10 +38,7 @@ class ProbeRequest {
|
|||||||
/// Sends one probe at a time from this device. A cancelled attempt is not
|
/// Sends one probe at a time from this device. A cancelled attempt is not
|
||||||
/// recorded, so stopping cannot paint a fake loss sample.
|
/// recorded, so stopping cannot paint a fake loss sample.
|
||||||
class ProbeLoop {
|
class ProbeLoop {
|
||||||
ProbeLoop({
|
ProbeLoop({this.lookup, this.onEndpoint, this.onResolved});
|
||||||
this.lookup,
|
|
||||||
this.onEndpoint,
|
|
||||||
});
|
|
||||||
|
|
||||||
/// Replaces [lookupAll] in tests.
|
/// Replaces [lookupAll] in tests.
|
||||||
final Future<List<InternetAddress>> Function(String host)? lookup;
|
final Future<List<InternetAddress>> Function(String host)? lookup;
|
||||||
@@ -47,10 +46,16 @@ class ProbeLoop {
|
|||||||
/// Fires when the address about to be used is chosen or changed.
|
/// Fires when the address about to be used is chosen or changed.
|
||||||
final void Function(InternetAddress address)? onEndpoint;
|
final void Function(InternetAddress address)? onEndpoint;
|
||||||
|
|
||||||
|
/// Fires once with the lookup result. This is not the address in use.
|
||||||
|
final void Function(List<InternetAddress> addresses)? onResolved;
|
||||||
|
|
||||||
_TcpPipe? _tcp;
|
_TcpPipe? _tcp;
|
||||||
_UdpPipe? _udp;
|
_UdpPipe? _udp;
|
||||||
EndpointPicker? _picker;
|
EndpointPicker? _picker;
|
||||||
|
SelectionLedger? _ledger;
|
||||||
InternetAddress? _announced;
|
InternetAddress? _announced;
|
||||||
|
InternetAddress? _tcpUsed;
|
||||||
|
List<InternetAddress>? _resolved;
|
||||||
int _seq = 0;
|
int _seq = 0;
|
||||||
int _dnsId = 1;
|
int _dnsId = 1;
|
||||||
final int _guid = DateTime.now().microsecondsSinceEpoch;
|
final int _guid = DateTime.now().microsecondsSinceEpoch;
|
||||||
@@ -65,20 +70,32 @@ class ProbeLoop {
|
|||||||
while (!cancelled()) {
|
while (!cancelled()) {
|
||||||
final started = DateTime.now();
|
final started = DateTime.now();
|
||||||
final outcome = await _once(request, cancelled);
|
final outcome = await _once(request, cancelled);
|
||||||
if (cancelled() || outcome == null) {
|
if (!countsAfterStop(outcome, cancelled: cancelled())) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (_usesDatagram(request.profileId)) {
|
var commit = <Outcome>[outcome!];
|
||||||
final responded = outcome.status == Outcome.ok ||
|
if (_usesDatagram(request.profileId) && _picker != null) {
|
||||||
outcome.status == Outcome.protocol ||
|
_ledger ??= SelectionLedger(_picker!.candidates.length);
|
||||||
outcome.status == Outcome.refused;
|
final responded = selectionResponded(outcome);
|
||||||
if (_picker != null && _picker!.record(responded)) {
|
final wasMeasuring = _ledger!.measuring;
|
||||||
|
final changed = _picker!.record(responded);
|
||||||
|
final decision = _ledger!.take(outcome, responded: responded);
|
||||||
|
if (wasMeasuring && changed) {
|
||||||
|
_ledger!.endMeasurement();
|
||||||
|
}
|
||||||
|
if (changed) {
|
||||||
await _dropUdp();
|
await _dropUdp();
|
||||||
_announce(_picker!.current);
|
_announce(_picker!.current);
|
||||||
}
|
}
|
||||||
|
commit = decision.commit;
|
||||||
|
if (commit.isEmpty) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (final item in commit) {
|
||||||
|
book.add(item);
|
||||||
|
onSample(book.sample(book.sent, item));
|
||||||
}
|
}
|
||||||
book.add(outcome);
|
|
||||||
onSample(book.sample(book.sent, outcome));
|
|
||||||
final spent = DateTime.now().difference(started);
|
final spent = DateTime.now().difference(started);
|
||||||
final rest = request.interval - spent;
|
final rest = request.interval - spent;
|
||||||
if (!cancelled() && rest > Duration.zero) {
|
if (!cancelled() && rest > Duration.zero) {
|
||||||
@@ -103,7 +120,10 @@ class ProbeLoop {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<Outcome?> _once(ProbeRequest request, bool Function() cancelled) async {
|
Future<Outcome?> _once(
|
||||||
|
ProbeRequest request,
|
||||||
|
bool Function() cancelled,
|
||||||
|
) async {
|
||||||
try {
|
try {
|
||||||
final outcome = await _dispatch(request, cancelled);
|
final outcome = await _dispatch(request, cancelled);
|
||||||
final peer = _udp?.peer;
|
final peer = _udp?.peer;
|
||||||
@@ -160,45 +180,58 @@ class ProbeLoop {
|
|||||||
ProbeRequest request,
|
ProbeRequest request,
|
||||||
bool Function() cancelled,
|
bool Function() cancelled,
|
||||||
) async {
|
) async {
|
||||||
final watch = Stopwatch()..start();
|
final opened = await _openTcp(request, cancelled);
|
||||||
final socket = await Socket.connect(
|
final failure = opened.failure;
|
||||||
request.host,
|
if (failure != null) {
|
||||||
request.port,
|
return failure;
|
||||||
timeout: request.timeout,
|
}
|
||||||
);
|
final socket = opened.socket!;
|
||||||
watch.stop();
|
opened.watch?.stop();
|
||||||
await socket.close();
|
await socket.close();
|
||||||
if (cancelled()) {
|
if (cancelled()) {
|
||||||
return const Outcome(status: Outcome.timeout, kind: Outcome.connect, note: '已停止');
|
return const Outcome(
|
||||||
|
status: Outcome.timeout,
|
||||||
|
kind: Outcome.connect,
|
||||||
|
note: '已停止',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return Outcome(
|
return _withUsed(
|
||||||
status: Outcome.ok,
|
Outcome(
|
||||||
kind: Outcome.connect,
|
status: Outcome.ok,
|
||||||
rttMs: watch.elapsedMicroseconds / 1000,
|
kind: Outcome.connect,
|
||||||
note: 'TCP 已连通',
|
rttMs: (opened.watch?.elapsedMicroseconds ?? 0) / 1000,
|
||||||
|
note: 'TCP 已连通',
|
||||||
|
),
|
||||||
|
opened.used,
|
||||||
|
opened.fallback,
|
||||||
|
opened.skipped,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<Outcome> _nqTcp(ProbeRequest request, bool Function() cancelled) async {
|
Future<Outcome> _nqTcp(
|
||||||
|
ProbeRequest request,
|
||||||
|
bool Function() cancelled,
|
||||||
|
) async {
|
||||||
|
var fallback = '';
|
||||||
|
var skipped = 0;
|
||||||
if (_tcp == null) {
|
if (_tcp == null) {
|
||||||
try {
|
final opened = await _openTcp(request, cancelled);
|
||||||
final socket = await Socket.connect(
|
final failure = opened.failure;
|
||||||
request.host,
|
if (failure != null) {
|
||||||
request.port,
|
return Outcome(
|
||||||
timeout: request.timeout,
|
status: failure.status,
|
||||||
);
|
kind: failure.kind,
|
||||||
socket.setOption(SocketOption.tcpNoDelay, true);
|
note: failure.note,
|
||||||
_tcp = _TcpPipe(socket);
|
reconnect: failure.note != '已停止',
|
||||||
} on SocketException catch (error) {
|
detail: failure.detail,
|
||||||
return classifySocket(error, reconnect: true);
|
|
||||||
} on TimeoutException {
|
|
||||||
return const Outcome(
|
|
||||||
status: Outcome.timeout,
|
|
||||||
kind: Outcome.connect,
|
|
||||||
reconnect: true,
|
|
||||||
note: '连接超时,将重试',
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
final socket = opened.socket!;
|
||||||
|
socket.setOption(SocketOption.tcpNoDelay, true);
|
||||||
|
_tcp = _TcpPipe(socket);
|
||||||
|
_tcpUsed = opened.used;
|
||||||
|
fallback = opened.fallback;
|
||||||
|
skipped = opened.skipped;
|
||||||
}
|
}
|
||||||
final pipe = _tcp!;
|
final pipe = _tcp!;
|
||||||
_seq += 1;
|
_seq += 1;
|
||||||
@@ -232,21 +265,35 @@ class ProbeLoop {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
if (cancelled()) {
|
if (cancelled()) {
|
||||||
return const Outcome(status: Outcome.timeout, kind: Outcome.connect, note: '已停止');
|
return const Outcome(
|
||||||
|
status: Outcome.timeout,
|
||||||
|
kind: Outcome.connect,
|
||||||
|
note: '已停止',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (matched == null) {
|
if (matched == null) {
|
||||||
await _dropTcp();
|
await _dropTcp();
|
||||||
return const Outcome(
|
return _withUsed(
|
||||||
status: Outcome.timeout,
|
const Outcome(
|
||||||
kind: Outcome.probe,
|
status: Outcome.timeout,
|
||||||
note: '已发出探测,超时前没有收到回显。TCP 会重传,这不是已证实的物理丢包',
|
kind: Outcome.probe,
|
||||||
|
note: '已发出探测,超时前没有收到回显。TCP 会重传,这不是已证实的物理丢包',
|
||||||
|
),
|
||||||
|
_tcpUsed,
|
||||||
|
fallback,
|
||||||
|
skipped,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return Outcome(
|
return _withUsed(
|
||||||
status: Outcome.ok,
|
Outcome(
|
||||||
kind: Outcome.probe,
|
status: Outcome.ok,
|
||||||
rttMs: watch.elapsedMicroseconds / 1000,
|
kind: Outcome.probe,
|
||||||
note: '收到回显',
|
rttMs: watch.elapsedMicroseconds / 1000,
|
||||||
|
note: '收到回显',
|
||||||
|
),
|
||||||
|
_tcpUsed,
|
||||||
|
fallback,
|
||||||
|
skipped,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -258,7 +305,10 @@ class ProbeLoop {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<Outcome> _nqUdp(ProbeRequest request, bool Function() cancelled) async {
|
Future<Outcome> _nqUdp(
|
||||||
|
ProbeRequest request,
|
||||||
|
bool Function() cancelled,
|
||||||
|
) async {
|
||||||
final pipe = await _datagram(request);
|
final pipe = await _datagram(request);
|
||||||
_seq += 1;
|
_seq += 1;
|
||||||
final seq = _seq;
|
final seq = _seq;
|
||||||
@@ -286,7 +336,11 @@ class ProbeLoop {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
if (cancelled()) {
|
if (cancelled()) {
|
||||||
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
|
return const Outcome(
|
||||||
|
status: Outcome.unknown,
|
||||||
|
kind: Outcome.query,
|
||||||
|
note: '已停止',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (reply == null) {
|
if (reply == null) {
|
||||||
if (sawInvalid) {
|
if (sawInvalid) {
|
||||||
@@ -329,7 +383,11 @@ class ProbeLoop {
|
|||||||
pipe.send(payload, request.port);
|
pipe.send(payload, request.port);
|
||||||
final reply = await pipe.waitMatch(request.timeout, (_) => true);
|
final reply = await pipe.waitMatch(request.timeout, (_) => true);
|
||||||
if (cancelled()) {
|
if (cancelled()) {
|
||||||
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
|
return const Outcome(
|
||||||
|
status: Outcome.unknown,
|
||||||
|
kind: Outcome.query,
|
||||||
|
note: '已停止',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (reply == null) {
|
if (reply == null) {
|
||||||
return const Outcome(
|
return const Outcome(
|
||||||
@@ -339,7 +397,8 @@ class ProbeLoop {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
final wanted = expect;
|
final wanted = expect;
|
||||||
if (wanted != null && (reply.length < wanted.length || !_prefix(reply, wanted))) {
|
if (wanted != null &&
|
||||||
|
(reply.length < wanted.length || !_prefix(reply, wanted))) {
|
||||||
return const Outcome(
|
return const Outcome(
|
||||||
status: Outcome.protocol,
|
status: Outcome.protocol,
|
||||||
kind: Outcome.query,
|
kind: Outcome.query,
|
||||||
@@ -358,7 +417,9 @@ class ProbeLoop {
|
|||||||
final pipe = await _datagram(request);
|
final pipe = await _datagram(request);
|
||||||
_dnsId = _dnsId == 65535 ? 1 : _dnsId + 1;
|
_dnsId = _dnsId == 65535 ? 1 : _dnsId + 1;
|
||||||
final id = _dnsId;
|
final id = _dnsId;
|
||||||
final name = request.dnsName.trim().isEmpty ? 'example.com' : request.dnsName.trim();
|
final name = request.dnsName.trim().isEmpty
|
||||||
|
? 'example.com'
|
||||||
|
: request.dnsName.trim();
|
||||||
final watch = Stopwatch()..start();
|
final watch = Stopwatch()..start();
|
||||||
pipe.send(dnsQuery(id, name), request.port);
|
pipe.send(dnsQuery(id, name), request.port);
|
||||||
var malformed = false;
|
var malformed = false;
|
||||||
@@ -378,7 +439,11 @@ class ProbeLoop {
|
|||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
if (cancelled()) {
|
if (cancelled()) {
|
||||||
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
|
return const Outcome(
|
||||||
|
status: Outcome.unknown,
|
||||||
|
kind: Outcome.query,
|
||||||
|
note: '已停止',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (reply == null) {
|
if (reply == null) {
|
||||||
if (malformed) {
|
if (malformed) {
|
||||||
@@ -422,7 +487,11 @@ class ProbeLoop {
|
|||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
if (cancelled()) {
|
if (cancelled()) {
|
||||||
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
|
return const Outcome(
|
||||||
|
status: Outcome.unknown,
|
||||||
|
kind: Outcome.query,
|
||||||
|
note: '已停止',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (reply == null) {
|
if (reply == null) {
|
||||||
if (sawInvalid) {
|
if (sawInvalid) {
|
||||||
@@ -448,11 +517,12 @@ class ProbeLoop {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<Outcome> _java(ProbeRequest request, bool Function() cancelled) async {
|
Future<Outcome> _java(ProbeRequest request, bool Function() cancelled) async {
|
||||||
final socket = await Socket.connect(
|
final opened = await _openTcp(request, cancelled);
|
||||||
request.host,
|
final failure = opened.failure;
|
||||||
request.port,
|
if (failure != null) {
|
||||||
timeout: request.timeout,
|
return failure;
|
||||||
);
|
}
|
||||||
|
final socket = opened.socket!;
|
||||||
final reader = _BytePipe(socket);
|
final reader = _BytePipe(socket);
|
||||||
try {
|
try {
|
||||||
socket.add(javaHandshake(request.host, request.port));
|
socket.add(javaHandshake(request.host, request.port));
|
||||||
@@ -460,18 +530,28 @@ class ProbeLoop {
|
|||||||
await socket.flush();
|
await socket.flush();
|
||||||
final status = await reader.nextPacket(request.timeout);
|
final status = await reader.nextPacket(request.timeout);
|
||||||
if (status == null || status.isEmpty || status[0] != 0x00) {
|
if (status == null || status.isEmpty || status[0] != 0x00) {
|
||||||
return const Outcome(
|
return _withUsed(
|
||||||
status: Outcome.protocol,
|
const Outcome(
|
||||||
kind: Outcome.query,
|
status: Outcome.protocol,
|
||||||
note: 'Minecraft 状态响应无效',
|
kind: Outcome.query,
|
||||||
|
note: 'Minecraft 状态响应无效',
|
||||||
|
),
|
||||||
|
opened.used,
|
||||||
|
opened.fallback,
|
||||||
|
opened.skipped,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
final jsonText = readMcString(status, 1);
|
final jsonText = readMcString(status, 1);
|
||||||
if (jsonText == null) {
|
if (jsonText == null) {
|
||||||
return const Outcome(
|
return _withUsed(
|
||||||
status: Outcome.protocol,
|
const Outcome(
|
||||||
kind: Outcome.query,
|
status: Outcome.protocol,
|
||||||
note: 'Minecraft 状态内容无法解析',
|
kind: Outcome.query,
|
||||||
|
note: 'Minecraft 状态内容无法解析',
|
||||||
|
),
|
||||||
|
opened.used,
|
||||||
|
opened.fallback,
|
||||||
|
opened.skipped,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
final detail = minecraftStatusDetail(jsonText);
|
final detail = minecraftStatusDetail(jsonText);
|
||||||
@@ -481,30 +561,49 @@ class ProbeLoop {
|
|||||||
await socket.flush();
|
await socket.flush();
|
||||||
final pong = await reader.nextPacket(request.timeout);
|
final pong = await reader.nextPacket(request.timeout);
|
||||||
if (cancelled()) {
|
if (cancelled()) {
|
||||||
return const Outcome(status: Outcome.timeout, kind: Outcome.connect, note: '已停止');
|
return const Outcome(
|
||||||
|
status: Outcome.timeout,
|
||||||
|
kind: Outcome.connect,
|
||||||
|
note: '已停止',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (pong == null || pong.length != 9 || pong[0] != 0x01) {
|
if (pong == null || pong.length != 9 || pong[0] != 0x01) {
|
||||||
return Outcome(
|
return _withUsed(
|
||||||
status: Outcome.protocol,
|
Outcome(
|
||||||
kind: Outcome.query,
|
status: Outcome.protocol,
|
||||||
note: '没有收到有效的 Minecraft pong',
|
kind: Outcome.query,
|
||||||
detail: detail,
|
note: '没有收到有效的 Minecraft pong',
|
||||||
|
detail: detail,
|
||||||
|
),
|
||||||
|
opened.used,
|
||||||
|
opened.fallback,
|
||||||
|
opened.skipped,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (ByteData.sublistView(pong).getUint64(1) != nonce) {
|
if (ByteData.sublistView(pong).getUint64(1) != nonce) {
|
||||||
return Outcome(
|
return _withUsed(
|
||||||
status: Outcome.protocol,
|
Outcome(
|
||||||
kind: Outcome.query,
|
status: Outcome.protocol,
|
||||||
note: 'Minecraft pong 的时间戳不匹配',
|
kind: Outcome.query,
|
||||||
detail: detail,
|
note: 'Minecraft pong 的时间戳不匹配',
|
||||||
|
detail: detail,
|
||||||
|
),
|
||||||
|
opened.used,
|
||||||
|
opened.fallback,
|
||||||
|
opened.skipped,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
return Outcome(
|
return _withUsed(
|
||||||
status: Outcome.ok,
|
Outcome(
|
||||||
kind: Outcome.query,
|
status: Outcome.ok,
|
||||||
rttMs: watch.elapsedMicroseconds / 1000,
|
kind: Outcome.query,
|
||||||
note: '收到 Minecraft 状态和 ping 应答',
|
rttMs: watch.elapsedMicroseconds / 1000,
|
||||||
detail: detail,
|
note: '收到 Minecraft 状态和 ping 应答',
|
||||||
|
detail: detail,
|
||||||
|
),
|
||||||
|
opened.used,
|
||||||
|
opened.fallback,
|
||||||
|
opened.skipped,
|
||||||
);
|
);
|
||||||
} finally {
|
} finally {
|
||||||
await reader.close();
|
await reader.close();
|
||||||
@@ -513,7 +612,7 @@ class ProbeLoop {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<_UdpPipe> _datagram(ProbeRequest request) async {
|
Future<_UdpPipe> _datagram(ProbeRequest request) async {
|
||||||
_picker ??= EndpointPicker(await (lookup ?? lookupAll)(request.host));
|
_picker ??= EndpointPicker(await _addresses(request.host));
|
||||||
final want = _picker!.current;
|
final want = _picker!.current;
|
||||||
final existing = _udp;
|
final existing = _udp;
|
||||||
if (existing != null && existing.peer.address == want.address) {
|
if (existing != null && existing.peer.address == want.address) {
|
||||||
@@ -550,6 +649,134 @@ class ProbeLoop {
|
|||||||
await udp.close();
|
await udp.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<List<InternetAddress>> _addresses(String host) async {
|
||||||
|
final cached = _resolved;
|
||||||
|
if (cached != null) {
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
final found = await (lookup ?? lookupAll)(host);
|
||||||
|
_resolved = found;
|
||||||
|
onResolved?.call(found);
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<_TcpOpen> _openTcp(
|
||||||
|
ProbeRequest request,
|
||||||
|
bool Function() cancelled,
|
||||||
|
) async {
|
||||||
|
List<InternetAddress> addresses;
|
||||||
|
try {
|
||||||
|
addresses = await _addresses(request.host);
|
||||||
|
} on SocketException catch (error) {
|
||||||
|
return _TcpOpen.fail(classifySocket(error));
|
||||||
|
}
|
||||||
|
final skipped = <String>[];
|
||||||
|
Object? last;
|
||||||
|
for (final address in addresses) {
|
||||||
|
if (cancelled()) {
|
||||||
|
return _TcpOpen.fail(
|
||||||
|
const Outcome(
|
||||||
|
status: Outcome.timeout,
|
||||||
|
kind: Outcome.connect,
|
||||||
|
note: '已停止',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
_announce(address);
|
||||||
|
final watch = Stopwatch()..start();
|
||||||
|
try {
|
||||||
|
final socket = await Socket.connect(
|
||||||
|
address,
|
||||||
|
request.port,
|
||||||
|
timeout: request.timeout,
|
||||||
|
);
|
||||||
|
watch.stop();
|
||||||
|
final fallback = skipped.isEmpty
|
||||||
|
? ''
|
||||||
|
: '候选未连通:${skipped.join(';')}。已改用 ${address.address}(${addressFamily(address)})。这些失败没有计入正式丢包或失败率。';
|
||||||
|
return _TcpOpen.ok(socket, address, watch, fallback, skipped.length);
|
||||||
|
} on SocketException catch (error) {
|
||||||
|
last = error;
|
||||||
|
skipped.add(
|
||||||
|
'${addressFamily(address)} ${address.address}:${classifySocket(error).note}',
|
||||||
|
);
|
||||||
|
} on TimeoutException {
|
||||||
|
last = TimeoutException('连接超时');
|
||||||
|
skipped.add('${addressFamily(address)} ${address.address}:连接超时');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
final failure = last is SocketException
|
||||||
|
? classifySocket(last)
|
||||||
|
: const Outcome(
|
||||||
|
status: Outcome.timeout,
|
||||||
|
kind: Outcome.connect,
|
||||||
|
note: '连接超时',
|
||||||
|
);
|
||||||
|
final attempted = skipped.join(';');
|
||||||
|
return _TcpOpen.fail(
|
||||||
|
Outcome(
|
||||||
|
status: failure.status,
|
||||||
|
kind: failure.kind,
|
||||||
|
note: skipped.length > 1 ? '没有地址连通。$attempted' : failure.note,
|
||||||
|
detail: attempted.isEmpty
|
||||||
|
? const {}
|
||||||
|
: {'fallback': '已尝试 $attempted。没有地址连通,这次记为失败。'},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _TcpOpen {
|
||||||
|
const _TcpOpen.ok(
|
||||||
|
this.socket,
|
||||||
|
this.used,
|
||||||
|
this.watch,
|
||||||
|
this.fallback,
|
||||||
|
this.skipped,
|
||||||
|
) : failure = null;
|
||||||
|
|
||||||
|
const _TcpOpen.fail(this.failure)
|
||||||
|
: socket = null,
|
||||||
|
used = null,
|
||||||
|
watch = null,
|
||||||
|
fallback = '',
|
||||||
|
skipped = 0;
|
||||||
|
|
||||||
|
final Socket? socket;
|
||||||
|
final InternetAddress? used;
|
||||||
|
final Stopwatch? watch;
|
||||||
|
final Outcome? failure;
|
||||||
|
final String fallback;
|
||||||
|
final int skipped;
|
||||||
|
}
|
||||||
|
|
||||||
|
Outcome _withUsed(
|
||||||
|
Outcome outcome,
|
||||||
|
InternetAddress? used,
|
||||||
|
String fallback,
|
||||||
|
int skipped,
|
||||||
|
) {
|
||||||
|
if (used == null && fallback.isEmpty && skipped == 0) {
|
||||||
|
return outcome;
|
||||||
|
}
|
||||||
|
final detail = {...outcome.detail};
|
||||||
|
if (used != null) {
|
||||||
|
detail['address'] = used.address;
|
||||||
|
detail['family'] = addressFamily(used);
|
||||||
|
}
|
||||||
|
if (fallback.isNotEmpty) {
|
||||||
|
detail['fallback'] = fallback;
|
||||||
|
}
|
||||||
|
return Outcome(
|
||||||
|
status: outcome.status,
|
||||||
|
kind: outcome.kind,
|
||||||
|
rttMs: outcome.rttMs,
|
||||||
|
note: outcome.note,
|
||||||
|
reconnect: outcome.reconnect,
|
||||||
|
selectionSkipped: skipped,
|
||||||
|
detail: detail,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool _usesDatagram(String profileId) {
|
bool _usesDatagram(String profileId) {
|
||||||
@@ -572,7 +799,12 @@ Outcome _stampAddress(Outcome outcome, InternetAddress peer) {
|
|||||||
rttMs: outcome.rttMs,
|
rttMs: outcome.rttMs,
|
||||||
note: outcome.note,
|
note: outcome.note,
|
||||||
reconnect: outcome.reconnect,
|
reconnect: outcome.reconnect,
|
||||||
detail: {...outcome.detail, 'address': peer.address},
|
selectionSkipped: outcome.selectionSkipped,
|
||||||
|
detail: {
|
||||||
|
...outcome.detail,
|
||||||
|
'address': peer.address,
|
||||||
|
'family': addressFamily(peer),
|
||||||
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import 'dart:io';
|
|||||||
|
|
||||||
import '../metrics/sample_book.dart';
|
import '../metrics/sample_book.dart';
|
||||||
import '../models/session_config.dart';
|
import '../models/session_config.dart';
|
||||||
|
import '../ui/address_text.dart';
|
||||||
|
|
||||||
class RemoteProbe {
|
class RemoteProbe {
|
||||||
HttpClient? _client;
|
HttpClient? _client;
|
||||||
@@ -16,6 +17,7 @@ class RemoteProbe {
|
|||||||
required ProbeBody body,
|
required ProbeBody body,
|
||||||
required void Function(ProbeSample sample) onSample,
|
required void Function(ProbeSample sample) onSample,
|
||||||
required bool Function() cancelled,
|
required bool Function() cancelled,
|
||||||
|
void Function(List<ResolvedAddress> resolved)? onResolved,
|
||||||
}) async {
|
}) async {
|
||||||
final normalized = normalizeNodeUrl(baseUrl);
|
final normalized = normalizeNodeUrl(baseUrl);
|
||||||
if (normalized == null) {
|
if (normalized == null) {
|
||||||
@@ -52,6 +54,7 @@ class RemoteProbe {
|
|||||||
throw RemoteException('节点返回的任务无效');
|
throw RemoteException('节点返回的任务无效');
|
||||||
}
|
}
|
||||||
_jobId = parsed['jobId'] as String;
|
_jobId = parsed['jobId'] as String;
|
||||||
|
onResolved?.call(readResolvedList(parsed));
|
||||||
if (cancelled()) {
|
if (cancelled()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -86,7 +89,13 @@ class RemoteProbe {
|
|||||||
_jobId = null;
|
_jobId = null;
|
||||||
if (client != null && id != null && base != null) {
|
if (client != null && id != null && base != null) {
|
||||||
try {
|
try {
|
||||||
await _send(client, 'DELETE', base.resolve('/v1/jobs/$id'), nodeToken, const []);
|
await _send(
|
||||||
|
client,
|
||||||
|
'DELETE',
|
||||||
|
base.resolve('/v1/jobs/$id'),
|
||||||
|
nodeToken,
|
||||||
|
const [],
|
||||||
|
);
|
||||||
} on Object {
|
} on Object {
|
||||||
// The stream ending already asks the node to drop the job.
|
// The stream ending already asks the node to drop the job.
|
||||||
}
|
}
|
||||||
@@ -101,7 +110,9 @@ class RemoteProbe {
|
|||||||
void Function(ProbeSample sample) onSample,
|
void Function(ProbeSample sample) onSample,
|
||||||
bool Function() cancelled,
|
bool Function() cancelled,
|
||||||
) async {
|
) async {
|
||||||
final request = await client.getUrl(_base!.resolve('/v1/jobs/$_jobId/stream'));
|
final request = await client.getUrl(
|
||||||
|
_base!.resolve('/v1/jobs/$_jobId/stream'),
|
||||||
|
);
|
||||||
request.followRedirects = false;
|
request.followRedirects = false;
|
||||||
_auth(request, nodeToken);
|
_auth(request, nodeToken);
|
||||||
final response = await request.close().timeout(const Duration(seconds: 20));
|
final response = await request.close().timeout(const Duration(seconds: 20));
|
||||||
@@ -194,7 +205,9 @@ Future<NodeInfo> fetchNodeInfo(String baseUrl) async {
|
|||||||
}
|
}
|
||||||
final client = HttpClient();
|
final client = HttpClient();
|
||||||
try {
|
try {
|
||||||
final request = await client.getUrl(Uri.parse(normalized).resolve('/v1/info'));
|
final request = await client.getUrl(
|
||||||
|
Uri.parse(normalized).resolve('/v1/info'),
|
||||||
|
);
|
||||||
request.followRedirects = false;
|
request.followRedirects = false;
|
||||||
final response = await request.close().timeout(const Duration(seconds: 8));
|
final response = await request.close().timeout(const Duration(seconds: 8));
|
||||||
final body = await response.transform(utf8.decoder).join();
|
final body = await response.transform(utf8.decoder).join();
|
||||||
@@ -206,7 +219,9 @@ Future<NodeInfo> fetchNodeInfo(String baseUrl) async {
|
|||||||
throw RemoteException('节点信息无效');
|
throw RemoteException('节点信息无效');
|
||||||
}
|
}
|
||||||
return NodeInfo(
|
return NodeInfo(
|
||||||
visibility: json['visibility'] is String ? json['visibility'] as String : '',
|
visibility: json['visibility'] is String
|
||||||
|
? json['visibility'] as String
|
||||||
|
: '',
|
||||||
authRequired: json['authRequired'] == true,
|
authRequired: json['authRequired'] == true,
|
||||||
);
|
);
|
||||||
} on RemoteException {
|
} on RemoteException {
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
class ResolvedAddress {
|
||||||
|
const ResolvedAddress({required this.address, required this.family});
|
||||||
|
|
||||||
|
final String address;
|
||||||
|
final String family;
|
||||||
|
}
|
||||||
|
|
||||||
|
String addressFamily(InternetAddress address) {
|
||||||
|
return address.type == InternetAddressType.IPv6 ? 'IPv6' : 'IPv4';
|
||||||
|
}
|
||||||
|
|
||||||
|
String familyOfAddress(String address) {
|
||||||
|
final parsed = InternetAddress.tryParse(address);
|
||||||
|
if (parsed == null) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
return addressFamily(parsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
class AddressLines {
|
||||||
|
const AddressLines({
|
||||||
|
this.used,
|
||||||
|
this.trying,
|
||||||
|
this.resolved,
|
||||||
|
this.fallback,
|
||||||
|
this.unreported,
|
||||||
|
this.fake = false,
|
||||||
|
});
|
||||||
|
|
||||||
|
final String? used;
|
||||||
|
final String? trying;
|
||||||
|
final String? resolved;
|
||||||
|
final String? fallback;
|
||||||
|
final String? unreported;
|
||||||
|
final bool fake;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [used] is an address a probe actually connected to or sent to.
|
||||||
|
/// [resolved] is only the lookup result and is never labeled as the address
|
||||||
|
/// in use. A remote sample that omits the address stays unreported.
|
||||||
|
AddressLines describeAddress({
|
||||||
|
required List<ResolvedAddress> resolved,
|
||||||
|
String? usedAddress,
|
||||||
|
String? usedFamily,
|
||||||
|
String? tryingAddress,
|
||||||
|
String? tryingFamily,
|
||||||
|
String fallbackText = '',
|
||||||
|
bool addressUnreported = false,
|
||||||
|
bool usedIsFake = false,
|
||||||
|
}) {
|
||||||
|
final hasUsed = usedAddress != null && usedAddress.isNotEmpty;
|
||||||
|
String? used;
|
||||||
|
if (hasUsed) {
|
||||||
|
final family = (usedFamily == null || usedFamily.isEmpty)
|
||||||
|
? familyOfAddress(usedAddress)
|
||||||
|
: usedFamily;
|
||||||
|
used = family.isEmpty ? '实际地址 $usedAddress' : '实际地址 $usedAddress($family)';
|
||||||
|
}
|
||||||
|
String? trying;
|
||||||
|
if (!hasUsed && tryingAddress != null && tryingAddress.isNotEmpty) {
|
||||||
|
final family = (tryingFamily == null || tryingFamily.isEmpty)
|
||||||
|
? ''
|
||||||
|
: '($tryingFamily)';
|
||||||
|
trying = '正在尝试 $tryingAddress$family,还没有正式结果';
|
||||||
|
}
|
||||||
|
String? resolvedLine;
|
||||||
|
if (resolved.isNotEmpty) {
|
||||||
|
final sameSingle =
|
||||||
|
resolved.length == 1 &&
|
||||||
|
hasUsed &&
|
||||||
|
resolved.single.address == usedAddress;
|
||||||
|
if (!sameSingle) {
|
||||||
|
final text = resolved
|
||||||
|
.map((item) {
|
||||||
|
final family = item.family.isEmpty ? '' : '(${item.family})';
|
||||||
|
return '${item.address}$family';
|
||||||
|
})
|
||||||
|
.join('、');
|
||||||
|
resolvedLine = '解析到 $text';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return AddressLines(
|
||||||
|
used: used,
|
||||||
|
trying: trying,
|
||||||
|
resolved: resolvedLine,
|
||||||
|
fallback: fallbackText.isEmpty ? null : fallbackText,
|
||||||
|
unreported: addressUnreported && !hasUsed ? '节点没有报告实际使用的地址' : null,
|
||||||
|
fake: usedIsFake && hasUsed,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<ResolvedAddress> readResolvedList(Object? parsed) {
|
||||||
|
if (parsed is! Map) {
|
||||||
|
return const [];
|
||||||
|
}
|
||||||
|
final raw = parsed['resolved'];
|
||||||
|
if (raw is! List) {
|
||||||
|
return const [];
|
||||||
|
}
|
||||||
|
final out = <ResolvedAddress>[];
|
||||||
|
for (final item in raw) {
|
||||||
|
if (item is! Map) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final address = item['address'];
|
||||||
|
if (address is! String || address.isEmpty) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
final family = item['family'];
|
||||||
|
out.add(
|
||||||
|
ResolvedAddress(
|
||||||
|
address: address,
|
||||||
|
family: family is String && family.isNotEmpty
|
||||||
|
? family
|
||||||
|
: familyOfAddress(address),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
const chartPinEpsilon = 0.0001;
|
||||||
|
|
||||||
|
class ChartSelection {
|
||||||
|
const ChartSelection({required this.sec, required this.sessionId});
|
||||||
|
|
||||||
|
final double sec;
|
||||||
|
final int sessionId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A tap chooses the nearest sample and keeps it after the pointer is
|
||||||
|
/// released. A new session, an empty series, or a point that has scrolled
|
||||||
|
/// off the front of the window clears the pin instead of jumping to another
|
||||||
|
/// sample. [tappedSec] null means "keep the current pin if it is still valid".
|
||||||
|
ChartSelection? nextChartSelection({
|
||||||
|
required ChartSelection? current,
|
||||||
|
required int sessionId,
|
||||||
|
required List<double> sampleSecs,
|
||||||
|
double? tappedSec,
|
||||||
|
}) {
|
||||||
|
if (tappedSec != null) {
|
||||||
|
double? nearest;
|
||||||
|
var best = double.infinity;
|
||||||
|
for (final sec in sampleSecs) {
|
||||||
|
final distance = (sec - tappedSec).abs();
|
||||||
|
if (distance < best) {
|
||||||
|
best = distance;
|
||||||
|
nearest = sec;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (nearest == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return ChartSelection(sec: nearest, sessionId: sessionId);
|
||||||
|
}
|
||||||
|
if (current == null || current.sessionId != sessionId || sampleSecs.isEmpty) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (current.sec + chartPinEpsilon < sampleSecs.first) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
for (final sec in sampleSecs) {
|
||||||
|
if ((sec - current.sec).abs() <= chartPinEpsilon) {
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../content/release_history.dart';
|
||||||
|
import '../version.dart';
|
||||||
|
import 'quality_charts.dart';
|
||||||
|
|
||||||
|
class HistoryPage extends StatelessWidget {
|
||||||
|
const HistoryPage({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final wide = MediaQuery.sizeOf(context).width >= 720;
|
||||||
|
return Scaffold(
|
||||||
|
appBar: AppBar(
|
||||||
|
title: const Text('更新历史'),
|
||||||
|
backgroundColor: const Color(0xFFF3F1EC),
|
||||||
|
),
|
||||||
|
body: SafeArea(
|
||||||
|
child: Align(
|
||||||
|
alignment: Alignment.topCenter,
|
||||||
|
child: ConstrainedBox(
|
||||||
|
constraints: const BoxConstraints(maxWidth: 760),
|
||||||
|
child: ListView(
|
||||||
|
padding: EdgeInsets.fromLTRB(
|
||||||
|
wide ? 24 : 12,
|
||||||
|
8,
|
||||||
|
wide ? 24 : 12,
|
||||||
|
28,
|
||||||
|
),
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
'当前版本 $appVersion(构建 $appBuild) · 署名 $appAttribution · $appLicense',
|
||||||
|
style: const TextStyle(
|
||||||
|
color: ink,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
const Text(
|
||||||
|
releaseHistoryNote,
|
||||||
|
style: TextStyle(color: muted, height: 1.4),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
for (final entry in releaseHistory) _entry(entry),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _entry(ReleaseEntry entry) {
|
||||||
|
return Card(
|
||||||
|
margin: const EdgeInsets.only(bottom: 12),
|
||||||
|
shape: RoundedRectangleBorder(
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
side: const BorderSide(color: line),
|
||||||
|
),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(14),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
entry.title,
|
||||||
|
style: const TextStyle(fontWeight: FontWeight.w700, color: ink),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 6),
|
||||||
|
Text(
|
||||||
|
entry.published == null
|
||||||
|
? entry.source
|
||||||
|
: '${entry.published} · ${entry.source}',
|
||||||
|
style: const TextStyle(color: muted, fontSize: 13, height: 1.4),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
for (final point in entry.points)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 6),
|
||||||
|
child: Text('· $point', style: const TextStyle(height: 1.4)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+269
-46
@@ -2,6 +2,8 @@ import 'dart:async';
|
|||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../models/node_edit.dart';
|
||||||
|
import '../models/port_field.dart';
|
||||||
import '../models/probe_profile.dart';
|
import '../models/probe_profile.dart';
|
||||||
import '../models/session_config.dart';
|
import '../models/session_config.dart';
|
||||||
import '../probe/endpoint_picker.dart';
|
import '../probe/endpoint_picker.dart';
|
||||||
@@ -9,7 +11,11 @@ import '../probe/probe_controller.dart';
|
|||||||
import '../probe/remote_client.dart';
|
import '../probe/remote_client.dart';
|
||||||
import '../storage/app_store.dart';
|
import '../storage/app_store.dart';
|
||||||
import '../storage/token_vault.dart';
|
import '../storage/token_vault.dart';
|
||||||
|
import 'address_text.dart';
|
||||||
import 'format.dart';
|
import 'format.dart';
|
||||||
|
import 'history_page.dart';
|
||||||
|
import 'metric_guide_page.dart';
|
||||||
|
import 'metrics_panel.dart';
|
||||||
import 'quality_charts.dart';
|
import 'quality_charts.dart';
|
||||||
|
|
||||||
class HomePage extends StatefulWidget {
|
class HomePage extends StatefulWidget {
|
||||||
@@ -134,7 +140,11 @@ class _HomePageState extends State<HomePage> {
|
|||||||
final nodeToken = config.node == null
|
final nodeToken = config.node == null
|
||||||
? ''
|
? ''
|
||||||
: (await _vault.read(nodeTokenKey(config.node!.id)) ?? '');
|
: (await _vault.read(nodeTokenKey(config.node!.id)) ?? '');
|
||||||
await _controller.start(config, nodeToken: nodeToken, echoToken: _echo.text);
|
await _controller.start(
|
||||||
|
config,
|
||||||
|
nodeToken: nodeToken,
|
||||||
|
echoToken: _echo.text,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
void _changeProfile(String? id) {
|
void _changeProfile(String? id) {
|
||||||
@@ -144,9 +154,11 @@ class _HomePageState extends State<HomePage> {
|
|||||||
final previous = ProbeProfile.byId(_profileId);
|
final previous = ProbeProfile.byId(_profileId);
|
||||||
final next = ProbeProfile.byId(id);
|
final next = ProbeProfile.byId(id);
|
||||||
setState(() {
|
setState(() {
|
||||||
if (_port.text.trim() == '${previous.port}') {
|
_port.text = portAfterProfileChange(
|
||||||
_port.text = '${next.port}';
|
current: _port.text,
|
||||||
}
|
previousDefault: previous.port,
|
||||||
|
nextDefault: next.port,
|
||||||
|
);
|
||||||
_profileId = id;
|
_profileId = id;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -160,6 +172,22 @@ class _HomePageState extends State<HomePage> {
|
|||||||
appBar: AppBar(
|
appBar: AppBar(
|
||||||
title: const Text('网络质量探测'),
|
title: const Text('网络质量探测'),
|
||||||
backgroundColor: const Color(0xFFF3F1EC),
|
backgroundColor: const Color(0xFFF3F1EC),
|
||||||
|
actions: [
|
||||||
|
PopupMenuButton<String>(
|
||||||
|
tooltip: '说明',
|
||||||
|
onSelected: (value) {
|
||||||
|
final page = value == 'history'
|
||||||
|
? const HistoryPage()
|
||||||
|
: const MetricGuidePage();
|
||||||
|
Navigator.of(context)
|
||||||
|
.push(MaterialPageRoute<void>(builder: (_) => page));
|
||||||
|
},
|
||||||
|
itemBuilder: (context) => const [
|
||||||
|
PopupMenuItem(value: 'metrics', child: Text('指标说明')),
|
||||||
|
PopupMenuItem(value: 'history', child: Text('更新历史')),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
body: SafeArea(
|
body: SafeArea(
|
||||||
child: Align(
|
child: Align(
|
||||||
@@ -167,12 +195,14 @@ class _HomePageState extends State<HomePage> {
|
|||||||
child: ConstrainedBox(
|
child: ConstrainedBox(
|
||||||
constraints: const BoxConstraints(maxWidth: 880),
|
constraints: const BoxConstraints(maxWidth: 880),
|
||||||
child: ListView(
|
child: ListView(
|
||||||
padding: EdgeInsets.fromLTRB(wide ? 24 : 12, 8, wide ? 24 : 12, 28),
|
padding: EdgeInsets.fromLTRB(
|
||||||
|
wide ? 24 : 12,
|
||||||
|
8,
|
||||||
|
wide ? 24 : 12,
|
||||||
|
28,
|
||||||
|
),
|
||||||
children: [
|
children: [
|
||||||
_card(
|
_card(title: '探测来源', child: _source(view, wide)),
|
||||||
title: '探测来源',
|
|
||||||
child: _source(view, wide),
|
|
||||||
),
|
|
||||||
_card(
|
_card(
|
||||||
title: '目标',
|
title: '目标',
|
||||||
child: Column(
|
child: Column(
|
||||||
@@ -181,7 +211,13 @@ class _HomePageState extends State<HomePage> {
|
|||||||
_pair(
|
_pair(
|
||||||
wide,
|
wide,
|
||||||
_field(_host, '目标地址', '域名或 IP'),
|
_field(_host, '目标地址', '域名或 IP'),
|
||||||
_field(_port, '端口', '1–65535'),
|
_field(
|
||||||
|
_port,
|
||||||
|
'端口',
|
||||||
|
portHint(profile),
|
||||||
|
fieldKey: const Key('port-field'),
|
||||||
|
helper: portHelperText,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
DropdownButtonFormField<String>(
|
DropdownButtonFormField<String>(
|
||||||
@@ -190,12 +226,18 @@ class _HomePageState extends State<HomePage> {
|
|||||||
decoration: const InputDecoration(labelText: '探测类型'),
|
decoration: const InputDecoration(labelText: '探测类型'),
|
||||||
items: [
|
items: [
|
||||||
for (final item in ProbeProfile.all)
|
for (final item in ProbeProfile.all)
|
||||||
DropdownMenuItem(value: item.id, child: Text(item.label)),
|
DropdownMenuItem(
|
||||||
|
value: item.id,
|
||||||
|
child: Text(item.label),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
onChanged: view.running ? null : _changeProfile,
|
onChanged: view.running ? null : _changeProfile,
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
Text(profile.blurb, style: const TextStyle(color: muted, fontSize: 13)),
|
Text(
|
||||||
|
profile.blurb,
|
||||||
|
style: const TextStyle(color: muted, fontSize: 13),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -206,7 +248,11 @@ class _HomePageState extends State<HomePage> {
|
|||||||
children: [
|
children: [
|
||||||
_pair(
|
_pair(
|
||||||
wide,
|
wide,
|
||||||
_field(_interval, '间隔(毫秒)', _remote ? '至少 200' : '至少 100'),
|
_field(
|
||||||
|
_interval,
|
||||||
|
'间隔(毫秒)',
|
||||||
|
_remote ? '至少 200' : '至少 100',
|
||||||
|
),
|
||||||
_field(_timeout, '超时(毫秒)', '100–15000'),
|
_field(_timeout, '超时(毫秒)', '100–15000'),
|
||||||
),
|
),
|
||||||
if (profile.needsPacketSize) ...[
|
if (profile.needsPacketSize) ...[
|
||||||
@@ -252,11 +298,44 @@ class _HomePageState extends State<HomePage> {
|
|||||||
_banner(view.banner!),
|
_banner(view.banner!),
|
||||||
],
|
],
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
_card(title: '结果', child: _result(view)),
|
_card(
|
||||||
|
title: '结果',
|
||||||
|
child: _result(
|
||||||
|
view,
|
||||||
|
view.profileId.isEmpty ? profile.id : view.profileId,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (view.report != null)
|
||||||
|
SessionSummaryCard(
|
||||||
|
report: view.report!,
|
||||||
|
profileId: view.report!.profileId,
|
||||||
|
),
|
||||||
QualityCharts(
|
QualityCharts(
|
||||||
samples: view.samples,
|
samples: view.samples,
|
||||||
rateLabel: view.rateLabel,
|
rateLabel: view.rateLabel,
|
||||||
running: view.running,
|
running: view.running,
|
||||||
|
sessionId: view.sessionId,
|
||||||
|
),
|
||||||
|
Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
children: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.of(context).push(
|
||||||
|
MaterialPageRoute<void>(
|
||||||
|
builder: (_) => const MetricGuidePage(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: const Text('指标说明'),
|
||||||
|
),
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.of(context).push(
|
||||||
|
MaterialPageRoute<void>(
|
||||||
|
builder: (_) => const HistoryPage(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: const Text('更新历史'),
|
||||||
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
const Text(
|
const Text(
|
||||||
'延迟用发包一侧的单调时钟计算。远程探测时,这个时间在节点上量好再传回来,不包含手机到节点的控制通道耗时。TCP 超时不是物理丢包。没有协议应答的 UDP 记为无应答/未知,不会在探测完成前显示 100%。',
|
'延迟用发包一侧的单调时钟计算。远程探测时,这个时间在节点上量好再传回来,不包含手机到节点的控制通道耗时。TCP 超时不是物理丢包。没有协议应答的 UDP 记为无应答/未知,不会在探测完成前显示 100%。',
|
||||||
@@ -271,17 +350,25 @@ class _HomePageState extends State<HomePage> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Widget _source(ProbeView view, bool wide) {
|
Widget _source(ProbeView view, bool wide) {
|
||||||
final selected = _nodes.cast<RemoteNode?>().followedBy(const [null]).firstWhere(
|
final selected = _nodes
|
||||||
(node) => node?.id == _nodeId,
|
.cast<RemoteNode?>()
|
||||||
orElse: () => null,
|
.followedBy(const [null])
|
||||||
);
|
.firstWhere((node) => node?.id == _nodeId, orElse: () => null);
|
||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
SegmentedButton<bool>(
|
SegmentedButton<bool>(
|
||||||
segments: const [
|
segments: const [
|
||||||
ButtonSegment(value: false, label: Text('本机'), icon: Icon(Icons.phone_android)),
|
ButtonSegment(
|
||||||
ButtonSegment(value: true, label: Text('远程节点'), icon: Icon(Icons.dns_outlined)),
|
value: false,
|
||||||
|
label: Text('本机'),
|
||||||
|
icon: Icon(Icons.phone_android),
|
||||||
|
),
|
||||||
|
ButtonSegment(
|
||||||
|
value: true,
|
||||||
|
label: Text('远程节点'),
|
||||||
|
icon: Icon(Icons.dns_outlined),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
selected: {_remote},
|
selected: {_remote},
|
||||||
onSelectionChanged: view.running
|
onSelectionChanged: view.running
|
||||||
@@ -290,9 +377,7 @@ class _HomePageState extends State<HomePage> {
|
|||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
Text(
|
Text(
|
||||||
_remote
|
_remote ? '由选中的节点向目标发包,这台设备只负责控制和显示。' : '由这台设备直接向目标发包。可以探测本机上的反射器。',
|
||||||
? '由选中的节点向目标发包,这台设备只负责控制和显示。'
|
|
||||||
: '由这台设备直接向目标发包。可以探测本机上的反射器。',
|
|
||||||
style: const TextStyle(color: muted, fontSize: 13),
|
style: const TextStyle(color: muted, fontSize: 13),
|
||||||
),
|
),
|
||||||
if (_remote) ...[
|
if (_remote) ...[
|
||||||
@@ -338,13 +423,18 @@ class _HomePageState extends State<HomePage> {
|
|||||||
return '${node.name} · $vis';
|
return '${node.name} · $vis';
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _result(ProbeView view) {
|
Widget _result(ProbeView view, String profileId) {
|
||||||
final summary = view.summary;
|
final summary = view.summary;
|
||||||
final rate = view.rateLabel == '探测无应答'
|
final address = describeAddress(
|
||||||
? summary.probeLossPct
|
resolved: view.resolved,
|
||||||
: view.rateLabel == '失败率'
|
usedAddress: view.usedAddress,
|
||||||
? summary.failurePct
|
usedFamily: view.usedFamily,
|
||||||
: summary.unknownPct;
|
tryingAddress: view.tryingAddress,
|
||||||
|
tryingFamily: view.tryingFamily,
|
||||||
|
fallbackText: view.fallbackText,
|
||||||
|
addressUnreported: view.addressUnreported,
|
||||||
|
usedIsFake: view.usedIsFake,
|
||||||
|
);
|
||||||
final motd = view.detail['motd'];
|
final motd = view.detail['motd'];
|
||||||
final version = view.detail['version'];
|
final version = view.detail['version'];
|
||||||
final players = view.detail['players'];
|
final players = view.detail['players'];
|
||||||
@@ -357,13 +447,42 @@ class _HomePageState extends State<HomePage> {
|
|||||||
children: [
|
children: [
|
||||||
_chip(view.phase),
|
_chip(view.phase),
|
||||||
_chip('来源 ${view.sourceLabel}'),
|
_chip('来源 ${view.sourceLabel}'),
|
||||||
if (view.targetAddress != null) _chip('发往 ${view.targetAddress}'),
|
if (view.targetHost.isNotEmpty) _chip(view.targetHost),
|
||||||
_chip('延迟 ${formatMs(summary.rttMs)}'),
|
|
||||||
_chip('抖动 ${formatMs(summary.jitterMs)}'),
|
|
||||||
_chip('${view.rateLabel} ${formatPct(rate)}'),
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
if (view.targetIsFake) ...[
|
const SizedBox(height: 8),
|
||||||
|
MetricsPanel(
|
||||||
|
summary: summary,
|
||||||
|
profileId: profileId,
|
||||||
|
elapsed: view.elapsed,
|
||||||
|
),
|
||||||
|
if (address.trying != null) ...[
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Text(address.trying!, style: const TextStyle(color: ink)),
|
||||||
|
],
|
||||||
|
if (address.used != null) ...[
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Text(address.used!, style: const TextStyle(color: ink)),
|
||||||
|
],
|
||||||
|
if (address.resolved != null) ...[
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Text(
|
||||||
|
address.resolved!,
|
||||||
|
style: const TextStyle(color: muted, fontSize: 13),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
if (address.unreported != null) ...[
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Text(
|
||||||
|
address.unreported!,
|
||||||
|
style: const TextStyle(color: Color(0xFF9A3412)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
if (address.fallback != null) ...[
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Text(address.fallback!, style: const TextStyle(color: ink)),
|
||||||
|
],
|
||||||
|
if (address.fake) ...[
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
const Text(
|
const Text(
|
||||||
clashFakeIpNote,
|
clashFakeIpNote,
|
||||||
@@ -386,7 +505,10 @@ class _HomePageState extends State<HomePage> {
|
|||||||
),
|
),
|
||||||
],
|
],
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
Text(summaryLine(summary), style: const TextStyle(color: muted, fontSize: 13)),
|
Text(
|
||||||
|
summaryLine(summary),
|
||||||
|
style: const TextStyle(color: muted, fontSize: 13),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -434,6 +556,7 @@ class _NodeDialogState extends State<_NodeDialog> {
|
|||||||
final _name = TextEditingController();
|
final _name = TextEditingController();
|
||||||
final _url = TextEditingController();
|
final _url = TextEditingController();
|
||||||
final _token = TextEditingController();
|
final _token = TextEditingController();
|
||||||
|
String? _editingId;
|
||||||
String? _hint;
|
String? _hint;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -450,6 +573,41 @@ class _NodeDialogState extends State<_NodeDialog> {
|
|||||||
setState(() => _hint = '请填写名称,以及不带口令的 http 或 https 地址');
|
setState(() => _hint = '请填写名称,以及不带口令的 http 或 https 地址');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
final editing = _editingId;
|
||||||
|
if (editing != null) {
|
||||||
|
RemoteNode? previous;
|
||||||
|
for (final node in _nodes) {
|
||||||
|
if (node.id == editing) {
|
||||||
|
previous = node;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (previous == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final next = applyNodeEdit(
|
||||||
|
previous,
|
||||||
|
name: _name.text.trim(),
|
||||||
|
baseUrl: url,
|
||||||
|
);
|
||||||
|
final replaced = await saveEditedNodeToken(
|
||||||
|
widget.vault,
|
||||||
|
editing,
|
||||||
|
_token.text,
|
||||||
|
);
|
||||||
|
setState(() {
|
||||||
|
_nodes = [
|
||||||
|
for (final node in _nodes)
|
||||||
|
if (node.id == editing) next else node,
|
||||||
|
];
|
||||||
|
_editingId = null;
|
||||||
|
_hint = replaced ? '已更新,口令已替换,仍只留在本机。' : '已更新。口令留空,原来的口令未改。';
|
||||||
|
_name.clear();
|
||||||
|
_url.clear();
|
||||||
|
_token.clear();
|
||||||
|
});
|
||||||
|
widget.onChanged(_nodes, editing);
|
||||||
|
return;
|
||||||
|
}
|
||||||
final id = DateTime.now().microsecondsSinceEpoch.toString();
|
final id = DateTime.now().microsecondsSinceEpoch.toString();
|
||||||
final node = RemoteNode(id: id, name: _name.text.trim(), baseUrl: url);
|
final node = RemoteNode(id: id, name: _name.text.trim(), baseUrl: url);
|
||||||
await widget.vault.write(nodeTokenKey(id), _token.text.trim());
|
await widget.vault.write(nodeTokenKey(id), _token.text.trim());
|
||||||
@@ -463,6 +621,26 @@ class _NodeDialogState extends State<_NodeDialog> {
|
|||||||
widget.onChanged(_nodes, id);
|
widget.onChanged(_nodes, id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void _beginEdit(RemoteNode node) {
|
||||||
|
setState(() {
|
||||||
|
_editingId = node.id;
|
||||||
|
_name.text = node.name;
|
||||||
|
_url.text = node.baseUrl;
|
||||||
|
_token.clear();
|
||||||
|
_hint = '正在修改「${node.name}」。口令留空则保留已保存的口令,不会显示原口令。';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void _cancelEdit() {
|
||||||
|
setState(() {
|
||||||
|
_editingId = null;
|
||||||
|
_name.clear();
|
||||||
|
_url.clear();
|
||||||
|
_token.clear();
|
||||||
|
_hint = null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> _check(RemoteNode node) async {
|
Future<void> _check(RemoteNode node) async {
|
||||||
try {
|
try {
|
||||||
final info = await fetchNodeInfo(node.baseUrl);
|
final info = await fetchNodeInfo(node.baseUrl);
|
||||||
@@ -487,7 +665,10 @@ class _NodeDialogState extends State<_NodeDialog> {
|
|||||||
|
|
||||||
Future<void> _delete(RemoteNode node) async {
|
Future<void> _delete(RemoteNode node) async {
|
||||||
await widget.vault.delete(nodeTokenKey(node.id));
|
await widget.vault.delete(nodeTokenKey(node.id));
|
||||||
final next = [for (final item in _nodes) if (item.id != node.id) item];
|
final next = [
|
||||||
|
for (final item in _nodes)
|
||||||
|
if (item.id != node.id) item,
|
||||||
|
];
|
||||||
setState(() => _nodes = next);
|
setState(() => _nodes = next);
|
||||||
widget.onChanged(next, null);
|
widget.onChanged(next, null);
|
||||||
}
|
}
|
||||||
@@ -510,22 +691,41 @@ class _NodeDialogState extends State<_NodeDialog> {
|
|||||||
for (final node in _nodes)
|
for (final node in _nodes)
|
||||||
ListTile(
|
ListTile(
|
||||||
contentPadding: EdgeInsets.zero,
|
contentPadding: EdgeInsets.zero,
|
||||||
title: Text(_nodes.isEmpty ? '' : '${node.name} · ${visibilityLabel(node.visibility)}'),
|
title: Text(
|
||||||
subtitle: Text(node.baseUrl, maxLines: 1, overflow: TextOverflow.ellipsis),
|
'${node.name} · ${visibilityLabel(node.visibility)}',
|
||||||
|
),
|
||||||
|
subtitle: Text(
|
||||||
|
node.baseUrl,
|
||||||
|
maxLines: 1,
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
),
|
||||||
trailing: Wrap(
|
trailing: Wrap(
|
||||||
spacing: 4,
|
spacing: 4,
|
||||||
children: [
|
children: [
|
||||||
TextButton(onPressed: () => _check(node), child: const Text('检查')),
|
TextButton(
|
||||||
TextButton(onPressed: () => _delete(node), child: const Text('删除')),
|
key: Key('edit-node-${node.id}'),
|
||||||
|
onPressed: () => _beginEdit(node),
|
||||||
|
child: const Text('编辑'),
|
||||||
|
),
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => _check(node),
|
||||||
|
child: const Text('检查'),
|
||||||
|
),
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => _delete(node),
|
||||||
|
child: const Text('删除'),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
TextField(
|
TextField(
|
||||||
|
key: const Key('node-name'),
|
||||||
controller: _name,
|
controller: _name,
|
||||||
decoration: const InputDecoration(labelText: '名称'),
|
decoration: const InputDecoration(labelText: '名称'),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
TextField(
|
TextField(
|
||||||
|
key: const Key('node-url'),
|
||||||
controller: _url,
|
controller: _url,
|
||||||
decoration: const InputDecoration(
|
decoration: const InputDecoration(
|
||||||
labelText: '节点地址',
|
labelText: '节点地址',
|
||||||
@@ -534,10 +734,14 @@ class _NodeDialogState extends State<_NodeDialog> {
|
|||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
TextField(
|
TextField(
|
||||||
|
key: const Key('node-token'),
|
||||||
controller: _token,
|
controller: _token,
|
||||||
obscureText: true,
|
obscureText: true,
|
||||||
decoration: const InputDecoration(
|
decoration: InputDecoration(
|
||||||
labelText: '节点口令(公开节点留空)',
|
labelText: _editingId == null ? '节点口令(公开节点留空)' : '新口令(留空则保留)',
|
||||||
|
helperText: _editingId == null
|
||||||
|
? null
|
||||||
|
: '留空则保留已保存的口令,不会显示原口令。',
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
if (_hint != null) ...[
|
if (_hint != null) ...[
|
||||||
@@ -549,8 +753,17 @@ class _NodeDialogState extends State<_NodeDialog> {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
actions: [
|
actions: [
|
||||||
TextButton(onPressed: _save, child: const Text('添加节点')),
|
if (_editingId != null)
|
||||||
TextButton(onPressed: () => Navigator.pop(context), child: const Text('完成')),
|
TextButton(onPressed: _cancelEdit, child: const Text('取消编辑')),
|
||||||
|
TextButton(
|
||||||
|
key: const Key('node-save'),
|
||||||
|
onPressed: _save,
|
||||||
|
child: Text(_editingId == null ? '添加节点' : '保存修改'),
|
||||||
|
),
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.pop(context),
|
||||||
|
child: const Text('完成'),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -568,7 +781,10 @@ Widget _card({required String title, required Widget child}) {
|
|||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
Text(title, style: const TextStyle(fontWeight: FontWeight.w700, color: ink)),
|
Text(
|
||||||
|
title,
|
||||||
|
style: const TextStyle(fontWeight: FontWeight.w700, color: ink),
|
||||||
|
),
|
||||||
const SizedBox(height: 10),
|
const SizedBox(height: 10),
|
||||||
child,
|
child,
|
||||||
],
|
],
|
||||||
@@ -582,11 +798,18 @@ Widget _field(
|
|||||||
String label,
|
String label,
|
||||||
String hint, {
|
String hint, {
|
||||||
bool secret = false,
|
bool secret = false,
|
||||||
|
Key? fieldKey,
|
||||||
|
String? helper,
|
||||||
}) {
|
}) {
|
||||||
return TextField(
|
return TextField(
|
||||||
|
key: fieldKey,
|
||||||
controller: controller,
|
controller: controller,
|
||||||
obscureText: secret,
|
obscureText: secret,
|
||||||
decoration: InputDecoration(labelText: label, hintText: hint),
|
decoration: InputDecoration(
|
||||||
|
labelText: label,
|
||||||
|
hintText: hint,
|
||||||
|
helperText: helper,
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import 'quality_charts.dart';
|
||||||
|
|
||||||
|
class MetricGuidePage extends StatelessWidget {
|
||||||
|
const MetricGuidePage({super.key});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final wide = MediaQuery.sizeOf(context).width >= 720;
|
||||||
|
return Scaffold(
|
||||||
|
appBar: AppBar(
|
||||||
|
title: const Text('指标说明'),
|
||||||
|
backgroundColor: const Color(0xFFF3F1EC),
|
||||||
|
),
|
||||||
|
body: SafeArea(
|
||||||
|
child: Align(
|
||||||
|
alignment: Alignment.topCenter,
|
||||||
|
child: ConstrainedBox(
|
||||||
|
constraints: const BoxConstraints(maxWidth: 760),
|
||||||
|
child: ListView(
|
||||||
|
padding: EdgeInsets.fromLTRB(
|
||||||
|
wide ? 24 : 12,
|
||||||
|
8,
|
||||||
|
wide ? 24 : 12,
|
||||||
|
28,
|
||||||
|
),
|
||||||
|
children: const [
|
||||||
|
_Section(
|
||||||
|
title: '这些数字从哪来',
|
||||||
|
body: '曲线和百分比只来自已经完成、并且计入正式结果的探测。还在途中的请求不会画成 100%,停止时被取消的请求也不算丢包。没有内置样本。',
|
||||||
|
),
|
||||||
|
_Section(
|
||||||
|
title: '已发送、已收到、超时',
|
||||||
|
body: '已发送是计入正式结果的次数。已收到是其中成功的次数:合作反射收到了对上序号的回显,普通 TCP 是连上了,其他类型是收到了符合协议的应答。\n\n合作反射的「超时」只计已经把探测帧写出去、但超时前没有对上序号的次数。还没连上、连接被拒绝,不算进这个超时,也不算进探测无应答。\n\n普通 UDP、DNS、自定义 UDP 和基岩版如果根本没有协议应答,记为「无应答」,超时这一项显示不适用。收到了包但内容不对,记为协议错误。UDP 沉默不能当成已经证实的丢包:对端可以合法地不回答。',
|
||||||
|
),
|
||||||
|
_Section(
|
||||||
|
title: '探测无应答、失败率、无应答',
|
||||||
|
body: '合作反射 TCP / UDP:探测无应答 = 超时 ÷(超时 + 成功)× 100%。分母只含已经写出的回显尝试。分母为 0 时显示 —,而不是 0%。TCP 会重传,所以这不是网卡上的物理丢包。\n\n普通 TCP 和 Minecraft Java:失败率 = 未成功的正式尝试 ÷ 已完成的正式尝试 × 100%。这里没有丢包百分比。\n\n其余 UDP 类探测:无应答 = 无应答次数 ÷ 已完成次数 × 100%。它回答的是「没有看到协议应答」,不是「丢了多少包」。',
|
||||||
|
),
|
||||||
|
_Section(
|
||||||
|
title: '延迟、中位数、P95 和抖动',
|
||||||
|
body: '延迟只来自成功的样本,单位是毫秒。当前延迟是最近一次成功的往返时间。最小、平均、最大都是这些成功样本的最小、算术平均和最大。\n\n中位数:把成功样本从小到大排列。奇数个取中间那个;偶数个取中间两个的平均。\n\nP95 用最近秩:秩 = ceil(0.95 × 次数),用整数 (95 × 次数 + 99) / 100 计算,从 1 开始,取排序后这个位置的值。次数为 1 时,P95 就是那一次。\n\n抖动按 RFC 3550:D 是相邻两次成功往返时间之差,J = J + (|D| − J) / 16。第一次成功时 J 为 0;没有成功时显示 —。远程探测的往返时间在节点上用单调时钟量好再传回来,不包含手机到节点的控制通道耗时。\n\n旧版本节点不会上报最小、平均、中位、P95 和最大。这时这些格子显示「节点未提供」,当前延迟和抖动仍用它原来上报的值。',
|
||||||
|
),
|
||||||
|
_Section(
|
||||||
|
title: '用时',
|
||||||
|
body: '用时是这次会话从按下开始到停止(或到当前)的墙钟时间。它不是各次往返时间相加,也不包括节点在创建任务之前花掉的时间。',
|
||||||
|
),
|
||||||
|
_Section(
|
||||||
|
title: '选址失败和正式丢包',
|
||||||
|
body: '一个域名可能同时有 IPv6 和 IPv4。程序会先试一个地址。还没有任何地址应答时,连不上或没有应答会换下一个。这种只为挑选地址而失败的尝试,如果后面有地址成功,就不计入已发送、超时和丢包,界面单独写明回退了哪个地址。\n\n一旦某个地址已经应答,之后对它的超时或失败都算正式结果,不会因为后来又换地址而被抹掉。只有一个地址时,失败从一开始就算正式结果。\n\n如果每一个候选都失败,这些失败会计入正式结果。界面显示失败或 100% 的无应答/失败率,不会显示 0% 成功。\n\n1.1.1 的远程节点还不会做这层区分,它的统计可能仍把第一次选址失败算进去。要分开看,节点也需要 1.1.2。',
|
||||||
|
),
|
||||||
|
_Section(
|
||||||
|
title: '实际地址和 IPv6 回退',
|
||||||
|
body: '「实际地址」是这次真正连通或真正发包的 IP,并注明 IPv4 或 IPv6。「解析到」只是域名解析的结果,不会被说成已经在用的地址。\n\n正在尝试、还没有正式结果时,会标明正在尝试,而不是写成已经发往。远程节点如果没有在结果里带上地址(旧版本就是这样),界面写「节点没有报告实际使用的地址」,不会在手机上另做一次解析来冒充。\n\n地址落在 198.18.0.0/15 时,会提示这是 VPN 假地址,只有这个 VPN 开着时才能用。',
|
||||||
|
),
|
||||||
|
_Section(
|
||||||
|
title: '停止以后',
|
||||||
|
body: '点停止会保留曲线,并给出开始、结束、用时、目标、类型、来源、实际地址和同一套最终指标。正在进行、因为停止而被取消的请求不计入丢包。重新开始会换一次新的会话,旧曲线不会混进来。\n\n点曲线上的一点可以钉住该时刻的延迟和比率,松手后仍然留着。再点另一点会换。新会话或这个点滚出窗口后,选择会被清掉,不会跳到别的点上。',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _Section extends StatelessWidget {
|
||||||
|
const _Section({required this.title, required this.body});
|
||||||
|
|
||||||
|
final String title;
|
||||||
|
final String body;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Card(
|
||||||
|
margin: const EdgeInsets.only(bottom: 12),
|
||||||
|
shape: RoundedRectangleBorder(
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
side: const BorderSide(color: line),
|
||||||
|
),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(14),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
title,
|
||||||
|
style: const TextStyle(fontWeight: FontWeight.w700, color: ink),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Text(body, style: const TextStyle(height: 1.45, color: ink)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,271 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../metrics/sample_book.dart';
|
||||||
|
import '../probe/endpoint_picker.dart';
|
||||||
|
import '../probe/probe_controller.dart';
|
||||||
|
import 'address_text.dart';
|
||||||
|
import 'format.dart';
|
||||||
|
import 'quality_charts.dart';
|
||||||
|
|
||||||
|
class MetricLine {
|
||||||
|
const MetricLine(this.label, this.value, {this.detail});
|
||||||
|
|
||||||
|
final String label;
|
||||||
|
final String value;
|
||||||
|
final String? detail;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rows use the same summary the live view and the stopped session share.
|
||||||
|
/// A metric that this profile does not measure is marked unsupported instead
|
||||||
|
/// of being shown as zero.
|
||||||
|
List<MetricLine> metricLines({
|
||||||
|
required ProbeSummary summary,
|
||||||
|
required String profileId,
|
||||||
|
required Duration elapsed,
|
||||||
|
}) {
|
||||||
|
final lines = <MetricLine>[
|
||||||
|
MetricLine(
|
||||||
|
'已发送',
|
||||||
|
'${summary.sent}',
|
||||||
|
detail: summary.selectionSkipped > 0
|
||||||
|
? '正式结果 ${summary.sent} 次。另有 ${summary.selectionSkipped} 次选址失败未计入。'
|
||||||
|
: '只计已经计入正式结果的次数,不含还在途中的探测。',
|
||||||
|
),
|
||||||
|
MetricLine('已收到', '${summary.ok}', detail: '成功收到应答,或成功连通的次数。'),
|
||||||
|
_timeoutLine(summary, profileId),
|
||||||
|
_rateLine(summary, profileId),
|
||||||
|
_latency('当前延迟', summary.rttMs, summary, recent: true),
|
||||||
|
_latency('最小延迟', summary.minRttMs, summary),
|
||||||
|
_latency('平均延迟', summary.meanRttMs, summary),
|
||||||
|
_latency('中位延迟', summary.medianRttMs, summary),
|
||||||
|
_latency('P95 延迟', summary.p95RttMs, summary),
|
||||||
|
_latency('最大延迟', summary.maxRttMs, summary),
|
||||||
|
MetricLine(
|
||||||
|
'抖动',
|
||||||
|
summary.jitterMs == null ? '—' : formatMs(summary.jitterMs),
|
||||||
|
detail: 'RFC 3550:J = J + (|D| − J) / 16。D 是相邻两次成功往返时间之差。只有一次成功时 J 为 0。',
|
||||||
|
),
|
||||||
|
MetricLine(
|
||||||
|
'用时',
|
||||||
|
formatDuration(elapsed),
|
||||||
|
detail: '从这次探测开始到现在或到停止的墙钟时间,不是往返时间相加。',
|
||||||
|
),
|
||||||
|
];
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
MetricLine _timeoutLine(ProbeSummary summary, String profileId) {
|
||||||
|
switch (profileId) {
|
||||||
|
case 'nq-tcp':
|
||||||
|
case 'nq-udp':
|
||||||
|
return MetricLine(
|
||||||
|
'超时',
|
||||||
|
'${summary.timeout}',
|
||||||
|
detail: '已经写出回显帧、在超时前没有对上序号的次数。连接失败另计,不在这里。',
|
||||||
|
);
|
||||||
|
case 'tcp-connect':
|
||||||
|
case 'minecraft-java':
|
||||||
|
return const MetricLine('超时', '不适用', detail: '这种探测把连不上记为失败,不单独叫探测超时。');
|
||||||
|
default:
|
||||||
|
return MetricLine(
|
||||||
|
'超时',
|
||||||
|
'不适用',
|
||||||
|
detail: '没有协议应答时记为无应答 ${summary.unknown} 次,不能据此断定丢包。',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
MetricLine _rateLine(ProbeSummary summary, String profileId) {
|
||||||
|
switch (profileId) {
|
||||||
|
case 'nq-tcp':
|
||||||
|
case 'nq-udp':
|
||||||
|
final denom = summary.timeout + summary.ok;
|
||||||
|
return MetricLine(
|
||||||
|
'探测无应答',
|
||||||
|
formatPct(summary.probeLossPct),
|
||||||
|
detail: denom == 0
|
||||||
|
? '还没有完成的回显尝试,所以不显示 0%。'
|
||||||
|
: '超时 ÷(超时 + 成功)= ${summary.timeout} ÷ $denom。连接失败不在分母里。',
|
||||||
|
);
|
||||||
|
case 'tcp-connect':
|
||||||
|
case 'minecraft-java':
|
||||||
|
return MetricLine(
|
||||||
|
'失败率',
|
||||||
|
formatPct(summary.failurePct),
|
||||||
|
detail: '未成功的正式尝试 ÷ 已完成的正式尝试。这不是物理丢包。',
|
||||||
|
);
|
||||||
|
default:
|
||||||
|
return MetricLine(
|
||||||
|
'无应答(未知)',
|
||||||
|
formatPct(summary.unknownPct),
|
||||||
|
detail: '无应答 ÷ 已完成。沉默不是丢包;明确的协议错误、拒绝和域名失败另看失败次数。',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
MetricLine _latency(
|
||||||
|
String label,
|
||||||
|
double? value,
|
||||||
|
ProbeSummary summary, {
|
||||||
|
bool recent = false,
|
||||||
|
}) {
|
||||||
|
if (!summary.latencyStats && summary.ok > 0 && !recent) {
|
||||||
|
return MetricLine(label, '节点未提供', detail: '这份结果来自没有上报延迟分布的节点。当前延迟仍然可用。');
|
||||||
|
}
|
||||||
|
return MetricLine(
|
||||||
|
label,
|
||||||
|
formatMs(value),
|
||||||
|
detail: recent ? '最近一次成功的往返时间。没有成功时为 —。' : '只统计成功样本。没有成功时为 —。',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
String formatDuration(Duration duration) {
|
||||||
|
final ms = duration.inMilliseconds;
|
||||||
|
if (ms < 0) {
|
||||||
|
return '—';
|
||||||
|
}
|
||||||
|
if (ms < 1000) {
|
||||||
|
return '$ms 毫秒';
|
||||||
|
}
|
||||||
|
final seconds = ms / 1000;
|
||||||
|
if (seconds < 60) {
|
||||||
|
return '${seconds.toStringAsFixed(1)} 秒';
|
||||||
|
}
|
||||||
|
final minutes = duration.inMinutes;
|
||||||
|
final rest = duration.inSeconds % 60;
|
||||||
|
return '$minutes 分 $rest 秒';
|
||||||
|
}
|
||||||
|
|
||||||
|
String formatClock(DateTime time) {
|
||||||
|
final local = time.toLocal();
|
||||||
|
String two(int value) => value.toString().padLeft(2, '0');
|
||||||
|
return '${local.year}-${two(local.month)}-${two(local.day)} ${two(local.hour)}:${two(local.minute)}:${two(local.second)}';
|
||||||
|
}
|
||||||
|
|
||||||
|
class MetricsPanel extends StatelessWidget {
|
||||||
|
const MetricsPanel({
|
||||||
|
super.key,
|
||||||
|
required this.summary,
|
||||||
|
required this.profileId,
|
||||||
|
required this.elapsed,
|
||||||
|
});
|
||||||
|
|
||||||
|
final ProbeSummary summary;
|
||||||
|
final String profileId;
|
||||||
|
final Duration elapsed;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final lines = metricLines(
|
||||||
|
summary: summary,
|
||||||
|
profileId: profileId,
|
||||||
|
elapsed: elapsed,
|
||||||
|
);
|
||||||
|
return Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
runSpacing: 8,
|
||||||
|
children: [
|
||||||
|
for (final line in lines)
|
||||||
|
Tooltip(
|
||||||
|
message: line.detail ?? '',
|
||||||
|
child: _chip('${line.label} ${line.value}'),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SessionSummaryCard extends StatelessWidget {
|
||||||
|
const SessionSummaryCard({
|
||||||
|
super.key,
|
||||||
|
required this.report,
|
||||||
|
required this.profileId,
|
||||||
|
});
|
||||||
|
|
||||||
|
final SessionReport report;
|
||||||
|
final String profileId;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final address = describeAddress(
|
||||||
|
resolved: report.resolved,
|
||||||
|
usedAddress: report.usedAddress,
|
||||||
|
usedFamily: report.usedFamily,
|
||||||
|
fallbackText: report.fallbackText,
|
||||||
|
addressUnreported: report.addressUnreported,
|
||||||
|
usedIsFake: report.usedIsFake,
|
||||||
|
);
|
||||||
|
return _panel(
|
||||||
|
title: '本次结果',
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
Text('开始 ${formatClock(report.startedAt)}'),
|
||||||
|
Text('结束 ${formatClock(report.endedAt)}'),
|
||||||
|
Text('用时 ${formatDuration(report.elapsed)}'),
|
||||||
|
Text('目标 ${report.target}'),
|
||||||
|
Text('类型 ${report.profileLabel}'),
|
||||||
|
Text('来源 ${report.sourceLabel}'),
|
||||||
|
if (address.used != null) Text(address.used!),
|
||||||
|
if (address.resolved != null) Text(address.resolved!),
|
||||||
|
if (address.unreported != null) Text(address.unreported!),
|
||||||
|
if (address.fallback != null) Text(address.fallback!),
|
||||||
|
if (address.fake)
|
||||||
|
const Text(
|
||||||
|
clashFakeIpNote,
|
||||||
|
style: TextStyle(color: Color(0xFF9A3412)),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
MetricsPanel(
|
||||||
|
summary: report.summary,
|
||||||
|
profileId: profileId,
|
||||||
|
elapsed: report.elapsed,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Text(
|
||||||
|
summaryLine(report.summary),
|
||||||
|
style: const TextStyle(color: muted, fontSize: 13),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _panel({required String title, required Widget child}) {
|
||||||
|
return Card(
|
||||||
|
margin: const EdgeInsets.only(bottom: 12),
|
||||||
|
shape: RoundedRectangleBorder(
|
||||||
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
side: const BorderSide(color: line),
|
||||||
|
),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(14),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
title,
|
||||||
|
style: const TextStyle(fontWeight: FontWeight.w700, color: ink),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 10),
|
||||||
|
child,
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _chip(String text) {
|
||||||
|
return Container(
|
||||||
|
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: const Color(0xFFE7EEF5),
|
||||||
|
borderRadius: BorderRadius.circular(99),
|
||||||
|
),
|
||||||
|
child: Text(text, style: const TextStyle(fontSize: 12, color: ink)),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -2,6 +2,8 @@ import 'package:fl_chart/fl_chart.dart';
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
import '../probe/probe_controller.dart';
|
import '../probe/probe_controller.dart';
|
||||||
|
import 'chart_selection.dart';
|
||||||
|
import 'format.dart';
|
||||||
|
|
||||||
const rttColor = Color(0xFF1F4E79);
|
const rttColor = Color(0xFF1F4E79);
|
||||||
const rateColor = Color(0xFF9A3412);
|
const rateColor = Color(0xFF9A3412);
|
||||||
@@ -9,20 +11,67 @@ const ink = Color(0xFF1C2430);
|
|||||||
const muted = Color(0xFF5E6872);
|
const muted = Color(0xFF5E6872);
|
||||||
const line = Color(0xFFE4DFD4);
|
const line = Color(0xFFE4DFD4);
|
||||||
|
|
||||||
class QualityCharts extends StatelessWidget {
|
class QualityCharts extends StatefulWidget {
|
||||||
const QualityCharts({
|
const QualityCharts({
|
||||||
super.key,
|
super.key,
|
||||||
required this.samples,
|
required this.samples,
|
||||||
required this.rateLabel,
|
required this.rateLabel,
|
||||||
required this.running,
|
required this.running,
|
||||||
|
required this.sessionId,
|
||||||
});
|
});
|
||||||
|
|
||||||
final List<ChartSample> samples;
|
final List<ChartSample> samples;
|
||||||
final String rateLabel;
|
final String rateLabel;
|
||||||
final bool running;
|
final bool running;
|
||||||
|
final int sessionId;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<QualityCharts> createState() => _QualityChartsState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _QualityChartsState extends State<QualityCharts> {
|
||||||
|
ChartSelection? _pin;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void didUpdateWidget(QualityCharts oldWidget) {
|
||||||
|
super.didUpdateWidget(oldWidget);
|
||||||
|
final kept = nextChartSelection(
|
||||||
|
current: _pin,
|
||||||
|
sessionId: widget.sessionId,
|
||||||
|
sampleSecs: [for (final sample in widget.samples) sample.sec],
|
||||||
|
);
|
||||||
|
if (kept?.sec != _pin?.sec || kept?.sessionId != _pin?.sessionId) {
|
||||||
|
_pin = kept;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void _pinAt(double sec) {
|
||||||
|
setState(() {
|
||||||
|
_pin = nextChartSelection(
|
||||||
|
current: _pin,
|
||||||
|
sessionId: widget.sessionId,
|
||||||
|
sampleSecs: [for (final sample in widget.samples) sample.sec],
|
||||||
|
tappedSec: sec,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
ChartSample? get _pinnedSample {
|
||||||
|
final pin = _pin;
|
||||||
|
if (pin == null || pin.sessionId != widget.sessionId) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
for (final sample in widget.samples) {
|
||||||
|
if ((sample.sec - pin.sec).abs() <= chartPinEpsilon) {
|
||||||
|
return sample;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
final pinned = _pinnedSample;
|
||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
children: [
|
children: [
|
||||||
@@ -34,29 +83,51 @@ class QualityCharts extends StatelessWidget {
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
|
Text(
|
||||||
|
pinned == null
|
||||||
|
? '点曲线上的一点可以钉住该时刻,松手后仍会保留。再点另一点会更换。'
|
||||||
|
: pinnedReadout(pinned, widget.rateLabel),
|
||||||
|
key: const Key('chart-pin'),
|
||||||
|
style: const TextStyle(color: ink, fontSize: 13, height: 1.4),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
_ChartCard(
|
_ChartCard(
|
||||||
title: '延迟',
|
title: '延迟',
|
||||||
unit: 'ms',
|
unit: 'ms',
|
||||||
samples: samples,
|
samples: widget.samples,
|
||||||
read: (sample) => sample.rttMs,
|
read: (sample) => sample.rttMs,
|
||||||
color: rttColor,
|
color: rttColor,
|
||||||
floor: 1,
|
floor: 1,
|
||||||
running: running,
|
running: widget.running,
|
||||||
|
pinnedSec: pinned?.sec,
|
||||||
|
onPin: _pinAt,
|
||||||
),
|
),
|
||||||
_ChartCard(
|
_ChartCard(
|
||||||
title: rateLabel,
|
title: widget.rateLabel,
|
||||||
unit: '%',
|
unit: '%',
|
||||||
samples: samples,
|
samples: widget.samples,
|
||||||
read: (sample) => sample.ratePct,
|
read: (sample) => sample.ratePct,
|
||||||
color: rateColor,
|
color: rateColor,
|
||||||
floor: 10,
|
floor: 10,
|
||||||
running: running,
|
running: widget.running,
|
||||||
|
pinnedSec: pinned?.sec,
|
||||||
|
onPin: _pinAt,
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
String pinnedReadout(ChartSample sample, String rateLabel) {
|
||||||
|
final latency = sample.rttMs == null
|
||||||
|
? '这一刻没有延迟'
|
||||||
|
: '延迟 ${formatMs(sample.rttMs)}';
|
||||||
|
final rate = sample.ratePct == null
|
||||||
|
? '$rateLabel —'
|
||||||
|
: '$rateLabel ${formatPct(sample.ratePct)}';
|
||||||
|
return '已选 ${sample.sec.toStringAsFixed(1)} 秒 · $latency · $rate';
|
||||||
|
}
|
||||||
|
|
||||||
class _Swatch extends StatelessWidget {
|
class _Swatch extends StatelessWidget {
|
||||||
const _Swatch({required this.color, required this.label});
|
const _Swatch({required this.color, required this.label});
|
||||||
|
|
||||||
@@ -92,6 +163,8 @@ class _ChartCard extends StatelessWidget {
|
|||||||
required this.color,
|
required this.color,
|
||||||
required this.floor,
|
required this.floor,
|
||||||
required this.running,
|
required this.running,
|
||||||
|
required this.pinnedSec,
|
||||||
|
required this.onPin,
|
||||||
});
|
});
|
||||||
|
|
||||||
final String title;
|
final String title;
|
||||||
@@ -101,6 +174,8 @@ class _ChartCard extends StatelessWidget {
|
|||||||
final Color color;
|
final Color color;
|
||||||
final double floor;
|
final double floor;
|
||||||
final bool running;
|
final bool running;
|
||||||
|
final double? pinnedSec;
|
||||||
|
final void Function(double sec) onPin;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
@@ -132,9 +207,7 @@ class _ChartCard extends StatelessWidget {
|
|||||||
? _lineChart(spots)
|
? _lineChart(spots)
|
||||||
: Center(
|
: Center(
|
||||||
child: Text(
|
child: Text(
|
||||||
running
|
running ? '正在等待第一次完成的探测。未完成的不会画成 100%。' : '暂无已完成的探测',
|
||||||
? '正在等待第一次完成的探测。未完成的不会画成 100%。'
|
|
||||||
: '暂无已完成的探测',
|
|
||||||
style: const TextStyle(color: muted),
|
style: const TextStyle(color: muted),
|
||||||
textAlign: TextAlign.center,
|
textAlign: TextAlign.center,
|
||||||
),
|
),
|
||||||
@@ -190,7 +263,8 @@ class _ChartCard extends StatelessWidget {
|
|||||||
show: true,
|
show: true,
|
||||||
drawVerticalLine: false,
|
drawVerticalLine: false,
|
||||||
horizontalInterval: yInterval,
|
horizontalInterval: yInterval,
|
||||||
getDrawingHorizontalLine: (_) => const FlLine(color: line, strokeWidth: 1),
|
getDrawingHorizontalLine: (_) =>
|
||||||
|
const FlLine(color: line, strokeWidth: 1),
|
||||||
),
|
),
|
||||||
borderData: FlBorderData(
|
borderData: FlBorderData(
|
||||||
show: true,
|
show: true,
|
||||||
@@ -200,14 +274,19 @@ class _ChartCard extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
titlesData: FlTitlesData(
|
titlesData: FlTitlesData(
|
||||||
topTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
|
topTitles: const AxisTitles(
|
||||||
rightTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
|
sideTitles: SideTitles(showTitles: false),
|
||||||
|
),
|
||||||
|
rightTitles: const AxisTitles(
|
||||||
|
sideTitles: SideTitles(showTitles: false),
|
||||||
|
),
|
||||||
leftTitles: AxisTitles(
|
leftTitles: AxisTitles(
|
||||||
sideTitles: SideTitles(
|
sideTitles: SideTitles(
|
||||||
showTitles: true,
|
showTitles: true,
|
||||||
reservedSize: 40,
|
reservedSize: 40,
|
||||||
interval: yInterval,
|
interval: yInterval,
|
||||||
getTitlesWidget: (value, meta) => _axisLabel(_formatTick(value, maxY)),
|
getTitlesWidget: (value, meta) =>
|
||||||
|
_axisLabel(_formatTick(value, maxY)),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
bottomTitles: AxisTitles(
|
bottomTitles: AxisTitles(
|
||||||
@@ -220,15 +299,46 @@ class _ChartCard extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
lineTouchData: const LineTouchData(handleBuiltInTouches: true),
|
extraLinesData: ExtraLinesData(
|
||||||
|
verticalLines: [
|
||||||
|
if (pinnedSec != null)
|
||||||
|
VerticalLine(
|
||||||
|
x: pinnedSec!,
|
||||||
|
color: color.withValues(alpha: 0.85),
|
||||||
|
strokeWidth: 1.5,
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
lineTouchData: LineTouchData(
|
||||||
|
handleBuiltInTouches: false,
|
||||||
|
touchSpotThreshold: 18,
|
||||||
|
touchCallback: (event, response) {
|
||||||
|
if (event is! FlTapUpEvent) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final spots = response?.lineBarSpots;
|
||||||
|
if (spots == null || spots.isEmpty) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onPin(spots.first.x);
|
||||||
|
},
|
||||||
|
),
|
||||||
lineBarsData: [
|
lineBarsData: [
|
||||||
LineChartBarData(
|
LineChartBarData(
|
||||||
spots: spots,
|
spots: spots,
|
||||||
isCurved: false,
|
isCurved: false,
|
||||||
color: color,
|
color: color,
|
||||||
barWidth: 2,
|
barWidth: 2,
|
||||||
dotData: const FlDotData(show: false),
|
dotData: FlDotData(
|
||||||
belowBarData: BarAreaData(show: true, color: color.withValues(alpha: 0.10)),
|
show: pinnedSec != null,
|
||||||
|
checkToShowDot: (spot, _) =>
|
||||||
|
pinnedSec != null &&
|
||||||
|
(spot.x - pinnedSec!).abs() <= chartPinEpsilon,
|
||||||
|
),
|
||||||
|
belowBarData: BarAreaData(
|
||||||
|
show: true,
|
||||||
|
color: color.withValues(alpha: 0.10),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
const appVersion = '1.1.2';
|
||||||
|
const appBuild = 5;
|
||||||
|
const appAttribution = '言灸';
|
||||||
|
const appLicense = 'AGPL-3.0-only';
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# 网络质量探测 · Linux 桌面客户端
|
||||||
|
|
||||||
|
这是 1.1.2 的 Linux 64 位桌面程序,解压后可以直接运行。不需要再安装 Flutter。
|
||||||
|
|
||||||
|
## 先安装系统库
|
||||||
|
|
||||||
|
Ubuntu 或 Debian:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo apt update
|
||||||
|
sudo apt install -y libgtk-3-0 libblkid1 liblzma5
|
||||||
|
```
|
||||||
|
|
||||||
|
其他发行版安装同样的 GTK 3 运行库即可。
|
||||||
|
|
||||||
|
## 运行
|
||||||
|
|
||||||
|
在解压出来的文件夹里执行:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./netquality
|
||||||
|
```
|
||||||
|
|
||||||
|
不要把 `netquality` 单独拷走。它需要旁边的 `lib` 和 `data` 目录。
|
||||||
|
|
||||||
|
第一次打开如果窗口一闪就关,把上面的系统库装上再试。
|
||||||
|
|
||||||
|
## 和手机版的关系
|
||||||
|
|
||||||
|
用法和手机相同:选「本机」直接测,或选「远程节点」让你自己的 Linux 节点去测。节点程序是另外的压缩包(文件名以 `netquality-server` 开头),不在这个包里。
|
||||||
+1
-1
@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
|
|||||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||||
# In Windows, build-name is used as the major, minor, and patch parts
|
# In Windows, build-name is used as the major, minor, and patch parts
|
||||||
# of the product and file versions while build-number is used as the build suffix.
|
# of the product and file versions while build-number is used as the build suffix.
|
||||||
version: 1.1.1+4
|
version: 1.1.2+5
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.13.7
|
sdk: ^3.13.7
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:netquality/content/release_history.dart';
|
||||||
|
import 'package:netquality/metrics/sample_book.dart';
|
||||||
|
import 'package:netquality/ui/address_text.dart';
|
||||||
|
import 'package:netquality/ui/chart_selection.dart';
|
||||||
|
import 'package:netquality/version.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('resolved addresses are not shown as the address in use', () {
|
||||||
|
const resolved = [
|
||||||
|
ResolvedAddress(address: '2001:db8::1', family: 'IPv6'),
|
||||||
|
ResolvedAddress(address: '203.0.113.5', family: 'IPv4'),
|
||||||
|
];
|
||||||
|
final onlyResolved = describeAddress(resolved: resolved);
|
||||||
|
expect(onlyResolved.used, isNull);
|
||||||
|
expect(onlyResolved.resolved, contains('解析到'));
|
||||||
|
expect(onlyResolved.resolved, contains('2001:db8::1'));
|
||||||
|
expect(onlyResolved.resolved, isNot(contains('实际地址')));
|
||||||
|
|
||||||
|
final used = describeAddress(
|
||||||
|
resolved: resolved,
|
||||||
|
usedAddress: '203.0.113.5',
|
||||||
|
usedFamily: 'IPv4',
|
||||||
|
fallbackText: '已改用 IPv4',
|
||||||
|
);
|
||||||
|
expect(used.used, '实际地址 203.0.113.5(IPv4)');
|
||||||
|
expect(used.resolved, contains('2001:db8::1'));
|
||||||
|
expect(used.fallback, '已改用 IPv4');
|
||||||
|
|
||||||
|
final oldNode = describeAddress(
|
||||||
|
resolved: const [],
|
||||||
|
addressUnreported: true,
|
||||||
|
);
|
||||||
|
expect(oldNode.used, isNull);
|
||||||
|
expect(oldNode.unreported, '节点没有报告实际使用的地址');
|
||||||
|
|
||||||
|
final missing = ProbeSample.fromJson({
|
||||||
|
'seq': 1,
|
||||||
|
'status': 'ok',
|
||||||
|
'kind': 'probe',
|
||||||
|
'rttMs': 3,
|
||||||
|
'summary': {'sent': 1, 'ok': 1},
|
||||||
|
});
|
||||||
|
expect(missing.detail['address'], isNull);
|
||||||
|
final parsed = readResolvedList({
|
||||||
|
'resolved': [
|
||||||
|
{'address': '2001:db8::1', 'family': 'IPv6'},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(parsed.single.address, '2001:db8::1');
|
||||||
|
expect(readResolvedList({'jobId': 'abc'}), isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a pinned chart point stays put until it scrolls off or the session changes', () {
|
||||||
|
const first = ChartSelection(sec: 1.5, sessionId: 3);
|
||||||
|
final kept = nextChartSelection(
|
||||||
|
current: first,
|
||||||
|
sessionId: 3,
|
||||||
|
sampleSecs: [1.5, 2.5, 3.5],
|
||||||
|
);
|
||||||
|
expect(kept, same(first));
|
||||||
|
|
||||||
|
final moved = nextChartSelection(
|
||||||
|
current: first,
|
||||||
|
sessionId: 3,
|
||||||
|
sampleSecs: [1.5, 2.5, 3.5],
|
||||||
|
tappedSec: 2.4,
|
||||||
|
);
|
||||||
|
expect(moved!.sec, 2.5);
|
||||||
|
expect(moved.sessionId, 3);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
nextChartSelection(current: moved, sessionId: 4, sampleSecs: [0.2, 0.4]),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
nextChartSelection(current: first, sessionId: 3, sampleSecs: [2.5, 3.5]),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
nextChartSelection(current: first, sessionId: 3, sampleSecs: const []),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('history only lists the real tag and this version', () {
|
||||||
|
expect(appVersion, '1.1.2');
|
||||||
|
expect(appBuild, 5);
|
||||||
|
expect(appAttribution, '言灸');
|
||||||
|
expect(releaseHistory.map((entry) => entry.version), ['1.1.2', '1.1.1']);
|
||||||
|
expect(releaseHistory.last.published, '2026-11-09');
|
||||||
|
expect(releaseHistory.last.source, contains('v1.1.1'));
|
||||||
|
expect(releaseHistoryNote, contains('不写成另一个版本'));
|
||||||
|
for (final entry in releaseHistory) {
|
||||||
|
expect(entry.version, isNot('1.1.0'));
|
||||||
|
expect(entry.version, isNot('1.0.0'));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
// The plot surface is not part of fl_chart's public API. The tap has to land
|
||||||
|
// on that surface, not on the axis titles around it.
|
||||||
|
// ignore_for_file: implementation_imports
|
||||||
|
|
||||||
|
import 'package:fl_chart/src/chart/line_chart/line_chart_renderer.dart';
|
||||||
|
import 'package:flutter/gestures.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:netquality/probe/probe_controller.dart';
|
||||||
|
import 'package:netquality/ui/chart_selection.dart';
|
||||||
|
import 'package:netquality/ui/quality_charts.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('a tap pins the nearest time and a later tap replaces it', () {
|
||||||
|
final first = nextChartSelection(
|
||||||
|
current: null,
|
||||||
|
sessionId: 3,
|
||||||
|
sampleSecs: const [1, 2, 4],
|
||||||
|
tappedSec: 2.2,
|
||||||
|
);
|
||||||
|
expect(first, isNotNull);
|
||||||
|
expect(first!.sec, 2);
|
||||||
|
expect(first.sessionId, 3);
|
||||||
|
|
||||||
|
final second = nextChartSelection(
|
||||||
|
current: first,
|
||||||
|
sessionId: 3,
|
||||||
|
sampleSecs: const [1, 2, 4],
|
||||||
|
tappedSec: 3.6,
|
||||||
|
);
|
||||||
|
expect(second!.sec, 4);
|
||||||
|
|
||||||
|
final kept = nextChartSelection(
|
||||||
|
current: second,
|
||||||
|
sessionId: 3,
|
||||||
|
sampleSecs: const [1, 2, 4],
|
||||||
|
);
|
||||||
|
expect(kept, same(second));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a new session or a point that rolled off does not jump', () {
|
||||||
|
const pin = ChartSelection(sec: 1, sessionId: 3);
|
||||||
|
expect(
|
||||||
|
nextChartSelection(current: pin, sessionId: 4, sampleSecs: const [1, 2]),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
nextChartSelection(current: pin, sessionId: 3, sampleSecs: const [2, 3]),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
nextChartSelection(current: pin, sessionId: 3, sampleSecs: const []),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('releasing a chart tap keeps the pinned readout', (tester) async {
|
||||||
|
const samples = [
|
||||||
|
ChartSample(sec: 0, rttMs: 10, ratePct: 0),
|
||||||
|
ChartSample(sec: 1, rttMs: 30, ratePct: 50),
|
||||||
|
];
|
||||||
|
await tester.pumpWidget(
|
||||||
|
const MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: QualityCharts(
|
||||||
|
samples: samples,
|
||||||
|
rateLabel: '探测无应答',
|
||||||
|
running: false,
|
||||||
|
sessionId: 1,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.textContaining('点曲线上的一点'), findsOneWidget);
|
||||||
|
|
||||||
|
final box = tester.getRect(find.byType(LineChartLeaf).first);
|
||||||
|
const maxY = 30 * 1.2;
|
||||||
|
Offset at(double sec, double value) {
|
||||||
|
final x = box.left + box.width * sec;
|
||||||
|
final y = box.top + (1 - value / maxY) * box.height;
|
||||||
|
return Offset(x.clamp(box.left + 2, box.right - 2), y);
|
||||||
|
}
|
||||||
|
|
||||||
|
await tester.tapAt(at(0, 10));
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.textContaining('已选 0.0 秒'), findsOneWidget);
|
||||||
|
expect(find.textContaining('延迟'), findsWidgets);
|
||||||
|
|
||||||
|
final mouse = await tester.startGesture(
|
||||||
|
at(1, 30),
|
||||||
|
kind: PointerDeviceKind.mouse,
|
||||||
|
);
|
||||||
|
await mouse.up();
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.textContaining('已选 1.0 秒'), findsOneWidget);
|
||||||
|
expect(find.textContaining('已选 0.0 秒'), findsNothing);
|
||||||
|
|
||||||
|
await tester.pumpWidget(
|
||||||
|
const MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: QualityCharts(
|
||||||
|
samples: [ChartSample(sec: 2, rttMs: 8, ratePct: 0)],
|
||||||
|
rateLabel: '探测无应答',
|
||||||
|
running: false,
|
||||||
|
sessionId: 1,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.textContaining('已选'), findsNothing);
|
||||||
|
expect(find.textContaining('点曲线上的一点'), findsOneWidget);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:netquality/metrics/latency.dart';
|
||||||
|
import 'package:netquality/metrics/sample_book.dart';
|
||||||
|
import 'package:netquality/ui/metrics_panel.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('percentile ranks match the documented integer formula', () {
|
||||||
|
expect(nearestRank95(1), 1);
|
||||||
|
expect(nearestRank95(2), 2);
|
||||||
|
expect(nearestRank95(4), 4);
|
||||||
|
expect(nearestRank95(5), 5);
|
||||||
|
expect(nearestRank95(20), 19);
|
||||||
|
|
||||||
|
final one = LatencyStats.from([10]);
|
||||||
|
expect(one!.min, 10);
|
||||||
|
expect(one.mean, 10);
|
||||||
|
expect(one.median, 10);
|
||||||
|
expect(one.p95, 10);
|
||||||
|
expect(one.max, 10);
|
||||||
|
|
||||||
|
final two = LatencyStats.from([10, 30]);
|
||||||
|
expect(two!.median, 20);
|
||||||
|
expect(two.p95, 30);
|
||||||
|
expect(two.mean, 20);
|
||||||
|
|
||||||
|
final four = LatencyStats.from([1, 2, 3, 4]);
|
||||||
|
expect(four!.median, 2.5);
|
||||||
|
expect(four.p95, 4);
|
||||||
|
expect(four.min, 1);
|
||||||
|
expect(four.max, 4);
|
||||||
|
|
||||||
|
final five = LatencyStats.from([1, 2, 3, 4, 10]);
|
||||||
|
expect(five!.median, 3);
|
||||||
|
expect(five.p95, 10);
|
||||||
|
expect(five.mean, 4);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('sample book keeps current rtt separate from the distribution', () {
|
||||||
|
final book = SampleBook('nq-udp');
|
||||||
|
book.add(const Outcome(status: Outcome.ok, kind: Outcome.probe, rttMs: 1));
|
||||||
|
book.add(const Outcome(status: Outcome.ok, kind: Outcome.probe, rttMs: 2));
|
||||||
|
book.add(const Outcome(status: Outcome.ok, kind: Outcome.probe, rttMs: 3));
|
||||||
|
book.add(const Outcome(status: Outcome.ok, kind: Outcome.probe, rttMs: 4));
|
||||||
|
final summary = book.summary();
|
||||||
|
expect(summary.rttMs, 4);
|
||||||
|
expect(summary.minRttMs, 1);
|
||||||
|
expect(summary.maxRttMs, 4);
|
||||||
|
expect(summary.medianRttMs, 2.5);
|
||||||
|
expect(summary.p95RttMs, 4);
|
||||||
|
expect(summary.meanRttMs, 2.5);
|
||||||
|
expect(summary.latencyStats, isTrue);
|
||||||
|
expect(summary.jitterMs, isNotNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('unsupported rates stay blank instead of a false zero', () {
|
||||||
|
final silent = SampleBook('udp-generic')
|
||||||
|
..add(const Outcome(status: Outcome.unknown, kind: Outcome.query));
|
||||||
|
final lines = metricLines(
|
||||||
|
summary: silent.summary(),
|
||||||
|
profileId: 'udp-generic',
|
||||||
|
elapsed: const Duration(seconds: 2),
|
||||||
|
);
|
||||||
|
expect(_value(lines, '超时'), '不适用');
|
||||||
|
expect(_value(lines, '无应答(未知)'), '100%');
|
||||||
|
expect(_value(lines, '探测无应答'), isNull);
|
||||||
|
expect(_value(lines, '当前延迟'), '—');
|
||||||
|
|
||||||
|
final connect = SampleBook('tcp-connect');
|
||||||
|
final empty = metricLines(
|
||||||
|
summary: connect.summary(),
|
||||||
|
profileId: 'tcp-connect',
|
||||||
|
elapsed: Duration.zero,
|
||||||
|
);
|
||||||
|
expect(_value(empty, '失败率'), '—');
|
||||||
|
expect(_value(empty, '探测无应答'), isNull);
|
||||||
|
|
||||||
|
final oldNode = ProbeSummary.fromJson({
|
||||||
|
'sent': 1,
|
||||||
|
'completed': 1,
|
||||||
|
'ok': 1,
|
||||||
|
'rttMs': 8,
|
||||||
|
'probeLossPct': 0,
|
||||||
|
});
|
||||||
|
final remote = metricLines(
|
||||||
|
summary: oldNode,
|
||||||
|
profileId: 'nq-udp',
|
||||||
|
elapsed: const Duration(seconds: 3),
|
||||||
|
);
|
||||||
|
expect(_value(remote, '当前延迟'), '8.00 ms');
|
||||||
|
expect(_value(remote, 'P95 延迟'), '节点未提供');
|
||||||
|
expect(_value(remote, '探测无应答'), '0%');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
String? _value(List<MetricLine> lines, String label) {
|
||||||
|
for (final line in lines) {
|
||||||
|
if (line.label == label) {
|
||||||
|
return line.value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:netquality/models/node_edit.dart';
|
||||||
|
import 'package:netquality/models/port_field.dart';
|
||||||
|
import 'package:netquality/models/probe_profile.dart';
|
||||||
|
import 'package:netquality/models/session_config.dart';
|
||||||
|
import 'package:netquality/storage/token_vault.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test(
|
||||||
|
'editing keeps the node id and replaces only a non-blank token',
|
||||||
|
() async {
|
||||||
|
const original = RemoteNode(
|
||||||
|
id: 'node-7',
|
||||||
|
name: '机房',
|
||||||
|
baseUrl: 'https://probe.example:8443',
|
||||||
|
visibility: 'private',
|
||||||
|
);
|
||||||
|
final renamed = applyNodeEdit(
|
||||||
|
original,
|
||||||
|
name: '机房乙',
|
||||||
|
baseUrl: 'https://probe.example:8443',
|
||||||
|
);
|
||||||
|
expect(renamed.id, 'node-7');
|
||||||
|
expect(renamed.name, '机房乙');
|
||||||
|
expect(renamed.visibility, 'private');
|
||||||
|
|
||||||
|
final moved = applyNodeEdit(
|
||||||
|
renamed,
|
||||||
|
name: '机房乙',
|
||||||
|
baseUrl: 'https://other.example:8443',
|
||||||
|
);
|
||||||
|
expect(moved.id, 'node-7');
|
||||||
|
expect(moved.visibility, '');
|
||||||
|
|
||||||
|
final vault = MemoryTokenVault();
|
||||||
|
await vault.write(nodeTokenKey('node-7'), 'saved-secret');
|
||||||
|
expect(await saveEditedNodeToken(vault, 'node-7', ' '), isFalse);
|
||||||
|
expect(await vault.read(nodeTokenKey('node-7')), 'saved-secret');
|
||||||
|
expect(replacementNodeToken(' '), isNull);
|
||||||
|
expect(
|
||||||
|
await saveEditedNodeToken(vault, 'node-7', ' next-secret '),
|
||||||
|
isTrue,
|
||||||
|
);
|
||||||
|
expect(await vault.read(nodeTokenKey('node-7')), 'next-secret');
|
||||||
|
final encoded = moved.toJson();
|
||||||
|
expect(encoded.containsKey('token'), isFalse);
|
||||||
|
expect(encoded.values, isNot(contains('saved-secret')));
|
||||||
|
expect(encoded.values, isNot(contains('next-secret')));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test(
|
||||||
|
'port follows the profile default unless the user typed another port',
|
||||||
|
() {
|
||||||
|
expect(ProbeProfile.nqTcp.port, 19090);
|
||||||
|
expect(ProbeProfile.nqUdp.port, 19091);
|
||||||
|
expect(portHint(ProbeProfile.nqTcp), '合作反射 TCP 默认 19090');
|
||||||
|
expect(portHint(ProbeProfile.nqUdp), '合作反射 UDP 默认 19091');
|
||||||
|
expect(
|
||||||
|
portAfterProfileChange(
|
||||||
|
current: '19090',
|
||||||
|
previousDefault: 19090,
|
||||||
|
nextDefault: 19091,
|
||||||
|
),
|
||||||
|
'19091',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
portAfterProfileChange(
|
||||||
|
current: ' 19090 ',
|
||||||
|
previousDefault: 19090,
|
||||||
|
nextDefault: 19132,
|
||||||
|
),
|
||||||
|
'19132',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
portAfterProfileChange(
|
||||||
|
current: '',
|
||||||
|
previousDefault: 19090,
|
||||||
|
nextDefault: 19091,
|
||||||
|
),
|
||||||
|
'19091',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
portAfterProfileChange(
|
||||||
|
current: '25565',
|
||||||
|
previousDefault: 19090,
|
||||||
|
nextDefault: 19091,
|
||||||
|
),
|
||||||
|
'25565',
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
portAfterProfileChange(
|
||||||
|
current: '25565',
|
||||||
|
previousDefault: 19091,
|
||||||
|
nextDefault: 80,
|
||||||
|
),
|
||||||
|
'25565',
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
+253
-226
@@ -25,238 +25,261 @@ void main() {
|
|||||||
expect(build.exitCode, 0, reason: '${build.stdout}\n${build.stderr}');
|
expect(build.exitCode, 0, reason: '${build.stdout}\n${build.stderr}');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('local nq tcp and udp get real rtt and do not call connect failure loss', () async {
|
test(
|
||||||
final reflector = await _reflector();
|
'local nq tcp and udp get real rtt and do not call connect failure loss',
|
||||||
addTearDown(() => reflector.process.kill());
|
() async {
|
||||||
final tcp = await _collect(
|
final reflector = await _reflector();
|
||||||
ProbeRequest(
|
addTearDown(() => reflector.process.kill());
|
||||||
host: '127.0.0.1',
|
final tcp = await _collect(
|
||||||
port: reflector.tcp,
|
ProbeRequest(
|
||||||
profileId: 'nq-tcp',
|
host: '127.0.0.1',
|
||||||
interval: const Duration(milliseconds: 200),
|
port: reflector.tcp,
|
||||||
timeout: const Duration(milliseconds: 800),
|
profileId: 'nq-tcp',
|
||||||
packetSize: 80,
|
interval: const Duration(milliseconds: 200),
|
||||||
echoToken: '',
|
timeout: const Duration(milliseconds: 800),
|
||||||
dnsName: '',
|
packetSize: 80,
|
||||||
payloadHex: '',
|
echoToken: '',
|
||||||
expectHex: '',
|
dnsName: '',
|
||||||
),
|
payloadHex: '',
|
||||||
count: 2,
|
expectHex: '',
|
||||||
);
|
),
|
||||||
expect(tcp.last.status, Outcome.ok);
|
count: 2,
|
||||||
expect(tcp.last.rttMs, greaterThan(0));
|
);
|
||||||
expect(tcp.last.summary.probeLossPct, 0);
|
expect(tcp.last.status, Outcome.ok);
|
||||||
|
expect(tcp.last.rttMs, greaterThan(0));
|
||||||
|
expect(tcp.last.summary.probeLossPct, 0);
|
||||||
|
|
||||||
final udp = await _collect(
|
final udp = await _collect(
|
||||||
ProbeRequest(
|
ProbeRequest(
|
||||||
host: '127.0.0.1',
|
host: '127.0.0.1',
|
||||||
port: reflector.udp,
|
port: reflector.udp,
|
||||||
profileId: 'nq-udp',
|
profileId: 'nq-udp',
|
||||||
interval: const Duration(milliseconds: 200),
|
interval: const Duration(milliseconds: 200),
|
||||||
timeout: const Duration(milliseconds: 800),
|
timeout: const Duration(milliseconds: 800),
|
||||||
packetSize: 80,
|
packetSize: 80,
|
||||||
echoToken: '',
|
echoToken: '',
|
||||||
dnsName: '',
|
dnsName: '',
|
||||||
payloadHex: '',
|
payloadHex: '',
|
||||||
expectHex: '',
|
expectHex: '',
|
||||||
),
|
),
|
||||||
count: 1,
|
count: 1,
|
||||||
);
|
);
|
||||||
expect(udp.single.status, Outcome.ok);
|
expect(udp.single.status, Outcome.ok);
|
||||||
expect(udp.single.summary.probeLossPct, 0);
|
expect(udp.single.summary.probeLossPct, 0);
|
||||||
|
|
||||||
final refused = await _collect(
|
final refused = await _collect(
|
||||||
ProbeRequest(
|
ProbeRequest(
|
||||||
host: '127.0.0.1',
|
host: '127.0.0.1',
|
||||||
port: 1,
|
port: 1,
|
||||||
profileId: 'tcp-connect',
|
profileId: 'tcp-connect',
|
||||||
interval: const Duration(milliseconds: 200),
|
interval: const Duration(milliseconds: 200),
|
||||||
timeout: const Duration(milliseconds: 400),
|
timeout: const Duration(milliseconds: 400),
|
||||||
packetSize: 64,
|
packetSize: 64,
|
||||||
echoToken: '',
|
echoToken: '',
|
||||||
dnsName: '',
|
dnsName: '',
|
||||||
payloadHex: '',
|
payloadHex: '',
|
||||||
expectHex: '',
|
expectHex: '',
|
||||||
),
|
),
|
||||||
count: 1,
|
count: 1,
|
||||||
);
|
);
|
||||||
expect(refused.single.status, Outcome.refused);
|
expect(refused.single.status, Outcome.refused);
|
||||||
expect(refused.single.summary.failurePct, 100);
|
expect(refused.single.summary.failurePct, 100);
|
||||||
expect(refused.single.summary.probeLossPct, isNull);
|
expect(refused.single.summary.probeLossPct, isNull);
|
||||||
});
|
},
|
||||||
|
);
|
||||||
|
|
||||||
test('silence is unknown, games answer, and a remote node measures rtt', () async {
|
test(
|
||||||
final hole = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
|
'silence is unknown, games answer, and a remote node measures rtt',
|
||||||
addTearDown(hole.close);
|
() async {
|
||||||
hole.listen((event) {
|
final hole = await RawDatagramSocket.bind(
|
||||||
if (event == RawSocketEvent.read) {
|
InternetAddress.loopbackIPv4,
|
||||||
hole.receive();
|
0,
|
||||||
}
|
);
|
||||||
});
|
addTearDown(hole.close);
|
||||||
final unknown = await _collect(
|
hole.listen((event) {
|
||||||
ProbeRequest(
|
if (event == RawSocketEvent.read) {
|
||||||
host: '127.0.0.1',
|
hole.receive();
|
||||||
port: hole.port,
|
|
||||||
profileId: 'udp-generic',
|
|
||||||
interval: const Duration(milliseconds: 200),
|
|
||||||
timeout: const Duration(milliseconds: 200),
|
|
||||||
packetSize: 16,
|
|
||||||
echoToken: '',
|
|
||||||
dnsName: '',
|
|
||||||
payloadHex: '',
|
|
||||||
expectHex: '',
|
|
||||||
),
|
|
||||||
count: 1,
|
|
||||||
);
|
|
||||||
expect(unknown.single.status, Outcome.unknown);
|
|
||||||
expect(unknown.single.summary.probeLossPct, isNull);
|
|
||||||
expect(unknown.single.summary.unknownPct, 100);
|
|
||||||
expect(unknown.single.detail['address'], '127.0.0.1');
|
|
||||||
|
|
||||||
final java = await _javaServer();
|
|
||||||
addTearDown(java.close);
|
|
||||||
final javaSample = await _collect(
|
|
||||||
ProbeRequest(
|
|
||||||
host: '127.0.0.1',
|
|
||||||
port: java.port,
|
|
||||||
profileId: 'minecraft-java',
|
|
||||||
interval: const Duration(milliseconds: 200),
|
|
||||||
timeout: const Duration(milliseconds: 800),
|
|
||||||
packetSize: 64,
|
|
||||||
echoToken: '',
|
|
||||||
dnsName: '',
|
|
||||||
payloadHex: '',
|
|
||||||
expectHex: '',
|
|
||||||
),
|
|
||||||
count: 1,
|
|
||||||
);
|
|
||||||
expect(javaSample.single.status, Outcome.ok);
|
|
||||||
expect(javaSample.single.detail['motd'], 'Hello');
|
|
||||||
expect(javaSample.single.rttMs, greaterThan(0));
|
|
||||||
expect(javaSample.single.summary.failurePct, 0);
|
|
||||||
|
|
||||||
final bedrock = await _bedrockServer();
|
|
||||||
addTearDown(bedrock.close);
|
|
||||||
final bedrockSample = await _collect(
|
|
||||||
ProbeRequest(
|
|
||||||
host: '127.0.0.1',
|
|
||||||
port: bedrock.port,
|
|
||||||
profileId: 'minecraft-bedrock',
|
|
||||||
interval: const Duration(milliseconds: 200),
|
|
||||||
timeout: const Duration(milliseconds: 800),
|
|
||||||
packetSize: 64,
|
|
||||||
echoToken: '',
|
|
||||||
dnsName: '',
|
|
||||||
payloadHex: '',
|
|
||||||
expectHex: '',
|
|
||||||
),
|
|
||||||
count: 1,
|
|
||||||
);
|
|
||||||
expect(bedrockSample.single.status, Outcome.ok);
|
|
||||||
expect(bedrockSample.single.detail['motd'], 'Bed');
|
|
||||||
|
|
||||||
final node = await _node();
|
|
||||||
addTearDown(node.kill);
|
|
||||||
final samples = <ProbeSample>[];
|
|
||||||
final remote = RemoteProbe();
|
|
||||||
final done = Completer<void>();
|
|
||||||
unawaited(() async {
|
|
||||||
try {
|
|
||||||
await remote.run(
|
|
||||||
baseUrl: 'http://127.0.0.1:${node.control}',
|
|
||||||
nodeToken: '',
|
|
||||||
body: ProbeBody(
|
|
||||||
target: '127.0.0.1',
|
|
||||||
port: node.udp,
|
|
||||||
profile: 'nq-udp',
|
|
||||||
intervalMs: 200,
|
|
||||||
timeoutMs: 800,
|
|
||||||
durationSec: 3,
|
|
||||||
packetSize: 80,
|
|
||||||
echoToken: '',
|
|
||||||
dnsName: '',
|
|
||||||
payloadHex: '',
|
|
||||||
expectHex: '',
|
|
||||||
),
|
|
||||||
onSample: (sample) {
|
|
||||||
samples.add(sample);
|
|
||||||
if (samples.length == 1 && !done.isCompleted) {
|
|
||||||
done.complete();
|
|
||||||
}
|
|
||||||
},
|
|
||||||
cancelled: () => done.isCompleted,
|
|
||||||
);
|
|
||||||
} finally {
|
|
||||||
if (!done.isCompleted) {
|
|
||||||
done.complete();
|
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
}());
|
final unknown = await _collect(
|
||||||
await done.future.timeout(const Duration(seconds: 5));
|
ProbeRequest(
|
||||||
await remote.stop('');
|
host: '127.0.0.1',
|
||||||
expect(samples, isNotEmpty);
|
port: hole.port,
|
||||||
expect(samples.first.status, Outcome.ok);
|
profileId: 'udp-generic',
|
||||||
expect(samples.first.rttMs, greaterThan(0));
|
interval: const Duration(milliseconds: 200),
|
||||||
expect(samples.first.summary.probeLossPct, 0);
|
timeout: const Duration(milliseconds: 200),
|
||||||
});
|
packetSize: 16,
|
||||||
|
echoToken: '',
|
||||||
|
dnsName: '',
|
||||||
|
payloadHex: '',
|
||||||
|
expectHex: '',
|
||||||
|
),
|
||||||
|
count: 1,
|
||||||
|
);
|
||||||
|
expect(unknown.single.status, Outcome.unknown);
|
||||||
|
expect(unknown.single.summary.probeLossPct, isNull);
|
||||||
|
expect(unknown.single.summary.unknownPct, 100);
|
||||||
|
expect(unknown.single.detail['address'], '127.0.0.1');
|
||||||
|
|
||||||
test('plain udp leaves a silent address and keeps one that answers', () async {
|
final java = await _javaServer();
|
||||||
final drop = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
|
addTearDown(java.close);
|
||||||
addTearDown(drop.close);
|
final javaSample = await _collect(
|
||||||
final port = drop.port;
|
ProbeRequest(
|
||||||
drop.listen((event) {
|
host: '127.0.0.1',
|
||||||
if (event == RawSocketEvent.read) {
|
port: java.port,
|
||||||
drop.receive();
|
profileId: 'minecraft-java',
|
||||||
}
|
interval: const Duration(milliseconds: 200),
|
||||||
});
|
timeout: const Duration(milliseconds: 800),
|
||||||
final RawDatagramSocket echo;
|
packetSize: 64,
|
||||||
try {
|
echoToken: '',
|
||||||
echo = await RawDatagramSocket.bind(InternetAddress.loopbackIPv6, port);
|
dnsName: '',
|
||||||
} on SocketException {
|
payloadHex: '',
|
||||||
markTestSkipped('IPv6 loopback is not available');
|
expectHex: '',
|
||||||
return;
|
),
|
||||||
}
|
count: 1,
|
||||||
addTearDown(echo.close);
|
);
|
||||||
echo.listen((event) {
|
expect(javaSample.single.status, Outcome.ok);
|
||||||
if (event != RawSocketEvent.read) {
|
expect(javaSample.single.detail['motd'], 'Hello');
|
||||||
|
expect(javaSample.single.rttMs, greaterThan(0));
|
||||||
|
expect(javaSample.single.summary.failurePct, 0);
|
||||||
|
|
||||||
|
final bedrock = await _bedrockServer();
|
||||||
|
addTearDown(bedrock.close);
|
||||||
|
final bedrockSample = await _collect(
|
||||||
|
ProbeRequest(
|
||||||
|
host: '127.0.0.1',
|
||||||
|
port: bedrock.port,
|
||||||
|
profileId: 'minecraft-bedrock',
|
||||||
|
interval: const Duration(milliseconds: 200),
|
||||||
|
timeout: const Duration(milliseconds: 800),
|
||||||
|
packetSize: 64,
|
||||||
|
echoToken: '',
|
||||||
|
dnsName: '',
|
||||||
|
payloadHex: '',
|
||||||
|
expectHex: '',
|
||||||
|
),
|
||||||
|
count: 1,
|
||||||
|
);
|
||||||
|
expect(bedrockSample.single.status, Outcome.ok);
|
||||||
|
expect(bedrockSample.single.detail['motd'], 'Bed');
|
||||||
|
|
||||||
|
final node = await _node();
|
||||||
|
addTearDown(node.kill);
|
||||||
|
final samples = <ProbeSample>[];
|
||||||
|
final remote = RemoteProbe();
|
||||||
|
final done = Completer<void>();
|
||||||
|
unawaited(() async {
|
||||||
|
try {
|
||||||
|
await remote.run(
|
||||||
|
baseUrl: 'http://127.0.0.1:${node.control}',
|
||||||
|
nodeToken: '',
|
||||||
|
body: ProbeBody(
|
||||||
|
target: '127.0.0.1',
|
||||||
|
port: node.udp,
|
||||||
|
profile: 'nq-udp',
|
||||||
|
intervalMs: 200,
|
||||||
|
timeoutMs: 800,
|
||||||
|
durationSec: 3,
|
||||||
|
packetSize: 80,
|
||||||
|
echoToken: '',
|
||||||
|
dnsName: '',
|
||||||
|
payloadHex: '',
|
||||||
|
expectHex: '',
|
||||||
|
),
|
||||||
|
onSample: (sample) {
|
||||||
|
samples.add(sample);
|
||||||
|
if (samples.length == 1 && !done.isCompleted) {
|
||||||
|
done.complete();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
cancelled: () => done.isCompleted,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
if (!done.isCompleted) {
|
||||||
|
done.complete();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}());
|
||||||
|
await done.future.timeout(const Duration(seconds: 5));
|
||||||
|
await remote.stop('');
|
||||||
|
expect(samples, isNotEmpty);
|
||||||
|
expect(samples.first.status, Outcome.ok);
|
||||||
|
expect(samples.first.rttMs, greaterThan(0));
|
||||||
|
expect(samples.first.summary.probeLossPct, 0);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test(
|
||||||
|
'a silent candidate is not a measured miss once another address answers',
|
||||||
|
() async {
|
||||||
|
final drop = await RawDatagramSocket.bind(
|
||||||
|
InternetAddress.loopbackIPv4,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
addTearDown(drop.close);
|
||||||
|
final port = drop.port;
|
||||||
|
drop.listen((event) {
|
||||||
|
if (event == RawSocketEvent.read) {
|
||||||
|
drop.receive();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
final RawDatagramSocket echo;
|
||||||
|
try {
|
||||||
|
echo = await RawDatagramSocket.bind(InternetAddress.loopbackIPv6, port);
|
||||||
|
} on SocketException {
|
||||||
|
markTestSkipped('IPv6 loopback is not available');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
final datagram = echo.receive();
|
addTearDown(echo.close);
|
||||||
if (datagram == null) {
|
echo.listen((event) {
|
||||||
return;
|
if (event != RawSocketEvent.read) {
|
||||||
}
|
return;
|
||||||
echo.send(datagram.data, datagram.address, datagram.port);
|
}
|
||||||
});
|
final datagram = echo.receive();
|
||||||
|
if (datagram == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
echo.send(datagram.data, datagram.address, datagram.port);
|
||||||
|
});
|
||||||
|
|
||||||
final seen = <String>[];
|
final seen = <String>[];
|
||||||
final samples = await _collect(
|
final samples = await _collect(
|
||||||
ProbeRequest(
|
ProbeRequest(
|
||||||
host: 'example.test',
|
host: 'example.test',
|
||||||
port: port,
|
port: port,
|
||||||
profileId: 'udp-generic',
|
profileId: 'udp-generic',
|
||||||
interval: const Duration(milliseconds: 40),
|
interval: const Duration(milliseconds: 40),
|
||||||
timeout: const Duration(milliseconds: 250),
|
timeout: const Duration(milliseconds: 250),
|
||||||
packetSize: 16,
|
packetSize: 16,
|
||||||
echoToken: '',
|
echoToken: '',
|
||||||
dnsName: '',
|
dnsName: '',
|
||||||
payloadHex: '',
|
payloadHex: '',
|
||||||
expectHex: '',
|
expectHex: '',
|
||||||
),
|
),
|
||||||
count: 2,
|
count: 2,
|
||||||
loop: ProbeLoop(
|
loop: ProbeLoop(
|
||||||
lookup: (host) async {
|
lookup: (host) async {
|
||||||
expect(host, 'example.test');
|
expect(host, 'example.test');
|
||||||
return [InternetAddress('127.0.0.1'), InternetAddress('::1')];
|
return [InternetAddress('127.0.0.1'), InternetAddress('::1')];
|
||||||
},
|
},
|
||||||
onEndpoint: (address) => seen.add(address.address),
|
onEndpoint: (address) => seen.add(address.address),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
expect(samples.first.status, Outcome.unknown);
|
expect(samples.first.status, Outcome.ok);
|
||||||
expect(samples.first.detail['address'], '127.0.0.1');
|
expect(samples.first.detail['address'], '::1');
|
||||||
expect(samples.last.status, Outcome.ok);
|
expect(samples.first.detail['family'], 'IPv6');
|
||||||
expect(samples.last.detail['address'], '::1');
|
expect(samples.first.detail['fallback'], contains('127.0.0.1'));
|
||||||
expect(seen, ['127.0.0.1', '::1']);
|
expect(samples.first.detail['fallback'], contains('没有计入'));
|
||||||
});
|
expect(samples.first.summary.sent, 1);
|
||||||
|
expect(samples.first.summary.unknown, 0);
|
||||||
|
expect(samples.first.summary.selectionSkipped, 1);
|
||||||
|
expect(samples.first.summary.unknownPct, 0);
|
||||||
|
expect(samples.last.status, Outcome.ok);
|
||||||
|
expect(samples.last.detail['address'], '::1');
|
||||||
|
expect(samples.last.summary.unknown, 0);
|
||||||
|
expect(seen, ['127.0.0.1', '::1']);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
test('a responding address is not replaced while it still answers', () async {
|
test('a responding address is not replaced while it still answers', () async {
|
||||||
final echo = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
|
final echo = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
|
||||||
@@ -293,7 +316,10 @@ void main() {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
expect(samples.map((sample) => sample.status), everyElement(Outcome.ok));
|
expect(samples.map((sample) => sample.status), everyElement(Outcome.ok));
|
||||||
expect(samples.map((sample) => sample.detail['address']), everyElement('127.0.0.1'));
|
expect(
|
||||||
|
samples.map((sample) => sample.detail['address']),
|
||||||
|
everyElement('127.0.0.1'),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -337,7 +363,8 @@ Future<({Process process, int tcp, int udp})> _reflector() async {
|
|||||||
return (process: process, tcp: tcp, udp: udp);
|
return (process: process, tcp: tcp, udp: udp);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<({Process process, int control, int udp, void Function() kill})> _node() async {
|
Future<({Process process, int control, int udp, void Function() kill})>
|
||||||
|
_node() async {
|
||||||
final udp = await _freeUdp();
|
final udp = await _freeUdp();
|
||||||
final control = await _freeTcp();
|
final control = await _freeTcp();
|
||||||
final process = await Process.start(binary, [
|
final process = await Process.start(binary, [
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:netquality/metrics/sample_book.dart';
|
||||||
|
import 'package:netquality/metrics/selection_ledger.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
const v6 = Outcome(
|
||||||
|
status: Outcome.timeout,
|
||||||
|
kind: Outcome.probe,
|
||||||
|
note: '未收到回显',
|
||||||
|
detail: {'address': '2001:db8::1', 'family': 'IPv6'},
|
||||||
|
);
|
||||||
|
const v4ok = Outcome(
|
||||||
|
status: Outcome.ok,
|
||||||
|
kind: Outcome.probe,
|
||||||
|
rttMs: 5,
|
||||||
|
note: '收到回显',
|
||||||
|
detail: {'address': '203.0.113.5', 'family': 'IPv4'},
|
||||||
|
);
|
||||||
|
const v4timeout = Outcome(
|
||||||
|
status: Outcome.timeout,
|
||||||
|
kind: Outcome.probe,
|
||||||
|
note: '未收到回显',
|
||||||
|
detail: {'address': '203.0.113.5', 'family': 'IPv4'},
|
||||||
|
);
|
||||||
|
|
||||||
|
test('ipv6 miss then ipv4 success is not formal loss', () {
|
||||||
|
final ledger = SelectionLedger(2);
|
||||||
|
expect(ledger.take(v6, responded: false).commit, isEmpty);
|
||||||
|
final decision = ledger.take(v4ok, responded: true);
|
||||||
|
expect(decision.skipped, 1);
|
||||||
|
expect(decision.commit.single.selectionSkipped, 1);
|
||||||
|
expect(decision.commit.single.detail['fallback'], contains('2001:db8::1'));
|
||||||
|
expect(decision.commit.single.detail['fallback'], contains('203.0.113.5'));
|
||||||
|
expect(decision.commit.single.detail['fallback'], contains('没有计入'));
|
||||||
|
final book = SampleBook('nq-udp');
|
||||||
|
book.add(decision.commit.single);
|
||||||
|
final summary = book.summary();
|
||||||
|
expect(summary.sent, 1);
|
||||||
|
expect(summary.ok, 1);
|
||||||
|
expect(summary.timeout, 0);
|
||||||
|
expect(summary.probeLossPct, 0);
|
||||||
|
expect(summary.selectionSkipped, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('every candidate failing is loss, not a false zero', () {
|
||||||
|
final ledger = SelectionLedger(2);
|
||||||
|
expect(ledger.take(v6, responded: false).commit, isEmpty);
|
||||||
|
final decision = ledger.take(v4timeout, responded: false);
|
||||||
|
expect(decision.commit, hasLength(2));
|
||||||
|
final book = SampleBook('nq-udp');
|
||||||
|
for (final outcome in decision.commit) {
|
||||||
|
book.add(outcome);
|
||||||
|
}
|
||||||
|
final summary = book.summary();
|
||||||
|
expect(summary.ok, 0);
|
||||||
|
expect(summary.sent, 2);
|
||||||
|
expect(summary.timeout, 2);
|
||||||
|
expect(summary.probeLossPct, 100);
|
||||||
|
expect(summary.selectionSkipped, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('timeouts after an address is selected still count', () {
|
||||||
|
final ledger = SelectionLedger(2);
|
||||||
|
final first = ledger.take(v4ok, responded: true);
|
||||||
|
expect(ledger.measuring, isTrue);
|
||||||
|
final again = ledger.take(v4timeout, responded: false);
|
||||||
|
expect(again.commit, hasLength(1));
|
||||||
|
final book = SampleBook('nq-udp');
|
||||||
|
book.add(first.commit.single);
|
||||||
|
book.add(again.commit.single);
|
||||||
|
expect(book.summary().probeLossPct, 50);
|
||||||
|
expect(book.summary().sent, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('one address never hides a failure', () {
|
||||||
|
final ledger = SelectionLedger(1);
|
||||||
|
final decision = ledger.take(v4timeout, responded: false);
|
||||||
|
expect(decision.commit, hasLength(1));
|
||||||
|
final book = SampleBook('nq-tcp');
|
||||||
|
book.add(decision.commit.single);
|
||||||
|
expect(book.summary().probeLossPct, 100);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a stopped in-flight attempt is not recorded', () {
|
||||||
|
expect(
|
||||||
|
countsAfterStop(
|
||||||
|
const Outcome(
|
||||||
|
status: Outcome.timeout,
|
||||||
|
kind: Outcome.probe,
|
||||||
|
note: '已停止',
|
||||||
|
),
|
||||||
|
cancelled: false,
|
||||||
|
),
|
||||||
|
isFalse,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
countsAfterStop(
|
||||||
|
const Outcome(status: Outcome.timeout, kind: Outcome.probe),
|
||||||
|
cancelled: true,
|
||||||
|
),
|
||||||
|
isFalse,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
countsAfterStop(
|
||||||
|
const Outcome(status: Outcome.ok, kind: Outcome.probe, rttMs: 1),
|
||||||
|
cancelled: false,
|
||||||
|
),
|
||||||
|
isTrue,
|
||||||
|
);
|
||||||
|
expect(countsAfterStop(null, cancelled: false), isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test(
|
||||||
|
'leaving a measured address does not drop the failure that caused it',
|
||||||
|
() {
|
||||||
|
final ledger = SelectionLedger(2);
|
||||||
|
ledger.take(v4ok, responded: true);
|
||||||
|
final miss = ledger.take(v4timeout, responded: false);
|
||||||
|
expect(miss.commit, hasLength(1));
|
||||||
|
ledger.endMeasurement();
|
||||||
|
expect(ledger.measuring, isFalse);
|
||||||
|
final held = ledger.take(v6, responded: false);
|
||||||
|
expect(held.commit, isEmpty);
|
||||||
|
final recovered = ledger.take(v4ok, responded: true);
|
||||||
|
expect(recovered.skipped, 1);
|
||||||
|
final book = SampleBook('nq-udp');
|
||||||
|
book.add(v4ok);
|
||||||
|
book.add(miss.commit.single);
|
||||||
|
book.add(recovered.commit.single);
|
||||||
|
expect(book.summary().sent, 3);
|
||||||
|
expect(book.summary().timeout, 1);
|
||||||
|
expect(book.summary().probeLossPct, closeTo(100 / 3, 0.0001));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
import 'package:netquality/main.dart';
|
import 'package:netquality/main.dart';
|
||||||
@@ -27,7 +29,9 @@ void main() {
|
|||||||
const config = SessionConfig(
|
const config = SessionConfig(
|
||||||
remote: true,
|
remote: true,
|
||||||
nodeId: 'n1',
|
nodeId: 'n1',
|
||||||
nodes: [RemoteNode(id: 'n1', name: '机房', baseUrl: 'https://probe.example:8443')],
|
nodes: [
|
||||||
|
RemoteNode(id: 'n1', name: '机房', baseUrl: 'https://probe.example:8443'),
|
||||||
|
],
|
||||||
host: '203.0.113.8',
|
host: '203.0.113.8',
|
||||||
port: 25565,
|
port: 25565,
|
||||||
profileId: 'minecraft-java',
|
profileId: 'minecraft-java',
|
||||||
@@ -47,4 +51,115 @@ void main() {
|
|||||||
expect(again.toJson().containsKey('nodeToken'), isFalse);
|
expect(again.toJson().containsKey('nodeToken'), isFalse);
|
||||||
expect(SessionConfig.defaults.validate(), isNull);
|
expect(SessionConfig.defaults.validate(), isNull);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
testWidgets(
|
||||||
|
'profile default port updates until the user types another port',
|
||||||
|
(tester) async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
tester.view.physicalSize = const Size(1280, 1600);
|
||||||
|
tester.view.devicePixelRatio = 1;
|
||||||
|
addTearDown(tester.view.resetPhysicalSize);
|
||||||
|
addTearDown(tester.view.resetDevicePixelRatio);
|
||||||
|
await tester.pumpWidget(const NetQualityApp());
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.text('合作反射 TCP 默认 19090'), findsOneWidget);
|
||||||
|
await tester.ensureVisible(find.byKey(const Key('profile')));
|
||||||
|
await tester.tap(find.byKey(const Key('profile')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.text('合作反射 UDP').last);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('19091'), findsWidgets);
|
||||||
|
expect(find.text('合作反射 UDP 默认 19091'), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.enterText(find.byKey(const Key('port-field')), '25565');
|
||||||
|
await tester.tap(find.byKey(const Key('profile')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.text('合作反射 TCP').last);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('25565'), findsOneWidget);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
testWidgets('editing a node keeps its id and does not reveal the token', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
tester.view.physicalSize = const Size(1280, 1600);
|
||||||
|
tester.view.devicePixelRatio = 1;
|
||||||
|
addTearDown(tester.view.resetPhysicalSize);
|
||||||
|
addTearDown(tester.view.resetDevicePixelRatio);
|
||||||
|
await tester.pumpWidget(const NetQualityApp());
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.text('远程节点').first);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.text('管理节点'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.enterText(find.byKey(const Key('node-name')), '机房');
|
||||||
|
await tester.enterText(
|
||||||
|
find.byKey(const Key('node-url')),
|
||||||
|
'http://127.0.0.1:8443',
|
||||||
|
);
|
||||||
|
await tester.enterText(find.byKey(const Key('node-token')), 'saved-secret');
|
||||||
|
await tester.tap(find.byKey(const Key('node-save')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.text('编辑'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
final token = tester.widget<TextField>(find.byKey(const Key('node-token')));
|
||||||
|
expect(token.controller?.text, isEmpty);
|
||||||
|
expect(find.text('saved-secret'), findsNothing);
|
||||||
|
await tester.enterText(find.byKey(const Key('node-name')), '机房乙');
|
||||||
|
await tester.tap(find.text('保存修改'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.textContaining('机房乙'), findsWidgets);
|
||||||
|
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final raw = prefs.getString('netquality.settings.v2') ?? '';
|
||||||
|
expect(raw, contains('机房乙'));
|
||||||
|
expect(raw, isNot(contains('saved-secret')));
|
||||||
|
final decoded = jsonDecode(raw) as Map<String, dynamic>;
|
||||||
|
final nodes = decoded['nodes'] as List<dynamic>;
|
||||||
|
expect(nodes, hasLength(1));
|
||||||
|
final node = nodes.single as Map<String, dynamic>;
|
||||||
|
expect(node['name'], '机房乙');
|
||||||
|
expect(node['baseUrl'], 'http://127.0.0.1:8443');
|
||||||
|
expect(decoded['nodeId'], node['id']);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('guide and history screens use the real versions', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
tester.view.physicalSize = const Size(900, 1400);
|
||||||
|
tester.view.devicePixelRatio = 1;
|
||||||
|
addTearDown(tester.view.resetPhysicalSize);
|
||||||
|
addTearDown(tester.view.resetDevicePixelRatio);
|
||||||
|
await tester.pumpWidget(const NetQualityApp());
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.byType(PopupMenuButton<String>));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.text('指标说明'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.textContaining('没有协议应答'), findsWidgets);
|
||||||
|
await tester.scrollUntilVisible(find.text('选址失败和正式丢包'), 200);
|
||||||
|
expect(find.text('选址失败和正式丢包'), findsOneWidget);
|
||||||
|
await tester.scrollUntilVisible(find.textContaining('RFC 3550'), 200);
|
||||||
|
expect(find.textContaining('RFC 3550'), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.pageBack();
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.byType(PopupMenuButton<String>));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.text('更新历史'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('网络质量探测 1.1.2'), findsOneWidget);
|
||||||
|
await tester.scrollUntilVisible(find.text('网络质量探测 1.1.1'), 200);
|
||||||
|
expect(find.text('网络质量探测 1.1.1'), findsOneWidget);
|
||||||
|
expect(find.textContaining('言灸'), findsOneWidget);
|
||||||
|
expect(find.textContaining('v1.1.1'), findsWidgets);
|
||||||
|
expect(find.text('网络质量探测 1.1.0'), findsNothing);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
+3
-1
@@ -44,7 +44,9 @@
|
|||||||
- **普通 TCP**:只记录连接耗时、成功或失败、连续失败。没有自定义帧。
|
- **普通 TCP**:只记录连接耗时、成功或失败、连续失败。没有自定义帧。
|
||||||
- **普通 UDP、DNS、自定义 UDP、基岩版**:没有收到符合协议的包时记为无应答/未知,不叫丢包。内容不对记为协议错误。
|
- **普通 UDP、DNS、自定义 UDP、基岩版**:没有收到符合协议的包时记为无应答/未知,不叫丢包。内容不对记为协议错误。
|
||||||
- **Minecraft Java**:状态握手加上 ping/pong。往返时间只算 ping 到对上 nonce 的 pong。连不上或协议不对记为失败率。
|
- **Minecraft Java**:状态握手加上 ping/pong。往返时间只算 ping 到对上 nonce 的 pong。连不上或协议不对记为失败率。
|
||||||
- **抖动**:RFC 3550。相邻两次成功的往返时间差 `D`,`J = J + (|D| - J) / 16`。
|
- **抖动**:RFC 3550。相邻两次成功的往返时间差 `D`,`J = J + (|D| - J) / 16`。第一次成功时 J 为 0。
|
||||||
|
- **延迟分布**:只统计成功样本。当前延迟是最近一次成功。最小、最大是极值。平均是算术平均。中位数在奇数个时取排序后的中间值,偶数个时取中间两个的平均。P95 用最近秩,秩 = ceil(0.95 × 次数),用整数 `(95 × 次数 + 99) / 100` 计算,从 1 起计。
|
||||||
|
- **选址**:一个名字解析出多个地址时,还没有任何地址应答之前的失败只用于挑选地址。后面有地址成功时,这些失败不进入已发送、超时和丢包,并在 `detail.fallback` 里说明。选定之后的失败照常计入。每个候选都失败时,这些失败计入正式结果,不能显示成 0% 成功。每条样本的 `detail.address` 和 `detail.family` 是这次实际连通或发包的地址;没有这个字段就表示节点没有报告,不能用解析结果代替。`summary` 另有 `minRttMs`、`meanRttMs`、`medianRttMs`、`p95RttMs`、`maxRttMs` 和 `selectionSkipped`。旧客户端会忽略不认识的字段。
|
||||||
|
|
||||||
## 控制接口
|
## 控制接口
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# 网络质量探测 1.1.2
|
||||||
|
|
||||||
|
构建号 5。署名:言灸。许可:GNU Affero General Public License v3.0(AGPL-3.0-only)。
|
||||||
|
|
||||||
|
这一版还没有打 Git 标签,也还没有发布安装包。下面是准备发布的说明。
|
||||||
|
|
||||||
|
## 节点和端口
|
||||||
|
|
||||||
|
- 已有远程节点可以改名称、控制地址和口令。节点编号和当前选择保持不变。
|
||||||
|
- 修改时口令留空表示继续使用已经保存在本机的口令。界面不会把原口令填出来。填写新口令才会替换。
|
||||||
|
- 端口框标明当前探测类型的默认端口。合作反射 TCP 默认 19090,合作反射 UDP 默认 19091。
|
||||||
|
- 只有端口仍是上一种类型的默认值,或者端口是空的,切换类型才会自动更换。自己填过的端口会留下。
|
||||||
|
|
||||||
|
## 实际地址
|
||||||
|
|
||||||
|
- 本机和 1.1.2 节点都会显示这次真正连通或真正发包的 IP,并注明 IPv4 或 IPv6。
|
||||||
|
- 域名解析出的地址单独标成「解析到」,不会被说成已经使用的地址。
|
||||||
|
- 1.1.2 之前的远程节点不会在结果里带地址。界面会写「节点没有报告实际使用的地址」,不会在手机上另做一次解析来冒充。
|
||||||
|
|
||||||
|
## 选址和丢包
|
||||||
|
|
||||||
|
- 还没有任何地址应答时,用来挑选地址的失败(例如 IPv6 没有应答,随后 IPv4 成功)不计入已发送、超时和正式丢包,并单独说明回退。
|
||||||
|
- 某个地址已经应答之后,对它的超时和失败仍然计入,不会因为后来又换地址而被抹掉。
|
||||||
|
- 只有一个地址时,失败从一开始就算正式结果。
|
||||||
|
- 每一个候选都失败时,这些失败计入正式结果。不会显示 0% 成功。
|
||||||
|
- 1.1.1 的节点仍可能把第一次选址失败算进统计。要分开看,节点也需要这一版。
|
||||||
|
|
||||||
|
## 指标和停止
|
||||||
|
|
||||||
|
- 结果给出已发送、已收到、超时、比率、当前/最小/平均/中位/P95/最大延迟、抖动和用时。
|
||||||
|
- 探测无应答 = 超时 ÷(超时 + 成功)。分母只含已经写出的回显尝试。分母为 0 时显示 —,不是 0%。
|
||||||
|
- 普通 TCP 和 Minecraft Java 显示失败率,不显示丢包百分比。
|
||||||
|
- 普通 UDP、DNS、自定义 UDP 和基岩版把沉默记为无应答。UDP 没有应答不能当成已经证实的丢包。
|
||||||
|
- 延迟分布只统计成功样本。P95 用最近秩,秩 = ceil(0.95 × 次数)。抖动沿用 RFC 3550。
|
||||||
|
- 手动停止后保留曲线,并给出开始、结束、用时、目标、来源、实际地址和同一套最终指标。
|
||||||
|
- 停止时还没完成的请求不计入丢包。
|
||||||
|
- 点曲线可以钉住该时刻的延迟和比率,松手后仍然保留。再点另一点会更换。新的一次探测,或该点滚出窗口后,选择不会跳到别的点上。
|
||||||
|
|
||||||
|
应用里增加了「指标说明」和「更新历史」。更新历史只列出仓库里真实存在的标签 v1.1.1,以及这一版。
|
||||||
+22
-14
@@ -31,7 +31,7 @@ go build -o netquality-reflector .
|
|||||||
- TCP `0.0.0.0:19090`
|
- TCP `0.0.0.0:19090`
|
||||||
- UDP `0.0.0.0:19091`
|
- UDP `0.0.0.0:19091`
|
||||||
|
|
||||||
看到两行 `listening` 就说明起来了。另开一个终端可以看端口:
|
同一目录里有 `.env`。不传参数时,程序会读它。启动后会打一行「生效配置」,口令只显示有没有设置,不会把口令打出来。看到 `listening` 就说明起来了。另开一个终端可以看端口:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
ss -ltnp | grep 19090
|
ss -ltnp | grep 19090
|
||||||
@@ -40,7 +40,11 @@ ss -lunp | grep 19091
|
|||||||
|
|
||||||
用 `Ctrl+C` 停止。确认客户端能连上之后,再做成开机自启。
|
用 `Ctrl+C` 停止。确认客户端能连上之后,再做成开机自启。
|
||||||
|
|
||||||
常用参数:
|
平常改 `.env` 就行,不必记命令行参数。文件里每一项都有中文注释,默认值就是下面这些端口。程序所在目录和当前目录都会找 `.env`;找不到不算错误。指定别的文件用 `-env /路径/.env`,这个文件必须存在。
|
||||||
|
|
||||||
|
优先级:命令行参数 > 环境变量 > `.env` > 内置默认值。
|
||||||
|
|
||||||
|
仍可以用参数临时覆盖 `.env`:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
./netquality-reflector -bind 0.0.0.0 -tcp-port 19090 -udp-port 19091
|
./netquality-reflector -bind 0.0.0.0 -tcp-port 19090 -udp-port 19091
|
||||||
@@ -49,33 +53,37 @@ ss -lunp | grep 19091
|
|||||||
./netquality-reflector -h
|
./netquality-reflector -h
|
||||||
```
|
```
|
||||||
|
|
||||||
也可以用环境变量:`NQ_BIND`、`NQ_TCP_PORT`、`NQ_UDP_PORT`、`NQ_TOKEN`(回显口令)、`NQ_MODE`、`NQ_CONTROL_ADDR`、`NQ_NODE_TOKEN`(节点口令)、`NQ_ALLOW_PRIVATE`、`NQ_TLS_CERT`、`NQ_TLS_KEY`。
|
对应的环境变量和 `.env` 键:`NQ_BIND`、`NQ_TCP_PORT`、`NQ_UDP_PORT`、`NQ_TOKEN`(回显口令)、`NQ_MODE`、`NQ_CONTROL_ADDR`、`NQ_NODE_TOKEN`(节点口令)、`NQ_ALLOW_PRIVATE`、`NQ_ALLOW_NETS`、`NQ_TLS_CERT`、`NQ_TLS_KEY`、`NQ_VERBOSE`。
|
||||||
|
|
||||||
|
给别人直接运行的说明在 [server/README.md](../server/README.md)。`.env` 和 `.env.example` 内容相同,都是默认可运行的配置。
|
||||||
|
|
||||||
## 3. 做成系统服务
|
## 3. 做成系统服务
|
||||||
|
|
||||||
|
发布包解压后,程序和 `.env` 已经在一起。装到 `/opt/netquality`:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd /opt/netquality/server
|
sudo mkdir -p /opt/netquality
|
||||||
go build -o netquality-reflector .
|
sudo tar -C /opt/netquality --strip-components=1 -xzf netquality-server-1.1.2-linux-amd64.tar.gz
|
||||||
sudo install -m 0755 netquality-reflector /usr/local/bin/netquality-reflector
|
sudo cp /opt/netquality/netquality.service /etc/systemd/system/netquality.service
|
||||||
sudo cp deploy/netquality-reflector.service /etc/systemd/system/netquality-reflector.service
|
|
||||||
sudo systemctl daemon-reload
|
sudo systemctl daemon-reload
|
||||||
sudo systemctl enable --now netquality-reflector
|
sudo systemctl enable --now netquality
|
||||||
sudo systemctl status netquality-reflector
|
sudo systemctl status netquality
|
||||||
```
|
```
|
||||||
|
|
||||||
|
从源码编译时,把二进制和 `.env` 放在同一目录,服务文件用 `deploy/netquality.service`(或 `deploy/netquality-reflector.service`)。两份都不再在 `ExecStart` 里写端口,避免盖过 `.env`。
|
||||||
|
|
||||||
日志:
|
日志:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
journalctl -u netquality-reflector -f
|
journalctl -u netquality -f
|
||||||
```
|
```
|
||||||
|
|
||||||
大约每分钟会打一行统计:收到多少请求、回了多少、拒绝了多少。
|
大约每分钟会打一行统计:收到多少请求、回了多少、拒绝了多少。
|
||||||
|
|
||||||
要加口令时,编辑服务文件,去掉 `NQ_TOKEN` 那一行的注释并写成你自己的口令,然后:
|
要加口令时,编辑 `/opt/netquality/.env` 里的 `NQ_TOKEN`,保存后:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo systemctl daemon-reload
|
sudo systemctl restart netquality
|
||||||
sudo systemctl restart netquality-reflector
|
|
||||||
```
|
```
|
||||||
|
|
||||||
App 里的「口令」必须和这里完全一致。口令是明文写在探测包里的,只能挡住无关的随机访问,不能当密码学上的加密。
|
App 里的「口令」必须和这里完全一致。口令是明文写在探测包里的,只能挡住无关的随机访问,不能当密码学上的加密。
|
||||||
@@ -136,7 +144,7 @@ sudo firewall-cmd --reload
|
|||||||
|
|
||||||
`-token` 是另一回事,它写进反射帧,只在别人来连你的 19090/19091 时使用。App 里对应「目标回显口令」。节点口令对应「管理节点」里的那一栏。
|
`-token` 是另一回事,它写进反射帧,只在别人来连你的 19090/19091 时使用。App 里对应「目标回显口令」。节点口令对应「管理节点」里的那一栏。
|
||||||
|
|
||||||
要开机启动节点,可以用 `deploy/netquality-node.service`。编辑里面的环境变量注释,再:
|
要开机启动节点,把 `.env` 里的 `NQ_MODE` 改成 `node` 或 `both`,用上面的 `netquality.service` 即可。`deploy/netquality-node.service` 会额外设置 `NQ_MODE=both`,从而盖过 `.env` 里的模式;端口和口令仍然来自 `.env`。不要和反射服务同时启用。
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo cp deploy/netquality-node.service /etc/systemd/system/netquality-node.service
|
sudo cp deploy/netquality-node.service /etc/systemd/system/netquality-node.service
|
||||||
|
|||||||
+60
@@ -0,0 +1,60 @@
|
|||||||
|
# 网络质量探测节点配置
|
||||||
|
# 用记事本或普通文本编辑器修改本文件,保存后重新运行程序才会生效。
|
||||||
|
# 以 # 开头的行是注释。某一项不写时,使用程序内置的默认值。
|
||||||
|
# 优先级:命令行参数 > 系统环境变量 > 本文件 > 内置默认值。
|
||||||
|
# 本文件不存在也不会报错,程序会按内置默认值启动。
|
||||||
|
# 下面这些值就是内置默认值,不改也能和以前的客户端配合使用。
|
||||||
|
|
||||||
|
# 反射服务监听哪块网卡。
|
||||||
|
# 0.0.0.0 表示本机所有网卡,同一局域网或公网可以连过来。
|
||||||
|
# 只在这台电脑上自己试,改成 127.0.0.1。
|
||||||
|
NQ_BIND=0.0.0.0
|
||||||
|
|
||||||
|
# TCP 反射端口。手机里「合作反射 TCP」要填同一个数字。
|
||||||
|
# 填 0 表示关闭 TCP。
|
||||||
|
NQ_TCP_PORT=19090
|
||||||
|
|
||||||
|
# UDP 反射端口。手机里「合作反射 UDP」要填同一个数字。
|
||||||
|
# 填 0 表示关闭 UDP。
|
||||||
|
NQ_UDP_PORT=19091
|
||||||
|
|
||||||
|
# 回显口令。它会写进探测包,用来挡住无关的访问,不是加密。
|
||||||
|
# 留空表示不检查口令,谁都能让本机把探测包送回去。
|
||||||
|
# 最长 32 字节(一般就是 32 个英文字符)。手机里对应「目标回显口令」。
|
||||||
|
# 这和下面的节点口令不是同一个东西。
|
||||||
|
NQ_TOKEN=
|
||||||
|
|
||||||
|
# 工作模式,三选一:
|
||||||
|
# reflector 只做反射:把收到的探测包原样送回去。这是默认。
|
||||||
|
# node 只做检测节点:按手机的指令去测别的地址。
|
||||||
|
# both 反射和节点一起开。
|
||||||
|
NQ_MODE=reflector
|
||||||
|
|
||||||
|
# 节点控制地址。手机「管理节点」里填的就是这个地址。
|
||||||
|
# 默认 127.0.0.1 只允许本机连接,外网连不上,这样更安全。
|
||||||
|
# 要让手机来用,改成 0.0.0.0:8443,并尽量放在 HTTPS 反向代理后面。
|
||||||
|
NQ_CONTROL_ADDR=127.0.0.1:8443
|
||||||
|
|
||||||
|
# 节点口令。留空表示公开节点:谁能连上控制端口,谁就能在上限内发起探测。
|
||||||
|
# 写上口令以后,手机「管理节点」里必须填同一个口令,否则不会向目标发包。
|
||||||
|
# 不要把真实口令发到聊天里,也不要提交到仓库。
|
||||||
|
NQ_NODE_TOKEN=
|
||||||
|
|
||||||
|
# 是否允许节点去测本机和局域网地址。只能写 true 或 false。
|
||||||
|
# 云服务器的元数据地址(例如 169.254.169.254)始终禁止,改成 true 也不会放行。
|
||||||
|
# 平常保持 false。只有故意测机房内网时才改成 true。
|
||||||
|
NQ_ALLOW_PRIVATE=false
|
||||||
|
|
||||||
|
# 额外允许探测的网段,用英文逗号分隔。
|
||||||
|
# 例如 10.1.2.0/24,192.168.1.10
|
||||||
|
# 留空表示没有额外放行。
|
||||||
|
NQ_ALLOW_NETS=
|
||||||
|
|
||||||
|
# 控制端口自己的 HTTPS 证书和私钥。两个都填才启用 TLS,只填一个会启动失败。
|
||||||
|
# 留空则使用明文 HTTP。不要把明文的控制端口直接暴露到公网。
|
||||||
|
NQ_TLS_CERT=
|
||||||
|
NQ_TLS_KEY=
|
||||||
|
|
||||||
|
# 是否把每一个收发的包都写进日志。只能写 true 或 false。
|
||||||
|
# 平常保持 false。排查问题时再改成 true。
|
||||||
|
NQ_VERBOSE=false
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
# 网络质量探测节点配置
|
||||||
|
# 用记事本或普通文本编辑器修改本文件,保存后重新运行程序才会生效。
|
||||||
|
# 以 # 开头的行是注释。某一项不写时,使用程序内置的默认值。
|
||||||
|
# 优先级:命令行参数 > 系统环境变量 > 本文件 > 内置默认值。
|
||||||
|
# 本文件不存在也不会报错,程序会按内置默认值启动。
|
||||||
|
# 下面这些值就是内置默认值,不改也能和以前的客户端配合使用。
|
||||||
|
|
||||||
|
# 反射服务监听哪块网卡。
|
||||||
|
# 0.0.0.0 表示本机所有网卡,同一局域网或公网可以连过来。
|
||||||
|
# 只在这台电脑上自己试,改成 127.0.0.1。
|
||||||
|
NQ_BIND=0.0.0.0
|
||||||
|
|
||||||
|
# TCP 反射端口。手机里「合作反射 TCP」要填同一个数字。
|
||||||
|
# 填 0 表示关闭 TCP。
|
||||||
|
NQ_TCP_PORT=19090
|
||||||
|
|
||||||
|
# UDP 反射端口。手机里「合作反射 UDP」要填同一个数字。
|
||||||
|
# 填 0 表示关闭 UDP。
|
||||||
|
NQ_UDP_PORT=19091
|
||||||
|
|
||||||
|
# 回显口令。它会写进探测包,用来挡住无关的访问,不是加密。
|
||||||
|
# 留空表示不检查口令,谁都能让本机把探测包送回去。
|
||||||
|
# 最长 32 字节(一般就是 32 个英文字符)。手机里对应「目标回显口令」。
|
||||||
|
# 这和下面的节点口令不是同一个东西。
|
||||||
|
NQ_TOKEN=
|
||||||
|
|
||||||
|
# 工作模式,三选一:
|
||||||
|
# reflector 只做反射:把收到的探测包原样送回去。这是默认。
|
||||||
|
# node 只做检测节点:按手机的指令去测别的地址。
|
||||||
|
# both 反射和节点一起开。
|
||||||
|
NQ_MODE=reflector
|
||||||
|
|
||||||
|
# 节点控制地址。手机「管理节点」里填的就是这个地址。
|
||||||
|
# 默认 127.0.0.1 只允许本机连接,外网连不上,这样更安全。
|
||||||
|
# 要让手机来用,改成 0.0.0.0:8443,并尽量放在 HTTPS 反向代理后面。
|
||||||
|
NQ_CONTROL_ADDR=127.0.0.1:8443
|
||||||
|
|
||||||
|
# 节点口令。留空表示公开节点:谁能连上控制端口,谁就能在上限内发起探测。
|
||||||
|
# 写上口令以后,手机「管理节点」里必须填同一个口令,否则不会向目标发包。
|
||||||
|
# 不要把真实口令发到聊天里,也不要提交到仓库。
|
||||||
|
NQ_NODE_TOKEN=
|
||||||
|
|
||||||
|
# 是否允许节点去测本机和局域网地址。只能写 true 或 false。
|
||||||
|
# 云服务器的元数据地址(例如 169.254.169.254)始终禁止,改成 true 也不会放行。
|
||||||
|
# 平常保持 false。只有故意测机房内网时才改成 true。
|
||||||
|
NQ_ALLOW_PRIVATE=false
|
||||||
|
|
||||||
|
# 额外允许探测的网段,用英文逗号分隔。
|
||||||
|
# 例如 10.1.2.0/24,192.168.1.10
|
||||||
|
# 留空表示没有额外放行。
|
||||||
|
NQ_ALLOW_NETS=
|
||||||
|
|
||||||
|
# 控制端口自己的 HTTPS 证书和私钥。两个都填才启用 TLS,只填一个会启动失败。
|
||||||
|
# 留空则使用明文 HTTP。不要把明文的控制端口直接暴露到公网。
|
||||||
|
NQ_TLS_CERT=
|
||||||
|
NQ_TLS_KEY=
|
||||||
|
|
||||||
|
# 是否把每一个收发的包都写进日志。只能写 true 或 false。
|
||||||
|
# 平常保持 false。排查问题时再改成 true。
|
||||||
|
NQ_VERBOSE=false
|
||||||
@@ -8,3 +8,4 @@ run: build
|
|||||||
|
|
||||||
test:
|
test:
|
||||||
go test ./...
|
go test ./...
|
||||||
|
go vet ./...
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
# 网络质量探测 · 检测节点
|
||||||
|
|
||||||
|
这是装在电脑或服务器上的小程序。手机上的 App 负责看结果,真正收发包的是这里。
|
||||||
|
|
||||||
|
它能做两件事,也可以一起做:
|
||||||
|
|
||||||
|
- **反射**:把探测包原样送回去。手机直接测到这台机器的延迟。
|
||||||
|
- **节点**:手机只下指令。这台机器替手机去测别的地址,例如游戏服务器。
|
||||||
|
|
||||||
|
压缩包里已经有一份能直接用的 `.env`,默认端口和以前一样:TCP `19090`、UDP `19091`。不改也能用。
|
||||||
|
|
||||||
|
## 三步启动
|
||||||
|
|
||||||
|
1. 解压整个压缩包,不要只把程序单独拷走。`.env` 要和程序放在同一个文件夹。
|
||||||
|
2. 用记事本(Windows)或任意文本编辑器打开 `.env`。每一项上面都有中文注释。改完保存。
|
||||||
|
3. 运行:
|
||||||
|
- Windows:双击 `start.bat`,不要关那个黑窗口。
|
||||||
|
- Linux:在解压出来的文件夹里打开终端,执行 `./netquality-reflector`。
|
||||||
|
|
||||||
|
程序启动后会打一行「生效配置」。口令只显示「已设置」或「未设置」,不会把口令本身打出来。看到 `listening` 就说明端口已经打开。
|
||||||
|
|
||||||
|
用 `Ctrl+C` 停止。Windows 上关闭黑窗口也会停。
|
||||||
|
|
||||||
|
## 配置写在哪里
|
||||||
|
|
||||||
|
程序启动时会读配置,优先级从高到低是:
|
||||||
|
|
||||||
|
1. 命令行参数,例如 `-tcp-port 19090`
|
||||||
|
2. 系统环境变量,例如 `NQ_TCP_PORT`
|
||||||
|
3. `.env` 文件
|
||||||
|
4. 程序内置的默认值
|
||||||
|
|
||||||
|
`.env` 会找两个地方:程序所在的文件夹,以及你当前打开的文件夹。两个路径不一样时,当前文件夹里的 `.env` 优先。文件不存在不算错误。
|
||||||
|
|
||||||
|
也可以指定别的文件:`./netquality-reflector -env /etc/netquality/.env`。这个文件必须存在,否则程序会退出。
|
||||||
|
|
||||||
|
`.env.example` 是同一份说明,给别人抄着用。真正生效的是 `.env`。
|
||||||
|
|
||||||
|
改完 `.env` 要重新运行程序。已经在跑的那一次不会自己重读。
|
||||||
|
|
||||||
|
## 每一项是什么
|
||||||
|
|
||||||
|
| 配置项 | 默认 | 作用 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `NQ_BIND` | `0.0.0.0` | 反射听哪块网卡。`0.0.0.0` 是全部网卡,`127.0.0.1` 是只给本机 |
|
||||||
|
| `NQ_TCP_PORT` | `19090` | TCP 反射端口。`0` 关闭 TCP |
|
||||||
|
| `NQ_UDP_PORT` | `19091` | UDP 反射端口。`0` 关闭 UDP |
|
||||||
|
| `NQ_TOKEN` | 空 | 回显口令。空表示不检查。最长 32 字节。对应手机里的「目标回显口令」 |
|
||||||
|
| `NQ_MODE` | `reflector` | `reflector` 只反射,`node` 只做节点,`both` 两个一起 |
|
||||||
|
| `NQ_CONTROL_ADDR` | `127.0.0.1:8443` | 节点控制地址。默认只有本机能连 |
|
||||||
|
| `NQ_NODE_TOKEN` | 空 | 节点口令。空表示公开节点。对应手机「管理节点」里的口令 |
|
||||||
|
| `NQ_ALLOW_PRIVATE` | `false` | `true` 才允许去测本机和局域网。云元数据地址始终禁止 |
|
||||||
|
| `NQ_ALLOW_NETS` | 空 | 额外允许的网段,逗号分隔,例如 `10.1.2.0/24` |
|
||||||
|
| `NQ_TLS_CERT` | 空 | 控制端口的证书。和私钥要同时填 |
|
||||||
|
| `NQ_TLS_KEY` | 空 | 控制端口的私钥 |
|
||||||
|
| `NQ_VERBOSE` | `false` | `true` 时每个包都写日志 |
|
||||||
|
|
||||||
|
回显口令 `NQ_TOKEN` 和节点口令 `NQ_NODE_TOKEN` 不是同一个。回显口令写在探测包里,只能挡住随便扫过来的访问,不能当加密。设了口令以后,把 `.env` 的权限收紧,别让别人读到:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
chmod 600 .env
|
||||||
|
```
|
||||||
|
|
||||||
|
## 在手机里怎么填
|
||||||
|
|
||||||
|
测这台机器自己(反射):
|
||||||
|
|
||||||
|
- 来源选「本机」
|
||||||
|
- 目标填这台机器的 IP,不要在手机上填 `127.0.0.1`
|
||||||
|
- 类型选「合作反射 TCP」或「合作反射 UDP」
|
||||||
|
- 端口填 `19090` 或 `19091`(和 `.env` 里一致)
|
||||||
|
- 目标回显口令和 `NQ_TOKEN` 一致;`.env` 里留空,手机也留空
|
||||||
|
|
||||||
|
让这台机器替手机去测别的地址:
|
||||||
|
|
||||||
|
1. `.env` 里把 `NQ_MODE` 改成 `node` 或 `both`,保存后重新运行。
|
||||||
|
2. 手机来源选「远程节点」,点「管理节点」。
|
||||||
|
3. 地址要能从手机访问到。`.env` 默认的 `127.0.0.1:8443` 只有服务器自己能用。给手机用时改成 `0.0.0.0:8443`,手机里填 `http://服务器IP:8443`。放到公网时请用 HTTPS,不要把明文控制端口直接敞开。
|
||||||
|
4. 节点口令和 `NQ_NODE_TOKEN` 一致。留空就是公开节点。
|
||||||
|
|
||||||
|
## 防火墙要放行的端口
|
||||||
|
|
||||||
|
只放行你真正用的端口。
|
||||||
|
|
||||||
|
- 反射 TCP:`.env` 里的 `NQ_TCP_PORT`,默认 `19090/tcp`
|
||||||
|
- 反射 UDP:`.env` 里的 `NQ_UDP_PORT`,默认 `19091/udp`
|
||||||
|
- 节点控制:只有控制地址不是 `127.0.0.1` 时才需要。默认 `8443/tcp`
|
||||||
|
|
||||||
|
Ubuntu 的 ufw:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo ufw allow 19090/tcp
|
||||||
|
sudo ufw allow 19091/udp
|
||||||
|
sudo ufw status
|
||||||
|
```
|
||||||
|
|
||||||
|
firewalld:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo firewall-cmd --permanent --add-port=19090/tcp
|
||||||
|
sudo firewall-cmd --permanent --add-port=19091/udp
|
||||||
|
sudo firewall-cmd --reload
|
||||||
|
```
|
||||||
|
|
||||||
|
云服务器还要在安全组里放行同样的端口。只改系统防火墙、不改安全组,外面还是连不上。
|
||||||
|
|
||||||
|
## Linux 开机自启
|
||||||
|
|
||||||
|
下面假设压缩包解压到 `/opt/netquality`,里面能看到 `netquality-reflector`、`.env` 和 `netquality.service`。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo mkdir -p /opt/netquality
|
||||||
|
sudo tar -C /opt/netquality --strip-components=1 -xzf netquality-server-1.1.2-linux-amd64.tar.gz
|
||||||
|
sudo chmod 755 /opt/netquality/netquality-reflector
|
||||||
|
sudo cp /opt/netquality/netquality.service /etc/systemd/system/netquality.service
|
||||||
|
sudo systemctl daemon-reload
|
||||||
|
sudo systemctl enable --now netquality
|
||||||
|
sudo systemctl status netquality
|
||||||
|
```
|
||||||
|
|
||||||
|
ARM 机器用文件名里带 `linux-arm64` 的那个压缩包,解压命令同样,只是文件名不同。
|
||||||
|
|
||||||
|
以后只改 `/opt/netquality/.env`,然后:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo systemctl restart netquality
|
||||||
|
```
|
||||||
|
|
||||||
|
看日志:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
journalctl -u netquality -f
|
||||||
|
```
|
||||||
|
|
||||||
|
大约每分钟会有一行统计:收到多少、回了多少、拒绝了多少。
|
||||||
|
|
||||||
|
`netquality.service` 的内容就是:
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[Unit]
|
||||||
|
Description=网络质量探测节点
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
WorkingDirectory=/opt/netquality
|
||||||
|
ExecStart=/opt/netquality/netquality-reflector
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=2
|
||||||
|
NoNewPrivileges=true
|
||||||
|
ProtectSystem=strict
|
||||||
|
ProtectHome=true
|
||||||
|
PrivateTmp=true
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
```
|
||||||
|
|
||||||
|
不要在服务文件里再写端口。端口以 `.env` 为准。如果服务文件里写了环境变量,那个值会盖过 `.env`。
|
||||||
|
|
||||||
|
仓库里还有两份示例:`deploy/netquality-reflector.service` 只按 `.env` 运行;`deploy/netquality-node.service` 额外固定 `NQ_MODE=both`。两份不要同时启用,否则会抢同一个端口。
|
||||||
@@ -0,0 +1,462 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"unicode"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultBind = "0.0.0.0"
|
||||||
|
defaultTCPPort = 19090
|
||||||
|
defaultUDPPort = 19091
|
||||||
|
defaultMode = "reflector"
|
||||||
|
defaultControlAddr = "127.0.0.1:8443"
|
||||||
|
)
|
||||||
|
|
||||||
|
// errHelp is returned when the user asks for -h. It is not a failure.
|
||||||
|
var errHelp = errors.New("help")
|
||||||
|
|
||||||
|
// Config is the fully resolved runtime configuration.
|
||||||
|
// Precedence for every field is: command-line flag, real environment
|
||||||
|
// variable, .env file, then the built-in default.
|
||||||
|
type Config struct {
|
||||||
|
Bind string
|
||||||
|
TCPPort int
|
||||||
|
UDPPort int
|
||||||
|
Token string
|
||||||
|
NodeToken string
|
||||||
|
Mode string
|
||||||
|
ControlAddr string
|
||||||
|
AllowPrivate bool
|
||||||
|
AllowNets string
|
||||||
|
TLSCert string
|
||||||
|
TLSKey string
|
||||||
|
Verbose bool
|
||||||
|
LoadedFiles []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Summary is a single startup line. Tokens are reported only as set or unset.
|
||||||
|
func (c Config) Summary() string {
|
||||||
|
files := "无"
|
||||||
|
if len(c.LoadedFiles) > 0 {
|
||||||
|
files = strings.Join(c.LoadedFiles, ", ")
|
||||||
|
}
|
||||||
|
return fmt.Sprintf(
|
||||||
|
"生效配置 mode=%s bind=%s tcp_port=%d udp_port=%d control_addr=%s echo_token=%s node_token=%s allow_private=%t allow_nets=%s tls_cert=%s tls_key=%s verbose=%t 配置文件=%s",
|
||||||
|
c.Mode,
|
||||||
|
c.Bind,
|
||||||
|
c.TCPPort,
|
||||||
|
c.UDPPort,
|
||||||
|
c.ControlAddr,
|
||||||
|
secretState(c.Token),
|
||||||
|
secretState(c.NodeToken),
|
||||||
|
c.AllowPrivate,
|
||||||
|
c.AllowNets,
|
||||||
|
pathState(c.TLSCert),
|
||||||
|
pathState(c.TLSKey),
|
||||||
|
c.Verbose,
|
||||||
|
files,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func secretState(s string) string {
|
||||||
|
if s == "" {
|
||||||
|
return "未设置"
|
||||||
|
}
|
||||||
|
return "已设置"
|
||||||
|
}
|
||||||
|
|
||||||
|
func pathState(s string) string {
|
||||||
|
if strings.TrimSpace(s) == "" {
|
||||||
|
return "未设置"
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadConfig resolves configuration for a real process start.
|
||||||
|
// A missing .env next to the executable or in the working directory is ignored.
|
||||||
|
func loadConfig(args []string, environ []string) (Config, error) {
|
||||||
|
exeDir := ""
|
||||||
|
if exe, err := os.Executable(); err == nil {
|
||||||
|
if resolved, err := filepath.EvalSymlinks(exe); err == nil {
|
||||||
|
exe = resolved
|
||||||
|
}
|
||||||
|
exeDir = filepath.Dir(exe)
|
||||||
|
}
|
||||||
|
cwd, err := os.Getwd()
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
return loadConfigAt(args, environ, exeDir, cwd)
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadConfigAt is the testable core of loadConfig.
|
||||||
|
func loadConfigAt(args []string, environ []string, exeDir, cwd string) (Config, error) {
|
||||||
|
fs := flag.NewFlagSet("netquality-reflector", flag.ContinueOnError)
|
||||||
|
fs.SetOutput(os.Stderr)
|
||||||
|
bind := fs.String("bind", defaultBind, "反射监听地址,对应 NQ_BIND")
|
||||||
|
tcpPort := fs.Int("tcp-port", defaultTCPPort, "TCP 反射端口,0 表示关闭,对应 NQ_TCP_PORT")
|
||||||
|
udpPort := fs.Int("udp-port", defaultUDPPort, "UDP 反射端口,0 表示关闭,对应 NQ_UDP_PORT")
|
||||||
|
token := fs.String("token", "", "回显口令,最长 32 字节,留空不校验,对应 NQ_TOKEN")
|
||||||
|
nodeToken := fs.String("node-token", "", "节点口令,留空则节点公开,对应 NQ_NODE_TOKEN")
|
||||||
|
mode := fs.String("mode", defaultMode, "reflector、node 或 both,对应 NQ_MODE")
|
||||||
|
controlAddr := fs.String("control-addr", defaultControlAddr, "节点控制地址,对应 NQ_CONTROL_ADDR")
|
||||||
|
allowPrivate := fs.Bool("allow-private", false, "允许探测本机和局域网,对应 NQ_ALLOW_PRIVATE")
|
||||||
|
allowNets := fs.String("allow-nets", "", "额外允许的网段,逗号分隔,对应 NQ_ALLOW_NETS")
|
||||||
|
tlsCert := fs.String("tls-cert", "", "控制端口证书,对应 NQ_TLS_CERT")
|
||||||
|
tlsKey := fs.String("tls-key", "", "控制端口私钥,对应 NQ_TLS_KEY")
|
||||||
|
envPath := fs.String("env", "", "额外的 .env 路径,会覆盖其他 .env;文件必须存在")
|
||||||
|
verbose := fs.Bool("v", false, "打印每一包日志,对应 NQ_VERBOSE")
|
||||||
|
fs.Usage = func() {
|
||||||
|
fmt.Fprintf(fs.Output(), `网络质量探测节点
|
||||||
|
|
||||||
|
优先级:命令行参数 > 环境变量 > .env 文件 > 内置默认值。
|
||||||
|
启动时读取程序所在目录和当前目录下的 .env(路径相同则只读一次)。
|
||||||
|
找不到这些 .env 不会报错。-env 指定的文件必须存在,并覆盖前面的 .env。
|
||||||
|
|
||||||
|
`)
|
||||||
|
fs.PrintDefaults()
|
||||||
|
}
|
||||||
|
if err := fs.Parse(args); err != nil {
|
||||||
|
if errors.Is(err, flag.ErrHelp) {
|
||||||
|
return Config{}, errHelp
|
||||||
|
}
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
if fs.NArg() != 0 {
|
||||||
|
return Config{}, fmt.Errorf("不认识的参数: %s", strings.Join(fs.Args(), " "))
|
||||||
|
}
|
||||||
|
visited := map[string]bool{}
|
||||||
|
fs.Visit(func(f *flag.Flag) { visited[f.Name] = true })
|
||||||
|
|
||||||
|
fileEnv, loaded, err := mergeEnvFiles(exeDir, cwd, strings.TrimSpace(*envPath))
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
real := envMap(environ)
|
||||||
|
|
||||||
|
cfg := Config{LoadedFiles: loaded}
|
||||||
|
cfg.Bind = pickString(visited["bind"], *bind, "NQ_BIND", real, fileEnv, defaultBind)
|
||||||
|
cfg.Token = pickString(visited["token"], *token, "NQ_TOKEN", real, fileEnv, "")
|
||||||
|
cfg.NodeToken = pickString(visited["node-token"], *nodeToken, "NQ_NODE_TOKEN", real, fileEnv, "")
|
||||||
|
cfg.Mode = pickString(visited["mode"], *mode, "NQ_MODE", real, fileEnv, defaultMode)
|
||||||
|
cfg.ControlAddr = pickString(visited["control-addr"], *controlAddr, "NQ_CONTROL_ADDR", real, fileEnv, defaultControlAddr)
|
||||||
|
cfg.AllowNets = pickString(visited["allow-nets"], *allowNets, "NQ_ALLOW_NETS", real, fileEnv, "")
|
||||||
|
cfg.TLSCert = pickString(visited["tls-cert"], *tlsCert, "NQ_TLS_CERT", real, fileEnv, "")
|
||||||
|
cfg.TLSKey = pickString(visited["tls-key"], *tlsKey, "NQ_TLS_KEY", real, fileEnv, "")
|
||||||
|
|
||||||
|
tcpRaw := pickString(visited["tcp-port"], strconv.Itoa(*tcpPort), "NQ_TCP_PORT", real, fileEnv, strconv.Itoa(defaultTCPPort))
|
||||||
|
udpRaw := pickString(visited["udp-port"], strconv.Itoa(*udpPort), "NQ_UDP_PORT", real, fileEnv, strconv.Itoa(defaultUDPPort))
|
||||||
|
allowRaw := pickString(visited["allow-private"], strconv.FormatBool(*allowPrivate), "NQ_ALLOW_PRIVATE", real, fileEnv, "false")
|
||||||
|
verboseRaw := pickString(visited["v"], strconv.FormatBool(*verbose), "NQ_VERBOSE", real, fileEnv, "false")
|
||||||
|
|
||||||
|
cfg.TCPPort, err = parsePort("NQ_TCP_PORT", tcpRaw)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
cfg.UDPPort, err = parsePort("NQ_UDP_PORT", udpRaw)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
cfg.AllowPrivate, err = parseBool("NQ_ALLOW_PRIVATE", allowRaw)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
cfg.Verbose, err = parseBool("NQ_VERBOSE", verboseRaw)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
if err := cfg.validate(); err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func pickString(fromFlag bool, flagVal, envKey string, real, file map[string]string, fallback string) string {
|
||||||
|
if fromFlag {
|
||||||
|
return flagVal
|
||||||
|
}
|
||||||
|
if v, ok := real[envKey]; ok {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
if v, ok := file[envKey]; ok {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Config) validate() error {
|
||||||
|
switch c.Mode {
|
||||||
|
case "reflector", "node", "both":
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("NQ_MODE 必须是 reflector、node 或 both,当前是 %q", c.Mode)
|
||||||
|
}
|
||||||
|
if c.TCPPort < 0 || c.TCPPort > 65535 || c.UDPPort < 0 || c.UDPPort > 65535 {
|
||||||
|
return fmt.Errorf("端口必须在 0 到 65535 之间")
|
||||||
|
}
|
||||||
|
if (c.Mode == "reflector" || c.Mode == "both") && c.TCPPort == 0 && c.UDPPort == 0 {
|
||||||
|
return fmt.Errorf("反射模式至少要打开 TCP 或 UDP 其中一个端口")
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(c.Bind) == "" {
|
||||||
|
return fmt.Errorf("NQ_BIND 不能为空")
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(c.ControlAddr) == "" {
|
||||||
|
return fmt.Errorf("NQ_CONTROL_ADDR 不能为空")
|
||||||
|
}
|
||||||
|
if (c.TLSCert == "") != (c.TLSKey == "") {
|
||||||
|
return fmt.Errorf("NQ_TLS_CERT 和 NQ_TLS_KEY 必须同时填写")
|
||||||
|
}
|
||||||
|
if _, err := tokenBytes(c.Token); err != nil {
|
||||||
|
return fmt.Errorf("回显口令无效: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := parseNets(c.AllowNets); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func envMap(environ []string) map[string]string {
|
||||||
|
out := make(map[string]string, len(environ))
|
||||||
|
for _, entry := range environ {
|
||||||
|
k, v, ok := strings.Cut(entry, "=")
|
||||||
|
if !ok || k == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out[k] = v
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func mergeEnvFiles(exeDir, cwd, explicit string) (map[string]string, []string, error) {
|
||||||
|
var paths []string
|
||||||
|
add := func(p string) {
|
||||||
|
if strings.TrimSpace(p) == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, have := range paths {
|
||||||
|
if samePath(have, p) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
paths = append(paths, p)
|
||||||
|
}
|
||||||
|
if exeDir != "" {
|
||||||
|
add(filepath.Join(exeDir, ".env"))
|
||||||
|
}
|
||||||
|
if cwd != "" {
|
||||||
|
add(filepath.Join(cwd, ".env"))
|
||||||
|
}
|
||||||
|
if explicit != "" {
|
||||||
|
if _, err := os.Stat(explicit); err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return nil, nil, fmt.Errorf("找不到 -env 指定的文件: %s", explicit)
|
||||||
|
}
|
||||||
|
return nil, nil, fmt.Errorf("无法读取 -env 文件 %s: %w", explicit, err)
|
||||||
|
}
|
||||||
|
// The explicit file wins over the default locations.
|
||||||
|
var rest []string
|
||||||
|
for _, p := range paths {
|
||||||
|
if !samePath(p, explicit) {
|
||||||
|
rest = append(rest, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
paths = append(rest, explicit)
|
||||||
|
}
|
||||||
|
|
||||||
|
merged := map[string]string{}
|
||||||
|
var loaded []string
|
||||||
|
for _, p := range paths {
|
||||||
|
required := explicit != "" && samePath(p, explicit)
|
||||||
|
vals, found, err := readEnvFile(p, required)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for k, v := range vals {
|
||||||
|
merged[k] = v
|
||||||
|
}
|
||||||
|
loaded = append(loaded, p)
|
||||||
|
}
|
||||||
|
return merged, loaded, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func readEnvFile(path string, required bool) (map[string]string, bool, error) {
|
||||||
|
f, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) && !required {
|
||||||
|
return nil, false, nil
|
||||||
|
}
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return nil, false, fmt.Errorf("找不到配置文件: %s", path)
|
||||||
|
}
|
||||||
|
return nil, false, fmt.Errorf("无法读取配置文件 %s: %w", path, err)
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
vals, err := parseDotEnv(f)
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, fmt.Errorf("%s: %w", path, err)
|
||||||
|
}
|
||||||
|
return vals, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func samePath(a, b string) bool {
|
||||||
|
aa, ea := filepath.Abs(a)
|
||||||
|
bb, eb := filepath.Abs(b)
|
||||||
|
if ea != nil || eb != nil {
|
||||||
|
return filepath.Clean(a) == filepath.Clean(b)
|
||||||
|
}
|
||||||
|
if ra, err := filepath.EvalSymlinks(aa); err == nil {
|
||||||
|
aa = ra
|
||||||
|
}
|
||||||
|
if rb, err := filepath.EvalSymlinks(bb); err == nil {
|
||||||
|
bb = rb
|
||||||
|
}
|
||||||
|
return aa == bb
|
||||||
|
}
|
||||||
|
|
||||||
|
var knownEnvKeys = map[string]struct{}{
|
||||||
|
"NQ_BIND": {},
|
||||||
|
"NQ_TCP_PORT": {},
|
||||||
|
"NQ_UDP_PORT": {},
|
||||||
|
"NQ_TOKEN": {},
|
||||||
|
"NQ_NODE_TOKEN": {},
|
||||||
|
"NQ_MODE": {},
|
||||||
|
"NQ_CONTROL_ADDR": {},
|
||||||
|
"NQ_ALLOW_PRIVATE": {},
|
||||||
|
"NQ_ALLOW_NETS": {},
|
||||||
|
"NQ_TLS_CERT": {},
|
||||||
|
"NQ_TLS_KEY": {},
|
||||||
|
"NQ_VERBOSE": {},
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseDotEnv(r io.Reader) (map[string]string, error) {
|
||||||
|
sc := bufio.NewScanner(r)
|
||||||
|
sc.Buffer(make([]byte, 64*1024), 1024*1024)
|
||||||
|
out := map[string]string{}
|
||||||
|
lineNo := 0
|
||||||
|
first := true
|
||||||
|
for sc.Scan() {
|
||||||
|
lineNo++
|
||||||
|
line := sc.Text()
|
||||||
|
if first {
|
||||||
|
line = strings.TrimPrefix(line, "\uFEFF")
|
||||||
|
first = false
|
||||||
|
}
|
||||||
|
line = strings.TrimSpace(line)
|
||||||
|
if line == "" || strings.HasPrefix(line, "#") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(line, "export ") {
|
||||||
|
line = strings.TrimSpace(strings.TrimPrefix(line, "export "))
|
||||||
|
}
|
||||||
|
key, raw, ok := strings.Cut(line, "=")
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("第 %d 行不是 KEY=VALUE", lineNo)
|
||||||
|
}
|
||||||
|
key = strings.TrimSpace(key)
|
||||||
|
if !validEnvKey(key) {
|
||||||
|
return nil, fmt.Errorf("第 %d 行配置名无效: %s", lineNo, key)
|
||||||
|
}
|
||||||
|
if _, known := knownEnvKeys[key]; !known {
|
||||||
|
return nil, fmt.Errorf("第 %d 行不认识的配置项 %s", lineNo, key)
|
||||||
|
}
|
||||||
|
val, err := parseEnvValue(raw)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("第 %d 行: %w", lineNo, err)
|
||||||
|
}
|
||||||
|
out[key] = val
|
||||||
|
}
|
||||||
|
if err := sc.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validEnvKey(k string) bool {
|
||||||
|
if k == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for i, r := range k {
|
||||||
|
if i == 0 {
|
||||||
|
if r != '_' && !unicode.IsLetter(r) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if r != '_' && !unicode.IsLetter(r) && !unicode.IsDigit(r) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseEnvValue(raw string) (string, error) {
|
||||||
|
s := strings.TrimSpace(raw)
|
||||||
|
if s == "" {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
if s[0] == '"' || s[0] == '\'' {
|
||||||
|
q := s[0]
|
||||||
|
var b strings.Builder
|
||||||
|
rest := s[1:]
|
||||||
|
for i := 0; i < len(rest); i++ {
|
||||||
|
c := rest[i]
|
||||||
|
if c == '\\' && q == '"' && i+1 < len(rest) {
|
||||||
|
b.WriteByte(rest[i+1])
|
||||||
|
i++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if c == q {
|
||||||
|
tail := strings.TrimSpace(rest[i+1:])
|
||||||
|
if tail != "" && !strings.HasPrefix(tail, "#") {
|
||||||
|
return "", fmt.Errorf("引号结束后还有多余内容")
|
||||||
|
}
|
||||||
|
return b.String(), nil
|
||||||
|
}
|
||||||
|
b.WriteByte(c)
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("引号没有结束")
|
||||||
|
}
|
||||||
|
if i := inlineComment(s); i >= 0 {
|
||||||
|
s = strings.TrimSpace(s[:i])
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func inlineComment(s string) int {
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
if s[i] == '#' && (i == 0 || s[i-1] == ' ' || s[i-1] == '\t') {
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
func parsePort(name, raw string) (int, error) {
|
||||||
|
n, err := strconv.Atoi(strings.TrimSpace(raw))
|
||||||
|
if err != nil || n < 0 || n > 65535 {
|
||||||
|
return 0, fmt.Errorf("%s 必须是 0 到 65535 的整数,当前是 %q", name, raw)
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseBool(name, raw string) (bool, error) {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(raw)) {
|
||||||
|
case "1", "true", "yes", "on":
|
||||||
|
return true, nil
|
||||||
|
case "0", "false", "no", "off":
|
||||||
|
return false, nil
|
||||||
|
default:
|
||||||
|
return false, fmt.Errorf("%s 必须是 true 或 false,当前是 %q", name, raw)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,226 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestParseDotEnv(t *testing.T) {
|
||||||
|
src := "\uFEFF# 注释\r\n\r\n" +
|
||||||
|
"NQ_BIND=127.0.0.1 # 只听本机\r\n" +
|
||||||
|
"export NQ_MODE=node\r\n" +
|
||||||
|
"NQ_TOKEN=\"a b # c\"\r\n" +
|
||||||
|
"NQ_NODE_TOKEN='keep # this'\r\n" +
|
||||||
|
"NQ_TCP_PORT=19090\r\n" +
|
||||||
|
"NQ_VERBOSE=true\r\n" +
|
||||||
|
"NQ_TOKEN=later\r\n"
|
||||||
|
got, err := parseDotEnv(strings.NewReader(src))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got["NQ_BIND"] != "127.0.0.1" || got["NQ_MODE"] != "node" {
|
||||||
|
t.Fatalf("basic: %#v", got)
|
||||||
|
}
|
||||||
|
if got["NQ_TOKEN"] != "later" {
|
||||||
|
t.Fatalf("last key wins, got %q", got["NQ_TOKEN"])
|
||||||
|
}
|
||||||
|
if got["NQ_NODE_TOKEN"] != "keep # this" {
|
||||||
|
t.Fatalf("quotes: %q", got["NQ_NODE_TOKEN"])
|
||||||
|
}
|
||||||
|
if got["NQ_VERBOSE"] != "true" {
|
||||||
|
t.Fatalf("verbose: %#v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseDotEnvErrors(t *testing.T) {
|
||||||
|
cases := []string{
|
||||||
|
"not a pair",
|
||||||
|
"NQ_NOPE=1",
|
||||||
|
"NQ_TOKEN=\"abc\" leftover",
|
||||||
|
"NQ_TOKEN=\"unterminated",
|
||||||
|
"1BAD=1",
|
||||||
|
}
|
||||||
|
for _, src := range cases {
|
||||||
|
if _, err := parseDotEnv(strings.NewReader(src)); err == nil {
|
||||||
|
t.Fatalf("expected error for %q", src)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMissingEnvFileIsNotAnError(t *testing.T) {
|
||||||
|
cfg, err := loadConfigAt(nil, nil, t.TempDir(), t.TempDir())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(cfg.LoadedFiles) != 0 {
|
||||||
|
t.Fatalf("loaded %v", cfg.LoadedFiles)
|
||||||
|
}
|
||||||
|
if cfg.Bind != defaultBind || cfg.TCPPort != defaultTCPPort || cfg.UDPPort != defaultUDPPort || cfg.Mode != defaultMode || cfg.ControlAddr != defaultControlAddr {
|
||||||
|
t.Fatalf("defaults: %+v", cfg)
|
||||||
|
}
|
||||||
|
if cfg.Token != "" || cfg.NodeToken != "" || cfg.AllowPrivate || cfg.Verbose || cfg.AllowNets != "" || cfg.TLSCert != "" || cfg.TLSKey != "" {
|
||||||
|
t.Fatalf("empty defaults: %+v", cfg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExplicitEnvMustExist(t *testing.T) {
|
||||||
|
missing := filepath.Join(t.TempDir(), "missing.env")
|
||||||
|
_, err := loadConfigAt([]string{"-env", missing}, nil, t.TempDir(), t.TempDir())
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected missing -env to fail")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnvFilePrecedence(t *testing.T) {
|
||||||
|
exe := t.TempDir()
|
||||||
|
cwd := t.TempDir()
|
||||||
|
explicit := filepath.Join(t.TempDir(), "custom.env")
|
||||||
|
mustWrite(t, filepath.Join(exe, ".env"), "NQ_TCP_PORT=1111\nNQ_TOKEN=from-exe\nNQ_VERBOSE=true\n")
|
||||||
|
mustWrite(t, filepath.Join(cwd, ".env"), "NQ_TCP_PORT=2222\nNQ_TOKEN=from-cwd\n")
|
||||||
|
mustWrite(t, explicit, "NQ_TCP_PORT=3333\nNQ_TOKEN=from-explicit\n")
|
||||||
|
|
||||||
|
cwdOnly, err := loadConfigAt(nil, nil, exe, cwd)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if cwdOnly.TCPPort != 2222 || cwdOnly.Token != "from-cwd" || !cwdOnly.Verbose {
|
||||||
|
t.Fatalf("cwd should override exe dir and keep untouched keys: %+v", cwdOnly)
|
||||||
|
}
|
||||||
|
|
||||||
|
envWins, err := loadConfigAt(nil, []string{"NQ_TCP_PORT=4444", "NQ_TOKEN="}, exe, cwd)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if envWins.TCPPort != 4444 || envWins.Token != "" {
|
||||||
|
t.Fatalf("real env should beat .env, including an empty value: %+v", envWins)
|
||||||
|
}
|
||||||
|
|
||||||
|
flagWins, err := loadConfigAt([]string{"-tcp-port", "5555", "-token", "from-flag"}, []string{"NQ_TCP_PORT=4444", "NQ_TOKEN=from-env"}, exe, cwd)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if flagWins.TCPPort != 5555 || flagWins.Token != "from-flag" {
|
||||||
|
t.Fatalf("flags should beat env: %+v", flagWins)
|
||||||
|
}
|
||||||
|
|
||||||
|
fileWins, err := loadConfigAt([]string{"-env", explicit}, nil, exe, cwd)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if fileWins.TCPPort != 3333 || fileWins.Token != "from-explicit" {
|
||||||
|
t.Fatalf("explicit -env should beat the other files: %+v", fileWins)
|
||||||
|
}
|
||||||
|
if !fileWins.Verbose {
|
||||||
|
t.Fatal("key only present in the exe .env should remain")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBoolFlagBeatsFile(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
mustWrite(t, filepath.Join(dir, ".env"), "NQ_ALLOW_PRIVATE=true\nNQ_VERBOSE=yes\n")
|
||||||
|
cfg, err := loadConfigAt([]string{"-allow-private=false", "-v=false"}, nil, dir, t.TempDir())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if cfg.AllowPrivate || cfg.Verbose {
|
||||||
|
t.Fatalf("flags should force false: %+v", cfg)
|
||||||
|
}
|
||||||
|
fromFile, err := loadConfigAt(nil, nil, dir, t.TempDir())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !fromFile.AllowPrivate || !fromFile.Verbose {
|
||||||
|
t.Fatalf("file should set bools when flags are absent: %+v", fromFile)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigValidation(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
cases := []string{
|
||||||
|
"NQ_TCP_PORT=nope\n",
|
||||||
|
"NQ_MODE=sometimes\n",
|
||||||
|
"NQ_TCP_PORT=0\nNQ_UDP_PORT=0\n",
|
||||||
|
"NQ_TLS_CERT=/tmp/cert.pem\n",
|
||||||
|
"NQ_TOKEN=" + strings.Repeat("a", 33) + "\n",
|
||||||
|
"NQ_ALLOW_PRIVATE=maybe\n",
|
||||||
|
"NQ_ALLOW_NETS=not-a-cidr\n",
|
||||||
|
}
|
||||||
|
for _, src := range cases {
|
||||||
|
mustWrite(t, filepath.Join(dir, ".env"), src)
|
||||||
|
if _, err := loadConfigAt(nil, nil, dir, t.TempDir()); err == nil {
|
||||||
|
t.Fatalf("expected error for %q", src)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSummaryMasksTokens(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
mustWrite(t, filepath.Join(dir, ".env"), "NQ_TOKEN=super-secret-echo\nNQ_NODE_TOKEN=super-secret-node\nNQ_MODE=both\n")
|
||||||
|
cfg, err := loadConfigAt(nil, nil, dir, t.TempDir())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
line := cfg.Summary()
|
||||||
|
if strings.Contains(line, "super-secret") {
|
||||||
|
t.Fatal(line)
|
||||||
|
}
|
||||||
|
if !strings.Contains(line, "echo_token=已设置") || !strings.Contains(line, "node_token=已设置") {
|
||||||
|
t.Fatal(line)
|
||||||
|
}
|
||||||
|
plain, err := loadConfigAt(nil, nil, t.TempDir(), t.TempDir())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(plain.Summary(), "echo_token=未设置") || !strings.Contains(plain.Summary(), "node_token=未设置") {
|
||||||
|
t.Fatal(plain.Summary())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestShippedEnvMatchesDefaults(t *testing.T) {
|
||||||
|
base, err := loadConfigAt(nil, nil, t.TempDir(), t.TempDir())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, name := range []string{".env", ".env.example"} {
|
||||||
|
dir := t.TempDir()
|
||||||
|
raw, err := os.ReadFile(name)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
mustWrite(t, filepath.Join(dir, ".env"), string(raw))
|
||||||
|
cfg, err := loadConfigAt(nil, nil, dir, t.TempDir())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s: %v", name, err)
|
||||||
|
}
|
||||||
|
if cfg.Bind != base.Bind || cfg.TCPPort != base.TCPPort || cfg.UDPPort != base.UDPPort ||
|
||||||
|
cfg.Token != base.Token || cfg.NodeToken != base.NodeToken || cfg.Mode != base.Mode ||
|
||||||
|
cfg.ControlAddr != base.ControlAddr || cfg.AllowPrivate != base.AllowPrivate ||
|
||||||
|
cfg.AllowNets != base.AllowNets || cfg.TLSCert != base.TLSCert || cfg.TLSKey != base.TLSKey ||
|
||||||
|
cfg.Verbose != base.Verbose {
|
||||||
|
t.Fatalf("%s changed defaults:\n got %+v\nwant %+v", name, cfg, base)
|
||||||
|
}
|
||||||
|
parsed, err := parseDotEnv(strings.NewReader(string(raw)))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(parsed) != len(knownEnvKeys) {
|
||||||
|
t.Fatalf("%s documents %d keys, want %d", name, len(parsed), len(knownEnvKeys))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHelp(t *testing.T) {
|
||||||
|
_, err := loadConfigAt([]string{"-h"}, nil, t.TempDir(), t.TempDir())
|
||||||
|
if err != errHelp {
|
||||||
|
t.Fatalf("got %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustWrite(t *testing.T, path, body string) {
|
||||||
|
t.Helper()
|
||||||
|
if err := os.WriteFile(path, []byte(body), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,7 +5,12 @@ Wants=network-online.target
|
|||||||
|
|
||||||
[Service]
|
[Service]
|
||||||
Type=simple
|
Type=simple
|
||||||
ExecStart=/usr/local/bin/netquality-reflector -mode both -bind 0.0.0.0 -tcp-port 19090 -udp-port 19091 -control-addr 127.0.0.1:8443
|
# 端口和口令写在 /opt/netquality/.env。
|
||||||
|
# 这份服务通过环境变量把模式固定成 both(反射 + 节点),会盖过 .env 里的 NQ_MODE。
|
||||||
|
# 节点口令请改 .env 的 NQ_NODE_TOKEN,不要把真实口令写进本文件。
|
||||||
|
WorkingDirectory=/opt/netquality
|
||||||
|
Environment=NQ_MODE=both
|
||||||
|
ExecStart=/opt/netquality/netquality-reflector
|
||||||
Restart=on-failure
|
Restart=on-failure
|
||||||
RestartSec=2
|
RestartSec=2
|
||||||
NoNewPrivileges=true
|
NoNewPrivileges=true
|
||||||
@@ -13,11 +18,5 @@ ProtectSystem=strict
|
|||||||
ProtectHome=true
|
ProtectHome=true
|
||||||
PrivateTmp=true
|
PrivateTmp=true
|
||||||
|
|
||||||
# 二选一,不要把真实口令提交到仓库。
|
|
||||||
# 留空或不设置 NQ_NODE_TOKEN:公开节点,任何人都能用,但有并发和时长上限。
|
|
||||||
# Environment=NQ_NODE_TOKEN=replace-with-your-own-node-token
|
|
||||||
# 下面这个是反射帧里的回显口令,和节点口令不是同一个。
|
|
||||||
# Environment=NQ_TOKEN=replace-with-your-own-echo-token
|
|
||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
WantedBy=multi-user.target
|
WantedBy=multi-user.target
|
||||||
@@ -5,7 +5,10 @@ Wants=network-online.target
|
|||||||
|
|
||||||
[Service]
|
[Service]
|
||||||
Type=simple
|
Type=simple
|
||||||
ExecStart=/usr/local/bin/netquality-reflector -bind 0.0.0.0 -tcp-port 19090 -udp-port 19091
|
# 端口、回显口令和模式写在 /opt/netquality/.env。
|
||||||
|
# 默认 NQ_MODE=reflector,只做反射。改完 .env 后执行 systemctl restart。
|
||||||
|
WorkingDirectory=/opt/netquality
|
||||||
|
ExecStart=/opt/netquality/netquality-reflector
|
||||||
Restart=on-failure
|
Restart=on-failure
|
||||||
RestartSec=2
|
RestartSec=2
|
||||||
NoNewPrivileges=true
|
NoNewPrivileges=true
|
||||||
@@ -13,8 +16,5 @@ ProtectSystem=strict
|
|||||||
ProtectHome=true
|
ProtectHome=true
|
||||||
PrivateTmp=true
|
PrivateTmp=true
|
||||||
|
|
||||||
# Optional shared token. Uncomment and set a short passphrase (max 32 bytes).
|
|
||||||
# Environment=NQ_TOKEN=replace-me
|
|
||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
WantedBy=multi-user.target
|
WantedBy=multi-user.target
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=网络质量探测节点
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
# 程序和 .env 放在同一目录。端口、口令、模式都改 .env,不要改这一行。
|
||||||
|
WorkingDirectory=/opt/netquality
|
||||||
|
ExecStart=/opt/netquality/netquality-reflector
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=2
|
||||||
|
NoNewPrivileges=true
|
||||||
|
ProtectSystem=strict
|
||||||
|
ProtectHome=true
|
||||||
|
PrivateTmp=true
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
+29
-79
@@ -1,8 +1,11 @@
|
|||||||
|
// Copyright (C) 2026 灸 言
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"flag"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"net"
|
"net"
|
||||||
@@ -16,49 +19,30 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
bind := flag.String("bind", envStr("NQ_BIND", "0.0.0.0"), "reflector bind address")
|
cfg, err := loadConfig(os.Args[1:], os.Environ())
|
||||||
tcpPort := flag.Int("tcp-port", envInt("NQ_TCP_PORT", 19090), "TCP echo port (0 disables)")
|
if err != nil {
|
||||||
udpPort := flag.Int("udp-port", envInt("NQ_UDP_PORT", 19091), "UDP echo port (0 disables)")
|
if errors.Is(err, errHelp) {
|
||||||
tokenFlag := flag.String("token", envStr("NQ_TOKEN", ""), "optional echo token written into NQ frames, max 32 bytes; empty accepts any echo token")
|
os.Exit(0)
|
||||||
nodeToken := flag.String("node-token", envStr("NQ_NODE_TOKEN", ""), "optional control-plane token; empty makes the node public")
|
}
|
||||||
mode := flag.String("mode", envStr("NQ_MODE", "reflector"), "reflector, node, or both")
|
log.Fatal(err)
|
||||||
controlAddr := flag.String("control-addr", envStr("NQ_CONTROL_ADDR", "127.0.0.1:8443"), "node control listen address")
|
}
|
||||||
allowPrivate := flag.Bool("allow-private", envBool("NQ_ALLOW_PRIVATE", false), "let the node probe loopback and private addresses (metadata stays blocked)")
|
log.Printf("netquality %s", appVersion)
|
||||||
allowNets := flag.String("allow-nets", envStr("NQ_ALLOW_NETS", ""), "comma-separated extra CIDRs the node may probe")
|
log.Printf("%s", cfg.Summary())
|
||||||
tlsCert := flag.String("tls-cert", envStr("NQ_TLS_CERT", ""), "TLS certificate for the control API")
|
|
||||||
tlsKey := flag.String("tls-key", envStr("NQ_TLS_KEY", ""), "TLS private key for the control API")
|
|
||||||
verbose := flag.Bool("v", false, "log each echoed packet")
|
|
||||||
flag.Parse()
|
|
||||||
|
|
||||||
switch *mode {
|
tok, err := tokenBytes(cfg.Token)
|
||||||
case "reflector", "node", "both":
|
|
||||||
default:
|
|
||||||
log.Fatal("-mode must be reflector, node, or both")
|
|
||||||
}
|
|
||||||
if *tcpPort < 0 || *tcpPort > 65535 || *udpPort < 0 || *udpPort > 65535 {
|
|
||||||
log.Fatal("ports must be between 0 and 65535")
|
|
||||||
}
|
|
||||||
if (*mode == "reflector" || *mode == "both") && *tcpPort == 0 && *udpPort == 0 {
|
|
||||||
log.Fatal("reflector mode needs -tcp-port and/or -udp-port")
|
|
||||||
}
|
|
||||||
if (*tlsCert == "") != (*tlsKey == "") {
|
|
||||||
log.Fatal("-tls-cert and -tls-key must be set together")
|
|
||||||
}
|
|
||||||
|
|
||||||
tok, err := tokenBytes(*tokenFlag)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
extra, err := parseNets(*allowNets)
|
extra, err := parseNets(cfg.AllowNets)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
errCh := make(chan error, 4)
|
errCh := make(chan error, 4)
|
||||||
var srv *Server
|
var srv *Server
|
||||||
if *mode == "reflector" || *mode == "both" {
|
if cfg.Mode == "reflector" || cfg.Mode == "both" {
|
||||||
srv = &Server{Token: tok, Required: *tokenFlag != "", Verbose: *verbose}
|
srv = &Server{Token: tok, Required: cfg.Token != "", Verbose: cfg.Verbose}
|
||||||
startReflector(srv, *bind, *tcpPort, *udpPort, errCh)
|
startReflector(srv, cfg.Bind, cfg.TCPPort, cfg.UDPPort, errCh)
|
||||||
if srv.Required {
|
if srv.Required {
|
||||||
log.Printf("echo token check enabled")
|
log.Printf("echo token check enabled")
|
||||||
} else {
|
} else {
|
||||||
@@ -67,23 +51,23 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var httpSrv *http.Server
|
var httpSrv *http.Server
|
||||||
if *mode == "node" || *mode == "both" {
|
if cfg.Mode == "node" || cfg.Mode == "both" {
|
||||||
node := newNode(*nodeToken, *allowPrivate, extra, defaultLimits())
|
node := newNode(cfg.NodeToken, cfg.AllowPrivate, extra, defaultLimits())
|
||||||
httpSrv = &http.Server{
|
httpSrv = &http.Server{
|
||||||
Addr: *controlAddr,
|
Addr: cfg.ControlAddr,
|
||||||
Handler: node.Handler(),
|
Handler: node.Handler(),
|
||||||
ReadHeaderTimeout: 5 * time.Second,
|
ReadHeaderTimeout: 5 * time.Second,
|
||||||
IdleTimeout: 2 * time.Minute,
|
IdleTimeout: 2 * time.Minute,
|
||||||
}
|
}
|
||||||
ln, err := net.Listen("tcp", *controlAddr)
|
ln, err := net.Listen("tcp", cfg.ControlAddr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("control listen %s: %v", *controlAddr, err)
|
log.Fatalf("control listen %s: %v", cfg.ControlAddr, err)
|
||||||
}
|
}
|
||||||
go func() {
|
go func() {
|
||||||
var serveErr error
|
var serveErr error
|
||||||
if *tlsCert != "" {
|
if cfg.TLSCert != "" {
|
||||||
log.Printf("node control listening with TLS on %s", ln.Addr())
|
log.Printf("node control listening with TLS on %s", ln.Addr())
|
||||||
serveErr = httpSrv.ServeTLS(ln, *tlsCert, *tlsKey)
|
serveErr = httpSrv.ServeTLS(ln, cfg.TLSCert, cfg.TLSKey)
|
||||||
} else {
|
} else {
|
||||||
log.Printf("node control listening on %s (no TLS; put an HTTPS reverse proxy in front if this is reachable from the internet)", ln.Addr())
|
log.Printf("node control listening on %s (no TLS; put an HTTPS reverse proxy in front if this is reachable from the internet)", ln.Addr())
|
||||||
serveErr = httpSrv.Serve(ln)
|
serveErr = httpSrv.Serve(ln)
|
||||||
@@ -92,15 +76,15 @@ func main() {
|
|||||||
errCh <- serveErr
|
errCh <- serveErr
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
if node.Public() && !loopbackHost(*controlAddr) {
|
if node.Public() && !loopbackHost(cfg.ControlAddr) {
|
||||||
log.Printf("WARNING: this node is PUBLIC. Anyone who can reach %s can start bounded probes. Set -node-token to require a control token. Caps stay on: jobs=%d duration=%s interval>=%s probes/s=%d bandwidth=%dB/s",
|
log.Printf("WARNING: this node is PUBLIC. Anyone who can reach %s can start bounded probes. Set NQ_NODE_TOKEN or -node-token to require a control token. Caps stay on: jobs=%d duration=%s interval>=%s probes/s=%d bandwidth=%dB/s",
|
||||||
*controlAddr, node.Limits.MaxJobs, node.Limits.MaxDuration, node.Limits.MinInterval, node.Limits.MaxProbePerSec, node.Limits.MaxBytesPerSec)
|
cfg.ControlAddr, node.Limits.MaxJobs, node.Limits.MaxDuration, node.Limits.MinInterval, node.Limits.MaxProbePerSec, node.Limits.MaxBytesPerSec)
|
||||||
} else if node.Public() {
|
} else if node.Public() {
|
||||||
log.Printf("node is public and bound to loopback; no control token is required")
|
log.Printf("node is public and bound to loopback; no control token is required")
|
||||||
} else {
|
} else {
|
||||||
log.Printf("node is private; a control token is required and is not logged")
|
log.Printf("node is private; a control token is required and is not logged")
|
||||||
}
|
}
|
||||||
if *allowPrivate {
|
if cfg.AllowPrivate {
|
||||||
log.Printf("private and loopback targets are allowed; metadata addresses stay blocked")
|
log.Printf("private and loopback targets are allowed; metadata addresses stay blocked")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -214,37 +198,3 @@ func loopbackHost(addr string) bool {
|
|||||||
ip := net.ParseIP(host)
|
ip := net.ParseIP(host)
|
||||||
return ip != nil && ip.IsLoopback()
|
return ip != nil && ip.IsLoopback()
|
||||||
}
|
}
|
||||||
|
|
||||||
func envStr(key, fallback string) string {
|
|
||||||
if v, ok := os.LookupEnv(key); ok && v != "" {
|
|
||||||
return v
|
|
||||||
}
|
|
||||||
return fallback
|
|
||||||
}
|
|
||||||
|
|
||||||
func envInt(key string, fallback int) int {
|
|
||||||
v, ok := os.LookupEnv(key)
|
|
||||||
if !ok || v == "" {
|
|
||||||
return fallback
|
|
||||||
}
|
|
||||||
n, err := strconv.Atoi(v)
|
|
||||||
if err != nil {
|
|
||||||
return fallback
|
|
||||||
}
|
|
||||||
return n
|
|
||||||
}
|
|
||||||
|
|
||||||
func envBool(key string, fallback bool) bool {
|
|
||||||
v, ok := os.LookupEnv(key)
|
|
||||||
if !ok || v == "" {
|
|
||||||
return fallback
|
|
||||||
}
|
|
||||||
switch strings.ToLower(v) {
|
|
||||||
case "1", "true", "yes", "on":
|
|
||||||
return true
|
|
||||||
case "0", "false", "no", "off":
|
|
||||||
return false
|
|
||||||
default:
|
|
||||||
return fallback
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+30
-11
@@ -19,13 +19,14 @@ const (
|
|||||||
// Outcome is one finished attempt. Pending attempts are never turned into
|
// Outcome is one finished attempt. Pending attempts are never turned into
|
||||||
// a sample, so a chart cannot show a fake 100% before the probe completes.
|
// a sample, so a chart cannot show a fake 100% before the probe completes.
|
||||||
type Outcome struct {
|
type Outcome struct {
|
||||||
Status string
|
Status string
|
||||||
Kind string
|
Kind string
|
||||||
Rtt time.Duration
|
Rtt time.Duration
|
||||||
HasRtt bool
|
HasRtt bool
|
||||||
Note string
|
Note string
|
||||||
Detail map[string]string
|
Detail map[string]string
|
||||||
Reconnect bool
|
Reconnect bool
|
||||||
|
SelectionSkipped int
|
||||||
}
|
}
|
||||||
|
|
||||||
type jitter struct {
|
type jitter struct {
|
||||||
@@ -64,15 +65,18 @@ type sampleBook struct {
|
|||||||
reconnect int
|
reconnect int
|
||||||
consecutive int
|
consecutive int
|
||||||
|
|
||||||
lastRttMs *float64
|
lastRttMs *float64
|
||||||
jitter jitter
|
jitter jitter
|
||||||
lastNote string
|
rtts []float64
|
||||||
detail map[string]string
|
selectionSkipped int
|
||||||
|
lastNote string
|
||||||
|
detail map[string]string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *sampleBook) add(o Outcome) {
|
func (b *sampleBook) add(o Outcome) {
|
||||||
b.sent++
|
b.sent++
|
||||||
b.completed++
|
b.completed++
|
||||||
|
b.selectionSkipped += o.SelectionSkipped
|
||||||
if o.Reconnect {
|
if o.Reconnect {
|
||||||
b.reconnect++
|
b.reconnect++
|
||||||
}
|
}
|
||||||
@@ -94,6 +98,7 @@ func (b *sampleBook) add(o Outcome) {
|
|||||||
if o.HasRtt {
|
if o.HasRtt {
|
||||||
ms := float64(o.Rtt) / float64(time.Millisecond)
|
ms := float64(o.Rtt) / float64(time.Millisecond)
|
||||||
b.lastRttMs = &ms
|
b.lastRttMs = &ms
|
||||||
|
b.rtts = append(b.rtts, ms)
|
||||||
b.jitter.push(ms)
|
b.jitter.push(ms)
|
||||||
}
|
}
|
||||||
case statusTimeout:
|
case statusTimeout:
|
||||||
@@ -138,6 +143,14 @@ func (b *sampleBook) summary() summaryMsg {
|
|||||||
ConsecutiveFailures: b.consecutive,
|
ConsecutiveFailures: b.consecutive,
|
||||||
LastNote: b.lastNote,
|
LastNote: b.lastNote,
|
||||||
Detail: b.detail,
|
Detail: b.detail,
|
||||||
|
SelectionSkipped: b.selectionSkipped,
|
||||||
|
}
|
||||||
|
if min, mean, median, p95, max, ok := latencyOf(b.rtts); ok {
|
||||||
|
s.MinRttMs = &min
|
||||||
|
s.MeanRttMs = &mean
|
||||||
|
s.MedianRttMs = &median
|
||||||
|
s.P95RttMs = &p95
|
||||||
|
s.MaxRttMs = &max
|
||||||
}
|
}
|
||||||
if b.lastRttMs != nil {
|
if b.lastRttMs != nil {
|
||||||
v := *b.lastRttMs
|
v := *b.lastRttMs
|
||||||
@@ -197,6 +210,12 @@ type summaryMsg struct {
|
|||||||
ProbeLossPct *float64 `json:"probeLossPct,omitempty"`
|
ProbeLossPct *float64 `json:"probeLossPct,omitempty"`
|
||||||
FailurePct *float64 `json:"failurePct,omitempty"`
|
FailurePct *float64 `json:"failurePct,omitempty"`
|
||||||
UnknownPct *float64 `json:"unknownPct,omitempty"`
|
UnknownPct *float64 `json:"unknownPct,omitempty"`
|
||||||
|
MinRttMs *float64 `json:"minRttMs,omitempty"`
|
||||||
|
MeanRttMs *float64 `json:"meanRttMs,omitempty"`
|
||||||
|
MedianRttMs *float64 `json:"medianRttMs,omitempty"`
|
||||||
|
P95RttMs *float64 `json:"p95RttMs,omitempty"`
|
||||||
|
MaxRttMs *float64 `json:"maxRttMs,omitempty"`
|
||||||
|
SelectionSkipped int `json:"selectionSkipped,omitempty"`
|
||||||
LastNote string `json:"lastNote,omitempty"`
|
LastNote string `json:"lastNote,omitempty"`
|
||||||
Detail map[string]string `json:"detail,omitempty"`
|
Detail map[string]string `json:"detail,omitempty"`
|
||||||
}
|
}
|
||||||
+48
-4
@@ -21,6 +21,7 @@ type jobSpec struct {
|
|||||||
Port int
|
Port int
|
||||||
Profile string
|
Profile string
|
||||||
IP net.IP
|
IP net.IP
|
||||||
|
state *dialState
|
||||||
Interval time.Duration
|
Interval time.Duration
|
||||||
Timeout time.Duration
|
Timeout time.Duration
|
||||||
Duration time.Duration
|
Duration time.Duration
|
||||||
@@ -110,6 +111,7 @@ func (n *Node) info(w http.ResponseWriter, _ *http.Request) {
|
|||||||
vis = "public"
|
vis = "public"
|
||||||
}
|
}
|
||||||
writeJSON(w, http.StatusOK, map[string]any{
|
writeJSON(w, http.StatusOK, map[string]any{
|
||||||
|
"version": appVersion,
|
||||||
"visibility": vis,
|
"visibility": vis,
|
||||||
"authRequired": !n.Public(),
|
"authRequired": !n.Public(),
|
||||||
"profiles": []string{
|
"profiles": []string{
|
||||||
@@ -185,10 +187,19 @@ func (n *Node) create(w http.ResponseWriter, r *http.Request) {
|
|||||||
writeErr(w, http.StatusInternalServerError, "error", "任务没有启动")
|
writeErr(w, http.StatusInternalServerError, "error", "任务没有启动")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
resolved := make([]map[string]string, 0, len(spec.candidates()))
|
||||||
|
for _, ip := range spec.candidates() {
|
||||||
|
resolved = append(resolved, map[string]string{
|
||||||
|
"address": ip.String(),
|
||||||
|
"family": familyOf(ip),
|
||||||
|
})
|
||||||
|
}
|
||||||
writeJSON(w, http.StatusCreated, map[string]any{
|
writeJSON(w, http.StatusCreated, map[string]any{
|
||||||
"jobId": job.id,
|
"jobId": job.id,
|
||||||
"expiresAt": job.expires.UTC().Format(time.RFC3339),
|
"expiresAt": job.expires.UTC().Format(time.RFC3339),
|
||||||
"visibility": map[bool]string{true: "public", false: "private"}[n.Public()],
|
"visibility": map[bool]string{true: "public", false: "private"}[n.Public()],
|
||||||
|
"version": appVersion,
|
||||||
|
"resolved": resolved,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -246,7 +257,7 @@ func (n *Node) prepare(ctx context.Context, req createReq) (jobSpec, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ip, err := targetOK(ctx, n.Resolver, req.Target, n.AllowPrivate, n.ExtraNets)
|
ips, err := resolveTargets(ctx, n.Resolver, req.Target, n.AllowPrivate, n.ExtraNets)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
var dnsErr *net.DNSError
|
var dnsErr *net.DNSError
|
||||||
if errors.As(err, &dnsErr) {
|
if errors.As(err, &dnsErr) {
|
||||||
@@ -258,7 +269,8 @@ func (n *Node) prepare(ctx context.Context, req createReq) (jobSpec, error) {
|
|||||||
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_target", "目标地址无效"}
|
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_target", "目标地址无效"}
|
||||||
}
|
}
|
||||||
return jobSpec{
|
return jobSpec{
|
||||||
Host: req.Target, Port: req.Port, Profile: req.Profile, IP: ip,
|
Host: req.Target, Port: req.Port, Profile: req.Profile, IP: ips[0],
|
||||||
|
state: &dialState{picker: newEndpointPicker(ips)},
|
||||||
Interval: interval, Timeout: timeout, Duration: duration, PacketSize: size,
|
Interval: interval, Timeout: timeout, Duration: duration, PacketSize: size,
|
||||||
Echo: echo, DNSName: req.DNSName, Payload: payload, Expect: expect,
|
Echo: echo, DNSName: req.DNSName, Payload: payload, Expect: expect,
|
||||||
}, nil
|
}, nil
|
||||||
@@ -334,18 +346,50 @@ func (n *Node) run(ctx context.Context, job *probeJob, spec jobSpec, p prober) {
|
|||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
ledger := &selectionLedger{candidates: len(spec.candidates())}
|
||||||
|
datagram := datagramProfile(spec.Profile)
|
||||||
for {
|
for {
|
||||||
if err := n.pace.wait(ctx, spec.PacketSize); err != nil {
|
if err := n.pace.wait(ctx, spec.PacketSize); err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
started := time.Now()
|
started := time.Now()
|
||||||
pctx, cancel := context.WithTimeout(ctx, spec.Timeout)
|
budget := spec.Timeout
|
||||||
|
if budget <= 0 {
|
||||||
|
budget = 1500 * time.Millisecond
|
||||||
|
}
|
||||||
|
if !datagram && spec.state != nil && spec.state.picker != nil && !spec.state.picker.locked && len(spec.state.picker.ips) > 1 {
|
||||||
|
budget *= time.Duration(len(spec.state.picker.ips))
|
||||||
|
}
|
||||||
|
if datagram && spec.state != nil {
|
||||||
|
if ip := spec.dialIP(); ip != nil {
|
||||||
|
spec.state.used = append(net.IP(nil), ip...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pctx, cancel := context.WithTimeout(ctx, budget)
|
||||||
out := p.Probe(pctx)
|
out := p.Probe(pctx)
|
||||||
cancel()
|
cancel()
|
||||||
if ctx.Err() != nil {
|
if ctx.Err() != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
emit(out)
|
out = spec.decorate(out)
|
||||||
|
var commit []Outcome
|
||||||
|
if datagram && spec.state != nil && spec.state.picker != nil {
|
||||||
|
responded := selectionResponded(out.Status)
|
||||||
|
wasMeasuring := ledger.measuring
|
||||||
|
changed := spec.state.picker.record(responded)
|
||||||
|
commit, _ = ledger.take(out, responded)
|
||||||
|
if wasMeasuring && changed {
|
||||||
|
ledger.measuring = false
|
||||||
|
}
|
||||||
|
if len(commit) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
commit = []Outcome{out}
|
||||||
|
}
|
||||||
|
for _, item := range commit {
|
||||||
|
emit(item)
|
||||||
|
}
|
||||||
wait := spec.Interval - time.Since(started)
|
wait := spec.Interval - time.Since(started)
|
||||||
if wait < 0 {
|
if wait < 0 {
|
||||||
wait = 0
|
wait = 0
|
||||||
|
|||||||
@@ -163,6 +163,12 @@ func TestNodeNQAndTCPAndUDP(t *testing.T) {
|
|||||||
if sample.Status != statusOK || sample.RttMs == nil || *sample.RttMs <= 0 {
|
if sample.Status != statusOK || sample.RttMs == nil || *sample.RttMs <= 0 {
|
||||||
t.Fatalf("nq tcp %+v", sample)
|
t.Fatalf("nq tcp %+v", sample)
|
||||||
}
|
}
|
||||||
|
if sample.Detail["address"] != "127.0.0.1" || sample.Detail["family"] != "IPv4" {
|
||||||
|
t.Fatalf("tcp did not report the connected address %+v", sample.Detail)
|
||||||
|
}
|
||||||
|
if sample.Summary.MinRttMs == nil || sample.Summary.P95RttMs == nil {
|
||||||
|
t.Fatalf("latency stats missing %+v", sample.Summary)
|
||||||
|
}
|
||||||
if sample.Summary.ProbeLossPct == nil || *sample.Summary.ProbeLossPct != 0 {
|
if sample.Summary.ProbeLossPct == nil || *sample.Summary.ProbeLossPct != 0 {
|
||||||
t.Fatalf("loss %+v", sample.Summary)
|
t.Fatalf("loss %+v", sample.Summary)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
@echo off
|
||||||
|
chcp 65001 >nul
|
||||||
|
cd /d "%~dp0"
|
||||||
|
echo 正在启动网络质量探测节点。端口和口令请改同目录下的 .env
|
||||||
|
netquality-reflector.exe
|
||||||
|
echo.
|
||||||
|
echo 程序已退出。如果上面有报错,请检查 .env 后重新双击本文件。
|
||||||
|
pause
|
||||||
+23
-25
@@ -127,7 +127,7 @@ func (p *nqTCP) Close() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *nqTCP) dial(ctx context.Context) error {
|
func (p *nqTCP) dial(ctx context.Context) error {
|
||||||
conn, err := dialTCP(ctx, p.spec.IP, p.spec.Port)
|
conn, err := dialSpecTCP(ctx, &p.spec)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -208,11 +208,9 @@ func (p *nqUDP) Close() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *nqUDP) ensure() error {
|
func (p *nqUDP) ensure() error {
|
||||||
if p.conn != nil {
|
c, err := ensureUDP(p.conn, p.spec)
|
||||||
return nil
|
|
||||||
}
|
|
||||||
c, err := dialUDP(p.spec.IP, p.spec.Port)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
p.conn = nil
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
p.conn = c
|
p.conn = c
|
||||||
@@ -273,7 +271,7 @@ func (p *tcpConnect) Close() error { return nil }
|
|||||||
|
|
||||||
func (p *tcpConnect) Probe(ctx context.Context) Outcome {
|
func (p *tcpConnect) Probe(ctx context.Context) Outcome {
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
conn, err := dialTCP(ctx, p.spec.IP, p.spec.Port)
|
conn, err := dialSpecTCP(ctx, &p.spec)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return classifyDial(err)
|
return classifyDial(err)
|
||||||
}
|
}
|
||||||
@@ -297,13 +295,12 @@ func (p *udpQuery) Close() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *udpQuery) Probe(ctx context.Context) Outcome {
|
func (p *udpQuery) Probe(ctx context.Context) Outcome {
|
||||||
if p.conn == nil {
|
c, err := ensureUDP(p.conn, p.spec)
|
||||||
c, err := dialUDP(p.spec.IP, p.spec.Port)
|
if err != nil {
|
||||||
if err != nil {
|
p.conn = nil
|
||||||
return classifyDial(err)
|
return classifyDial(err)
|
||||||
}
|
|
||||||
p.conn = c
|
|
||||||
}
|
}
|
||||||
|
p.conn = c
|
||||||
payload := p.spec.Payload
|
payload := p.spec.Payload
|
||||||
if p.generic {
|
if p.generic {
|
||||||
n := p.spec.PacketSize
|
n := p.spec.PacketSize
|
||||||
@@ -358,13 +355,12 @@ func (p *dnsQuery) Close() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *dnsQuery) Probe(ctx context.Context) Outcome {
|
func (p *dnsQuery) Probe(ctx context.Context) Outcome {
|
||||||
if p.conn == nil {
|
c, err := ensureUDP(p.conn, p.spec)
|
||||||
c, err := dialUDP(p.spec.IP, p.spec.Port)
|
if err != nil {
|
||||||
if err != nil {
|
p.conn = nil
|
||||||
return classifyDial(err)
|
return classifyDial(err)
|
||||||
}
|
|
||||||
p.conn = c
|
|
||||||
}
|
}
|
||||||
|
p.conn = c
|
||||||
p.id++
|
p.id++
|
||||||
if p.id == 0 {
|
if p.id == 0 {
|
||||||
p.id = 1
|
p.id = 1
|
||||||
@@ -449,12 +445,14 @@ func (p *mcBedrock) Close() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *mcBedrock) Probe(ctx context.Context) Outcome {
|
func (p *mcBedrock) Probe(ctx context.Context) Outcome {
|
||||||
if p.conn == nil {
|
fresh := p.conn == nil
|
||||||
c, err := dialUDP(p.spec.IP, p.spec.Port)
|
c, err := ensureUDP(p.conn, p.spec)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return classifyDial(err)
|
p.conn = nil
|
||||||
}
|
return classifyDial(err)
|
||||||
p.conn = c
|
}
|
||||||
|
p.conn = c
|
||||||
|
if fresh || p.guid == 0 {
|
||||||
p.guid = uint64(time.Now().UnixNano())
|
p.guid = uint64(time.Now().UnixNano())
|
||||||
}
|
}
|
||||||
ts := uint64(time.Now().UnixNano())
|
ts := uint64(time.Now().UnixNano())
|
||||||
@@ -529,7 +527,7 @@ type mcJava struct{ spec jobSpec }
|
|||||||
func (p *mcJava) Close() error { return nil }
|
func (p *mcJava) Close() error { return nil }
|
||||||
|
|
||||||
func (p *mcJava) Probe(ctx context.Context) Outcome {
|
func (p *mcJava) Probe(ctx context.Context) Outcome {
|
||||||
conn, err := dialTCP(ctx, p.spec.IP, p.spec.Port)
|
conn, err := dialSpecTCP(ctx, &p.spec)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return classifyDial(err)
|
return classifyDial(err)
|
||||||
}
|
}
|
||||||
|
|||||||
+12
-3
@@ -25,8 +25,17 @@ var metadataIP = net.ParseIP("169.254.169.254")
|
|||||||
// Loopback, private, link-local and cloud metadata are rejected unless
|
// Loopback, private, link-local and cloud metadata are rejected unless
|
||||||
// allowPrivate is set. Metadata addresses stay blocked either way.
|
// allowPrivate is set. Metadata addresses stay blocked either way.
|
||||||
// Every resolved address is checked so a later DNS answer cannot rebind
|
// Every resolved address is checked so a later DNS answer cannot rebind
|
||||||
// the dial onto a forbidden IP; the caller dials only the returned IP.
|
// the dial onto a forbidden IP. targetOK returns the first allowed address;
|
||||||
|
// resolveTargets returns every allowed address in resolver order.
|
||||||
func targetOK(ctx context.Context, resolver resolver, host string, allowPrivate bool, extra []*net.IPNet) (net.IP, error) {
|
func targetOK(ctx context.Context, resolver resolver, host string, allowPrivate bool, extra []*net.IPNet) (net.IP, error) {
|
||||||
|
ips, err := resolveTargets(ctx, resolver, host, allowPrivate, extra)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return ips[0], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveTargets(ctx context.Context, resolver resolver, host string, allowPrivate bool, extra []*net.IPNet) ([]net.IP, error) {
|
||||||
host = strings.TrimSpace(host)
|
host = strings.TrimSpace(host)
|
||||||
host = strings.Trim(host, "[]")
|
host = strings.Trim(host, "[]")
|
||||||
if host == "" {
|
if host == "" {
|
||||||
@@ -39,7 +48,7 @@ func targetOK(ctx context.Context, resolver resolver, host string, allowPrivate
|
|||||||
if !ipAllowed(ip, allowPrivate, extra) {
|
if !ipAllowed(ip, allowPrivate, extra) {
|
||||||
return nil, fmt.Errorf("%w: %s", errForbiddenTarget, ip.String())
|
return nil, fmt.Errorf("%w: %s", errForbiddenTarget, ip.String())
|
||||||
}
|
}
|
||||||
return ip, nil
|
return []net.IP{ip}, nil
|
||||||
}
|
}
|
||||||
if resolver == nil {
|
if resolver == nil {
|
||||||
resolver = net.DefaultResolver
|
resolver = net.DefaultResolver
|
||||||
@@ -65,7 +74,7 @@ func targetOK(ctx context.Context, resolver resolver, host string, allowPrivate
|
|||||||
if len(allowed) != len(addrs) {
|
if len(allowed) != len(addrs) {
|
||||||
return nil, fmt.Errorf("%w: %s resolved to a mix of public and blocked addresses", errForbiddenTarget, host)
|
return nil, fmt.Errorf("%w: %s resolved to a mix of public and blocked addresses", errForbiddenTarget, host)
|
||||||
}
|
}
|
||||||
return allowed[0], nil
|
return allowed, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func ipAllowed(ip net.IP, allowPrivate bool, extra []*net.IPNet) bool {
|
func ipAllowed(ip net.IP, allowPrivate bool, extra []*net.IPNet) bool {
|
||||||
|
|||||||
@@ -0,0 +1,368 @@
|
|||||||
|
// Copyright (C) 2026 言灸
|
||||||
|
// SPDX-License-Identifier: AGPL-3.0-only
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const appVersion = "1.1.2"
|
||||||
|
|
||||||
|
// dialState is shared by the job runner and the prober. Both hold a copy of
|
||||||
|
// jobSpec, so the mutable address choice has to live behind a pointer.
|
||||||
|
type dialState struct {
|
||||||
|
picker *endpointPicker
|
||||||
|
used net.IP
|
||||||
|
fallback string
|
||||||
|
skipped int
|
||||||
|
}
|
||||||
|
|
||||||
|
type endpointPicker struct {
|
||||||
|
ips []net.IP
|
||||||
|
index int
|
||||||
|
misses int
|
||||||
|
locked bool
|
||||||
|
sticky int
|
||||||
|
}
|
||||||
|
|
||||||
|
func newEndpointPicker(ips []net.IP) *endpointPicker {
|
||||||
|
return &endpointPicker{ips: append([]net.IP(nil), ips...), sticky: 3}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *endpointPicker) current() net.IP {
|
||||||
|
if p == nil || len(p.ips) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return p.ips[p.index]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *endpointPicker) lock(ip net.IP) {
|
||||||
|
for i, cand := range p.ips {
|
||||||
|
if cand.Equal(ip) {
|
||||||
|
p.index = i
|
||||||
|
p.locked = true
|
||||||
|
p.misses = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// record matches the client EndpointPicker: one miss rotates until some
|
||||||
|
// address has answered; after that, sticky misses are required.
|
||||||
|
func (p *endpointPicker) record(responded bool) bool {
|
||||||
|
if responded {
|
||||||
|
p.locked = true
|
||||||
|
p.misses = 0
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
p.misses++
|
||||||
|
limit := 1
|
||||||
|
if p.locked {
|
||||||
|
limit = p.sticky
|
||||||
|
}
|
||||||
|
if len(p.ips) < 2 || p.misses < limit {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
p.misses = 0
|
||||||
|
p.locked = false
|
||||||
|
p.index = (p.index + 1) % len(p.ips)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s jobSpec) candidates() []net.IP {
|
||||||
|
if s.state != nil && s.state.picker != nil && len(s.state.picker.ips) > 0 {
|
||||||
|
return s.state.picker.ips
|
||||||
|
}
|
||||||
|
if s.IP != nil {
|
||||||
|
return []net.IP{s.IP}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s jobSpec) dialIP() net.IP {
|
||||||
|
if s.state != nil && s.state.picker != nil {
|
||||||
|
if ip := s.state.picker.current(); ip != nil {
|
||||||
|
return ip
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s.IP != nil {
|
||||||
|
return s.IP
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func familyOf(ip net.IP) string {
|
||||||
|
if ip == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if ip.To4() != nil {
|
||||||
|
return "IPv4"
|
||||||
|
}
|
||||||
|
return "IPv6"
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyDetail(in map[string]string) map[string]string {
|
||||||
|
out := make(map[string]string, len(in)+2)
|
||||||
|
for k, v := range in {
|
||||||
|
out[k] = v
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func stampIP(o Outcome, ip net.IP) Outcome {
|
||||||
|
if ip == nil {
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
o.Detail = copyDetail(o.Detail)
|
||||||
|
o.Detail["address"] = ip.String()
|
||||||
|
o.Detail["family"] = familyOf(ip)
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
// decorate attaches the address actually dialed. Candidate-connect failures
|
||||||
|
// that were skipped in favor of a working address are copied onto this one
|
||||||
|
// outcome and then cleared, so they are not repeated on later probes.
|
||||||
|
func (s jobSpec) decorate(o Outcome) Outcome {
|
||||||
|
if s.state == nil {
|
||||||
|
if s.IP != nil {
|
||||||
|
return stampIP(o, s.IP)
|
||||||
|
}
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
if s.state.used != nil {
|
||||||
|
o = stampIP(o, s.state.used)
|
||||||
|
}
|
||||||
|
if s.state.fallback != "" {
|
||||||
|
o.Detail = copyDetail(o.Detail)
|
||||||
|
o.Detail["fallback"] = s.state.fallback
|
||||||
|
s.state.fallback = ""
|
||||||
|
}
|
||||||
|
if s.state.skipped > 0 {
|
||||||
|
o.SelectionSkipped += s.state.skipped
|
||||||
|
s.state.skipped = 0
|
||||||
|
}
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
func selectionResponded(status string) bool {
|
||||||
|
switch status {
|
||||||
|
case statusOK, statusProtocol, statusRefused:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func datagramProfile(profile string) bool {
|
||||||
|
switch profile {
|
||||||
|
case "nq-udp", "udp-generic", "custom-udp", "dns", "minecraft-bedrock":
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type selectionLedger struct {
|
||||||
|
candidates int
|
||||||
|
measuring bool
|
||||||
|
held []Outcome
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *selectionLedger) take(o Outcome, responded bool) (commit []Outcome, skipped int) {
|
||||||
|
if l.candidates <= 1 {
|
||||||
|
if responded {
|
||||||
|
l.measuring = true
|
||||||
|
}
|
||||||
|
return []Outcome{o}, 0
|
||||||
|
}
|
||||||
|
if l.measuring {
|
||||||
|
return []Outcome{o}, 0
|
||||||
|
}
|
||||||
|
if responded {
|
||||||
|
skipped = len(l.held)
|
||||||
|
if skipped > 0 {
|
||||||
|
o.Detail = copyDetail(o.Detail)
|
||||||
|
o.Detail["fallback"] = fallbackFromHeld(l.held, o)
|
||||||
|
o.SelectionSkipped += skipped
|
||||||
|
}
|
||||||
|
l.held = nil
|
||||||
|
l.measuring = true
|
||||||
|
return []Outcome{o}, skipped
|
||||||
|
}
|
||||||
|
l.held = append(l.held, o)
|
||||||
|
if len(l.held) >= l.candidates {
|
||||||
|
commit = append([]Outcome(nil), l.held...)
|
||||||
|
l.held = nil
|
||||||
|
return commit, 0
|
||||||
|
}
|
||||||
|
return nil, 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func fallbackFromHeld(held []Outcome, success Outcome) string {
|
||||||
|
parts := make([]string, 0, len(held))
|
||||||
|
for _, o := range held {
|
||||||
|
addr := ""
|
||||||
|
fam := ""
|
||||||
|
if o.Detail != nil {
|
||||||
|
addr = o.Detail["address"]
|
||||||
|
fam = o.Detail["family"]
|
||||||
|
}
|
||||||
|
where := "未知地址"
|
||||||
|
if addr != "" {
|
||||||
|
where = addr
|
||||||
|
if fam != "" {
|
||||||
|
where = addr + "(" + fam + ")"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
why := o.Note
|
||||||
|
if why == "" {
|
||||||
|
why = "没有成功"
|
||||||
|
}
|
||||||
|
parts = append(parts, where+":"+why)
|
||||||
|
}
|
||||||
|
used := ""
|
||||||
|
usedFam := ""
|
||||||
|
if success.Detail != nil {
|
||||||
|
used = success.Detail["address"]
|
||||||
|
usedFam = success.Detail["family"]
|
||||||
|
}
|
||||||
|
usedText := "另一个地址"
|
||||||
|
if used != "" {
|
||||||
|
usedText = used
|
||||||
|
if usedFam != "" {
|
||||||
|
usedText = used + "(" + usedFam + ")"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "候选未成功:" + strings.Join(parts, ";") + "。已改用 " + usedText + "。这些失败没有计入正式丢包或失败率。"
|
||||||
|
}
|
||||||
|
|
||||||
|
type dialFunc func(context.Context, net.IP) (net.Conn, error)
|
||||||
|
|
||||||
|
// dialFirst tries each address with its own timeout. A failure is described
|
||||||
|
// and not returned as a separate measured attempt. If a later address
|
||||||
|
// connects, the skipped notes are returned for the diagnostic. If every
|
||||||
|
// address fails, err is the last error. A cancelled parent context does not
|
||||||
|
// become a measured timeout.
|
||||||
|
func dialFirst(ctx context.Context, ips []net.IP, timeout time.Duration, dial dialFunc) (net.Conn, net.IP, []string, error) {
|
||||||
|
if len(ips) == 0 {
|
||||||
|
return nil, nil, nil, errors.New("no address")
|
||||||
|
}
|
||||||
|
if timeout <= 0 {
|
||||||
|
timeout = 1500 * time.Millisecond
|
||||||
|
}
|
||||||
|
var skipped []string
|
||||||
|
var last error
|
||||||
|
for _, ip := range ips {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, nil, skipped, err
|
||||||
|
}
|
||||||
|
dialCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||||
|
conn, err := dial(dialCtx, ip)
|
||||||
|
cancel()
|
||||||
|
if err == nil {
|
||||||
|
return conn, ip, skipped, nil
|
||||||
|
}
|
||||||
|
if errors.Is(err, context.Canceled) && ctx.Err() != nil {
|
||||||
|
return nil, nil, skipped, ctx.Err()
|
||||||
|
}
|
||||||
|
skipped = append(skipped, fmt.Sprintf("%s %s %s", familyOf(ip), ip.String(), classifyDial(err).Note))
|
||||||
|
last = err
|
||||||
|
}
|
||||||
|
if last == nil {
|
||||||
|
last = errors.New("连接失败")
|
||||||
|
}
|
||||||
|
return nil, nil, skipped, last
|
||||||
|
}
|
||||||
|
|
||||||
|
func dialSpecTCP(ctx context.Context, spec *jobSpec) (net.Conn, error) {
|
||||||
|
ips := spec.candidates()
|
||||||
|
start := 0
|
||||||
|
if spec.state != nil && spec.state.picker != nil {
|
||||||
|
start = spec.state.picker.index
|
||||||
|
}
|
||||||
|
rotated := make([]net.IP, 0, len(ips))
|
||||||
|
for n := 0; n < len(ips); n++ {
|
||||||
|
rotated = append(rotated, ips[(start+n)%len(ips)])
|
||||||
|
}
|
||||||
|
conn, ip, skipped, err := dialFirst(ctx, rotated, spec.Timeout, func(ctx context.Context, ip net.IP) (net.Conn, error) {
|
||||||
|
return dialTCP(ctx, ip, spec.Port)
|
||||||
|
})
|
||||||
|
if spec.state != nil {
|
||||||
|
spec.state.used = nil
|
||||||
|
spec.state.fallback = ""
|
||||||
|
spec.state.skipped = 0
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
if spec.state != nil && len(skipped) > 0 && !errors.Is(err, context.Canceled) {
|
||||||
|
spec.state.fallback = "已尝试 " + strings.Join(skipped, ";") + "。没有地址连通,这次记为失败。"
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if spec.state != nil {
|
||||||
|
if spec.state.picker != nil {
|
||||||
|
spec.state.picker.lock(ip)
|
||||||
|
}
|
||||||
|
spec.state.used = append(net.IP(nil), ip...)
|
||||||
|
if len(skipped) > 0 {
|
||||||
|
spec.state.skipped = len(skipped)
|
||||||
|
spec.state.fallback = "候选未连通:" + strings.Join(skipped, ";") + "。已改用 " + ip.String() + "(" + familyOf(ip) + ")。这些失败没有计入正式丢包或失败率。"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return conn, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureUDP(conn *net.UDPConn, spec jobSpec) (*net.UDPConn, error) {
|
||||||
|
want := spec.dialIP()
|
||||||
|
if want == nil {
|
||||||
|
return nil, errors.New("no address")
|
||||||
|
}
|
||||||
|
if conn != nil {
|
||||||
|
if ra, ok := conn.RemoteAddr().(*net.UDPAddr); ok && ra.IP.Equal(want) {
|
||||||
|
return conn, nil
|
||||||
|
}
|
||||||
|
_ = conn.Close()
|
||||||
|
}
|
||||||
|
return dialUDP(want, spec.Port)
|
||||||
|
}
|
||||||
|
|
||||||
|
// nearestRank95 is ceil(0.95*n) in integer arithmetic.
|
||||||
|
func nearestRank95(n int) int {
|
||||||
|
if n <= 1 {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
rank := (95*n + 99) / 100
|
||||||
|
if rank < 1 {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if rank > n {
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
return rank
|
||||||
|
}
|
||||||
|
|
||||||
|
func latencyOf(samples []float64) (min, mean, median, p95, max float64, ok bool) {
|
||||||
|
if len(samples) == 0 {
|
||||||
|
return 0, 0, 0, 0, 0, false
|
||||||
|
}
|
||||||
|
sorted := append([]float64(nil), samples...)
|
||||||
|
sort.Float64s(sorted)
|
||||||
|
var sum float64
|
||||||
|
for _, v := range sorted {
|
||||||
|
sum += v
|
||||||
|
}
|
||||||
|
n := len(sorted)
|
||||||
|
if n%2 == 1 {
|
||||||
|
median = sorted[n/2]
|
||||||
|
} else {
|
||||||
|
median = (sorted[n/2-1] + sorted[n/2]) / 2
|
||||||
|
}
|
||||||
|
rank := nearestRank95(n)
|
||||||
|
return sorted[0], sum / float64(n), median, sorted[rank-1], sorted[n-1], true
|
||||||
|
}
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSelectionLedgerDoesNotCountFallback(t *testing.T) {
|
||||||
|
ledger := &selectionLedger{candidates: 2}
|
||||||
|
miss := Outcome{
|
||||||
|
Status: statusTimeout,
|
||||||
|
Kind: kindProbe,
|
||||||
|
Note: "未收到回显",
|
||||||
|
Detail: map[string]string{"address": "2001:db8::1", "family": "IPv6"},
|
||||||
|
}
|
||||||
|
commit, skipped := ledger.take(miss, false)
|
||||||
|
if commit != nil || skipped != 0 {
|
||||||
|
t.Fatalf("held failure was counted: %+v %d", commit, skipped)
|
||||||
|
}
|
||||||
|
ok := Outcome{
|
||||||
|
Status: statusOK,
|
||||||
|
Kind: kindProbe,
|
||||||
|
HasRtt: true,
|
||||||
|
Rtt: 5 * time.Millisecond,
|
||||||
|
Note: "收到回显",
|
||||||
|
Detail: map[string]string{"address": "203.0.113.5", "family": "IPv4"},
|
||||||
|
}
|
||||||
|
commit, skipped = ledger.take(ok, true)
|
||||||
|
if skipped != 1 || len(commit) != 1 || commit[0].SelectionSkipped != 1 {
|
||||||
|
t.Fatalf("success %+v skipped %d", commit, skipped)
|
||||||
|
}
|
||||||
|
if commit[0].Detail["fallback"] == "" || !containsAll(commit[0].Detail["fallback"], "2001:db8::1", "203.0.113.5", "没有计入") {
|
||||||
|
t.Fatalf("fallback %q", commit[0].Detail["fallback"])
|
||||||
|
}
|
||||||
|
book := &sampleBook{profile: "nq-udp"}
|
||||||
|
book.add(commit[0])
|
||||||
|
summary := book.summary()
|
||||||
|
if summary.Sent != 1 || summary.OK != 1 || summary.Timeout != 0 || summary.ProbeLossPct == nil || *summary.ProbeLossPct != 0 {
|
||||||
|
t.Fatalf("summary %+v", summary)
|
||||||
|
}
|
||||||
|
if summary.SelectionSkipped != 1 || summary.MinRttMs == nil || *summary.MinRttMs != 5 || summary.P95RttMs == nil || *summary.P95RttMs != 5 {
|
||||||
|
t.Fatalf("stats %+v", summary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSelectionLedgerCommitsTotalFailure(t *testing.T) {
|
||||||
|
ledger := &selectionLedger{candidates: 2}
|
||||||
|
first := Outcome{Status: statusTimeout, Kind: kindProbe, Detail: map[string]string{"address": "2001:db8::1", "family": "IPv6"}}
|
||||||
|
second := Outcome{Status: statusTimeout, Kind: kindProbe, Detail: map[string]string{"address": "203.0.113.5", "family": "IPv4"}}
|
||||||
|
if commit, _ := ledger.take(first, false); commit != nil {
|
||||||
|
t.Fatal("first failure committed early")
|
||||||
|
}
|
||||||
|
commit, _ := ledger.take(second, false)
|
||||||
|
if len(commit) != 2 {
|
||||||
|
t.Fatalf("commit %+v", commit)
|
||||||
|
}
|
||||||
|
book := &sampleBook{profile: "nq-udp"}
|
||||||
|
for _, outcome := range commit {
|
||||||
|
book.add(outcome)
|
||||||
|
}
|
||||||
|
summary := book.summary()
|
||||||
|
if summary.OK != 0 || summary.Sent != 2 || summary.ProbeLossPct == nil || *summary.ProbeLossPct != 100 {
|
||||||
|
t.Fatalf("summary %+v", summary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMeasuredTimeoutStillCounts(t *testing.T) {
|
||||||
|
ledger := &selectionLedger{candidates: 2}
|
||||||
|
ok := Outcome{Status: statusOK, Kind: kindProbe, HasRtt: true, Rtt: 4 * time.Millisecond}
|
||||||
|
if commit, _ := ledger.take(ok, true); len(commit) != 1 {
|
||||||
|
t.Fatal(commit)
|
||||||
|
}
|
||||||
|
miss := Outcome{Status: statusTimeout, Kind: kindProbe}
|
||||||
|
commit, _ := ledger.take(miss, false)
|
||||||
|
if len(commit) != 1 || commit[0].Status != statusTimeout {
|
||||||
|
t.Fatalf("post-selection miss hidden: %+v", commit)
|
||||||
|
}
|
||||||
|
book := &sampleBook{profile: "nq-udp"}
|
||||||
|
book.add(ok)
|
||||||
|
book.add(commit[0])
|
||||||
|
summary := book.summary()
|
||||||
|
if summary.ProbeLossPct == nil || *summary.ProbeLossPct != 50 || summary.Sent != 2 {
|
||||||
|
t.Fatalf("summary %+v", summary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLatencyRanks(t *testing.T) {
|
||||||
|
if nearestRank95(1) != 1 || nearestRank95(2) != 2 || nearestRank95(4) != 4 || nearestRank95(5) != 5 || nearestRank95(20) != 19 {
|
||||||
|
t.Fatalf("ranks %d %d %d %d %d", nearestRank95(1), nearestRank95(2), nearestRank95(4), nearestRank95(5), nearestRank95(20))
|
||||||
|
}
|
||||||
|
min, mean, median, p95, max, ok := latencyOf([]float64{1, 2, 3, 4})
|
||||||
|
if !ok || min != 1 || mean != 2.5 || median != 2.5 || p95 != 4 || max != 4 {
|
||||||
|
t.Fatalf("four %v %v %v %v %v", min, mean, median, p95, max)
|
||||||
|
}
|
||||||
|
_, _, median, p95, _, ok = latencyOf([]float64{1, 2, 3, 4, 10})
|
||||||
|
if !ok || median != 3 || p95 != 10 {
|
||||||
|
t.Fatalf("five median %v p95 %v", median, p95)
|
||||||
|
}
|
||||||
|
_, _, _, _, _, ok = latencyOf(nil)
|
||||||
|
if ok {
|
||||||
|
t.Fatal("empty latency")
|
||||||
|
}
|
||||||
|
book := &sampleBook{profile: "nq-udp"}
|
||||||
|
book.add(Outcome{Status: statusOK, Kind: kindProbe, HasRtt: true, Rtt: time.Millisecond})
|
||||||
|
book.add(Outcome{Status: statusOK, Kind: kindProbe, HasRtt: true, Rtt: 4 * time.Millisecond})
|
||||||
|
summary := book.summary()
|
||||||
|
if summary.MinRttMs == nil || *summary.MinRttMs != 1 || summary.MaxRttMs == nil || *summary.MaxRttMs != 4 || summary.MedianRttMs == nil || *summary.MedianRttMs != 2.5 {
|
||||||
|
t.Fatalf("aliased latency %+v", summary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDialFirstSkipsFailedCandidate(t *testing.T) {
|
||||||
|
good, bad := net.Pipe()
|
||||||
|
defer good.Close()
|
||||||
|
defer bad.Close()
|
||||||
|
v6 := net.ParseIP("2001:db8::1")
|
||||||
|
v4 := net.ParseIP("203.0.113.5")
|
||||||
|
calls := 0
|
||||||
|
conn, used, skipped, err := dialFirst(context.Background(), []net.IP{v6, v4}, time.Second, func(ctx context.Context, ip net.IP) (net.Conn, error) {
|
||||||
|
calls++
|
||||||
|
if ip.Equal(v6) {
|
||||||
|
return nil, errors.New("network unreachable")
|
||||||
|
}
|
||||||
|
return good, nil
|
||||||
|
})
|
||||||
|
if err != nil || !used.Equal(v4) || len(skipped) != 1 || calls != 2 {
|
||||||
|
t.Fatalf("used %v skipped %v err %v calls %d", used, skipped, err, calls)
|
||||||
|
}
|
||||||
|
_ = conn.Close()
|
||||||
|
|
||||||
|
_, _, skipped, err = dialFirst(context.Background(), []net.IP{v6, v4}, time.Second, func(context.Context, net.IP) (net.Conn, error) {
|
||||||
|
return nil, context.DeadlineExceeded
|
||||||
|
})
|
||||||
|
if err == nil || len(skipped) != 2 {
|
||||||
|
t.Fatalf("all-fail err %v skipped %v", err, skipped)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
_, _, _, err = dialFirst(ctx, []net.IP{v6, v4}, time.Second, func(context.Context, net.IP) (net.Conn, error) {
|
||||||
|
t.Fatal("dialled after cancel")
|
||||||
|
return nil, nil
|
||||||
|
})
|
||||||
|
if !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatalf("cancel err %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveTargetsKeepsOrder(t *testing.T) {
|
||||||
|
resolver := stubResolver{[]net.IP{net.ParseIP("2001:db8::1"), net.ParseIP("203.0.113.5")}}
|
||||||
|
ips, err := resolveTargets(context.Background(), resolver, "example.com", false, nil)
|
||||||
|
if err != nil || len(ips) != 2 || ips[0].String() != "2001:db8::1" || ips[1].String() != "203.0.113.5" {
|
||||||
|
t.Fatalf("ips %v err %v", ips, err)
|
||||||
|
}
|
||||||
|
first, err := targetOK(context.Background(), resolver, "example.com", false, nil)
|
||||||
|
if err != nil || first.String() != "2001:db8::1" {
|
||||||
|
t.Fatalf("first %v err %v", first, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStopDoesNotRecordInFlight(t *testing.T) {
|
||||||
|
blackhole, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer blackhole.Close()
|
||||||
|
node := newNode("", true, nil, testLimits())
|
||||||
|
srv := httptest.NewServer(node.Handler())
|
||||||
|
defer srv.Close()
|
||||||
|
id := createJob(t, srv.URL, "", map[string]any{
|
||||||
|
"target": "127.0.0.1", "port": blackhole.LocalAddr().(*net.UDPAddr).Port,
|
||||||
|
"profile": "nq-udp", "intervalMs": 200, "timeoutMs": 4000, "durationSec": 5, "packetSize": 80,
|
||||||
|
})
|
||||||
|
time.Sleep(50 * time.Millisecond)
|
||||||
|
req, err := http.NewRequest(http.MethodDelete, srv.URL+"/v1/jobs/"+id, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
res, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
res.Body.Close()
|
||||||
|
time.Sleep(100 * time.Millisecond)
|
||||||
|
snapReq, err := http.NewRequest(http.MethodGet, srv.URL+"/v1/jobs/"+id, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
snapRes, err := http.DefaultClient.Do(snapReq)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer snapRes.Body.Close()
|
||||||
|
if snapRes.StatusCode == http.StatusNotFound {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
body, _ := io.ReadAll(snapRes.Body)
|
||||||
|
var msg sampleMsg
|
||||||
|
if err := json.Unmarshal(body, &msg); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if msg.Summary.Sent > 0 || msg.Status == statusTimeout || msg.Status == statusUnknown {
|
||||||
|
t.Fatalf("cancelled probe counted %s", body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNodeUDPFallbackIsNotLoss(t *testing.T) {
|
||||||
|
drop, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.ParseIP("127.0.0.2")})
|
||||||
|
if err != nil {
|
||||||
|
t.Skipf("127.0.0.2 unavailable: %v", err)
|
||||||
|
}
|
||||||
|
defer drop.Close()
|
||||||
|
go func() {
|
||||||
|
buf := make([]byte, 2048)
|
||||||
|
for {
|
||||||
|
if _, _, err := drop.ReadFromUDP(buf); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
port := drop.LocalAddr().(*net.UDPAddr).Port
|
||||||
|
echo, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: port})
|
||||||
|
if err != nil {
|
||||||
|
t.Skipf("paired echo: %v", err)
|
||||||
|
}
|
||||||
|
defer echo.Close()
|
||||||
|
reflector := &Server{}
|
||||||
|
go reflector.ServeUDP(echo)
|
||||||
|
defer reflector.Close()
|
||||||
|
|
||||||
|
node := newNode("", true, nil, testLimits())
|
||||||
|
node.Resolver = stubResolver{[]net.IP{net.ParseIP("127.0.0.2"), net.ParseIP("127.0.0.1")}}
|
||||||
|
srv := httptest.NewServer(node.Handler())
|
||||||
|
defer srv.Close()
|
||||||
|
id := createJob(t, srv.URL, "", map[string]any{
|
||||||
|
"target": "example.test", "port": port, "profile": "nq-udp",
|
||||||
|
"intervalMs": 200, "timeoutMs": 300, "durationSec": 5, "packetSize": 80,
|
||||||
|
})
|
||||||
|
sample := readOneSample(t, srv.URL, "", id)
|
||||||
|
if sample.Status != statusOK || sample.Detail["address"] != "127.0.0.1" || sample.Detail["family"] != "IPv4" {
|
||||||
|
t.Fatalf("sample %+v", sample)
|
||||||
|
}
|
||||||
|
if sample.Summary.Sent != 1 || sample.Summary.Timeout != 0 || sample.Summary.ProbeLossPct == nil || *sample.Summary.ProbeLossPct != 0 || sample.Summary.SelectionSkipped != 1 {
|
||||||
|
t.Fatalf("loss polluted %+v", sample.Summary)
|
||||||
|
}
|
||||||
|
if !strings.Contains(sample.Detail["fallback"], "127.0.0.2") || !strings.Contains(sample.Detail["fallback"], "没有计入") {
|
||||||
|
t.Fatalf("fallback %q", sample.Detail["fallback"])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsAll(text string, parts ...string) bool {
|
||||||
|
for _, part := range parts {
|
||||||
|
if !strings.Contains(text, part) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
Reference in new issue
Block a user