mirror of
https://github.com/yuezk/GlobalProtect-openconnect.git
synced 2026-11-19 22:46:14 -05:00
feat: prepare 3.0.0 release
This commit is contained in:
252 files changed
+26210
-7457
No files matched your search
@@ -2,11 +2,12 @@
|
||||
name = "openconnect"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
license = "MIT"
|
||||
links = "openconnect"
|
||||
|
||||
[dependencies]
|
||||
log.workspace = true
|
||||
libc = "0.2"
|
||||
is_executable.workspace = true
|
||||
|
||||
[build-dependencies]
|
||||
|
||||
+21
-674
@@ -1,674 +1,21 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 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 General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is 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. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
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.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
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 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. Use with the GNU Affero General Public License.
|
||||
|
||||
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 Affero 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 special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU 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 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 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 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 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU 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 the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
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 GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Kevin Yue
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+67
-69
@@ -1,37 +1,8 @@
|
||||
use std::{env, path::PathBuf, process::Command};
|
||||
|
||||
fn apply_patches(patches_dir: &PathBuf, build_src: &PathBuf) {
|
||||
let patches = std::fs::read_dir(patches_dir)
|
||||
.expect("Failed to read patches directory")
|
||||
.filter_map(|entry| entry.ok())
|
||||
.filter(|entry| entry.path().extension().and_then(|s| s.to_str()) == Some("patch"))
|
||||
.map(|entry| entry.path())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Sort patches to ensure they are applied in order
|
||||
let mut patches = patches;
|
||||
patches.sort();
|
||||
|
||||
for patch in patches {
|
||||
println!("cargo:rerun-if-changed={}", patch.display());
|
||||
println!("Applying patch: {}", patch.display());
|
||||
|
||||
let status = Command::new("patch")
|
||||
.arg("-p1") // Strip one level of path (standard for git diffs)
|
||||
.arg("-i") // Input file
|
||||
.arg(&patch)
|
||||
.current_dir(build_src) // Run INSIDE the copied dir
|
||||
.status()
|
||||
.expect("Failed to execute patch command");
|
||||
|
||||
if !status.success() {
|
||||
panic!("Failed to apply patch file: {}", patch.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
use std::{env, path::PathBuf};
|
||||
|
||||
fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
|
||||
let libxml2_dir = deps_dir.join("libxml2");
|
||||
let install_dir = out_dir.join("libxml2_install");
|
||||
|
||||
// The temporary location where we will build
|
||||
let build_src = out_dir.join("libxml2_build");
|
||||
@@ -44,6 +15,10 @@ fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
|
||||
if build_src.exists() {
|
||||
std::fs::remove_dir_all(&build_src).unwrap();
|
||||
}
|
||||
if install_dir.exists() {
|
||||
std::fs::remove_dir_all(&install_dir).unwrap();
|
||||
}
|
||||
std::fs::create_dir_all(&install_dir).unwrap();
|
||||
std::fs::create_dir_all(&build_src).unwrap();
|
||||
|
||||
// Copy the source code to OUT_DIR
|
||||
@@ -55,24 +30,28 @@ fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
|
||||
fs_extra::dir::copy(&libxml2_dir, &build_src, &options).expect("Failed to copy C source code to OUT_DIR");
|
||||
|
||||
// Build the libxml2 library using autotools
|
||||
let dst = autotools::Config::new(&build_src)
|
||||
.reconf("-ivf")
|
||||
.enable_static()
|
||||
.disable_shared()
|
||||
// Disable optional features that complicate static builds
|
||||
.with("python", Some("no"))
|
||||
.with("icu", Some("no"))
|
||||
.with("http", Some("no"))
|
||||
.with("ftp", Some("no"))
|
||||
.with("catalog", Some("no"))
|
||||
.with("docbook", Some("no"))
|
||||
.with("legacy", Some("no"))
|
||||
.with("threads", Some("no"))
|
||||
.with("zlib", Some("no"))
|
||||
.with("lzma", Some("no"))
|
||||
// Ensure position-independent code (safe for static linking)
|
||||
.cflag("-fPIC")
|
||||
.build();
|
||||
let dst = {
|
||||
let mut config = autotools::Config::new(&build_src);
|
||||
config
|
||||
.out_dir(&install_dir)
|
||||
.reconf("-ivf")
|
||||
.enable_static()
|
||||
.disable_shared()
|
||||
// Disable optional features that complicate static builds
|
||||
.with("python", Some("no"))
|
||||
.with("icu", Some("no"))
|
||||
.with("http", Some("no"))
|
||||
.with("ftp", Some("no"))
|
||||
.with("catalog", Some("no"))
|
||||
.with("docbook", Some("no"))
|
||||
.with("legacy", Some("no"))
|
||||
.with("threads", Some("no"))
|
||||
.with("zlib", Some("no"))
|
||||
.with("lzma", Some("no"))
|
||||
// Ensure position-independent code (safe for static linking)
|
||||
.cflag("-fPIC");
|
||||
config.build()
|
||||
};
|
||||
|
||||
let lib_dir = dst.join("lib");
|
||||
let include_dir = dst.join("include/libxml2");
|
||||
@@ -91,12 +70,12 @@ fn build_libxml2(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
|
||||
|
||||
fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
|
||||
let openconnect_dir = deps_dir.join("openconnect");
|
||||
let patches_dir = deps_dir.join("patches");
|
||||
let install_dir = out_dir.join("openconnect_install");
|
||||
|
||||
// The temporary location where we will build
|
||||
let build_src = out_dir.join("openconnect_build");
|
||||
|
||||
// Track changes so cargo rebuilds if patch or submodule changes
|
||||
// Track changes so cargo rebuilds if submodule changes
|
||||
println!("cargo:rerun-if-changed={}", openconnect_dir.display());
|
||||
|
||||
// Prepare the build directory
|
||||
@@ -104,6 +83,10 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
|
||||
if build_src.exists() {
|
||||
std::fs::remove_dir_all(&build_src).unwrap();
|
||||
}
|
||||
if install_dir.exists() {
|
||||
std::fs::remove_dir_all(&install_dir).unwrap();
|
||||
}
|
||||
std::fs::create_dir_all(&install_dir).unwrap();
|
||||
std::fs::create_dir_all(&build_src).unwrap();
|
||||
|
||||
// Copy the source code to OUT_DIR
|
||||
@@ -114,18 +97,13 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
|
||||
|
||||
fs_extra::dir::copy(&openconnect_dir, &build_src, &options).expect("Failed to copy C source code to OUT_DIR");
|
||||
|
||||
// Apply all patches from the patches directory
|
||||
apply_patches(&patches_dir, &build_src);
|
||||
|
||||
// Build the OpenConnect library using autotools
|
||||
// We explicitly enable static and disable shared to ensure we get a .a file.
|
||||
// .reconf("-ivf") is CRITICAL for git submodules because 'configure'
|
||||
// usually doesn't exist yet and needs to be generated.
|
||||
// Build the OpenConnect library using autotools. Keep the upstream LGPL
|
||||
// library dynamically linked on macOS so it remains replaceable in the app
|
||||
// bundle. Other platforms retain the existing static-link behavior.
|
||||
let mut config = autotools::Config::new(&build_src);
|
||||
config
|
||||
.out_dir(&install_dir)
|
||||
.reconf("-ivf")
|
||||
.enable_static()
|
||||
.disable_shared()
|
||||
.disable("nls", None) // disable translations to save space
|
||||
.disable("docs", None)
|
||||
.disable("dsa-tests", None)
|
||||
@@ -139,10 +117,14 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
config.disable_static().enable_shared().without("gnutls", None);
|
||||
config.ldflag("-liconv");
|
||||
config.env("LIBS", "-liconv");
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
config.enable_static().disable_shared();
|
||||
|
||||
#[cfg(any(target_os = "freebsd", target_os = "openbsd"))]
|
||||
{
|
||||
config.ldflag("-L/usr/local/lib");
|
||||
@@ -155,10 +137,12 @@ fn build_openconnect(deps_dir: &PathBuf, out_dir: &PathBuf) -> PathBuf {
|
||||
let lib_dir = dst.join("lib");
|
||||
let include_dir = dst.join("include");
|
||||
|
||||
// Tell rustc where to find the static library
|
||||
println!("cargo:rustc-link-search=native={}", lib_dir.display());
|
||||
|
||||
// Static linking of openconnect
|
||||
#[cfg(target_os = "macos")]
|
||||
println!("cargo:rustc-link-lib=dylib=openconnect");
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
println!("cargo:rustc-link-lib=static=openconnect");
|
||||
|
||||
// Export include path for downstream use (bindgen / cc)
|
||||
@@ -173,6 +157,14 @@ fn main() {
|
||||
let deps_dir = PathBuf::from(manifest_dir).join("deps");
|
||||
|
||||
let oc_dst = build_openconnect(&deps_dir, &out_dir);
|
||||
println!(
|
||||
"cargo:rustc-env=OPENCONNECT_PROTOCOL_BUILD={}",
|
||||
oc_dst.join("build").display()
|
||||
);
|
||||
println!(
|
||||
"cargo:rustc-env=OPENCONNECT_PROTOCOL_SOURCE={}",
|
||||
out_dir.join("openconnect_build").display()
|
||||
);
|
||||
|
||||
// Only statically link libxml2 if `LIBXML2_STATIC` is set
|
||||
if env::var("LIBXML2_STATIC").is_ok() {
|
||||
@@ -184,14 +176,20 @@ fn main() {
|
||||
|
||||
// Using pkg-config to find system deps
|
||||
pkg_config::probe_library("zlib").unwrap();
|
||||
pkg_config::probe_library("liblz4").unwrap();
|
||||
pkg_config::probe_library("gnutls").unwrap();
|
||||
#[cfg(target_os = "macos")]
|
||||
pkg_config::probe_library("openssl").unwrap();
|
||||
|
||||
// Below are required by gnutls
|
||||
pkg_config::probe_library("p11-kit-1").unwrap();
|
||||
pkg_config::probe_library("hogweed").unwrap();
|
||||
pkg_config::probe_library("nettle").unwrap();
|
||||
pkg_config::probe_library("gmp").unwrap();
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
pkg_config::probe_library("liblz4").unwrap();
|
||||
pkg_config::probe_library("gnutls").unwrap();
|
||||
|
||||
// Below are required by gnutls
|
||||
pkg_config::probe_library("p11-kit-1").unwrap();
|
||||
pkg_config::probe_library("hogweed").unwrap();
|
||||
pkg_config::probe_library("nettle").unwrap();
|
||||
pkg_config::probe_library("gmp").unwrap();
|
||||
}
|
||||
|
||||
// Compile the vpn.c file
|
||||
println!("cargo:rerun-if-changed=src/ffi/vpn.c");
|
||||
|
||||
Submodule crates/openconnect/deps/openconnect updated: 0dcdff87db...0557ead16b.
-114
@@ -1,114 +0,0 @@
|
||||
From a8d5ec198ca9ae47a0e6b4f1ea244d2738acf055 Mon Sep 17 00:00:00 2001
|
||||
From: Kevin Yue <[email protected]>
|
||||
Date: Sun, 14 Dec 2025 17:10:02 +0800
|
||||
Subject: [PATCH 1/4] Add support for GlobalProtect app version handling
|
||||
|
||||
- Introduced `gp_app_version` field in `openconnect_info` structure.
|
||||
- Implemented `openconnect_set_gp_app_version` and `openconnect_get_gp_app_version` functions.
|
||||
- Updated `gpst_get_config` to use the app version in requests.
|
||||
- Free `gp_app_version` in `openconnect_vpninfo_free` to prevent memory leaks.
|
||||
---
|
||||
gpst.c | 8 +++++---
|
||||
library.c | 15 +++++++++++++++
|
||||
openconnect-internal.h | 4 ++++
|
||||
openconnect.h | 2 ++
|
||||
4 files changed, 26 insertions(+), 3 deletions(-)
|
||||
|
||||
diff --git a/gpst.c b/gpst.c
|
||||
index 244aaf04..5c24bbd2 100644
|
||||
--- a/gpst.c
|
||||
+++ b/gpst.c
|
||||
@@ -650,8 +650,11 @@ static int gpst_get_config(struct openconnect_info *vpninfo)
|
||||
|
||||
|
||||
/* submit getconfig request */
|
||||
+ const char *app_version = openconnect_get_gp_app_version(vpninfo);
|
||||
+ vpn_progress(vpninfo, PRG_DEBUG, _("Using GlobalProtect app version: %s\n"), app_version);
|
||||
+
|
||||
buf_append(request_body, "client-type=1&protocol-version=p1&internal=no");
|
||||
- append_opt(request_body, "app-version", vpninfo->csd_ticket ? : "6.3.0-33");
|
||||
+ append_opt(request_body, "app-version", app_version);
|
||||
append_opt(request_body, "ipv6-support", vpninfo->disable_ipv6 ? "no" : "yes");
|
||||
append_opt(request_body, "clientos", gpst_os_name(vpninfo));
|
||||
append_opt(request_body, "os-version", vpninfo->platname);
|
||||
@@ -1040,8 +1043,7 @@ static int run_hip_script(struct openconnect_info *vpninfo)
|
||||
* accept new ones.
|
||||
*/
|
||||
unsetenv("APP_VERSION");
|
||||
- if (vpninfo->csd_ticket)
|
||||
- if (setenv("APP_VERSION", vpninfo->csd_ticket, 1))
|
||||
+ if (setenv("APP_VERSION", openconnect_get_gp_app_version(vpninfo), 1))
|
||||
goto out;
|
||||
|
||||
execv(hip_argv[0], (char **)hip_argv);
|
||||
diff --git a/library.c b/library.c
|
||||
index b5e74e9b..18334c76 100644
|
||||
--- a/library.c
|
||||
+++ b/library.c
|
||||
@@ -896,6 +896,7 @@ void openconnect_vpninfo_free(struct openconnect_info *vpninfo)
|
||||
|
||||
free(vpninfo->localname);
|
||||
free(vpninfo->useragent);
|
||||
+ free(vpninfo->gp_app_version);
|
||||
free(vpninfo->authgroup);
|
||||
#ifdef HAVE_LIBSTOKEN
|
||||
if (vpninfo->stoken_pin)
|
||||
@@ -1019,6 +1020,20 @@ int openconnect_set_useragent(struct openconnect_info *vpninfo,
|
||||
return 0;
|
||||
}
|
||||
|
||||
+int openconnect_set_gp_app_version(struct openconnect_info *vpninfo,
|
||||
+ const char *gp_app_version)
|
||||
+{
|
||||
+ UTF8CHECK(gp_app_version);
|
||||
+
|
||||
+ STRDUP(vpninfo->gp_app_version, gp_app_version);
|
||||
+ return 0;
|
||||
+}
|
||||
+
|
||||
+const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo)
|
||||
+{
|
||||
+ return vpninfo->csd_ticket ?: (vpninfo->gp_app_version ?: "6.3.0-33");
|
||||
+}
|
||||
+
|
||||
int openconnect_set_urlpath(struct openconnect_info *vpninfo,
|
||||
const char *urlpath)
|
||||
{
|
||||
diff --git a/openconnect-internal.h b/openconnect-internal.h
|
||||
index abf45bbd..988f85f0 100644
|
||||
--- a/openconnect-internal.h
|
||||
+++ b/openconnect-internal.h
|
||||
@@ -786,6 +786,7 @@ struct openconnect_info {
|
||||
int is_dyndns; /* Attempt to redo DNS lookup on each CSTP reconnect */
|
||||
char *useragent;
|
||||
char *version_string;
|
||||
+ char *gp_app_version;
|
||||
|
||||
const char *quit_reason;
|
||||
const char *delay_tunnel_reason; /* If non-null, provides a reason why protocol is not yet ready for tunnel setup */
|
||||
@@ -1677,6 +1678,9 @@ void openconnect_set_juniper(struct openconnect_info *vpninfo);
|
||||
/* hpke.c */
|
||||
int handle_external_browser(struct openconnect_info *vpninfo);
|
||||
|
||||
+/* Get the app version */
|
||||
+const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo);
|
||||
+
|
||||
/* version.c */
|
||||
extern const char openconnect_version_str[];
|
||||
|
||||
diff --git a/openconnect.h b/openconnect.h
|
||||
index 136f181a..7d4f3399 100644
|
||||
--- a/openconnect.h
|
||||
+++ b/openconnect.h
|
||||
@@ -470,6 +470,8 @@ int openconnect_set_http_proxy(struct openconnect_info *vpninfo,
|
||||
int openconnect_set_useragent(struct openconnect_info *vpninfo,
|
||||
const char *useragent);
|
||||
|
||||
+int openconnect_set_gp_app_version(struct openconnect_info *vpninfo,
|
||||
+ const char *gp_app_version);
|
||||
int openconnect_passphrase_from_fsid(struct openconnect_info *vpninfo);
|
||||
int openconnect_obtain_cookie(struct openconnect_info *vpninfo);
|
||||
int openconnect_init_ssl(void);
|
||||
--
|
||||
2.50.1 (Apple Git-155)
|
||||
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
From 8591eba702f52dae335601c997271786be50dff7 Mon Sep 17 00:00:00 2001
|
||||
From: Kevin Yue <[email protected]>
|
||||
Date: Sun, 14 Dec 2025 17:10:52 +0800
|
||||
Subject: [PATCH 2/4] Update user agent for common headers in GlobalProtect
|
||||
authentication
|
||||
|
||||
---
|
||||
auth-globalprotect.c | 7 -------
|
||||
1 file changed, 7 deletions(-)
|
||||
|
||||
diff --git a/auth-globalprotect.c b/auth-globalprotect.c
|
||||
index 8d094273..27e41c2b 100644
|
||||
--- a/auth-globalprotect.c
|
||||
+++ b/auth-globalprotect.c
|
||||
@@ -34,14 +34,7 @@ struct login_context {
|
||||
void gpst_common_headers(struct openconnect_info *vpninfo,
|
||||
struct oc_text_buf *buf)
|
||||
{
|
||||
- char *orig_ua = vpninfo->useragent;
|
||||
-
|
||||
- /* XX: more recent servers don't appear to require this specific UA value,
|
||||
- * but we don't have any good way to detect them.
|
||||
- */
|
||||
- vpninfo->useragent = (char *)"PAN GlobalProtect";
|
||||
http_common_headers(vpninfo, buf);
|
||||
- vpninfo->useragent = orig_ua;
|
||||
}
|
||||
|
||||
/* Translate platform names (derived from AnyConnect) into the values
|
||||
--
|
||||
2.50.1 (Apple Git-155)
|
||||
|
||||
-121
@@ -1,121 +0,0 @@
|
||||
From dda2aceca7e614af65b968e632065ef223cb6612 Mon Sep 17 00:00:00 2001
|
||||
From: Kevin Yue <[email protected]>
|
||||
Date: Sun, 14 Dec 2025 17:14:08 +0800
|
||||
Subject: [PATCH 3/4] Add support for OS version handling in GlobalProtect
|
||||
authentication
|
||||
|
||||
---
|
||||
auth-globalprotect.c | 2 +-
|
||||
gpst.c | 4 ++--
|
||||
library.c | 15 +++++++++++++++
|
||||
openconnect-internal.h | 4 ++++
|
||||
openconnect.h | 3 +++
|
||||
5 files changed, 25 insertions(+), 3 deletions(-)
|
||||
|
||||
diff --git a/auth-globalprotect.c b/auth-globalprotect.c
|
||||
index 27e41c2b..59d6de3b 100644
|
||||
--- a/auth-globalprotect.c
|
||||
+++ b/auth-globalprotect.c
|
||||
@@ -731,7 +731,7 @@ static int gpst_login(struct openconnect_info *vpninfo, int portal, struct login
|
||||
buf_append(request_body, "jnlpReady=jnlpReady&ok=Login&direct=yes&clientVer=4100&prot=https:&internal=no");
|
||||
append_opt(request_body, "ipv6-support", vpninfo->disable_ipv6 ? "no" : "yes");
|
||||
append_opt(request_body, "clientos", gpst_os_name(vpninfo));
|
||||
- append_opt(request_body, "os-version", vpninfo->platname);
|
||||
+ append_opt(request_body, "os-version", openconnect_get_gp_os_version(vpninfo));
|
||||
append_opt(request_body, "server", vpninfo->hostname);
|
||||
append_opt(request_body, "computer", vpninfo->localname);
|
||||
if (ctx->portal_userauthcookie)
|
||||
diff --git a/gpst.c b/gpst.c
|
||||
index 5c24bbd2..0373fce0 100644
|
||||
--- a/gpst.c
|
||||
+++ b/gpst.c
|
||||
@@ -657,7 +657,7 @@ static int gpst_get_config(struct openconnect_info *vpninfo)
|
||||
append_opt(request_body, "app-version", app_version);
|
||||
append_opt(request_body, "ipv6-support", vpninfo->disable_ipv6 ? "no" : "yes");
|
||||
append_opt(request_body, "clientos", gpst_os_name(vpninfo));
|
||||
- append_opt(request_body, "os-version", vpninfo->platname);
|
||||
+ append_opt(request_body, "os-version", openconnect_get_gp_os_version(vpninfo));
|
||||
append_opt(request_body, "hmac-algo", "sha1,md5,sha256");
|
||||
append_opt(request_body, "enc-algo", "aes-128-cbc,aes-256-cbc");
|
||||
if (old_addr || old_addr6) {
|
||||
@@ -1044,7 +1044,7 @@ static int run_hip_script(struct openconnect_info *vpninfo)
|
||||
*/
|
||||
unsetenv("APP_VERSION");
|
||||
if (setenv("APP_VERSION", openconnect_get_gp_app_version(vpninfo), 1))
|
||||
- goto out;
|
||||
+ goto out;
|
||||
|
||||
execv(hip_argv[0], (char **)hip_argv);
|
||||
|
||||
diff --git a/library.c b/library.c
|
||||
index 18334c76..e2169054 100644
|
||||
--- a/library.c
|
||||
+++ b/library.c
|
||||
@@ -897,6 +897,7 @@ void openconnect_vpninfo_free(struct openconnect_info *vpninfo)
|
||||
free(vpninfo->localname);
|
||||
free(vpninfo->useragent);
|
||||
free(vpninfo->gp_app_version);
|
||||
+ free(vpninfo->gp_os_version);
|
||||
free(vpninfo->authgroup);
|
||||
#ifdef HAVE_LIBSTOKEN
|
||||
if (vpninfo->stoken_pin)
|
||||
@@ -1034,6 +1035,20 @@ const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo)
|
||||
return vpninfo->csd_ticket ?: (vpninfo->gp_app_version ?: "6.3.0-33");
|
||||
}
|
||||
|
||||
+int openconnect_set_gp_os_version(struct openconnect_info *vpninfo,
|
||||
+ const char *gp_os_version)
|
||||
+{
|
||||
+ UTF8CHECK(gp_os_version);
|
||||
+
|
||||
+ STRDUP(vpninfo->gp_os_version, gp_os_version);
|
||||
+ return 0;
|
||||
+}
|
||||
+
|
||||
+const char *openconnect_get_gp_os_version(struct openconnect_info *vpninfo)
|
||||
+{
|
||||
+ return vpninfo->gp_os_version ?: vpninfo->platname;
|
||||
+}
|
||||
+
|
||||
int openconnect_set_urlpath(struct openconnect_info *vpninfo,
|
||||
const char *urlpath)
|
||||
{
|
||||
diff --git a/openconnect-internal.h b/openconnect-internal.h
|
||||
index 988f85f0..5c8d2909 100644
|
||||
--- a/openconnect-internal.h
|
||||
+++ b/openconnect-internal.h
|
||||
@@ -787,6 +787,7 @@ struct openconnect_info {
|
||||
char *useragent;
|
||||
char *version_string;
|
||||
char *gp_app_version;
|
||||
+ char *gp_os_version;
|
||||
|
||||
const char *quit_reason;
|
||||
const char *delay_tunnel_reason; /* If non-null, provides a reason why protocol is not yet ready for tunnel setup */
|
||||
@@ -1681,6 +1682,9 @@ int handle_external_browser(struct openconnect_info *vpninfo);
|
||||
/* Get the app version */
|
||||
const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo);
|
||||
|
||||
+/* Get the OS version string for GP */
|
||||
+const char *openconnect_get_gp_os_version(struct openconnect_info *vpninfo);
|
||||
+
|
||||
/* version.c */
|
||||
extern const char openconnect_version_str[];
|
||||
|
||||
diff --git a/openconnect.h b/openconnect.h
|
||||
index 7d4f3399..aa96a53b 100644
|
||||
--- a/openconnect.h
|
||||
+++ b/openconnect.h
|
||||
@@ -472,6 +472,9 @@ int openconnect_set_useragent(struct openconnect_info *vpninfo,
|
||||
|
||||
int openconnect_set_gp_app_version(struct openconnect_info *vpninfo,
|
||||
const char *gp_app_version);
|
||||
+int openconnect_set_gp_os_version(struct openconnect_info *vpninfo,
|
||||
+ const char *gp_os_version);
|
||||
+
|
||||
int openconnect_passphrase_from_fsid(struct openconnect_info *vpninfo);
|
||||
int openconnect_obtain_cookie(struct openconnect_info *vpninfo);
|
||||
int openconnect_init_ssl(void);
|
||||
--
|
||||
2.50.1 (Apple Git-155)
|
||||
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
From 3915a51c81831a1a9b087d82f0c760365682f23b Mon Sep 17 00:00:00 2001
|
||||
From: Kevin Yue <[email protected]>
|
||||
Date: Mon, 15 Dec 2025 19:20:44 +0800
|
||||
Subject: [PATCH 4/4] Add client version and OS information to HIP script
|
||||
arguments
|
||||
|
||||
---
|
||||
gpst.c | 8 ++++++--
|
||||
1 file changed, 6 insertions(+), 2 deletions(-)
|
||||
|
||||
diff --git a/gpst.c b/gpst.c
|
||||
index 0373fce0..d04c42c2 100644
|
||||
--- a/gpst.c
|
||||
+++ b/gpst.c
|
||||
@@ -1013,6 +1013,12 @@ static int run_hip_script(struct openconnect_info *vpninfo)
|
||||
exit(1);
|
||||
|
||||
hip_argv[i++] = openconnect_utf8_to_legacy(vpninfo, vpninfo->csd_wrapper);
|
||||
+ hip_argv[i++] = "--client-version";
|
||||
+ hip_argv[i++] = openconnect_get_gp_app_version(vpninfo);
|
||||
+ hip_argv[i++] = "--client-os";
|
||||
+ hip_argv[i++] = gpst_os_name(vpninfo);
|
||||
+ hip_argv[i++] = "--os-version";
|
||||
+ hip_argv[i++] = openconnect_get_gp_os_version(vpninfo);
|
||||
hip_argv[i++] = "--cookie";
|
||||
hip_argv[i++] = vpninfo->cookie;
|
||||
if (vpninfo->ip_info.addr) {
|
||||
@@ -1025,8 +1031,6 @@ static int run_hip_script(struct openconnect_info *vpninfo)
|
||||
}
|
||||
hip_argv[i++] = "--md5";
|
||||
hip_argv[i++] = vpninfo->csd_token;
|
||||
- hip_argv[i++] = "--client-os";
|
||||
- hip_argv[i++] = gpst_os_name(vpninfo);
|
||||
hip_argv[i++] = NULL;
|
||||
|
||||
/* XX: Sending the above parameters as --long-options was a mistake that was
|
||||
--
|
||||
2.50.1 (Apple Git-155)
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
diff --git a/gpst.c b/gpst.c
|
||||
index 244aaf04..78c16d1c 100644
|
||||
--- a/gpst.c
|
||||
+++ b/gpst.c
|
||||
@@ -438,8 +438,19 @@ static int gpst_parse_config_xml(struct openconnect_info *vpninfo, xmlNode *xml_
|
||||
new_ip_info.netmask = add_option_steal(&new_opts, "netmask", &s);
|
||||
} else if (!xmlnode_get_val(xml_node, "mtu", &s))
|
||||
new_ip_info.mtu = atoi(s);
|
||||
- else if (!xmlnode_get_val(xml_node, "lifetime", &s))
|
||||
+ else if (!xmlnode_get_val(xml_node, "lifetime", &s)) {
|
||||
+ vpninfo->gp_session_lifetime = atoi(s);
|
||||
vpninfo->auth_expiration = time(NULL) + atol(s);
|
||||
+ } else if (!xmlnode_get_val(xml_node, "user-expires", &s) ||
|
||||
+ !xmlnode_get_val(xml_node, "user_expires", &s)) {
|
||||
+ vpninfo->gp_user_expires = atol(s);
|
||||
+ } else if (!xmlnode_get_val(xml_node, "lifetime-notify-prior", &s)) {
|
||||
+ vpninfo->gp_lifetime_notify_prior = atoi(s);
|
||||
+ } else if (!xmlnode_get_val(xml_node, "lifetime-notify-message", &s)) {
|
||||
+ free(vpninfo->gp_lifetime_notify_message);
|
||||
+ vpninfo->gp_lifetime_notify_message = s;
|
||||
+ s = NULL;
|
||||
+ }
|
||||
else if (!xmlnode_get_val(xml_node, "quarantine", &s)) {
|
||||
if (strcmp(s, "no"))
|
||||
vpn_progress(vpninfo, PRG_DEBUG,
|
||||
diff --git a/libopenconnect.map.in b/libopenconnect.map.in
|
||||
index f036c071..44110486 100644
|
||||
--- a/libopenconnect.map.in
|
||||
+++ b/libopenconnect.map.in
|
||||
@@ -113,6 +113,10 @@ OPENCONNECT_5_7 {
|
||||
openconnect_set_cookie;
|
||||
openconnect_set_allow_insecure_crypto;
|
||||
openconnect_get_auth_expiration;
|
||||
+ openconnect_get_gp_session_lifetime;
|
||||
+ openconnect_get_gp_user_expires;
|
||||
+ openconnect_get_gp_lifetime_notify_prior;
|
||||
+ openconnect_get_gp_lifetime_notify_message;
|
||||
openconnect_disable_dtls;
|
||||
openconnect_get_connect_url;
|
||||
openconnect_set_webview_callback;
|
||||
diff --git a/libopenconnect5.symbols b/libopenconnect5.symbols
|
||||
index 7cb04d05..2c7af781 100644
|
||||
--- a/libopenconnect5.symbols
|
||||
+++ b/libopenconnect5.symbols
|
||||
@@ -94,6 +94,10 @@ libopenconnect.so.5 libopenconnect5 #MINVER#
|
||||
openconnect_set_cookie@OPENCONNECT_5_7 8.20
|
||||
openconnect_set_allow_insecure_crypto@OPENCONNECT_5_7 8.20
|
||||
openconnect_get_auth_expiration@OPENCONNECT_5_7 8.20
|
||||
+ openconnect_get_gp_session_lifetime@OPENCONNECT_5_7 8.20
|
||||
+ openconnect_get_gp_user_expires@OPENCONNECT_5_7 8.20
|
||||
+ openconnect_get_gp_lifetime_notify_prior@OPENCONNECT_5_7 8.20
|
||||
+ openconnect_get_gp_lifetime_notify_message@OPENCONNECT_5_7 8.20
|
||||
openconnect_disable_dtls@OPENCONNECT_5_7 8.20
|
||||
openconnect_get_connect_url@OPENCONNECT_5_7 8.20
|
||||
openconnect_set_webview_callback@OPENCONNECT_5_7 8.20
|
||||
diff --git a/library.c b/library.c
|
||||
index b5e74e9b..03f47004 100644
|
||||
--- a/library.c
|
||||
+++ b/library.c
|
||||
@@ -838,6 +838,7 @@ void openconnect_vpninfo_free(struct openconnect_info *vpninfo)
|
||||
free(vpninfo->dtls_cipher);
|
||||
free(vpninfo->peer_cert_hash);
|
||||
free(vpninfo->ciphersuite_config);
|
||||
+ free(vpninfo->gp_lifetime_notify_message);
|
||||
#if defined(OPENCONNECT_OPENSSL)
|
||||
free(vpninfo->cstp_cipher);
|
||||
#if defined(HAVE_BIO_METH_FREE)
|
||||
@@ -1137,6 +1138,26 @@ time_t openconnect_get_auth_expiration(struct openconnect_info *vpninfo)
|
||||
return vpninfo->auth_expiration;
|
||||
}
|
||||
|
||||
+int openconnect_get_gp_session_lifetime(struct openconnect_info *vpninfo)
|
||||
+{
|
||||
+ return vpninfo->gp_session_lifetime;
|
||||
+}
|
||||
+
|
||||
+time_t openconnect_get_gp_user_expires(struct openconnect_info *vpninfo)
|
||||
+{
|
||||
+ return vpninfo->gp_user_expires;
|
||||
+}
|
||||
+
|
||||
+int openconnect_get_gp_lifetime_notify_prior(struct openconnect_info *vpninfo)
|
||||
+{
|
||||
+ return vpninfo->gp_lifetime_notify_prior;
|
||||
+}
|
||||
+
|
||||
+const char *openconnect_get_gp_lifetime_notify_message(struct openconnect_info *vpninfo)
|
||||
+{
|
||||
+ return vpninfo->gp_lifetime_notify_message;
|
||||
+}
|
||||
+
|
||||
int openconnect_get_ip_info(struct openconnect_info *vpninfo,
|
||||
const struct oc_ip_info **info,
|
||||
const struct oc_vpn_option **cstp_options,
|
||||
diff --git a/openconnect-internal.h b/openconnect-internal.h
|
||||
index abf45bbd..dd5507ca 100644
|
||||
--- a/openconnect-internal.h
|
||||
+++ b/openconnect-internal.h
|
||||
@@ -647,6 +647,10 @@ struct openconnect_info {
|
||||
int dtls_attempt_period;
|
||||
int udp_probes_sent;
|
||||
time_t auth_expiration;
|
||||
+ int gp_session_lifetime;
|
||||
+ time_t gp_user_expires;
|
||||
+ int gp_lifetime_notify_prior;
|
||||
+ char *gp_lifetime_notify_message;
|
||||
time_t new_dtls_started;
|
||||
#if defined(OPENCONNECT_OPENSSL)
|
||||
SSL_CTX *dtls_ctx;
|
||||
diff --git a/openconnect.h b/openconnect.h
|
||||
index 136f181a..febf15cc 100644
|
||||
--- a/openconnect.h
|
||||
+++ b/openconnect.h
|
||||
@@ -655,6 +655,10 @@ void openconnect_set_dpd(struct openconnect_info *, int min_seconds);
|
||||
void openconnect_set_trojan_interval(struct openconnect_info *, int seconds);
|
||||
int openconnect_get_idle_timeout(struct openconnect_info *);
|
||||
time_t openconnect_get_auth_expiration(struct openconnect_info *);
|
||||
+int openconnect_get_gp_session_lifetime(struct openconnect_info *);
|
||||
+time_t openconnect_get_gp_user_expires(struct openconnect_info *);
|
||||
+int openconnect_get_gp_lifetime_notify_prior(struct openconnect_info *);
|
||||
+const char *openconnect_get_gp_lifetime_notify_message(struct openconnect_info *);
|
||||
|
||||
/* The returned structures are owned by the library and may be freed/replaced
|
||||
due to rekey or reconnect. Assume that once the mainloop starts, the
|
||||
@@ -1,101 +0,0 @@
|
||||
From 78078b21f53801b31fef352ec0de40d319edcae9 Mon Sep 17 00:00:00 2001
|
||||
From: Kevin Yue <[email protected]>
|
||||
Date: Sat, 13 Jun 2026 12:00:00 +0800
|
||||
Subject: [PATCH 6/6] Add host ID to GlobalProtect HIP script arguments
|
||||
|
||||
---
|
||||
gpst.c | 4 ++++
|
||||
library.c | 15 +++++++++++++++
|
||||
openconnect-internal.h | 4 ++++
|
||||
openconnect.h | 3 +++
|
||||
4 files changed, 26 insertions(+)
|
||||
|
||||
diff --git a/gpst.c b/gpst.c
|
||||
index 78c16d1c..f1e1f6bb 100644
|
||||
--- a/gpst.c
|
||||
+++ b/gpst.c
|
||||
@@ -1019,6 +1019,10 @@ static int run_hip_script(struct openconnect_info *vpninfo)
|
||||
hip_argv[i++] = "--client-os";
|
||||
hip_argv[i++] = gpst_os_name(vpninfo);
|
||||
hip_argv[i++] = "--os-version";
|
||||
hip_argv[i++] = openconnect_get_gp_os_version(vpninfo);
|
||||
+ if (openconnect_get_gp_host_id(vpninfo)) {
|
||||
+ hip_argv[i++] = "--host-id";
|
||||
+ hip_argv[i++] = openconnect_get_gp_host_id(vpninfo);
|
||||
+ }
|
||||
hip_argv[i++] = "--cookie";
|
||||
hip_argv[i++] = vpninfo->cookie;
|
||||
if (vpninfo->ip_info.addr) {
|
||||
diff --git a/library.c b/library.c
|
||||
index 03f47004..9e585119 100644
|
||||
--- a/library.c
|
||||
+++ b/library.c
|
||||
@@ -900,6 +900,7 @@ void openconnect_vpninfo_free(struct openconnect_info *vpninfo)
|
||||
free(vpninfo->useragent);
|
||||
free(vpninfo->gp_app_version);
|
||||
free(vpninfo->gp_os_version);
|
||||
+ free(vpninfo->gp_host_id);
|
||||
free(vpninfo->authgroup);
|
||||
#ifdef HAVE_LIBSTOKEN
|
||||
if (vpninfo->stoken_pin)
|
||||
@@ -1049,6 +1050,20 @@ const char *openconnect_get_gp_os_version(struct openconnect_info *vpninfo)
|
||||
return vpninfo->gp_os_version ?: vpninfo->platname;
|
||||
}
|
||||
|
||||
+int openconnect_set_gp_host_id(struct openconnect_info *vpninfo,
|
||||
+ const char *gp_host_id)
|
||||
+{
|
||||
+ UTF8CHECK(gp_host_id);
|
||||
+
|
||||
+ STRDUP(vpninfo->gp_host_id, gp_host_id);
|
||||
+ return 0;
|
||||
+}
|
||||
+
|
||||
+const char *openconnect_get_gp_host_id(struct openconnect_info *vpninfo)
|
||||
+{
|
||||
+ return vpninfo->gp_host_id;
|
||||
+}
|
||||
+
|
||||
int openconnect_set_urlpath(struct openconnect_info *vpninfo,
|
||||
const char *urlpath)
|
||||
{
|
||||
diff --git a/openconnect-internal.h b/openconnect-internal.h
|
||||
index a7e80659..76034fbd 100644
|
||||
--- a/openconnect-internal.h
|
||||
+++ b/openconnect-internal.h
|
||||
@@ -788,6 +788,7 @@ struct openconnect_info {
|
||||
char *version_string;
|
||||
char *gp_app_version;
|
||||
char *gp_os_version;
|
||||
+ char *gp_host_id;
|
||||
|
||||
const char *quit_reason;
|
||||
const char *delay_tunnel_reason; /* If non-null, provides a reason why protocol is not yet ready for tunnel setup */
|
||||
@@ -1684,6 +1685,9 @@ const char *openconnect_get_gp_app_version(struct openconnect_info *vpninfo);
|
||||
/* Get the OS version string for GP */
|
||||
const char *openconnect_get_gp_os_version(struct openconnect_info *vpninfo);
|
||||
|
||||
+/* Get the host ID string for GP */
|
||||
+const char *openconnect_get_gp_host_id(struct openconnect_info *vpninfo);
|
||||
+
|
||||
/* version.c */
|
||||
extern const char openconnect_version_str[];
|
||||
|
||||
diff --git a/openconnect.h b/openconnect.h
|
||||
index 40de2811..3c65c090 100644
|
||||
--- a/openconnect.h
|
||||
+++ b/openconnect.h
|
||||
@@ -472,8 +472,11 @@ int openconnect_set_useragent(struct openconnect_info *vpninfo,
|
||||
int openconnect_set_gp_app_version(struct openconnect_info *vpninfo,
|
||||
const char *gp_app_version);
|
||||
int openconnect_set_gp_os_version(struct openconnect_info *vpninfo,
|
||||
const char *gp_os_version);
|
||||
+int openconnect_set_gp_host_id(struct openconnect_info *vpninfo,
|
||||
+ const char *gp_host_id);
|
||||
+
|
||||
|
||||
int openconnect_passphrase_from_fsid(struct openconnect_info *vpninfo);
|
||||
int openconnect_obtain_cookie(struct openconnect_info *vpninfo);
|
||||
int openconnect_init_ssl(void);
|
||||
--
|
||||
2.50.1 (Apple Git-155)
|
||||
@@ -1,15 +0,0 @@
|
||||
diff --git a/gpst.c b/gpst.c
|
||||
index 244aaf04..fb8d945d 100644
|
||||
--- a/gpst.c
|
||||
+++ b/gpst.c
|
||||
@@ -669,6 +669,10 @@ static int gpst_get_config(struct openconnect_info *vpninfo)
|
||||
result = do_https_request(vpninfo, "POST", "application/x-www-form-urlencoded", request_body, &xml_buf, NULL, HTTP_NO_FLAGS);
|
||||
free(vpninfo->urlpath);
|
||||
vpninfo->urlpath = orig_path;
|
||||
+ if (result >= 0 && xml_buf)
|
||||
+ vpn_progress(vpninfo, PRG_DEBUG,
|
||||
+ "GlobalProtect getconfig.esp response:\n%s\n",
|
||||
+ xml_buf);
|
||||
|
||||
/* parse getconfig result */
|
||||
if (result >= 0)
|
||||
@@ -0,0 +1,513 @@
|
||||
use crate::{HipControl, HipRequest, HipScript, HipSource, Vpn};
|
||||
use std::{
|
||||
ffi::{CString, c_char, c_int, c_void},
|
||||
io,
|
||||
marker::PhantomData,
|
||||
panic::{AssertUnwindSafe, catch_unwind},
|
||||
};
|
||||
#[link(name = "vpn")]
|
||||
unsafe extern "C" {
|
||||
fn vpn_collect_hip_report(
|
||||
script: *const HipScriptRaw,
|
||||
request: *const HipRequestRaw,
|
||||
control: *const HipControlRaw,
|
||||
generate: Option<HipGenerateFn>,
|
||||
data: *mut c_void,
|
||||
output: *mut c_char,
|
||||
capacity: usize,
|
||||
written: *mut usize,
|
||||
) -> c_int;
|
||||
}
|
||||
#[repr(C)]
|
||||
pub(crate) struct HipRequestRaw {
|
||||
cookie: *const c_char,
|
||||
client_ip: *const c_char,
|
||||
client_ipv6: *const c_char,
|
||||
md5: *const c_char,
|
||||
client_version: *const c_char,
|
||||
client_os: *const c_char,
|
||||
os_version: *const c_char,
|
||||
host_id: *const c_char,
|
||||
local_hostname: *const c_char,
|
||||
}
|
||||
#[repr(C)]
|
||||
pub(crate) struct HipControlRaw {
|
||||
pub data: *mut c_void,
|
||||
pub check: unsafe extern "C" fn(*mut c_void) -> c_int,
|
||||
}
|
||||
pub(crate) type HipGenerateFn =
|
||||
extern "C" fn(*mut c_void, *const HipRequestRaw, *const HipControlRaw, *mut c_char, usize, *mut usize) -> c_int;
|
||||
#[repr(C)]
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct HipScriptRaw {
|
||||
pub path: *const c_char,
|
||||
pub uid: u32,
|
||||
pub uid_present: c_int,
|
||||
pub validation_data: *mut c_void,
|
||||
pub validate: Option<extern "C" fn(*mut c_void, *const HipControlRaw) -> c_int>,
|
||||
pub environment: *const *const c_char,
|
||||
pub cwd: *const c_char,
|
||||
}
|
||||
impl Default for HipScriptRaw {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
path: std::ptr::null(),
|
||||
uid: 0,
|
||||
uid_present: 0,
|
||||
validation_data: std::ptr::null_mut(),
|
||||
validate: None,
|
||||
environment: std::ptr::null(),
|
||||
cwd: std::ptr::null(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl HipScriptRaw {
|
||||
pub fn from_script(script: &HipScript) -> Self {
|
||||
Self {
|
||||
path: script.path.as_ptr(),
|
||||
uid: script.user.unwrap_or(0),
|
||||
uid_present: script.user.is_some().into(),
|
||||
validation_data: script as *const _ as *mut _,
|
||||
validate: script.validator.as_ref().map(|_| validate_hip_script as _),
|
||||
environment: std::ptr::null(),
|
||||
cwd: script.cwd.as_ref().map_or(std::ptr::null(), |value| value.as_ptr()),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(crate) fn script_environment(script: &HipScript) -> Vec<*const c_char> {
|
||||
match &script.environment {
|
||||
Some(values) => values
|
||||
.iter()
|
||||
.map(|value| value.as_ptr())
|
||||
.chain(std::iter::once(std::ptr::null()))
|
||||
.collect(),
|
||||
None => Vec::new(),
|
||||
}
|
||||
}
|
||||
fn error_code(error: io::Error) -> c_int {
|
||||
let errno = error.raw_os_error().unwrap_or_else(|| match error.kind() {
|
||||
io::ErrorKind::Interrupted => libc::EINTR,
|
||||
io::ErrorKind::TimedOut => libc::ETIMEDOUT,
|
||||
io::ErrorKind::InvalidInput | io::ErrorKind::InvalidData => libc::EINVAL,
|
||||
io::ErrorKind::PermissionDenied => libc::EPERM,
|
||||
io::ErrorKind::NotFound => libc::ENOENT,
|
||||
_ => libc::EIO,
|
||||
});
|
||||
-errno
|
||||
}
|
||||
|
||||
unsafe fn request_string(pointer: *const c_char) -> io::Result<Option<String>> {
|
||||
if pointer.is_null() {
|
||||
return Ok(None);
|
||||
}
|
||||
unsafe { std::ffi::CStr::from_ptr(pointer) }
|
||||
.to_str()
|
||||
.map(|s| Some(s.to_owned()))
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid HIP request encoding"))
|
||||
}
|
||||
unsafe fn read_hip_request(raw: &HipRequestRaw) -> io::Result<HipRequest> {
|
||||
unsafe {
|
||||
Ok(HipRequest {
|
||||
cookie: request_string(raw.cookie)?.unwrap_or_default(),
|
||||
client_ip: request_string(raw.client_ip)?,
|
||||
client_ipv6: request_string(raw.client_ipv6)?,
|
||||
md5: request_string(raw.md5)?.unwrap_or_default(),
|
||||
client_version: request_string(raw.client_version)?.unwrap_or_default(),
|
||||
client_os: request_string(raw.client_os)?.unwrap_or_default(),
|
||||
os_version: request_string(raw.os_version)?.unwrap_or_default(),
|
||||
host_id: request_string(raw.host_id)?,
|
||||
local_hostname: request_string(raw.local_hostname)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
pub(crate) extern "C" fn generate_hip_report(
|
||||
data: *mut c_void,
|
||||
request: *const HipRequestRaw,
|
||||
control: *const HipControlRaw,
|
||||
output: *mut c_char,
|
||||
capacity: usize,
|
||||
written: *mut usize,
|
||||
) -> c_int {
|
||||
let vpn = unsafe { &*(data as *const Vpn) };
|
||||
generate_source_report(
|
||||
vpn.hip_source.as_ref() as *const HipSource as *mut _,
|
||||
request,
|
||||
control,
|
||||
output,
|
||||
capacity,
|
||||
written,
|
||||
)
|
||||
}
|
||||
|
||||
extern "C" fn generate_source_report(
|
||||
data: *mut c_void,
|
||||
request: *const HipRequestRaw,
|
||||
control: *const HipControlRaw,
|
||||
output: *mut c_char,
|
||||
capacity: usize,
|
||||
written: *mut usize,
|
||||
) -> c_int {
|
||||
let result = catch_unwind(AssertUnwindSafe(|| -> io::Result<()> {
|
||||
let source = unsafe { &*(data as *const HipSource) };
|
||||
let HipSource::Generator(generate) = source else {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "No HIP generator"));
|
||||
};
|
||||
let request = unsafe { read_hip_request(&*request)? };
|
||||
let control = HipControl {
|
||||
raw: unsafe { &*control },
|
||||
_thread: PhantomData,
|
||||
};
|
||||
control.check()?;
|
||||
let report = generate(&request, &control)?;
|
||||
control.check()?;
|
||||
if report.len() > capacity {
|
||||
return Err(io::Error::from_raw_os_error(libc::E2BIG));
|
||||
}
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(report.as_ptr(), output.cast(), report.len());
|
||||
*written = report.len();
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
match result {
|
||||
Ok(Ok(())) => 0,
|
||||
Ok(Err(error)) => error_code(error),
|
||||
Err(_) => -libc::EIO,
|
||||
}
|
||||
}
|
||||
extern "C" fn validate_hip_script(data: *mut c_void, control: *const HipControlRaw) -> c_int {
|
||||
let result = catch_unwind(AssertUnwindSafe(|| {
|
||||
let script = unsafe { &*(data as *const HipScript) };
|
||||
let control = HipControl {
|
||||
raw: unsafe { &*control },
|
||||
_thread: PhantomData,
|
||||
};
|
||||
control.check()?;
|
||||
if let Some(validate) = &script.validator {
|
||||
validate(&control)?;
|
||||
}
|
||||
control.check()
|
||||
}));
|
||||
match result {
|
||||
Ok(Ok(())) => 0,
|
||||
Ok(Err(error)) => error_code(error),
|
||||
Err(_) => -libc::EIO,
|
||||
}
|
||||
}
|
||||
pub(crate) fn collect_hip_source(
|
||||
source: &HipSource,
|
||||
request: &HipRequest,
|
||||
check: &dyn Fn() -> io::Result<()>,
|
||||
) -> io::Result<String> {
|
||||
match source {
|
||||
HipSource::Disabled => Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"HIP collection is disabled",
|
||||
)),
|
||||
HipSource::Script(script) => collect_hip_script(script, request, check),
|
||||
HipSource::Generator(_) => collect_hip_report(
|
||||
&HipScriptRaw::default(),
|
||||
Some(generate_source_report),
|
||||
source as *const _ as *mut _,
|
||||
request,
|
||||
check,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn collect_hip_script(
|
||||
script: &HipScript,
|
||||
request: &HipRequest,
|
||||
check: &dyn Fn() -> io::Result<()>,
|
||||
) -> io::Result<String> {
|
||||
let mut raw = HipScriptRaw::from_script(script);
|
||||
let environment = script_environment(script);
|
||||
if !environment.is_empty() {
|
||||
raw.environment = environment.as_ptr();
|
||||
}
|
||||
collect_hip_report(&raw, None, std::ptr::null_mut(), request, check)
|
||||
}
|
||||
|
||||
fn collect_hip_report(
|
||||
script_raw: &HipScriptRaw,
|
||||
generate: Option<HipGenerateFn>,
|
||||
data: *mut c_void,
|
||||
request: &HipRequest,
|
||||
check: &dyn Fn() -> io::Result<()>,
|
||||
) -> io::Result<String> {
|
||||
let values = [
|
||||
Some(request.cookie.as_str()),
|
||||
request.client_ip.as_deref(),
|
||||
request.client_ipv6.as_deref(),
|
||||
Some(request.md5.as_str()),
|
||||
Some(request.client_version.as_str()),
|
||||
Some(request.client_os.as_str()),
|
||||
Some(request.os_version.as_str()),
|
||||
request.host_id.as_deref(),
|
||||
request.local_hostname.as_deref(),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|value| value.map(CString::new).transpose())
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "HIP request contains NUL"))?;
|
||||
let ptr = |i: usize| values[i].as_ref().map_or(std::ptr::null(), |value| value.as_ptr());
|
||||
let raw = HipRequestRaw {
|
||||
cookie: ptr(0),
|
||||
client_ip: ptr(1),
|
||||
client_ipv6: ptr(2),
|
||||
md5: ptr(3),
|
||||
client_version: ptr(4),
|
||||
client_os: ptr(5),
|
||||
os_version: ptr(6),
|
||||
host_id: ptr(7),
|
||||
local_hostname: ptr(8),
|
||||
};
|
||||
let control = HipControlRaw {
|
||||
data: &check as *const _ as *mut _,
|
||||
check: collection_check,
|
||||
};
|
||||
let mut output = vec![0u8; 1024 * 1024 + 1];
|
||||
let mut written = 0;
|
||||
let result = unsafe {
|
||||
vpn_collect_hip_report(
|
||||
script_raw,
|
||||
&raw,
|
||||
&control,
|
||||
generate,
|
||||
data,
|
||||
output.as_mut_ptr().cast(),
|
||||
1024 * 1024,
|
||||
&mut written,
|
||||
)
|
||||
};
|
||||
if result < 0 {
|
||||
return Err(io::Error::from_raw_os_error(-result));
|
||||
}
|
||||
output.truncate(written);
|
||||
String::from_utf8(output).map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "HIP output is not UTF-8"))
|
||||
}
|
||||
unsafe extern "C" fn collection_check(data: *mut c_void) -> c_int {
|
||||
let check = unsafe { &*(data as *const &dyn Fn() -> io::Result<()>) };
|
||||
match catch_unwind(AssertUnwindSafe(check)) {
|
||||
Ok(Ok(())) => 0,
|
||||
Ok(Err(error)) => error_code(error),
|
||||
Err(_) => -libc::EIO,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod hip_tests {
|
||||
use super::*;
|
||||
use std::{
|
||||
fs,
|
||||
os::unix::fs::PermissionsExt,
|
||||
sync::atomic::{AtomicUsize, Ordering},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
fn provider(generate: impl Fn(&HipRequest, &HipControl<'_>) -> io::Result<String> + Send + Sync + 'static) -> Vpn {
|
||||
Vpn::builder("vpn.example", "cookie")
|
||||
.script_path("/bin/sh".to_owned())
|
||||
.hip_source(HipSource::Generator(std::sync::Arc::new(generate)))
|
||||
.build()
|
||||
.unwrap()
|
||||
}
|
||||
fn collect(vpn: &Vpn, script: &HipScriptRaw, check: &dyn Fn() -> io::Result<()>) -> io::Result<String> {
|
||||
collect_hip_report(
|
||||
script,
|
||||
Some(generate_hip_report),
|
||||
vpn as *const _ as *mut _,
|
||||
&HipRequest::default(),
|
||||
check,
|
||||
)
|
||||
}
|
||||
struct ScriptFixture(std::path::PathBuf);
|
||||
impl ScriptFixture {
|
||||
fn new(contents: &str) -> Self {
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||
let directory = std::env::temp_dir().join(format!(
|
||||
"gp-hip-script-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir(&directory).unwrap();
|
||||
let path = directory.join("script");
|
||||
fs::write(&path, format!("#!/bin/sh\n{contents}\n")).unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
Self(directory)
|
||||
}
|
||||
fn script(&self, user: Option<u32>) -> HipScript {
|
||||
HipScript::new(self.0.join("script").to_str().unwrap().to_owned(), user).unwrap()
|
||||
}
|
||||
}
|
||||
impl Drop for ScriptFixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standalone_source_uses_bounded_executor_without_a_vpn() {
|
||||
let source = HipSource::Generator(std::sync::Arc::new(|request, control| {
|
||||
control.check()?;
|
||||
assert_eq!(request.client_ip.as_deref(), Some("192.0.2.42"));
|
||||
assert_eq!(request.md5, "physical-session-token");
|
||||
Ok("<hip-report/>".into())
|
||||
}));
|
||||
let request = HipRequest {
|
||||
client_ip: Some("192.0.2.42".into()),
|
||||
md5: "physical-session-token".into(),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(source.collect(&request, &|| Ok(())).unwrap(), "<hip-report/>");
|
||||
let too_large = HipSource::Generator(std::sync::Arc::new(|_, _| Ok("x".repeat(1024 * 1024 + 1))));
|
||||
assert_eq!(
|
||||
too_large.collect(&request, &|| Ok(())).unwrap_err().raw_os_error(),
|
||||
Some(libc::E2BIG)
|
||||
);
|
||||
assert!(HipSource::Disabled.collect(&request, &|| Ok(())).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standalone_source_checks_cancellation_before_generation() {
|
||||
let source = HipSource::Generator(std::sync::Arc::new(|_, _| panic!("Cancelled source must not run")));
|
||||
assert_eq!(
|
||||
source
|
||||
.collect(&HipRequest::default(), &|| Err(io::Error::from(
|
||||
io::ErrorKind::Interrupted
|
||||
)))
|
||||
.unwrap_err()
|
||||
.raw_os_error(),
|
||||
Some(libc::EINTR)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_outputs_are_bounded_and_validated_by_c() {
|
||||
let raw = HipScriptRaw::default();
|
||||
for (report, errno) in [
|
||||
(String::new(), libc::EINVAL),
|
||||
("x\0x".to_owned(), libc::EINVAL),
|
||||
("x".repeat(1024 * 1024 + 1), libc::E2BIG),
|
||||
] {
|
||||
let vpn = provider(move |_, _| Ok(report.clone()));
|
||||
assert_eq!(collect(&vpn, &raw, &|| Ok(())).unwrap_err().raw_os_error(), Some(errno));
|
||||
}
|
||||
let vpn = provider(|_, _| Ok("x".repeat(1024 * 1024)));
|
||||
assert_eq!(collect(&vpn, &raw, &|| Ok(())).unwrap().len(), 1024 * 1024);
|
||||
}
|
||||
#[test]
|
||||
fn callback_panics_and_control_errors_do_not_cross_ffi() {
|
||||
let vpn = provider(|_, _| panic!("test generator panic"));
|
||||
assert_eq!(
|
||||
collect(&vpn, &Default::default(), &|| Ok(()))
|
||||
.unwrap_err()
|
||||
.raw_os_error(),
|
||||
Some(libc::EIO)
|
||||
);
|
||||
let vpn = provider(|_, _| Err(io::Error::from(io::ErrorKind::TimedOut)));
|
||||
assert_eq!(
|
||||
collect(&vpn, &Default::default(), &|| Ok(()))
|
||||
.unwrap_err()
|
||||
.raw_os_error(),
|
||||
Some(libc::ETIMEDOUT)
|
||||
);
|
||||
let vpn = provider(|_, _| panic!("Canceled provider must not run"));
|
||||
assert_eq!(
|
||||
collect(&vpn, &Default::default(), &|| Err(io::Error::from(
|
||||
io::ErrorKind::Interrupted
|
||||
)))
|
||||
.unwrap_err()
|
||||
.raw_os_error(),
|
||||
Some(libc::EINTR)
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn explicit_script_wins_and_uid_presence_is_preserved() {
|
||||
let fixture = ScriptFixture::new("printf '<script/>'");
|
||||
let script = fixture.script(None);
|
||||
let raw = HipScriptRaw::from_script(&script);
|
||||
assert_eq!(raw.uid_present, 0);
|
||||
let vpn = provider(|_, _| panic!("Script must win"));
|
||||
assert_eq!(collect(&vpn, &raw, &|| Ok(())).unwrap(), "<script/>");
|
||||
let script = fixture.script(Some(unsafe { libc::getuid() }));
|
||||
assert_eq!(HipScriptRaw::from_script(&script).uid_present, 1);
|
||||
assert_eq!(script.collect(&HipRequest::default(), &|| Ok(())).unwrap(), "<script/>");
|
||||
}
|
||||
#[test]
|
||||
fn validator_refusal_prevents_execution_and_errors_propagate() {
|
||||
let fixture = ScriptFixture::new("touch executed; printf '<script/>'");
|
||||
let script = fixture
|
||||
.script(None)
|
||||
.with_validator(|_| Err(io::Error::from(io::ErrorKind::PermissionDenied)));
|
||||
assert_eq!(
|
||||
script
|
||||
.collect(&HipRequest::default(), &|| Ok(()))
|
||||
.unwrap_err()
|
||||
.raw_os_error(),
|
||||
Some(libc::EPERM)
|
||||
);
|
||||
assert!(!fixture.0.join("executed").exists());
|
||||
let script = fixture.script(None).with_validator(|_| panic!("test validator panic"));
|
||||
assert_eq!(
|
||||
script
|
||||
.collect(&HipRequest::default(), &|| Ok(()))
|
||||
.unwrap_err()
|
||||
.raw_os_error(),
|
||||
Some(libc::EIO)
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn child_environment_and_cwd_are_explicit_without_parent_mutation() {
|
||||
let fixture = ScriptFixture::new("printf '%s:%s' \"$HIP_TEST_VALUE\" \"$PWD\"");
|
||||
let cwd = fs::canonicalize(&fixture.0).unwrap().to_str().unwrap().to_owned();
|
||||
let script = fixture
|
||||
.script(None)
|
||||
.with_environment(crate::HipScriptEnvironment {
|
||||
variables: vec![("HIP_TEST_VALUE".into(), "child".into())],
|
||||
cwd: cwd.clone(),
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
script.collect(&HipRequest::default(), &|| Ok(())).unwrap(),
|
||||
format!("child:{cwd}")
|
||||
);
|
||||
assert!(std::env::var_os("HIP_TEST_VALUE").is_none());
|
||||
}
|
||||
#[test]
|
||||
fn script_empty_nul_and_nonzero_outputs_fail() {
|
||||
for contents in ["true", "printf '\\000'", "printf '<script/>'; exit 1"] {
|
||||
let fixture = ScriptFixture::new(contents);
|
||||
assert_eq!(
|
||||
fixture
|
||||
.script(None)
|
||||
.collect(&HipRequest::default(), &|| Ok(()))
|
||||
.unwrap_err()
|
||||
.raw_os_error(),
|
||||
Some(libc::EINVAL)
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn cancellation_and_deadline_kill_descendants_and_reap_child() {
|
||||
for errno in [libc::EINTR, libc::ETIMEDOUT] {
|
||||
let fixture = ScriptFixture::new("sleep 20 &\nwait\nprintf '<script/>'");
|
||||
let start = Instant::now();
|
||||
let check = || {
|
||||
if start.elapsed() > Duration::from_millis(80) {
|
||||
Err(io::Error::from_raw_os_error(errno))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
assert_eq!(
|
||||
fixture
|
||||
.script(None)
|
||||
.collect(&HipRequest::default(), &check)
|
||||
.unwrap_err()
|
||||
.raw_os_error(),
|
||||
Some(errno)
|
||||
);
|
||||
assert!(start.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,19 @@
|
||||
mod hip;
|
||||
use crate::Vpn;
|
||||
use hip::HipGenerateFn;
|
||||
pub(crate) use hip::{
|
||||
HipControlRaw, HipScriptRaw, collect_hip_script, collect_hip_source, generate_hip_report, script_environment,
|
||||
};
|
||||
use log::{debug, info, trace, warn};
|
||||
use std::ffi::{c_char, c_int, c_long, c_void};
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
|
||||
/// ConnectOptions struct for FFI, the field names and order must match the C definition.
|
||||
#[repr(C)]
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ConnectOptions {
|
||||
pub user_data: *mut c_void,
|
||||
pub on_hip_report_submitted: Option<extern "C" fn(*mut c_void, *const c_char, usize)>,
|
||||
|
||||
pub server: *const c_char,
|
||||
pub cookie: *const c_char,
|
||||
@@ -27,8 +34,8 @@ pub(crate) struct ConnectOptions {
|
||||
pub key_password: *const c_char,
|
||||
pub servercert: *const c_char,
|
||||
|
||||
pub csd_uid: u32,
|
||||
pub csd_wrapper: *const c_char,
|
||||
pub hip_script: HipScriptRaw,
|
||||
pub generate_hip: Option<HipGenerateFn>,
|
||||
|
||||
pub reconnect_timeout: u32,
|
||||
pub mtu: u32,
|
||||
@@ -47,26 +54,56 @@ pub(crate) struct VpnSessionInfoRaw {
|
||||
pub user_expires: c_long,
|
||||
pub lifetime_warning_prior: c_int,
|
||||
pub lifetime_warning_message: *const c_char,
|
||||
pub nlb_enabled: c_int,
|
||||
pub nlb_connected_gw_ip: *const c_char,
|
||||
}
|
||||
|
||||
#[link(name = "vpn")]
|
||||
unsafe extern "C" {
|
||||
fn vpn_write_cancel(fd: c_int) -> c_int;
|
||||
#[link_name = "vpn_connect"]
|
||||
fn vpn_connect(
|
||||
options: *const ConnectOptions,
|
||||
callback: extern "C" fn(i32, *const VpnSessionInfoRaw, *mut c_void),
|
||||
) -> c_int;
|
||||
|
||||
#[link_name = "vpn_disconnect"]
|
||||
fn vpn_disconnect();
|
||||
}
|
||||
|
||||
pub(crate) fn write_cancel(fd: i32) -> std::io::Result<()> {
|
||||
let error = unsafe { vpn_write_cancel(fd) };
|
||||
if error == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(std::io::Error::from_raw_os_error(error))
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
extern "C" fn vpn_attach_command_pipe(vpn: *mut c_void, fd: c_int) -> c_int {
|
||||
unsafe { &*(vpn as *const Vpn) }.attach_command_pipe(fd).into()
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
extern "C" fn vpn_detach_command_pipe(vpn: *mut c_void) {
|
||||
unsafe { &*(vpn as *const Vpn) }.detach_command_pipe();
|
||||
}
|
||||
|
||||
pub(crate) fn connect(options: &ConnectOptions) -> i32 {
|
||||
unsafe { vpn_connect(options, on_vpn_connected) }
|
||||
}
|
||||
|
||||
pub(crate) fn disconnect() {
|
||||
unsafe { vpn_disconnect() }
|
||||
#[unsafe(no_mangle)]
|
||||
pub(crate) extern "C" fn on_hip_report_submitted(vpn: *mut c_void, report: *const c_char, length: usize) {
|
||||
let vpn = unsafe { &*(vpn as *const Vpn) };
|
||||
if report.is_null() || length > 1024 * 1024 {
|
||||
return;
|
||||
}
|
||||
let bytes = unsafe { std::slice::from_raw_parts(report.cast::<u8>(), length) };
|
||||
if let Ok(report) = std::str::from_utf8(bytes) {
|
||||
if catch_unwind(AssertUnwindSafe(|| vpn.on_hip_report_submitted(report))).is_err() {
|
||||
warn!("HIP submission observer failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include <openconnect.h>
|
||||
#include <errno.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -7,13 +8,12 @@
|
||||
|
||||
#include "vpn.h"
|
||||
|
||||
void *g_user_data;
|
||||
|
||||
static int g_cmd_pipe_fd;
|
||||
static const char *g_vpnc_script;
|
||||
static const char *g_vpnc_interface;
|
||||
static int g_script_tun;
|
||||
static vpn_connected_callback on_vpn_connected;
|
||||
struct vpn_context {
|
||||
struct openconnect_info *vpninfo;
|
||||
int command_fd;
|
||||
const vpn_options *options;
|
||||
vpn_connected_callback on_connected;
|
||||
};
|
||||
|
||||
/* Validate the peer certificate */
|
||||
static int validate_peer_cert(__attribute__((unused)) void *_vpninfo,
|
||||
@@ -40,14 +40,17 @@ static void print_progress(__attribute__((unused)) void *_vpninfo, int level,
|
||||
}
|
||||
}
|
||||
|
||||
static void setup_tun_handler(void *_vpninfo)
|
||||
static void setup_tun_handler(void *private_data)
|
||||
{
|
||||
struct vpn_context *context = private_data;
|
||||
struct openconnect_info *_vpninfo = context->vpninfo;
|
||||
const vpn_options *options = context->options;
|
||||
int ret;
|
||||
if (g_script_tun) {
|
||||
ret = openconnect_setup_tun_script(_vpninfo, g_vpnc_script);
|
||||
if (options->script_tun) {
|
||||
ret = openconnect_setup_tun_script(_vpninfo, options->script);
|
||||
} else {
|
||||
ret = openconnect_setup_tun_device(_vpninfo, g_vpnc_script,
|
||||
g_vpnc_interface);
|
||||
ret = openconnect_setup_tun_device(_vpninfo, options->script,
|
||||
options->interface);
|
||||
}
|
||||
|
||||
if (!ret) {
|
||||
@@ -59,8 +62,11 @@ static void setup_tun_handler(void *_vpninfo)
|
||||
openconnect_get_gp_lifetime_notify_prior(_vpninfo),
|
||||
.lifetime_warning_message =
|
||||
openconnect_get_gp_lifetime_notify_message(_vpninfo),
|
||||
.nlb_enabled = openconnect_get_gp_nlb_enabled(_vpninfo),
|
||||
.nlb_connected_gw_ip =
|
||||
openconnect_get_gp_nlb_connected_gw_ip(_vpninfo),
|
||||
};
|
||||
on_vpn_connected(g_cmd_pipe_fd, &session_info, g_user_data);
|
||||
context->on_connected(context->command_fd, &session_info, options->user_data);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,20 +77,17 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
|
||||
struct utsname utsbuf;
|
||||
const char *effective_local_hostname = NULL;
|
||||
|
||||
g_user_data = options->user_data;
|
||||
g_vpnc_script = options->script;
|
||||
g_vpnc_interface = options->interface;
|
||||
g_script_tun = options->script_tun;
|
||||
on_vpn_connected = callback;
|
||||
struct vpn_context context = { .options = options, .on_connected = callback };
|
||||
int result = 1;
|
||||
|
||||
INFO("USER_AGENT: %s", options->user_agent);
|
||||
INFO("OS: %s", options->os);
|
||||
INFO("CLIENT_VERSION: %s", options->client_version);
|
||||
INFO("HOST_ID: %s", options->host_id ? options->host_id : "(not set)");
|
||||
INFO("VPNC_SCRIPT: %s", options->script);
|
||||
INFO("SCRIPT_TUN: %d", g_script_tun);
|
||||
INFO("CSD_USER: %d", options->csd_uid);
|
||||
INFO("CSD_WRAPPER: %s", options->csd_wrapper);
|
||||
INFO("SCRIPT_TUN: %d", options->script_tun);
|
||||
INFO("CSD_USER: %d", options->hip_script.uid);
|
||||
INFO("CSD_WRAPPER: %s", options->hip_script.path);
|
||||
INFO("RECONNECT_TIMEOUT: %d", options->reconnect_timeout);
|
||||
INFO("MTU: %d", options->mtu);
|
||||
INFO("DISABLE_IPV6: %d", options->disable_ipv6);
|
||||
@@ -94,13 +97,28 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
|
||||
|
||||
vpninfo =
|
||||
openconnect_vpninfo_new(options->user_agent, validate_peer_cert,
|
||||
NULL, NULL, print_progress, NULL);
|
||||
NULL, NULL, print_progress, &context);
|
||||
|
||||
if (!vpninfo) {
|
||||
ERROR("openconnect_vpninfo_new failed");
|
||||
return 1;
|
||||
}
|
||||
|
||||
context.vpninfo = vpninfo;
|
||||
openconnect_set_gp_hip_report_callback(vpninfo, options->user_data,
|
||||
options->on_hip_report_submitted);
|
||||
context.command_fd = openconnect_setup_cmd_pipe(vpninfo);
|
||||
if (context.command_fd < 0) {
|
||||
ERROR("openconnect_setup_cmd_pipe failed");
|
||||
goto cleanup;
|
||||
}
|
||||
/* An earlier disconnect remains latched on this attempt. */
|
||||
if (vpn_attach_command_pipe(options->user_data, context.command_fd)) {
|
||||
INFO("VPN attempt canceled before startup");
|
||||
result = -EINTR;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
openconnect_set_loglevel(vpninfo, PRG_TRACE);
|
||||
openconnect_init_ssl();
|
||||
openconnect_set_protocol(vpninfo, "gp");
|
||||
@@ -150,9 +168,14 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
|
||||
openconnect_set_xmlpost(vpninfo, 0);
|
||||
}
|
||||
|
||||
if (options->csd_wrapper) {
|
||||
openconnect_setup_csd(vpninfo, options->csd_uid, 1,
|
||||
options->csd_wrapper);
|
||||
openconnect_set_gp_hip_generator(vpninfo, options->user_data, options->generate_hip);
|
||||
if (options->hip_script.path) {
|
||||
result = openconnect_set_gp_hip_script(vpninfo, options->hip_script.path,
|
||||
options->hip_script.uid_present, options->hip_script.uid,
|
||||
options->hip_script.validation_data, options->hip_script.validate,
|
||||
options->hip_script.environment, options->hip_script.cwd);
|
||||
if (result)
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
if (options->mtu > 0) {
|
||||
@@ -167,23 +190,15 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
|
||||
if (options->dpd_interval > 0) {
|
||||
openconnect_set_dpd(vpninfo, options->dpd_interval);
|
||||
}
|
||||
|
||||
g_cmd_pipe_fd = openconnect_setup_cmd_pipe(vpninfo);
|
||||
if (g_cmd_pipe_fd < 0) {
|
||||
ERROR("openconnect_setup_cmd_pipe failed");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Essential step
|
||||
if (openconnect_make_cstp_connection(vpninfo) != 0) {
|
||||
ERROR("openconnect_make_cstp_connection failed");
|
||||
return 1;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
if (options->no_dtls || openconnect_setup_dtls(vpninfo, 60) != 0) {
|
||||
openconnect_disable_dtls(vpninfo);
|
||||
}
|
||||
|
||||
// Essential step
|
||||
openconnect_set_setup_tun_handler(vpninfo, setup_tun_handler);
|
||||
|
||||
@@ -193,23 +208,42 @@ int vpn_connect(const vpn_options *options, vpn_connected_callback callback)
|
||||
|
||||
if (ret) {
|
||||
INFO("openconnect_mainloop returned %d, exiting", ret);
|
||||
openconnect_vpninfo_free(vpninfo);
|
||||
return ret;
|
||||
result = ret;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
INFO("openconnect_mainloop returned 0, reconnecting");
|
||||
}
|
||||
cleanup:
|
||||
vpn_detach_command_pipe(options->user_data);
|
||||
openconnect_vpninfo_free(vpninfo);
|
||||
return result;
|
||||
}
|
||||
|
||||
/* Stop the VPN connection */
|
||||
void vpn_disconnect()
|
||||
/* Called with the attempt cancellation mutex held, never after detach/free. */
|
||||
int vpn_write_cancel(int fd)
|
||||
{
|
||||
char cmd = OC_CMD_CANCEL;
|
||||
char command = OC_CMD_CANCEL;
|
||||
ssize_t written;
|
||||
do {
|
||||
written = write(fd, &command, 1);
|
||||
} while (written < 0 && errno == EINTR);
|
||||
return written == 1 ? 0 : (written < 0 ? errno : EIO);
|
||||
}
|
||||
|
||||
INFO("Stopping VPN connection: %d", g_cmd_pipe_fd);
|
||||
|
||||
if (write(g_cmd_pipe_fd, &cmd, 1) < 0) {
|
||||
ERROR("Failed to write to command pipe, VPN connection may not "
|
||||
"be stopped");
|
||||
}
|
||||
int vpn_collect_hip_report(const vpn_hip_script *script,
|
||||
const struct openconnect_gp_hip_request *request,
|
||||
const struct openconnect_gp_hip_control *control, openconnect_gp_hip_generate_fn generate, void *data,
|
||||
char *output, size_t capacity, size_t *written)
|
||||
{
|
||||
struct openconnect_info *vpninfo = openconnect_vpninfo_new("HIP preview", NULL, NULL, NULL, print_progress, NULL);
|
||||
int result;
|
||||
if (!vpninfo)
|
||||
return -ENOMEM;
|
||||
openconnect_set_gp_hip_generator(vpninfo, data, generate);
|
||||
result = openconnect_set_gp_hip_script(vpninfo, script->path, script->uid_present,
|
||||
script->uid, script->validation_data, script->validate, script->environment, script->cwd);
|
||||
if (!result) result = openconnect_collect_gp_hip_report(vpninfo, request, control, output, capacity, written);
|
||||
openconnect_vpninfo_free(vpninfo);
|
||||
return result;
|
||||
}
|
||||
@@ -9,14 +9,29 @@ typedef struct vpn_session_info {
|
||||
long user_expires;
|
||||
int lifetime_warning_prior;
|
||||
const char *lifetime_warning_message;
|
||||
int nlb_enabled;
|
||||
const char *nlb_connected_gw_ip;
|
||||
} vpn_session_info;
|
||||
|
||||
typedef void (*vpn_connected_callback)(int cmd_pipe_fd,
|
||||
const vpn_session_info *session_info,
|
||||
void *user_data);
|
||||
typedef void (*vpn_hip_report_callback)(void *user_data, const char *report,
|
||||
size_t length);
|
||||
|
||||
typedef struct vpn_hip_script {
|
||||
const char *path;
|
||||
uid_t uid;
|
||||
int uid_present;
|
||||
void *validation_data;
|
||||
openconnect_gp_hip_validate_fn validate;
|
||||
const char *const *environment;
|
||||
const char *cwd;
|
||||
} vpn_hip_script;
|
||||
|
||||
typedef struct vpn_options {
|
||||
void *user_data;
|
||||
vpn_hip_report_callback on_hip_report_submitted;
|
||||
|
||||
const char *server;
|
||||
const char *cookie;
|
||||
@@ -37,8 +52,8 @@ typedef struct vpn_options {
|
||||
const char *key_password;
|
||||
const char *servercert;
|
||||
|
||||
const uid_t csd_uid;
|
||||
const char *csd_wrapper;
|
||||
vpn_hip_script hip_script;
|
||||
openconnect_gp_hip_generate_fn generate_hip;
|
||||
|
||||
const int reconnect_timeout;
|
||||
const int mtu;
|
||||
@@ -50,7 +65,11 @@ typedef struct vpn_options {
|
||||
} vpn_options;
|
||||
|
||||
int vpn_connect(const vpn_options *options, vpn_connected_callback callback);
|
||||
void vpn_disconnect();
|
||||
int vpn_collect_hip_report(const vpn_hip_script *, const struct openconnect_gp_hip_request *,
|
||||
const struct openconnect_gp_hip_control *, openconnect_gp_hip_generate_fn, void *, char *, size_t, size_t *);
|
||||
|
||||
extern int vpn_attach_command_pipe(void *user_data, int fd);
|
||||
extern void vpn_detach_command_pipe(void *user_data);
|
||||
|
||||
extern void vpn_log(int level, const char *msg);
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
use std::{ffi::CString, io, marker::PhantomData, rc::Rc, sync::Arc};
|
||||
|
||||
use crate::{ffi, vpn_utils::check_executable};
|
||||
|
||||
pub type HipGenerator = dyn Fn(&HipRequest, &HipControl<'_>) -> io::Result<String> + Send + Sync;
|
||||
type HipValidator = dyn Fn(&HipControl<'_>) -> io::Result<()> + Send + Sync;
|
||||
|
||||
#[derive(Default)]
|
||||
pub enum HipSource {
|
||||
#[default]
|
||||
Disabled,
|
||||
Generator(Arc<HipGenerator>),
|
||||
Script(HipScript),
|
||||
}
|
||||
|
||||
impl HipSource {
|
||||
/// Collect through the same bounded executor used by tunnel submissions.
|
||||
/// Disabled posture is a caller policy; this method never invents a report.
|
||||
pub fn collect(&self, request: &HipRequest, check: &dyn Fn() -> io::Result<()>) -> io::Result<String> {
|
||||
ffi::collect_hip_source(self, request, check)
|
||||
}
|
||||
}
|
||||
|
||||
/// Current gateway and negotiated identity inputs for one report invocation.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct HipRequest {
|
||||
pub cookie: String,
|
||||
pub client_ip: Option<String>,
|
||||
pub client_ipv6: Option<String>,
|
||||
pub md5: String,
|
||||
pub client_version: String,
|
||||
pub client_os: String,
|
||||
pub os_version: String,
|
||||
pub host_id: Option<String>,
|
||||
pub local_hostname: Option<String>,
|
||||
}
|
||||
|
||||
/// Borrowed cancellation and deadline control. It must stay on the invocation thread.
|
||||
pub struct HipControl<'a> {
|
||||
pub(crate) raw: &'a ffi::HipControlRaw,
|
||||
pub(crate) _thread: PhantomData<Rc<()>>,
|
||||
}
|
||||
|
||||
impl HipControl<'_> {
|
||||
pub fn check(&self) -> io::Result<()> {
|
||||
let result = unsafe { (self.raw.check)(self.raw.data) };
|
||||
if result < 0 {
|
||||
Err(io::Error::from_raw_os_error(-result))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct HipScriptEnvironment {
|
||||
pub variables: Vec<(String, String)>,
|
||||
pub cwd: String,
|
||||
}
|
||||
|
||||
pub struct HipScript {
|
||||
pub(crate) path: CString,
|
||||
pub(crate) user: Option<u32>,
|
||||
pub(crate) validator: Option<Arc<HipValidator>>,
|
||||
pub(crate) environment: Option<Vec<CString>>,
|
||||
pub(crate) cwd: Option<CString>,
|
||||
}
|
||||
|
||||
impl HipScript {
|
||||
pub fn new(path: String, user: Option<u32>) -> io::Result<Self> {
|
||||
if !std::fs::metadata(&path)?.is_file() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"HIP executable is not a regular file",
|
||||
));
|
||||
}
|
||||
check_executable(&path)?;
|
||||
let path = c_string(path)?;
|
||||
Ok(Self {
|
||||
path,
|
||||
user,
|
||||
validator: None,
|
||||
environment: None,
|
||||
cwd: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn with_validator(
|
||||
mut self,
|
||||
validator: impl Fn(&HipControl<'_>) -> io::Result<()> + Send + Sync + 'static,
|
||||
) -> Self {
|
||||
self.validator = Some(Arc::new(validator));
|
||||
self
|
||||
}
|
||||
|
||||
/// A child-local replacement environment and working directory, never process-global changes.
|
||||
pub fn with_environment(mut self, environment: HipScriptEnvironment) -> io::Result<Self> {
|
||||
let variables = environment
|
||||
.variables
|
||||
.into_iter()
|
||||
.map(|(key, value)| {
|
||||
if key.is_empty() || key.contains('=') {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"Invalid HIP environment key",
|
||||
));
|
||||
}
|
||||
c_string(format!("{key}={value}"))
|
||||
})
|
||||
.collect::<io::Result<Vec<_>>>()?;
|
||||
self.environment = Some(variables);
|
||||
self.cwd = Some(c_string(environment.cwd)?);
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Collect using the same OpenConnect subprocess machinery as connected submissions.
|
||||
pub fn collect(&self, request: &HipRequest, check: &dyn Fn() -> io::Result<()>) -> io::Result<String> {
|
||||
ffi::collect_hip_script(self, request, check)
|
||||
}
|
||||
}
|
||||
|
||||
fn c_string(value: String) -> io::Result<CString> {
|
||||
CString::new(value).map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "HIP value contains NUL"))
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
mod ffi;
|
||||
mod hip;
|
||||
mod vpn;
|
||||
mod vpn_utils;
|
||||
|
||||
pub use hip::*;
|
||||
pub use vpn::*;
|
||||
pub use vpn_utils::*;
|
||||
+369
-55
@@ -1,21 +1,24 @@
|
||||
use std::{
|
||||
ffi::{CStr, CString, c_char},
|
||||
fmt,
|
||||
sync::{Arc, RwLock},
|
||||
fmt, io,
|
||||
sync::{Arc, Mutex, RwLock},
|
||||
};
|
||||
|
||||
use log::info;
|
||||
use log::{info, warn};
|
||||
|
||||
use crate::ffi;
|
||||
use crate::vpn_utils::{check_executable, find_csd_wrapper, find_vpnc_script};
|
||||
use crate::vpn_utils::{check_executable, find_vpnc_script};
|
||||
use crate::{HipSource, ffi};
|
||||
|
||||
type OnConnectedCallback = Arc<RwLock<Option<Box<dyn FnOnce(VpnSessionInfo) + 'static + Send + Sync>>>>;
|
||||
type OnHipReportCallback = RwLock<Option<Arc<dyn Fn(&str) + Send + Sync>>>;
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct VpnSessionInfo {
|
||||
pub lifetime_secs: Option<u32>,
|
||||
pub user_expires: Option<u32>,
|
||||
pub lifetime_warning: Option<VpnSessionWarning>,
|
||||
pub nlb_enabled: bool,
|
||||
pub nlb_connected_gw_ip: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -41,6 +44,8 @@ pub(crate) fn session_info_from_raw(raw: *const ffi::VpnSessionInfoRaw) -> VpnSe
|
||||
(Some(prior_secs), Some(message)) => Some(VpnSessionWarning { prior_secs, message }),
|
||||
_ => None,
|
||||
},
|
||||
nlb_enabled: raw.nlb_enabled != 0,
|
||||
nlb_connected_gw_ip: unsafe { optional_c_string(raw.nlb_connected_gw_ip) },
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,7 +61,45 @@ fn positive_i64_to_u32(value: i64) -> Option<u32> {
|
||||
u32::try_from(value).ok().filter(|value| *value > 0)
|
||||
}
|
||||
|
||||
// The descriptor is borrowed only between attach and detach. Serialize writes
|
||||
// against teardown and retain cancellation before the pipe exists.
|
||||
#[derive(Default)]
|
||||
struct Cancellation {
|
||||
state: Mutex<CancellationState>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct CancellationState {
|
||||
requested: bool,
|
||||
command_fd: Option<i32>,
|
||||
}
|
||||
|
||||
impl Cancellation {
|
||||
fn attach(&self, fd: i32) -> bool {
|
||||
let mut state = self.state.lock().unwrap();
|
||||
state.command_fd = Some(fd);
|
||||
state.requested
|
||||
}
|
||||
|
||||
fn detach(&self) {
|
||||
self.state.lock().unwrap().command_fd = None;
|
||||
}
|
||||
|
||||
fn cancel(&self) -> io::Result<()> {
|
||||
let mut state = self.state.lock().unwrap();
|
||||
if state.requested {
|
||||
return Ok(());
|
||||
}
|
||||
state.requested = true;
|
||||
if let Some(fd) = state.command_fd {
|
||||
ffi::write_cancel(fd)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Vpn {
|
||||
cancellation: Cancellation,
|
||||
server: CString,
|
||||
cookie: CString,
|
||||
|
||||
@@ -76,8 +119,7 @@ pub struct Vpn {
|
||||
key_password: Option<CString>,
|
||||
servercert: Option<CString>,
|
||||
|
||||
csd_uid: u32,
|
||||
csd_wrapper: Option<CString>,
|
||||
pub(crate) hip_source: Arc<HipSource>,
|
||||
|
||||
reconnect_timeout: u32,
|
||||
mtu: u32,
|
||||
@@ -88,6 +130,7 @@ pub struct Vpn {
|
||||
no_xmlpost: bool,
|
||||
|
||||
callback: OnConnectedCallback,
|
||||
hip_report_callback: OnHipReportCallback,
|
||||
}
|
||||
|
||||
impl Vpn {
|
||||
@@ -96,12 +139,47 @@ impl Vpn {
|
||||
}
|
||||
|
||||
pub fn connect(&self, on_connected: impl FnOnce(VpnSessionInfo) + 'static + Send + Sync) -> i32 {
|
||||
match self.hip_source.as_ref() {
|
||||
HipSource::Disabled => info!("HIP reporting: disabled"),
|
||||
HipSource::Generator(_) => info!("HIP reporting: enabled, source=callback"),
|
||||
HipSource::Script(script) => {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let uid = script.user.unwrap_or_else(|| unsafe { libc::geteuid() });
|
||||
info!("HIP reporting: enabled, source=script, uid={uid}");
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
match script.user {
|
||||
Some(uid) => info!("HIP reporting: enabled, source=script, uid={uid}"),
|
||||
None => info!("HIP reporting: enabled, source=script, user=process-user"),
|
||||
}
|
||||
}
|
||||
}
|
||||
self.callback.write().unwrap().replace(Box::new(on_connected));
|
||||
let options = self.build_connect_options();
|
||||
|
||||
let mut options = self.build_connect_options();
|
||||
let environment = match self.hip_source.as_ref() {
|
||||
HipSource::Script(script) => ffi::script_environment(script),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if !environment.is_empty() {
|
||||
options.hip_script.environment = environment.as_ptr();
|
||||
}
|
||||
ffi::connect(&options)
|
||||
}
|
||||
|
||||
/// Receives a borrowed report after the gateway accepts its HIP submission.
|
||||
/// The callback must copy the XML if it needs to retain it.
|
||||
pub fn set_hip_report_callback(&self, callback: impl Fn(&str) + Send + Sync + 'static) {
|
||||
*self.hip_report_callback.write().unwrap() = Some(Arc::new(callback));
|
||||
}
|
||||
|
||||
pub(crate) fn on_hip_report_submitted(&self, report: &str) {
|
||||
let callback = self.hip_report_callback.read().unwrap().clone();
|
||||
if let Some(callback) = callback {
|
||||
callback(report);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn on_connected(&self, pipe_fd: i32, session_info: VpnSessionInfo) {
|
||||
info!("Connected to VPN, pipe_fd: {}", pipe_fd);
|
||||
|
||||
@@ -110,13 +188,24 @@ impl Vpn {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn attach_command_pipe(&self, fd: i32) -> bool {
|
||||
self.cancellation.attach(fd)
|
||||
}
|
||||
|
||||
pub(crate) fn detach_command_pipe(&self) {
|
||||
self.cancellation.detach();
|
||||
}
|
||||
|
||||
pub fn disconnect(&self) {
|
||||
ffi::disconnect();
|
||||
if let Err(error) = self.cancellation.cancel() {
|
||||
warn!("Failed to signal VPN cancellation: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
fn build_connect_options(&self) -> ffi::ConnectOptions {
|
||||
ffi::ConnectOptions {
|
||||
user_data: self as *const _ as *mut _,
|
||||
on_hip_report_submitted: Some(ffi::on_hip_report_submitted),
|
||||
|
||||
server: self.server.as_ptr(),
|
||||
cookie: self.cookie.as_ptr(),
|
||||
@@ -137,8 +226,14 @@ impl Vpn {
|
||||
key_password: Self::option_to_ptr(&self.key_password),
|
||||
servercert: Self::option_to_ptr(&self.servercert),
|
||||
|
||||
csd_uid: self.csd_uid,
|
||||
csd_wrapper: Self::option_to_ptr(&self.csd_wrapper),
|
||||
hip_script: match self.hip_source.as_ref() {
|
||||
HipSource::Script(script) => ffi::HipScriptRaw::from_script(script),
|
||||
_ => Default::default(),
|
||||
},
|
||||
generate_hip: match self.hip_source.as_ref() {
|
||||
HipSource::Generator(_) => Some(ffi::generate_hip_report),
|
||||
_ => None,
|
||||
},
|
||||
|
||||
reconnect_timeout: self.reconnect_timeout,
|
||||
mtu: self.mtu,
|
||||
@@ -180,6 +275,7 @@ pub struct VpnBuilder {
|
||||
server: String,
|
||||
cookie: String,
|
||||
script: Option<String>,
|
||||
script_is_path: bool,
|
||||
interface: Option<String>,
|
||||
script_tun: bool,
|
||||
|
||||
@@ -194,9 +290,7 @@ pub struct VpnBuilder {
|
||||
sslkey: Option<String>,
|
||||
key_password: Option<String>,
|
||||
|
||||
hip: bool,
|
||||
csd_uid: u32,
|
||||
csd_wrapper: Option<String>,
|
||||
hip_source: Arc<HipSource>,
|
||||
|
||||
reconnect_timeout: u32,
|
||||
mtu: u32,
|
||||
@@ -213,6 +307,7 @@ impl VpnBuilder {
|
||||
server: server.to_string(),
|
||||
cookie: cookie.to_string(),
|
||||
script: None,
|
||||
script_is_path: false,
|
||||
interface: None,
|
||||
script_tun: false,
|
||||
|
||||
@@ -227,9 +322,7 @@ impl VpnBuilder {
|
||||
sslkey: None,
|
||||
key_password: None,
|
||||
|
||||
hip: false,
|
||||
csd_uid: 0,
|
||||
csd_wrapper: None,
|
||||
hip_source: Arc::new(HipSource::Disabled),
|
||||
|
||||
reconnect_timeout: 300,
|
||||
mtu: 0,
|
||||
@@ -242,6 +335,13 @@ impl VpnBuilder {
|
||||
|
||||
pub fn script<T: Into<Option<String>>>(mut self, script: T) -> Self {
|
||||
self.script = script.into();
|
||||
self.script_is_path = false;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn script_path<T: Into<Option<String>>>(mut self, script: T) -> Self {
|
||||
self.script = script.into();
|
||||
self.script_is_path = true;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -300,18 +400,8 @@ impl VpnBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn hip(mut self, hip: bool) -> Self {
|
||||
self.hip = hip;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn csd_uid(mut self, csd_uid: u32) -> Self {
|
||||
self.csd_uid = csd_uid;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn csd_wrapper<T: Into<Option<String>>>(mut self, csd_wrapper: T) -> Self {
|
||||
self.csd_wrapper = csd_wrapper.into();
|
||||
pub fn hip_source(mut self, hip_source: impl Into<Arc<HipSource>>) -> Self {
|
||||
self.hip_source = hip_source.into();
|
||||
self
|
||||
}
|
||||
|
||||
@@ -345,41 +435,32 @@ impl VpnBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
fn determine_script(&self) -> Result<&str, VpnError> {
|
||||
fn determine_script(&self) -> Result<String, VpnError> {
|
||||
match &self.script {
|
||||
Some(script) => {
|
||||
if self.script_is_path && !std::path::Path::new(script).exists() {
|
||||
return Err(VpnError::new(format!("VPN script does not exist: {script}")));
|
||||
}
|
||||
check_executable(script).map_err(|e| VpnError::new(e.to_string()))?;
|
||||
Ok(script)
|
||||
Ok(script.clone())
|
||||
}
|
||||
None => find_vpnc_script().ok_or_else(|| VpnError::new(String::from("Failed to find vpnc-script"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn determine_csd_wrapper(&self) -> Result<Option<&str>, VpnError> {
|
||||
if !self.hip {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
match &self.csd_wrapper {
|
||||
Some(csd_wrapper) if !csd_wrapper.is_empty() => {
|
||||
check_executable(csd_wrapper).map_err(|e| VpnError::new(e.to_string()))?;
|
||||
Ok(Some(csd_wrapper))
|
||||
}
|
||||
_ => {
|
||||
let s = find_csd_wrapper().ok_or_else(|| VpnError::new(String::from("Failed to find csd wrapper")))?;
|
||||
Ok(Some(s))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build(self) -> Result<Vpn, VpnError> {
|
||||
let script = self.determine_script()?.to_owned();
|
||||
let csd_wrapper = self.determine_csd_wrapper()?.map(|s| s.to_owned());
|
||||
let script = self.determine_script()?;
|
||||
let script = if self.script_is_path || self.script.is_none() {
|
||||
shell_quote_path(&script)
|
||||
} else {
|
||||
script
|
||||
};
|
||||
|
||||
let user_agent = self.user_agent.unwrap_or_default();
|
||||
let os = self.os.unwrap_or("linux".to_string());
|
||||
|
||||
Ok(Vpn {
|
||||
cancellation: Cancellation::default(),
|
||||
server: Self::to_cstring(&self.server),
|
||||
cookie: Self::to_cstring(&self.cookie),
|
||||
|
||||
@@ -399,8 +480,7 @@ impl VpnBuilder {
|
||||
key_password: self.key_password.as_deref().map(Self::to_cstring),
|
||||
servercert: None,
|
||||
|
||||
csd_uid: self.csd_uid,
|
||||
csd_wrapper: csd_wrapper.as_deref().map(Self::to_cstring),
|
||||
hip_source: self.hip_source,
|
||||
|
||||
reconnect_timeout: self.reconnect_timeout,
|
||||
mtu: self.mtu,
|
||||
@@ -410,6 +490,7 @@ impl VpnBuilder {
|
||||
no_xmlpost: self.no_xmlpost,
|
||||
|
||||
callback: Default::default(),
|
||||
hip_report_callback: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -418,20 +499,57 @@ impl VpnBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
fn shell_quote_path(path: &str) -> String {
|
||||
format!("'{}'", path.replace('\'', "'\\''"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::ffi::CString;
|
||||
|
||||
#[test]
|
||||
fn quotes_vpnc_script_path_for_the_shell() {
|
||||
assert_eq!(
|
||||
shell_quote_path("/Applications/GP Connect.app/Contents/Helpers/vpnc-script"),
|
||||
"'/Applications/GP Connect.app/Contents/Helpers/vpnc-script'"
|
||||
);
|
||||
assert_eq!(shell_quote_path("/tmp/user's script"), "'/tmp/user'\\''s script'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_vpnc_script_commands() {
|
||||
let command = "\"/tmp/script with spaces\" --option";
|
||||
let vpn = Vpn::builder("vpn.example.com", "cookie")
|
||||
.script(command.to_string())
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(vpn.script.to_str().unwrap(), command);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quotes_explicit_vpnc_script_paths() {
|
||||
let vpn = Vpn::builder("vpn.example.com", "cookie")
|
||||
.script_path("/bin/sh".to_string())
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(vpn.script.to_str().unwrap(), "'/bin/sh'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_session_info_from_callback_payload() {
|
||||
let message = CString::new("Session expires soon").unwrap();
|
||||
let connected_gw = CString::new("10.1.2.3").unwrap();
|
||||
let raw = ffi::VpnSessionInfoRaw {
|
||||
auth_expiration: 0,
|
||||
lifetime_secs: 43_200,
|
||||
user_expires: 1_776_828_409,
|
||||
lifetime_warning_prior: 1_800,
|
||||
lifetime_warning_message: message.as_ptr(),
|
||||
nlb_enabled: 1,
|
||||
nlb_connected_gw_ip: connected_gw.as_ptr(),
|
||||
};
|
||||
|
||||
let info = session_info_from_raw(&raw);
|
||||
@@ -445,6 +563,8 @@ mod tests {
|
||||
message: "Session expires soon".to_string(),
|
||||
})
|
||||
);
|
||||
assert!(info.nlb_enabled);
|
||||
assert_eq!(info.nlb_connected_gw_ip.as_deref(), Some("10.1.2.3"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -455,6 +575,8 @@ mod tests {
|
||||
user_expires: 0,
|
||||
lifetime_warning_prior: 0,
|
||||
lifetime_warning_message: std::ptr::null(),
|
||||
nlb_enabled: 0,
|
||||
nlb_connected_gw_ip: std::ptr::null(),
|
||||
};
|
||||
|
||||
let info = session_info_from_raw(&raw);
|
||||
@@ -467,6 +589,7 @@ mod tests {
|
||||
#[test]
|
||||
fn connect_options_include_host_id() {
|
||||
let vpn = Vpn {
|
||||
cancellation: Cancellation::default(),
|
||||
server: CString::new("gateway.example.com").unwrap(),
|
||||
cookie: CString::new("cookie").unwrap(),
|
||||
user_agent: CString::new("agent").unwrap(),
|
||||
@@ -482,8 +605,7 @@ mod tests {
|
||||
sslkey: None,
|
||||
key_password: None,
|
||||
servercert: None,
|
||||
csd_uid: 0,
|
||||
csd_wrapper: None,
|
||||
hip_source: Arc::new(HipSource::Disabled),
|
||||
reconnect_timeout: 300,
|
||||
mtu: 0,
|
||||
disable_ipv6: false,
|
||||
@@ -491,6 +613,7 @@ mod tests {
|
||||
dpd_interval: 0,
|
||||
no_xmlpost: false,
|
||||
callback: Default::default(),
|
||||
hip_report_callback: Default::default(),
|
||||
};
|
||||
|
||||
let options = vpn.build_connect_options();
|
||||
@@ -498,4 +621,195 @@ mod tests {
|
||||
let host_id = unsafe { CStr::from_ptr(options.host_id) }.to_str().unwrap();
|
||||
assert_eq!(host_id, "profile-host-id");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hip_report_callback_copies_only_bounded_utf8() {
|
||||
let vpn = Vpn::builder("vpn.example.com", "cookie")
|
||||
.script_path("/bin/sh".to_string())
|
||||
.build()
|
||||
.unwrap();
|
||||
let reports = Arc::new(Mutex::new(Vec::new()));
|
||||
let received = Arc::clone(&reports);
|
||||
vpn.set_hip_report_callback(move |report| received.lock().unwrap().push(report.to_owned()));
|
||||
|
||||
let options = vpn.build_connect_options();
|
||||
let callback = options.on_hip_report_submitted.unwrap();
|
||||
callback(options.user_data, b"<report/>".as_ptr().cast(), 9);
|
||||
callback(options.user_data, b"\xff".as_ptr().cast(), 1);
|
||||
callback(options.user_data, b"x".as_ptr().cast(), 1024 * 1024 + 1);
|
||||
|
||||
assert_eq!(*reports.lock().unwrap(), ["<report/>"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disconnect_before_connect_is_retained_without_contacting_server() {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
let vpn = Vpn::builder(&format!("https://{}", listener.local_addr().unwrap()), "test-cookie")
|
||||
.script_path("/bin/sh".to_string())
|
||||
.build()
|
||||
.unwrap();
|
||||
vpn.disconnect();
|
||||
vpn.disconnect();
|
||||
assert_ne!(vpn.connect(|_| panic!("Canceled attempt connected")), 0);
|
||||
assert_eq!(listener.accept().unwrap_err().kind(), io::ErrorKind::WouldBlock);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_pipe_failure_preserves_stdin() {
|
||||
use std::{
|
||||
ffi::{c_int, c_void},
|
||||
fs::File,
|
||||
os::fd::AsFd,
|
||||
process::{Command, Stdio},
|
||||
};
|
||||
|
||||
const CHILD: &str = "OPENCONNECT_TEST_PIPE_FAILURE";
|
||||
if std::env::var_os(CHILD).is_none() {
|
||||
// Limit descriptors only in a subprocess, leaving the test runner untouched.
|
||||
let output = Command::new("sh")
|
||||
.args([
|
||||
"-c",
|
||||
"ulimit -n 64 && exec \"$1\" --exact vpn::tests::command_pipe_failure_preserves_stdin --nocapture",
|
||||
"sh",
|
||||
])
|
||||
.arg(std::env::current_exe().unwrap())
|
||||
.env(CHILD, "1")
|
||||
.stdin(Stdio::null())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
unsafe extern "C" {
|
||||
fn openconnect_vpninfo_new(
|
||||
agent: *const c_char,
|
||||
validate: Option<unsafe extern "C" fn(*mut c_void, *const c_char) -> c_int>,
|
||||
config: Option<unsafe extern "C" fn(*mut c_void, *const c_char, c_int) -> c_int>,
|
||||
auth: Option<unsafe extern "C" fn(*mut c_void, *mut c_void) -> c_int>,
|
||||
progress: Option<unsafe extern "C" fn(*mut c_void, c_int, *const c_char, ...)>,
|
||||
data: *mut c_void,
|
||||
) -> *mut c_void;
|
||||
fn openconnect_setup_cmd_pipe(info: *mut c_void) -> c_int;
|
||||
fn openconnect_vpninfo_free(info: *mut c_void);
|
||||
}
|
||||
// Construct first so resource exhaustion targets pipe creation specifically.
|
||||
let info = unsafe { openconnect_vpninfo_new(c"test".as_ptr(), None, None, None, None, std::ptr::null_mut()) };
|
||||
assert!(!info.is_null());
|
||||
let mut descriptors = Vec::new();
|
||||
loop {
|
||||
match File::open("/dev/null") {
|
||||
Ok(file) => descriptors.push(file),
|
||||
Err(error) => {
|
||||
assert_eq!(error.raw_os_error(), Some(24)); // EMFILE on supported Unix platforms.
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(unsafe { openconnect_setup_cmd_pipe(info) } < 0);
|
||||
unsafe { openconnect_vpninfo_free(info) };
|
||||
// Constructor resource acquisition may also fail before selecting a protocol.
|
||||
let info = unsafe { openconnect_vpninfo_new(c"test".as_ptr(), None, None, None, None, std::ptr::null_mut()) };
|
||||
if !info.is_null() {
|
||||
unsafe { openconnect_vpninfo_free(info) };
|
||||
}
|
||||
drop(descriptors);
|
||||
std::io::stdin()
|
||||
.as_fd()
|
||||
.try_clone_to_owned()
|
||||
.expect("Cleanup closed stdin");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disconnect_interrupts_in_progress_tls_and_cannot_cancel_another_attempt() {
|
||||
use std::{io::Read, sync::mpsc, thread, time::Duration};
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
listener.set_nonblocking(true).unwrap();
|
||||
let vpn = Arc::new(
|
||||
Vpn::builder(&format!("https://{}", listener.local_addr().unwrap()), "test-cookie")
|
||||
.script_path("/bin/sh".to_string())
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let worker_vpn = vpn.clone();
|
||||
let worker = thread::spawn(move || {
|
||||
tx.send(worker_vpn.connect(|_| panic!("Test peer never completes TLS")))
|
||||
.unwrap();
|
||||
});
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(3);
|
||||
let peer = loop {
|
||||
match listener.accept() {
|
||||
Ok((peer, _)) => break peer,
|
||||
Err(error) if error.kind() == io::ErrorKind::WouldBlock && std::time::Instant::now() < deadline => {
|
||||
thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
other => {
|
||||
vpn.disconnect();
|
||||
worker.join().unwrap();
|
||||
panic!("Connection did not reach test peer: {other:?}");
|
||||
}
|
||||
}
|
||||
};
|
||||
vpn.disconnect();
|
||||
let result = rx.recv_timeout(Duration::from_secs(2));
|
||||
drop(peer); // Release the peer even if cancellation regresses.
|
||||
worker.join().unwrap();
|
||||
assert_ne!(result.expect("Cancellation did not interrupt TLS"), 0);
|
||||
use std::os::{fd::AsRawFd, unix::net::UnixStream};
|
||||
let next = Cancellation::default();
|
||||
let (mut reader, writer) = UnixStream::pair().unwrap();
|
||||
reader.set_nonblocking(true).unwrap();
|
||||
assert!(!next.attach(writer.as_raw_fd()));
|
||||
vpn.disconnect(); // A late stop of the old attempt cannot affect the new one.
|
||||
assert_eq!(reader.read(&mut [0]).unwrap_err().kind(), io::ErrorKind::WouldBlock);
|
||||
next.detach();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_racing_pipe_attachment_is_never_lost() {
|
||||
use std::{
|
||||
io::Read,
|
||||
os::{fd::AsRawFd, unix::net::UnixStream},
|
||||
thread,
|
||||
};
|
||||
for _ in 0..100 {
|
||||
let cancellation = Cancellation::default();
|
||||
let (mut reader, writer) = UnixStream::pair().unwrap();
|
||||
reader.set_nonblocking(true).unwrap();
|
||||
let pending = thread::scope(|scope| {
|
||||
let cancel = scope.spawn(|| cancellation.cancel().unwrap());
|
||||
let pending = cancellation.attach(writer.as_raw_fd());
|
||||
cancel.join().unwrap();
|
||||
pending
|
||||
});
|
||||
if !pending {
|
||||
let mut command = [0];
|
||||
assert_eq!(reader.read(&mut command).unwrap(), 1);
|
||||
assert_eq!(command[0], b'x');
|
||||
}
|
||||
cancellation.detach();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disconnect_after_detach_never_writes_to_the_old_descriptor() {
|
||||
use std::{
|
||||
io::Read,
|
||||
os::{fd::AsRawFd, unix::net::UnixStream},
|
||||
};
|
||||
let cancellation = Cancellation::default();
|
||||
let (mut reader, writer) = UnixStream::pair().unwrap();
|
||||
reader.set_nonblocking(true).unwrap();
|
||||
assert!(!cancellation.attach(writer.as_raw_fd()));
|
||||
cancellation.detach();
|
||||
cancellation.cancel().unwrap();
|
||||
assert_eq!(reader.read(&mut [0]).unwrap_err().kind(), io::ErrorKind::WouldBlock);
|
||||
}
|
||||
}
|
||||
@@ -19,21 +19,6 @@ const VPNC_SCRIPT_LOCATIONS: &[&str] = &[
|
||||
"/usr/local/etc/vpnc/vpnc-script",
|
||||
];
|
||||
|
||||
const CSD_WRAPPER_LOCATIONS: &[&str] = &[
|
||||
"/usr/local/libexec/gpclient/hipreport.sh",
|
||||
"/usr/libexec/gpclient/hipreport.sh",
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
"/usr/lib/x86_64-linux-gnu/openconnect/hipreport.sh",
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
"/usr/lib/aarch64-linux-gnu/openconnect/hipreport.sh",
|
||||
"/usr/lib/openconnect/hipreport.sh",
|
||||
"/usr/libexec/openconnect/hipreport.sh",
|
||||
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
|
||||
"/opt/homebrew/opt/openconnect/libexec/openconnect/hipreport.sh",
|
||||
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
|
||||
"/usr/local/opt/openconnect/libexec/openconnect/hipreport.sh",
|
||||
];
|
||||
|
||||
fn find_executable(locations: &[&'static str]) -> Option<&'static str> {
|
||||
for location in locations.iter() {
|
||||
let path = Path::new(location);
|
||||
@@ -45,12 +30,18 @@ fn find_executable(locations: &[&'static str]) -> Option<&'static str> {
|
||||
None
|
||||
}
|
||||
|
||||
pub fn find_vpnc_script() -> Option<&'static str> {
|
||||
find_executable(VPNC_SCRIPT_LOCATIONS)
|
||||
pub fn find_vpnc_script() -> Option<String> {
|
||||
if let Some(path) = std::env::var_os("GP_VPNC_SCRIPT").filter(|path| !path.is_empty()) {
|
||||
return configured_script(Path::new(&path));
|
||||
}
|
||||
find_executable(VPNC_SCRIPT_LOCATIONS).map(str::to_owned)
|
||||
}
|
||||
|
||||
pub fn find_csd_wrapper() -> Option<&'static str> {
|
||||
find_executable(CSD_WRAPPER_LOCATIONS)
|
||||
fn configured_script(path: &Path) -> Option<String> {
|
||||
if path.is_absolute() && path.is_file() && path.is_executable() {
|
||||
return path.to_str().map(str::to_owned);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// If file exists, check if it is executable
|
||||
@@ -66,3 +57,17 @@ pub fn check_executable(file: &str) -> Result<(), io::Error> {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn configured_script_requires_an_absolute_executable_path() {
|
||||
assert_eq!(configured_script(Path::new("/bin/sh")), Some("/bin/sh".to_owned()));
|
||||
assert!(configured_script(Path::new("bin/sh")).is_none());
|
||||
assert!(configured_script(Path::new("/missing-openconnect-vpnc-script")).is_none());
|
||||
assert!(configured_script(Path::new("/etc/passwd")).is_none());
|
||||
assert!(configured_script(Path::new("/tmp")).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Local TLS GlobalProtect fixture accepting HIP and raw SSL tunnel setup."""
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
import threading
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
cert, key, records = sys.argv[1:]
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.load_cert_chain(cert, key)
|
||||
listener = socket.socket()
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
listener.listen()
|
||||
state = {"configs": 0, "checks": 0, "reports": 0}
|
||||
lock = threading.Lock()
|
||||
|
||||
|
||||
def serve(connection):
|
||||
try:
|
||||
connection.settimeout(5)
|
||||
with context.wrap_socket(connection, server_side=True) as stream:
|
||||
buffer = b""
|
||||
while True:
|
||||
while b"\r\n\r\n" not in buffer:
|
||||
data = stream.recv(4096)
|
||||
if not data:
|
||||
return
|
||||
buffer += data
|
||||
headers, buffer = buffer.split(b"\r\n\r\n", 1)
|
||||
method, path, _ = headers.split(b"\r\n", 1)[0].decode().split()
|
||||
print(f"Gateway received {method} {path.split('?')[0]}", file=sys.stderr, flush=True)
|
||||
if method == "GET" and path.startswith("/ssl-tunnel-connect.sslvpn?"):
|
||||
stream.sendall(b"START_TUNNEL")
|
||||
while stream.recv(4096):
|
||||
pass
|
||||
return
|
||||
length = 0
|
||||
for header in headers.split(b"\r\n")[1:]:
|
||||
name, value = header.split(b":", 1)
|
||||
if name.lower() == b"content-length":
|
||||
length = int(value)
|
||||
while len(buffer) < length:
|
||||
data = stream.recv(4096)
|
||||
if not data:
|
||||
raise EOFError(f"Incomplete body for {path}: {len(buffer)}/{length}")
|
||||
buffer += data
|
||||
body, buffer = buffer[:length], buffer[length:]
|
||||
form = parse_qs(body.decode())
|
||||
status = "200 OK"
|
||||
with lock:
|
||||
if path == "/ssl-vpn/getconfig.esp":
|
||||
state["configs"] += 1
|
||||
ip = "10.0.0.1"
|
||||
response = f"<response><ip-address>{ip}</ip-address><gw-address>127.0.0.1</gw-address><ssl-tunnel-url>/ssl-tunnel-connect.sslvpn</ssl-tunnel-url></response>"
|
||||
elif path == "/ssl-vpn/hipreportcheck.esp":
|
||||
state["checks"] += 1
|
||||
needed = "no" if state["checks"] == 4 else "yes"
|
||||
response = f"<response><hip-report-needed>{needed}</hip-report-needed></response>"
|
||||
elif path == "/ssl-vpn/hipreport.esp":
|
||||
state["reports"] += 1
|
||||
seq = state["reports"]
|
||||
expected_ip = "10.0.0.1"
|
||||
assert form.get("authcookie") == ["test" if seq < 3 else "refreshed"]
|
||||
expected = f'<hip seq="{seq}" ip="{expected_ip}"/>'
|
||||
assert form.get("report") == [expected], form
|
||||
assert form.get("client-ip") == [expected_ip], form
|
||||
with open(records, "a", encoding="utf-8") as output:
|
||||
output.write(expected + "\n")
|
||||
if seq == 4:
|
||||
status = "403 Forbidden"
|
||||
response = "<response/>"
|
||||
else:
|
||||
raise AssertionError(path)
|
||||
payload = response.encode()
|
||||
stream.sendall(f"HTTP/1.1 {status}\r\nContent-Length: {len(payload)}\r\nContent-Type: text/xml\r\nConnection: keep-alive\r\n\r\n".encode() + payload)
|
||||
print(f"Gateway responded {status} to {path.split('?')[0]}", file=sys.stderr, flush=True)
|
||||
except (ConnectionError, ssl.SSLError):
|
||||
pass
|
||||
|
||||
|
||||
print(listener.getsockname()[1], flush=True)
|
||||
while True:
|
||||
connection, _ = listener.accept()
|
||||
threading.Thread(target=serve, args=(connection,), daemon=True).start()
|
||||
@@ -0,0 +1,157 @@
|
||||
/* Integration harness: exercise setup and the actual connected periodic branch. */
|
||||
#include <config.h>
|
||||
#include "openconnect-internal.h"
|
||||
#include <assert.h>
|
||||
#include <stdarg.h>
|
||||
|
||||
struct state { int generated, accepted; };
|
||||
static int accept_cert(void *data, const char *reason) { return 0; }
|
||||
static void progress(void *data, int level, const char *format, ...) {
|
||||
if (level > PRG_INFO) return;
|
||||
va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args);
|
||||
}
|
||||
static int generate(void *data, const struct openconnect_gp_hip_request *request,
|
||||
const struct openconnect_gp_hip_control *control, char *output, size_t capacity, size_t *written)
|
||||
{
|
||||
struct state *state = data;
|
||||
int length;
|
||||
assert(!control->check(control->data));
|
||||
assert(!strcmp(request->client_os, "Linux"));
|
||||
assert(!strcmp(request->client_version, "6.3.3"));
|
||||
assert(!strcmp(request->host_id, "test-host"));
|
||||
assert(request->cookie && request->md5 && strlen(request->md5) == 32);
|
||||
/* Shared golden fixture with gpapi's non-tunnel HIP transport. */
|
||||
assert(!strcmp(request->md5, "20f30054f721fd212925866b5778447d"));
|
||||
if (state->generated >= 2) assert(strstr(request->cookie, "authcookie=refreshed"));
|
||||
state->generated++;
|
||||
length = snprintf(output, capacity, "<hip seq=\"%d\" ip=\"%s\"/>", state->generated, request->client_ip);
|
||||
assert(length > 0 && length < capacity);
|
||||
*written = length;
|
||||
return 0;
|
||||
}
|
||||
static void submitted(void *data, const char *report, size_t length) {
|
||||
struct state *state = data;
|
||||
assert(report && length > 0);
|
||||
state->accepted++;
|
||||
}
|
||||
static int periodic(struct openconnect_info *vpninfo) {
|
||||
int timeout = 1000;
|
||||
vpninfo->trojan_interval = 1;
|
||||
vpninfo->last_trojan = time(NULL) - 2;
|
||||
return gpst_mainloop(vpninfo, &timeout, 0);
|
||||
}
|
||||
|
||||
static int validate_script(void *data, const struct openconnect_gp_hip_control *control)
|
||||
{
|
||||
return control->check(control->data);
|
||||
}
|
||||
|
||||
static void script_registration_lifecycle(struct openconnect_info *vpninfo)
|
||||
{
|
||||
const char *environment[] = { "PATH=/usr/bin:/bin", NULL };
|
||||
char *path, **saved_environment, *cwd;
|
||||
int validator_data;
|
||||
uid_t uid = getuid();
|
||||
gid_t gid;
|
||||
|
||||
assert(!openconnect_set_gp_hip_script(vpninfo, "/bin/true", 1, uid,
|
||||
&validator_data, validate_script, environment, "/"));
|
||||
path = vpninfo->csd_wrapper;
|
||||
saved_environment = vpninfo->gp_hip_environment;
|
||||
cwd = vpninfo->gp_hip_cwd;
|
||||
gid = vpninfo->gid_csd;
|
||||
|
||||
/* A refused update must preserve the entire registered policy. */
|
||||
assert(openconnect_set_gp_hip_script(vpninfo, "/bin/false", 1, (uid_t)-1,
|
||||
NULL, NULL, NULL, NULL) < 0);
|
||||
assert(vpninfo->csd_wrapper == path);
|
||||
assert(vpninfo->gp_hip_environment == saved_environment);
|
||||
assert(vpninfo->gp_hip_cwd == cwd);
|
||||
assert(vpninfo->uid_csd_given == 1 && vpninfo->uid_csd == uid && vpninfo->gid_csd == gid);
|
||||
assert(vpninfo->gp_hip_validate == validate_script);
|
||||
assert(vpninfo->gp_hip_validate_data == &validator_data);
|
||||
|
||||
/* Re-registration may use pointers borrowed from the existing policy. */
|
||||
assert(!openconnect_set_gp_hip_script(vpninfo, path, 0, 0,
|
||||
&validator_data, validate_script, (const char *const *)saved_environment, cwd));
|
||||
assert(!strcmp(vpninfo->csd_wrapper, "/bin/true"));
|
||||
assert(!strcmp(vpninfo->gp_hip_environment[0], environment[0]));
|
||||
assert(!strcmp(vpninfo->gp_hip_cwd, "/"));
|
||||
assert(!vpninfo->uid_csd_given);
|
||||
|
||||
/* Legacy replacement must not retain another script's approval policy. */
|
||||
assert(!openconnect_setup_csd(vpninfo, uid, 1, "/bin/false"));
|
||||
assert(!strcmp(vpninfo->csd_wrapper, "/bin/false"));
|
||||
assert(vpninfo->uid_csd_given == 2 && vpninfo->uid_csd == uid && vpninfo->gid_csd == gid);
|
||||
assert(!vpninfo->gp_hip_validate && !vpninfo->gp_hip_validate_data);
|
||||
assert(!vpninfo->gp_hip_environment && !vpninfo->gp_hip_cwd);
|
||||
assert(!openconnect_set_gp_hip_script(vpninfo, NULL, 0, 0, NULL, NULL, NULL, NULL));
|
||||
assert(!vpninfo->csd_wrapper);
|
||||
}
|
||||
|
||||
static int close_count;
|
||||
static int count_session_close(struct openconnect_info *vpninfo, const char *reason)
|
||||
{
|
||||
assert(!strcmp(reason, "fixture exit"));
|
||||
close_count++;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void native_session_logout(void)
|
||||
{
|
||||
struct openconnect_info *vpninfo = openconnect_vpninfo_new("logout owner test",
|
||||
accept_cert, NULL, NULL, progress, NULL);
|
||||
const struct vpn_proto *original;
|
||||
struct vpn_proto protocol;
|
||||
assert(vpninfo);
|
||||
assert(!openconnect_set_protocol(vpninfo, "gp"));
|
||||
original = vpninfo->proto;
|
||||
protocol = *original;
|
||||
protocol.vpn_close_session = count_session_close;
|
||||
vpninfo->proto = &protocol;
|
||||
vpninfo->quit_reason = "fixture exit";
|
||||
/* All exit causes use this same mainloop cleanup path. */
|
||||
openconnect_mainloop(vpninfo, 0, 0);
|
||||
assert(close_count == 1);
|
||||
openconnect_mainloop(vpninfo, 0, 0);
|
||||
assert(close_count == 2);
|
||||
vpninfo->proto = original;
|
||||
openconnect_vpninfo_free(vpninfo);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
struct state state = {0};
|
||||
struct openconnect_info *vpninfo;
|
||||
assert(argc == 2);
|
||||
native_session_logout();
|
||||
openconnect_init_ssl();
|
||||
vpninfo = openconnect_vpninfo_new("HIP protocol test", accept_cert, NULL, NULL, progress, &state);
|
||||
assert(vpninfo);
|
||||
script_registration_lifecycle(vpninfo);
|
||||
assert(!openconnect_set_protocol(vpninfo, "gp"));
|
||||
assert(!openconnect_set_reported_os(vpninfo, "linux"));
|
||||
assert(!openconnect_parse_url(vpninfo, argv[1]));
|
||||
assert(!openconnect_set_cookie(vpninfo, "user=test&authcookie=test&persistent-cookie=persistent%2Bcookie&portal=test&domain=test&preferred-ip=192.0.2.1&preferred-ipv6=2001%3Adb8%3A%3A1&computer=test"));
|
||||
assert(!openconnect_set_gp_app_version(vpninfo, "6.3.3"));
|
||||
assert(!openconnect_set_gp_host_id(vpninfo, "test-host"));
|
||||
openconnect_disable_dtls(vpninfo);
|
||||
openconnect_set_gp_hip_generator(vpninfo, &state, generate);
|
||||
openconnect_set_gp_hip_report_callback(vpninfo, &state, submitted);
|
||||
assert(!openconnect_make_cstp_connection(vpninfo));
|
||||
assert(vpninfo->ssl_fd >= 0 && state.generated == 1 && state.accepted == 1);
|
||||
assert(!periodic(vpninfo));
|
||||
assert(state.generated == 2 && state.accepted == 2);
|
||||
/* A real reconnect re-fetches configuration and uses refreshed session inputs. */
|
||||
openconnect_close_https(vpninfo, 0);
|
||||
assert(!openconnect_set_cookie(vpninfo, "user=test&authcookie=refreshed&persistent-cookie=persistent%2Bcookie&portal=test&domain=test&preferred-ip=192.0.2.2&preferred-ipv6=2001%3Adb8%3A%3A2&computer=test"));
|
||||
assert(!openconnect_make_cstp_connection(vpninfo));
|
||||
assert(state.generated == 3 && state.accepted == 3);
|
||||
/* Fourth gateway check says no report needed. */
|
||||
assert(!periodic(vpninfo));
|
||||
assert(state.generated == 3 && state.accepted == 3);
|
||||
/* Fifth submission is rejected; observer must not see it. */
|
||||
assert(periodic(vpninfo));
|
||||
assert(state.generated == 4 && state.accepted == 3);
|
||||
openconnect_vpninfo_free(vpninfo);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
use std::{
|
||||
fs,
|
||||
io::{BufRead, BufReader},
|
||||
os::unix::process::CommandExt,
|
||||
path::PathBuf,
|
||||
process::{Child, Command, Stdio},
|
||||
sync::mpsc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
struct ChildGuard(Child);
|
||||
impl Drop for ChildGuard {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
libc::kill(-(self.0.id() as i32), libc::SIGKILL);
|
||||
}
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
struct TestDirectory(PathBuf);
|
||||
impl Drop for TestDirectory {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn c_protocol_submits_initial_periodic_and_reconnect_reports() {
|
||||
let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let build = PathBuf::from(env!("OPENCONNECT_PROTOCOL_BUILD"));
|
||||
let source = PathBuf::from(env!("OPENCONNECT_PROTOCOL_SOURCE"));
|
||||
let directory = TestDirectory(std::env::temp_dir().join(format!("gp-hip-protocol-{}", std::process::id())));
|
||||
fs::create_dir(&directory.0).unwrap();
|
||||
let executable = directory.0.join("hip-protocol");
|
||||
let flags = Command::new("pkg-config")
|
||||
.args([
|
||||
"--cflags",
|
||||
"libxml-2.0",
|
||||
if cfg!(target_os = "macos") { "openssl" } else { "gnutls" },
|
||||
])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(flags.status.success());
|
||||
let compile_command = Command::new(build.join("libtool"))
|
||||
.args(["--mode=link", "cc"])
|
||||
.arg(manifest.join("tests/hip_protocol.c"))
|
||||
.arg("-I")
|
||||
.arg(&build)
|
||||
.arg("-I")
|
||||
.arg(&source)
|
||||
.arg("-I")
|
||||
.arg(source.join("json"))
|
||||
.args(String::from_utf8(flags.stdout).unwrap().split_whitespace())
|
||||
.arg(build.join("libopenconnect.la"))
|
||||
.arg("-o")
|
||||
.arg(&executable)
|
||||
.process_group(0)
|
||||
.stdout(Stdio::from(fs::File::create(directory.0.join("compile.log")).unwrap()))
|
||||
.stderr(Stdio::from(
|
||||
fs::File::options()
|
||||
.append(true)
|
||||
.open(directory.0.join("compile.log"))
|
||||
.unwrap(),
|
||||
))
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut compile_command = ChildGuard(compile_command);
|
||||
wait_bounded(
|
||||
&mut compile_command,
|
||||
Duration::from_secs(30),
|
||||
&directory.0.join("compile.log"),
|
||||
);
|
||||
let records = directory.0.join("submissions");
|
||||
let certificates = manifest.join("deps/openconnect/tests/certs");
|
||||
let server = Command::new("python3")
|
||||
.arg(manifest.join("tests/hip_gateway.py"))
|
||||
.arg(certificates.join("server-cert.pem"))
|
||||
.arg(certificates.join("server-key.pem"))
|
||||
.arg(&records)
|
||||
.process_group(0)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut server = ChildGuard(server);
|
||||
let stdout = server.0.stdout.take().unwrap();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let reader = std::thread::spawn(move || {
|
||||
let mut port = String::new();
|
||||
let result = BufReader::new(stdout).read_line(&mut port).map(|_| port);
|
||||
let _ = tx.send(result);
|
||||
});
|
||||
let port = match rx.recv_timeout(Duration::from_secs(3)) {
|
||||
Ok(result) => result.expect("Fake gateway startup failed"),
|
||||
Err(error) => {
|
||||
let _ = server.0.kill();
|
||||
let _ = server.0.wait();
|
||||
let _ = reader.join();
|
||||
panic!("Fake gateway startup timed out: {error}");
|
||||
}
|
||||
};
|
||||
reader.join().unwrap();
|
||||
let port: u16 = port.trim().parse().expect("Fake gateway did not start");
|
||||
let log = fs::File::create(directory.0.join("client.log")).unwrap();
|
||||
let mut client = ChildGuard(
|
||||
Command::new(build.join("libtool"))
|
||||
.args(["--mode=execute"])
|
||||
.arg(executable)
|
||||
.arg(format!("https://127.0.0.1:{port}"))
|
||||
.process_group(0)
|
||||
.stdout(log.try_clone().unwrap())
|
||||
.stderr(log)
|
||||
.spawn()
|
||||
.unwrap(),
|
||||
);
|
||||
wait_bounded(&mut client, Duration::from_secs(15), &directory.0.join("client.log"));
|
||||
let reports = fs::read_to_string(records).unwrap();
|
||||
assert_eq!(
|
||||
reports,
|
||||
"<hip seq=\"1\" ip=\"10.0.0.1\"/>\n<hip seq=\"2\" ip=\"10.0.0.1\"/>\n<hip seq=\"3\" ip=\"10.0.0.1\"/>\n<hip seq=\"4\" ip=\"10.0.0.1\"/>\n"
|
||||
);
|
||||
}
|
||||
|
||||
fn wait_bounded(child: &mut ChildGuard, timeout: Duration, log: &std::path::Path) {
|
||||
let deadline = Instant::now() + timeout;
|
||||
loop {
|
||||
if let Some(status) = child.0.try_wait().unwrap() {
|
||||
assert!(status.success(), "{}", fs::read_to_string(log).unwrap());
|
||||
return;
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"HIP protocol test process timed out: {}",
|
||||
fs::read_to_string(log).unwrap()
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user