pax_global_header00006660000000000000000000000064151163742470014524gustar00rootroot0000000000000052 comment=c52db0a9849908613ab8775b519834671b7bec8b rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/000077500000000000000000000000001511637424700202335ustar00rootroot00000000000000rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/.editorconfig000066400000000000000000000002651511637424700227130ustar00rootroot00000000000000root = true [*] end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true charset = utf-8 indent_style = space indent_size = 8 [Makefile.am] indent_style = tab rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/.gitignore000066400000000000000000000000201511637424700222130ustar00rootroot00000000000000*.cache /build/ rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/.gitlab-ci.yml000066400000000000000000000025321511637424700226710ustar00rootroot00000000000000include: - project: 'freedesktop/ci-templates' ref: master file: '/templates/fedora.yml' # Let's define some stages to get the correct order of jobs. stages: - container - build variables: # The upstream repository path on gitlab.freedesktop.org to check # for existing container images. FDO_UPSTREAM_REPO: pipewire/rtkit # A simple template so we only have one place where we need to # define the Fedora version and the image tag # Using a date as tag is best practice but it can be any string # allowed by the GitLab registry. .rtkit.fedora:43: variables: FDO_DISTRIBUTION_VERSION: 43 FDO_DISTRIBUTION_TAG: '2025-12-09.0' # A job to build a Fedora 43 container with required deps build-fedora-container: extends: - .fdo.container-build@fedora # the CI template - .rtkit.fedora:43 # our template job above stage: container variables: # Packages to install on the container FDO_DISTRIBUTION_PACKAGES: >- dbus-devel gcc git libcap-devel meson polkit-devel systemd-devel xxd # The build job for your project. Extending from the CI Templates # .fdo.distribution-image makes it use the same image we built above. build: extends: - .fdo.distribution-image@fedora - .rtkit.fedora:43 stage: build script: - meson setup build - ninja -C build rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/GPL000066400000000000000000001045151511637424700206060ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. 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. Copyright (C) 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 . 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: Copyright (C) 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 . 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 . rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/LICENSE000066400000000000000000000003631511637424700212420ustar00rootroot00000000000000LICENSES The daemon itself is GPL3 licensed, for more information see the GPL file. The client library is BSD licensed, for more information see the headers of the appropriate files. Lennart Poettering, 2009 rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/README000066400000000000000000000241561511637424700211230ustar00rootroot00000000000000REALTIMEKIT Realtime Policy and Watchdog Daemon GIT: https://github.com/heftig/rtkit NOTES: RealtimeKit is a D-Bus system service that changes the scheduling policy of user processes/threads to SCHED_RR (i.e. realtime scheduling mode) on request. It is intended to be used as a secure mechanism to allow real-time scheduling to be used by normal user processes. RealtimeKit enforces strict policies when handing out real-time security to user threads: * Only clients with RLIMIT_RTTIME set will get RT scheduling * RT scheduling will only be handed out to processes with SCHED_RESET_ON_FORK set to guarantee that the scheduling settings cannot 'leak' to child processes, thus making sure that 'RT fork bombs' cannot be used to bypass RLIMIT_RTTIME and take the system down. * Limits are enforced on all user controllable resources, only a maximum number of users, processes, threads can request RT scheduling at the same time. * Only a limited number of threads may be made RT in a specific time frame. * Client authorization is verified with PolicyKit RealtimeKit can also be used to hand outh high priority scheduling (i.e. negative nice level) to user processes. In addition to this a-priori policy enforcement, RealtimeKit also provides a-posteriori policy enforcement, i.e. it includes a canary-based watchdog that automatically demotes all real-time threads to SCHED_OTHER should the system overload despite the logic pointed out above. For more information regarding canary-based RT watchdogs, see the Acknowledgments section below. In its duty to manage real-time scheduling *securely* RealtimeKit runs as unpriviliged user, and uses capabalities, resource limits and chroot() to minimize its security impact. RealtimeKit probably has little use in embedded or server use cases, use RLIMIT_RTPRIO there instead. WHY: If processes that have real-time scheduling privileges enter a busy loop they can freeze the entire the system. To make sure such run-away processes cannot do this RLIMIT_RTTIME has been introduced. Being a per-process limit it is however easily cirumvented by combining a fork bomb with a busy loop. RealtimeKit hands out RT scheduling to specific threads that ask for it -- but only to those and due to SCHED_RESET_ON_FORK it can be sure that this won't 'leak'. In contrast to RLIMIT_RTPRIO the RealtimeKit logic makes sure that only a certain number of threads can be made realtime, per user, per process and per time interval. CLIENTS: An MIT-licensed reference implementation of the client is available in rtkit.[ch] as part of the package. If you just want rtkit realtime scheduling and don't care about the details, you may copy these files into your source tree, then run this function to enable realtime scheduling: if (rtkit_make_realtime_simple() < 0) { fprintf(stderr, "Failed to switch to realtime scheduling.\n"); } This implementation depends on dbus. Run pkgconf --cflags dbus-1 for the C flags necessary for compiling and pkgconf --libs dbus-1 for the libs necessary for linking. However, given how simple the D-Bus interface is, you might choose to implement your own client implementation. ADVANCED CLIENTS: Clients communicate with rtkit through a small D-Bus interface: service: org.freedesktop.RealtimeKit1 object: /org/freedesktop/RealtimeKit1 interface: org.freedesktop.RealtimeKit1 This interface has the following properties: s32 MaxRealtimePriority; s32 MinNiceLevel; s64 RTTimeUSecMax; To request realtime scheduling, a client calls this method: void MakeThreadRealtime(u64 thread_id, u32 priority); priority may be any value between 1 and MaxRealtimePriority. Use setrlimit() to set RLIMIT_RTTIME to any value between 1 and RTTimeUSecMax before calling this method, or it will fail. This method merely reduces niceness without changing the scheduling policy: void MakeThreadHighPriority(u64 thread_id, s32 nice_level); nice_level may be any value between MinNiceLevel and 0. In both cases, the thread IDs need to be passed as kernel tids as returned by gettid(), not a pthread_t! It is possible to promote thread in process to realtime/high priority from another process, that will make the DBUS call, using: void MakeThreadRealtimeWithPID(u64 process, u64 thread_id, u32 priority); void MakeThreadHighPriorityWithPID(u64 process, u64 thread_id, s32 nice_level); where process is the PID of the process that has thread thread_id. It is advisable to try acquiring realtime scheduling with sched_setsheduler() first, so that systems where RLIMIT_RTPRIO is set can be supported. Here's an example using the reference implementation. Replace this: struct sched_param p; memset(&p, 0, sizeof(p)); p.sched_priority = 3; sched_setscheduler(0, SCHED_RR|SCHED_RESET_ON_FORK, &p); by this: struct sched_param p; memset(&p, 0, sizeof(p)); p.sched_priority = 3; if (sched_setscheduler(0, SCHED_RR|SCHED_RESET_ON_FORK, &p) < 0 && errno == EPERM) rtkit_make_realtime(system_bus, 0, p.sched_priority); But of course add more appropriate error checking! Also, falling back to plain SCHED_RR when SCHED_RESET_ON_FORK causes EINVAL migt be advisable). DAEMON: The daemon is automatically started on first use via D-Bus system bus activation. Currently the daemon does not read on any configuration file, however it can be configured with command line parameters. You can edit /usr/share/dbus-1/system-services/org.freedesktop.RealtimeKit1.service to set those. Run /usr/libexec/rtkit-daemon --help to get a quick overview on the supported parameters and their defaults. Many of them should be obvious in their meaning. For the remaining ones see below: --max-realtime-priority= may be used to specify the maximum realtime priority a client can acquire through RealtimeKit. Please note that this value must be smaller than the value passed to --our-realtime-priority=. --our-realtime-priority= may be used to specify the realtime priority of the daemon itself. Please note that this priority is only used for a very short time while processing a client request. Normally the daemon will not be running with a realtime scheduling policy. The real-time priorities handed out to the user must be lower than this value. (see above). --min-nice-level= may be used to specify the minimum nice level a client can acquire through RealtimeKit. --our-nice-level= may be used to specify the nice level the the daemon itself uses most of the time (except when processing requests, see above). It is probably a good idea to set this to a small positive value, to make sure that if the system is overloaded already handing out further RT scheduling will be delayed a bit. --rttime-usec-max= may be used to control which RLIMIT_RTTIME value clients need to have chosen at minimum before they may acquire RT scheduling through RealtimeKit. --users-max= specifies how many users may acquire RT scheduling at the same time for one or multiple of their processes. --processes-per-user-max= specifies how many processes per user may acquire RT scheduling at the same time. --threads-per-user-max= specifies how many threads per user may acquire RT scheduling at the same time. Of course this value should be set higher than --process-per-user-max=. --actions-burst-sec= may be used to influence the rate limiting logic in RealtimeKit. The daemon will only pass realtime scheduling privileges to a maximum number of threads within this timeframe (see below). --actions-per-burst-max= may be used to influence the rate limiting logic in RealtimeKit. The daemon will only pass realtime scheduling privileges to this number of threads within the time frame configured via --actions-burst-sec=. When this limit is reached clients need to wait until that time passes before requesting RT scheduling again. --canary-cheep-msec= may be used to control how often the canary thread shall cheep. --canary-watchdog-msec= may be used to control how quickly the watchdog thread expects to receive a cheep from the canary thread. This value must be chosen larger than --canary-cheep-msec=. If the former is set 10s and the latter to 7s, then the canary thread can trigger and deliver the cheep with a maximum latency of 3s. ACKNOWLEDGMENTS: The canary watchdog logic is inspired by previous work of Vernon Mauery, Florian Schmidt, Kjetil Matheussen: http://rt.wiki.kernel.org/index.php/RT_Watchdog LICENSE: GPLv3+ for the daemon MIT for the client reference implementation AUTHOR: Lennart Poettering REQUIREMENTS: Linux kernel >= 2.6.31 D-Bus PolicyKit >= 0.92 OPTIONAL DEPENDENCIES: libsystemd - to let rtkit talk to systemd using the sd-daemon API logind (runtime) - to gracefully handle system-suspend rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/config.h.meson000066400000000000000000000001601511637424700227660ustar00rootroot00000000000000#ifndef fooconfighfoo #define fooconfighfoo #mesondefine PACKAGE_VERSION #mesondefine HAVE_LIBSYSTEMD #endif rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/m4/000077500000000000000000000000001511637424700205535ustar00rootroot00000000000000rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/m4/acx_pthread.m4000066400000000000000000000254231511637424700233050ustar00rootroot00000000000000# =========================================================================== # http://www.nongnu.org/autoconf-archive/acx_pthread.html # =========================================================================== # # SYNOPSIS # # ACX_PTHREAD([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]]) # # DESCRIPTION # # This macro figures out how to build C programs using POSIX threads. It # sets the PTHREAD_LIBS output variable to the threads library and linker # flags, and the PTHREAD_CFLAGS output variable to any special C compiler # flags that are needed. (The user can also force certain compiler # flags/libs to be tested by setting these environment variables.) # # Also sets PTHREAD_CC to any special C compiler that is needed for # multi-threaded programs (defaults to the value of CC otherwise). (This # is necessary on AIX to use the special cc_r compiler alias.) # # NOTE: You are assumed to not only compile your program with these flags, # but also link it with them as well. e.g. you should link with # $PTHREAD_CC $CFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS $LIBS # # If you are only building threads programs, you may wish to use these # variables in your default LIBS, CFLAGS, and CC: # # LIBS="$PTHREAD_LIBS $LIBS" # CFLAGS="$CFLAGS $PTHREAD_CFLAGS" # CC="$PTHREAD_CC" # # In addition, if the PTHREAD_CREATE_JOINABLE thread-attribute constant # has a nonstandard name, defines PTHREAD_CREATE_JOINABLE to that name # (e.g. PTHREAD_CREATE_UNDETACHED on AIX). # # ACTION-IF-FOUND is a list of shell commands to run if a threads library # is found, and ACTION-IF-NOT-FOUND is a list of commands to run it if it # is not found. If ACTION-IF-FOUND is not specified, the default action # will define HAVE_PTHREAD. # # Please let the authors know if this macro fails on any platform, or if # you have any other suggestions or comments. This macro was based on work # by SGJ on autoconf scripts for FFTW (http://www.fftw.org/) (with help # from M. Frigo), as well as ac_pthread and hb_pthread macros posted by # Alejandro Forero Cuervo to the autoconf macro repository. We are also # grateful for the helpful feedback of numerous users. # # LICENSE # # Copyright (c) 2008 Steven G. Johnson # # 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 . # # As a special exception, the respective Autoconf Macro's copyright owner # gives unlimited permission to copy, distribute and modify the configure # scripts that are the output of Autoconf when processing the Macro. You # need not follow the terms of the GNU General Public License when using # or distributing such scripts, even though portions of the text of the # Macro appear in them. The GNU General Public License (GPL) does govern # all other use of the material that constitutes the Autoconf Macro. # # This special exception to the GPL applies to versions of the Autoconf # Macro released by the Autoconf Archive. When you make and distribute a # modified version of the Autoconf Macro, you may extend this special # exception to the GPL to apply to your modified version as well. AC_DEFUN([ACX_PTHREAD], [ AC_REQUIRE([AC_CANONICAL_HOST]) AC_LANG_SAVE AC_LANG_C acx_pthread_ok=no # We used to check for pthread.h first, but this fails if pthread.h # requires special compiler flags (e.g. on True64 or Sequent). # It gets checked for in the link test anyway. # First of all, check if the user has set any of the PTHREAD_LIBS, # etcetera environment variables, and if threads linking works using # them: if test x"$PTHREAD_LIBS$PTHREAD_CFLAGS" != x; then save_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS $PTHREAD_CFLAGS" save_LIBS="$LIBS" LIBS="$PTHREAD_LIBS $LIBS" AC_MSG_CHECKING([for pthread_join in LIBS=$PTHREAD_LIBS with CFLAGS=$PTHREAD_CFLAGS]) AC_TRY_LINK_FUNC(pthread_join, acx_pthread_ok=yes) AC_MSG_RESULT($acx_pthread_ok) if test x"$acx_pthread_ok" = xno; then PTHREAD_LIBS="" PTHREAD_CFLAGS="" fi LIBS="$save_LIBS" CFLAGS="$save_CFLAGS" fi # We must check for the threads library under a number of different # names; the ordering is very important because some systems # (e.g. DEC) have both -lpthread and -lpthreads, where one of the # libraries is broken (non-POSIX). # Create a list of thread flags to try. Items starting with a "-" are # C compiler flags, and other items are library names, except for "none" # which indicates that we try without any flags at all, and "pthread-config" # which is a program returning the flags for the Pth emulation library. acx_pthread_flags="pthreads none -Kthread -kthread lthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config" # The ordering *is* (sometimes) important. Some notes on the # individual items follow: # pthreads: AIX (must check this before -lpthread) # none: in case threads are in libc; should be tried before -Kthread and # other compiler flags to prevent continual compiler warnings # -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h) # -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able) # lthread: LinuxThreads port on FreeBSD (also preferred to -pthread) # -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads) # -pthreads: Solaris/gcc # -mthreads: Mingw32/gcc, Lynx/gcc # -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it # doesn't hurt to check since this sometimes defines pthreads too; # also defines -D_REENTRANT) # ... -mt is also the pthreads flag for HP/aCC # pthread: Linux, etcetera # --thread-safe: KAI C++ # pthread-config: use pthread-config program (for GNU Pth library) case "${host_cpu}-${host_os}" in *solaris*) # On Solaris (at least, for some versions), libc contains stubbed # (non-functional) versions of the pthreads routines, so link-based # tests will erroneously succeed. (We need to link with -pthreads/-mt/ # -lpthread.) (The stubs are missing pthread_cleanup_push, or rather # a function called by this macro, so we could check for that, but # who knows whether they'll stub that too in a future libc.) So, # we'll just look for -pthreads and -lpthread first: acx_pthread_flags="-pthreads pthread -mt -pthread $acx_pthread_flags" ;; esac if test x"$acx_pthread_ok" = xno; then for flag in $acx_pthread_flags; do case $flag in none) AC_MSG_CHECKING([whether pthreads work without any flags]) ;; -*) AC_MSG_CHECKING([whether pthreads work with $flag]) PTHREAD_CFLAGS="$flag" ;; pthread-config) AC_CHECK_PROG(acx_pthread_config, pthread-config, yes, no) if test x"$acx_pthread_config" = xno; then continue; fi PTHREAD_CFLAGS="`pthread-config --cflags`" PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`" ;; *) AC_MSG_CHECKING([for the pthreads library -l$flag]) PTHREAD_LIBS="-l$flag" ;; esac save_LIBS="$LIBS" save_CFLAGS="$CFLAGS" LIBS="$PTHREAD_LIBS $LIBS" CFLAGS="$CFLAGS $PTHREAD_CFLAGS" # Check for various functions. We must include pthread.h, # since some functions may be macros. (On the Sequent, we # need a special flag -Kthread to make this header compile.) # We check for pthread_join because it is in -lpthread on IRIX # while pthread_create is in libc. We check for pthread_attr_init # due to DEC craziness with -lpthreads. We check for # pthread_cleanup_push because it is one of the few pthread # functions on Solaris that doesn't have a non-functional libc stub. # We try pthread_create on general principles. AC_TRY_LINK([#include ], [pthread_t th; pthread_join(th, 0); pthread_attr_init(0); pthread_cleanup_push(0, 0); pthread_create(0,0,0,0); pthread_cleanup_pop(0); ], [acx_pthread_ok=yes]) LIBS="$save_LIBS" CFLAGS="$save_CFLAGS" AC_MSG_RESULT($acx_pthread_ok) if test "x$acx_pthread_ok" = xyes; then break; fi PTHREAD_LIBS="" PTHREAD_CFLAGS="" done fi # Various other checks: if test "x$acx_pthread_ok" = xyes; then save_LIBS="$LIBS" LIBS="$PTHREAD_LIBS $LIBS" save_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS $PTHREAD_CFLAGS" # Detect AIX lossage: JOINABLE attribute is called UNDETACHED. AC_MSG_CHECKING([for joinable pthread attribute]) attr_name=unknown for attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do AC_TRY_LINK([#include ], [int attr=$attr; return attr;], [attr_name=$attr; break]) done AC_MSG_RESULT($attr_name) if test "$attr_name" != PTHREAD_CREATE_JOINABLE; then AC_DEFINE_UNQUOTED(PTHREAD_CREATE_JOINABLE, $attr_name, [Define to necessary symbol if this constant uses a non-standard name on your system.]) fi AC_MSG_CHECKING([if more special flags are required for pthreads]) flag=no case "${host_cpu}-${host_os}" in *-aix* | *-freebsd* | *-darwin*) flag="-D_THREAD_SAFE";; *solaris* | *-osf* | *-hpux*) flag="-D_REENTRANT";; esac AC_MSG_RESULT(${flag}) if test "x$flag" != xno; then PTHREAD_CFLAGS="$flag $PTHREAD_CFLAGS" fi LIBS="$save_LIBS" CFLAGS="$save_CFLAGS" # More AIX lossage: must compile with xlc_r or cc_r if test x"$GCC" != xyes; then AC_CHECK_PROGS(PTHREAD_CC, xlc_r cc_r, ${CC}) else PTHREAD_CC=$CC fi else PTHREAD_CC="$CC" fi AC_SUBST(PTHREAD_LIBS) AC_SUBST(PTHREAD_CFLAGS) AC_SUBST(PTHREAD_CC) # Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND: if test x"$acx_pthread_ok" = xyes; then ifelse([$1],,AC_DEFINE(HAVE_PTHREAD,1,[Define if you have POSIX threads libraries and header files.]),[$1]) : else acx_pthread_ok=no $2 fi AC_LANG_RESTORE ])dnl ACX_PTHREAD rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/m4/attributes.m4000066400000000000000000000231561511637424700232120ustar00rootroot00000000000000dnl Macros to check the presence of generic (non-typed) symbols. dnl Copyright (c) 2006-2008 Diego Pettenò dnl Copyright (c) 2006-2008 xine project dnl Copyright (c) 2012 Lucas De Marchi dnl dnl This program is free software; you can redistribute it and/or modify dnl it under the terms of the GNU General Public License as published by dnl the Free Software Foundation; either version 2, or (at your option) dnl any later version. dnl dnl This program is distributed in the hope that it will be useful, dnl but WITHOUT ANY WARRANTY; without even the implied warranty of dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the dnl GNU General Public License for more details. dnl dnl You should have received a copy of the GNU General Public License dnl along with this program; if not, write to the Free Software dnl Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA dnl 02110-1301, USA. dnl dnl As a special exception, the copyright owners of the dnl macro gives unlimited permission to copy, distribute and modify the dnl configure scripts that are the output of Autoconf when processing the dnl Macro. You need not follow the terms of the GNU General Public dnl License when using or distributing such scripts, even though portions dnl of the text of the Macro appear in them. The GNU General Public dnl License (GPL) does govern all other use of the material that dnl constitutes the Autoconf Macro. dnl dnl This special exception to the GPL applies to versions of the dnl Autoconf Macro released by this project. When you make and dnl distribute a modified version of the Autoconf Macro, you may extend dnl this special exception to the GPL to apply to your modified version as dnl well. dnl Check if FLAG in ENV-VAR is supported by compiler and append it dnl to WHERE-TO-APPEND variable dnl CC_CHECK_FLAG_APPEND([WHERE-TO-APPEND], [ENV-VAR], [FLAG]) AC_DEFUN([CC_CHECK_FLAG_APPEND], [ AC_CACHE_CHECK([if $CC supports flag $3 in envvar $2], AS_TR_SH([cc_cv_$2_$3]), [eval "AS_TR_SH([cc_save_$2])='${$2}'" eval "AS_TR_SH([$2])='$3'" AC_COMPILE_IFELSE([AC_LANG_SOURCE([int a = 0; int main(void) { return a; } ])], [eval "AS_TR_SH([cc_cv_$2_$3])='yes'"], [eval "AS_TR_SH([cc_cv_$2_$3])='no'"]) eval "AS_TR_SH([$2])='$cc_save_$2'"]) AS_IF([eval test x$]AS_TR_SH([cc_cv_$2_$3])[ = xyes], [eval "$1='${$1} $3'"]) ]) dnl CC_CHECK_FLAGS_APPEND([WHERE-TO-APPEND], [ENV-VAR], [FLAG1 FLAG2]) AC_DEFUN([CC_CHECK_FLAGS_APPEND], [ for flag in $3; do CC_CHECK_FLAG_APPEND($1, $2, $flag) done ]) dnl Check if the flag is supported by linker (cacheable) dnl CC_CHECK_LDFLAGS([FLAG], [ACTION-IF-FOUND],[ACTION-IF-NOT-FOUND]) AC_DEFUN([CC_CHECK_LDFLAGS], [ AC_CACHE_CHECK([if $CC supports $1 flag], AS_TR_SH([cc_cv_ldflags_$1]), [ac_save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS $1" AC_LINK_IFELSE([int main() { return 1; }], [eval "AS_TR_SH([cc_cv_ldflags_$1])='yes'"], [eval "AS_TR_SH([cc_cv_ldflags_$1])="]) LDFLAGS="$ac_save_LDFLAGS" ]) AS_IF([eval test x$]AS_TR_SH([cc_cv_ldflags_$1])[ = xyes], [$2], [$3]) ]) dnl define the LDFLAGS_NOUNDEFINED variable with the correct value for dnl the current linker to avoid undefined references in a shared object. AC_DEFUN([CC_NOUNDEFINED], [ dnl We check $host for which systems to enable this for. AC_REQUIRE([AC_CANONICAL_HOST]) case $host in dnl FreeBSD (et al.) does not complete linking for shared objects when pthreads dnl are requested, as different implementations are present; to avoid problems dnl use -Wl,-z,defs only for those platform not behaving this way. *-freebsd* | *-openbsd*) ;; *) dnl First of all check for the --no-undefined variant of GNU ld. This allows dnl for a much more readable commandline, so that people can understand what dnl it does without going to look for what the heck -z defs does. for possible_flags in "-Wl,--no-undefined" "-Wl,-z,defs"; do CC_CHECK_LDFLAGS([$possible_flags], [LDFLAGS_NOUNDEFINED="$possible_flags"]) break done ;; esac AC_SUBST([LDFLAGS_NOUNDEFINED]) ]) dnl Check for a -Werror flag or equivalent. -Werror is the GCC dnl and ICC flag that tells the compiler to treat all the warnings dnl as fatal. We usually need this option to make sure that some dnl constructs (like attributes) are not simply ignored. dnl dnl Other compilers don't support -Werror per se, but they support dnl an equivalent flag: dnl - Sun Studio compiler supports -errwarn=%all AC_DEFUN([CC_CHECK_WERROR], [ AC_CACHE_CHECK( [for $CC way to treat warnings as errors], [cc_cv_werror], [CC_CHECK_CFLAGS_SILENT([-Werror], [cc_cv_werror=-Werror], [CC_CHECK_CFLAGS_SILENT([-errwarn=%all], [cc_cv_werror=-errwarn=%all])]) ]) ]) AC_DEFUN([CC_CHECK_ATTRIBUTE], [ AC_REQUIRE([CC_CHECK_WERROR]) AC_CACHE_CHECK([if $CC supports __attribute__(( ifelse([$2], , [$1], [$2]) ))], AS_TR_SH([cc_cv_attribute_$1]), [ac_save_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS $cc_cv_werror" AC_COMPILE_IFELSE([AC_LANG_SOURCE([$3])], [eval "AS_TR_SH([cc_cv_attribute_$1])='yes'"], [eval "AS_TR_SH([cc_cv_attribute_$1])='no'"]) CFLAGS="$ac_save_CFLAGS" ]) AS_IF([eval test x$]AS_TR_SH([cc_cv_attribute_$1])[ = xyes], [AC_DEFINE( AS_TR_CPP([SUPPORT_ATTRIBUTE_$1]), 1, [Define this if the compiler supports __attribute__(( ifelse([$2], , [$1], [$2]) ))] ) $4], [$5]) ]) AC_DEFUN([CC_ATTRIBUTE_CONSTRUCTOR], [ CC_CHECK_ATTRIBUTE( [constructor],, [void __attribute__((constructor)) ctor() { int a; }], [$1], [$2]) ]) AC_DEFUN([CC_ATTRIBUTE_FORMAT], [ CC_CHECK_ATTRIBUTE( [format], [format(printf, n, n)], [void __attribute__((format(printf, 1, 2))) printflike(const char *fmt, ...) { fmt = (void *)0; }], [$1], [$2]) ]) AC_DEFUN([CC_ATTRIBUTE_FORMAT_ARG], [ CC_CHECK_ATTRIBUTE( [format_arg], [format_arg(printf)], [char *__attribute__((format_arg(1))) gettextlike(const char *fmt) { fmt = (void *)0; }], [$1], [$2]) ]) AC_DEFUN([CC_ATTRIBUTE_VISIBILITY], [ CC_CHECK_ATTRIBUTE( [visibility_$1], [visibility("$1")], [void __attribute__((visibility("$1"))) $1_function() { }], [$2], [$3]) ]) AC_DEFUN([CC_ATTRIBUTE_NONNULL], [ CC_CHECK_ATTRIBUTE( [nonnull], [nonnull()], [void __attribute__((nonnull())) some_function(void *foo, void *bar) { foo = (void*)0; bar = (void*)0; }], [$1], [$2]) ]) AC_DEFUN([CC_ATTRIBUTE_UNUSED], [ CC_CHECK_ATTRIBUTE( [unused], , [void some_function(void *foo, __attribute__((unused)) void *bar);], [$1], [$2]) ]) AC_DEFUN([CC_ATTRIBUTE_SENTINEL], [ CC_CHECK_ATTRIBUTE( [sentinel], , [void some_function(void *foo, ...) __attribute__((sentinel));], [$1], [$2]) ]) AC_DEFUN([CC_ATTRIBUTE_DEPRECATED], [ CC_CHECK_ATTRIBUTE( [deprecated], , [void some_function(void *foo, ...) __attribute__((deprecated));], [$1], [$2]) ]) AC_DEFUN([CC_ATTRIBUTE_ALIAS], [ CC_CHECK_ATTRIBUTE( [alias], [weak, alias], [void other_function(void *foo) { } void some_function(void *foo) __attribute__((weak, alias("other_function")));], [$1], [$2]) ]) AC_DEFUN([CC_ATTRIBUTE_MALLOC], [ CC_CHECK_ATTRIBUTE( [malloc], , [void * __attribute__((malloc)) my_alloc(int n);], [$1], [$2]) ]) AC_DEFUN([CC_ATTRIBUTE_PACKED], [ CC_CHECK_ATTRIBUTE( [packed], , [struct astructure { char a; int b; long c; void *d; } __attribute__((packed));], [$1], [$2]) ]) AC_DEFUN([CC_ATTRIBUTE_CONST], [ CC_CHECK_ATTRIBUTE( [const], , [int __attribute__((const)) twopow(int n) { return 1 << n; } ], [$1], [$2]) ]) AC_DEFUN([CC_FLAG_VISIBILITY], [ AC_REQUIRE([CC_CHECK_WERROR]) AC_CACHE_CHECK([if $CC supports -fvisibility=hidden], [cc_cv_flag_visibility], [cc_flag_visibility_save_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS $cc_cv_werror" CC_CHECK_CFLAGS_SILENT([-fvisibility=hidden], cc_cv_flag_visibility='yes', cc_cv_flag_visibility='no') CFLAGS="$cc_flag_visibility_save_CFLAGS"]) AS_IF([test "x$cc_cv_flag_visibility" = "xyes"], [AC_DEFINE([SUPPORT_FLAG_VISIBILITY], 1, [Define this if the compiler supports the -fvisibility flag]) $1], [$2]) ]) AC_DEFUN([CC_FUNC_EXPECT], [ AC_REQUIRE([CC_CHECK_WERROR]) AC_CACHE_CHECK([if compiler has __builtin_expect function], [cc_cv_func_expect], [ac_save_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS $cc_cv_werror" AC_COMPILE_IFELSE([AC_LANG_SOURCE( [int some_function() { int a = 3; return (int)__builtin_expect(a, 3); }])], [cc_cv_func_expect=yes], [cc_cv_func_expect=no]) CFLAGS="$ac_save_CFLAGS" ]) AS_IF([test "x$cc_cv_func_expect" = "xyes"], [AC_DEFINE([SUPPORT__BUILTIN_EXPECT], 1, [Define this if the compiler supports __builtin_expect() function]) $1], [$2]) ]) AC_DEFUN([CC_ATTRIBUTE_ALIGNED], [ AC_REQUIRE([CC_CHECK_WERROR]) AC_CACHE_CHECK([highest __attribute__ ((aligned ())) supported], [cc_cv_attribute_aligned], [ac_save_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS $cc_cv_werror" for cc_attribute_align_try in 64 32 16 8 4 2; do AC_COMPILE_IFELSE([AC_LANG_SOURCE([ int main() { static char c __attribute__ ((aligned($cc_attribute_align_try))) = 0; return c; }])], [cc_cv_attribute_aligned=$cc_attribute_align_try; break]) done CFLAGS="$ac_save_CFLAGS" ]) if test "x$cc_cv_attribute_aligned" != "x"; then AC_DEFINE_UNQUOTED([ATTRIBUTE_ALIGNED_MAX], [$cc_cv_attribute_aligned], [Define the highest alignment supported]) fi ]) rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/meson.build000066400000000000000000000114731511637424700224030ustar00rootroot00000000000000project( 'rtkit', 'c', version: '0.14', license: 'GPL3', meson_version: '>=0.58.0', default_options: ['c_std=c99', 'warning_level=2'], ) add_project_arguments( '-D_GNU_SOURCE', '-DHAVE_CONFIG_H', language: 'c' ) cc = meson.get_compiler('c') sh = find_program('sh') xxd = find_program('xxd', required: false) all_warnings = [ '-Wno-unused-parameter', ] supported_warnings = cc.get_supported_arguments(all_warnings) add_project_arguments(supported_warnings, language: 'c') dbus_dep = dependency('dbus-1') libcap_dep = dependency('libcap') libsystemd_dep = dependency('libsystemd', required: get_option('libsystemd')) polkit_dep = dependency('polkit-gobject-1', required: false) systemd_dep = dependency('systemd', required: false) thread_dep = dependency('threads') librt_dep = cc.find_library('rt') cc.check_header('sched.h', dependencies: librt_dep) cc.has_function('sched_setscheduler', dependencies: librt_dep) libexecdir = get_option('libexecdir') testsdir = get_option('libexecdir') / 'installed-tests' / meson.project_name() busservicedir = get_option('dbus_systemservicedir') if busservicedir == '' busservicedir = dbus_dep.get_variable( 'system_bus_services_dir', default_value: get_option('datadir') / 'dbus-1' / 'system-services', ) endif interfacedir = get_option('dbus_interfacedir') if interfacedir == '' interfacedir = dbus_dep.get_variable( 'interfaces_dir', default_value: get_option('datadir') / 'dbus-1' / 'interfaces', ) endif rulesdir = get_option('dbus_rulesdir') if rulesdir == '' rulesdir = get_option('datadir') / 'dbus-1' / 'system.d' endif policydir = get_option('polkit_actiondir') if policydir == '' and polkit_dep.found() policydir = polkit_dep.get_variable('actiondir', default_value: '') endif if policydir == '' policydir = get_option('datadir') / 'polkit-1' / 'actions' endif systemunitdir = get_option('systemd_systemunitdir') if systemunitdir == '' and systemd_dep.found() systemunitdir = systemd_dep.get_variable( 'systemdsystemunitdir', default_value: '', ) endif if systemunitdir == '' systemunitdir = get_option('libdir') / 'systemd' / 'system' endif sysusersdir = '' if sysusersdir == '' and systemd_dep.found() sysusersdir = systemd_dep.get_variable( 'sysusersdir', default_value: '', ) endif if sysusersdir == '' sysusersdir = get_option('libdir') / 'sysusers.d' endif config = configuration_data() config.set('LIBEXECDIR', get_option('prefix') / libexecdir) config.set_quoted('PACKAGE_VERSION', meson.project_version()) config.set('HAVE_LIBSYSTEMD', libsystemd_dep.found()) config_h = configure_file( input: 'config.h.meson', output: 'config.h', configuration: config, ) if xxd.found() xml_introspection_h = configure_file( input: 'org.freedesktop.RealtimeKit1.xml', output: 'xml-introspection.h', command: [ sh, '-c', '"$1" -i < "$2" > "$3"', sh, xxd, '@INPUT@', '@OUTPUT@' ], ) else warning('xxd not found, cannot compile introspection XML. Looking for existing one...') xml_introspection_h = files('xml-introspection.h') endif executable( 'rtkit-daemon', 'rtkit-daemon.c', 'rtkit.c', 'rtkit.h', config_h, xml_introspection_h, dependencies: [ dbus_dep, libcap_dep, librt_dep, libsystemd_dep, thread_dep ], install: true, install_dir: libexecdir, ) executable( 'rtkit-test', 'rtkit-test.c', 'rtkit.c', 'rtkit.h', config_h, dependencies: [dbus_dep, librt_dep], install: get_option('installed_tests'), install_dir: testsdir, ) executable( 'rtkitctl', 'rtkitctl.c', 'rtkit.h', config_h, install: true, install_dir: get_option('sbindir'), dependencies: [dbus_dep], ) install_man('rtkitctl.8') install_data('org.freedesktop.RealtimeKit1.xml', install_dir: interfacedir) install_data('org.freedesktop.RealtimeKit1.conf', install_dir: rulesdir) install_data('org.freedesktop.RealtimeKit1.policy', install_dir: policydir) configure_file( input: 'org.freedesktop.RealtimeKit1.service.in', output: 'org.freedesktop.RealtimeKit1.service', configuration: config, install_dir: busservicedir, ) configure_file( input: 'rtkit-daemon.service.in', output: 'rtkit-daemon.service', configuration: config, install_dir: systemunitdir, ) install_data( 'rtkit.sysusers', rename: 'rtkit.conf', install_dir: sysusersdir, ) rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/meson_options.txt000066400000000000000000000017531511637424700236760ustar00rootroot00000000000000option( 'dbus_interfacedir', type: 'string', value: '', description: 'Directory for D-Bus interface definitions', ) option( 'dbus_rulesdir', type: 'string', value: '', description: 'Directory for D-Bus system bus policy rules', ) option( 'dbus_systemservicedir', type: 'string', value: '', description: 'Directory for D-Bus system services', ) option( 'libsystemd', type: 'feature', value: 'auto', description: 'Use the libsystemd sd-daemon API to communicate with systemd' ) option( 'polkit_actiondir', type: 'string', value: '', description: 'Directory for Polkit actions', ) option( 'systemd_systemunitdir', type: 'string', value: '', description: 'Directory for systemd system units', ) option( 'installed_tests', type: 'boolean', value: true, description: 'Install tests' ) rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/org.freedesktop.RealtimeKit1.conf000066400000000000000000000033051511637424700264760ustar00rootroot00000000000000 rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/org.freedesktop.RealtimeKit1.policy000066400000000000000000000033711511637424700270530ustar00rootroot00000000000000 Lennart Poettering Grant high priority scheduling to a user process Bir sürece yüksek öncelikli çalışabilme yetkisi ver Authentication is required to grant an application high priority scheduling Sürecin yüksek öncelikli çalıştırılabilmesi için yetki gerekiyor no yes yes Grant realtime scheduling to a user process Bir sürece gerçek zamanlı çalışabilme yetkisi ver Authentication is required to grant an application realtime scheduling Sürecin gerçek zamanlı çalıştırılabilmesi için yetki gerekiyor no yes yes rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/org.freedesktop.RealtimeKit1.service.in000066400000000000000000000015011511637424700276120ustar00rootroot00000000000000# This file is part of RealtimeKit. # # Copyright 2009 Lennart Poettering # # RealtimeKit 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. # # RealtimeKit 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 RealtimeKit. If not, see . [D-BUS Service] Name=org.freedesktop.RealtimeKit1 Exec=@LIBEXECDIR@/rtkit-daemon SystemdService=rtkit-daemon.service User=root rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/org.freedesktop.RealtimeKit1.xml000066400000000000000000000047241511637424700263570ustar00rootroot00000000000000 rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/rtkit-daemon.c000066400000000000000000002725161511637424700230120ustar00rootroot00000000000000/*-*- Mode: C; c-basic-offset: 8 -*-*/ /*** This file is part of RealtimeKit. Copyright 2009 Lennart Poettering Copyright 2010 Maarten Lankhorst RealtimeKit 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. RealtimeKit 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 RealtimeKit. If not, see . ***/ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_LIBSYSTEMD #include #endif #include "rtkit.h" #ifndef __linux__ #error "This stuff only works on Linux!" #endif #ifndef SCHED_RESET_ON_FORK /* "Your libc lacks the definition of SCHED_RESET_ON_FORK. We'll now define it ourselves, however make sure your kernel is new enough! */ #define SCHED_RESET_ON_FORK 0x40000000 #endif #ifndef RLIMIT_RTTIME #define RLIMIT_RTTIME 15 #endif /* The introspection XML from org.freedesktop.RealtimeKit1.xml */ static const char introspect_xml[] = { #include "xml-introspection.h" ,0x00}; /* Similar to assert(), but has side effects, and hence shall never be optimized away, regardless of NDEBUG */ #define assert_se(expr) \ do { \ if (__builtin_expect(!(expr), 0)) { \ fprintf(stderr, "Assertion %s failed at %s:%u, function %s(). Aborting.\n", #expr, __FILE__, __LINE__, __PRETTY_FUNCTION__); \ abort(); \ } \ } while(0) #define ELEMENTSOF(x) (sizeof(x)/sizeof(x[0])) #define TIMESPEC_MSEC(ts) (((int64_t) (ts).tv_sec * 1000LL) + ((int64_t) (ts).tv_nsec / 1000000LL)) #ifndef ARRAY_SIZE #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) #endif /* If we actually execute a request we temporarily upgrade our realtime priority to this level */ static unsigned our_realtime_priority = 21; /* Normally we run at this nice level */ static int our_nice_level = 1; /* The maximum realtime priority to hand out */ static unsigned max_realtime_priority = 20; /* The minimum nice level to hand out */ static int min_nice_level = -15; /* Username we shall run under */ static const char *username = "rtkit"; /* Enforce that clients have RLIMIT_RTTIME set to a value <= this */ static unsigned long long rttime_usec_max = 200000ULL; /* 200 ms */ /* How many users do we supervise at max? */ static unsigned users_max = 2048; /* How many processes of a single user do we supervise at max? */ static unsigned processes_per_user_max = 15; /* How many threads of a single user do we supervise at max? */ static unsigned threads_per_user_max = 25; /* Refuse further requests if one user issues more than ACTIONS_PER_BURST_MAX in this time */ static unsigned actions_burst_sec = 20; /* Refuse further requests if one user issues more than this many in ACTIONS_BURST_SEC time */ static unsigned actions_per_burst_max = 25; /* Drop privileges */ static bool do_drop_privileges = TRUE; /* Change root directory to /proc */ static bool do_chroot = TRUE; /* Limit resources */ static bool do_limit_resources = TRUE; /* Run a canary watchdog */ static bool do_canary = TRUE; /* Canary cheep interval */ static unsigned canary_cheep_msec = 5000; /* 5s */ /* Canary watchdog interval */ static unsigned canary_watchdog_msec = 10000; /* 10s */ /* Watchdog realtime priority */ static unsigned canary_watchdog_realtime_priority = 99; /* How long after the canary died shall we refuse further RT requests? */ static unsigned canary_refusal_sec = 5*60; /* Demote root processes? */ static bool canary_demote_root = FALSE; /* Demote unknown processes? */ static bool canary_demote_unknown = FALSE; /* Log to stderr? */ static bool log_stderr = FALSE; /* Also log debugging messages? */ static bool log_debug = FALSE; /* Scheduling policy to use */ static int sched_policy = SCHED_RR; /* Current suspend state */ static bool suspended = FALSE; /* Logind sleep inhibitor pipefd */ static int inhibit_sleep_fd = -1; struct thread { /* We use the thread id plus its starttime as a unique identifier for threads */ pid_t pid; unsigned long long starttime; unsigned priority; int nice_level; struct thread *next; }; struct process { /* We use the process id plus its starttime as a unique identifier for processes */ pid_t pid; unsigned long long starttime; struct thread *threads; struct process *next; }; struct rtkit_user { uid_t uid; time_t timestamp; unsigned n_actions; struct process *processes; unsigned n_processes; unsigned n_threads; struct rtkit_user *next; }; static struct rtkit_user *users = NULL; static unsigned n_users = 0; static unsigned n_total_processes = 0; static unsigned n_total_threads = 0; static const char *proc = NULL; static int quit_fd = -1, canary_fd = -1; static pthread_t canary_thread_id = 0, watchdog_thread_id = 0; static volatile uint32_t refuse_until = 0; static int start_canary(void); static void stop_canary(void); static const char *get_proc_path(void) { /* Useful for chroot environments */ if (proc) return proc; return "/proc"; } static char* get_user_name(uid_t uid, char *user, size_t len) { struct passwd *pw; if ((pw = getpwuid(uid))) { strncpy(user, pw->pw_name, len-1); user[len-1] = 0; return user; } snprintf(user, len-1, "%llu", (unsigned long long) uid); user[len-1] = 0; return user; } static int read_starttime(pid_t pid, pid_t tid, unsigned long long *st) { char fn[128], line[256], *p; int r; FILE *f; if (tid != 0) assert_se(snprintf(fn, sizeof(fn)-1, "%s/%llu/task/%llu/stat", get_proc_path(), (unsigned long long) pid, (unsigned long long) tid) < (int) (sizeof(fn)-1)); else assert_se(snprintf(fn, sizeof(fn)-1, "%s/%llu/stat", get_proc_path(), (unsigned long long) pid) < (int) (sizeof(fn)-1)); fn[sizeof(fn)-1] = 0; if (!(f = fopen(fn, "r"))) return -errno; if (!(fgets(line, sizeof(line), f))) { r = -errno; fclose(f); return r; } fclose(f); /* Let's skip the pid and comm fields. The latter is enclosed * in () but does not escape any () in its value, so let's * skip over it manually */ if (!(p = strrchr(line, ')'))) return -EIO; p++; if (sscanf(p, " " "%*c " /* state */ "%*d " /* ppid */ "%*d " /* pgrp */ "%*d " /* session */ "%*d " /* tty_nr */ "%*d " /* tpgid */ "%*u " /* flags */ "%*u " /* minflt */ "%*u " /* cminflt */ "%*u " /* majflt */ "%*u " /* cmajflt */ "%*u " /* utime */ "%*u " /* stime */ "%*d " /* cutime */ "%*d " /* cstime */ "%*d " /* priority */ "%*d " /* nice */ "%*d " /* num_threads */ "%*d " /* itrealvalue */ "%llu " /* starttime */, st) != 1) return -EIO; return 0; } static void free_thread(struct thread *t) { free(t); } static void free_process(struct process *p) { struct thread *t; while ((t = p->threads)) { p->threads = t->next; free_thread(t); } free(p); } static void free_user(struct rtkit_user *u) { struct process *p; while ((p = u->processes)) { u->processes = p->next; free_process(p); } free(u); } static bool user_in_burst(struct rtkit_user *u) { time_t now = time(NULL); return now < u->timestamp + (time_t) actions_burst_sec; } static bool verify_burst(struct rtkit_user *u) { if (!user_in_burst(u)) { /* Restart burst phase */ time(&u->timestamp); u->n_actions = 0; return true; } if (u->n_actions >= actions_per_burst_max) { char user[64]; syslog(LOG_WARNING, "Warning: Reached burst limit for user '%s', denying request.\n", get_user_name(u->uid, user, sizeof(user))); return false; } u->n_actions++; return true; } static int find_user(struct rtkit_user **_u, uid_t uid) { struct rtkit_user *u; for (u = users; u; u = u->next) if (u->uid == uid) { *_u = u; return 0; } if (n_users >= users_max) { syslog(LOG_WARNING, "Warning: Reached maximum concurrent user limit, denying request.\n"); return -EBUSY; } if (!(u = malloc(sizeof(struct rtkit_user)))) return -ENOMEM; u->uid = uid; u->timestamp = time(NULL); u->n_actions = 0; u->processes = NULL; u->n_processes = u->n_threads = 0; u->next = users; users = u; n_users++; *_u = u; return 0; } static int find_process(struct process** _p, struct rtkit_user *u, pid_t pid, unsigned long long starttime) { struct process *p; for (p = u->processes; p; p = p->next) if (p->pid == pid && p->starttime == starttime) { *_p = p; return 0; } if (u->n_processes >= processes_per_user_max) { char user[64]; syslog(LOG_WARNING, "Warning: Reached maximum concurrent process limit for user '%s', denying request.\n", get_user_name(u->uid, user, sizeof(user))); return -EBUSY; } if (!(p = malloc(sizeof(struct process)))) return -ENOMEM; p->pid = pid; p->starttime = starttime; p->threads = NULL; p->next = u->processes; u->processes = p; u->n_processes++; n_total_processes++; *_p = p; return 0; } static int find_thread(struct thread** _t, struct rtkit_user *u, struct process *p, pid_t pid, unsigned long long starttime) { struct thread *t; for (t = p->threads; t; t = t->next) if (t->pid == pid && t->starttime == starttime) { *_t = t; return 0; } if (u->n_threads >= threads_per_user_max) { char user[64]; syslog(LOG_WARNING, "Warning: Reached maximum concurrent threads limit for user '%s', denying request.\n", get_user_name(u->uid, user, sizeof(user))); return -EBUSY; } if (!(t = malloc(sizeof(struct thread)))) return -ENOMEM; t->pid = pid; t->starttime = starttime; t->next = p->threads; t->priority = (unsigned) -1; t->nice_level = 0; p->threads = t; u->n_threads++; n_total_threads++; *_t = t; return 0; } static bool thread_relevant(struct process *p, struct thread *t, bool reset) { unsigned long long st; int r; /* This checks if a thread still matters to us, i.e. if its * PID still refers to the same thread and if it is still high * priority or real time */ if ((r = read_starttime(p->pid, t->pid, &st)) < 0) { /* Did the thread die? */ if (r == -ENOENT) return FALSE; syslog(LOG_WARNING, "Warning: failed to read start time: %s\n", strerror(-r)); return FALSE; } /* Did the thread get replaced by another thread? */ if (st != t->starttime) return FALSE; /* If suspended, don't verify scheduling unless it's a reset. */ if (suspended && !reset) return TRUE; if ((r = sched_getscheduler(t->pid)) < 0) { /* Maybe it died right now? */ if (errno == ESRCH) return FALSE; syslog(LOG_WARNING, "Warning: failed to read scheduler policy: %s\n", strerror(errno)); return FALSE; } /* Is this a realtime thread? */ r &= ~SCHED_RESET_ON_FORK; if (r == SCHED_RR || r == SCHED_FIFO) return TRUE; errno = 0; r = getpriority(PRIO_PROCESS, t->pid); if (errno != 0) { /* Maybe it died right now? */ if (errno == ESRCH) return FALSE; syslog(LOG_WARNING, "Warning: failed to read nice level: %s\n", strerror(errno)); return FALSE; } /* Is this a high priority thread? */ if (r < 0) return TRUE; return FALSE; } static void thread_gc(struct rtkit_user *u, struct process *p, bool reset) { struct thread *t, *n, *l; /* Cleanup dead theads of a specific user we don't need to keep track about anymore */ for (l = NULL, t = p->threads; t; t = n) { n = t->next; if (!thread_relevant(p, t, reset)) { free_thread(t); if (l) l->next = n; else p->threads = n; assert(u->n_threads >= 1); u->n_threads--; assert(n_total_threads >= 1); n_total_threads--; } else l = t; } assert(!p->threads || u->n_threads); } static void process_gc(struct rtkit_user *u, bool reset) { struct process *p, *n, *l; /* Cleanup dead processes of a specific user we don't need to keep track about anymore */ for (l = NULL, p = u->processes; p; p = n) { n = p->next; thread_gc(u, p, reset); if (!p->threads) { free_process(p); if (l) l->next = n; else u->processes = n; assert(u->n_processes >= 1); u->n_processes--; assert(n_total_processes >= 1); n_total_processes--; } else l = p; } assert(!u->processes == !u->n_processes); } static void user_gc(bool reset) { struct rtkit_user *u, *n, *l; /* Cleanup all users we don't need to keep track about anymore */ for (l = NULL, u = users; u; u = n) { n = u->next; process_gc(u, reset); if (!u->processes && !user_in_burst(u)) { free_user(u); if (l) l->next = n; else users = n; assert(n_users >= 1); n_users--; } else l = u; } assert(!users == !n_users); } static bool startswith(const char *s, const char *prefix) { return strncmp(s, prefix, strlen(prefix)) == 0; } static int self_set_realtime(unsigned priority) { struct sched_param param; int r; memset(¶m, 0, sizeof(param)); param.sched_priority = priority; if (sched_setscheduler(0, sched_policy|SCHED_RESET_ON_FORK, ¶m) < 0) { r = -errno; syslog(LOG_ERR, "Failed to make ourselves RT: %s\n", strerror(errno)); goto finish; } r = 0; finish: return r; } static void self_drop_realtime(int nice_level) { struct sched_param param; memset(¶m, 0, sizeof(param)); if (sched_setscheduler(0, SCHED_OTHER, ¶m) < 0) syslog(LOG_WARNING, "Warning: Failed to reset scheduling to SCHED_OTHER: %s\n", strerror(errno)); if (setpriority(PRIO_PROCESS, 0, nice_level) < 0) syslog(LOG_WARNING, "Warning: Failed to reset nice level to %u: %s\n", our_nice_level, strerror(errno)); } /* Verifies that RLIMIT_RTTIME is set for the specified process */ static int verify_process_rttime(struct process *p) { char fn[128]; FILE *f; int r; bool good = false; assert_se(snprintf(fn, sizeof(fn)-1, "%s/%llu/limits", get_proc_path(), (unsigned long long) p->pid) < (int) (sizeof(fn)-1)); fn[sizeof(fn)-1] = 0; if (!(f = fopen(fn, "r"))) { r = -errno; syslog(LOG_ERR, "Failed to open '%s': %s\n", fn, strerror(errno)); return r; } for (;;) { char line[128]; char soft[32], hard[32]; unsigned long long rttime; char *e = NULL; if (!fgets(line, sizeof(line), f)) break; if (!startswith(line, "Max realtime timeout")) continue; if (sscanf(line + 20, "%s %s", soft, hard) != 2) { syslog(LOG_WARNING, "Warning: parse failure in %s.\n", fn); break; } errno = 0; rttime = strtoll(hard, &e, 10); if (errno != 0 || !e || *e != 0) break; if (rttime <= rttime_usec_max) good = true; break; } fclose(f); return good ? 0 : -EPERM; } static int verify_process_user(struct rtkit_user *u, struct process *p) { char fn[128]; int r; struct stat st; assert_se(snprintf(fn, sizeof(fn)-1, "%s/%llu", get_proc_path(), (unsigned long long) p->pid) < (int) (sizeof(fn)-1)); fn[sizeof(fn)-1] = 0; memset(&st, 0, sizeof(st)); if (stat(fn, &st) < 0) { r = -errno; if (r != -ENOENT) syslog(LOG_WARNING, "Warning: Failed to stat() file '%s': %s\n", fn, strerror(-r)); return r; } return st.st_uid == u->uid ? 0 : -EPERM; } static int verify_process_starttime(struct process *p) { unsigned long long st; int r; if ((r = read_starttime(p->pid, 0, &st)) < 0) { if (r != -ENOENT) syslog(LOG_WARNING, "Warning: Failed to read start time of process %llu: %s\n", (unsigned long long) p->pid, strerror(-r)); return r; } return st == p->starttime ? 0 : -EPERM; } static int verify_thread_starttime(struct process *p, struct thread *t) { unsigned long long st; int r; if ((r = read_starttime(p->pid, t->pid, &st)) < 0) { if (r != -ENOENT) syslog(LOG_WARNING, "Warning: Failed to read start time of thread %llu: %s\n", (unsigned long long) t->pid, strerror(-r)); return r; } return st == t->starttime ? 0 : -EPERM; } static int thread_reset(pid_t tid) { struct sched_param param; int r = 0; memset(¶m, 0, sizeof(param)); param.sched_priority = 0; if (sched_setscheduler(tid, SCHED_OTHER, ¶m) < 0) { if (errno != ESRCH) syslog(LOG_WARNING, "Warning: Failed to reset scheduling to SCHED_OTHER for thread %llu: %s\n", (unsigned long long) tid, strerror(errno)); r = -1; } if (setpriority(PRIO_PROCESS, tid, 0) < 0) { if (errno != ESRCH) syslog(LOG_WARNING, "Warning: Failed to reset nice level to 0 for thread %llu: %s\n", (unsigned long long) tid, strerror(errno)); r = -1; } return r; } static int process_set_realtime(struct rtkit_user *u, struct process *p, struct thread *t, unsigned priority) { int r; struct sched_param param; char user[64]; if ((int) priority < sched_get_priority_min(sched_policy) || (int) priority > sched_get_priority_max(sched_policy)) return -EINVAL; /* We always want to be able to get a higher RT priority than * the client */ if (priority >= our_realtime_priority || priority > max_realtime_priority) return -EPERM; /* Temporarily become a realtime process. We do this to make * sure that our verification code is not preempted by an evil * client's code which might have gotten RT through * us. */ if ((r = self_set_realtime(our_realtime_priority)) < 0) return r; /* Let's make sure that everything is alright before we make * the process realtime */ if ((r = verify_process_user(u, p)) < 0 || (r = verify_process_starttime(p)) < 0 || (r = verify_process_rttime(p)) < 0 || (r = verify_thread_starttime(p, t)) < 0) goto finish; /* Ok, everything seems to be in order, now, let's do it */ memset(¶m, 0, sizeof(param)); param.sched_priority = (int) priority; if (sched_setscheduler(t->pid, sched_policy|SCHED_RESET_ON_FORK, ¶m) < 0) { r = -errno; syslog(LOG_ERR, "Failed to make thread %llu RT: %s\n", (unsigned long long) t->pid, strerror(errno)); goto finish; } /* We do some sanity checks afterwards, to verify that the * caller didn't play games with us and replaced the process * behind the PID */ if ((r = verify_thread_starttime(p, t)) < 0 || (r = verify_process_rttime(p)) < 0 || (r = verify_process_starttime(p)) < 0 || (r = verify_process_user(u, p)) < 0) { thread_reset(t->pid); goto finish; } syslog(LOG_INFO, "Successfully made thread %llu of process %llu owned by '%s' RT at priority %u.\n", (unsigned long long) t->pid, (unsigned long long) p->pid, get_user_name(u->uid, user, sizeof(user)), priority); r = 0; finish: self_drop_realtime(our_nice_level); return r; } static int process_set_realtime_request(struct rtkit_user *u, struct process *p, struct thread *t, int priority) { int r; /* Make sure users don't flood us with requests */ if (!verify_burst(u)) return -EBUSY; if (suspended) return -EBUSY; if (!(r = process_set_realtime(u, p, t, priority))) t->priority = priority; return r; } static int process_set_high_priority(struct rtkit_user *u, struct process *p, struct thread *t, int nice_level) { int r; struct sched_param param; char user[64]; if (nice_level < PRIO_MIN || nice_level >= PRIO_MAX) return -EINVAL; if (nice_level < min_nice_level) return -EPERM; /* Temporarily become a realtime process */ if ((r = self_set_realtime(our_realtime_priority)) < 0) return r; /* Let's make sure that everything is alright before we make * the process high priority */ if ((r = verify_process_user(u, p)) < 0 || (r = verify_process_starttime(p)) < 0 || (r = verify_thread_starttime(p, t)) < 0) goto finish; /* Ok, everything seems to be in order, now, let's do it */ memset(¶m, 0, sizeof(param)); param.sched_priority = 0; if (sched_setscheduler(t->pid, SCHED_OTHER|SCHED_RESET_ON_FORK, ¶m) < 0) { r = -errno; syslog(LOG_ERR, "Failed to make process %llu SCHED_NORMAL: %s\n", (unsigned long long) t->pid, strerror(errno)); goto finish; } if (setpriority(PRIO_PROCESS, t->pid, nice_level) < 0) { r = -errno; syslog(LOG_ERR, "Failed to set nice level of process %llu to %i: %s\n", (unsigned long long) t->pid, nice_level, strerror(errno)); goto finish; } if ((r = verify_thread_starttime(p, t)) < 0 || (r = verify_process_starttime(p)) < 0 || (r = verify_process_user(u, p)) < 0) { thread_reset(t->pid); goto finish; } syslog(LOG_INFO, "Successfully made thread %llu of process %llu owned by '%s' high priority at nice level %i.\n", (unsigned long long) t->pid, (unsigned long long) p->pid, get_user_name(u->uid, user, sizeof(user)), nice_level); r = 0; finish: self_drop_realtime(our_nice_level); return r; } static int process_set_high_priority_request(struct rtkit_user *u, struct process *p, struct thread *t, int nice_level) { int r; /* Make sure users don't flood us with requests */ if (!verify_burst(u)) return -EBUSY; if (suspended) return -EBUSY; if (!(r = process_set_high_priority(u, p, t, nice_level))) t->nice_level = nice_level; return r; } static int thread_resume(struct rtkit_user *u, struct process *p, struct thread *t) { if (t->priority != (unsigned) -1) return process_set_realtime(u, p, t, t->priority); else return process_set_high_priority(u, p, t, t->nice_level); } static void reset_known(void) { struct rtkit_user *u; struct process *p; struct thread *t; unsigned n_demoted = 0; syslog(LOG_INFO, "Demoting known real-time threads.\n"); for (u = users; u; u = u->next) for (p = u->processes; p; p = p->next) for (t = p->threads; t; t = t->next) if (verify_process_user(u, p) >= 0 && verify_process_starttime(p) >= 0 && verify_thread_starttime(p, t) >= 0) if (thread_reset(t->pid) >= 0) { syslog(LOG_NOTICE, "Successfully demoted thread %llu of process %llu.\n", (unsigned long long) t->pid, (unsigned long long) p->pid); n_demoted++; } syslog(LOG_NOTICE, "Demoted %u threads.\n", n_demoted); } static int reset_all(void) { DIR *pd; int r; unsigned n_demoted = 0; /* Goes through /proc and demotes *all* threads to * SCHED_OTHER */ syslog(LOG_INFO, "Demoting known and unknown real-time threads.\n"); if (!(pd = opendir(get_proc_path()))) { r = -errno; syslog(LOG_ERR, "opendir(%s) failed: %s\n", get_proc_path(), strerror(errno)); return r; } for (;;) { const struct dirent *pde; char *e = NULL; unsigned long long pid; char fn[128]; DIR *td; struct stat st; if (!(pde = readdir(pd))) break; if (!(pde->d_type & DT_DIR)) continue; errno = 0; pid = strtoull(pde->d_name, &e, 10); if (errno != 0 || !e || *e != 0) continue; if ((pid_t) pid == getpid() || pid == 1) continue; assert_se(snprintf(fn, sizeof(fn)-1, "%s/%llu", get_proc_path(), pid) < (int) (sizeof(fn)-1)); fn[sizeof(fn)-1] = 0; if (stat(fn, &st) < 0) { if (errno != ENOENT) syslog(LOG_WARNING, "Warning: stat(%s) failed: %s\n", fn, strerror(errno)); continue; } if (!S_ISDIR(st.st_mode)) continue; if (!canary_demote_root && st.st_uid == 0) continue; assert_se(snprintf(fn, sizeof(fn)-1, "%s/%llu/task", get_proc_path(), pid) < (int) (sizeof(fn)-1)); fn[sizeof(fn)-1] = 0; if (!(td = opendir(fn))) continue; for (;;) { const struct dirent *tde; unsigned long long tid; if (!(tde = readdir(td))) break; if (!(tde->d_type & DT_DIR)) continue; e = NULL; errno = 0; tid = strtoull(tde->d_name, &e, 10); if (errno != 0 || !e || *e != 0) continue; if ((r = sched_getscheduler(tid)) < 0) { if (errno != ESRCH) syslog(LOG_WARNING, "Warning: sched_getscheduler() failed: %s\n", strerror(errno)); continue; } if (r == SCHED_FIFO || r == SCHED_RR || r == (SCHED_FIFO|SCHED_RESET_ON_FORK) || r == (SCHED_RR|SCHED_RESET_ON_FORK)) if (thread_reset((pid_t) tid) >= 0) { syslog(LOG_NOTICE, "Successfully demoted thread %llu of process %llu.\n", (unsigned long long) tid, (unsigned long long) pid); n_demoted++; } } closedir(td); } closedir(pd); syslog(LOG_NOTICE, "Demoted %u threads.\n", n_demoted); return 0; } static void suspend(void) { if (suspended) return ; suspended = TRUE; stop_canary(); reset_known(); } static void resume(void) { struct rtkit_user *u; struct process *p; struct thread *t; unsigned n_resumed = 0; if (!suspended) return; syslog(LOG_INFO, "Resuming known real-time threads.\n"); /* It is not possible for there to be more resumable processes and * threads than user limits, as suspended processes and threads can * only be created when non-suspended, subject to normal enforcement. */ for (u = users; u; u = u->next) { /* Force restart burst phase, extending time window. */ time(&u->timestamp); for (p = u->processes; p; p = p->next) { for (t = p->threads; t; t = t->next) { if (thread_resume(u, p, t) >= 0) { n_resumed++; } } } } syslog(LOG_NOTICE, "Resumed scheduling %u threads.\n", n_resumed); start_canary(); suspended = FALSE; } static int logind_inhibit_sleep(DBusConnection *connection) { DBusError error; DBusMessage *m, *r; const char *arg_what = "sleep"; const char *arg_who = "Realtime Kit"; const char *arg_why = "Demote realtime scheduling and stop canary."; const char *arg_mode = "delay"; int fd = -1; dbus_error_init(&error); assert_se(m = dbus_message_new_method_call( "org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", "Inhibit")); assert_se(dbus_message_append_args( m, DBUS_TYPE_STRING, &arg_what, DBUS_TYPE_STRING, &arg_who, DBUS_TYPE_STRING, &arg_why, DBUS_TYPE_STRING, &arg_mode, DBUS_TYPE_INVALID)); r = dbus_connection_send_with_reply_and_block(connection, m, -1, &error); dbus_message_unref(m); if (!r) goto finish; if (dbus_set_error_from_message(&error, r)) { syslog(LOG_NOTICE, "Could not setup logind system-suspend handling: %s", error.message); goto finish; } if (!dbus_message_get_args( r, &error, DBUS_TYPE_UNIX_FD, &fd, DBUS_TYPE_INVALID)) { syslog(LOG_DEBUG, "Failed to parse inhibit sleep reply: %s", error.message); } finish: if (r) dbus_message_unref(r); dbus_error_free(&error); return fd; } /* This mimics dbus_bus_get_unix_user() */ static unsigned long get_unix_process_id( DBusConnection *connection, const char *name, DBusError *error) { DBusMessage *m, *r; uint32_t pid = (uint32_t) -1; assert_se(m = dbus_message_new_method_call( DBUS_SERVICE_DBUS, DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, "GetConnectionUnixProcessID")); assert_se(dbus_message_append_args( m, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID)); r = dbus_connection_send_with_reply_and_block(connection, m, -1, error); dbus_message_unref (m); if (!r) goto finish; if (dbus_set_error_from_message(error, r)) goto finish; if (!dbus_message_get_args( r, error, DBUS_TYPE_UINT32, &pid, DBUS_TYPE_INVALID)) { pid = (uint32_t) -1; goto finish; } finish: if (r) dbus_message_unref(r); return (unsigned long) pid; } static int lookup_client( struct rtkit_user **_u, struct process **_p, struct thread **_t, DBusConnection *c, DBusMessage *m, pid_t pid, pid_t tid) { DBusError error; int r; unsigned long uid; unsigned long long starttime; struct rtkit_user *u; struct process *p; struct thread *t; dbus_error_init(&error); /* Determine caller credentials */ if ((uid = dbus_bus_get_unix_user(c, dbus_message_get_sender(m), &error)) == (unsigned long) -1) { syslog(LOG_ERR, "dbus_message_get_unix_user() failed: %s\n", error.message); r = -EIO; goto fail; } if (pid == (pid_t) -1 && (pid = get_unix_process_id(c, dbus_message_get_sender(m), &error)) == (pid_t) -1) { syslog(LOG_ERR, "get_unix_process_id() failed: %s\n", error.message); r = -EIO; goto fail; } /* Find or create user structure */ if ((r = find_user(&u, (uid_t) uid) < 0)) goto fail; /* Find or create process structure */ if ((r = read_starttime((pid_t) pid, 0, &starttime)) < 0) goto fail; if ((r = find_process(&p, u, (pid_t) pid, starttime)) < 0) goto fail; /* Find or create thread structure */ if (tid == 0) tid = p->pid; if ((r = read_starttime(p->pid, tid, &starttime)) < 0) goto fail; if ((r = find_thread(&t, u, p, (pid_t) tid, starttime)) < 0) goto fail; *_u = u; *_p = p; *_t = t; return 0; fail: dbus_error_free(&error); return r; } static const char *translate_error_forward(int error) { switch (error) { case -EPERM: case -EACCES: case -EBUSY: return DBUS_ERROR_ACCESS_DENIED; case -ENOMEM: return DBUS_ERROR_NO_MEMORY; default: return DBUS_ERROR_FAILED; } } static int translate_error_backwards(const char *name) { if (strcmp(name, DBUS_ERROR_NO_MEMORY) == 0) return -ENOMEM; if (strcmp(name, DBUS_ERROR_SERVICE_UNKNOWN) == 0 || strcmp(name, DBUS_ERROR_NAME_HAS_NO_OWNER) == 0) return -ENOENT; if (strcmp(name, DBUS_ERROR_ACCESS_DENIED) == 0 || strcmp(name, DBUS_ERROR_AUTH_FAILED) == 0) return -EACCES; return -EIO; } static int verify_polkit(DBusConnection *c, struct rtkit_user *u, struct process *p, const char *action) { DBusError error; DBusMessage *m = NULL, *r = NULL; const char *unix_process = "unix-process"; const char *pid = "pid"; const char *uid = "uid"; const char *start_time = "start-time"; const char *cancel_id = ""; uint32_t flags = 0; uint32_t pid_u32 = p->pid; uint32_t uid_u32 = (uint32_t)u->uid; DBusMessageIter iter_msg, iter_struct, iter_array, iter_dict, iter_variant; uint64_t start_time_u64 = p->starttime; int ret; dbus_bool_t authorized = FALSE; dbus_error_init(&error); assert_se(m = dbus_message_new_method_call( "org.freedesktop.PolicyKit1", "/org/freedesktop/PolicyKit1/Authority", "org.freedesktop.PolicyKit1.Authority", "CheckAuthorization")); dbus_message_iter_init_append(m, &iter_msg); assert_se(dbus_message_iter_open_container(&iter_msg, DBUS_TYPE_STRUCT, NULL, &iter_struct)); assert_se(dbus_message_iter_append_basic(&iter_struct, DBUS_TYPE_STRING, &unix_process)); assert_se(dbus_message_iter_open_container(&iter_struct, DBUS_TYPE_ARRAY, "{sv}", &iter_array)); assert_se(dbus_message_iter_open_container(&iter_array, DBUS_TYPE_DICT_ENTRY, NULL, &iter_dict)); assert_se(dbus_message_iter_append_basic(&iter_dict, DBUS_TYPE_STRING, &pid)); assert_se(dbus_message_iter_open_container(&iter_dict, DBUS_TYPE_VARIANT, "u", &iter_variant)); assert_se(dbus_message_iter_append_basic(&iter_variant, DBUS_TYPE_UINT32, &pid_u32)); assert_se(dbus_message_iter_close_container(&iter_dict, &iter_variant)); assert_se(dbus_message_iter_close_container(&iter_array, &iter_dict)); assert_se(dbus_message_iter_open_container(&iter_array, DBUS_TYPE_DICT_ENTRY, NULL, &iter_dict)); assert_se(dbus_message_iter_append_basic(&iter_dict, DBUS_TYPE_STRING, &start_time)); assert_se(dbus_message_iter_open_container(&iter_dict, DBUS_TYPE_VARIANT, "t", &iter_variant)); assert_se(dbus_message_iter_append_basic(&iter_variant, DBUS_TYPE_UINT64, &start_time_u64)); assert_se(dbus_message_iter_close_container(&iter_dict, &iter_variant)); assert_se(dbus_message_iter_close_container(&iter_array, &iter_dict)); assert_se(dbus_message_iter_open_container(&iter_array, DBUS_TYPE_DICT_ENTRY, NULL, &iter_dict)); assert_se(dbus_message_iter_append_basic(&iter_dict, DBUS_TYPE_STRING, &uid)); assert_se(dbus_message_iter_open_container(&iter_dict, DBUS_TYPE_VARIANT, "u", &iter_variant)); assert_se(dbus_message_iter_append_basic(&iter_variant, DBUS_TYPE_UINT32, &uid_u32)); assert_se(dbus_message_iter_close_container(&iter_dict, &iter_variant)); assert_se(dbus_message_iter_close_container(&iter_array, &iter_dict)); assert_se(dbus_message_iter_close_container(&iter_struct, &iter_array)); assert_se(dbus_message_iter_close_container(&iter_msg, &iter_struct)); assert_se(dbus_message_iter_append_basic(&iter_msg, DBUS_TYPE_STRING, &action)); assert_se(dbus_message_iter_open_container(&iter_msg, DBUS_TYPE_ARRAY, "{ss}", &iter_array)); assert_se(dbus_message_iter_close_container(&iter_msg, &iter_array)); assert_se(dbus_message_iter_append_basic(&iter_msg, DBUS_TYPE_UINT32, &flags)); assert_se(dbus_message_iter_append_basic(&iter_msg, DBUS_TYPE_STRING, &cancel_id)); if (!(r = dbus_connection_send_with_reply_and_block(c, m, -1, &error))) { ret = translate_error_backwards(error.name); goto finish; } if (dbus_set_error_from_message(&error, r)) { ret = translate_error_backwards(error.name); goto finish; } if (!dbus_message_iter_init(r, &iter_msg) || dbus_message_iter_get_arg_type(&iter_msg) != DBUS_TYPE_STRUCT) { ret = -EIO; goto finish; } dbus_message_iter_recurse(&iter_msg, &iter_struct); if (dbus_message_iter_get_arg_type(&iter_struct) != DBUS_TYPE_BOOLEAN) { ret = -EIO; goto finish; } dbus_message_iter_get_basic(&iter_struct, &authorized); ret = authorized ? 0 : -EPERM; finish: if (m) dbus_message_unref(m); if (r) dbus_message_unref(r); if (error.message) syslog(LOG_WARNING, "Warning: PolicyKit call failed: %s\n", error.message); dbus_error_free(&error); return ret; } static int verify_canary_refusal(void) { struct timespec now; assert_se(clock_gettime(CLOCK_MONOTONIC, &now) == 0); if (now.tv_sec < (time_t) refuse_until) { syslog(LOG_WARNING, "Recovering from system lockup, not allowing further RT threads.\n"); return -EPERM; } return 0; } static void add_variant( DBusMessage *m, int type, const void *data) { DBusMessageIter iter, sub; char t[2]; t[0] = (char) type; t[1] = 0; dbus_message_iter_init_append(m, &iter); assert_se(dbus_message_iter_open_container(&iter, DBUS_TYPE_VARIANT, t, &sub)); assert_se(dbus_message_iter_append_basic(&sub, type, data)); assert_se(dbus_message_iter_close_container(&iter, &sub)); } static int handle_dbus_prop_get(const char* property, DBusMessage *r) { if (strcmp(property, "RTTimeUSecMax") == 0) add_variant(r, DBUS_TYPE_INT64, &rttime_usec_max); else if (strcmp(property, "MaxRealtimePriority") == 0) add_variant(r, DBUS_TYPE_INT32, &max_realtime_priority); else if (strcmp(property, "MinNiceLevel") == 0) add_variant(r, DBUS_TYPE_INT32, &min_nice_level); else return -1; return 0; } static int handle_dbus_prop_get_all(DBusMessage *r) { DBusMessageIter iter, dict_iter; struct { const char *name; int type; const char *type_string; void *value; } props[] = { { .name = "RTTimeUSecMax", .type = DBUS_TYPE_INT64, .type_string = DBUS_TYPE_INT64_AS_STRING, .value = &rttime_usec_max, }, { .name = "MaxRealtimePriority", .type = DBUS_TYPE_INT32, .type_string = DBUS_TYPE_INT32_AS_STRING, .value = &max_realtime_priority, }, { .name = "MinNiceLevel", .type = DBUS_TYPE_INT32, .type_string = DBUS_TYPE_INT32_AS_STRING, .value = &min_nice_level, } }; size_t i; dbus_message_iter_init_append(r, &iter); assert_se(dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict_iter)); for (i = 0; i < ARRAY_SIZE(props); i++) { DBusMessageIter dict_entry_iter, sub; assert_se(dbus_message_iter_open_container(&dict_iter, DBUS_TYPE_DICT_ENTRY, NULL, &dict_entry_iter)); assert_se(dbus_message_iter_append_basic(&dict_entry_iter, DBUS_TYPE_STRING, &props[i].name)); assert_se(dbus_message_iter_open_container(&dict_entry_iter, DBUS_TYPE_VARIANT, props[i].type_string, &sub)); assert_se(dbus_message_iter_append_basic(&sub, props[i].type, props[i].value)); assert_se(dbus_message_iter_close_container(&dict_entry_iter, &sub)); assert_se(dbus_message_iter_close_container(&dict_iter, &dict_entry_iter)); } assert_se(dbus_message_iter_close_container(&iter, &dict_iter)); return 0; } static DBusHandlerResult dbus_handler(DBusConnection *c, DBusMessage *m, void *userdata) { DBusError error; DBusMessage *r = NULL; int is2 = 0; dbus_error_init(&error); /* We garbage collect on every user call */ user_gc(FALSE); if (dbus_message_is_method_call(m, "org.freedesktop.RealtimeKit1", "MakeThreadRealtime") || (is2 = dbus_message_is_method_call(m, "org.freedesktop.RealtimeKit1", "MakeThreadRealtimeWithPID"))) { uint64_t thread, process = (uint64_t) -1; uint32_t priority; struct rtkit_user *u; struct process *p; struct thread *t; int ret; if ((ret = verify_canary_refusal()) < 0) { assert_se(r = dbus_message_new_error_printf(m, translate_error_forward(ret), "%s", strerror(-ret))); goto finish; } if (is2) ret = dbus_message_get_args(m, &error, DBUS_TYPE_UINT64, &process, DBUS_TYPE_UINT64, &thread, DBUS_TYPE_UINT32, &priority, DBUS_TYPE_INVALID); else ret = dbus_message_get_args(m, &error, DBUS_TYPE_UINT64, &thread, DBUS_TYPE_UINT32, &priority, DBUS_TYPE_INVALID); if (!ret) { syslog(LOG_DEBUG, "Failed to parse MakeThreadRealtime() method call: %s\n", error.message); assert_se(r = dbus_message_new_error(m, error.name, error.message)); goto finish; } if ((ret = lookup_client(&u, &p, &t, c, m, (pid_t)process, (pid_t) thread)) < 0) { syslog(LOG_DEBUG, "Failed to look up client: %s\n", strerror(-ret)); assert_se(r = dbus_message_new_error_printf(m, translate_error_forward(ret), "%s", strerror(-ret))); goto finish; } if ((ret = verify_polkit(c, u, p, "org.freedesktop.RealtimeKit1.acquire-real-time")) < 0) { assert_se(r = dbus_message_new_error_printf(m, translate_error_forward(ret), "%s", strerror(-ret))); goto finish; } if ((ret = process_set_realtime_request(u, p, t, priority))) { assert_se(r = dbus_message_new_error_printf(m, translate_error_forward(ret), "%s", strerror(-ret))); goto finish; } assert_se(r = dbus_message_new_method_return(m)); } else if (dbus_message_is_method_call(m, "org.freedesktop.RealtimeKit1", "MakeThreadHighPriority") || (is2 = dbus_message_is_method_call(m, "org.freedesktop.RealtimeKit1", "MakeThreadHighPriorityWithPID"))) { uint64_t thread, process = (uint64_t) -1; int32_t nice_level; struct rtkit_user *u; struct process *p; struct thread *t; int ret; if ((ret = verify_canary_refusal()) < 0) { assert_se(r = dbus_message_new_error_printf(m, translate_error_forward(ret), "%s", strerror(-ret))); goto finish; } if (is2) ret = dbus_message_get_args(m, &error, DBUS_TYPE_UINT64, &process, DBUS_TYPE_UINT64, &thread, DBUS_TYPE_INT32, &nice_level, DBUS_TYPE_INVALID); else ret = dbus_message_get_args(m, &error, DBUS_TYPE_UINT64, &thread, DBUS_TYPE_INT32, &nice_level, DBUS_TYPE_INVALID); if (!ret) { syslog(LOG_DEBUG, "Failed to parse MakeThreadHighPriority() method call: %s\n", error.message); assert_se(r = dbus_message_new_error(m, error.name, error.message)); goto finish; } if ((ret = lookup_client(&u, &p, &t, c, m, (pid_t)process, (pid_t) thread)) < 0) { syslog(LOG_DEBUG, "Failed to look up client: %s\n", strerror(-ret)); assert_se(r = dbus_message_new_error_printf(m, translate_error_forward(ret), "%s", strerror(-ret))); goto finish; } if ((ret = verify_polkit(c, u, p, "org.freedesktop.RealtimeKit1.acquire-high-priority")) < 0) { assert_se(r = dbus_message_new_error_printf(m, translate_error_forward(ret), "%s", strerror(-ret))); goto finish; } if ((ret = process_set_high_priority_request(u, p, t, nice_level))) { assert_se(r = dbus_message_new_error_printf(m, translate_error_forward(ret), "%s", strerror(-ret))); goto finish; } assert_se(r = dbus_message_new_method_return(m)); } else if (dbus_message_is_method_call(m, "org.freedesktop.RealtimeKit1", "ResetAll")) { reset_all(); user_gc(TRUE); assert_se(r = dbus_message_new_method_return(m)); } else if (dbus_message_is_method_call(m, "org.freedesktop.RealtimeKit1", "ResetKnown")) { reset_known(); user_gc(TRUE); assert_se(r = dbus_message_new_method_return(m)); } else if (dbus_message_is_method_call(m, "org.freedesktop.RealtimeKit1", "Suspend")) { suspend(); assert_se(r = dbus_message_new_method_return(m)); } else if (dbus_message_is_method_call(m, "org.freedesktop.RealtimeKit1", "Resume")) { resume(); assert_se(r = dbus_message_new_method_return(m)); } else if (dbus_message_is_method_call(m, "org.freedesktop.RealtimeKit1", "Exit")) { assert_se(r = dbus_message_new_method_return(m)); assert_se(dbus_connection_send(c, r, NULL)); dbus_message_unref(r); r = NULL; dbus_connection_close(c); } else if (dbus_message_is_method_call(m, "org.freedesktop.DBus.Properties", "Get")) { const char *interface, *property; if (!dbus_message_get_args(m, &error, DBUS_TYPE_STRING, &interface, DBUS_TYPE_STRING, &property, DBUS_TYPE_INVALID)) { syslog(LOG_DEBUG, "Failed to parse property get call: %s\n", error.message); assert_se(r = dbus_message_new_error(m, error.name, error.message)); goto finish; } if (strcmp(interface, "org.freedesktop.RealtimeKit1") == 0) { assert_se(r = dbus_message_new_method_return(m)); if (handle_dbus_prop_get(property, r) < 0) { dbus_message_unref(r); assert_se(r = dbus_message_new_error_printf( m, DBUS_ERROR_UNKNOWN_PROPERTY, "Unknown property %s", property)); } } else assert_se(r = dbus_message_new_error_printf( m, DBUS_ERROR_UNKNOWN_PROPERTY, "Unknown interface %s", interface)); goto finish; } else if (dbus_message_is_method_call(m, "org.freedesktop.DBus.Properties", "GetAll")) { const char *interface; if (!dbus_message_get_args(m, &error, DBUS_TYPE_STRING, &interface, DBUS_TYPE_INVALID)) { syslog(LOG_DEBUG, "Failed to parse property get call: %s\n", error.message); assert_se(r = dbus_message_new_error(m, error.name, error.message)); goto finish; } if (strcmp(interface, "org.freedesktop.RealtimeKit1") == 0) { assert_se(r = dbus_message_new_method_return(m)); handle_dbus_prop_get_all(r); } else assert_se(r = dbus_message_new_error_printf( m, DBUS_ERROR_UNKNOWN_PROPERTY, "Unknown interface %s", interface)); } else if (dbus_message_is_method_call(m, "org.freedesktop.DBus.Introspectable", "Introspect")) { const char *xml = introspect_xml; assert_se(r = dbus_message_new_method_return(m)); assert_se(dbus_message_append_args( r, DBUS_TYPE_STRING, &xml, DBUS_TYPE_INVALID)); goto finish; } else return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; syslog(LOG_DEBUG, "Supervising %u threads of %u processes of %u users.\n", n_total_threads, n_total_processes, n_users); #ifdef HAVE_LIBSYSTEMD sd_notifyf(0, "STATUS=Supervising %u threads of %u processes of %u users.", n_total_threads, n_total_processes, n_users); #endif finish: if (r) { assert_se(dbus_connection_send(c, r, NULL)); dbus_message_unref(r); } dbus_error_free(&error); return DBUS_HANDLER_RESULT_HANDLED; } static DBusHandlerResult dbus_logind_handler(DBusConnection *c, DBusMessage *m, void *userdata) { if (dbus_message_is_signal(m, "org.freedesktop.login1.Manager", "PrepareForSleep")) { DBusError error; bool active; dbus_error_init(&error); if (dbus_message_get_args(m, &error, DBUS_TYPE_BOOLEAN, &active, DBUS_TYPE_INVALID)) { if (active) { suspend(); if (inhibit_sleep_fd >= 0) { close(inhibit_sleep_fd); inhibit_sleep_fd = -1; } } else { if (inhibit_sleep_fd < 0) inhibit_sleep_fd = logind_inhibit_sleep(c); resume(); } } else syslog(LOG_DEBUG, "Failed to parse signal argument: %s\n", error.message); dbus_error_free(&error); } else return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; return DBUS_HANDLER_RESULT_HANDLED; } static void setup_logind(DBusConnection *c) { DBusError error; inhibit_sleep_fd = logind_inhibit_sleep(c); if (inhibit_sleep_fd < 0) return; dbus_error_init(&error); dbus_bus_add_match(c, "type='signal',path='/org/freedesktop/login1',member='PrepareForSleep'", &error); if (dbus_error_is_set(&error)) { syslog(LOG_ERR, "Failed to add match for logind signals: %s\n", error.message); close(inhibit_sleep_fd); inhibit_sleep_fd = -1; dbus_error_free(&error); return; } assert_se(dbus_connection_add_filter(c, dbus_logind_handler, NULL, NULL)); syslog(LOG_INFO, "Handling system-suspend using logind.\n"); } static int setup_dbus(DBusConnection **c) { static const DBusObjectPathVTable vtable = { .message_function = dbus_handler, }; DBusError error; dbus_error_init(&error); if (!(*c = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error))) { syslog(LOG_ERR, "Failed to connect to system bus: %s\n", error.message); goto fail; } if (dbus_bus_request_name(*c, RTKIT_SERVICE_NAME, DBUS_NAME_FLAG_DO_NOT_QUEUE, &error) < 0) { syslog(LOG_ERR, "Failed to register name on bus: %s\n", error.message); goto fail; } assert_se(dbus_connection_register_object_path(*c, RTKIT_OBJECT_PATH, &vtable, NULL)); return 0; fail: dbus_error_free(&error); return -EIO; } static void block_all_signals(void) { sigset_t set; assert_se(sigfillset(&set) == 0); assert_se(pthread_sigmask(SIG_BLOCK, &set, NULL) == 0); } static void* canary_thread(void *data) { struct timespec last_cheep, now; struct pollfd pollfd; assert(canary_fd >= 0); assert(quit_fd >= 0); /* Make sure we are not disturbed by any signal */ block_all_signals(); self_drop_realtime(0); memset(&pollfd, 0, sizeof(pollfd)); pollfd.fd = quit_fd; pollfd.events = POLLIN; assert_se(clock_gettime(CLOCK_MONOTONIC, &now) == 0); last_cheep = now; syslog(LOG_DEBUG, "Canary thread running.\n"); for (;;) { int r; int64_t msec; msec = TIMESPEC_MSEC(last_cheep) + canary_cheep_msec - TIMESPEC_MSEC(now); if (msec < 0) msec = 0; r = poll(&pollfd, 1, (int) msec); assert_se(clock_gettime(CLOCK_MONOTONIC, &now) == 0); if (r < 0) { if (errno == EINTR || errno == EAGAIN) continue; syslog(LOG_ERR, "poll() failed: %s\n", strerror(errno)); break; } if (pollfd.revents) { syslog(LOG_DEBUG, "Exiting canary thread.\n"); break; } if (TIMESPEC_MSEC(last_cheep) + canary_cheep_msec <= TIMESPEC_MSEC(now)) { eventfd_t value = 1; if (eventfd_write(canary_fd, value) < 0) { syslog(LOG_ERR, "eventfd_write() failed: %s\n", strerror(errno)); break; } last_cheep = now; continue; } } return NULL; } static void* watchdog_thread(void *data) { enum { POLLFD_CANARY, POLLFD_QUIT, _POLLFD_MAX }; struct timespec last_cheep, now; struct pollfd pollfd[_POLLFD_MAX]; assert(canary_fd >= 0); assert(quit_fd >= 0); /* Make sure we are not disturbed by any signal */ block_all_signals(); self_set_realtime(canary_watchdog_realtime_priority); memset(pollfd, 0, sizeof(pollfd)); pollfd[POLLFD_CANARY].fd = canary_fd; pollfd[POLLFD_CANARY].events = POLLIN; pollfd[POLLFD_QUIT].fd = quit_fd; pollfd[POLLFD_QUIT].events = POLLIN; assert_se(clock_gettime(CLOCK_MONOTONIC, &now) == 0); last_cheep = now; syslog(LOG_DEBUG, "Watchdog thread running.\n"); for (;;) { int r; int64_t msec; msec = TIMESPEC_MSEC(last_cheep) + canary_watchdog_msec - TIMESPEC_MSEC(now); if (msec < 0) msec = 0; r = poll(pollfd, _POLLFD_MAX, (int) msec); assert_se(clock_gettime(CLOCK_MONOTONIC, &now) == 0); if (r < 0) { if (errno == EINTR || errno == EAGAIN) continue; syslog(LOG_ERR, "poll() failed: %s\n", strerror(errno)); break; } if (pollfd[POLLFD_QUIT].revents) { syslog(LOG_DEBUG, "Exiting watchdog thread.\n"); break; } if (pollfd[POLLFD_CANARY].revents) { eventfd_t value; if (eventfd_read(canary_fd, &value) < 0) { syslog(LOG_ERR, "eventfd_read() failed: %s\n", strerror(errno)); break; } last_cheep = now; continue; } if (TIMESPEC_MSEC(last_cheep) + canary_watchdog_msec <= TIMESPEC_MSEC(now)) { last_cheep = now; syslog(LOG_WARNING, "The canary thread is apparently starving. Taking action.\n"); refuse_until = (uint32_t) now.tv_sec + canary_refusal_sec; __sync_synchronize(); if (canary_demote_unknown) reset_all(); else reset_known(); continue; } } return NULL; } static void stop_canary(void) { int r; if (quit_fd >= 0) { eventfd_t value = 1; if (eventfd_write(quit_fd, value) < 0) syslog(LOG_WARNING, "Warning: eventfd_write() failed: %s\n", strerror(errno)); } if (canary_thread_id != 0) { if ((r = pthread_join(canary_thread_id, NULL)) != 0) syslog(LOG_WARNING, "Warning: pthread_join() failed: %s\n", strerror(r)); canary_thread_id = 0; } if (watchdog_thread_id != 0) { if ((r = pthread_join(watchdog_thread_id, NULL)) != 0) syslog(LOG_WARNING, "Warning: pthread_join() failed: %s\n", strerror(r)); watchdog_thread_id = 0; } if (canary_fd >= 0) { close(canary_fd); canary_fd = -1; } if (quit_fd >= 0) { close(quit_fd); quit_fd = -1; } } static int start_canary(void) { int r; if (!do_canary) return 0; if ((canary_fd = eventfd(0, EFD_NONBLOCK|EFD_CLOEXEC)) < 0 || (quit_fd = eventfd(0, EFD_NONBLOCK|EFD_CLOEXEC)) < 0) { r = -errno; syslog(LOG_ERR, "eventfd() failed: %s\n", strerror(errno)); goto fail; } if ((r = -pthread_create(&canary_thread_id, NULL, canary_thread, NULL)) < 0 || (r = -pthread_create(&watchdog_thread_id, NULL, watchdog_thread, NULL)) < 0) { syslog(LOG_ERR, "pthread_create failed: %s\n", strerror(-r)); goto fail; } return 0; fail: stop_canary(); return r; } static int drop_privileges(void) { struct passwd *pw = NULL; int r; if (do_drop_privileges) { /* First, get user data */ if (!(pw = getpwnam(username))) { syslog(LOG_ERR, "Failed to find user '%s'.\n", username); return -ENOENT; } } if (do_chroot) { /* Second, chroot() */ if (chroot("/proc") < 0 || chdir("/") < 0) { r = -errno; syslog(LOG_ERR, "Failed to chroot() to /proc: %s\n", strerror(errno)); return r; } proc = "/"; syslog(LOG_DEBUG, "Successfully called chroot.\n"); } if (do_drop_privileges) { static const cap_value_t cap_values[] = { CAP_SYS_NICE, /* Needed for obvious reasons */ CAP_DAC_READ_SEARCH /* Needed so that we can verify resource limits */ }; cap_value_t c, m; cap_t caps; m = CAP_LAST_CAP; /* In case the number of caps in the kernel is increased, drop them too */ if (m < 63) m = 63; /* Third, reduce bounding set */ for (c = 0; c <= m; c++) { unsigned u; bool keep = false; for (u = 0; u < ELEMENTSOF(cap_values); u++) if (cap_values[u] == c) { keep = true; break; } if (!keep) assert_se(prctl(PR_CAPBSET_DROP, c) == 0 || errno == EINVAL || errno == EPERM); } /* Fourth, say that we want to keep caps */ if (prctl(PR_SET_KEEPCAPS, 1) < 0) { r = -errno; syslog(LOG_ERR, "PR_SET_KEEPCAPS failed: %s\n", strerror(errno)); return r; } /* Fifth, drop privs */ if (setgroups(0, NULL) < 0 || setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) < 0 || setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) < 0) { r = -errno; syslog(LOG_ERR, "Failed to become %s: %s\n", username, strerror(errno)); return r; } /* Sixth, reset caps flag */ if (prctl(PR_SET_KEEPCAPS, 0) < 0) { r = -errno; syslog(LOG_ERR, "PR_SET_KEEPCAPS failed: %s\n", strerror(errno)); return r; } /* Seventh, reduce caps */ assert_se(caps = cap_init()); assert_se(cap_clear(caps) == 0); assert_se(cap_set_flag(caps, CAP_EFFECTIVE, ELEMENTSOF(cap_values), cap_values, CAP_SET) == 0); assert_se(cap_set_flag(caps, CAP_PERMITTED, ELEMENTSOF(cap_values), cap_values, CAP_SET) == 0); if (cap_set_proc(caps) < 0) { r = -errno; syslog(LOG_ERR, "cap_set_proc() failed: %s\n", strerror(errno)); return r; } assert_se(cap_free(caps) == 0); /* Eigth, update environment */ setenv("USER", username, 1); setenv("USERNAME", username, 1); setenv("LOGNAME", username, 1); setenv("HOME", get_proc_path(), 1); syslog(LOG_DEBUG, "Successfully dropped privileges.\n"); } return 0; } static int set_resource_limits(void) { static struct { int id; const char *name; rlim_t value; } table[] = { { .id = RLIMIT_FSIZE, .name = "RLIMIT_FSIZE", .value = 0 }, { .id = RLIMIT_MEMLOCK, .name = "RLIMIT_MEMLOCK", .value = 0 }, { .id = RLIMIT_MSGQUEUE, .name = "RLIMIT_MSGQUEUE", .value = 0 }, { .id = RLIMIT_NICE, .name = "RLIMIT_NICE", .value = 20 }, { .id = RLIMIT_NOFILE, .name = "RLIMIT_NOFILE", .value = 50 }, { .id = RLIMIT_NPROC, .name = "RLIMIT_NPROC", .value = 3 }, { .id = RLIMIT_RTPRIO, .name = "RLIMIT_RTPRIO", .value = 0 }, /* Since we have CAP_SYS_NICE we don't need this */ { .id = RLIMIT_RTTIME, .name = "RLIMIT_RTTIME", .value = 0 } }; unsigned u; int r; assert(table[7].id == RLIMIT_RTTIME); table[7].value = rttime_usec_max; /* Do as I say AND do as I do */ if (!do_limit_resources) return 0; for (u = 0; u < ELEMENTSOF(table); u++) { struct rlimit rlim; if (getrlimit(table[u].id, &rlim) < 0) { r = -errno; syslog(LOG_ERR, "Failed to get %s: %s\n", table[u].name, strerror(errno)); return r; } if (rlim.rlim_max < table[u].value) continue; rlim.rlim_cur = rlim.rlim_max = table[u].value; if (setrlimit(table[u].id, &rlim) < 0) { r = -errno; syslog(LOG_ERR, "Failed to set %s: %s\n", table[u].name, strerror(errno)); return r; } } syslog(LOG_DEBUG, "Successfully limited resources.\n"); return 0; } enum { ARG_HELP = 256, ARG_VERSION, ARG_SCHEDULING_POLICY, ARG_OUR_REALTIME_PRIORITY, ARG_OUR_NICE_LEVEL, ARG_MAX_REALTIME_PRIORITY, ARG_MIN_NICE_LEVEL, ARG_USER_NAME, ARG_RTTIME_USEC_MAX, ARG_USERS_MAX, ARG_PROCESSES_PER_USER_MAX, ARG_THREADS_PER_USER_MAX, ARG_ACTIONS_BURST_SEC, ARG_ACTIONS_PER_BURST_MAX, ARG_NO_DROP_PRIVILEGES, ARG_NO_CHROOT, ARG_NO_LIMIT_RESOURCES, ARG_NO_CANARY, ARG_CANARY_CHEEP_MSEC, ARG_CANARY_WATCHDOG_MSEC, ARG_CANARY_DEMOTE_ROOT, ARG_CANARY_DEMOTE_UNKNOWN, ARG_CANARY_REFUSE_SEC, ARG_STDERR, ARG_DEBUG, ARG_INTROSPECT }; /* Table for getopt_long() */ static const struct option long_options[] = { { "help", no_argument, 0, ARG_HELP }, { "version", no_argument, 0, ARG_VERSION }, { "scheduling-policy", required_argument, 0, ARG_SCHEDULING_POLICY }, { "our-realtime-priority", required_argument, 0, ARG_OUR_REALTIME_PRIORITY }, { "our-nice-level", required_argument, 0, ARG_OUR_NICE_LEVEL }, { "max-realtime-priority", required_argument, 0, ARG_MAX_REALTIME_PRIORITY }, { "min-nice-level", required_argument, 0, ARG_MIN_NICE_LEVEL }, { "user-name", required_argument, 0, ARG_USER_NAME }, { "rttime-usec-max", required_argument, 0, ARG_RTTIME_USEC_MAX }, { "users-max", required_argument, 0, ARG_USERS_MAX }, { "processes-per-user-max", required_argument, 0, ARG_PROCESSES_PER_USER_MAX }, { "threads-per-user-max", required_argument, 0, ARG_THREADS_PER_USER_MAX }, { "actions-burst-sec", required_argument, 0, ARG_ACTIONS_BURST_SEC }, { "actions-per-burst-max", required_argument, 0, ARG_ACTIONS_PER_BURST_MAX }, { "no-drop-privileges", no_argument, 0, ARG_NO_DROP_PRIVILEGES }, { "no-chroot", no_argument, 0, ARG_NO_CHROOT }, { "no-limit-resources", no_argument, 0, ARG_NO_LIMIT_RESOURCES }, { "no-canary", no_argument, 0, ARG_NO_CANARY }, { "canary-cheep-msec", required_argument, 0, ARG_CANARY_CHEEP_MSEC }, { "canary-watchdog-msec", required_argument, 0, ARG_CANARY_WATCHDOG_MSEC }, { "canary-demote-root", no_argument, 0, ARG_CANARY_DEMOTE_ROOT }, { "canary-demote-unknown", no_argument, 0, ARG_CANARY_DEMOTE_UNKNOWN }, { "canary-refuse-sec", required_argument, 0, ARG_CANARY_REFUSE_SEC }, { "stderr", no_argument, 0, ARG_STDERR }, { "debug", no_argument, 0, ARG_DEBUG }, { "introspect", no_argument, 0, ARG_INTROSPECT }, { NULL, 0, 0, 0} }; static char* get_file_name(const char *p) { char *e; if ((e = strrchr(p, '/'))) return e + 1; else return (char*) p; } static void show_help(const char *exe) { static const char * const sp_names[] = { [SCHED_OTHER] = "OTHER", [SCHED_BATCH] = "BATCH", [SCHED_FIFO] = "FIFO", [SCHED_RR] = "RR" }; printf("%s [options]\n\n" "COMMANDS:\n" " -h, --help Show this help\n" " --version Show version\n\n" "OPTIONS:\n" " --stderr Log to STDERR in addition to syslog\n" " --debug Also log debugging mssages\n" " --user-name=USER Run daemon as user (%s)\n\n" " --scheduling-policy=(RR|FIFO) Choose scheduling policy (%s)\n" " --our-realtime-priority=[%i..%i] Realtime priority for the daemon (%u)\n" " --our-nice-level=[%i..%i] Nice level for the daemon (%i)\n" " --max-realtime-priority=[%i..%i] Max realtime priority for clients (%u)\n" " --min-nice-level=[%i..%i] Min nice level for clients (%i)\n\n" " --rttime-usec-max=USEC Require clients to have set RLIMIT_RTTIME\n" " not greater than this (%llu)\n\n" " --users-max=INT How many users this daemon will serve at\n" " max at the same time (%u)\n" " --processes-per-user-max=INT How many processes this daemon will serve\n" " at max per user at the same time (%u)\n" " --threads-per-user-max=INT How many threads this daemon will serve\n" " at max per user at the same time (%u)\n\n" " --actions-burst-sec=SEC Enforce requests limits in this time (%u)\n" " --actions-per-burst-max=INT Allow this many requests per burst (%u)\n\n" " --canary-cheep-msec=MSEC Canary cheep interval (%u)\n" " --canary-watchdog-msec=MSEC Watchdog action delay (%u)\n" " --canary-demote-unknown When the canary dies demote unknown\n" " processes too?\n" " --canary-demote-root When the canary dies demote root\n" " processes too?\n" " --canary-refuse-sec=SEC How long to refuse further requests\n" " after the canary died (%u)\n\n" " --no-canary Don't run a canary-based RT watchdog\n\n" " --no-drop-privileges Don't drop privileges\n" " --no-chroot Don't chroot\n" " --no-limit-resources Don't limit daemon's resources\n", exe, username, sp_names[sched_policy], sched_get_priority_min(sched_policy), sched_get_priority_max(sched_policy), our_realtime_priority, PRIO_MIN, PRIO_MAX-1, our_nice_level, sched_get_priority_min(sched_policy), sched_get_priority_max(sched_policy), max_realtime_priority, PRIO_MIN, PRIO_MAX-1, min_nice_level, rttime_usec_max, users_max, processes_per_user_max, threads_per_user_max, actions_burst_sec, actions_per_burst_max, canary_cheep_msec, canary_watchdog_msec, canary_refusal_sec); } static int parse_command_line(int argc, char *argv[], int *ret) { int c; while ((c = getopt_long(argc, argv, "h", long_options, NULL)) >= 0) { switch (c) { case 'h': case ARG_HELP: show_help(get_file_name(argv[0])); *ret = 0; return 0; case ARG_VERSION: printf("%s " PACKAGE_VERSION "\n", get_file_name(argv[0])); *ret = 0; return 0; case ARG_USER_NAME: username = optarg; break; case ARG_SCHEDULING_POLICY: { if (strcasecmp(optarg, "rr") == 0) sched_policy = SCHED_RR; else if (strcasecmp(optarg, "fifo") == 0) sched_policy = SCHED_FIFO; else { fprintf(stderr, "--scheduling-policy parameter invalid.\n"); return -1; } break; } case ARG_OUR_REALTIME_PRIORITY: { char *e = NULL; unsigned long u; errno = 0; u = strtoul(optarg, &e, 0); if (errno != 0 || !e || *e || u < (unsigned) sched_get_priority_min(sched_policy) || u > (unsigned) sched_get_priority_max(sched_policy)) { fprintf(stderr, "--our-realtime-priority parameter invalid.\n"); return -1; } our_realtime_priority = u; break; } case ARG_OUR_NICE_LEVEL: { char *e = NULL; long i; errno = 0; i = strtol(optarg, &e, 0); if (errno != 0 || !e || *e || i < PRIO_MIN || i > PRIO_MAX*2) { fprintf(stderr, "--our-nice-level parameter invalid.\n"); return -1; } our_nice_level = i; break; } case ARG_MAX_REALTIME_PRIORITY: { char *e = NULL; unsigned long u; errno = 0; u = strtoul(optarg, &e, 0); if (errno != 0 || !e || *e || u < (unsigned) sched_get_priority_min(sched_policy) || u > (unsigned) sched_get_priority_max(sched_policy)) { fprintf(stderr, "--max-realtime-priority parameter invalid.\n"); return -1; } max_realtime_priority = u; break; } case ARG_MIN_NICE_LEVEL: { char *e = NULL; long i; errno = 0; i = strtol(optarg, &e, 0); if (errno != 0 || !e || *e || i < PRIO_MIN || i >= PRIO_MAX) { fprintf(stderr, "--min-nice-level parameter invalid.\n"); return -1; } min_nice_level = i; break; } case ARG_RTTIME_USEC_MAX: { char *e = NULL; errno = 0; rttime_usec_max = strtoull(optarg, &e, 0); if (errno != 0 || !e || *e || rttime_usec_max <= 0) { fprintf(stderr, "--rttime-usec-max parameter invalid.\n"); return -1; } break; } case ARG_USERS_MAX: { char *e = NULL; unsigned long u; errno = 0; u = strtoul(optarg, &e, 0); if (errno != 0 || !e || *e || u <= 0) { fprintf(stderr, "--users-max parameter invalid.\n"); return -1; } users_max = u; break; } case ARG_PROCESSES_PER_USER_MAX: { char *e = NULL; unsigned long u; errno = 0; u = strtoul(optarg, &e, 0); if (errno != 0 || !e || *e || u <= 0) { fprintf(stderr, "--processes-per-user-max parameter invalid.\n"); return -1; } processes_per_user_max = u; break; } case ARG_THREADS_PER_USER_MAX: { char *e = NULL; unsigned long u; errno = 0; u = strtoul(optarg, &e, 0); if (errno != 0 || !e || *e || u <= 0) { fprintf(stderr, "--threads-per-user-max parameter invalid.\n"); return -1; } threads_per_user_max = u; break; } case ARG_ACTIONS_BURST_SEC: { char *e = NULL; unsigned long u; errno = 0; u = strtoul(optarg, &e, 0); if (errno != 0 || !e || *e || u <= 0) { fprintf(stderr, "--actions-burst-sec parameter invalid.\n"); return -1; } actions_burst_sec = u; break; } case ARG_ACTIONS_PER_BURST_MAX: { char *e = NULL; unsigned long u; errno = 0; u = strtoul(optarg, &e, 0); if (errno != 0 || !e || *e || u <= 0) { fprintf(stderr, "--actions-per-burst-max parameter invalid.\n"); return -1; } actions_per_burst_max = u; break; } case ARG_NO_DROP_PRIVILEGES: do_drop_privileges = FALSE; break; case ARG_NO_CHROOT: do_chroot = FALSE; break; case ARG_NO_LIMIT_RESOURCES: do_limit_resources = FALSE; break; case ARG_NO_CANARY: do_canary = FALSE; break; case ARG_CANARY_WATCHDOG_MSEC: { char *e = NULL; unsigned long u; errno = 0; u = strtoul(optarg, &e, 0); if (errno != 0 || !e || *e || u <= 0) { fprintf(stderr, "--canary-watchdog-msec parameter invalid.\n"); return -1; } canary_watchdog_msec = u; break; } case ARG_CANARY_CHEEP_MSEC: { char *e = NULL; unsigned long u; errno = 0; u = strtoul(optarg, &e, 0); if (errno != 0 || !e || *e || u <= 0) { fprintf(stderr, "--canary-cheep-msec parameter invalid.\n"); return -1; } canary_cheep_msec = u; break; } case ARG_CANARY_DEMOTE_ROOT: canary_demote_root = TRUE; break; case ARG_CANARY_DEMOTE_UNKNOWN: canary_demote_unknown = TRUE; break; case ARG_CANARY_REFUSE_SEC: { char *e = NULL; unsigned long u; errno = 0; u = strtoul(optarg, &e, 0); if (errno != 0 || !e || *e) { fprintf(stderr, "--canary-refuse-sec parameter invalid.\n"); return -1; } canary_refusal_sec = (uint32_t) u; break; } case ARG_STDERR: log_stderr = TRUE; break; case ARG_DEBUG: log_debug = TRUE; break; case ARG_INTROSPECT: fputs(introspect_xml, stdout); *ret = 0; return 0; case '?': default: fprintf(stderr, "Unknown command.\n"); return -1; } } if (optind < argc) { fprintf(stderr, "Too many arguments.\n"); return -1; } if (max_realtime_priority >= our_realtime_priority) { fprintf(stderr, "The maximum realtime priority (%u) handed out to clients cannot be higher then our own (%u).\n", max_realtime_priority, our_realtime_priority); return -1; } if (canary_cheep_msec >= canary_watchdog_msec) { fprintf(stderr, "The canary watchdog interval must be larger than the cheep interval.\n"); return -1; } if (!log_debug) setlogmask(LOG_UPTO(LOG_INFO)); assert(our_realtime_priority >= (unsigned) sched_get_priority_min(sched_policy)); assert(our_realtime_priority <= (unsigned) sched_get_priority_max(sched_policy)); assert(max_realtime_priority >= (unsigned) sched_get_priority_min(sched_policy)); assert(max_realtime_priority <= (unsigned) sched_get_priority_max(sched_policy)); assert(canary_watchdog_realtime_priority >= (unsigned) sched_get_priority_min(sched_policy)); assert(canary_watchdog_realtime_priority <= (unsigned) sched_get_priority_max(sched_policy)); assert(our_nice_level >= PRIO_MIN); assert(our_nice_level < PRIO_MAX); assert(min_nice_level >= PRIO_MIN); assert(min_nice_level < PRIO_MAX); return 1; } int main(int argc, char *argv[]) { DBusConnection *bus = NULL; int ret = 1; struct rtkit_user *u; unsigned long slack_ns; if (parse_command_line(argc, argv, &ret) <= 0) goto finish; if (getuid() != 0) { fprintf(stderr, "Need to be run as root.\n"); goto finish; } openlog(get_file_name(argv[0]), LOG_NDELAY|LOG_PID|(log_stderr ? LOG_PERROR : 0), LOG_DAEMON); /* Raise our timer slack, we don't really need to be woken up * on time. */ slack_ns = (((unsigned long) canary_watchdog_msec - (unsigned long) canary_cheep_msec) / 2UL) * 1000000UL; if (prctl(PR_SET_TIMERSLACK, slack_ns) < 0) syslog(LOG_WARNING, "PRT_SET_TIMERSLACK failed: %s\n", strerror(errno)); self_drop_realtime(our_nice_level); if (setup_dbus(&bus) < 0) goto finish; if (drop_privileges() < 0) goto finish; if (set_resource_limits() < 0) goto finish; if (start_canary() < 0) goto finish; setup_logind(bus); umask(0777); syslog(LOG_DEBUG, "Running.\n"); #ifdef HAVE_LIBSYSTEMD sd_notify(0, "STATUS=Running."); #endif dbus_connection_set_exit_on_disconnect(bus, FALSE); while (dbus_connection_read_write_dispatch(bus, -1)) ; ret = 0; syslog(LOG_DEBUG, "Exiting cleanly.\n"); finish: if (bus) { if (dbus_connection_get_is_connected(bus)) dbus_connection_close(bus); dbus_connection_unref(bus); } reset_known(); while ((u = users)) { users = u->next; free_user(u); } stop_canary(); dbus_shutdown(); return ret; } rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/rtkit-daemon.service.in000066400000000000000000000020001511637424700246100ustar00rootroot00000000000000# This file is part of RealtimeKit. # # Copyright 2010 Lennart Poettering # # RealtimeKit 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. # # RealtimeKit 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 RealtimeKit. If not, see . [Unit] Description=RealtimeKit Scheduling Policy Service [Service] ExecStart=@LIBEXECDIR@/rtkit-daemon Type=dbus BusName=org.freedesktop.RealtimeKit1 NotifyAccess=main CapabilityBoundingSet=CAP_SYS_NICE CAP_DAC_READ_SEARCH CAP_SYS_CHROOT CAP_SETGID CAP_SETUID PrivateNetwork=yes [Install] WantedBy=multi-user.target rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/rtkit-test.c000066400000000000000000000104631511637424700225150ustar00rootroot00000000000000/*-*- Mode: C; c-basic-offset: 8 -*-*/ /*** This file is part of RealtimeKit. Copyright 2009 Lennart Poettering RealtimeKit 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. RealtimeKit 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 RealtimeKit. If not, see . ***/ #include #include #include #include #include #include #include "rtkit.h" #ifndef SCHED_RESET_ON_FORK #define SCHED_RESET_ON_FORK 0x40000000 #endif #ifndef RLIMIT_RTTIME #define RLIMIT_RTTIME 15 #endif static void print_status(const char *t) { int ret; if ((ret = sched_getscheduler(0)) < 0) { fprintf(stderr, "sched_getscheduler() failed: %s\n", strerror(errno)); return; } printf("%s:\n" "\tSCHED_RESET_ON_FORK: %s\n", t, (ret & SCHED_RESET_ON_FORK) ? "yes" : "no"); if ((ret & ~SCHED_RESET_ON_FORK) == SCHED_RR) { struct sched_param param; if (sched_getparam(0, ¶m) < 0) { fprintf(stderr, "sched_getschedparam() failed: %s\n", strerror(errno)); return; } printf("\tSCHED_RR with priority %i\n", param.sched_priority); } else if ((ret & ~SCHED_RESET_ON_FORK) == SCHED_OTHER) { errno = 0; ret = getpriority(PRIO_PROCESS, 0); if (errno != 0) { fprintf(stderr, "getpriority() failed: %s\n", strerror(errno)); return; } printf("\tSCHED_OTHER with nice level: %i\n", ret); } else fprintf(stderr, "Neither SCHED_RR nor SCHED_OTHER.\n"); } int main(int argc, char *argv[]) { DBusError error; DBusConnection *bus; int r, max_realtime_priority, min_nice_level; long long rttime_usec_max; struct rlimit rlim; dbus_error_init(&error); if (!(bus = dbus_bus_get(DBUS_BUS_SYSTEM, &error))) { fprintf(stderr, "Failed to connect to system bus: %s\n", error.message); return 1; } if ((max_realtime_priority = rtkit_get_max_realtime_priority(bus)) < 0) fprintf(stderr, "Failed to retrieve max realtime priority: %s\n", strerror(-max_realtime_priority)); else printf("Max realtime priority is: %d\n", max_realtime_priority); if ((r = rtkit_get_min_nice_level(bus, &min_nice_level))) fprintf(stderr, "Failed to retrieve min nice level: %s\n", strerror(-r)); else printf("Min nice level is: %d\n", min_nice_level); if ((rttime_usec_max = rtkit_get_rttime_usec_max(bus)) < 0) fprintf(stderr, "Failed to retrieve rttime limit: %s\n", strerror(-rttime_usec_max)); else printf("Rttime limit is: %lld ns\n", rttime_usec_max); memset(&rlim, 0, sizeof(rlim)); rlim.rlim_cur = rlim.rlim_max = 100000ULL; /* 100ms */ if ((setrlimit(RLIMIT_RTTIME, &rlim) < 0)) fprintf(stderr, "Failed to set RLIMIT_RTTIME: %s\n", strerror(errno)); print_status("before"); if ((r = rtkit_make_high_priority(bus, 0, -10)) < 0) fprintf(stderr, "Failed to become high priority: %s\n", strerror(-r)); else printf("Successfully became high priority.\n"); print_status("after high priority"); if ((r = rtkit_make_realtime(bus, 0, 10)) < 0) fprintf(stderr, "Failed to become realtime: %s\n", strerror(-r)); else printf("Successfully became realtime.\n"); print_status("after realtime"); dbus_connection_unref(bus); return 0; } rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/rtkit.c000066400000000000000000000242501511637424700215370ustar00rootroot00000000000000/*-*- Mode: C; c-basic-offset: 8 -*-*/ /*** Copyright 2009 Lennart Poettering Copyright 2010 David Henningsson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ***/ #include #include "rtkit.h" #ifdef __linux__ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include #include #include #include #include static pid_t _gettid(void) { return (pid_t) syscall(SYS_gettid); } static int translate_error(const char *name) { if (strcmp(name, DBUS_ERROR_NO_MEMORY) == 0) return -ENOMEM; if (strcmp(name, DBUS_ERROR_SERVICE_UNKNOWN) == 0 || strcmp(name, DBUS_ERROR_NAME_HAS_NO_OWNER) == 0) return -ENOENT; if (strcmp(name, DBUS_ERROR_ACCESS_DENIED) == 0 || strcmp(name, DBUS_ERROR_AUTH_FAILED) == 0) return -EACCES; return -EIO; } static long long rtkit_get_int_property(DBusConnection *connection, const char* propname, long long* propval) { DBusMessage *m = NULL, *r = NULL; DBusMessageIter iter, subiter; dbus_int64_t i64; dbus_int32_t i32; DBusError error; int current_type; long long ret; const char * interfacestr = "org.freedesktop.RealtimeKit1"; dbus_error_init(&error); if (!(m = dbus_message_new_method_call( RTKIT_SERVICE_NAME, RTKIT_OBJECT_PATH, "org.freedesktop.DBus.Properties", "Get"))) { ret = -ENOMEM; goto finish; } if (!dbus_message_append_args( m, DBUS_TYPE_STRING, &interfacestr, DBUS_TYPE_STRING, &propname, DBUS_TYPE_INVALID)) { ret = -ENOMEM; goto finish; } if (!(r = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) { ret = translate_error(error.name); goto finish; } if (dbus_set_error_from_message(&error, r)) { ret = translate_error(error.name); goto finish; } ret = -EBADMSG; dbus_message_iter_init(r, &iter); while ((current_type = dbus_message_iter_get_arg_type (&iter)) != DBUS_TYPE_INVALID) { if (current_type == DBUS_TYPE_VARIANT) { dbus_message_iter_recurse(&iter, &subiter); while ((current_type = dbus_message_iter_get_arg_type (&subiter)) != DBUS_TYPE_INVALID) { if (current_type == DBUS_TYPE_INT32) { dbus_message_iter_get_basic(&subiter, &i32); *propval = i32; ret = 0; } if (current_type == DBUS_TYPE_INT64) { dbus_message_iter_get_basic(&subiter, &i64); *propval = i64; ret = 0; } dbus_message_iter_next (&subiter); } } dbus_message_iter_next (&iter); } finish: if (m) dbus_message_unref(m); if (r) dbus_message_unref(r); dbus_error_free(&error); return ret; } int rtkit_get_max_realtime_priority(DBusConnection *connection) { long long retval; int err; err = rtkit_get_int_property(connection, "MaxRealtimePriority", &retval); return err < 0 ? err : retval; } int rtkit_get_min_nice_level(DBusConnection *connection, int* min_nice_level) { long long retval; int err; err = rtkit_get_int_property(connection, "MinNiceLevel", &retval); if (err >= 0) *min_nice_level = retval; return err; } long long rtkit_get_rttime_usec_max(DBusConnection *connection) { long long retval; int err; err = rtkit_get_int_property(connection, "RTTimeUSecMax", &retval); return err < 0 ? err : retval; } int rtkit_make_realtime(DBusConnection *connection, pid_t thread, int priority) { DBusMessage *m = NULL, *r = NULL; dbus_uint64_t u64; dbus_uint32_t u32; DBusError error; int ret; dbus_error_init(&error); if (thread == 0) thread = _gettid(); if (!(m = dbus_message_new_method_call( RTKIT_SERVICE_NAME, RTKIT_OBJECT_PATH, "org.freedesktop.RealtimeKit1", "MakeThreadRealtime"))) { ret = -ENOMEM; goto finish; } u64 = (dbus_uint64_t) thread; u32 = (dbus_uint32_t) priority; if (!dbus_message_append_args( m, DBUS_TYPE_UINT64, &u64, DBUS_TYPE_UINT32, &u32, DBUS_TYPE_INVALID)) { ret = -ENOMEM; goto finish; } if (!(r = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) { ret = translate_error(error.name); goto finish; } if (dbus_set_error_from_message(&error, r)) { ret = translate_error(error.name); goto finish; } ret = 0; finish: if (m) dbus_message_unref(m); if (r) dbus_message_unref(r); dbus_error_free(&error); return ret; } int rtkit_make_high_priority(DBusConnection *connection, pid_t thread, int nice_level) { DBusMessage *m = NULL, *r = NULL; dbus_uint64_t u64; dbus_int32_t s32; DBusError error; int ret; dbus_error_init(&error); if (thread == 0) thread = _gettid(); if (!(m = dbus_message_new_method_call( RTKIT_SERVICE_NAME, RTKIT_OBJECT_PATH, "org.freedesktop.RealtimeKit1", "MakeThreadHighPriority"))) { ret = -ENOMEM; goto finish; } u64 = (dbus_uint64_t) thread; s32 = (dbus_int32_t) nice_level; if (!dbus_message_append_args( m, DBUS_TYPE_UINT64, &u64, DBUS_TYPE_INT32, &s32, DBUS_TYPE_INVALID)) { ret = -ENOMEM; goto finish; } if (!(r = dbus_connection_send_with_reply_and_block(connection, m, -1, &error))) { ret = translate_error(error.name); goto finish; } if (dbus_set_error_from_message(&error, r)) { ret = translate_error(error.name); goto finish; } ret = 0; finish: if (m) dbus_message_unref(m); if (r) dbus_message_unref(r); dbus_error_free(&error); return ret; } int rtkit_make_realtime_simple(void) { DBusConnection *dc; long long rtt; int ret; struct rlimit old_rlim; struct rlimit rlim; int prio; dc = dbus_bus_get(DBUS_BUS_SYSTEM, NULL); if (dc == NULL) return -ENETUNREACH; rtt = rtkit_get_rttime_usec_max(dc); if (rtt < 0) { ret = rtt; goto finish; } ret = getrlimit(RLIMIT_RTTIME, &old_rlim); if (ret < 0) { ret = -errno; goto finish; } rlim.rlim_cur = rtt; rlim.rlim_max = rtt; ret = setrlimit(RLIMIT_RTTIME, &rlim); if (ret < 0) { ret = -errno; goto finish; } prio = rtkit_get_max_realtime_priority(dc); if (prio < 0) { ret = prio; setrlimit(RLIMIT_RTTIME, &old_rlim); goto finish; } ret = rtkit_make_realtime(dc, 0, prio); if (ret < 0) setrlimit(RLIMIT_RTTIME, &old_rlim); finish: dbus_connection_unref(dc); return ret; } #else int rtkit_make_realtime(DBusConnection *connection, pid_t thread, int priority) { return -ENOTSUP; } int rtkit_make_high_priority(DBusConnection *connection, pid_t thread, int nice_level) { return -ENOTSUP; } int rtkit_get_max_realtime_priority(DBusConnection *connection) { return -ENOTSUP; } int rtkit_get_min_nice_level(DBusConnection *connection, int* min_nice_level) { return -ENOTSUP; } long long rtkit_get_rttime_usec_max(DBusConnection *connection) { return -ENOTSUP; } int rtkit_make_realtime_simple() { return -ENOTSUP; } #endif rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/rtkit.h000066400000000000000000000065641511637424700215540ustar00rootroot00000000000000/*-*- Mode: C; c-basic-offset: 8 -*-*/ #ifndef foortkithfoo #define foortkithfoo /*** Copyright 2009 Lennart Poettering Copyright 2010 David Henningsson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ***/ #include #include #ifdef __cplusplus extern "C" { #endif /* This is the reference implementation for a client for * RealtimeKit. You don't have to use this, but if do, just copy these * sources into your repository */ #define RTKIT_SERVICE_NAME "org.freedesktop.RealtimeKit1" #define RTKIT_OBJECT_PATH "/org/freedesktop/RealtimeKit1" /* This is mostly equivalent to sched_setparam(thread, SCHED_RR, { * .sched_priority = priority }). 'thread' needs to be a kernel thread * id as returned by gettid(), not a pthread_t! If 'thread' is 0 the * current thread is used. The returned value is a negative errno * style error code, or 0 on success. */ int rtkit_make_realtime(DBusConnection *system_bus, pid_t thread, int priority); /* This is mostly equivalent to setpriority(PRIO_PROCESS, thread, * nice_level). 'thread' needs to be a kernel thread id as returned by * gettid(), not a pthread_t! If 'thread' is 0 the current thread is * used. The returned value is a negative errno style error code, or 0 * on success.*/ int rtkit_make_high_priority(DBusConnection *system_bus, pid_t thread, int nice_level); /* Return the maximum value of realtime priority available. Realtime requests * above this value will fail. A negative value is an errno style error code. */ int rtkit_get_max_realtime_priority(DBusConnection *system_bus); /* Retreive the minimum value of nice level available. High prio requests * below this value will fail. The returned value is a negative errno * style error code, or 0 on success.*/ int rtkit_get_min_nice_level(DBusConnection *system_bus, int* min_nice_level); /* Return the maximum value of RLIMIT_RTTIME to set before attempting a * realtime request. A negative value is an errno style error code. */ long long rtkit_get_rttime_usec_max(DBusConnection *system_bus); /* Make the current thread realtime in one function call. * Returns 0 on success and -errno on failure. * A failure to connect to dbus counts as -ENETUNREACH. */ int rtkit_make_realtime_simple(void); #ifdef __cplusplus } #endif #endif rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/rtkit.sysusers000066400000000000000000000001561511637424700232140ustar00rootroot00000000000000#Type Name ID GECOS Home directory Shell u rtkit - "RealtimeKit" - - rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/rtkitctl.8000066400000000000000000000032141511637424700221640ustar00rootroot00000000000000.\" Hey, EMACS: -*- nroff -*- .\" First parameter, NAME, should be all caps .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection .\" other parameters are allowed: see man(7), man(1) .TH RTKITCTL 8 "October 16, 2023" .\" Please adjust this date whenever revising the manpage. .\" .\" Some roff macros, for reference: .\" .nh disable hyphenation .\" .hy enable hyphenation .\" .ad l left justify .\" .ad b justify to both left and right margins .\" .nf disable filling .\" .fi enable filling .\" .br insert line break .\" .sp insert n+1 empty lines .\" for manpage-specific macros, see man(7) .SH NAME rtkitctl \- Realtime Policy and Watchdog daemon control .SH SYNOPSIS .B rtkitctl .RI [ options ] .SH DESCRIPTION .B RealtimeKit is a D-Bus system service that changes the scheduling policy of user processes/threads to SCHED_RR (i.e. realtime scheduling mode) on request. It is intended to be used as a secure mechanism to allow real-time scheduling to be used by normal user processes. .SH OPTIONS .TP .B \-h, \-\-help Show a summary of options. .TP .B \-\-version Show version. .TP .B \-\-reset\-known Reset real-time status of known threads. .TP .B \-\-reset\-all Reset real-time status of all threads. .TP .B \-\-suspend Temporarily reset real-time status of known threads. .TP .B \-\-resume Restore real-time status of known threads temporarily reset by suspend. .TP .B \-\-start Start RealtimeKit if it is not running already. .TP .B \-k, \-\-exit Terminate running RealtimeKit daemon. .SH AUTHOR RealtimeKit was written by Lennart Poettering . rtkit-v0.14-c52db0a9849908613ab8775b519834671b7bec8b/rtkitctl.c000066400000000000000000000172021511637424700222410ustar00rootroot00000000000000/*-*- Mode: C; c-basic-offset: 8 -*-*/ /*** This file is part of RealtimeKit. Copyright 2009 Lennart Poettering RealtimeKit 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. RealtimeKit 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 RealtimeKit. If not, see . ***/ #ifdef HAVE_CONFIG_H #include #endif #include #include #include #include "rtkit.h" static char* get_file_name(const char *p) { char *e; if ((e = strrchr(p, '/'))) return e + 1; else return (char*) p; } static void show_help(const char *exe) { printf("%s [options]\n\n" " -h, --help Show this help\n" " --version Show version\n\n" " --reset-known Reset real-time status of known threads\n" " --reset-all Reset real-time status of all threads\n" " --start Start RealtimeKit if it is not running already\n" " -k, --exit Terminate running RealtimeKit daemon\n" " --suspend Suspend real-time status of known threads and reject new requests\n" " --resume Resume real-time status of known threads and allow new requests\n", exe); } int main (int argc, char*argv[]) { enum { ARG_HELP = 256, ARG_VERSION, ARG_START, ARG_EXIT, ARG_RESET_KNOWN, ARG_RESET_ALL, ARG_SUSPEND, ARG_RESUME, }; static const struct option long_options[] = { { "help", no_argument, 0, ARG_HELP }, { "version", no_argument, 0, ARG_VERSION }, { "start", no_argument, 0, ARG_START }, { "exit", no_argument, 0, ARG_EXIT }, { "reset-known", no_argument, 0, ARG_RESET_KNOWN }, { "reset-all", no_argument, 0, ARG_RESET_ALL }, { "suspend", no_argument, 0, ARG_SUSPEND }, { "resume", no_argument, 0, ARG_RESUME }, { NULL, 0, 0, 0} }; enum { OPERATION_START, OPERATION_EXIT, OPERATION_RESET_KNOWN, OPERATION_RESET_ALL, OPERATION_SUSPEND, OPERATION_RESUME, _OPERATION_MAX }; static const char *method[_OPERATION_MAX] = { [OPERATION_START] = "StartServiceByName", [OPERATION_EXIT] = "Exit", [OPERATION_RESET_KNOWN] = "ResetKnown", [OPERATION_RESET_ALL] = "ResetAll", [OPERATION_SUSPEND] = "Suspend", [OPERATION_RESUME] = "Resume" }; DBusError error; DBusConnection *bus = NULL; int operation = -1; int ret = 1; DBusMessage *m = NULL, *r = NULL; int c; dbus_error_init(&error); while ((c = getopt_long(argc, argv, "hk", long_options, NULL)) >= 0) { switch (c) { case 'h': case ARG_HELP: show_help(get_file_name(argv[0])); ret = 0; goto finish; case ARG_VERSION: printf("%s " PACKAGE_VERSION "\n", get_file_name(argv[0])); ret = 0; goto finish; case ARG_START: operation = OPERATION_START; break; case 'k': case ARG_EXIT: operation = OPERATION_EXIT; break; case ARG_RESET_KNOWN: operation = OPERATION_RESET_KNOWN; break; case ARG_RESET_ALL: operation = OPERATION_RESET_ALL; break; case ARG_SUSPEND: operation = OPERATION_SUSPEND; break; case ARG_RESUME: operation = OPERATION_RESUME; break; case '?': default: fprintf(stderr, "Unknown command.\n"); goto finish; } } if (optind < argc) { fprintf(stderr, "Too many arguments.\n"); goto finish; } if (operation < 0) { fprintf(stderr, "Need to specify operation.\n"); goto finish; } if (!(bus = dbus_bus_get(DBUS_BUS_SYSTEM, &error))) { fprintf(stderr, "Failed to connect to system bus: %s\n", error.message); goto finish; } if (operation == OPERATION_START) { const char *service = RTKIT_SERVICE_NAME; dbus_uint32_t flags = 0; if (!(m = dbus_message_new_method_call( DBUS_SERVICE_DBUS, DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS, method[operation]))) { fprintf(stderr, "Failed to allocated message.\n"); goto finish; } if (!(dbus_message_append_args( m, DBUS_TYPE_STRING, &service, DBUS_TYPE_UINT32, &flags, DBUS_TYPE_INVALID))) { fprintf(stderr, "Failed to append to message.\n"); goto finish; } } else { if (!(m = dbus_message_new_method_call( RTKIT_SERVICE_NAME, RTKIT_OBJECT_PATH, "org.freedesktop.RealtimeKit1", method[operation]))) { fprintf(stderr, "Failed to allocated message.\n"); goto finish; } } if (!(r = dbus_connection_send_with_reply_and_block(bus, m, -1, &error))) { fprintf(stderr, "Failed to send %s request: %s\n", method[operation], error.message); goto finish; } if (dbus_set_error_from_message(&error, r)) { fprintf(stderr, "%s request failed: %s\n", method[operation], error.message); goto finish; } ret = 0; finish: if (m) dbus_message_unref(m); if (r) dbus_message_unref(r); if (bus) dbus_connection_unref(bus); return ret; }