pax_global_header00006660000000000000000000000064144122333750014516gustar00rootroot0000000000000052 comment=a9c324db67470a222b20d8ddaa9b4e1e488e9771 mbpfan-2.4.0/000077500000000000000000000000001441223337500127645ustar00rootroot00000000000000mbpfan-2.4.0/.gitignore000066400000000000000000000002571441223337500147600ustar00rootroot00000000000000# Intellij .idea *.iml # Eclipse .cproject .project # Object files *.o bin/* # Libraries *.lib # Shared objects (inc. Windows DLLs) *.dll *.so # Executables *.exe *.out mbpfan-2.4.0/.travis.yml000066400000000000000000000000511441223337500150710ustar00rootroot00000000000000dist: xenial language: c script: - make mbpfan-2.4.0/AUTHORS000066400000000000000000000015521441223337500140370ustar00rootroot00000000000000AUTHORS, 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 mbpfan-2.4.0/COPYING000066400000000000000000001045051441223337500140240ustar00rootroot00000000000000 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 . mbpfan-2.4.0/Makefile000066400000000000000000000042771441223337500144360ustar00rootroot00000000000000COMPILER=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 -std=c99 -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=500 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 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 mbpfan-2.4.0/README.md000066400000000000000000000147051441223337500142520ustar00rootroot00000000000000# 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. mbpfan-2.4.0/mbpfan.8.gz000066400000000000000000000011131441223337500147330ustar00rootroot00000000000000‹ŸaÃ^mbpfan.8eSËnÛ0¼ó+99@)Ù EQÔnœÆ@ý€äЦJZYDDRà#irêGô û%]Rj –³³3³«ìî ÖÔèøN:heð(}Ç2z:YÓ¶À•ÐÀÂÕR‚ª†VèlßYv¼íêp½ÜÁ%œÝ:´°:ˆÞÑ[y»åvÍÆ¸ãKpR 4¡¨Œo 6Ú[ÓC„¸±ª‹¾‡åµQCðhüùõf¨;¡k=PIÒ´°ì{êÝÖ…ÀIÝy^~Ûíå¦dÙjªÃ÷ýá¸ÙïÊ pµ.?›Ty…a”‚xØ Á¡©I´Ö(ÒdÑ£@™&F¡pèc‚øÊGpRŸRMD+NÕSCì³þÏŒp.(š%ôè *Š“ü ã~Œui p0Sâg‹ùù›T“ˆ¯‘Ž¢ä©rVcÏ¥np@úhŸ%ÏS,Û€w¬ìÌc’Øa?€«-¢ßZVM®GSä˜n!èf||`+„™è?â+ã0±_o¾®#7äèë|:Úp˲¢$ÓîÉQttaMÜ­nå)Xá£ùxy¤±X'¦åíñf_°+¡%öðÅŠgi<©M*}’š2&î¶Eü˜Z¶ûb ›ÝõžuÞî}žŸèŽCE •7§“¬œ½À^Så——¹àž¤Ö´îƒ7VŠžS|ìåZª }˜ˆˆGÄCTµ˜F¾/æùü]>ž<ýDueÌ=§uòÈ1^Xþi’ç ‚mbpfan-2.4.0/mbpfan.conf000066400000000000000000000023421441223337500150770ustar00rootroot00000000000000[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 mbpfan-2.4.0/mbpfan.conf.test0000066400000000000000000000010771441223337500161410ustar00rootroot00000000000000[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 mbpfan-2.4.0/mbpfan.conf.test1000066400000000000000000000004361441223337500161400ustar00rootroot00000000000000[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 mbpfan-2.4.0/mbpfan.conf.test2000066400000000000000000000004361441223337500161410ustar00rootroot00000000000000[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 mbpfan-2.4.0/mbpfan.depend.conf000066400000000000000000000000111441223337500163240ustar00rootroot00000000000000coretemp mbpfan-2.4.0/mbpfan.dinit000066400000000000000000000002411441223337500152550ustar00rootroot00000000000000type = bgprocess command = /usr/bin/mbpfan restart = true logfile = /var/log/dinit/mbpfan.log waits-for = loginready pid-file = /var/run/mbpfan.pid mbpfan-2.4.0/mbpfan.init.debian000066400000000000000000000045651441223337500163470ustar00rootroot00000000000000#! /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 : mbpfan-2.4.0/mbpfan.init.gentoo000066400000000000000000000004021441223337500164020ustar00rootroot00000000000000#!/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 $? } mbpfan-2.4.0/mbpfan.init.redhat000066400000000000000000000032531441223337500163650ustar00rootroot00000000000000#!/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 $? mbpfan-2.4.0/mbpfan.service000066400000000000000000000004241441223337500156110ustar00rootroot00000000000000[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 mbpfan-2.4.0/mbpfan.spec000066400000000000000000000037461441223337500151150ustar00rootroot00000000000000Name: 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 mbpfan-2.4.0/mbpfan.upstart000066400000000000000000000004261441223337500156550ustar00rootroot00000000000000# 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 mbpfan-2.4.0/src/000077500000000000000000000000001441223337500135535ustar00rootroot00000000000000mbpfan-2.4.0/src/daemon.c000066400000000000000000000127451441223337500151730ustar00rootroot00000000000000/** * 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; 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); } static 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); } void signal_handler(int signal) { switch (signal) { case SIGHUP: syslog(LOG_WARNING, "Received SIGHUP signal."); retrieve_settings(NULL, fans); break; case SIGTERM: syslog(LOG_WARNING, "Received SIGTERM signal."); cleanup_and_exit(EXIT_SUCCESS); break; case SIGQUIT: syslog(LOG_WARNING, "Received SIGQUIT signal."); cleanup_and_exit(EXIT_SUCCESS); break; case SIGINT: syslog(LOG_WARNING, "Received SIGINT signal."); cleanup_and_exit(EXIT_SUCCESS); break; default: syslog(LOG_WARNING, "Unhandled signal (%d) %s", signal, strsignal(signal)); break; } } void go_daemon(void (*fan_control)()) { // Setup signal handling before we start signal(SIGHUP, signal_handler); signal(SIGTERM, signal_handler); signal(SIGQUIT, signal_handler); signal(SIGINT, signal_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); } } mbpfan-2.4.0/src/daemon.h000066400000000000000000000023261441223337500151720ustar00rootroot00000000000000/** * 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_ /** * 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)()); #endif mbpfan-2.4.0/src/global.h000066400000000000000000000013001441223337500151560ustar00rootroot00000000000000#ifndef _GLOBAL_H_ #define _GLOBAL_H_ #define PROGRAM_NAME "mbpfan" #define PROGRAM_VERSION "2.4.0" #define PROGRAM_PID "/var/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; }; typedef struct s_sensors t_sensors; typedef struct s_fans t_fans; extern t_sensors *sensors; extern t_fans *fans; #endif mbpfan-2.4.0/src/main.c000066400000000000000000000036031441223337500146450ustar00rootroot00000000000000/** * 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 #include #include #include #include "mbpfan.h" #include "daemon.h" #include "global.h" #include "util.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) { switch (c) { case 'h': print_usage(argc, argv); exit(EXIT_SUCCESS); break; case 'f': daemonize = 0; break; case 'v': verbose = 1; break; default: print_usage(argc, argv); exit(EXIT_SUCCESS); break; } } check_requirements(argv[0]); // pointer to mbpfan() function in mbpfan.c void (*fan_control)() = mbpfan; go_daemon(fan_control); exit(EXIT_SUCCESS); } mbpfan-2.4.0/src/mbpfan.c000066400000000000000000000471601441223337500151720ustar00rootroot00000000000000/** * 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 "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, "%d", &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 (ENOENT == errno) { 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 (ENOENT != errno) { strncpy((char *) &applesmc_path, APPLESMC_PATH, PATH_MAX); } else { /** * Check for alternate ACPI device path for newer macbooks */ closedir(dir); dir = opendir(ALT_APPLESMC_PATH); if (ENOENT != errno) { 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) { 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; } } } mbpfan-2.4.0/src/mbpfan.h000066400000000000000000000054211441223337500151710ustar00rootroot00000000000000/** * 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 /** 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; /** Represents a Temperature sensor */ struct s_sensors; typedef struct s_sensors t_sensors; struct s_fans; typedef struct s_fans t_fans; 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 mbpfan-2.4.0/src/settings.c000066400000000000000000000745111441223337500155670ustar00rootroot00000000000000/* * 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 "settings.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. */ mbpfan-2.4.0/src/settings.h000066400000000000000000000436161441223337500155760ustar00rootroot00000000000000/* * 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 #include #include #include #include "strmap.h" #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. */ mbpfan-2.4.0/src/strmap.c000066400000000000000000000367141441223337500152400ustar00rootroot00000000000000/* * 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 "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; Pair *pair; if (map == NULL) { return 0; } bucket = map->buckets; n = map->count; i = 0; count = 0; while (i < n) { pair = bucket->pairs; m = bucket->count; j = 0; while (j < m) { count++; pair++; 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. */ mbpfan-2.4.0/src/strmap.h000066400000000000000000000311431441223337500152340ustar00rootroot00000000000000/* * 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 #include #include 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. */ mbpfan-2.4.0/src/util.c000066400000000000000000000005771441223337500147050ustar00rootroot00000000000000#include #include #define __USE_MISC #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); va_end(args); } va_start(args, fmt); vprintf(fmt, args); puts(""); // trailing newline va_end(args); } mbpfan-2.4.0/src/util.h000066400000000000000000000002001441223337500146710ustar00rootroot00000000000000#ifndef _UTIL_H_ #define _UTIL_H_ void mbp_log(int level, const char *fmt, ...) __attribute__((format(printf, 2, 3))); #endif mbpfan-2.4.0/tests/000077500000000000000000000000001441223337500141265ustar00rootroot00000000000000mbpfan-2.4.0/tests/main.c000066400000000000000000000001371441223337500152170ustar00rootroot00000000000000#include "minunit.h" int main(int argc, char *argv[]) { (void)argc; tests(argv[0]); } mbpfan-2.4.0/tests/minunit.c000066400000000000000000000152111441223337500157550ustar00rootroot00000000000000/* 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; } mbpfan-2.4.0/tests/minunit.h000066400000000000000000000013571441223337500157700ustar00rootroot00000000000000/** * 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(); static const char *test_fan_paths(); static const char *test_get_temp(); static const char *test_config_file(); static const char *test_settings(); static void handler(int signal); static const char *test_sighup_receive(); static const char *test_settings_reload(); static const char *all_tests(); int tests(); #endif