diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000..651b962 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,44 @@ +WarningsAsErrors: '*' +Checks: ' + *, + -altera-*, + -android-*, + -bugprone-assignment-in-if-condition, + -bugprone-branch-clone, + -bugprone-easily-swappable-parameters, + -bugprone-implicit-widening-of-multiplication-result, + -bugprone-narrowing-conversions, + -bugprone-reserved-identifier, + -bugprone-signed-char-misuse, + -cert-dcl37-c, + -cert-dcl51-cpp, + -cert-err33-c, + -cert-err34-c, + -cert-str34-c, + -clang-analyzer-core.CallAndMessage, + -clang-analyzer-security.insecureAPI.strcpy, + -clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling, + -clang-diagnostic-macro-redefined, + -concurrency-mt-unsafe, + -cppcoreguidelines-avoid-magic-numbers, + -cppcoreguidelines-avoid-non-const-global-variables, + -cppcoreguidelines-init-variables, + -cppcoreguidelines-macro-to-enum, + -cppcoreguidelines-narrowing-conversions, + -google-readability-braces-around-statements, + -google-readability-todo, + -hicpp-*, + -llvm-*, + -llvmlibc-*, + -misc-unused-parameters, + -modernize-macro-to-enum, + -readability-braces-around-statements, + -readability-else-after-return, + -readability-function-cognitive-complexity, + -readability-identifier-length, + -readability-inconsistent-declaration-parameter-name, + -readability-isolate-declaration, + -readability-magic-numbers, + -readability-math-missing-parentheses, + -readability-suspicious-call-argument, +' diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3634137 --- /dev/null +++ b/.gitignore @@ -0,0 +1,23 @@ +# Intellij +.idea +*.iml + +# Eclipse +.cproject +.project + +# Object files +*.o +bin/* + +# Libraries +*.lib + +# Shared objects (inc. Windows DLLs) +*.dll +*.so + +# Executables +*.exe +*.out + diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..f55bd0b --- /dev/null +++ b/.travis.yml @@ -0,0 +1,4 @@ +dist: xenial +language: c +script: + - make diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000..3c0b507 --- /dev/null +++ b/AUTHORS @@ -0,0 +1,23 @@ +AUTHORS, CONTRIBUTORS, MAINTAINERS +---------------------------------- + +Daniel Graziotin + +Marji Cermak +John Ferlito +Andrew Gaul +Ismail Khatib +Trevor Joynson +Magnus Stubman +Olivier Tilmans +Yamakaky +Yi Yang +Herminio Hernandez Jr +Robert Musial +Ati Sharma + + +ORIGINARY AUTHORS +----------------- +Allan McRae mbpfan +rvega diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..9cecc1d --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + 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. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +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: + + {project} Copyright (C) {year} {fullname} + 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 +. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..ff1b7e6 --- /dev/null +++ b/Makefile @@ -0,0 +1,88 @@ +COMPILER=cc + +C = c +OBJ = o +OUTPUT_PATH = bin/ +SOURCE_PATH = src/ +TESTS_PATH = tests/ +TESTS_BIN = bin/mbpfan-tests +BIN = bin/mbpfan +CONF = mbpfan.conf +DEPEND_MODULE = mbpfan.depend.conf +DOC = README.md +MAN = mbpfan.8.gz + +COPT = +CC ?= cc +OBJFLAG = -o +BINFLAG = -o +INCLUDES = +LIBS = -lm +LIBPATH = +CFLAGS += $(COPT) -g $(INCLUDES) -Wall -Wextra -Wno-unused-function -Wno-unused-parameter -std=c99 -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=500 -D_DEFAULT_SOURCE +LDFLAGS += $(LIBPATH) -g + +OBJS := $(patsubst %.$(C),%.$(OBJ),$(wildcard $(SOURCE_PATH)*.$(C))) +TESTS_OBJS := $(patsubst %.$(C),%.$(OBJ),$(wildcard $(TESTS_PATH)*.$(C))) +TESTS_OBJS += $(filter-out %main.$(OBJ),$(OBJS)) + +.PHONY: all clean tests uninstall install rebuild + +%.$(OBJ):%.$(C) + mkdir -p bin + @echo Compiling $(basename $<)... + $(CC) -c $(CFLAGS) $< $(OBJFLAG)$@ + +all: $(BIN) $(TESTS_BIN) + +$(BIN): $(OBJS) + @echo Linking... + $(CC) $(LDFLAGS) $^ $(LIBS) $(BINFLAG) $(BIN) + +$(TESTS_BIN): $(TESTS_OBJS) + @echo Linking... + $(CC) $(LDFLAGS) $^ $(LIBS) $(BINFLAG) $(TESTS_BIN) + +clean: + rm -rf $(SOURCE_PATH)*.$(OBJ) $(BIN) + rm -rf $(TESTS_PATH)*.$(OBJ) $(TESTS_BIN) + +tests: all + ./bin/mbpfan-tests + +clang-tidy: + clang-tidy src/*.[ch] + +uninstall: + rm /usr/sbin/mbpfan + rm /etc/mbpfan.conf + rm /lib/modules-load.d/mbpfan.depend.conf + rm /lib/systemd/system/mbpfan.service + rm /usr/share/man/man8/mbpfan.8.gz + rm -rf /usr/share/doc/mbpfan + +install: all + install -d $(DESTDIR)/usr/sbin + install -d $(DESTDIR)/etc + install -d $(DESTDIR)/lib/systemd/system + install -d $(DESTDIR)/usr/share/doc/mbpfan + install -d $(DESTDIR)/lib/modules-load.d + install $(BIN) $(DESTDIR)/usr/sbin + install -m644 $(CONF) $(DESTDIR)/etc + install -m644 $(DEPEND_MODULE) $(DESTDIR)/lib/modules-load.d + install -m644 $(DOC) $(DESTDIR)/usr/share/doc/mbpfan + install -d $(DESTDIR)/usr/share/man/man8 + install -m644 $(MAN) $(DESTDIR)/usr/share/man/man8 + @echo "" + @echo "******************" + @echo "INSTALL COMPLETED" + @echo "******************" + @echo "" + @echo "A configuration file has been copied (might overwrite existing file) to /etc/mbpfan.conf." + @echo "See README.md file to have mbpfan automatically started at system boot." + @echo "" + @echo "Please run the tests now with the command" + @echo " sudo make tests" + @echo "" +rebuild: clean all +#rebuild is not entirely correct diff --git a/PKGBUILD b/PKGBUILD deleted file mode 100644 index 9442188..0000000 --- a/PKGBUILD +++ /dev/null @@ -1,23 +0,0 @@ -# Maintainer: Allan McRae - -pkgname=mbpfan -pkgver=1.1 -pkgrel=1 -pkgdesc="Automatically adjust the fan on a MacBook Pro" -arch=('i686' 'x86_64') -license=('GPL3') -source=(mbpfan.c - mbpfan.rc) - -md5sums=('57be3248ffa6563f06435f0b3b3451f5' - '6b58ce23ade4c2ccb8cadc004bb9e172') - -build() { - cd $srcdir/ - gcc -o mbpfan -lm -Wall $CFLAGS $LDFLAGS mbpfan.c -} - -package() { - install -Dm755 $srcdir/mbpfan $pkgdir/usr/bin/mbpfan - install -Dm755 $srcdir/mbpfan.rc $pkgdir/etc/rc.d/mbpfan -} diff --git a/README b/README deleted file mode 100644 index a85248e..0000000 --- a/README +++ /dev/null @@ -1,9 +0,0 @@ -This is a daemon that uses input from coretemp module and sets the fan speed using the applesmc module. It includes a PKGBUILD for easy installation in Arch Linux. - -Based on: - -http://allanmcrae.com/2010/05/simple-macbook-pro-fan-daemon/ -http://allanmcrae.com/2011/08/mbp-fan-daemon-update/ -https://launchpad.net/macfanctld -http://paste2.org/p/862259 -http://www.lobotomo.com/products/FanControl/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..2770693 --- /dev/null +++ b/README.md @@ -0,0 +1,260 @@ +# mbpfan + +[![Build Status](https://travis-ci.org/dgraziotin/mbpfan.svg?branch=master)](https://travis-ci.org/dgraziotin/mbpfan) + +This is an enhanced version of [Allan McRae mbpfan](http://allanmcrae.com/2010/05/simple-macbook-pro-fan-daemon/) + +mbpfan is a daemon that uses input from coretemp module and sets the fan speed using the applesmc module. +This enhanced version assumes any number of processors and fans (max. 10). + +* It only uses the temperatures from the processors as input. +* It requires coretemp and applesmc kernel modules to be loaded. +* It requires root use +* It daemonizes or stays in foreground +* Verbose mode for both syslog and stdout +* Users can configure it using the file /etc/mbpfan.conf + +**Table Of Contents** + +- [Supported GNU/Linux Distributions](#supported-gnulinux-distributions) +- [Tested Mac Models](#tested-mac-models) +- [Requirements](#requirements) +- [Installation](#installation) + - [Arch Linux](#arch-linux) + - [CRUX Linux](#crux-linux) + - [Debian](#debian) + - [Fedora](#fedora) + - [Gentoo](#gentoo) + - [Solus](#solus) + - [Ubuntu](#ubuntu) + - [Generic Install Instructions (All Other Operating Systems)](#generic-install-instructions-all-other-operating-systems) +- [Run Instructions](#run-instructions) +- [Starting at boot](#starting-at-boot) +- [Usage](#usage) +- [References](#references) +- [License](#license) +- [Credits](#credits) + +## Supported GNU/Linux Distributions + +We provide scripts to to load mbpfan daemon at system boot for many distros. +Please note that the support is provided by volunteers. mbpfan needs tests and bug reports. + +Supported distributions: + +- Ubuntu +- Debian +- Archlinux +- Fedora +- RedHat +- CentOS +- Gentoo +- Alpine +- Trisquel +- Solus + +## Tested Mac Models + +See https://github.com/linux-on-mac/mbpfan/wiki/Tested-Mac-Models . + +## Requirements + +Be sure to load the kernel modules **applesmc** and **coretemp**. + +These modules are often automatically loaded when booting up GNU/Linux on a MacBook. If that is not the case, you should make sure to load them at system startup. + +**How do I know if applesmc and coretemp are loaded?** + +In most distributions, you can run the following command: + +```bash +lsmod | grep -e applesmc -e coretemp +``` + +If you see `coretemp` and `applesmc` listed, you are all set. + +**If you do not see `coretemp` and `applesmc` listed, you must load them.** + +This is _usually_ achieved by inserting the following two lines in the file `/etc/modules` + +``` +coretemp +applesmc +``` + +Please check the relevant documentation of your GNU/Linux distribution. + +## Installation + +### Arch Linux + +See [mbpfan-git at AUR](https://aur.archlinux.org/packages/mbpfan-git/). +Otherwise, please refer to the Generic Instructions. + +### CRUX Linux + +Follow the instructions on [jolupalabs REPO](https://github.com/jolupa/jolupalabs) for installation. + +### Debian + +On Debian 10 or later install via: + +``` +sudo apt-get install mbpfan +``` + +### Fedora + +On Fedora 30 or later: + +``` +sudo dnf install mbpfan +``` + +### Gentoo + +Install the ```mbpfan``` package with: + + sudo emerge -av app-laptop/mbpfan + + +### Solus + +On Solus, install the package with: +``` +sudo eopkg install mbpfan +``` +then enable the service. + + +### Ubuntu + +On Ubuntu 18.04 or later install via: + +``` +sudo apt-get install mbpfan +``` + +### Generic Install Instructions (All Other Operating Systems) + +Compile with + + make + +Install with + + sudo make install + +It copies mbpfan to /usr/sbin, mbpfan.conf to /etc (and overwrites existing files), +README.md to /usr/share/doc/mbpfan, and mbpfan.8.gz to /usr/share/man/man8 + +If you would like to compile with Clang instead of GCC, simply set your system's +default compiler to be Clang. Tested with Clang 3.8 and 3.9. Tested with Clang +4.0 along with llvm-lld (The LLVM Linker). + + +Run The Tests (Optional) +------------------------ +Users may run the tests after building the program. Please run the following command _from within the source directory_. + + sudo make tests + +Note that this only works on MacBook and not desktop computers due to different environment expectations. + + +## Run Instructions + +If not installed, run with + + sudo bin/mbpfan + +If installed, manually run with + + sudo mbpfan + +If installed and using the init file, run with (Ubuntu example) + + sudo service mbpfan start + + +## Starting at boot + +**Ubuntu** + +For systemd based init systems (Ubuntu 16.04+), see the systemd section below. + +For upstart based init systems (Ubuntu before 16.04), an example upstart job has been provided. +For using it, execute: + + sudo cp mbpfan.upstart /etc/init/mbpfan.conf + sudo start mbpfan + +**Debian** +An init file suitable for /lib/lsb/init-functions (Debian) +is located in the main folder of the source files, called mbpfan.init.debian +Rename it to mbpfan, give it execution permissions (chmod +x mbpfan) +and move it to /etc/init.d +Then, add it to the default runlevels with (as root): + + sudo update-rc.d mbpfan defaults + +**Redhat, CentOS, Fedora** +An init file suitable for /etc/rc.d/init.d/functions +(RHEL/CentOS & Fedora) is also located at the same place, this file is called +mbpfan.init.redhat. Also rename it to mbpfan, give it execution permissions +and move it to /etc/init.d +To add the script to the default runlevels, run the following as root: + + chkconfig --level 2345 mbpfan on && chkconfig --level 016 mbpfan off + +**Gentoo** + +To automatically run mbpfan at boot, run as root: + + rc-update add mbpfan default + + +**systemd** +As a special bonus, a service file for systemd is also included. To use it, +execute the following (as root): + + sudo cp mbpfan.service /etc/systemd/system/ + sudo systemctl enable mbpfan.service + sudo systemctl daemon-reload + sudo systemctl start mbpfan.service + +**dinit** +A [dinit](https://github.com/davmac314/dinit) service definition is also included. To use it, execute the following: + + sudo cp mbpfan.dinit /etc/dinit.d/mbpfan + sudo dinitctl enable mbpfan + sudo dinitctl start mbpfan + +## Usage + + Usage: ./mbpfan OPTION(S) + + -h Show the help screen + -f Run in foreground + -v Be (a lot) verbose + +## References + +* [mbpfan on Ask Ubuntu](https://askubuntu.com/search?q=mbpfan+is%3Aquestion) + +## License + +GNU General Public License version 3 + +## Credits + +**This Project Is Based On:** + +* http://allanmcrae.com/2010/05/simple-macbook-pro-fan-daemon/ +* http://allanmcrae.com/2011/08/mbp-fan-daemon-update/ +* https://launchpad.net/macfanctld +* https://www.lobotomo.com/products/FanControl/ + +**This Project uses following library:** + +* [ANSI C Application Settings Management](http://pokristensson.com/settings.html) by Per Ola Kristensson. diff --git a/mbpfan.8.gz b/mbpfan.8.gz new file mode 100644 index 0000000..76146d0 Binary files /dev/null and b/mbpfan.8.gz differ diff --git a/mbpfan.c b/mbpfan.c deleted file mode 100644 index 7cf3844..0000000 --- a/mbpfan.c +++ /dev/null @@ -1,147 +0,0 @@ -/* - * mbpfan.c - automatically control fan for MacBook Pro - * Copyright (C) 2010 Allan McRae - * Modifications by Rafael Vega - * - * 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. - * - * 20110811 - v1.1 - * - * Notes: - * Uses only the temperatures from the processors as input. - * Assumes two processors and one fan. - * Requires coretemp and applesmc kernel modules to be loaded. - * - * Tested models: - * MacBook Pro 8.1 13" (Intel i7 - Linux 3.2) - */ - - -#include -#include -#include - -/* lazy min/max... */ -#define min(a,b) a < b ? a : b -#define max(a,b) a > b ? a : b - -/* basic fan speed parameters */ -unsigned short min_fan_speed=2000; -unsigned short max_fan_speed=6200; - -/* temperature thresholds - * low_temp - temperature below which fan speed will be at minimum - * high_temp - fan will increase speed when higher than this temperature - * max_temp - fan will run at full speed above this temperature */ -unsigned short low_temp=63; -unsigned short high_temp=66; -unsigned short max_temp=86; -/* unsigned short low_temp=55; */ -/* unsigned short high_temp=65; */ -/* unsigned short max_temp=80; */ - -/* temperature polling interval */ -unsigned short polling_interval=10; - - -/* Controls the speed of the fan */ -void set_fan_speed(unsigned short speed) -{ - FILE *file; - - file=fopen("/sys/devices/platform/applesmc.768/fan1_min", "w"); - fprintf(file, "%d", speed); - fclose(file); -} - - -/* Takes "manual" control of fan */ -/* void prepare_fan() */ -/* { */ -/* FILE *file; */ -/* */ -/* file=fopen("/sys/devices/platform/applesmc.768/fan1_manual", "w"); */ -/* fprintf(file, "%d", 1); */ -/* fclose(file); */ -/* } */ - - -/* Returns average CPU temp in degrees (ceiling) */ -unsigned short get_temp() -{ - FILE *file; - unsigned short temp; - unsigned int t0, t1; - - file=fopen("/sys/devices/platform/coretemp.0/temp2_input", "r"); - fscanf(file, "%d", &t0); - fclose(file); - - file=fopen("/sys/devices/platform/coretemp.0/temp3_input", "r"); - fscanf(file, "%d", &t1); - fclose(file); - - temp = (unsigned short)(ceil((float)(t0 + t1) / 2000.)); - return temp; -} - - -int main() -{ - unsigned short old_temp, new_temp, fan_speed, steps; - short temp_change; - float step_up, step_down; - - /* prepare_fan(); */ - - /* assume running on boot so set fan speed to minimum */ - new_temp = get_temp(); - fan_speed = 2000; - set_fan_speed(fan_speed); - sleep(polling_interval); - - step_up = (float)(max_fan_speed - min_fan_speed) / - (float)((max_temp - high_temp) * (max_temp - high_temp + 1) / 2); - - step_down = (float)(max_fan_speed - min_fan_speed) / - (float)((max_temp - low_temp) * (max_temp - low_temp + 1) / 2); - - while(1) - { - old_temp = new_temp; - new_temp = get_temp(); - - if(new_temp >= max_temp && fan_speed != max_fan_speed) { - fan_speed = max_fan_speed; - } - - if(new_temp <= low_temp && fan_speed != min_fan_speed) { - fan_speed = min_fan_speed; - } - - temp_change = new_temp - old_temp; - - if(temp_change > 0 && new_temp > high_temp && new_temp < max_temp) { - steps = (new_temp - high_temp) * (new_temp - high_temp + 1) / 2; - fan_speed = max(fan_speed, ceil(min_fan_speed + steps * step_up)); - } - - if(temp_change < 0 && new_temp > low_temp && new_temp < max_temp) { - steps = (max_temp - new_temp) * (max_temp - new_temp + 1) / 2; - fan_speed = min(fan_speed, floor(max_fan_speed - steps * step_down)); - } - - set_fan_speed(fan_speed); - sleep(polling_interval); - } - - return 0; -} diff --git a/mbpfan.conf b/mbpfan.conf new file mode 100644 index 0000000..c2a9caf --- /dev/null +++ b/mbpfan.conf @@ -0,0 +1,20 @@ +[general] +# see https://ineed.coffee/3838/a-beginners-tutorial-for-mbpfan-under-ubuntu for the values +# +# mbpfan will load the max / min speed of from the files produced by the applesmc driver. If these files are not found it will set all fans to the default of min_speed = 2000 and max_speed = 6200 +# by setting the values for the speeds in this config it will override whatever it finds in: +# /sys/devices/platform/applesmc.768/fan*_min +# /sys/devices/platform/applesmc.768/fan*_max +# or the defaults. +# +# multiple fans can be configured by using the config key of min_fan*_speed and max_fan*_speed +# the number used will correlate to the file number of the fan in the applesmc driver that are used to control the fan speed. +# +#min_fan1_speed = 2000 # put the *lowest* value of "cat /sys/devices/platform/applesmc.768/fan*_min" +#max_fan1_speed = 6200 # put the *highest* value of "cat /sys/devices/platform/applesmc.768/fan*_max" + +# temperature units in celcius +low_temp = 63 # if temperature is below this, fans will run at minimum speed +high_temp = 66 # if temperature is above this, fan speed will gradually increase +max_temp = 86 # if temperature is above this, fans will run at maximum speed +polling_interval = 1 # default is 1 seconds diff --git a/mbpfan.conf.test0 b/mbpfan.conf.test0 new file mode 100644 index 0000000..5095078 --- /dev/null +++ b/mbpfan.conf.test0 @@ -0,0 +1,8 @@ +[general] +# see https://ineed.coffee/3838/a-beginners-tutorial-for-mbpfan-under-ubuntu for the values +min_fan1_speed = 2000 # put the *lowest* value of "cat /sys/devices/platform/applesmc.768/fan*_min" +max_fan1_speed = 6200 # put the *highest* value of "cat /sys/devices/platform/applesmc.768/fan*_max" +low_temp = 63 # try ranges 55-63, default is 63 +high_temp = 66 # try ranges 58-66, default is 66 +max_temp = 86 # take highest number returned by "cat /sys/devices/platform/coretemp.*/hwmon/hwmon*/temp*_max", divide by 1000 +polling_interval = 7 # default is 1 second diff --git a/mbpfan.conf.test1 b/mbpfan.conf.test1 new file mode 100644 index 0000000..5f098b7 --- /dev/null +++ b/mbpfan.conf.test1 @@ -0,0 +1,7 @@ +[general] +min_fan1_speed = 2000 # default is 2000 +max_fan1_speed = 2600 # default is 2600 +low_temp = 63 # try ranges 55-63, default is 63 +high_temp = 66 # try ranges 58-66, default is 66 +max_temp = 86 # do not set it > 90, default is 86 +polling_interval = 2 # default is 1 second diff --git a/mbpfan.conf.test2 b/mbpfan.conf.test2 new file mode 100644 index 0000000..90b5537 --- /dev/null +++ b/mbpfan.conf.test2 @@ -0,0 +1,7 @@ +[general] +min_fan1_speed = 2000 # default is 2000 +min_fan2_speed = 2000 # default is 6200 +low_temp = 63 # try ranges 55-63, default is 63 +high_temp = 66 # try ranges 58-66, default is 66 +max_temp = 86 # do not set it > 90, default is 86 +polling_interval = 1 # default is 1 second diff --git a/mbpfan.depend.conf b/mbpfan.depend.conf new file mode 100644 index 0000000..77ce462 --- /dev/null +++ b/mbpfan.depend.conf @@ -0,0 +1 @@ +coretemp diff --git a/mbpfan.dinit b/mbpfan.dinit new file mode 100644 index 0000000..cb2c3a7 --- /dev/null +++ b/mbpfan.dinit @@ -0,0 +1,7 @@ +type = bgprocess +command = /usr/bin/mbpfan +restart = true +logfile = /var/log/dinit/mbpfan.log +waits-for = loginready +pid-file = /var/run/mbpfan.pid + diff --git a/mbpfan.init.debian b/mbpfan.init.debian new file mode 100644 index 0000000..e279704 --- /dev/null +++ b/mbpfan.init.debian @@ -0,0 +1,103 @@ +#! /bin/sh +### BEGIN INIT INFO +# Provides: mbpfan +# Required-Start: $remote_fs $syslog +# Required-Stop: $remote_fs $syslog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: mbpfan initscript +# Description: Start the mbpfan daemon +### END INIT INFO + +DESC="Start the mbpfan daemon" +NAME=mbpfan +PATH=/sbin:/usr/sbin:/bin:/usr/bin +DAEMON=/usr/sbin/$NAME +PIDFILE=/var/run/$NAME.pid +SCRIPTNAME=/etc/init.d/$NAME +DAEMON_ARGS="" + +# Exit if the package is not installed +[ -x "$DAEMON" ] || exit 0 + +# Load the VERBOSE setting and other rcS variables +. /lib/init/vars.sh + +# Define LSB log_* functions. +# Depend on lsb-base (>= 3.0-6) to ensure that this file is present. +. /lib/lsb/init-functions + +# Function that starts the daemon/service +do_start() +{ + start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \ + || return 1 + start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- \ + $DAEMON_ARGS \ + || return 2 +} + +# Function that stops the daemon/service +do_stop() +{ + # Return + start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME + RETVAL="$?" + [ "$RETVAL" = 2 ] && return 2 + start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON + [ "$?" = 2 ] && return 2 + return "$RETVAL" +} + +# Function that sends a SIGHUP to the daemon/service +do_reload() +{ + start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME + return 0 +} + +case "$1" in + start) + [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME" + do_start + case "$?" in + 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; + 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; + esac + ;; + stop) + [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME" + do_stop + case "$?" in + 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; + 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; + esac + ;; + status) + status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $? + ;; + restart|force-reload) + log_daemon_msg "Restarting $DESC" "$NAME" + do_stop + case "$?" in + 0|1) + do_start + case "$?" in + 0) log_end_msg 0 ;; + 1) log_end_msg 1 ;; # Old process is still running + *) log_end_msg 1 ;; # Failed to start + esac + ;; + *) + # Failed to stop + log_end_msg 1 + ;; + esac + ;; + *) + echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2 + exit 3 + ;; +esac + +: diff --git a/mbpfan.init.gentoo b/mbpfan.init.gentoo new file mode 100644 index 0000000..cd41258 --- /dev/null +++ b/mbpfan.init.gentoo @@ -0,0 +1,18 @@ +#!/sbin/openrc-run + +depend() { + use logger +} + +start() { + ebegin "Starting mbpfan" + start-stop-daemon --start --quiet --exec /usr/sbin/mbpfan + eend $? +} + +stop() { + ebegin "Stopping mbpfan" + start-stop-daemon --stop --quiet --exec /usr/sbin/mbpfan + eend $? +} + diff --git a/mbpfan.init.redhat b/mbpfan.init.redhat new file mode 100644 index 0000000..a83765b --- /dev/null +++ b/mbpfan.init.redhat @@ -0,0 +1,101 @@ +#!/bin/sh +# +# mbpfan Start the mbpfan daemon +# +# chkconfig: 2 3 4 5 15 85 +# description: Start the mbpfan daemon + +### BEGIN INIT INFO +# Provides: mbpfan +# Required-Start: $remote_fs $syslog +# Required-Stop: $remote_fs $syslog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: mbpfan initscript +# Description: Start the mbpfan daemon +### END INIT INFO + +# Source function library. +. /etc/rc.d/init.d/functions + +exec="/usr/sbin/mbpfan" +prog="mbpfan" + +[ -e /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog + +lockfile=/var/lock/subsys/$prog + +start() { + [ -x $exec ] || exit 5 + echo -n $"Starting $prog: " + daemon $exec + retval=$? + echo + [ $retval -eq 0 ] && touch $lockfile + return $retval +} + +stop() { + echo -n $"Stopping $prog: " + killproc $prog + retval=$? + echo + [ $retval -eq 0 ] && rm -f $lockfile + return $retval +} + +restart() { + stop + start +} + +reload() { + restart +} + +force_reload() { + restart +} + +rh_status() { + # run checks to determine if the service is running or use generic status + status $prog +} + +rh_status_q() { + rh_status >/dev/null 2>&1 +} + + +case "$1" in + start) + rh_status_q && exit 0 + $1 + ;; + stop) + rh_status_q || exit 0 + $1 + ;; + restart) + $1 + ;; + reload) + rh_status_q || exit 7 + $1 + ;; + force-reload) + force_reload + ;; + status) + rh_status + ;; + condrestart|try-restart) + rh_status_q || exit 0 + restart + ;; + *) + echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}" + exit 2 +esac +exit $? + diff --git a/mbpfan.rc b/mbpfan.rc deleted file mode 100644 index 630ea4a..0000000 --- a/mbpfan.rc +++ /dev/null @@ -1,67 +0,0 @@ -#!/bin/bash - -daemon_name=mbpfan - -. /etc/rc.conf -. /etc/rc.d/functions - -get_pid() { - pidof -o %PPID $daemon_name -} - -case "$1" in - start) - stat_busy "Starting $daemon_name daemon" - - PID=$(get_pid) - if [ -z "$PID" ]; then - [ -f /var/run/$daemon_name.pid ] && rm -f /var/run/$daemon_name.pid - # RUN - $daemon_name & - # - if [ $? -gt 0 ]; then - stat_fail - exit 1 - else - echo $(get_pid) > /var/run/$daemon_name.pid - add_daemon $daemon_name - stat_done - fi - else - stat_fail - exit 1 - fi - ;; - - stop) - stat_busy "Stopping $daemon_name daemon" - PID=$(get_pid) - # KILL - [ ! -z "$PID" ] && kill $PID &> /dev/null - # - if [ $? -gt 0 ]; then - stat_fail - exit 1 - else - rm -f /var/run/$daemon_name.pid &> /dev/null - rm_daemon $daemon_name - stat_done - fi - ;; - - restart) - $0 stop - sleep 3 - $0 start - ;; - - status) - stat_busy "Checking $daemon_name status"; - ck_status $daemon_name - ;; - - *) - echo "usage: $0 {start|stop|restart|status}" -esac - -exit 0 diff --git a/mbpfan.service b/mbpfan.service new file mode 100644 index 0000000..5ac729a --- /dev/null +++ b/mbpfan.service @@ -0,0 +1,15 @@ +[Unit] +Description=A fan manager daemon for MacBook Pro +After=syslog.target +After=sysinit.target + +[Service] +Type=simple +ExecStart=/usr/sbin/mbpfan -f +ExecReload=/usr/bin/kill -HUP $MAINPID +PIDFile=/run/mbpfan.pid +Restart=always +RestartSec=1 + +[Install] +WantedBy=sysinit.target diff --git a/mbpfan.spec b/mbpfan.spec new file mode 100644 index 0000000..8d1f550 --- /dev/null +++ b/mbpfan.spec @@ -0,0 +1,65 @@ +Name: mbpfan +URL: https://github.com/dgraziotin/mbpfan +License: GPLv3 +Group: System Environment/Daemons +Version: %{SOURCE_VERSION} +Release: 3 +Summary: A simple daemon to control fan speed on all MacBook/MacBook Pros (probably all Apple computers) for Linux 3.x.x and 4.x.x +Source: v%{version}.tar.gz + +%description +This is an enhanced version of Allan McRae mbpfan + +mbpfan is a daemon that uses input from coretemp module and sets the fan speed using the applesmc module. This enhanced version assumes any number of processors and fans (max. 10). + +It only uses the temperatures from the processors as input. +It requires coretemp and applesmc kernel modules to be loaded. +It requires root use +It daemonizes or stays in foreground +Verbose mode for both syslog and stdout +Users can configure it using the file /etc/mbpfan.conf + +%prep +%setup -q -n %{name}-%{version} + +%build +make + +%install +install -D -m755 bin/mbpfan $RPM_BUILD_ROOT/usr/sbin/mbpfan +install -D -m644 mbpfan.conf $RPM_BUILD_ROOT/etc/mbpfan.conf +install -D -m644 mbpfan.service $RPM_BUILD_ROOT/usr/lib/systemd/system/mbpfan.service + +%clean +rm -rf $RPM_BUILD_ROOT + +%post +%systemd_post mbpfan.service +echo "mbpfan will auto detect sane values for min and max fan speeds." +echo "If you want to customize these values please edit:" +echo "/etc/mbpfan.conf" +echo "To start the daemon now type:" +echo "systemctl start mbpfan" +echo "To run also at boot, type:" +echo "systemctl enable mbpfan" + +%preun +%systemd_preun mbpfan.service + +%postun +%systemd_postun_with_restart mbpfan.service + +%files +%defattr (-,root,root) +%doc AUTHORS README.md +/usr/sbin/mbpfan +%config /etc/mbpfan.conf +/usr/lib/systemd/system/mbpfan.service + +%changelog +* Mon Sep 10 2018 Michele Codutti - 2.0.2-3 +- Removed autoconfig with suggested procedure because has been integrated on mbpfan. + +* Sun Aug 19 2018 Michele Codutti - 2.0.2-2 +- Autoconfig with suggested procedure. +- Initial packaging diff --git a/mbpfan.upstart b/mbpfan.upstart new file mode 100644 index 0000000..7299b4f --- /dev/null +++ b/mbpfan.upstart @@ -0,0 +1,14 @@ +# mbpfan - A simple daemon to control fan speed on all Macbook/Macbook Pros \ +# (probably all Apple computers) for Linux 3.x.x + +description "mbpfan" + +start on filesystem or runlevel [2345] +stop on runlevel [!2345] + +respawn +umask 022 + +console log + +exec /usr/sbin/mbpfan -f diff --git a/src/daemon.c b/src/daemon.c new file mode 100644 index 0000000..dd3e61d --- /dev/null +++ b/src/daemon.c @@ -0,0 +1,214 @@ +/** + * Copyright (C) 2012 Peter Lombardo + * Modifications (2012) by Ismail Khatib + * Modifications (2012-present) by Daniel Graziotin + * Modifications (2017-present) by Robert Musial + * + * 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. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "mbpfan.h" +#include "global.h" +#include "daemon.h" +#include "util.h" + +int daemonize = 1; +int verbose = 0; +sig_atomic_t do_exit = 0; +sig_atomic_t do_reload = 0; + +int write_pid(int pid) +{ + FILE *file = NULL; + file = fopen(PROGRAM_PID, "w"); + + if (file != NULL) { + fprintf(file, "%d", pid); + fclose(file); + return 1; + + } else { + return 0; + } +} + +int read_pid() +{ + FILE *file = NULL; + int pid = -1; + file = fopen(PROGRAM_PID, "r"); + + if (file != NULL) { + fscanf(file, "%d", &pid); + fclose(file); + if (kill(pid, 0) == -1 && errno == ESRCH) { /* a process with such a pid does not exist, remove the pid file */ + if (remove(PROGRAM_PID) == 0) { + return -1; + } + } + return pid; + } + + return -1; +} + +int delete_pid() +{ + return remove(PROGRAM_PID); +} + +void cleanup_and_exit(int exit_code) +{ + delete_pid(); + set_fans_auto(fans); + + struct s_fans *next_fan; + while (fans != NULL) { + next_fan = fans->next; + if (fans->file != NULL) { + fclose(fans->file); + } + free(fans->label); + free(fans->fan_output_path); + free(fans->fan_manual_path); + free(fans); + fans = next_fan; + } + + struct s_sensors *next_sensor; + while (sensors != NULL) { + next_sensor = sensors->next; + if (sensors->file != NULL) { + fclose(sensors->file); + } + free(sensors->path); + free(sensors); + sensors = next_sensor; + } + + exit(exit_code); +} + +static void sighup_handler(int signal) +{ + do_reload = 1; +} + +static void sigterm_handler(int signal) +{ + do_exit = 1; +} + +void go_daemon(void (*fan_control)()) +{ + + // Setup signal handling before we start + signal(SIGHUP, sighup_handler); + signal(SIGTERM, sigterm_handler); + signal(SIGQUIT, sigterm_handler); + signal(SIGINT, sigterm_handler); + + // Setup syslog logging - see SETLOGMASK(3) + if (verbose) { + setlogmask(LOG_UPTO(LOG_DEBUG)); + openlog(PROGRAM_NAME, LOG_CONS | LOG_NDELAY | LOG_PERROR | LOG_PID, LOG_USER); + + } else { + setlogmask(LOG_UPTO(LOG_INFO)); + openlog(PROGRAM_NAME, LOG_CONS, LOG_USER); + } + + mbp_log(LOG_INFO, "%s %s starting up", PROGRAM_NAME, PROGRAM_VERSION); + + // configure timer slack + int err = prctl(PR_SET_TIMERSLACK, 1000 * 1000 * 1000, 0, 0, 0); + if (err == -1) { + perror("prctl"); + } + + pid_t pid_slave; + pid_t sid_slave; + + if (daemonize) { + + pid_slave = fork(); + + if (pid_slave < 0) { + exit(EXIT_FAILURE); + } + + if (pid_slave > 0) { + signal(SIGCHLD, SIG_IGN); + // kill the father + exit(EXIT_SUCCESS); + } + + umask(0022); + + // new sid_slave for the child process + sid_slave = setsid(); + + if (sid_slave < 0) { + exit(EXIT_FAILURE); + } + + if ((chdir("/")) < 0) { + exit(EXIT_FAILURE); + } + + /* Close out the standard file descriptors */ + close(STDIN_FILENO); + close(STDOUT_FILENO); + close(STDERR_FILENO); + } + + int current_pid = getpid(); + + if (read_pid() == -1) { + if (verbose) { + mbp_log(LOG_INFO, "Writing a new .pid file with value %d at: %s", current_pid, PROGRAM_PID); + } + + if (write_pid(current_pid) == 0) { + mbp_log(LOG_ERR, "Can not create a .pid file at: %s. Aborting", PROGRAM_PID); + exit(EXIT_FAILURE); + + } else { + if (verbose) { + mbp_log(LOG_INFO, "Successfully written a new .pid file with value %d at: %s", current_pid, PROGRAM_PID); + } + } + + } else { + mbp_log(LOG_ERR, "A previously created .pid file exists at: %s. Aborting", PROGRAM_PID); + exit(EXIT_FAILURE); + } + + fan_control(); + + if (daemonize) { + syslog(LOG_INFO, "%s daemon exiting", PROGRAM_NAME); + } +} diff --git a/src/daemon.h b/src/daemon.h new file mode 100644 index 0000000..b935a34 --- /dev/null +++ b/src/daemon.h @@ -0,0 +1,60 @@ +/** + * Copyright (C) (2012-present) Daniel Graziotin + * + * 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. + * + */ + +#ifndef _DAEMON_H_ +#define _DAEMON_H_ + +#include + +extern sig_atomic_t do_exit; +extern sig_atomic_t do_reload; + +/** + * Write the PID of the forked daemon to the + * .pid file defined in char *program_pid + * Return TRUE on success + * Return FALSE otherwise + */ +int write_pid(int pid); + +/** + * Read PID of the forked daemon from the + * .pid file defined in char *program_pid + * Return the pid on success + * Return -1 otherwise + */ +int read_pid(); + +/** + * Deletes the .pid file defined in + * char *program_pid + * Return TRUE on success + * Return FALSE otherwise + */ +int delete_pid(); + +/** + * ...handles signals :-) + */ +void signal_handler(int signal); + +/** + * Daemonizes + */ +void go_daemon(void (*function)()); + +void cleanup_and_exit(int exit_code); + +#endif diff --git a/src/global.h b/src/global.h new file mode 100644 index 0000000..65a22a5 --- /dev/null +++ b/src/global.h @@ -0,0 +1,43 @@ +#ifndef _GLOBAL_H_ +#define _GLOBAL_H_ + +#include + +#define PROGRAM_NAME "mbpfan" +#define PROGRAM_VERSION "2.4.0" +#define PROGRAM_PID "/run/mbpfan.pid" + +extern int daemonize; +extern int verbose; + +struct s_sensors { + FILE *file; + char *path; + unsigned int temperature; + struct s_sensors *next; +}; + +struct s_fans { + FILE *file; + char *path; // TODO: unused + char *label; + char *fan_output_path; + char *fan_manual_path; + int step_up; + int step_down; + int fan_id; + int old_speed; + int fan_max_speed; + int fan_min_speed; + struct s_fans *next; +}; + +/** Represents a Temperature sensor + */ +typedef struct s_sensors t_sensors; +typedef struct s_fans t_fans; + +extern t_sensors *sensors; +extern t_fans *fans; + +#endif diff --git a/src/main.c b/src/main.c new file mode 100644 index 0000000..14f0b7a --- /dev/null +++ b/src/main.c @@ -0,0 +1,75 @@ +/** + * Copyright (C) (2012-present) Daniel Graziotin + * Modifications (2017-present) by Robert Musial + * + * 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. + * + */ + +/** + * Code formatted with astyle -A3 -s --break-blocks=all --add-brackets *.c *.h + */ + +#include +#include +#include // NOLINT(misc-include-cleaner) +#include +#include +#include "mbpfan.h" +#include "daemon.h" +#include "global.h" + +void print_usage(int argc, char *argv[]) +{ + if (argc >= 1) { + printf("Usage: %s OPTION(S) \n", argv[0]); + printf("Options:\n"); + printf("\t-h Show this help screen\n"); + printf("\t-f Run in foreground\n"); + printf("\t-v Be (a lot) verbose\n"); + printf("\n"); + } +} + +int main(int argc, char *argv[]) +{ + + int c; + + while ((c = getopt(argc, argv, "hfv|help")) != -1) { // NOLINT(misc-include-cleaner) + switch (c) { + case 'h': + print_usage(argc, argv); + return EXIT_SUCCESS; + break; + + case 'f': + daemonize = 0; + break; + + case 'v': + verbose = 1; + break; + + default: + print_usage(argc, argv); + return EXIT_SUCCESS; + break; + } + } + + check_requirements(argv[0]); + + // pointer to mbpfan() function in mbpfan.c + void (*fan_control)() = mbpfan; + go_daemon(fan_control); + return EXIT_SUCCESS; +} diff --git a/src/mbpfan.c b/src/mbpfan.c new file mode 100644 index 0000000..b45788c --- /dev/null +++ b/src/mbpfan.c @@ -0,0 +1,734 @@ +/** + * mbpfan.c - automatically control fan for MacBook Pro + * Copyright (C) 2010 Allan McRae + * Modifications by Rafael Vega + * Modifications (2012) by Ismail Khatib + * Modifications (2012-present) by Daniel Graziotin [CURRENT MAINTAINER] + * Modifications (2017-present) by Robert Musial + * Modifications (2018-present) by Ati Sharma + * + * 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. + * + * + * Notes: + * Assumes any number of processors, cores, sensors and fans + * (as defined in NUM_PROCESSORS, NUM_HWMONS, NUM_TEMP_INPUTS and NUM_FANS) + * It uses only the temperatures from the processors as input. + * Requires coretemp and applesmc kernel modules to be loaded. + * Requires root use + * + * Tested models: see README.md + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "daemon.h" +#include "mbpfan.h" +#include "global.h" +#include "settings.h" +#include "util.h" + +/* lazy min/max... */ +#define min(a, b) ((a) < (b) ? (a) : (b)) +#define max(a, b) ((a) > (b) ? (a) : (b)) + +#define CORETEMP_PATH "/sys/devices/platform/coretemp.0" +#define APPLESMC_PATH "/sys/devices/platform/applesmc.768" +#define ALT_APPLESMC_PATH "/sys/bus/acpi/drivers/applesmc" + +/* temperature thresholds + * low_temp - temperature below which fan speed will be at minimum + * high_temp - fan will increase speed when higher than this temperature + * max_temp - fan will run at full speed above this temperature */ +int low_temp = 63; // try ranges 55-63 +int high_temp = 66; // try ranges 58-66 +int max_temp = 86; // do not set it > 90 + +// maximum number of processors etc supported +#define NUM_PROCESSORS 6 +#define NUM_HWMONS 12 +#define NUM_TEMP_INPUTS 64 +#define NUM_FANS 10 +// sane defaults when user provides unexpected values +#define MIN_FAN_SPEED_DEFAULT 500 +#define MAX_FAN_SPEED_DEFAULT 6500 + +int polling_interval = 1; + +t_sensors *sensors = NULL; +t_fans *fans = NULL; +char applesmc_path[PATH_MAX]; +char applesmc_fan_path[PATH_MAX]; + + +char *smprintf(const char *fmt, ...) +{ + char *buf; + int cnt; + va_list ap; + + // find buffer length + va_start(ap, fmt); + cnt = vsnprintf(NULL, 0, fmt, ap); + va_end(ap); + if (cnt < 0) { + return NULL; + } + + // create and write to buffer + buf = malloc(cnt + 1); + va_start(ap, fmt); + vsnprintf(buf, cnt + 1, fmt, ap); + va_end(ap); + return buf; +} + +bool is_modern_sensors_path() +{ + struct utsname kernel; + uname(&kernel); + + char *str_kernel_version; + str_kernel_version = strtok(kernel.release, "."); + + if (atoi(str_kernel_version) < 3) { + mbp_log(LOG_ERR, "mbpfan detected a pre-3.x.x linux kernel. Detected version: %s. Exiting.\n", kernel.release); + exit(EXIT_FAILURE); + } + + int counter; + + for (counter = 0; counter < NUM_HWMONS; counter++) { + int temp; + for (temp = 1; temp < NUM_TEMP_INPUTS; ++temp) { + char *path = smprintf("/sys/devices/platform/coretemp.0/hwmon/hwmon%d/temp%d_input", counter, temp); + int res = access(path, R_OK); + free(path); + if (res == 0) { + return 1; + } + } + } + + return 0; +} + +t_sensors *retrieve_sensors() +{ + t_sensors *sensors_head = NULL; + t_sensors *s = NULL; + + char *path = NULL; + char *path_begin = NULL; + + const char *path_end = "_input"; + int sensors_found = 0; + + if (!is_modern_sensors_path()) { + if (verbose) { + mbp_log(LOG_INFO, "Using legacy path for kernel < 3.15.0"); + } + + path_begin = strdup("/sys/devices/platform/coretemp.0/temp"); + + } else { + + if (verbose) { + mbp_log(LOG_INFO, "Using new sensor path for kernel >= 3.15.0 or some CentOS versions with kernel 3.10.0 "); + } + + // loop over up to 6 processors + int processor; + for (processor = 0; processor < NUM_PROCESSORS; processor++) { + + if (path_begin != NULL) { + free(path_begin); + } + path_begin = smprintf("/sys/devices/platform/coretemp.%d/hwmon/hwmon", processor); + + int counter; + for (counter = 0; counter < NUM_HWMONS; counter++) { + + char *hwmon_path = smprintf("%s%d", path_begin, counter); + + int res = access(hwmon_path, R_OK); + if (res == 0) { + + free(path_begin); + path_begin = smprintf("%s/temp", hwmon_path); + + if (verbose) { + mbp_log(LOG_INFO, "Found hwmon path at %s", path_begin); + } + + free(hwmon_path); + break; + } + + free(hwmon_path); + } + + int core = 0; + for (core = 0; core < NUM_TEMP_INPUTS; core++) { + path = smprintf("%s%d%s", path_begin, core, path_end); + + FILE *file = fopen(path, "r"); + + if (file != NULL) { + s = (t_sensors *)malloc(sizeof(t_sensors)); + s->path = strdup(path); + fscanf(file, "%u", &s->temperature); + + if (sensors_head == NULL) { + sensors_head = s; + sensors_head->next = NULL; + + } else { + t_sensors *tmp = sensors_head; + + while (tmp->next != NULL) { + tmp = tmp->next; + } + + tmp->next = s; + tmp->next->next = NULL; + } + + s->file = file; + sensors_found++; + } + + free(path); + path = NULL; + } + } + } + + if (verbose) { + mbp_log(LOG_INFO, "Found %d sensors", sensors_found); + } + + if (sensors_found == 0) { + mbp_log(LOG_CRIT, "mbpfan could not detect any temp sensor. Please contact the developer."); + exit(EXIT_FAILURE); + } + + free(path_begin); + path_begin = NULL; + + return sensors_head; +} + +static int read_value(const char *path) +{ + int value = -1; + FILE *file = fopen(path, "r"); + if (file != NULL) { + fscanf(file, "%d", &value); + fclose(file); + } + return value; +} + +static void read_value_str(const char *path, char *str, size_t len) +{ + FILE *file = fopen(path, "r"); + if (file != NULL) { + fgets(str, len, file); + fclose(file); + } +} + +static void trim_trailing_whitespace(char *str) +{ + for (ssize_t i = strlen(str) - 1; i >= 0; --i) { + if (isspace(str[i]) || str[i] == '\n') { + str[i] = '\0'; + } + } +} + +t_fans *retrieve_fans() +{ + t_fans *fans_head = NULL; + t_fans *fan = NULL; + + char *path_output = NULL; + char *path_label = NULL; + char *path_manual = NULL; + char *path_fan_max = NULL; + char *path_fan_min = NULL; + + const char *path_begin = (const char *) &applesmc_fan_path; + const char *path_output_end = "_output"; + const char *path_label_end = "_label"; + const char *path_man_end = "_manual"; + const char *path_max_speed = "_max"; + const char *path_min_speed = "_min"; + + int counter = 0; + int fans_found = 0; + + for (counter = 0; counter < NUM_FANS; counter++) { + + path_output = smprintf("%s%d%s", path_begin, counter, path_output_end); + path_label = smprintf("%s%d%s", path_begin, counter, path_label_end); + path_manual = smprintf("%s%d%s", path_begin, counter, path_man_end); + path_fan_min = smprintf("%s%d%s", path_begin, counter, path_min_speed); + path_fan_max = smprintf("%s%d%s", path_begin, counter, path_max_speed); + + FILE *file = fopen(path_output, "w"); + + if (file != NULL) { + fan = (t_fans *)malloc(sizeof(t_fans)); + fan->fan_output_path = strdup(path_output); + fan->fan_manual_path = strdup(path_manual); + fan->fan_id = counter; + + int fan_speed = read_value(path_fan_min); + if (fan_speed == -1 || fan_speed < MIN_FAN_SPEED_DEFAULT) + fan->fan_min_speed = MIN_FAN_SPEED_DEFAULT; + else + fan->fan_min_speed = fan_speed; + + fan_speed = read_value(path_fan_max); + if (fan_speed == -1 || fan_speed > MAX_FAN_SPEED_DEFAULT) + fan->fan_max_speed = MAX_FAN_SPEED_DEFAULT; + else + fan->fan_max_speed = fan_speed; + + size_t max_label_len = 64; + fan->label = malloc(max_label_len); + read_value_str(path_label, fan->label, max_label_len); + trim_trailing_whitespace(fan->label); + + fan->old_speed = 0; + + if (fans_head == NULL) { + fans_head = fan; + fans_head->next = NULL; + + } else { + t_fans *tmp = fans_head; + + while (tmp->next != NULL) { + tmp = tmp->next; + } + + tmp->next = fan; + tmp->next->next = NULL; + } + + fan->file = file; + fans_found++; + } + free(path_fan_min); + path_fan_min = NULL; + free(path_label); + path_label = NULL; + free(path_fan_max); + path_fan_max = NULL; + free(path_output); + path_output = NULL; + free(path_manual); + path_manual = NULL; + } + + if (verbose) { + mbp_log(LOG_INFO, "Found %d fans", fans_found); + } + + if (fans_found == 0) { + mbp_log(LOG_CRIT, "mbpfan could not detect any fan. Please contact the developer."); + exit(EXIT_FAILURE); + } + + return fans_head; +} + +static void set_fans_mode(t_fans *fans, int mode) +{ + t_fans *tmp = fans; + FILE *file; + + while (tmp != NULL) { + file = fopen(tmp->fan_manual_path, "rw+"); + + if (file != NULL) { + fprintf(file, "%d", mode); + fclose(file); + } + + tmp = tmp->next; + } +} + +void set_fans_man(t_fans *fans) +{ + + set_fans_mode(fans, 1); +} + +void set_fans_auto(t_fans *fans) +{ + + set_fans_mode(fans, 0); +} + +t_sensors *refresh_sensors(t_sensors *sensors) +{ + t_sensors *tmp = sensors; + + while (tmp != NULL) { + if (tmp->file != NULL) { + char buf[16]; + int len = pread(fileno(tmp->file), buf, sizeof(buf), /*offset=*/0); + buf[len] = '\0'; + tmp->temperature = strtod(buf, NULL); + } + + tmp = tmp->next; + } + + return sensors; +} + +/* Controls the speed of a fan */ +void set_fan_speed(t_fans *fan, int speed) +{ + if (fan != NULL && fan->file != NULL && fan->old_speed != speed) { + char buf[16]; + int len = snprintf(buf, sizeof(buf), "%d", speed); + int res = pwrite(fileno(fan->file), buf, len, /*offset=*/0); + if (res == -1) { + perror("Could not set fan speed"); + } + fan->old_speed = speed; + } +} + +void set_fan_minimum_speed(t_fans *fans) +{ + t_fans *tmp = fans; + + while (tmp != NULL) { + set_fan_speed(tmp, tmp->fan_min_speed); + tmp = tmp->next; + } +} +unsigned short get_temp(t_sensors *sensors) +{ + sensors = refresh_sensors(sensors); + unsigned int temp = 0; + + t_sensors *tmp = sensors; + + while (tmp != NULL) { + temp = max(temp, tmp->temperature); + tmp = tmp->next; + } + + return temp / 1000; +} + +void retrieve_settings(const char *settings_path, t_fans *fans) +{ + Settings *settings = NULL; + int result = 0; + FILE *f = NULL; + + if (settings_path == NULL) { + f = fopen("/etc/mbpfan.conf", "r"); + + } else { + f = fopen(settings_path, "r"); + } + + if (f == NULL) { + /* Could not open configfile */ + if (verbose) { + mbp_log(LOG_INFO, "Couldn't open configfile, using defaults"); + } + + } else { + settings = settings_open(f); + fclose(f); + + if (settings == NULL) { + /* Could not read configfile */ + if (verbose) { + mbp_log(LOG_WARNING, "Couldn't read configfile"); + } + + } else { + + t_fans *fan = fans; + + while (fan != NULL) { + + char *config_key; + config_key = smprintf("min_fan%d_speed", fan->fan_id); + /* Read configfile values */ + result = settings_get_int(settings, "general", config_key); + if (result != 0) { + fan->fan_min_speed = result; + } + free(config_key); + + config_key = smprintf("max_fan%d_speed", fan->fan_id); + result = settings_get_int(settings, "general", config_key); + + if (result != 0) { + fan->fan_max_speed = result; + } + free(config_key); + fan = fan->next; + } + result = settings_get_int(settings, "general", "low_temp"); + + if (result != 0) { + low_temp = result; + } + + result = settings_get_int(settings, "general", "high_temp"); + + if (result != 0) { + high_temp = result; + } + + result = settings_get_int(settings, "general", "max_temp"); + + if (result != 0) { + max_temp = result; + } + + result = settings_get_int(settings, "general", "polling_interval"); + + if (result != 0) { + polling_interval = result; + } + + /* Destroy the settings object */ + settings_delete(settings); + } + } +} + +void check_requirements(const char *program_path) +{ + + /** + * Check for root + */ + + uid_t uid = getuid(), euid = geteuid(); + + if (uid != 0 || euid != 0) { + mbp_log(LOG_ERR, "%s needs root privileges. Please run %s as root. Exiting.", program_path, program_path); + exit(EXIT_FAILURE); + } + + /** + * Check for coretemp and applesmc modules + */ + DIR *dir = opendir(CORETEMP_PATH); + + if (dir == NULL) { + mbp_log(LOG_ERR, "%s needs coretemp support. Please either load it or build it into the kernel. Exiting.", program_path); + exit(EXIT_FAILURE); + } + + closedir(dir); + memset(&applesmc_path, 0, PATH_MAX); + memset(&applesmc_fan_path, 0, PATH_MAX); + + dir = opendir(APPLESMC_PATH); + + if (dir != NULL) { + strncpy((char *) &applesmc_path, APPLESMC_PATH, PATH_MAX); + closedir(dir); + } else { + /** + * Check for alternate ACPI device path for newer macbooks + */ + dir = opendir(ALT_APPLESMC_PATH); + if (dir != NULL) { + struct dirent *ent; + while ((ent = readdir(dir)) != NULL) { + if (strncmp("APP", (const char *) &ent->d_name, 3) == 0) { + snprintf((char *) &applesmc_path, PATH_MAX, "%s/%s", ALT_APPLESMC_PATH, (char *) &ent->d_name); + break; + } + } + closedir(dir); + } + } + + if (strlen(applesmc_path) != 0) { + strncpy((char *) &applesmc_fan_path, (char *) &applesmc_path, PATH_MAX); + strcat((char *) &applesmc_fan_path, "/fan"); + if (verbose) mbp_log(LOG_INFO, "applesmc device path: %s", (char *) &applesmc_path); + + } else { + mbp_log(LOG_ERR, "%s needs applesmc support. Please either load it or build it into the kernel. Exiting.", program_path); + exit(EXIT_FAILURE); + } +} + +int get_max_mhz(void) +{ + int max_mhz = -1; + DIR *dir = opendir("/sys/devices/system/cpu"); + if (dir == NULL) { + return -1; + } + struct dirent *ent; + while ((ent = readdir(dir)) != NULL) { + if (strncmp(ent->d_name, "cpu", 3) != 0 || strcmp(ent->d_name, "cpufreq") == 0 || strcmp(ent->d_name, "cpuidle") == 0) { + continue; + } + char *path = smprintf("/sys/devices/system/cpu/%s/cpufreq/scaling_cur_freq", ent->d_name); + max_mhz = max(max_mhz, read_value(path) / 1000); + free(path); + } + closedir(dir); + return max_mhz; +} + +void mbpfan() +{ + int old_temp, new_temp, fan_speed, steps; + int temp_change; + + sensors = retrieve_sensors(); + fans = retrieve_fans(); + + retrieve_settings(NULL, fans); + + t_fans *fan = fans; + while (fan != NULL) { + + if (fan->fan_min_speed > fan->fan_max_speed) { + mbp_log(LOG_ERR, "Invalid fan speeds: %d %d", fan->fan_min_speed, fan->fan_max_speed); + exit(EXIT_FAILURE); + } + fan = fan->next; + } + + if (low_temp > high_temp || high_temp > max_temp) { + mbp_log(LOG_ERR, "Invalid temperatures: %d %d %d", low_temp, high_temp, max_temp); + exit(EXIT_FAILURE); + } + + set_fans_man(fans); + + new_temp = get_temp(sensors); + set_fan_minimum_speed(fans); + + fan = fans; + while (fan != NULL) { + + fan->step_up = (float)(fan->fan_max_speed - fan->fan_min_speed) / (float)((max_temp - high_temp) * (max_temp - high_temp + 1) / 2.0); + + fan->step_down = (float)(fan->fan_max_speed - fan->fan_min_speed) / (float)((max_temp - low_temp) * (max_temp - low_temp + 1) / 2.0); + fan = fan->next; + } + +recalibrate: + if (verbose) { + mbp_log(LOG_INFO, "Sleeping for 2 seconds to get first temp delta"); + } + sleep(2); + + while (1) { + if (do_exit) { + syslog(LOG_WARNING, "Received SIGTERM, SIGQUIT, or SIGINT signal."); + cleanup_and_exit(EXIT_SUCCESS); + } + + if (do_reload) { + syslog(LOG_WARNING, "Received SIGHUP signal."); + retrieve_settings(NULL, fans); + do_reload = 0; + } + + old_temp = new_temp; + new_temp = get_temp(sensors); + + fan = fans; + + while (fan != NULL) { + fan_speed = fan->old_speed; + + if (new_temp >= max_temp && fan->old_speed != fan->fan_max_speed) { + fan_speed = fan->fan_max_speed; + } + + if (new_temp <= low_temp && fan_speed != fan->fan_min_speed) { + fan_speed = fan->fan_min_speed; + } + + temp_change = new_temp - old_temp; + + if (temp_change > 0 && new_temp > high_temp && new_temp < max_temp) { + steps = (new_temp - high_temp) * (new_temp - high_temp + 1) / 2; + fan_speed = max(fan_speed, ceil(fan->fan_min_speed + steps * fan->step_up)); + } + + if (temp_change < 0 && new_temp > low_temp && new_temp < max_temp) { + steps = (max_temp - new_temp) * (max_temp - new_temp + 1) / 2; + fan_speed = min(fan_speed, floor(fan->fan_max_speed - steps * fan->step_down)); + } + + if (verbose) { + mbp_log(LOG_INFO, "Old Temp: %d New Temp: %d Fan: %s Speed: %d Max MHz: %d", old_temp, new_temp, fan->label, fan_speed, get_max_mhz()); + } + + set_fan_speed(fan, fan_speed); + fan = fan->next; + } + + if (verbose) { + mbp_log(LOG_INFO, "Sleeping for %d seconds", polling_interval); + } + + time_t before_sleep = time(NULL); + + // call nanosleep instead of sleep to avoid rt_sigprocmask and + // rt_sigaction + struct timespec ts; + ts.tv_sec = polling_interval; + ts.tv_nsec = 0; + nanosleep(&ts, NULL); + + time_t after_sleep = time(NULL); + if (after_sleep - before_sleep > 2 * polling_interval) { + mbp_log(LOG_INFO, "Clock skew detected - slept for %ld seconds but expected %d", after_sleep - before_sleep, polling_interval); + set_fans_man(fans); + goto recalibrate; + } + } +} diff --git a/src/mbpfan.h b/src/mbpfan.h new file mode 100644 index 0000000..e09d562 --- /dev/null +++ b/src/mbpfan.h @@ -0,0 +1,108 @@ +/** + * Copyright (C) 2010 Allan McRae + * Modifications (2012-present) by Daniel Graziotin + * + * 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. + * + */ + +#ifndef _MBPFAN_H_ +#define _MBPFAN_H_ + +#include + +#include "global.h" + +/** Temperature Thresholds + * low_temp - temperature below which fan speed will be at minimum + * high_temp - fan will increase speed when higher than this temperature + * max_temp - fan will run at full speed above this temperature */ +extern int low_temp; +extern int high_temp; +extern int max_temp; + +/** Temperature polling interval + * Default value was 10 (seconds) + */ +extern int polling_interval; + +char *smprintf(const char *fmt, ...) __attribute__((format(printf, 1, 2))); + +/** + * Return true if the kernel is < 3.15.0 + */ +bool is_legacy_sensors_path(); + +/** + * Tries to use the settings located in + * /etc/mbpfan.conf + * If it fails, the default hardcoded settings are used + */ +void retrieve_settings(const char *settings_path, t_fans *fans); + +/** + * Detect the sensors in /sys/devices/platform/coretemp.0/temp + * and /sys/devices/platform/coretemp.1/temp etc + * Return a linked list of t_sensors (first temperature detected) + */ +t_sensors *retrieve_sensors(); + +/** + * Given a linked list of t_sensors, refresh their detected + * temperature + */ +t_sensors *refresh_sensors(t_sensors *sensors); + +/** + * Detect the fans in /sys/devices/platform/applesmc.768/ + * Associate each fan to a sensor + */ +t_fans *retrieve_fans(); + +/** + * Given a list of sensors with associated fans + * Set them to manual control + */ +void set_fans_man(t_fans *fans); + +/** + * Given a list of sensors with associated fans + * Set them to automatic control + */ +void set_fans_auto(t_fans *fans); + +/** + * Given a sensors with associated fans + * Change their speed + */ +void set_fan_speed(t_fans *fan, int speed); + +/** + * Given a list of fans set their minumum fan speed + */ +void set_fan_minimum_speed(t_fans *fans); +/** + * Return maximum CPU temp in degrees + */ +unsigned short get_temp(t_sensors *sensors); + +/** + * Check if user has proper access and that required + * kernel modules are available + */ +void check_requirements(const char *program_path); + +/** + * Main Program + */ +void mbpfan(); + +#endif diff --git a/src/settings.c b/src/settings.c new file mode 100644 index 0000000..b89c143 --- /dev/null +++ b/src/settings.c @@ -0,0 +1,1069 @@ +/* + * settings version 1.0.1 + * + * ANSI C implementation for managing application settings. + * + * Version History: + * 1.0.0 (2009) - Initial release + * 1.0.1 (2010) - Fixed small memory leak in settings_delete + * (Thanks to Edwin van den Oetelaar) + * 1.0.2 (2011) - Adapted code for new strmap API + * + * settings.c + * + * Copyright (c) 2009-2011 Per Ola Kristensson. + * + * Per Ola Kristensson + * Inference Group, Department of Physics + * University of Cambridge + * Cavendish Laboratory + * JJ Thomson Avenue + * CB3 0HE Cambridge + * United Kingdom + * + * settings is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * settings 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with settings. If not, see . + */ +#include +#include +#include +#include "settings.h" +#include "strmap.h" + +#define MAX_SECTIONCHARS 256 +#define MAX_KEYCHARS 256 +#define MAX_VALUECHARS 256 +#define MAX_LINECHARS (MAX_KEYCHARS + MAX_VALUECHARS + 10) + +#define COMMENT_CHAR '#' +#define SECTION_START_CHAR '[' +#define SECTION_END_CHAR ']' +#define KEY_VALUE_SEPARATOR_CHAR '=' + +#define DEFAULT_STRMAP_CAPACITY 256 + +typedef struct Section Section; +typedef struct ParseState ParseState; + +struct Settings { + Section *sections; + unsigned int section_count; +}; + +struct Section { + char *name; + StrMap *map; +}; + +struct ParseState { + char *current_section; + unsigned int current_section_n; + int has_section; +}; + +enum ConvertMode { + CONVERT_MODE_INT, + CONVERT_MODE_LONG, + CONVERT_MODE_DOUBLE, +}; + +typedef enum ConvertMode ConvertMode; + +static void trim_str(const char *str, char *out_buf); +static int parse_str(Settings *settings, char *str, ParseState *parse_state); +static int is_blank_char(char c); +static int is_blank_str(const char *str); +static int is_comment_str(const char *str); +static int is_section_str(const char *str); +static int is_key_value_str(const char *str); +static int is_key_without_value_str(const char *str); +static const char *get_token(char *str, char delim, char **last); +static int get_section_from_str(const char *str, char *out_buf, unsigned int out_buf_n); +static int get_key_value_from_str(const char *str, char *out_buf1, unsigned int out_buf1_n, char *out_buf2, unsigned int out_buf2_n); +static int get_key_without_value_from_str(const char *str, char *out_buf, unsigned int out_buf_n); +static int get_converted_value(const Settings *settings, const char *section, const char *key, ConvertMode mode, void *out); +static int get_converted_tuple(const Settings *settings, const char *section, const char *key, char delim, ConvertMode mode, void *out, unsigned int n_out); +static Section *get_section(Section *sections, unsigned int n, const char *name); +static void enum_map(const char *key, const char *value, const void *obj); + +Settings *settings_new() +{ + Settings *settings; + + settings = (Settings *)malloc(sizeof(Settings)); + + if (settings == NULL) { + return NULL; + } + + settings->section_count = 0; + settings->sections = NULL; + return settings; +} + +void settings_delete(Settings *settings) +{ + unsigned int i, n; + Section *section; + + if (settings == NULL) { + return; + } + + section = settings->sections; + n = settings->section_count; + i = 0; + + while (i < n) { + sm_delete(section->map); + + if (section->name != NULL) { + free(section->name); + } + + section++; + i++; + } + + free(settings->sections); + free(settings); +} + +Settings *settings_open(FILE *stream) +{ + Settings *settings; + char buf[MAX_LINECHARS]; + char trimmed_buf[MAX_LINECHARS]; + char section_buf[MAX_LINECHARS]; + ParseState parse_state; + + if (stream == NULL) { + return NULL; + } + + settings = settings_new(); + + if (settings == NULL) { + return NULL; + } + + parse_state.current_section = section_buf; + parse_state.current_section_n = sizeof(section_buf); + parse_state.has_section = 0; + trim_str("", trimmed_buf); + + while (fgets(buf, MAX_LINECHARS, stream) != NULL) { + trim_str(buf, trimmed_buf); + + if (!parse_str(settings, trimmed_buf, &parse_state)) { + return NULL; + } + } + + return settings; +} + +int settings_save(const Settings *settings, FILE *stream) +{ + unsigned int i, n; + Section *section; + char buf[MAX_LINECHARS]; + + if (settings == NULL) { + return 0; + } + + if (stream == NULL) { + return 0; + } + + section = settings->sections; + n = settings->section_count; + i = 0; + + while (i < n) { + sprintf(buf, "[%s]\n", section->name); + fputs(buf, stream); + sm_enum(section->map, enum_map, stream); + section++; + i++; + fputs("\n", stream); + } + + return 0; +} + +int settings_get(const Settings *settings, const char *section, const char *key, char *out_buf, unsigned int n_out_buf) +{ + Section *s; + + if (settings == NULL) { + return 0; + } + + s = get_section(settings->sections, settings->section_count, section); + + if (s == NULL) { + return 0; + } + + return sm_get(s->map, key, out_buf, n_out_buf); +} + +int settings_get_int(const Settings *settings, const char *section, const char *key) +{ + int i; + + if (get_converted_value(settings, section, key, CONVERT_MODE_INT, &i)) { + return i; + } + + return 0; +} + +long settings_get_long(const Settings *settings, const char *section, const char *key) +{ + long l; + + if (get_converted_value(settings, section, key, CONVERT_MODE_LONG, &l)) { + return l; + } + + return 0; +} + +double settings_get_double(const Settings *settings, const char *section, const char *key) +{ + double d; + + if (get_converted_value(settings, section, key, CONVERT_MODE_DOUBLE, &d)) { + return d; + } + + return 0; +} + +int settings_get_int_tuple(const Settings *settings, const char *section, const char *key, int *out, unsigned int n_out) +{ + return get_converted_tuple(settings, section, key, ',', CONVERT_MODE_INT, out, n_out); +} + +long settings_get_long_tuple(const Settings *settings, const char *section, const char *key, long *out, unsigned int n_out) +{ + return get_converted_tuple(settings, section, key, ',', CONVERT_MODE_LONG, out, n_out); +} + +double settings_get_double_tuple(const Settings *settings, const char *section, const char *key, double *out, unsigned int n_out) +{ + return get_converted_tuple(settings, section, key, ',', CONVERT_MODE_DOUBLE, out, n_out); +} + +int settings_set(Settings *settings, const char *section, const char *key, const char *value) +{ + Section *s; + + if (settings == NULL) { + return 0; + } + + if (section == NULL || key == NULL || value == NULL) { + return 0; + } + + if (strlen(section) == 0) { + return 0; + } + + /* Get a pointer to the section */ + s = get_section(settings->sections, settings->section_count, section); + + if (s == NULL) { + /* The section is not created---create it */ + s = (Section *)realloc(settings->sections, (settings->section_count + 1) * sizeof(Section)); + + if (s == NULL) { + return 0; + } + + settings->sections = s; + settings->section_count++; + s = &(settings->sections[settings->section_count - 1]); + s->map = sm_new(DEFAULT_STRMAP_CAPACITY); + + if (s->map == NULL) { + free(s); + return 0; + } + + s->name = (char *)malloc((strlen(section) + 1) * sizeof(char)); + + if (s->name == NULL) { + sm_delete(s->map); + free(s); + return 0; + } + + strcpy(s->name, section); + } + + return sm_put(s->map, key, value); +} + +int settings_section_get_count(const Settings *settings, const char *section) +{ + Section *sect; + + if (settings == NULL) { + return 0; + } + + sect = get_section(settings->sections, settings->section_count, section); + + if (sect == NULL) { + return 0; + } + + return sm_get_count(sect->map); +} + +int settings_section_enum(const Settings *settings, const char *section, settings_section_enum_func enum_func, const void *obj) +{ + Section *sect; + + sect = get_section(settings->sections, settings->section_count, section); + + if (sect == NULL) { + return 0; + } + + return sm_enum(sect->map, enum_func, obj); +} + +/* Copies a trimmed variant without leading and trailing blank characters + * of the input string into the output buffer. The output buffer is assumed + * to be large enough to contain the entire input string. + */ +static void trim_str(const char *str, char *out_buf) +{ + unsigned int len; + const char *s0; + + while (*str != '\0' && is_blank_char(*str)) { + str++; + } + + s0 = str; + len = 0; + + while (*str != '\0') { + len++; + str++; + } + + if (len > 0) { + str--; + } + + while (is_blank_char(*str)) { + str--; + len--; + } + + memcpy(out_buf, s0, len); + out_buf[len] = '\0'; +} + +/* Parses a single input string and updates the provided settings object. + * The given parse state may be updated following a call. It is assumed this + * function is called in repeated succession for each input line read. The + * provided parse state should be initialized to the following before this + * function is called for the first time for an intended parse: + * + * parse_state->current_section: a pre-allocated character buffer this function + * can read and write to + * parse_state->current_section_n: sizeof(parse_state->current_section) + * parse_state->has_section: 0 (false) + */ +static int parse_str(Settings *settings, char *str, ParseState *parse_state) +{ + char buf[MAX_LINECHARS]; + char buf1[MAX_LINECHARS]; + char buf2[MAX_LINECHARS]; + int result; + + if (*str == '\0') { + return 1; + + } else if (is_blank_str(str)) { + return 1; + + } else if (is_comment_str(str)) { + return 1; + + } else if (is_section_str(str)) { + result = get_section_from_str(str, buf, sizeof(buf)); + + if (!result) { + return 0; + } + + if (strlen(buf) + 1 > parse_state->current_section_n) { + return 0; + } + + strcpy(parse_state->current_section, buf); + parse_state->has_section = 1; + return 1; + + } else if (is_key_value_str(str)) { + result = get_key_value_from_str(str, buf1, sizeof(buf1), buf2, sizeof(buf2)); + + if (!result) { + return 0; + } + + if (!parse_state->has_section) { + return 0; + } + + return settings_set(settings, parse_state->current_section, buf1, buf2); + + } else if (is_key_without_value_str(str)) { + result = get_key_without_value_from_str(str, buf, sizeof(buf)); + + if (!result) { + return 0; + } + + if (!parse_state->has_section) { + return 0; + } + + return settings_set(settings, parse_state->current_section, buf, ""); + + } else { + return 0; + } +} + +/* Returns true if the input character is blank, + * false otherwise. + */ +static int is_blank_char(char c) +{ + return c == ' ' || c == '\t' || c == '\r' || c == '\n'; +} + +/* Returns true if the input string is blank, + * false otherwise. + */ +static int is_blank_str(const char *str) +{ + while (*str != '\0') { + if (!is_blank_char(*str)) { + return 0; + } + + str++; + } + + return 1; +} + +/* Returns true if the input string denotes a comment, + * false otherwise. + */ +static int is_comment_str(const char *str) +{ + if (*str == COMMENT_CHAR) { + /* To be a comment the first character must be the + * comment character. + */ + return 1; + } + + return 0; +} + +/* Returns true if the input string denotes a section name, + * false otherwise. + */ +static int is_section_str(const char *str) +{ + if (*str != SECTION_START_CHAR) { + /* The first character must be the section start character */ + return 0; + } + + while (*str != '\0' && *str != SECTION_END_CHAR) { + str++; + } + + if (*str != SECTION_END_CHAR) { + /* The section end character must be present somewhere thereafter */ + return 0; + } + + return 1; +} + +/* Returns true if the input string denotes a key-value pair, + * false otherwise. + */ +static int is_key_value_str(const char *str) +{ + if (*str == KEY_VALUE_SEPARATOR_CHAR) { + /* It is illegal to start with the key-value separator */ + return 0; + } + + while (*str != '\0' && *str != KEY_VALUE_SEPARATOR_CHAR) { + str++; + } + + if (*str != KEY_VALUE_SEPARATOR_CHAR) { + /* The key-value separator must be present after the key part */ + return 0; + } + + return 1; +} + +/* Returns true if the input string denotes a key without a value, + * false otherwise. + */ +static int is_key_without_value_str(const char *str) +{ + if (*str == KEY_VALUE_SEPARATOR_CHAR) { + /* It is illegal to start with the key-value separator */ + return 0; + } + + while (*str != '\0' && *str != KEY_VALUE_SEPARATOR_CHAR) { + str++; + } + + if (*str == KEY_VALUE_SEPARATOR_CHAR) { + /* The key-value separator must not be present after the key part */ + return 0; + } + + return 1; +} + +/* + * Parses a section name from an input string. The input string is assumed to + * already have been identified as a valid input string denoting a section name. + */ +static int get_section_from_str(const char *str, char *out_buf, unsigned int out_buf_n) +{ + unsigned int count; + + count = 0; + /* Jump past the section begin character */ + str++; + + while (*str != '\0' && *str != SECTION_END_CHAR) { + /* Read in the section name into the output buffer */ + if (count == out_buf_n) { + return 0; + } + + *out_buf = *str; + out_buf++; + str++; + count++; + } + + /* Terminate the output buffer */ + if (count == out_buf_n) { + return 0; + } + + *out_buf = '\0'; + return 1; +} + +/* + * Parses a key and value from an input string. The input string is assumed to + * already have been identified as a valid input string denoting a key-value pair. + */ +static int get_key_value_from_str(const char *str, char *out_buf1, unsigned int out_buf1_n, char *out_buf2, unsigned int out_buf2_n) +{ + unsigned int count1; + unsigned int count2; + + count1 = 0; + count2 = 0; + + /* Read the key value from the input string and write it sequentially + * to the first output buffer by walking the input string until we either hit + * the null-terminator or the key-value separator. + */ + while (*str != '\0' && *str != KEY_VALUE_SEPARATOR_CHAR) { + /* Ensure the first output buffer is large enough. */ + if (count1 == out_buf1_n) { + return 0; + } + + /* Copy the character to the first output buffer */ + *out_buf1 = *str; + out_buf1++; + str++; + count1++; + } + + /* Terminate the first output buffer */ + if (count1 == out_buf1_n) { + return 0; + } + + *out_buf1 = '\0'; + + /* Now trace the first input buffer backwards until we hit a non-blank character */ + while (is_blank_char(*(out_buf1 - 1))) { + out_buf1--; + } + + *out_buf1 = '\0'; + + /* Try to proceed one more character, past the last read key-value + * delimiter, in the input string. + */ + if (*str != '\0') { + str++; + } + + /* Now find start of the value in the input string by walking the input + * string until we either hit the null-terminator or a blank character. + */ + while (*str != '\0' && is_blank_char(*str)) { + str++; + } + + while (*str != '\0') { + /* Fail if there is a possibility that we are overwriting the second + * input buffer. + */ + if (count2 == out_buf2_n) { + return 0; + } + + /* Copy the character to the second output buffer */ + *out_buf2 = *str; + out_buf2++; + str++; + count2++; + } + + /* Terminate the second output buffer */ + if (count2 == out_buf2_n) { + return 0; + } + + *out_buf2 = '\0'; + return 1; +} + +/* + * Parses a key from an input string. The input string is assumed to already + * have been identified as a valid input string denoting a key without a value. + */ +static int get_key_without_value_from_str(const char *str, char *out_buf, unsigned int out_buf_n) +{ + unsigned int count; + + count = 0; + + /* Now read the key value from the input string and write it sequentially + * to the output buffer by walking the input string until we either hit + * the null-terminator or the key-value separator. + */ + while (*str != '\0') { + /* Ensure the output buffer is large enough. */ + if (count == out_buf_n) { + return 0; + } + + /* Copy the character to the input buffer */ + *out_buf = *str; + out_buf++; + str++; + count++; + } + + /* Terminate the output buffer */ + if (count == out_buf_n) { + return 0; + } + + *out_buf = '\0'; + return 1; +} + +/* Returns a pointer to the next token in the input string delimited + * by the specified delimiter or null if no such token exist. The provided + * last pointer will be changed to point one position after the pointed + * token. The currently ouputted token will be null-terminated. + * + * An idiom for tokenizing a (in this case, comma-separated) string is: + * + * char test_string[] = "Token1,Token2,Token3"; + * char token[255]; + * char *str; + * + * str = test_string; + * while ((token = get_token(str, ',', &str) != NULL) { + * printf("token: %s", token); + * } + */ +static const char *get_token(char *str, char delim, char **last) +{ + + char *s0; + + s0 = str; + + /* If we hit the null-terminator the string + * is exhausted and another token does not + * exist. + */ + if (*str == '\0') { + return NULL; + } + + /* Walk the string until we encounter a + * null-terminator or the delimiter. + */ + while (*str != '\0' && *str != delim) { + str++; + } + + /* Terminate the return token, if necessary */ + if (*str != '\0') { + *str = '\0'; + str++; + } + + *last = str; + return s0; +} + +/* Returns a converted value pointed to by the provided key in the given section. + * The mode specifies which conversion takes place and dictates what value out + * is pointing to. The value out is pointing to will be replaced by the converted + * value assuming conversion is succesful. The function returns 1 if conversion + * is succsessful and 0 if the convertion could not be carried out. + */ +static int get_converted_value(const Settings *settings, const char *section, const char *key, ConvertMode mode, void *out) +{ + char value[MAX_VALUECHARS]; + + if (!settings_get(settings, section, key, value, MAX_VALUECHARS)) { + return 0; + } + + switch (mode) { + case CONVERT_MODE_INT: + *((int *)out) = atoi(value); + return 1; + + case CONVERT_MODE_LONG: + *((long *)out) = atol(value); + return 1; + + case CONVERT_MODE_DOUBLE: + *((double *)out) = atof(value); + return 1; + } + + return 0; +} + +/* Returns a converted tuple pointed to by the provided key in the given section. + * The tuple is created by splitting the value by the supplied delimiter and then + * converting each token after the split according to the specified mode. + * The array out is pointing to will be replaced by the converted tuple + * assuming conversion is succesful. The function returns 1 if conversion + * is succsessful and 0 if the convertion could not be carried out. + */ +static int get_converted_tuple(const Settings *settings, const char *section, const char *key, char delim, ConvertMode mode, void *out, unsigned int n_out) +{ + unsigned int count; + const char *token; + static char value[MAX_VALUECHARS]; + char *v; + + if (out == NULL) { + return 0; + } + + if (n_out == 0) { + return 0; + } + + if (!settings_get(settings, section, key, value, MAX_VALUECHARS)) { + return 0; + } + + v = value; + count = 0; + + /* Walk over all tokens in the value, and convert them and assign them + * to the output array as specified by the mode. + */ + while ((token = get_token(v, delim, &v)) != NULL && count < n_out) { + switch (mode) { + case CONVERT_MODE_INT: + ((int *)out)[count] = atoi(token); + break; + + case CONVERT_MODE_LONG: + ((long *)out)[count] = atol(token); + break; + + case CONVERT_MODE_DOUBLE: + ((double *)out)[count] = atof(token); + break; + + default: + return 0; + } + + count++; + } + + return 1; +} + +/* Returns a pointer to the section or null if the named section does not + * exist. + */ +static Section *get_section(Section *sections, unsigned int n, const char *name) +{ + unsigned int i; + Section *section; + + if (name == NULL) { + return NULL; + } + + section = sections; + i = 0; + + while (i < n) { + if (strcmp(section->name, name) == 0) { + return section; + } + + section++; + i++; + } + + return NULL; +} + +/* Callback function that is passed into the enumeration function in the + * string map. It casts the passed into object into a FILE pointer and + * writes out the key and value to the file. + */ +static void enum_map(const char *key, const char *value, const void *obj) +{ + FILE *stream; + char buf[MAX_LINECHARS]; + + if (key == NULL || value == NULL) { + return; + } + + if (obj == NULL) { + return; + } + + stream = (FILE *)obj; + + if (strlen(key) < MAX_KEYCHARS && strlen(value) < MAX_VALUECHARS) { + sprintf(buf, "%s%c%s\n", key, KEY_VALUE_SEPARATOR_CHAR, value); + fputs(buf, stream); + } +} + +/* + + GNU LESSER 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. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. + +*/ diff --git a/src/settings.h b/src/settings.h new file mode 100644 index 0000000..91266aa --- /dev/null +++ b/src/settings.h @@ -0,0 +1,501 @@ +/* + * settings version 1.0.0 + * + * ANSI C implementation for managing application settings. + * + * settings.h + * + * Copyright (c) 2009 Per Ola Kristensson. + * + * Per Ola Kristensson + * Inference Group, Department of Physics + * University of Cambridge + * Cavendish Laboratory + * JJ Thomson Avenue + * CB3 0HE Cambridge + * United Kingdom + * + * settings is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * settings 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with settings. If not, see . + */ +#ifndef _SETTINGS_H_ +#define _SETTINGS_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct Settings Settings; + +/* + * This callback function is called once per key-value when enumerating + * all keys inside a section. + * + * Parameters: + * + * key: A pointer to a null-terminated C string. The string must not + * be modified by the client. + * + * value: A pointer to a null-terminated C string. The string must + * not be modified by the client. + * + * obj: A pointer to a client-specific object. This parameter may be + * null. + * + * Return value: None. + */ +typedef void (*settings_section_enum_func)(const char *key, const char *value, const void *obj); + +/* + * Creates a settings object. + * + * Return value: A pointer to a settings object, + * or null if a new settings object could not be allocated. + */ +Settings *settings_new(); + +/* + * Releases all memory held by a settings object. + * + * Parameters: + * + * settings: A pointer to a settings object. This parameter cannot be null. + * If the supplied settings object has been previously released, the + * behaviour of this function is undefined. + * + * Return value: None. + */ +void settings_delete(Settings *settings); + +/* + * Constructs a settings object by loading settings in textual form + * from the given stream. + * + * Parameters: + * + * settings: A pointer to a settings object. This parameter cannot be null. + * + * stream: A pointer to a stream. This parameter cannot be null. + * + * Return value: A pointer to a settings object, + * or null if an error occurred. + */ +Settings *settings_open(FILE *stream); + +/* + * Saves the current settings object in textual form to the given stream. + * + * Parameters: + * + * settings: A pointer to a settings object. This parameter cannot be null. + * + * stream: A pointer to a stream. This parameter cannot be null. + * + * Return value: 1 if the operation succeeded, 0 otherwise. + */ +int settings_save(const Settings *settings, FILE *stream); + +/* + * Returns the value associated with the supplied key in the + * provided section. + * + * Parameters: + * + * settings: A pointer to a settings object. This parameter cannot be null. + * + * section: A pointer to a null-terminated C string. This parameter cannot + * be null. + * + * key: A pointer to a null-terminated C string. This parameter cannot + * be null. + * + * out_buf: A pointer to an output buffer which will contain the value, + * if it exists and fits into the buffer. + * + * n_out_buf: The size of the output buffer in bytes. + * + * Return value: If out_buf is set to null and n_out_buf is set to 0 the return + * value will be the number of bytes required to store the value (if it exists) + * and its null-terminator. For all other parameter configurations the return value + * is 1 if an associated value was found and completely copied into the output buffer, + * 0 otherwise. + */ +int settings_get(const Settings *settings, const char *section, const char *key, char *out_buf, unsigned int n_out_buf); + +/* + * Returns the integer value associated with the supplied key in the + * provided section. + * + * Parameters: + * + * settings: A pointer to a settings object. This parameter cannot be null. + * + * section: A pointer to a null-terminated C string. This parameter cannot + * be null. + * + * key: A pointer to a null-terminated C string. This parameter cannot + * be null. + * + * Return value: The integer value associated to the provided section and + * key, or 0 if no such value exists. + */ +int settings_get_int(const Settings *settings, const char *section, const char *key); + +/* + * Returns the long integer value associated with the supplied key in the + * provided section. + * + * Parameters: + * + * settings: A pointer to a settings object. This parameter cannot be null. + * + * section: A pointer to a null-terminated C string. This parameter cannot + * be null. + * + * key: A pointer to a null-terminated C string. This parameter cannot + * be null. + * + * Return value: The long integer value associated to the provided section and + * key, or 0 if no such value exists. + */ +long settings_get_long(const Settings *settings, const char *section, const char *key); + +/* + * Returns the double value associated with the supplied key in the + * provided section. + * + * Parameters: + * + * settings: A pointer to a settings object. This parameter cannot be null. + * + * section: A pointer to a null-terminated C string. This parameter cannot + * be null. + * + * key: A pointer to a null-terminated C string. This parameter cannot + * be null. + * + * Return value: The double value associated to the provided section and + * key, or 0 if no such value exists. + */ +double settings_get_double(const Settings *settings, const char *section, const char *key); + +/* + * Returns the integer tuple associated with the supplied key in the + * provided section. + * + * Parameters: + * + * settings: A pointer to a settings object. This parameter cannot be null. + * + * section: A pointer to a null-terminated C string. This parameter cannot + * be null. + * + * key: A pointer to a null-terminated C string. This parameter cannot + * be null. + * + * out: A pointer to an output buffer. + * + * n_out: The maximum number of elements the output buffer can hold. + * + * Return value: 1 if the entire tuple was copied into the output buffer, + * 0 otherwise. + */ +int settings_get_int_tuple(const Settings *settings, const char *section, const char *key, int *out, unsigned int n_out); + +/* + * Returns the long tuple associated with the supplied key in the + * provided section. + * + * Parameters: + * + * settings: A pointer to a settings object. This parameter cannot be null. + * + * section: A pointer to a null-terminated C string. This parameter cannot + * be null. + * + * key: A pointer to a null-terminated C string. This parameter cannot + * be null. + * + * out: A pointer to an output buffer. + * + * n_out: The maximum number of elements the output buffer can hold. + * + * Return value: 1 if the entire tuple was copied into the output buffer, + * 0 otherwise. + */ +long settings_get_long_tuple(const Settings *settings, const char *section, const char *key, long *out, unsigned int n_out); + +/* + * Returns the double tuple associated with the supplied key in the + * provided section. + * + * Parameters: + * + * settings: A pointer to a settings object. This parameter cannot be null. + * + * section: A pointer to a null-terminated C string. This parameter cannot + * be null. + * + * key: A pointer to a null-terminated C string. This parameter cannot + * be null. + * + * out: A pointer to an output buffer. + * + * n_out: The maximum number of elements the output buffer can hold. + * + * Return value: 1 if the entire tuple was copied into the output buffer, + * 0 otherwise. + */ +double settings_get_double_tuple(const Settings *settings, const char *section, const char *key, double *out, unsigned int n_out); + +/* + * Associates a value with the supplied key in the provided section. + * If the key is already associated with a value, the previous value + * is replaced. + * + * Parameters: + * + * settings: A pointer to a settings object. This parameter cannot be null. + * + * section: A pointer to a null-terminated C string. This parameter cannot + * be null. The string must have a string length > 0. The string will + * be copied. + * + * key: A pointer to a null-terminated C string. This parameter + * cannot be null. The string must have a string length > 0. The + * string will be copied. + * + * value: A pointer to a null-terminated C string. This parameter + * cannot be null. The string must have a string length > 0. The + * string will be copied. + * + * Return value: 1 if the association succeeded, 0 otherwise. + */ +int settings_set(Settings *setting, const char *section, const char *key, const char *value); + +/* + * Returns the number of associations between keys and values that exist + * in the provided section. + * + * Parameters: + * + * settings: A pointer to a settings object. This parameter cannot be null. + * + * section: A pointer to a null-terminated C string. This parameter cannot + * be null. + * + * Return value: The number of associations between keys and values in + * the provided section. + */ +int settings_section_get_count(const Settings *settings, const char *section); + +/* + * Enumerates all associations between keys and values in the provided + * section. + * + * Parameters: + * + * settings: A pointer to a settings object. This parameter cannot be null. + * + * section: A pointer to a null-terminated C string. This parameter cannot + * be null. + * + * enum_func: A pointer to a callback function that will be + * called by this procedure once for every key associated + * with a value. This parameter cannot be null. + * + * obj: A pointer to a client-specific object. This parameter will be + * passed back to the client's callback function. This parameter can + * be null. + * + * Return value: 1 if enumeration completed, 0 otherwise. + */ +int settings_section_enum(const Settings *settings, const char *section, settings_section_enum_func enum_func, const void *obj); + +#ifdef __cplusplus +} +#endif + +#endif + +/* + + GNU LESSER 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. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. + +*/ diff --git a/src/strmap.c b/src/strmap.c new file mode 100644 index 0000000..deebb7b --- /dev/null +++ b/src/strmap.c @@ -0,0 +1,566 @@ +/* + * strmap version 2.0.0 + * + * ANSI C hash table for strings. + * + * Version history: + * 1.0.0 - initial release + * 2.0.0 - changed function prefix from strmap to sm to ensure + * ANSI C compatibility + * + * strmap.c + * + * Copyright (c) 2009, 2011 Per Ola Kristensson. + * + * Per Ola Kristensson + * Inference Group, Department of Physics + * University of Cambridge + * Cavendish Laboratory + * JJ Thomson Avenue + * CB3 0HE Cambridge + * United Kingdom + * + * strmap is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * strmap 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with strmap. If not, see . + */ +#include +#include +#include "strmap.h" + +typedef struct Pair Pair; + +typedef struct Bucket Bucket; + +struct Pair { + char *key; + char *value; +}; + +struct Bucket { + unsigned int count; + Pair *pairs; +}; + +struct StrMap { + unsigned int count; + Bucket *buckets; +}; + +static Pair *get_pair(Bucket *bucket, const char *key); +static unsigned long hash(const char *str); + +StrMap *sm_new(unsigned int capacity) +{ + StrMap *map; + + map = (StrMap *)malloc(sizeof(StrMap)); + + if (map == NULL) { + return NULL; + } + + map->count = capacity; + map->buckets = (Bucket *)malloc(map->count * sizeof(Bucket)); + + if (map->buckets == NULL) { + free(map); + return NULL; + } + + memset(map->buckets, 0, map->count * sizeof(Bucket)); + return map; +} + +void sm_delete(StrMap *map) +{ + unsigned int i, j, n, m; + Bucket *bucket; + Pair *pair; + + if (map == NULL) { + return; + } + + n = map->count; + bucket = map->buckets; + i = 0; + + while (i < n) { + m = bucket->count; + pair = bucket->pairs; + j = 0; + + while (j < m) { + free(pair->key); + free(pair->value); + pair++; + j++; + } + + free(bucket->pairs); + bucket++; + i++; + } + + free(map->buckets); + free(map); +} + +int sm_get(const StrMap *map, const char *key, char *out_buf, unsigned int n_out_buf) +{ + unsigned int index; + Bucket *bucket; + Pair *pair; + + if (map == NULL) { + return 0; + } + + if (key == NULL) { + return 0; + } + + index = hash(key) % map->count; + bucket = &(map->buckets[index]); + pair = get_pair(bucket, key); + + if (pair == NULL) { + return 0; + } + + if (out_buf == NULL && n_out_buf == 0) { + return strlen(pair->value) + 1; + } + + if (out_buf == NULL) { + return 0; + } + + if (strlen(pair->value) >= n_out_buf) { + return 0; + } + + strcpy(out_buf, pair->value); + return 1; +} + +int sm_exists(const StrMap *map, const char *key) +{ + unsigned int index; + Bucket *bucket; + Pair *pair; + + if (map == NULL) { + return 0; + } + + if (key == NULL) { + return 0; + } + + index = hash(key) % map->count; + bucket = &(map->buckets[index]); + pair = get_pair(bucket, key); + + if (pair == NULL) { + return 0; + } + + return 1; +} + +int sm_put(StrMap *map, const char *key, const char *value) +{ + unsigned int key_len, value_len, index; + Bucket *bucket; + Pair *tmp_pairs, *pair; + char *tmp_value; + char *new_key, *new_value; + + if (map == NULL) { + return 0; + } + + if (key == NULL || value == NULL) { + return 0; + } + + key_len = strlen(key); + value_len = strlen(value); + /* Get a pointer to the bucket the key string hashes to */ + index = hash(key) % map->count; + bucket = &(map->buckets[index]); + + /* Check if we can handle insertion by simply replacing + * an existing value in a key-value pair in the bucket. + */ + if ((pair = get_pair(bucket, key)) != NULL) { + /* The bucket contains a pair that matches the provided key, + * change the value for that pair to the new value. + */ + if (strlen(pair->value) < value_len) { + /* If the new value is larger than the old value, re-allocate + * space for the new larger value. + */ + tmp_value = (char *)realloc(pair->value, (value_len + 1) * sizeof(char)); + + if (tmp_value == NULL) { + return 0; + } + + pair->value = tmp_value; + } + + /* Copy the new value into the pair that matches the key */ + strcpy(pair->value, value); + return 1; + } + + /* Allocate space for a new key and value */ + new_key = (char *)malloc((key_len + 1) * sizeof(char)); + + if (new_key == NULL) { + return 0; + } + + new_value = (char *)malloc((value_len + 1) * sizeof(char)); + + if (new_value == NULL) { + free(new_key); + return 0; + } + + /* Create a key-value pair */ + if (bucket->count == 0) { + /* The bucket is empty, lazily allocate space for a single + * key-value pair. + */ + bucket->pairs = (Pair *)malloc(sizeof(Pair)); + + if (bucket->pairs == NULL) { + free(new_key); + free(new_value); + return 0; + } + + bucket->count = 1; + + } else { + /* The bucket wasn't empty but no pair existed that matches the provided + * key, so create a new key-value pair. + */ + tmp_pairs = (Pair *)realloc(bucket->pairs, (bucket->count + 1) * sizeof(Pair)); + + if (tmp_pairs == NULL) { + free(new_key); + free(new_value); + return 0; + } + + bucket->pairs = tmp_pairs; + bucket->count++; + } + + /* Get the last pair in the chain for the bucket */ + pair = &(bucket->pairs[bucket->count - 1]); + pair->key = new_key; + pair->value = new_value; + /* Copy the key and its value into the key-value pair */ + strcpy(pair->key, key); + strcpy(pair->value, value); + return 1; +} + +int sm_get_count(const StrMap *map) +{ + unsigned int i, j, n, m; + unsigned int count; + Bucket *bucket; + + if (map == NULL) { + return 0; + } + + bucket = map->buckets; + n = map->count; + i = 0; + count = 0; + + while (i < n) { + m = bucket->count; + j = 0; + + while (j < m) { + count++; + j++; + } + + bucket++; + i++; + } + + return count; +} + +int sm_enum(const StrMap *map, sm_enum_func enum_func, const void *obj) +{ + unsigned int i, j, n, m; + Bucket *bucket; + Pair *pair; + + if (map == NULL) { + return 0; + } + + if (enum_func == NULL) { + return 0; + } + + bucket = map->buckets; + n = map->count; + i = 0; + + while (i < n) { + pair = bucket->pairs; + m = bucket->count; + j = 0; + + while (j < m) { + enum_func(pair->key, pair->value, obj); + pair++; + j++; + } + + bucket++; + i++; + } + + return 1; +} + +/* + * Returns a pair from the bucket that matches the provided key, + * or null if no such pair exist. + */ +static Pair *get_pair(Bucket *bucket, const char *key) +{ + unsigned int i, n; + Pair *pair; + + n = bucket->count; + + if (n == 0) { + return NULL; + } + + pair = bucket->pairs; + i = 0; + + while (i < n) { + if (pair->key != NULL && pair->value != NULL) { + if (strcmp(pair->key, key) == 0) { + return pair; + } + } + + pair++; + i++; + } + + return NULL; +} + +/* + * Returns a hash code for the provided string. + */ +static unsigned long hash(const char *str) +{ + unsigned long hash = 5381; + int c; + + while ((c = *str++)) { + hash = ((hash << 5) + hash) + c; + } + + return hash; +} + +/* + + GNU LESSER 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. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. + +*/ diff --git a/src/strmap.h b/src/strmap.h new file mode 100644 index 0000000..4f7ade1 --- /dev/null +++ b/src/strmap.h @@ -0,0 +1,351 @@ +/* + * strmap version 2.0.0 + * + * ANSI C hash table for strings. + * + * Version history: + * 1.0.0 - initial release + * 2.0.0 - changed function prefix from strmap to sm to ensure + * ANSI C compatibility + * + * strmap.h + * + * Copyright (c) 2009, 2011 Per Ola Kristensson. + * + * Per Ola Kristensson + * Inference Group, Department of Physics + * University of Cambridge + * Cavendish Laboratory + * JJ Thomson Avenue + * CB3 0HE Cambridge + * United Kingdom + * + * strmap is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * strmap 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with strmap. If not, see . + */ +#ifndef _STRMAP_H_ +#define _STRMAP_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct StrMap StrMap; + +/* + * This callback function is called once per key-value when enumerating + * all keys associated to values. + * + * Parameters: + * + * key: A pointer to a null-terminated C string. The string must not + * be modified by the client. + * + * value: A pointer to a null-terminated C string. The string must + * not be modified by the client. + * + * obj: A pointer to a client-specific object. This parameter may be + * null. + * + * Return value: None. + */ +typedef void (*sm_enum_func)(const char *key, const char *value, const void *obj); + +/* + * Creates a string map. + * + * Parameters: + * + * capacity: The number of top-level slots this string map + * should allocate. This parameter must be > 0. + * + * Return value: A pointer to a string map object, + * or null if a new string map could not be allocated. + */ +StrMap *sm_new(unsigned int capacity); + +/* + * Releases all memory held by a string map object. + * + * Parameters: + * + * map: A pointer to a string map. This parameter cannot be null. + * If the supplied string map has been previously released, the + * behaviour of this function is undefined. + * + * Return value: None. + */ +void sm_delete(StrMap *map); + +/* + * Returns the value associated with the supplied key. + * + * Parameters: + * + * map: A pointer to a string map. This parameter cannot be null. + * + * key: A pointer to a null-terminated C string. This parameter cannot + * be null. + * + * out_buf: A pointer to an output buffer which will contain the value, + * if it exists and fits into the buffer. + * + * n_out_buf: The size of the output buffer in bytes. + * + * Return value: If out_buf is set to null and n_out_buf is set to 0 the return + * value will be the number of bytes required to store the value (if it exists) + * and its null-terminator. For all other parameter configurations the return value + * is 1 if an associated value was found and completely copied into the output buffer, + * 0 otherwise. + */ +int sm_get(const StrMap *map, const char *key, char *out_buf, unsigned int n_out_buf); + +/* + * Queries the existence of a key. + * + * Parameters: + * + * map: A pointer to a string map. This parameter cannot be null. + * + * key: A pointer to a null-terminated C string. This parameter cannot + * be null. + * + * Return value: 1 if the key exists, 0 otherwise. + */ +int sm_exists(const StrMap *map, const char *key); + +/* + * Associates a value with the supplied key. If the key is already + * associated with a value, the previous value is replaced. + * + * Parameters: + * + * map: A pointer to a string map. This parameter cannot be null. + * + * key: A pointer to a null-terminated C string. This parameter + * cannot be null. The string must have a string length > 0. The + * string will be copied. + * + * value: A pointer to a null-terminated C string. This parameter + * cannot be null. The string must have a string length > 0. The + * string will be copied. + * + * Return value: 1 if the association succeeded, 0 otherwise. + */ +int sm_put(StrMap *map, const char *key, const char *value); + +/* + * Returns the number of associations between keys and values. + * + * Parameters: + * + * map: A pointer to a string map. This parameter cannot be null. + * + * Return value: The number of associations between keys and values. + */ +int sm_get_count(const StrMap *map); + +/* + * Enumerates all associations between keys and values. + * + * Parameters: + * + * map: A pointer to a string map. This parameter cannot be null. + * + * enum_func: A pointer to a callback function that will be + * called by this procedure once for every key associated + * with a value. This parameter cannot be null. + * + * obj: A pointer to a client-specific object. This parameter will be + * passed back to the client's callback function. This parameter can + * be null. + * + * Return value: 1 if enumeration completed, 0 otherwise. + */ +int sm_enum(const StrMap *map, sm_enum_func enum_func, const void *obj); + +#ifdef __cplusplus +} +#endif + +#endif + +/* + + GNU LESSER 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. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. + +*/ diff --git a/src/util.c b/src/util.c new file mode 100644 index 0000000..25415b9 --- /dev/null +++ b/src/util.c @@ -0,0 +1,21 @@ +#include +#include +#define _GNU_SOURCE +#include + +#include "global.h" + +void mbp_log(int level, const char *fmt, ...) +{ + va_list args; + if (daemonize) { + va_start(args, fmt); + vsyslog(level, fmt, args); // NOLINT(misc-include-cleaner) + va_end(args); + } + + va_start(args, fmt); + vprintf(fmt, args); + puts(""); // trailing newline + va_end(args); +} diff --git a/src/util.h b/src/util.h new file mode 100644 index 0000000..7f4a280 --- /dev/null +++ b/src/util.h @@ -0,0 +1,6 @@ +#ifndef _UTIL_H_ +#define _UTIL_H_ + +void mbp_log(int level, const char *fmt, ...) __attribute__((format(printf, 2, 3))); + +#endif diff --git a/tests/main.c b/tests/main.c new file mode 100644 index 0000000..2870554 --- /dev/null +++ b/tests/main.c @@ -0,0 +1,7 @@ +#include "minunit.h" + +int main(int argc, char *argv[]) +{ + (void)argc; + tests(argv[0]); +} diff --git a/tests/minunit.c b/tests/minunit.c new file mode 100644 index 0000000..5a54299 --- /dev/null +++ b/tests/minunit.c @@ -0,0 +1,275 @@ +/* file minunit_example.c */ +#include +#include +#include +#include +#include +#include +#include +#include "../src/global.h" +#include "../src/mbpfan.h" +#include "../src/settings.h" +#include "minunit.h" + +int tests_run = 0; + +static void free_fans(t_fans* fans) +{ + while (fans != NULL) { + t_fans* tmp = fans->next; + free(fans->fan_manual_path); + free(fans->fan_output_path); + free(fans->label); + free(fans); + fans = tmp; + } +} + +static void free_sensors(t_sensors* sensors) +{ + while (sensors != NULL) { + t_sensors* tmp = sensors->next; + free(sensors->path); + free(sensors); + sensors = tmp; + } +} + +static const char *test_sensor_paths() +{ + t_sensors* sensors = retrieve_sensors(); + mu_assert("No sensors found", sensors != NULL); + t_sensors* tmp = sensors; + + while(tmp != NULL) { + mu_assert("Sensor does not have a valid path", tmp->path != NULL); + + if(tmp->path != NULL) { + mu_assert("Sensor does not have valid temperature", tmp->temperature > 0); + } + + tmp = tmp->next; + } + + free_sensors(sensors); + return 0; +} + + +static const char *test_fan_paths() +{ + t_fans* fans = retrieve_fans(); + mu_assert("No fans found", fans != NULL); + t_fans* tmp = fans; + int found_fan_path = 0; + + while(tmp != NULL) { + if(tmp->fan_output_path != NULL) { + found_fan_path++; + } + + tmp = tmp->next; + } + + mu_assert("No fans found", found_fan_path != 0); + free_fans(fans); + return 0; +} + +unsigned time_seed() +{ + time_t now = time ( 0 ); + unsigned char *p = (unsigned char *)&now; + unsigned seed = 0; + size_t i; + + for ( i = 0; i < sizeof now; i++ ) { + seed = seed * ( UCHAR_MAX + 2U ) + p[i]; + } + + return seed; +} + +// nothing better than a horrible piece of code to +// stress a little bit the CPU +int stress(int n) +{ + int f = n; + + while (f > 0) { + while(n > 0) { + srand ( time_seed() ); + n--; + } + + f--; + n = f; + } + return 0; +} + +static const char *test_get_temp() +{ + t_sensors* sensors = retrieve_sensors(); + mu_assert("No sensors found", sensors != NULL); + unsigned short temp_1 = get_temp(sensors); + mu_assert("Invalid Global Temperature Found", temp_1 > 1 && temp_1 < 150); + stress(2000); + unsigned short temp_2 = get_temp(sensors); + mu_assert("Invalid Higher temp test (if fan was already spinning high, this is not worrying)", temp_1 < temp_2); + free_sensors(sensors); + return 0; +} + +static const char *test_config_file() +{ + FILE *f = NULL; + Settings *settings = NULL; + f = fopen("/etc/mbpfan.conf", "r"); + mu_assert("No config file found", f != NULL); + + if (f == NULL) { + return 0; + } + + settings = settings_open(f); + fclose(f); + mu_assert("Could not read settings from config file", settings != NULL); + + if (settings == NULL) { + return 0; + } + + mu_assert("Could not read low_temp from config file",settings_get_int(settings, "general", "low_temp") != 0); + mu_assert("Could not read high_temp from config file",settings_get_int(settings, "general", "high_temp") != 0); + mu_assert("Could not read max_temp from config file",settings_get_int(settings, "general", "max_temp") != 0); + mu_assert("Could not read polling_interval from config file",settings_get_int(settings, "general", "polling_interval") != 0); + /* Destroy the settings object */ + settings_delete(settings); + + return 0; +} + +static const char *test_settings() +{ + t_fans* fan = (t_fans *) malloc( sizeof( t_fans ) ); + fan->fan_id = 1; + fan->fan_max_speed = -1; + fan->next = NULL; + + retrieve_settings("./mbpfan.conf.test1", fan); + // choosing the maximum for iMac mid 2011 + mu_assert("max_fan_speed value is not 2600", fan->fan_max_speed == 2600); + mu_assert("polling_interval is not 2", polling_interval == 2); + + fan->fan_min_speed = -1; + retrieve_settings("./mbpfan.conf.test0", fan); + mu_assert("min_fan_speed value is not 2000", fan->fan_min_speed == 2000); + mu_assert("polling_interval is not 7", polling_interval == 7); + + t_fans* fan2 = (t_fans *)malloc(sizeof(t_fans)); + fan2->fan_id = 2; + fan2->fan_max_speed = -1; + fan2->next = NULL; + fan->next = fan2; + + retrieve_settings("./mbpfan.conf.test2", fan); + mu_assert("min_fan1_speed value is not 2000", fan->fan_min_speed == 2000); + mu_assert("min_fan2_speed value is not 2000", fan->next->fan_min_speed == 2000); + + free(fan2); + fan->next = NULL; + free(fan); + + return 0; + +} +int received = 0; + +static void handler(int signal) +{ + t_fans* fan = (t_fans *) malloc( sizeof( t_fans ) ); + fan->fan_id = 1; + fan->next = NULL; + + + switch(signal) { + case SIGHUP: + received = 1; + retrieve_settings("./mbpfan.conf.test1", fan); + free(fan); + break; + + default: + received = 0; + free(fan); + break; + } +} + +static const char *test_sighup_receive() +{ + signal(SIGHUP, handler); + raise(SIGHUP); + mu_assert("did not receive SIGHUP signal", received == 1); + return 0; +} + +static const char *test_settings_reload() +{ + t_fans* fan = (t_fans *) malloc( sizeof( t_fans ) ); + fan->fan_id = 1; + fan->fan_min_speed = -1; + fan->fan_manual_path = NULL; + fan->fan_output_path = NULL; + fan->label = NULL; + fan->next = NULL; + + signal(SIGHUP, handler); + retrieve_settings("./mbpfan.conf", fan); + printf("Testing the _supplied_ mbpfan.conf (not the one you are using)..\n"); + // cannot tests min_fan_speed since it is not set and thus auto-detected + mu_assert("polling_interval is not 1 before SIGHUP", polling_interval == 1); + raise(SIGHUP); + // cannot tests min_fan_speed since it is not set and thus auto-detected + mu_assert("polling_interval is not 2 after SIGHUP", polling_interval == 2); + retrieve_settings("./mbpfan.conf", fan); + free_fans(fan); + return 0; +} + + +static const char *all_tests() +{ + mu_run_test(test_sensor_paths); + mu_run_test(test_fan_paths); + mu_run_test(test_get_temp); + mu_run_test(test_config_file); + mu_run_test(test_settings); + mu_run_test(test_sighup_receive); + mu_run_test(test_settings_reload); + return 0; +} + +int tests(const char *program_path) +{ + verbose = 1; + + check_requirements(program_path); + + printf("Starting the tests..\n"); + printf("It is normal for them to take a bit to finish.\n"); + + const char *result = all_tests(); + + if (result != 0) { + printf("Error: %s \n", result); + + } else { + printf("ALL TESTS PASSED\n"); + } + + printf("Tests run: %d\n", tests_run); + + return result != 0; +} diff --git a/tests/minunit.h b/tests/minunit.h new file mode 100644 index 0000000..ba99383 --- /dev/null +++ b/tests/minunit.h @@ -0,0 +1,27 @@ +/** + * This is the MinUnit testing framework - http://www.jera.com/techinfo/jtns/jtn002.html + */ + +#ifndef _MINUNIT_H_ +#define _MINUNIT_H_ + +#define mu_assert(message, test) do { if (!(test)) return message; } while (0) +#define mu_run_test(test) do { const char *message = test(); tests_run++; \ + if (message) return message; } while (0) + +extern int tests_run; + + +static const char *test_sensor_paths(void); +static const char *test_fan_paths(void); +static const char *test_get_temp(void); +static const char *test_config_file(void); +static const char *test_settings(void); +static void handler(int signal); +static const char *test_sighup_receive(void); +static const char *test_settings_reload(void); +static const char *all_tests(void); + +int tests(const char *program_path); + +#endif