File libalternatives-v1.2+3.b848aad.obscpio of Package libalternatives
07070100000000000081A4000003E80000006400000001614066780000000F000000000000000000000000000000000000002A00000000libalternatives-v1.2+3.b848aad/.gitignorebuild
.vscode
07070100000001000081A4000003E800000064000000016140667800000367000000000000000000000000000000000000002E00000000libalternatives-v1.2+3.b848aad/CMakeLists.txtcmake_minimum_required(VERSION 3.8)
project(libalternatives LANGUAGES C)
include(GNUInstallDirs)
include(CTest)
option(ENABLE_COVERAGE "Add coverage target" OFF)
set(CONFIG_DIR
"${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_DATAROOTDIR}/${PROJECT_NAME}"
CACHE PATH
"Root path for alternative configs"
)
set(CONFIG_FILENAME "libalternatives.conf" CACHE STRING "Configueration filename in the SYSCONFDIR")
add_compile_options(-Wall -Wextra -Wpedantic)
if(ENABLE_COVERAGE)
include(./cmake/CodeCoverage.cmake)
APPEND_COVERAGE_COMPILER_FLAGS()
setup_target_for_coverage_lcov(
NAME coverage
EXECUTABLE units
EXCLUDE ${CMAKE_CURRENT_SOURCE_DIR}/test/*
)
endif()
add_subdirectory(src)
add_subdirectory(utils)
add_subdirectory(test)
add_subdirectory(doc)
add_test(check_version sh ${CMAKE_CURRENT_SOURCE_DIR}/release_tag.sh -c)07070100000002000081A4000003E80000006400000001614066780000894D000000000000000000000000000000000000002700000000libalternatives-v1.2+3.b848aad/COPYING 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>.
07070100000003000081A4000003E800000064000000016140667800001DE4000000000000000000000000000000000000002B00000000libalternatives-v1.2+3.b848aad/COPYING.LIB GNU LESSER 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.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
07070100000004000081A4000003E800000064000000016140667800000E97000000000000000000000000000000000000002900000000libalternatives-v1.2+3.b848aad/README.mdlibalternatives
==============
A configurable alternative for update-alternatives.
Purpose
-------
`update-alternatives`, at its core, is a symlink management system. This
system is then mostly used as means for *administrators* of a system to
select a default application. For example, if we have `vim` or `emacs`
installed, the admin can then make one accessible as an `editor`
application.
The simple principle behind `update-alternatives` also is its main
drawback. Since it only manages symlinks, the preferred configuration
is only managed per system and cannot be altered per user. Furthermore,
if an application requires additional processing prior to execution via
the default handler, this is outside the domain of `update-alternatives`.
Another major drawback of `update-alternatives` is that it is a state
system and this state is modified or updated at *installation* time. If
the state of the running system is to be kept separate from the installation
state (eg. multiple snapshots of parts of the system), the symlinks
state can become stale or simply wrong without a *possibility* of a
fallback mechanism.
Description
-----------
`libalterntive` provides an *alternative*, not a replacement, to this
symlink management system. Instead of symlinks, the preferred executable
is executed directly. Which executable is executed depends on the
available alternatives installed on the system and the system and/or
user configuration files. By default, the preferred alternative with the
highest priority is executed. If an alternative is selected by the user
or the system administrator, this alternative will be executed instead.
If the user or system selection is unavailable, the system will fall
back to the default, highest installed priority alternative.
`alts` is a simple wrapper around two config files. First is a
config file provided by packages that describe the alternatives
provided. The second config file is either a system or a user
preferences file that overrides default alternative preference.
Packages need to ship their package preferences in following format,
/usr/share/libalternatives/<binary>/<pref>.conf
where
+ *binary* is the name of the alternative provided
+ *pref* is a numeric priority
The config file must be of the following format:
binary=<absolute path to binary>
man=<list of manpages>
group=<list of binaries>
where *binary* entry is mandatory.
Typically, the *binary* can then be a symlink to
*/usr/bin/alts* that will **exec()** the configured binary
with largest pref number forwarding all the arguments to the configured
binary.
*list* constitutes a comma (,) separated items
For example:
binary=/usr/bin/vim
man=vim.1
*alts* is also the configuration utility that allows system or user
override of the default binary. See *alts(1)* for details.
Groups
------
At times, multiple alternatives should be controlled as a group.
Altering the preferred binary in one should alter the entire group. To
facilitate this, one should use the `group` entry in the package
preferences to list all the binaries that are to be altered together.
It is important that all the binaries have the same group entries in
their package preference files and have the same priorities. It is also
important that no higher priority alternative exists unless it also
forms the same sized group. The `alts` binary will warn you when reading
the state of one of the executables with a `group` entry.
Notes
-----
`libalternatives` is NOT aimed to be a replacement for
`update-alternatives`. It is meant as an alternative that tends to stay
out of the way and provides more flexibility and stability for users and
the package maintainers.
API
---
See Also
--------
+ alts(1)
07070100000005000041ED000003E800000064000000016140667800000000000000000000000000000000000000000000002500000000libalternatives-v1.2+3.b848aad/cmake07070100000006000081A4000003E80000006400000001614066780000465D000000000000000000000000000000000000003800000000libalternatives-v1.2+3.b848aad/cmake/CodeCoverage.cmake# Copyright (c) 2012 - 2017, Lars Bilke
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# CHANGES:
#
# 2012-01-31, Lars Bilke
# - Enable Code Coverage
#
# 2013-09-17, Joakim Söderberg
# - Added support for Clang.
# - Some additional usage instructions.
#
# 2016-02-03, Lars Bilke
# - Refactored functions to use named parameters
#
# 2017-06-02, Lars Bilke
# - Merged with modified version from github.com/ufz/ogs
#
# 2019-05-06, Anatolii Kurotych
# - Remove unnecessary --coverage flag
#
# 2019-12-13, FeRD (Frank Dana)
# - Deprecate COVERAGE_LCOVR_EXCLUDES and COVERAGE_GCOVR_EXCLUDES lists in favor
# of tool-agnostic COVERAGE_EXCLUDES variable, or EXCLUDE setup arguments.
# - CMake 3.4+: All excludes can be specified relative to BASE_DIRECTORY
# - All setup functions: accept BASE_DIRECTORY, EXCLUDE list
# - Set lcov basedir with -b argument
# - Add automatic --demangle-cpp in lcovr, if 'c++filt' is available (can be
# overridden with NO_DEMANGLE option in setup_target_for_coverage_lcovr().)
# - Delete output dir, .info file on 'make clean'
# - Remove Python detection, since version mismatches will break gcovr
# - Minor cleanup (lowercase function names, update examples...)
#
# 2019-12-19, FeRD (Frank Dana)
# - Rename Lcov outputs, make filtered file canonical, fix cleanup for targets
#
# 2020-01-19, Bob Apthorpe
# - Added gfortran support
#
# 2020-02-17, FeRD (Frank Dana)
# - Make all add_custom_target()s VERBATIM to auto-escape wildcard characters
# in EXCLUDEs, and remove manual escaping from gcovr targets
#
# USAGE:
#
# 1. Copy this file into your cmake modules path.
#
# 2. Add the following line to your CMakeLists.txt (best inside an if-condition
# using a CMake option() to enable it just optionally):
# include(CodeCoverage)
#
# 3. Append necessary compiler flags:
# append_coverage_compiler_flags()
#
# 3.a (OPTIONAL) Set appropriate optimization flags, e.g. -O0, -O1 or -Og
#
# 4. If you need to exclude additional directories from the report, specify them
# using full paths in the COVERAGE_EXCLUDES variable before calling
# setup_target_for_coverage_*().
# Example:
# set(COVERAGE_EXCLUDES
# '${PROJECT_SOURCE_DIR}/src/dir1/*'
# '/path/to/my/src/dir2/*')
# Or, use the EXCLUDE argument to setup_target_for_coverage_*().
# Example:
# setup_target_for_coverage_lcov(
# NAME coverage
# EXECUTABLE testrunner
# EXCLUDE "${PROJECT_SOURCE_DIR}/src/dir1/*" "/path/to/my/src/dir2/*")
#
# 4.a NOTE: With CMake 3.4+, COVERAGE_EXCLUDES or EXCLUDE can also be set
# relative to the BASE_DIRECTORY (default: PROJECT_SOURCE_DIR)
# Example:
# set(COVERAGE_EXCLUDES "dir1/*")
# setup_target_for_coverage_gcovr_html(
# NAME coverage
# EXECUTABLE testrunner
# BASE_DIRECTORY "${PROJECT_SOURCE_DIR}/src"
# EXCLUDE "dir2/*")
#
# 5. Use the functions described below to create a custom make target which
# runs your test executable and produces a code coverage report.
#
# 6. Build a Debug build:
# cmake -DCMAKE_BUILD_TYPE=Debug ..
# make
# make my_coverage_target
#
include(CMakeParseArguments)
# Check prereqs
find_program( GCOV_PATH gcov )
find_program( LCOV_PATH NAMES lcov lcov.bat lcov.exe lcov.perl)
find_program( GENHTML_PATH NAMES genhtml genhtml.perl genhtml.bat )
find_program( GCOVR_PATH gcovr PATHS ${CMAKE_SOURCE_DIR}/scripts/test)
find_program( CPPFILT_PATH NAMES c++filt )
if(NOT GCOV_PATH)
message(FATAL_ERROR "gcov not found! Aborting...")
endif() # NOT GCOV_PATH
if("${CMAKE_CXX_COMPILER_ID}" MATCHES "(Apple)?[Cc]lang")
if("${CMAKE_CXX_COMPILER_VERSION}" VERSION_LESS 3)
message(FATAL_ERROR "Clang version must be 3.0.0 or greater! Aborting...")
endif()
elseif(NOT CMAKE_COMPILER_IS_GNUCXX AND NOT ("${CMAKE_C_COMPILER_ID}" MATCHES "GNU"))
message(FATAL_ERROR "Compiler is not GNU gcc! Aborting...")
endif()
set(COVERAGE_COMPILER_FLAGS "-g -fprofile-arcs -ftest-coverage"
CACHE INTERNAL "")
set(CMAKE_Fortran_FLAGS_COVERAGE
${COVERAGE_COMPILER_FLAGS}
CACHE STRING "Flags used by the Fortran compiler during coverage builds."
FORCE )
set(CMAKE_CXX_FLAGS_COVERAGE
${COVERAGE_COMPILER_FLAGS}
CACHE STRING "Flags used by the C++ compiler during coverage builds."
FORCE )
set(CMAKE_C_FLAGS_COVERAGE
${COVERAGE_COMPILER_FLAGS}
CACHE STRING "Flags used by the C compiler during coverage builds."
FORCE )
set(CMAKE_EXE_LINKER_FLAGS_COVERAGE
""
CACHE STRING "Flags used for linking binaries during coverage builds."
FORCE )
set(CMAKE_SHARED_LINKER_FLAGS_COVERAGE
""
CACHE STRING "Flags used by the shared libraries linker during coverage builds."
FORCE )
mark_as_advanced(
CMAKE_Fortran_FLAGS_COVERAGE
CMAKE_CXX_FLAGS_COVERAGE
CMAKE_C_FLAGS_COVERAGE
CMAKE_EXE_LINKER_FLAGS_COVERAGE
CMAKE_SHARED_LINKER_FLAGS_COVERAGE )
if(NOT CMAKE_BUILD_TYPE STREQUAL "Debug")
message(WARNING "Code coverage results with an optimised (non-Debug) build may be misleading")
endif() # NOT CMAKE_BUILD_TYPE STREQUAL "Debug"
if(CMAKE_C_COMPILER_ID STREQUAL "GNU" OR CMAKE_Fortran_COMPILER_ID STREQUAL "GNU")
link_libraries(gcov)
endif()
# Defines a target for running and collection code coverage information
# Builds dependencies, runs the given executable and outputs reports.
# NOTE! The executable should always have a ZERO as exit code otherwise
# the coverage generation will not complete.
#
# setup_target_for_coverage_lcov(
# NAME testrunner_coverage # New target name
# EXECUTABLE testrunner -j ${PROCESSOR_COUNT} # Executable in PROJECT_BINARY_DIR
# DEPENDENCIES testrunner # Dependencies to build first
# BASE_DIRECTORY "../" # Base directory for report
# # (defaults to PROJECT_SOURCE_DIR)
# EXCLUDE "src/dir1/*" "src/dir2/*" # Patterns to exclude (can be relative
# # to BASE_DIRECTORY, with CMake 3.4+)
# NO_DEMANGLE # Don't demangle C++ symbols
# # even if c++filt is found
# )
function(setup_target_for_coverage_lcov)
set(options NO_DEMANGLE)
set(oneValueArgs BASE_DIRECTORY NAME)
set(multiValueArgs EXCLUDE EXECUTABLE EXECUTABLE_ARGS DEPENDENCIES LCOV_ARGS GENHTML_ARGS)
cmake_parse_arguments(Coverage "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
if(NOT LCOV_PATH)
message(FATAL_ERROR "lcov not found! Aborting...")
endif() # NOT LCOV_PATH
if(NOT GENHTML_PATH)
message(FATAL_ERROR "genhtml not found! Aborting...")
endif() # NOT GENHTML_PATH
# Set base directory (as absolute path), or default to PROJECT_SOURCE_DIR
if(${Coverage_BASE_DIRECTORY})
get_filename_component(BASEDIR ${Coverage_BASE_DIRECTORY} ABSOLUTE)
else()
set(BASEDIR ${PROJECT_SOURCE_DIR})
endif()
# Collect excludes (CMake 3.4+: Also compute absolute paths)
set(LCOV_EXCLUDES "")
foreach(EXCLUDE ${Coverage_EXCLUDE} ${COVERAGE_EXCLUDES} ${COVERAGE_LCOV_EXCLUDES})
if(CMAKE_VERSION VERSION_GREATER 3.4)
get_filename_component(EXCLUDE ${EXCLUDE} ABSOLUTE BASE_DIR ${BASEDIR})
endif()
list(APPEND LCOV_EXCLUDES "${EXCLUDE}")
endforeach()
list(REMOVE_DUPLICATES LCOV_EXCLUDES)
# Conditional arguments
if(CPPFILT_PATH AND NOT ${Coverage_NO_DEMANGLE})
set(GENHTML_EXTRA_ARGS "--demangle-cpp")
endif()
# Setup target
add_custom_target(${Coverage_NAME}
# Cleanup lcov
COMMAND ${LCOV_PATH} ${Coverage_LCOV_ARGS} --gcov-tool ${GCOV_PATH} -directory . -b ${BASEDIR} --zerocounters
# Create baseline to make sure untouched files show up in the report
COMMAND ${LCOV_PATH} ${Coverage_LCOV_ARGS} --gcov-tool ${GCOV_PATH} -c -i -d . -b ${BASEDIR} -o ${Coverage_NAME}.base
# Run tests
COMMAND ${Coverage_EXECUTABLE} ${Coverage_EXECUTABLE_ARGS}
# Capturing lcov counters and generating report
COMMAND ${LCOV_PATH} ${Coverage_LCOV_ARGS} --gcov-tool ${GCOV_PATH} --directory . -b ${BASEDIR} --capture --output-file ${Coverage_NAME}.capture
# add baseline counters
COMMAND ${LCOV_PATH} ${Coverage_LCOV_ARGS} --gcov-tool ${GCOV_PATH} -a ${Coverage_NAME}.base -a ${Coverage_NAME}.capture --output-file ${Coverage_NAME}.total
# filter collected data to final coverage report
COMMAND ${LCOV_PATH} ${Coverage_LCOV_ARGS} --gcov-tool ${GCOV_PATH} --remove ${Coverage_NAME}.total ${LCOV_EXCLUDES} --output-file ${Coverage_NAME}.info
# Generate HTML output
COMMAND ${GENHTML_PATH} ${GENHTML_EXTRA_ARGS} ${Coverage_GENHTML_ARGS} -o ${Coverage_NAME} ${Coverage_NAME}.info
# Set output files as GENERATED (will be removed on 'make clean')
BYPRODUCTS
${Coverage_NAME}.base
${Coverage_NAME}.capture
${Coverage_NAME}.total
${Coverage_NAME}.info
${Coverage_NAME} # report directory
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
DEPENDS ${Coverage_DEPENDENCIES}
VERBATIM # Protect arguments to commands
COMMENT "Resetting code coverage counters to zero.\nProcessing code coverage counters and generating report."
)
# Show where to find the lcov info report
add_custom_command(TARGET ${Coverage_NAME} POST_BUILD
COMMAND ;
COMMENT "Lcov code coverage info report saved in ${Coverage_NAME}.info."
)
# Show info where to find the report
add_custom_command(TARGET ${Coverage_NAME} POST_BUILD
COMMAND ;
COMMENT "Open ./${Coverage_NAME}/index.html in your browser to view the coverage report."
)
endfunction() # setup_target_for_coverage_lcov
# Defines a target for running and collection code coverage information
# Builds dependencies, runs the given executable and outputs reports.
# NOTE! The executable should always have a ZERO as exit code otherwise
# the coverage generation will not complete.
#
# setup_target_for_coverage_gcovr_xml(
# NAME ctest_coverage # New target name
# EXECUTABLE ctest -j ${PROCESSOR_COUNT} # Executable in PROJECT_BINARY_DIR
# DEPENDENCIES executable_target # Dependencies to build first
# BASE_DIRECTORY "../" # Base directory for report
# # (defaults to PROJECT_SOURCE_DIR)
# EXCLUDE "src/dir1/*" "src/dir2/*" # Patterns to exclude (can be relative
# # to BASE_DIRECTORY, with CMake 3.4+)
# )
function(setup_target_for_coverage_gcovr_xml)
set(options NONE)
set(oneValueArgs BASE_DIRECTORY NAME)
set(multiValueArgs EXCLUDE EXECUTABLE EXECUTABLE_ARGS DEPENDENCIES)
cmake_parse_arguments(Coverage "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
if(NOT GCOVR_PATH)
message(FATAL_ERROR "gcovr not found! Aborting...")
endif() # NOT GCOVR_PATH
# Set base directory (as absolute path), or default to PROJECT_SOURCE_DIR
if(${Coverage_BASE_DIRECTORY})
get_filename_component(BASEDIR ${Coverage_BASE_DIRECTORY} ABSOLUTE)
else()
set(BASEDIR ${PROJECT_SOURCE_DIR})
endif()
# Collect excludes (CMake 3.4+: Also compute absolute paths)
set(GCOVR_EXCLUDES "")
foreach(EXCLUDE ${Coverage_EXCLUDE} ${COVERAGE_EXCLUDES} ${COVERAGE_GCOVR_EXCLUDES})
if(CMAKE_VERSION VERSION_GREATER 3.4)
get_filename_component(EXCLUDE ${EXCLUDE} ABSOLUTE BASE_DIR ${BASEDIR})
endif()
list(APPEND GCOVR_EXCLUDES "${EXCLUDE}")
endforeach()
list(REMOVE_DUPLICATES GCOVR_EXCLUDES)
# Combine excludes to several -e arguments
set(GCOVR_EXCLUDE_ARGS "")
foreach(EXCLUDE ${GCOVR_EXCLUDES})
list(APPEND GCOVR_EXCLUDE_ARGS "-e")
list(APPEND GCOVR_EXCLUDE_ARGS "${EXCLUDE}")
endforeach()
add_custom_target(${Coverage_NAME}
# Run tests
${Coverage_EXECUTABLE} ${Coverage_EXECUTABLE_ARGS}
# Running gcovr
COMMAND ${GCOVR_PATH} --xml
-r ${BASEDIR} ${GCOVR_EXCLUDE_ARGS}
--object-directory=${PROJECT_BINARY_DIR}
-o ${Coverage_NAME}.xml
BYPRODUCTS ${Coverage_NAME}.xml
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
DEPENDS ${Coverage_DEPENDENCIES}
VERBATIM # Protect arguments to commands
COMMENT "Running gcovr to produce Cobertura code coverage report."
)
# Show info where to find the report
add_custom_command(TARGET ${Coverage_NAME} POST_BUILD
COMMAND ;
COMMENT "Cobertura code coverage report saved in ${Coverage_NAME}.xml."
)
endfunction() # setup_target_for_coverage_gcovr_xml
# Defines a target for running and collection code coverage information
# Builds dependencies, runs the given executable and outputs reports.
# NOTE! The executable should always have a ZERO as exit code otherwise
# the coverage generation will not complete.
#
# setup_target_for_coverage_gcovr_html(
# NAME ctest_coverage # New target name
# EXECUTABLE ctest -j ${PROCESSOR_COUNT} # Executable in PROJECT_BINARY_DIR
# DEPENDENCIES executable_target # Dependencies to build first
# BASE_DIRECTORY "../" # Base directory for report
# # (defaults to PROJECT_SOURCE_DIR)
# EXCLUDE "src/dir1/*" "src/dir2/*" # Patterns to exclude (can be relative
# # to BASE_DIRECTORY, with CMake 3.4+)
# )
function(setup_target_for_coverage_gcovr_html)
set(options NONE)
set(oneValueArgs BASE_DIRECTORY NAME)
set(multiValueArgs EXCLUDE EXECUTABLE EXECUTABLE_ARGS DEPENDENCIES)
cmake_parse_arguments(Coverage "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
if(NOT GCOVR_PATH)
message(FATAL_ERROR "gcovr not found! Aborting...")
endif() # NOT GCOVR_PATH
# Set base directory (as absolute path), or default to PROJECT_SOURCE_DIR
if(${Coverage_BASE_DIRECTORY})
get_filename_component(BASEDIR ${Coverage_BASE_DIRECTORY} ABSOLUTE)
else()
set(BASEDIR ${PROJECT_SOURCE_DIR})
endif()
# Collect excludes (CMake 3.4+: Also compute absolute paths)
set(GCOVR_EXCLUDES "")
foreach(EXCLUDE ${Coverage_EXCLUDE} ${COVERAGE_EXCLUDES} ${COVERAGE_GCOVR_EXCLUDES})
if(CMAKE_VERSION VERSION_GREATER 3.4)
get_filename_component(EXCLUDE ${EXCLUDE} ABSOLUTE BASE_DIR ${BASEDIR})
endif()
list(APPEND GCOVR_EXCLUDES "${EXCLUDE}")
endforeach()
list(REMOVE_DUPLICATES GCOVR_EXCLUDES)
# Combine excludes to several -e arguments
set(GCOVR_EXCLUDE_ARGS "")
foreach(EXCLUDE ${GCOVR_EXCLUDES})
list(APPEND GCOVR_EXCLUDE_ARGS "-e")
list(APPEND GCOVR_EXCLUDE_ARGS "${EXCLUDE}")
endforeach()
add_custom_target(${Coverage_NAME}
# Run tests
${Coverage_EXECUTABLE} ${Coverage_EXECUTABLE_ARGS}
# Create folder
COMMAND ${CMAKE_COMMAND} -E make_directory ${PROJECT_BINARY_DIR}/${Coverage_NAME}
# Running gcovr
COMMAND ${GCOVR_PATH} --html --html-details
-r ${BASEDIR} ${GCOVR_EXCLUDE_ARGS}
--object-directory=${PROJECT_BINARY_DIR}
-o ${Coverage_NAME}/index.html
BYPRODUCTS ${PROJECT_BINARY_DIR}/${Coverage_NAME} # report directory
WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
DEPENDS ${Coverage_DEPENDENCIES}
VERBATIM # Protect arguments to commands
COMMENT "Running gcovr to produce HTML code coverage report."
)
# Show info where to find the report
add_custom_command(TARGET ${Coverage_NAME} POST_BUILD
COMMAND ;
COMMENT "Open ./${Coverage_NAME}/index.html in your browser to view the coverage report."
)
endfunction() # setup_target_for_coverage_gcovr_html
function(append_coverage_compiler_flags)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${COVERAGE_COMPILER_FLAGS}" PARENT_SCOPE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${COVERAGE_COMPILER_FLAGS}" PARENT_SCOPE)
set(CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} ${COVERAGE_COMPILER_FLAGS}" PARENT_SCOPE)
message(STATUS "Appending code coverage compiler flags: ${COVERAGE_COMPILER_FLAGS}")
endfunction() # append_coverage_compiler_flags
07070100000007000081A4000003E800000064000000016140667800000042000000000000000000000000000000000000002800000000libalternatives-v1.2+3.b848aad/config.h#define LIBALTS_VERSION "1.1"
#define LIBALTS_RELEASE_YEAR "2021"
07070100000008000081A4000003E80000006400000001614066780000005A000000000000000000000000000000000000002B00000000libalternatives-v1.2+3.b848aad/config.h.in#define LIBALTS_VERSION "@PROJECT_VERSION@"
#define LIBALTS_RELEASE_YEAR "@PROJECT_YEAR@"
07070100000009000041ED000003E800000064000000016140667800000000000000000000000000000000000000000000002300000000libalternatives-v1.2+3.b848aad/doc0707010000000A000081A4000003E800000064000000016140667800000058000000000000000000000000000000000000003200000000libalternatives-v1.2+3.b848aad/doc/CMakeLists.txtinclude(GNUInstallDirs)
install(FILES alts.1 DESTINATION ${CMAKE_INSTALL_MANDIR}/man1/)
0707010000000B000081A4000003E8000000640000000161406678000004AD000000000000000000000000000000000000002A00000000libalternatives-v1.2+3.b848aad/doc/alts.1'\" -*- coding: UTF-8 -*-
.\" Man page for alts
.\"
.\" Copyright ©2021 SUSE LLC
.\"
.\" You may distribute under the terms of the GNU General Public
.\" License as specified in the COPYING file that comes with the
.\" libalterntaives distribution.
.\"
.pc
.TH ALTS 1 "2021-07-07" "1.0.0" "libalterntaives"
.SH NAME
alts - manages preferred default commands
.SH SYNOPSIS
alts [options]
.SH DESCRIPTION
alts is a defaul program manager and its aim is to provide an alternative to update-alternatives system
without relying on symlinks. Instead of symlinks, it relies on configuration files. This allows for
simple per-system or per-user override of default configuration.
.SH OPTIONS
alts -h --- this help screen
alts -l[name] --- list programs or just one with given name
alts [-u] [-s] -n <program> [-p <alt_priority>]
sets an override with a given priority as default
if priority is not set, then resets to default by removing override
-u -- user override, default for non-root users
-s -- system overrude, default for root users
-n -- program to override with a given priority alternative
.SH SEE ALSO
update-alternatives(1)
.
0707010000000C000081A4000003E800000064000000016140667800000311000000000000000000000000000000000000002E00000000libalternatives-v1.2+3.b848aad/release_tag.sh#!/bin/bash
if test "x$1" = "x-c"; then
# skip if not in git
git rev-list -n 0 HEAD 2>/dev/null || exec true
echo Checking that last tag matches last release
ver=$(grep LIBALTS_VERSION config.h | awk '{print $3}' | sed 's,",,g')
git describe --abbrev=0 --tags | grep -q v$ver || exit 1
echo "All good! Version $ver tag found."
exit 0
fi
if [ "$1" = "-s" ]; then
git status | grep -q 'nothing to commit, working tree clean' || exec echo Pending commits
echo "Tagging new release v$2"
echo $2 | grep '^[0-9]\+\.[0-9]\+$' || exec echo 'Invalid version format'
sed -e "s,@PROJECT_VERSION@,$2," -e "s,@PROJECT_YEAR@,`date +%Y`," config.h.in > config.h
git add config.h &&
git commit -m "Releasing version $2" &&
git tag v$2
exit 0
fi
echo "Unknown options" "$1"
exit 1
0707010000000D000041ED000003E800000064000000016140667800000000000000000000000000000000000000000000002300000000libalternatives-v1.2+3.b848aad/src0707010000000E000081A4000003E800000064000000016140667800000666000000000000000000000000000000000000003200000000libalternatives-v1.2+3.b848aad/src/CMakeLists.txtset(libalternatives_SOURCES
libalternatives.c
options_parser.c
config_parser.c
)
set(libalternatives_PUBLIC_HEADERS
libalternatives.h
)
set(libalternatives_HEADERS
${libalternatives_PUBLIC_HEADERS}
parser.h
)
add_library(alternatives SHARED "${libalternatives_SOURCES}")
set_property(TARGET alternatives PROPERTY SOVERSION 1)
set_property(TARGET alternatives PROPERTY ETC_PATH test)
target_compile_definitions(alternatives PUBLIC
ETC_PATH="/${CMAKE_INSTALL_SYSCONFDIR}"
CONFIG_DIR="${CONFIG_DIR}"
CONFIG_FILENAME="${CONFIG_FILENAME}"
)
set_target_properties(alternatives PROPERTIES C_VISIBILITY_PRESET hidden)
set_target_properties(alternatives PROPERTIES LINK_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/libalternatives.version)
set (CMAKE_SHARED_LINKER_FLAGS ${CMAKE_SHARED_LINKER_FLAGS} "-Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/libalternatives.version")
# disable the <libname>_EXPORTS
#set_target_properties(alternatives PROPERTIES DEFINE_SYMBOL "")
set_property(TARGET alternatives PROPERTY C_STANDARD 99)
if(BUILD_TESTING)
# test library also contains utilities that will be tested
add_library(TestLibalternatives STATIC ${libalternatives_SOURCES})
target_compile_definitions(TestLibalternatives PRIVATE
ETC_PATH="${CMAKE_CURRENT_SOURCE_DIR}/../test"
CONFIG_DIR="${CMAKE_CURRENT_SOURCE_DIR}/../test/test_defaults"
CONFIG_FILENAME="${CONFIG_FILENAME}"
UNITTESTS=1
)
set_property(TARGET TestLibalternatives PROPERTY C_STANDARD 99)
endif()
install(FILES ${libalternatives_PUBLIC_HEADERS} DESTINATION include)
install(TARGETS alternatives)
0707010000000F000081A4000003E8000000640000000161406678000018EC000000000000000000000000000000000000003300000000libalternatives-v1.2+3.b848aad/src/config_parser.c/* libalternatives - update-alternatives alternative
* Copyright (C) 2021 SUSE LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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/>.
*/
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdbool.h>
#include "parser.h"
/*----------------------------------------------------------------------*/
struct ConfigParserState
{
char *binary_name;
u_int32_t priority;
/* The complete buffer which has been initialiazed by the call
* parseConfigData and can be changed by the set/reset calls.
*/
char *complete_content;
};
/*------------------------------static----------------------------------*/
static char *ltrim(char *s)
{
while(isspace(*s)) s++;
return s;
}
static char *rtrim(char *s)
{
char* back = s + strlen(s);
while(isspace(*--back));
*(back+1) = '\0';
return s;
}
static char *trim(char *s)
{
return rtrim(ltrim(s));
}
static bool is_key(const char *buffer, const char *key, int buffer_len)
{
int ret = true;
char *raw_key, *parsed_key = NULL;
raw_key = strndup(buffer,buffer_len);
parsed_key = strdup(trim(raw_key)); /* strip whitespaces */
free(raw_key);
if (strcmp(parsed_key,key) != 0)
ret = false;
free(parsed_key);
return ret;
}
static void free_buffer(char **buffer)
{
free(*buffer);
}
/** @brief Set priority for a binary name in the given state struct.
*
* @param priority Priority which has to be set. The entry will be deleted
if priority is <= 0.
* @param state Reference on an ConfigParserState object in which the
* priority will be set.
* @return Complete string buffer (with other values)
*/
static const char *setBinaryPriority(int priority, struct ConfigParserState *state)
{
char *buf = state->complete_content;
state->complete_content = strdup("");
bool entry_found = false;
char *line;
while ((line = strsep(&buf, "\n")) != NULL) {
const char *equal_pos = strstr(line,"=");
if (equal_pos != NULL)
{
/* check key (binary_name) */
if (is_key(line, state->binary_name, equal_pos-line))
{
if (!entry_found)
{
entry_found = true;
if (priority>0)
{
/* update; entry will be removed if priority <= 0 */
char *content = state->complete_content;
asprintf(&state->complete_content, "%s%s%s=%d", content,
strlen(content) == 0 ? "" : "\n",
state->binary_name, priority);
free(content);
}
}
continue;
}
}
char *content = state->complete_content;
asprintf(&state->complete_content, "%s%s%s", content,
strlen(content) == 0 ? "" : "\n",
line);
free(content);
}
free(buf);
if (!entry_found && priority > 0)
{
/* appending */
char *content = state->complete_content;
asprintf(&state->complete_content, "%s%s%s=%d", content,
strlen(content) == 0 ? "" : "\n",
state->binary_name, priority);
free(content);
}
return state->complete_content;
}
/*----------------------------------------------------------------------*/
struct ConfigParserState* initConfigParser(const char *binary_name)
{
if (binary_name == NULL)
return NULL;
struct ConfigParserState *state = (struct ConfigParserState*)malloc(sizeof(struct ConfigParserState));
state->binary_name = strdup(binary_name);
state->priority = 0;
state->complete_content = strdup("");
return state;
}
int parseConfigData(const char *buffer, struct ConfigParserState *state)
{
/* strsep changes the buffer. So we need a copy of it.*/
char *begin_buf __attribute__ ((__cleanup__(free_buffer))) = strdup(buffer);
char *buf = begin_buf;
free(state->complete_content);
state->complete_content = strdup(buffer);
char *line;
while (state->priority == 0 && (line = strsep(&buf, "\n")) != NULL) {
const char *equal_pos = strstr(line,"=");
if (equal_pos != NULL)
{
/* check key (binary_name) */
if (!is_key(line, state->binary_name, equal_pos-line))
{
continue; /* not the binary key */
}
} else {
/* no "=" found */
continue;
}
/* evaluating priority */
const char *comment_pos = strstr(line,"#"); /* stripping comment */
char *raw_value = NULL;
if (comment_pos == NULL) {
raw_value = strdup(equal_pos+1);
} else {
raw_value = strndup(equal_pos+1,comment_pos-equal_pos-1);
}
char *endptr = NULL;
long int val = strtol(raw_value, &endptr, 10);
if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
|| (errno != 0 && val == 0)
|| (endptr == raw_value) /* No digits were found. */
|| (*trim(endptr) != '\0') /* There is still a rest */
|| val <= 0) {
free(raw_value);
continue;
}
free(raw_value);
state->priority = (int) val;
}
return state->priority;
}
void doneConfigParser(struct ConfigParserState *state)
{
if (state != NULL) {
free(state->binary_name);
free(state->complete_content);
free(state);
}
}
int getConfigPriority(const struct ConfigParserState *state)
{
if (state == NULL)
return -1;
return state->priority;
}
const char *getConfigBinaryName(const struct ConfigParserState *state)
{
if (state == NULL)
return NULL;
return state->binary_name;
}
const char *setBinaryPriorityAndReturnUpdatedConfig(int priority, struct ConfigParserState *state)
{
if (state == NULL || priority <= 0)
return NULL;
state->priority = priority;
return setBinaryPriority(priority, state);
}
const char *resetToDefaultPriorityAndReturnUpdatedConfig(struct ConfigParserState *state)
{
if (state == NULL)
return NULL;
state->priority = 0;
return setBinaryPriority(0, state);
}
07070100000010000081A4000003E800000064000000016140667800003C25000000000000000000000000000000000000003500000000libalternatives-v1.2+3.b848aad/src/libalternatives.c/* libalternatives - update-alternatives alternative
* Copyright (C) 2021 SUSE LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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/>.
*/
//#define _POSIX_C_SOURCE 202000L
#define __USE_MISC 1
#define _GNU_SOURCE 1
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include "libalternatives.h"
#include "parser.h"
#if !defined(ETC_PATH)
#error "ETC_PATH is undefined"
#endif
#if !defined(CONFIG_FILENAME)
#error "CONFIG_FILENAME is undefined"
#endif
#define SYSTEM_OVERRIDE_PATH ETC_PATH "/" CONFIG_FILENAME
#if !defined(CONFIG_DIR)
#error "CONFIG_DIR is undefind"
#endif
const char system_override_path[] = "";
const char user_override_path[] = "";
#ifdef __GNUC__
#define unlikely(x) __builtin_expect(!!(x), 0)
#define PUBLIC_FUNC __attribute__ ((visibility ("default")))
#else
#define unlikely(x) (x)
#define PUBLIC_FUNC
#endif
int libalternatives_debug = 0;
#define IS_DEBUG unlikely(libalternatives_debug)
static char *__config_path = CONFIG_DIR;
static const char* getConfigDirectory()
{
return __config_path;
}
#ifdef UNITTESTS
void setConfigDirectory(const char *config_directory)
{
if (strcmp(__config_path, CONFIG_DIR) != 0)
free(__config_path);
__config_path = strdup(config_directory);
}
#endif
static void checkEnvDebug()
{
const char *debug = secure_getenv("LIBALTERNATIVES_DEBUG");
libalternatives_debug = ( debug != NULL && debug[0] == '1' && debug[1] == '\x00' );
}
static const char *concat_str_safe(const char *str1, int len1, const char *str2, int len2)
{
char *str = malloc(len1 + len2);
strncpy(str, str1, len1);
strncpy(str+len1, str2, len2);
return str;
}
// new_priority = priority from the filesystem
// old_priority = priority from old calls, or 0
// data = additional data
// return => 1 to set new priority, 0 to retain old
typedef int(*PriorityMatchFunction)(int new_priority, int old_priority, void *data);
static int PriorityMatch_highest(int a, int b, __attribute__((unused)) void *unused)
{
return (a > b ? 1 : 0);
}
/*
static int PriorityMatch_highestButSmallerThanSupplied(int a, int b, int max)
{
return (a < max && a > b ? 1 : 0);
}
*/
static int PriorityMatch_getExact(int a, __attribute__((unused)) int b, void *prio)
{
return (a == *(int*)prio ? 1 : 0);
}
static int findAltConfig(const char *binary_name, PriorityMatchFunction priority_match_func, int *prio, void *data)
{
int configdirfd = open(getConfigDirectory(), O_DIRECTORY, O_RDONLY);
if (configdirfd < 0)
return -1;
int binaryconfigdirfd = openat(configdirfd, binary_name, O_DIRECTORY, O_RDONLY);
if (binaryconfigdirfd < 0) {
int saved_error = errno;
close(configdirfd);
errno = saved_error;
return -1;
}
close(configdirfd);
DIR *dir = fdopendir(dup(binaryconfigdirfd));
if (dir == NULL) {
int saved_error = errno;
close(binaryconfigdirfd);
errno = saved_error;
return -1;
}
struct dirent *dirptr;
*prio = 0;
const char *filename = NULL;
errno = 0;
while ((dirptr = readdir(dir)) != NULL) {
if (dirptr->d_name[0] == '.')
continue;
switch (dirptr->d_type) {
case DT_REG:
break;
case DT_UNKNOWN: {
struct stat info;
if (fstatat(binaryconfigdirfd, dirptr->d_name, &info, AT_SYMLINK_NOFOLLOW) < 0) {
int saved_error = errno;
closedir(dir);
errno = saved_error;
return -1;
}
if (S_ISREG(info.st_mode))
break;
}
// fallthrough
default:
continue;
}
int new_prio = atoi(dirptr->d_name);
if (priority_match_func(new_prio, *prio, data) == 1) {
*prio = new_prio;
free((void*)filename);
filename = strdup(dirptr->d_name);
}
}
if (errno != 0) {
int saved_error = errno;
closedir(dir);
errno = saved_error;
free((void*)filename);
return -1;
}
closedir(dir);
if (filename == NULL) {
errno = ENOENT;
return -1;
}
int fd = openat(binaryconfigdirfd, filename, 0, O_RDONLY);
if (fd < 0) {
int saved_error = errno;
free((void*)filename);
close(binaryconfigdirfd);
errno = saved_error;
return -1;
}
free((void*)filename);
close (binaryconfigdirfd);
return fd;
}
static int loadAlternativeForBinary(const char *binary_name, PriorityMatchFunction matcher, int *prio, struct AlternativeLink **alternatives)
{
int data = *prio;
int fd = findAltConfig(binary_name, matcher, prio, &data);
if (fd < 0) {
*alternatives = NULL;
return fd;
}
struct OptionsParserState *state = initOptionsParser();
char buffer[1024];
int ret = 0;
struct stat stat_data;
if (fstat(fd, &stat_data) < 0) {
*alternatives = NULL;
return -1;
}
if (stat_data.st_size > 10240) {
fprintf(stderr, "options file with priority %d is unusually large. Truncating to 10kB", *prio);
stat_data.st_size = 10240;
}
while (ret == 0 && stat_data.st_size > 0) {
ssize_t s = read(fd, buffer, 1024);
if (s > 0) {
ret = parseOptionsData(buffer, s, state);
stat_data.st_size -= s;
}
else if (s == 0) {
fprintf(stderr, "options file with priority %d changed during reading?", *prio);
break;
}
else {
switch (errno) {
case EINTR:
continue;
default:
return -1;
}
}
}
close(fd);
*alternatives = doneOptionsParser(*prio, state);
return ret;
}
PUBLIC_FUNC
int libalts_load_highest_priority_binary_alternatives(const char *binary_name, struct AlternativeLink **alternatives)
{
int prio = 0;
return loadAlternativeForBinary(binary_name, PriorityMatch_highest, &prio, alternatives);
}
PUBLIC_FUNC
int libalts_load_exact_priority_binary_alternatives(const char *binary_name, int prio, struct AlternativeLink **alternatives)
{
return loadAlternativeForBinary(binary_name, PriorityMatch_getExact, &prio, alternatives);
}
static int isDotPseudoDirectory(const char *name)
{
const char null_byte = '\0';
if (name[0] == '.') {
switch (name[1]) {
case '.':
return name[2] == null_byte;
default:
return name[1] == null_byte;
}
}
return 0;
}
PUBLIC_FUNC
int libalts_load_available_binaries(char ***binaries_ptr, size_t *size)
{
errno = 0;
int fd = open(getConfigDirectory(), O_RDONLY | O_DIRECTORY);
if (fd == -1)
return -1;
DIR *dir = fdopendir(fd);
if (dir == NULL)
return -1;
*size = 0;
*binaries_ptr = NULL;
size_t pos = 0;
struct dirent *dirent;
while ((dirent = readdir(dir)) != NULL) {
if (pos >= *size) {
*size = 2 * (*size + 1);
*binaries_ptr = (char**)realloc(*binaries_ptr, sizeof(char*)**size);
}
if (*binaries_ptr == NULL)
return -1;
switch (dirent->d_type) {
case DT_DIR:
break;
case DT_UNKNOWN: {
// fall-back to detect directory via stat
struct stat st;
if (fstatat(fd, dirent->d_name, &st, 0) == -1) {
int saved_err = errno;
closedir(dir);
errno = saved_err;
return -1;
}
if (S_ISDIR(st.st_mode))
break;
}
// fall-through
default:
// skip all non-directories
continue;
}
if (isDotPseudoDirectory(dirent->d_name))
continue;
(*binaries_ptr)[pos++] = strdup(dirent->d_name);
}
closedir(dir);
*size = pos;
return 0;
}
struct collectPrioData
{
int **alts;
size_t *size;
size_t pos;
};
int collectAllPrioritiesInData(int new_prio, __attribute__((unused)) int old_prio, void *data_ptr)
{
struct collectPrioData *data = (struct collectPrioData*)data_ptr;
if (data->pos >= *data->size) {
*data->size += 32;
*data->alts = (int*)realloc(*data->alts, sizeof(int)**data->size);
}
(*data->alts)[data->pos++] = new_prio;
return 1;
}
PUBLIC_FUNC
int libalts_load_binary_priorities(const char *binary_name, int **alts, size_t *size)
{
int ignored;
*size = 0;
*alts = NULL;
struct collectPrioData data = {alts, size, 0};
int fd = findAltConfig(binary_name, collectAllPrioritiesInData, &ignored, &data);
*size = data.pos;
if (fd < 0)
return fd;
close(fd);
return 0;
}
static ssize_t loadConfigData(const char *config_path, char *data, const ssize_t max_config_size)
{
int fd = open(config_path, O_RDONLY | O_NOFOLLOW);
if (fd < 0)
return -1;
struct stat stat_data;
if (fstat(fd, &stat_data) < 0) {
switch (errno) {
case ENOENT:
return 0;
default:
return -1;
}
}
if (stat_data.st_size >= max_config_size) {
fprintf(stderr, "ignoring libalternatives config file: %s. Too large.\n", config_path);
close(fd);
return 0;
}
ssize_t pos = 0;
while (stat_data.st_size != 0) {
ssize_t rs = read(fd, data + pos, stat_data.st_size);
if (rs == 0 && stat_data.st_size > 0) {
fprintf(stderr, "libalternatives config seems to have changed: %s. Trying to parse anyway\n", config_path);
break;
}
else if (rs < 0) {
switch (errno) {
case EINTR:
continue;
default:
return -1;
}
}
else {
stat_data.st_size -= rs;
pos += rs;
}
}
data[pos] = '\x00';
return pos;
}
PUBLIC_FUNC
int libalts_read_binary_configured_priority_from_file(const char *binary_name, const char *config_path)
{
const ssize_t max_config_size = 1 << 10;
char data[max_config_size];
data[0] = '\0';
loadConfigData(config_path, data, max_config_size);
struct ConfigParserState *state = initConfigParser(binary_name);
int prio = parseConfigData(data, state);
doneConfigParser(state);
return prio;
}
static int saveConfigData(const char *config_path, const char *data)
{
const char *saved_path = concat_str_safe(config_path, strlen(config_path), ".new", 5);
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
struct stat st;
const size_t len = strlen(data);
int ret = 0;
int olderr;
size_t pos;
if (stat(config_path, &st) == 0) {
mode = st.st_mode & (S_IRWXO | S_IRWXG | S_IRWXU);
}
int fd = open(saved_path, O_CREAT | O_TRUNC | O_WRONLY, mode);
if (fd < 0) {
ret = -1;
goto ret;
}
pos = 0;
while (pos < len) {
int write_count = write(fd, data+pos, len-pos);
if (write_count > 0) {
pos += write_count;
}
else {
switch (errno) {
case EINTR:
break;
default:
ret = -1;
goto ret;
}
}
}
if (close(fd) == -1 && errno != EINTR) {
ret = -1;
goto ret;
}
ret = rename(saved_path, config_path);
ret:
olderr = errno;
free((void*)saved_path);
errno = olderr;
return ret;
}
PUBLIC_FUNC
int libalts_write_binary_configured_priority_to_file(const char *binary_name, int priority, const char *config_path)
{
const ssize_t max_config_size = 1 << 10;
char data[max_config_size];
data[0] = '\0';
loadConfigData(config_path, data, max_config_size);
struct ConfigParserState *state = initConfigParser(binary_name);
parseConfigData(data, state);
const char *new_data;
if (priority == 0)
new_data = resetToDefaultPriorityAndReturnUpdatedConfig(state);
else
new_data = setBinaryPriorityAndReturnUpdatedConfig(priority, state);
if (new_data == NULL)
return -1;
int ret = saveConfigData(config_path, new_data);
doneConfigParser(state);
return ret;
}
PUBLIC_FUNC
void libalts_free_alternatives_ptr(struct AlternativeLink **links)
{
for (struct AlternativeLink *ptr=*links; ptr != NULL && ptr->type != ALTLINK_EOL; ptr++)
free((void*)ptr->target);
free(*links);
*links = NULL;
}
PUBLIC_FUNC
int libalts_read_configured_priority(const char *binary_name, int *src)
{
// try to load user override
const char *config_path = libalts_get_user_config_path();
int priority = 0;
if (config_path != NULL) {
if (IS_DEBUG)
fprintf(stderr, "Trying to load user override for %s from: %s\n", binary_name, config_path);
priority = libalts_read_binary_configured_priority_from_file(binary_name, config_path);
if (IS_DEBUG)
fprintf(stderr, "user override priority: %d\n", priority);
if (unlikely(src != NULL)) {
if (priority > 0) {
*src = 2;
}
}
}
// if not loaded, try system override
if (priority <= 0) {
priority = libalts_read_binary_configured_priority_from_file(binary_name, SYSTEM_OVERRIDE_PATH);
if (IS_DEBUG)
fprintf(stderr, "system override priority: %d\n", priority);
if (unlikely(src != NULL)) {
if (priority > 0) {
*src = 1;
}
}
}
return priority;
}
PUBLIC_FUNC
const char* libalts_get_system_config_path()
{
return SYSTEM_OVERRIDE_PATH;
}
static const char* __override_path;
PUBLIC_FUNC
const char* libalts_get_user_config_path()
{
if (__override_path == NULL) {
const char *config_home = secure_getenv("XDG_CONFIG_HOME");
if (config_home != NULL) {
const char config_filename[] = "/" CONFIG_FILENAME;
__override_path = concat_str_safe(config_home, strlen(config_home), config_filename, sizeof(config_filename));
}
else {
config_home = secure_getenv("HOME");
const char config_filename[] = "/.config/" CONFIG_FILENAME;
if (config_home != NULL)
__override_path = concat_str_safe(config_home, strlen(config_home), config_filename, sizeof(config_filename));
}
}
return __override_path;
}
// for debugging
void setConfigPath(const char *config_path)
{
if (__override_path)
free((void*)__override_path);
__override_path = NULL;
if (config_path)
__override_path = strdup(config_path);
}
static int loadAlternatives(const char *binary_name, struct AlternativeLink **alts)
{
int priority = libalts_read_configured_priority(binary_name, NULL);
int ret = 0;
if (priority > 0) {
ret = libalts_load_exact_priority_binary_alternatives(binary_name, priority, alts);
if (unlikely(ret != 0)) {
if (IS_DEBUG)
fprintf(stderr, "failed to load override priority %d - reseting to default", priority);
priority = 0;
}
}
if (priority == 0)
ret = libalts_load_highest_priority_binary_alternatives(binary_name, alts);
if (IS_DEBUG)
fprintf(stderr, "loaded alternatives?: %d\n", ret);
return ret;
}
PUBLIC_FUNC
int libalts_exec_default(char *argv[])
{
argv[0]=basename(argv[0]);
struct AlternativeLink *alts;
checkEnvDebug();
loadAlternatives(argv[0], &alts);
if (alts) {
while (alts->type != ALTLINK_EOL) {
if (alts->type == ALTLINK_BINARY) {
if ((alts->options & ALTLINK_OPTIONS_KEEPARGV0) == 0)
argv[0] = (char*)alts->target;
execv(alts->target, argv);
perror("Failed to execute target.");
break;
}
alts++;
}
}
if (IS_DEBUG)
fprintf(stderr, "execDefault() failed with target %s\n", (alts ? alts->target : NULL));
errno = ENOENT;
return -1;
}
PUBLIC_FUNC
char** libalts_get_default_manpages(const char *binary_name)
{
struct AlternativeLink *alts;
checkEnvDebug();
loadAlternatives(binary_name, &alts);
size_t size = 16, pos = 0;
char **manpages = malloc(sizeof(char*)*size);
if (alts) {
struct AlternativeLink *ptr = alts;
while (ptr->type != ALTLINK_EOL && pos < size-1) {
if (ptr->type == ALTLINK_MANPAGE)
manpages[pos++] = strdup(ptr->target);
ptr++;
}
libalts_free_alternatives_ptr(&alts);
}
manpages[pos] = NULL;
return manpages;
}
07070100000011000081A4000003E800000064000000016140667800000ACF000000000000000000000000000000000000003500000000libalternatives-v1.2+3.b848aad/src/libalternatives.h/* libalternatives - update-alternatives alternative
* Copyright (C) 2021 SUSE LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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/>.
*/
#pragma once
#include <sys/types.h>
#ifdef __cplusplus
extern "C" {
#endif
enum AlternativeLinkType
{
ALTLINK_BINARY = 0,
ALTLINK_MANPAGE = 1,
ALTLINK_GROUP = 2,
ALTLINK_EOL = -1
};
enum AlternativeLinkOptions
{
ALTLINK_OPTIONS_NONE = 0,
ALTLINK_OPTIONS_KEEPARGV0 = 1,
};
struct AlternativeLink
{
int priority;
int type;
const char *target;
int options;
};
// loads highest priority alternative
int libalts_load_highest_priority_binary_alternatives(const char *binary_name, struct AlternativeLink **alternatives);
int libalts_load_exact_priority_binary_alternatives(const char *binary_name, int prio, struct AlternativeLink **alternatives);
int libalts_load_available_binaries(char ***binaries, size_t *size);
int libalts_load_binary_priorities(const char *binary_name, int **alts, size_t *size);
// returns config override (priority) from a given config file
// 0 otherwise, or -1 on error
int libalts_read_binary_configured_priority_from_file(const char *binary_name, const char *config_path);
// return 0 on success and -1 on error
int libalts_write_binary_configured_priority_to_file(const char *binary_name, int priority, const char *config_path);
// returns config override (priority) from default config files
// set src => 1 for system, 2 for user
// returns 0 if not overriden or -1 on error
int libalts_read_configured_priority(const char *binary_name, int *src);
// config filenames, they may or may not exist
const char* libalts_get_system_config_path();
const char* libalts_get_user_config_path();
// convenience
void libalts_free_alternatives_ptr(struct AlternativeLink **);
// convenience
int libalts_exec_default(char *argv[]); // binary in argv[0]
// returns a list of manpages followed by a NULL ptr
// returned data should be freed
char** libalts_get_default_manpages(const char *binary_name);
// for unit testing only, remove from library symbols later
#ifdef UNITTESTS
void setConfigDirectory(const char *config_directory);
#endif
#ifdef __cplusplus
}
#endif
07070100000012000081A4000003E8000000640000000161406678000001EA000000000000000000000000000000000000003B00000000libalternatives-v1.2+3.b848aad/src/libalternatives.versionALTS_1 {
global:
libalts_load_highest_priority_binary_alternatives;
libalts_load_exact_priority_binary_alternatives;
libalts_load_available_binaries;
libalts_load_binary_priorities;
libalts_read_binary_configured_priority_from_file;
libalts_write_binary_configured_priority_to_file;
libalts_read_configured_priority;
libalts_get_system_config_path;
libalts_get_user_config_path;
libalts_free_alternatives_ptr;
libalts_exec_default;
libalts_get_default_manpages;
};
07070100000013000081A4000003E800000064000000016140667800003004000000000000000000000000000000000000003400000000libalternatives-v1.2+3.b848aad/src/options_parser.c/* libalternatives - update-alternatives alternative
* Copyright (C) 2021 SUSE LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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/>.
*/
#include <stdlib.h>
#include <memory.h>
#include "libalternatives.h"
#include "parser.h"
#ifndef MIN
#define MIN(a,b) ((a<b)?(a):(b))
#endif
typedef int(*ParserFunction)(const char *data, size_t len, struct OptionsParserState *state);
struct OptionsParserState
{
u_int32_t parser_func_param, parser_func_param2, parser_func_param3;
ParserFunction parser_func;
u_int32_t options;
struct AlternativeLink *parsed_data;
int parsed_data_size;
};
static int isWhitespace(const char c)
{
return c == ' ' || c == '\t';
}
static int isDelimeter(const char c)
{
return c == '=';
}
static int parser_alreadyErrorNoResumePossible(const char *data, size_t len, struct OptionsParserState *state)
{
(void)data;
(void)len;
(void)state;
return -1;
}
static void allocateBuffer(struct AlternativeLink **link, int *size_ptr)
{
int size = *size_ptr;
if (*link == NULL || size < 8)
size += 8;
*link = realloc(*link, sizeof(struct AlternativeLink) * size);
for (int i=*size_ptr; i<size; ++i) {
(*link+i)->type = ALTLINK_EOL;
(*link+i)->target = 0;
}
*size_ptr = size;
}
static int findFirstParsedDataLocation(struct OptionsParserState *state, int type)
{
for (int i=0; i<state->parsed_data_size - 1; ++i) {
struct AlternativeLink *data = state->parsed_data + i;
if (data->type == type)
return i;
if (data->type == ALTLINK_EOL) {
data->type = type;
return i;
}
}
allocateBuffer(&state->parsed_data, &state->parsed_data_size);
return findFirstParsedDataLocation(state, type);
}
static int findFirstFreeDataLocation(struct OptionsParserState *state, int type)
{
int pos = findFirstParsedDataLocation(state, ALTLINK_EOL);
(state->parsed_data+pos)->type = type;
return pos;
}
static int parser_parseValue(const char *data, size_t len, struct OptionsParserState *state);
static int parser_skipOptionalWhitespaceBeforeManpageEntries(const char *data, size_t len, struct OptionsParserState *state)
{
while (len>0) {
if (!isWhitespace(*data)) {
state->parser_func = parser_parseValue;
return state->parser_func(data, len, state);
}
len--;
data++;
}
return 0;
}
static int parser_searchToken(const char *data, size_t len, struct OptionsParserState *state);
static int parser_parseValue(const char *data, size_t len, struct OptionsParserState *state)
{
struct AlternativeLink *link = state->parsed_data + state->parser_func_param;
u_int16_t value_string_pos = state->parser_func_param2 & 0xFFFF;
u_int16_t value_string_size = state->parser_func_param2 >> 16;
const int is_multi_value = state->parser_func_param3 & 0x1;
while (len > 0) {
char c = *data;
char *out = (char*)link->target;
if (value_string_pos >= value_string_size) {
value_string_size += 0x100;
link->target = realloc((void*)link->target, value_string_size);
out = (char*)link->target;
}
switch (c) {
case ',':
if (is_multi_value) {
out[value_string_pos] = '\x00';
while (value_string_pos > 0 && isWhitespace(out[value_string_pos-1])) {
out[--value_string_pos] = '\x00';
}
if (value_string_pos > 0) {
state->parser_func_param = findFirstFreeDataLocation(state, link->type);
state->parser_func_param2 = 0;
}
state->parser_func = parser_skipOptionalWhitespaceBeforeManpageEntries;
return state->parser_func(data+1, len-1, state);
}
out[value_string_pos] = c;
break;
case '\n':
case '\r':
case '\0':
out[value_string_pos] = '\x00';
while (value_string_pos > 0 && isWhitespace(out[value_string_pos-1])) {
out[--value_string_pos] = '\x00';
}
state->parser_func = parser_searchToken;
return state->parser_func(data+1, len-1, state);
default:
out[value_string_pos] = c;
break;
}
data++;
len--;
value_string_pos++;
}
state->parser_func_param2 = value_string_pos | (((u_int32_t)value_string_size) << 16);
return 0;
}
static int parser_parseMultiValue(const char *data, size_t len, struct OptionsParserState *state)
{
state->parser_func_param3 = 1;
state->parser_func = parser_parseValue;
return state->parser_func(data, len, state);
}
struct valid_option_string {
const char *label;
int options;
};
static int parser_parseOptions(const char *data, size_t len, struct OptionsParserState *state);
static int parser_skipWhitespaceBeforeOption(const char *data, size_t len, struct OptionsParserState *state)
{
while (len > 0 && isWhitespace(*data)) {
len--;
data++;
}
if (len == 0)
return 0;
state->parser_func = parser_parseOptions;
return state->parser_func(data, len, state);
}
static int parser_skipWhitespaceBeforeCommaAndOption(const char *data, size_t len, struct OptionsParserState *state)
{
while (len > 0 && isWhitespace(*data)) {
len--;
data++;
}
if (len == 0)
return 0;
if (*data != ',' && *data != '\n')
state->parser_func = parser_alreadyErrorNoResumePossible;
if (*data == ',') {
len--;
data++;
}
state->parser_func = parser_skipWhitespaceBeforeOption;
return state->parser_func(data, len, state);
}
static int parser_asssertOption_KeepArgv0(const char *data, size_t len, struct OptionsParserState *state)
{
if (len == 0)
return 0;
const char token[] = "KeepArgv0";
u_int32_t pos = state->parser_func_param;
u_int32_t max_pos_to_match = MIN(sizeof(token)-1, pos+len);
while (pos < max_pos_to_match && *data == token[pos]) {
pos++;
data++;
len--;
}
if (pos == max_pos_to_match) {
if (pos == sizeof(token)-1) {
state->parser_func = parser_skipWhitespaceBeforeCommaAndOption;
state->options |= ALTLINK_OPTIONS_KEEPARGV0;
}
else
state->parser_func_param = pos;
}
else
state->parser_func = parser_alreadyErrorNoResumePossible;
return state->parser_func(data, len, state);
}
static int parser_parseOptions(const char *data, size_t len, struct OptionsParserState *state)
{
if (len == 0)
return 0;
switch (*data) {
case 'K':
state->parser_func = parser_asssertOption_KeepArgv0;
state->parser_func_param = 1;
break;
case '\n':
case '\r':
state->parser_func = parser_searchToken;
break;
default:
state->parser_func = parser_alreadyErrorNoResumePossible;
break;
}
return state->parser_func(data+1, len-1, state);
}
#define AFTER_OFFSET 1000
enum WhiteSpaceSkipType
{
BINARY_FUNCTION_BEFORE_EQUAL=1,
BINARY_FUNCTION_AFTER_EQUAL=BINARY_FUNCTION_BEFORE_EQUAL+AFTER_OFFSET,
MAN_FUNCTION_BEFORE_EQUAL=2,
MAN_FUNCTION_AFTER_EQUAL=MAN_FUNCTION_BEFORE_EQUAL+AFTER_OFFSET,
GROUP_FUNCTION_BEFORE_EQUAL=3,
GROUP_FUNCTION_AFTER_EQUAL=GROUP_FUNCTION_BEFORE_EQUAL+AFTER_OFFSET,
OPTIONS_FUNCTION_BEFORE_EQUAL=4,
OPTIONS_FUNCTION_AFTER_EQUAL=OPTIONS_FUNCTION_BEFORE_EQUAL+AFTER_OFFSET,
};
static int parser_skipOptionalWhiteSpace(const char *data, size_t len, struct OptionsParserState *state)
{
while (len > 0 && isWhitespace(*data)) {
len--;
data++;
}
if (len == 0)
return 0;
switch (state->parser_func_param) {
case BINARY_FUNCTION_BEFORE_EQUAL:
case MAN_FUNCTION_BEFORE_EQUAL:
case GROUP_FUNCTION_BEFORE_EQUAL:
case OPTIONS_FUNCTION_BEFORE_EQUAL:
if (!isDelimeter(*data)) {
state->parser_func = parser_alreadyErrorNoResumePossible;
break;
}
data++;
len--;
state->parser_func_param = state->parser_func_param + AFTER_OFFSET;
break;
case BINARY_FUNCTION_AFTER_EQUAL:
state->parser_func = parser_parseValue;
state->parser_func_param = findFirstParsedDataLocation(state, ALTLINK_BINARY);
state->parser_func_param2 = 0;
state->parser_func_param3 = 0;
break;
case MAN_FUNCTION_AFTER_EQUAL:
state->parser_func = parser_parseMultiValue;
state->parser_func_param = findFirstParsedDataLocation(state, ALTLINK_MANPAGE);
state->parser_func_param2 = 0;
break;
case GROUP_FUNCTION_AFTER_EQUAL:
state->parser_func = parser_parseMultiValue;
state->parser_func_param = findFirstParsedDataLocation(state, ALTLINK_GROUP);
state->parser_func_param2 = 0;
state->parser_func_param3 = 0;
break;
case OPTIONS_FUNCTION_AFTER_EQUAL:
state->parser_func = parser_skipWhitespaceBeforeOption;
break;
}
return state->parser_func(data, len, state);
}
static int assertTokenMatch(const char *data, size_t len, struct OptionsParserState *state, const char *match, int match_len, int whiteSpace_param)
{
int pos = state->parser_func_param;
int end_pos = match_len - pos + 1 <= (int)len ? match_len - pos + 1 : (int)len + pos;
while (pos < end_pos && *data == match[pos]) {
data++;
pos++;
len--;
}
if (pos != end_pos) {
state->parser_func = parser_alreadyErrorNoResumePossible;
return -1;
}
if (len == 0 && pos < match_len) {
state->parser_func_param = pos;
return 0;
}
state->parser_func = parser_skipOptionalWhiteSpace;
state->parser_func_param = whiteSpace_param;
return state->parser_func(data, len, state);
}
static int parser_assertBinaryToken(const char *data, size_t len, struct OptionsParserState *state)
{
const char match[] = "binary";
return assertTokenMatch(data, len, state, match, sizeof(match)-1, BINARY_FUNCTION_BEFORE_EQUAL);
}
static int parser_assertManpageToken(const char *data, size_t len, struct OptionsParserState *state)
{
const char match[] = "man";
return assertTokenMatch(data, len, state, match, sizeof(match)-1, MAN_FUNCTION_BEFORE_EQUAL);
}
static int parser_assertGroupToken(const char *data, size_t len, struct OptionsParserState *state)
{
const char match[] = "group";
return assertTokenMatch(data, len, state, match, sizeof(match)-1, GROUP_FUNCTION_BEFORE_EQUAL);
}
static int parser_assertOptionsToken(const char *data, size_t len, struct OptionsParserState *state)
{
const char match[] = "options";
return assertTokenMatch(data, len, state, match, sizeof(match)-1, OPTIONS_FUNCTION_BEFORE_EQUAL);
}
static int parser_searchToken(const char *data, size_t len, struct OptionsParserState *state)
{
while (len > 0 && (isWhitespace(*data) || *data == '\n' || *data == '\r')) {
data++;
len--;
}
if (len == 0)
return 0;
switch (data[0]) {
case 'b':
state->parser_func_param = 1;
state->parser_func = parser_assertBinaryToken;
break;
case 'g':
state->parser_func_param = 1;
state->parser_func = parser_assertGroupToken;
break;
case 'm':
state->parser_func_param = 1;
state->parser_func = parser_assertManpageToken;
break;
case 'o':
state->parser_func_param = 1;
state->parser_func = parser_assertOptionsToken;
break;
default:
state->parser_func = parser_alreadyErrorNoResumePossible;
};
return state->parser_func(data+1, len-1, state);
}
struct OptionsParserState* initOptionsParser()
{
struct OptionsParserState *state = malloc(sizeof(struct OptionsParserState));
state->parser_func = parser_searchToken;
state->parser_func_param = 0;
state->parsed_data = NULL;
state->parsed_data_size = 0;
state->options = 0;
return state;
}
int parseOptionsData(const char *buffer, size_t len, struct OptionsParserState *state)
{
return state->parser_func(buffer, len, state);
}
struct AlternativeLink* doneOptionsParser(int priority, struct OptionsParserState *state)
{
int errors = 0;
while (state->parser_func != parser_searchToken && (errors = state->parser_func("\n", 1, state)) == 0);
if (errors != 0) {
free(state->parsed_data);
free(state);
return NULL;
}
struct AlternativeLink *parsed_data = state->parsed_data;
for (struct AlternativeLink *ptr = parsed_data; ptr && ptr->type != ALTLINK_EOL; ptr++) {
ptr->priority = priority;
ptr->options = state->options;
}
free(state);
return parsed_data;
}
07070100000014000081A4000003E800000064000000016140667800001447000000000000000000000000000000000000002C00000000libalternatives-v1.2+3.b848aad/src/parser.h/* libalternatives - update-alternatives alternative
* Copyright (C) 2021 SUSE LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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/>.
*/
extern int libalternatives_debug;
struct AlternativeLink;
struct OptionsParserState;
/* options_parser.c
* parsing priority options installed on the system
*
* format:
* binary = /some/path
* man = some_manpage.1
*
* space is optional and ignored. Fail on unexpected input.
*/
struct OptionsParserState* initOptionsParser();
// parses some input, can be partial
// return 0 on OK, -1 on fail
int parseOptionsData(const char *buffer, size_t len, struct OptionsParserState *state);
// Frees parsing state. returns array of links from the options, end with ALTLINK_EOL type
// entry. NULL on error.
struct AlternativeLink* doneOptionsParser(int priority, struct OptionsParserState *state);
/* config_parser.c
* Parsing user override config files which is located in
* /etc/libalternatives.conf or $HOME/.config/libalternatives.conf
*
* format:
* binary_name=<priority>
*
* where
* binary_name is passed exactly in the init function.
* <priority> is a base-10 number followed by a \n.
* Comments starts with #.
*
* Space is optional and ignored.
* Lines that do not match this syntax are to be treated as comments and
* ignored.
*/
struct ConfigParserState;
/*
// parses some input, can be partial
// returns
// "priority" when match found and is parsed, 0 otherwise
// on further input, returns already matched priority above and ignores
// input as comments
int parseConfigData(const char *buffer, size_t len, struct ConfigParserState *state);
// frees any memory allocated by parser
void doneConfigParser(struct ConfigParserState *state);
// set or resets priority (clears config entry) for the binary_name
// assumes the entire config is already parsed by parseCondifData()
// return NULL if state is freed (eg. by the doneConfigParser
// function)
const char* setBinaryPriorityAndReturnUpdatedConfig(int priority, struct ConfigParserState *state);
const char* resetToDefaultPriorityAndReturnUpdatedConfig(struct ConfigParserState *state);
*/
/** @brief Initialize an ConfigParserState object with a given binary name.
*
* @param binary_name Binary name (group name).
* @return Pointer of an allocated ConfigParserState object or NULL if
* binary_name is NULL.
*/
struct ConfigParserState* initConfigParser(const char *binary_name);
/** @brief Parsing a string for the FIRST entry <binary_name>=<priority>.
*
* @param buffer String which has to be parsed.
* @param state Reference on an ConfigParserState object with which binary_name
* has been defined. The priority and line number will be stored
* there too if an entry has been found.
* @return Priority for the given binary name or 0 it it has not been found.
*/
int parseConfigData(const char *buffer, struct ConfigParserState *state);
/** @brief Frees any memory allocated by parser.
*
* @param state Reference on an ConfigParserState object which will be freed.
*/
void doneConfigParser(struct ConfigParserState *state);
/** @brief Set priority for a binary name in the given state struct.
*
* @param priority Priority which has to be set.
* @param state Reference on an ConfigParserState object in which the
* priority will be set.
* @return Complete string buffer (with other values), changed value included.
* NULL if state has been NULL or the priority has been <= 0.
*/
const char* setBinaryPriorityAndReturnUpdatedConfig(int priority, struct ConfigParserState *state);
/** @brief Set default priority for a binary name in the given state struct.
*
* @param state Reference on an ConfigParserState object in which the
* priority will be set.
* @return Complete string buffer (with other values).
* NULL if state has been NULL.
* The key/value defined in state has been removed.
*/
const char* resetToDefaultPriorityAndReturnUpdatedConfig(struct ConfigParserState *state);
/** @brief Get priority for a binary name in the given state struct.
*
* @param state Reference on an ConfigParserState object in which the
* priority is set.
* @return priority
*/
int getConfigPriority(const struct ConfigParserState *state);
/** @brief Get binary name of the given state struct.
*
* @param state Reference on an ConfigParserState object in which the
* binary name is set.
* @return binary name
*/
const char *getConfigBinaryName(const struct ConfigParserState *state);
07070100000015000041ED000003E800000064000000016140667800000000000000000000000000000000000000000000002400000000libalternatives-v1.2+3.b848aad/test07070100000016000081A4000003E8000000640000000161406678000001FF000000000000000000000000000000000000003300000000libalternatives-v1.2+3.b848aad/test/CMakeLists.txtset(test_SOURCES
alternatives_tests.c
config_parser_tests.c
options_parser_tests.c
test.c
)
if(BUILD_TESTING)
add_executable(units ${test_SOURCES})
target_link_libraries(units PRIVATE cunit)
target_link_libraries(units PRIVATE TestAlternativeHelper TestLibalternatives)
target_compile_definitions(units PUBLIC CONFIG_DIR="${CMAKE_CURRENT_SOURCE_DIR}/test_defaults")
add_executable(argv_replaced_helper argv_replaced_helper.c)
add_test(NAME unit COMMAND units)
endif()
07070100000017000081A4000003E800000064000000016140667800003932000000000000000000000000000000000000003900000000libalternatives-v1.2+3.b848aad/test/alternatives_tests.c/* libalternatives - update-alternatives alternative
* Copyright (C) 2021 SUSE LLC
*
* 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/>.
*/
#define _POSIX_C_SOURCE 200809L
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
#include <CUnit/CUnit.h>
#include "../src/libalternatives.h"
extern int alternative_app_main(int argc, char *argv[]);
static int saved_io[3];
static char stdout_buffer[10240];
static char stderr_buffer[10240];
static int start_error_count;
static int wrapCall(int argc, char *argv[])
{
int stdout_fd = open("test.stdout", O_CREAT | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR);
int stderr_fd = open("test.stderr", O_CREAT | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR);
for (int i=0; i<3; i++)
saved_io[i] = dup(i);
fflush(stdout);
fflush(stderr);
close(0);
close(1);
close(2);
dup2(stdout_fd, STDOUT_FILENO);
dup2(stderr_fd, STDERR_FILENO);
int ret = alternative_app_main(argc, argv);
fflush(stdout);
fflush(stderr);
for (int i=0; i<3; i++)
dup2(saved_io[i], i);
lseek(stdout_fd, 0, SEEK_SET);
lseek(stderr_fd, 0, SEEK_SET);
int pos = read(stdout_fd, stdout_buffer, 10240-1);
stdout_buffer[pos>0?pos:0] = '\x00';
pos = read(stderr_fd, stderr_buffer, 10240-1);
stderr_buffer[pos>0?pos:0] = '\x00';
return ret;
}
extern void setConfigPath(const char *config_path);
static int setupTests()
{
const char fn[] = "/libalternatives_local.conf";
const char *wd = get_current_dir_name();
char *full_path = (char*)malloc(strlen(wd) + sizeof(fn)); // includes trailing NULL
strcpy(full_path, wd);
strcat(full_path, fn);
setConfigPath(full_path);
free((void*)wd);
free(full_path);
unlink(libalts_get_user_config_path());
unlink(libalts_get_system_config_path());
return 0;
}
static int cleanupTests()
{
if (CU_get_number_of_failures() == 0) {
unlink(libalts_get_user_config_path());
unlink(libalts_get_system_config_path());
}
unlink("test.stdout");
unlink("test.stderr");
return 0;
}
static void storeErrorCount()
{
start_error_count = CU_get_number_of_failures();
}
static void printOutputOnErrorIncrease()
{
int new_err_count = CU_get_number_of_failures();
if (start_error_count < new_err_count) {
puts("************** TEST OUTPUT ***************");
printf("stdout: '%s'\n", stdout_buffer);
printf("stderr: '%s'\n", stderr_buffer);
}
}
#define WRAP_CALL(a) wrapCall(sizeof(a)/sizeof(char*), a)
void helpScreenWithoutParameters()
{
char *args[] = {"app"};
CU_ASSERT_EQUAL(WRAP_CALL(args), -1);
CU_ASSERT_PTR_NOT_NULL(strstr(stdout_buffer, "this help screen"));
}
void helpScreen()
{
char *args[] = {"app", "-h"};
CU_ASSERT_EQUAL(WRAP_CALL(args), 0);
CU_ASSERT_PTR_NOT_NULL(strstr(stdout_buffer, "this help screen"));
}
void unknownParamsHelpScreen()
{
char *args[] = {"app", "-8", "nothing to see here"};
CU_ASSERT_EQUAL(WRAP_CALL(args), -1);
CU_ASSERT_PTR_NOT_NULL(strstr(stdout_buffer, "this help screen"));
}
void moreThanOneCommand()
{
char *args[] = {"app", "-h", "-a"};
CU_ASSERT_EQUAL(WRAP_CALL(args), -1);
CU_ASSERT_PTR_NOT_NULL(strstr(stdout_buffer, "this help screen"));
}
void listAllAvailablePrograms()
{
char *args[] = {"app", "-l"};
CU_ASSERT_EQUAL(WRAP_CALL(args), 0);
CU_ASSERT_STRING_EQUAL(stdout_buffer,
"Binary: multiple_alts\n\
Alternatives: 3\n\
Priority: 10 Target: /usr/bin/node10\n\
Priority: 20 Target: /usr/bin/node20\n\
Priority: 30* Target: /usr/bin/node30\n\
---\n\
Binary: no_size_alternatives\n\
Alternatives: 0\n\
---\n\
Binary: one_alternative\n\
Alternatives: 1\n\
Priority: 90* Target: /usr/bin/ls\n\
---\n\
Binary: test\n\
Alternatives: 2\n\
Priority: 10 Target: /usr/bin/false\n\
Priority: 20* Target: /usr/bin/true\n\
");
}
void listSpecificProgram()
{
char *args[] = {"app", "-l", "multiple_alts"};
CU_ASSERT_EQUAL(WRAP_CALL(args), 0);
CU_ASSERT_STRING_EQUAL(stdout_buffer,
"Binary: multiple_alts\n\
Alternatives: 3\n\
Priority: 10 Target: /usr/bin/node10\n\
Priority: 20 Target: /usr/bin/node20\n\
Priority: 30* Target: /usr/bin/node30\n\
");
}
void adjustPriorityForSpecificProgram()
{
const char binary_name[] = "multiple_alts";
char *args_read[] = {"app", "-l", (char*)binary_name};
char *args_set[] = {"app", "-u", "-n", (char*)binary_name, "-p", "20"};
char *args_set_system[] = {"app", "-s", "-n", (char*)binary_name, "-p", "10"};
char *args_reset[] = {"app", "-u", "-n", (char*)binary_name};
char *args_reset_system[] = {"app", "-s", "-n", (char*)binary_name};
int src;
CU_ASSERT_EQUAL(WRAP_CALL(args_read), 0);
CU_ASSERT_STRING_EQUAL(stdout_buffer,
"Binary: multiple_alts\n\
Alternatives: 3\n\
Priority: 10 Target: /usr/bin/node10\n\
Priority: 20 Target: /usr/bin/node20\n\
Priority: 30* Target: /usr/bin/node30\n\
");
CU_ASSERT_EQUAL(libalts_read_configured_priority(binary_name, &src), 0);
CU_ASSERT_EQUAL(WRAP_CALL(args_set), 0);
CU_ASSERT_EQUAL(stdout_buffer[0], '\0');
CU_ASSERT_EQUAL(WRAP_CALL(args_read), 0);
CU_ASSERT_STRING_EQUAL(stdout_buffer,
"Binary: multiple_alts\n\
Alternatives: 3\n\
Priority: 10 Target: /usr/bin/node10\n\
Priority: 20~ Target: /usr/bin/node20\n\
Priority: 30 Target: /usr/bin/node30\n\
");
CU_ASSERT_EQUAL(libalts_read_configured_priority(binary_name, &src), 20);
CU_ASSERT_EQUAL(src, 2);
CU_ASSERT_EQUAL(WRAP_CALL(args_set_system), 0);
CU_ASSERT_EQUAL(stdout_buffer[0], '\0');
CU_ASSERT_EQUAL(WRAP_CALL(args_read), 0);
CU_ASSERT_STRING_EQUAL(stdout_buffer,
"Binary: multiple_alts\n\
Alternatives: 3\n\
Priority: 10 Target: /usr/bin/node10\n\
Priority: 20~ Target: /usr/bin/node20\n\
Priority: 30 Target: /usr/bin/node30\n\
");
CU_ASSERT_EQUAL(libalts_read_configured_priority(binary_name, &src), 20);
CU_ASSERT_EQUAL(src, 2);
CU_ASSERT_EQUAL(WRAP_CALL(args_reset), 0);
CU_ASSERT_EQUAL(stdout_buffer[0], '\0');
CU_ASSERT_EQUAL(WRAP_CALL(args_read), 0);
CU_ASSERT_STRING_EQUAL(stdout_buffer,
"Binary: multiple_alts\n\
Alternatives: 3\n\
Priority: 10! Target: /usr/bin/node10\n\
Priority: 20 Target: /usr/bin/node20\n\
Priority: 30 Target: /usr/bin/node30\n\
");
CU_ASSERT_EQUAL(libalts_read_configured_priority(binary_name, &src), 10);
CU_ASSERT_EQUAL(src, 1);
CU_ASSERT_EQUAL(WRAP_CALL(args_reset_system), 0);
CU_ASSERT_EQUAL(stdout_buffer[0], '\0');
CU_ASSERT_EQUAL(WRAP_CALL(args_read), 0);
CU_ASSERT_STRING_EQUAL(stdout_buffer,
"Binary: multiple_alts\n\
Alternatives: 3\n\
Priority: 10 Target: /usr/bin/node10\n\
Priority: 20 Target: /usr/bin/node20\n\
Priority: 30* Target: /usr/bin/node30\n\
");
CU_ASSERT_EQUAL(libalts_read_configured_priority(binary_name, &src), 0);
}
extern void setConfigDirectory(const char *);
static int setupGroupTests()
{
setConfigDirectory(CONFIG_DIR "/../test_groups");
return setupTests();
}
static int restoreGroupTestsAndRemoveIOFiles()
{
setConfigDirectory(CONFIG_DIR);
return cleanupTests();
}
static void listSpecificProgramInAGroup()
{
char *args[] = {"app", "-l", "node"};
CU_ASSERT_EQUAL(WRAP_CALL(args), 0);
CU_ASSERT_STRING_EQUAL(stdout_buffer,
"Binary: node\n\
Alternatives: 3\n\
Priority: 10 Target: /usr/bin/node10\n\
Group: node, npm\n\
Priority: 20 Target: /usr/bin/node20\n\
Group: node, npm\n\
Priority: 30* Target: /usr/bin/node30\n\
Group: node, npm\n\
");
}
static void showErrorsForInconsistentGroups()
{
char *args[] = {"app", "-l", "node_bad"};
CU_ASSERT_EQUAL(WRAP_CALL(args), 1);
CU_ASSERT_STRING_EQUAL(stdout_buffer,
"Binary: node_bad\n\
Alternatives: 3\n\
Priority: 10 Target: /usr/bin/node10\n\
Group: node_bad, npm\n\
Priority: 20 Target: /usr/bin/node20\n\
Group: npm\n\
WARNING: binary not part of the Group\n\
WARNING: shadows more complete Group with lower priority\n\
Priority: 30* Target: /usr/bin/node30\n\
WARNING: shadows more complete Group with lower priority\n\
");
}
static void setPrioritiesAffectEntireGroup()
{
char *args_set[] = {"app", "-u", "-n", "node", "-p", "10"};
char *args_reset[] = {"app", "-u", "-n", "node"};
char *args_set_system[] = {"app", "-s", "-n", "node", "-p", "10"};
char *args_reset_system[] = {"app", "-s", "-n", "node"};
char *args_status[] = {"app", "-l", "npm"};
CU_ASSERT_EQUAL(WRAP_CALL(args_status), 0);
CU_ASSERT_STRING_EQUAL(stdout_buffer,
"Binary: npm\n\
Alternatives: 3\n\
Priority: 10 Target: /usr/bin/npm10\n\
Group: node, npm\n\
Priority: 20 Target: /usr/bin/npm20\n\
Group: node, npm\n\
Priority: 30* Target: /usr/bin/npm30\n\
Group: node, npm\n\
");
char **manpages = libalts_get_default_manpages("npm");
CU_ASSERT_STRING_EQUAL(manpages[0], "npm30.1");
CU_ASSERT_EQUAL(manpages[1], NULL);
free(manpages[0]);
free(manpages);
CU_ASSERT_EQUAL(WRAP_CALL(args_set), 0);
CU_ASSERT_EQUAL(WRAP_CALL(args_status), 0);
CU_ASSERT_STRING_EQUAL(stdout_buffer,
"Binary: npm\n\
Alternatives: 3\n\
Priority: 10~ Target: /usr/bin/npm10\n\
Group: node, npm\n\
Priority: 20 Target: /usr/bin/npm20\n\
Group: node, npm\n\
Priority: 30 Target: /usr/bin/npm30\n\
Group: node, npm\n\
");
manpages = libalts_get_default_manpages("npm");
CU_ASSERT_STRING_EQUAL(manpages[0], "npm10.1");
CU_ASSERT_EQUAL(manpages[1], NULL);
free(manpages[0]);
free(manpages);
CU_ASSERT_EQUAL(WRAP_CALL(args_set_system), 0);
CU_ASSERT_EQUAL(WRAP_CALL(args_status), 0);
CU_ASSERT_STRING_EQUAL(stdout_buffer,
"Binary: npm\n\
Alternatives: 3\n\
Priority: 10~ Target: /usr/bin/npm10\n\
Group: node, npm\n\
Priority: 20 Target: /usr/bin/npm20\n\
Group: node, npm\n\
Priority: 30 Target: /usr/bin/npm30\n\
Group: node, npm\n\
");
CU_ASSERT_EQUAL(WRAP_CALL(args_reset), 0);
CU_ASSERT_EQUAL(WRAP_CALL(args_status), 0);
CU_ASSERT_STRING_EQUAL(stdout_buffer,
"Binary: npm\n\
Alternatives: 3\n\
Priority: 10! Target: /usr/bin/npm10\n\
Group: node, npm\n\
Priority: 20 Target: /usr/bin/npm20\n\
Group: node, npm\n\
Priority: 30 Target: /usr/bin/npm30\n\
Group: node, npm\n\
");
manpages = libalts_get_default_manpages("npm");
CU_ASSERT_STRING_EQUAL(manpages[0], "npm10.1");
CU_ASSERT_EQUAL(manpages[1], NULL);
free(manpages[0]);
free(manpages);
CU_ASSERT_EQUAL(WRAP_CALL(args_reset_system), 0);
CU_ASSERT_EQUAL(WRAP_CALL(args_status), 0);
CU_ASSERT_STRING_EQUAL(stdout_buffer,
"Binary: npm\n\
Alternatives: 3\n\
Priority: 10 Target: /usr/bin/npm10\n\
Group: node, npm\n\
Priority: 20 Target: /usr/bin/npm20\n\
Group: node, npm\n\
Priority: 30* Target: /usr/bin/npm30\n\
Group: node, npm\n\
");
manpages = libalts_get_default_manpages("npm");
CU_ASSERT_STRING_EQUAL(manpages[0], "npm30.1");
CU_ASSERT_EQUAL(manpages[1], NULL);
free(manpages[0]);
free(manpages);
}
static int setupExecTests()
{
setConfigDirectory(CONFIG_DIR "/../test_exec");
//setenv("LIBALTERNATIVES_DEBUG", "1", 1);
return setupTests();
}
static int cleanupExecTests()
{
setConfigDirectory(CONFIG_DIR);
//unsetenv("LIBALTERNATIVES_DEBUG");
return cleanupTests();
}
static void failedExecOfUnknown()
{
char *command_not_found[] = { "/usr/some/something_not_there", "-param", NULL };
CU_ASSERT_EQUAL(libalts_exec_default(command_not_found), -1);
CU_ASSERT_EQUAL(errno, ENOENT);
}
static void validExecCommand()
{
char *command_false[] = { "/usr/path/test42", NULL };
pid_t child_pid = fork();
int status = 1000;
switch (child_pid) {
case -1:
CU_ASSERT_FATAL(-1);
return;
case 0:
libalts_exec_default(command_false);
exit(100);
default:
CU_ASSERT_EQUAL_FATAL(wait(&status), child_pid);
CU_ASSERT(WIFEXITED(status));
CU_ASSERT_EQUAL(WEXITSTATUS(status), 1);
}
}
static void validExecCommandKeepArgv0()
{
char *command_keep_argv[] = { "/usr/path/area47", "area47", NULL };
pid_t child_pid = fork();
int status = 1000;
switch (child_pid) {
case -1:
CU_ASSERT_FATAL(-1);
return;
case 0:
libalts_exec_default(command_keep_argv);
exit(100);
default:
CU_ASSERT_EQUAL_FATAL(wait(&status), child_pid);
CU_ASSERT(WIFEXITED(status));
CU_ASSERT_EQUAL(WEXITSTATUS(status), 0);
}
}
static void validExecCommandReplacedArgv0()
{
char *command_replace_argv[] = { "/usr/path/area48", "argv_replaced_helper", NULL };
pid_t child_pid = fork();
int status = 1000;
switch (child_pid) {
case -1:
CU_ASSERT_FATAL(-1);
return;
case 0:
libalts_exec_default(command_replace_argv);
exit(100);
default:
CU_ASSERT_EQUAL_FATAL(wait(&status), child_pid);
CU_ASSERT(WIFEXITED(status));
CU_ASSERT_EQUAL(WEXITSTATUS(status), 0);
}
}
void addAlternativesAppTests()
{
CU_pSuite suite = CU_add_suite_with_setup_and_teardown("Alternative App Tests", setupTests, cleanupTests, storeErrorCount, printOutputOnErrorIncrease);
CU_ADD_TEST(suite, helpScreen);
CU_ADD_TEST(suite, unknownParamsHelpScreen);
CU_ADD_TEST(suite, moreThanOneCommand);
CU_ADD_TEST(suite, helpScreenWithoutParameters);
CU_ADD_TEST(suite, listAllAvailablePrograms);
CU_ADD_TEST(suite, listSpecificProgram);
CU_ADD_TEST(suite, adjustPriorityForSpecificProgram);
suite = CU_add_suite_with_setup_and_teardown("Alternative App with Groups Tests", setupGroupTests, restoreGroupTestsAndRemoveIOFiles, storeErrorCount, printOutputOnErrorIncrease);
CU_ADD_TEST(suite, listSpecificProgramInAGroup);
CU_ADD_TEST(suite, showErrorsForInconsistentGroups);
CU_ADD_TEST(suite, setPrioritiesAffectEntireGroup);
suite = CU_add_suite_with_setup_and_teardown("Default Exec Tests", setupExecTests, cleanupExecTests, storeErrorCount, printOutputOnErrorIncrease);
CU_ADD_TEST(suite, failedExecOfUnknown);
CU_ADD_TEST(suite, validExecCommand);
CU_ADD_TEST(suite, validExecCommandKeepArgv0);
CU_ADD_TEST(suite, validExecCommandReplacedArgv0);
}
07070100000018000081A4000003E800000064000000016140667800000102000000000000000000000000000000000000003B00000000libalternatives-v1.2+3.b848aad/test/argv_replaced_helper.c#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
int len0 = strlen(argv[0]);
int len1 = argc < 2 ? 0 : strlen(argv[1]);
if (argv[1] != NULL && strcmp(argv[0]+len0-len1, argv[1]) == 0)
return 0;
return 42;
}
07070100000019000081A4000003E800000064000000016140667800002956000000000000000000000000000000000000003A00000000libalternatives-v1.2+3.b848aad/test/config_parser_tests.c/* libalternatives - update-alternatives alternative
* Copyright (C) 2021 SUSE LLC
*
* 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/>.
*/
#include <stdlib.h>
#include <CUnit/CUnit.h>
#include "../src/parser.h"
static int noop_function()
{
return 0;
}
static struct ConfigParserState *state;
static void resultsWithoutParsing()
{
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
doneConfigParser(state);
}
static void resultsWithoutParsingNULLBinary()
{
CU_ASSERT_PTR_NULL(state = initConfigParser(NULL));
doneConfigParser(state);
}
static void parsingEmptyData()
{
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData("", state), 0);
doneConfigParser(state);
}
static void parseEmptyDataAndAddSingleEntry()
{
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData("", state), 0);
CU_ASSERT_EQUAL(strcmp(setBinaryPriorityAndReturnUpdatedConfig(20, state), "editor=20"), 0)
doneConfigParser(state);
}
static void parsingSimpleEntry()
{
const char simple_entry[] = "editor=10";
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData(simple_entry, state),10);
doneConfigParser(state);
}
static void parsingGarbageData1()
{
const char data[] = "nothing to see here";
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData(data, state), 0);
doneConfigParser(state);
}
static void parsingGarbageData2()
{
const char simple_entry[] = "editor=10 foo";
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData(simple_entry, state),0);
doneConfigParser(state);
}
static void parsingGarbageData3()
{
const char simple_entry[] = "editor foo=10";
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData(simple_entry, state),0);
doneConfigParser(state);
}
static void parsingFalseEntry()
{
const char simple_entry[] = "foo=10";
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData(simple_entry, state),0);
doneConfigParser(state);
}
static void parsingWithOtherEntries()
{
const char entries[] = "line1 \n line 2 \neditor=5\n line 3";
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData(entries, state),5);
doneConfigParser(state);
}
static void parsingWithWhitespaces1()
{
const char entries[] = "\n\n editor = 50 \n \n";
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData(entries, state),50);
doneConfigParser(state);
}
static void parsingWithWhitespaces2()
{
const char entries[] = "\n\n \t editor\t =\t 56 \t \n";
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData(entries, state),56);
doneConfigParser(state);
}
static void parsingWithComment()
{
const char entries[] = "editor = 57 #this is a comment \n";
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData(entries, state),57);
doneConfigParser(state);
}
static void parsingNoneDigitalValue()
{
const char entries[] = "editor=123foo";
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData(entries, state),0);
doneConfigParser(state);
}
static void duplicateUseFirstEntry()
{
const char entries[] = "\n\n editor=5 \n editor=10 \n";
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData(entries, state),5);
doneConfigParser(state);
}
static void similarBinaries()
{
const char editor_with_space[] = "my editor=10\neditor=11\n";
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData(editor_with_space, state), 11);
}
static void invalidNegativePriority()
{
const char editor_with_space[] = "editor=-10\neditor=11\n";
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData(editor_with_space, state), 11);
}
static void setEntryInTheMiddle()
{
const char entries[] = "line1 \n line 2 \neditor=5\n line 3";
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData(entries, state),5);
const char *buffer = setBinaryPriorityAndReturnUpdatedConfig(22,state);
CU_ASSERT_EQUAL(strcmp(buffer, "line1 \n line 2 \neditor=22\n line 3"), 0);
CU_ASSERT_EQUAL(getConfigPriority(state), 22);
doneConfigParser(state);
}
static void setEntryAtTheEnd()
{
const char entries[] = "line1 \n line 2 \n line 3\neditor=5";
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData(entries, state),5);
const char *buffer = setBinaryPriorityAndReturnUpdatedConfig(333,state);
CU_ASSERT_EQUAL(strcmp(buffer, "line1 \n line 2 \n line 3\neditor=333"), 0);
CU_ASSERT_EQUAL(getConfigPriority(state), 333);
doneConfigParser(state);
}
static void setEntryAtTheBeginning()
{
const char entries[] = "editor=555\n line 2 \n line 3\n";
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData(entries, state),555);
const char *buffer = setBinaryPriorityAndReturnUpdatedConfig(4,state);
CU_ASSERT_EQUAL(strcmp(buffer, "editor=4\n line 2 \n line 3\n"), 0);
CU_ASSERT_EQUAL(getConfigPriority(state), 4);
doneConfigParser(state);
}
static void setNewEntry()
{
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
const char *buffer = setBinaryPriorityAndReturnUpdatedConfig(4,state);
CU_ASSERT_EQUAL(strcmp(buffer, "editor=4"), 0);
CU_ASSERT_EQUAL(getConfigPriority(state), 4);
doneConfigParser(state);
}
static void setEntryRemoveDoubleEntry1()
{
const char entries[] = "line1 \n line 2 \neditor=5\n line 3\neditor=7";
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData(entries, state),5);
const char *buffer = setBinaryPriorityAndReturnUpdatedConfig(22,state);
CU_ASSERT_EQUAL(strcmp(buffer, "line1 \n line 2 \neditor=22\n line 3"), 0);
CU_ASSERT_EQUAL(getConfigPriority(state), 22);
doneConfigParser(state);
}
static void setEntryRemoveDoubleEntry2()
{
const char entries[] = "line1 \neditor=2\n line 2 \neditor=5\n line 3";
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData(entries, state),2);
const char *buffer = setBinaryPriorityAndReturnUpdatedConfig(22,state);
CU_ASSERT_EQUAL(strcmp(buffer, "line1 \neditor=22\n line 2 \n line 3"), 0);
CU_ASSERT_EQUAL(getConfigPriority(state), 22);
doneConfigParser(state);
}
static void setWithEmptyArguments()
{
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_PTR_NULL(setBinaryPriorityAndReturnUpdatedConfig(0,state));
CU_ASSERT_PTR_NULL(setBinaryPriorityAndReturnUpdatedConfig(1,NULL));
}
static void resetEntries()
{
const char entries[] = "editor=5\nline1 \n line 2 \neditor=5\n line 3\neditor=6";
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData(entries, state),5);
const char *buffer = resetToDefaultPriorityAndReturnUpdatedConfig(state);
CU_ASSERT_EQUAL(strcmp(buffer, "line1 \n line 2 \n line 3"), 0);
CU_ASSERT_EQUAL(getConfigPriority(state), 0);
doneConfigParser(state);
}
static void setPriorityMultipleTimes()
{
const char entries[] = "editor=5\nline1 \n line 2 \neditor=5\n line 3\neditor=6";
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData(entries, state),5);
const char *b1 = setBinaryPriorityAndReturnUpdatedConfig(10, state);
CU_ASSERT_EQUAL(strcmp(b1, "editor=10\nline1 \n line 2 \n line 3"), 0);
const char *buffer = resetToDefaultPriorityAndReturnUpdatedConfig(state);
CU_ASSERT_EQUAL(strcmp(buffer, "line1 \n line 2 \n line 3"), 0);
CU_ASSERT_EQUAL(getConfigPriority(state), 0);
// CU_ASSERT_EQUAL(strcmp(b1, "editor=10\nline1 \n line 2 \n line 3"), 0);
doneConfigParser(state);
}
static void resetNULLEntry()
{
CU_ASSERT_PTR_NULL(resetToDefaultPriorityAndReturnUpdatedConfig(NULL));
}
static void resetNonExistentEntryShouldNotAddNewEntry()
{
const char entries[] = "";
CU_ASSERT_PTR_NOT_NULL(state = initConfigParser("editor"));
CU_ASSERT_EQUAL(parseConfigData(entries, state),0);
const char *buffer = resetToDefaultPriorityAndReturnUpdatedConfig(state);
CU_ASSERT_STRING_EQUAL(buffer, "");
doneConfigParser(state);
}
void addConfigParserTests()
{
CU_pSuite tests = CU_add_suite_with_setup_and_teardown("ConfigParser",
noop_function,
noop_function,
(void(*)(void))noop_function,
(void(*)(void))noop_function);
CU_ADD_TEST(tests, resultsWithoutParsing);
CU_ADD_TEST(tests, resultsWithoutParsingNULLBinary);
CU_ADD_TEST(tests, parsingEmptyData);
CU_ADD_TEST(tests, parsingGarbageData1);
CU_ADD_TEST(tests, parsingGarbageData2);
CU_ADD_TEST(tests, parsingGarbageData3);
CU_ADD_TEST(tests, parsingSimpleEntry);
CU_ADD_TEST(tests, parsingFalseEntry);
CU_ADD_TEST(tests, parsingWithOtherEntries);
CU_ADD_TEST(tests, parsingWithWhitespaces1);
CU_ADD_TEST(tests, parsingWithWhitespaces2);
CU_ADD_TEST(tests, parsingNoneDigitalValue);
CU_ADD_TEST(tests, duplicateUseFirstEntry);
CU_ADD_TEST(tests, parsingWithComment);
CU_ADD_TEST(tests, similarBinaries);
CU_ADD_TEST(tests, invalidNegativePriority);
CU_ADD_TEST(tests, setEntryInTheMiddle);
CU_ADD_TEST(tests, setEntryAtTheEnd);
CU_ADD_TEST(tests, setEntryAtTheBeginning);
CU_ADD_TEST(tests, setNewEntry);
CU_ADD_TEST(tests, setEntryRemoveDoubleEntry1);
CU_ADD_TEST(tests, setEntryRemoveDoubleEntry2);
CU_ADD_TEST(tests, setWithEmptyArguments);
CU_ADD_TEST(tests, resetEntries);
CU_ADD_TEST(tests, setPriorityMultipleTimes);
CU_ADD_TEST(tests, resetNULLEntry);
CU_ADD_TEST(tests, parseEmptyDataAndAddSingleEntry);
CU_ADD_TEST(tests, resetNonExistentEntryShouldNotAddNewEntry);
}
0707010000001A000081A4000003E8000000640000000161406678000025B9000000000000000000000000000000000000003B00000000libalternatives-v1.2+3.b848aad/test/options_parser_tests.c/* libalternatives - update-alternatives alternative
* Copyright (C) 2021 SUSE LLC
*
* 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/>.
*/
#include <stdlib.h>
#include <CUnit/CUnit.h>
#include "../src/libalternatives.h"
#include "../src/parser.h"
static int noop_function()
{
return 0;
}
static struct OptionsParserState *state;
static struct AlternativeLink *result = NULL;
static void freeResults()
{
for (struct AlternativeLink *link=result; link != NULL && link->type != ALTLINK_EOL; link++)
free((void*)link->target);
free(result);
result = NULL;
}
static void resultsWithoutParsing()
{
CU_ASSERT_PTR_NOT_NULL(state = initOptionsParser());
CU_ASSERT_PTR_NULL(doneOptionsParser(0, state));
}
static void parsingEmptyData()
{
CU_ASSERT_PTR_NOT_NULL(state = initOptionsParser());
CU_ASSERT_EQUAL(parseOptionsData("", 0, state), 0);
CU_ASSERT_PTR_NULL(doneOptionsParser(0, state));
}
static void parsingGarbageData()
{
const char data[] = "nothing to see here";
CU_ASSERT_PTR_NOT_NULL(state = initOptionsParser());
CU_ASSERT_EQUAL(parseOptionsData(data, sizeof(data)-1, state), -1);
CU_ASSERT_PTR_NULL(doneOptionsParser(0, state));
}
static void parsingSimpleEntry()
{
const char simple_entry[] = "binary=/usr/bin/vim";
CU_ASSERT_PTR_NOT_NULL(state = initOptionsParser());
CU_ASSERT_EQUAL(parseOptionsData(simple_entry, sizeof(simple_entry)-1, state), 0);
CU_ASSERT_PTR_NOT_NULL_FATAL(result = doneOptionsParser(10, state));
CU_ASSERT_EQUAL(result->type, ALTLINK_BINARY);
CU_ASSERT_STRING_EQUAL(result->target, "/usr/bin/vim");
CU_ASSERT_EQUAL(result->priority, 10);
CU_ASSERT_EQUAL(result->options, 0);
}
static void parsingSimpleWithManpage()
{
const char simple_entry[] = "binary=/usr/bin/vim\nman=vim.123";
CU_ASSERT_PTR_NOT_NULL(state = initOptionsParser());
CU_ASSERT_EQUAL(parseOptionsData(simple_entry, sizeof(simple_entry)-1, state), 0);
CU_ASSERT_PTR_NOT_NULL_FATAL(result = doneOptionsParser(10, state));
CU_ASSERT_EQUAL(result->type, ALTLINK_BINARY);
CU_ASSERT_STRING_EQUAL(result->target, "/usr/bin/vim");
CU_ASSERT_EQUAL(result->priority, 10);
CU_ASSERT_EQUAL(result[1].type, ALTLINK_MANPAGE);
CU_ASSERT_STRING_EQUAL(result[1].target,"vim.123");
CU_ASSERT_EQUAL(result[1].priority, 10);
}
static void parsingSimpleWithManpageOneBytePerCall()
{
const char simple_entry[] = "binary=/usr/bin/vim\nman=vim.123";
CU_ASSERT_PTR_NOT_NULL(state = initOptionsParser());
for (unsigned i=0; i<sizeof(simple_entry); ++i) {
CU_ASSERT_EQUAL(parseOptionsData(simple_entry+i, 1, state), 0);
}
CU_ASSERT_PTR_NOT_NULL_FATAL(result = doneOptionsParser(10, state));
CU_ASSERT_EQUAL(result->type, ALTLINK_BINARY);
CU_ASSERT_STRING_EQUAL(result->target, "/usr/bin/vim");
CU_ASSERT_EQUAL(result->priority, 10);
CU_ASSERT_EQUAL(result[1].type, ALTLINK_MANPAGE);
CU_ASSERT_STRING_EQUAL(result[1].target,"vim.123");
CU_ASSERT_EQUAL(result[1].priority, 10);
}
static void duplicateBinariesUseLatestEntryOnly()
{
const char data[] = "binary=/usr/bin/vim\nbinary=/usr/bin/emacs";
CU_ASSERT_PTR_NOT_NULL(state = initOptionsParser());
CU_ASSERT_EQUAL(parseOptionsData(data, sizeof(data)-1, state), 0);
CU_ASSERT_PTR_NOT_NULL_FATAL(result = doneOptionsParser(10, state));
CU_ASSERT_EQUAL(result->type, ALTLINK_BINARY);
CU_ASSERT_STRING_EQUAL(result->target, "/usr/bin/emacs");
CU_ASSERT_EQUAL(result->priority, 10);
}
static void truncateWhitespaceFromEntries()
{
const char data[] = " man = \t man.123 \n \t \n\t\n binary = /usr/bin/em \tacs\t\t \t";
CU_ASSERT_PTR_NOT_NULL(state = initOptionsParser());
CU_ASSERT_EQUAL(parseOptionsData(data, sizeof(data)-1, state), 0);
CU_ASSERT_PTR_NOT_NULL_FATAL(result = doneOptionsParser(10, state));
CU_ASSERT_EQUAL(result[0].type, ALTLINK_MANPAGE);
CU_ASSERT_STRING_EQUAL(result[0].target, "man.123");
CU_ASSERT_EQUAL(result[0].priority, 10);
CU_ASSERT_EQUAL(result[1].type, ALTLINK_BINARY);
CU_ASSERT_STRING_EQUAL(result[1].target, "/usr/bin/em \tacs");
CU_ASSERT_EQUAL(result[1].priority, 10);
}
static void noDelimeterAfterValidToken()
{
const char data[] = "binary /usr/bin/emacs";
CU_ASSERT_PTR_NOT_NULL(state = initOptionsParser());
CU_ASSERT_EQUAL(parseOptionsData(data, sizeof(data)-1, state), -1);
CU_ASSERT_PTR_NULL(doneOptionsParser(10, state));
}
static void invalidToken()
{
const char data[] = "binaries = /usr/bin/emacs";
CU_ASSERT_PTR_NOT_NULL(state = initOptionsParser());
CU_ASSERT_EQUAL(parseOptionsData(data, sizeof(data)-1, state), -1);
CU_ASSERT_PTR_NULL(doneOptionsParser(10, state));
}
static void noResumeFromError()
{
const char data[] = "bbinary = /usr/bin/ls";
CU_ASSERT_PTR_NOT_NULL(state = initOptionsParser());
CU_ASSERT_EQUAL(parseOptionsData(data, 2, state), -1);
CU_ASSERT_EQUAL(parseOptionsData(data+2, sizeof(data)-1-2, state), -1);
CU_ASSERT_PTR_NULL(doneOptionsParser(10, state));
const char data2[] = "~binary = /usr/bin/ls";
CU_ASSERT_PTR_NOT_NULL(state = initOptionsParser());
CU_ASSERT_EQUAL(parseOptionsData(data2, sizeof(data2)-1, state), -1);
CU_ASSERT_EQUAL(parseOptionsData(data2+1, sizeof(data2)-1-1, state), -1);
CU_ASSERT_PTR_NULL(doneOptionsParser(10, state));
const char data3[] = "binary != /usr/bin/ls";
CU_ASSERT_PTR_NOT_NULL(state = initOptionsParser());
CU_ASSERT_EQUAL(parseOptionsData(data3, 8, state), -1);
CU_ASSERT_EQUAL(parseOptionsData(data3+8, sizeof(data3)-1-8, state), -1);
CU_ASSERT_PTR_NULL(doneOptionsParser(10, state));
}
static void parsingMultipleManpages()
{
const char data[] = "binary=/usr/bin/ls\nman=foo.1, \t bar.5n,, , omega.8section ";
CU_ASSERT_PTR_NOT_NULL(state = initOptionsParser());
CU_ASSERT_EQUAL(parseOptionsData(data, sizeof(data), state), 0);
CU_ASSERT_PTR_NOT_NULL(result = doneOptionsParser(10, state));
CU_ASSERT_EQUAL(result[0].type, ALTLINK_BINARY);
CU_ASSERT_EQUAL(result[1].type, ALTLINK_MANPAGE);
CU_ASSERT_EQUAL(result[2].type, ALTLINK_MANPAGE);
CU_ASSERT_EQUAL(result[3].type, ALTLINK_MANPAGE);
CU_ASSERT_EQUAL(result[4].type, ALTLINK_EOL);
CU_ASSERT_STRING_EQUAL(result[0].target, "/usr/bin/ls");
CU_ASSERT_STRING_EQUAL(result[1].target, "foo.1");
CU_ASSERT_STRING_EQUAL(result[2].target, "bar.5n");
CU_ASSERT_STRING_EQUAL(result[3].target, "omega.8section");
}
static void parsesSingleGroup()
{
const char data[] = "binary=/usr/bin/ls\ngroup=foobar";
CU_ASSERT_PTR_NOT_NULL(state = initOptionsParser());
CU_ASSERT_EQUAL(parseOptionsData(data, sizeof(data), state), 0);
CU_ASSERT_PTR_NOT_NULL(result = doneOptionsParser(10, state));
CU_ASSERT_EQUAL(result[0].type, ALTLINK_BINARY);
CU_ASSERT_EQUAL(result[1].type, ALTLINK_GROUP);
CU_ASSERT_EQUAL(result[2].type, ALTLINK_EOL);
CU_ASSERT_STRING_EQUAL(result[1].target, "foobar");
CU_ASSERT_EQUAL(result[1].options, ALTLINK_OPTIONS_NONE);
}
static void parsesMultipleGroupsAsLatestGroupList()
{
const char data[] = "binary=/usr/bin/ls\ngroup=foobar\ngroup=bar,foo";
CU_ASSERT_PTR_NOT_NULL(state = initOptionsParser());
CU_ASSERT_EQUAL(parseOptionsData(data, sizeof(data), state), 0);
CU_ASSERT_PTR_NOT_NULL(result = doneOptionsParser(10, state));
CU_ASSERT_EQUAL(result[0].type, ALTLINK_BINARY);
CU_ASSERT_EQUAL(result[1].type, ALTLINK_GROUP);
CU_ASSERT_EQUAL(result[2].type, ALTLINK_GROUP);
CU_ASSERT_EQUAL(result[3].type, ALTLINK_EOL);
CU_ASSERT_STRING_EQUAL(result[1].target, "bar");
CU_ASSERT_STRING_EQUAL(result[2].target, "foo");
}
static void parseWithBadOptions()
{
const char data[] = "binary=/usr/bin/ls\noptions=BadOptions";
CU_ASSERT_PTR_NOT_NULL(state = initOptionsParser());
CU_ASSERT_EQUAL(parseOptionsData(data, sizeof(data)-1, state), -1);
CU_ASSERT_PTR_NULL(result = doneOptionsParser(10, state));
}
static void parseWithGoodOptions()
{
const char data[] = "binary=/usr/bin/ls\noptions= KeepArgv0 , KeepArgv0, ";
CU_ASSERT_PTR_NOT_NULL(state = initOptionsParser());
for (unsigned i=0; i<sizeof(data)-1; i++)
CU_ASSERT_EQUAL(parseOptionsData(data+i, 1, state), 0);
CU_ASSERT_PTR_NOT_NULL(result = doneOptionsParser(10, state));
CU_ASSERT_EQUAL(result->options, ALTLINK_OPTIONS_KEEPARGV0);
}
void addOptionsParserTests()
{
CU_pSuite tests = CU_add_suite_with_setup_and_teardown("parser",
noop_function, noop_function,
(void(*)(void))noop_function, freeResults);
CU_ADD_TEST(tests, resultsWithoutParsing);
CU_ADD_TEST(tests, parsingEmptyData);
CU_ADD_TEST(tests, parsingGarbageData);
CU_ADD_TEST(tests, parsingSimpleEntry);
CU_ADD_TEST(tests, parsingSimpleWithManpage);
CU_ADD_TEST(tests, parsingSimpleWithManpageOneBytePerCall);
CU_ADD_TEST(tests, duplicateBinariesUseLatestEntryOnly);
CU_ADD_TEST(tests, truncateWhitespaceFromEntries);
CU_ADD_TEST(tests, noDelimeterAfterValidToken);
CU_ADD_TEST(tests, invalidToken);
CU_ADD_TEST(tests, noResumeFromError);
CU_ADD_TEST(tests, parsingMultipleManpages);
CU_ADD_TEST(tests, parsesSingleGroup);
CU_ADD_TEST(tests, parsesMultipleGroupsAsLatestGroupList);
CU_ADD_TEST(tests, parseWithBadOptions);
CU_ADD_TEST(tests, parseWithGoodOptions);
}
0707010000001B000081A4000003E800000064000000016140667800000CD5000000000000000000000000000000000000002B00000000libalternatives-v1.2+3.b848aad/test/test.c/* libalternatives - update-alternatives alternative
* Copyright (C) 2021 SUSE LLC
*
* 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/>.
*/
#define _GNU_SOURCE
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <CUnit/CUnit.h>
#include <CUnit/Basic.h>
#include <unistd.h>
#include "../src/libalternatives.h"
static int suite_init()
{
return 0;
}
static int suite_cleanup()
{
return 0;
}
static void free_null()
{
struct AlternativeLink *data = NULL;
libalts_free_alternatives_ptr(&data);
CU_ASSERT_PTR_NULL(data);
}
static void invalid_binary()
{
int ret;
struct AlternativeLink *data = NULL;
ret = libalts_load_highest_priority_binary_alternatives("not_real_binary_binary", &data);
CU_ASSERT_EQUAL(ret, -1);
CU_ASSERT_EQUAL(errno, ENOENT);
CU_ASSERT_PTR_NULL(data);
ret = libalts_load_highest_priority_binary_alternatives("no_size_alternatives", &data);
CU_ASSERT_EQUAL(ret, -1);
CU_ASSERT_PTR_NULL(data);
}
static void single_alternative_binary()
{
size_t ret;
struct AlternativeLink *data;
ret = libalts_load_highest_priority_binary_alternatives("one_alternative", &data);
CU_ASSERT_EQUAL(ret, 0);
CU_ASSERT_PTR_NOT_NULL(data);
CU_ASSERT_EQUAL(data->priority, 90);
CU_ASSERT_STRING_EQUAL(data->target, "/usr/bin/ls");
CU_ASSERT_EQUAL(data->type, ALTLINK_BINARY);
CU_ASSERT_EQUAL(data[1].type, ALTLINK_EOL);
libalts_free_alternatives_ptr(&data);
CU_ASSERT_PTR_NULL(data);
}
static void multiple_alternative_binary()
{
size_t ret;
struct AlternativeLink *data;
ret = libalts_load_highest_priority_binary_alternatives("multiple_alts", &data);
CU_ASSERT_EQUAL(ret, 0);
CU_ASSERT_PTR_NOT_NULL(data);
CU_ASSERT_EQUAL(data->priority, 30);
CU_ASSERT_STRING_EQUAL(data->target, "/usr/bin/node30");
CU_ASSERT_EQUAL(data->type, ALTLINK_BINARY);
CU_ASSERT_EQUAL(data[1].type, ALTLINK_EOL);
libalts_free_alternatives_ptr(&data);
CU_ASSERT_PTR_NULL(data);
}
extern void addOptionsParserTests();
extern void addConfigParserTests();
extern void addAlternativesAppTests();
int main()
{
mkdir(CONFIG_DIR "/no_size_alternatives", 0777);
chdir(CONFIG_DIR "/../..");
printf("cwd: %s\n", get_current_dir_name());
CU_initialize_registry();
CU_pSuite suite = CU_add_suite("libalternatives test suite", suite_init, suite_cleanup);
CU_ADD_TEST(suite, free_null);
CU_ADD_TEST(suite, invalid_binary);
CU_ADD_TEST(suite, single_alternative_binary);
CU_ADD_TEST(suite, multiple_alternative_binary);
addOptionsParserTests();
addConfigParserTests();
addAlternativesAppTests();
CU_basic_run_tests();
int failed_tests = CU_get_number_of_tests_failed();
CU_cleanup_registry();
return failed_tests != 0;
}
0707010000001C000041ED000003E800000064000000016140667800000000000000000000000000000000000000000000003200000000libalternatives-v1.2+3.b848aad/test/test_defaults0707010000001D000041ED000003E800000064000000016140667800000000000000000000000000000000000000000000004000000000libalternatives-v1.2+3.b848aad/test/test_defaults/multiple_alts0707010000001E000081A4000003E800000064000000016140667800000024000000000000000000000000000000000000004800000000libalternatives-v1.2+3.b848aad/test/test_defaults/multiple_alts/10.confbinary=/usr/bin/node10
man=node10.1
0707010000001F000081A4000003E800000064000000016140667800000023000000000000000000000000000000000000004800000000libalternatives-v1.2+3.b848aad/test/test_defaults/multiple_alts/20.confbinary=/usr/bin/node20
man=node20.107070100000020000081A4000003E800000064000000016140667800000016000000000000000000000000000000000000004800000000libalternatives-v1.2+3.b848aad/test/test_defaults/multiple_alts/30.confbinary=/usr/bin/node3007070100000021000041ED000003E800000064000000016140667800000000000000000000000000000000000000000000004200000000libalternatives-v1.2+3.b848aad/test/test_defaults/one_alternative07070100000022000081A4000003E800000064000000016140667800000013000000000000000000000000000000000000004A00000000libalternatives-v1.2+3.b848aad/test/test_defaults/one_alternative/90.confbinary=/usr/bin/ls
07070100000023000041ED000003E800000064000000016140667800000000000000000000000000000000000000000000003700000000libalternatives-v1.2+3.b848aad/test/test_defaults/test07070100000024000081A4000003E800000064000000016140667800000022000000000000000000000000000000000000003F00000000libalternatives-v1.2+3.b848aad/test/test_defaults/test/10.confbinary=/usr/bin/false
man=false.1
07070100000025000081A4000003E80000006400000001614066780000001F000000000000000000000000000000000000003F00000000libalternatives-v1.2+3.b848aad/test/test_defaults/test/20.confbinary=/usr/bin/true
man=true.107070100000026000041ED000003E800000064000000016140667800000000000000000000000000000000000000000000002E00000000libalternatives-v1.2+3.b848aad/test/test_exec07070100000027000041ED000003E800000064000000016140667800000000000000000000000000000000000000000000003500000000libalternatives-v1.2+3.b848aad/test/test_exec/area4707070100000028000081A4000003E800000064000000016140667800000043000000000000000000000000000000000000003D00000000libalternatives-v1.2+3.b848aad/test/test_exec/area47/10.confman=test
binary=./build/test/argv_replaced_helper
options=KeepArgv007070100000029000041ED000003E800000064000000016140667800000000000000000000000000000000000000000000003500000000libalternatives-v1.2+3.b848aad/test/test_exec/area480707010000002A000081A4000003E80000006400000001614066780000003A000000000000000000000000000000000000003D00000000libalternatives-v1.2+3.b848aad/test/test_exec/area48/10.confman=test
binary=./build/test/argv_replaced_helper
options=0707010000002B000041ED000003E800000064000000016140667800000000000000000000000000000000000000000000003500000000libalternatives-v1.2+3.b848aad/test/test_exec/test420707010000002C000081A4000003E80000006400000001614066780000001E000000000000000000000000000000000000003D00000000libalternatives-v1.2+3.b848aad/test/test_exec/test42/10.confman=test
binary=/usr/bin/false0707010000002D000081A4000003E800000064000000016140667800000024000000000000000000000000000000000000003C00000000libalternatives-v1.2+3.b848aad/test/test_exec/test42/8.confbinary=/usr/bin/true
man=testing man0707010000002E000041ED000003E800000064000000016140667800000000000000000000000000000000000000000000003000000000libalternatives-v1.2+3.b848aad/test/test_groups0707010000002F000041ED000003E800000064000000016140667800000000000000000000000000000000000000000000003500000000libalternatives-v1.2+3.b848aad/test/test_groups/node07070100000030000081A4000003E800000064000000016140667800000033000000000000000000000000000000000000003D00000000libalternatives-v1.2+3.b848aad/test/test_groups/node/10.confbinary=/usr/bin/node10
man=node10.1
group=node,npm
07070100000031000081A4000003E800000064000000016140667800000033000000000000000000000000000000000000003D00000000libalternatives-v1.2+3.b848aad/test/test_groups/node/20.confbinary=/usr/bin/node20
man=node20.1
group=npm,node
07070100000032000081A4000003E800000064000000016140667800000032000000000000000000000000000000000000003D00000000libalternatives-v1.2+3.b848aad/test/test_groups/node/30.confbinary=/usr/bin/node30
man=node30.1
group=node,npm07070100000033000041ED000003E800000064000000016140667800000000000000000000000000000000000000000000003900000000libalternatives-v1.2+3.b848aad/test/test_groups/node_bad07070100000034000081A4000003E800000064000000016140667800000037000000000000000000000000000000000000004100000000libalternatives-v1.2+3.b848aad/test/test_groups/node_bad/10.confbinary=/usr/bin/node10
man=node10.1
group=node_bad,npm
07070100000035000081A4000003E80000006400000001614066780000002E000000000000000000000000000000000000004100000000libalternatives-v1.2+3.b848aad/test/test_groups/node_bad/20.confbinary=/usr/bin/node20
man=node20.1
group=npm
07070100000036000081A4000003E800000064000000016140667800000023000000000000000000000000000000000000004100000000libalternatives-v1.2+3.b848aad/test/test_groups/node_bad/30.confbinary=/usr/bin/node30
man=node30.107070100000037000041ED000003E800000064000000016140667800000000000000000000000000000000000000000000003400000000libalternatives-v1.2+3.b848aad/test/test_groups/npm07070100000038000081A4000003E800000064000000016140667800000030000000000000000000000000000000000000003C00000000libalternatives-v1.2+3.b848aad/test/test_groups/npm/10.confbinary=/usr/bin/npm10
man=npm10.1
group=node,npm07070100000039000081A4000003E800000064000000016140667800000030000000000000000000000000000000000000003C00000000libalternatives-v1.2+3.b848aad/test/test_groups/npm/20.confbinary=/usr/bin/npm20
man=npm20.1
group=node,npm0707010000003A000081A4000003E800000064000000016140667800000031000000000000000000000000000000000000003C00000000libalternatives-v1.2+3.b848aad/test/test_groups/npm/30.confbinary=/usr/bin/npm30
man=npm30.1
group=node,npm
0707010000003B000041ED000003E800000064000000016140667800000000000000000000000000000000000000000000002500000000libalternatives-v1.2+3.b848aad/utils0707010000003C000081A4000003E80000006400000001614066780000032E000000000000000000000000000000000000003400000000libalternatives-v1.2+3.b848aad/utils/CMakeLists.txtset(alts_SOURCES
alternatives.c
group_consistency_rules.c
list_binaries.c
)
set(alts_HEADERS
utils.h
)
add_executable(AlternativesHelper
${alts_SOURCES}
)
target_link_libraries(AlternativesHelper PRIVATE alternatives)
set_property(TARGET AlternativesHelper PROPERTY SKIP_BUILD_RPATH TRUE)
set_target_properties(AlternativesHelper PROPERTIES OUTPUT_NAME alts)
if(BUILD_TESTING)
add_library(TestAlternativeHelper STATIC ${alts_SOURCES})
target_compile_definitions(TestAlternativeHelper PRIVATE
ETC_PATH="${CMAKE_CURRENT_SOURCE_DIR}/../test"
CONFIG_DIR="${CMAKE_CURRENT_SOURCE_DIR}/../test/test_defaults"
CONFIG_FILENAME="${CONFIG_FILENAME}"
UNITTESTS=1
)
set_property(TARGET TestAlternativeHelper PROPERTY C_STANDARD 99)
endif()
install(TARGETS AlternativesHelper)
0707010000003D000081A4000003E80000006400000001614066780000142C000000000000000000000000000000000000003400000000libalternatives-v1.2+3.b848aad/utils/alternatives.c/* libalternatives - update-alternatives alternative
* Copyright (C) 2021 SUSE LLC
*
* 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/>.
*/
#define _GNU_SOURCE
#include <errno.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include "../src/libalternatives.h"
#include "../config.h"
const char binname[] = "alts";
extern int printInstalledBinariesAndTheirOverrideStates(const char *program);
static int setProgramOverride(const char *program, int priority, int is_system, int is_user)
{
if (!is_user && !is_system) {
if (geteuid() == 0)
is_system = 1;
else
is_user = 1;
}
if (is_system && is_user) {
fprintf(stderr, "Trying to override both system and user priorities. Decide on one.\n");
return -1;
}
const char *config_fn = (is_user ? libalts_get_user_config_path() : libalts_get_system_config_path());
struct AlternativeLink *alts = NULL;
int group_priority = priority;
if (group_priority == 0) {
group_priority = libalts_read_binary_configured_priority_from_file(program, config_fn);
if (group_priority < 0) {
fprintf(stderr, "Failed to load current state from the config file for binary: %s\n", program);
return -1;
}
}
if (group_priority > 0 && libalts_load_exact_priority_binary_alternatives(program, group_priority, &alts) != 0) {
fprintf(stderr, "Failed to load config file for binary: %s\n", program);
return -1;
}
int ret = libalts_write_binary_configured_priority_to_file(program, priority, config_fn);
if (ret < 0) {
perror(config_fn);
fprintf(stderr, "Error updating override file\n");
return -1;
}
if (group_priority > 0) {
for (const struct AlternativeLink *p = alts; p->type != ALTLINK_EOL; p++) {
if (p->type == ALTLINK_GROUP) {
if (libalts_write_binary_configured_priority_to_file(p->target, priority, config_fn) < 0) {
perror(config_fn);
fprintf(stderr, "Error updating override file for group member: %s (orig binary: %s)\n", p->target, program);
ret = -2;
}
}
}
}
libalts_free_alternatives_ptr(&alts);
return ret;
}
static void printHelp()
{
puts(
"\n\n"
" libalternatives (C) " LIBALTS_RELEASE_YEAR " SUSE LLC\n"
"\n"
" alts -h --- this help screen\n"
" alts -l[name] --- list programs or just one with given name\n"
" alts [-u] [-s] -n <program> [-p <alt_priority>]\n"
" sets an override with a given priority as default\n"
" if priority is not set, then resets to default by removing override\n"
" -u -- user override, default for non-root users\n"
" -s -- system overrude, default for root users\n"
" -n -- program to override with a given priority alternative\n"
"\n\n"
);
}
static void setFirstCommandOrError(int *command, int new_command)
{
if (*command == 0)
*command = new_command;
else
*command = -1;
}
static int processOptions(int argc, char *argv[])
{
int opt;
int command = 0;
const char *program = NULL;
int priority = 0;
int is_system = 0, is_user = 0;
optind = 1; // reset since we call this multiple times in unit tests
while ((opt = getopt(argc, argv, ":hn:p:l::us")) != -1) {
switch(opt) {
case 'h':
case 'r':
setFirstCommandOrError(&command, opt);
break;
case 'u':
is_user = 1;
break;
case 's':
is_system = 1;
break;
case 'l':
case 'n':
setFirstCommandOrError(&command, opt);
program = optarg;
if (!optarg && optind < argc && argv[optind] != NULL && argv[optind][0] != '-') {
program = argv[optind++];
}
break;
case 'p': {
char *ptr;
errno = 0;
priority = strtol(optarg, &ptr, 10);
if (errno != 0 || *ptr != '\x00') {
command = -1;
}
break;
}
default:
fprintf(stderr, "unexpected return from getopt: %d\n", opt);
setFirstCommandOrError(&command, opt);
}
}
switch (command) {
case 'h':
printHelp();
break;
case '?':
case -1:
case 0:
printHelp();
return -1;
case 'l':
return printInstalledBinariesAndTheirOverrideStates(program);
case 'n':
return setProgramOverride(program, priority, is_system, is_user);
default:
printf("unimplemented command %c %d\n", command, (int)command);
return 10;
}
return 0;
}
#ifdef UNITTESTS
int alternative_app_main(int argc, char *argv[])
{
#else
int main(int argc, char *argv[])
{
if (strcmp(binname, basename(argv[0])) != 0)
return libalts_exec_default(argv);
#endif
return processOptions(argc, argv);
}
0707010000003E000081A4000003E800000064000000016140667800000C5C000000000000000000000000000000000000003F00000000libalternatives-v1.2+3.b848aad/utils/group_consistency_rules.c/* libalternatives - update-alternatives alternative
* Copyright (C) 2021 SUSE LLC
*
* 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/>.
*/
#define _GNU_SOURCE
#include <errno.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include "utils.h"
static unsigned numBinariesInGroup(struct AlternativeLink *data)
{
unsigned size = 0;
for (; data->type != ALTLINK_EOL; data++)
if (data->type == ALTLINK_GROUP)
size++;
return size;
}
static int isBinaryInGroupOfBinariesOrWithoutGroup(const char *binary_name, struct AlternativeLink *data)
{
int ret = 1;
for (; data->type != ALTLINK_EOL; data++) {
if (data->type == ALTLINK_GROUP) {
ret = 0;
if (strcmp(binary_name, data->target) == 0)
return 1;
}
}
return ret;
}
static int isLargestOrSameSizeGroupAsLowerPriorityBinary(unsigned *group_sizes, unsigned group_idx)
{
if (group_idx == 0 || group_sizes[group_idx-1] <= group_sizes[group_idx])
return 1;
return 0;
}
static void appendError(const struct AlternativeLink *data, const char *message, struct ConsistencyError **errors_ptr, unsigned *n_err)
{
if (errors_ptr == NULL)
return;
struct ConsistencyError *errors = *errors_ptr;
unsigned idx = *n_err;
errors = *errors_ptr = (struct ConsistencyError*)realloc(errors, sizeof(struct ConsistencyError) * (idx + 1));
errors[idx].message = message;
errors[idx].record = data;
*n_err = idx + 1;
}
int checkGroupConsistencies(const struct InstalledBinaryData *data, unsigned n_binaries, enum ConsistencyCheckFlags flags, struct ConsistencyError **errors, unsigned *n_errors)
{
int ret = 0;
if (n_errors != NULL)
*n_errors = 0;
for (unsigned i=0; i<n_binaries; i++) {
const struct InstalledBinaryData *d = data + i;
unsigned *group_sizes = (unsigned*)malloc(sizeof(unsigned) * d->num_priorities);
for (unsigned pidx=0; pidx<d->num_priorities; pidx++) {
struct AlternativeLink *alts = d->alts[pidx];
if (alts == NULL) {
ret |= 1;
continue;
}
if (!isBinaryInGroupOfBinariesOrWithoutGroup(d->binary_name, alts)) {
appendError(alts, "WARNING: binary not part of the Group", errors, n_errors);
ret |= 1;
}
group_sizes[pidx] = numBinariesInGroup(d->alts[pidx]);
if (!isLargestOrSameSizeGroupAsLowerPriorityBinary(group_sizes, pidx)) {
appendError(alts, "WARNING: shadows more complete Group with lower priority", errors, n_errors);
ret |= 1;
}
}
free(group_sizes);
}
return ret;
}
0707010000003F000081A4000003E8000000640000000161406678000018B5000000000000000000000000000000000000003500000000libalternatives-v1.2+3.b848aad/utils/list_binaries.c/* libalternatives - update-alternatives alternative
* Copyright (C) 2021 SUSE LLC
*
* 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/>.
*/
#define _GNU_SOURCE
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "utils.h"
static int strcmpp(const void *a, const void *b, __attribute__((unused)) void *ptr)
{
return strcmp(*(const char * const *)a, *(const char * const *)b);
}
static int numcmp(const void *a, const void *b, __attribute__((unused)) void *ptr)
{
return *(const int*)a - *(const int*)b;
}
static void filterStringsArray(const char *filter, char **bins, size_t *bin_size)
{
if (filter == NULL)
return;
size_t already_matched = 0;
for (size_t i=0; i<*bin_size; i++) {
char *binary_name = bins[i];
if (already_matched == 0 && strcmp(binary_name, filter) == 0) {
bins[0] = binary_name;
already_matched = 1;
}
else {
free(binary_name);
}
}
*bin_size = already_matched;
}
static int loadInstalledBinariesAndTheirOverrides(const char *program_filter, struct InstalledBinaryData **binaries_ptr, size_t *bin_size)
{
char **binary_names_array;
if (libalts_load_available_binaries(&binary_names_array, bin_size) != 0) {
perror(binname);
return -1;
}
filterStringsArray(program_filter, binary_names_array, bin_size);
qsort_r(&binary_names_array[0], *bin_size, sizeof(char*), strcmpp, NULL);
*binaries_ptr = (struct InstalledBinaryData*)malloc(sizeof(struct InstalledBinaryData) * *bin_size);
for (size_t i=0; i<*bin_size; i++) {
struct InstalledBinaryData *binary = (*binaries_ptr) + i;
binary->binary_name = binary_names_array[i];
binary->alts = NULL;
if (libalts_load_binary_priorities(binary->binary_name, &binary->priorities, &binary->num_priorities) != 0) {
if (errno == ENOENT) {
binary->num_priorities = 0;
continue;
}
else {
perror(binname);
return -1;
}
}
binary->def_priority_src = 0;
binary->def_priority = libalts_read_configured_priority(binary->binary_name, &binary->def_priority_src);
qsort_r(binary->priorities, binary->num_priorities, sizeof(int), numcmp, NULL);
if (binary->num_priorities > 0 && binary->def_priority <= 0) {
binary->def_priority_src = 0;
binary->def_priority = binary->priorities[binary->num_priorities-1];
}
binary->alts = (struct AlternativeLink**)malloc(sizeof(struct AlternativeLink*) * binary->num_priorities);
for (size_t i=0; i<binary->num_priorities; i++) {
int priority = binary->priorities[i];
struct AlternativeLink *alts;
if (libalts_load_exact_priority_binary_alternatives(binary->binary_name, priority, &alts) < 0) {
alts = NULL;
}
binary->alts[i] = alts;
}
}
free(binary_names_array);
return 0;
}
static void printErrorsAssociatedWithBinary(const struct AlternativeLink *link, const struct ConsistencyError *errors, unsigned n_errors)
{
while (link->type != ALTLINK_EOL) {
for (unsigned err=0; err<n_errors; err++) {
if (errors[err].record == link) {
fwrite(" ", 1, 2, stdout);
puts(errors[err].message);
}
}
link++;
}
}
static void printInstalledBinaryAlternatives(const struct InstalledBinaryData *binary, const struct ConsistencyError *errors, unsigned n_errors)
{
const char *alt_no_str = "Alternatives: %d\n";
printf("Binary: %s\n", binary->binary_name);
printf(alt_no_str, binary->num_priorities);
for (size_t i = 0; i < binary->num_priorities; i++)
{
int priority = binary->priorities[i];
struct AlternativeLink *alts = binary->alts[i];
char priority_mark = ' ';
if (binary->def_priority == priority)
{
switch (binary->def_priority_src)
{
default:
case 0: // default selection
priority_mark = '*';
break;
case 1: // system
priority_mark = '!';
break;
case 2: // user
priority_mark = '~';
break;
}
}
if (!alts) {
printf("*** %d priority data unparsable config.\n", priority);
continue;
}
int group_pos = 0;
const char *group[16];
for (struct AlternativeLink *link = binary->alts[i]; link && link->type != ALTLINK_EOL; link++)
{
switch (link->type) {
case ALTLINK_BINARY:
printf(" Priority: %d%c Target: %s\n", priority, priority_mark, link->target);
break;
case ALTLINK_GROUP:
if (group_pos < 16)
group[group_pos++] = link->target;
break;
default:
break;
}
}
if (group_pos > 0) {
qsort_r(&group[0], group_pos, sizeof(const char**), strcmpp, NULL);
const char header[] = " Group: ";
fwrite(header, 1, sizeof(header)-1, stdout);
fwrite(group[0], 1, strlen(group[0]), stdout);
for (int i=1; i<group_pos; i++) {
fwrite(", ", 1, 2, stdout);
fwrite(group[i], 1, strlen(group[i]), stdout);
}
fwrite("\n", 1, 1, stdout);
}
printErrorsAssociatedWithBinary(binary->alts[i], errors, n_errors);
}
}
static void freeInstalledBinaryDataStruct(struct InstalledBinaryData *data)
{
free((void*)data->binary_name);
free(data->priorities);
for (size_t i=0; i<data->num_priorities; i++)
libalts_free_alternatives_ptr(&data->alts[i]);
free(data->alts);
}
int printInstalledBinariesAndTheirOverrideStates(const char *program)
{
struct InstalledBinaryData *binaries;
struct ConsistencyError *errors = NULL;
unsigned n_errors;
size_t bin_size;
int ret;
ret = loadInstalledBinariesAndTheirOverrides(program, &binaries, &bin_size);
if (ret != 0)
return ret;
ret = checkGroupConsistencies(binaries, bin_size, 0, &errors, &n_errors);
for (size_t i=0; i<bin_size; i++) {
if (i > 0)
puts("---");
printInstalledBinaryAlternatives(binaries + i, errors, n_errors);
freeInstalledBinaryDataStruct(binaries + i);
}
free(binaries);
free(errors);
return ret;
}
07070100000040000081A4000003E800000064000000016140667800000594000000000000000000000000000000000000002D00000000libalternatives-v1.2+3.b848aad/utils/utils.h/* libalternatives - update-alternatives alternative
* Copyright (C) 2021 SUSE LLC
*
* 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/>.
*/
#include "../src/libalternatives.h"
extern const char binname[];
struct ConsistencyError {
const struct AlternativeLink *record;
const char *message;
};
struct InstalledBinaryData
{
const char *binary_name;
size_t num_priorities;
int *priorities;
int def_priority, def_priority_src;
struct AlternativeLink **alts; // [0..num_priorities)
};
enum ConsistencyCheckFlags
{
CONSISTENCY_LOAD_ADDITIONAL_BINARIES = 1
};
int printInstalledBinariesAndTheirOverrideStates(const char *program);
int checkGroupConsistencies(const struct InstalledBinaryData *data, unsigned n_binaries, enum ConsistencyCheckFlags flags, struct ConsistencyError **errors, unsigned *n_errors);
07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!351 blocks