├── .clang-tidy ├── .gitignore ├── .travis.yml ├── AUTHORS ├── COPYING ├── Makefile ├── README.md ├── mbpfan.8.gz ├── mbpfan.conf ├── mbpfan.conf.test0 ├── mbpfan.conf.test1 ├── mbpfan.conf.test2 ├── mbpfan.depend.conf ├── mbpfan.dinit ├── mbpfan.init.debian ├── mbpfan.init.gentoo ├── mbpfan.init.redhat ├── mbpfan.service ├── mbpfan.spec ├── mbpfan.upstart ├── src ├── daemon.c ├── daemon.h ├── global.h ├── main.c ├── mbpfan.c ├── mbpfan.h ├── settings.c ├── settings.h ├── strmap.c ├── strmap.h ├── util.c └── util.h └── tests ├── main.c ├── minunit.c └── minunit.h /.clang-tidy: -------------------------------------------------------------------------------- 1 | WarningsAsErrors: '*' 2 | Checks: ' 3 | *, 4 | -altera-*, 5 | -android-*, 6 | -bugprone-assignment-in-if-condition, 7 | -bugprone-branch-clone, 8 | -bugprone-easily-swappable-parameters, 9 | -bugprone-implicit-widening-of-multiplication-result, 10 | -bugprone-narrowing-conversions, 11 | -bugprone-reserved-identifier, 12 | -bugprone-signed-char-misuse, 13 | -cert-dcl37-c, 14 | -cert-dcl51-cpp, 15 | -cert-err33-c, 16 | -cert-err34-c, 17 | -cert-str34-c, 18 | -clang-analyzer-core.CallAndMessage, 19 | -clang-analyzer-security.insecureAPI.strcpy, 20 | -clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling, 21 | -clang-diagnostic-macro-redefined, 22 | -concurrency-mt-unsafe, 23 | -cppcoreguidelines-avoid-magic-numbers, 24 | -cppcoreguidelines-avoid-non-const-global-variables, 25 | -cppcoreguidelines-init-variables, 26 | -cppcoreguidelines-macro-to-enum, 27 | -cppcoreguidelines-narrowing-conversions, 28 | -google-readability-braces-around-statements, 29 | -google-readability-todo, 30 | -hicpp-*, 31 | -llvm-*, 32 | -llvmlibc-*, 33 | -misc-unused-parameters, 34 | -modernize-macro-to-enum, 35 | -readability-braces-around-statements, 36 | -readability-else-after-return, 37 | -readability-function-cognitive-complexity, 38 | -readability-identifier-length, 39 | -readability-inconsistent-declaration-parameter-name, 40 | -readability-isolate-declaration, 41 | -readability-magic-numbers, 42 | -readability-math-missing-parentheses, 43 | -readability-suspicious-call-argument, 44 | ' 45 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Intellij 2 | .idea 3 | *.iml 4 | 5 | # Eclipse 6 | .cproject 7 | .project 8 | 9 | # Object files 10 | *.o 11 | bin/* 12 | 13 | # Libraries 14 | *.lib 15 | 16 | # Shared objects (inc. Windows DLLs) 17 | *.dll 18 | *.so 19 | 20 | # Executables 21 | *.exe 22 | *.out 23 | 24 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: xenial 2 | language: c 3 | script: 4 | - make 5 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | AUTHORS, CONTRIBUTORS, MAINTAINERS 2 | ---------------------------------- 3 | 4 | Daniel Graziotin 5 | 6 | Marji Cermak 7 | John Ferlito 8 | Andrew Gaul 9 | Ismail Khatib 10 | Trevor Joynson 11 | Magnus Stubman 12 | Olivier Tilmans 13 | Yamakaky 14 | Yi Yang 15 | Herminio Hernandez Jr 16 | Robert Musial 17 | Ati Sharma 18 | 19 | 20 | ORIGINARY AUTHORS 21 | ----------------- 22 | Allan McRae mbpfan 23 | rvega 24 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | COMPILER=cc 2 | 3 | C = c 4 | OBJ = o 5 | OUTPUT_PATH = bin/ 6 | SOURCE_PATH = src/ 7 | TESTS_PATH = tests/ 8 | TESTS_BIN = bin/mbpfan-tests 9 | BIN = bin/mbpfan 10 | CONF = mbpfan.conf 11 | DEPEND_MODULE = mbpfan.depend.conf 12 | DOC = README.md 13 | MAN = mbpfan.8.gz 14 | 15 | COPT = 16 | CC ?= cc 17 | OBJFLAG = -o 18 | BINFLAG = -o 19 | INCLUDES = 20 | LIBS = -lm 21 | LIBPATH = 22 | CFLAGS += $(COPT) -g $(INCLUDES) -Wall -Wextra -Wno-unused-function -Wno-unused-parameter -std=c99 -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=500 23 | LDFLAGS += $(LIBPATH) -g 24 | 25 | OBJS := $(patsubst %.$(C),%.$(OBJ),$(wildcard $(SOURCE_PATH)*.$(C))) 26 | TESTS_OBJS := $(patsubst %.$(C),%.$(OBJ),$(wildcard $(TESTS_PATH)*.$(C))) 27 | TESTS_OBJS += $(filter-out %main.$(OBJ),$(OBJS)) 28 | 29 | .PHONY: all clean tests uninstall install rebuild 30 | 31 | %.$(OBJ):%.$(C) 32 | mkdir -p bin 33 | @echo Compiling $(basename $<)... 34 | $(CC) -c $(CFLAGS) $< $(OBJFLAG)$@ 35 | 36 | all: $(BIN) $(TESTS_BIN) 37 | 38 | $(BIN): $(OBJS) 39 | @echo Linking... 40 | $(CC) $(LDFLAGS) $^ $(LIBS) $(BINFLAG) $(BIN) 41 | 42 | $(TESTS_BIN): $(TESTS_OBJS) 43 | @echo Linking... 44 | $(CC) $(LDFLAGS) $^ $(LIBS) $(BINFLAG) $(TESTS_BIN) 45 | 46 | clean: 47 | rm -rf $(SOURCE_PATH)*.$(OBJ) $(BIN) 48 | rm -rf $(TESTS_PATH)*.$(OBJ) $(TESTS_BIN) 49 | 50 | tests: all 51 | ./bin/mbpfan-tests 52 | 53 | clang-tidy: 54 | clang-tidy src/*.[ch] 55 | 56 | uninstall: 57 | rm /usr/sbin/mbpfan 58 | rm /etc/mbpfan.conf 59 | rm /lib/modules-load.d/mbpfan.depend.conf 60 | rm /lib/systemd/system/mbpfan.service 61 | rm /usr/share/man/man8/mbpfan.8.gz 62 | rm -rf /usr/share/doc/mbpfan 63 | 64 | install: all 65 | install -d $(DESTDIR)/usr/sbin 66 | install -d $(DESTDIR)/etc 67 | install -d $(DESTDIR)/lib/systemd/system 68 | install -d $(DESTDIR)/usr/share/doc/mbpfan 69 | install -d $(DESTDIR)/lib/modules-load.d 70 | install $(BIN) $(DESTDIR)/usr/sbin 71 | install -m644 $(CONF) $(DESTDIR)/etc 72 | install -m644 $(DEPEND_MODULE) $(DESTDIR)/lib/modules-load.d 73 | install -m644 $(DOC) $(DESTDIR)/usr/share/doc/mbpfan 74 | install -d $(DESTDIR)/usr/share/man/man8 75 | install -m644 $(MAN) $(DESTDIR)/usr/share/man/man8 76 | @echo "" 77 | @echo "******************" 78 | @echo "INSTALL COMPLETED" 79 | @echo "******************" 80 | @echo "" 81 | @echo "A configuration file has been copied (might overwrite existing file) to /etc/mbpfan.conf." 82 | @echo "See README.md file to have mbpfan automatically started at system boot." 83 | @echo "" 84 | @echo "Please run the tests now with the command" 85 | @echo " sudo make tests" 86 | @echo "" 87 | rebuild: clean all 88 | #rebuild is not entirely correct 89 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mbpfan 2 | 3 | [![Build Status](https://travis-ci.org/dgraziotin/mbpfan.svg?branch=master)](https://travis-ci.org/dgraziotin/mbpfan) 4 | 5 | This is an enhanced version of [Allan McRae mbpfan](http://allanmcrae.com/2010/05/simple-macbook-pro-fan-daemon/) 6 | 7 | mbpfan is a daemon that uses input from coretemp module and sets the fan speed using the applesmc module. 8 | This enhanced version assumes any number of processors and fans (max. 10). 9 | 10 | * It only uses the temperatures from the processors as input. 11 | * It requires coretemp and applesmc kernel modules to be loaded. 12 | * It requires root use 13 | * It daemonizes or stays in foreground 14 | * Verbose mode for both syslog and stdout 15 | * Users can configure it using the file /etc/mbpfan.conf 16 | 17 | **Table Of Contents** 18 | 19 | - [Supported GNU/Linux Distributions](#supported-gnulinux-distributions) 20 | - [Tested Mac Models](#tested-mac-models) 21 | - [Requirements](#requirements) 22 | - [Installation](#installation) 23 | - [Arch Linux](#arch-linux) 24 | - [CRUX Linux](#crux-linux) 25 | - [Debian](#debian) 26 | - [Fedora](#fedora) 27 | - [Gentoo](#gentoo) 28 | - [Solus](#solus) 29 | - [Ubuntu](#ubuntu) 30 | - [Generic Install Instructions (All Other Operating Systems)](#generic-install-instructions-all-other-operating-systems) 31 | - [Run Instructions](#run-instructions) 32 | - [Starting at boot](#starting-at-boot) 33 | - [Usage](#usage) 34 | - [References](#references) 35 | - [License](#license) 36 | - [Credits](#credits) 37 | 38 | ## Supported GNU/Linux Distributions 39 | 40 | We provide scripts to to load mbpfan daemon at system boot for many distros. 41 | Please note that the support is provided by volunteers. mbpfan needs tests and bug reports. 42 | 43 | Supported distributions: 44 | 45 | - Ubuntu 46 | - Debian 47 | - Archlinux 48 | - Fedora 49 | - RedHat 50 | - CentOS 51 | - Gentoo 52 | - Alpine 53 | - Trisquel 54 | - Solus 55 | 56 | ## Tested Mac Models 57 | 58 | See https://github.com/linux-on-mac/mbpfan/wiki/Tested-Mac-Models . 59 | 60 | ## Requirements 61 | 62 | Be sure to load the kernel modules **applesmc** and **coretemp**. 63 | 64 | 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. 65 | 66 | **How do I know if applesmc and coretemp are loaded?** 67 | 68 | In most distributions, you can run the following command: 69 | 70 | ```bash 71 | lsmod | grep -e applesmc -e coretemp 72 | ``` 73 | 74 | If you see `coretemp` and `applesmc` listed, you are all set. 75 | 76 | **If you do not see `coretemp` and `applesmc` listed, you must load them.** 77 | 78 | This is _usually_ achieved by inserting the following two lines in the file `/etc/modules` 79 | 80 | ``` 81 | coretemp 82 | applesmc 83 | ``` 84 | 85 | Please check the relevant documentation of your GNU/Linux distribution. 86 | 87 | ## Installation 88 | 89 | ### Arch Linux 90 | 91 | See [mbpfan-git at AUR](https://aur.archlinux.org/packages/mbpfan-git/). 92 | Otherwise, please refer to the Generic Instructions. 93 | 94 | ### CRUX Linux 95 | 96 | Follow the instructions on [jolupalabs REPO](https://github.com/jolupa/jolupalabs) for installation. 97 | 98 | ### Debian 99 | 100 | On Debian 10 or later install via: 101 | 102 | ``` 103 | sudo apt-get install mbpfan 104 | ``` 105 | 106 | ### Fedora 107 | 108 | On Fedora 30 or later: 109 | 110 | ``` 111 | sudo dnf install mbpfan 112 | ``` 113 | 114 | ### Gentoo 115 | 116 | Install the ```mbpfan``` package with: 117 | 118 | sudo emerge -av app-laptop/mbpfan 119 | 120 | 121 | ### Solus 122 | 123 | On Solus, install the package with: 124 | ``` 125 | sudo eopkg install mbpfan 126 | ``` 127 | then enable the service. 128 | 129 | 130 | ### Ubuntu 131 | 132 | On Ubuntu 18.04 or later install via: 133 | 134 | ``` 135 | sudo apt-get install mbpfan 136 | ``` 137 | 138 | ### Generic Install Instructions (All Other Operating Systems) 139 | 140 | Compile with 141 | 142 | make 143 | 144 | Install with 145 | 146 | sudo make install 147 | 148 | It copies mbpfan to /usr/sbin, mbpfan.conf to /etc (and overwrites existing files), 149 | README.md to /usr/share/doc/mbpfan, and mbpfan.8.gz to /usr/share/man/man8 150 | 151 | If you would like to compile with Clang instead of GCC, simply set your system's 152 | default compiler to be Clang. Tested with Clang 3.8 and 3.9. Tested with Clang 153 | 4.0 along with llvm-lld (The LLVM Linker). 154 | 155 | 156 | Run The Tests (Optional) 157 | ------------------------ 158 | Users may run the tests after building the program. Please run the following command _from within the source directory_. 159 | 160 | sudo make tests 161 | 162 | Note that this only works on MacBook and not desktop computers due to different environment expectations. 163 | 164 | 165 | ## Run Instructions 166 | 167 | If not installed, run with 168 | 169 | sudo bin/mbpfan 170 | 171 | If installed, manually run with 172 | 173 | sudo mbpfan 174 | 175 | If installed and using the init file, run with (Ubuntu example) 176 | 177 | sudo service mbpfan start 178 | 179 | 180 | ## Starting at boot 181 | 182 | **Ubuntu** 183 | 184 | For systemd based init systems (Ubuntu 16.04+), see the systemd section below. 185 | 186 | For upstart based init systems (Ubuntu before 16.04), an example upstart job has been provided. 187 | For using it, execute: 188 | 189 | sudo cp mbpfan.upstart /etc/init/mbpfan.conf 190 | sudo start mbpfan 191 | 192 | **Debian** 193 | An init file suitable for /lib/lsb/init-functions (Debian) 194 | is located in the main folder of the source files, called mbpfan.init.debian 195 | Rename it to mbpfan, give it execution permissions (chmod +x mbpfan) 196 | and move it to /etc/init.d 197 | Then, add it to the default runlevels with (as root): 198 | 199 | sudo update-rc.d mbpfan defaults 200 | 201 | **Redhat, CentOS, Fedora** 202 | An init file suitable for /etc/rc.d/init.d/functions 203 | (RHEL/CentOS & Fedora) is also located at the same place, this file is called 204 | mbpfan.init.redhat. Also rename it to mbpfan, give it execution permissions 205 | and move it to /etc/init.d 206 | To add the script to the default runlevels, run the following as root: 207 | 208 | chkconfig --level 2345 mbpfan on && chkconfig --level 016 mbpfan off 209 | 210 | **Gentoo** 211 | 212 | To automatically run mbpfan at boot, run as root: 213 | 214 | rc-update add mbpfan default 215 | 216 | 217 | **systemd** 218 | As a special bonus, a service file for systemd is also included. To use it, 219 | execute the following (as root): 220 | 221 | sudo cp mbpfan.service /etc/systemd/system/ 222 | sudo systemctl enable mbpfan.service 223 | sudo systemctl daemon-reload 224 | sudo systemctl start mbpfan.service 225 | 226 | **dinit** 227 | A [dinit](https://github.com/davmac314/dinit) service definition is also included. To use it, execute the following: 228 | 229 | sudo cp mbpfan.dinit /etc/dinit.d/mbpfan 230 | sudo dinitctl enable mbpfan 231 | sudo dinitctl start mbpfan 232 | 233 | ## Usage 234 | 235 | Usage: ./mbpfan OPTION(S) 236 | 237 | -h Show the help screen 238 | -f Run in foreground 239 | -v Be (a lot) verbose 240 | 241 | ## References 242 | 243 | * [mbpfan on Ask Ubuntu](https://askubuntu.com/search?q=mbpfan+is%3Aquestion) 244 | 245 | ## License 246 | 247 | GNU General Public License version 3 248 | 249 | ## Credits 250 | 251 | **This Project Is Based On:** 252 | 253 | * http://allanmcrae.com/2010/05/simple-macbook-pro-fan-daemon/ 254 | * http://allanmcrae.com/2011/08/mbp-fan-daemon-update/ 255 | * https://launchpad.net/macfanctld 256 | * https://www.lobotomo.com/products/FanControl/ 257 | 258 | **This Project uses following library:** 259 | 260 | * [ANSI C Application Settings Management](http://pokristensson.com/settings.html) by Per Ola Kristensson. 261 | -------------------------------------------------------------------------------- /mbpfan.8.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/linux-on-mac/mbpfan/14e1c42109271e96fcdfe91fbdaeb5ed939764dd/mbpfan.8.gz -------------------------------------------------------------------------------- /mbpfan.conf: -------------------------------------------------------------------------------- 1 | [general] 2 | # see https://ineed.coffee/3838/a-beginners-tutorial-for-mbpfan-under-ubuntu for the values 3 | # 4 | # 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 5 | # by setting the values for the speeds in this config it will override whatever it finds in: 6 | # /sys/devices/platform/applesmc.768/fan*_min 7 | # /sys/devices/platform/applesmc.768/fan*_max 8 | # or the defaults. 9 | # 10 | # multiple fans can be configured by using the config key of min_fan*_speed and max_fan*_speed 11 | # the number used will correlate to the file number of the fan in the applesmc driver that are used to control the fan speed. 12 | # 13 | #min_fan1_speed = 2000 # put the *lowest* value of "cat /sys/devices/platform/applesmc.768/fan*_min" 14 | #max_fan1_speed = 6200 # put the *highest* value of "cat /sys/devices/platform/applesmc.768/fan*_max" 15 | 16 | # temperature units in celcius 17 | low_temp = 63 # if temperature is below this, fans will run at minimum speed 18 | high_temp = 66 # if temperature is above this, fan speed will gradually increase 19 | max_temp = 86 # if temperature is above this, fans will run at maximum speed 20 | polling_interval = 1 # default is 1 seconds 21 | -------------------------------------------------------------------------------- /mbpfan.conf.test0: -------------------------------------------------------------------------------- 1 | [general] 2 | # see https://ineed.coffee/3838/a-beginners-tutorial-for-mbpfan-under-ubuntu for the values 3 | min_fan1_speed = 2000 # put the *lowest* value of "cat /sys/devices/platform/applesmc.768/fan*_min" 4 | max_fan1_speed = 6200 # put the *highest* value of "cat /sys/devices/platform/applesmc.768/fan*_max" 5 | low_temp = 63 # try ranges 55-63, default is 63 6 | high_temp = 66 # try ranges 58-66, default is 66 7 | max_temp = 86 # take highest number returned by "cat /sys/devices/platform/coretemp.*/hwmon/hwmon*/temp*_max", divide by 1000 8 | polling_interval = 7 # default is 1 second 9 | -------------------------------------------------------------------------------- /mbpfan.conf.test1: -------------------------------------------------------------------------------- 1 | [general] 2 | min_fan1_speed = 2000 # default is 2000 3 | max_fan1_speed = 2600 # default is 2600 4 | low_temp = 63 # try ranges 55-63, default is 63 5 | high_temp = 66 # try ranges 58-66, default is 66 6 | max_temp = 86 # do not set it > 90, default is 86 7 | polling_interval = 2 # default is 1 second 8 | -------------------------------------------------------------------------------- /mbpfan.conf.test2: -------------------------------------------------------------------------------- 1 | [general] 2 | min_fan1_speed = 2000 # default is 2000 3 | min_fan2_speed = 2000 # default is 6200 4 | low_temp = 63 # try ranges 55-63, default is 63 5 | high_temp = 66 # try ranges 58-66, default is 66 6 | max_temp = 86 # do not set it > 90, default is 86 7 | polling_interval = 1 # default is 1 second 8 | -------------------------------------------------------------------------------- /mbpfan.depend.conf: -------------------------------------------------------------------------------- 1 | coretemp 2 | -------------------------------------------------------------------------------- /mbpfan.dinit: -------------------------------------------------------------------------------- 1 | type = bgprocess 2 | command = /usr/bin/mbpfan 3 | restart = true 4 | logfile = /var/log/dinit/mbpfan.log 5 | waits-for = loginready 6 | pid-file = /var/run/mbpfan.pid 7 | 8 | -------------------------------------------------------------------------------- /mbpfan.init.debian: -------------------------------------------------------------------------------- 1 | #! /bin/sh 2 | ### BEGIN INIT INFO 3 | # Provides: mbpfan 4 | # Required-Start: $remote_fs $syslog 5 | # Required-Stop: $remote_fs $syslog 6 | # Default-Start: 2 3 4 5 7 | # Default-Stop: 0 1 6 8 | # Short-Description: mbpfan initscript 9 | # Description: Start the mbpfan daemon 10 | ### END INIT INFO 11 | 12 | DESC="Start the mbpfan daemon" 13 | NAME=mbpfan 14 | PATH=/sbin:/usr/sbin:/bin:/usr/bin 15 | DAEMON=/usr/sbin/$NAME 16 | PIDFILE=/var/run/$NAME.pid 17 | SCRIPTNAME=/etc/init.d/$NAME 18 | DAEMON_ARGS="" 19 | 20 | # Exit if the package is not installed 21 | [ -x "$DAEMON" ] || exit 0 22 | 23 | # Load the VERBOSE setting and other rcS variables 24 | . /lib/init/vars.sh 25 | 26 | # Define LSB log_* functions. 27 | # Depend on lsb-base (>= 3.0-6) to ensure that this file is present. 28 | . /lib/lsb/init-functions 29 | 30 | # Function that starts the daemon/service 31 | do_start() 32 | { 33 | start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \ 34 | || return 1 35 | start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- \ 36 | $DAEMON_ARGS \ 37 | || return 2 38 | } 39 | 40 | # Function that stops the daemon/service 41 | do_stop() 42 | { 43 | # Return 44 | start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME 45 | RETVAL="$?" 46 | [ "$RETVAL" = 2 ] && return 2 47 | start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON 48 | [ "$?" = 2 ] && return 2 49 | return "$RETVAL" 50 | } 51 | 52 | # Function that sends a SIGHUP to the daemon/service 53 | do_reload() 54 | { 55 | start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME 56 | return 0 57 | } 58 | 59 | case "$1" in 60 | start) 61 | [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME" 62 | do_start 63 | case "$?" in 64 | 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; 65 | 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; 66 | esac 67 | ;; 68 | stop) 69 | [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME" 70 | do_stop 71 | case "$?" in 72 | 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; 73 | 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; 74 | esac 75 | ;; 76 | status) 77 | status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $? 78 | ;; 79 | restart|force-reload) 80 | log_daemon_msg "Restarting $DESC" "$NAME" 81 | do_stop 82 | case "$?" in 83 | 0|1) 84 | do_start 85 | case "$?" in 86 | 0) log_end_msg 0 ;; 87 | 1) log_end_msg 1 ;; # Old process is still running 88 | *) log_end_msg 1 ;; # Failed to start 89 | esac 90 | ;; 91 | *) 92 | # Failed to stop 93 | log_end_msg 1 94 | ;; 95 | esac 96 | ;; 97 | *) 98 | echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2 99 | exit 3 100 | ;; 101 | esac 102 | 103 | : 104 | -------------------------------------------------------------------------------- /mbpfan.init.gentoo: -------------------------------------------------------------------------------- 1 | #!/sbin/openrc-run 2 | 3 | depend() { 4 | use logger 5 | } 6 | 7 | start() { 8 | ebegin "Starting mbpfan" 9 | start-stop-daemon --start --quiet --exec /usr/sbin/mbpfan 10 | eend $? 11 | } 12 | 13 | stop() { 14 | ebegin "Stopping mbpfan" 15 | start-stop-daemon --stop --quiet --exec /usr/sbin/mbpfan 16 | eend $? 17 | } 18 | 19 | -------------------------------------------------------------------------------- /mbpfan.init.redhat: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # mbpfan Start the mbpfan daemon 4 | # 5 | # chkconfig: 2 3 4 5 15 85 6 | # description: Start the mbpfan daemon 7 | 8 | ### BEGIN INIT INFO 9 | # Provides: mbpfan 10 | # Required-Start: $remote_fs $syslog 11 | # Required-Stop: $remote_fs $syslog 12 | # Default-Start: 2 3 4 5 13 | # Default-Stop: 0 1 6 14 | # Short-Description: mbpfan initscript 15 | # Description: Start the mbpfan daemon 16 | ### END INIT INFO 17 | 18 | # Source function library. 19 | . /etc/rc.d/init.d/functions 20 | 21 | exec="/usr/sbin/mbpfan" 22 | prog="mbpfan" 23 | 24 | [ -e /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog 25 | 26 | lockfile=/var/lock/subsys/$prog 27 | 28 | start() { 29 | [ -x $exec ] || exit 5 30 | echo -n $"Starting $prog: " 31 | daemon $exec 32 | retval=$? 33 | echo 34 | [ $retval -eq 0 ] && touch $lockfile 35 | return $retval 36 | } 37 | 38 | stop() { 39 | echo -n $"Stopping $prog: " 40 | killproc $prog 41 | retval=$? 42 | echo 43 | [ $retval -eq 0 ] && rm -f $lockfile 44 | return $retval 45 | } 46 | 47 | restart() { 48 | stop 49 | start 50 | } 51 | 52 | reload() { 53 | restart 54 | } 55 | 56 | force_reload() { 57 | restart 58 | } 59 | 60 | rh_status() { 61 | # run checks to determine if the service is running or use generic status 62 | status $prog 63 | } 64 | 65 | rh_status_q() { 66 | rh_status >/dev/null 2>&1 67 | } 68 | 69 | 70 | case "$1" in 71 | start) 72 | rh_status_q && exit 0 73 | $1 74 | ;; 75 | stop) 76 | rh_status_q || exit 0 77 | $1 78 | ;; 79 | restart) 80 | $1 81 | ;; 82 | reload) 83 | rh_status_q || exit 7 84 | $1 85 | ;; 86 | force-reload) 87 | force_reload 88 | ;; 89 | status) 90 | rh_status 91 | ;; 92 | condrestart|try-restart) 93 | rh_status_q || exit 0 94 | restart 95 | ;; 96 | *) 97 | echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}" 98 | exit 2 99 | esac 100 | exit $? 101 | 102 | -------------------------------------------------------------------------------- /mbpfan.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=A fan manager daemon for MacBook Pro 3 | After=syslog.target 4 | After=sysinit.target 5 | 6 | [Service] 7 | Type=simple 8 | ExecStart=/usr/sbin/mbpfan -f 9 | ExecReload=/usr/bin/kill -HUP $MAINPID 10 | PIDFile=/run/mbpfan.pid 11 | Restart=always 12 | RestartSec=1 13 | 14 | [Install] 15 | WantedBy=sysinit.target 16 | -------------------------------------------------------------------------------- /mbpfan.spec: -------------------------------------------------------------------------------- 1 | Name: mbpfan 2 | URL: https://github.com/dgraziotin/mbpfan 3 | License: GPLv3 4 | Group: System Environment/Daemons 5 | Version: %{SOURCE_VERSION} 6 | Release: 3 7 | 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 8 | Source: v%{version}.tar.gz 9 | 10 | %description 11 | This is an enhanced version of Allan McRae mbpfan 12 | 13 | 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). 14 | 15 | It only uses the temperatures from the processors as input. 16 | It requires coretemp and applesmc kernel modules to be loaded. 17 | It requires root use 18 | It daemonizes or stays in foreground 19 | Verbose mode for both syslog and stdout 20 | Users can configure it using the file /etc/mbpfan.conf 21 | 22 | %prep 23 | %setup -q -n %{name}-%{version} 24 | 25 | %build 26 | make 27 | 28 | %install 29 | install -D -m755 bin/mbpfan $RPM_BUILD_ROOT/usr/sbin/mbpfan 30 | install -D -m644 mbpfan.conf $RPM_BUILD_ROOT/etc/mbpfan.conf 31 | install -D -m644 mbpfan.service $RPM_BUILD_ROOT/usr/lib/systemd/system/mbpfan.service 32 | 33 | %clean 34 | rm -rf $RPM_BUILD_ROOT 35 | 36 | %post 37 | %systemd_post mbpfan.service 38 | echo "mbpfan will auto detect sane values for min and max fan speeds." 39 | echo "If you want to customize these values please edit:" 40 | echo "/etc/mbpfan.conf" 41 | echo "To start the daemon now type:" 42 | echo "systemctl start mbpfan" 43 | echo "To run also at boot, type:" 44 | echo "systemctl enable mbpfan" 45 | 46 | %preun 47 | %systemd_preun mbpfan.service 48 | 49 | %postun 50 | %systemd_postun_with_restart mbpfan.service 51 | 52 | %files 53 | %defattr (-,root,root) 54 | %doc AUTHORS README.md 55 | /usr/sbin/mbpfan 56 | %config /etc/mbpfan.conf 57 | /usr/lib/systemd/system/mbpfan.service 58 | 59 | %changelog 60 | * Mon Sep 10 2018 Michele Codutti - 2.0.2-3 61 | - Removed autoconfig with suggested procedure because has been integrated on mbpfan. 62 | 63 | * Sun Aug 19 2018 Michele Codutti - 2.0.2-2 64 | - Autoconfig with suggested procedure. 65 | - Initial packaging 66 | -------------------------------------------------------------------------------- /mbpfan.upstart: -------------------------------------------------------------------------------- 1 | # mbpfan - A simple daemon to control fan speed on all Macbook/Macbook Pros \ 2 | # (probably all Apple computers) for Linux 3.x.x 3 | 4 | description "mbpfan" 5 | 6 | start on filesystem or runlevel [2345] 7 | stop on runlevel [!2345] 8 | 9 | respawn 10 | umask 022 11 | 12 | console log 13 | 14 | exec /usr/sbin/mbpfan -f 15 | -------------------------------------------------------------------------------- /src/daemon.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2012 Peter Lombardo 3 | * Modifications (2012) by Ismail Khatib 4 | * Modifications (2012-present) by Daniel Graziotin 5 | * Modifications (2017-present) by Robert Musial 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | */ 18 | 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include "mbpfan.h" 34 | #include "global.h" 35 | #include "daemon.h" 36 | #include "util.h" 37 | 38 | int daemonize = 1; 39 | int verbose = 0; 40 | sig_atomic_t do_exit = 0; 41 | sig_atomic_t do_reload = 0; 42 | 43 | int write_pid(int pid) 44 | { 45 | FILE *file = NULL; 46 | file = fopen(PROGRAM_PID, "w"); 47 | 48 | if (file != NULL) { 49 | fprintf(file, "%d", pid); 50 | fclose(file); 51 | return 1; 52 | 53 | } else { 54 | return 0; 55 | } 56 | } 57 | 58 | int read_pid() 59 | { 60 | FILE *file = NULL; 61 | int pid = -1; 62 | file = fopen(PROGRAM_PID, "r"); 63 | 64 | if (file != NULL) { 65 | fscanf(file, "%d", &pid); 66 | fclose(file); 67 | if (kill(pid, 0) == -1 && errno == ESRCH) { /* a process with such a pid does not exist, remove the pid file */ 68 | if (remove(PROGRAM_PID) == 0) { 69 | return -1; 70 | } 71 | } 72 | return pid; 73 | } 74 | 75 | return -1; 76 | } 77 | 78 | int delete_pid() 79 | { 80 | return remove(PROGRAM_PID); 81 | } 82 | 83 | void cleanup_and_exit(int exit_code) 84 | { 85 | delete_pid(); 86 | set_fans_auto(fans); 87 | 88 | struct s_fans *next_fan; 89 | while (fans != NULL) { 90 | next_fan = fans->next; 91 | if (fans->file != NULL) { 92 | fclose(fans->file); 93 | } 94 | free(fans->label); 95 | free(fans->fan_output_path); 96 | free(fans->fan_manual_path); 97 | free(fans); 98 | fans = next_fan; 99 | } 100 | 101 | struct s_sensors *next_sensor; 102 | while (sensors != NULL) { 103 | next_sensor = sensors->next; 104 | if (sensors->file != NULL) { 105 | fclose(sensors->file); 106 | } 107 | free(sensors->path); 108 | free(sensors); 109 | sensors = next_sensor; 110 | } 111 | 112 | exit(exit_code); 113 | } 114 | 115 | static void sighup_handler(int signal) 116 | { 117 | do_reload = 1; 118 | } 119 | 120 | static void sigterm_handler(int signal) 121 | { 122 | do_exit = 1; 123 | } 124 | 125 | void go_daemon(void (*fan_control)()) 126 | { 127 | 128 | // Setup signal handling before we start 129 | signal(SIGHUP, sighup_handler); 130 | signal(SIGTERM, sigterm_handler); 131 | signal(SIGQUIT, sigterm_handler); 132 | signal(SIGINT, sigterm_handler); 133 | 134 | // Setup syslog logging - see SETLOGMASK(3) 135 | if (verbose) { 136 | setlogmask(LOG_UPTO(LOG_DEBUG)); 137 | openlog(PROGRAM_NAME, LOG_CONS | LOG_NDELAY | LOG_PERROR | LOG_PID, LOG_USER); 138 | 139 | } else { 140 | setlogmask(LOG_UPTO(LOG_INFO)); 141 | openlog(PROGRAM_NAME, LOG_CONS, LOG_USER); 142 | } 143 | 144 | mbp_log(LOG_INFO, "%s %s starting up", PROGRAM_NAME, PROGRAM_VERSION); 145 | 146 | // configure timer slack 147 | int err = prctl(PR_SET_TIMERSLACK, 1000 * 1000 * 1000, 0, 0, 0); 148 | if (err == -1) { 149 | perror("prctl"); 150 | } 151 | 152 | pid_t pid_slave; 153 | pid_t sid_slave; 154 | 155 | if (daemonize) { 156 | 157 | pid_slave = fork(); 158 | 159 | if (pid_slave < 0) { 160 | exit(EXIT_FAILURE); 161 | } 162 | 163 | if (pid_slave > 0) { 164 | signal(SIGCHLD, SIG_IGN); 165 | // kill the father 166 | exit(EXIT_SUCCESS); 167 | } 168 | 169 | umask(0022); 170 | 171 | // new sid_slave for the child process 172 | sid_slave = setsid(); 173 | 174 | if (sid_slave < 0) { 175 | exit(EXIT_FAILURE); 176 | } 177 | 178 | if ((chdir("/")) < 0) { 179 | exit(EXIT_FAILURE); 180 | } 181 | 182 | /* Close out the standard file descriptors */ 183 | close(STDIN_FILENO); 184 | close(STDOUT_FILENO); 185 | close(STDERR_FILENO); 186 | } 187 | 188 | int current_pid = getpid(); 189 | 190 | if (read_pid() == -1) { 191 | if (verbose) { 192 | mbp_log(LOG_INFO, "Writing a new .pid file with value %d at: %s", current_pid, PROGRAM_PID); 193 | } 194 | 195 | if (write_pid(current_pid) == 0) { 196 | mbp_log(LOG_ERR, "Can not create a .pid file at: %s. Aborting", PROGRAM_PID); 197 | exit(EXIT_FAILURE); 198 | 199 | } else { 200 | if (verbose) { 201 | mbp_log(LOG_INFO, "Successfully written a new .pid file with value %d at: %s", current_pid, PROGRAM_PID); 202 | } 203 | } 204 | 205 | } else { 206 | mbp_log(LOG_ERR, "A previously created .pid file exists at: %s. Aborting", PROGRAM_PID); 207 | exit(EXIT_FAILURE); 208 | } 209 | 210 | fan_control(); 211 | 212 | if (daemonize) { 213 | syslog(LOG_INFO, "%s daemon exiting", PROGRAM_NAME); 214 | } 215 | } 216 | -------------------------------------------------------------------------------- /src/daemon.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) (2012-present) Daniel Graziotin 3 | * 4 | * This program is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * This program is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | * GNU General Public License for more details. 13 | * 14 | */ 15 | 16 | #ifndef _DAEMON_H_ 17 | #define _DAEMON_H_ 18 | 19 | #include 20 | 21 | extern sig_atomic_t do_exit; 22 | extern sig_atomic_t do_reload; 23 | 24 | /** 25 | * Write the PID of the forked daemon to the 26 | * .pid file defined in char *program_pid 27 | * Return TRUE on success 28 | * Return FALSE otherwise 29 | */ 30 | int write_pid(int pid); 31 | 32 | /** 33 | * Read PID of the forked daemon from the 34 | * .pid file defined in char *program_pid 35 | * Return the pid on success 36 | * Return -1 otherwise 37 | */ 38 | int read_pid(); 39 | 40 | /** 41 | * Deletes the .pid file defined in 42 | * char *program_pid 43 | * Return TRUE on success 44 | * Return FALSE otherwise 45 | */ 46 | int delete_pid(); 47 | 48 | /** 49 | * ...handles signals :-) 50 | */ 51 | void signal_handler(int signal); 52 | 53 | /** 54 | * Daemonizes 55 | */ 56 | void go_daemon(void (*function)()); 57 | 58 | void cleanup_and_exit(int exit_code); 59 | 60 | #endif 61 | -------------------------------------------------------------------------------- /src/global.h: -------------------------------------------------------------------------------- 1 | #ifndef _GLOBAL_H_ 2 | #define _GLOBAL_H_ 3 | 4 | #include 5 | 6 | #define PROGRAM_NAME "mbpfan" 7 | #define PROGRAM_VERSION "2.4.0" 8 | #define PROGRAM_PID "/run/mbpfan.pid" 9 | 10 | extern int daemonize; 11 | extern int verbose; 12 | 13 | struct s_sensors { 14 | FILE *file; 15 | char *path; 16 | unsigned int temperature; 17 | struct s_sensors *next; 18 | }; 19 | 20 | struct s_fans { 21 | FILE *file; 22 | char *path; // TODO: unused 23 | char *label; 24 | char *fan_output_path; 25 | char *fan_manual_path; 26 | int step_up; 27 | int step_down; 28 | int fan_id; 29 | int old_speed; 30 | int fan_max_speed; 31 | int fan_min_speed; 32 | struct s_fans *next; 33 | }; 34 | 35 | /** Represents a Temperature sensor 36 | */ 37 | typedef struct s_sensors t_sensors; 38 | typedef struct s_fans t_fans; 39 | 40 | extern t_sensors *sensors; 41 | extern t_fans *fans; 42 | 43 | #endif 44 | -------------------------------------------------------------------------------- /src/main.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) (2012-present) Daniel Graziotin 3 | * Modifications (2017-present) by Robert Musial 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | */ 16 | 17 | /** 18 | * Code formatted with astyle -A3 -s --break-blocks=all --add-brackets *.c *.h 19 | */ 20 | 21 | #include 22 | #include 23 | #include // NOLINT(misc-include-cleaner) 24 | #include 25 | #include 26 | #include "mbpfan.h" 27 | #include "daemon.h" 28 | #include "global.h" 29 | 30 | void print_usage(int argc, char *argv[]) 31 | { 32 | if (argc >= 1) { 33 | printf("Usage: %s OPTION(S) \n", argv[0]); 34 | printf("Options:\n"); 35 | printf("\t-h Show this help screen\n"); 36 | printf("\t-f Run in foreground\n"); 37 | printf("\t-v Be (a lot) verbose\n"); 38 | printf("\n"); 39 | } 40 | } 41 | 42 | int main(int argc, char *argv[]) 43 | { 44 | 45 | int c; 46 | 47 | while ((c = getopt(argc, argv, "hfv|help")) != -1) { // NOLINT(misc-include-cleaner) 48 | switch (c) { 49 | case 'h': 50 | print_usage(argc, argv); 51 | return EXIT_SUCCESS; 52 | break; 53 | 54 | case 'f': 55 | daemonize = 0; 56 | break; 57 | 58 | case 'v': 59 | verbose = 1; 60 | break; 61 | 62 | default: 63 | print_usage(argc, argv); 64 | return EXIT_SUCCESS; 65 | break; 66 | } 67 | } 68 | 69 | check_requirements(argv[0]); 70 | 71 | // pointer to mbpfan() function in mbpfan.c 72 | void (*fan_control)() = mbpfan; 73 | go_daemon(fan_control); 74 | return EXIT_SUCCESS; 75 | } 76 | -------------------------------------------------------------------------------- /src/mbpfan.c: -------------------------------------------------------------------------------- 1 | /** 2 | * mbpfan.c - automatically control fan for MacBook Pro 3 | * Copyright (C) 2010 Allan McRae 4 | * Modifications by Rafael Vega 5 | * Modifications (2012) by Ismail Khatib 6 | * Modifications (2012-present) by Daniel Graziotin [CURRENT MAINTAINER] 7 | * Modifications (2017-present) by Robert Musial 8 | * Modifications (2018-present) by Ati Sharma 9 | * 10 | * This program is free software: you can redistribute it and/or modify 11 | * it under the terms of the GNU General Public License as published by 12 | * the Free Software Foundation, either version 3 of the License, or 13 | * (at your option) any later version. 14 | * 15 | * This program is distributed in the hope that it will be useful, 16 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | * GNU General Public License for more details. 19 | * 20 | * 21 | * Notes: 22 | * Assumes any number of processors, cores, sensors and fans 23 | * (as defined in NUM_PROCESSORS, NUM_HWMONS, NUM_TEMP_INPUTS and NUM_FANS) 24 | * It uses only the temperatures from the processors as input. 25 | * Requires coretemp and applesmc kernel modules to be loaded. 26 | * Requires root use 27 | * 28 | * Tested models: see README.md 29 | */ 30 | 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | #include 44 | #include 45 | #include 46 | #include 47 | #include 48 | #include "daemon.h" 49 | #include "mbpfan.h" 50 | #include "global.h" 51 | #include "settings.h" 52 | #include "util.h" 53 | 54 | /* lazy min/max... */ 55 | #define min(a, b) ((a) < (b) ? (a) : (b)) 56 | #define max(a, b) ((a) > (b) ? (a) : (b)) 57 | 58 | #define CORETEMP_PATH "/sys/devices/platform/coretemp.0" 59 | #define APPLESMC_PATH "/sys/devices/platform/applesmc.768" 60 | #define ALT_APPLESMC_PATH "/sys/bus/acpi/drivers/applesmc" 61 | 62 | /* temperature thresholds 63 | * low_temp - temperature below which fan speed will be at minimum 64 | * high_temp - fan will increase speed when higher than this temperature 65 | * max_temp - fan will run at full speed above this temperature */ 66 | int low_temp = 63; // try ranges 55-63 67 | int high_temp = 66; // try ranges 58-66 68 | int max_temp = 86; // do not set it > 90 69 | 70 | // maximum number of processors etc supported 71 | #define NUM_PROCESSORS 6 72 | #define NUM_HWMONS 12 73 | #define NUM_TEMP_INPUTS 64 74 | #define NUM_FANS 10 75 | // sane defaults when user provides unexpected values 76 | #define MIN_FAN_SPEED_DEFAULT 500 77 | #define MAX_FAN_SPEED_DEFAULT 6500 78 | 79 | int polling_interval = 1; 80 | 81 | t_sensors *sensors = NULL; 82 | t_fans *fans = NULL; 83 | char applesmc_path[PATH_MAX]; 84 | char applesmc_fan_path[PATH_MAX]; 85 | 86 | 87 | char *smprintf(const char *fmt, ...) 88 | { 89 | char *buf; 90 | int cnt; 91 | va_list ap; 92 | 93 | // find buffer length 94 | va_start(ap, fmt); 95 | cnt = vsnprintf(NULL, 0, fmt, ap); 96 | va_end(ap); 97 | if (cnt < 0) { 98 | return NULL; 99 | } 100 | 101 | // create and write to buffer 102 | buf = malloc(cnt + 1); 103 | va_start(ap, fmt); 104 | vsnprintf(buf, cnt + 1, fmt, ap); 105 | va_end(ap); 106 | return buf; 107 | } 108 | 109 | bool is_modern_sensors_path() 110 | { 111 | struct utsname kernel; 112 | uname(&kernel); 113 | 114 | char *str_kernel_version; 115 | str_kernel_version = strtok(kernel.release, "."); 116 | 117 | if (atoi(str_kernel_version) < 3) { 118 | mbp_log(LOG_ERR, "mbpfan detected a pre-3.x.x linux kernel. Detected version: %s. Exiting.\n", kernel.release); 119 | exit(EXIT_FAILURE); 120 | } 121 | 122 | int counter; 123 | 124 | for (counter = 0; counter < NUM_HWMONS; counter++) { 125 | int temp; 126 | for (temp = 1; temp < NUM_TEMP_INPUTS; ++temp) { 127 | char *path = smprintf("/sys/devices/platform/coretemp.0/hwmon/hwmon%d/temp%d_input", counter, temp); 128 | int res = access(path, R_OK); 129 | free(path); 130 | if (res == 0) { 131 | return 1; 132 | } 133 | } 134 | } 135 | 136 | return 0; 137 | } 138 | 139 | t_sensors *retrieve_sensors() 140 | { 141 | t_sensors *sensors_head = NULL; 142 | t_sensors *s = NULL; 143 | 144 | char *path = NULL; 145 | char *path_begin = NULL; 146 | 147 | const char *path_end = "_input"; 148 | int sensors_found = 0; 149 | 150 | if (!is_modern_sensors_path()) { 151 | if (verbose) { 152 | mbp_log(LOG_INFO, "Using legacy path for kernel < 3.15.0"); 153 | } 154 | 155 | path_begin = strdup("/sys/devices/platform/coretemp.0/temp"); 156 | 157 | } else { 158 | 159 | if (verbose) { 160 | mbp_log(LOG_INFO, "Using new sensor path for kernel >= 3.15.0 or some CentOS versions with kernel 3.10.0 "); 161 | } 162 | 163 | // loop over up to 6 processors 164 | int processor; 165 | for (processor = 0; processor < NUM_PROCESSORS; processor++) { 166 | 167 | if (path_begin != NULL) { 168 | free(path_begin); 169 | } 170 | path_begin = smprintf("/sys/devices/platform/coretemp.%d/hwmon/hwmon", processor); 171 | 172 | int counter; 173 | for (counter = 0; counter < NUM_HWMONS; counter++) { 174 | 175 | char *hwmon_path = smprintf("%s%d", path_begin, counter); 176 | 177 | int res = access(hwmon_path, R_OK); 178 | if (res == 0) { 179 | 180 | free(path_begin); 181 | path_begin = smprintf("%s/temp", hwmon_path); 182 | 183 | if (verbose) { 184 | mbp_log(LOG_INFO, "Found hwmon path at %s", path_begin); 185 | } 186 | 187 | free(hwmon_path); 188 | break; 189 | } 190 | 191 | free(hwmon_path); 192 | } 193 | 194 | int core = 0; 195 | for (core = 0; core < NUM_TEMP_INPUTS; core++) { 196 | path = smprintf("%s%d%s", path_begin, core, path_end); 197 | 198 | FILE *file = fopen(path, "r"); 199 | 200 | if (file != NULL) { 201 | s = (t_sensors *)malloc(sizeof(t_sensors)); 202 | s->path = strdup(path); 203 | fscanf(file, "%u", &s->temperature); 204 | 205 | if (sensors_head == NULL) { 206 | sensors_head = s; 207 | sensors_head->next = NULL; 208 | 209 | } else { 210 | t_sensors *tmp = sensors_head; 211 | 212 | while (tmp->next != NULL) { 213 | tmp = tmp->next; 214 | } 215 | 216 | tmp->next = s; 217 | tmp->next->next = NULL; 218 | } 219 | 220 | s->file = file; 221 | sensors_found++; 222 | } 223 | 224 | free(path); 225 | path = NULL; 226 | } 227 | } 228 | } 229 | 230 | if (verbose) { 231 | mbp_log(LOG_INFO, "Found %d sensors", sensors_found); 232 | } 233 | 234 | if (sensors_found == 0) { 235 | mbp_log(LOG_CRIT, "mbpfan could not detect any temp sensor. Please contact the developer."); 236 | exit(EXIT_FAILURE); 237 | } 238 | 239 | free(path_begin); 240 | path_begin = NULL; 241 | 242 | return sensors_head; 243 | } 244 | 245 | static int read_value(const char *path) 246 | { 247 | int value = -1; 248 | FILE *file = fopen(path, "r"); 249 | if (file != NULL) { 250 | fscanf(file, "%d", &value); 251 | fclose(file); 252 | } 253 | return value; 254 | } 255 | 256 | static void read_value_str(const char *path, char *str, size_t len) 257 | { 258 | FILE *file = fopen(path, "r"); 259 | if (file != NULL) { 260 | fgets(str, len, file); 261 | fclose(file); 262 | } 263 | } 264 | 265 | static void trim_trailing_whitespace(char *str) 266 | { 267 | for (ssize_t i = strlen(str) - 1; i >= 0; --i) { 268 | if (isspace(str[i]) || str[i] == '\n') { 269 | str[i] = '\0'; 270 | } 271 | } 272 | } 273 | 274 | t_fans *retrieve_fans() 275 | { 276 | t_fans *fans_head = NULL; 277 | t_fans *fan = NULL; 278 | 279 | char *path_output = NULL; 280 | char *path_label = NULL; 281 | char *path_manual = NULL; 282 | char *path_fan_max = NULL; 283 | char *path_fan_min = NULL; 284 | 285 | const char *path_begin = (const char *) &applesmc_fan_path; 286 | const char *path_output_end = "_output"; 287 | const char *path_label_end = "_label"; 288 | const char *path_man_end = "_manual"; 289 | const char *path_max_speed = "_max"; 290 | const char *path_min_speed = "_min"; 291 | 292 | int counter = 0; 293 | int fans_found = 0; 294 | 295 | for (counter = 0; counter < NUM_FANS; counter++) { 296 | 297 | path_output = smprintf("%s%d%s", path_begin, counter, path_output_end); 298 | path_label = smprintf("%s%d%s", path_begin, counter, path_label_end); 299 | path_manual = smprintf("%s%d%s", path_begin, counter, path_man_end); 300 | path_fan_min = smprintf("%s%d%s", path_begin, counter, path_min_speed); 301 | path_fan_max = smprintf("%s%d%s", path_begin, counter, path_max_speed); 302 | 303 | FILE *file = fopen(path_output, "w"); 304 | 305 | if (file != NULL) { 306 | fan = (t_fans *)malloc(sizeof(t_fans)); 307 | fan->fan_output_path = strdup(path_output); 308 | fan->fan_manual_path = strdup(path_manual); 309 | fan->fan_id = counter; 310 | 311 | int fan_speed = read_value(path_fan_min); 312 | if (fan_speed == -1 || fan_speed < MIN_FAN_SPEED_DEFAULT) 313 | fan->fan_min_speed = MIN_FAN_SPEED_DEFAULT; 314 | else 315 | fan->fan_min_speed = fan_speed; 316 | 317 | fan_speed = read_value(path_fan_max); 318 | if (fan_speed == -1 || fan_speed > MAX_FAN_SPEED_DEFAULT) 319 | fan->fan_max_speed = MAX_FAN_SPEED_DEFAULT; 320 | else 321 | fan->fan_max_speed = fan_speed; 322 | 323 | size_t max_label_len = 64; 324 | fan->label = malloc(max_label_len); 325 | read_value_str(path_label, fan->label, max_label_len); 326 | trim_trailing_whitespace(fan->label); 327 | 328 | fan->old_speed = 0; 329 | 330 | if (fans_head == NULL) { 331 | fans_head = fan; 332 | fans_head->next = NULL; 333 | 334 | } else { 335 | t_fans *tmp = fans_head; 336 | 337 | while (tmp->next != NULL) { 338 | tmp = tmp->next; 339 | } 340 | 341 | tmp->next = fan; 342 | tmp->next->next = NULL; 343 | } 344 | 345 | fan->file = file; 346 | fans_found++; 347 | } 348 | free(path_fan_min); 349 | path_fan_min = NULL; 350 | free(path_label); 351 | path_label = NULL; 352 | free(path_fan_max); 353 | path_fan_max = NULL; 354 | free(path_output); 355 | path_output = NULL; 356 | free(path_manual); 357 | path_manual = NULL; 358 | } 359 | 360 | if (verbose) { 361 | mbp_log(LOG_INFO, "Found %d fans", fans_found); 362 | } 363 | 364 | if (fans_found == 0) { 365 | mbp_log(LOG_CRIT, "mbpfan could not detect any fan. Please contact the developer."); 366 | exit(EXIT_FAILURE); 367 | } 368 | 369 | return fans_head; 370 | } 371 | 372 | static void set_fans_mode(t_fans *fans, int mode) 373 | { 374 | t_fans *tmp = fans; 375 | FILE *file; 376 | 377 | while (tmp != NULL) { 378 | file = fopen(tmp->fan_manual_path, "rw+"); 379 | 380 | if (file != NULL) { 381 | fprintf(file, "%d", mode); 382 | fclose(file); 383 | } 384 | 385 | tmp = tmp->next; 386 | } 387 | } 388 | 389 | void set_fans_man(t_fans *fans) 390 | { 391 | 392 | set_fans_mode(fans, 1); 393 | } 394 | 395 | void set_fans_auto(t_fans *fans) 396 | { 397 | 398 | set_fans_mode(fans, 0); 399 | } 400 | 401 | t_sensors *refresh_sensors(t_sensors *sensors) 402 | { 403 | t_sensors *tmp = sensors; 404 | 405 | while (tmp != NULL) { 406 | if (tmp->file != NULL) { 407 | char buf[16]; 408 | int len = pread(fileno(tmp->file), buf, sizeof(buf), /*offset=*/0); 409 | buf[len] = '\0'; 410 | tmp->temperature = strtod(buf, NULL); 411 | } 412 | 413 | tmp = tmp->next; 414 | } 415 | 416 | return sensors; 417 | } 418 | 419 | /* Controls the speed of a fan */ 420 | void set_fan_speed(t_fans *fan, int speed) 421 | { 422 | if (fan != NULL && fan->file != NULL && fan->old_speed != speed) { 423 | char buf[16]; 424 | int len = snprintf(buf, sizeof(buf), "%d", speed); 425 | int res = pwrite(fileno(fan->file), buf, len, /*offset=*/0); 426 | if (res == -1) { 427 | perror("Could not set fan speed"); 428 | } 429 | fan->old_speed = speed; 430 | } 431 | } 432 | 433 | void set_fan_minimum_speed(t_fans *fans) 434 | { 435 | t_fans *tmp = fans; 436 | 437 | while (tmp != NULL) { 438 | set_fan_speed(tmp, tmp->fan_min_speed); 439 | tmp = tmp->next; 440 | } 441 | } 442 | unsigned short get_temp(t_sensors *sensors) 443 | { 444 | sensors = refresh_sensors(sensors); 445 | unsigned int temp = 0; 446 | 447 | t_sensors *tmp = sensors; 448 | 449 | while (tmp != NULL) { 450 | temp = max(temp, tmp->temperature); 451 | tmp = tmp->next; 452 | } 453 | 454 | return temp / 1000; 455 | } 456 | 457 | void retrieve_settings(const char *settings_path, t_fans *fans) 458 | { 459 | Settings *settings = NULL; 460 | int result = 0; 461 | FILE *f = NULL; 462 | 463 | if (settings_path == NULL) { 464 | f = fopen("/etc/mbpfan.conf", "r"); 465 | 466 | } else { 467 | f = fopen(settings_path, "r"); 468 | } 469 | 470 | if (f == NULL) { 471 | /* Could not open configfile */ 472 | if (verbose) { 473 | mbp_log(LOG_INFO, "Couldn't open configfile, using defaults"); 474 | } 475 | 476 | } else { 477 | settings = settings_open(f); 478 | fclose(f); 479 | 480 | if (settings == NULL) { 481 | /* Could not read configfile */ 482 | if (verbose) { 483 | mbp_log(LOG_WARNING, "Couldn't read configfile"); 484 | } 485 | 486 | } else { 487 | 488 | t_fans *fan = fans; 489 | 490 | while (fan != NULL) { 491 | 492 | char *config_key; 493 | config_key = smprintf("min_fan%d_speed", fan->fan_id); 494 | /* Read configfile values */ 495 | result = settings_get_int(settings, "general", config_key); 496 | if (result != 0) { 497 | fan->fan_min_speed = result; 498 | } 499 | free(config_key); 500 | 501 | config_key = smprintf("max_fan%d_speed", fan->fan_id); 502 | result = settings_get_int(settings, "general", config_key); 503 | 504 | if (result != 0) { 505 | fan->fan_max_speed = result; 506 | } 507 | free(config_key); 508 | fan = fan->next; 509 | } 510 | result = settings_get_int(settings, "general", "low_temp"); 511 | 512 | if (result != 0) { 513 | low_temp = result; 514 | } 515 | 516 | result = settings_get_int(settings, "general", "high_temp"); 517 | 518 | if (result != 0) { 519 | high_temp = result; 520 | } 521 | 522 | result = settings_get_int(settings, "general", "max_temp"); 523 | 524 | if (result != 0) { 525 | max_temp = result; 526 | } 527 | 528 | result = settings_get_int(settings, "general", "polling_interval"); 529 | 530 | if (result != 0) { 531 | polling_interval = result; 532 | } 533 | 534 | /* Destroy the settings object */ 535 | settings_delete(settings); 536 | } 537 | } 538 | } 539 | 540 | void check_requirements(const char *program_path) 541 | { 542 | 543 | /** 544 | * Check for root 545 | */ 546 | 547 | uid_t uid = getuid(), euid = geteuid(); 548 | 549 | if (uid != 0 || euid != 0) { 550 | mbp_log(LOG_ERR, "%s needs root privileges. Please run %s as root. Exiting.", program_path, program_path); 551 | exit(EXIT_FAILURE); 552 | } 553 | 554 | /** 555 | * Check for coretemp and applesmc modules 556 | */ 557 | DIR *dir = opendir(CORETEMP_PATH); 558 | 559 | if (dir == NULL) { 560 | mbp_log(LOG_ERR, "%s needs coretemp support. Please either load it or build it into the kernel. Exiting.", program_path); 561 | exit(EXIT_FAILURE); 562 | } 563 | 564 | closedir(dir); 565 | memset(&applesmc_path, 0, PATH_MAX); 566 | memset(&applesmc_fan_path, 0, PATH_MAX); 567 | 568 | dir = opendir(APPLESMC_PATH); 569 | 570 | if (dir != NULL) { 571 | strncpy((char *) &applesmc_path, APPLESMC_PATH, PATH_MAX); 572 | closedir(dir); 573 | } else { 574 | /** 575 | * Check for alternate ACPI device path for newer macbooks 576 | */ 577 | dir = opendir(ALT_APPLESMC_PATH); 578 | if (dir != NULL) { 579 | struct dirent *ent; 580 | while ((ent = readdir(dir)) != NULL) { 581 | if (strncmp("APP", (const char *) &ent->d_name, 3) == 0) { 582 | snprintf((char *) &applesmc_path, PATH_MAX, "%s/%s", ALT_APPLESMC_PATH, (char *) &ent->d_name); 583 | break; 584 | } 585 | } 586 | closedir(dir); 587 | } 588 | } 589 | 590 | if (strlen(applesmc_path) != 0) { 591 | strncpy((char *) &applesmc_fan_path, (char *) &applesmc_path, PATH_MAX); 592 | strcat((char *) &applesmc_fan_path, "/fan"); 593 | if (verbose) mbp_log(LOG_INFO, "applesmc device path: %s", (char *) &applesmc_path); 594 | 595 | } else { 596 | mbp_log(LOG_ERR, "%s needs applesmc support. Please either load it or build it into the kernel. Exiting.", program_path); 597 | exit(EXIT_FAILURE); 598 | } 599 | } 600 | 601 | int get_max_mhz(void) 602 | { 603 | int max_mhz = -1; 604 | DIR *dir = opendir("/sys/devices/system/cpu"); 605 | if (dir == NULL) { 606 | return -1; 607 | } 608 | struct dirent *ent; 609 | while ((ent = readdir(dir)) != NULL) { 610 | if (strncmp(ent->d_name, "cpu", 3) != 0 || strcmp(ent->d_name, "cpufreq") == 0 || strcmp(ent->d_name, "cpuidle") == 0) { 611 | continue; 612 | } 613 | char *path = smprintf("/sys/devices/system/cpu/%s/cpufreq/scaling_cur_freq", ent->d_name); 614 | max_mhz = max(max_mhz, read_value(path) / 1000); 615 | free(path); 616 | } 617 | closedir(dir); 618 | return max_mhz; 619 | } 620 | 621 | void mbpfan() 622 | { 623 | int old_temp, new_temp, fan_speed, steps; 624 | int temp_change; 625 | 626 | sensors = retrieve_sensors(); 627 | fans = retrieve_fans(); 628 | 629 | retrieve_settings(NULL, fans); 630 | 631 | t_fans *fan = fans; 632 | while (fan != NULL) { 633 | 634 | if (fan->fan_min_speed > fan->fan_max_speed) { 635 | mbp_log(LOG_ERR, "Invalid fan speeds: %d %d", fan->fan_min_speed, fan->fan_max_speed); 636 | exit(EXIT_FAILURE); 637 | } 638 | fan = fan->next; 639 | } 640 | 641 | if (low_temp > high_temp || high_temp > max_temp) { 642 | mbp_log(LOG_ERR, "Invalid temperatures: %d %d %d", low_temp, high_temp, max_temp); 643 | exit(EXIT_FAILURE); 644 | } 645 | 646 | set_fans_man(fans); 647 | 648 | new_temp = get_temp(sensors); 649 | set_fan_minimum_speed(fans); 650 | 651 | fan = fans; 652 | while (fan != NULL) { 653 | 654 | fan->step_up = (float)(fan->fan_max_speed - fan->fan_min_speed) / (float)((max_temp - high_temp) * (max_temp - high_temp + 1) / 2.0); 655 | 656 | fan->step_down = (float)(fan->fan_max_speed - fan->fan_min_speed) / (float)((max_temp - low_temp) * (max_temp - low_temp + 1) / 2.0); 657 | fan = fan->next; 658 | } 659 | 660 | recalibrate: 661 | if (verbose) { 662 | mbp_log(LOG_INFO, "Sleeping for 2 seconds to get first temp delta"); 663 | } 664 | sleep(2); 665 | 666 | while (1) { 667 | if (do_exit) { 668 | syslog(LOG_WARNING, "Received SIGTERM, SIGQUIT, or SIGINT signal."); 669 | cleanup_and_exit(EXIT_SUCCESS); 670 | } 671 | 672 | if (do_reload) { 673 | syslog(LOG_WARNING, "Received SIGHUP signal."); 674 | retrieve_settings(NULL, fans); 675 | do_reload = 0; 676 | } 677 | 678 | old_temp = new_temp; 679 | new_temp = get_temp(sensors); 680 | 681 | fan = fans; 682 | 683 | while (fan != NULL) { 684 | fan_speed = fan->old_speed; 685 | 686 | if (new_temp >= max_temp && fan->old_speed != fan->fan_max_speed) { 687 | fan_speed = fan->fan_max_speed; 688 | } 689 | 690 | if (new_temp <= low_temp && fan_speed != fan->fan_min_speed) { 691 | fan_speed = fan->fan_min_speed; 692 | } 693 | 694 | temp_change = new_temp - old_temp; 695 | 696 | if (temp_change > 0 && new_temp > high_temp && new_temp < max_temp) { 697 | steps = (new_temp - high_temp) * (new_temp - high_temp + 1) / 2; 698 | fan_speed = max(fan_speed, ceil(fan->fan_min_speed + steps * fan->step_up)); 699 | } 700 | 701 | if (temp_change < 0 && new_temp > low_temp && new_temp < max_temp) { 702 | steps = (max_temp - new_temp) * (max_temp - new_temp + 1) / 2; 703 | fan_speed = min(fan_speed, floor(fan->fan_max_speed - steps * fan->step_down)); 704 | } 705 | 706 | if (verbose) { 707 | 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()); 708 | } 709 | 710 | set_fan_speed(fan, fan_speed); 711 | fan = fan->next; 712 | } 713 | 714 | if (verbose) { 715 | mbp_log(LOG_INFO, "Sleeping for %d seconds", polling_interval); 716 | } 717 | 718 | time_t before_sleep = time(NULL); 719 | 720 | // call nanosleep instead of sleep to avoid rt_sigprocmask and 721 | // rt_sigaction 722 | struct timespec ts; 723 | ts.tv_sec = polling_interval; 724 | ts.tv_nsec = 0; 725 | nanosleep(&ts, NULL); 726 | 727 | time_t after_sleep = time(NULL); 728 | if (after_sleep - before_sleep > 2 * polling_interval) { 729 | mbp_log(LOG_INFO, "Clock skew detected - slept for %ld seconds but expected %d", after_sleep - before_sleep, polling_interval); 730 | set_fans_man(fans); 731 | goto recalibrate; 732 | } 733 | } 734 | } 735 | -------------------------------------------------------------------------------- /src/mbpfan.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2010 Allan McRae 3 | * Modifications (2012-present) by Daniel Graziotin 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | */ 16 | 17 | #ifndef _MBPFAN_H_ 18 | #define _MBPFAN_H_ 19 | 20 | #include 21 | 22 | #include "global.h" 23 | 24 | /** Temperature Thresholds 25 | * low_temp - temperature below which fan speed will be at minimum 26 | * high_temp - fan will increase speed when higher than this temperature 27 | * max_temp - fan will run at full speed above this temperature */ 28 | extern int low_temp; 29 | extern int high_temp; 30 | extern int max_temp; 31 | 32 | /** Temperature polling interval 33 | * Default value was 10 (seconds) 34 | */ 35 | extern int polling_interval; 36 | 37 | char *smprintf(const char *fmt, ...) __attribute__((format(printf, 1, 2))); 38 | 39 | /** 40 | * Return true if the kernel is < 3.15.0 41 | */ 42 | bool is_legacy_sensors_path(); 43 | 44 | /** 45 | * Tries to use the settings located in 46 | * /etc/mbpfan.conf 47 | * If it fails, the default hardcoded settings are used 48 | */ 49 | void retrieve_settings(const char *settings_path, t_fans *fans); 50 | 51 | /** 52 | * Detect the sensors in /sys/devices/platform/coretemp.0/temp 53 | * and /sys/devices/platform/coretemp.1/temp etc 54 | * Return a linked list of t_sensors (first temperature detected) 55 | */ 56 | t_sensors *retrieve_sensors(); 57 | 58 | /** 59 | * Given a linked list of t_sensors, refresh their detected 60 | * temperature 61 | */ 62 | t_sensors *refresh_sensors(t_sensors *sensors); 63 | 64 | /** 65 | * Detect the fans in /sys/devices/platform/applesmc.768/ 66 | * Associate each fan to a sensor 67 | */ 68 | t_fans *retrieve_fans(); 69 | 70 | /** 71 | * Given a list of sensors with associated fans 72 | * Set them to manual control 73 | */ 74 | void set_fans_man(t_fans *fans); 75 | 76 | /** 77 | * Given a list of sensors with associated fans 78 | * Set them to automatic control 79 | */ 80 | void set_fans_auto(t_fans *fans); 81 | 82 | /** 83 | * Given a sensors with associated fans 84 | * Change their speed 85 | */ 86 | void set_fan_speed(t_fans *fan, int speed); 87 | 88 | /** 89 | * Given a list of fans set their minumum fan speed 90 | */ 91 | void set_fan_minimum_speed(t_fans *fans); 92 | /** 93 | * Return maximum CPU temp in degrees 94 | */ 95 | unsigned short get_temp(t_sensors *sensors); 96 | 97 | /** 98 | * Check if user has proper access and that required 99 | * kernel modules are available 100 | */ 101 | void check_requirements(const char *program_path); 102 | 103 | /** 104 | * Main Program 105 | */ 106 | void mbpfan(); 107 | 108 | #endif 109 | -------------------------------------------------------------------------------- /src/settings.c: -------------------------------------------------------------------------------- 1 | /* 2 | * settings version 1.0.1 3 | * 4 | * ANSI C implementation for managing application settings. 5 | * 6 | * Version History: 7 | * 1.0.0 (2009) - Initial release 8 | * 1.0.1 (2010) - Fixed small memory leak in settings_delete 9 | * (Thanks to Edwin van den Oetelaar) 10 | * 1.0.2 (2011) - Adapted code for new strmap API 11 | * 12 | * settings.c 13 | * 14 | * Copyright (c) 2009-2011 Per Ola Kristensson. 15 | * 16 | * Per Ola Kristensson 17 | * Inference Group, Department of Physics 18 | * University of Cambridge 19 | * Cavendish Laboratory 20 | * JJ Thomson Avenue 21 | * CB3 0HE Cambridge 22 | * United Kingdom 23 | * 24 | * settings is free software: you can redistribute it and/or modify 25 | * it under the terms of the GNU Lesser General Public License as published by 26 | * the Free Software Foundation, either version 3 of the License, or 27 | * (at your option) any later version. 28 | * 29 | * settings is distributed in the hope that it will be useful, 30 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 31 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 32 | * GNU Lesser General Public License for more details. 33 | * 34 | * You should have received a copy of the GNU Lesser General Public License 35 | * along with settings. If not, see . 36 | */ 37 | #include 38 | #include 39 | #include 40 | #include "settings.h" 41 | #include "strmap.h" 42 | 43 | #define MAX_SECTIONCHARS 256 44 | #define MAX_KEYCHARS 256 45 | #define MAX_VALUECHARS 256 46 | #define MAX_LINECHARS (MAX_KEYCHARS + MAX_VALUECHARS + 10) 47 | 48 | #define COMMENT_CHAR '#' 49 | #define SECTION_START_CHAR '[' 50 | #define SECTION_END_CHAR ']' 51 | #define KEY_VALUE_SEPARATOR_CHAR '=' 52 | 53 | #define DEFAULT_STRMAP_CAPACITY 256 54 | 55 | typedef struct Section Section; 56 | typedef struct ParseState ParseState; 57 | 58 | struct Settings { 59 | Section *sections; 60 | unsigned int section_count; 61 | }; 62 | 63 | struct Section { 64 | char *name; 65 | StrMap *map; 66 | }; 67 | 68 | struct ParseState { 69 | char *current_section; 70 | unsigned int current_section_n; 71 | int has_section; 72 | }; 73 | 74 | enum ConvertMode { 75 | CONVERT_MODE_INT, 76 | CONVERT_MODE_LONG, 77 | CONVERT_MODE_DOUBLE, 78 | }; 79 | 80 | typedef enum ConvertMode ConvertMode; 81 | 82 | static void trim_str(const char *str, char *out_buf); 83 | static int parse_str(Settings *settings, char *str, ParseState *parse_state); 84 | static int is_blank_char(char c); 85 | static int is_blank_str(const char *str); 86 | static int is_comment_str(const char *str); 87 | static int is_section_str(const char *str); 88 | static int is_key_value_str(const char *str); 89 | static int is_key_without_value_str(const char *str); 90 | static const char *get_token(char *str, char delim, char **last); 91 | static int get_section_from_str(const char *str, char *out_buf, unsigned int out_buf_n); 92 | 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); 93 | static int get_key_without_value_from_str(const char *str, char *out_buf, unsigned int out_buf_n); 94 | static int get_converted_value(const Settings *settings, const char *section, const char *key, ConvertMode mode, void *out); 95 | static int get_converted_tuple(const Settings *settings, const char *section, const char *key, char delim, ConvertMode mode, void *out, unsigned int n_out); 96 | static Section *get_section(Section *sections, unsigned int n, const char *name); 97 | static void enum_map(const char *key, const char *value, const void *obj); 98 | 99 | Settings *settings_new() 100 | { 101 | Settings *settings; 102 | 103 | settings = (Settings *)malloc(sizeof(Settings)); 104 | 105 | if (settings == NULL) { 106 | return NULL; 107 | } 108 | 109 | settings->section_count = 0; 110 | settings->sections = NULL; 111 | return settings; 112 | } 113 | 114 | void settings_delete(Settings *settings) 115 | { 116 | unsigned int i, n; 117 | Section *section; 118 | 119 | if (settings == NULL) { 120 | return; 121 | } 122 | 123 | section = settings->sections; 124 | n = settings->section_count; 125 | i = 0; 126 | 127 | while (i < n) { 128 | sm_delete(section->map); 129 | 130 | if (section->name != NULL) { 131 | free(section->name); 132 | } 133 | 134 | section++; 135 | i++; 136 | } 137 | 138 | free(settings->sections); 139 | free(settings); 140 | } 141 | 142 | Settings *settings_open(FILE *stream) 143 | { 144 | Settings *settings; 145 | char buf[MAX_LINECHARS]; 146 | char trimmed_buf[MAX_LINECHARS]; 147 | char section_buf[MAX_LINECHARS]; 148 | ParseState parse_state; 149 | 150 | if (stream == NULL) { 151 | return NULL; 152 | } 153 | 154 | settings = settings_new(); 155 | 156 | if (settings == NULL) { 157 | return NULL; 158 | } 159 | 160 | parse_state.current_section = section_buf; 161 | parse_state.current_section_n = sizeof(section_buf); 162 | parse_state.has_section = 0; 163 | trim_str("", trimmed_buf); 164 | 165 | while (fgets(buf, MAX_LINECHARS, stream) != NULL) { 166 | trim_str(buf, trimmed_buf); 167 | 168 | if (!parse_str(settings, trimmed_buf, &parse_state)) { 169 | return NULL; 170 | } 171 | } 172 | 173 | return settings; 174 | } 175 | 176 | int settings_save(const Settings *settings, FILE *stream) 177 | { 178 | unsigned int i, n; 179 | Section *section; 180 | char buf[MAX_LINECHARS]; 181 | 182 | if (settings == NULL) { 183 | return 0; 184 | } 185 | 186 | if (stream == NULL) { 187 | return 0; 188 | } 189 | 190 | section = settings->sections; 191 | n = settings->section_count; 192 | i = 0; 193 | 194 | while (i < n) { 195 | sprintf(buf, "[%s]\n", section->name); 196 | fputs(buf, stream); 197 | sm_enum(section->map, enum_map, stream); 198 | section++; 199 | i++; 200 | fputs("\n", stream); 201 | } 202 | 203 | return 0; 204 | } 205 | 206 | int settings_get(const Settings *settings, const char *section, const char *key, char *out_buf, unsigned int n_out_buf) 207 | { 208 | Section *s; 209 | 210 | if (settings == NULL) { 211 | return 0; 212 | } 213 | 214 | s = get_section(settings->sections, settings->section_count, section); 215 | 216 | if (s == NULL) { 217 | return 0; 218 | } 219 | 220 | return sm_get(s->map, key, out_buf, n_out_buf); 221 | } 222 | 223 | int settings_get_int(const Settings *settings, const char *section, const char *key) 224 | { 225 | int i; 226 | 227 | if (get_converted_value(settings, section, key, CONVERT_MODE_INT, &i)) { 228 | return i; 229 | } 230 | 231 | return 0; 232 | } 233 | 234 | long settings_get_long(const Settings *settings, const char *section, const char *key) 235 | { 236 | long l; 237 | 238 | if (get_converted_value(settings, section, key, CONVERT_MODE_LONG, &l)) { 239 | return l; 240 | } 241 | 242 | return 0; 243 | } 244 | 245 | double settings_get_double(const Settings *settings, const char *section, const char *key) 246 | { 247 | double d; 248 | 249 | if (get_converted_value(settings, section, key, CONVERT_MODE_DOUBLE, &d)) { 250 | return d; 251 | } 252 | 253 | return 0; 254 | } 255 | 256 | int settings_get_int_tuple(const Settings *settings, const char *section, const char *key, int *out, unsigned int n_out) 257 | { 258 | return get_converted_tuple(settings, section, key, ',', CONVERT_MODE_INT, out, n_out); 259 | } 260 | 261 | long settings_get_long_tuple(const Settings *settings, const char *section, const char *key, long *out, unsigned int n_out) 262 | { 263 | return get_converted_tuple(settings, section, key, ',', CONVERT_MODE_LONG, out, n_out); 264 | } 265 | 266 | double settings_get_double_tuple(const Settings *settings, const char *section, const char *key, double *out, unsigned int n_out) 267 | { 268 | return get_converted_tuple(settings, section, key, ',', CONVERT_MODE_DOUBLE, out, n_out); 269 | } 270 | 271 | int settings_set(Settings *settings, const char *section, const char *key, const char *value) 272 | { 273 | Section *s; 274 | 275 | if (settings == NULL) { 276 | return 0; 277 | } 278 | 279 | if (section == NULL || key == NULL || value == NULL) { 280 | return 0; 281 | } 282 | 283 | if (strlen(section) == 0) { 284 | return 0; 285 | } 286 | 287 | /* Get a pointer to the section */ 288 | s = get_section(settings->sections, settings->section_count, section); 289 | 290 | if (s == NULL) { 291 | /* The section is not created---create it */ 292 | s = (Section *)realloc(settings->sections, (settings->section_count + 1) * sizeof(Section)); 293 | 294 | if (s == NULL) { 295 | return 0; 296 | } 297 | 298 | settings->sections = s; 299 | settings->section_count++; 300 | s = &(settings->sections[settings->section_count - 1]); 301 | s->map = sm_new(DEFAULT_STRMAP_CAPACITY); 302 | 303 | if (s->map == NULL) { 304 | free(s); 305 | return 0; 306 | } 307 | 308 | s->name = (char *)malloc((strlen(section) + 1) * sizeof(char)); 309 | 310 | if (s->name == NULL) { 311 | sm_delete(s->map); 312 | free(s); 313 | return 0; 314 | } 315 | 316 | strcpy(s->name, section); 317 | } 318 | 319 | return sm_put(s->map, key, value); 320 | } 321 | 322 | int settings_section_get_count(const Settings *settings, const char *section) 323 | { 324 | Section *sect; 325 | 326 | if (settings == NULL) { 327 | return 0; 328 | } 329 | 330 | sect = get_section(settings->sections, settings->section_count, section); 331 | 332 | if (sect == NULL) { 333 | return 0; 334 | } 335 | 336 | return sm_get_count(sect->map); 337 | } 338 | 339 | int settings_section_enum(const Settings *settings, const char *section, settings_section_enum_func enum_func, const void *obj) 340 | { 341 | Section *sect; 342 | 343 | sect = get_section(settings->sections, settings->section_count, section); 344 | 345 | if (sect == NULL) { 346 | return 0; 347 | } 348 | 349 | return sm_enum(sect->map, enum_func, obj); 350 | } 351 | 352 | /* Copies a trimmed variant without leading and trailing blank characters 353 | * of the input string into the output buffer. The output buffer is assumed 354 | * to be large enough to contain the entire input string. 355 | */ 356 | static void trim_str(const char *str, char *out_buf) 357 | { 358 | unsigned int len; 359 | const char *s0; 360 | 361 | while (*str != '\0' && is_blank_char(*str)) { 362 | str++; 363 | } 364 | 365 | s0 = str; 366 | len = 0; 367 | 368 | while (*str != '\0') { 369 | len++; 370 | str++; 371 | } 372 | 373 | if (len > 0) { 374 | str--; 375 | } 376 | 377 | while (is_blank_char(*str)) { 378 | str--; 379 | len--; 380 | } 381 | 382 | memcpy(out_buf, s0, len); 383 | out_buf[len] = '\0'; 384 | } 385 | 386 | /* Parses a single input string and updates the provided settings object. 387 | * The given parse state may be updated following a call. It is assumed this 388 | * function is called in repeated succession for each input line read. The 389 | * provided parse state should be initialized to the following before this 390 | * function is called for the first time for an intended parse: 391 | * 392 | * parse_state->current_section: a pre-allocated character buffer this function 393 | * can read and write to 394 | * parse_state->current_section_n: sizeof(parse_state->current_section) 395 | * parse_state->has_section: 0 (false) 396 | */ 397 | static int parse_str(Settings *settings, char *str, ParseState *parse_state) 398 | { 399 | char buf[MAX_LINECHARS]; 400 | char buf1[MAX_LINECHARS]; 401 | char buf2[MAX_LINECHARS]; 402 | int result; 403 | 404 | if (*str == '\0') { 405 | return 1; 406 | 407 | } else if (is_blank_str(str)) { 408 | return 1; 409 | 410 | } else if (is_comment_str(str)) { 411 | return 1; 412 | 413 | } else if (is_section_str(str)) { 414 | result = get_section_from_str(str, buf, sizeof(buf)); 415 | 416 | if (!result) { 417 | return 0; 418 | } 419 | 420 | if (strlen(buf) + 1 > parse_state->current_section_n) { 421 | return 0; 422 | } 423 | 424 | strcpy(parse_state->current_section, buf); 425 | parse_state->has_section = 1; 426 | return 1; 427 | 428 | } else if (is_key_value_str(str)) { 429 | result = get_key_value_from_str(str, buf1, sizeof(buf1), buf2, sizeof(buf2)); 430 | 431 | if (!result) { 432 | return 0; 433 | } 434 | 435 | if (!parse_state->has_section) { 436 | return 0; 437 | } 438 | 439 | return settings_set(settings, parse_state->current_section, buf1, buf2); 440 | 441 | } else if (is_key_without_value_str(str)) { 442 | result = get_key_without_value_from_str(str, buf, sizeof(buf)); 443 | 444 | if (!result) { 445 | return 0; 446 | } 447 | 448 | if (!parse_state->has_section) { 449 | return 0; 450 | } 451 | 452 | return settings_set(settings, parse_state->current_section, buf, ""); 453 | 454 | } else { 455 | return 0; 456 | } 457 | } 458 | 459 | /* Returns true if the input character is blank, 460 | * false otherwise. 461 | */ 462 | static int is_blank_char(char c) 463 | { 464 | return c == ' ' || c == '\t' || c == '\r' || c == '\n'; 465 | } 466 | 467 | /* Returns true if the input string is blank, 468 | * false otherwise. 469 | */ 470 | static int is_blank_str(const char *str) 471 | { 472 | while (*str != '\0') { 473 | if (!is_blank_char(*str)) { 474 | return 0; 475 | } 476 | 477 | str++; 478 | } 479 | 480 | return 1; 481 | } 482 | 483 | /* Returns true if the input string denotes a comment, 484 | * false otherwise. 485 | */ 486 | static int is_comment_str(const char *str) 487 | { 488 | if (*str == COMMENT_CHAR) { 489 | /* To be a comment the first character must be the 490 | * comment character. 491 | */ 492 | return 1; 493 | } 494 | 495 | return 0; 496 | } 497 | 498 | /* Returns true if the input string denotes a section name, 499 | * false otherwise. 500 | */ 501 | static int is_section_str(const char *str) 502 | { 503 | if (*str != SECTION_START_CHAR) { 504 | /* The first character must be the section start character */ 505 | return 0; 506 | } 507 | 508 | while (*str != '\0' && *str != SECTION_END_CHAR) { 509 | str++; 510 | } 511 | 512 | if (*str != SECTION_END_CHAR) { 513 | /* The section end character must be present somewhere thereafter */ 514 | return 0; 515 | } 516 | 517 | return 1; 518 | } 519 | 520 | /* Returns true if the input string denotes a key-value pair, 521 | * false otherwise. 522 | */ 523 | static int is_key_value_str(const char *str) 524 | { 525 | if (*str == KEY_VALUE_SEPARATOR_CHAR) { 526 | /* It is illegal to start with the key-value separator */ 527 | return 0; 528 | } 529 | 530 | while (*str != '\0' && *str != KEY_VALUE_SEPARATOR_CHAR) { 531 | str++; 532 | } 533 | 534 | if (*str != KEY_VALUE_SEPARATOR_CHAR) { 535 | /* The key-value separator must be present after the key part */ 536 | return 0; 537 | } 538 | 539 | return 1; 540 | } 541 | 542 | /* Returns true if the input string denotes a key without a value, 543 | * false otherwise. 544 | */ 545 | static int is_key_without_value_str(const char *str) 546 | { 547 | if (*str == KEY_VALUE_SEPARATOR_CHAR) { 548 | /* It is illegal to start with the key-value separator */ 549 | return 0; 550 | } 551 | 552 | while (*str != '\0' && *str != KEY_VALUE_SEPARATOR_CHAR) { 553 | str++; 554 | } 555 | 556 | if (*str == KEY_VALUE_SEPARATOR_CHAR) { 557 | /* The key-value separator must not be present after the key part */ 558 | return 0; 559 | } 560 | 561 | return 1; 562 | } 563 | 564 | /* 565 | * Parses a section name from an input string. The input string is assumed to 566 | * already have been identified as a valid input string denoting a section name. 567 | */ 568 | static int get_section_from_str(const char *str, char *out_buf, unsigned int out_buf_n) 569 | { 570 | unsigned int count; 571 | 572 | count = 0; 573 | /* Jump past the section begin character */ 574 | str++; 575 | 576 | while (*str != '\0' && *str != SECTION_END_CHAR) { 577 | /* Read in the section name into the output buffer */ 578 | if (count == out_buf_n) { 579 | return 0; 580 | } 581 | 582 | *out_buf = *str; 583 | out_buf++; 584 | str++; 585 | count++; 586 | } 587 | 588 | /* Terminate the output buffer */ 589 | if (count == out_buf_n) { 590 | return 0; 591 | } 592 | 593 | *out_buf = '\0'; 594 | return 1; 595 | } 596 | 597 | /* 598 | * Parses a key and value from an input string. The input string is assumed to 599 | * already have been identified as a valid input string denoting a key-value pair. 600 | */ 601 | 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) 602 | { 603 | unsigned int count1; 604 | unsigned int count2; 605 | 606 | count1 = 0; 607 | count2 = 0; 608 | 609 | /* Read the key value from the input string and write it sequentially 610 | * to the first output buffer by walking the input string until we either hit 611 | * the null-terminator or the key-value separator. 612 | */ 613 | while (*str != '\0' && *str != KEY_VALUE_SEPARATOR_CHAR) { 614 | /* Ensure the first output buffer is large enough. */ 615 | if (count1 == out_buf1_n) { 616 | return 0; 617 | } 618 | 619 | /* Copy the character to the first output buffer */ 620 | *out_buf1 = *str; 621 | out_buf1++; 622 | str++; 623 | count1++; 624 | } 625 | 626 | /* Terminate the first output buffer */ 627 | if (count1 == out_buf1_n) { 628 | return 0; 629 | } 630 | 631 | *out_buf1 = '\0'; 632 | 633 | /* Now trace the first input buffer backwards until we hit a non-blank character */ 634 | while (is_blank_char(*(out_buf1 - 1))) { 635 | out_buf1--; 636 | } 637 | 638 | *out_buf1 = '\0'; 639 | 640 | /* Try to proceed one more character, past the last read key-value 641 | * delimiter, in the input string. 642 | */ 643 | if (*str != '\0') { 644 | str++; 645 | } 646 | 647 | /* Now find start of the value in the input string by walking the input 648 | * string until we either hit the null-terminator or a blank character. 649 | */ 650 | while (*str != '\0' && is_blank_char(*str)) { 651 | str++; 652 | } 653 | 654 | while (*str != '\0') { 655 | /* Fail if there is a possibility that we are overwriting the second 656 | * input buffer. 657 | */ 658 | if (count2 == out_buf2_n) { 659 | return 0; 660 | } 661 | 662 | /* Copy the character to the second output buffer */ 663 | *out_buf2 = *str; 664 | out_buf2++; 665 | str++; 666 | count2++; 667 | } 668 | 669 | /* Terminate the second output buffer */ 670 | if (count2 == out_buf2_n) { 671 | return 0; 672 | } 673 | 674 | *out_buf2 = '\0'; 675 | return 1; 676 | } 677 | 678 | /* 679 | * Parses a key from an input string. The input string is assumed to already 680 | * have been identified as a valid input string denoting a key without a value. 681 | */ 682 | static int get_key_without_value_from_str(const char *str, char *out_buf, unsigned int out_buf_n) 683 | { 684 | unsigned int count; 685 | 686 | count = 0; 687 | 688 | /* Now read the key value from the input string and write it sequentially 689 | * to the output buffer by walking the input string until we either hit 690 | * the null-terminator or the key-value separator. 691 | */ 692 | while (*str != '\0') { 693 | /* Ensure the output buffer is large enough. */ 694 | if (count == out_buf_n) { 695 | return 0; 696 | } 697 | 698 | /* Copy the character to the input buffer */ 699 | *out_buf = *str; 700 | out_buf++; 701 | str++; 702 | count++; 703 | } 704 | 705 | /* Terminate the output buffer */ 706 | if (count == out_buf_n) { 707 | return 0; 708 | } 709 | 710 | *out_buf = '\0'; 711 | return 1; 712 | } 713 | 714 | /* Returns a pointer to the next token in the input string delimited 715 | * by the specified delimiter or null if no such token exist. The provided 716 | * last pointer will be changed to point one position after the pointed 717 | * token. The currently ouputted token will be null-terminated. 718 | * 719 | * An idiom for tokenizing a (in this case, comma-separated) string is: 720 | * 721 | * char test_string[] = "Token1,Token2,Token3"; 722 | * char token[255]; 723 | * char *str; 724 | * 725 | * str = test_string; 726 | * while ((token = get_token(str, ',', &str) != NULL) { 727 | * printf("token: %s", token); 728 | * } 729 | */ 730 | static const char *get_token(char *str, char delim, char **last) 731 | { 732 | 733 | char *s0; 734 | 735 | s0 = str; 736 | 737 | /* If we hit the null-terminator the string 738 | * is exhausted and another token does not 739 | * exist. 740 | */ 741 | if (*str == '\0') { 742 | return NULL; 743 | } 744 | 745 | /* Walk the string until we encounter a 746 | * null-terminator or the delimiter. 747 | */ 748 | while (*str != '\0' && *str != delim) { 749 | str++; 750 | } 751 | 752 | /* Terminate the return token, if necessary */ 753 | if (*str != '\0') { 754 | *str = '\0'; 755 | str++; 756 | } 757 | 758 | *last = str; 759 | return s0; 760 | } 761 | 762 | /* Returns a converted value pointed to by the provided key in the given section. 763 | * The mode specifies which conversion takes place and dictates what value out 764 | * is pointing to. The value out is pointing to will be replaced by the converted 765 | * value assuming conversion is succesful. The function returns 1 if conversion 766 | * is succsessful and 0 if the convertion could not be carried out. 767 | */ 768 | static int get_converted_value(const Settings *settings, const char *section, const char *key, ConvertMode mode, void *out) 769 | { 770 | char value[MAX_VALUECHARS]; 771 | 772 | if (!settings_get(settings, section, key, value, MAX_VALUECHARS)) { 773 | return 0; 774 | } 775 | 776 | switch (mode) { 777 | case CONVERT_MODE_INT: 778 | *((int *)out) = atoi(value); 779 | return 1; 780 | 781 | case CONVERT_MODE_LONG: 782 | *((long *)out) = atol(value); 783 | return 1; 784 | 785 | case CONVERT_MODE_DOUBLE: 786 | *((double *)out) = atof(value); 787 | return 1; 788 | } 789 | 790 | return 0; 791 | } 792 | 793 | /* Returns a converted tuple pointed to by the provided key in the given section. 794 | * The tuple is created by splitting the value by the supplied delimiter and then 795 | * converting each token after the split according to the specified mode. 796 | * The array out is pointing to will be replaced by the converted tuple 797 | * assuming conversion is succesful. The function returns 1 if conversion 798 | * is succsessful and 0 if the convertion could not be carried out. 799 | */ 800 | static int get_converted_tuple(const Settings *settings, const char *section, const char *key, char delim, ConvertMode mode, void *out, unsigned int n_out) 801 | { 802 | unsigned int count; 803 | const char *token; 804 | static char value[MAX_VALUECHARS]; 805 | char *v; 806 | 807 | if (out == NULL) { 808 | return 0; 809 | } 810 | 811 | if (n_out == 0) { 812 | return 0; 813 | } 814 | 815 | if (!settings_get(settings, section, key, value, MAX_VALUECHARS)) { 816 | return 0; 817 | } 818 | 819 | v = value; 820 | count = 0; 821 | 822 | /* Walk over all tokens in the value, and convert them and assign them 823 | * to the output array as specified by the mode. 824 | */ 825 | while ((token = get_token(v, delim, &v)) != NULL && count < n_out) { 826 | switch (mode) { 827 | case CONVERT_MODE_INT: 828 | ((int *)out)[count] = atoi(token); 829 | break; 830 | 831 | case CONVERT_MODE_LONG: 832 | ((long *)out)[count] = atol(token); 833 | break; 834 | 835 | case CONVERT_MODE_DOUBLE: 836 | ((double *)out)[count] = atof(token); 837 | break; 838 | 839 | default: 840 | return 0; 841 | } 842 | 843 | count++; 844 | } 845 | 846 | return 1; 847 | } 848 | 849 | /* Returns a pointer to the section or null if the named section does not 850 | * exist. 851 | */ 852 | static Section *get_section(Section *sections, unsigned int n, const char *name) 853 | { 854 | unsigned int i; 855 | Section *section; 856 | 857 | if (name == NULL) { 858 | return NULL; 859 | } 860 | 861 | section = sections; 862 | i = 0; 863 | 864 | while (i < n) { 865 | if (strcmp(section->name, name) == 0) { 866 | return section; 867 | } 868 | 869 | section++; 870 | i++; 871 | } 872 | 873 | return NULL; 874 | } 875 | 876 | /* Callback function that is passed into the enumeration function in the 877 | * string map. It casts the passed into object into a FILE pointer and 878 | * writes out the key and value to the file. 879 | */ 880 | static void enum_map(const char *key, const char *value, const void *obj) 881 | { 882 | FILE *stream; 883 | char buf[MAX_LINECHARS]; 884 | 885 | if (key == NULL || value == NULL) { 886 | return; 887 | } 888 | 889 | if (obj == NULL) { 890 | return; 891 | } 892 | 893 | stream = (FILE *)obj; 894 | 895 | if (strlen(key) < MAX_KEYCHARS && strlen(value) < MAX_VALUECHARS) { 896 | sprintf(buf, "%s%c%s\n", key, KEY_VALUE_SEPARATOR_CHAR, value); 897 | fputs(buf, stream); 898 | } 899 | } 900 | 901 | /* 902 | 903 | GNU LESSER GENERAL PUBLIC LICENSE 904 | Version 3, 29 June 2007 905 | 906 | Copyright (C) 2007 Free Software Foundation, Inc. 907 | Everyone is permitted to copy and distribute verbatim copies 908 | of this license document, but changing it is not allowed. 909 | 910 | 911 | This version of the GNU Lesser General Public License incorporates 912 | the terms and conditions of version 3 of the GNU General Public 913 | License, supplemented by the additional permissions listed below. 914 | 915 | 0. Additional Definitions. 916 | 917 | As used herein, "this License" refers to version 3 of the GNU Lesser 918 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 919 | General Public License. 920 | 921 | "The Library" refers to a covered work governed by this License, 922 | other than an Application or a Combined Work as defined below. 923 | 924 | An "Application" is any work that makes use of an interface provided 925 | by the Library, but which is not otherwise based on the Library. 926 | Defining a subclass of a class defined by the Library is deemed a mode 927 | of using an interface provided by the Library. 928 | 929 | A "Combined Work" is a work produced by combining or linking an 930 | Application with the Library. The particular version of the Library 931 | with which the Combined Work was made is also called the "Linked 932 | Version". 933 | 934 | The "Minimal Corresponding Source" for a Combined Work means the 935 | Corresponding Source for the Combined Work, excluding any source code 936 | for portions of the Combined Work that, considered in isolation, are 937 | based on the Application, and not on the Linked Version. 938 | 939 | The "Corresponding Application Code" for a Combined Work means the 940 | object code and/or source code for the Application, including any data 941 | and utility programs needed for reproducing the Combined Work from the 942 | Application, but excluding the System Libraries of the Combined Work. 943 | 944 | 1. Exception to Section 3 of the GNU GPL. 945 | 946 | You may convey a covered work under sections 3 and 4 of this License 947 | without being bound by section 3 of the GNU GPL. 948 | 949 | 2. Conveying Modified Versions. 950 | 951 | If you modify a copy of the Library, and, in your modifications, a 952 | facility refers to a function or data to be supplied by an Application 953 | that uses the facility (other than as an argument passed when the 954 | facility is invoked), then you may convey a copy of the modified 955 | version: 956 | 957 | a) under this License, provided that you make a good faith effort to 958 | ensure that, in the event an Application does not supply the 959 | function or data, the facility still operates, and performs 960 | whatever part of its purpose remains meaningful, or 961 | 962 | b) under the GNU GPL, with none of the additional permissions of 963 | this License applicable to that copy. 964 | 965 | 3. Object Code Incorporating Material from Library Header Files. 966 | 967 | The object code form of an Application may incorporate material from 968 | a header file that is part of the Library. You may convey such object 969 | code under terms of your choice, provided that, if the incorporated 970 | material is not limited to numerical parameters, data structure 971 | layouts and accessors, or small macros, inline functions and templates 972 | (ten or fewer lines in length), you do both of the following: 973 | 974 | a) Give prominent notice with each copy of the object code that the 975 | Library is used in it and that the Library and its use are 976 | covered by this License. 977 | 978 | b) Accompany the object code with a copy of the GNU GPL and this license 979 | document. 980 | 981 | 4. Combined Works. 982 | 983 | You may convey a Combined Work under terms of your choice that, 984 | taken together, effectively do not restrict modification of the 985 | portions of the Library contained in the Combined Work and reverse 986 | engineering for debugging such modifications, if you also do each of 987 | the following: 988 | 989 | a) Give prominent notice with each copy of the Combined Work that 990 | the Library is used in it and that the Library and its use are 991 | covered by this License. 992 | 993 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 994 | document. 995 | 996 | c) For a Combined Work that displays copyright notices during 997 | execution, include the copyright notice for the Library among 998 | these notices, as well as a reference directing the user to the 999 | copies of the GNU GPL and this license document. 1000 | 1001 | d) Do one of the following: 1002 | 1003 | 0) Convey the Minimal Corresponding Source under the terms of this 1004 | License, and the Corresponding Application Code in a form 1005 | suitable for, and under terms that permit, the user to 1006 | recombine or relink the Application with a modified version of 1007 | the Linked Version to produce a modified Combined Work, in the 1008 | manner specified by section 6 of the GNU GPL for conveying 1009 | Corresponding Source. 1010 | 1011 | 1) Use a suitable shared library mechanism for linking with the 1012 | Library. A suitable mechanism is one that (a) uses at run time 1013 | a copy of the Library already present on the user's computer 1014 | system, and (b) will operate properly with a modified version 1015 | of the Library that is interface-compatible with the Linked 1016 | Version. 1017 | 1018 | e) Provide Installation Information, but only if you would otherwise 1019 | be required to provide such information under section 6 of the 1020 | GNU GPL, and only to the extent that such information is 1021 | necessary to install and execute a modified version of the 1022 | Combined Work produced by recombining or relinking the 1023 | Application with a modified version of the Linked Version. (If 1024 | you use option 4d0, the Installation Information must accompany 1025 | the Minimal Corresponding Source and Corresponding Application 1026 | Code. If you use option 4d1, you must provide the Installation 1027 | Information in the manner specified by section 6 of the GNU GPL 1028 | for conveying Corresponding Source.) 1029 | 1030 | 5. Combined Libraries. 1031 | 1032 | You may place library facilities that are a work based on the 1033 | Library side by side in a single library together with other library 1034 | facilities that are not Applications and are not covered by this 1035 | License, and convey such a combined library under terms of your 1036 | choice, if you do both of the following: 1037 | 1038 | a) Accompany the combined library with a copy of the same work based 1039 | on the Library, uncombined with any other library facilities, 1040 | conveyed under the terms of this License. 1041 | 1042 | b) Give prominent notice with the combined library that part of it 1043 | is a work based on the Library, and explaining where to find the 1044 | accompanying uncombined form of the same work. 1045 | 1046 | 6. Revised Versions of the GNU Lesser General Public License. 1047 | 1048 | The Free Software Foundation may publish revised and/or new versions 1049 | of the GNU Lesser General Public License from time to time. Such new 1050 | versions will be similar in spirit to the present version, but may 1051 | differ in detail to address new problems or concerns. 1052 | 1053 | Each version is given a distinguishing version number. If the 1054 | Library as you received it specifies that a certain numbered version 1055 | of the GNU Lesser General Public License "or any later version" 1056 | applies to it, you have the option of following the terms and 1057 | conditions either of that published version or of any later version 1058 | published by the Free Software Foundation. If the Library as you 1059 | received it does not specify a version number of the GNU Lesser 1060 | General Public License, you may choose any version of the GNU Lesser 1061 | General Public License ever published by the Free Software Foundation. 1062 | 1063 | If the Library as you received it specifies that a proxy can decide 1064 | whether future versions of the GNU Lesser General Public License shall 1065 | apply, that proxy's public statement of acceptance of any version is 1066 | permanent authorization for you to choose that version for the 1067 | Library. 1068 | 1069 | */ 1070 | -------------------------------------------------------------------------------- /src/settings.h: -------------------------------------------------------------------------------- 1 | /* 2 | * settings version 1.0.0 3 | * 4 | * ANSI C implementation for managing application settings. 5 | * 6 | * settings.h 7 | * 8 | * Copyright (c) 2009 Per Ola Kristensson. 9 | * 10 | * Per Ola Kristensson 11 | * Inference Group, Department of Physics 12 | * University of Cambridge 13 | * Cavendish Laboratory 14 | * JJ Thomson Avenue 15 | * CB3 0HE Cambridge 16 | * United Kingdom 17 | * 18 | * settings is free software: you can redistribute it and/or modify 19 | * it under the terms of the GNU Lesser General Public License as published by 20 | * the Free Software Foundation, either version 3 of the License, or 21 | * (at your option) any later version. 22 | * 23 | * settings is distributed in the hope that it will be useful, 24 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 25 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 26 | * GNU Lesser General Public License for more details. 27 | * 28 | * You should have received a copy of the GNU Lesser General Public License 29 | * along with settings. If not, see . 30 | */ 31 | #ifndef _SETTINGS_H_ 32 | #define _SETTINGS_H_ 33 | 34 | #include 35 | 36 | #ifdef __cplusplus 37 | extern "C" { 38 | #endif 39 | 40 | typedef struct Settings Settings; 41 | 42 | /* 43 | * This callback function is called once per key-value when enumerating 44 | * all keys inside a section. 45 | * 46 | * Parameters: 47 | * 48 | * key: A pointer to a null-terminated C string. The string must not 49 | * be modified by the client. 50 | * 51 | * value: A pointer to a null-terminated C string. The string must 52 | * not be modified by the client. 53 | * 54 | * obj: A pointer to a client-specific object. This parameter may be 55 | * null. 56 | * 57 | * Return value: None. 58 | */ 59 | typedef void (*settings_section_enum_func)(const char *key, const char *value, const void *obj); 60 | 61 | /* 62 | * Creates a settings object. 63 | * 64 | * Return value: A pointer to a settings object, 65 | * or null if a new settings object could not be allocated. 66 | */ 67 | Settings *settings_new(); 68 | 69 | /* 70 | * Releases all memory held by a settings object. 71 | * 72 | * Parameters: 73 | * 74 | * settings: A pointer to a settings object. This parameter cannot be null. 75 | * If the supplied settings object has been previously released, the 76 | * behaviour of this function is undefined. 77 | * 78 | * Return value: None. 79 | */ 80 | void settings_delete(Settings *settings); 81 | 82 | /* 83 | * Constructs a settings object by loading settings in textual form 84 | * from the given stream. 85 | * 86 | * Parameters: 87 | * 88 | * settings: A pointer to a settings object. This parameter cannot be null. 89 | * 90 | * stream: A pointer to a stream. This parameter cannot be null. 91 | * 92 | * Return value: A pointer to a settings object, 93 | * or null if an error occurred. 94 | */ 95 | Settings *settings_open(FILE *stream); 96 | 97 | /* 98 | * Saves the current settings object in textual form to the given stream. 99 | * 100 | * Parameters: 101 | * 102 | * settings: A pointer to a settings object. This parameter cannot be null. 103 | * 104 | * stream: A pointer to a stream. This parameter cannot be null. 105 | * 106 | * Return value: 1 if the operation succeeded, 0 otherwise. 107 | */ 108 | int settings_save(const Settings *settings, FILE *stream); 109 | 110 | /* 111 | * Returns the value associated with the supplied key in the 112 | * provided section. 113 | * 114 | * Parameters: 115 | * 116 | * settings: A pointer to a settings object. This parameter cannot be null. 117 | * 118 | * section: A pointer to a null-terminated C string. This parameter cannot 119 | * be null. 120 | * 121 | * key: A pointer to a null-terminated C string. This parameter cannot 122 | * be null. 123 | * 124 | * out_buf: A pointer to an output buffer which will contain the value, 125 | * if it exists and fits into the buffer. 126 | * 127 | * n_out_buf: The size of the output buffer in bytes. 128 | * 129 | * Return value: If out_buf is set to null and n_out_buf is set to 0 the return 130 | * value will be the number of bytes required to store the value (if it exists) 131 | * and its null-terminator. For all other parameter configurations the return value 132 | * is 1 if an associated value was found and completely copied into the output buffer, 133 | * 0 otherwise. 134 | */ 135 | int settings_get(const Settings *settings, const char *section, const char *key, char *out_buf, unsigned int n_out_buf); 136 | 137 | /* 138 | * Returns the integer value associated with the supplied key in the 139 | * provided section. 140 | * 141 | * Parameters: 142 | * 143 | * settings: A pointer to a settings object. This parameter cannot be null. 144 | * 145 | * section: A pointer to a null-terminated C string. This parameter cannot 146 | * be null. 147 | * 148 | * key: A pointer to a null-terminated C string. This parameter cannot 149 | * be null. 150 | * 151 | * Return value: The integer value associated to the provided section and 152 | * key, or 0 if no such value exists. 153 | */ 154 | int settings_get_int(const Settings *settings, const char *section, const char *key); 155 | 156 | /* 157 | * Returns the long integer value associated with the supplied key in the 158 | * provided section. 159 | * 160 | * Parameters: 161 | * 162 | * settings: A pointer to a settings object. This parameter cannot be null. 163 | * 164 | * section: A pointer to a null-terminated C string. This parameter cannot 165 | * be null. 166 | * 167 | * key: A pointer to a null-terminated C string. This parameter cannot 168 | * be null. 169 | * 170 | * Return value: The long integer value associated to the provided section and 171 | * key, or 0 if no such value exists. 172 | */ 173 | long settings_get_long(const Settings *settings, const char *section, const char *key); 174 | 175 | /* 176 | * Returns the double value associated with the supplied key in the 177 | * provided section. 178 | * 179 | * Parameters: 180 | * 181 | * settings: A pointer to a settings object. This parameter cannot be null. 182 | * 183 | * section: A pointer to a null-terminated C string. This parameter cannot 184 | * be null. 185 | * 186 | * key: A pointer to a null-terminated C string. This parameter cannot 187 | * be null. 188 | * 189 | * Return value: The double value associated to the provided section and 190 | * key, or 0 if no such value exists. 191 | */ 192 | double settings_get_double(const Settings *settings, const char *section, const char *key); 193 | 194 | /* 195 | * Returns the integer tuple associated with the supplied key in the 196 | * provided section. 197 | * 198 | * Parameters: 199 | * 200 | * settings: A pointer to a settings object. This parameter cannot be null. 201 | * 202 | * section: A pointer to a null-terminated C string. This parameter cannot 203 | * be null. 204 | * 205 | * key: A pointer to a null-terminated C string. This parameter cannot 206 | * be null. 207 | * 208 | * out: A pointer to an output buffer. 209 | * 210 | * n_out: The maximum number of elements the output buffer can hold. 211 | * 212 | * Return value: 1 if the entire tuple was copied into the output buffer, 213 | * 0 otherwise. 214 | */ 215 | int settings_get_int_tuple(const Settings *settings, const char *section, const char *key, int *out, unsigned int n_out); 216 | 217 | /* 218 | * Returns the long tuple associated with the supplied key in the 219 | * provided section. 220 | * 221 | * Parameters: 222 | * 223 | * settings: A pointer to a settings object. This parameter cannot be null. 224 | * 225 | * section: A pointer to a null-terminated C string. This parameter cannot 226 | * be null. 227 | * 228 | * key: A pointer to a null-terminated C string. This parameter cannot 229 | * be null. 230 | * 231 | * out: A pointer to an output buffer. 232 | * 233 | * n_out: The maximum number of elements the output buffer can hold. 234 | * 235 | * Return value: 1 if the entire tuple was copied into the output buffer, 236 | * 0 otherwise. 237 | */ 238 | long settings_get_long_tuple(const Settings *settings, const char *section, const char *key, long *out, unsigned int n_out); 239 | 240 | /* 241 | * Returns the double tuple associated with the supplied key in the 242 | * provided section. 243 | * 244 | * Parameters: 245 | * 246 | * settings: A pointer to a settings object. This parameter cannot be null. 247 | * 248 | * section: A pointer to a null-terminated C string. This parameter cannot 249 | * be null. 250 | * 251 | * key: A pointer to a null-terminated C string. This parameter cannot 252 | * be null. 253 | * 254 | * out: A pointer to an output buffer. 255 | * 256 | * n_out: The maximum number of elements the output buffer can hold. 257 | * 258 | * Return value: 1 if the entire tuple was copied into the output buffer, 259 | * 0 otherwise. 260 | */ 261 | double settings_get_double_tuple(const Settings *settings, const char *section, const char *key, double *out, unsigned int n_out); 262 | 263 | /* 264 | * Associates a value with the supplied key in the provided section. 265 | * If the key is already associated with a value, the previous value 266 | * is replaced. 267 | * 268 | * Parameters: 269 | * 270 | * settings: A pointer to a settings object. This parameter cannot be null. 271 | * 272 | * section: A pointer to a null-terminated C string. This parameter cannot 273 | * be null. The string must have a string length > 0. The string will 274 | * be copied. 275 | * 276 | * key: A pointer to a null-terminated C string. This parameter 277 | * cannot be null. The string must have a string length > 0. The 278 | * string will be copied. 279 | * 280 | * value: A pointer to a null-terminated C string. This parameter 281 | * cannot be null. The string must have a string length > 0. The 282 | * string will be copied. 283 | * 284 | * Return value: 1 if the association succeeded, 0 otherwise. 285 | */ 286 | int settings_set(Settings *setting, const char *section, const char *key, const char *value); 287 | 288 | /* 289 | * Returns the number of associations between keys and values that exist 290 | * in the provided section. 291 | * 292 | * Parameters: 293 | * 294 | * settings: A pointer to a settings object. This parameter cannot be null. 295 | * 296 | * section: A pointer to a null-terminated C string. This parameter cannot 297 | * be null. 298 | * 299 | * Return value: The number of associations between keys and values in 300 | * the provided section. 301 | */ 302 | int settings_section_get_count(const Settings *settings, const char *section); 303 | 304 | /* 305 | * Enumerates all associations between keys and values in the provided 306 | * section. 307 | * 308 | * Parameters: 309 | * 310 | * settings: A pointer to a settings object. This parameter cannot be null. 311 | * 312 | * section: A pointer to a null-terminated C string. This parameter cannot 313 | * be null. 314 | * 315 | * enum_func: A pointer to a callback function that will be 316 | * called by this procedure once for every key associated 317 | * with a value. This parameter cannot be null. 318 | * 319 | * obj: A pointer to a client-specific object. This parameter will be 320 | * passed back to the client's callback function. This parameter can 321 | * be null. 322 | * 323 | * Return value: 1 if enumeration completed, 0 otherwise. 324 | */ 325 | int settings_section_enum(const Settings *settings, const char *section, settings_section_enum_func enum_func, const void *obj); 326 | 327 | #ifdef __cplusplus 328 | } 329 | #endif 330 | 331 | #endif 332 | 333 | /* 334 | 335 | GNU LESSER GENERAL PUBLIC LICENSE 336 | Version 3, 29 June 2007 337 | 338 | Copyright (C) 2007 Free Software Foundation, Inc. 339 | Everyone is permitted to copy and distribute verbatim copies 340 | of this license document, but changing it is not allowed. 341 | 342 | 343 | This version of the GNU Lesser General Public License incorporates 344 | the terms and conditions of version 3 of the GNU General Public 345 | License, supplemented by the additional permissions listed below. 346 | 347 | 0. Additional Definitions. 348 | 349 | As used herein, "this License" refers to version 3 of the GNU Lesser 350 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 351 | General Public License. 352 | 353 | "The Library" refers to a covered work governed by this License, 354 | other than an Application or a Combined Work as defined below. 355 | 356 | An "Application" is any work that makes use of an interface provided 357 | by the Library, but which is not otherwise based on the Library. 358 | Defining a subclass of a class defined by the Library is deemed a mode 359 | of using an interface provided by the Library. 360 | 361 | A "Combined Work" is a work produced by combining or linking an 362 | Application with the Library. The particular version of the Library 363 | with which the Combined Work was made is also called the "Linked 364 | Version". 365 | 366 | The "Minimal Corresponding Source" for a Combined Work means the 367 | Corresponding Source for the Combined Work, excluding any source code 368 | for portions of the Combined Work that, considered in isolation, are 369 | based on the Application, and not on the Linked Version. 370 | 371 | The "Corresponding Application Code" for a Combined Work means the 372 | object code and/or source code for the Application, including any data 373 | and utility programs needed for reproducing the Combined Work from the 374 | Application, but excluding the System Libraries of the Combined Work. 375 | 376 | 1. Exception to Section 3 of the GNU GPL. 377 | 378 | You may convey a covered work under sections 3 and 4 of this License 379 | without being bound by section 3 of the GNU GPL. 380 | 381 | 2. Conveying Modified Versions. 382 | 383 | If you modify a copy of the Library, and, in your modifications, a 384 | facility refers to a function or data to be supplied by an Application 385 | that uses the facility (other than as an argument passed when the 386 | facility is invoked), then you may convey a copy of the modified 387 | version: 388 | 389 | a) under this License, provided that you make a good faith effort to 390 | ensure that, in the event an Application does not supply the 391 | function or data, the facility still operates, and performs 392 | whatever part of its purpose remains meaningful, or 393 | 394 | b) under the GNU GPL, with none of the additional permissions of 395 | this License applicable to that copy. 396 | 397 | 3. Object Code Incorporating Material from Library Header Files. 398 | 399 | The object code form of an Application may incorporate material from 400 | a header file that is part of the Library. You may convey such object 401 | code under terms of your choice, provided that, if the incorporated 402 | material is not limited to numerical parameters, data structure 403 | layouts and accessors, or small macros, inline functions and templates 404 | (ten or fewer lines in length), you do both of the following: 405 | 406 | a) Give prominent notice with each copy of the object code that the 407 | Library is used in it and that the Library and its use are 408 | covered by this License. 409 | 410 | b) Accompany the object code with a copy of the GNU GPL and this license 411 | document. 412 | 413 | 4. Combined Works. 414 | 415 | You may convey a Combined Work under terms of your choice that, 416 | taken together, effectively do not restrict modification of the 417 | portions of the Library contained in the Combined Work and reverse 418 | engineering for debugging such modifications, if you also do each of 419 | the following: 420 | 421 | a) Give prominent notice with each copy of the Combined Work that 422 | the Library is used in it and that the Library and its use are 423 | covered by this License. 424 | 425 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 426 | document. 427 | 428 | c) For a Combined Work that displays copyright notices during 429 | execution, include the copyright notice for the Library among 430 | these notices, as well as a reference directing the user to the 431 | copies of the GNU GPL and this license document. 432 | 433 | d) Do one of the following: 434 | 435 | 0) Convey the Minimal Corresponding Source under the terms of this 436 | License, and the Corresponding Application Code in a form 437 | suitable for, and under terms that permit, the user to 438 | recombine or relink the Application with a modified version of 439 | the Linked Version to produce a modified Combined Work, in the 440 | manner specified by section 6 of the GNU GPL for conveying 441 | Corresponding Source. 442 | 443 | 1) Use a suitable shared library mechanism for linking with the 444 | Library. A suitable mechanism is one that (a) uses at run time 445 | a copy of the Library already present on the user's computer 446 | system, and (b) will operate properly with a modified version 447 | of the Library that is interface-compatible with the Linked 448 | Version. 449 | 450 | e) Provide Installation Information, but only if you would otherwise 451 | be required to provide such information under section 6 of the 452 | GNU GPL, and only to the extent that such information is 453 | necessary to install and execute a modified version of the 454 | Combined Work produced by recombining or relinking the 455 | Application with a modified version of the Linked Version. (If 456 | you use option 4d0, the Installation Information must accompany 457 | the Minimal Corresponding Source and Corresponding Application 458 | Code. If you use option 4d1, you must provide the Installation 459 | Information in the manner specified by section 6 of the GNU GPL 460 | for conveying Corresponding Source.) 461 | 462 | 5. Combined Libraries. 463 | 464 | You may place library facilities that are a work based on the 465 | Library side by side in a single library together with other library 466 | facilities that are not Applications and are not covered by this 467 | License, and convey such a combined library under terms of your 468 | choice, if you do both of the following: 469 | 470 | a) Accompany the combined library with a copy of the same work based 471 | on the Library, uncombined with any other library facilities, 472 | conveyed under the terms of this License. 473 | 474 | b) Give prominent notice with the combined library that part of it 475 | is a work based on the Library, and explaining where to find the 476 | accompanying uncombined form of the same work. 477 | 478 | 6. Revised Versions of the GNU Lesser General Public License. 479 | 480 | The Free Software Foundation may publish revised and/or new versions 481 | of the GNU Lesser General Public License from time to time. Such new 482 | versions will be similar in spirit to the present version, but may 483 | differ in detail to address new problems or concerns. 484 | 485 | Each version is given a distinguishing version number. If the 486 | Library as you received it specifies that a certain numbered version 487 | of the GNU Lesser General Public License "or any later version" 488 | applies to it, you have the option of following the terms and 489 | conditions either of that published version or of any later version 490 | published by the Free Software Foundation. If the Library as you 491 | received it does not specify a version number of the GNU Lesser 492 | General Public License, you may choose any version of the GNU Lesser 493 | General Public License ever published by the Free Software Foundation. 494 | 495 | If the Library as you received it specifies that a proxy can decide 496 | whether future versions of the GNU Lesser General Public License shall 497 | apply, that proxy's public statement of acceptance of any version is 498 | permanent authorization for you to choose that version for the 499 | Library. 500 | 501 | */ 502 | -------------------------------------------------------------------------------- /src/strmap.c: -------------------------------------------------------------------------------- 1 | /* 2 | * strmap version 2.0.0 3 | * 4 | * ANSI C hash table for strings. 5 | * 6 | * Version history: 7 | * 1.0.0 - initial release 8 | * 2.0.0 - changed function prefix from strmap to sm to ensure 9 | * ANSI C compatibility 10 | * 11 | * strmap.c 12 | * 13 | * Copyright (c) 2009, 2011 Per Ola Kristensson. 14 | * 15 | * Per Ola Kristensson 16 | * Inference Group, Department of Physics 17 | * University of Cambridge 18 | * Cavendish Laboratory 19 | * JJ Thomson Avenue 20 | * CB3 0HE Cambridge 21 | * United Kingdom 22 | * 23 | * strmap is free software: you can redistribute it and/or modify 24 | * it under the terms of the GNU Lesser General Public License as published by 25 | * the Free Software Foundation, either version 3 of the License, or 26 | * (at your option) any later version. 27 | * 28 | * strmap is distributed in the hope that it will be useful, 29 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 30 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 31 | * GNU Lesser General Public License for more details. 32 | * 33 | * You should have received a copy of the GNU Lesser General Public License 34 | * along with strmap. If not, see . 35 | */ 36 | #include 37 | #include 38 | #include "strmap.h" 39 | 40 | typedef struct Pair Pair; 41 | 42 | typedef struct Bucket Bucket; 43 | 44 | struct Pair { 45 | char *key; 46 | char *value; 47 | }; 48 | 49 | struct Bucket { 50 | unsigned int count; 51 | Pair *pairs; 52 | }; 53 | 54 | struct StrMap { 55 | unsigned int count; 56 | Bucket *buckets; 57 | }; 58 | 59 | static Pair *get_pair(Bucket *bucket, const char *key); 60 | static unsigned long hash(const char *str); 61 | 62 | StrMap *sm_new(unsigned int capacity) 63 | { 64 | StrMap *map; 65 | 66 | map = (StrMap *)malloc(sizeof(StrMap)); 67 | 68 | if (map == NULL) { 69 | return NULL; 70 | } 71 | 72 | map->count = capacity; 73 | map->buckets = (Bucket *)malloc(map->count * sizeof(Bucket)); 74 | 75 | if (map->buckets == NULL) { 76 | free(map); 77 | return NULL; 78 | } 79 | 80 | memset(map->buckets, 0, map->count * sizeof(Bucket)); 81 | return map; 82 | } 83 | 84 | void sm_delete(StrMap *map) 85 | { 86 | unsigned int i, j, n, m; 87 | Bucket *bucket; 88 | Pair *pair; 89 | 90 | if (map == NULL) { 91 | return; 92 | } 93 | 94 | n = map->count; 95 | bucket = map->buckets; 96 | i = 0; 97 | 98 | while (i < n) { 99 | m = bucket->count; 100 | pair = bucket->pairs; 101 | j = 0; 102 | 103 | while (j < m) { 104 | free(pair->key); 105 | free(pair->value); 106 | pair++; 107 | j++; 108 | } 109 | 110 | free(bucket->pairs); 111 | bucket++; 112 | i++; 113 | } 114 | 115 | free(map->buckets); 116 | free(map); 117 | } 118 | 119 | int sm_get(const StrMap *map, const char *key, char *out_buf, unsigned int n_out_buf) 120 | { 121 | unsigned int index; 122 | Bucket *bucket; 123 | Pair *pair; 124 | 125 | if (map == NULL) { 126 | return 0; 127 | } 128 | 129 | if (key == NULL) { 130 | return 0; 131 | } 132 | 133 | index = hash(key) % map->count; 134 | bucket = &(map->buckets[index]); 135 | pair = get_pair(bucket, key); 136 | 137 | if (pair == NULL) { 138 | return 0; 139 | } 140 | 141 | if (out_buf == NULL && n_out_buf == 0) { 142 | return strlen(pair->value) + 1; 143 | } 144 | 145 | if (out_buf == NULL) { 146 | return 0; 147 | } 148 | 149 | if (strlen(pair->value) >= n_out_buf) { 150 | return 0; 151 | } 152 | 153 | strcpy(out_buf, pair->value); 154 | return 1; 155 | } 156 | 157 | int sm_exists(const StrMap *map, const char *key) 158 | { 159 | unsigned int index; 160 | Bucket *bucket; 161 | Pair *pair; 162 | 163 | if (map == NULL) { 164 | return 0; 165 | } 166 | 167 | if (key == NULL) { 168 | return 0; 169 | } 170 | 171 | index = hash(key) % map->count; 172 | bucket = &(map->buckets[index]); 173 | pair = get_pair(bucket, key); 174 | 175 | if (pair == NULL) { 176 | return 0; 177 | } 178 | 179 | return 1; 180 | } 181 | 182 | int sm_put(StrMap *map, const char *key, const char *value) 183 | { 184 | unsigned int key_len, value_len, index; 185 | Bucket *bucket; 186 | Pair *tmp_pairs, *pair; 187 | char *tmp_value; 188 | char *new_key, *new_value; 189 | 190 | if (map == NULL) { 191 | return 0; 192 | } 193 | 194 | if (key == NULL || value == NULL) { 195 | return 0; 196 | } 197 | 198 | key_len = strlen(key); 199 | value_len = strlen(value); 200 | /* Get a pointer to the bucket the key string hashes to */ 201 | index = hash(key) % map->count; 202 | bucket = &(map->buckets[index]); 203 | 204 | /* Check if we can handle insertion by simply replacing 205 | * an existing value in a key-value pair in the bucket. 206 | */ 207 | if ((pair = get_pair(bucket, key)) != NULL) { 208 | /* The bucket contains a pair that matches the provided key, 209 | * change the value for that pair to the new value. 210 | */ 211 | if (strlen(pair->value) < value_len) { 212 | /* If the new value is larger than the old value, re-allocate 213 | * space for the new larger value. 214 | */ 215 | tmp_value = (char *)realloc(pair->value, (value_len + 1) * sizeof(char)); 216 | 217 | if (tmp_value == NULL) { 218 | return 0; 219 | } 220 | 221 | pair->value = tmp_value; 222 | } 223 | 224 | /* Copy the new value into the pair that matches the key */ 225 | strcpy(pair->value, value); 226 | return 1; 227 | } 228 | 229 | /* Allocate space for a new key and value */ 230 | new_key = (char *)malloc((key_len + 1) * sizeof(char)); 231 | 232 | if (new_key == NULL) { 233 | return 0; 234 | } 235 | 236 | new_value = (char *)malloc((value_len + 1) * sizeof(char)); 237 | 238 | if (new_value == NULL) { 239 | free(new_key); 240 | return 0; 241 | } 242 | 243 | /* Create a key-value pair */ 244 | if (bucket->count == 0) { 245 | /* The bucket is empty, lazily allocate space for a single 246 | * key-value pair. 247 | */ 248 | bucket->pairs = (Pair *)malloc(sizeof(Pair)); 249 | 250 | if (bucket->pairs == NULL) { 251 | free(new_key); 252 | free(new_value); 253 | return 0; 254 | } 255 | 256 | bucket->count = 1; 257 | 258 | } else { 259 | /* The bucket wasn't empty but no pair existed that matches the provided 260 | * key, so create a new key-value pair. 261 | */ 262 | tmp_pairs = (Pair *)realloc(bucket->pairs, (bucket->count + 1) * sizeof(Pair)); 263 | 264 | if (tmp_pairs == NULL) { 265 | free(new_key); 266 | free(new_value); 267 | return 0; 268 | } 269 | 270 | bucket->pairs = tmp_pairs; 271 | bucket->count++; 272 | } 273 | 274 | /* Get the last pair in the chain for the bucket */ 275 | pair = &(bucket->pairs[bucket->count - 1]); 276 | pair->key = new_key; 277 | pair->value = new_value; 278 | /* Copy the key and its value into the key-value pair */ 279 | strcpy(pair->key, key); 280 | strcpy(pair->value, value); 281 | return 1; 282 | } 283 | 284 | int sm_get_count(const StrMap *map) 285 | { 286 | unsigned int i, j, n, m; 287 | unsigned int count; 288 | Bucket *bucket; 289 | 290 | if (map == NULL) { 291 | return 0; 292 | } 293 | 294 | bucket = map->buckets; 295 | n = map->count; 296 | i = 0; 297 | count = 0; 298 | 299 | while (i < n) { 300 | m = bucket->count; 301 | j = 0; 302 | 303 | while (j < m) { 304 | count++; 305 | j++; 306 | } 307 | 308 | bucket++; 309 | i++; 310 | } 311 | 312 | return count; 313 | } 314 | 315 | int sm_enum(const StrMap *map, sm_enum_func enum_func, const void *obj) 316 | { 317 | unsigned int i, j, n, m; 318 | Bucket *bucket; 319 | Pair *pair; 320 | 321 | if (map == NULL) { 322 | return 0; 323 | } 324 | 325 | if (enum_func == NULL) { 326 | return 0; 327 | } 328 | 329 | bucket = map->buckets; 330 | n = map->count; 331 | i = 0; 332 | 333 | while (i < n) { 334 | pair = bucket->pairs; 335 | m = bucket->count; 336 | j = 0; 337 | 338 | while (j < m) { 339 | enum_func(pair->key, pair->value, obj); 340 | pair++; 341 | j++; 342 | } 343 | 344 | bucket++; 345 | i++; 346 | } 347 | 348 | return 1; 349 | } 350 | 351 | /* 352 | * Returns a pair from the bucket that matches the provided key, 353 | * or null if no such pair exist. 354 | */ 355 | static Pair *get_pair(Bucket *bucket, const char *key) 356 | { 357 | unsigned int i, n; 358 | Pair *pair; 359 | 360 | n = bucket->count; 361 | 362 | if (n == 0) { 363 | return NULL; 364 | } 365 | 366 | pair = bucket->pairs; 367 | i = 0; 368 | 369 | while (i < n) { 370 | if (pair->key != NULL && pair->value != NULL) { 371 | if (strcmp(pair->key, key) == 0) { 372 | return pair; 373 | } 374 | } 375 | 376 | pair++; 377 | i++; 378 | } 379 | 380 | return NULL; 381 | } 382 | 383 | /* 384 | * Returns a hash code for the provided string. 385 | */ 386 | static unsigned long hash(const char *str) 387 | { 388 | unsigned long hash = 5381; 389 | int c; 390 | 391 | while ((c = *str++)) { 392 | hash = ((hash << 5) + hash) + c; 393 | } 394 | 395 | return hash; 396 | } 397 | 398 | /* 399 | 400 | GNU LESSER GENERAL PUBLIC LICENSE 401 | Version 3, 29 June 2007 402 | 403 | Copyright (C) 2007 Free Software Foundation, Inc. 404 | Everyone is permitted to copy and distribute verbatim copies 405 | of this license document, but changing it is not allowed. 406 | 407 | 408 | This version of the GNU Lesser General Public License incorporates 409 | the terms and conditions of version 3 of the GNU General Public 410 | License, supplemented by the additional permissions listed below. 411 | 412 | 0. Additional Definitions. 413 | 414 | As used herein, "this License" refers to version 3 of the GNU Lesser 415 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 416 | General Public License. 417 | 418 | "The Library" refers to a covered work governed by this License, 419 | other than an Application or a Combined Work as defined below. 420 | 421 | An "Application" is any work that makes use of an interface provided 422 | by the Library, but which is not otherwise based on the Library. 423 | Defining a subclass of a class defined by the Library is deemed a mode 424 | of using an interface provided by the Library. 425 | 426 | A "Combined Work" is a work produced by combining or linking an 427 | Application with the Library. The particular version of the Library 428 | with which the Combined Work was made is also called the "Linked 429 | Version". 430 | 431 | The "Minimal Corresponding Source" for a Combined Work means the 432 | Corresponding Source for the Combined Work, excluding any source code 433 | for portions of the Combined Work that, considered in isolation, are 434 | based on the Application, and not on the Linked Version. 435 | 436 | The "Corresponding Application Code" for a Combined Work means the 437 | object code and/or source code for the Application, including any data 438 | and utility programs needed for reproducing the Combined Work from the 439 | Application, but excluding the System Libraries of the Combined Work. 440 | 441 | 1. Exception to Section 3 of the GNU GPL. 442 | 443 | You may convey a covered work under sections 3 and 4 of this License 444 | without being bound by section 3 of the GNU GPL. 445 | 446 | 2. Conveying Modified Versions. 447 | 448 | If you modify a copy of the Library, and, in your modifications, a 449 | facility refers to a function or data to be supplied by an Application 450 | that uses the facility (other than as an argument passed when the 451 | facility is invoked), then you may convey a copy of the modified 452 | version: 453 | 454 | a) under this License, provided that you make a good faith effort to 455 | ensure that, in the event an Application does not supply the 456 | function or data, the facility still operates, and performs 457 | whatever part of its purpose remains meaningful, or 458 | 459 | b) under the GNU GPL, with none of the additional permissions of 460 | this License applicable to that copy. 461 | 462 | 3. Object Code Incorporating Material from Library Header Files. 463 | 464 | The object code form of an Application may incorporate material from 465 | a header file that is part of the Library. You may convey such object 466 | code under terms of your choice, provided that, if the incorporated 467 | material is not limited to numerical parameters, data structure 468 | layouts and accessors, or small macros, inline functions and templates 469 | (ten or fewer lines in length), you do both of the following: 470 | 471 | a) Give prominent notice with each copy of the object code that the 472 | Library is used in it and that the Library and its use are 473 | covered by this License. 474 | 475 | b) Accompany the object code with a copy of the GNU GPL and this license 476 | document. 477 | 478 | 4. Combined Works. 479 | 480 | You may convey a Combined Work under terms of your choice that, 481 | taken together, effectively do not restrict modification of the 482 | portions of the Library contained in the Combined Work and reverse 483 | engineering for debugging such modifications, if you also do each of 484 | the following: 485 | 486 | a) Give prominent notice with each copy of the Combined Work that 487 | the Library is used in it and that the Library and its use are 488 | covered by this License. 489 | 490 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 491 | document. 492 | 493 | c) For a Combined Work that displays copyright notices during 494 | execution, include the copyright notice for the Library among 495 | these notices, as well as a reference directing the user to the 496 | copies of the GNU GPL and this license document. 497 | 498 | d) Do one of the following: 499 | 500 | 0) Convey the Minimal Corresponding Source under the terms of this 501 | License, and the Corresponding Application Code in a form 502 | suitable for, and under terms that permit, the user to 503 | recombine or relink the Application with a modified version of 504 | the Linked Version to produce a modified Combined Work, in the 505 | manner specified by section 6 of the GNU GPL for conveying 506 | Corresponding Source. 507 | 508 | 1) Use a suitable shared library mechanism for linking with the 509 | Library. A suitable mechanism is one that (a) uses at run time 510 | a copy of the Library already present on the user's computer 511 | system, and (b) will operate properly with a modified version 512 | of the Library that is interface-compatible with the Linked 513 | Version. 514 | 515 | e) Provide Installation Information, but only if you would otherwise 516 | be required to provide such information under section 6 of the 517 | GNU GPL, and only to the extent that such information is 518 | necessary to install and execute a modified version of the 519 | Combined Work produced by recombining or relinking the 520 | Application with a modified version of the Linked Version. (If 521 | you use option 4d0, the Installation Information must accompany 522 | the Minimal Corresponding Source and Corresponding Application 523 | Code. If you use option 4d1, you must provide the Installation 524 | Information in the manner specified by section 6 of the GNU GPL 525 | for conveying Corresponding Source.) 526 | 527 | 5. Combined Libraries. 528 | 529 | You may place library facilities that are a work based on the 530 | Library side by side in a single library together with other library 531 | facilities that are not Applications and are not covered by this 532 | License, and convey such a combined library under terms of your 533 | choice, if you do both of the following: 534 | 535 | a) Accompany the combined library with a copy of the same work based 536 | on the Library, uncombined with any other library facilities, 537 | conveyed under the terms of this License. 538 | 539 | b) Give prominent notice with the combined library that part of it 540 | is a work based on the Library, and explaining where to find the 541 | accompanying uncombined form of the same work. 542 | 543 | 6. Revised Versions of the GNU Lesser General Public License. 544 | 545 | The Free Software Foundation may publish revised and/or new versions 546 | of the GNU Lesser General Public License from time to time. Such new 547 | versions will be similar in spirit to the present version, but may 548 | differ in detail to address new problems or concerns. 549 | 550 | Each version is given a distinguishing version number. If the 551 | Library as you received it specifies that a certain numbered version 552 | of the GNU Lesser General Public License "or any later version" 553 | applies to it, you have the option of following the terms and 554 | conditions either of that published version or of any later version 555 | published by the Free Software Foundation. If the Library as you 556 | received it does not specify a version number of the GNU Lesser 557 | General Public License, you may choose any version of the GNU Lesser 558 | General Public License ever published by the Free Software Foundation. 559 | 560 | If the Library as you received it specifies that a proxy can decide 561 | whether future versions of the GNU Lesser General Public License shall 562 | apply, that proxy's public statement of acceptance of any version is 563 | permanent authorization for you to choose that version for the 564 | Library. 565 | 566 | */ 567 | -------------------------------------------------------------------------------- /src/strmap.h: -------------------------------------------------------------------------------- 1 | /* 2 | * strmap version 2.0.0 3 | * 4 | * ANSI C hash table for strings. 5 | * 6 | * Version history: 7 | * 1.0.0 - initial release 8 | * 2.0.0 - changed function prefix from strmap to sm to ensure 9 | * ANSI C compatibility 10 | * 11 | * strmap.h 12 | * 13 | * Copyright (c) 2009, 2011 Per Ola Kristensson. 14 | * 15 | * Per Ola Kristensson 16 | * Inference Group, Department of Physics 17 | * University of Cambridge 18 | * Cavendish Laboratory 19 | * JJ Thomson Avenue 20 | * CB3 0HE Cambridge 21 | * United Kingdom 22 | * 23 | * strmap is free software: you can redistribute it and/or modify 24 | * it under the terms of the GNU Lesser General Public License as published by 25 | * the Free Software Foundation, either version 3 of the License, or 26 | * (at your option) any later version. 27 | * 28 | * strmap is distributed in the hope that it will be useful, 29 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 30 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 31 | * GNU Lesser General Public License for more details. 32 | * 33 | * You should have received a copy of the GNU Lesser General Public License 34 | * along with strmap. If not, see . 35 | */ 36 | #ifndef _STRMAP_H_ 37 | #define _STRMAP_H_ 38 | 39 | #ifdef __cplusplus 40 | extern "C" { 41 | #endif 42 | 43 | typedef struct StrMap StrMap; 44 | 45 | /* 46 | * This callback function is called once per key-value when enumerating 47 | * all keys associated to values. 48 | * 49 | * Parameters: 50 | * 51 | * key: A pointer to a null-terminated C string. The string must not 52 | * be modified by the client. 53 | * 54 | * value: A pointer to a null-terminated C string. The string must 55 | * not be modified by the client. 56 | * 57 | * obj: A pointer to a client-specific object. This parameter may be 58 | * null. 59 | * 60 | * Return value: None. 61 | */ 62 | typedef void (*sm_enum_func)(const char *key, const char *value, const void *obj); 63 | 64 | /* 65 | * Creates a string map. 66 | * 67 | * Parameters: 68 | * 69 | * capacity: The number of top-level slots this string map 70 | * should allocate. This parameter must be > 0. 71 | * 72 | * Return value: A pointer to a string map object, 73 | * or null if a new string map could not be allocated. 74 | */ 75 | StrMap *sm_new(unsigned int capacity); 76 | 77 | /* 78 | * Releases all memory held by a string map object. 79 | * 80 | * Parameters: 81 | * 82 | * map: A pointer to a string map. This parameter cannot be null. 83 | * If the supplied string map has been previously released, the 84 | * behaviour of this function is undefined. 85 | * 86 | * Return value: None. 87 | */ 88 | void sm_delete(StrMap *map); 89 | 90 | /* 91 | * Returns the value associated with the supplied key. 92 | * 93 | * Parameters: 94 | * 95 | * map: A pointer to a string map. This parameter cannot be null. 96 | * 97 | * key: A pointer to a null-terminated C string. This parameter cannot 98 | * be null. 99 | * 100 | * out_buf: A pointer to an output buffer which will contain the value, 101 | * if it exists and fits into the buffer. 102 | * 103 | * n_out_buf: The size of the output buffer in bytes. 104 | * 105 | * Return value: If out_buf is set to null and n_out_buf is set to 0 the return 106 | * value will be the number of bytes required to store the value (if it exists) 107 | * and its null-terminator. For all other parameter configurations the return value 108 | * is 1 if an associated value was found and completely copied into the output buffer, 109 | * 0 otherwise. 110 | */ 111 | int sm_get(const StrMap *map, const char *key, char *out_buf, unsigned int n_out_buf); 112 | 113 | /* 114 | * Queries the existence of a key. 115 | * 116 | * Parameters: 117 | * 118 | * map: A pointer to a string map. This parameter cannot be null. 119 | * 120 | * key: A pointer to a null-terminated C string. This parameter cannot 121 | * be null. 122 | * 123 | * Return value: 1 if the key exists, 0 otherwise. 124 | */ 125 | int sm_exists(const StrMap *map, const char *key); 126 | 127 | /* 128 | * Associates a value with the supplied key. If the key is already 129 | * associated with a value, the previous value is replaced. 130 | * 131 | * Parameters: 132 | * 133 | * map: A pointer to a string map. This parameter cannot be null. 134 | * 135 | * key: A pointer to a null-terminated C string. This parameter 136 | * cannot be null. The string must have a string length > 0. The 137 | * string will be copied. 138 | * 139 | * value: A pointer to a null-terminated C string. This parameter 140 | * cannot be null. The string must have a string length > 0. The 141 | * string will be copied. 142 | * 143 | * Return value: 1 if the association succeeded, 0 otherwise. 144 | */ 145 | int sm_put(StrMap *map, const char *key, const char *value); 146 | 147 | /* 148 | * Returns the number of associations between keys and values. 149 | * 150 | * Parameters: 151 | * 152 | * map: A pointer to a string map. This parameter cannot be null. 153 | * 154 | * Return value: The number of associations between keys and values. 155 | */ 156 | int sm_get_count(const StrMap *map); 157 | 158 | /* 159 | * Enumerates all associations between keys and values. 160 | * 161 | * Parameters: 162 | * 163 | * map: A pointer to a string map. This parameter cannot be null. 164 | * 165 | * enum_func: A pointer to a callback function that will be 166 | * called by this procedure once for every key associated 167 | * with a value. This parameter cannot be null. 168 | * 169 | * obj: A pointer to a client-specific object. This parameter will be 170 | * passed back to the client's callback function. This parameter can 171 | * be null. 172 | * 173 | * Return value: 1 if enumeration completed, 0 otherwise. 174 | */ 175 | int sm_enum(const StrMap *map, sm_enum_func enum_func, const void *obj); 176 | 177 | #ifdef __cplusplus 178 | } 179 | #endif 180 | 181 | #endif 182 | 183 | /* 184 | 185 | GNU LESSER GENERAL PUBLIC LICENSE 186 | Version 3, 29 June 2007 187 | 188 | Copyright (C) 2007 Free Software Foundation, Inc. 189 | Everyone is permitted to copy and distribute verbatim copies 190 | of this license document, but changing it is not allowed. 191 | 192 | 193 | This version of the GNU Lesser General Public License incorporates 194 | the terms and conditions of version 3 of the GNU General Public 195 | License, supplemented by the additional permissions listed below. 196 | 197 | 0. Additional Definitions. 198 | 199 | As used herein, "this License" refers to version 3 of the GNU Lesser 200 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 201 | General Public License. 202 | 203 | "The Library" refers to a covered work governed by this License, 204 | other than an Application or a Combined Work as defined below. 205 | 206 | An "Application" is any work that makes use of an interface provided 207 | by the Library, but which is not otherwise based on the Library. 208 | Defining a subclass of a class defined by the Library is deemed a mode 209 | of using an interface provided by the Library. 210 | 211 | A "Combined Work" is a work produced by combining or linking an 212 | Application with the Library. The particular version of the Library 213 | with which the Combined Work was made is also called the "Linked 214 | Version". 215 | 216 | The "Minimal Corresponding Source" for a Combined Work means the 217 | Corresponding Source for the Combined Work, excluding any source code 218 | for portions of the Combined Work that, considered in isolation, are 219 | based on the Application, and not on the Linked Version. 220 | 221 | The "Corresponding Application Code" for a Combined Work means the 222 | object code and/or source code for the Application, including any data 223 | and utility programs needed for reproducing the Combined Work from the 224 | Application, but excluding the System Libraries of the Combined Work. 225 | 226 | 1. Exception to Section 3 of the GNU GPL. 227 | 228 | You may convey a covered work under sections 3 and 4 of this License 229 | without being bound by section 3 of the GNU GPL. 230 | 231 | 2. Conveying Modified Versions. 232 | 233 | If you modify a copy of the Library, and, in your modifications, a 234 | facility refers to a function or data to be supplied by an Application 235 | that uses the facility (other than as an argument passed when the 236 | facility is invoked), then you may convey a copy of the modified 237 | version: 238 | 239 | a) under this License, provided that you make a good faith effort to 240 | ensure that, in the event an Application does not supply the 241 | function or data, the facility still operates, and performs 242 | whatever part of its purpose remains meaningful, or 243 | 244 | b) under the GNU GPL, with none of the additional permissions of 245 | this License applicable to that copy. 246 | 247 | 3. Object Code Incorporating Material from Library Header Files. 248 | 249 | The object code form of an Application may incorporate material from 250 | a header file that is part of the Library. You may convey such object 251 | code under terms of your choice, provided that, if the incorporated 252 | material is not limited to numerical parameters, data structure 253 | layouts and accessors, or small macros, inline functions and templates 254 | (ten or fewer lines in length), you do both of the following: 255 | 256 | a) Give prominent notice with each copy of the object code that the 257 | Library is used in it and that the Library and its use are 258 | covered by this License. 259 | 260 | b) Accompany the object code with a copy of the GNU GPL and this license 261 | document. 262 | 263 | 4. Combined Works. 264 | 265 | You may convey a Combined Work under terms of your choice that, 266 | taken together, effectively do not restrict modification of the 267 | portions of the Library contained in the Combined Work and reverse 268 | engineering for debugging such modifications, if you also do each of 269 | the following: 270 | 271 | a) Give prominent notice with each copy of the Combined Work that 272 | the Library is used in it and that the Library and its use are 273 | covered by this License. 274 | 275 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 276 | document. 277 | 278 | c) For a Combined Work that displays copyright notices during 279 | execution, include the copyright notice for the Library among 280 | these notices, as well as a reference directing the user to the 281 | copies of the GNU GPL and this license document. 282 | 283 | d) Do one of the following: 284 | 285 | 0) Convey the Minimal Corresponding Source under the terms of this 286 | License, and the Corresponding Application Code in a form 287 | suitable for, and under terms that permit, the user to 288 | recombine or relink the Application with a modified version of 289 | the Linked Version to produce a modified Combined Work, in the 290 | manner specified by section 6 of the GNU GPL for conveying 291 | Corresponding Source. 292 | 293 | 1) Use a suitable shared library mechanism for linking with the 294 | Library. A suitable mechanism is one that (a) uses at run time 295 | a copy of the Library already present on the user's computer 296 | system, and (b) will operate properly with a modified version 297 | of the Library that is interface-compatible with the Linked 298 | Version. 299 | 300 | e) Provide Installation Information, but only if you would otherwise 301 | be required to provide such information under section 6 of the 302 | GNU GPL, and only to the extent that such information is 303 | necessary to install and execute a modified version of the 304 | Combined Work produced by recombining or relinking the 305 | Application with a modified version of the Linked Version. (If 306 | you use option 4d0, the Installation Information must accompany 307 | the Minimal Corresponding Source and Corresponding Application 308 | Code. If you use option 4d1, you must provide the Installation 309 | Information in the manner specified by section 6 of the GNU GPL 310 | for conveying Corresponding Source.) 311 | 312 | 5. Combined Libraries. 313 | 314 | You may place library facilities that are a work based on the 315 | Library side by side in a single library together with other library 316 | facilities that are not Applications and are not covered by this 317 | License, and convey such a combined library under terms of your 318 | choice, if you do both of the following: 319 | 320 | a) Accompany the combined library with a copy of the same work based 321 | on the Library, uncombined with any other library facilities, 322 | conveyed under the terms of this License. 323 | 324 | b) Give prominent notice with the combined library that part of it 325 | is a work based on the Library, and explaining where to find the 326 | accompanying uncombined form of the same work. 327 | 328 | 6. Revised Versions of the GNU Lesser General Public License. 329 | 330 | The Free Software Foundation may publish revised and/or new versions 331 | of the GNU Lesser General Public License from time to time. Such new 332 | versions will be similar in spirit to the present version, but may 333 | differ in detail to address new problems or concerns. 334 | 335 | Each version is given a distinguishing version number. If the 336 | Library as you received it specifies that a certain numbered version 337 | of the GNU Lesser General Public License "or any later version" 338 | applies to it, you have the option of following the terms and 339 | conditions either of that published version or of any later version 340 | published by the Free Software Foundation. If the Library as you 341 | received it does not specify a version number of the GNU Lesser 342 | General Public License, you may choose any version of the GNU Lesser 343 | General Public License ever published by the Free Software Foundation. 344 | 345 | If the Library as you received it specifies that a proxy can decide 346 | whether future versions of the GNU Lesser General Public License shall 347 | apply, that proxy's public statement of acceptance of any version is 348 | permanent authorization for you to choose that version for the 349 | Library. 350 | 351 | */ 352 | -------------------------------------------------------------------------------- /src/util.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define __USE_MISC 4 | #define _GNU_SOURCE 5 | #include 6 | 7 | #include "global.h" 8 | 9 | void mbp_log(int level, const char *fmt, ...) 10 | { 11 | va_list args; 12 | if (daemonize) { 13 | va_start(args, fmt); 14 | vsyslog(level, fmt, args); // NOLINT(misc-include-cleaner) 15 | va_end(args); 16 | } 17 | 18 | va_start(args, fmt); 19 | vprintf(fmt, args); 20 | puts(""); // trailing newline 21 | va_end(args); 22 | } 23 | -------------------------------------------------------------------------------- /src/util.h: -------------------------------------------------------------------------------- 1 | #ifndef _UTIL_H_ 2 | #define _UTIL_H_ 3 | 4 | void mbp_log(int level, const char *fmt, ...) __attribute__((format(printf, 2, 3))); 5 | 6 | #endif 7 | -------------------------------------------------------------------------------- /tests/main.c: -------------------------------------------------------------------------------- 1 | #include "minunit.h" 2 | 3 | int main(int argc, char *argv[]) 4 | { 5 | (void)argc; 6 | tests(argv[0]); 7 | } 8 | -------------------------------------------------------------------------------- /tests/minunit.c: -------------------------------------------------------------------------------- 1 | /* file minunit_example.c */ 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include "../src/global.h" 10 | #include "../src/mbpfan.h" 11 | #include "../src/settings.h" 12 | #include "minunit.h" 13 | 14 | int tests_run = 0; 15 | 16 | static void free_fans(t_fans* fans) 17 | { 18 | while (fans != NULL) { 19 | t_fans* tmp = fans->next; 20 | free(fans->fan_manual_path); 21 | free(fans->fan_output_path); 22 | free(fans->label); 23 | free(fans); 24 | fans = tmp; 25 | } 26 | } 27 | 28 | static void free_sensors(t_sensors* sensors) 29 | { 30 | while (sensors != NULL) { 31 | t_sensors* tmp = sensors->next; 32 | free(sensors->path); 33 | free(sensors); 34 | sensors = tmp; 35 | } 36 | } 37 | 38 | static const char *test_sensor_paths() 39 | { 40 | t_sensors* sensors = retrieve_sensors(); 41 | mu_assert("No sensors found", sensors != NULL); 42 | t_sensors* tmp = sensors; 43 | 44 | while(tmp != NULL) { 45 | mu_assert("Sensor does not have a valid path", tmp->path != NULL); 46 | 47 | if(tmp->path != NULL) { 48 | mu_assert("Sensor does not have valid temperature", tmp->temperature > 0); 49 | } 50 | 51 | tmp = tmp->next; 52 | } 53 | 54 | free_sensors(sensors); 55 | return 0; 56 | } 57 | 58 | 59 | static const char *test_fan_paths() 60 | { 61 | t_fans* fans = retrieve_fans(); 62 | mu_assert("No fans found", fans != NULL); 63 | t_fans* tmp = fans; 64 | int found_fan_path = 0; 65 | 66 | while(tmp != NULL) { 67 | if(tmp->fan_output_path != NULL) { 68 | found_fan_path++; 69 | } 70 | 71 | tmp = tmp->next; 72 | } 73 | 74 | mu_assert("No fans found", found_fan_path != 0); 75 | free_fans(fans); 76 | return 0; 77 | } 78 | 79 | unsigned time_seed() 80 | { 81 | time_t now = time ( 0 ); 82 | unsigned char *p = (unsigned char *)&now; 83 | unsigned seed = 0; 84 | size_t i; 85 | 86 | for ( i = 0; i < sizeof now; i++ ) { 87 | seed = seed * ( UCHAR_MAX + 2U ) + p[i]; 88 | } 89 | 90 | return seed; 91 | } 92 | 93 | // nothing better than a horrible piece of code to 94 | // stress a little bit the CPU 95 | int stress(int n) 96 | { 97 | int f = n; 98 | 99 | while (f > 0) { 100 | while(n > 0) { 101 | srand ( time_seed() ); 102 | n--; 103 | } 104 | 105 | f--; 106 | n = f; 107 | } 108 | return 0; 109 | } 110 | 111 | static const char *test_get_temp() 112 | { 113 | t_sensors* sensors = retrieve_sensors(); 114 | mu_assert("No sensors found", sensors != NULL); 115 | unsigned short temp_1 = get_temp(sensors); 116 | mu_assert("Invalid Global Temperature Found", temp_1 > 1 && temp_1 < 150); 117 | stress(2000); 118 | unsigned short temp_2 = get_temp(sensors); 119 | mu_assert("Invalid Higher temp test (if fan was already spinning high, this is not worrying)", temp_1 < temp_2); 120 | free_sensors(sensors); 121 | return 0; 122 | } 123 | 124 | static const char *test_config_file() 125 | { 126 | FILE *f = NULL; 127 | Settings *settings = NULL; 128 | f = fopen("/etc/mbpfan.conf", "r"); 129 | mu_assert("No config file found", f != NULL); 130 | 131 | if (f == NULL) { 132 | return 0; 133 | } 134 | 135 | settings = settings_open(f); 136 | fclose(f); 137 | mu_assert("Could not read settings from config file", settings != NULL); 138 | 139 | if (settings == NULL) { 140 | return 0; 141 | } 142 | 143 | mu_assert("Could not read low_temp from config file",settings_get_int(settings, "general", "low_temp") != 0); 144 | mu_assert("Could not read high_temp from config file",settings_get_int(settings, "general", "high_temp") != 0); 145 | mu_assert("Could not read max_temp from config file",settings_get_int(settings, "general", "max_temp") != 0); 146 | mu_assert("Could not read polling_interval from config file",settings_get_int(settings, "general", "polling_interval") != 0); 147 | /* Destroy the settings object */ 148 | settings_delete(settings); 149 | 150 | return 0; 151 | } 152 | 153 | static const char *test_settings() 154 | { 155 | t_fans* fan = (t_fans *) malloc( sizeof( t_fans ) ); 156 | fan->fan_id = 1; 157 | fan->fan_max_speed = -1; 158 | fan->next = NULL; 159 | 160 | retrieve_settings("./mbpfan.conf.test1", fan); 161 | // choosing the maximum for iMac mid 2011 162 | mu_assert("max_fan_speed value is not 2600", fan->fan_max_speed == 2600); 163 | mu_assert("polling_interval is not 2", polling_interval == 2); 164 | 165 | fan->fan_min_speed = -1; 166 | retrieve_settings("./mbpfan.conf.test0", fan); 167 | mu_assert("min_fan_speed value is not 2000", fan->fan_min_speed == 2000); 168 | mu_assert("polling_interval is not 7", polling_interval == 7); 169 | 170 | t_fans* fan2 = (t_fans *)malloc(sizeof(t_fans)); 171 | fan2->fan_id = 2; 172 | fan2->fan_max_speed = -1; 173 | fan2->next = NULL; 174 | fan->next = fan2; 175 | 176 | retrieve_settings("./mbpfan.conf.test2", fan); 177 | mu_assert("min_fan1_speed value is not 2000", fan->fan_min_speed == 2000); 178 | mu_assert("min_fan2_speed value is not 2000", fan->next->fan_min_speed == 2000); 179 | 180 | free(fan2); 181 | fan->next = NULL; 182 | free(fan); 183 | 184 | return 0; 185 | 186 | } 187 | int received = 0; 188 | 189 | static void handler(int signal) 190 | { 191 | t_fans* fan = (t_fans *) malloc( sizeof( t_fans ) ); 192 | fan->fan_id = 1; 193 | fan->next = NULL; 194 | 195 | 196 | switch(signal) { 197 | case SIGHUP: 198 | received = 1; 199 | retrieve_settings("./mbpfan.conf.test1", fan); 200 | free(fan); 201 | break; 202 | 203 | default: 204 | received = 0; 205 | free(fan); 206 | break; 207 | } 208 | } 209 | 210 | static const char *test_sighup_receive() 211 | { 212 | signal(SIGHUP, handler); 213 | raise(SIGHUP); 214 | mu_assert("did not receive SIGHUP signal", received == 1); 215 | return 0; 216 | } 217 | 218 | static const char *test_settings_reload() 219 | { 220 | t_fans* fan = (t_fans *) malloc( sizeof( t_fans ) ); 221 | fan->fan_id = 1; 222 | fan->fan_min_speed = -1; 223 | fan->fan_manual_path = NULL; 224 | fan->fan_output_path = NULL; 225 | fan->label = NULL; 226 | fan->next = NULL; 227 | 228 | signal(SIGHUP, handler); 229 | retrieve_settings("./mbpfan.conf", fan); 230 | printf("Testing the _supplied_ mbpfan.conf (not the one you are using)..\n"); 231 | // cannot tests min_fan_speed since it is not set and thus auto-detected 232 | mu_assert("polling_interval is not 1 before SIGHUP", polling_interval == 1); 233 | raise(SIGHUP); 234 | // cannot tests min_fan_speed since it is not set and thus auto-detected 235 | mu_assert("polling_interval is not 2 after SIGHUP", polling_interval == 2); 236 | retrieve_settings("./mbpfan.conf", fan); 237 | free_fans(fan); 238 | return 0; 239 | } 240 | 241 | 242 | static const char *all_tests() 243 | { 244 | mu_run_test(test_sensor_paths); 245 | mu_run_test(test_fan_paths); 246 | mu_run_test(test_get_temp); 247 | mu_run_test(test_config_file); 248 | mu_run_test(test_settings); 249 | mu_run_test(test_sighup_receive); 250 | mu_run_test(test_settings_reload); 251 | return 0; 252 | } 253 | 254 | int tests(const char *program_path) 255 | { 256 | verbose = 1; 257 | 258 | check_requirements(program_path); 259 | 260 | printf("Starting the tests..\n"); 261 | printf("It is normal for them to take a bit to finish.\n"); 262 | 263 | const char *result = all_tests(); 264 | 265 | if (result != 0) { 266 | printf("Error: %s \n", result); 267 | 268 | } else { 269 | printf("ALL TESTS PASSED\n"); 270 | } 271 | 272 | printf("Tests run: %d\n", tests_run); 273 | 274 | return result != 0; 275 | } 276 | -------------------------------------------------------------------------------- /tests/minunit.h: -------------------------------------------------------------------------------- 1 | /** 2 | * This is the MinUnit testing framework - http://www.jera.com/techinfo/jtns/jtn002.html 3 | */ 4 | 5 | #ifndef _MINUNIT_H_ 6 | #define _MINUNIT_H_ 7 | 8 | #define mu_assert(message, test) do { if (!(test)) return message; } while (0) 9 | #define mu_run_test(test) do { const char *message = test(); tests_run++; \ 10 | if (message) return message; } while (0) 11 | 12 | extern int tests_run; 13 | 14 | 15 | static const char *test_sensor_paths(void); 16 | static const char *test_fan_paths(void); 17 | static const char *test_get_temp(void); 18 | static const char *test_config_file(void); 19 | static const char *test_settings(void); 20 | static void handler(int signal); 21 | static const char *test_sighup_receive(void); 22 | static const char *test_settings_reload(void); 23 | static const char *all_tests(void); 24 | 25 | int tests(const char *program_path); 26 | 27 | #endif 28 | --------------------------------------------------------------------------------